aboutsummaryrefslogtreecommitdiff
path: root/apps/extension/src/background.ts
blob: d2f8759e38ad04cc6a3c8428814e050205b85eda (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
import { getEnv } from "./util";
import { Space } from "./types/memory";

const backendUrl =
  getEnv() === "development"
    ? "http://localhost:3000"
    : "https://supermemory.dhr.wtf";

interface TweetData {
  tweetText: string;
  postUrl: string;
  authorName: string;
  handle: string;
  time: string;
  saveToUser: string;
}

// TODO: Implement getting bookmarks from Twitter API directly
// let authorizationHeader: string | null = null;
// let csrfToken: string | null = null;
// let cookies: string | null = null;

// chrome.webRequest.onBeforeSendHeaders.addListener(
//   (details) => {
//     for (let i = 0; i < details.requestHeaders!.length; ++i) {
//       const header = details.requestHeaders![i];
//       if (header.name.toLowerCase() === 'authorization') {
//         authorizationHeader = header.value || null;
//       } else if (header.name.toLowerCase() === 'x-csrf-token') {
//         csrfToken = header.value || null;
//       } else if (header.name.toLowerCase() === 'cookie') {
//         cookies = header.value || null;
//       }

//       console.log(header, authorizationHeader, csrfToken, cookies)
//     }
//   },
//   { urls: ['https://twitter.com/*', 'https://x.com/*'] },
//   ['requestHeaders']
// );

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === "getJwt") {
    chrome.storage.local.get(["jwt"], ({ jwt }) => {
      sendResponse({ jwt });
    });

    return true;
  } else if (request.type === "urlChange") {
    const content = request.content;
    const url = request.url;
    const spaces = request.spaces(
      // eslint-disable-next-line no-unexpected-multiline
      async () => {
        chrome.storage.local.get(["jwt"], ({ jwt }) => {
          if (!jwt) {
            console.error("No JWT found");
            return;
          }
          fetch(`${backendUrl}/api/store`, {
            method: "POST",
            headers: {
              Authorization: `Bearer ${jwt}`,
            },
            body: JSON.stringify({ pageContent: content, url, spaces }),
          }).then((ers) => console.log(ers.status));
        });
      },
    )();
  } else if (request.type === "fetchSpaces") {
    chrome.storage.local.get(["jwt"], async ({ jwt }) => {
      if (!jwt) {
        console.error("No JWT found");
        return;
      }
      const resp = await fetch(`${backendUrl}/api/spaces`, {
        headers: {
          Authorization: `Bearer ${jwt}`,
        },
      });

      const data: {
        message: "OK" | string;
        data: Space[] | undefined;
      } = await resp.json();

      if (data.message === "OK" && data.data) {
        sendResponse(data.data);
      }
    });

    return true;
  } else if (request.type === "queryApi") {
    const input = request.input;
    const jwt = request.jwt;

    (async () => {
      await fetch(`${backendUrl}/api/ask`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${jwt}`,
        },
        body: JSON.stringify({
          query: input,
        }),
      }).then(async (response) => {
        if (!response.body) {
          throw new Error("No response body");
        }
        if (!sender.tab?.id) {
          throw new Error("No tab ID");
        }
        const reader = response.body.getReader();
        // eslint-disable-next-line no-constant-condition
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          // For simplicity, we're sending chunks as they come.
          // This might need to be adapted based on your data and needs.
          const chunkAsString = new TextDecoder("utf-8")
            .decode(value)
            .replace("data: ", "");
          chrome.tabs.sendMessage(sender.tab.id, {
            action: "streamData",
            data: chunkAsString,
          });
        }
        // Notify the content script that the stream is complete.
        chrome.tabs.sendMessage(sender.tab.id, { action: "streamEnd" });
      });
      // Indicate that sendResponse will be called asynchronously.
      return true;
    })();
  }
  // TODO: Implement getting bookmarks from Twitter API directly
  // else if (request.action === 'getAuthData') {
  //   sendResponse({
  //     authorizationHeader: authorizationHeader,
  //     csrfToken: csrfToken,
  //     cookies: cookies
  //   });
  // }
  else if (request.type === "sendBookmarkedTweets") {
    const jwt = request.jwt;
    const tweets = request.tweets as TweetData[];

    (async () => {
      await fetch(`${backendUrl}/api/vectorizeTweets`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${jwt}`,
        },
        body: JSON.stringify(tweets),
      }).then(async (response) => {
        return response.json();
      });
    })();

    return true;
  }
});