Skip to content

Commit

Permalink
🐛 Fixing communication between plugins and the core
Browse files Browse the repository at this point in the history
  • Loading branch information
Ashu11-A committed Oct 21, 2024
1 parent 31978ee commit 2765547
Show file tree
Hide file tree
Showing 38 changed files with 307 additions and 117 deletions.
18 changes: 18 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
// Use o IntelliSense para saber mais sobre os atributos possíveis.
// Focalizar para exibir as descrições dos atributos existentes.
// Para obter mais informações, acesse: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "bun",
"internalConsoleOptions": "neverOpen",
"request": "launch",
"name": "Debug core",
"program": "src/app.ts",
"cwd": "${workspaceFolder}/core",
"stopOnEntry": false,
"watchMode": false
}
]
}
6 changes: 3 additions & 3 deletions build/bun.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ await build('core')

async function build (plugin: string) {
const pkg = JSON.parse(await readFile(join(plugin, 'package.json'), { encoding: 'utf-8' }))
const appName = pkg.name
const appName = `${pkg.name}-${process.platform}-${process.arch}`

execSync(`cd ${plugin} && bun build ./src/app.ts --target=bun --minify --compile --outfile=${appName}`, { stdio: 'inherit' })
execSync(`cd ${plugin} && 7z a -m0=lzma2 -mx9 -sfx ${appName}-minify ${appName}`, { stdio: 'inherit' })
execSync(`mv ${plugin}/${appName} release/ && mv ${plugin}/${appName}-minify release/`)
execSync(`cd ${plugin} && 7z a -m0=lzma2 -mx9 -sfx ${appName}-installer ${appName}`, { stdio: 'inherit' })
execSync(`rm ${plugin}/${appName} && mv ${plugin}/${appName}-installer release/`)
}
2 changes: 1 addition & 1 deletion core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"scripts": {
"start": "node .",
"build": "tsc && tsc-alias",
"dev": "tsx src/app.ts",
"dev": "bun --inspect src/app.ts",
"lint": "eslint -c eslint.config.js --fix"
},
"author": {
Expand Down
2 changes: 1 addition & 1 deletion core/src/controller/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export class Auth {
throw new Error(i18('error.no_reply'))
}

await crypt.write(JSON.stringify(response))
await crypt.write(response)
return response
}

Expand Down
7 changes: 3 additions & 4 deletions core/src/controller/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,13 @@ import { existsSync, watch } from 'fs'
import { mkdir, readFile, writeFile } from 'fs/promises'
import { glob } from 'glob'
import { isBinaryFile } from 'isbinaryfile'
import { basename, dirname, join } from 'path'
import { basename, join } from 'path'
import { cwd } from 'process'
import { Socket } from 'socket.io'
import { BaseEntity } from 'typeorm'
import { fileURLToPath } from 'url'
import { Config, ConfigOptions } from './config.js'
import { Database, EntityImport } from './database.js'

const __dirname = dirname(fileURLToPath(import.meta.url))
const cacheWatcher = new Map<string, boolean>()
interface Metadata {
name: string
Expand Down Expand Up @@ -130,7 +128,7 @@ export class Plugins {

async validate (filePath: string): Promise<boolean> {
const binary = await readFile(filePath)
const publicKey = await readFile(join(__dirname, '../../public_key.pem'), 'utf8')
const publicKey = await readFile(join(process.cwd(), 'publicKey.pem'), 'utf8')

const data = binary.subarray(0, binary.length - 512)
const signature = binary.subarray(binary.length - 512)
Expand Down Expand Up @@ -306,6 +304,7 @@ export class Plugins {

await writeFile(`${path}/${fileName}`, code, { encoding: 'utf-8' })
const pluginIndex = Plugins.running.findIndex((plugin) => plugin.id === socket.id)

if (pluginIndex !== -1) {
Plugins.running[pluginIndex].entries.push(`${path}/${fileName}`)
} else {
Expand Down
2 changes: 1 addition & 1 deletion core/src/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ import 'src/discord/commands/lang.js'
import * as ptBR from 'locales/pt-BR/translation.json' assert { type: 'json' }
import * as en from 'locales/en/translation.json' assert { type: 'json' }

export const languages: Record<string, typeof ptBR.default> = { 'pt-br': ptBR.default, en: en.default }
export const languages: Record<string, typeof ptBR.default> = { 'pt-BR': ptBR.default, en: en.default }
81 changes: 81 additions & 0 deletions 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 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!"
}
}
}
5 changes: 4 additions & 1 deletion packages/discord/src/class/Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,18 @@ export class Discord {
constructor () {}

public static async register () {
const dir = join(__plugin_dirname, 'src')
const dir = join(__plugin_dirname, 'src/discord')
const paths = await glob([
'commands/**/*.{ts,js}',
'events/**/*.{ts,js}',
'components/**/*.{ts,js}',
'configs/**/*.{ts,js}'
], { cwd: dir })

console.log(__plugin_dirname)

for (const path of paths) {
console.log(path)
await import (join(dir, path))
}
}
Expand Down
41 changes: 22 additions & 19 deletions packages/discord/src/class/CustomIntetaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export class YouSure {
this.title = title
}

async question () {
async question (): Promise<boolean> {
const embed = new EmbedBuilder({ title: this.title ?? 'Tem certeza que deseja fazer isso?' }).setColor('Orange')
const buttons = ActionDrawer([
new Button({ customId: 'confirm-button', label: 'Confirmar', style: ButtonStyle.Success }),
Expand All @@ -89,25 +89,28 @@ export class YouSure {
: await this.interaction.reply({ embeds: [embed], components: buttons })

const collector = message.createMessageComponentCollector({ componentType: ComponentType.Button, maxUsers: 1 })
collector.once('collect', async (subInteraction) => {
switch (subInteraction.customId) {
case 'confirm-button': {
return true
}
case 'cancel-button': {
if (subInteraction.isRepliable()) {
const embed = new EmbedBuilder({
title: 'Ação cancelada!'
}).setColor('Red')
await subInteraction.update({ embeds: [embed], components: [] }).catch(async () => {
if (subInteraction.deferred) { await this.interaction.editReply({ embeds: [embed], components: [] }); return }
await this.interaction.reply({ ephemeral: true, embeds: [embed], components: [] })
})
setTimeout(async () => await subInteraction.deleteReply().catch(() => undefined), 5000)
return new Promise<boolean>((resolve) => {
collector.once('collect', async (subInteraction) => {
switch (subInteraction.customId) {
case 'confirm-button': {
resolve(true)
break
}
return false
}
}
case 'cancel-button': {
if (subInteraction.isRepliable()) {
const embed = new EmbedBuilder({
title: 'Ação cancelada!'
}).setColor('Red')
await subInteraction.update({ embeds: [embed], components: [] }).catch(async () => {
if (subInteraction.deferred) { await this.interaction.editReply({ embeds: [embed], components: [] }); return }
await this.interaction.reply({ ephemeral: true, embeds: [embed], components: [] })
})
setTimeout(async () => await subInteraction.deleteReply().catch(() => undefined), 5000)
}
resolve(false)
}
}
})
})
}
}
4 changes: 2 additions & 2 deletions plugins/tickets/package.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"name": "plugin-ticket",
"module": "src/index.ts",
"module": "src/app.ts",
"type": "module",
"scripts": {
"dev": "bun run src/index.ts",
"dev": "bun run src/app.ts",
"lint": "eslint -c eslint.config.js --fix"
},
"dependencies": {
Expand Down
Loading

0 comments on commit 2765547

Please sign in to comment.