its for when you want to get like notifications for your reposts
1import { 2 ConnectionStatus, 3 connectService, 4 Notification, 5} from "bsky-repost-likes-monitor/background"; 6import { onMessage, sendMessage } from "webext-bridge/background"; 7 8let websocket: WebSocket | null = null; 9let reconnectBackoff = 1000 * 1; 10 11let connectionStatus: ConnectionStatus = "disconnected"; 12let error: string | null = null; 13let items: Notification[] = []; 14 15export default defineBackground({ 16 persistent: true, 17 main: async () => { 18 browser.action.setBadgeBackgroundColor({ color: "#0886FE" }); 19 browser.action.setBadgeTextColor({ color: "#FFFFFF" }); 20 21 onMessage("connectService", connect); 22 onMessage("disconnectService", disconnect); 23 onMessage("connectionStatus", () => { 24 return connectionStatus; 25 }); 26 onMessage("error", () => { 27 return error; 28 }); 29 onMessage("items", () => { 30 return items; 31 }); 32 onMessage("clearItems", () => { 33 items = []; 34 browser.action.setBadgeText({ text: "" }); 35 }); 36 37 // connect on service start once 38 let actorId = await store.actorId.getValue(); 39 let serviceDomain = await store.serviceDomain.getValue(); 40 if (actorId.length > 0 && serviceDomain.length > 0) { 41 connect({ data: { actorId, serviceDomain } }); 42 } 43 44 // send pings to keep service alive 45 setInterval(() => { 46 if (websocket && connectionStatus === "connected") websocket.send(""); 47 }, 1000 * 15); 48 }, 49}); 50 51const connect = ({ 52 data: { actorId, serviceDomain }, 53}: { 54 data: { actorId: string; serviceDomain: string }; 55}) => { 56 connectService({ 57 actorId, 58 serviceDomain, 59 pushNotification: (item) => { 60 items = [item, ...items]; 61 browser.action.setBadgeText({ text: items.length.toString() }); 62 sendMessage("setItems", items, "popup"); 63 }, 64 setConnectionStatus, 65 setError, 66 doRetry: () => { 67 if (websocket !== null && connectionStatus === "error") { 68 const b = reconnectBackoff; 69 reconnectBackoff *= 2; 70 return b; 71 } else return null; 72 }, 73 }).then((ws) => { 74 websocket = ws ?? null; 75 }); 76}; 77const disconnect = () => { 78 setConnectionStatus("disconnected"); 79 setError(null); 80 websocket?.close(); 81 websocket = null; 82}; 83const setConnectionStatus = (status: ConnectionStatus) => { 84 connectionStatus = status; 85 sendMessage("setConnectionStatus", status, "popup"); 86}; 87const setError = (_error: string | null) => { 88 error = _error; 89 sendMessage("setError", error, "popup"); 90};