Skip to content

Commit

Permalink
🧳 Migration to ESM
Browse files Browse the repository at this point in the history
  • Loading branch information
Ashu11-A committed Jun 11, 2024
1 parent b8ae32f commit d10f97a
Show file tree
Hide file tree
Showing 44 changed files with 814 additions and 207 deletions.
28 changes: 13 additions & 15 deletions core/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import { Auth } from '@/controller/auth'
import { Auth } from '@/controller/auth.js'
import { existsSync } from 'fs'
import { readFile, rm } from 'fs/promises'
import { join } from 'path'
import { argv, cwd } from 'process'
import prompts from 'prompts'
import 'reflect-metadata'
import { PKG_MODE } from '.'
import { Plugins } from './controller/plugins'
import { SocketController } from './controller/socket'
import { generatePort } from './functions/port'
import { Crypt } from './controller/crypt'
import { License } from './controller/license'
import('dotenv').then(async (dotenv) => {
dotenv.config()
})
import yargs from 'yargs'
import { Crypt } from './controller/crypt.js'
import { License } from './controller/license.js'
import { Plugins } from './controller/plugins.js'
import { SocketController } from './controller/socket.js'
import { generatePort } from './functions/port.js'
import { PKG_MODE } from './index.js'
import { config } from 'dotenv'

