Skip to content

Commit

Permalink
✨ New System: I18
Browse files Browse the repository at this point in the history
  • Loading branch information
Ashu11-A committed Jun 18, 2024
1 parent 4c297ae commit b8b4155
Show file tree
Hide file tree
Showing 20 changed files with 548 additions and 145 deletions.
81 changes: 81 additions & 0 deletions core/locales/en/translation.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
{
"discord": {
"start": "📌 Starting Discord",
"create": "💡 Creating the Discord client",
"close": "💥 Destroying connection with Discord",
"connected": "📡 Connected with {{botName}}",
"isConnected": "⛔ Sorry, but I'm already connected to Discord!",
"commands": "📝 {{length}} Commands successfully defined!",
"token_send": "⚠️ Token{{isEncrypted}} being sent to: {{pluginId}}",
"token_not_found": "❌ Discord token is empty!"
},
"plugins": {
"new": "✨ New plugin added!",
"starting": "✅ Starting Plugin {{name}}",
"disconnect": "🔌 Plugin Disconnected: {{name}}",
"commands": "🤖 Commands: {{length}}",
"components": "🧩 Components: {{length}}",
"events": "🎉 Events: {{length}}",
"configs": "⚙️ Configs: {{length}}",
"crons": "🕑 Crons: {{length}}",
"entry_load": "⏳ Loading entry: {{name}}",
"hasLoaded": "⚠️ Attention: Plugin added after the first registration, it may be necessary to remove the bot and add it again to the server!",
"devlop": "🚨 Development mode",
"last_plugin": "🚩 Last plugin loaded ({{current}}/{{total}})",
"invalid": "❌ Valid Plugin!",
"duplicate": "❌ Plugin {{name}} is duplicated!",
"invalid_file": "❌ Invalid file: {{fileName}}",
"invalid_signature": "❌ Signature verification failed: {{fileName}}",
"reject": "❌ The Plugin {{filePath}} exited with error code {{code}} and signal {{signal}}"
},
"crypt": {
"question": "How would you like to protect your local information?",
"generate_title": "Generate random password",
"generate_description": "It will be used to encrypt your information",
"define_title": "Define password",
"define_description": "It will be used to encrypt your information",
"your_password": "🔐 Your Password:",
"weak_password": "Password too weak! (1 Uppercase letter, 1 Lowercase letter, 1 Number, 1 Special character)",
"file_change": "⚠️ A change was detected in a protected file!",
"delete_file": "🗑️ Deleting encrypted files!",
"sensitive_information": "⚠️ Sensitive information being read"
},
"license": {
"accept": "❓ Do you agree with the terms presented above?"
},
"authenticate": {
"registered": "📝 Registered at:",
"hello": "👋 Hello {{name}}",
"change_token": "🔄 Change Token",
"try_again": "🔁 Try Again",
"logout": "↪️ Logout"
},
"websocket": {
"initialized": "🚀 Server initialized on port {{port}}"
},
"database": {
"starting": "🗂️ Starting Database",
"initialized": "✨ Database initialized with {{length}} entries",
"invalid_entity": "⛔ {{tableName}} Invalid entity, loaded entities:"
},
"error": {
"unstable": "🔴 {{element}} unstable",
"no_found": "🚫 No {{name}} found",
"not_exist": "❌ {{name}} does not exist!",
"not_select": "❌ No option selected!",
"no_possible": "❌ It is not possible to continue!",
"undefined": "❌ {{element}} undefined!",
"invalid": "❌ {{element}} invalid!",
"no_reply": "❌ Form not replied!",
"expired": "❌ {{element}} expired!",
"disabled": "❌ {{element}} disabled!",
"an_error_occurred": "❌ An error occurred:",
"timeout": "⏳ Timeout of {{time}} seconds... trying after the timeout"
},
"commands": {
"lang": {
"sucess": "✅ Language changed successfully!",
"error": "❌ Unable to change the bot's language!"
}
}
}
81 changes: 81 additions & 0 deletions core/locales/pt-BR/translation.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
{
"discord": {
"start": "📌 Iniciando Discord",
"create": "💡 Criando o client do Discord",
"close": "💥 Destruindo conexão com o Discord",
"connected": "📡 Connected with {{botName}}`",
"isConnected": "⛔ Desculpe, mas já estou conectado ao Discord!",
"commands": "📝 {{length}} Comandos definidos com sucesso!",
"token_send": "⚠️ Token{{isEncrypted}} sendo enviado para: {{pluginId}}",
"token_not_found": "❌ Token do Discord está vazio!"
},
"plugins": {
"new": "✨ Novo plugin adicionado!",
"starting": "✅ Iniciando Plugin {{name}}",
"disconnect": "🔌 Plugin Desconectado: {{name}}",
"commands": "🤖 Commands: {{length}}",
"components": "🧩 Components: {{length}}",
"events": "🎉 Events: {{length}}",
"configs": "⚙️ Configs: {{length}}",
"crons": "🕑 Crons: {{length}}",
"entry_load": "⏳ Carregando entry: {{name}}",
"hasLoaded": "⚠️ Atenção: Plugin adicionado após o primeiro registro, talvez seja necessário expulsar o bot, e adicioná-lo novamente ao servidor!",
"devlop": "🚨 Modo de desenvolvimento",
"last_plugin": "🚩 Último plugin carregado ({{current}}/{{total}})",
"invalid": "❌ Plugin Valido!",
"duplicate": "❌ Plugin {{name}} está duplicado!",
"invalid_file": "❌ Arquivo invalido: {{fileName}}",
"invalid_signature": "❌ Falha na verificação da assinatura: {{fileName}}",
"reject": "❌ O Plugin {{filePath}} saiu com código de erro {{code}} e sinal {{signal}}"
},
"crypt": {
"question": "Como deseja proteger suas informações locais?",
"generate_title": "Gerar senha aleatória",
"generate_description": "Será usada para criptografar suas informações",
"define_title": "Definir senha",
"define_description": "Será usada para criptografar suas informações",
"your_password": "🔐 Sua Senha:",
"weak_password": "Senha muito fraca! (1 Letra maiúscula, 1 Letra Minuscula, 1 Numero, 1 Carácter especial)",
"file_change": "⚠️ Foi detectado uma mudança em um arquivo protegido!",
"delete_file": "🗑️ Deletando arquivos encriptados!",
"sensitive_information": "⚠️ Informações sensíveis sendo lidas"
},
"license": {
"accept": "❓ Você concorda com os termos apresentados acima?"
},
"authenticate": {
"registered": "📝 Cadastrado em:",
"hello": "👋 Olá {{name}}",
"change_token": "🔄 Mudar Token",
"try_again": "🔁 Tentar Novamente",
"logout": "↪️ Deslogar"
},
"websocket": {
"initialized": "🚀 Servidor inicializado na porta {{port}}"
},
"database": {
"starting": "🗂️ Iniciando Banco de dados",
"initialized": "✨ Banco de dados inicializado com {{length}} entries",
"invalid_entity": "⛔ {{tableName}} Entidade invalida, Entidades carregadas:"
},
"error": {
"unstable": "🔴 {{element}} instável",
"no_found": "🚫 Nenhum {{name}} encontrado",
"not_exist": "❌ {{name}} não existe!",
"not_select": "❌ Nenhuma opção selecionada!",
"no_possible": "❌ Não é possivel continuar!",
"undefined": "❌ {{element}} indefinido!",
"invalid": "❌ {{element}} invalido!",
"no_reply": "❌ Formulário não respondido!",
"expired": "❌ {{element}} expired!",
"disabled": "❌ {{element}} disabled!",
"an_error_occurred": "❌ Ocorreu um erro:",
"timeout": "⏳ Timeout de {{time}} segundos... tentando após o timeout"
},
"commands": {
"lang": {
"sucess": "✅ Linguagem alterado com sucesso!",
"error": "❌ Não foi possivel alterar a linguagem do bot!"
}
}
}
33 changes: 30 additions & 3 deletions core/package-lock.json

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

