aboutsummaryrefslogtreecommitdiff
path: root/apps/extension/src/background.ts
blob: 74bb0f0987ee94caba4c9b1766c488f50d1ad15a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import { getBaseURL } from "@/lib/utils";
import {
  messageListener,
  MessageType,
  registerMessageHandler,
} from "./helpers";
import { handleExportXBookmarks, setupTwitterHeaderListener } from "./twitter";

type TabState = {
  isActive: boolean;
};

const tabStates = new Map<number, TabState>();

const checkIfLoggedIn = async () => {
  const baseURL = await getBaseURL();
  const response = await fetch(`${baseURL}/backend/v1/session`);

  return response.status == 200;
};

// When extension is installed
chrome.runtime.onInstalled.addListener(async (details) => {
  const isLoggedIn = await checkIfLoggedIn();

  const baseURL = await getBaseURL();
  if (!isLoggedIn) {
    chrome.tabs.create({ url: `${baseURL}/signin` });
  }

  // TODO: show extension help page
});

// Clean up tab state when tab is closed
chrome.tabs.onRemoved.addListener((tabId) => {
  tabStates.delete(tabId);
});

// communication with content script
chrome.action.onClicked.addListener(async (tab) => {
  if (!tab.id) return;

  try {
    // Check if we can inject into this tab
    if (
      !tab.url ||
      tab.url.startsWith("chrome://") ||
      tab.url.startsWith("edge://") ||
      tab.url.startsWith("about:")
    ) {
      alert("Cannot modify Chrome system pages");
      return;
    }

    const baseURL = await getBaseURL();

    const isLoggedIn = await checkIfLoggedIn();
    if (!isLoggedIn) {
      chrome.tabs.create({ url: `${baseURL}/signin` });
      return;
    }

    const currentState = tabStates.get(tab.id) || { isActive: false };
    const newState = { isActive: !currentState.isActive };

    chrome.scripting.executeScript({
      target: { tabId: tab.id },
      files: ["scripts/content.js"],
    });

    // Update state
    tabStates.set(tab.id, newState);

    // Update icon title
    await chrome.action.setTitle({
      tabId: tab.id,
      title: newState.isActive ? "Disable SuperMemory" : "Enable SuperMemory",
    });
  } catch (error) {
    console.error("Failed to toggle content:", error);
  }
});

chrome.runtime.onMessage.addListener(messageListener);

registerMessageHandler<MessageType>(
  "GET_SPACES",
  async (message, sender, sendResponse) => {
    // Handle getting spaces
    const baseURL = await getBaseURL();
    const response = await fetch(`${baseURL}/backend/v1/spaces`);
    const data = await response.json();
    sendResponse(data);
  }
);

registerMessageHandler<MessageType>(
  "EXPORT_TWITTER_BOOKMARKS",
  async (message, sender, sendResponse) => {
    handleExportXBookmarks();
    sendResponse({ status: "started" });
  }
);

registerMessageHandler<MessageType>(
  "SAVE_PAGE",
  async (message, sender, sendResponse) => {
    if (!message.payload) {
      sendResponse({ error: "No payload" });
      return;
    }

    const baseURL = await getBaseURL();

    const isLoggedIn = await checkIfLoggedIn();
    if (!isLoggedIn) {
      sendResponse({ error: "Not logged in" });
      chrome.tabs.create({ url: `${baseURL}/signin` });
      return;
    }

    console.log(message.payload);

    const response = await fetch(`${baseURL}/backend/v1/add`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        spaces: message.payload.spaces || [],
        content: message.payload.url,
        prefetched: message.payload.prefetched,
      }),
    });
    if (response.status !== 200) {
      sendResponse({ error: "Failed to save page", status: response.status });
      return;
    }
    const data = await response.json();
    // Handle saving highlight
    sendResponse({ success: true, data, status: response.status });
  }
);

registerMessageHandler<MessageType>(
  "ACTIVATE_CONTENT",
  async (message, sender, sendResponse) => {
    console.log("Activating content");
    chrome.tabs.query({ active: true, currentWindow: true }, async (tabs) => {
      const currentTab = tabs[0];
      if (currentTab.id) {
        try {
          await chrome.scripting.executeScript({
            target: { tabId: currentTab.id },
            files: ["scripts/content.js"],
          });
        } catch (error) {
          console.error("Error injecting content script:", error);
        }
      }
    });
    sendResponse({ success: true });
  }
);

registerMessageHandler<MessageType>(
  "SYNC_CHROME_BOOKMARKS",
  async (message, sender, sendResponse) => {
    // activate the chrome bookmarks syncing.

    // TODO: We probably want to sync bookmarks from the extension to the web app.
    chrome.bookmarks.onCreated.addListener((id, bookmark) => {
      console.log("Bookmark created:", bookmark);
    });
  }
);

registerMessageHandler<MessageType>(
  "IMPORT_CHROME_BOOKMARKS",
  async (message, sender, sendResponse) => {
    // activate the chrome bookmarks importing.
    // first get all chrome bookmarks
    chrome.bookmarks.getRecent(100, (bookmarks) => {
      console.log("Bookmarks:", bookmarks);
    });
  }
);

// External message listener
chrome.runtime.onMessageExternal.addListener(
  async (request, sender, sendResponse) => {
    if (request.action === "exportBookmarks") {
      handleExportXBookmarks();
      sendResponse({ status: "exported" });
      return true;
    }
    if (request.action === "importBookmarks") {
      const baseURL = await getBaseURL();
      chrome.bookmarks.getRecent(100, async (bookmarks) => {
        for (const { url } of bookmarks) {
          console.log("Importing bookmark:", url);
          const r = await fetch(`${baseURL}/backend/v1/add`, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({ content: url, spaces: [] }),
          });

          const response = await r.json();
          console.log("Response:", response);
        }
        sendResponse({ status: "imported", bookmarks });
      });
      return true;
    }
    if (request.action === "ping") {
      sendResponse({ status: "pong" });
      return true;
    }
  }
);

setupTwitterHeaderListener();