-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
294 lines (239 loc) · 10.4 KB
/
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
chrome.commands.onCommand.addListener((shortcut) => {
console.log('lets reload');
console.log(shortcut);
if (shortcut.includes("+M")) {
// reload current tab
chrome.tabs.reload();
chrome.runtime.reload();
}
})
function generateUUIDv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0,
v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
async function getToken() {
let accessToken
let response = await fetch("https://chat.openai.com/api/auth/session")
let body = await response.json()
console.log(body.accessToken)
accessToken = body.accessToken
return accessToken
}
let targetTabId; // The ID of the tab where the content script is running
let oldMessageId
async function handleStreamedResponse(token, question, videoId, parts) {
// Make a request to the server that returns a streamed response
const uuid1 = generateUUIDv4();
console.log("videoId: " + videoId)
console.log("question: " + question)
let subs
let questionParts
let multipart = false
// if the question is more than 15k characters, then we need to split it into multiple requests
questionParts = question.match(/.{1,15000}/g);
console.log(questionParts)
for (let i = parts.length; i < questionParts.length; i++) {
if (i == 0) {
console.log("first part")
if (question.length > 15000) {
subs = `This is the first part of the transcript. Keep it to a super short summary, no more than 3 sentences. Dont mention that you're reading a transcript, and exlude any parts about a sponsership: ` + questionParts[i]
} else {
subs = "this is a youtube video's transcript. Short summary (dont mention that you're reading a transcript): " + questionParts[i]
}
break
} else {
subs = `Previous summary: ${parts}. This is the ${i + 1} part of the transcript. Rewritten, continued summary (dont mention that you're reading a transcript): ` + questionParts[i]
multipart = true
break
}
}
console.log("subs ", subs)
let body
if (!multipart) {
body = { "action": "next", "messages": [{ "id": "73954541-ff9e-4785-85e4-d45527ccca73", "author": { "role": "user" }, "content": { "content_type": "text", "parts": [subs] } }], "parent_message_id": uuid1, "model": "text-davinci-002-render-sha", "timezone_offset_min": 240 }
} else {
let response = await fetch("https://chat.openai.com/backend-api/conversations?offset=0&limit=20", {
"headers": {
"accept": "text/event-stream",
"accept-language": "en-US,en;q=0.9",
"authorization": `Bearer ${token}`,
"content-type": "application/json",
"sec-ch-ua": "\"Not_A Brand\";v=\"99\", \"Google Chrome\";v=\"109\", \"Chromium\";v=\"109\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"macOS\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-openai-assistant-app-id": "",
"origin": "https://chat.openai.com"
},
})
let body2 = await response.json()
console.log(response, body2)
let id = body2.items[0].id
console.log(id)
body = { "action": "next", "conversation_id": id, "messages": [{ "id": "73954541-ff9e-4785-85e4-d45527ccca73", "author": { "role": "user" }, "content": { "content_type": "text", "parts": [subs] } }], "parent_message_id": uuid1, "model": "text-davinci-002-render-sha", "timezone_offset_min": 240 }
}
body = JSON.stringify(body);
const response = await fetch("https://chat.openai.com/backend-api/conversation", {
"headers": {
"accept": "text/event-stream",
"accept-language": "en-US,en;q=0.9",
"authorization": `Bearer ${token}`,
"content-type": "application/json",
"sec-ch-ua": "\"Not_A Brand\";v=\"99\", \"Google Chrome\";v=\"109\", \"Chromium\";v=\"109\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"macOS\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-openai-assistant-app-id": "",
"origin": "https://chat.openai.com"
},
"referrer": "https://chat.openai.com/chat",
"referrerPolicy": "strict-origin-when-cross-origin",
"body": body,
"method": "POST",
"mode": "cors",
"credentials": "include"
});
// Access the body property of the response, which is a ReadableStream
const reader = response.body.getReader();
// Recursive function to read and process chunks of data from the stream
const readChunk = async () => {
try {
// Read a chunk of data from the stream
const { value, done } = await reader.read();
// If the stream is done, exit the recursion
if (done) {
console.log('Stream complete.');
await deleteConvo(token)
return;
}
// Process the received data chunk (e.g., convert to string and log to console)
const chunkText = new TextDecoder().decode(value);
let chunks = chunkText.split("\n\n")
chunks = chunks.map((chunk) => {
return chunk.replaceAll('data: ', '')
})
console.log(chunks)
if (chunks[0].includes("[DONE]")) {
if (parts.length != questionParts.length) {
// add the last final text to the parts array
parts.push(chunks[1])
console.log("parts: ", parts)
return handleStreamedResponse(token, question, videoId, parts)
}
console.log("done")
await deleteConvo(token)
return;
}
// console.log(chunkText.replace('data: ', ''))
let chunkJson
for (let i = 0; i < chunks.length; i++) {
if (chunks[i]) {
try {
chunkJson = JSON.parse(chunks[i])
break;
} catch (e) {
console.log(e)
}
}
}
if (!chunkJson) {
return readChunk();
}
let finalText = chunkJson.message.content.parts[0]
console.log(finalText)
// Check if the tab is still open before sending the message
chrome.tabs.get(targetTabId, (tab) => {
if (chrome.runtime.lastError) {
console.log('Tab is closed. Stopping streaming.');
} else {
// Send the message to the content script in the specified tab
chrome.tabs.sendMessage(targetTabId, { action: 'streamed_text_' + videoId, text: finalText });
}
});
// Continue reading the next chunk
return readChunk();
} catch (error) {
// Handle any errors that may occur while reading the stream
console.error('Error while reading the stream:', error);
}
};
// Start reading the stream
readChunk();
// deleteConvo(token)
}
async function deleteConvo(token) {
// https://chat.openai.com/backend-api/conversations?offset=0&limit=20
let response = await fetch("https://chat.openai.com/backend-api/conversations?offset=0&limit=20", {
"headers": {
"accept": "text/event-stream",
"accept-language": "en-US,en;q=0.9",
"authorization": `Bearer ${token}`,
"content-type": "application/json",
"sec-ch-ua": "\"Not_A Brand\";v=\"99\", \"Google Chrome\";v=\"109\", \"Chromium\";v=\"109\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"macOS\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-openai-assistant-app-id": "",
"origin": "https://chat.openai.com"
},
})
let body = await response.json()
console.log(response, body)
let id = body.items[0].id
console.log(id)
let deleteResponse = await fetch(`https://chat.openai.com/backend-api/conversation/${id}`, {
"headers": {
"accept": "text/event-stream",
"accept-language": "en-US,en;q=0.9",
"authorization": `Bearer ${token}`,
"content-type": "application/json",
"sec-ch-ua": "\"Not_A Brand\";v=\"99\", \"Google Chrome\";v=\"109\", \"Chromium\";v=\"109\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"macOS\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-openai-assistant-app-id": "",
"origin": "https://chat.openai.com"
},
"method": "PATCH",
"body": `{"is_visible":false}`
})
let deleteBody = await deleteResponse.json()
console.log(deleteResponse, deleteBody)
}
// Listen for messages from content script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === 'getAccessToken') {
getToken().then(accessToken => {
targetTabId = sender.tab.id
handleStreamedResponse(accessToken, request.subs, request.videoId, [])
sendResponse({ accessToken: accessToken });
});
// Indicate that the response will be sent asynchronously
return true;
}
});
// detect when the tab url changes, and it's a youtube video
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.url && changeInfo.url.includes('youtube.com/watch')) {
// send message to content script to start the stream
console.log("New Video")
chrome.tabs.sendMessage(tabId, { action: 'start_stream' });
}
// otherwise detect if the page is refreshed
else if (changeInfo.status === 'complete') {
// send message to content script to start the stream
console.log("Page Refreshed")
chrome.tabs.sendMessage(tabId, { action: 'start_stream' });
}
});