2 changes: 2 additions & 0 deletions core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@
"eiows": "^7.1.0",
"express": "^4.19.2",
"glob": "^10.4.1",
"i18next": "^23.11.5",
"i18next-fs-backend": "^2.3.1",
"isbinaryfile": "^5.0.2",
"marked": "^12.0.2",
"marked-terminal": "^7.0.0",
Expand Down
1 change: 1 addition & 0 deletions core/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ const argsList: Args[] = [
prompts.override(yargs().argv)
config()

await import('./lang.js')
await new License().checker()
await new Crypt().checker()
await new Auth().checker()
Expand Down
44 changes: 23 additions & 21 deletions core/src/controller/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { CronJob } from 'cron'
import { rm } from 'fs/promises'
import prompts, { Choice, PromptObject } from 'prompts'
import { credentials, Crypt } from './crypt.js'
import { i18 } from '@/lang.js'

const emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/g
const crypt = new Crypt()
Expand All @@ -16,23 +17,23 @@ const questions: PromptObject<string>[] = [
name: 'email',
message: 'Email',
type: 'text',
initial: 'Cadastrado em https://fragmentbot.com',
validate: (value: string) => !emailRegex.test(value) ? 'Informe um email valido!' : true
initial: `${i18('authenticate.registered')} https://fragmentbot.com`,
validate: (value: string) => !emailRegex.test(value) ? i18('error.invalid', { element: 'Email' }) : true
},
{
name: 'password',
message: 'Senha (Cadastrado em https://fragmentbot.com)',
message: `${i18('authenticate.registered')} https://fragmentbot.com`,
type: 'password',
validate: (value: string) => value.length < 0 ? 'Senha muito pequena!' : true },
{
name: 'uuid',
message: 'UUID',
type: 'text',
initial: 'Visível no Dashboard (https://fragmentbot.com)',
initial: `${i18('authenticate.registered')} https://fragmentbot.com`,
validate: (value: string) => value.split('-').length < 5 ? 'UUID invalido!' : true },
{
name: 'token',
message: 'Token (Token Do seu Bot https://discord.com/developers/applications)',
message: 'Token Discord (https://discord.com/developers/applications)',
type: 'password'
}
]
Expand All @@ -48,7 +49,7 @@ export class Auth {
const response = await prompts(filteredQuestions) as DataCrypted

if (Object.keys(response).length !== filteredQuestions.length || Object.entries(response).filter(([, content]) => content === '').length > 0) {
throw new Error('Formulário não respondido!')
throw new Error(i18('error.no_reply'))
}

await crypt.write(response)
Expand All @@ -57,7 +58,7 @@ export class Auth {

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')
console.log(i18('error.timeout', { time: 10 }))
await new Promise<void>((resolve) => setTimeout(() => resolve(), 10 * 1000))
}
lastTry = new Date()
Expand Down Expand Up @@ -86,14 +87,14 @@ export class Auth {
"Content-Type": "application/json",
}
}).catch((err) => {
console.log(`🔴 API instável!`)
console.log(i18('error.unstable', { element: 'API' }))
return err
})

