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 connectionStatus: ConnectionStatus = "disconnected";
10let error: string | null = null;
11let items: Notification[] = [];
12
13export default defineBackground({
14 persistent: true,
15 main: async () => {
16 onMessage("connectService", connect);
17 onMessage("disconnectService", disconnect);
18 onMessage("connectionStatus", () => {
19 return connectionStatus;
20 });
21 onMessage("error", () => {
22 return error;
23 });
24 onMessage("items", () => {
25 return items;
26 });
27 onMessage("setItems", ({ data }) => {
28 items = data;
29 });
30
31 // connect on service start once
32 let actorId = await store.actorId.getValue();
33 let serviceDomain = await store.serviceDomain.getValue();
34 if (actorId.length > 0 && serviceDomain.length > 0) {
35 connect({ data: { actorId, serviceDomain } });
36 }
37
38 // send pings to keep service alive
39 setInterval(() => {
40 if (websocket && connectionStatus === "connected") websocket.send("");
41 }, 1000 * 15);
42 },
43});
44
45const connect = ({
46 data: { actorId, serviceDomain },
47}: {
48 data: { actorId: string; serviceDomain: string };
49}) => {
50 connectService({
51 actorId,
52 serviceDomain,
53 pushNotification: (item) => {
54 items = [item, ...items];
55 sendMessage("setItems", items, "popup");
56 },
57 setConnectionStatus,
58 setError,
59 backoff: 1000 * 1,
60 }).then((ws) => {
61 websocket = ws ?? null;
62 });
63};
64const disconnect = () => {
65 setConnectionStatus("disconnecting...");
66 websocket?.close();
67 websocket = null;
68};
69const setConnectionStatus = (status: ConnectionStatus) => {
70 connectionStatus = status;
71 sendMessage("setConnectionStatus", status, "popup");
72};
73const setError = (_error: string | null) => {
74 error = _error;
75 sendMessage("setError", error, "popup");
76};