From c4ec7f33b80835b66fc7a336dbc897c3f8761223 Mon Sep 17 00:00:00 2001 From: Elysia <71698422+aiko-chan-ai@users.noreply.github.com> Date: Tue, 11 Jul 2023 22:15:48 +0700 Subject: [PATCH] refactor: remove axios --- package.json | 1 - src/client/Client.js | 10 ++--- src/structures/WebEmbed.js | 26 +++--------- src/util/RemoteAuth.js | 86 +++++++++++++++++--------------------- src/util/Util.js | 17 +++++++- typings/index.d.ts | 1 - 6 files changed, 65 insertions(+), 76 deletions(-) diff --git a/package.json b/package.json index 95ebf7d..4a1da91 100644 --- a/package.json +++ b/package.json @@ -59,7 +59,6 @@ "@sapphire/shapeshift": "^3.8.2", "@types/node-fetch": "^2.6.3", "@types/ws": "^8.5.4", - "axios": "1.1", "chalk": "^4.1.2", "discord-api-types": "^0.37.40", "fetch-cookie": "^2.1.0", diff --git a/src/client/Client.js b/src/client/Client.js index 294991b..feafc23 100644 --- a/src/client/Client.js +++ b/src/client/Client.js @@ -4,8 +4,8 @@ const process = require('node:process'); const { setInterval, setTimeout } = require('node:timers'); const { Collection } = require('@discordjs/collection'); const { getVoiceConnection } = require('@discordjs/voice'); -const axios = require('axios'); const chalk = require('chalk'); +const fetch = require('node-fetch'); const BaseClient = require('./BaseClient'); const ActionsManager = require('./actions/ActionsManager'); const ClientVoiceManager = require('./voice/ClientVoiceManager'); @@ -505,11 +505,11 @@ class Client extends BaseClient { * @returns {Promise} */ async checkUpdate() { - const res_ = await axios - .get(`https://registry.npmjs.com/${encodeURIComponent('discord.js-selfbot-v13')}`) - .catch(() => {}); + const res_ = await ( + await fetch(`https://registry.npmjs.com/${encodeURIComponent('discord.js-selfbot-v13')}`) + ).json(); try { - const latest_tag = res_.data['dist-tags'].latest; + const latest_tag = res_['dist-tags'].latest; this.emit('update', Discord.version, latest_tag); this.emit('debug', `${chalk.greenBright('[OK]')} Check Update success`); } catch { diff --git a/src/structures/WebEmbed.js b/src/structures/WebEmbed.js index 670f901..e562e66 100644 --- a/src/structures/WebEmbed.js +++ b/src/structures/WebEmbed.js @@ -1,8 +1,8 @@ 'use strict'; -const axios = require('axios'); const baseURL = 'https://webembed-sb.onrender.com/embed?'; const hiddenCharter = '||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||'; +const fetch = require('node-fetch'); const { RangeError } = require('../errors'); const Util = require('../util/Util'); @@ -60,13 +60,6 @@ class WebEmbed { * @see https://github.com/aiko-chan-ai/WebEmbed */ this.baseURL = data.baseURL ?? baseURL; - - /** - * Shorten API - * @type {?string} https://webembed-sb.onrender.com/short?url= - * @see https://github.com/aiko-chan-ai/WebEmbed - */ - this.shortenAPI = data.shortenAPI; } /** * @private @@ -371,7 +364,7 @@ class WebEmbed { } const fullURL = `${this.baseURL}${arrayQuery.join('&')}`; if (this.shorten) { - const url = await this.constructor.getShorten(fullURL, this); + const url = await this.constructor.getShorten(fullURL); if (!url) console.log('Cannot shorten URL in WebEmbed'); return this.hidden ? `${hiddenCharter} ${url || fullURL}` : url || fullURL; } else { @@ -379,18 +372,11 @@ class WebEmbed { } } - static async getShorten(url, embed) { - const APIurl = ['https://tinyurl.com/api-create.php?url=']; - const shorten = `${ - embed.shortenAPI && typeof embed.shortenAPI == 'string' - ? embed.shortenAPI - : APIurl[Math.floor(Math.random() * APIurl.length)] - }${encodeURIComponent(url)}`; + static async getShorten(url) { + const shorten = `https://tinyurl.com/api-create.php?url=${encodeURIComponent(url)}`; try { - const res = await axios.get(`${shorten}`); - if (typeof res.data === 'string') return res.data; - else if (typeof res.data === 'object') return res.data.shorten; - else throw new Error('Unknown error'); + const res = await (await fetch(shorten)).text(); + return res; } catch { return undefined; } diff --git a/src/util/RemoteAuth.js b/src/util/RemoteAuth.js index 19d9bb0..ff89ec1 100644 --- a/src/util/RemoteAuth.js +++ b/src/util/RemoteAuth.js @@ -4,8 +4,8 @@ const crypto = require('crypto'); const EventEmitter = require('node:events'); const { setTimeout } = require('node:timers'); const { StringDecoder } = require('string_decoder'); -const axios = require('axios'); const chalk = require('chalk'); +const fetch = require('node-fetch'); const { encode: urlsafe_b64encode } = require('safe-base64'); const WebSocket = require('ws'); const { defaultUA } = require('./Constants'); @@ -268,13 +268,8 @@ new DiscordAuthWebsocket({ } } _throwError(error) { - if (error.request) { - // Axios error - console.log(chalk.red(`[DiscordRemoteAuth] ERROR`), error.message, error.response); - throw new Error(`Request failed with status code ${error.response.status}`); - } else { - throw error; - } + console.log(chalk.red(`[DiscordRemoteAuth] ERROR`), error); + throw error; } _send(op, data) { if (!this.ws) this._throwError(new Error('WebSocket is not connected.')); @@ -432,46 +427,43 @@ new DiscordAuthWebsocket({ ); } this._logger('debug', 'Find real token...'); - const res = await axios - .post( - `https://discord.com/api/v${this.options.apiVersion}/users/@me/remote-auth/login`, - captchaSolveData - ? { - ticket: this.token, - captcha_rqtoken: this.captchaCache.captcha_rqtoken, - captcha_key: captchaSolveData, - } - : { - ticket: this.token, - }, - { - headers: { - Accept: '*/*', - 'Accept-Language': 'en-US', - 'Content-Type': 'application/json', - 'Sec-Fetch-Dest': 'empty', - 'Sec-Fetch-Mode': 'cors', - 'Sec-Fetch-Site': 'same-origin', - 'X-Debug-Options': 'bugReporterEnabled', - 'X-Super-Properties': `${Buffer.from(JSON.stringify(this.options.wsProperties), 'ascii').toString( - 'base64', - )}`, - 'X-Discord-Locale': 'en-US', - 'User-Agent': this.options.userAgent, - Referer: 'https://discord.com/channels/@me', - Connection: 'keep-alive', - Origin: 'https://discord.com', - }, + const res = await ( + await fetch(`https://discord.com/api/v${this.options.apiVersion}/users/@me/remote-auth/login`, { + method: 'POST', + headers: { + Accept: '*/*', + 'Accept-Language': 'en-US', + 'Content-Type': 'application/json', + 'Sec-Fetch-Dest': 'empty', + 'Sec-Fetch-Mode': 'cors', + 'Sec-Fetch-Site': 'same-origin', + 'X-Debug-Options': 'bugReporterEnabled', + 'X-Super-Properties': `${Buffer.from(JSON.stringify(this.options.wsProperties), 'ascii').toString('base64')}`, + 'X-Discord-Locale': 'en-US', + 'User-Agent': this.options.userAgent, + Referer: 'https://discord.com/channels/@me', + Connection: 'keep-alive', + Origin: 'https://discord.com', }, - ) - .catch(e => { - if (e.response.data?.captcha_key) { - this.captchaCache = e.response.data; - } else { - this._throwError(e); - this.captchaCache = null; - } - }); + body: JSON.stringify( + captchaSolveData + ? { + ticket: this.token, + captcha_rqtoken: this.captchaCache.captcha_rqtoken, + captcha_key: captchaSolveData, + } + : { + ticket: this.token, + }, + ), + }) + ).json(); + if (res?.captcha_key) { + this.captchaCache = res; + } else { + this._throwError(new Error('Request failed. Please try again.', res)); + this.captchaCache = null; + } if (!res && this.captchaCache) { this._logger('default', 'Captcha is detected. Please solve the captcha to continue.'); this._logger('debug', 'Try call captchaSolver()', this.captchaCache); diff --git a/src/util/Util.js b/src/util/Util.js index 52d6b3b..fa5b88f 100644 --- a/src/util/Util.js +++ b/src/util/Util.js @@ -3,7 +3,7 @@ const { parse } = require('node:path'); const process = require('node:process'); const { Collection } = require('@discordjs/collection'); -const axios = require('axios'); +const fetch = require('node-fetch'); const { Colors } = require('./Constants'); const { RangeError, TypeError } = require('../errors'); const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k); @@ -722,7 +722,20 @@ class Util extends null { } static uploadFile(data, url) { - return axios.put(url, data); + return new Promise((resolve, reject) => { + fetch(url, { + method: 'PUT', + body: data, + }) + .then(res => { + if (res.ok) { + resolve(res); + } else { + reject(res); + } + }) + .catch(reject); + }); } static testImportModule(name) { diff --git a/typings/index.d.ts b/typings/index.d.ts index 3925dc8..6647b70 100644 --- a/typings/index.d.ts +++ b/typings/index.d.ts @@ -2317,7 +2317,6 @@ export class WebEmbed { public constructor(data?: WebEmbedOptions); public author: MessageEmbedAuthor | null; public baseURL: string | undefined; - public shortenAPI: string | undefined; public color: number | null; public description: string | null; public image: MessageEmbedImage | null;