if (!response.ok) {
const choices: Choice[] = [
{ title: 'Deslogar', description: 'Removerá seção atual', value: 'logout' },
{ title: 'Tentar Novamente', description: 'Tentar novamente fazer o login', value: 'try_again' }
{ title: i18('authenticate.logout'), value: 'logout' },
{ title: i18('authenticate.try_again'), value: 'try_again' }
]

const conclusion = await prompts({
Expand All @@ -113,15 +114,16 @@ export class Auth {
case 'try_again': {
return await this.login()
}
default: throw new Error('Nenhum elemento selecionado!')
default: throw new Error(i18('error.no_reply'))
}
}
const data = await response.json() as AuthData

Auth.user = data.user
this.accessToken = data.accessToken

console.log(`\n👋 Olá ${data.user.name}\n`)
console.log()
console.log(i18('authenticate.hello', { name: data.user.name }))
console.log()
return data.user
}

Expand All @@ -146,23 +148,23 @@ export class Auth {
Authorization: `Bearer ${(this.accessToken as AccessToken).token}`
}
}).catch((err) => {
console.log(`🔴 API instável!`)
console.log(i18('error.unstable', { element: 'API' }))
return err
})

if (!response.ok && attempts >= 4 || response.status === 404) {
console.log(`☝️ Então ${(Auth.user as User).name}, não achei o registro do seu bot!`)
const choices: Choice[] = [
{ title: 'Mudar Token', value: 'change' },
{ title: 'Tentar Novamente', value: 'try_again' },
{ title: 'Deslogar', value: 'logout' }
{ title: i18('authenticate.change_token'), value: 'change' },
{ title: i18('authenticate.try_again'), value: 'try_again' },
{ title: i18('authenticate.logout'), value: 'logout' }
]

const conclusion = await prompts({
name: 'Error',
type: 'select',
choices,
message: `Ocorreu um erro ${response.statusText}`,
message: i18('error.an_error_occurred', { element: response.statusText }),
initial: 1
})

Expand All @@ -184,7 +186,7 @@ export class Auth {
await this.validator()
break
}
default: throw new Error('Nenhum elemento selecionado!')
default: throw new Error(i18('error.no_reply'))
}

return
Expand All @@ -194,9 +196,9 @@ export class Auth {
const data = await response.json() as BotInfo

if (data.expired) {
console.log('❌ Bot expirou!')
console.log(i18('error.expired', { element: 'Bot' }))
} else if (!data.enabled) {
console.log('❌ Bot desabilitado!')
console.log(i18('error.disabled', { element: 'Bot' }))
}

if (Auth.bot === undefined) this.cron()
Expand Down
Loading

0 comments on commit b8b4155

Please sign in to comment.