-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunpacked-background.js
332 lines (303 loc) · 9.09 KB
/
unpacked-background.js
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import { createParser } from "eventsource-parser";
import { v4 as uuidv4 } from "uuid";
let controller, timeout;
const errorMessages = {
standard:
"A network or API error occurred! Please wait a minute and try again.",
network: "Your network is down.",
prompt: "Invalid prompt.",
denied:
"ChatGPT says you are sending too many requests in a row. Please slow down before sending another request.",
abort: "User aborted search.",
timeout:
"Timeout error. This most likely means either your network or ChatGPT is too slow.",
};
async function getResponse(accessToken, query, limit) {
let convoID = null;
let cleared = false;
let timestamp = Date.now();
let response;
const finalQuery = limit
? "Limit your response to 130 characters:\n" + query
: query;
try {
if (query == null || query.trim() === "") throw new Error("prompt");
controller = new AbortController();
timeout = setTimeout(() => controller.abort("timeout"), 3000);
const modelName = await getModelName(accessToken, controller);
clearTimeout(timeout);
timeout = setTimeout(() => controller.abort("timeout"), 15000);
await fetchMethod(
controller,
accessToken,
finalQuery,
modelName,
(segment) => {
if (segment === "[DONE]") return;
try {
const data = JSON.parse(segment);
if (!cleared) {
clearTimeout(timeout);
cleared = true;
}
if (convoID != data.conversation_id) convoID = data.conversation_id;
response = data.message.content.parts[0];
const now = Date.now();
if (now - timestamp > 250) {
setStorage("query", [query, data.message.content.parts[0], false]);
timestamp = now;
}
} catch (err) {
return;
}
}
);
timeout = setTimeout(() => controller.abort("timeout"), 3000);
await clearMessage(convoID, accessToken, controller);
clearTimeout(timeout);
return [response, false];
} catch (err) {
console.log(err);
clearTimeout(timeout);
if (controller == null || err.message === "prompt") {
return [errorMessages.prompt, true];
} else if (controller.signal.reason === "user") {
return [errorMessages.abort, true];
} else if (controller.signal.reason === "timeout") {
return [errorMessages.timeout, true];
} else if (err.message === "fetch") {
return [errorMessages.denied, true];
} else if (err.name === "NetworkError") {
return [errorMessages.network, true];
} else {
return [errorMessages.standard, true];
}
}
}
chrome.runtime.onInstalled.addListener(async (details) => {
if (details.reason === "install") {
chrome.runtime.openOptionsPage();
}
if (details.reason === "install" || details.reason === "update") {
var uninstallGoogleFormLink =
"https://docs.google.com/forms/d/e/1FAIpQLSdv3c9RmDmphP1pihYgmNmV6DJ_UxMXq6NNi1oOW5XsIhyxOg/viewform?usp=sf_link";
if (chrome.runtime.setUninstallURL) {
chrome.runtime.setUninstallURL(uninstallGoogleFormLink);
}
}
if (details.reason === "update") {
const loading = await getStorage("loading");
if (loading == "true") {
setStorage("loading", "false");
}
}
});
chrome.contextMenus.removeAll(() => {
chrome.contextMenus.create({
id: "3",
title: "Search + get response as notification",
contexts: ["selection"],
});
});
chrome.runtime.onMessage.addListener((request, sender, callBack) => {
switch (request.type) {
case "query":
query(request);
return true;
case "callAPI":
callAPI(request).then(() => {
callBack();
});
return true;
case "abort":
abort().then(() => {
callBack();
});
return true;
}
});
const getOtherId = async () => {
const accessArr = await getStorage("accessArr");
if (accessArr != null) {
const expireDate = new Date(accessArr[1]);
const now = new Date();
if (now < expireDate) {
return [true, accessArr[0]];
} else {
return [false, null];
}
} else {
return [false, null];
}
};
chrome.contextMenus.onClicked.addListener(async (info) => {
const loading = await getStorage("loading");
if (loading == null || loading === "false") {
const controllerNotif = new AbortController();
setTimeout(() => controllerNotif.abort("timeout"), 5000);
try {
const resp = await fetch("https://chat.openai.com/api/auth/session", {
signal: controllerNotif == null ? null : controllerNotif.signal,
});
const otherId = await getOtherId();
if (resp.status === 403 && otherId[0] === false) {
sendNotification(
"Error!!!",
"Open the GptGO popup and sign in before sending search requests"
);
} else {
let token = null;
try {
const data = await resp.json().catch(() => ({}));
if (data.accessToken) {
token = data.accessToken;
} else {
token = otherId[1];
}
} catch (err) {
token = otherId[1];
}
if (token != null) {
await setStorage("loading", "true");
await setStorage("query", [info.selectionText, null, false]);
const response = await getResponse(token, info.selectionText, true);
await setStorage("query", [
info.selectionText,
response[0],
response[1],
]);
await setStorage("loading", "false");
sendNotification(
response[1] === true
? "Error!!!"
: "Response to: " + info.selectionText,
response[0].replace(/\n/g, "")
);
} else {
sendNotification(
"Error!!!",
"Open the GptGO popup and sign in before sending search requests"
);
}
}
} catch (err) {
console.log(err);
sendNotification("Error!!!", "There was a problem connecting to ChatGPT");
}
}
});
//############################## Helper Functions ###########################
const callAPI = async (request) => {
await setStorage("loading", "true");
await setStorage("query", [request.query, null, false]);
const accessToken = await getStorage("accessToken");
const response = await getResponse(accessToken, request.query, false);
await setStorage("query", [request.query, response[0], response[1]]);
await setStorage("loading", "false");
};
const query = async (request) => {
const loading = await getStorage("loading");
if (loading == null || loading === "false") {
await setStorage("query", [request.payload, null, false]);
}
};
const abort = async () => {
controller.abort("user");
};
async function getModelName(accessToken, controller) {
const models = await fetch(`https://chat.openai.com/backend-api/models`, {
method: "GET",
signal: controller == null ? null : controller.signal,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
});
const modelsJson = await models.json();
return modelsJson.models[0].slug;
}
async function clearMessage(convoID, accessToken, controller) {
await fetch("https://chat.openai.com/backend-api/conversation/" + convoID, {
method: "PATCH",
signal: controller == null ? null : controller.signal,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({ is_visible: false }),
});
return;
}
async function* streamMethod(stream) {
const reader = stream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) return;
yield value;
}
} finally {
reader.releaseLock();
}
}
async function fetchMethod(
controller,
accessToken,
finalQuery,
modelName,
callback
) {
const resp = await fetch("https://chat.openai.com/backend-api/conversation", {
method: "POST",
signal: controller == null ? null : controller.signal,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
action: "next",
messages: [
{
id: uuidv4(),
role: "user",
content: {
content_type: "text",
parts: [finalQuery],
},
},
],
model: modelName,
parent_message_id: uuidv4(),
}),
});
if (!resp.ok) {
throw new Error("fetch");
}
const parser = createParser((event) => {
if (event.type === "event") {
callback(event.data);
}
});
for await (const segment of streamMethod(resp.body)) {
const decoded = new TextDecoder().decode(segment);
parser.feed(decoded);
}
}
const sendNotification = (query, response) => {
chrome.notifications.create("", {
title: query,
type: "basic",
message: response,
iconUrl: "images/logo192.png",
});
};
const getStorage = async (key) => {
const response = await chrome.storage.local.get([key]);
const value = response[key];
return value;
};
const setStorage = async (key, value) => {
await chrome.storage.local.set({
[key]: value,
});
};