forked from realcoloride/node_characterai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
requester.js
255 lines (203 loc) · 9.1 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
const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth')
class Requester {
browser = undefined;
page = undefined;
#initialized = false;
#hasDisplayed = false;
#headless = 'new';
puppeteerPath = undefined;
usePlus = false;
constructor() {
}
isInitialized() {
return this.#initialized;
}
async waitForWaitingRoom(page) {
if (!this.usePlus) {
return new Promise(async(resolve) => {
try {
let interval;
let pass = true;
await page.goto("https://beta.character.ai");
const minute = 1000 * 60; // 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[i].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 {
clearInterval(interval);
resolve();
}
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());
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: [
'--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'
],
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 = 'CharacterAI/1.0.0 (iPhone; iOS 14.4.2; Scale/3.00)';
await page.setUserAgent(userAgent);
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
if (this.usePlus) url.replace('beta.character.ai', 'plus.character.ai');
try {
const payload = {
method: method,
headers: headers,
body: body
}
if (url.endsWith("/streaming/")) {
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;
}
// 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: 'networkidle2' });
}
} catch (error) {
console.log("[node_characterai] Puppeteer - " + error)
}
return response;
}
async uploadBuffer(buffer, client) {
const page = this.page;
let response
try {
await page.setRequestInterception(false);
response = await page.evaluate(
async (headers, buffer) => {
var result = {
code: 500
};
const blob = new Blob([buffer], { type: 'image/png' });
const formData = new FormData();
formData.append("image", blob, 'image.png');
let head = headers;
delete head["Content-Type"];
// ^ Is this even being used?
const uploadResponse = await fetch("https://beta.character.ai/chat/upload-image/", {
headers: headers,
method: "POST",
body: formData
})
if (uploadResponse.status == 200) {
result.code = 200;
let uploadResponseJSON = await uploadResponse.json();
result.response = uploadResponseJSON.value;
}
return result;
},
client.getHeaders(), buffer
);
response.status = () => response.code // compatibilty reasons
response.body = () => response.response // compatibilty reasons
} catch (error) {
console.log("[node_characterai] Puppeteer - " + error)
}
return response;
}
}
module.exports = Requester;