-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathrequester.js
305 lines (248 loc) · 11.5 KB
/
requester.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
const puppeteer = require("puppeteer-extra");
const StealthPlugin = require("puppeteer-extra-plugin-stealth")
const fs = require("fs");
let chromiumPath = process.platform === "linux" ? "/usr/bin/chromium-browser" : null;
if (chromiumPath && !fs.existsSync(chromiumPath)) console.log("[node_characterai] Puppeteer - Warning: the specified Chromium path for puppeteer could not be located. If the script does not work properly, you may need to specify a path to the Chromium binary file/executable.");
class Requester {
browser = undefined;
page = undefined;
#initialized = false;
#hasDisplayed = false;
headless = "new";
puppeteerPath = undefined;
puppeteerLaunchArgs = [
"--fast-start",
"--disable-extensions",
"--no-sandbox",
"--disable-setuid-sandbox",
"--no-gpu",
"--disable-background-timer-throttling",
"--disable-renderer-backgrounding",
"--override-plugin-power-saver-for-testing=never",
"--disable-extensions-http-throttling",
"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.3"
];
puppeteerNoDefaultTimeout = false;
puppeteerProtocolTimeout = 0;
usePlus = false;
forceWaitingRoom = false;
constructor() {}
isInitialized() {
return this.#initialized;
}
async waitForWaitingRoom(page) {
// Enable force waiting room to ensure you check for waiting room even on C.AI+
if (!this.usePlus || (this.usePlus && this.forceWaitingRoom)) {
return new Promise(async (resolve) => {
try {
let interval;
let pass = true;
const minute = 60000; // Update every minute
// Keep waiting until false
async function check() {
if (pass) {
pass = false;
const waitingRoomTimeLeft = await page.evaluate(async() => {
try {
const contentContainer = document.querySelector(".content-container");
const sections = contentContainer.querySelectorAll("section");
const h2Element = sections[1].querySelector("h2");
const h2Text = h2Element.innerText;
const regex = /\d+/g;
const matches = h2Text.match(regex);
if (matches) return matches[0];
} catch (error) {
return;
}
}, minute);
const waiting = (waitingRoomTimeLeft != null);
if (waiting) {
console.log(`[node_characterai] Puppeteer - Currently in cloudflare's waiting room. Time left: ${waitingRoomTimeLeft}`);
} else {
resolve();
clearInterval(interval);
}
pass = true;
};
}
interval = setInterval(check, minute);
await check();
} catch (error) {
console.log("[node_characterai] Puppeteer - There was a fatal error while checking for cloudflare's waiting room");
console.log(error);
}
});
}
}
async initialize() {
if (!this.isInitialized());
// Handle chromium tabs cleanup
process.on('exit', () => {
this.uninitialize();
});
console.log("[node_characterai] Puppeteer - This is an experimental feature. Please report any issues on github.");
puppeteer.use(StealthPlugin());
const browser = await puppeteer.launch({
headless: this.headless,
args: this.puppeteerLaunchArgs,
protocolTimeout: this.puppeteerProtocolTimeout || 0, // Props to monckey100
executablePath: this.puppeteerPath || null
});
this.browser = browser;
let page = await browser.pages();
page = page[0];
this.page = page;
await page.setRequestInterception(false);
page.setViewport({
width: 1920 + Math.floor(Math.random() * 100),
height: 3000 + Math.floor(Math.random() * 100),
deviceScaleFactor: 1,
hasTouch: false,
isLandscape: false,
isMobile: false,
});
await page.setJavaScriptEnabled(true);
await page.setDefaultNavigationTimeout(0);
const userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
await page.setUserAgent(userAgent);
// Special thanks to @Parking-Master for this fix
await page.deleteCookie();
const client = await page.target().createCDPSession();
await client.send("Network.clearBrowserCookies");
await client.send("Network.clearBrowserCache");
await page.goto("https://beta.character.ai/favicon.ico");
await page.evaluate(() => localStorage.clear());
// If there is no waiting room, the script will continue anyway
await this.waitForWaitingRoom(page);
console.log("[node_characterai] Puppeteer - Done with setup");
}
async request(url, options) {
const page = this.page;
const method = options.method;
const body = (method == "GET" ? {} : options.body);
const headers = options.headers;
let response;
try {
const payload = {
method: method,
headers: headers,
body: body
}
await page.setRequestInterception(false);
if (!this.#hasDisplayed) {
console.log("[node_characterai] Puppeteer - Eval-fetching is an experimental feature and may be slower. Please report any issues on github")
this.#hasDisplayed = true;
}
if (url.endsWith("/streaming/")) {
// Bless @roogue & @drizzle-mizzle for the code here!
response = await page.evaluate(async (payload, url) => {
const response = await fetch(url, payload);
const data = await response.text();
const matches = data.match(/\{.*\}/g);
const responseText = matches[matches.length - 1];
let result = {
code: 500
};
if (!matches) result = null;
else {
result.code = 200;
result.response = responseText;
};
return result;
}, payload, url);
response.status = () => response.code; // compatibilty reasons
response.text = () => response.response; // compatibilty reasons
} else {
await page.setRequestInterception(true);
let initialRequest = true;
page.once("request", request => {
var data = {
"method": method,
"postData": body,
"headers": headers
};
if (request.isNavigationRequest() && !initialRequest) {
return request.abort();
}
try {
initialRequest = false;
request.continue(data);
} catch (error) {
console.log("[node_characterai] Puppeteer - Non fatal error: " + error);
}
});
response = await page.goto(url, { waitUntil: "domcontentloaded" });
}
} catch (error) {
console.log("[node_characterai] Puppeteer - " + error)
}
return response;
}
async uploadImage(options, buffer) {
const url = "https://beta.character.ai/chat/upload-image/";
const page = this.page;
const method = options.method;
const headers = options.headers;
const mime = options.mime;
let response;
try {
const payload = {
method: method,
headers: headers,
body: buffer
}
await page.setRequestInterception(false);
if (!this.#hasDisplayed) {
console.log("[node_characterai] Puppeteer - Image-uploading is an experimental feature and may have bugs. Please report any issues on github")
this.#hasDisplayed = true;
}
response = await page.evaluate(async (payload, url, mime) => {
const formData = new FormData();
console.log(mime);
const b64 = payload.body;
// converted from b64 to blob
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
const blob = b64toBlob(b64.includes("base64,") ? b64.split("base64,")[1] : b64);
const file = new File([blob], "image", { type: mime });
formData.append("image", file);
delete payload.headers['Content-Type'];
payload.body = formData;
const response = await fetch(url, payload);
const data = await response.text();
let result = {
code: 500
};
result.code = 200;
result.response = data;
return result;
}, payload, url, mime);
response.status = () => response.code; // compatibilty reasons
response.text = () => response.response; // compatibilty reasons
} catch (error) {
console.log(error);
console.log("[node_characterai] Puppeteer - " + error)
}
return response;
}
async uninitialize() {
// Handle chromium tabs cleanup
try {
this.browser.close();
} catch {}
}
};
module.exports = Requester;