Skip to content

Commit

Permalink
🆕 Create setLanguage
Browse files Browse the repository at this point in the history
Lang is now a class
Remove ` in translate pt-BR
  • Loading branch information
Ashu11-A committed Jun 20, 2024
1 parent b8b4155 commit 8a80298
Show file tree
Hide file tree
Showing 13 changed files with 82 additions and 71 deletions.
2 changes: 1 addition & 1 deletion core/locales/pt-BR/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"start": "📌 Iniciando Discord",
"create": "💡 Criando o client do Discord",
"close": "💥 Destruindo conexão com o Discord",
"connected": "📡 Connected with {{botName}}`",
"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}}",
Expand Down
2 changes: 1 addition & 1 deletion core/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const argsList: Args[] = [
prompts.override(yargs().argv)
config()

await import('./lang.js')
await import('./controller/lang.js')
await new License().checker()
await new Crypt().checker()
await new Auth().checker()
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 @@ -5,7 +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'
import { i18 } from '@/controller/lang.js'

const emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/g
const crypt = new Crypt()
Expand Down
6 changes: 2 additions & 4 deletions core/src/controller/crypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { exists } from "@/functions/fs-extra.js";
import { isJson } from "@/functions/validate.js";
import { RootPATH } from "@/index.js";
import { DataCrypted } from "@/interfaces/crypt.js";
import { i18 } from "@/lang.js";
import { i18, Lang } from '@/controller/lang.js';
import * as argon2 from "argon2";
import { passwordStrength } from 'check-password-strength';
import { watch } from 'chokidar';
Expand Down Expand Up @@ -144,9 +144,7 @@ export class Crypt {

const outputData = JSON.parse(AESCrypt) as DataCrypted

if (outputData.language !== undefined) {
i18next.changeLanguage(outputData.language)
}
if (outputData.language !== undefined) new Lang().setLanguage(outputData.language)


for (const [key, value] of Object.entries(outputData) as Array<[string, string | object | boolean | number]>) {
Expand Down
2 changes: 1 addition & 1 deletion core/src/controller/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { join } from 'path'
import { Socket } from 'socket.io'
import { DataSource, FindOptionsWhere, ObjectId, type BaseEntity, type DataSourceOptions } from 'typeorm'
import { RootPATH } from '@/index.js'
import { i18 } from '@/lang.js'
import { i18 } from '@/controller/lang.js'

export interface EntityImport<T extends typeof BaseEntity> { default: T }

Expand Down
2 changes: 1 addition & 1 deletion core/src/controller/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Config } from './config.js'
import { credentials, Crypt } from './crypt.js'
import { Database } from './database.js'
import { Plugins } from './plugins.js'
import { i18 } from '@/lang.js'
import { i18 } from '@/controller/lang.js'

interface EventOptions {
client: Socket
Expand Down
70 changes: 70 additions & 0 deletions core/src/controller/lang.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { RootPATH } from '@/index.js'
import { watch } from 'chokidar'
import { mkdir, readFile, writeFile } from 'fs/promises'
import { glob } from 'glob'
import i18next from 'i18next'
import Backend, { FsBackendOptions } from 'i18next-fs-backend'
import { dirname, join } from 'path'
import { exists } from '@/functions/fs-extra.js'
import { __dirname } from '@/index.js'

export class Lang {
/**
* Recriar os arquivos de lang externamente (do PKG) para possibilitar customizações
*/
async register () {
const path = join(__dirname, '..', 'locales')
const internalLangs = await glob('**/*.json', { cwd: path })
const wather = watch(path)
const cache = new Map<string, boolean>()
void wather.on('all', async (action, path) => {
const language = path.split('/')[path.split('/').length - 2]

if (cache.get(path)) return
switch (action) {
case 'add': {
i18next.options.backend = {
backend: join(RootPATH, 'locales', '{{lng}}', '{{ns}}.json'),
}
break
}
case 'change':
cache.set(path, true)
await i18next.reloadResources(language).finally(() => setTimeout(() => cache.delete(path), 5000))
break
}
for (const lang of internalLangs) {
const content = await readFile(join(path, lang), { encoding: 'utf8' })
const externalDir = join(RootPATH, 'locales', dirname(lang.split('/')[0]))
const externalPath = join(externalDir, lang)

if (!(await exists(externalPath))) {
await mkdir(externalDir, { recursive: true }).catch(() => undefined)
await writeFile(externalPath, content, { encoding: 'utf8' })
}
}
})
}
async setLanguage (lang: string) {
const path = join(RootPATH, 'locales', lang)
if (!(await exists(path))) {
console.log(`⛔ The selected language (${lang}) does not exist, using English by default`)
i18next.changeLanguage('en')
return
}
await i18next.changeLanguage(lang)
}
}



/**
* Inicializar i18
*/
export const i18 = await i18next.use(Backend).init<FsBackendOptions>({
debug: false,
lng: 'en',
backend: {
loadPath: join(RootPATH, 'locales', '{{lng}}', '{{ns}}.json'),
}
})
2 changes: 1 addition & 1 deletion core/src/controller/license.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { existsSync } from "fs";
import { readFile, writeFile } from "fs/promises";
import { join } from "path";
import { __dirname } from '@/index.js'
import { i18 } from "@/lang.js";
import { i18 } from '@/controller/lang.js';

let watched = false

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 @@ -15,7 +15,7 @@ import { Config, ConfigOptions } from './config.js'
import { Database, EntityImport } from './database.js'
import { fileURLToPath } from 'url'
import { createVerify } from 'crypto'
import { i18 } from '@/lang.js'
import { i18 } from '@/controller/lang.js'

const __dirname = dirname(fileURLToPath(import.meta.url))
const cacheWatcher = new Map<string, boolean>()
Expand Down
2 changes: 1 addition & 1 deletion core/src/controller/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Server } from 'socket.io'
import ws from 'ws'
import { Event } from './events.js'
import eiows from 'eiows'
import { i18 } from '@/lang.js'
import { i18 } from '@/controller/lang.js'

export class SocketController {
protected readonly app: Application
Expand Down
2 changes: 1 addition & 1 deletion core/src/discord/base/Client.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Config } from '@/controller/config.js'
import { credentials } from '@/controller/crypt.js'
import { i18 } from '@/lang.js'
import { i18 } from '@/controller/lang.js'
import { ApplicationCommandType, AutocompleteInteraction, type BitFieldResolvable, ChatInputCommandInteraction, Client, CommandInteraction, type GatewayIntentsString, IntentsBitField, MessageContextMenuCommandInteraction, Partials, PermissionsBitField, UserContextMenuCommandInteraction } from 'discord.js'
import { glob } from 'glob'
import { dirname, join } from 'path'
Expand Down
2 changes: 1 addition & 1 deletion core/src/discord/commands/lang.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { glob } from "glob";
import i18next from "i18next";
import { Command } from "../base/Commands.js";
import { Crypt } from "@/controller/crypt.js";
import { i18 } from "@/lang.js";
import { i18 } from '@/controller/lang.js';

new Command({
name: 'language',
Expand Down
57 changes: 0 additions & 57 deletions core/src/lang.ts

This file was deleted.

0 comments on commit 8a80298

Please sign in to comment.