-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.ts
420 lines (355 loc) · 13 KB
/
client.ts
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import { Languages, Themes, Answers } from './storage';
const AVAILABLE_THEMES: { [key in Languages]: Themes[] } = {
[Languages.English]: [Themes.Character, Themes.Animals, Themes.Objects],
[Languages.Arabic]: [Themes.Character],
[Languages.Chinese]: [Themes.Character],
[Languages.German]: [Themes.Character, Themes.Animals],
[Languages.Spanish]: [Themes.Character, Themes.Animals],
[Languages.French]: [Themes.Character, Themes.Animals, Themes.Objects],
[Languages.Hebrew]: [Themes.Character],
[Languages.Italian]: [Themes.Character, Themes.Animals],
[Languages.Japanese]: [Themes.Character, Themes.Animals],
[Languages.Korean]: [Themes.Character],
[Languages.Dutch]: [Themes.Character],
[Languages.Polish]: [Themes.Character],
[Languages.Portuguese]: [Themes.Character],
[Languages.Russian]: [Themes.Character],
[Languages.Turkish]: [Themes.Character],
[Languages.Indonesian]: [Themes.Character],
};
class WinResult {
/**
* Proposition identifier
*/
propositionId = 0;
/**
* Base proposition identifier
*/
basePropositionId = 0;
/**
* Proposition submitter
*/
submittedBy = "";
/**
* Name of the proposition
*/
name = "";
/**
* Picture URL of the proposition
*/
pictureUrl = "";
/**
* Description of the proposition
*/
description = "";
reset() {
this.propositionId = 0;
this.basePropositionId = 0;
this.submittedBy = "";
this.name = "";
this.pictureUrl = "";
this.description = "";
}
}
class AnswerResult {
/**
* Represents if Akinator won or not
*/
won = false;
/**
* Represents the file name of Akinator's attitude
*/
akitude = "";
/**
* Represents the step of how far the game has gone
*/
step = 0;
/**
* Represents the progression in percentage (%) of the game
*/
progression = 0;
/**
* Represents the currently asked question
*/
question = "";
/**
* Represents if Akinator lost or not
*/
ko = false;
reset() {
this.won = false;
this.akitude = "";
this.step = 0;
this.progression = 0;
this.question = "";
this.ko = false;
}
}
class AkinatorClient {
private _session = "";
private _signature = "";
private _url = "";
private _identifiant = "";
/**
* The language Akinator will use
*/
language: Languages = Languages.English;
/**
* Child mode disables NSFW
*/
childMode: boolean = true;
/**
* Theme to use (some themes might not be available to all languages)
*/
theme: Themes = Themes.Character;
private _akitude = "";
private _progression = "";
private _question = "";
private _step = "";
private _step_last_proposition = "";
// winning
private _idProposition = "";
private _idBaseProposition = "";
private _nameProposition = "";
private _descriptionProposition = "";
private _photo = "";
private _pseudo = "";
private _flagPhoto = 0;
private _currentAnswerResult = new AnswerResult();
private _currentWinResult = new WinResult();
// getters
/**
* Represents the latest result of the latest answer
*/
public get answerResult() { return this._currentAnswerResult; }
/**
* Represents the latest win result
*/
public get winResult() { return this._currentWinResult; }
/**
* Represents the file name of Akinator's attitude
*/
public get akitude() { return this._akitude; }
/**
* Represents the progression in percentage (%) of the game
*/
public get progression(): number { return Number.parseInt(this._progression); }
/**
* Represents the currently asked question
*/
public get question() { return this._question; }
/**
* Represents the step of how far the game has gone
*/
public get step(): number { return Number.parseInt(this._step); }
/**
* Represents if Akinator won or not
*/
public get won() { return this.answerResult.won; }
/**
* Represents if Akinator lost or not
*/
public get ko() { return this.answerResult.ko; }
/**
* Creates a new Akinator client.
* @param language The language Akinator will use
* @param childMode Child mode disables NSFW
* @param theme Theme to use (some themes might not be available to all languages)
*/
constructor(language: Languages, childMode: boolean, theme: Themes) {
this.language = language;
this.childMode = childMode;
this.theme = theme;
}
#getChildModeString() { return `${this.childMode}`; }
#getThemeAsNumber() { return this.theme as number; }
static #createForm(options: any) {
const formData = new FormData();
for (const [key, value] of Object.entries(options))
formData.append(key, value as string);
return formData;
}
/**
* Starts a new akinator game under this client
* @returns First question result
*/
async start(): Promise<AnswerResult> {
this.#resetResults();
await this.#fetchRegion(this.language);
const request = await this.#request("/game", {
method: "POST",
body: AkinatorClient.#createForm({
sid: this.#getThemeAsNumber(),
cm: this.#getChildModeString()
})
});
if (request.status != 200)
throw new Error("HTTP Error: " + request.statusText);
const response = await request.text();
const sessionMatch = response.match(/name="session" id="session" value="([^"]+)"/);
const signatureMatch = response.match(/name="signature" id="signature" value="([^"]+)"/);
if (sessionMatch && signatureMatch) {
this._session = sessionMatch[1];
this._signature = signatureMatch[1];
}
const questionMatch = response.match(/<div class="bubble-body"><p class="question-text" id="question-label">(.*?)<\/p><\/div>/);
if (questionMatch && questionMatch[1])
this._question = questionMatch[1];
const identifiantMatch = response.match(/localStorage\.setItem\('identifiant', '([^']+)'\);/);
if (identifiantMatch && identifiantMatch[1])
this._identifiant = identifiantMatch[1];
this._progression = "0.00000";
this._step = "0";
this._currentAnswerResult.akitude = "defi.png";
this._currentAnswerResult.step = Number.parseInt(this._step);
this._currentAnswerResult.progression = Number.parseFloat(this._progression);
this._currentAnswerResult.question = this._question;
return this._currentAnswerResult;
}
#update(action: string, response: any) {
if (action == "answer" || action == "back") {
const { akitude, step, progression, question, completion } = response;
if (completion == "KO") {
this._currentAnswerResult.ko = true;
return this._currentAnswerResult;
}
this._akitude = akitude;
this._step = step;
this._progression = progression;
this._question = question;
this._currentAnswerResult.akitude = this._akitude;
this._currentAnswerResult.step = Number.parseInt(this._step);
this._currentAnswerResult.progression = Number.parseFloat(this._progression);
this._currentAnswerResult.question = this._question;
return this._currentAnswerResult;
}
const { name_proposition, description_proposition, pseudo, photo, flag_photo } = response;
this._nameProposition = name_proposition;
this._descriptionProposition = description_proposition;
this._pseudo = pseudo;
this._photo = photo;
this._flagPhoto = flag_photo;
this._currentWinResult.propositionId = Number.parseInt(this._idProposition);
this._currentWinResult.basePropositionId = Number.parseInt(this._idBaseProposition);
this._currentWinResult.submittedBy = this._pseudo;
this._currentWinResult.name = this._nameProposition;
this._currentWinResult.pictureUrl = this._photo;
this._currentWinResult.description = this._descriptionProposition;
this._currentAnswerResult.won = true;
return this._currentAnswerResult;
}
#resetResults() {
this._currentWinResult.reset();
this._currentAnswerResult.reset();
}
async #fetchRegion(language: Languages) {
this.language = language;
this._url = `https://${language}.akinator.com`;
const request = await this.#request("", { method: "GET" });
if (request.status != 200)
throw new Error("HTTP Error: " + request.statusText);
const availableThemes: Themes[] = AVAILABLE_THEMES[this.language];
if (!availableThemes.includes(this.theme))
throw new Error("Theme not supported in this language. Sorry!");
}
async #request(endpoint: string, options: RequestInit) {
return await fetch(this._url + endpoint, options);
}
// https://en.akinator.com/answer
/**
* Answers Akinator
* @param answer The answer
* @returns Question resulting this answer
*/
async answer(answer: Answers) : Promise<AnswerResult> {
const request = await this.#request("/answer", {
method: "POST",
body: AkinatorClient.#createForm({
step: this._step,
progression: this._progression,
sid: this.#getThemeAsNumber(),
cm: this.#getChildModeString(),
answer: answer as number,
step_last_proposition: this._step_last_proposition,
session: this._session,
signature: this._signature
})
});
const response = await request.json();
if (request.status != 200)
throw new Error("HTTP Error: " + request.statusText);
const idProposition = response["id_proposition"];
return this.#update(idProposition ? "win" : "answer", response) as AnswerResult;
}
// https://en.akinator.com/cancel_answer
/**
* Corrects an answer and goes back
* @returns Previous question
*/
async back(): Promise<AnswerResult> {
if (this._step == "0") throw new Error("Cannot go any further.");
const request = await this.#request("/cancel_answer", {
method: "POST",
body: AkinatorClient.#createForm({
step: this._step,
progression: this._progression,
sid: this.#getThemeAsNumber(),
cm: this.#getChildModeString(),
session: this._session,
signature: this._signature
})
});
const response = await request.json();
if (request.status != 200)
throw new Error("HTTP Error: " + request.statusText);
return this.#update("back", response) as AnswerResult;
}
// https://en.akinator.com/exclude
/**
* Continues the game even if Akinator won
*/
async continue() {
if (!this.won) throw new Error("You cannot continue a game that's ongoing.");
if (this.ko) throw new Error("You cannot continue because Akinator has lost.");
const request = await this.#request("/exclude", {
method: "POST",
body: AkinatorClient.#createForm({
step: this._step,
sid: this.#getThemeAsNumber(),
cm: this.#getChildModeString(),
progression: this._progression,
session: this._session,
signature: this._signature
})
});
this._currentAnswerResult.won = false;
const response = await request.json();
if (request.status != 200)
throw new Error("HTTP Error: " + request.statusText);
return this.#update("back", response) as AnswerResult;
}
// https://en.akinator.com/choice
/**
* Tells Akinator he won
*/
async submitWin() {
if (!this.won) throw new Error("You cannot submit Akinator's result while the game is ongoing.");
const request = await this.#request("/choice", {
method: "POST",
body: AkinatorClient.#createForm({
sid: this.#getThemeAsNumber(),
pid: this._idProposition,
identifiant: this._identifiant,
pflag_photo: this._flagPhoto,
charac_name: this._nameProposition,
charac_desc: this._descriptionProposition,
session: this._session,
signature: this._signature,
step: this._step,
})
});
if (request.status != 302 && request.status != 200)
throw new Error("HTTP Error: " + request.statusText);
}
}
export { AkinatorClient, Languages, Themes, Answers };