interface Args {
command: string
Expand All @@ -28,13 +27,12 @@ const argsList: Args[] = [
];

(async () => {
prompts.override((await import('yargs')).argv)
prompts.override(yargs().argv)
config()

await new License().checker()
await new Crypt().checker()
const auth = new Auth()

await auth.login()
await auth.validator()
await new Auth().checker()

if (existsSync(join(cwd(), 'entries'))) await rm(join(cwd(), 'entries'), { recursive: true })

Expand Down
53 changes: 28 additions & 25 deletions core/src/controller/auth.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { RootPATH } from '@/index.js'
import { AccessToken, AuthData, BotInfo, User } from '@/interfaces/auth.js'
import { DataCrypted } from '@/interfaces/crypt.js'
import { CronJob } from 'cron'
import { rm } from 'fs/promises'
import prompts, { Choice, PromptObject } from 'prompts'
import { RootPATH } from '@/index.js'
import { api } from '../../package.json'
import { credentials, Crypt } from './crypt.js'
import fetch from 'node-fetch'

const emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/g
const crypt = new Crypt()
Expand Down Expand Up @@ -40,9 +41,11 @@ const questions: PromptObject<string>[] = [
export class Auth {
public static user?: User
public static bot?: BotInfo
private email?: string
private password?: string
private accessToken?: AccessToken

async askCredentials ({ question }: { question?: (keyof DataCrypted)[] }): Promise<DataCrypted> {
async askCredentials (question?: (keyof DataCrypted)[]): Promise<DataCrypted> {
const filteredQuestions = questions.filter((propmt) => question === undefined || question?.includes(propmt.name as keyof DataCrypted))
const response = await prompts(filteredQuestions) as DataCrypted

Expand All @@ -54,21 +57,32 @@ export class Auth {
return response
}

async timeout () {
if (lastTry !== undefined && (new Date().getTime() - new Date(lastTry ?? 0).getTime()) < 10 * 1000) {
console.log('⏳ Timeout de 10 segundos... tentando após o timeout')
await new Promise<void>((resolve) => setTimeout(() => resolve(), 10 * 1000))
}
lastTry = new Date()
}

async login(): Promise<User> {
await this.timeout()
async checker (): Promise<void> {
await new Crypt().read()
const email = credentials.get('email')
const password = credentials.get('password')
this.email = credentials.get('email') as string | undefined
this.password = credentials.get('password') as string | undefined

if (email === undefined || password === undefined) {
await this.askCredentials({})
return await this.login()
if (this.email === undefined || this.password === undefined) {
await this.askCredentials()
return await this.checker()
}
await this.login().then(() => setTimeout(() => this.validator(), 10000))
}

async login(): Promise<User> {
await this.timeout()

const response = await fetch(`${api}/auth/login`, {
method: 'POST',
body: JSON.stringify({ email: email, password: password }),
body: JSON.stringify({ email: this.email, password: this.password }),
headers: {
"Content-Type": "application/json",
}
Expand All @@ -94,7 +108,7 @@ export class Auth {
switch (conclusion.Error) {
case 'logout': {
await this.logout()
await this.askCredentials({})
await this.askCredentials()
return await this.login()
}
case 'try_again': {
Expand All @@ -112,19 +126,10 @@ export class Auth {
return data.user
}


async logout () {
await rm(`${RootPATH}/.key`)
}

async timeout () {
if (lastTry !== undefined && (new Date().getTime() - new Date(lastTry ?? 0).getTime()) < 10 * 1000) {
console.log('⏳ Timeout de 10 segundos... tentando após o timeout')
await new Promise<void>((resolve) => setTimeout(() => resolve(), 10 * 1000))
}
lastTry = new Date()
}

async validator() {
await this.timeout()
if (
Expand Down Expand Up @@ -163,7 +168,7 @@ export class Auth {

switch (conclusion.Error) {
case 'change': {
await this.askCredentials({ question: ['uuid'] })
await this.askCredentials(['uuid'])
await this.login()
await this.validator()
break
Expand All @@ -174,7 +179,7 @@ export class Auth {
}
case 'logout': {
await this.logout()
await this.askCredentials({})
await this.askCredentials()
await this.login()
await this.validator()
break
Expand All @@ -195,9 +200,7 @@ export class Auth {
}

if (Auth.bot === undefined) this.cron()
const token = credentials.get('token')

Auth.bot = Object.assign(data, { token })
Auth.bot = data
}
}

Expand Down
8 changes: 5 additions & 3 deletions core/src/controller/events.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Command } from '@/discord/Commands.js'
import { type Socket } from 'socket.io'
import { Auth } from './auth.js'
import { Config } from './config.js'
import { credentials } from './crypt.js'
import { Database } from './database.js'
import { Plugins } from './plugins.js'

Expand Down Expand Up @@ -35,9 +35,11 @@ export class Event {
}

connected () {
if (Auth.bot?.token === undefined) throw new Error('Token do Discord está vazio!')
const token = credentials.get('token')
console.log(token)
if (token === undefined || typeof token !== 'string') throw new Error('Token do Discord está vazio!')
console.log(`⚠️ Token sendo enviado para: ${this.client.id}`)
this.client.emit('discord', Auth.bot.token)
this.client.emit('discord', token)
}

async disconnect () {
Expand Down
2 changes: 1 addition & 1 deletion core/src/controller/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export class Plugins {
const childInfo = spawn(filePath, ['--info'])
let info: Metadata | undefined

childInfo.on('exit', (code, signal) => {
childInfo.on('exit', (code) => {
if (code === 0 && info !== undefined) {
const process = Plugins.running.find((run) => run.metadata?.name === info?.name)

Expand Down
4 changes: 2 additions & 2 deletions core/src/discord/Client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Auth } from '@/controller/auth.js'
import { Config } from '@/controller/config.js'
import { credentials } from '@/controller/crypt.js'
import { ApplicationCommandType, type BitFieldResolvable, Client, type GatewayIntentsString, IntentsBitField, Partials, PermissionsBitField } from 'discord.js'
import { Command } from './Commands.js'

Expand Down Expand Up @@ -49,7 +49,7 @@ export class Discord {

console.log('📌 Iniciando Discord...')

await Discord.client.login(Auth.bot?.token)
await Discord.client.login(credentials.get('token') as string)
Discord.client.prependOnceListener('ready', async (client) => {
await new Discord().register()
console.info(`📡 Connected with ${client.user.username}`)
Expand Down
109 changes: 97 additions & 12 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"glob": "^10.3.15",
"gradient-string": "^2.0.2",
"javascript-obfuscator": "^4.1.0",
"node-fetch": "^3.3.2",
"prompts": "^2.4.2",
"randomstring": "^1.3.0",
"socket.io-client": "^4.7.5",
Expand Down
1 change: 1 addition & 0 deletions plugins/plugin_base/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"version": "1.0.0",
"description": "Controler dos modulos do PaymentBot",
"main": "src/app.ts",
"type": "module",
"scripts": {
"build": "tsc && tsc-alias",
"dev": "ts-node -r tsconfig-paths/register src/app.ts",
Expand Down
Loading

0 comments on commit d10f97a

Please sign in to comment.