From 21540e70467452b01f37fe3b9e3d4ea2b5dbac0f Mon Sep 17 00:00:00 2001 From: Ruthenic Date: Mon, 13 Feb 2023 17:58:59 -0500 Subject: [PATCH] this code is an affront to any god, lord, anyone really --- src/Chat.ts | 16 +++++++++++++--- src/Client.ts | 25 +++++++++++++++++++++++-- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/src/Chat.ts b/src/Chat.ts index d24b6f8..003c9c7 100644 --- a/src/Chat.ts +++ b/src/Chat.ts @@ -84,10 +84,11 @@ export default class Chat { * @returns Object with replies */ public async sendMessage(message: string): Promise { - if (!this.characterInternalId) + if (!this.characterInternalId) { this.characterInternalId = ( await this.#client.fetchCharacterInfo(this.characterId) ).participant__user__username; + } const payload = { history_external_id: this.historyId, @@ -125,7 +126,8 @@ export default class Chat { Accept: "application/json", "Content-Type": "application/json", }, - } + }, + false, ); const reader = res.body?.getReader(); @@ -139,6 +141,14 @@ export default class Chat { reply = new TextDecoder("utf-8").decode(value); } - return JSON.parse(reply); + reply = '{"replies": [{"text": "' + + reply.split(' {"replies": [{"text": "').at(-1); + + try { + return JSON.parse(reply); + } catch (e) { + console.log(e); + return JSON.parse(atob(reply)); + } } } diff --git a/src/Client.ts b/src/Client.ts index ffe004a..770821b 100644 --- a/src/Client.ts +++ b/src/Client.ts @@ -1,5 +1,7 @@ import Chat from "./Chat.ts"; +import { wrapFetch } from "https://deno.land/x/another_cookiejar@v5.0.2/mod.ts"; + interface FetchOptions extends RequestInit { client?: Deno.HttpClient; } @@ -57,6 +59,7 @@ interface SearchResult { export default class Client { public token?: string; #client?: Deno.HttpClient; + #cookieFetch = wrapFetch(); /** * Initalizes a HTTP(S) proxy for each request (Requires --unstable) @@ -73,6 +76,7 @@ export default class Client { async fetch( input: string | URL | Request, options?: FetchOptions | undefined, + retryUntilSuccess = true, ) { if (this.#client) { options = { @@ -80,7 +84,23 @@ export default class Client { ...options, }; } - return await fetch(input, options); + let res = await this.#cookieFetch(input, options); + let resText = await res.clone().text(); + + while ( + !resText.startsWith("{") && !resText.startsWith("[") && retryUntilSuccess + ) { + console.log("Failed request! Retrying..."); + await new Promise((resolve) => setTimeout(resolve, 1000)); + res = await this.#cookieFetch(input, options); + resText = await res.clone().text(); + } + + return { + body: res.body, + text: () => res, + json: () => JSON.parse(resText), + }; } /** @@ -170,7 +190,7 @@ export default class Client { }, }, ); - const { character } = await res.json(); + const { character } = res.json(); return character; } @@ -193,6 +213,7 @@ export default class Client { "Content-Type": "application/json", }, }); + const resText = await res.text(); const { characters } = await res.json(); if (!Array.isArray(characters)) {