diff --git a/package-lock.json b/package-lock.json index 751be418e..967dbdae6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,7 @@ "version": "6.5.7", "license": "Apache-2.0", "dependencies": { - "@akarui/aoi.db": "^1.0.0", + "@akarui/aoi.db": "github:akaruidevelopment/aoi.db#v2", "@akarui/structures": "^1.0.2", "chalk": "^4.1.2", "discord.js": "^14.13.0", @@ -28,11 +28,12 @@ } }, "node_modules/@akarui/aoi.db": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@akarui/aoi.db/-/aoi.db-1.0.0.tgz", - "integrity": "sha512-36JdJO22tjJVcTvbHzG026k8ZYn/PX+wDj4Agd2y/06Ih85AcoPLcOhWm0o6K+Nz5Rs98U/jdHZJhWOMGFx1pw==", + "version": "2.0.0", + "resolved": "git+ssh://git@github.com/akaruidevelopment/aoi.db.git#1846455cdf072a2a4927b878e60465e0eaa7e746", + "license": "MIT", "dependencies": { - "tiny-typed-emitter": "^2.1.0" + "tar": "^6.1.15", + "ws": "^8.13.0" }, "engines": { "node": ">=16.x" @@ -1220,9 +1221,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", - "dev": true, - "optional": true, - "peer": true, "engines": { "node": ">=10" } @@ -1633,9 +1631,6 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", - "dev": true, - "optional": true, - "peer": true, "dependencies": { "minipass": "^3.0.0" }, @@ -2064,9 +2059,6 @@ "version": "3.3.6", "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", - "dev": true, - "optional": true, - "peer": true, "dependencies": { "yallist": "^4.0.0" }, @@ -2078,9 +2070,6 @@ "version": "2.1.2", "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", - "dev": true, - "optional": true, - "peer": true, "dependencies": { "minipass": "^3.0.0", "yallist": "^4.0.0" @@ -2093,9 +2082,6 @@ "version": "1.0.4", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", - "dev": true, - "optional": true, - "peer": true, "bin": { "mkdirp": "bin/cmd.js" }, @@ -2607,16 +2593,13 @@ } }, "node_modules/tar": { - "version": "6.1.12", - "resolved": "https://registry.npmjs.org/tar/-/tar-6.1.12.tgz", - "integrity": "sha512-jU4TdemS31uABHd+Lt5WEYJuzn+TJTCBLljvIAHZOz6M9Os5pJ4dD+vRFLxPa/n3T0iEFzpi+0x1UfuDZYbRMw==", - "dev": true, - "optional": true, - "peer": true, + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.0.tgz", + "integrity": "sha512-/Wo7DcT0u5HUV486xg675HtjNd3BXZ6xDbzsCUZPt5iw8bTQ63bP0Raut3mvro9u+CUyq7YQd8Cx55fsZXxqLQ==", "dependencies": { "chownr": "^2.0.0", "fs-minipass": "^2.0.0", - "minipass": "^3.0.0", + "minipass": "^5.0.0", "minizlib": "^2.1.1", "mkdirp": "^1.0.3", "yallist": "^4.0.0" @@ -2625,10 +2608,19 @@ "node": ">=10" } }, + "node_modules/tar/node_modules/minipass": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", + "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", + "engines": { + "node": ">=8" + } + }, "node_modules/tiny-typed-emitter": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/tiny-typed-emitter/-/tiny-typed-emitter-2.1.0.tgz", - "integrity": "sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA==" + "integrity": "sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA==", + "dev": true }, "node_modules/tr46": { "version": "0.0.3", @@ -2932,10 +2924,7 @@ "node_modules/yallist": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true, - "optional": true, - "peer": true + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" }, "node_modules/youtubei.js": { "version": "3.3.0", diff --git a/package.json b/package.json index d485137e2..fa7ff5bd5 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,7 @@ "discordbot" ], "dependencies": { - "@akarui/aoi.db": "^1.0.0", + "@akarui/aoi.db": "github:akaruidevelopment/aoi.db#v2", "@akarui/structures": "^1.0.2", "chalk": "^4.1.2", "discord.js": "^14.13.0", diff --git a/src/classes/AoiBase.js b/src/classes/AoiBase.js index 5095b9ec8..6a24da47d 100644 --- a/src/classes/AoiBase.js +++ b/src/classes/AoiBase.js @@ -1,5 +1,5 @@ const Discord = require("discord.js"); -const {VariableManager} = require("./Variables.js"); +const { VariableManager } = require("./Variables.js"); const InteractionManager = require("./Interaction.js"); const LoadCommands = require("./LoadCommands.js"); const { @@ -9,14 +9,12 @@ const { EventsToDjsEvents, EventstoFile, } = require("../utils/Constants.js"); -const { - AoijsAPI -} = require("./Database.js"); +const Database = require("./Database.js"); const CacheManager = require("./CacheManager.js"); -const {CommandManager} = require("./Commands.js"); -const {Group} = require("@akarui/structures"); +const { CommandManager } = require("./Commands.js"); +const { Group } = require("@akarui/structures"); const AoiError = require("./AoiError.js"); -const {functions: parser} = require("../core/AoiReader.js"); +const { functions: parser } = require("../core/AoiReader.js"); class BaseClient extends Discord.Client { constructor(options) { @@ -51,26 +49,41 @@ class BaseClient extends Discord.Client { this.variableManager = new VariableManager(this); if ( - [ - "default", - "aoi.db", - ].includes(options?.database?.type) + ["default", "aoi.db"].includes(options?.database?.type) || + !options?.database ) { - this.db = new AoijsAPI( - options?.database?.db || require("@akarui/aoi.db"), - { - path: options?.database?.path || "./database/", - tables: options?.database?.tables || ["main"], - }, + const dbData = options?.database; + + this.db = new Database( + dbData?.type + ? dbData?.type === "default" + ? "aoi.db" + : dbData?.type + : "aoi.db", + dbData?.db ?? require("@akarui/aoi.db"), + dbData?.dbType ?? "KeyValue", { - type: options?.database?.type || "default", - promisify: options?.database?.promisify || false, + dataConfig: { + path: dbData?.path ?? "./database", + tables: dbData?.tables?.length + ? [...dbData?.tables, "__aoijs_vars__"] + : ["main", "__aoijs_vars__"], + }, + encryptionConfig: { + securityKey: + dbData?.securityKey ?? + "a-32-characters-long-string-here", + encriptData: dbData?.encriptData ?? false, + }, + ...dbData?.extraOptions, }, - options?.database?.extraOptions || {}, ); } - if (Array.isArray(options?.disableFunctions) && options?.disableFunctions.length) { + if ( + Array.isArray(options?.disableFunctions) && + options?.disableFunctions.length + ) { options?.disableFunctions.forEach((func) => { const index = parser.findIndex((f) => f === func); if (index !== -1) { @@ -82,7 +95,7 @@ class BaseClient extends Discord.Client { this.prefix = options.prefix; this.#bindEvents(); - Object.defineProperty(this, "statuses", {value: new Group()}); + Object.defineProperty(this, "statuses", { value: new Group() }); this.on("ready", async () => { await require("../handler/NonIntents/ready.js")(this); @@ -93,7 +106,6 @@ class BaseClient extends Discord.Client { } loadCommands(directory, debug = true) { - const loader = new LoadCommands(this); loader.load(this.cmd, directory, debug); } @@ -101,8 +113,9 @@ class BaseClient extends Discord.Client { status(...statuses) { for (const status of statuses) { status.type = - Object.keys(ActivityTypeAvailables).includes(status.type.toLowerCase()) || - Object.values(ActivityTypeAvailables).includes(status.type) + Object.keys(ActivityTypeAvailables).includes( + status.type.toLowerCase(), + ) || Object.values(ActivityTypeAvailables).includes(status.type) ? ActivityTypeAvailables[status.type.toLowerCase()] : ActivityTypeAvailables.playing; @@ -113,7 +126,7 @@ class BaseClient extends Discord.Client { }; this.statuses.set(this.statuses.size, { - status: status.status || 'online', + status: status.status || "online", time: isNaN(status.time) ? 12 : status.time, activity: option, afk: status.afk || false, @@ -128,7 +141,9 @@ class BaseClient extends Discord.Client { */ variables(d, table = this.db?.tables?.[0]) { if (this.db === undefined) { - throw new TypeError('A database must be provided to use the variables method.'); + throw new TypeError( + "A database must be provided to use the variables method.", + ); } for (const [name, value] of Object.entries(d)) { @@ -168,15 +183,18 @@ class BaseClient extends Discord.Client { ].includes(event) ? require(`../shardhandler/${event}.js`) : Array.isArray(file) - ? file.map((x) => require(`../handler/${filedir}/${x}.js`)) - : require(`../handler/${filedir}/${file}.js`); + ? file.map((x) => require(`../handler/${filedir}/${x}.js`)) + : require(`../handler/${filedir}/${file}.js`); this.on(eventName, (...args) => { - if (Array.isArray(func)) func.forEach((x) => x(...args, this)); + if (Array.isArray(func)) + func.forEach((x) => x(...args, this)); else func(...args, this); }); } catch (error) { - throw new TypeError(`Error loading "${event}" event, does not exist!`); + throw new TypeError( + `Error loading "${event}" event, does not exist!`, + ); } } } diff --git a/src/classes/Database.js b/src/classes/Database.js index 394cc4081..ae3fc9fe8 100644 --- a/src/classes/Database.js +++ b/src/classes/Database.js @@ -1,165 +1,72 @@ -class Database { - constructor( - DbModule, - options = {path: "./database/", tables: ["main"]}, - promisify = false, - ) { - this.path = options.path; - this.tables = options.tables || ["main"]; - this.module = DbModule; - this.promisify = promisify || false; - this.db = AoijsAPI - } +const aoidb = require("@akarui/aoi.db"); - get ping() { - const start = Date.now(); - this.db.all(this.tables[0]); - return Date.now() - start; - } - - async set(table, name, id, value) { - await this.db.set(table, id ? `${name}_${id}` : name, value); - } - - get(table, name, id) { - if (!this.promisify) return this.db.get(table, id ? `${name}_${id}` : name); - else - return new Promise((res) => - res(this.db.get(table, id ? `${name}_${id}` : name)), - ); - } +class Database { + /** + * @type {aoidb.KeyValue | aoidb.Transmitter} db + * @type {boolean} ready + * @type {number} readyAt + * @type {"aoi.db"} type + * @type {"KeyValue" | "Transmitter"} moduleType + * @type {string[]} tables + */ + db; + ready = false; + readyAt = 0; + type; + tables = []; + moduleType = "KeyValue"; + /** + * Description + * @param {any} module + * @param {"KeyValue" | "Transmitter"} type + * @param {aoidb.KeyValueOptions | aoidb.TransmitterOptions} config + * @returns {any} + */ + constructor(moduleType, module, type, config) { + this.moduleType = type; + this.db = new module[type](config); + this.tables = config.dataConfig.tables; + this.type = moduleType; + this.db.on(aoidb.DatabaseEvents.Connect, () => { + console.log(`[@akarui/aoi.db] Connected ${type} database`); + this.ready = true; + this.readyAt = Date.now(); + }); - async all(table, varname, lengthofId, funconId) { - if (!varname) { - return await this.db.all(table); - } else { - return await this.db.all(table, { - filter: (x) => - x.key.startsWith(`${varname}_`) && - (lengthofId - ? x.key.split("_").slice(1).length === lengthofId - : true) && - (funconId ? this.checkConditionOnId(x.key, ...funconId) : true), - }); - } + this.db.connect(); } - checkConditionOnId(id, position, value) { - id = id.split("_").slice(1); - return id[position] === value; + async set(table, key, id, value) { + return await this.db.set(table, id ? `${key}_${id}` : key, { value }); } - delete(table, name, id) { - if (!this.promisify) - return this.db.delete(table, id ? `${name}_${id}` : name); - else - return new Promise((res) => - res(this.db.delete(table, id ? `${name}_${id}` : name)), - ); + async get(table, key, id) { + return await this.db.get(table, id ? `${key}_${id}` : key); } -} -class AoijsAPI extends Database { - constructor(module, options = {}, db = {}, extraOptions = {}) { - super(module, options, db.promisify); - this.type = db.type || "aoi.db"; - if (this.type === "default") this.type = "aoi.db"; - this.extraOptions = extraOptions; - this.createTable(this.type); + async delete(table, key, id) { + return await this.db.delete(table, id ? `${key}_${id}` : key); } - createTable(type) { - if ( - type === "aoi.db" || - type === "default" || - this.type === "aoi.db-dev" - ) { - if (!this.extraOptions.dbType) - this.extraOptions.dbType = "KeyValue"; - this.db = new this.module[this.extraOptions.dbType || "KeyValue"]({ - path: this.path, - tables: this.tables, - ...(this.extraOptions ?? {}), - }); - this.db.connect(); - } + async all(table, query, limit) { + return await this.db.all(table, query, limit); } - async set(table, name, id, value) { - if (this.type === "aoi.db" || this.type === "aoi.db-dev") { - if (this.extraOptions.dbType === "KeyValue") { - await this.db.set(table, id ? `${name}_${id}` : name, { - value, - }); - } else if (this.extraOptions.dbType === "WideColumn") { - return await this.db.set( - table, - { name: name, value }, - { name: "id", value: id }, - ); - } else if (this.extraOptions.dbType === "Transmitter") { - if (this.extraOptions.dbOptions.databaseType === "KeyValue") - return await this.db.set(table, name, id); - else if ( - this.extraOptions.dbOptions.databaseType === "WideColumn" - ) - return await this.db.set( - table, - { name: name, value }, - { name: "id", value: id }, - ); - } - } else { - await super.set(table, name, id, value); - } + async has(table, key, id) { + return await this.db.has(table, id ? `${key}_${id}` : key); } - async get(table, name, id) { - if (this.type === "aoi.db" || this.type === "aoi.db-dev") { - if (this.extraOptions.dbType === "KeyValue") { - return await this.db.get(table, id ? `${name}_${id}` : name); - } else if (this.extraOptions.dbType === "WideColumn") { - return await this.db.get(table, name, id); - } else if (this.extraOptions.dbType === "Transmitter") { - return await this.db.get(table, name, id); - } - } else { - return super.get(table, name, id); - } + async deleteMany(table, query) { + return await this.db.deleteMany(table, query); } - async all(table, varname, lengthofId, funconId) { - if (this.type === "aoi.db") { - return await this.db.all( - table, - (x) => - x.startsWith(`${varname}_`) && - (lengthofId ? x.split("_").slice(1).length === lengthofId : true) && - (funconId ? this.checkConditionOnId(x, ...funconId) : true), - Infinity, - ); - } else if(this.type === "aoi.db-dev") { - return await this.db.all(table, (x) => - x.key.startsWith(`${varname}_`) && - (lengthofId ? x.key.split("_").slice(1).length === lengthofId : true) && - (funconId ? this.checkConditionOnId(x.key, ...funconId) : true), - Infinity, - ); - } - else { - return await super.all(table, varname, lengthofId, funconId); - } + async findOne(table, query) { + return await this.db.findOne(table, query); } - async delete(table, name, id) { - if (this.type === "aoi.db" || this.type === "aoi.db-dev") { - return await this.db.delete(table, id ? `${name}_${id}` : name); - } else { - return super.delete(table, name, id); - } + async findMany(table, query, limit) { + return await this.db.findMany(table, query, limit); } } -module.exports = { - AoijsAPI -}; \ No newline at end of file +module.exports = Database; \ No newline at end of file diff --git a/src/functions/database/advanceCooldown.js b/src/functions/database/advanceCooldown.js index 413d3e659..f8a998ff4 100644 --- a/src/functions/database/advanceCooldown.js +++ b/src/functions/database/advanceCooldown.js @@ -7,11 +7,11 @@ module.exports = async (d) => { let [time, id, errorObject = ""] = data.inside.splits; let error; - let cooldown = await d.client.db.get(d.client.db.tables[0], "cooldown", id); + let cooldown = await d.client.db.get("__aoijs_vars__", "cooldown", id); cooldown = cooldown?.value; if (!cooldown) { cooldown = Date.now() + Time.parse(time).ms; - d.client.db.set(d.client.db.tables[0], "cooldown", id, cooldown); + d.client.db.set("__aoijs_vars__", "cooldown", id, cooldown); } else if (Date.now() < cooldown) { if (errorObject.trim() === "") { } else { @@ -40,7 +40,7 @@ module.exports = async (d) => { error = true; } else { cooldown = Date.now() + Time.parse(time).ms; - d.client.db.set(d.client.db.tables[0], "cooldown", id, cooldown); + d.client.db.set("__aoijs_vars__", "cooldown", id, cooldown); } return { diff --git a/src/functions/database/channelCooldown.js b/src/functions/database/channelCooldown.js index 4012df135..331715364 100644 --- a/src/functions/database/channelCooldown.js +++ b/src/functions/database/channelCooldown.js @@ -7,7 +7,7 @@ module.exports = async (d) => { let error; let cooldown = await d.client.db.get( - d.client.db.tables[0], + "__aoijs_vars__", "cooldown", `${d.command.name}_${d.channel.id}`, ); @@ -15,7 +15,7 @@ module.exports = async (d) => { if (!cooldown) { cooldown = Date.now() + Time.parse(time).ms; d.client.db.set( - d.client.db.tables[0], + "__aoijs_vars__", "cooldown", `${d.command.name}_${d.channel.id}`, cooldown, @@ -49,7 +49,7 @@ module.exports = async (d) => { } else { cooldown = Date.now() + Time.parse(time).ms; d.client.db.set( - d.client.db.tables[0], + "__aoijs_vars__", "cooldown", `${d.command.name}_${d.channel.id}`, cooldown, diff --git a/src/functions/database/cooldown.js b/src/functions/database/cooldown.js index edf917d09..ef19bd4e0 100644 --- a/src/functions/database/cooldown.js +++ b/src/functions/database/cooldown.js @@ -9,7 +9,7 @@ module.exports = async (d) => { let error; let cooldown = await d.client.db.get( - d.client.db.tables[0], + "__aoijs_vars__", "cooldown", `${d.command.name}_${d.author.id}_${d.guild.id || "dm"}`, ); @@ -18,7 +18,7 @@ module.exports = async (d) => { if (!cooldown) { cooldown = Date.now() + Time.parse(time).ms; d.client.db.set( - d.client.db.tables[0], + "__aoijs_vars__", "cooldown", `${d.command.name}_${d.author.id}_${d.guild.id || "dm"}`, cooldown, @@ -52,7 +52,7 @@ module.exports = async (d) => { } else { cooldown = Date.now() + Time.parse(time).ms; d.client.db.set( - d.client.db.tables[0], + "__aoijs_vars__", "cooldown", `${d.command.name}_${d.author.id}_${d.guild.id || "dm"}`, cooldown, diff --git a/src/functions/database/getLeaderboardInfo.js b/src/functions/database/getLeaderboardInfo.js index 0ec2ccdba..b5d56e63d 100644 --- a/src/functions/database/getLeaderboardInfo.js +++ b/src/functions/database/getLeaderboardInfo.js @@ -16,34 +16,41 @@ module.exports = async (d) => { let key = null; let cache = null; let user = null; + if (type === "guild") { + key = `${variable.addBrackets()}_${`${id}_${ + d.guild?.id === "undefined" ? "dm" : d.guild?.id + }`}`; + cache = await d.util.getGuild(d, id); + user = + typeof cache === "undefined" || Object.keys(cache).length === 0 + ? await d.util.getUser(d, id) + : undefined; + } else if (type === "global") { + key = `${variable.addBrackets()}_${id}`; + cache = await d.util.getGuild(d, id); + user = + typeof cache === "undefined" || Object.keys(cache).length === 0 + ? await d.util.getUser(d, id) + : undefined; + } else if (type === "message" || type === "channel") { + key = `${variable.addBrackets()}_${id}`; + } else { + d.aoiError.fnError(d, "custom", { inside: data.inside }, `type`); + } + const all = await d.client.db.all(table, (data) => + data.key.startsWith(variable.deleteBrackets()) && + data.key.split("_").length === key.split("_").length && ( + type === "guild" ? data.key.split("_")[2] === key.split("_")[2] : true + ) + ); + + - const all = await d.client.db.all(table, variable); - - if (type === "guild") { - key = `${variable.addBrackets()}_${`${id}_${ - d.guild?.id === "undefined" ? "dm" : d.guild?.id - }`}`; - cache = await d.util.getGuild(d, id); - user = - typeof cache === "undefined" || Object.keys(cache).length === 0 - ? await d.util.getUser(d, id) - : undefined; - } else if (type === "global") { - key = `${variable.addBrackets()}_${id}`; - cache = await d.util.getGuild(d, id); - user = - typeof cache === "undefined" || Object.keys(cache).length === 0 - ? await d.util.getUser(d, id) - : undefined; - } else if (type === "message" || type === "channel") { - key = `${variable.addBrackets()}_${id}`; - } else { - d.aoiError.fnError(d, "custom", { inside: data.inside }, `type`); - } + switch (format) { case "top": - data.result = all.slice().sort((a, b) => b.value - a.value).findIndex((x) => x.key === key) + 1 || 0; + data.result = all.sort((a, b) => b.value - a.value).findIndex((x) => x.key === key) + 1 || 0; break; case "value": data.result = all.find(x => x.key === key).value || 0; diff --git a/src/functions/database/globalCooldown.js b/src/functions/database/globalCooldown.js index d549788ed..7fdc70337 100644 --- a/src/functions/database/globalCooldown.js +++ b/src/functions/database/globalCooldown.js @@ -1,6 +1,6 @@ -const {Time} = require("../../utils/helpers/customParser.js"); +const { Time } = require("../../utils/helpers/customParser.js"); module.exports = async (d) => { - const {code} = d.command; + const { code } = d.command; const inside = d.unpack(); const err = d.inside(inside); if (err) return d.error(err); @@ -9,7 +9,7 @@ module.exports = async (d) => { let error; let cooldown = await d.client.db.get( - d.client.db.tables[0], + "__aoijs_vars__", "cooldown", `${d.command.name}_${d.author.id}`, ); @@ -18,7 +18,7 @@ module.exports = async (d) => { if (!cooldown) { cooldown = Date.now() + Time.parse(time).ms; d.client.db.set( - d.client.db.tables[0], + "__aoijs_vars__", "cooldown", `${d.command.name}_${d.author.id}`, cooldown, @@ -26,7 +26,9 @@ module.exports = async (d) => { } else if (Date.now() < cooldown) { if (errorObject.trim() === "") { } else { - const {object, humanize, toString} = Time.format(cooldown - Date.now()); + const { object, humanize, toString } = Time.format( + cooldown - Date.now(), + ); errorObject = errorObject .replaceAll("%time%", humanize()) .replaceAll("%year%", object.years) @@ -45,21 +47,21 @@ module.exports = async (d) => { d.channel, errorObject.data ?? errorObject, errorObject.options, - d + d, ); } error = true; } else { cooldown = Date.now() + Time.parse(time).ms; d.client.db.set( - d.client.db.tables[0], + "__aoijs_vars__", "cooldown", `${d.command.name}_${d.author.id}`, cooldown, ); } return { - code: d.util.setCode({function: d.func, code, inside}), + code: d.util.setCode({ function: d.func, code, inside }), error, }; }; diff --git a/src/functions/database/globalUserLeaderBoard.js b/src/functions/database/globalUserLeaderBoard.js index e3027a6d0..c341e868a 100644 --- a/src/functions/database/globalUserLeaderBoard.js +++ b/src/functions/database/globalUserLeaderBoard.js @@ -1,7 +1,3 @@ -const { - AoijsAPI -} = require("../../classes/Database.js"); - module.exports = async (d) => { const data = d.util.aoiFunc(d); if (data.err) return d.error(data.err); @@ -15,28 +11,24 @@ module.exports = async (d) => { table = d.client.db.tables[0], ] = data.inside.splits; - const all = await d.client.db.all(table, variable.addBrackets(), 1); + const all = await d.client.db.all(table, (data) => + data.key.startsWith(variable.deleteBrackets()) && data.key.split("_").length === 2, + ); + let y = 0; let value; let content = []; for (const Data of all.sort((x, y) => { - if (d.client.db instanceof AoijsAPI) { - if (d.client.db.type === "aoi.db") return Number(y.value) - Number(x.value); - - else return Number(y.data.value) - Number(x.data.value); - } + if (d.client.db.type === "aoi.db") + return Number(y.value) - Number(x.value); + else return Number(y.data.value) - Number(x.data.value); })) { let user; - - if (d.client.db instanceof AoijsAPI) { - if (d.client.db.type === "aoi.db") - value = Number(Data.value) - else value = Number(Data.data.value); - - user = await d.util.getUser(d, Data.key.split("_")[1]); - } + if (d.client.db.type === "aoi.db") value = Number(Data.value); + else value = Number(Data.data.value); + user = await d.util.getUser(d, Data.key.split("_")[1]); if (user) { y++; @@ -51,13 +43,15 @@ module.exports = async (d) => { if (text.includes("{execute:")) { let ins = text.split("{execute:")[1].split("}")[0]; - const awaited = d.client.cmd.awaited.find((c) => c.name === ins); + const awaited = d.client.cmd.awaited.find( + (c) => c.name === ins, + ); if (!awaited) return d.aoiError.fnError( d, "custom", - {inside: data.inside}, + { inside: data.inside }, ` Invalid awaited command '${ins}' in`, ); @@ -91,4 +85,4 @@ module.exports = async (d) => { return { code: d.util.setCode(data), }; -}; \ No newline at end of file +}; diff --git a/src/functions/database/guildLeaderBoard.js b/src/functions/database/guildLeaderBoard.js index 07a954318..9719fe3a2 100644 --- a/src/functions/database/guildLeaderBoard.js +++ b/src/functions/database/guildLeaderBoard.js @@ -1,7 +1,3 @@ -const { - AoijsAPI -} = require("../../classes/Database.js"); - module.exports = async (d) => { const data = d.util.aoiFunc(d); if (data.err) return d.error(data.err); @@ -15,26 +11,25 @@ module.exports = async (d) => { table = d.client.db.tables[0], ] = data.inside.splits; - const all = await d.client.db.all(table, variable.addBrackets(), 1); + const all = await d.client.db.all(table, (data) => + data.key.startsWith(variable.deleteBrackets()) && data.key.split("_").length === 2, + ); let y = 0; let value; let content = []; for (const Data of all.sort((x, y) => { - if (d.client.db instanceof AoijsAPI) { - if (d.client.db.type === "aoi.db") - return Number(y.value) - Number(x.value); - else return Number(y.data.value) - Number(x.data.value); - } + if (d.client.db.type === "aoi.db") + return Number(y.value) - Number(x.value); + else return Number(y.data.value) - Number(x.data.value); })) { let user; - if (d.client.db instanceof AoijsAPI) { - if (d.client.db.type === "aoi.db") value = Number(Data.value); - else value = Number(Data.data.value); - user = await d.util.getGuild(d, Data.key.split("_")[1]); - } + if (d.client.db.type === "aoi.db") value = Number(Data.value); + else value = Number(Data.data.value); + + user = await d.util.getGuild(d, Data.key.split("_")[1]); if (user) { y++; @@ -48,13 +43,15 @@ module.exports = async (d) => { if (text.includes("{execute:")) { let ins = text.split("{execute:")[1].split("}")[0]; - const awaited = d.client.cmd.awaited.find((c) => c.name === ins); + const awaited = d.client.cmd.awaited.find( + (c) => c.name === ins, + ); if (!awaited) return d.aoiError.fnError( d, "custom", - {inside: data.inside}, + { inside: data.inside }, ` Invalid awaited command '${ins}' in`, ); @@ -87,4 +84,4 @@ module.exports = async (d) => { return { code: d.util.setCode(data), }; -}; \ No newline at end of file +}; diff --git a/src/functions/database/rawLeaderboard.js b/src/functions/database/rawLeaderboard.js index c10ef8816..00cf778ab 100644 --- a/src/functions/database/rawLeaderboard.js +++ b/src/functions/database/rawLeaderboard.js @@ -1,7 +1,3 @@ -const { - AoijsAPI -} = require("../../classes/Database.js"); - module.exports = async (d) => { const data = d.util.aoiFunc(d); if (data.err) return d.error(data.err); @@ -28,22 +24,41 @@ module.exports = async (d) => { let y = 0; let value; let content = []; - const all = await d.client.db.all(table, variable.addBrackets(), idLength); + let all = await d.client.db.all( + table, + (data) => + data.key.startsWith(variable.deleteBrackets()) && + data.key.split("_").length === idLength + 1, + ); + + all = all.sort((x, y) => { + if (d.client.db.type === "aoi.db") + return Number(y.value) - Number(x.value); + else return Number(y.data.value) - Number(x.data.value); + }); + + const getdata = async (user, Data, key) => { + user = + (type === "globalUser" + ? await d.util.getUser(d, Data.key.split("_")[key]) + : type === "user" + ? await d.util.getMember(d.guild, Data.key.split("_")[key]) + : type === "server" + ? await d.util.getGuild(d, Data.key.split("_")[key]) + : Data.key.split("_")[key]) ?? Data.key.split("_")[key]; + return user; + }; + + for (let i = 0; i < all.length; i++) { + const Data = all[i]; - for (const Data of all.sort((x, y) => { - if (d.client.db instanceof AoijsAPI) { - if (d.client.db.type === "aoi.db") - return Number(y.value) - Number(x.value); - else return Number(y.data.value) - Number(x.data.value); - } - })) { let user; - if (d.client.db instanceof AoijsAPI) { - if (d.client.db.type === "aoi.db") value = Number(Data.value); - else value = Number(Data.data.value); - user = await getdata(user, Data, 1); - } + if (d.client.db.type === "aoi.db") value = Number(Data.value); + else value = Number(Data.data.value); + + user = await getdata(user, Data, 1); + if (user) { user = @@ -51,7 +66,7 @@ module.exports = async (d) => { ? type === "user" ? user.user : user - : {id: user}; + : { id: user }; y++; let text = custom @@ -69,13 +84,15 @@ module.exports = async (d) => { if (text.includes("{execute:")) { let ins = text.split("{execute:")[1].split("}")[0]; - const awaited = d.client.cmd.awaited.find((c) => c.name === ins); + const awaited = d.client.cmd.awaited.find( + (c) => c.name === ins, + ); if (!awaited) return d.aoiError.fnError( d, "custom", - {inside: data.inside}, + { inside: data.inside }, ` Invalid awaited command '${ins}' in`, ); @@ -97,39 +114,27 @@ module.exports = async (d) => { content.push(text); } - if (order === "desc") content = content.reverse(); - - const px = page * list - list, - py = page * list; - - data.result = content.slice(px, py).join("\n"); - - return { - code: d.util.setCode(data), - }; - } - - async function customarr(arr) { - user = - (type === "globalUser" - ? await d.util.getUser(d, arr[1]) - : type === "user" - ? await d.util.getMember(d.guild, arr[1]) - : type === "server" - ? await d.util.getGuild(d, arr[1]) - : arr[1]) ?? arr[1]; - return user; - } - - async function getdata(user, Data, key) { - user = - (type === "globalUser" - ? await d.util.getUser(d, Data.key.split("_")[key]) - : type === "user" - ? await d.util.getMember(d.guild, Data.key.split("_")[key]) - : type === "server" - ? await d.util.getGuild(d, Data.key.split("_")[key]) - : Data.key.split("_")[key]) ?? Data.key.split("_")[key]; - return user; } -}; \ No newline at end of file + if (order === "desc") content = content.reverse(); + + const px = page * list - list, + py = page * list; + + data.result = content.slice(px, py).join("\n"); + + return { + code: d.util.setCode(data), + }; +}; + +async function customarr(arr) { + user = + (type === "globalUser" + ? await d.util.getUser(d, arr[1]) + : type === "user" + ? await d.util.getMember(d.guild, arr[1]) + : type === "server" + ? await d.util.getGuild(d, arr[1]) + : arr[1]) ?? arr[1]; + return user; +} diff --git a/src/functions/database/resetGlobalUserVar.js b/src/functions/database/resetGlobalUserVar.js index a4ae2c095..03214b96e 100644 --- a/src/functions/database/resetGlobalUserVar.js +++ b/src/functions/database/resetGlobalUserVar.js @@ -1,6 +1,3 @@ -const { - AoijsAPI -} = require("../../classes/Database.js"); module.exports = async (d) => { const data = d.util.aoiFunc(d); @@ -16,12 +13,8 @@ module.exports = async (d) => { `Variable ${varname.addBrackets()} Doesn't Exist!`, ); - const all = await d.client.db.all(table, varname.addBrackets(), 1); - if (d.client.db instanceof AoijsAPI) { - all - .filter(async (x) => await d.util.getUser(d, x.key.split("_")[1])) - .forEach(async (x) => await d.client.db.delete(table, x.key)); - } + await d.client.db.deleteMany(table, (Data) => Data.key.startsWith(`${varname}_`)); + return { code: d.util.setCode(data), }; diff --git a/src/functions/database/resetGuildVar.js b/src/functions/database/resetGuildVar.js index efbaf72dc..ec74d4075 100644 --- a/src/functions/database/resetGuildVar.js +++ b/src/functions/database/resetGuildVar.js @@ -1,6 +1,3 @@ -const { - AoijsAPI -} = require("../../classes/Database.js"); module.exports = async (d) => { const data = d.util.aoiFunc(d); @@ -16,12 +13,11 @@ module.exports = async (d) => { `Variable ${varname.addBrackets()} Doesn't Exist!`, ); - const all = await d.client.db.all(table, varname.addBrackets(), 1); - if (d.client.db instanceof AoijsAPI) { - all - .filter(async (x) => await d.util.getGuild(d, x.key.split("_")[1])) - .forEach(async (x) => await d.client.db.delete(table, x.key)); - } + await d.client.db.deleteMany(table, (Data) => { + return Data.key.startsWith(`${varname}_`) && + Data.key.split("_").length == 2 && + d.client.guilds.cache.has(Data.key.split("_")[1]); + }); return { code: d.util.setCode(data), diff --git a/src/functions/database/resetUserVar.js b/src/functions/database/resetUserVar.js index f3d099ca6..e221b980b 100644 --- a/src/functions/database/resetUserVar.js +++ b/src/functions/database/resetUserVar.js @@ -1,6 +1,3 @@ -const { - AoijsAPI -} = require("../../classes/Database.js"); module.exports = async (d) => { const data = d.util.aoiFunc(d); @@ -17,15 +14,14 @@ module.exports = async (d) => { `Variable ${varname.addBrackets()} Doesn't Exist!`, ); - const all = await d.client.db.all(table, varname.addBrackets(), 2, [ - 1, - guildID, - ]); - if (d.client.db instanceof AoijsAPI) { - all - .filter(async (x) => await d.util.getUser(d, x.key.split("_")[1])) - .forEach(async (x) => await d.client.db.delete(table, x.key)); - } + await d.client.db.deleteMany(table, (Data) => { + return ( + Data.key.startsWith(`${varname}_`) && + Data.key.split("_").length == 3&& + Data.key.split("_").endsWith(`_${guildID}`) + ); + }); + return { code: d.util.setCode(data), }; diff --git a/src/functions/database/userLeaderBoard.js b/src/functions/database/userLeaderBoard.js index 41964f0e3..8f30d936a 100644 --- a/src/functions/database/userLeaderBoard.js +++ b/src/functions/database/userLeaderBoard.js @@ -1,69 +1,96 @@ -const {AoijsAPI} = require("../../classes/Database.js"); - -module.exports = async d => { +module.exports = async (d) => { const data = d.util.aoiFunc(d); - if (data.err) return d.error(data.err) - - const [guildID = d.guild?.id, variable, type = 'asc', custom = `{top}. {username}: {value}`, list = 10, page = 1, table = d.client.db.tables[0]] = data.inside.splits; - - const all = await d.client.db.all(table, variable.addBrackets(), 2, [1, guildID]) + if (data.err) return d.error(data.err); + + const [ + guildID = d.guild?.id, + variable, + type = "asc", + custom = `{top}. {username}: {value}`, + list = 10, + page = 1, + table = d.client.db.tables[0], + ] = data.inside.splits; + + let all = await d.client.db.all( + table, + (data) => + data.key.startsWith(variable.deleteBrackets()) && + data.key.split("_").length === 3 && + data.key.split("_")[2] === guildID, + ); const guild = await d.util.getGuild(d, guildID); - if (!guild) return d.aoiError.fnError(d, "guild", {inside: data.inside}); - + if (!guild) return d.aoiError.fnError(d, "guild", { inside: data.inside }); - let y = 0 let value; - let content = [] + let content = []; - for (const Data of all.sort((x, y) => { - if (d.client.db instanceof AoijsAPI) { - if (d.client.db.type === "aoi.db") - return Number(y.value) - Number(x.value); - else return Number(y.data.value) - Number(x.data.value); - } - })) { + const px = (page-1) * list, + py = page * list; + + all = all.sort((x, y) => { + if (d.client.db.type === "aoi.db") + return Number(y.value) - Number(x.value); + else return Number(y.data.value) - Number(x.data.value); + }); + all = all.slice(px, py); + let y = px+1; + + for (const Data of all ) { let user; - if (d.client.db instanceof AoijsAPI) { - if (d.client.db.type === "aoi.db") value = Number(Data.value); - else value = Number(Data.data.value); - user = await d.util.getMember(guild, Data.key.split('_')[1]) - } + if (d.client.db.type === "aoi.db") value = Number(Data.value); + else value = Number(Data.data.value); - if (user) { - user = user.user; - y++ + user = await d.util.getMember(guild, Data.key.split("_")[1]); + // console.log(user) - let text = custom.replaceAll(`{top}`, y).replaceAll("{id}", user.id).replaceAll("{tag}", user.tag).replaceAll(`{username}`, user.username.removeBrackets()).replaceAll(`{value}`, value) + let text = custom + .replaceAll(`{top}`, y) + .replaceAll("{id}", user.user.id) + .replaceAll("{tag}", user.user.tag) + .replaceAll(`{username}`, user.user.username.removeBrackets()) + .replaceAll(`{value}`, value); - if (text.includes("{execute:")) { - let ins = text.split("{execute:")[1].split("}")[0] + if (text.includes("{execute:")) { + let ins = text.split("{execute:")[1].split("}")[0]; - const awaited = d.client.cmd.awaited.find(c => c.name === ins) + const awaited = d.client.cmd.awaited.find((c) => c.name === ins); - if (!awaited) return d.aoiError.fnError(d, 'custom', {inside: data.inside}, ` Invalid awaited command '${ins}' in`) + if (!awaited) + return d.aoiError.fnError( + d, + "custom", + { inside: data.inside }, + ` Invalid awaited command '${ins}' in`, + ); - const CODE = await d.interpreter(d.client, { + const CODE = await d.interpreter( + d.client, + { guild: guild, channel: d.message.channel, - author: user - }, d.args, awaited, undefined, true) - - text = text.replace(`{execute:${ins}}`, CODE) - } - - content.push(text) + author: user, + }, + d.args, + awaited, + undefined, + true, + ); + + text = text.replace(`{execute:${ins}}`, CODE); } - } - if (type === "desc") content = content.reverse() + content.push(text); + y++; + } - const px = page * list - list, py = page * list + if (type === "desc") content = content.reverse(); data.result = content.slice(px, py).join("\n"); return { - code: d.util.setCode(data) - } -} \ No newline at end of file + code: d.util.setCode(data), + }; +}; diff --git a/src/handler/AoiStart.js b/src/handler/AoiStart.js index 8ff5a6208..e343fcb6d 100644 --- a/src/handler/AoiStart.js +++ b/src/handler/AoiStart.js @@ -1,7 +1,6 @@ const Interpreter = require("../core/interpreter.js"); module.exports = async (client, options) => { - if (client.aoiOptions.aoiLogs !== false) { await require("./AoiLogs.js")(client); } @@ -20,7 +19,7 @@ module.exports = async (client, options) => { undefined, undefined, undefined, - true + true, ); await require("./Custom/timeoutPulse.js")( @@ -29,11 +28,15 @@ module.exports = async (client, options) => { undefined, undefined, undefined, - true + true, ); + + setInterval(async () => { + await require("./Custom/handleResidueData.js")(client); + }, 3.6e6); } if (client.cmd.loop.size) { await require("./Custom/loop.js")(client); } -}; \ No newline at end of file +}; diff --git a/src/handler/Custom/handleResidueData.js b/src/handler/Custom/handleResidueData.js new file mode 100644 index 000000000..96afbdbd5 --- /dev/null +++ b/src/handler/Custom/handleResidueData.js @@ -0,0 +1,9 @@ +async function handleResidueData(client) { + const db = client.db; + await client.db.deleteMany("__aoijs_vars__", (data) => { + const key = data.id.split("_")[0]; + if (key === "cooldown" && data.value < Date.now()) return true; + }); +} + +module.exports = handleResidueData; diff --git a/src/handler/Custom/timeout.js b/src/handler/Custom/timeout.js index 1ee8c0d89..6ab7c24be 100644 --- a/src/handler/Custom/timeout.js +++ b/src/handler/Custom/timeout.js @@ -1,100 +1,103 @@ -const { AoijsAPI } = require("../../classes/Database.js"); - module.exports = async (d, name, duration, timeoutData, onReady) => { - let cmds = d.client.cmd.timeout.allValues(); - if (onReady) { - const datas = await d.client.db.all(d.client.db.tables[0], "setTimeout"); - for (const data of datas.filter((x) => { - if (d.client.db instanceof AoijsAPI) { - return !x.value.__pulseEvery__; - } else { - return ( - !x?.value?.__pulseEvery__ && - (typeof x.data === "object" - ? !x.data.value?.__pulseEvery__ - : !x.data?.__pulseEvery__) + let cmds = d.client.cmd.timeout.allValues(); + if (onReady) { + const datas = await d.client.db.all( + "__aoijs_vars__", + (data) => data.key.startsWith("setTimeout_"), ); - } - })) { - let t; - - if (d.client.db instanceof AoijsAPI) { - t = data.value; - } else { - t = data?.value || (typeof data.data === "object" ? data.data.value : data.data); - } - t.__timeoutIds__ = []; - const dura = t.__duration__ - Date.now(); - cmds = cmds.filter((x) => x.name === t.__timeoutName__); - if (dura > 0) { - for (const cmd of cmds) { - const timeout = setTimeout(async () => { - await d.interpreter( - d.client, - {}, - [], - cmd, - d.client.db, - false, - undefined, - { timeoutData: t }, - ); - t.__timeoutIds__.push(timeout[Symbol.toPrimitive]()); + for (const data of datas.filter((x) => { + return !x.value.__pulseEvery__; + })) { + let t = data.value; + t.__timeoutIds__ = []; + const dura = t.__duration__ - Date.now(); + cmds = cmds.filter((x) => x.name === t.__timeoutName__); + if (dura > 0) { + for (const cmd of cmds) { + const timeout = setTimeout(async () => { + await d.interpreter( + d.client, + {}, + [], + cmd, + d.client.db, + false, + undefined, + { timeoutData: t }, + ); + t.__timeoutIds__.push(timeout[Symbol.toPrimitive]()); - await d.client.db.delete(d.client.db.tables[0], data.key); - }, dura); + await d.client.db.delete( + "__aoijs_vars__", + data.key, + ); + }, dura); + } + d.client.db.set( + "__aoijs_vars__", + "setTimeout", + t.__id__, + t, + ); + } else { + for (const cmd of cmds) { + await d.interpreter( + d.client, + {}, + [], + cmd, + d.client.db, + false, + undefined, + { timeoutData: t }, + ); + } + await d.client.db.delete("__aoijs_vars__", data.key); + continue; + } } - d.client.db.set(d.client.db.tables[0], "setTimeout", t.__id__, t); - } else { - for (const cmd of cmds) { - await d.interpreter( - d.client, - {}, - [], - cmd, - d.client.db, - false, - undefined, - { timeoutData: t }, - ); + } else { + timeoutData.__timeoutIds__ = []; + if (name) { + cmds = cmds.filter((x) => x.name === name); } - await d.client.db.delete(d.client.db.tables[0], data.key); - continue; - } - } - } else { - timeoutData.__timeoutIds__ = []; - if (name) { - cmds = cmds.filter((x) => x.name === name); - } - const ids = []; - for (const cmd of cmds) { - const timeout = setTimeout(async () => { - await d.interpreter( - d.client, - {}, - [], - cmd, - d.client.db, - false, - undefined, - { timeoutData }, - ); + const ids = []; + for (const cmd of cmds) { + const timeout = setTimeout(async () => { + await d.interpreter( + d.client, + {}, + [], + cmd, + d.client.db, + false, + undefined, + { timeoutData }, + ); - d.client.db.delete( - d.client.db.tables[0], + ids.splice(ids.indexOf(timeout[Symbol.toPrimitive]()), 1); + if (ids.length === 0) { + await d.client.db.delete( + "__aoijs_vars__", + timeoutData.__id__, + ); + } else { + await d.client.db.set( + "__aoijs_vars__", + "setTimeout", + timeoutData.__id__, + timeoutData, + ); + } + }, duration); + ids.push(timeout[Symbol.toPrimitive]()); + } + timeoutData.__timeoutIds__ = ids; + await d.client.db.set( + "__aoijs_vars__", "setTimeout", timeoutData.__id__, + timeoutData, ); - }, duration); - ids.push(timeout[Symbol.toPrimitive]()); } - timeoutData.__timeoutIds__ = ids; - await d.client.db.set( - d.client.db.tables[0], - "setTimeout", - timeoutData.__id__, - timeoutData, - ); - } }; diff --git a/src/handler/Custom/timeoutPulse.js b/src/handler/Custom/timeoutPulse.js index 1dc12ad89..1246b7601 100644 --- a/src/handler/Custom/timeoutPulse.js +++ b/src/handler/Custom/timeoutPulse.js @@ -1,81 +1,102 @@ -const { AoijsAPI } = require("../../classes/Database.js"); - module.exports = async (d, name, duration, pulse, timeoutData, onReady) => { - let cmds = d.client.cmd.pulse.allValues(); - - if (onReady) { - const datas = await d.client.db.all(d.client.db.tables[0], "setTimeout"); - for (const data of datas.filter((x) => x.value?.__pulseEvery__)) { - let t; + let cmds = d.client.cmd.pulse.allValues(); - if (d.client.db instanceof AoijsAPI) { - t = data.value; - } else { - t = data.data.value; - } + if (onReady) { + const datas = await d.client.db.all("__aoijs_vars__", (data) => + data.key.startsWith("setTimeout_"), + ); + for (const data of datas.filter((x) => x.value?.__pulseEvery__)) { + let t = data.value; - t.__timeoutIds__ = []; - t.__pulseIds__ = []; - cmds = cmds.filter((x) => x.name === t.__timeoutName__); + t.__timeoutIds__ = []; + t.__pulseIds__ = []; + cmds = cmds.filter((x) => x.name === t.__timeoutName__); - if (t.__duration__ - Date.now() > 0) { - for (const cmd of cmds) { - const interval = setInterval(async () => { - await d.interpreter( - d.client, - {}, - [], - cmd, - d.client.db, - false, - undefined, - { timeoutData: t } - ); - }, t.__pulseEvery__); + if (t.__duration__ - Date.now() > 0) { + for (const cmd of cmds) { + const interval = setInterval(async () => { + await d.interpreter( + d.client, + {}, + [], + cmd, + d.client.db, + false, + undefined, + { timeoutData: t }, + ); + }, t.__pulseEvery__); - t.__pulseIds__.push(interval[Symbol.toPrimitive()]()); + t.__pulseIds__.push(interval[Symbol.toPrimitive()]()); - const timeout = setTimeout(async () => { - clearInterval(interval); - await d.client.db.delete(d.client.db.tables[0], data.key); - }, t.__duration__ - Date.now()); + const timeout = setTimeout(async () => { + clearInterval(interval); + await d.client.db.delete("__aoijs_vars__", data.key); + }, t.__duration__ - Date.now()); - t.__timeoutIds__.push(timeout[Symbol.toPrimitive()]()); + t.__timeoutIds__.push(timeout[Symbol.toPrimitive()]()); + } + d.client.db.set("__aoijs_vars__", "setTimeout", t.__id__, t); + } else { + await d.client.db + .delete("__aoijs_vars__", data.key) + .catch(console.error); + } + } + } else { + if (name) { + cmds = cmds.filter((x) => x.name === name); } - d.client.db.set(d.client.db.tables[0], "setTimeout", t.__id__, t); - } else { - await d.client.db.delete(d.client.db.tables[0], data.key).catch(console.error); - } - } - } else { - if (name) { - cmds = cmds.filter((x) => x.name === name); - } - timeoutData.__timeoutIds__ = []; - timeoutData.__pulseIds__ = []; + timeoutData.__timeoutIds__ = []; + timeoutData.__pulseIds__ = []; - for (const cmd of cmds) { - const interval = setInterval(() => { - d.interpreter(d.client, {}, [], cmd, d.client.db, false, undefined, { - timeoutData, - }); - }, pulse || duration); + for (const cmd of cmds) { + const interval = setInterval(() => { + d.interpreter( + d.client, + {}, + [], + cmd, + d.client.db, + false, + undefined, + { + timeoutData, + }, + ); + }, pulse || duration); - timeoutData.__pulseIds__.push(interval[Symbol.toPrimitive()]()); + timeoutData.__pulseIds__.push(interval[Symbol.toPrimitive()]()); - const timeout = setTimeout(async () => { - clearInterval(interval); - await d.client.db.delete( - d.client.db.tables[0], + const timeout = setTimeout(async () => { + clearInterval(interval); + + const ids = timeoutData.__timeoutIds__; + ids.splice(ids.indexOf(timeout[Symbol.toPrimitive]()), 1); + + if (ids.length === 0) + await d.client.db.delete( + "__aoijs_vars__", + timeoutData.__id__, + ); + else + await d.client.db.set( + "__aoijs_vars__", + "setTimeout", + timeoutData.__id__, + timeoutData, + ); + }, duration); + + timeoutData.__timeoutIds__.push(timeout[Symbol.toPrimitive()]()); + } + + d.client.db.set( + "__aoijs_vars__", "setTimeout", - timeoutData.__id__ + timeoutData.__id__, + timeoutData, ); - }, duration); - - timeoutData.__timeoutIds__.push(timeout[Symbol.toPrimitive()]()); } - - d.client.db.set(d.client.db.tables[0], "setTimeout", timeoutData.__id__, timeoutData); - } }; diff --git a/src/index.js b/src/index.js index af1a79e1c..7f9031db7 100644 --- a/src/index.js +++ b/src/index.js @@ -4,7 +4,7 @@ const LoadCommands = require("./classes/LoadCommands.js"); const ClientShard = require("./classes/ClientShard.js"); const AoiError = require("./classes/AoiError.js"); const Util = require("./classes/Util.js"); -const {AoijsAPI} = require("./classes/Database.js"); +const Database = require("./classes/Database.js"); const CacheManager = require("./classes/CacheManager.js"); /** @@ -18,6 +18,6 @@ module.exports = { ClientShard, AoiError, Util, - AoijsAPI, + Database, CacheManager, };