diff options
author | TheArcaneBrony <myrainbowdash949@gmail.com> | 2022-08-20 03:27:03 +0200 |
---|---|---|
committer | TheArcaneBrony <myrainbowdash949@gmail.com> | 2022-08-20 03:27:03 +0200 |
commit | 04dea8d788acfaf485f4aa9ad255e39f6aac2a08 (patch) | |
tree | 2a61e45ef6f313012a585a0a80c1fa5bfe3ddae8 | |
parent | Fix merge conflicts (diff) | |
download | server-04dea8d788acfaf485f4aa9ad255e39f6aac2a08.tar.xz |
prettier
339 files changed, 3835 insertions, 4235 deletions
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index a4ca0bb9..8ab6ab5a 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,11 +1,11 @@ blank_issues_enabled: true contact_links: - - name: Fosscord Documentation - url: https://docs.fosscord.com/ - about: Need documentation and examples for the Fosscord? Head over to Fosscord's official documentation. - - name: Discord's Developer Documentation - url: https://discord.com/developers/docs/intro - about: Need help with the Discord resources? Head here instead of asking on Fosscord! - - name: Fosscord' Official Discord server - url: https://discord.com/invite/Ms5Ev7S6bF - about: Need help with the server? Talk with us in our official server. + - name: Fosscord Documentation + url: https://docs.fosscord.com/ + about: Need documentation and examples for the Fosscord? Head over to Fosscord's official documentation. + - name: Discord's Developer Documentation + url: https://discord.com/developers/docs/intro + about: Need help with the Discord resources? Head here instead of asking on Fosscord! + - name: Fosscord' Official Discord server + url: https://discord.com/invite/Ms5Ev7S6bF + about: Need help with the server? Talk with us in our official server. diff --git a/.github/relase_body_template.md b/.github/relase_body_template.md index 994e83d3..c410b0c2 100644 --- a/.github/relase_body_template.md +++ b/.github/relase_body_template.md @@ -1,13 +1,17 @@ ## Notes ## Additions -- + +- ## Fixes + - + ## Download -- [Windows]() -- [MacOS]() -- [Linux]() + +- [Windows]() +- [MacOS]() +- [Linux]() After (extracting) and starting the server executable you can access your own Fosscord server on http://localhost:3001/ diff --git a/.vscode/launch.json b/.vscode/launch.json index 09ff7134..076cc65f 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,17 +1,13 @@ { - "version": "0.2.0", - "configurations": [ - { - "type": "node", - "request": "launch", - "name": "Launch Program", - "skipFiles": [ - "<node_internals>/**" - ], - "program": "${file}", - "outFiles": [ - "${workspaceFolder}/**/*.js" - ] - } - ] -} \ No newline at end of file + "version": "0.2.0", + "configurations": [ + { + "type": "node", + "request": "launch", + "name": "Launch Program", + "skipFiles": ["<node_internals>/**"], + "program": "${file}", + "outFiles": ["${workspaceFolder}/**/*.js"] + } + ] +} diff --git a/docker-compose-dev.yml b/docker-compose-dev.yml index 80429042..d6f086be 100644 --- a/docker-compose-dev.yml +++ b/docker-compose-dev.yml @@ -1,2 +1 @@ - -The Docker image is coming with the dashboard. The planned release date is 2022-12-24. +The Docker image is coming with the dashboard. The planned release date is 2022-12-24. diff --git a/package.json b/package.json index 117db412..d8febb96 100644 --- a/package.json +++ b/package.json @@ -87,6 +87,7 @@ "node-fetch": "^2.6.7", "patch-package": "^6.4.7", "picocolors": "^1.0.0", + "prettier": "^2.7.1", "proxy-agent": "^5.0.0", "reflect-metadata": "^0.1.13", "typeorm": "^0.3.7", diff --git a/scripts/first_setup.js b/scripts/first_setup.js index 0f69cacd..4ba0385c 100644 --- a/scripts/first_setup.js +++ b/scripts/first_setup.js @@ -8,9 +8,9 @@ const rl = readline.createInterface({ input: process.stdin, output: process.stdo const data = { env: [], config: { register: {} }, extra_pkgs: [] }; let rights = []; -process.on('SIGINT', function() { - console.log("Caught interrupt signal"); - process.exit(); +process.on("SIGINT", function () { + console.log("Caught interrupt signal"); + process.exit(); }); console.log("Welcome to Fosscord!"); @@ -18,8 +18,8 @@ console.log("Please remember this is pre-release software!"); console.log("We will guide you through some important setup steps."); console.log(); -if(fs.existsSync("package-lock.json")) fs.rmSync("package-lock.json"); -if(fs.existsSync("yarn.lock")) fs.rmSync("yarn.lock"); +if (fs.existsSync("package-lock.json")) fs.rmSync("package-lock.json"); +if (fs.existsSync("yarn.lock")) fs.rmSync("yarn.lock"); async function main() { printTitle("Step 1: Database setup"); @@ -82,7 +82,7 @@ async function main() { if (data.db != "sqlite") data.env.push(`DATABASE=${data.db}://${data.db_user}:${data.db_pass}@${data.db_host}:${data.db_port}/${data.db_name}`); data.env.push(`PORT=${data.port}`); - data.env.push('THREADS=1') + data.env.push("THREADS=1"); printTitle("Step 4: Default rights"); console.log("Please enter the default rights for new users."); @@ -126,8 +126,9 @@ async function main() { }; printTitle("Step 5: extra options"); - if(/y?/i.test(await ask("Use fast BCrypt implementation (requires a compiler) (Y/n): "))) data.extra_pkgs.push("bcrypt"); - if(/y?/.test(await ask("Enable support for widgets (requires compiler, known to fail on some ARM devices.) (Y/n): "))) data.extra_pkgs.push("canvas"); + if (/y?/i.test(await ask("Use fast BCrypt implementation (requires a compiler) (Y/n): "))) data.extra_pkgs.push("bcrypt"); + if (/y?/.test(await ask("Enable support for widgets (requires compiler, known to fail on some ARM devices.) (Y/n): "))) + data.extra_pkgs.push("canvas"); printTitle("Step 6: finalizing..."); //save @@ -140,13 +141,13 @@ async function main() { console.log(" ==> Ensuring yarn is up to date (v3, not v1)..."); execIn("npx yarn set version stable", process.cwd()); console.log(" ==> Installing base packages"); - execIn("npx --yes yarn install", process.cwd(), {stdio: "inherit"}); + execIn("npx --yes yarn install", process.cwd(), { stdio: "inherit" }); - console.log(` ==> Installing extra packages: ${data.extra_pkgs.join(', ')}...`); - execIn(`npx --yes yarn add -O ${data.extra_pkgs.join(' ')}`, process.cwd(), {stdio: "inherit"}); + console.log(` ==> Installing extra packages: ${data.extra_pkgs.join(", ")}...`); + execIn(`npx --yes yarn add -O ${data.extra_pkgs.join(" ")}`, process.cwd(), { stdio: "inherit" }); - console.log('==> Building...') - execIn('npx --yes yarn run build', process.cwd(), {stdio: "inherit"}); + console.log("==> Building..."); + execIn("npx --yes yarn run build", process.cwd(), { stdio: "inherit" }); printTitle("Step 6: run your instance!"); console.log("Installation is complete!"); console.log("You can now start your instance by running 'npm run start:bundle'!"); diff --git a/src/Server.ts b/src/Server.ts index 4d5d6422..c94c3bc7 100644 --- a/src/Server.ts +++ b/src/Server.ts @@ -1,15 +1,15 @@ process.on("unhandledRejection", console.error); process.on("uncaughtException", console.error); -import http from "http"; import * as Api from "@fosscord/api"; -import * as Gateway from "@fosscord/gateway"; import { CDNServer } from "@fosscord/cdn"; -import express from "express"; -import { green, bold, yellow } from "picocolors"; +import * as Gateway from "@fosscord/gateway"; import { Config, getOrInitialiseDatabase } from "@fosscord/util"; import * as Sentry from "@sentry/node"; import * as Tracing from "@sentry/tracing"; +import express from "express"; +import http from "http"; +import { bold, green, yellow } from "picocolors"; // import { PluginLoader } from "@fosscord/util"; const app = express(); @@ -26,12 +26,12 @@ const cdn = new CDNServer({ server, port, production, app }); const gateway = new Gateway.Server({ server, port, production }); //this is what has been added for the /stop API route -process.on('SIGTERM', () => { - setTimeout(()=>process.exit(0), 3000) +process.on("SIGTERM", () => { + setTimeout(() => process.exit(0), 3000); server.close(() => { - console.log("Stop API has been successfully POSTed, SIGTERM sent") - }) -}) + console.log("Stop API has been successfully POSTed, SIGTERM sent"); + }); +}); //this is what has been added for the /stop API route async function main() { @@ -42,16 +42,15 @@ async function main() { await Config.set({ cdn: { endpointClient: "${location.host}", - endpointPrivate: `http://localhost:${port}`, + endpointPrivate: `http://localhost:${port}` }, gateway: { - endpointClient: - '${location.protocol === "https:" ? "wss://" : "ws://"}${location.host}', + endpointClient: '${location.protocol === "https:" ? "wss://" : "ws://"}${location.host}', endpointPrivate: `ws://localhost:${port}`, ...(!Config.get().gateway.endpointPublic && { - endpointPublic: `ws://localhost:${port}`, - }), - }, + endpointPublic: `ws://localhost:${port}` + }) + } // regions: { // default: "fosscord", // useDefaultAsOptimal: true, @@ -70,15 +69,10 @@ async function main() { //Sentry if (Config.get().sentry.enabled) { - console.log( - `[Bundle] ${yellow("You are using Sentry! This may slightly impact performance on large loads!")}` - ); + console.log(`[Bundle] ${yellow("You are using Sentry! This may slightly impact performance on large loads!")}`); Sentry.init({ dsn: Config.get().sentry.endpoint, - integrations: [ - new Sentry.Integrations.Http({ tracing: true }), - new Tracing.Integrations.Express({ app }), - ], + integrations: [new Sentry.Integrations.Http({ tracing: true }), new Tracing.Integrations.Express({ app })], tracesSampleRate: Config.get().sentry.traceSampleRate, environment: Config.get().sentry.environment }); diff --git a/src/api/Server.ts b/src/api/Server.ts index 136f9814..e92335a5 100644 --- a/src/api/Server.ts +++ b/src/api/Server.ts @@ -1,16 +1,16 @@ +import { Config, getOrInitialiseDatabase, initEvent, registerRoutes } from "@fosscord/util"; +import { NextFunction, Request, Response, Router } from "express"; import { Server, ServerOptions } from "lambert-server"; +import morgan from "morgan"; +import path from "path"; +import { red } from "picocolors"; import { Authentication, CORS } from "./middlewares/"; -import { Config, getOrInitialiseDatabase, initEvent, registerRoutes } from "@fosscord/util"; -import { ErrorHandler } from "./middlewares/ErrorHandler"; import { BodyParser } from "./middlewares/BodyParser"; -import { Router, Request, Response, NextFunction } from "express"; -import path from "path"; +import { ErrorHandler } from "./middlewares/ErrorHandler"; import { initRateLimits } from "./middlewares/RateLimit"; import TestClient from "./middlewares/TestClient"; import { initTranslation } from "./middlewares/Translation"; -import morgan from "morgan"; import { initInstance } from "./util/handlers/Instance"; -import { red } from "picocolors" export interface FosscordServerOptions extends ServerOptions {} @@ -85,8 +85,13 @@ export class FosscordServer extends Server { this.app.use(ErrorHandler); TestClient(this.app); - if (logRequests) console.log(red(`Warning: Request logging is enabled! This will spam your console!\nTo disable this, unset the 'LOG_REQUESTS' environment variable!`)); - + if (logRequests) + console.log( + red( + `Warning: Request logging is enabled! This will spam your console!\nTo disable this, unset the 'LOG_REQUESTS' environment variable!` + ) + ); + return super.start(); } -} \ No newline at end of file +} diff --git a/src/api/index.ts b/src/api/index.ts index adc7649c..5f97a463 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -1,3 +1,3 @@ -export * from "./Server"; export * from "./middlewares/"; +export * from "./Server"; export * from "./util/"; diff --git a/src/api/middlewares/Authentication.ts b/src/api/middlewares/Authentication.ts index 2d9ccf57..6d063953 100644 --- a/src/api/middlewares/Authentication.ts +++ b/src/api/middlewares/Authentication.ts @@ -1,6 +1,5 @@ +import { checkToken, Config, HTTPError, Rights } from "@fosscord/util"; import { NextFunction, Request, Response } from "express"; -import { HTTPError } from "@fosscord/util"; -import { checkToken, Config, Rights } from "@fosscord/util"; export const NO_AUTHORIZATION_ROUTES = [ // Authentication routes @@ -10,7 +9,7 @@ export const NO_AUTHORIZATION_ROUTES = [ "/auth/mfa/totp", // Routes with a seperate auth system "/webhooks/", - // Public information endpoints + // Public information endpoints "/ping", "/gateway", "/experiments", diff --git a/src/api/middlewares/BodyParser.ts b/src/api/middlewares/BodyParser.ts index 35db3c6f..36d89da7 100644 --- a/src/api/middlewares/BodyParser.ts +++ b/src/api/middlewares/BodyParser.ts @@ -1,6 +1,6 @@ +import { HTTPError } from "@fosscord/util"; import bodyParser, { OptionsJson } from "body-parser"; import { NextFunction, Request, Response } from "express"; -import { HTTPError } from "@fosscord/util"; export function BodyParser(opts?: OptionsJson) { const jsonParser = bodyParser.json(opts); diff --git a/src/api/middlewares/ErrorHandler.ts b/src/api/middlewares/ErrorHandler.ts index 8a046e06..813adc18 100644 --- a/src/api/middlewares/ErrorHandler.ts +++ b/src/api/middlewares/ErrorHandler.ts @@ -1,6 +1,5 @@ +import { ApiError, FieldError, HTTPError } from "@fosscord/util"; import { NextFunction, Request, Response } from "express"; -import { HTTPError } from "@fosscord/util"; -import { ApiError, FieldError } from "@fosscord/util"; const EntityNotFoundErrorRegex = /"(\w+)"/; export function ErrorHandler(error: Error, req: Request, res: Response, next: NextFunction) { diff --git a/src/api/middlewares/RateLimit.ts b/src/api/middlewares/RateLimit.ts index 47180b62..7754edf6 100644 --- a/src/api/middlewares/RateLimit.ts +++ b/src/api/middlewares/RateLimit.ts @@ -1,6 +1,6 @@ -import { Config, getRights, listenEvent, Rights } from "@fosscord/util"; -import { NextFunction, Request, Response, Router } from "express"; import { getIpAdress } from "@fosscord/api"; +import { Config, getRights, listenEvent } from "@fosscord/util"; +import { NextFunction, Request, Response, Router } from "express"; import { API_PREFIX_TRAILING_SLASH } from "./Authentication"; // Docs: https://discord.com/developers/docs/topics/rate-limits @@ -163,7 +163,7 @@ export async function initRateLimits(app: Router) { app.use("/auth/register", rateLimit({ onlyIp: true, success: true, ...routes.auth.register })); } -async function hitRoute(opts: { executor_id: string; bucket_id: string; max_hits: number; window: number; }) { +async function hitRoute(opts: { executor_id: string; bucket_id: string; max_hits: number; window: number }) { const id = opts.executor_id + opts.bucket_id; let limit = Cache.get(id); if (!limit) { diff --git a/src/api/middlewares/TestClient.ts b/src/api/middlewares/TestClient.ts index c8ea57f6..2c872068 100644 --- a/src/api/middlewares/TestClient.ts +++ b/src/api/middlewares/TestClient.ts @@ -1,17 +1,17 @@ -import express, { Request, Response, Application } from "express"; +import { Config } from "@fosscord/util"; +import express, { Application, Request, Response } from "express"; import fs from "fs"; +import fetch, { Headers, Response as FetchResponse } from "node-fetch"; import path from "path"; -import fetch, { Response as FetchResponse, Headers } from "node-fetch"; -import ProxyAgent from 'proxy-agent'; -import { Config } from "@fosscord/util"; -import { AssetCacheItem } from "../util/entities/AssetCacheItem" import { green } from "picocolors"; +import ProxyAgent from "proxy-agent"; +import { AssetCacheItem } from "../util/entities/AssetCacheItem"; -const AssetsPath = path.join(__dirname, "..", "..", "..", "assets") +const AssetsPath = path.join(__dirname, "..", "..", "..", "assets"); export default function TestClient(app: Application) { const agent = new ProxyAgent(); - + //build client page let html = fs.readFileSync(path.join(AssetsPath, "index.html"), { encoding: "utf8" }); html = applyEnv(html); @@ -22,31 +22,29 @@ export default function TestClient(app: Application) { //load asset cache let newAssetCache: Map<string, AssetCacheItem> = new Map<string, AssetCacheItem>(); let assetCacheDir = path.join(AssetsPath, "cache"); - if(process.env.ASSET_CACHE_DIR) - assetCacheDir = process.env.ASSET_CACHE_DIR + if (process.env.ASSET_CACHE_DIR) assetCacheDir = process.env.ASSET_CACHE_DIR; - console.log(`[TestClient] ${green(`Using asset cache path: ${assetCacheDir}`)}`) - if(!fs.existsSync(assetCacheDir)) { + console.log(`[TestClient] ${green(`Using asset cache path: ${assetCacheDir}`)}`); + if (!fs.existsSync(assetCacheDir)) { fs.mkdirSync(assetCacheDir); } - if(fs.existsSync(path.join(assetCacheDir, "index.json"))) { + if (fs.existsSync(path.join(assetCacheDir, "index.json"))) { let rawdata = fs.readFileSync(path.join(assetCacheDir, "index.json")); newAssetCache = new Map<string, AssetCacheItem>(Object.entries(JSON.parse(rawdata.toString()))); } - app.use("/assets", express.static(path.join(AssetsPath))); + app.use("/assets", express.static(path.join(AssetsPath))); app.get("/assets/:file", async (req: Request, res: Response) => { delete req.headers.host; let response: FetchResponse; let buffer: Buffer; let assetCacheItem: AssetCacheItem = new AssetCacheItem(req.params.file); - if(newAssetCache.has(req.params.file)){ + if (newAssetCache.has(req.params.file)) { assetCacheItem = newAssetCache.get(req.params.file)!; assetCacheItem.Headers.forEach((value: any, name: any) => { res.set(name, value); }); - } - else { + } else { console.log(`[TestClient] Downloading file not yet cached! Asset file: ${req.params.file}`); response = await fetch(`https://discord.com/assets/${req.params.file}`, { agent, @@ -55,7 +53,7 @@ export default function TestClient(app: Application) { ...req.headers } }); - + //set cache info assetCacheItem.Headers = Object.fromEntries(stripHeaders(response.headers)); assetCacheItem.FilePath = path.join(assetCacheDir, req.params.file); @@ -66,7 +64,7 @@ export default function TestClient(app: Application) { //download file fs.writeFileSync(assetCacheItem.FilePath, await response.buffer()); } - + assetCacheItem.Headers.forEach((value: string, name: string) => { res.set(name, value); }); @@ -77,8 +75,8 @@ export default function TestClient(app: Application) { res.set("Cache-Control", "public, max-age=" + 60 * 60 * 24); res.set("content-type", "text/html"); - if(!useTestClient) return res.send("Test client is disabled on this instance. Use a stand-alone client to connect this instance.") - + if (!useTestClient) return res.send("Test client is disabled on this instance. Use a stand-alone client to connect this instance."); + res.send(fs.readFileSync(path.join(__dirname, "..", "..", "..", "assets", "developers.html"), { encoding: "utf8" })); }); app.get("*", (req: Request, res: Response) => { @@ -86,15 +84,13 @@ export default function TestClient(app: Application) { res.set("Cache-Control", "public, max-age=" + 60 * 60 * 24); res.set("content-type", "text/html"); - if(req.url.startsWith("/api") || req.url.startsWith("/__development")) return; + if (req.url.startsWith("/api") || req.url.startsWith("/__development")) return; - if(!useTestClient) return res.send("Test client is disabled on this instance. Use a stand-alone client to connect this instance.") + if (!useTestClient) return res.send("Test client is disabled on this instance. Use a stand-alone client to connect this instance."); if (req.url.startsWith("/invite")) return res.send(html.replace("9b2b7f0632acd0c5e781", "9f24f709a3de09b67c49")); - + res.send(html); }); - - } function applyEnv(html: string): string { @@ -117,23 +113,29 @@ function applyPlugins(html: string): string { // plugins let files = fs.readdirSync(path.join(AssetsPath, "plugins")); let plugins = ""; - files.forEach(x =>{if(x.endsWith(".js")) plugins += `<script src='/assets/plugins/${x}'></script>\n`; }); + files.forEach((x) => { + if (x.endsWith(".js")) plugins += `<script src='/assets/plugins/${x}'></script>\n`; + }); return html.replaceAll("<!-- plugin marker -->", plugins); } -function applyInlinePlugins(html: string): string{ +function applyInlinePlugins(html: string): string { // inline plugins let files = fs.readdirSync(path.join(AssetsPath, "inline-plugins")); let plugins = ""; - files.forEach(x =>{if(x.endsWith(".js")) plugins += `<script src='/assets/inline-plugins/${x}'></script>\n\n`; }); + files.forEach((x) => { + if (x.endsWith(".js")) plugins += `<script src='/assets/inline-plugins/${x}'></script>\n\n`; + }); return html.replaceAll("<!-- inline plugin marker -->", plugins); } -function applyPreloadPlugins(html: string): string{ +function applyPreloadPlugins(html: string): string { //preload plugins let files = fs.readdirSync(path.join(AssetsPath, "preload-plugins")); let plugins = ""; - files.forEach(x =>{if(x.endsWith(".js")) plugins += `<script>${fs.readFileSync(path.join(AssetsPath, "preload-plugins", x))}</script>\n`; }); + files.forEach((x) => { + if (x.endsWith(".js")) plugins += `<script>${fs.readFileSync(path.join(AssetsPath, "preload-plugins", x))}</script>\n`; + }); return html.replaceAll("<!-- preload plugin marker -->", plugins); } @@ -147,7 +149,7 @@ function stripHeaders(headers: Headers): Headers { "expect-ct", "access-control-allow-origin", "content-encoding" - ].forEach(headerName => { + ].forEach((headerName) => { headers.delete(headerName); }); return headers; diff --git a/src/api/middlewares/Translation.ts b/src/api/middlewares/Translation.ts index 64b03bf8..8e5e67e6 100644 --- a/src/api/middlewares/Translation.ts +++ b/src/api/middlewares/Translation.ts @@ -1,9 +1,9 @@ +import { Router } from "express"; import fs from "fs"; -import path from "path"; import i18next from "i18next"; import i18nextMiddleware from "i18next-http-middleware"; import i18nextBackend from "i18next-node-fs-backend"; -import { Router } from "express"; +import path from "path"; export async function initTranslation(router: Router) { const languages = fs.readdirSync(path.join(__dirname, "..", "..", "..", "assets", "locales")); diff --git a/src/api/routes/-/healthz.ts b/src/api/routes/-/healthz.ts index f7bcfebf..5dee9e86 100644 --- a/src/api/routes/-/healthz.ts +++ b/src/api/routes/-/healthz.ts @@ -1,5 +1,5 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; import { getConnection } from "typeorm"; const router = Router(); diff --git a/src/api/routes/-/readyz.ts b/src/api/routes/-/readyz.ts index f7bcfebf..5dee9e86 100644 --- a/src/api/routes/-/readyz.ts +++ b/src/api/routes/-/readyz.ts @@ -1,5 +1,5 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; import { getConnection } from "typeorm"; const router = Router(); diff --git a/src/api/routes/applications/#id/bot/index.ts b/src/api/routes/applications/#id/bot/index.ts index 5cae5215..e663059e 100644 --- a/src/api/routes/applications/#id/bot/index.ts +++ b/src/api/routes/applications/#id/bot/index.ts @@ -1,14 +1,14 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; -import { Application, Config, FieldErrors, generateToken, OrmUtils, Snowflake, trimSpecial, User, handleFile } from "@fosscord/util"; +import { Application, Config, FieldErrors, generateToken, handleFile, OrmUtils, trimSpecial, User } from "@fosscord/util"; +import { Request, Response, Router } from "express"; import { HTTPError } from "lambert-server"; import { verifyToken } from "node-2fa"; const router: Router = Router(); router.post("/", route({}), async (req: Request, res: Response) => { - const app = await Application.findOne({where: {id: req.params.id}}); - if(!app) return res.status(404); + const app = await Application.findOne({ where: { id: req.params.id } }); + if (!app) return res.status(404); const username = trimSpecial(app.name); const discriminator = await User.generateDiscriminator(username); if (!discriminator) { @@ -16,8 +16,8 @@ router.post("/", route({}), async (req: Request, res: Response) => { throw FieldErrors({ username: { code: "USERNAME_TOO_MANY_USERS", - message: req?.t("auth:register.USERNAME_TOO_MANY_USERS"), - }, + message: req?.t("auth:register.USERNAME_TOO_MANY_USERS") + } }); } @@ -47,37 +47,37 @@ router.post("/", route({}), async (req: Request, res: Response) => { flags: "0", data: { hash: null, - valid_tokens_since: new Date(), + valid_tokens_since: new Date() }, settings: {}, extended_settings: {}, fingerprints: [], - notes: {}, + notes: {} }); await user.save(); app.bot = user; await app.save(); - res.send().status(204) + res.send().status(204); }); router.post("/reset", route({}), async (req: Request, res: Response) => { - let bot = await User.findOne({where: {id: req.params.id}}); - let owner = await User.findOne({where: {id: req.user_id}}); - if(!bot) return res.status(404); - if(owner?.totp_secret && (!req.body.code || verifyToken(owner.totp_secret, req.body.code))) { + let bot = await User.findOne({ where: { id: req.params.id } }); + let owner = await User.findOne({ where: { id: req.user_id } }); + if (!bot) return res.status(404); + if (owner?.totp_secret && (!req.body.code || verifyToken(owner.totp_secret, req.body.code))) { throw new HTTPError(req.t("auth:login.INVALID_TOTP_CODE"), 60008); } bot.data = { hash: undefined, valid_tokens_since: new Date() }; await bot.save(); let token = await generateToken(bot.id); - res.json({token}).status(200); + res.json({ token }).status(200); }); router.patch("/", route({}), async (req: Request, res: Response) => { if (req.body.avatar) req.body.avatar = await handleFile(`/avatars/${req.params.id}`, req.body.avatar as string); - let app = OrmUtils.mergeDeep(await User.findOne({where: {id: req.params.id}}), req.body); + let app = OrmUtils.mergeDeep(await User.findOne({ where: { id: req.params.id } }), req.body); await app.save(); res.json(app).status(200); }); -export default router; \ No newline at end of file +export default router; diff --git a/src/api/routes/applications/#id/entitlements.ts b/src/api/routes/applications/#id/entitlements.ts index cfcfe40f..26054eb0 100644 --- a/src/api/routes/applications/#id/entitlements.ts +++ b/src/api/routes/applications/#id/entitlements.ts @@ -1,5 +1,5 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/applications/#id/index.ts b/src/api/routes/applications/#id/index.ts index 0aced582..398227fd 100644 --- a/src/api/routes/applications/#id/index.ts +++ b/src/api/routes/applications/#id/index.ts @@ -1,22 +1,22 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; -import { Application, OrmUtils, Team, trimSpecial, User } from "@fosscord/util"; +import { Application, OrmUtils } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); router.get("/", route({}), async (req: Request, res: Response) => { - let results = await Application.findOne({where: {id: req.params.id}, relations: ["owner", "bot"] }); + let results = await Application.findOne({ where: { id: req.params.id }, relations: ["owner", "bot"] }); res.json(results).status(200); }); router.patch("/", route({}), async (req: Request, res: Response) => { delete req.body.icon; - let app = OrmUtils.mergeDeep(await Application.findOne({where: {id: req.params.id}, relations: ["owner", "bot"]}), req.body); - if(app.bot) { - app.bot.bio = req.body.description + let app = OrmUtils.mergeDeep(await Application.findOne({ where: { id: req.params.id }, relations: ["owner", "bot"] }), req.body); + if (app.bot) { + app.bot.bio = req.body.description; app.bot?.save(); } - if(req.body.tags) app.tags = req.body.tags; + if (req.body.tags) app.tags = req.body.tags; await app.save(); res.json(app).status(200); }); @@ -26,5 +26,4 @@ router.post("/delete", route({}), async (req: Request, res: Response) => { res.send().status(200); }); - -export default router; \ No newline at end of file +export default router; diff --git a/src/api/routes/applications/#id/skus.ts b/src/api/routes/applications/#id/skus.ts index 5b667f36..df7ad4bb 100644 --- a/src/api/routes/applications/#id/skus.ts +++ b/src/api/routes/applications/#id/skus.ts @@ -1,6 +1,5 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; -import { Application, OrmUtils, Team, trimSpecial, User } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); @@ -8,4 +7,4 @@ router.get("/", route({}), async (req: Request, res: Response) => { res.json([]).status(200); }); -export default router; \ No newline at end of file +export default router; diff --git a/src/api/routes/applications/detectable.ts b/src/api/routes/applications/detectable.ts index 28ce42da..f012a595 100644 --- a/src/api/routes/applications/detectable.ts +++ b/src/api/routes/applications/detectable.ts @@ -1,5 +1,5 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/applications/index.ts b/src/api/routes/applications/index.ts index 033dcc51..191833f2 100644 --- a/src/api/routes/applications/index.ts +++ b/src/api/routes/applications/index.ts @@ -1,6 +1,6 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; -import { Application, OrmUtils, Team, trimSpecial, User } from "@fosscord/util"; +import { Application, OrmUtils, trimSpecial, User } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); @@ -11,14 +11,14 @@ export interface ApplicationCreateSchema { router.get("/", route({}), async (req: Request, res: Response) => { //TODO - let results = await Application.find({where: {owner: {id: req.user_id}}, relations: ["owner", "bot"] }); + let results = await Application.find({ where: { owner: { id: req.user_id } }, relations: ["owner", "bot"] }); res.json(results).status(200); }); router.post("/", route({}), async (req: Request, res: Response) => { const body = req.body as ApplicationCreateSchema; - const user = await User.findOne({where: {id: req.user_id}}) - if(!user) res.status(420); + const user = await User.findOne({ where: { id: req.user_id } }); + if (!user) res.status(420); let app = OrmUtils.mergeDeep(new Application(), { name: trimSpecial(body.name), description: "", @@ -31,4 +31,4 @@ router.post("/", route({}), async (req: Request, res: Response) => { res.json(app).status(200); }); -export default router; \ No newline at end of file +export default router; diff --git a/src/api/routes/auth/location-metadata.ts b/src/api/routes/auth/location-metadata.ts index f4c2bd16..b8caf579 100644 --- a/src/api/routes/auth/location-metadata.ts +++ b/src/api/routes/auth/location-metadata.ts @@ -1,13 +1,12 @@ -import { Router, Request, Response } from "express"; -import { route } from "@fosscord/api"; -import { getIpAdress, IPAnalysis } from "@fosscord/api"; +import { getIpAdress, IPAnalysis, route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); -router.get("/",route({}), async (req: Request, res: Response) => { - //TODO - //Note: It's most likely related to legal. At the moment Discord hasn't finished this too - const country_code = (await IPAnalysis(getIpAdress(req))).country_code; - res.json({ consent_required: false, country_code: country_code, promotional_email_opt_in: { required: true, pre_checked: false}}); +router.get("/", route({}), async (req: Request, res: Response) => { + //TODO + //Note: It's most likely related to legal. At the moment Discord hasn't finished this too + const country_code = (await IPAnalysis(getIpAdress(req))).country_code; + res.json({ consent_required: false, country_code: country_code, promotional_email_opt_in: { required: true, pre_checked: false } }); }); export default router; diff --git a/src/api/routes/auth/login.ts b/src/api/routes/auth/login.ts index 0fcd43de..5923708c 100644 --- a/src/api/routes/auth/login.ts +++ b/src/api/routes/auth/login.ts @@ -1,7 +1,7 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; import { adjustEmail, Config, FieldErrors, generateToken, LoginSchema, User } from "@fosscord/util"; import crypto from "crypto"; +import { Request, Response, Router } from "express"; let bcrypt: any; try { @@ -64,9 +64,9 @@ router.post("/", route({ body: "LoginSchema" }), async (req: Request, res: Respo return res.json({ ticket: ticket, mfa: true, - sms: false, // TODO - token: null, - }) + sms: false, // TODO + token: null + }); } const token = await generateToken(user.id); diff --git a/src/api/routes/auth/mfa/totp.ts b/src/api/routes/auth/mfa/totp.ts index 421dbafa..9938569e 100644 --- a/src/api/routes/auth/mfa/totp.ts +++ b/src/api/routes/auth/mfa/totp.ts @@ -1,8 +1,8 @@ -import { Router, Request, Response } from "express"; import { route } from "@fosscord/api"; -import { BackupCode, FieldErrors, generateToken, TotpSchema, User } from "@fosscord/util"; -import { verifyToken } from "node-2fa"; +import { BackupCode, generateToken, TotpSchema, User } from "@fosscord/util"; +import { Request, Response, Router } from "express"; import { HTTPError } from "lambert-server"; +import { verifyToken } from "node-2fa"; const router = Router(); router.post("/", route({ body: "TotpSchema" }), async (req: Request, res: Response) => { @@ -10,23 +10,17 @@ router.post("/", route({ body: "TotpSchema" }), async (req: Request, res: Respon const user = await User.findOneOrFail({ where: { - totp_last_ticket: ticket, + totp_last_ticket: ticket }, - select: [ - "id", - "totp_secret", - "settings", - ], + select: ["id", "totp_secret", "settings"] }); const backup = await BackupCode.findOne({ where: { code: code, expired: false, consumed: false, user: { id: user.id } } }); if (!backup) { const ret = verifyToken(user.totp_secret!, code); - if (!ret || ret.delta != 0) - throw new HTTPError(req.t("auth:login.INVALID_TOTP_CODE"), 60008); - } - else { + if (!ret || ret.delta != 0) throw new HTTPError(req.t("auth:login.INVALID_TOTP_CODE"), 60008); + } else { backup.consumed = true; await backup.save(); } @@ -35,7 +29,7 @@ router.post("/", route({ body: "TotpSchema" }), async (req: Request, res: Respon return res.json({ token: await generateToken(user.id), - user_settings: user.settings, + user_settings: user.settings }); }); diff --git a/src/api/routes/channels/#channel_id/followers.ts b/src/api/routes/channels/#channel_id/followers.ts index 641af4f8..c06db61b 100644 --- a/src/api/routes/channels/#channel_id/followers.ts +++ b/src/api/routes/channels/#channel_id/followers.ts @@ -1,4 +1,4 @@ -import { Router, Response, Request } from "express"; +import { Router } from "express"; const router: Router = Router(); // TODO: diff --git a/src/api/routes/channels/#channel_id/index.ts b/src/api/routes/channels/#channel_id/index.ts index bb8b868b..a65cf451 100644 --- a/src/api/routes/channels/#channel_id/index.ts +++ b/src/api/routes/channels/#channel_id/index.ts @@ -1,17 +1,16 @@ +import { route } from "@fosscord/api"; import { Channel, ChannelDeleteEvent, - ChannelPermissionOverwriteType, + ChannelModifySchema, ChannelType, ChannelUpdateEvent, emitEvent, - Recipient, handleFile, - ChannelModifySchema + OrmUtils, + Recipient } from "@fosscord/util"; import { Request, Response, Router } from "express"; -import { route } from "@fosscord/api"; -import { OrmUtils } from "@fosscord/util"; const router: Router = Router(); // TODO: delete channel diff --git a/src/api/routes/channels/#channel_id/invites.ts b/src/api/routes/channels/#channel_id/invites.ts index b5c65c0d..3a1d2666 100644 --- a/src/api/routes/channels/#channel_id/invites.ts +++ b/src/api/routes/channels/#channel_id/invites.ts @@ -1,45 +1,45 @@ -import { Router, Request, Response } from "express"; -import { HTTPError } from "@fosscord/util"; import { route } from "@fosscord/api"; -import { random } from "@fosscord/api"; -import { Channel, Invite, InviteCreateEvent, emitEvent, User, Guild, PublicInviteRelation } from "@fosscord/util"; +import { Channel, emitEvent, Guild, HTTPError, Invite, InviteCreateEvent, OrmUtils, PublicInviteRelation, User } from "@fosscord/util"; +import { Request, Response, Router } from "express"; import { isTextChannel } from "./messages"; -import { OrmUtils } from "@fosscord/util"; const router: Router = Router(); -router.post("/", route({ body: "InviteCreateSchema", permission: "CREATE_INSTANT_INVITE", right: "CREATE_INVITES" }), - async (req: Request, res: Response) => { - const { user_id } = req; - const { channel_id } = req.params; - const channel = await Channel.findOneOrFail({ where: { id: channel_id }, select: ["id", "name", "type", "guild_id"] }); - isTextChannel(channel.type); - - if (!channel.guild_id) { - throw new HTTPError("This channel doesn't exist", 404); +router.post( + "/", + route({ body: "InviteCreateSchema", permission: "CREATE_INSTANT_INVITE", right: "CREATE_INVITES" }), + async (req: Request, res: Response) => { + const { user_id } = req; + const { channel_id } = req.params; + const channel = await Channel.findOneOrFail({ where: { id: channel_id }, select: ["id", "name", "type", "guild_id"] }); + isTextChannel(channel.type); + + if (!channel.guild_id) { + throw new HTTPError("This channel doesn't exist", 404); + } + const { guild_id } = channel; + + const expires_at = new Date(req.body.max_age * 1000 + Date.now()); + + const invite = await OrmUtils.mergeDeep(new Invite(), { + temporary: req.body.temporary || true, + max_uses: req.body.max_uses, + max_age: req.body.max_age, + expires_at, + guild_id, + channel_id, + inviter_id: user_id + }).save(); + //TODO: check this, removed toJSON call + const data = JSON.parse(JSON.stringify(invite)); + data.inviter = await User.getPublicUser(req.user_id); + data.guild = await Guild.findOne({ where: { id: guild_id } }); + data.channel = channel; + + await emitEvent({ event: "INVITE_CREATE", data, guild_id } as InviteCreateEvent); + res.status(201).send(data); } - const { guild_id } = channel; - - const expires_at = new Date(req.body.max_age * 1000 + Date.now()); - - const invite = await OrmUtils.mergeDeep(new Invite(),{ - temporary: req.body.temporary || true, - max_uses: req.body.max_uses, - max_age: req.body.max_age, - expires_at, - guild_id, - channel_id, - inviter_id: user_id - }).save(); - //TODO: check this, removed toJSON call - const data = JSON.parse(JSON.stringify(invite)); - data.inviter = await User.getPublicUser(req.user_id); - data.guild = await Guild.findOne({ where: { id: guild_id } }); - data.channel = channel; - - await emitEvent({ event: "INVITE_CREATE", data, guild_id } as InviteCreateEvent); - res.status(201).send(data); -}); +); router.get("/", route({ permission: "MANAGE_CHANNELS" }), async (req: Request, res: Response) => { const { channel_id } = req.params; diff --git a/src/api/routes/channels/#channel_id/messages/#message_id/ack.ts b/src/api/routes/channels/#channel_id/messages/#message_id/ack.ts index 041f4d5e..5ebeed49 100644 --- a/src/api/routes/channels/#channel_id/messages/#message_id/ack.ts +++ b/src/api/routes/channels/#channel_id/messages/#message_id/ack.ts @@ -1,7 +1,6 @@ -import { emitEvent, getPermission, MessageAckEvent, ReadState, Snowflake } from "@fosscord/util"; -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; -import { OrmUtils } from "@fosscord/util"; +import { emitEvent, getPermission, MessageAckEvent, OrmUtils, ReadState } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/channels/#channel_id/messages/#message_id/crosspost.ts b/src/api/routes/channels/#channel_id/messages/#message_id/crosspost.ts index b2cb6763..fbbc65f0 100644 --- a/src/api/routes/channels/#channel_id/messages/#message_id/crosspost.ts +++ b/src/api/routes/channels/#channel_id/messages/#message_id/crosspost.ts @@ -1,5 +1,5 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/channels/#channel_id/messages/#message_id/index.ts b/src/api/routes/channels/#channel_id/messages/#message_id/index.ts index d7e27062..b082e083 100644 --- a/src/api/routes/channels/#channel_id/messages/#message_id/index.ts +++ b/src/api/routes/channels/#channel_id/messages/#message_id/index.ts @@ -1,25 +1,22 @@ +import { handleMessage, postHandleMessage, route } from "@fosscord/api"; import { Attachment, Channel, - Embed, - DiscordApiErrors, emitEvent, FosscordApiErrors, getPermission, getRights, - Message, + HTTPError, + Message, MessageCreateEvent, + MessageCreateSchema, MessageDeleteEvent, MessageUpdateEvent, Snowflake, - uploadFile, - MessageCreateSchema + uploadFile } from "@fosscord/util"; -import { Router, Response, Request } from "express"; +import { Request, Response, Router } from "express"; import multer from "multer"; -import { route } from "@fosscord/api"; -import { handleMessage, postHandleMessage } from "@fosscord/api"; -import { HTTPError } from "@fosscord/util"; const router = Router(); // TODO: message content/embed string length limit @@ -33,50 +30,53 @@ const messageUpload = multer({ storage: multer.memoryStorage() }); // max upload 50 mb -router.patch("/", route({ body: "MessageCreateSchema", permission: "SEND_MESSAGES", right: "SEND_MESSAGES" }), async (req: Request, res: Response) => { - const { message_id, channel_id } = req.params; - let body = req.body as MessageCreateSchema; +router.patch( + "/", + route({ body: "MessageCreateSchema", permission: "SEND_MESSAGES", right: "SEND_MESSAGES" }), + async (req: Request, res: Response) => { + const { message_id, channel_id } = req.params; + let body = req.body as MessageCreateSchema; - const message = await Message.findOneOrFail({ where: { id: message_id, channel_id }, relations: ["attachments"] }); + const message = await Message.findOneOrFail({ where: { id: message_id, channel_id }, relations: ["attachments"] }); - const permissions = await getPermission(req.user_id, undefined, channel_id); - - const rights = await getRights(req.user_id); + const permissions = await getPermission(req.user_id, undefined, channel_id); - if ((req.user_id !== message.author_id)) { - if (!rights.has("MANAGE_MESSAGES")) { - permissions.hasThrow("MANAGE_MESSAGES"); - body = { flags: body.flags }; -// guild admins can only suppress embeds of other messages, no such restriction imposed to instance-wide admins - } - } else rights.hasThrow("SELF_EDIT_MESSAGES"); - - const new_message = await handleMessage({ - ...message, - // TODO: should message_reference be overridable? - // @ts-ignore - message_reference: message.message_reference, - ...body, - author_id: message.author_id, - channel_id, - id: message_id, - edited_timestamp: new Date() - }); - - await Promise.all([ - new_message!.save(), - await emitEvent({ - event: "MESSAGE_UPDATE", + const rights = await getRights(req.user_id); + + if (req.user_id !== message.author_id) { + if (!rights.has("MANAGE_MESSAGES")) { + permissions.hasThrow("MANAGE_MESSAGES"); + body = { flags: body.flags }; + // guild admins can only suppress embeds of other messages, no such restriction imposed to instance-wide admins + } + } else rights.hasThrow("SELF_EDIT_MESSAGES"); + + const new_message = await handleMessage({ + ...message, + // TODO: should message_reference be overridable? + // @ts-ignore + message_reference: message.message_reference, + ...body, + author_id: message.author_id, channel_id, - data: { ...new_message, nonce: undefined } - } as MessageUpdateEvent) - ]); + id: message_id, + edited_timestamp: new Date() + }); - postHandleMessage(message); + await Promise.all([ + new_message!.save(), + await emitEvent({ + event: "MESSAGE_UPDATE", + channel_id, + data: { ...new_message, nonce: undefined } + } as MessageUpdateEvent) + ]); - return res.json(message); -}); + postHandleMessage(message); + return res.json(message); + } +); // Backfill message with specific timestamp router.put( @@ -94,7 +94,7 @@ router.put( const { channel_id, message_id } = req.params; let body = req.body as MessageCreateSchema; const attachments: Attachment[] = []; - + const rights = await getRights(req.user_id); rights.hasThrow("SEND_MESSAGES"); @@ -103,13 +103,13 @@ router.put( throw new HTTPError("Message IDs must be positive integers", 400); } - const snowflake = Snowflake.deconstruct(message_id) + const snowflake = Snowflake.deconstruct(message_id); if (Date.now() < snowflake.timestamp) { // message is in the future throw FosscordApiErrors.CANNOT_BACKFILL_TO_THE_FUTURE; } - const exists = await Message.findOne({ where: { id: message_id, channel_id: channel_id }}); + const exists = await Message.findOne({ where: { id: message_id, channel_id: channel_id } }); if (exists) { throw FosscordApiErrors.CANNOT_REPLACE_BY_BACKFILL; } @@ -136,19 +136,19 @@ router.put( channel_id, attachments, edited_timestamp: undefined, - timestamp: new Date(snowflake.timestamp), + timestamp: new Date(snowflake.timestamp) }); //Fix for the client bug - delete message.member - + delete message.member; + await Promise.all([ message.save(), emitEvent({ event: "MESSAGE_CREATE", channel_id: channel_id, data: message } as MessageCreateEvent), channel.save() ]); - postHandleMessage(message).catch((e) => { }); // no await as it shouldnt block the message send function and silently catch error + postHandleMessage(message).catch((e) => {}); // no await as it shouldnt block the message send function and silently catch error return res.json(message); } @@ -160,7 +160,7 @@ router.get("/", route({ permission: "VIEW_CHANNEL" }), async (req: Request, res: const message = await Message.findOneOrFail({ where: { id: message_id, channel_id }, relations: ["attachments"] }); const permissions = await getPermission(req.user_id, undefined, channel_id); - + if (message.author_id !== req.user_id) permissions.hasThrow("READ_MESSAGE_HISTORY"); return res.json(message); @@ -171,10 +171,10 @@ router.delete("/", route({}), async (req: Request, res: Response) => { const channel = await Channel.findOneOrFail({ where: { id: channel_id } }); const message = await Message.findOneOrFail({ where: { id: message_id } }); - + const rights = await getRights(req.user_id); - if ((message.author_id !== req.user_id)) { + if (message.author_id !== req.user_id) { if (!rights.has("MANAGE_MESSAGES")) { const permission = await getPermission(req.user_id, channel.guild_id, channel_id); permission.hasThrow("MANAGE_MESSAGES"); diff --git a/src/api/routes/channels/#channel_id/messages/#message_id/reactions.ts b/src/api/routes/channels/#channel_id/messages/#message_id/reactions.ts index d0ab35bb..44de5c45 100644 --- a/src/api/routes/channels/#channel_id/messages/#message_id/reactions.ts +++ b/src/api/routes/channels/#channel_id/messages/#message_id/reactions.ts @@ -1,8 +1,10 @@ +import { route } from "@fosscord/api"; import { Channel, emitEvent, Emoji, getPermission, + HTTPError, Member, Message, MessageReactionAddEvent, @@ -13,9 +15,7 @@ import { PublicUserProjection, User } from "@fosscord/util"; -import { route } from "@fosscord/api"; -import { Router, Response, Request } from "express"; -import { HTTPError } from "@fosscord/util"; +import { Request, Response, Router } from "express"; import { In } from "typeorm"; const router = Router(); @@ -101,48 +101,52 @@ router.get("/:emoji", route({ permission: "VIEW_CHANNEL" }), async (req: Request res.json(users); }); -router.put("/:emoji/:user_id", route({ permission: "READ_MESSAGE_HISTORY", right: "SELF_ADD_REACTIONS" }), async (req: Request, res: Response) => { - const { message_id, channel_id, user_id } = req.params; - if (user_id !== "@me") throw new HTTPError("Invalid user"); - const emoji = getEmoji(req.params.emoji); - - const channel = await Channel.findOneOrFail({ where: { id: channel_id } }); - const message = await Message.findOneOrFail({ where: { id: message_id, channel_id } }); - const already_added = message.reactions.find((x) => (x.emoji.id === emoji.id && emoji.id) || x.emoji.name === emoji.name); - - if (!already_added) req.permission!.hasThrow("ADD_REACTIONS"); - - if (emoji.id) { - const external_emoji = await Emoji.findOneOrFail({ where: { id: emoji.id } }); - if (!already_added) req.permission!.hasThrow("USE_EXTERNAL_EMOJIS"); - emoji.animated = external_emoji.animated; - emoji.name = external_emoji.name; - } +router.put( + "/:emoji/:user_id", + route({ permission: "READ_MESSAGE_HISTORY", right: "SELF_ADD_REACTIONS" }), + async (req: Request, res: Response) => { + const { message_id, channel_id, user_id } = req.params; + if (user_id !== "@me") throw new HTTPError("Invalid user"); + const emoji = getEmoji(req.params.emoji); + + const channel = await Channel.findOneOrFail({ where: { id: channel_id } }); + const message = await Message.findOneOrFail({ where: { id: message_id, channel_id } }); + const already_added = message.reactions.find((x) => (x.emoji.id === emoji.id && emoji.id) || x.emoji.name === emoji.name); + + if (!already_added) req.permission!.hasThrow("ADD_REACTIONS"); + + if (emoji.id) { + const external_emoji = await Emoji.findOneOrFail({ where: { id: emoji.id } }); + if (!already_added) req.permission!.hasThrow("USE_EXTERNAL_EMOJIS"); + emoji.animated = external_emoji.animated; + emoji.name = external_emoji.name; + } - if (already_added) { - if (already_added.user_ids.includes(req.user_id)) return res.sendStatus(204); // Do not throw an error ¯\_(ツ)_/¯ as discord also doesn't throw any error - already_added.count++; - } else message.reactions.push({ count: 1, emoji, user_ids: [req.user_id] }); + if (already_added) { + if (already_added.user_ids.includes(req.user_id)) return res.sendStatus(204); // Do not throw an error ¯\_(ツ)_/¯ as discord also doesn't throw any error + already_added.count++; + } else message.reactions.push({ count: 1, emoji, user_ids: [req.user_id] }); - await message.save(); + await message.save(); - const member = channel.guild_id && (await Member.findOneOrFail({ where: { id: req.user_id } })); + const member = channel.guild_id && (await Member.findOneOrFail({ where: { id: req.user_id } })); - await emitEvent({ - event: "MESSAGE_REACTION_ADD", - channel_id, - data: { - user_id: req.user_id, + await emitEvent({ + event: "MESSAGE_REACTION_ADD", channel_id, - message_id, - guild_id: channel.guild_id, - emoji, - member - } - } as MessageReactionAddEvent); + data: { + user_id: req.user_id, + channel_id, + message_id, + guild_id: channel.guild_id, + emoji, + member + } + } as MessageReactionAddEvent); - res.sendStatus(204); -}); + res.sendStatus(204); + } +); router.delete("/:emoji/:user_id", route({}), async (req: Request, res: Response) => { let { message_id, channel_id, user_id } = req.params; diff --git a/src/api/routes/channels/#channel_id/messages/bulk-delete.ts b/src/api/routes/channels/#channel_id/messages/bulk-delete.ts index af44b522..561a40c0 100644 --- a/src/api/routes/channels/#channel_id/messages/bulk-delete.ts +++ b/src/api/routes/channels/#channel_id/messages/bulk-delete.ts @@ -1,7 +1,6 @@ -import { Router, Response, Request } from "express"; -import { Channel, Config, emitEvent, getPermission, getRights, MessageDeleteBulkEvent, Message } from "@fosscord/util"; -import { HTTPError } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { Channel, Config, emitEvent, getPermission, getRights, HTTPError, Message, MessageDeleteBulkEvent } from "@fosscord/util"; +import { Request, Response, Router } from "express"; import { In } from "typeorm"; const router: Router = Router(); @@ -13,7 +12,7 @@ export default router; // https://discord.com/developers/docs/resources/channel#bulk-delete-messages router.post("/", route({ body: "BulkDeleteSchema" }), async (req: Request, res: Response) => { const { channel_id } = req.params; - const channel = await Channel.findOneOrFail({where:{ id: channel_id} }); + const channel = await Channel.findOneOrFail({ where: { id: channel_id } }); if (!channel.guild_id) throw new HTTPError("Can't bulk delete dm channel messages", 400); const rights = await getRights(req.user_id); diff --git a/src/api/routes/channels/#channel_id/messages/index.ts b/src/api/routes/channels/#channel_id/messages/index.ts index 9ab0d97d..5fdcb6f9 100644 --- a/src/api/routes/channels/#channel_id/messages/index.ts +++ b/src/api/routes/channels/#channel_id/messages/index.ts @@ -1,4 +1,4 @@ -import { Router, Response, Request } from "express"; +import { handleMessage, postHandleMessage, route } from "@fosscord/api"; import { Attachment, Channel, @@ -7,16 +7,15 @@ import { DmChannelDTO, emitEvent, getPermission, - getRights, + HTTPError, + Member, Message, MessageCreateEvent, + MessageCreateSchema, Snowflake, - uploadFile, - Member, - MessageCreateSchema + uploadFile } from "@fosscord/util"; -import { HTTPError } from "@fosscord/util"; -import { handleMessage, postHandleMessage, route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; import multer from "multer"; import { FindManyOptions, LessThan, MoreThan } from "typeorm"; import { URL } from "url"; @@ -69,23 +68,20 @@ router.get("/", async (req: Request, res: Response) => { permissions.hasThrow("VIEW_CHANNEL"); if (!permissions.has("READ_MESSAGE_HISTORY")) return res.json([]); - let query: FindManyOptions<Message> & { where: { id?: any; }; } = { + let query: FindManyOptions<Message> & { where: { id?: any } } = { order: { id: "DESC" }, take: limit, where: { channel_id }, relations: ["author", "webhook", "application", "mentions", "mention_roles", "mention_channels", "sticker_items", "attachments"] }; - if (after) { if (after > new Snowflake()) return res.status(422); query.where.id = MoreThan(after); - } - else if (before) { + } else if (before) { if (before < req.params.channel_id) return res.status(422); query.where.id = LessThan(before); - } - else if (around) { + } else if (around) { query.where.id = [ MoreThan((BigInt(around) - BigInt(halfLimit)).toString()), LessThan((BigInt(around) + BigInt(halfLimit)).toString()) @@ -110,15 +106,14 @@ router.get("/", async (req: Request, res: Response) => { const uri = y.proxy_url.startsWith("http") ? y.proxy_url : `https://example.org${y.proxy_url}`; y.proxy_url = `${endpoint == null ? "" : endpoint}${new URL(uri).pathname}`; }); - + /** Some clients ( discord.js ) only check if a property exists within the response, which causes erorrs when, say, the `application` property is `null`. **/ - + for (let curr in x) { - if (x[curr] === null) - delete x[curr]; + if (x[curr] === null) delete x[curr]; } return x; @@ -130,7 +125,7 @@ router.get("/", async (req: Request, res: Response) => { const messageUpload = multer({ limits: { fileSize: 1024 * 1024 * 100, - fields: 10, + fields: 10 // files: 1 }, storage: multer.memoryStorage() @@ -162,16 +157,15 @@ router.post( const channel = await Channel.findOneOrFail({ where: { id: channel_id }, relations: ["recipients", "recipients.user"] }); if (!channel.isWritable()) { - throw new HTTPError(`Cannot send messages to channel of type ${channel.type}`, 400) + throw new HTTPError(`Cannot send messages to channel of type ${channel.type}`, 400); } - const files = req.files as Express.Multer.File[] ?? []; + const files = (req.files as Express.Multer.File[]) ?? []; for (let currFile of files) { try { const file: any = await uploadFile(`/attachments/${channel.id}`, currFile); attachments.push({ ...file, proxy_url: file.url }); - } - catch (error) { + } catch (error) { return res.status(400).json(error); } } @@ -212,11 +206,11 @@ router.post( }) ); } - - //Defining member fields + + //Defining member fields var member = await Member.findOneOrFail({ where: { id: req.user_id }, relations: ["roles"] }); // TODO: This doesn't work either - // member.roles = member.roles.filter((role) => { + // member.roles = member.roles.filter((role) => { // return role.id !== role.guild_id; // }).map((role) => { // return role.id; @@ -225,7 +219,7 @@ router.post( // TODO: Figure this out // delete message.member.last_message_id; // delete message.member.index; - + await Promise.all([ message.save(), emitEvent({ event: "MESSAGE_CREATE", channel_id: channel_id, data: message } as MessageCreateEvent), @@ -233,9 +227,8 @@ router.post( channel.save() ]); - postHandleMessage(message).catch((e) => { }); // no await as it shouldnt block the message send function and silently catch error + postHandleMessage(message).catch((e) => {}); // no await as it shouldnt block the message send function and silently catch error return res.json(message); } ); - diff --git a/src/api/routes/channels/#channel_id/permissions.ts b/src/api/routes/channels/#channel_id/permissions.ts index 34052fe5..bd462ea6 100644 --- a/src/api/routes/channels/#channel_id/permissions.ts +++ b/src/api/routes/channels/#channel_id/permissions.ts @@ -1,17 +1,15 @@ +import { route } from "@fosscord/api"; import { Channel, ChannelPermissionOverwrite, ChannelPermissionOverwriteSchema, - ChannelPermissionOverwriteType, ChannelUpdateEvent, emitEvent, - getPermission, + HTTPError, Member, Role } from "@fosscord/util"; -import { Router, Response, Request } from "express"; -import { HTTPError } from "@fosscord/util"; -import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router: Router = Router(); @@ -22,7 +20,7 @@ router.put( const { channel_id, overwrite_id } = req.params; const body = req.body as ChannelPermissionOverwriteSchema; - let channel = await Channel.findOneOrFail({ where: {id: channel_id} }); + let channel = await Channel.findOneOrFail({ where: { id: channel_id } }); if (!channel.guild_id) throw new HTTPError("Channel not found", 404); if (body.type === 0) { diff --git a/src/api/routes/channels/#channel_id/pins.ts b/src/api/routes/channels/#channel_id/pins.ts index 003638c5..5c28feac 100644 --- a/src/api/routes/channels/#channel_id/pins.ts +++ b/src/api/routes/channels/#channel_id/pins.ts @@ -1,16 +1,6 @@ -import { - Channel, - ChannelPinsUpdateEvent, - Config, - emitEvent, - getPermission, - Message, - MessageUpdateEvent, - DiscordApiErrors -} from "@fosscord/util"; -import { Router, Request, Response } from "express"; -import { HTTPError } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { Channel, ChannelPinsUpdateEvent, Config, DiscordApiErrors, emitEvent, Message, MessageUpdateEvent } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/channels/#channel_id/purge.ts b/src/api/routes/channels/#channel_id/purge.ts index 1ef6e1d7..aebdb832 100644 --- a/src/api/routes/channels/#channel_id/purge.ts +++ b/src/api/routes/channels/#channel_id/purge.ts @@ -1,10 +1,18 @@ -import { HTTPError, PurgeSchema } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { + Channel, + Config, + emitEvent, + getPermission, + getRights, + HTTPError, + Message, + MessageDeleteBulkEvent, + PurgeSchema +} from "@fosscord/util"; +import { Request, Response, Router } from "express"; +import { Between, FindManyOptions, In, Not } from "typeorm"; import { isTextChannel } from "./messages"; -import { FindManyOptions, Between, Not } from "typeorm"; -import { Channel, Config, emitEvent, getPermission, getRights, Message, MessageDeleteBulkEvent } from "@fosscord/util"; -import { Router, Response, Request } from "express"; -import { In } from "typeorm"; const router: Router = Router(); @@ -13,7 +21,12 @@ export default router; /** TODO: apply the delete bit by bit to prevent client and database stress **/ -router.post("/",route({ /*body: "PurgeSchema",*/ }), async (req: Request, res: Response) => { +router.post( + "/", + route({ + /*body: "PurgeSchema",*/ + }), + async (req: Request, res: Response) => { const { channel_id } = req.params; const channel = await Channel.findOneOrFail({ where: { id: channel_id } }); diff --git a/src/api/routes/channels/#channel_id/recipients.ts b/src/api/routes/channels/#channel_id/recipients.ts index 069212e2..276a0eda 100644 --- a/src/api/routes/channels/#channel_id/recipients.ts +++ b/src/api/routes/channels/#channel_id/recipients.ts @@ -1,4 +1,4 @@ -import { Request, Response, Router } from "express"; +import { route } from "@fosscord/api"; import { Channel, ChannelRecipientAddEvent, @@ -6,12 +6,12 @@ import { DiscordApiErrors, DmChannelDTO, emitEvent, + OrmUtils, PublicUserProjection, Recipient, User } from "@fosscord/util"; -import { route } from "@fosscord/api"; -import { OrmUtils } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/channels/#channel_id/typing.ts b/src/api/routes/channels/#channel_id/typing.ts index 99460f6e..26d0fcfa 100644 --- a/src/api/routes/channels/#channel_id/typing.ts +++ b/src/api/routes/channels/#channel_id/typing.ts @@ -1,6 +1,6 @@ -import { Channel, emitEvent, Member, TypingStartEvent } from "@fosscord/util"; import { route } from "@fosscord/api"; -import { Router, Request, Response } from "express"; +import { Channel, emitEvent, Member, TypingStartEvent } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/channels/#channel_id/webhooks.ts b/src/api/routes/channels/#channel_id/webhooks.ts index b11c8eb9..38dcb869 100644 --- a/src/api/routes/channels/#channel_id/webhooks.ts +++ b/src/api/routes/channels/#channel_id/webhooks.ts @@ -1,9 +1,7 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; -import { Channel, Config, getPermission, trimSpecial, Webhook } from "@fosscord/util"; -import { HTTPError } from "@fosscord/util"; +import { Channel, Config, DiscordApiErrors, HTTPError, trimSpecial, Webhook } from "@fosscord/util"; +import { Request, Response, Router } from "express"; import { isTextChannel } from "./messages/index"; -import { DiscordApiErrors } from "@fosscord/util"; const router: Router = Router(); //TODO: implement webhooks diff --git a/src/api/routes/discoverable-guilds.ts b/src/api/routes/discoverable-guilds.ts index 35ecf28c..2bf49287 100644 --- a/src/api/routes/discoverable-guilds.ts +++ b/src/api/routes/discoverable-guilds.ts @@ -1,8 +1,8 @@ -import { Guild, Config } from "@fosscord/util"; +import { Config, Guild } from "@fosscord/util"; -import { Router, Request, Response } from "express"; -import { route } from ".."; +import { Request, Response, Router } from "express"; import { Like } from "typeorm"; +import { route } from ".."; const router = Router(); diff --git a/src/api/routes/discovery.ts b/src/api/routes/discovery.ts index 30c418c6..7b9edd48 100644 --- a/src/api/routes/discovery.ts +++ b/src/api/routes/discovery.ts @@ -1,5 +1,5 @@ import { Categories } from "@fosscord/util"; -import { Router, Response, Request } from "express"; +import { Request, Response, Router } from "express"; import { route } from ".."; const router = Router(); @@ -10,7 +10,7 @@ router.get("/categories", route({}), async (req: Request, res: Response) => { const { locale, primary_only } = req.query; - const out = primary_only ? await Categories.find() : await Categories.find({ where: {is_primary: true} }); + const out = primary_only ? await Categories.find() : await Categories.find({ where: { is_primary: true } }); res.send(out); }); diff --git a/src/api/routes/downloads.ts b/src/api/routes/downloads.ts index 44530353..c86c1fb0 100644 --- a/src/api/routes/downloads.ts +++ b/src/api/routes/downloads.ts @@ -1,6 +1,6 @@ -import { Router, Response, Request } from "express"; +import { Config, Release } from "@fosscord/util"; +import { Request, Response, Router } from "express"; import { route } from ".."; -import { Release, Config } from "@fosscord/util"; const router = Router(); @@ -10,7 +10,7 @@ router.get("/:branch", route({}), async (req: Request, res: Response) => { const { platform } = req.query; //TODO - if(!platform || !["linux", "osx", "win"].includes(platform.toString())) return res.status(404) + if (!platform || !["linux", "osx", "win"].includes(platform.toString())) return res.status(404); const release = await Release.findOneOrFail({ where: { name: client.releases.upstreamVersion } }); diff --git a/src/api/routes/experiments.ts b/src/api/routes/experiments.ts index fcbd9271..0355c631 100644 --- a/src/api/routes/experiments.ts +++ b/src/api/routes/experiments.ts @@ -1,11 +1,11 @@ -import { Router, Response, Request } from "express"; +import { Request, Response, Router } from "express"; import { route } from ".."; const router = Router(); router.get("/", route({}), (req: Request, res: Response) => { // TODO: - res.send({ fingerprint: "", assignments: [], guild_experiments:[] }); + res.send({ fingerprint: "", assignments: [], guild_experiments: [] }); }); export default router; diff --git a/src/api/routes/gateway/bot.ts b/src/api/routes/gateway/bot.ts index f1dbb9df..0e44f6b2 100644 --- a/src/api/routes/gateway/bot.ts +++ b/src/api/routes/gateway/bot.ts @@ -1,6 +1,6 @@ -import { Config } from "@fosscord/util"; -import { Router, Response, Request } from "express"; import { route, RouteOptions } from "@fosscord/api"; +import { Config } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/gateway/index.ts b/src/api/routes/gateway/index.ts index 9bad7478..47037573 100644 --- a/src/api/routes/gateway/index.ts +++ b/src/api/routes/gateway/index.ts @@ -1,6 +1,6 @@ -import { Config } from "@fosscord/util"; -import { Router, Response, Request } from "express"; import { route, RouteOptions } from "@fosscord/api"; +import { Config } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/gifs/search.ts b/src/api/routes/gifs/search.ts index 1099dc4a..8b5e984a 100644 --- a/src/api/routes/gifs/search.ts +++ b/src/api/routes/gifs/search.ts @@ -1,7 +1,7 @@ -import { Router, Response, Request } from "express"; -import fetch from "node-fetch"; -import ProxyAgent from 'proxy-agent'; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; +import fetch from "node-fetch"; +import ProxyAgent from "proxy-agent"; import { getGifApiKey, parseGifResult } from "./trending"; const router = Router(); @@ -11,7 +11,7 @@ router.get("/", route({}), async (req: Request, res: Response) => { const { q, media_format, locale } = req.query; const apiKey = getGifApiKey(); - + const agent = new ProxyAgent(); const response = await fetch(`https://g.tenor.com/v1/search?q=${q}&media_format=${media_format}&locale=${locale}&key=${apiKey}`, { @@ -20,7 +20,7 @@ router.get("/", route({}), async (req: Request, res: Response) => { headers: { "Content-Type": "application/json" } }); - const { results } = await response.json() as any; + const { results } = (await response.json()) as any; res.json(results.map(parseGifResult)).status(200); }); diff --git a/src/api/routes/gifs/trending-gifs.ts b/src/api/routes/gifs/trending-gifs.ts index 2b28d9d2..65a9600e 100644 --- a/src/api/routes/gifs/trending-gifs.ts +++ b/src/api/routes/gifs/trending-gifs.ts @@ -1,7 +1,7 @@ -import { Router, Response, Request } from "express"; -import fetch from "node-fetch"; -import ProxyAgent from 'proxy-agent'; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; +import fetch from "node-fetch"; +import ProxyAgent from "proxy-agent"; import { getGifApiKey, parseGifResult } from "./trending"; const router = Router(); @@ -11,7 +11,7 @@ router.get("/", route({}), async (req: Request, res: Response) => { const { media_format, locale } = req.query; const apiKey = getGifApiKey(); - + const agent = new ProxyAgent(); const response = await fetch(`https://g.tenor.com/v1/trending?media_format=${media_format}&locale=${locale}&key=${apiKey}`, { @@ -20,7 +20,7 @@ router.get("/", route({}), async (req: Request, res: Response) => { headers: { "Content-Type": "application/json" } }); - const { results } = await response.json() as any; + const { results } = (await response.json()) as any; res.json(results.map(parseGifResult)).status(200); }); diff --git a/src/api/routes/gifs/trending.ts b/src/api/routes/gifs/trending.ts index 61eb76c4..45396ff0 100644 --- a/src/api/routes/gifs/trending.ts +++ b/src/api/routes/gifs/trending.ts @@ -1,9 +1,8 @@ -import { Router, Response, Request } from "express"; -import fetch from "node-fetch"; -import ProxyAgent from 'proxy-agent'; import { route } from "@fosscord/api"; -import { Config } from "@fosscord/util"; -import { HTTPError } from "@fosscord/util"; +import { Config, HTTPError } from "@fosscord/util"; +import { Request, Response, Router } from "express"; +import fetch from "node-fetch"; +import ProxyAgent from "proxy-agent"; const router = Router(); @@ -34,7 +33,7 @@ router.get("/", route({}), async (req: Request, res: Response) => { const { media_format, locale } = req.query; const apiKey = getGifApiKey(); - + const agent = new ProxyAgent(); const [responseSource, trendGifSource] = await Promise.all([ @@ -50,8 +49,8 @@ router.get("/", route({}), async (req: Request, res: Response) => { }) ]); - const { tags } = await responseSource.json() as any; - const { results } = await trendGifSource.json() as any; + const { tags } = (await responseSource.json()) as any; + const { results } = (await trendGifSource.json()) as any; res.json({ categories: tags.map((x: any) => ({ name: x.searchterm, src: x.image })), diff --git a/src/api/routes/guild-recommendations.ts b/src/api/routes/guild-recommendations.ts index bd0140d6..0248a9c3 100644 --- a/src/api/routes/guild-recommendations.ts +++ b/src/api/routes/guild-recommendations.ts @@ -1,8 +1,8 @@ -import { Guild, Config } from "@fosscord/util"; +import { Config, Guild } from "@fosscord/util"; -import { Router, Request, Response } from "express"; +import { Request, Response, Router } from "express"; +import { Like } from "typeorm"; import { route } from ".."; -import {Like} from "typeorm" const router = Router(); @@ -13,12 +13,12 @@ router.get("/", route({}), async (req: Request, res: Response) => { // TODO: implement this with default typeorm query // const guilds = await Guild.find({ where: { features: "DISCOVERABLE" } }); //, take: Math.abs(Number(limit)) }); - const genLoadId = (size: Number) => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join(''); + const genLoadId = (size: Number) => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join(""); const guilds = showAllGuilds ? await Guild.find({ take: Math.abs(Number(limit || 24)) }) - : await Guild.find({ where: { features: Like('%DISCOVERABLE%') }, take: Math.abs(Number(limit || 24)) }); - res.send({ recommended_guilds: guilds, load_id: `server_recs/${genLoadId(32)}`}).status(200); + : await Guild.find({ where: { features: Like("%DISCOVERABLE%") }, take: Math.abs(Number(limit || 24)) }); + res.send({ recommended_guilds: guilds, load_id: `server_recs/${genLoadId(32)}` }).status(200); }); export default router; diff --git a/src/api/routes/guilds/#guild_id/audit-logs.ts b/src/api/routes/guilds/#guild_id/audit-logs.ts index b54835fc..05b9982e 100644 --- a/src/api/routes/guilds/#guild_id/audit-logs.ts +++ b/src/api/routes/guilds/#guild_id/audit-logs.ts @@ -1,5 +1,5 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); //TODO: implement audit logs diff --git a/src/api/routes/guilds/#guild_id/bans.ts b/src/api/routes/guilds/#guild_id/bans.ts index 3d405344..4600b4cb 100644 --- a/src/api/routes/guilds/#guild_id/bans.ts +++ b/src/api/routes/guilds/#guild_id/bans.ts @@ -1,8 +1,18 @@ -import { Request, Response, Router } from "express"; -import { DiscordApiErrors, emitEvent, getPermission, GuildBanAddEvent, GuildBanRemoveEvent, Guild, Ban, User, Member, BanRegistrySchema, BanModeratorSchema } from "@fosscord/util"; -import { HTTPError } from "@fosscord/util"; import { getIpAdress, route } from "@fosscord/api"; -import { OrmUtils } from "@fosscord/util"; +import { + Ban, + BanModeratorSchema, + BanRegistrySchema, + DiscordApiErrors, + emitEvent, + GuildBanAddEvent, + GuildBanRemoveEvent, + HTTPError, + Member, + OrmUtils, + User +} from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); @@ -44,16 +54,16 @@ router.get("/:user", route({ permission: "BAN_MEMBERS" }), async (req: Request, const { guild_id } = req.params; const user_id = req.params.ban; - let ban = await Ban.findOneOrFail({ where: { guild_id, user_id } }) as BanRegistrySchema; - + let ban = (await Ban.findOneOrFail({ where: { guild_id, user_id } })) as BanRegistrySchema; + if (ban.user_id === ban.executor_id) throw DiscordApiErrors.UNKNOWN_BAN; // pretend self-bans don't exist to prevent victim chasing - + /* Filter secret from registry. */ - + ban = ban as BanModeratorSchema; - delete ban.ip + delete ban.ip; return res.json(ban); }); @@ -62,14 +72,14 @@ router.put("/:user_id", route({ body: "BanCreateSchema", permission: "BAN_MEMBER const { guild_id } = req.params; const banned_user_id = req.params.user_id; - if ( (req.user_id === banned_user_id) && (banned_user_id === req.permission!.cache.guild?.owner_id)) + if (req.user_id === banned_user_id && banned_user_id === req.permission!.cache.guild?.owner_id) throw new HTTPError("You are the guild owner, hence can't ban yourself", 403); - + if (req.permission!.cache.guild?.owner_id === banned_user_id) throw new HTTPError("You can't ban the owner", 400); - + const banned_user = await User.getPublicUser(banned_user_id); - const ban = OrmUtils.mergeDeep(new Ban(),{ + const ban = OrmUtils.mergeDeep(new Ban(), { user_id: banned_user_id, guild_id: guild_id, ip: getIpAdress(req), @@ -93,14 +103,14 @@ router.put("/:user_id", route({ body: "BanCreateSchema", permission: "BAN_MEMBER return res.json(ban); }); -router.put("/@me", route({ body: "BanCreateSchema"}), async (req: Request, res: Response) => { +router.put("/@me", route({ body: "BanCreateSchema" }), async (req: Request, res: Response) => { const { guild_id } = req.params; const banned_user = await User.getPublicUser(req.params.user_id); - if (req.permission!.cache.guild?.owner_id === req.params.user_id) + if (req.permission!.cache.guild?.owner_id === req.params.user_id) throw new HTTPError("You are the guild owner, hence can't ban yourself", 403); - + const ban = OrmUtils.mergeDeep(new Ban(), { user_id: req.params.user_id, guild_id: guild_id, @@ -129,12 +139,12 @@ router.delete("/:user_id", route({ permission: "BAN_MEMBERS" }), async (req: Req const { guild_id, user_id } = req.params; let ban = await Ban.findOneOrFail({ where: { guild_id, user_id } }); - + if (ban.user_id === ban.executor_id) throw DiscordApiErrors.UNKNOWN_BAN; // make self-bans irreversible and hide them from view to avoid victim chasing - + const banned_user = await User.getPublicUser(user_id); - + await Promise.all([ Ban.delete({ user_id: user_id, diff --git a/src/api/routes/guilds/#guild_id/channels.ts b/src/api/routes/guilds/#guild_id/channels.ts index 8f2d3643..3563eb4c 100644 --- a/src/api/routes/guilds/#guild_id/channels.ts +++ b/src/api/routes/guilds/#guild_id/channels.ts @@ -1,7 +1,6 @@ -import { Router, Response, Request } from "express"; -import { Channel, ChannelUpdateEvent, getPermission, emitEvent, ChannelModifySchema, ChannelReorderSchema } from "@fosscord/util"; -import { HTTPError } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { Channel, ChannelModifySchema, ChannelReorderSchema, ChannelUpdateEvent, emitEvent, HTTPError } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router = Router(); router.get("/", route({}), async (req: Request, res: Response) => { diff --git a/src/api/routes/guilds/#guild_id/delete.ts b/src/api/routes/guilds/#guild_id/delete.ts index e2624651..e6a1a6b2 100644 --- a/src/api/routes/guilds/#guild_id/delete.ts +++ b/src/api/routes/guilds/#guild_id/delete.ts @@ -1,7 +1,6 @@ -import { Channel, emitEvent, GuildDeleteEvent, Guild, Member, Message, Role, Invite, Emoji } from "@fosscord/util"; -import { Router, Request, Response } from "express"; -import { HTTPError } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { emitEvent, Guild, GuildDeleteEvent, HTTPError } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/guilds/#guild_id/discovery-requirements.ts b/src/api/routes/guilds/#guild_id/discovery-requirements.ts index ad20633f..c0260fe7 100644 --- a/src/api/routes/guilds/#guild_id/discovery-requirements.ts +++ b/src/api/routes/guilds/#guild_id/discovery-requirements.ts @@ -1,38 +1,36 @@ -import { Guild, Config } from "@fosscord/util"; - -import { Router, Request, Response } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); router.get("/", route({}), async (req: Request, res: Response) => { - const { guild_id } = req.params; - // TODO: - // Load from database - // Admin control, but for now it allows anyone to be discoverable + const { guild_id } = req.params; + // TODO: + // Load from database + // Admin control, but for now it allows anyone to be discoverable res.send({ guild_id: guild_id, safe_environment: true, - healthy: true, - health_score_pending: false, - size: true, - nsfw_properties: {}, - protected: true, - sufficient: true, - sufficient_without_grace_period: true, - valid_rules_channel: true, - retention_healthy: true, - engagement_healthy: true, - age: true, - minimum_age: 0, - health_score: { - avg_nonnew_participators: 0, - avg_nonnew_communicators: 0, - num_intentful_joiners: 0, - perc_ret_w1_intentful: 0 - }, - minimum_size: 0 + healthy: true, + health_score_pending: false, + size: true, + nsfw_properties: {}, + protected: true, + sufficient: true, + sufficient_without_grace_period: true, + valid_rules_channel: true, + retention_healthy: true, + engagement_healthy: true, + age: true, + minimum_age: 0, + health_score: { + avg_nonnew_participators: 0, + avg_nonnew_communicators: 0, + num_intentful_joiners: 0, + perc_ret_w1_intentful: 0 + }, + minimum_size: 0 }); }); diff --git a/src/api/routes/guilds/#guild_id/emojis.ts b/src/api/routes/guilds/#guild_id/emojis.ts index 4bf4bdcd..db5ae325 100644 --- a/src/api/routes/guilds/#guild_id/emojis.ts +++ b/src/api/routes/guilds/#guild_id/emojis.ts @@ -1,7 +1,19 @@ -import { Router, Request, Response } from "express"; -import { Config, DiscordApiErrors, emitEvent, Emoji, EmojiCreateSchema, EmojiModifySchema, GuildEmojisUpdateEvent, handleFile, Member, Snowflake, User } from "@fosscord/util"; import { route } from "@fosscord/api"; -import { OrmUtils } from "@fosscord/util"; +import { + Config, + DiscordApiErrors, + emitEvent, + Emoji, + EmojiCreateSchema, + EmojiModifySchema, + GuildEmojisUpdateEvent, + handleFile, + Member, + OrmUtils, + Snowflake, + User +} from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/guilds/#guild_id/index.ts b/src/api/routes/guilds/#guild_id/index.ts index a9712c71..af889982 100644 --- a/src/api/routes/guilds/#guild_id/index.ts +++ b/src/api/routes/guilds/#guild_id/index.ts @@ -1,8 +1,18 @@ -import { Request, Response, Router } from "express"; -import { DiscordApiErrors, emitEvent, getPermission, getRights, Guild, GuildUpdateEvent, GuildUpdateSchema, handleFile, Member } from "@fosscord/util"; -import { HTTPError } from "@fosscord/util"; import { route } from "@fosscord/api"; -import { OrmUtils } from "@fosscord/util"; +import { + DiscordApiErrors, + emitEvent, + getPermission, + getRights, + Guild, + GuildUpdateEvent, + GuildUpdateSchema, + handleFile, + HTTPError, + Member, + OrmUtils +} from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router = Router(); @@ -21,17 +31,16 @@ router.get("/", route({}), async (req: Request, res: Response) => { return res.send(guild); }); -router.patch("/", route({ body: "GuildUpdateSchema"}), async (req: Request, res: Response) => { +router.patch("/", route({ body: "GuildUpdateSchema" }), async (req: Request, res: Response) => { const body = req.body as GuildUpdateSchema; const { guild_id } = req.params; - - + const rights = await getRights(req.user_id); const permission = await getPermission(req.user_id, guild_id); - - if (!rights.has("MANAGE_GUILDS")||!permission.has("MANAGE_GUILD")) + + if (!rights.has("MANAGE_GUILDS") || !permission.has("MANAGE_GUILD")) throw DiscordApiErrors.MISSING_PERMISSIONS.withParams("MANAGE_GUILD"); - + // TODO: guild update check image if (body.icon) body.icon = await handleFile(`/icons/${guild_id}`, body.icon); diff --git a/src/api/routes/guilds/#guild_id/integrations.ts b/src/api/routes/guilds/#guild_id/integrations.ts index 90650111..6a5abec3 100644 --- a/src/api/routes/guilds/#guild_id/integrations.ts +++ b/src/api/routes/guilds/#guild_id/integrations.ts @@ -1,7 +1,5 @@ -import { Router, Response, Request } from "express"; -import { Channel, ChannelUpdateEvent, getPermission, emitEvent } from "@fosscord/util"; -import { HTTPError } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); //TODO: implement integrations list diff --git a/src/api/routes/guilds/#guild_id/invites.ts b/src/api/routes/guilds/#guild_id/invites.ts index b7534e31..c663df72 100644 --- a/src/api/routes/guilds/#guild_id/invites.ts +++ b/src/api/routes/guilds/#guild_id/invites.ts @@ -1,5 +1,5 @@ -import { getPermission, Invite, PublicInviteRelation } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { Invite, PublicInviteRelation } from "@fosscord/util"; import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/guilds/#guild_id/members/#member_id/index.ts b/src/api/routes/guilds/#guild_id/members/#member_id/index.ts index 794369d8..57152f9a 100644 --- a/src/api/routes/guilds/#guild_id/members/#member_id/index.ts +++ b/src/api/routes/guilds/#guild_id/members/#member_id/index.ts @@ -1,8 +1,18 @@ -import { Request, Response, Router } from "express"; -import { Member, getPermission, getRights, Role, GuildMemberUpdateEvent, emitEvent, Sticker, Emoji, Rights, Guild, MemberChangeSchema } from "@fosscord/util"; -import { HTTPError } from "@fosscord/util"; import { route } from "@fosscord/api"; -import { OrmUtils } from "@fosscord/util"; +import { + emitEvent, + Emoji, + getPermission, + getRights, + Guild, + GuildMemberUpdateEvent, + Member, + MemberChangeSchema, + OrmUtils, + Role, + Sticker +} from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router = Router(); @@ -46,7 +56,6 @@ router.patch("/", route({ body: "MemberChangeSchema" }), async (req: Request, re }); router.put("/", route({}), async (req: Request, res: Response) => { - // TODO: Lurker mode const rights = await getRights(req.user_id); @@ -56,7 +65,7 @@ router.put("/", route({}), async (req: Request, res: Response) => { member_id = req.user_id; rights.hasThrow("JOIN_GUILDS"); } else { - // TODO: join others by controller + // TODO: join others by controller } let guild = await Guild.findOneOrFail({ diff --git a/src/api/routes/guilds/#guild_id/members/#member_id/nick.ts b/src/api/routes/guilds/#guild_id/members/#member_id/nick.ts index a6c71333..26411f97 100644 --- a/src/api/routes/guilds/#guild_id/members/#member_id/nick.ts +++ b/src/api/routes/guilds/#guild_id/members/#member_id/nick.ts @@ -1,5 +1,5 @@ -import { getPermission, Member, PermissionResolvable } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { getPermission, Member, PermissionResolvable } from "@fosscord/util"; import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/guilds/#guild_id/members/#member_id/roles/#role_id/index.ts b/src/api/routes/guilds/#guild_id/members/#member_id/roles/#role_id/index.ts index 8f5ca7ba..0aa7a4dc 100644 --- a/src/api/routes/guilds/#guild_id/members/#member_id/roles/#role_id/index.ts +++ b/src/api/routes/guilds/#guild_id/members/#member_id/roles/#role_id/index.ts @@ -1,5 +1,5 @@ -import { getPermission, Member } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { Member } from "@fosscord/util"; import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/guilds/#guild_id/members/index.ts b/src/api/routes/guilds/#guild_id/members/index.ts index 2ed28bda..08164626 100644 --- a/src/api/routes/guilds/#guild_id/members/index.ts +++ b/src/api/routes/guilds/#guild_id/members/index.ts @@ -1,8 +1,7 @@ -import { Request, Response, Router } from "express"; -import { Guild, Member, PublicMemberProjection } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { HTTPError, Member, PublicMemberProjection } from "@fosscord/util"; +import { Request, Response, Router } from "express"; import { MoreThan } from "typeorm"; -import { HTTPError } from "@fosscord/util"; const router = Router(); diff --git a/src/api/routes/guilds/#guild_id/premium.ts b/src/api/routes/guilds/#guild_id/premium.ts index 75361ac6..b7716378 100644 --- a/src/api/routes/guilds/#guild_id/premium.ts +++ b/src/api/routes/guilds/#guild_id/premium.ts @@ -1,5 +1,5 @@ -import { Router, Request, Response } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); router.get("/subscriptions", route({}), async (req: Request, res: Response) => { diff --git a/src/api/routes/guilds/#guild_id/prune.ts b/src/api/routes/guilds/#guild_id/prune.ts index 673f022f..3645721c 100644 --- a/src/api/routes/guilds/#guild_id/prune.ts +++ b/src/api/routes/guilds/#guild_id/prune.ts @@ -1,7 +1,7 @@ -import { Router, Request, Response } from "express"; -import { Guild, Member, Snowflake } from "@fosscord/util"; -import { LessThan, IsNull } from "typeorm"; import { route } from "@fosscord/api"; +import { Guild, Member, Snowflake } from "@fosscord/util"; +import { Request, Response, Router } from "express"; +import { IsNull, LessThan } from "typeorm"; const router = Router(); //Returns all inactive members, respecting role hierarchy diff --git a/src/api/routes/guilds/#guild_id/regions.ts b/src/api/routes/guilds/#guild_id/regions.ts index 308d5ee5..aa57ec65 100644 --- a/src/api/routes/guilds/#guild_id/regions.ts +++ b/src/api/routes/guilds/#guild_id/regions.ts @@ -1,7 +1,6 @@ -import { Config, Guild, Member } from "@fosscord/util"; +import { getIpAdress, getVoiceRegions, route } from "@fosscord/api"; +import { Guild } from "@fosscord/util"; import { Request, Response, Router } from "express"; -import { getVoiceRegions, route } from "@fosscord/api"; -import { getIpAdress } from "@fosscord/api"; const router = Router(); diff --git a/src/api/routes/guilds/#guild_id/roles/#role_id/index.ts b/src/api/routes/guilds/#guild_id/roles/#role_id/index.ts index d4422a9c..7f9dbc6f 100644 --- a/src/api/routes/guilds/#guild_id/roles/#role_id/index.ts +++ b/src/api/routes/guilds/#guild_id/roles/#role_id/index.ts @@ -1,8 +1,16 @@ -import { Router, Request, Response } from "express"; -import { Role, Member, GuildRoleUpdateEvent, GuildRoleDeleteEvent, emitEvent, handleFile, RoleModifySchema } from "@fosscord/util"; import { route } from "@fosscord/api"; -import { HTTPError } from "@fosscord/util"; -import { OrmUtils } from "@fosscord/util"; +import { + emitEvent, + GuildRoleDeleteEvent, + GuildRoleUpdateEvent, + handleFile, + HTTPError, + Member, + OrmUtils, + Role, + RoleModifySchema +} from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/guilds/#guild_id/roles/index.ts b/src/api/routes/guilds/#guild_id/roles/index.ts index 17f0b5e9..9791f7a9 100644 --- a/src/api/routes/guilds/#guild_id/roles/index.ts +++ b/src/api/routes/guilds/#guild_id/roles/index.ts @@ -1,21 +1,18 @@ -import { Request, Response, Router } from "express"; +import { route } from "@fosscord/api"; import { - Role, + Config, + DiscordApiErrors, + emitEvent, getPermission, - Member, GuildRoleCreateEvent, GuildRoleUpdateEvent, - GuildRoleDeleteEvent, - emitEvent, - Config, - DiscordApiErrors, - handleFile, + Member, + OrmUtils, + Role, RoleModifySchema, RolePositionUpdateSchema } from "@fosscord/util"; -import { HTTPError } from "@fosscord/util"; -import { route } from "@fosscord/api"; -import { OrmUtils } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); @@ -38,7 +35,7 @@ router.post("/", route({ body: "RoleModifySchema", permission: "MANAGE_ROLES" }) if (role_count > maxRoles) throw DiscordApiErrors.MAXIMUM_ROLES.withParams(maxRoles); - let role: Role = OrmUtils.mergeDeep(new Role(),{ + let role: Role = OrmUtils.mergeDeep(new Role(), { // values before ...body are default and can be overriden position: 0, hoist: false, diff --git a/src/api/routes/guilds/#guild_id/stickers.ts b/src/api/routes/guilds/#guild_id/stickers.ts index 71c9dfcd..15741780 100644 --- a/src/api/routes/guilds/#guild_id/stickers.ts +++ b/src/api/routes/guilds/#guild_id/stickers.ts @@ -1,20 +1,19 @@ +import { route } from "@fosscord/api"; import { emitEvent, GuildStickersUpdateEvent, - handleFile, + HTTPError, Member, ModifyGuildStickerSchema, + OrmUtils, Snowflake, Sticker, StickerFormatType, StickerType, uploadFile } from "@fosscord/util"; -import { Router, Request, Response } from "express"; -import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; import multer from "multer"; -import { HTTPError } from "@fosscord/util"; -import { OrmUtils } from "@fosscord/util"; const router = Router(); router.get("/", route({}), async (req: Request, res: Response) => { diff --git a/src/api/routes/guilds/#guild_id/templates.ts b/src/api/routes/guilds/#guild_id/templates.ts index 9c79692d..448ee033 100644 --- a/src/api/routes/guilds/#guild_id/templates.ts +++ b/src/api/routes/guilds/#guild_id/templates.ts @@ -1,9 +1,6 @@ +import { generateCode, route } from "@fosscord/api"; +import { Guild, HTTPError, OrmUtils, Template } from "@fosscord/util"; import { Request, Response, Router } from "express"; -import { Guild, Template } from "@fosscord/util"; -import { HTTPError } from "@fosscord/util"; -import { route } from "@fosscord/api"; -import { generateCode } from "@fosscord/api"; -import { OrmUtils } from "@fosscord/util"; const router: Router = Router(); @@ -75,7 +72,12 @@ router.patch("/:code", route({ body: "TemplateModifySchema", permission: "MANAGE const { code, guild_id } = req.params; const { name, description } = req.body; - const template = await OrmUtils.mergeDeep(new Template(), { code, name: name, description: description, source_guild_id: guild_id }).save(); + const template = await OrmUtils.mergeDeep(new Template(), { + code, + name: name, + description: description, + source_guild_id: guild_id + }).save(); res.json(template); }); diff --git a/src/api/routes/guilds/#guild_id/vanity-url.ts b/src/api/routes/guilds/#guild_id/vanity-url.ts index ff92ce8d..bf2db134 100644 --- a/src/api/routes/guilds/#guild_id/vanity-url.ts +++ b/src/api/routes/guilds/#guild_id/vanity-url.ts @@ -1,8 +1,6 @@ -import { Channel, ChannelType, getPermission, Guild, Invite, trimSpecial, VanityUrlSchema } from "@fosscord/util"; -import { Router, Request, Response } from "express"; import { route } from "@fosscord/api"; -import { HTTPError } from "@fosscord/util"; -import { OrmUtils } from "@fosscord/util"; +import { Channel, ChannelType, Guild, HTTPError, Invite, OrmUtils, VanityUrlSchema } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/guilds/#guild_id/voice-states/#user_id/index.ts b/src/api/routes/guilds/#guild_id/voice-states/#user_id/index.ts index 28a9e8c1..797d348e 100644 --- a/src/api/routes/guilds/#guild_id/voice-states/#user_id/index.ts +++ b/src/api/routes/guilds/#guild_id/voice-states/#user_id/index.ts @@ -1,7 +1,16 @@ -import { Channel, ChannelType, DiscordApiErrors, emitEvent, getPermission, VoiceState, VoiceStateUpdateEvent, VoiceStateUpdateSchema } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { + Channel, + ChannelType, + DiscordApiErrors, + emitEvent, + getPermission, + OrmUtils, + VoiceState, + VoiceStateUpdateEvent, + VoiceStateUpdateSchema +} from "@fosscord/util"; import { Request, Response, Router } from "express"; -import { OrmUtils } from "@fosscord/util"; const router = Router(); router.patch("/", route({ body: "VoiceStateUpdateSchema" }), async (req: Request, res: Response) => { diff --git a/src/api/routes/guilds/#guild_id/webhooks.ts b/src/api/routes/guilds/#guild_id/webhooks.ts index c8c1eb5c..80e6a59a 100644 --- a/src/api/routes/guilds/#guild_id/webhooks.ts +++ b/src/api/routes/guilds/#guild_id/webhooks.ts @@ -1,7 +1,5 @@ -import { Router, Response, Request } from "express"; -import { Channel, ChannelUpdateEvent, getPermission, emitEvent } from "@fosscord/util"; -import { HTTPError } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); //TODO: implement webhooks diff --git a/src/api/routes/guilds/#guild_id/welcome_screen.ts b/src/api/routes/guilds/#guild_id/welcome_screen.ts index d08300ba..85c22a19 100644 --- a/src/api/routes/guilds/#guild_id/welcome_screen.ts +++ b/src/api/routes/guilds/#guild_id/welcome_screen.ts @@ -1,7 +1,6 @@ -import { Request, Response, Router } from "express"; -import { Guild, getPermission, Snowflake, Member, GuildUpdateWelcomeScreenSchema } from "@fosscord/util"; -import { HTTPError } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { Guild, GuildUpdateWelcomeScreenSchema, HTTPError, Member } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/guilds/#guild_id/widget.json.ts b/src/api/routes/guilds/#guild_id/widget.json.ts index 37739418..368fe46e 100644 --- a/src/api/routes/guilds/#guild_id/widget.json.ts +++ b/src/api/routes/guilds/#guild_id/widget.json.ts @@ -1,8 +1,6 @@ -import { Request, Response, Router } from "express"; -import { Config, Permissions, Guild, Invite, Channel, Member } from "@fosscord/util"; -import { HTTPError } from "@fosscord/util"; import { random, route } from "@fosscord/api"; -import { OrmUtils } from "@fosscord/util"; +import { Channel, Guild, HTTPError, Invite, Member, OrmUtils, Permissions } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/guilds/#guild_id/widget.png.ts b/src/api/routes/guilds/#guild_id/widget.png.ts index d064fa13..1c4ef29b 100644 --- a/src/api/routes/guilds/#guild_id/widget.png.ts +++ b/src/api/routes/guilds/#guild_id/widget.png.ts @@ -1,7 +1,6 @@ -import { Request, Response, Router } from "express"; -import { Guild } from "@fosscord/util"; -import { HTTPError } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { Guild, HTTPError } from "@fosscord/util"; +import { Request, Response, Router } from "express"; import fs from "fs"; import path from "path"; diff --git a/src/api/routes/guilds/#guild_id/widget.ts b/src/api/routes/guilds/#guild_id/widget.ts index dbb4cc0c..d2369dd1 100644 --- a/src/api/routes/guilds/#guild_id/widget.ts +++ b/src/api/routes/guilds/#guild_id/widget.ts @@ -1,6 +1,6 @@ -import { Request, Response, Router } from "express"; -import { Guild, WidgetModifySchema } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { Guild, WidgetModifySchema } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/guilds/index.ts b/src/api/routes/guilds/index.ts index e4d66192..6946e2f7 100644 --- a/src/api/routes/guilds/index.ts +++ b/src/api/routes/guilds/index.ts @@ -1,6 +1,6 @@ -import { Router, Request, Response } from "express"; -import { Role, Guild, Snowflake, Config, getRights, Member, Channel, DiscordApiErrors, handleFile, GuildCreateSchema } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { Config, DiscordApiErrors, getRights, Guild, GuildCreateSchema, Member } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); @@ -12,7 +12,7 @@ router.post("/", route({ body: "GuildCreateSchema", right: "CREATE_GUILDS" }), a const { maxGuilds } = Config.get().limits.user; const guild_count = await Member.count({ where: { id: req.user_id } }); const rights = await getRights(req.user_id); - if ((guild_count >= maxGuilds)&&!rights.has("MANAGE_GUILDS")) { + if (guild_count >= maxGuilds && !rights.has("MANAGE_GUILDS")) { throw DiscordApiErrors.MAXIMUM_GUILDS.withParams(maxGuilds); } diff --git a/src/api/routes/guilds/templates/index.ts b/src/api/routes/guilds/templates/index.ts index 3a0de9e8..467186a3 100644 --- a/src/api/routes/guilds/templates/index.ts +++ b/src/api/routes/guilds/templates/index.ts @@ -1,6 +1,6 @@ -import { Request, Response, Router } from "express"; -import { Template, Guild, Role, Snowflake, Config, User, Member, DiscordApiErrors, OrmUtils, GuildTemplateCreateSchema } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { Config, DiscordApiErrors, Guild, GuildTemplateCreateSchema, Member, OrmUtils, Role, Snowflake, Template } from "@fosscord/util"; +import { Request, Response, Router } from "express"; import fetch from "node-fetch"; const router: Router = Router(); @@ -9,9 +9,10 @@ router.get("/:code", route({}), async (req: Request, res: Response) => { if (!enabled) res.json({ code: 403, message: "Template creation & usage is disabled on this instance." }).sendStatus(403); const { code } = req.params; - + if (code.startsWith("discord:")) { - if (!allowDiscordTemplates) return res.json({ code: 403, message: "Discord templates cannot be used on this instance." }).sendStatus(403); + if (!allowDiscordTemplates) + return res.json({ code: 403, message: "Discord templates cannot be used on this instance." }).sendStatus(403); const discordTemplateID = code.split("discord:", 2)[1]; const discordTemplateData = await fetch(`https://discord.com/api/v9/guilds/templates/${discordTemplateID}`, { @@ -22,7 +23,7 @@ router.get("/:code", route({}), async (req: Request, res: Response) => { } if (code.startsWith("external:")) { - if (!allowRaws) return res.json({ code: 403, message: "Importing raws is disabled on this instance." }).sendStatus(403); + if (!allowRaws) return res.json({ code: 403, message: "Importing raws is disabled on this instance." }).sendStatus(403); return res.json(code.split("external:", 2)[1]); } @@ -57,18 +58,20 @@ router.post("/:code", route({ body: "GuildTemplateCreateSchema" }), async (req: id: guild_id, owner_id: req.user_id }).save(), - (OrmUtils.mergeDeep(new Role(), { - id: guild_id, - guild_id: guild_id, - color: 0, - hoist: false, - managed: true, - mentionable: true, - name: "@everyone", - permissions: BigInt("2251804225"), - position: 0, - tags: null - }) as Role).save() + ( + OrmUtils.mergeDeep(new Role(), { + id: guild_id, + guild_id: guild_id, + color: 0, + hoist: false, + managed: true, + mentionable: true, + name: "@everyone", + permissions: BigInt("2251804225"), + position: 0, + tags: null + }) as Role + ).save() ]); await Member.addToGuild(req.user_id, guild_id); diff --git a/src/api/routes/invites/index.ts b/src/api/routes/invites/index.ts index 1b434505..73c9324c 100644 --- a/src/api/routes/invites/index.ts +++ b/src/api/routes/invites/index.ts @@ -1,7 +1,6 @@ -import { Router, Request, Response } from "express"; -import { emitEvent, getPermission, Guild, Invite, InviteDeleteEvent, User, PublicInviteRelation } from "@fosscord/util"; import { route } from "@fosscord/api"; -import { HTTPError } from "@fosscord/util"; +import { emitEvent, getPermission, Guild, HTTPError, Invite, InviteDeleteEvent, PublicInviteRelation, User } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); @@ -13,15 +12,16 @@ router.get("/:code", route({}), async (req: Request, res: Response) => { res.status(200).send(invite); }); -router.post("/:code", route({right: "USE_MASS_INVITES"}), async (req: Request, res: Response) => { +router.post("/:code", route({ right: "USE_MASS_INVITES" }), async (req: Request, res: Response) => { const { code } = req.params; - const { guild_id } = await Invite.findOneOrFail({ where: { code } }) - const { features } = await Guild.findOneOrFail({ where: { id: guild_id} }); + const { guild_id } = await Invite.findOneOrFail({ where: { code } }); + const { features } = await Guild.findOneOrFail({ where: { id: guild_id } }); const { public_flags } = await User.findOneOrFail({ where: { id: req.user_id } }); - - if(features.includes("INTERNAL_EMPLOYEE_ONLY") && (public_flags & 1) !== 1) throw new HTTPError("Only intended for the staff of this server.", 401); - if(features.includes("INVITES_CLOSED")) throw new HTTPError("Sorry, this guild has joins closed.", 403); - + + if (features.includes("INTERNAL_EMPLOYEE_ONLY") && (public_flags & 1) !== 1) + throw new HTTPError("Only intended for the staff of this server.", 401); + if (features.includes("INVITES_CLOSED")) throw new HTTPError("Sorry, this guild has joins closed.", 403); + const invite = await Invite.joinGuild(req.user_id, code); res.json(invite); diff --git a/src/api/routes/oauth2/tokens.ts b/src/api/routes/oauth2/tokens.ts index bd284221..831dc7af 100644 --- a/src/api/routes/oauth2/tokens.ts +++ b/src/api/routes/oauth2/tokens.ts @@ -1,5 +1,5 @@ -import { Router, Request, Response } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); router.get("/", route({}), async (req: Request, res: Response) => { diff --git a/src/api/routes/outbound-promotions.ts b/src/api/routes/outbound-promotions.ts index 411e95bf..8e407184 100644 --- a/src/api/routes/outbound-promotions.ts +++ b/src/api/routes/outbound-promotions.ts @@ -1,5 +1,5 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/partners/#guild_id/requirements.ts b/src/api/routes/partners/#guild_id/requirements.ts index 545c5c78..c0260fe7 100644 --- a/src/api/routes/partners/#guild_id/requirements.ts +++ b/src/api/routes/partners/#guild_id/requirements.ts @@ -1,39 +1,36 @@ - -import { Guild, Config } from "@fosscord/util"; - -import { Router, Request, Response } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); router.get("/", route({}), async (req: Request, res: Response) => { - const { guild_id } = req.params; - // TODO: - // Load from database - // Admin control, but for now it allows anyone to be discoverable + const { guild_id } = req.params; + // TODO: + // Load from database + // Admin control, but for now it allows anyone to be discoverable res.send({ guild_id: guild_id, safe_environment: true, - healthy: true, - health_score_pending: false, - size: true, - nsfw_properties: {}, - protected: true, - sufficient: true, - sufficient_without_grace_period: true, - valid_rules_channel: true, - retention_healthy: true, - engagement_healthy: true, - age: true, - minimum_age: 0, - health_score: { - avg_nonnew_participators: 0, - avg_nonnew_communicators: 0, - num_intentful_joiners: 0, - perc_ret_w1_intentful: 0 - }, - minimum_size: 0 + healthy: true, + health_score_pending: false, + size: true, + nsfw_properties: {}, + protected: true, + sufficient: true, + sufficient_without_grace_period: true, + valid_rules_channel: true, + retention_healthy: true, + engagement_healthy: true, + age: true, + minimum_age: 0, + health_score: { + avg_nonnew_participators: 0, + avg_nonnew_communicators: 0, + num_intentful_joiners: 0, + perc_ret_w1_intentful: 0 + }, + minimum_size: 0 }); }); diff --git a/src/api/routes/ping.ts b/src/api/routes/ping.ts index 3c1da2c3..5f1b0174 100644 --- a/src/api/routes/ping.ts +++ b/src/api/routes/ping.ts @@ -1,6 +1,6 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; import { Config } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router = Router(); @@ -18,8 +18,8 @@ router.get("/", route({}), (req: Request, res: Response) => { correspondenceUserID: general.correspondenceUserID, frontPage: general.frontPage, - tosPage: general.tosPage, - }, + tosPage: general.tosPage + } }); }); diff --git a/src/api/routes/policies/instance/domains.ts b/src/api/routes/policies/instance/domains.ts index 20cd07ba..fed0a627 100644 --- a/src/api/routes/policies/instance/domains.ts +++ b/src/api/routes/policies/instance/domains.ts @@ -1,16 +1,15 @@ -import { Router, Request, Response } from "express"; import { route } from "@fosscord/api"; import { Config } from "@fosscord/util"; -import { config } from "dotenv" +import { Request, Response, Router } from "express"; const router = Router(); -router.get("/",route({}), async (req: Request, res: Response) => { - const { cdn, gateway } = Config.get(); - - const IdentityForm = { - cdn: cdn.endpointPublic || process.env.CDN || "http://localhost:3001", - gateway: gateway.endpointPublic || process.env.GATEWAY || "ws://localhost:3002" - }; +router.get("/", route({}), async (req: Request, res: Response) => { + const { cdn, gateway } = Config.get(); + + const IdentityForm = { + cdn: cdn.endpointPublic || process.env.CDN || "http://localhost:3001", + gateway: gateway.endpointPublic || process.env.GATEWAY || "ws://localhost:3002" + }; res.json(IdentityForm); }); diff --git a/src/api/routes/policies/instance/index.ts b/src/api/routes/policies/instance/index.ts index e3da014f..a8ffd285 100644 --- a/src/api/routes/policies/instance/index.ts +++ b/src/api/routes/policies/instance/index.ts @@ -1,10 +1,9 @@ -import { Router, Request, Response } from "express"; import { route } from "@fosscord/api"; import { Config } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router = Router(); - -router.get("/",route({}), async (req: Request, res: Response) => { +router.get("/", route({}), async (req: Request, res: Response) => { const { general } = Config.get(); res.json(general); }); diff --git a/src/api/routes/policies/instance/limits.ts b/src/api/routes/policies/instance/limits.ts index 7de1476b..0d42fc7b 100644 --- a/src/api/routes/policies/instance/limits.ts +++ b/src/api/routes/policies/instance/limits.ts @@ -1,9 +1,9 @@ -import { Router, Request, Response } from "express"; import { route } from "@fosscord/api"; import { Config } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router = Router(); -router.get("/",route({}), async (req: Request, res: Response) => { +router.get("/", route({}), async (req: Request, res: Response) => { const { limits } = Config.get(); res.json(limits); }); diff --git a/src/api/routes/scheduled-maintenances/upcoming_json.ts b/src/api/routes/scheduled-maintenances/upcoming_json.ts index 83092e44..ec4ddc7c 100644 --- a/src/api/routes/scheduled-maintenances/upcoming_json.ts +++ b/src/api/routes/scheduled-maintenances/upcoming_json.ts @@ -1,12 +1,12 @@ -import { Router, Request, Response } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); -router.get("/scheduled-maintenances/upcoming.json",route({}), async (req: Request, res: Response) => { +router.get("/scheduled-maintenances/upcoming.json", route({}), async (req: Request, res: Response) => { res.json({ - "page": {}, - "scheduled_maintenances": {} - }); + page: {}, + scheduled_maintenances: {} + }); }); export default router; diff --git a/src/api/routes/science.ts b/src/api/routes/science.ts index 8556a3ad..cb01e576 100644 --- a/src/api/routes/science.ts +++ b/src/api/routes/science.ts @@ -1,5 +1,5 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/stage-instances.ts b/src/api/routes/stage-instances.ts index 411e95bf..8e407184 100644 --- a/src/api/routes/stage-instances.ts +++ b/src/api/routes/stage-instances.ts @@ -1,5 +1,5 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/sticker-packs/index.ts b/src/api/routes/sticker-packs/index.ts index e6560d12..dddc7f70 100644 --- a/src/api/routes/sticker-packs/index.ts +++ b/src/api/routes/sticker-packs/index.ts @@ -1,6 +1,6 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; import { StickerPack } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/stickers/#sticker_id/index.ts b/src/api/routes/stickers/#sticker_id/index.ts index b484a7a1..16eb2059 100644 --- a/src/api/routes/stickers/#sticker_id/index.ts +++ b/src/api/routes/stickers/#sticker_id/index.ts @@ -1,6 +1,6 @@ -import { Sticker } from "@fosscord/util"; -import { Router, Request, Response } from "express"; import { route } from "@fosscord/api"; +import { Sticker } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router = Router(); router.get("/", route({}), async (req: Request, res: Response) => { diff --git a/src/api/routes/stop.ts b/src/api/routes/stop.ts index 7f8b78ba..fb77b4f3 100644 --- a/src/api/routes/stop.ts +++ b/src/api/routes/stop.ts @@ -1,22 +1,21 @@ -import { Router, Request, Response } from "express"; import { route } from "@fosscord/api"; import { User } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); router.post("/", route({}), async (req: Request, res: Response) => { //EXPERIMENTAL: have an "OPERATOR" platform permission implemented for this API route const user = await User.findOneOrFail({ where: { id: req.user_id }, select: ["rights"] }); - if((Number(user.rights) << Number(0))%Number(2)==Number(1)) { + if ((Number(user.rights) << Number(0)) % Number(2) == Number(1)) { console.log("user that POSTed to the API was ALLOWED"); console.log(user.rights); - res.sendStatus(200) - process.kill(process.pid, 'SIGTERM') - } - else { + res.sendStatus(200); + process.kill(process.pid, "SIGTERM"); + } else { console.log("operation failed"); console.log(user.rights); - res.sendStatus(403) + res.sendStatus(403); } }); diff --git a/src/api/routes/store/published-listings/applications.ts b/src/api/routes/store/published-listings/applications.ts index 060a4c3d..3d0f7998 100644 --- a/src/api/routes/store/published-listings/applications.ts +++ b/src/api/routes/store/published-listings/applications.ts @@ -1,5 +1,5 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/store/published-listings/applications/#id/subscription-plans.ts b/src/api/routes/store/published-listings/applications/#id/subscription-plans.ts index 54151ae5..86fce75d 100644 --- a/src/api/routes/store/published-listings/applications/#id/subscription-plans.ts +++ b/src/api/routes/store/published-listings/applications/#id/subscription-plans.ts @@ -1,5 +1,5 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/store/published-listings/skus.ts b/src/api/routes/store/published-listings/skus.ts index 060a4c3d..3d0f7998 100644 --- a/src/api/routes/store/published-listings/skus.ts +++ b/src/api/routes/store/published-listings/skus.ts @@ -1,5 +1,5 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/store/published-listings/skus/#sku_id/subscription-plans.ts b/src/api/routes/store/published-listings/skus/#sku_id/subscription-plans.ts index e7f44ded..fdd775b7 100644 --- a/src/api/routes/store/published-listings/skus/#sku_id/subscription-plans.ts +++ b/src/api/routes/store/published-listings/skus/#sku_id/subscription-plans.ts @@ -1,5 +1,5 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/teams.ts b/src/api/routes/teams.ts index 7ce3abcb..9aa1c10e 100644 --- a/src/api/routes/teams.ts +++ b/src/api/routes/teams.ts @@ -1,5 +1,5 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/track.ts b/src/api/routes/track.ts index 8556a3ad..cb01e576 100644 --- a/src/api/routes/track.ts +++ b/src/api/routes/track.ts @@ -1,5 +1,5 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/updates.ts b/src/api/routes/updates.ts index a24e94c1..6019371e 100644 --- a/src/api/routes/updates.ts +++ b/src/api/routes/updates.ts @@ -1,20 +1,20 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; import { Config, Release } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router = Router(); router.get("/", route({}), async (req: Request, res: Response) => { const { client } = Config.get(); - const release = await Release.findOneOrFail({ where: { name: client.releases.upstreamVersion } }) + const release = await Release.findOneOrFail({ where: { name: client.releases.upstreamVersion } }); res.json({ - name: release.name, - pub_date: release.pub_date, - url: release.url, - notes: release.notes - }); + name: release.name, + pub_date: release.pub_date, + url: release.url, + notes: release.notes + }); }); export default router; diff --git a/src/api/routes/users/#id/index.ts b/src/api/routes/users/#id/index.ts index bdb1060f..e33e5695 100644 --- a/src/api/routes/users/#id/index.ts +++ b/src/api/routes/users/#id/index.ts @@ -1,6 +1,6 @@ -import { Router, Request, Response } from "express"; -import { User } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { User } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/users/#id/profile.ts b/src/api/routes/users/#id/profile.ts index 7a995a8c..27717c79 100644 --- a/src/api/routes/users/#id/profile.ts +++ b/src/api/routes/users/#id/profile.ts @@ -1,6 +1,6 @@ -import { Router, Request, Response } from "express"; -import { PublicConnectedAccount, PublicUser, User, UserPublic, Member } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { Member, PublicConnectedAccount, User, UserPublic } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); @@ -17,22 +17,22 @@ router.get("/", route({ test: { response: { body: "UserProfileResponse" } } }), let mutual_guilds: object[] = []; let premium_guild_since; - const requested_member = await Member.find( { where: { id: req.params.id, } }) - const self_member = await Member.find( { where: { id: req.user_id, } }) + const requested_member = await Member.find({ where: { id: req.params.id } }); + const self_member = await Member.find({ where: { id: req.user_id } }); - for(const rmem of requested_member) { - if(rmem.premium_since) { - if(premium_guild_since){ - if(premium_guild_since > rmem.premium_since) { + for (const rmem of requested_member) { + if (rmem.premium_since) { + if (premium_guild_since) { + if (premium_guild_since > rmem.premium_since) { premium_guild_since = rmem.premium_since; } } else { premium_guild_since = rmem.premium_since; } } - for(const smem of self_member) { + for (const smem of self_member) { if (smem.guild_id === rmem.guild_id) { - mutual_guilds.push({id: rmem.guild_id, nick: rmem.nick}) + mutual_guilds.push({ id: rmem.guild_id, nick: rmem.nick }); } } } diff --git a/src/api/routes/users/#id/relationships.ts b/src/api/routes/users/#id/relationships.ts index 61655c25..9b7e3402 100644 --- a/src/api/routes/users/#id/relationships.ts +++ b/src/api/routes/users/#id/relationships.ts @@ -1,41 +1,46 @@ -import { Router, Request, Response } from "express"; -import { User } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { User } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); export interface UserRelationsResponse { object: { - id?: string, - username?: string, - avatar?: string, - discriminator?: string, - public_flags?: number - } + id?: string; + username?: string; + avatar?: string; + discriminator?: string; + public_flags?: number; + }; } - router.get("/", route({ test: { response: { body: "UserRelationsResponse" } } }), async (req: Request, res: Response) => { let mutual_relations: object[] = []; - const requested_relations = await User.findOneOrFail({ + const requested_relations = await User.findOneOrFail({ where: { id: req.params.id }, relations: ["relationships"] }); - const self_relations = await User.findOneOrFail({ + const self_relations = await User.findOneOrFail({ where: { id: req.user_id }, relations: ["relationships"] }); - - for(const rmem of requested_relations.relationships) { - for(const smem of self_relations.relationships) - if (rmem.to_id === smem.to_id && rmem.type === 1 && rmem.to_id !== req.user_id) { - let relation_user = await User.getPublicUser(rmem.to_id) - mutual_relations.push({id: relation_user.id, username: relation_user.username, avatar: relation_user.avatar, discriminator: relation_user.discriminator, public_flags: relation_user.public_flags}) - } + for (const rmem of requested_relations.relationships) { + for (const smem of self_relations.relationships) + if (rmem.to_id === smem.to_id && rmem.type === 1 && rmem.to_id !== req.user_id) { + let relation_user = await User.getPublicUser(rmem.to_id); + + mutual_relations.push({ + id: relation_user.id, + username: relation_user.username, + avatar: relation_user.avatar, + discriminator: relation_user.discriminator, + public_flags: relation_user.public_flags + }); + } } - res.json(mutual_relations) + res.json(mutual_relations); }); export default router; diff --git a/src/api/routes/users/@me/activities/statistics/applications.ts b/src/api/routes/users/@me/activities/statistics/applications.ts index 014df8af..ba359b47 100644 --- a/src/api/routes/users/@me/activities/statistics/applications.ts +++ b/src/api/routes/users/@me/activities/statistics/applications.ts @@ -1,5 +1,5 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/users/@me/affinities/guilds.ts b/src/api/routes/users/@me/affinities/guilds.ts index 8d744744..e733910f 100644 --- a/src/api/routes/users/@me/affinities/guilds.ts +++ b/src/api/routes/users/@me/affinities/guilds.ts @@ -1,5 +1,5 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/users/@me/affinities/users.ts b/src/api/routes/users/@me/affinities/users.ts index 6d4e4991..758bedc3 100644 --- a/src/api/routes/users/@me/affinities/users.ts +++ b/src/api/routes/users/@me/affinities/users.ts @@ -1,5 +1,5 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/users/@me/applications/#app_id/entitlements.ts b/src/api/routes/users/@me/applications/#app_id/entitlements.ts index 411e95bf..8e407184 100644 --- a/src/api/routes/users/@me/applications/#app_id/entitlements.ts +++ b/src/api/routes/users/@me/applications/#app_id/entitlements.ts @@ -1,5 +1,5 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/users/@me/billing/country-code.ts b/src/api/routes/users/@me/billing/country-code.ts index 33d40796..72601f42 100644 --- a/src/api/routes/users/@me/billing/country-code.ts +++ b/src/api/routes/users/@me/billing/country-code.ts @@ -1,5 +1,5 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/users/@me/billing/payment-sources.ts b/src/api/routes/users/@me/billing/payment-sources.ts index 014df8af..ba359b47 100644 --- a/src/api/routes/users/@me/billing/payment-sources.ts +++ b/src/api/routes/users/@me/billing/payment-sources.ts @@ -1,5 +1,5 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/users/@me/billing/subscriptions.ts b/src/api/routes/users/@me/billing/subscriptions.ts index 411e95bf..8e407184 100644 --- a/src/api/routes/users/@me/billing/subscriptions.ts +++ b/src/api/routes/users/@me/billing/subscriptions.ts @@ -1,5 +1,5 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/users/@me/channels.ts b/src/api/routes/users/@me/channels.ts index ad483529..c17275ec 100644 --- a/src/api/routes/users/@me/channels.ts +++ b/src/api/routes/users/@me/channels.ts @@ -1,6 +1,6 @@ -import { Request, Response, Router } from "express"; -import { Recipient, DmChannelDTO, Channel, DmChannelCreateSchema } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { Channel, DmChannelCreateSchema, DmChannelDTO, Recipient } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/users/@me/connections.ts b/src/api/routes/users/@me/connections.ts index 411e95bf..8e407184 100644 --- a/src/api/routes/users/@me/connections.ts +++ b/src/api/routes/users/@me/connections.ts @@ -1,5 +1,5 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/users/@me/devices.ts b/src/api/routes/users/@me/devices.ts index 8556a3ad..cb01e576 100644 --- a/src/api/routes/users/@me/devices.ts +++ b/src/api/routes/users/@me/devices.ts @@ -1,5 +1,5 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/users/@me/disable.ts b/src/api/routes/users/@me/disable.ts index 3a1d48b8..05976908 100644 --- a/src/api/routes/users/@me/disable.ts +++ b/src/api/routes/users/@me/disable.ts @@ -1,6 +1,6 @@ +import { route } from "@fosscord/api"; import { User } from "@fosscord/util"; import { Request, Response, Router } from "express"; -import { route } from "@fosscord/api"; let bcrypt: any; try { diff --git a/src/api/routes/users/@me/email-settings.ts b/src/api/routes/users/@me/email-settings.ts index 3114984e..28d0864a 100644 --- a/src/api/routes/users/@me/email-settings.ts +++ b/src/api/routes/users/@me/email-settings.ts @@ -1,5 +1,5 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/users/@me/entitlements.ts b/src/api/routes/users/@me/entitlements.ts index 341e2b4c..7aaa5d7c 100644 --- a/src/api/routes/users/@me/entitlements.ts +++ b/src/api/routes/users/@me/entitlements.ts @@ -1,5 +1,5 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/users/@me/guilds.ts b/src/api/routes/users/@me/guilds.ts index 4d4fccd4..5141aa3d 100644 --- a/src/api/routes/users/@me/guilds.ts +++ b/src/api/routes/users/@me/guilds.ts @@ -1,7 +1,6 @@ -import { Router, Request, Response } from "express"; -import { Guild, Member, User, GuildDeleteEvent, GuildMemberRemoveEvent, emitEvent, Config } from "@fosscord/util"; -import { HTTPError } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { Config, emitEvent, Guild, GuildDeleteEvent, GuildMemberRemoveEvent, HTTPError, Member, User } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/routes/users/@me/guilds/premium/subscription-slots.ts b/src/api/routes/users/@me/guilds/premium/subscription-slots.ts index 014df8af..ba359b47 100644 --- a/src/api/routes/users/@me/guilds/premium/subscription-slots.ts +++ b/src/api/routes/users/@me/guilds/premium/subscription-slots.ts @@ -1,5 +1,5 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/users/@me/index.ts b/src/api/routes/users/@me/index.ts index 4421d54f..fcb0a9df 100644 --- a/src/api/routes/users/@me/index.ts +++ b/src/api/routes/users/@me/index.ts @@ -53,17 +53,17 @@ router.patch("/", route({ body: "UserModifySchema" }), async (req: Request, res: } user.data.hash = await bcrypt.hash(body.new_password, 12); user.data.valid_tokens_since = new Date(); - token = await generateToken(user.id) as string; + token = (await generateToken(user.id)) as string; } - if(body.username){ - let check_username = body?.username?.replace(/\s/g, ''); - if(!check_username) { - throw FieldErrors({ - username: { code: "BASE_TYPE_REQUIRED", message: req.t("common:field.BASE_TYPE_REQUIRED") } - }); - } - } + if (body.username) { + let check_username = body?.username?.replace(/\s/g, ""); + if (!check_username) { + throw FieldErrors({ + username: { code: "BASE_TYPE_REQUIRED", message: req.t("common:field.BASE_TYPE_REQUIRED") } + }); + } + } user = OrmUtils.mergeDeep(user, body); await user.save(); @@ -77,7 +77,7 @@ router.patch("/", route({ body: "UserModifySchema" }), async (req: Request, res: user_id: req.user_id, data: user } as UserUpdateEvent); - + res.json({ ...user, token diff --git a/src/api/routes/users/@me/library.ts b/src/api/routes/users/@me/library.ts index 7ac13bae..0aea02a0 100644 --- a/src/api/routes/users/@me/library.ts +++ b/src/api/routes/users/@me/library.ts @@ -1,5 +1,5 @@ -import { Router, Response, Request } from "express"; import { route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/users/@me/mfa/codes.ts b/src/api/routes/users/@me/mfa/codes.ts index 8d90f993..c62581cc 100644 --- a/src/api/routes/users/@me/mfa/codes.ts +++ b/src/api/routes/users/@me/mfa/codes.ts @@ -19,25 +19,21 @@ router.post("/", route({ body: "MfaCodesSchema" }), async (req: Request, res: Re const user = await User.findOneOrFail({ where: { id: req.user_id }, select: ["data"] }); - if (!await bcrypt.compare(password, user.data.hash || "")) { + if (!(await bcrypt.compare(password, user.data.hash || ""))) { throw FieldErrors({ password: { message: req.t("auth:login.INVALID_PASSWORD"), code: "INVALID_PASSWORD" } }); } var codes: BackupCode[]; if (regenerate && Config.get().security.twoFactor.generateBackupCodes) { - await BackupCode.update( - { user: { id: req.user_id } }, - { expired: true } - ); + await BackupCode.update({ user: { id: req.user_id } }, { expired: true }); codes = generateMfaBackupCodes(req.user_id); - await Promise.all(codes.map(x => x.save())); - } - else { + await Promise.all(codes.map((x) => x.save())); + } else { codes = await BackupCode.find({ where: { user: { - id: req.user_id, + id: req.user_id }, expired: false } @@ -45,8 +41,8 @@ router.post("/", route({ body: "MfaCodesSchema" }), async (req: Request, res: Re } return res.json({ - backup_codes: codes.map(x => ({ ...x, expired: undefined })), - }) + backup_codes: codes.map((x) => ({ ...x, expired: undefined })) + }); }); export default router; diff --git a/src/api/routes/users/@me/mfa/totp/disable.ts b/src/api/routes/users/@me/mfa/totp/disable.ts index 2fe9355c..6bc9a5c7 100644 --- a/src/api/routes/users/@me/mfa/totp/disable.ts +++ b/src/api/routes/users/@me/mfa/totp/disable.ts @@ -1,8 +1,8 @@ -import { Router, Request, Response } from "express"; import { route } from "@fosscord/api"; -import { verifyToken } from 'node-2fa'; +import { BackupCode, generateToken, TotpDisableSchema, User } from "@fosscord/util"; +import { Request, Response, Router } from "express"; import { HTTPError } from "lambert-server"; -import { User, generateToken, BackupCode, TotpDisableSchema } from "@fosscord/util"; +import { verifyToken } from "node-2fa"; const router = Router(); @@ -14,28 +14,27 @@ router.post("/", route({ body: "TotpDisableSchema" }), async (req: Request, res: const backup = await BackupCode.findOne({ where: { code: body.code } }); if (!backup) { const ret = verifyToken(user.totp_secret!, body.code); - if (!ret || ret.delta != 0) - throw new HTTPError(req.t("auth:login.INVALID_TOTP_CODE"), 60008); + if (!ret || ret.delta != 0) throw new HTTPError(req.t("auth:login.INVALID_TOTP_CODE"), 60008); } await User.update( { id: req.user_id }, { mfa_enabled: false, - totp_secret: "", - }, + totp_secret: "" + } ); await BackupCode.update( { user: { id: req.user_id } }, { - expired: true, + expired: true } ); return res.json({ - token: await generateToken(user.id), + token: await generateToken(user.id) }); }); -export default router; \ No newline at end of file +export default router; diff --git a/src/api/routes/users/@me/mfa/totp/enable.ts b/src/api/routes/users/@me/mfa/totp/enable.ts index a38a133a..f3a73c28 100644 --- a/src/api/routes/users/@me/mfa/totp/enable.ts +++ b/src/api/routes/users/@me/mfa/totp/enable.ts @@ -1,8 +1,8 @@ +import { route } from "@fosscord/api"; import { BackupCode, Config, generateMfaBackupCodes, generateToken, TotpEnableSchema, User } from "@fosscord/util"; import { Request, Response, Router } from "express"; import { HTTPError } from "lambert-server"; -import { verifyToken } from 'node-2fa'; -import { route } from '@fosscord/api'; +import { verifyToken } from "node-2fa"; let bcrypt: any; try { @@ -21,34 +21,28 @@ router.post("/", route({ body: "TotpEnableSchema" }), async (req: Request, res: // TODO: Are guests allowed to enable 2fa? if (user.data.hash) { - if (!await bcrypt.compare(body.password, user.data.hash)) { + if (!(await bcrypt.compare(body.password, user.data.hash))) { throw new HTTPError(req.t("auth:login.INVALID_PASSWORD")); } } - if (!body.secret) - throw new HTTPError(req.t("auth:login.INVALID_TOTP_SECRET"), 60005); + if (!body.secret) throw new HTTPError(req.t("auth:login.INVALID_TOTP_SECRET"), 60005); - if (!body.code) - throw new HTTPError(req.t("auth:login.INVALID_TOTP_CODE"), 60008); + if (!body.code) throw new HTTPError(req.t("auth:login.INVALID_TOTP_CODE"), 60008); - if (verifyToken(body.secret, body.code)?.delta != 0) - throw new HTTPError(req.t("auth:login.INVALID_TOTP_CODE"), 60008); + if (verifyToken(body.secret, body.code)?.delta != 0) throw new HTTPError(req.t("auth:login.INVALID_TOTP_CODE"), 60008); let backup_codes: BackupCode[] = []; if (Config.get().security.twoFactor.generateBackupCodes) { backup_codes = generateMfaBackupCodes(req.user_id); - await Promise.all(backup_codes.map(x => x.save())); + await Promise.all(backup_codes.map((x) => x.save())); } - await User.update( - { id: req.user_id }, - { mfa_enabled: true, totp_secret: body.secret } - ); + await User.update({ id: req.user_id }, { mfa_enabled: true, totp_secret: body.secret }); res.send({ token: await generateToken(user.id), - backup_codes: backup_codes.map(x => ({ ...x, expired: undefined })), + backup_codes: backup_codes.map((x) => ({ ...x, expired: undefined })) }); }); diff --git a/src/api/routes/users/@me/notes.ts b/src/api/routes/users/@me/notes.ts index f938f088..fc207401 100644 --- a/src/api/routes/users/@me/notes.ts +++ b/src/api/routes/users/@me/notes.ts @@ -1,6 +1,6 @@ -import { Request, Response, Router } from "express"; import { route } from "@fosscord/api"; -import { User, Note, emitEvent, Snowflake } from "@fosscord/util"; +import { emitEvent, Note, Snowflake, User } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router: Router = Router(); @@ -10,38 +10,31 @@ router.get("/:id", route({}), async (req: Request, res: Response) => { const note = await Note.findOneOrFail({ where: { owner: { id: req.user_id }, - target: { id: id }, + target: { id: id } } }); return res.json({ note: note?.content, note_user_id: id, - user_id: req.user_id, + user_id: req.user_id }); }); router.put("/:id", route({}), async (req: Request, res: Response) => { const { id } = req.params; const owner = await User.findOneOrFail({ where: { id: req.user_id } }); - const target = await User.findOneOrFail({ where: { id: id } }); //if noted user does not exist throw + const target = await User.findOneOrFail({ where: { id: id } }); //if noted user does not exist throw const { note } = req.body; if (note && note.length) { // upsert a note if (await Note.findOne({ where: { owner: { id: owner.id }, target: { id: target.id } } })) { - Note.update( - { owner: { id: owner.id }, target: { id: target.id } }, - { owner, target, content: note } - ); + Note.update({ owner: { id: owner.id }, target: { id: target.id } }, { owner, target, content: note }); + } else { + Note.insert({ id: Snowflake.generate(), owner, target, content: note }); } - else { - Note.insert( - { id: Snowflake.generate(), owner, target, content: note } - ); - } - } - else { + } else { await Note.delete({ owner: { id: owner.id }, target: { id: target.id } }); } @@ -51,7 +44,7 @@ router.put("/:id", route({}), async (req: Request, res: Response) => { note: note, id: target.id }, - user_id: owner.id, + user_id: owner.id }); return res.status(204); diff --git a/src/api/routes/users/@me/relationships.ts b/src/api/routes/users/@me/relationships.ts index f7464b99..8267c142 100644 --- a/src/api/routes/users/@me/relationships.ts +++ b/src/api/routes/users/@me/relationships.ts @@ -1,18 +1,18 @@ +import { route } from "@fosscord/api"; import { - RelationshipAddEvent, - User, - PublicUserProjection, - RelationshipType, - RelationshipRemoveEvent, + Config, + DiscordApiErrors, emitEvent, + HTTPError, + OrmUtils, + PublicUserProjection, Relationship, - Config + RelationshipAddEvent, + RelationshipRemoveEvent, + RelationshipType, + User } from "@fosscord/util"; -import { Router, Response, Request } from "express"; -import { HTTPError } from "@fosscord/util"; -import { DiscordApiErrors } from "@fosscord/util"; -import { route } from "@fosscord/api"; -import { OrmUtils } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router = Router(); @@ -42,7 +42,11 @@ router.put("/:id", route({ body: "RelationshipPutSchema" }), async (req: Request return await updateRelationship( req, res, - await User.findOneOrFail({ where: { id: req.params.id }, relations: ["relationships", "relationships.to"], select: userProjection }), + await User.findOneOrFail({ + where: { id: req.params.id }, + relations: ["relationships", "relationships.to"], + select: userProjection + }), req.body.type ?? RelationshipType.friends ); }); @@ -132,7 +136,9 @@ async function updateRelationship(req: Request, res: Response, friend: User, typ relationship.type = RelationshipType.blocked; await relationship.save(); } else { - relationship = await (OrmUtils.mergeDeep(new Relationship(), { to_id: id, type: RelationshipType.blocked, from_id: req.user_id }) as Relationship).save(); + relationship = await ( + OrmUtils.mergeDeep(new Relationship(), { to_id: id, type: RelationshipType.blocked, from_id: req.user_id }) as Relationship + ).save(); } if (friendRequest && friendRequest.type !== RelationshipType.blocked) { @@ -158,7 +164,12 @@ async function updateRelationship(req: Request, res: Response, friend: User, typ const { maxFriends } = Config.get().limits.user; if (user.relationships.length >= maxFriends) throw DiscordApiErrors.MAXIMUM_FRIENDS.withParams(maxFriends); - let incoming_relationship = OrmUtils.mergeDeep(new Relationship(), { nickname: undefined, type: RelationshipType.incoming, to: user, from: friend }); + let incoming_relationship = OrmUtils.mergeDeep(new Relationship(), { + nickname: undefined, + type: RelationshipType.incoming, + to: user, + from: friend + }); let outgoing_relationship = OrmUtils.mergeDeep(new Relationship(), { nickname: undefined, type: RelationshipType.outgoing, diff --git a/src/api/routes/users/@me/settings.ts b/src/api/routes/users/@me/settings.ts index 7578d36e..e276a22a 100644 --- a/src/api/routes/users/@me/settings.ts +++ b/src/api/routes/users/@me/settings.ts @@ -1,6 +1,6 @@ -import { Router, Response, Request } from "express"; -import { User, UserSettings } from "@fosscord/util"; import { route } from "@fosscord/api"; +import { User, UserSettings } from "@fosscord/util"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/api/routes/voice/regions.ts b/src/api/routes/voice/regions.ts index 4de304ee..eacdcf11 100644 --- a/src/api/routes/voice/regions.ts +++ b/src/api/routes/voice/regions.ts @@ -1,6 +1,5 @@ -import { Router, Request, Response } from "express"; -import { getIpAdress, route } from "@fosscord/api"; -import { getVoiceRegions } from "@fosscord/api"; +import { getIpAdress, getVoiceRegions, route } from "@fosscord/api"; +import { Request, Response, Router } from "express"; const router: Router = Router(); diff --git a/src/api/start.ts b/src/api/start.ts index 9ba198e7..c407484d 100644 --- a/src/api/start.ts +++ b/src/api/start.ts @@ -1,16 +1,16 @@ process.on("uncaughtException", console.error); process.on("unhandledRejection", console.error); -import { config } from "dotenv"; -config(); -import { FosscordServer } from "./Server"; import cluster from "cluster"; +import { config } from "dotenv"; import os from "os"; +import { FosscordServer } from "./Server"; +config(); let cores = 1; try { cores = Number(process.env.THREADS) || os.cpus().length; } catch { - console.log("[API] Failed to get thread count! Using 1...") + console.log("[API] Failed to get thread count! Using 1..."); } if (cluster.isMaster && process.env.NODE_ENV == "production") { diff --git a/src/api/util/entities/AssetCacheItem.ts b/src/api/util/entities/AssetCacheItem.ts index 160dece6..958d5a61 100644 --- a/src/api/util/entities/AssetCacheItem.ts +++ b/src/api/util/entities/AssetCacheItem.ts @@ -1,3 +1,3 @@ export class AssetCacheItem { constructor(public Key: string, public FilePath: string = "", public Headers: any = null as any) {} -} \ No newline at end of file +} diff --git a/src/api/util/handlers/Instance.ts b/src/api/util/handlers/Instance.ts index 7c337270..e03c9488 100644 --- a/src/api/util/handlers/Instance.ts +++ b/src/api/util/handlers/Instance.ts @@ -1,5 +1,4 @@ import { Config, Guild, Session } from "@fosscord/util"; -import { createQueryBuilder } from "typeorm"; export async function initInstance() { // TODO: clean up database and delete tombstone data @@ -10,7 +9,7 @@ export async function initInstance() { const { autoJoin } = Config.get().guild; if (autoJoin.enabled && !autoJoin.guilds?.length) { - let guild = await Guild.findOne({where: {}, order: {id: "ASC"}}); + let guild = await Guild.findOne({ where: {}, order: { id: "ASC" } }); if (guild) { // @ts-ignore await Config.set({ guild: { autoJoin: { guilds: [guild.id] } } }); diff --git a/src/api/util/handlers/Message.ts b/src/api/util/handlers/Message.ts index ff5ece75..d760d27c 100644 --- a/src/api/util/handlers/Message.ts +++ b/src/api/util/handlers/Message.ts @@ -1,32 +1,31 @@ import { + Application, + Attachment, Channel, + CHANNEL_MENTION, + Config, Embed, emitEvent, + EVERYONE_MENTION, + getPermission, + getRights, Guild, + HERE_MENTION, + HTTPError, Message, MessageCreateEvent, + MessageCreateSchema, + MessageType, MessageUpdateEvent, - getPermission, - getRights, - CHANNEL_MENTION, - Snowflake, - USER_MENTION, - ROLE_MENTION, + OrmUtils, Role, - EVERYONE_MENTION, - HERE_MENTION, - MessageType, + ROLE_MENTION, User, - Application, - Webhook, - Attachment, - Config, - MessageCreateSchema, + USER_MENTION, + Webhook } from "@fosscord/util"; -import { HTTPError } from "@fosscord/util"; -import fetch from "node-fetch"; import cheerio from "cheerio"; -import { OrmUtils } from "@fosscord/util"; +import fetch from "node-fetch"; const allow_empty = false; // TODO: check webhook, application, system author, stickers @@ -61,21 +60,21 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> { }); if (message.content && message.content.length > Config.get().limits.message.maxCharacters) { - throw new HTTPError("Content length over max character limit") + throw new HTTPError("Content length over max character limit"); } if (opts.author_id) { message.author = await User.getPublicUser(opts.author_id); const rights = await getRights(opts.author_id); rights.hasThrow("SEND_MESSAGES"); - } + } if (opts.application_id) { message.application = await Application.findOneOrFail({ where: { id: opts.application_id } }); } if (opts.webhook_id) { message.webhook = await Webhook.findOneOrFail({ where: { id: opts.webhook_id } }); } - + const permission = await getPermission(opts.author_id, channel.guild_id, opts.channel_id); permission.hasThrow("SEND_MESSAGES"); if (permission.cache.member) { @@ -89,8 +88,10 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> { if (message.guild_id !== null) { const guild = await Guild.findOneOrFail({ where: { id: channel.guild_id } }); if (!guild.features.includes("CROSS_CHANNEL_REPLIES")) { - if (opts.message_reference.guild_id !== channel.guild_id) throw new HTTPError("You can only reference messages from this guild"); - if (opts.message_reference.channel_id !== opts.channel_id) throw new HTTPError("You can only reference messages from this channel"); + if (opts.message_reference.guild_id !== channel.guild_id) + throw new HTTPError("You can only reference messages from this guild"); + if (opts.message_reference.channel_id !== opts.channel_id) + throw new HTTPError("You can only reference messages from this channel"); } } /** Q: should be checked if the referenced message exists? ANSWER: NO @@ -100,7 +101,7 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> { } // TODO: stickers/activity - if (!allow_empty && (!opts.content && !opts.embeds?.length && !opts.attachments?.length && !opts.sticker_ids?.length)) { + if (!allow_empty && !opts.content && !opts.embeds?.length && !opts.attachments?.length && !opts.sticker_ids?.length) { throw new HTTPError("Empty messages are not allowed", 50006); } @@ -110,7 +111,8 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> { let mention_user_ids = [] as string[]; let mention_everyone = false; - if (content) { // TODO: explicit-only mentions + if (content) { + // TODO: explicit-only mentions message.content = content.trim(); for (const [_, mention] of content.matchAll(CHANNEL_MENTION)) { if (!mention_channel_ids.includes(mention)) mention_channel_ids.push(mention); @@ -158,7 +160,7 @@ export async function postHandleMessage(message: Message) { try { const request = await fetch(link, { ...DEFAULT_FETCH_OPTIONS, - size: Config.get().limits.message.maxEmbedDownloadSize, + size: Config.get().limits.message.maxEmbedDownloadSize }); const text = await request.text(); diff --git a/src/api/util/handlers/route.ts b/src/api/util/handlers/route.ts index 71e14955..d43ae103 100644 --- a/src/api/util/handlers/route.ts +++ b/src/api/util/handlers/route.ts @@ -1,8 +1,6 @@ import { DiscordApiErrors, EVENT, - Event, - EventData, FieldErrors, FosscordApiErrors, getPermission, @@ -12,14 +10,14 @@ import { RightResolvable, Rights } from "@fosscord/util"; +import Ajv from "ajv"; +import addFormats from "ajv-formats"; +import { AnyValidateFunction } from "ajv/dist/core"; import { NextFunction, Request, Response } from "express"; import fs from "fs"; import path from "path"; -import Ajv from "ajv"; -import { AnyValidateFunction } from "ajv/dist/core"; -import addFormats from "ajv-formats"; -const SchemaPath = path.join(__dirname, "..", "..", "..","..", "assets", "schemas.json"); +const SchemaPath = path.join(__dirname, "..", "..", "..", "..", "assets", "schemas.json"); const schemas = JSON.parse(fs.readFileSync(SchemaPath, { encoding: "utf8" })); export const ajv = new Ajv({ @@ -117,10 +115,10 @@ export function route(opts: RouteOptions) { const valid = validate(normalizeBody(req.body)); if (!valid) { const fields: Record<string, { code?: string; message: string }> = {}; - if(process.env.LOG_INVALID_BODY) { - console.log(`Got invalid request: ${req.method} ${req.originalUrl}`) - console.log(req.body) - validate.errors?.forEach(x => console.log(x.params)) + if (process.env.LOG_INVALID_BODY) { + console.log(`Got invalid request: ${req.method} ${req.originalUrl}`); + console.log(req.body); + validate.errors?.forEach((x) => console.log(x.params)); } validate.errors?.forEach((x) => (fields[x.instancePath.slice(1)] = { code: x.keyword, message: x.message || "" })); throw FieldErrors(fields); diff --git a/src/api/util/index.ts b/src/api/util/index.ts index b3c7559f..76db5fd0 100644 --- a/src/api/util/index.ts +++ b/src/api/util/index.ts @@ -6,4 +6,4 @@ export * from "./utility/Base64"; export * from "./utility/ipAddress"; export * from "./utility/passwordStrength"; export * from "./utility/RandomInviteID"; -export * from "./utility/String"; \ No newline at end of file +export * from "./utility/String"; diff --git a/src/api/util/utility/RandomInviteID.ts b/src/api/util/utility/RandomInviteID.ts index 7ea344e0..feebfd3d 100644 --- a/src/api/util/utility/RandomInviteID.ts +++ b/src/api/util/utility/RandomInviteID.ts @@ -22,11 +22,10 @@ export function snowflakeBasedInvite() { // snowflakes hold ~10.75 characters worth of entropy; // safe to generate a 8-char invite out of them let str = ""; - for (let i=0; i < 10; i++) { - + for (let i = 0; i < 10; i++) { str.concat(chars.charAt(Number(snowflake % base))); snowflake = snowflake / base; } - - return str.substr(3,8).split("").reverse().join(""); + + return str.substr(3, 8).split("").reverse().join(""); } diff --git a/src/api/util/utility/String.ts b/src/api/util/utility/String.ts index 982b7e11..a2e491e4 100644 --- a/src/api/util/utility/String.ts +++ b/src/api/util/utility/String.ts @@ -1,6 +1,6 @@ +import { FieldErrors } from "@fosscord/util"; import { Request } from "express"; import { ntob } from "./Base64"; -import { FieldErrors } from "@fosscord/util"; export function checkLength(str: string, min: number, max: number, key: string, req: Request) { if (str.length < min || str.length > max) { diff --git a/src/api/util/utility/passwordStrength.ts b/src/api/util/utility/passwordStrength.ts index 8eca63b8..ff83d3df 100644 --- a/src/api/util/utility/passwordStrength.ts +++ b/src/api/util/utility/passwordStrength.ts @@ -44,16 +44,16 @@ export function checkPassword(password: string): number { if (password.length == password.count(reNUMBER) || password.length === password.count(reUPPERCASELETTER)) { strength = 0; } - + let entropyMap: { [key: string]: number } = {}; for (let i = 0; i < password.length; i++) { if (entropyMap[password[i]]) entropyMap[password[i]]++; else entropyMap[password[i]] = 1; } - + let entropies = Object.values(entropyMap); - - entropies.map(x => (x / entropyMap.length)); - strength += entropies.reduceRight((a: number, x: number) => a - (x * Math.log2(x))) / Math.log2(password.length); + + entropies.map((x) => x / entropyMap.length); + strength += entropies.reduceRight((a: number, x: number) => a - x * Math.log2(x)) / Math.log2(password.length); return strength; } diff --git a/src/cdn/Server.ts b/src/cdn/Server.ts index b27d3321..ec5edc68 100644 --- a/src/cdn/Server.ts +++ b/src/cdn/Server.ts @@ -1,9 +1,9 @@ -import { Server, ServerOptions } from "lambert-server"; import { Config, getOrInitialiseDatabase, registerRoutes } from "@fosscord/util"; +import bodyParser from "body-parser"; +import { Server, ServerOptions } from "lambert-server"; import path from "path"; import avatarsRoute from "./routes/avatars"; import iconsRoute from "./routes/role-icons"; -import bodyParser from "body-parser"; export interface CDNServerOptions extends ServerOptions {} @@ -24,14 +24,8 @@ export class CDNServer extends Server { "Content-security-policy", "default-src * data: blob: filesystem: about: ws: wss: 'unsafe-inline' 'unsafe-eval'; script-src * data: blob: 'unsafe-inline' 'unsafe-eval'; connect-src * data: blob: 'unsafe-inline'; img-src * data: blob: 'unsafe-inline'; frame-src * data: blob: ; style-src * data: blob: 'unsafe-inline'; font-src * data: blob: 'unsafe-inline';" ); - res.set( - "Access-Control-Allow-Headers", - req.header("Access-Control-Request-Headers") || "*" - ); - res.set( - "Access-Control-Allow-Methods", - req.header("Access-Control-Request-Methods") || "*" - ); + res.set("Access-Control-Allow-Headers", req.header("Access-Control-Request-Headers") || "*"); + res.set("Access-Control-Allow-Methods", req.header("Access-Control-Request-Methods") || "*"); next(); }); this.app.use(bodyParser.json({ inflate: true, limit: "10mb" })); diff --git a/src/cdn/index.ts b/src/cdn/index.ts index a24300d6..e32fd606 100644 --- a/src/cdn/index.ts +++ b/src/cdn/index.ts @@ -1,4 +1,4 @@ export * from "./Server"; export * from "./util/FileStorage"; -export * from "./util/Storage"; export * from "./util/multer"; +export * from "./util/Storage"; diff --git a/src/cdn/routes/attachments.ts b/src/cdn/routes/attachments.ts index 723a6c03..013f03d8 100644 --- a/src/cdn/routes/attachments.ts +++ b/src/cdn/routes/attachments.ts @@ -1,100 +1,77 @@ -import { Router, Response, Request } from "express"; -import { Config, Snowflake } from "@fosscord/util"; -import { storage } from "../util/Storage"; +import { Config, HTTPError, Snowflake } from "@fosscord/util"; +import { Request, Response, Router } from "express"; import FileType from "file-type"; -import { HTTPError } from "@fosscord/util"; -import { multer } from "../util/multer"; import imageSize from "image-size"; +import { multer } from "../util/multer"; +import { storage } from "../util/Storage"; const router = Router(); -const SANITIZED_CONTENT_TYPE = [ - "text/html", - "text/mhtml", - "multipart/related", - "application/xhtml+xml", -]; - -router.post( - "/:channel_id", - multer.single("file"), - async (req: Request, res: Response) => { - if (req.headers.signature !== Config.get().security.requestSignature) - throw new HTTPError("Invalid request signature"); - if (!req.file) throw new HTTPError("file missing"); - - const { buffer, mimetype, size, originalname, fieldname } = req.file; - const { channel_id } = req.params; - const filename = originalname - .replaceAll(" ", "_") - .replace(/[^a-zA-Z0-9._]+/g, ""); - const id = Snowflake.generate(); - const path = `attachments/${channel_id}/${id}/${filename}`; - - const endpoint = - Config.get()?.cdn.endpointPublic || "http://localhost:3003"; - - await storage.set(path, buffer); - let width; - let height; - if (mimetype.includes("image")) { - const dimensions = imageSize(buffer); - if (dimensions) { - width = dimensions.width; - height = dimensions.height; - } +const SANITIZED_CONTENT_TYPE = ["text/html", "text/mhtml", "multipart/related", "application/xhtml+xml"]; + +router.post("/:channel_id", multer.single("file"), async (req: Request, res: Response) => { + if (req.headers.signature !== Config.get().security.requestSignature) throw new HTTPError("Invalid request signature"); + if (!req.file) throw new HTTPError("file missing"); + + const { buffer, mimetype, size, originalname, fieldname } = req.file; + const { channel_id } = req.params; + const filename = originalname.replaceAll(" ", "_").replace(/[^a-zA-Z0-9._]+/g, ""); + const id = Snowflake.generate(); + const path = `attachments/${channel_id}/${id}/${filename}`; + + const endpoint = Config.get()?.cdn.endpointPublic || "http://localhost:3003"; + + await storage.set(path, buffer); + let width; + let height; + if (mimetype.includes("image")) { + const dimensions = imageSize(buffer); + if (dimensions) { + width = dimensions.width; + height = dimensions.height; } + } - const file = { - id, - content_type: mimetype, - filename: filename, - size, - url: `${endpoint}/${path}`, - width, - height, - }; - - return res.json(file); + const file = { + id, + content_type: mimetype, + filename: filename, + size, + url: `${endpoint}/${path}`, + width, + height + }; + + return res.json(file); +}); + +router.get("/:channel_id/:id/:filename", async (req: Request, res: Response) => { + const { channel_id, id, filename } = req.params; + + const file = await storage.get(`attachments/${channel_id}/${id}/${filename}`); + if (!file) throw new HTTPError("File not found"); + const type = await FileType.fromBuffer(file); + let content_type = type?.mime || "application/octet-stream"; + + if (SANITIZED_CONTENT_TYPE.includes(content_type)) { + content_type = "application/octet-stream"; } -); - -router.get( - "/:channel_id/:id/:filename", - async (req: Request, res: Response) => { - const { channel_id, id, filename } = req.params; - - const file = await storage.get( - `attachments/${channel_id}/${id}/${filename}` - ); - if (!file) throw new HTTPError("File not found"); - const type = await FileType.fromBuffer(file); - let content_type = type?.mime || "application/octet-stream"; - - if (SANITIZED_CONTENT_TYPE.includes(content_type)) { - content_type = "application/octet-stream"; - } - res.set("Content-Type", content_type); - res.set("Cache-Control", "public, max-age=31536000"); + res.set("Content-Type", content_type); + res.set("Cache-Control", "public, max-age=31536000"); - return res.send(file); - } -); + return res.send(file); +}); -router.delete( - "/:channel_id/:id/:filename", - async (req: Request, res: Response) => { - if (req.headers.signature !== Config.get().security.requestSignature) - throw new HTTPError("Invalid request signature"); +router.delete("/:channel_id/:id/:filename", async (req: Request, res: Response) => { + if (req.headers.signature !== Config.get().security.requestSignature) throw new HTTPError("Invalid request signature"); - const { channel_id, id, filename } = req.params; - const path = `attachments/${channel_id}/${id}/${filename}`; + const { channel_id, id, filename } = req.params; + const path = `attachments/${channel_id}/${id}/${filename}`; - await storage.delete(path); + await storage.delete(path); - return res.send({ success: true }); - } -); + return res.send({ success: true }); +}); export default router; diff --git a/src/cdn/routes/avatars.ts b/src/cdn/routes/avatars.ts index 40705b2e..fa26938f 100644 --- a/src/cdn/routes/avatars.ts +++ b/src/cdn/routes/avatars.ts @@ -1,10 +1,9 @@ -import { Router, Response, Request } from "express"; -import { Config, Snowflake } from "@fosscord/util"; -import { storage } from "../util/Storage"; -import FileType from "file-type"; -import { HTTPError } from "@fosscord/util"; +import { Config, HTTPError, Snowflake } from "@fosscord/util"; import crypto from "crypto"; +import { Request, Response, Router } from "express"; +import FileType from "file-type"; import { multer } from "../util/multer"; +import { storage } from "../util/Storage"; // TODO: check premium and animated pfp are allowed in the config // TODO: generate different sizes of icon @@ -12,51 +11,35 @@ import { multer } from "../util/multer"; // TODO: delete old icons const ANIMATED_MIME_TYPES = ["image/apng", "image/gif", "image/gifv"]; -const STATIC_MIME_TYPES = [ - "image/png", - "image/jpeg", - "image/webp", - "image/svg+xml", - "image/svg", -]; +const STATIC_MIME_TYPES = ["image/png", "image/jpeg", "image/webp", "image/svg+xml", "image/svg"]; const ALLOWED_MIME_TYPES = [...ANIMATED_MIME_TYPES, ...STATIC_MIME_TYPES]; const router = Router(); -router.post( - "/:user_id", - multer.single("file"), - async (req: Request, res: Response) => { - if (req.headers.signature !== Config.get().security.requestSignature) - throw new HTTPError("Invalid request signature"); - if (!req.file) throw new HTTPError("Missing file"); - const { buffer, mimetype, size, originalname, fieldname } = req.file; - const { user_id } = req.params; - - let hash = crypto - .createHash("md5") - .update(Snowflake.generate()) - .digest("hex"); - - const type = await FileType.fromBuffer(buffer); - if (!type || !ALLOWED_MIME_TYPES.includes(type.mime)) - throw new HTTPError("Invalid file type"); - if (ANIMATED_MIME_TYPES.includes(type.mime)) hash = `a_${hash}`; // animated icons have a_ infront of the hash - - const path = `avatars/${user_id}/${hash}`; - const endpoint = - Config.get().cdn.endpointPublic || "http://localhost:3003"; - - await storage.set(path, buffer); - - return res.json({ - id: hash, - content_type: type.mime, - size, - url: `${endpoint}${req.baseUrl}/${user_id}/${hash}`, - }); - } -); +router.post("/:user_id", multer.single("file"), async (req: Request, res: Response) => { + if (req.headers.signature !== Config.get().security.requestSignature) throw new HTTPError("Invalid request signature"); + if (!req.file) throw new HTTPError("Missing file"); + const { buffer, mimetype, size, originalname, fieldname } = req.file; + const { user_id } = req.params; + + let hash = crypto.createHash("md5").update(Snowflake.generate()).digest("hex"); + + const type = await FileType.fromBuffer(buffer); + if (!type || !ALLOWED_MIME_TYPES.includes(type.mime)) throw new HTTPError("Invalid file type"); + if (ANIMATED_MIME_TYPES.includes(type.mime)) hash = `a_${hash}`; // animated icons have a_ infront of the hash + + const path = `avatars/${user_id}/${hash}`; + const endpoint = Config.get().cdn.endpointPublic || "http://localhost:3003"; + + await storage.set(path, buffer); + + return res.json({ + id: hash, + content_type: type.mime, + size, + url: `${endpoint}${req.baseUrl}/${user_id}/${hash}` + }); +}); router.get("/:user_id", async (req: Request, res: Response) => { let { user_id } = req.params; @@ -89,8 +72,7 @@ router.get("/:user_id/:hash", async (req: Request, res: Response) => { }); router.delete("/:user_id/:id", async (req: Request, res: Response) => { - if (req.headers.signature !== Config.get().security.requestSignature) - throw new HTTPError("Invalid request signature"); + if (req.headers.signature !== Config.get().security.requestSignature) throw new HTTPError("Invalid request signature"); const { user_id, id } = req.params; const path = `avatars/${user_id}/${id}`; diff --git a/src/cdn/routes/external.ts b/src/cdn/routes/external.ts index c9441fc2..7ccf9b8a 100644 --- a/src/cdn/routes/external.ts +++ b/src/cdn/routes/external.ts @@ -1,9 +1,8 @@ -import { Router, Response, Request } from "express"; +import { Config, HTTPError, Snowflake } from "@fosscord/util"; +import { Request, Response, Router } from "express"; +import FileType from "file-type"; import fetch from "node-fetch"; -import { HTTPError } from "@fosscord/util"; -import { Snowflake, Config } from "@fosscord/util"; import { storage } from "../util/Storage"; -import FileType from "file-type"; // TODO: somehow handle the deletion of images posted to the /external route @@ -12,17 +11,15 @@ const DEFAULT_FETCH_OPTIONS: any = { redirect: "follow", follow: 1, headers: { - "user-agent": - "Mozilla/5.0 (compatible Fosscordbot/0.1; +https://fosscord.com)", + "user-agent": "Mozilla/5.0 (compatible Fosscordbot/0.1; +https://fosscord.com)" }, size: 1024 * 1024 * 8, compress: true, - method: "GET", + method: "GET" }; router.post("/", async (req: Request, res: Response) => { - if (req.headers.signature !== Config.get().security.requestSignature) - throw new HTTPError("Invalid request signature"); + if (req.headers.signature !== Config.get().security.requestSignature) throw new HTTPError("Invalid request signature"); if (!req.body) throw new HTTPError("Invalid Body"); diff --git a/src/cdn/routes/ping.ts b/src/cdn/routes/ping.ts index 38daf81e..420cf567 100644 --- a/src/cdn/routes/ping.ts +++ b/src/cdn/routes/ping.ts @@ -1,4 +1,4 @@ -import { Router, Response, Request } from "express"; +import { Request, Response, Router } from "express"; const router = Router(); diff --git a/src/cdn/routes/role-icons.ts b/src/cdn/routes/role-icons.ts index 2e5c42dd..768e194f 100644 --- a/src/cdn/routes/role-icons.ts +++ b/src/cdn/routes/role-icons.ts @@ -1,10 +1,9 @@ -import { Router, Response, Request } from "express"; -import { Config, Snowflake } from "@fosscord/util"; -import { storage } from "../util/Storage"; -import FileType from "file-type"; -import { HTTPError } from "@fosscord/util"; +import { Config, HTTPError, Snowflake } from "@fosscord/util"; import crypto from "crypto"; +import { Request, Response, Router } from "express"; +import FileType from "file-type"; import { multer } from "../util/multer"; +import { storage } from "../util/Storage"; //Role icons ---> avatars.ts modified @@ -12,50 +11,34 @@ import { multer } from "../util/multer"; // TODO: generate different sizes of icon // TODO: generate different image types of icon -const STATIC_MIME_TYPES = [ - "image/png", - "image/jpeg", - "image/webp", - "image/svg+xml", - "image/svg", -]; +const STATIC_MIME_TYPES = ["image/png", "image/jpeg", "image/webp", "image/svg+xml", "image/svg"]; const ALLOWED_MIME_TYPES = [...STATIC_MIME_TYPES]; const router = Router(); -router.post( - "/:role_id", - multer.single("file"), - async (req: Request, res: Response) => { - if (req.headers.signature !== Config.get().security.requestSignature) - throw new HTTPError("Invalid request signature"); - if (!req.file) throw new HTTPError("Missing file"); - const { buffer, mimetype, size, originalname, fieldname } = req.file; - const { role_id } = req.params; - - let hash = crypto - .createHash("md5") - .update(Snowflake.generate()) - .digest("hex"); - - const type = await FileType.fromBuffer(buffer); - if (!type || !ALLOWED_MIME_TYPES.includes(type.mime)) - throw new HTTPError("Invalid file type"); - - const path = `role-icons/${role_id}/${hash}.png`; - const endpoint = - Config.get().cdn.endpointPublic || "http://localhost:3003"; - - await storage.set(path, buffer); - - return res.json({ - id: hash, - content_type: type.mime, - size, - url: `${endpoint}${req.baseUrl}/${role_id}/${hash}`, - }); - } -); +router.post("/:role_id", multer.single("file"), async (req: Request, res: Response) => { + if (req.headers.signature !== Config.get().security.requestSignature) throw new HTTPError("Invalid request signature"); + if (!req.file) throw new HTTPError("Missing file"); + const { buffer, mimetype, size, originalname, fieldname } = req.file; + const { role_id } = req.params; + + let hash = crypto.createHash("md5").update(Snowflake.generate()).digest("hex"); + + const type = await FileType.fromBuffer(buffer); + if (!type || !ALLOWED_MIME_TYPES.includes(type.mime)) throw new HTTPError("Invalid file type"); + + const path = `role-icons/${role_id}/${hash}.png`; + const endpoint = Config.get().cdn.endpointPublic || "http://localhost:3003"; + + await storage.set(path, buffer); + + return res.json({ + id: hash, + content_type: type.mime, + size, + url: `${endpoint}${req.baseUrl}/${role_id}/${hash}` + }); +}); router.get("/:role_id", async (req: Request, res: Response) => { let { role_id } = req.params; @@ -88,8 +71,7 @@ router.get("/:role_id/:hash", async (req: Request, res: Response) => { }); router.delete("/:role_id/:id", async (req: Request, res: Response) => { - if (req.headers.signature !== Config.get().security.requestSignature) - throw new HTTPError("Invalid request signature"); + if (req.headers.signature !== Config.get().security.requestSignature) throw new HTTPError("Invalid request signature"); const { role_id, id } = req.params; const path = `role-icons/${role_id}/${id}`; diff --git a/src/cdn/util/FileStorage.ts b/src/cdn/util/FileStorage.ts index aee9d345..fea013a6 100644 --- a/src/cdn/util/FileStorage.ts +++ b/src/cdn/util/FileStorage.ts @@ -1,7 +1,7 @@ -import { Storage } from "./Storage"; import fs from "fs"; -import { join, relative, dirname } from "path"; +import { dirname, join } from "path"; import { Readable } from "stream"; +import { Storage } from "./Storage"; //import ExifTransformer = require("exif-be-gone"); import ExifTransformer from "exif-be-gone"; @@ -12,8 +12,7 @@ function getPath(path: string) { const root = process.env.STORAGE_LOCATION || "../"; let filename = join(root, path); - if (path.indexOf("\0") !== -1 || !filename.startsWith(root)) - throw new Error("invalid path"); + if (path.indexOf("\0") !== -1 || !filename.startsWith(root)) throw new Error("invalid path"); return filename; } @@ -36,7 +35,7 @@ export class FileStorage implements Storage { async set(path: string, value: any) { path = getPath(path); //fse.ensureDirSync(dirname(path)); - fs.mkdirSync(dirname(path), {recursive: true}); + fs.mkdirSync(dirname(path), { recursive: true }); value = Readable.from(value); const cleaned_file = fs.createWriteStream(path); diff --git a/src/cdn/util/S3Storage.ts b/src/cdn/util/S3Storage.ts index c4066817..a7892e5e 100644 --- a/src/cdn/util/S3Storage.ts +++ b/src/cdn/util/S3Storage.ts @@ -11,11 +11,7 @@ const readableToBuffer = (readable: Readable): Promise<Buffer> => }); export class S3Storage implements Storage { - public constructor( - private client: S3, - private bucket: string, - private basePath?: string - ) {} + public constructor(private client: S3, private bucket: string, private basePath?: string) {} /** * Always return a string, to ensure consistency. @@ -28,7 +24,7 @@ export class S3Storage implements Storage { await this.client.putObject({ Bucket: this.bucket, Key: `${this.bucketBasePath}${path}`, - Body: data, + Body: data }); } @@ -36,7 +32,7 @@ export class S3Storage implements Storage { try { const s3Object = await this.client.getObject({ Bucket: this.bucket, - Key: `${this.bucketBasePath ?? ""}${path}`, + Key: `${this.bucketBasePath ?? ""}${path}` }); if (!s3Object.Body) return null; @@ -54,7 +50,7 @@ export class S3Storage implements Storage { async delete(path: string): Promise<void> { await this.client.deleteObject({ Bucket: this.bucket, - Key: `${this.bucketBasePath}${path}`, + Key: `${this.bucketBasePath}${path}` }); } } diff --git a/src/cdn/util/Storage.ts b/src/cdn/util/Storage.ts index 728804a0..1ab6a1d9 100644 --- a/src/cdn/util/Storage.ts +++ b/src/cdn/util/Storage.ts @@ -1,9 +1,9 @@ -import { FileStorage } from "./FileStorage"; import path from "path"; +import { FileStorage } from "./FileStorage"; //import fse from "fs-extra"; +import { S3 } from "@aws-sdk/client-s3"; import fs from "fs"; import { bgCyan, black } from "picocolors"; -import { S3 } from "@aws-sdk/client-s3"; import { S3Storage } from "./S3Storage"; process.cwd(); @@ -24,7 +24,7 @@ if (process.env.STORAGE_PROVIDER === "file" || !process.env.STORAGE_PROVIDER) { } console.log(`[CDN] storage location: ${bgCyan(`${black(location)}`)}`); //fse.ensureDirSync(location); - fs.mkdirSync(location, {recursive: true}); + fs.mkdirSync(location, { recursive: true }); process.env.STORAGE_LOCATION = location; storage = new FileStorage(); @@ -33,16 +33,12 @@ if (process.env.STORAGE_PROVIDER === "file" || !process.env.STORAGE_PROVIDER) { bucket = process.env.STORAGE_BUCKET; if (!region) { - console.error( - `[CDN] You must provide a region when using the S3 storage provider.` - ); + console.error(`[CDN] You must provide a region when using the S3 storage provider.`); process.exit(1); } if (!bucket) { - console.error( - `[CDN] You must provide a bucket when using the S3 storage provider.` - ); + console.error(`[CDN] You must provide a bucket when using the S3 storage provider.`); process.exit(1); } @@ -50,9 +46,7 @@ if (process.env.STORAGE_PROVIDER === "file" || !process.env.STORAGE_PROVIDER) { let location = process.env.STORAGE_LOCATION; if (!location) { - console.warn( - `[CDN] STORAGE_LOCATION unconfigured for S3 provider, defaulting to the bucket root...` - ); + console.warn(`[CDN] STORAGE_LOCATION unconfigured for S3 provider, defaulting to the bucket root...`); location = undefined; } diff --git a/src/cdn/util/multer.ts b/src/cdn/util/multer.ts index bfdf6aff..f56b0fb5 100644 --- a/src/cdn/util/multer.ts +++ b/src/cdn/util/multer.ts @@ -5,6 +5,6 @@ export const multer = multerConfig({ limits: { fields: 10, files: 10, - fileSize: 1024 * 1024 * 100, // 100 mb - }, + fileSize: 1024 * 1024 * 100 // 100 mb + } }); diff --git a/src/gateway/Server.ts b/src/gateway/Server.ts index 82fbeba2..97da3fa0 100644 --- a/src/gateway/Server.ts +++ b/src/gateway/Server.ts @@ -1,9 +1,9 @@ -import dotenv from "dotenv"; -dotenv.config(); import { closeDatabase, Config, getOrInitialiseDatabase, initEvent } from "@fosscord/util"; +import dotenv from "dotenv"; +import http from "http"; import ws from "ws"; import { Connection } from "./events/Connection"; -import http from "http"; +dotenv.config(); export class Server { public ws: ws.Server; @@ -11,15 +11,7 @@ export class Server { public server: http.Server; public production: boolean; - constructor({ - port, - server, - production, - }: { - port: number; - server?: http.Server; - production?: boolean; - }) { + constructor({ port, server, production }: { port: number; server?: http.Server; production?: boolean }) { this.port = port; this.production = production || false; @@ -39,7 +31,7 @@ export class Server { this.ws = new ws.Server({ maxPayload: 4096, - noServer: true, + noServer: true }); this.ws.on("connection", Connection); this.ws.on("error", console.error); diff --git a/src/gateway/events/Close.ts b/src/gateway/events/Close.ts index 5b7c512c..34831eab 100644 --- a/src/gateway/events/Close.ts +++ b/src/gateway/events/Close.ts @@ -1,12 +1,5 @@ import { WebSocket } from "@fosscord/gateway"; -import { - emitEvent, - PresenceUpdateEvent, - PrivateSessionProjection, - Session, - SessionsReplace, - User, -} from "@fosscord/util"; +import { emitEvent, PresenceUpdateEvent, PrivateSessionProjection, Session, SessionsReplace, User } from "@fosscord/util"; export async function Close(this: WebSocket, code: number, reason: string) { console.log("[WebSocket] closed", code, reason); @@ -19,17 +12,17 @@ export async function Close(this: WebSocket, code: number, reason: string) { await Session.delete({ session_id: this.session_id }); const sessions = await Session.find({ where: { user_id: this.user_id }, - select: PrivateSessionProjection, + select: PrivateSessionProjection }); await emitEvent({ event: "SESSIONS_REPLACE", user_id: this.user_id, - data: sessions, + data: sessions } as SessionsReplace); const session = sessions.first() || { activities: [], client_info: {}, - status: "offline", + status: "offline" }; await emitEvent({ @@ -39,8 +32,8 @@ export async function Close(this: WebSocket, code: number, reason: string) { user: await User.getPublicUser(this.user_id), activities: session.activities, client_status: session?.client_info, - status: session.status, - }, + status: session.status + } } as PresenceUpdateEvent); } } diff --git a/src/gateway/events/Connection.ts b/src/gateway/events/Connection.ts index 508b4741..5a5ce48f 100644 --- a/src/gateway/events/Connection.ts +++ b/src/gateway/events/Connection.ts @@ -1,13 +1,13 @@ -import WS from "ws"; import { WebSocket } from "@fosscord/gateway"; -import { Send } from "../util/Send"; +import { IncomingMessage } from "http"; +import { URL } from "url"; +import WS from "ws"; +import { createDeflate } from "zlib"; import { CLOSECODES, OPCODES } from "../util/Constants"; import { setHeartbeat } from "../util/Heartbeat"; -import { IncomingMessage } from "http"; +import { Send } from "../util/Send"; import { Close } from "./Close"; import { Message } from "./Message"; -import { createDeflate } from "zlib"; -import { URL } from "url"; let erlpack: any; try { erlpack = require("@yukikaze-bot/erlpack"); @@ -17,30 +17,26 @@ try { // TODO: specify rate limit in config // TODO: check msg max size -export async function Connection( - this: WS.Server, - socket: WebSocket, - request: IncomingMessage -) { +export async function Connection(this: WS.Server, socket: WebSocket, request: IncomingMessage) { try { // @ts-ignore socket.on("close", Close); // @ts-ignore socket.on("message", Message); - - if(process.env.WS_LOGEVENTS) - [ - "close", - "error", - "upgrade", - //"message", - "open", - "ping", - "pong", - "unexpected-response" - ].forEach(x=>{ - socket.on(x, y => console.log(x, y)); - }); + + if (process.env.WS_LOGEVENTS) + [ + "close", + "error", + "upgrade", + //"message", + "open", + "ping", + "pong", + "unexpected-response" + ].forEach((x) => { + socket.on(x, (y) => console.log(x, y)); + }); console.log(`[Gateway] Connections: ${this.clients.size}`); @@ -49,23 +45,19 @@ export async function Connection( socket.encoding = searchParams.get("encoding") || "json"; if (!["json", "etf"].includes(socket.encoding)) { if (socket.encoding === "etf" && erlpack) { - throw new Error( - "Erlpack is not installed: 'npm i @yukikaze-bot/erlpack'" - ); + throw new Error("Erlpack is not installed: 'npm i @yukikaze-bot/erlpack'"); } return socket.close(CLOSECODES.Decode_error); } // @ts-ignore socket.version = Number(searchParams.get("version")) || 8; - if (socket.version != 8) - return socket.close(CLOSECODES.Invalid_API_version); + if (socket.version != 8) return socket.close(CLOSECODES.Invalid_API_version); // @ts-ignore socket.compress = searchParams.get("compress") || ""; if (socket.compress) { - if (socket.compress !== "zlib-stream") - return socket.close(CLOSECODES.Decode_error); + if (socket.compress !== "zlib-stream") return socket.close(CLOSECODES.Decode_error); socket.deflate = createDeflate({ chunkSize: 65535 }); socket.deflate.on("data", (chunk) => socket.send(chunk)); } @@ -80,8 +72,8 @@ export async function Connection( await Send(socket, { op: OPCODES.Hello, d: { - heartbeat_interval: 1000 * 30, - }, + heartbeat_interval: 1000 * 30 + } }); socket.readyTimeout = setTimeout(() => { diff --git a/src/gateway/events/Message.ts b/src/gateway/events/Message.ts index 569f5fc7..96950a42 100644 --- a/src/gateway/events/Message.ts +++ b/src/gateway/events/Message.ts @@ -1,42 +1,39 @@ +import { Payload, WebSocket } from "@fosscord/gateway"; +import OPCodeHandlers from "../opcodes"; +import { check } from "../opcodes/instanceOf"; import { CLOSECODES } from "../util/Constants"; -import { WebSocket, Payload } from "@fosscord/gateway"; let erlpack: any; try { erlpack = require("@yukikaze-bot/erlpack"); } catch (error) {} -import OPCodeHandlers from "../opcodes"; -import { check } from "../opcodes/instanceOf"; const PayloadSchema = { op: Number, $d: Object || Number, // or number for heartbeat sequence $s: Number, - $t: String, + $t: String }; export async function Message(this: WebSocket, buffer: Buffer) { // TODO: compression let data: Payload; - if (this.encoding === "etf" && buffer instanceof Buffer) - data = erlpack.unpack(buffer); + if (this.encoding === "etf" && buffer instanceof Buffer) data = erlpack.unpack(buffer); else if (this.encoding === "json") data = JSON.parse(buffer as unknown as string); //TODO: is this even correct?? seems to work for web clients... - else if(/--debug|--inspect/.test(process.execArgv.join(' '))) { + else if (/--debug|--inspect/.test(process.execArgv.join(" "))) { debugger; return; - } - else { + } else { console.log("Invalid gateway connection! Use a debugger to inspect!"); return; } - if(process.env.WS_VERBOSE) - console.log(`[Websocket] Incomming message: ${JSON.stringify(data)}`); - if(data.op !== 1) - check.call(this, PayloadSchema, data); - else { //custom validation for numbers, because heartbeat - if(data.s || data.t || (typeof data.d !== "number" && data.d)) { + if (process.env.WS_VERBOSE) console.log(`[Websocket] Incomming message: ${JSON.stringify(data)}`); + if (data.op !== 1) check.call(this, PayloadSchema, data); + else { + //custom validation for numbers, because heartbeat + if (data.s || data.t || (typeof data.d !== "number" && data.d)) { console.log("Invalid heartbeat..."); this.close(CLOSECODES.Decode_error); } @@ -55,7 +52,6 @@ export async function Message(this: WebSocket, buffer: Buffer) { return await OPCodeHandler.call(this, data); } catch (error) { console.error(error); - if (!this.CLOSED && this.CLOSING) - return this.close(CLOSECODES.Unknown_error); + if (!this.CLOSED && this.CLOSING) return this.close(CLOSECODES.Unknown_error); } } diff --git a/src/gateway/index.ts b/src/gateway/index.ts index d77ce931..730347f9 100644 --- a/src/gateway/index.ts +++ b/src/gateway/index.ts @@ -1,4 +1,4 @@ +export * from "./listener/listener"; +export * from "./opcodes/"; export * from "./Server"; export * from "./util/"; -export * from "./opcodes/"; -export * from "./listener/listener"; diff --git a/src/gateway/listener/listener.ts b/src/gateway/listener/listener.ts index 8c69e193..811318af 100644 --- a/src/gateway/listener/listener.ts +++ b/src/gateway/listener/listener.ts @@ -1,20 +1,20 @@ +import { WebSocket } from "@fosscord/gateway"; import { + EVENTEnum, + EventOpts, getPermission, - Permissions, - RabbitMQ, listenEvent, - EventOpts, ListenEventOpts, Member, - EVENTEnum, + Permissions, + RabbitMQ, + Recipient, Relationship, - RelationshipType, + RelationshipType } from "@fosscord/util"; +import { Channel as AMQChannel } from "amqplib"; import { OPCODES } from "../util/Constants"; import { Send } from "../util/Send"; -import { WebSocket } from "@fosscord/gateway"; -import { Channel as AMQChannel } from "amqplib"; -import { Recipient } from "@fosscord/util"; // TODO: close connection on Invalidated Token // TODO: check intent @@ -23,17 +23,14 @@ import { Recipient } from "@fosscord/util"; // Sharding: calculate if the current shard id matches the formula: shard_id = (guild_id >> 22) % num_shards // https://discord.com/developers/docs/topics/gateway#sharding -export function handlePresenceUpdate( - this: WebSocket, - { event, acknowledge, data }: EventOpts -) { +export function handlePresenceUpdate(this: WebSocket, { event, acknowledge, data }: EventOpts) { acknowledge?.(); if (event === EVENTEnum.PresenceUpdate) { return Send(this, { op: OPCODES.Dispatch, t: event, d: data, - s: this.sequence++, + s: this.sequence++ }); } } @@ -43,23 +40,25 @@ export async function setupListener(this: WebSocket) { const [members, recipients, relationships] = await Promise.all([ Member.find({ where: { id: this.user_id }, - relations: ["guild", "guild.channels"], + relations: ["guild", "guild.channels"] }), Recipient.find({ where: { user_id: this.user_id, closed: false }, - relations: ["channel"], + relations: ["channel"] }), - Relationship.find({ where: { - from_id: this.user_id, - type: RelationshipType.friends, - } }), + Relationship.find({ + where: { + from_id: this.user_id, + type: RelationshipType.friends + } + }) ]); const guilds = members.map((x) => x.guild); const dm_channels = recipients.map((x) => x.channel); const opts: { acknowledge: boolean; channel?: AMQChannel } = { - acknowledge: true, + acknowledge: true }; this.listen_options = opts; const consumer = consume.bind(this); @@ -73,11 +72,7 @@ export async function setupListener(this: WebSocket) { this.events[this.user_id] = await listenEvent(this.user_id, consumer, opts); relationships.forEach(async (relationship) => { - this.events[relationship.to_id] = await listenEvent( - relationship.to_id, - handlePresenceUpdate.bind(this), - opts - ); + this.events[relationship.to_id] = await listenEvent(relationship.to_id, handlePresenceUpdate.bind(this), opts); }); dm_channels.forEach(async (channel) => { @@ -90,16 +85,8 @@ export async function setupListener(this: WebSocket) { this.events[guild.id] = await listenEvent(guild.id, consumer, opts); guild.channels.forEach(async (channel) => { - if ( - permission - .overwriteChannel(channel.permission_overwrites!) - .has("VIEW_CHANNEL") - ) { - this.events[channel.id] = await listenEvent( - channel.id, - consumer, - opts - ); + if (permission.overwriteChannel(channel.permission_overwrites!).has("VIEW_CHANNEL")) { + this.events[channel.id] = await listenEvent(channel.id, consumer, opts); } }); }); @@ -131,11 +118,7 @@ async function consume(this: WebSocket, opts: EventOpts) { delete this.member_events[data.user.id]; case "GUILD_MEMBER_ADD": if (this.member_events[data.user.id]) break; // already subscribed - this.member_events[data.user.id] = await listenEvent( - data.user.id, - handlePresenceUpdate.bind(this), - this.listen_options - ); + this.member_events[data.user.id] = await listenEvent(data.user.id, handlePresenceUpdate.bind(this), this.listen_options); break; case "GUILD_MEMBER_REMOVE": if (!this.member_events[data.user.id]) break; @@ -148,21 +131,13 @@ async function consume(this: WebSocket, opts: EventOpts) { opts.cancel(); break; case "CHANNEL_CREATE": - if ( - !permission - .overwriteChannel(data.permission_overwrites) - .has("VIEW_CHANNEL") - ) { + if (!permission.overwriteChannel(data.permission_overwrites).has("VIEW_CHANNEL")) { return; } this.events[id] = await listenEvent(id, consumer, listenOpts); break; case "RELATIONSHIP_ADD": - this.events[data.user.id] = await listenEvent( - data.user.id, - handlePresenceUpdate.bind(this), - this.listen_options - ); + this.events[data.user.id] = await listenEvent(data.user.id, handlePresenceUpdate.bind(this), this.listen_options); break; case "GUILD_CREATE": this.events[id] = await listenEvent(id, consumer, listenOpts); @@ -170,11 +145,7 @@ async function consume(this: WebSocket, opts: EventOpts) { case "CHANNEL_UPDATE": const exists = this.events[id]; // @ts-ignore - if ( - permission - .overwriteChannel(data.permission_overwrites) - .has("VIEW_CHANNEL") - ) { + if (permission.overwriteChannel(data.permission_overwrites).has("VIEW_CHANNEL")) { if (exists) break; this.events[id] = await listenEvent(id, consumer, listenOpts); } else { @@ -244,6 +215,6 @@ async function consume(this: WebSocket, opts: EventOpts) { op: OPCODES.Dispatch, t: event, d: data, - s: this.sequence++, + s: this.sequence++ }); } diff --git a/src/gateway/opcodes/Identify.ts b/src/gateway/opcodes/Identify.ts index 44db598c..ac6955fd 100644 --- a/src/gateway/opcodes/Identify.ts +++ b/src/gateway/opcodes/Identify.ts @@ -1,35 +1,35 @@ -import { WebSocket, Payload } from "@fosscord/gateway"; +import { Payload, WebSocket } from "@fosscord/gateway"; import { + Application, checkToken, + Config, + emitEvent, + EVENTEnum, + IdentifySchema, Intents, Member, - ReadyEventData, - User, - Session, - EVENTEnum, - Config, + MemberPrivateProjection, + OrmUtils, + PresenceUpdateEvent, + PrivateSessionProjection, + PrivateUserProjection, PublicMember, PublicUser, - PrivateUserProjection, ReadState, - Application, - emitEvent, + ReadyEventData, + Recipient, + Session, SessionsReplace, - PrivateSessionProjection, - MemberPrivateProjection, - PresenceUpdateEvent, - UserSettings, - IdentifySchema, + User, + UserSettings } from "@fosscord/util"; -import { Send } from "../util/Send"; +import { setupListener } from "../listener/listener"; import { CLOSECODES, OPCODES } from "../util/Constants"; +import { Send } from "../util/Send"; import { genSessionId } from "../util/SessionUtils"; -import { setupListener } from "../listener/listener"; +import { check } from "./instanceOf"; // import experiments from "./experiments.json"; const experiments: any = []; -import { check } from "./instanceOf"; -import { Recipient } from "@fosscord/util"; -import { OrmUtils } from "@fosscord/util"; // TODO: user sharding // TODO: check privileged intents, if defined in the config @@ -52,57 +52,44 @@ export async function onIdentify(this: WebSocket, data: Payload) { const session_id = genSessionId(); this.session_id = session_id; //Set the session of the WebSocket object - - const [user, read_states, members, recipients, session, application] = - await Promise.all([ - User.findOneOrFail({ - where: { id: this.user_id }, - relations: ["relationships", "relationships.to", "settings"], - select: [...PrivateUserProjection, "relationships"], - }), - ReadState.find({ where: { user_id: this.user_id } }), - Member.find({ - where: { id: this.user_id }, - select: MemberPrivateProjection, - relations: [ - "guild", - "guild.channels", - "guild.emojis", - "guild.emojis.user", - "guild.roles", - "guild.stickers", - "user", - "roles", - ], - }), - Recipient.find({ - where: { user_id: this.user_id, closed: false }, - relations: [ - "channel", - "channel.recipients", - "channel.recipients.user", - ], - // TODO: public user selection - }), - // save the session and delete it when the websocket is closed - await OrmUtils.mergeDeep(new Session(), { - user_id: this.user_id, - session_id: session_id, - // TODO: check if status is only one of: online, dnd, offline, idle - status: identify.presence?.status || "offline", //does the session always start as online? - client_info: { - //TODO read from identity - client: "desktop", - os: identify.properties?.os, - version: 0, - }, - activities: [], - }).save(), - Application.findOne({ where: { id: this.user_id } }), - ]); + + const [user, read_states, members, recipients, session, application] = await Promise.all([ + User.findOneOrFail({ + where: { id: this.user_id }, + relations: ["relationships", "relationships.to", "settings"], + select: [...PrivateUserProjection, "relationships"] + }), + ReadState.find({ where: { user_id: this.user_id } }), + Member.find({ + where: { id: this.user_id }, + select: MemberPrivateProjection, + relations: ["guild", "guild.channels", "guild.emojis", "guild.emojis.user", "guild.roles", "guild.stickers", "user", "roles"] + }), + Recipient.find({ + where: { user_id: this.user_id, closed: false }, + relations: ["channel", "channel.recipients", "channel.recipients.user"] + // TODO: public user selection + }), + // save the session and delete it when the websocket is closed + await OrmUtils.mergeDeep(new Session(), { + user_id: this.user_id, + session_id: session_id, + // TODO: check if status is only one of: online, dnd, offline, idle + status: identify.presence?.status || "offline", //does the session always start as online? + client_info: { + //TODO read from identity + client: "desktop", + os: identify.properties?.os, + version: 0 + }, + activities: [] + }).save(), + Application.findOne({ where: { id: this.user_id } }) + ]); if (!user) return this.close(CLOSECODES.Authentication_failed); - if (!user.settings) { //settings may not exist after updating... + if (!user.settings) { + //settings may not exist after updating... user.settings = new UserSettings(); user.settings.id = user.id; //await (user.settings as UserSettings).save(); @@ -132,8 +119,8 @@ export async function onIdentify(this: WebSocket, data: Payload) { ...x, roles: x.roles.map((x) => x.id), settings: undefined, - guild: undefined, - }, + guild: undefined + } ]; }) as PublicMember[][]; let guilds = members.map((x) => ({ ...x.guild, joined_at: x.joined_at })); @@ -146,7 +133,7 @@ export async function onIdentify(this: WebSocket, data: Payload) { op: OPCODES.Dispatch, t: EVENTEnum.GuildCreate, s: this.sequence++, - d: guild, + d: guild }); }, 500); return { id: guild.id, unavailable: true }; @@ -163,9 +150,7 @@ export async function onIdentify(this: WebSocket, data: Payload) { //TODO is this needed? check if users in group dm that are not friends are sent in the READY event users = users.concat(x.channel.recipients as unknown as User[]); if (x.channel.isDm()) { - x.channel.recipients = x.channel.recipients!.filter( - (x) => x.id !== this.user_id - ); + x.channel.recipients = x.channel.recipients!.filter((x) => x.id !== this.user_id); } return x.channel; }); @@ -192,8 +177,8 @@ export async function onIdentify(this: WebSocket, data: Payload) { user_id: this.user_id, data: await Session.find({ where: { user_id: this.user_id }, - select: PrivateSessionProjection, - }), + select: PrivateSessionProjection + }) } as SessionsReplace); emitEvent({ event: "PRESENCE_UPDATE", @@ -202,8 +187,8 @@ export async function onIdentify(this: WebSocket, data: Payload) { user: await User.getPublicUser(this.user_id), activities: session.activities, client_status: session?.client_info, - status: session.status, - }, + status: session.status + } } as PresenceUpdateEvent); }); @@ -238,7 +223,7 @@ export async function onIdentify(this: WebSocket, data: Payload) { const d: ReadyEventData = { v: 8, - application: {id: application?.id??'', flags: application?.flags??0}, //TODO: check this code! + application: { id: application?.id ?? "", flags: application?.flags ?? 0 }, //TODO: check this code! user: privateUser, user_settings: user.settings, // @ts-ignore @@ -255,12 +240,12 @@ export async function onIdentify(this: WebSocket, data: Payload) { read_state: { entries: read_states, partial: false, - version: 304128, + version: 304128 }, user_guild_settings: { entries: user_guild_settings_entries, partial: false, // TODO partial - version: 642, + version: 642 }, private_channels: channels, session_id: session_id, @@ -268,8 +253,8 @@ export async function onIdentify(this: WebSocket, data: Payload) { connected_accounts: [], // TODO consents: { personalization: { - consented: false, // TODO - }, + consented: false // TODO + } }, country_code: user.settings.locale, friend_suggestion_count: 0, // TODO @@ -277,7 +262,7 @@ export async function onIdentify(this: WebSocket, data: Payload) { experiments: experiments, // TODO guild_join_requests: [], // TODO what is this? users: users.filter((x) => x).unique(), - merged_members: merged_members, + merged_members: merged_members // shard // TODO: only for user sharding }; @@ -286,7 +271,7 @@ export async function onIdentify(this: WebSocket, data: Payload) { op: OPCODES.Dispatch, t: EVENTEnum.Ready, s: this.sequence++, - d, + d }); //TODO send READY_SUPPLEMENTAL diff --git a/src/gateway/opcodes/LazyRequest.ts b/src/gateway/opcodes/LazyRequest.ts index 74996f5b..ea69779e 100644 --- a/src/gateway/opcodes/LazyRequest.ts +++ b/src/gateway/opcodes/LazyRequest.ts @@ -1,9 +1,8 @@ -import { getPermission, listenEvent, Member, Role, getOrInitialiseDatabase, LazyRequest } from "@fosscord/util"; -import { Send } from "../util/Send"; +import { handlePresenceUpdate, Payload, WebSocket } from "@fosscord/gateway"; +import { getOrInitialiseDatabase, getPermission, LazyRequest, listenEvent, Member, Role } from "@fosscord/util"; import { OPCODES } from "../util/Constants"; -import { WebSocket, Payload, handlePresenceUpdate } from "@fosscord/gateway"; +import { Send } from "../util/Send"; import { check } from "./instanceOf"; -import { getRepository } from "typeorm"; // TODO: only show roles/members that have access to this channel // TODO: config: to list all members (even those who are offline) sorted by role, or just those who are online @@ -16,16 +15,16 @@ async function getMembers(guild_id: string, range: [number, number]) { // TODO: wait for typeorm to implement ordering for .find queries https://github.com/typeorm/typeorm/issues/2620 // TODO: rewrite this, released in 0.3.0 - let members: Member[] = await (await getOrInitialiseDatabase()).getRepository(Member) + let members: Member[] = await ( + await getOrInitialiseDatabase() + ) + .getRepository(Member) .createQueryBuilder("member") .where("member.guild_id = :guild_id", { guild_id }) .leftJoinAndSelect("member.roles", "role") .leftJoinAndSelect("member.user", "user") .leftJoinAndSelect("user.sessions", "session") - .addSelect( - "CASE WHEN session.status = 'offline' THEN 0 ELSE 1 END", - "_status" - ) + .addSelect("CASE WHEN session.status = 'offline' THEN 0 ELSE 1 END", "_status") .orderBy("role.position", "DESC") .addOrderBy("_status", "DESC") .addOrderBy("user.username", "ASC") @@ -44,21 +43,17 @@ async function getMembers(guild_id: string, range: [number, number]) { for (const role of member_roles) { // @ts-ignore - const [role_members, other_members] = partition(members, (m: Member) => - m.roles.find((r) => r.id === role.id) - ); + const [role_members, other_members] = partition(members, (m: Member) => m.roles.find((r) => r.id === role.id)); const group = { count: role_members.length, - id: role.id === guild_id ? "online" : role.id, + id: role.id === guild_id ? "online" : role.id }; items.push({ group }); groups.push(group); for (const member of role_members) { - const roles = member.roles - .filter((x: Role) => x.id !== guild_id) - .map((x: Role) => x.id); + const roles = member.roles.filter((x: Role) => x.id !== guild_id).map((x: Role) => x.id); const session = member.user.sessions.first(); @@ -71,10 +66,10 @@ async function getMembers(guild_id: string, range: [number, number]) { presence: { ...session, activities: session?.activities || [], - user: { id: member.user.id }, - }, - }, - } + user: { id: member.user.id } + } + } + }; if (!member?.user?.sessions || !member.user.sessions.length) { offlineItems.push(item); @@ -90,7 +85,7 @@ async function getMembers(guild_id: string, range: [number, number]) { if (offlineItems.length) { const group = { count: offlineItems.length, - id: "offline", + id: "offline" }; items.push({ group }); groups.push(group); @@ -102,7 +97,7 @@ async function getMembers(guild_id: string, range: [number, number]) { items, groups, range, - members: items.map((x) => 'member' in x ? x.member : undefined).filter(x => !!x), + members: items.map((x) => ("member" in x ? x.member : undefined)).filter((x) => !!x) }; } @@ -129,11 +124,7 @@ export async function onLazyRequest(this: WebSocket, { d }: Payload) { op.members.forEach(async (member) => { if (this.events[member.user.id]) return; // already subscribed as friend if (this.member_events[member.user.id]) return; // already subscribed in member list - this.member_events[member.user.id] = await listenEvent( - member.user.id, - handlePresenceUpdate.bind(this), - this.listen_options - ); + this.member_events[member.user.id] = await listenEvent(member.user.id, handlePresenceUpdate.bind(this), this.listen_options); }); }); @@ -145,7 +136,7 @@ export async function onLazyRequest(this: WebSocket, { d }: Payload) { ops: ops.map((x) => ({ items: x.items, op: "SYNC", - range: x.range, + range: x.range })), online_count: member_count, member_count, @@ -154,8 +145,8 @@ export async function onLazyRequest(this: WebSocket, { d }: Payload) { groups: ops .map((x) => x.groups) .flat() - .unique(), - }, + .unique() + } }); } @@ -164,9 +155,7 @@ function partition<T>(array: T[], isValid: Function) { return array.reduce( // @ts-ignore ([pass, fail], elem) => { - return isValid(elem) - ? [[...pass, elem], fail] - : [pass, [...fail, elem]]; + return isValid(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]]; }, [[], []] ); diff --git a/src/gateway/opcodes/PresenceUpdate.ts b/src/gateway/opcodes/PresenceUpdate.ts index f31c9161..ad712234 100644 --- a/src/gateway/opcodes/PresenceUpdate.ts +++ b/src/gateway/opcodes/PresenceUpdate.ts @@ -1,4 +1,4 @@ -import { WebSocket, Payload } from "@fosscord/gateway"; +import { Payload, WebSocket } from "@fosscord/gateway"; import { ActivitySchema, emitEvent, PresenceUpdateEvent, Session, User } from "@fosscord/util"; import { check } from "./instanceOf"; @@ -6,10 +6,7 @@ export async function onPresenceUpdate(this: WebSocket, { d }: Payload) { check.call(this, ActivitySchema, d); const presence = d as ActivitySchema; - await Session.update( - { session_id: this.session_id }, - { status: presence.status, activities: presence.activities } - ); + await Session.update({ session_id: this.session_id }, { status: presence.status, activities: presence.activities }); await emitEvent({ event: "PRESENCE_UPDATE", @@ -18,7 +15,7 @@ export async function onPresenceUpdate(this: WebSocket, { d }: Payload) { user: await User.getPublicUser(this.user_id), activities: presence.activities, client_status: {}, // TODO: - status: presence.status, - }, + status: presence.status + } } as PresenceUpdateEvent); } diff --git a/src/gateway/opcodes/Resume.ts b/src/gateway/opcodes/Resume.ts index 42dc586d..f320864b 100644 --- a/src/gateway/opcodes/Resume.ts +++ b/src/gateway/opcodes/Resume.ts @@ -1,11 +1,11 @@ -import { WebSocket, Payload } from "@fosscord/gateway"; +import { Payload, WebSocket } from "@fosscord/gateway"; import { Send } from "../util/Send"; export async function onResume(this: WebSocket, data: Payload) { console.log("Got Resume -> cancel not implemented"); await Send(this, { op: 9, - d: false, + d: false }); // return this.close(CLOSECODES.Invalid_session); diff --git a/src/gateway/opcodes/VoiceStateUpdate.ts b/src/gateway/opcodes/VoiceStateUpdate.ts index c4297a68..20502584 100644 --- a/src/gateway/opcodes/VoiceStateUpdate.ts +++ b/src/gateway/opcodes/VoiceStateUpdate.ts @@ -1,18 +1,18 @@ import { Payload, WebSocket } from "@fosscord/gateway"; -import { genVoiceToken } from "../util/SessionUtils"; -import { check } from "./instanceOf"; import { Config, emitEvent, Guild, Member, + OrmUtils, + Region, VoiceServerUpdateEvent, VoiceState, VoiceStateUpdateEvent, - VoiceStateUpdateSchema, + VoiceStateUpdateSchema } from "@fosscord/util"; -import { OrmUtils } from "@fosscord/util"; -import { Region } from "@fosscord/util"; +import { genVoiceToken } from "../util/SessionUtils"; +import { check } from "./instanceOf"; // TODO: check if a voice server is setup // Notice: Bot users respect the voice channel's user limit, if set. When the voice channel is full, you will not receive the Voice State Update or Voice Server Update events in response to your own Voice State Update. Having MANAGE_CHANNELS permission bypasses this limit and allows you to join regardless of the channel being full or not. @@ -20,7 +20,7 @@ export async function onVoiceStateUpdate(this: WebSocket, data: Payload) { check.call(this, VoiceStateUpdateSchema, data.d); const body = data.d as VoiceStateUpdateSchema; - if(body.guild_id == null) { + if (body.guild_id == null) { console.log(`[Gateway] VoiceStateUpdate called with guild_id == null by user ${this.user_id}!`); return; } @@ -28,26 +28,20 @@ export async function onVoiceStateUpdate(this: WebSocket, data: Payload) { let voiceState: VoiceState; try { voiceState = await VoiceState.findOneOrFail({ - where: { user_id: this.user_id }, + where: { user_id: this.user_id } }); - if ( - voiceState.session_id !== this.session_id && - body.channel_id === null - ) { + if (voiceState.session_id !== this.session_id && body.channel_id === null) { //Should we also check guild_id === null? //changing deaf or mute on a client that's not the one with the same session of the voicestate in the database should be ignored return; } //If a user change voice channel between guild we should send a left event first - if ( - voiceState.guild_id !== body.guild_id && - voiceState.session_id === this.session_id - ) { + if (voiceState.guild_id !== body.guild_id && voiceState.session_id === this.session_id) { await emitEvent({ event: "VOICE_STATE_UPDATE", data: { ...voiceState, channel_id: null }, - guild_id: voiceState.guild_id, + guild_id: voiceState.guild_id }); } @@ -60,7 +54,7 @@ export async function onVoiceStateUpdate(this: WebSocket, data: Payload) { user_id: this.user_id, deaf: false, mute: false, - suppress: false, + suppress: false }); } @@ -69,12 +63,11 @@ export async function onVoiceStateUpdate(this: WebSocket, data: Payload) { //TODO this may fail voiceState.member = await Member.findOneOrFail({ where: { id: voiceState.user_id, guild_id: voiceState.guild_id }, - relations: ["user", "roles"], + relations: ["user", "roles"] }); //If the session changed we generate a new token - if (voiceState.session_id !== this.session_id) - voiceState.token = genVoiceToken(); + if (voiceState.session_id !== this.session_id) voiceState.token = genVoiceToken(); voiceState.session_id = this.session_id; const { id, ...newObj } = voiceState; @@ -84,8 +77,8 @@ export async function onVoiceStateUpdate(this: WebSocket, data: Payload) { emitEvent({ event: "VOICE_STATE_UPDATE", data: newObj, - guild_id: voiceState.guild_id, - } as VoiceStateUpdateEvent), + guild_id: voiceState.guild_id + } as VoiceStateUpdateEvent) ]); //If it's null it means that we are leaving the channel and this event is not needed @@ -94,13 +87,9 @@ export async function onVoiceStateUpdate(this: WebSocket, data: Payload) { const regions = Config.get().regions; let guildRegion: Region; if (guild && guild.region) { - guildRegion = regions.available.filter( - (r) => r.id === guild.region - )[0]; + guildRegion = regions.available.filter((r) => r.id === guild.region)[0]; } else { - guildRegion = regions.available.filter( - (r) => r.id === regions.default - )[0]; + guildRegion = regions.available.filter((r) => r.id === regions.default)[0]; } await emitEvent({ @@ -108,9 +97,9 @@ export async function onVoiceStateUpdate(this: WebSocket, data: Payload) { data: { token: voiceState.token, guild_id: voiceState.guild_id, - endpoint: guildRegion.endpoint, + endpoint: guildRegion.endpoint }, - guild_id: voiceState.guild_id, + guild_id: voiceState.guild_id } as VoiceServerUpdateEvent); } } diff --git a/src/gateway/opcodes/index.ts b/src/gateway/opcodes/index.ts index 027739db..d5dc7de1 100644 --- a/src/gateway/opcodes/index.ts +++ b/src/gateway/opcodes/index.ts @@ -1,4 +1,4 @@ -import { WebSocket, Payload } from "@fosscord/gateway"; +import { Payload, WebSocket } from "@fosscord/gateway"; import { onHeartbeat } from "./Heartbeat"; import { onIdentify } from "./Identify"; import { onLazyRequest } from "./LazyRequest"; @@ -21,5 +21,5 @@ export default { // 9: Invalid Session // 10: Hello // 13: Dm_update - 14: onLazyRequest, + 14: onLazyRequest }; diff --git a/src/gateway/opcodes/instanceOf.ts b/src/gateway/opcodes/instanceOf.ts index eb6f6ea1..95d74963 100644 --- a/src/gateway/opcodes/instanceOf.ts +++ b/src/gateway/opcodes/instanceOf.ts @@ -1,5 +1,5 @@ -import { instanceOf } from "@fosscord/util"; import { WebSocket } from "@fosscord/gateway"; +import { instanceOf } from "@fosscord/util"; import { CLOSECODES } from "../util/Constants"; export function check(this: WebSocket, schema: any, data: any) { diff --git a/src/gateway/start.ts b/src/gateway/start.ts index 2000522a..97420d7e 100644 --- a/src/gateway/start.ts +++ b/src/gateway/start.ts @@ -1,14 +1,14 @@ process.on("uncaughtException", console.error); process.on("unhandledRejection", console.error); -import { Server } from "./Server"; import { config } from "dotenv"; +import { Server } from "./Server"; config(); let port = Number(process.env.PORT); if (isNaN(port)) port = 3002; const server = new Server({ - port, + port }); server.start(); diff --git a/src/gateway/util/Constants.ts b/src/gateway/util/Constants.ts index 692f9028..78455ff8 100644 --- a/src/gateway/util/Constants.ts +++ b/src/gateway/util/Constants.ts @@ -22,7 +22,7 @@ export enum OPCODES { Stream_Watch = 20, Stream_Ping = 21, Stream_Set_Paused = 22, - Request_Application_Commands = 24, + Request_Application_Commands = 24 } export enum CLOSECODES { Unknown_error = 4000, @@ -39,7 +39,7 @@ export enum CLOSECODES { Sharding_required, Invalid_API_version, Invalid_intent, - Disallowed_intent, + Disallowed_intent } export interface Payload { diff --git a/src/gateway/util/Send.ts b/src/gateway/util/Send.ts index 2a28d8e0..7826dd40 100644 --- a/src/gateway/util/Send.ts +++ b/src/gateway/util/Send.ts @@ -7,8 +7,7 @@ try { import { Payload, WebSocket } from "@fosscord/gateway"; export async function Send(socket: WebSocket, data: Payload) { - if(process.env.WS_VERBOSE) - console.log(`[Websocket] Outgoing message: ${JSON.stringify(data)}`); + if (process.env.WS_VERBOSE) console.log(`[Websocket] Outgoing message: ${JSON.stringify(data)}`); let buffer: Buffer | string; if (socket.encoding === "etf") buffer = erlpack.pack(data); // TODO: encode circular object diff --git a/src/gateway/util/SessionUtils.ts b/src/gateway/util/SessionUtils.ts index bf854042..c66c7e76 100644 --- a/src/gateway/util/SessionUtils.ts +++ b/src/gateway/util/SessionUtils.ts @@ -7,7 +7,5 @@ export function genVoiceToken() { } function genRanHex(size: number) { - return [...Array(size)] - .map(() => Math.floor(Math.random() * 16).toString(16)) - .join(""); + return [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join(""); } diff --git a/src/gateway/util/index.ts b/src/gateway/util/index.ts index 0be5ecee..a5085228 100644 --- a/src/gateway/util/index.ts +++ b/src/gateway/util/index.ts @@ -1,5 +1,5 @@ export * from "./Constants"; +export * from "./Heartbeat"; export * from "./Send"; export * from "./SessionUtils"; -export * from "./Heartbeat"; export * from "./WebSocket"; diff --git a/src/start.ts b/src/start.ts index a20581c3..cf1a42a5 100644 --- a/src/start.ts +++ b/src/start.ts @@ -1,19 +1,19 @@ // process.env.MONGOMS_DEBUG = "true"; -import "reflect-metadata"; +import { execSync } from "child_process"; import cluster, { Worker } from "cluster"; +import { config } from "dotenv"; import os from "os"; -import { red, bold, yellow, cyan } from "picocolors"; +import { bold, cyan, red, yellow } from "picocolors"; +import "reflect-metadata"; import { initStats } from "./stats"; -import { config } from "dotenv"; config(); -import { execSync } from "child_process"; // TODO: add socket event transmission let cores = 1; try { cores = Number(process.env.THREADS) || os.cpus().length; } catch { - console.log("[API] Failed to get thread count! Using 1...") + console.log("[API] Failed to get thread count! Using 1..."); } if (cluster.isMaster) { @@ -35,19 +35,9 @@ if (cluster.isMaster) { ██║ ╚██████╔╝███████║███████║╚██████╗╚██████╔╝██║ ██║██████╔╝ ╚═╝ ╚═════╝ ╚══════╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═════╝ - fosscord-server | ${yellow( - `Pre-release (${ - commit !== null - ? commit.slice(0, 7) - : "Unknown (Git cannot be found)" - })` - )} + fosscord-server | ${yellow(`Pre-release (${commit !== null ? commit.slice(0, 7) : "Unknown (Git cannot be found)"})`)} -Commit Hash: ${ - commit !== null - ? `${cyan(commit)} (${yellow(commit.slice(0, 7))})` - : "Unknown (Git cannot be found)" - } +Commit Hash: ${commit !== null ? `${cyan(commit)} (${yellow(commit.slice(0, 7))})` : "Unknown (Git cannot be found)"} Cores: ${cyan(os.cpus().length)} (Using ${cores} thread(s).) `) ); @@ -84,11 +74,7 @@ Cores: ${cyan(os.cpus().length)} (Using ${cores} thread(s).) }); cluster.on("exit", (worker: any, code: any, signal: any) => { - console.log( - `[Worker] ${red( - `died with PID: ${worker.process.pid} , restarting ...` - )}` - ); + console.log(`[Worker] ${red(`died with PID: ${worker.process.pid} , restarting ...`)}`); cluster.fork(); }); } diff --git a/src/stats.ts b/src/stats.ts index 654e0a4f..05f0ab77 100644 --- a/src/stats.ts +++ b/src/stats.ts @@ -2,15 +2,13 @@ import os from "os"; import { red } from "picocolors"; export function initStats() { - console.log(`[Path] running in ${__dirname}`); try { console.log(`[CPU] ${os.cpus()[0].model} Cores x${os.cpus().length}`); + } catch { + console.log("[CPU] Failed to get cpu model!"); } - catch { - console.log('[CPU] Failed to get cpu model!') - } - + console.log(`[System] ${os.platform()} ${os.arch()}`); console.log(`[Process] running with PID: ${process.pid}`); if (process.getuid && process.getuid() === 0) { @@ -20,5 +18,4 @@ export function initStats() { ) ); } - } diff --git a/src/util/config/Config.ts b/src/util/config/Config.ts index 7aee1775..27450f95 100644 --- a/src/util/config/Config.ts +++ b/src/util/config/Config.ts @@ -1,4 +1,22 @@ -import { ApiConfiguration, ClientConfiguration, DefaultsConfiguration, EndpointConfiguration, GeneralConfiguration, GifConfiguration, GuildConfiguration, KafkaConfiguration, LimitsConfiguration, LoginConfiguration, MetricsConfiguration, RabbitMQConfiguration, RegionConfiguration, RegisterConfiguration, SecurityConfiguration, SentryConfiguration, TemplateConfiguration } from "."; +import { + ApiConfiguration, + ClientConfiguration, + DefaultsConfiguration, + EndpointConfiguration, + GeneralConfiguration, + GifConfiguration, + GuildConfiguration, + KafkaConfiguration, + LimitsConfiguration, + LoginConfiguration, + MetricsConfiguration, + RabbitMQConfiguration, + RegionConfiguration, + RegisterConfiguration, + SecurityConfiguration, + SentryConfiguration, + TemplateConfiguration +} from "."; export class ConfigValue { gateway: EndpointConfiguration = new EndpointConfiguration(); @@ -19,4 +37,4 @@ export class ConfigValue { metrics: MetricsConfiguration = new MetricsConfiguration(); sentry: SentryConfiguration = new SentryConfiguration(); defaults: DefaultsConfiguration = new DefaultsConfiguration(); -} \ No newline at end of file +} diff --git a/src/util/config/types/ApiConfiguration.ts b/src/util/config/types/ApiConfiguration.ts index 16b1efba..442a5986 100644 --- a/src/util/config/types/ApiConfiguration.ts +++ b/src/util/config/types/ApiConfiguration.ts @@ -2,4 +2,4 @@ export class ApiConfiguration { defaultVersion: string = "9"; activeVersions: string[] = ["6", "7", "8", "9"]; useFosscordEnhancements: boolean = true; -} \ No newline at end of file +} diff --git a/src/util/config/types/ClientConfiguration.ts b/src/util/config/types/ClientConfiguration.ts index 1adda1e2..44704404 100644 --- a/src/util/config/types/ClientConfiguration.ts +++ b/src/util/config/types/ClientConfiguration.ts @@ -1,8 +1,8 @@ import { ClientReleaseConfiguration } from "."; export class ClientConfiguration { - //classes - releases: ClientReleaseConfiguration = new ClientReleaseConfiguration(); - //base types - useTestClient: boolean = true; -} \ No newline at end of file + //classes + releases: ClientReleaseConfiguration = new ClientReleaseConfiguration(); + //base types + useTestClient: boolean = true; +} diff --git a/src/util/config/types/DefaultsConfiguration.ts b/src/util/config/types/DefaultsConfiguration.ts index 9b02a590..d5ee39e7 100644 --- a/src/util/config/types/DefaultsConfiguration.ts +++ b/src/util/config/types/DefaultsConfiguration.ts @@ -1,6 +1,6 @@ import { GuildDefaults, UserDefaults } from "."; export class DefaultsConfiguration { - guild: GuildDefaults = new GuildDefaults(); - user: UserDefaults = new UserDefaults(); -} \ No newline at end of file + guild: GuildDefaults = new GuildDefaults(); + user: UserDefaults = new UserDefaults(); +} diff --git a/src/util/config/types/EndpointConfiguration.ts b/src/util/config/types/EndpointConfiguration.ts index 87baea31..5e5e8ca9 100644 --- a/src/util/config/types/EndpointConfiguration.ts +++ b/src/util/config/types/EndpointConfiguration.ts @@ -2,4 +2,4 @@ export class EndpointConfiguration { endpointClient: string | null = null; endpointPrivate: string | null = null; endpointPublic: string | null = null; -} \ No newline at end of file +} diff --git a/src/util/config/types/GeneralConfiguration.ts b/src/util/config/types/GeneralConfiguration.ts index 55848b44..5cb8df89 100644 --- a/src/util/config/types/GeneralConfiguration.ts +++ b/src/util/config/types/GeneralConfiguration.ts @@ -9,4 +9,4 @@ export class GeneralConfiguration { correspondenceUserID: string | null = null; image: string | null = null; instanceId: string = Snowflake.generate(); -} \ No newline at end of file +} diff --git a/src/util/config/types/GifConfiguration.ts b/src/util/config/types/GifConfiguration.ts index 6a2d520d..565c2ac0 100644 --- a/src/util/config/types/GifConfiguration.ts +++ b/src/util/config/types/GifConfiguration.ts @@ -1,5 +1,5 @@ export class GifConfiguration { - enabled: boolean = true; - provider: "tenor" = "tenor"; // more coming soon - apiKey?: string = "LIVDSRZULELA"; -} \ No newline at end of file + enabled: boolean = true; + provider: "tenor" = "tenor"; // more coming soon + apiKey?: string = "LIVDSRZULELA"; +} diff --git a/src/util/config/types/GuildConfiguration.ts b/src/util/config/types/GuildConfiguration.ts index 3d43b368..ebc1b442 100644 --- a/src/util/config/types/GuildConfiguration.ts +++ b/src/util/config/types/GuildConfiguration.ts @@ -1,6 +1,6 @@ -import { DiscoveryConfiguration, AutoJoinConfiguration } from "."; +import { AutoJoinConfiguration, DiscoveryConfiguration } from "."; export class GuildConfiguration { - discovery: DiscoveryConfiguration = new DiscoveryConfiguration(); - autoJoin: AutoJoinConfiguration = new AutoJoinConfiguration(); + discovery: DiscoveryConfiguration = new DiscoveryConfiguration(); + autoJoin: AutoJoinConfiguration = new AutoJoinConfiguration(); } diff --git a/src/util/config/types/KafkaConfiguration.ts b/src/util/config/types/KafkaConfiguration.ts index 7932f49e..a3aa8058 100644 --- a/src/util/config/types/KafkaConfiguration.ts +++ b/src/util/config/types/KafkaConfiguration.ts @@ -1,5 +1,5 @@ import { KafkaBroker } from "."; export class KafkaConfiguration { - brokers: KafkaBroker[] | null = null; -} \ No newline at end of file + brokers: KafkaBroker[] | null = null; +} diff --git a/src/util/config/types/LimitConfigurations.ts b/src/util/config/types/LimitConfigurations.ts index bcc2e7e2..a3a52cf5 100644 --- a/src/util/config/types/LimitConfigurations.ts +++ b/src/util/config/types/LimitConfigurations.ts @@ -6,4 +6,4 @@ export class LimitsConfiguration { message: MessageLimits = new MessageLimits(); channel: ChannelLimits = new ChannelLimits(); rate: RateLimits = new RateLimits(); -} \ No newline at end of file +} diff --git a/src/util/config/types/LoginConfiguration.ts b/src/util/config/types/LoginConfiguration.ts index 255c9451..d8b737b9 100644 --- a/src/util/config/types/LoginConfiguration.ts +++ b/src/util/config/types/LoginConfiguration.ts @@ -1,3 +1,3 @@ export class LoginConfiguration { - requireCaptcha: boolean = false; -} \ No newline at end of file + requireCaptcha: boolean = false; +} diff --git a/src/util/config/types/MetricsConfiguration.ts b/src/util/config/types/MetricsConfiguration.ts index d7cd4937..f6b1d8e6 100644 --- a/src/util/config/types/MetricsConfiguration.ts +++ b/src/util/config/types/MetricsConfiguration.ts @@ -1,3 +1,3 @@ export class MetricsConfiguration { - timeout: number = 30000; -} \ No newline at end of file + timeout: number = 30000; +} diff --git a/src/util/config/types/RabbitMQConfiguration.ts b/src/util/config/types/RabbitMQConfiguration.ts index ce4a9123..bd4b6ca3 100644 --- a/src/util/config/types/RabbitMQConfiguration.ts +++ b/src/util/config/types/RabbitMQConfiguration.ts @@ -1,3 +1,3 @@ export class RabbitMQConfiguration { - host: string | null = null; -} \ No newline at end of file + host: string | null = null; +} diff --git a/src/util/config/types/RegionConfiguration.ts b/src/util/config/types/RegionConfiguration.ts index 09d9271c..b4b8c4a3 100644 --- a/src/util/config/types/RegionConfiguration.ts +++ b/src/util/config/types/RegionConfiguration.ts @@ -1,16 +1,16 @@ import { Region } from "."; export class RegionConfiguration { - default: string = "fosscord"; - useDefaultAsOptimal: boolean = true; - available: Region[] = [ - { - id: "fosscord", - name: "Fosscord", - endpoint: "127.0.0.1:3004", - vip: false, - custom: false, - deprecated: false, - }, - ]; -} \ No newline at end of file + default: string = "fosscord"; + useDefaultAsOptimal: boolean = true; + available: Region[] = [ + { + id: "fosscord", + name: "Fosscord", + endpoint: "127.0.0.1:3004", + vip: false, + custom: false, + deprecated: false + } + ]; +} diff --git a/src/util/config/types/RegisterConfiguration.ts b/src/util/config/types/RegisterConfiguration.ts index a0dc97c5..939605a6 100644 --- a/src/util/config/types/RegisterConfiguration.ts +++ b/src/util/config/types/RegisterConfiguration.ts @@ -1,18 +1,18 @@ import { DateOfBirthConfiguration, EmailConfiguration, PasswordConfiguration } from "."; export class RegisterConfiguration { - //classes - email: EmailConfiguration = new EmailConfiguration(); - dateOfBirth: DateOfBirthConfiguration = new DateOfBirthConfiguration(); - password: PasswordConfiguration = new PasswordConfiguration(); - //base types - disabled: boolean = false; - requireCaptcha: boolean = true; - requireInvite: boolean = false; - guestsRequireInvite: boolean = true; - allowNewRegistration: boolean = true; - allowMultipleAccounts: boolean = true; - blockProxies: boolean = true; - incrementingDiscriminators: boolean = false; // random otherwise - defaultRights: string = "0"; + //classes + email: EmailConfiguration = new EmailConfiguration(); + dateOfBirth: DateOfBirthConfiguration = new DateOfBirthConfiguration(); + password: PasswordConfiguration = new PasswordConfiguration(); + //base types + disabled: boolean = false; + requireCaptcha: boolean = true; + requireInvite: boolean = false; + guestsRequireInvite: boolean = true; + allowNewRegistration: boolean = true; + allowMultipleAccounts: boolean = true; + blockProxies: boolean = true; + incrementingDiscriminators: boolean = false; // random otherwise + defaultRights: string = "0"; } diff --git a/src/util/config/types/SecurityConfiguration.ts b/src/util/config/types/SecurityConfiguration.ts index 405b86ac..98c04c99 100644 --- a/src/util/config/types/SecurityConfiguration.ts +++ b/src/util/config/types/SecurityConfiguration.ts @@ -2,16 +2,16 @@ import crypto from "crypto"; import { CaptchaConfiguration, TwoFactorConfiguration } from "."; export class SecurityConfiguration { - //classes - captcha: CaptchaConfiguration = new CaptchaConfiguration(); - twoFactor: TwoFactorConfiguration = new TwoFactorConfiguration(); - //base types - autoUpdate: boolean | number = true; - requestSignature: string = crypto.randomBytes(32).toString("base64"); - jwtSecret: string = crypto.randomBytes(256).toString("base64"); - // header to get the real user ip address - // X-Forwarded-For for nginx/reverse proxies - // CF-Connecting-IP for cloudflare - forwadedFor: string | null = null; - ipdataApiKey: string | null = "eca677b284b3bac29eb72f5e496aa9047f26543605efe99ff2ce35c9"; + //classes + captcha: CaptchaConfiguration = new CaptchaConfiguration(); + twoFactor: TwoFactorConfiguration = new TwoFactorConfiguration(); + //base types + autoUpdate: boolean | number = true; + requestSignature: string = crypto.randomBytes(32).toString("base64"); + jwtSecret: string = crypto.randomBytes(256).toString("base64"); + // header to get the real user ip address + // X-Forwarded-For for nginx/reverse proxies + // CF-Connecting-IP for cloudflare + forwadedFor: string | null = null; + ipdataApiKey: string | null = "eca677b284b3bac29eb72f5e496aa9047f26543605efe99ff2ce35c9"; } diff --git a/src/util/config/types/SentryConfiguration.ts b/src/util/config/types/SentryConfiguration.ts index 836094a1..d50f5f4c 100644 --- a/src/util/config/types/SentryConfiguration.ts +++ b/src/util/config/types/SentryConfiguration.ts @@ -1,8 +1,8 @@ import { hostname } from "os"; export class SentryConfiguration { - enabled: boolean = false; - endpoint: string = "https://05e8e3d005f34b7d97e920ae5870a5e5@sentry.thearcanebrony.net/6"; - traceSampleRate: number = 1.0; - environment: string = hostname(); -} \ No newline at end of file + enabled: boolean = false; + endpoint: string = "https://05e8e3d005f34b7d97e920ae5870a5e5@sentry.thearcanebrony.net/6"; + traceSampleRate: number = 1.0; + environment: string = hostname(); +} diff --git a/src/util/config/types/TemplateConfiguration.ts b/src/util/config/types/TemplateConfiguration.ts index 4a9aa8f2..aade2934 100644 --- a/src/util/config/types/TemplateConfiguration.ts +++ b/src/util/config/types/TemplateConfiguration.ts @@ -1,6 +1,6 @@ export class TemplateConfiguration { - enabled: boolean = true; - allowTemplateCreation: boolean = true; - allowDiscordTemplates: boolean = true; - allowRaws: boolean = true; -} \ No newline at end of file + enabled: boolean = true; + allowTemplateCreation: boolean = true; + allowDiscordTemplates: boolean = true; + allowRaws: boolean = true; +} diff --git a/src/util/config/types/index.ts b/src/util/config/types/index.ts index 608503a0..a8cdff4c 100644 --- a/src/util/config/types/index.ts +++ b/src/util/config/types/index.ts @@ -14,5 +14,5 @@ export * from "./RegionConfiguration"; export * from "./RegisterConfiguration"; export * from "./SecurityConfiguration"; export * from "./SentryConfiguration"; -export * from "./TemplateConfiguration"; export * from "./subconfigurations/index"; +export * from "./TemplateConfiguration"; diff --git a/src/util/config/types/subconfigurations/client/ClientReleaseConfiguration.ts b/src/util/config/types/subconfigurations/client/ClientReleaseConfiguration.ts index 54e7f365..b082b711 100644 --- a/src/util/config/types/subconfigurations/client/ClientReleaseConfiguration.ts +++ b/src/util/config/types/subconfigurations/client/ClientReleaseConfiguration.ts @@ -1,4 +1,4 @@ export class ClientReleaseConfiguration { - useLocalRelease: boolean = true; //TODO - upstreamVersion: string = "0.0.264"; -} \ No newline at end of file + useLocalRelease: boolean = true; //TODO + upstreamVersion: string = "0.0.264"; +} diff --git a/src/util/config/types/subconfigurations/defaults/GuildDefaults.ts b/src/util/config/types/subconfigurations/defaults/GuildDefaults.ts index d6ff7697..435ae06c 100644 --- a/src/util/config/types/subconfigurations/defaults/GuildDefaults.ts +++ b/src/util/config/types/subconfigurations/defaults/GuildDefaults.ts @@ -1,8 +1,8 @@ export class GuildDefaults { - maxPresences: number = 250000; - maxVideoChannelUsers: number = 200; - afkTimeout: number = 300; - defaultMessageNotifications: number = 1; - explicitContentFilter: number = 0; - test: number = 123; -} \ No newline at end of file + maxPresences: number = 250000; + maxVideoChannelUsers: number = 200; + afkTimeout: number = 300; + defaultMessageNotifications: number = 1; + explicitContentFilter: number = 0; + test: number = 123; +} diff --git a/src/util/config/types/subconfigurations/defaults/UserDefaults.ts b/src/util/config/types/subconfigurations/defaults/UserDefaults.ts index 4481c011..cc56be36 100644 --- a/src/util/config/types/subconfigurations/defaults/UserDefaults.ts +++ b/src/util/config/types/subconfigurations/defaults/UserDefaults.ts @@ -1,5 +1,5 @@ export class UserDefaults { - premium: boolean = false; - premium_type: number = 2; - verified: boolean = true; -} \ No newline at end of file + premium: boolean = false; + premium_type: number = 2; + verified: boolean = true; +} diff --git a/src/util/config/types/subconfigurations/guild/AutoJoin.ts b/src/util/config/types/subconfigurations/guild/AutoJoin.ts index 47dfe5ec..4d7af352 100644 --- a/src/util/config/types/subconfigurations/guild/AutoJoin.ts +++ b/src/util/config/types/subconfigurations/guild/AutoJoin.ts @@ -1,5 +1,5 @@ export class AutoJoinConfiguration { - enabled: boolean = true; - guilds: string[] = []; - canLeave: boolean = true; -} \ No newline at end of file + enabled: boolean = true; + guilds: string[] = []; + canLeave: boolean = true; +} diff --git a/src/util/config/types/subconfigurations/guild/Discovery.ts b/src/util/config/types/subconfigurations/guild/Discovery.ts index 59d8a8ae..a7cb81db 100644 --- a/src/util/config/types/subconfigurations/guild/Discovery.ts +++ b/src/util/config/types/subconfigurations/guild/Discovery.ts @@ -1,6 +1,6 @@ export class DiscoveryConfiguration { - showAllGuilds: boolean = false; - useRecommendation: boolean = false; // TODO: Recommendation, privacy concern? - offset: number = 0; - limit: number = 24; -} \ No newline at end of file + showAllGuilds: boolean = false; + useRecommendation: boolean = false; // TODO: Recommendation, privacy concern? + offset: number = 0; + limit: number = 24; +} diff --git a/src/util/config/types/subconfigurations/kafka/KafkaBroker.ts b/src/util/config/types/subconfigurations/kafka/KafkaBroker.ts index 4f9a5e51..f7dc1cf7 100644 --- a/src/util/config/types/subconfigurations/kafka/KafkaBroker.ts +++ b/src/util/config/types/subconfigurations/kafka/KafkaBroker.ts @@ -1,4 +1,4 @@ export interface KafkaBroker { ip: string; port: number; -} \ No newline at end of file +} diff --git a/src/util/config/types/subconfigurations/limits/ChannelLimits.ts b/src/util/config/types/subconfigurations/limits/ChannelLimits.ts index 2f8f9485..76eeeb41 100644 --- a/src/util/config/types/subconfigurations/limits/ChannelLimits.ts +++ b/src/util/config/types/subconfigurations/limits/ChannelLimits.ts @@ -1,5 +1,5 @@ export class ChannelLimits { - maxPins: number = 500; - maxTopic: number = 1024; - maxWebhooks: number = 100; -} \ No newline at end of file + maxPins: number = 500; + maxTopic: number = 1024; + maxWebhooks: number = 100; +} diff --git a/src/util/config/types/subconfigurations/limits/GuildLimits.ts b/src/util/config/types/subconfigurations/limits/GuildLimits.ts index 91ad39ae..015654cb 100644 --- a/src/util/config/types/subconfigurations/limits/GuildLimits.ts +++ b/src/util/config/types/subconfigurations/limits/GuildLimits.ts @@ -1,8 +1,8 @@ export class GuildLimits { - maxRoles: number = 1000; - maxEmojis: number = 2000; - maxMembers: number = 25000000; - maxChannels: number = 65535; - maxChannelsInCategory: number = 65535; - hideOfflineMember: number = 3; -} \ No newline at end of file + maxRoles: number = 1000; + maxEmojis: number = 2000; + maxMembers: number = 25000000; + maxChannels: number = 65535; + maxChannelsInCategory: number = 65535; + hideOfflineMember: number = 3; +} diff --git a/src/util/config/types/subconfigurations/limits/MessageLimits.ts b/src/util/config/types/subconfigurations/limits/MessageLimits.ts index 51576b90..684a5057 100644 --- a/src/util/config/types/subconfigurations/limits/MessageLimits.ts +++ b/src/util/config/types/subconfigurations/limits/MessageLimits.ts @@ -1,8 +1,8 @@ export class MessageLimits { - maxCharacters: number = 1048576; - maxTTSCharacters: number = 160; - maxReactions: number = 2048; - maxAttachmentSize: number = 1024 * 1024 * 1024; - maxBulkDelete: number = 1000; - maxEmbedDownloadSize: number = 1024 * 1024 * 5; -} \ No newline at end of file + maxCharacters: number = 1048576; + maxTTSCharacters: number = 160; + maxReactions: number = 2048; + maxAttachmentSize: number = 1024 * 1024 * 1024; + maxBulkDelete: number = 1000; + maxEmbedDownloadSize: number = 1024 * 1024 * 5; +} diff --git a/src/util/config/types/subconfigurations/limits/RateLimits.ts b/src/util/config/types/subconfigurations/limits/RateLimits.ts index 25e7a1e0..db3f8a4c 100644 --- a/src/util/config/types/subconfigurations/limits/RateLimits.ts +++ b/src/util/config/types/subconfigurations/limits/RateLimits.ts @@ -1,18 +1,18 @@ -import { RouteRateLimit, RateLimitOptions } from "."; +import { RateLimitOptions, RouteRateLimit } from "."; export class RateLimits { - disabled: boolean = true; - ip: Omit<RateLimitOptions, "bot_count"> = { - count: 500, - window: 5 - }; - global: RateLimitOptions = { - count: 250, - window: 5 - }; - error: RateLimitOptions = { - count: 10, - window: 5 - }; - routes: RouteRateLimit; -} \ No newline at end of file + disabled: boolean = true; + ip: Omit<RateLimitOptions, "bot_count"> = { + count: 500, + window: 5 + }; + global: RateLimitOptions = { + count: 250, + window: 5 + }; + error: RateLimitOptions = { + count: 10, + window: 5 + }; + routes: RouteRateLimit; +} diff --git a/src/util/config/types/subconfigurations/limits/UserLimits.ts b/src/util/config/types/subconfigurations/limits/UserLimits.ts index 0d10e0b3..b8bdcb2d 100644 --- a/src/util/config/types/subconfigurations/limits/UserLimits.ts +++ b/src/util/config/types/subconfigurations/limits/UserLimits.ts @@ -1,5 +1,5 @@ export class UserLimits { - maxGuilds: number = 1048576; - maxUsername: number = 127; - maxFriends: number = 5000; -} \ No newline at end of file + maxGuilds: number = 1048576; + maxUsername: number = 127; + maxFriends: number = 5000; +} diff --git a/src/util/config/types/subconfigurations/limits/index.ts b/src/util/config/types/subconfigurations/limits/index.ts index 0b7304f6..a4911542 100644 --- a/src/util/config/types/subconfigurations/limits/index.ts +++ b/src/util/config/types/subconfigurations/limits/index.ts @@ -2,5 +2,5 @@ export * from "./ChannelLimits"; export * from "./GuildLimits"; export * from "./MessageLimits"; export * from "./RateLimits"; -export * from "./UserLimits"; export * from "./ratelimits/index"; +export * from "./UserLimits"; diff --git a/src/util/config/types/subconfigurations/limits/ratelimits/Auth.ts b/src/util/config/types/subconfigurations/limits/ratelimits/Auth.ts index df171044..0f363e7f 100644 --- a/src/util/config/types/subconfigurations/limits/ratelimits/Auth.ts +++ b/src/util/config/types/subconfigurations/limits/ratelimits/Auth.ts @@ -1,12 +1,12 @@ import { RateLimitOptions } from "./RateLimitOptions"; export class AuthRateLimit { - login: RateLimitOptions = { - count: 5, - window: 60 - }; - register: RateLimitOptions = { - count: 2, - window: 60 * 60 * 12 - }; -} \ No newline at end of file + login: RateLimitOptions = { + count: 5, + window: 60 + }; + register: RateLimitOptions = { + count: 2, + window: 60 * 60 * 12 + }; +} diff --git a/src/util/config/types/subconfigurations/limits/ratelimits/RateLimitOptions.ts b/src/util/config/types/subconfigurations/limits/ratelimits/RateLimitOptions.ts index 7089e28e..829813fb 100644 --- a/src/util/config/types/subconfigurations/limits/ratelimits/RateLimitOptions.ts +++ b/src/util/config/types/subconfigurations/limits/ratelimits/RateLimitOptions.ts @@ -3,4 +3,4 @@ export interface RateLimitOptions { count: number; window: number; onyIp?: boolean; -} \ No newline at end of file +} diff --git a/src/util/config/types/subconfigurations/limits/ratelimits/Route.ts b/src/util/config/types/subconfigurations/limits/ratelimits/Route.ts index 844b1b9a..464670f2 100644 --- a/src/util/config/types/subconfigurations/limits/ratelimits/Route.ts +++ b/src/util/config/types/subconfigurations/limits/ratelimits/Route.ts @@ -2,18 +2,18 @@ import { AuthRateLimit } from "./Auth"; import { RateLimitOptions } from "./RateLimitOptions"; export class RouteRateLimit { - guild: RateLimitOptions = { - count: 5, - window: 5 - }; - webhook: RateLimitOptions = { - count: 10, - window: 5 - }; - channel: RateLimitOptions = { - count: 10, - window: 5 - }; - auth: AuthRateLimit; - // TODO: rate limit configuration for all routes -} \ No newline at end of file + guild: RateLimitOptions = { + count: 5, + window: 5 + }; + webhook: RateLimitOptions = { + count: 10, + window: 5 + }; + channel: RateLimitOptions = { + count: 10, + window: 5 + }; + auth: AuthRateLimit; + // TODO: rate limit configuration for all routes +} diff --git a/src/util/config/types/subconfigurations/region/Region.ts b/src/util/config/types/subconfigurations/region/Region.ts index a8717e1f..c1bcfd01 100644 --- a/src/util/config/types/subconfigurations/region/Region.ts +++ b/src/util/config/types/subconfigurations/region/Region.ts @@ -9,4 +9,4 @@ export interface Region { vip: boolean; custom: boolean; deprecated: boolean; -} \ No newline at end of file +} diff --git a/src/util/config/types/subconfigurations/register/DateOfBirth.ts b/src/util/config/types/subconfigurations/register/DateOfBirth.ts index 5a3c4e9d..4831a4b7 100644 --- a/src/util/config/types/subconfigurations/register/DateOfBirth.ts +++ b/src/util/config/types/subconfigurations/register/DateOfBirth.ts @@ -1,4 +1,4 @@ export class DateOfBirthConfiguration { - required: boolean = true; - minimum: number = 13; // in years -} \ No newline at end of file + required: boolean = true; + minimum: number = 13; // in years +} diff --git a/src/util/config/types/subconfigurations/register/Email.ts b/src/util/config/types/subconfigurations/register/Email.ts index 115d49e0..7f54faa7 100644 --- a/src/util/config/types/subconfigurations/register/Email.ts +++ b/src/util/config/types/subconfigurations/register/Email.ts @@ -1,7 +1,7 @@ export class EmailConfiguration { - required: boolean = false; - allowlist: boolean = false; - blocklist: boolean = true; - domains: string[] = [];// TODO: efficiently save domain blocklist in database - // domains: fs.readFileSync(__dirname + "/blockedEmailDomains.txt", { encoding: "utf8" }).split("\n"), -} \ No newline at end of file + required: boolean = false; + allowlist: boolean = false; + blocklist: boolean = true; + domains: string[] = []; // TODO: efficiently save domain blocklist in database + // domains: fs.readFileSync(__dirname + "/blockedEmailDomains.txt", { encoding: "utf8" }).split("\n"), +} diff --git a/src/util/config/types/subconfigurations/register/Password.ts b/src/util/config/types/subconfigurations/register/Password.ts index 977473ac..383bdcfa 100644 --- a/src/util/config/types/subconfigurations/register/Password.ts +++ b/src/util/config/types/subconfigurations/register/Password.ts @@ -1,7 +1,7 @@ export class PasswordConfiguration { - required: boolean = false; - minLength: number = 8; - minNumbers: number = 2; - minUpperCase: number =2; - minSymbols: number = 0; -} \ No newline at end of file + required: boolean = false; + minLength: number = 8; + minNumbers: number = 2; + minUpperCase: number = 2; + minSymbols: number = 0; +} diff --git a/src/util/config/types/subconfigurations/security/Captcha.ts b/src/util/config/types/subconfigurations/security/Captcha.ts index ad6aa762..21c4ef44 100644 --- a/src/util/config/types/subconfigurations/security/Captcha.ts +++ b/src/util/config/types/subconfigurations/security/Captcha.ts @@ -1,6 +1,6 @@ export class CaptchaConfiguration { - enabled: boolean = false; - service: "recaptcha" | "hcaptcha" | null = null; // TODO: hcaptcha, custom - sitekey: string | null = null; - secret: string | null = null; -} \ No newline at end of file + enabled: boolean = false; + service: "recaptcha" | "hcaptcha" | null = null; // TODO: hcaptcha, custom + sitekey: string | null = null; + secret: string | null = null; +} diff --git a/src/util/config/types/subconfigurations/security/TwoFactor.ts b/src/util/config/types/subconfigurations/security/TwoFactor.ts index 33a47385..20d2f9ab 100644 --- a/src/util/config/types/subconfigurations/security/TwoFactor.ts +++ b/src/util/config/types/subconfigurations/security/TwoFactor.ts @@ -1,3 +1,3 @@ export class TwoFactorConfiguration { - generateBackupCodes: boolean = true; -} \ No newline at end of file + generateBackupCodes: boolean = true; +} diff --git a/src/util/dtos/DmChannelDTO.ts b/src/util/dtos/DmChannelDTO.ts index 226b2f9d..93b1adfa 100644 --- a/src/util/dtos/DmChannelDTO.ts +++ b/src/util/dtos/DmChannelDTO.ts @@ -1,5 +1,5 @@ -import { MinimalPublicUserDTO } from "./UserDTO"; import { Channel, PublicUserProjection, User } from "../entities"; +import { MinimalPublicUserDTO } from "./UserDTO"; export class DmChannelDTO { icon: string | null; @@ -35,7 +35,7 @@ export class DmChannelDTO { excludedRecipients(excluded_recipients: string[]): DmChannelDTO { return { ...this, - recipients: this.recipients.filter((r) => !excluded_recipients.includes(r.id)), + recipients: this.recipients.filter((r) => !excluded_recipients.includes(r.id)) }; } } diff --git a/src/util/entities/Application.ts b/src/util/entities/Application.ts index 103f8e84..35fc496d 100644 --- a/src/util/entities/Application.ts +++ b/src/util/entities/Application.ts @@ -1,6 +1,5 @@ -import { Column, Entity, JoinColumn, ManyToOne, OneToOne, RelationId } from "typeorm"; +import { Column, Entity, JoinColumn, ManyToOne, OneToOne } from "typeorm"; import { BaseClass } from "./BaseClass"; -import { Guild } from "./Guild"; import { Team } from "./Team"; import { User } from "./User"; @@ -8,77 +7,77 @@ import { User } from "./User"; export class Application extends BaseClass { @Column() name: string; - + @Column({ nullable: true }) icon?: string; - + @Column({ nullable: true }) description: string; - + @Column({ nullable: true }) summary: string = ""; - + @Column({ type: "simple-json", nullable: true }) type?: any; - + @Column() hook: boolean = true; - + @Column() bot_public?: boolean = true; - + @Column() bot_require_code_grant?: boolean = false; - + @Column() verify_key: string; - + @JoinColumn({ name: "owner_id" }) @ManyToOne(() => User) owner: User; - + @Column() flags: number = 0; - + @Column({ type: "simple-array", nullable: true }) redirect_uris: string[] = []; - + @Column({ nullable: true }) rpc_application_state: number = 0; - + @Column({ nullable: true }) store_application_state: number = 1; - + @Column({ nullable: true }) verification_state: number = 1; - + @Column({ nullable: true }) interactions_endpoint_url?: string; - + @Column({ nullable: true }) integration_public: boolean = true; - + @Column({ nullable: true }) integration_require_code_grant: boolean = false; - + @Column({ nullable: true }) discoverability_state: number = 1; - + @Column({ nullable: true }) discovery_eligibility_flags: number = 2240; - + @JoinColumn({ name: "bot_user_id" }) @OneToOne(() => User) bot?: User; - + @Column({ type: "simple-array", nullable: true }) tags?: string[]; - + @Column({ nullable: true }) cover_image?: string; // the application's default rich presence invite cover image hash - + @Column({ type: "simple-json", nullable: true }) - install_params?: {scopes: string[], permissions: string}; + install_params?: { scopes: string[]; permissions: string }; @Column({ nullable: true }) terms_of_service_url?: string; @@ -90,7 +89,7 @@ export class Application extends BaseClass { //@Column({ type: "simple-array", nullable: true }) //rpc_origins?: string[]; - + //@JoinColumn({ name: "guild_id" }) //@ManyToOne(() => Guild) //guild?: Guild; // if this application is a game sold, this field will be the guild to which it has been linked @@ -107,8 +106,7 @@ export class Application extends BaseClass { nullable: true }) team?: Team; - - } +} export interface ApplicationCommand { id: string; @@ -140,7 +138,7 @@ export enum ApplicationCommandOptionType { BOOLEAN = 5, USER = 6, CHANNEL = 7, - ROLE = 8, + ROLE = 8 } export interface ApplicationCommandInteractionData { diff --git a/src/util/entities/Attachment.ts b/src/util/entities/Attachment.ts index 7b4b17eb..8392f415 100644 --- a/src/util/entities/Attachment.ts +++ b/src/util/entities/Attachment.ts @@ -32,7 +32,7 @@ export class Attachment extends BaseClass { @JoinColumn({ name: "message_id" }) @ManyToOne(() => require("./Message").Message, (message: import("./Message").Message) => message.attachments, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) message: import("./Message").Message; diff --git a/src/util/entities/AuditLog.ts b/src/util/entities/AuditLog.ts index b003e7ba..6f394f42 100644 --- a/src/util/entities/AuditLog.ts +++ b/src/util/entities/AuditLog.ts @@ -5,24 +5,24 @@ import { User } from "./User"; export enum AuditLogEvents { // guild level - GUILD_UPDATE = 1, + GUILD_UPDATE = 1, GUILD_IMPORT = 2, GUILD_EXPORTED = 3, GUILD_ARCHIVE = 4, GUILD_UNARCHIVE = 5, // join-leave - USER_JOIN = 6, + USER_JOIN = 6, USER_LEAVE = 7, // channels - CHANNEL_CREATE = 10, + CHANNEL_CREATE = 10, CHANNEL_UPDATE = 11, CHANNEL_DELETE = 12, // permission overrides - CHANNEL_OVERWRITE_CREATE = 13, + CHANNEL_OVERWRITE_CREATE = 13, CHANNEL_OVERWRITE_UPDATE = 14, CHANNEL_OVERWRITE_DELETE = 15, // kick and ban - MEMBER_KICK = 20, + MEMBER_KICK = 20, MEMBER_PRUNE = 21, MEMBER_BAN_ADD = 22, MEMBER_BAN_REMOVE = 23, @@ -79,18 +79,18 @@ export enum AuditLogEvents { // application commands APPLICATION_COMMAND_PERMISSION_UPDATE = 121, // automod - POLICY_CREATE = 140, + POLICY_CREATE = 140, POLICY_UPDATE = 141, POLICY_DELETE = 142, - MESSAGE_BLOCKED_BY_POLICIES = 143, // in fosscord, blocked messages are stealth-dropped + MESSAGE_BLOCKED_BY_POLICIES = 143, // in fosscord, blocked messages are stealth-dropped // instance policies affecting the guild GUILD_AFFECTED_BY_POLICIES = 216, // message moves IN_GUILD_MESSAGE_MOVE = 223, CROSS_GUILD_MESSAGE_MOVE = 224, // message routing - ROUTE_CREATE = 225, - ROUTE_UPDATE = 226, + ROUTE_CREATE = 225, + ROUTE_UPDATE = 226 } @Entity("audit_logs") diff --git a/src/util/entities/BackupCodes.ts b/src/util/entities/BackupCodes.ts index 9092c14e..503b1dbd 100644 --- a/src/util/entities/BackupCodes.ts +++ b/src/util/entities/BackupCodes.ts @@ -1,4 +1,4 @@ -import { Column, Entity, JoinColumn, ManyToOne, RelationId } from "typeorm"; +import { Column, Entity, JoinColumn, ManyToOne } from "typeorm"; import { BaseClass } from "./BaseClass"; import { User } from "./User"; @@ -16,4 +16,4 @@ export class BackupCode extends BaseClass { @Column() expired: boolean; -} \ No newline at end of file +} diff --git a/src/util/entities/Ban.ts b/src/util/entities/Ban.ts index 9504bd8e..27c75278 100644 --- a/src/util/entities/Ban.ts +++ b/src/util/entities/Ban.ts @@ -11,7 +11,7 @@ export class Ban extends BaseClass { @JoinColumn({ name: "user_id" }) @ManyToOne(() => User, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) user: User; @@ -21,7 +21,7 @@ export class Ban extends BaseClass { @JoinColumn({ name: "guild_id" }) @ManyToOne(() => Guild, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) guild: Guild; diff --git a/src/util/entities/Categories.ts b/src/util/entities/Categories.ts index 81fbc303..08a79112 100644 --- a/src/util/entities/Categories.ts +++ b/src/util/entities/Categories.ts @@ -1,4 +1,4 @@ -import { PrimaryColumn, Column, Entity} from "typeorm"; +import { Column, Entity, PrimaryColumn } from "typeorm"; import { BaseClassWithoutId } from "./BaseClass"; // TODO: categories: @@ -16,18 +16,18 @@ import { BaseClassWithoutId } from "./BaseClass"; // Also populate discord default categories @Entity("categories") -export class Categories extends BaseClassWithoutId { // Not using snowflake - - @PrimaryColumn() - id: number; +export class Categories extends BaseClassWithoutId { + // Not using snowflake - @Column({ nullable: true }) - name: string; + @PrimaryColumn() + id: number; - @Column({ type: "simple-json" }) - localizations: string; + @Column({ nullable: true }) + name: string; - @Column({ nullable: true }) - is_primary: boolean; + @Column({ type: "simple-json" }) + localizations: string; -} \ No newline at end of file + @Column({ nullable: true }) + is_primary: boolean; +} diff --git a/src/util/entities/Channel.ts b/src/util/entities/Channel.ts index a576d7af..23fc6544 100644 --- a/src/util/entities/Channel.ts +++ b/src/util/entities/Channel.ts @@ -1,391 +1,383 @@ -import { Column, Entity, JoinColumn, ManyToOne, OneToMany, RelationId } from "typeorm"; -import { OrmUtils } from "../util/imports/OrmUtils"; -import { BaseClass } from "./BaseClass"; -import { Guild } from "./Guild"; -import { PublicUserProjection, User } from "./User"; -import { HTTPError } from "../util/imports/HTTPError"; -import { containsAll, emitEvent, getPermission, Snowflake, trimSpecial, InvisibleCharacters } from "../util"; -import { ChannelCreateEvent, ChannelRecipientRemoveEvent } from "../interfaces"; -import { Recipient } from "./Recipient"; -import { Message } from "./Message"; -import { ReadState } from "./ReadState"; -import { Invite } from "./Invite"; -import { VoiceState } from "./VoiceState"; -import { Webhook } from "./Webhook"; -import { DmChannelDTO } from "../dtos"; - -export enum ChannelType { - GUILD_TEXT = 0, // a text channel within a guild - DM = 1, // a direct message between users - GUILD_VOICE = 2, // a voice channel within a guild - GROUP_DM = 3, // a direct message between multiple users - GUILD_CATEGORY = 4, // an organizational category that contains zero or more channels - GUILD_NEWS = 5, // a channel that users can follow and crosspost into a guild or route - GUILD_STORE = 6, // a channel in which game developers can sell their things - ENCRYPTED = 7, // end-to-end encrypted channel - ENCRYPTED_THREAD = 8, // end-to-end encrypted thread channel - TRANSACTIONAL = 9, // event chain style transactional channel - GUILD_NEWS_THREAD = 10, // a temporary sub-channel within a GUILD_NEWS channel - GUILD_PUBLIC_THREAD = 11, // a temporary sub-channel within a GUILD_TEXT channel - GUILD_PRIVATE_THREAD = 12, // a temporary sub-channel within a GUILD_TEXT channel that is only viewable by those invited and those with the MANAGE_THREADS permission - GUILD_STAGE_VOICE = 13, // a voice channel for hosting events with an audience - DIRECTORY = 14, // guild directory listing channel - GUILD_FORUM = 15, // forum composed of IM threads - TICKET_TRACKER = 33, // ticket tracker, individual ticket items shall have type 12 - KANBAN = 34, // confluence like kanban board - VOICELESS_WHITEBOARD = 35, // whiteboard but without voice (whiteboard + voice is the same as stage) - CUSTOM_START = 64, // start custom channel types from here - UNHANDLED = 255, // unhandled unowned pass-through channel type -} - -@Entity("channels") -export class Channel extends BaseClass { - @Column() - created_at: Date; - - @Column({ nullable: true }) - name?: string; - - @Column({ type: "text", nullable: true }) - icon?: string | null; - - @Column({ type: "int" }) - type: ChannelType; - - @OneToMany(() => Recipient, (recipient: Recipient) => recipient.channel, { - cascade: true, - orphanedRowAction: "delete", - }) - recipients?: Recipient[]; - - @Column({ nullable: true }) - last_message_id: string; - - @Column({ nullable: true }) - @RelationId((channel: Channel) => channel.guild) - guild_id?: string; - - @JoinColumn({ name: "guild_id" }) - @ManyToOne(() => Guild, { - onDelete: "CASCADE", - }) - guild: Guild; - - @Column({ nullable: true }) - @RelationId((channel: Channel) => channel.parent) - parent_id: string; - - @JoinColumn({ name: "parent_id" }) - @ManyToOne(() => Channel) - parent?: Channel; - - // for group DMs and owned custom channel types - @Column({ nullable: true }) - @RelationId((channel: Channel) => channel.owner) - owner_id: string; - - @JoinColumn({ name: "owner_id" }) - @ManyToOne(() => User) - owner: User; - - @Column({ nullable: true }) - last_pin_timestamp?: number; - - @Column({ nullable: true }) - default_auto_archive_duration?: number; - - @Column({ nullable: true }) - position?: number; - - @Column({ type: "simple-json", nullable: true }) - permission_overwrites?: ChannelPermissionOverwrite[]; - - @Column({ nullable: true }) - video_quality_mode?: number; - - @Column({ nullable: true }) - bitrate?: number; - - @Column({ nullable: true }) - user_limit?: number; - - @Column({ nullable: true }) - nsfw?: boolean; - - @Column({ nullable: true }) - rate_limit_per_user?: number; - - @Column({ nullable: true }) - topic?: string; - - @OneToMany(() => Invite, (invite: Invite) => invite.channel, { - cascade: true, - orphanedRowAction: "delete", - }) - invites?: Invite[]; - - @Column({ nullable: true }) - retention_policy_id?: string; - - @OneToMany(() => Message, (message: Message) => message.channel, { - cascade: true, - orphanedRowAction: "delete", - }) - messages?: Message[]; - - @OneToMany(() => VoiceState, (voice_state: VoiceState) => voice_state.channel, { - cascade: true, - orphanedRowAction: "delete", - }) - voice_states?: VoiceState[]; - - @OneToMany(() => ReadState, (read_state: ReadState) => read_state.channel, { - cascade: true, - orphanedRowAction: "delete", - }) - read_states?: ReadState[]; - - @OneToMany(() => Webhook, (webhook: Webhook) => webhook.channel, { - cascade: true, - orphanedRowAction: "delete", - }) - webhooks?: Webhook[]; - - @Column({ nullable: true }) - flags?: number = 0; - - @Column({ nullable: true }) - default_thread_rate_limit_per_user?: number = 0; - - - // TODO: DM channel - static async createChannel( - channel: Partial<Channel>, - user_id: string = "0", - opts?: { - keepId?: boolean; - skipExistsCheck?: boolean; - skipPermissionCheck?: boolean; - skipEventEmit?: boolean; - skipNameChecks?: boolean; - } - ) { - if (!opts?.skipPermissionCheck) { - // Always check if user has permission first - const permissions = await getPermission(user_id, channel.guild_id); - permissions.hasThrow("MANAGE_CHANNELS"); - } - - if (!opts?.skipNameChecks) { - const guild = await Guild.findOneOrFail({ where: { id: channel.guild_id } }); - if (!guild.features.includes("ALLOW_INVALID_CHANNEL_NAMES") && channel.name) { - for (let character of InvisibleCharacters) - if (channel.name.includes(character)) - throw new HTTPError("Channel name cannot include invalid characters", 403); - - if (channel.name.match(/\-\-+/g)) - throw new HTTPError("Channel name cannot include multiple adjacent dashes.", 403); - - if (channel.name.charAt(0) === "-" || channel.name.charAt(channel.name.length - 1) === "-") - throw new HTTPError("Channel name cannot start/end with dash.", 403); - } - - if (!guild.features.includes("ALLOW_UNNAMED_CHANNELS")) { - if (!channel.name) throw new HTTPError("Channel name cannot be empty.", 403); - } - } - - switch (channel.type) { - case ChannelType.GUILD_TEXT: - case ChannelType.GUILD_NEWS: - case ChannelType.GUILD_VOICE: - if (channel.parent_id && !opts?.skipExistsCheck) { - const exists = await Channel.findOneOrFail({ where: { id: channel.parent_id } }); - if (!exists) throw new HTTPError("Parent id channel doesn't exist", 400); - if (exists.guild_id !== channel.guild_id) - throw new HTTPError("The category channel needs to be in the guild"); - } - break; - case ChannelType.GUILD_CATEGORY: - case ChannelType.UNHANDLED: - break; - case ChannelType.DM: - case ChannelType.GROUP_DM: - throw new HTTPError("You can't create a dm channel in a guild"); - case ChannelType.GUILD_STORE: - default: - throw new HTTPError("Not yet supported"); - } - - if (!channel.permission_overwrites) channel.permission_overwrites = []; - // TODO: eagerly auto generate position of all guild channels - - channel = { - ...channel, - ...(!opts?.keepId && { id: Snowflake.generate() }), - created_at: new Date(), - position: (channel.type === ChannelType.UNHANDLED ? 0 : channel.position) || 0, - }; - - await Promise.all([ - OrmUtils.mergeDeep(new Channel(), channel).save(), - !opts?.skipEventEmit - ? emitEvent({ - event: "CHANNEL_CREATE", - data: channel, - guild_id: channel.guild_id, - } as ChannelCreateEvent) - : Promise.resolve(), - ]); - - return channel; - } - - static async createDMChannel(recipients: string[], creator_user_id: string, name?: string) { - recipients = recipients.unique().filter((x) => x !== creator_user_id); - const otherRecipientsUsers = await User.find({ where: recipients.map((x) => ({ id: x })) }); - - // TODO: check config for max number of recipients - /** if you want to disallow note to self channels, uncomment the conditional below - if (otherRecipientsUsers.length !== recipients.length) { - throw new HTTPError("Recipient/s not found"); - } - **/ - - const type = recipients.length > 1 ? ChannelType.GROUP_DM : ChannelType.DM; - - let channel = null; - - const channelRecipients = [...recipients, creator_user_id]; - - const userRecipients = await Recipient.find({ - where: { user_id: creator_user_id }, - relations: ["channel", "channel.recipients"], - }); - - for (let ur of userRecipients) { - let re = ur.channel.recipients!.map((r) => r.user_id); - if (re.length === channelRecipients.length) { - if (containsAll(re, channelRecipients)) { - if (channel == null) { - channel = ur.channel; - ur = OrmUtils.mergeDeep(ur, { closed: false }); - await ur.save(); - } - } - } - } - - if (channel == null) { - name = trimSpecial(name); - - channel = await ( - OrmUtils.mergeDeep(new Channel(), { - name, - type, - owner_id: type === ChannelType.DM ? undefined : null, // 1:1 DMs are ownerless in fosscord-server - created_at: new Date(), - last_message_id: null, - recipients: channelRecipients.map((x) => - OrmUtils.mergeDeep(new Recipient(), { - user_id: x, - closed: !(type === ChannelType.GROUP_DM || x === creator_user_id), - }) - ), - }) as Channel - ).save(); - } - - const channel_dto = await DmChannelDTO.from(channel); - - if (type === ChannelType.GROUP_DM) { - for (let recipient of channel.recipients!) { - await emitEvent({ - event: "CHANNEL_CREATE", - data: channel_dto.excludedRecipients([recipient.user_id]), - user_id: recipient.user_id, - }); - } - } else { - await emitEvent({ event: "CHANNEL_CREATE", data: channel_dto, user_id: creator_user_id }); - } - - if (recipients.length === 1) return channel_dto; - else return channel_dto.excludedRecipients([creator_user_id]); - } - - static async removeRecipientFromChannel(channel: Channel, user_id: string) { - await Recipient.delete({ channel_id: channel.id, user_id: user_id }); - channel.recipients = channel.recipients?.filter((r) => r.user_id !== user_id); - - if (channel.recipients?.length === 0) { - await Channel.deleteChannel(channel); - await emitEvent({ - event: "CHANNEL_DELETE", - data: await DmChannelDTO.from(channel, [user_id]), - user_id: user_id, - }); - return; - } - - await emitEvent({ - event: "CHANNEL_DELETE", - data: await DmChannelDTO.from(channel, [user_id]), - user_id: user_id, - }); - - //If the owner leave the server user is the new owner - if (channel.owner_id === user_id) { - channel.owner_id = "1"; // The channel is now owned by the server user - await emitEvent({ - event: "CHANNEL_UPDATE", - data: await DmChannelDTO.from(channel, [user_id]), - channel_id: channel.id, - }); - } - - await channel.save(); - - await emitEvent({ - event: "CHANNEL_RECIPIENT_REMOVE", - data: { - channel_id: channel.id, - user: await User.findOneOrFail({ where: { id: user_id }, select: PublicUserProjection }), - }, - channel_id: channel.id, - } as ChannelRecipientRemoveEvent); - } - - static async deleteChannel(channel: Channel) { - await Message.delete({ channel_id: channel.id }); //TODO we should also delete the attachments from the cdn but to do that we need to move cdn.ts in util - //TODO before deleting the channel we should check and delete other relations - await Channel.delete({ id: channel.id }); - } - - isDm() { - return this.type === ChannelType.DM || this.type === ChannelType.GROUP_DM; - } - - // Does the channel support sending messages ( eg categories do not ) - isWritable() { - const disallowedChannelTypes = [ - ChannelType.GUILD_CATEGORY, - ChannelType.GUILD_STAGE_VOICE, - ChannelType.VOICELESS_WHITEBOARD, - ]; - return disallowedChannelTypes.indexOf(this.type) == -1; - } -} - -export interface ChannelPermissionOverwrite { - allow: string; - deny: string; - id: string; - type: ChannelPermissionOverwriteType; -} - -export enum ChannelPermissionOverwriteType { - role = 0, - member = 1, - group = 2, -} +import { Column, Entity, JoinColumn, ManyToOne, OneToMany, RelationId } from "typeorm"; +import { DmChannelDTO } from "../dtos"; +import { ChannelCreateEvent, ChannelRecipientRemoveEvent } from "../interfaces"; +import { containsAll, emitEvent, getPermission, InvisibleCharacters, Snowflake, trimSpecial } from "../util"; +import { HTTPError } from "../util/imports/HTTPError"; +import { OrmUtils } from "../util/imports/OrmUtils"; +import { BaseClass } from "./BaseClass"; +import { Guild } from "./Guild"; +import { Invite } from "./Invite"; +import { Message } from "./Message"; +import { ReadState } from "./ReadState"; +import { Recipient } from "./Recipient"; +import { PublicUserProjection, User } from "./User"; +import { VoiceState } from "./VoiceState"; +import { Webhook } from "./Webhook"; + +export enum ChannelType { + GUILD_TEXT = 0, // a text channel within a guild + DM = 1, // a direct message between users + GUILD_VOICE = 2, // a voice channel within a guild + GROUP_DM = 3, // a direct message between multiple users + GUILD_CATEGORY = 4, // an organizational category that contains zero or more channels + GUILD_NEWS = 5, // a channel that users can follow and crosspost into a guild or route + GUILD_STORE = 6, // a channel in which game developers can sell their things + ENCRYPTED = 7, // end-to-end encrypted channel + ENCRYPTED_THREAD = 8, // end-to-end encrypted thread channel + TRANSACTIONAL = 9, // event chain style transactional channel + GUILD_NEWS_THREAD = 10, // a temporary sub-channel within a GUILD_NEWS channel + GUILD_PUBLIC_THREAD = 11, // a temporary sub-channel within a GUILD_TEXT channel + GUILD_PRIVATE_THREAD = 12, // a temporary sub-channel within a GUILD_TEXT channel that is only viewable by those invited and those with the MANAGE_THREADS permission + GUILD_STAGE_VOICE = 13, // a voice channel for hosting events with an audience + DIRECTORY = 14, // guild directory listing channel + GUILD_FORUM = 15, // forum composed of IM threads + TICKET_TRACKER = 33, // ticket tracker, individual ticket items shall have type 12 + KANBAN = 34, // confluence like kanban board + VOICELESS_WHITEBOARD = 35, // whiteboard but without voice (whiteboard + voice is the same as stage) + CUSTOM_START = 64, // start custom channel types from here + UNHANDLED = 255 // unhandled unowned pass-through channel type +} + +@Entity("channels") +export class Channel extends BaseClass { + @Column() + created_at: Date; + + @Column({ nullable: true }) + name?: string; + + @Column({ type: "text", nullable: true }) + icon?: string | null; + + @Column({ type: "int" }) + type: ChannelType; + + @OneToMany(() => Recipient, (recipient: Recipient) => recipient.channel, { + cascade: true, + orphanedRowAction: "delete" + }) + recipients?: Recipient[]; + + @Column({ nullable: true }) + last_message_id: string; + + @Column({ nullable: true }) + @RelationId((channel: Channel) => channel.guild) + guild_id?: string; + + @JoinColumn({ name: "guild_id" }) + @ManyToOne(() => Guild, { + onDelete: "CASCADE" + }) + guild: Guild; + + @Column({ nullable: true }) + @RelationId((channel: Channel) => channel.parent) + parent_id: string; + + @JoinColumn({ name: "parent_id" }) + @ManyToOne(() => Channel) + parent?: Channel; + + // for group DMs and owned custom channel types + @Column({ nullable: true }) + @RelationId((channel: Channel) => channel.owner) + owner_id: string; + + @JoinColumn({ name: "owner_id" }) + @ManyToOne(() => User) + owner: User; + + @Column({ nullable: true }) + last_pin_timestamp?: number; + + @Column({ nullable: true }) + default_auto_archive_duration?: number; + + @Column({ nullable: true }) + position?: number; + + @Column({ type: "simple-json", nullable: true }) + permission_overwrites?: ChannelPermissionOverwrite[]; + + @Column({ nullable: true }) + video_quality_mode?: number; + + @Column({ nullable: true }) + bitrate?: number; + + @Column({ nullable: true }) + user_limit?: number; + + @Column({ nullable: true }) + nsfw?: boolean; + + @Column({ nullable: true }) + rate_limit_per_user?: number; + + @Column({ nullable: true }) + topic?: string; + + @OneToMany(() => Invite, (invite: Invite) => invite.channel, { + cascade: true, + orphanedRowAction: "delete" + }) + invites?: Invite[]; + + @Column({ nullable: true }) + retention_policy_id?: string; + + @OneToMany(() => Message, (message: Message) => message.channel, { + cascade: true, + orphanedRowAction: "delete" + }) + messages?: Message[]; + + @OneToMany(() => VoiceState, (voice_state: VoiceState) => voice_state.channel, { + cascade: true, + orphanedRowAction: "delete" + }) + voice_states?: VoiceState[]; + + @OneToMany(() => ReadState, (read_state: ReadState) => read_state.channel, { + cascade: true, + orphanedRowAction: "delete" + }) + read_states?: ReadState[]; + + @OneToMany(() => Webhook, (webhook: Webhook) => webhook.channel, { + cascade: true, + orphanedRowAction: "delete" + }) + webhooks?: Webhook[]; + + @Column({ nullable: true }) + flags?: number = 0; + + @Column({ nullable: true }) + default_thread_rate_limit_per_user?: number = 0; + + // TODO: DM channel + static async createChannel( + channel: Partial<Channel>, + user_id: string = "0", + opts?: { + keepId?: boolean; + skipExistsCheck?: boolean; + skipPermissionCheck?: boolean; + skipEventEmit?: boolean; + skipNameChecks?: boolean; + } + ) { + if (!opts?.skipPermissionCheck) { + // Always check if user has permission first + const permissions = await getPermission(user_id, channel.guild_id); + permissions.hasThrow("MANAGE_CHANNELS"); + } + + if (!opts?.skipNameChecks) { + const guild = await Guild.findOneOrFail({ where: { id: channel.guild_id } }); + if (!guild.features.includes("ALLOW_INVALID_CHANNEL_NAMES") && channel.name) { + for (let character of InvisibleCharacters) + if (channel.name.includes(character)) throw new HTTPError("Channel name cannot include invalid characters", 403); + + if (channel.name.match(/\-\-+/g)) throw new HTTPError("Channel name cannot include multiple adjacent dashes.", 403); + + if (channel.name.charAt(0) === "-" || channel.name.charAt(channel.name.length - 1) === "-") + throw new HTTPError("Channel name cannot start/end with dash.", 403); + } + + if (!guild.features.includes("ALLOW_UNNAMED_CHANNELS")) { + if (!channel.name) throw new HTTPError("Channel name cannot be empty.", 403); + } + } + + switch (channel.type) { + case ChannelType.GUILD_TEXT: + case ChannelType.GUILD_NEWS: + case ChannelType.GUILD_VOICE: + if (channel.parent_id && !opts?.skipExistsCheck) { + const exists = await Channel.findOneOrFail({ where: { id: channel.parent_id } }); + if (!exists) throw new HTTPError("Parent id channel doesn't exist", 400); + if (exists.guild_id !== channel.guild_id) throw new HTTPError("The category channel needs to be in the guild"); + } + break; + case ChannelType.GUILD_CATEGORY: + case ChannelType.UNHANDLED: + break; + case ChannelType.DM: + case ChannelType.GROUP_DM: + throw new HTTPError("You can't create a dm channel in a guild"); + case ChannelType.GUILD_STORE: + default: + throw new HTTPError("Not yet supported"); + } + + if (!channel.permission_overwrites) channel.permission_overwrites = []; + // TODO: eagerly auto generate position of all guild channels + + channel = { + ...channel, + ...(!opts?.keepId && { id: Snowflake.generate() }), + created_at: new Date(), + position: (channel.type === ChannelType.UNHANDLED ? 0 : channel.position) || 0 + }; + + await Promise.all([ + OrmUtils.mergeDeep(new Channel(), channel).save(), + !opts?.skipEventEmit + ? emitEvent({ + event: "CHANNEL_CREATE", + data: channel, + guild_id: channel.guild_id + } as ChannelCreateEvent) + : Promise.resolve() + ]); + + return channel; + } + + static async createDMChannel(recipients: string[], creator_user_id: string, name?: string) { + recipients = recipients.unique().filter((x) => x !== creator_user_id); + const otherRecipientsUsers = await User.find({ where: recipients.map((x) => ({ id: x })) }); + + // TODO: check config for max number of recipients + /** if you want to disallow note to self channels, uncomment the conditional below + if (otherRecipientsUsers.length !== recipients.length) { + throw new HTTPError("Recipient/s not found"); + } + **/ + + const type = recipients.length > 1 ? ChannelType.GROUP_DM : ChannelType.DM; + + let channel = null; + + const channelRecipients = [...recipients, creator_user_id]; + + const userRecipients = await Recipient.find({ + where: { user_id: creator_user_id }, + relations: ["channel", "channel.recipients"] + }); + + for (let ur of userRecipients) { + let re = ur.channel.recipients!.map((r) => r.user_id); + if (re.length === channelRecipients.length) { + if (containsAll(re, channelRecipients)) { + if (channel == null) { + channel = ur.channel; + ur = OrmUtils.mergeDeep(ur, { closed: false }); + await ur.save(); + } + } + } + } + + if (channel == null) { + name = trimSpecial(name); + + channel = await ( + OrmUtils.mergeDeep(new Channel(), { + name, + type, + owner_id: type === ChannelType.DM ? undefined : null, // 1:1 DMs are ownerless in fosscord-server + created_at: new Date(), + last_message_id: null, + recipients: channelRecipients.map((x) => + OrmUtils.mergeDeep(new Recipient(), { + user_id: x, + closed: !(type === ChannelType.GROUP_DM || x === creator_user_id) + }) + ) + }) as Channel + ).save(); + } + + const channel_dto = await DmChannelDTO.from(channel); + + if (type === ChannelType.GROUP_DM) { + for (let recipient of channel.recipients!) { + await emitEvent({ + event: "CHANNEL_CREATE", + data: channel_dto.excludedRecipients([recipient.user_id]), + user_id: recipient.user_id + }); + } + } else { + await emitEvent({ event: "CHANNEL_CREATE", data: channel_dto, user_id: creator_user_id }); + } + + if (recipients.length === 1) return channel_dto; + else return channel_dto.excludedRecipients([creator_user_id]); + } + + static async removeRecipientFromChannel(channel: Channel, user_id: string) { + await Recipient.delete({ channel_id: channel.id, user_id: user_id }); + channel.recipients = channel.recipients?.filter((r) => r.user_id !== user_id); + + if (channel.recipients?.length === 0) { + await Channel.deleteChannel(channel); + await emitEvent({ + event: "CHANNEL_DELETE", + data: await DmChannelDTO.from(channel, [user_id]), + user_id: user_id + }); + return; + } + + await emitEvent({ + event: "CHANNEL_DELETE", + data: await DmChannelDTO.from(channel, [user_id]), + user_id: user_id + }); + + //If the owner leave the server user is the new owner + if (channel.owner_id === user_id) { + channel.owner_id = "1"; // The channel is now owned by the server user + await emitEvent({ + event: "CHANNEL_UPDATE", + data: await DmChannelDTO.from(channel, [user_id]), + channel_id: channel.id + }); + } + + await channel.save(); + + await emitEvent({ + event: "CHANNEL_RECIPIENT_REMOVE", + data: { + channel_id: channel.id, + user: await User.findOneOrFail({ where: { id: user_id }, select: PublicUserProjection }) + }, + channel_id: channel.id + } as ChannelRecipientRemoveEvent); + } + + static async deleteChannel(channel: Channel) { + await Message.delete({ channel_id: channel.id }); //TODO we should also delete the attachments from the cdn but to do that we need to move cdn.ts in util + //TODO before deleting the channel we should check and delete other relations + await Channel.delete({ id: channel.id }); + } + + isDm() { + return this.type === ChannelType.DM || this.type === ChannelType.GROUP_DM; + } + + // Does the channel support sending messages ( eg categories do not ) + isWritable() { + const disallowedChannelTypes = [ChannelType.GUILD_CATEGORY, ChannelType.GUILD_STAGE_VOICE, ChannelType.VOICELESS_WHITEBOARD]; + return disallowedChannelTypes.indexOf(this.type) == -1; + } +} + +export interface ChannelPermissionOverwrite { + allow: string; + deny: string; + id: string; + type: ChannelPermissionOverwriteType; +} + +export enum ChannelPermissionOverwriteType { + role = 0, + member = 1, + group = 2 +} diff --git a/src/util/entities/ClientRelease.ts b/src/util/entities/ClientRelease.ts index c5afd307..2723ab67 100644 --- a/src/util/entities/ClientRelease.ts +++ b/src/util/entities/ClientRelease.ts @@ -1,4 +1,4 @@ -import { Column, Entity} from "typeorm"; +import { Column, Entity } from "typeorm"; import { BaseClass } from "./BaseClass"; @Entity("client_release") diff --git a/src/util/entities/Config.ts b/src/util/entities/Config.ts index 606fe901..fc33bb65 100644 --- a/src/util/entities/Config.ts +++ b/src/util/entities/Config.ts @@ -8,4 +8,4 @@ export class ConfigEntity extends BaseClassWithoutId { @Column({ type: "simple-json", nullable: true }) value: number | boolean | null | string | undefined; -} \ No newline at end of file +} diff --git a/src/util/entities/ConnectedAccount.ts b/src/util/entities/ConnectedAccount.ts index 09ae30ab..018b3995 100644 --- a/src/util/entities/ConnectedAccount.ts +++ b/src/util/entities/ConnectedAccount.ts @@ -12,7 +12,7 @@ export class ConnectedAccount extends BaseClass { @JoinColumn({ name: "user_id" }) @ManyToOne(() => User, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) user: User; diff --git a/src/util/entities/Emoji.ts b/src/util/entities/Emoji.ts index a3615b7d..a2552995 100644 --- a/src/util/entities/Emoji.ts +++ b/src/util/entities/Emoji.ts @@ -2,7 +2,6 @@ import { Column, Entity, JoinColumn, ManyToOne, RelationId } from "typeorm"; import { User } from "."; import { BaseClass } from "./BaseClass"; import { Guild } from "./Guild"; -import { Role } from "./Role"; @Entity("emojis") export class Emoji extends BaseClass { @@ -17,7 +16,7 @@ export class Emoji extends BaseClass { @JoinColumn({ name: "guild_id" }) @ManyToOne(() => Guild, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) guild: Guild; @@ -40,7 +39,7 @@ export class Emoji extends BaseClass { @Column({ type: "simple-array" }) roles: string[]; // roles this emoji is whitelisted to (new discord feature?) - + @Column({ type: "simple-array", nullable: true }) groups: string[]; // user groups this emoji is whitelisted to (Fosscord extension) } diff --git a/src/util/entities/Encryption.ts b/src/util/entities/Encryption.ts index 6b578d15..43f02962 100644 --- a/src/util/entities/Encryption.ts +++ b/src/util/entities/Encryption.ts @@ -1,35 +1,25 @@ -import { Column, Entity, JoinColumn, ManyToOne, OneToMany, RelationId } from "typeorm"; +import { Column, Entity } from "typeorm"; +import { Snowflake } from "../util"; +import { BitField } from "../util/BitField"; import { BaseClass } from "./BaseClass"; -import { Guild } from "./Guild"; -import { PublicUserProjection, User } from "./User"; -import { HTTPError } from ".."; -import { containsAll, emitEvent, getPermission, Snowflake, trimSpecial, InvisibleCharacters } from "../util"; -import { BitField, BitFieldResolvable, BitFlag } from "../util/BitField"; -import { Recipient } from "./Recipient"; -import { Message } from "./Message"; -import { ReadState } from "./ReadState"; -import { Invite } from "./Invite"; -import { DmChannelDTO } from "../dtos"; @Entity("security_settings") export class SecuritySettings extends BaseClass { + @Column({ nullable: true }) + guild_id: Snowflake; - @Column({nullable: true}) - guild_id: Snowflake; + @Column({ nullable: true }) + channel_id: Snowflake; - @Column({nullable: true}) - channel_id: Snowflake; + @Column() + encryption_permission_mask: BitField; - @Column() - encryption_permission_mask: BitField; + @Column() + allowed_algorithms: string[]; - @Column() - allowed_algorithms: string[]; - - @Column() - current_algorithm: string; - - @Column({nullable: true}) - used_since_message: Snowflake; + @Column() + current_algorithm: string; + @Column({ nullable: true }) + used_since_message: Snowflake; } diff --git a/src/util/entities/Group.ts b/src/util/entities/Group.ts index b24d38cf..23aaabf2 100644 --- a/src/util/entities/Group.ts +++ b/src/util/entities/Group.ts @@ -1,11 +1,11 @@ -import { Column, Entity, JoinColumn, ManyToOne, RelationId } from "typeorm"; +import { Column, Entity } from "typeorm"; import { BaseClass } from "./BaseClass"; @Entity("groups") export class UserGroup extends BaseClass { - @Column({ nullable: true }) - parent?: BigInt; + @Column({ nullable: true }) + parent?: BigInt; @Column() color: number; @@ -13,7 +13,7 @@ export class UserGroup extends BaseClass { @Column() hoist: boolean; - @Column() + @Column() mentionable: boolean; @Column() diff --git a/src/util/entities/Guild.ts b/src/util/entities/Guild.ts index d146e577..015c6d04 100644 --- a/src/util/entities/Guild.ts +++ b/src/util/entities/Guild.ts @@ -1,6 +1,6 @@ -import { Column, Entity, JoinColumn, ManyToMany, ManyToOne, OneToMany, OneToOne, RelationId } from "typeorm"; -import { OrmUtils } from "../util/imports/OrmUtils"; +import { Column, Entity, JoinColumn, ManyToOne, OneToMany, RelationId } from "typeorm"; import { Config, handleFile, Snowflake } from ".."; +import { OrmUtils } from "../util/imports/OrmUtils"; import { Ban } from "./Ban"; import { BaseClass } from "./BaseClass"; import { Channel } from "./Channel"; @@ -32,15 +32,7 @@ import { Webhook } from "./Webhook"; // "Gacha" // ], -export const PublicGuildRelations = [ - "channels", - "emojis", - "members", - "roles", - "stickers", - "voice_states", - "members.user", -]; +export const PublicGuildRelations = ["channels", "emojis", "members", "roles", "stickers", "voice_states", "members.user"]; @Entity("guilds") export class Guild extends BaseClass { @@ -63,7 +55,7 @@ export class Guild extends BaseClass { @JoinColumn({ name: "ban_ids" }) @OneToMany(() => Ban, (ban: Ban) => ban.guild, { cascade: true, - orphanedRowAction: "delete", + orphanedRowAction: "delete" }) bans: Ban[]; @@ -113,7 +105,7 @@ export class Guild extends BaseClass { @OneToMany(() => Member, (member: Member) => member.guild, { cascade: true, orphanedRowAction: "delete", - onDelete: "CASCADE", + onDelete: "CASCADE" }) members: Member[]; @@ -121,14 +113,14 @@ export class Guild extends BaseClass { @OneToMany(() => Role, (role: Role) => role.guild, { cascade: true, orphanedRowAction: "delete", - onDelete: "CASCADE", + onDelete: "CASCADE" }) roles: Role[]; @JoinColumn({ name: "channel_ids" }) @OneToMany(() => Channel, (channel: Channel) => channel.guild, { cascade: true, - orphanedRowAction: "delete", + orphanedRowAction: "delete" }) channels: Channel[]; @@ -144,7 +136,7 @@ export class Guild extends BaseClass { @OneToMany(() => Emoji, (emoji: Emoji) => emoji.guild, { cascade: true, orphanedRowAction: "delete", - onDelete: "CASCADE", + onDelete: "CASCADE" }) emojis: Emoji[]; @@ -152,7 +144,7 @@ export class Guild extends BaseClass { @OneToMany(() => Sticker, (sticker: Sticker) => sticker.guild, { cascade: true, orphanedRowAction: "delete", - onDelete: "CASCADE", + onDelete: "CASCADE" }) stickers: Sticker[]; @@ -160,7 +152,7 @@ export class Guild extends BaseClass { @OneToMany(() => Invite, (invite: Invite) => invite.guild, { cascade: true, orphanedRowAction: "delete", - onDelete: "CASCADE", + onDelete: "CASCADE" }) invites: Invite[]; @@ -168,7 +160,7 @@ export class Guild extends BaseClass { @OneToMany(() => VoiceState, (voicestate: VoiceState) => voicestate.guild, { cascade: true, orphanedRowAction: "delete", - onDelete: "CASCADE", + onDelete: "CASCADE" }) voice_states: VoiceState[]; @@ -176,7 +168,7 @@ export class Guild extends BaseClass { @OneToMany(() => Webhook, (webhook: Webhook) => webhook.guild, { cascade: true, orphanedRowAction: "delete", - onDelete: "CASCADE", + onDelete: "CASCADE" }) webhooks: Webhook[]; @@ -282,12 +274,7 @@ export class Guild extends BaseClass { @Column({ nullable: true }) premium_progress_bar_enabled: boolean = false; - static async createGuild(body: { - name?: string; - icon?: string | null; - owner_id?: string; - channels?: Partial<Channel>[]; - }) { + static async createGuild(body: { name?: string; icon?: string | null; owner_id?: string; channels?: Partial<Channel>[] }) { const guild_id = Snowflake.generate(); const guild: Guild = OrmUtils.mergeDeep(new Guild(), { @@ -318,9 +305,9 @@ export class Guild extends BaseClass { welcome_screen: { enabled: false, description: "Fill in your description", - welcome_channels: [], + welcome_channels: [] }, - widget_enabled: true, // NB: don't set it as false to prevent artificial restrictions + widget_enabled: true // NB: don't set it as false to prevent artificial restrictions }); await guild.save(); @@ -338,7 +325,7 @@ export class Guild extends BaseClass { permissions: String("2251804225"), position: 0, icon: null, - unicode_emoji: null, + unicode_emoji: null }); await role.save(); @@ -361,7 +348,7 @@ export class Guild extends BaseClass { keepId: true, skipExistsCheck: true, skipPermissionCheck: true, - skipEventEmit: true, + skipEventEmit: true }); } diff --git a/src/util/entities/Invite.ts b/src/util/entities/Invite.ts index 1e0ebe52..f6ba85d7 100644 --- a/src/util/entities/Invite.ts +++ b/src/util/entities/Invite.ts @@ -1,10 +1,10 @@ -import { Column, Entity, JoinColumn, ManyToOne, RelationId, PrimaryColumn } from "typeorm"; -import { Member } from "./Member"; +import { random } from "@fosscord/api"; +import { Column, Entity, JoinColumn, ManyToOne, PrimaryColumn, RelationId } from "typeorm"; import { BaseClassWithoutId } from "./BaseClass"; import { Channel } from "./Channel"; import { Guild } from "./Guild"; +import { Member } from "./Member"; import { User } from "./User"; -import { random } from "@fosscord/api"; export const PublicInviteRelation = ["inviter", "guild", "channel"]; @@ -37,7 +37,7 @@ export class Invite extends BaseClassWithoutId { @JoinColumn({ name: "guild_id" }) @ManyToOne(() => Guild, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) guild: Guild; @@ -47,7 +47,7 @@ export class Invite extends BaseClassWithoutId { @JoinColumn({ name: "channel_id" }) @ManyToOne(() => Channel, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) channel: Channel; @@ -67,7 +67,7 @@ export class Invite extends BaseClassWithoutId { @JoinColumn({ name: "target_user_id" }) @ManyToOne(() => User, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) target_user?: string; // could be used for "User specific invites" https://github.com/fosscord/fosscord/issues/62 diff --git a/src/util/entities/Member.ts b/src/util/entities/Member.ts index baac58ed..42a014d4 100644 --- a/src/util/entities/Member.ts +++ b/src/util/entities/Member.ts @@ -1,31 +1,14 @@ -import { PublicUser, User } from "./User"; -import { BaseClass } from "./BaseClass"; -import { - Column, - Entity, - Index, - JoinColumn, - JoinTable, - ManyToMany, - ManyToOne, - PrimaryGeneratedColumn, - RelationId, -} from "typeorm"; -import { Guild } from "./Guild"; -import { Config, emitEvent } from "../util"; -import { - GuildCreateEvent, - GuildDeleteEvent, - GuildMemberAddEvent, - GuildMemberRemoveEvent, - GuildMemberUpdateEvent, -} from "../interfaces"; -import { HTTPError } from "../util/imports/HTTPError"; -import { Role } from "./Role"; -import { BaseClassWithoutId } from "./BaseClass"; +import { Column, Entity, Index, JoinColumn, JoinTable, ManyToMany, ManyToOne, PrimaryGeneratedColumn, RelationId } from "typeorm"; import { Ban, PublicGuildRelations } from "."; +import { GuildCreateEvent, GuildDeleteEvent, GuildMemberAddEvent, GuildMemberRemoveEvent, GuildMemberUpdateEvent } from "../interfaces"; +import { Config, emitEvent } from "../util"; import { DiscordApiErrors } from "../util/Constants"; +import { HTTPError } from "../util/imports/HTTPError"; import { OrmUtils } from "../util/imports/OrmUtils"; +import { BaseClassWithoutId } from "./BaseClass"; +import { Guild } from "./Guild"; +import { Role } from "./Role"; +import { PublicUser, User } from "./User"; export const MemberPrivateProjection: (keyof Member)[] = [ "id", @@ -40,7 +23,7 @@ export const MemberPrivateProjection: (keyof Member)[] = [ "premium_since", "roles", "settings", - "user", + "user" ]; @Entity("members") @@ -55,7 +38,7 @@ export class Member extends BaseClassWithoutId { @JoinColumn({ name: "id" }) @ManyToOne(() => User, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) user: User; @@ -65,7 +48,7 @@ export class Member extends BaseClassWithoutId { @JoinColumn({ name: "guild_id" }) @ManyToOne(() => Guild, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) guild: Guild; @@ -77,8 +60,8 @@ export class Member extends BaseClassWithoutId { joinColumn: { name: "index", referencedColumnName: "index" }, inverseJoinColumn: { name: "role_id", - referencedColumnName: "id", - }, + referencedColumnName: "id" + } }) @ManyToMany(() => Role, { cascade: true }) roles: Role[]; @@ -133,22 +116,22 @@ export class Member extends BaseClassWithoutId { return Promise.all([ Member.delete({ id: user_id, - guild_id, + guild_id }), //Guild.decrement({ id: guild_id }, "member_count", -1), emitEvent({ event: "GUILD_DELETE", data: { - id: guild_id, + id: guild_id }, - user_id: user_id, + user_id: user_id } as GuildDeleteEvent), emitEvent({ event: "GUILD_MEMBER_REMOVE", data: { guild_id, user: member.user }, - guild_id, - } as GuildMemberRemoveEvent), + guild_id + } as GuildMemberRemoveEvent) ]); } @@ -158,9 +141,9 @@ export class Member extends BaseClassWithoutId { Member.findOneOrFail({ where: { id: user_id, guild_id }, relations: ["user", "roles"], // we don't want to load the role objects just the ids - select: ["index"], + select: ["index"] }), - Role.findOneOrFail({ where: { id: role_id, guild_id }, select: ["id"] }), + Role.findOneOrFail({ where: { id: role_id, guild_id }, select: ["id"] }) ]); member.roles.push(OrmUtils.mergeDeep(new Role(), { id: role_id })); @@ -171,10 +154,10 @@ export class Member extends BaseClassWithoutId { data: { guild_id, user: member.user, - roles: member.roles.map((x) => x.id), + roles: member.roles.map((x) => x.id) }, - guild_id, - } as GuildMemberUpdateEvent), + guild_id + } as GuildMemberUpdateEvent) ]); } @@ -184,9 +167,9 @@ export class Member extends BaseClassWithoutId { Member.findOneOrFail({ where: { id: user_id, guild_id }, relations: ["user", "roles"], // we don't want to load the role objects just the ids - select: ["index"], + select: ["index"] }), - await Role.findOneOrFail({ where: { id: role_id, guild_id } }), + await Role.findOneOrFail({ where: { id: role_id, guild_id } }) ]); member.roles = member.roles.filter((x) => x.id == role_id); @@ -197,10 +180,10 @@ export class Member extends BaseClassWithoutId { data: { guild_id, user: member.user, - roles: member.roles.map((x) => x.id), + roles: member.roles.map((x) => x.id) }, - guild_id, - } as GuildMemberUpdateEvent), + guild_id + } as GuildMemberUpdateEvent) ]); } @@ -208,9 +191,9 @@ export class Member extends BaseClassWithoutId { const member = await Member.findOneOrFail({ where: { id: user_id, - guild_id, + guild_id }, - relations: ["user"], + relations: ["user"] }); member.nick = nickname; @@ -222,10 +205,10 @@ export class Member extends BaseClassWithoutId { data: { guild_id, user: member.user, - nick: nickname, + nick: nickname }, - guild_id, - } as GuildMemberUpdateEvent), + guild_id + } as GuildMemberUpdateEvent) ]); } @@ -243,9 +226,9 @@ export class Member extends BaseClassWithoutId { const guild = await Guild.findOneOrFail({ where: { - id: guild_id, + id: guild_id }, - relations: PublicGuildRelations, + relations: PublicGuildRelations }); if (await Member.count({ where: { id: user.id, guild: { id: guild_id } } })) @@ -260,7 +243,7 @@ export class Member extends BaseClassWithoutId { premium_since: null, deaf: false, mute: false, - pending: false, + pending: false }; //TODO: check for bugs if (guild.member_count) guild.member_count++; @@ -276,8 +259,8 @@ export class Member extends BaseClassWithoutId { muted: false, suppress_everyone: false, suppress_roles: false, - version: 0, - }, + version: 0 + } // Member.save is needed because else the roles relations wouldn't be updated }).save(), //Guild.increment({ id: guild_id }, "member_count", 1), @@ -286,9 +269,9 @@ export class Member extends BaseClassWithoutId { data: { ...member, user, - guild_id, + guild_id }, - guild_id, + guild_id } as GuildMemberAddEvent), emitEvent({ event: "GUILD_CREATE", @@ -301,10 +284,10 @@ export class Member extends BaseClassWithoutId { joined_at: member.joined_at, presences: [], stage_instances: [], - threads: [], + threads: [] }, - user_id, - } as GuildCreateEvent), + user_id + } as GuildCreateEvent) ]); } } @@ -330,16 +313,7 @@ export interface MuteConfig { selected_time_window: number; } -export type PublicMemberKeys = - | "id" - | "guild_id" - | "nick" - | "roles" - | "joined_at" - | "pending" - | "deaf" - | "mute" - | "premium_since"; +export type PublicMemberKeys = "id" | "guild_id" | "nick" | "roles" | "joined_at" | "pending" | "deaf" | "mute" | "premium_since"; export const PublicMemberProjection: PublicMemberKeys[] = [ "id", @@ -350,7 +324,7 @@ export const PublicMemberProjection: PublicMemberKeys[] = [ "pending", "deaf", "mute", - "premium_since", + "premium_since" ]; // @ts-ignore diff --git a/src/util/entities/Message.ts b/src/util/entities/Message.ts index ba3d4f2d..8122b532 100644 --- a/src/util/entities/Message.ts +++ b/src/util/entities/Message.ts @@ -1,28 +1,15 @@ -import { User } from "./User"; -import { Member } from "./Member"; -import { Role } from "./Role"; -import { Channel } from "./Channel"; +import { Column, CreateDateColumn, Entity, Index, JoinColumn, JoinTable, ManyToMany, ManyToOne, OneToMany, RelationId } from "typeorm"; import { InteractionType } from "../interfaces/Interaction"; import { Application } from "./Application"; -import { - Column, - CreateDateColumn, - Entity, - Index, - JoinColumn, - JoinTable, - ManyToMany, - ManyToOne, - OneToMany, - RelationId, - RemoveOptions, - UpdateDateColumn, -} from "typeorm"; +import { Attachment } from "./Attachment"; import { BaseClass } from "./BaseClass"; +import { Channel } from "./Channel"; import { Guild } from "./Guild"; -import { Webhook } from "./Webhook"; +import { Member } from "./Member"; +import { Role } from "./Role"; import { Sticker } from "./Sticker"; -import { Attachment } from "./Attachment"; +import { User } from "./User"; +import { Webhook } from "./Webhook"; export enum MessageType { DEFAULT = 0, @@ -62,7 +49,7 @@ export class Message extends BaseClass { @JoinColumn({ name: "channel_id" }) @ManyToOne(() => Channel, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) channel: Channel; @@ -72,7 +59,7 @@ export class Message extends BaseClass { @JoinColumn({ name: "guild_id" }) @ManyToOne(() => Guild, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) guild?: Guild; @@ -83,7 +70,7 @@ export class Message extends BaseClass { @JoinColumn({ name: "author_id", referencedColumnName: "id" }) @ManyToOne(() => User, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) author?: User; @@ -93,7 +80,7 @@ export class Message extends BaseClass { @JoinColumn({ name: "member_id", referencedColumnName: "id" }) @ManyToOne(() => User, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) member?: Member; @@ -147,7 +134,7 @@ export class Message extends BaseClass { @OneToMany(() => Attachment, (attachment: Attachment) => attachment.message, { cascade: true, - orphanedRowAction: "delete", + orphanedRowAction: "delete" }) attachments?: Attachment[]; @@ -212,7 +199,7 @@ export interface MessageComponent { export enum MessageComponentType { Script = 0, // self command script ActionRow = 1, - Button = 2, + Button = 2 } export interface Embed { @@ -253,7 +240,7 @@ export enum EmbedType { video = "video", gifv = "gifv", article = "article", - link = "link", + link = "link" } export interface EmbedImage { diff --git a/src/util/entities/Migration.ts b/src/util/entities/Migration.ts index 3f39ae72..626ec429 100644 --- a/src/util/entities/Migration.ts +++ b/src/util/entities/Migration.ts @@ -1,9 +1,7 @@ import { Column, Entity, ObjectIdColumn, PrimaryGeneratedColumn } from "typeorm"; import { BaseClassWithoutId } from "."; -export const PrimaryIdAutoGenerated = process.env.DATABASE?.startsWith("mongodb") - ? ObjectIdColumn - : PrimaryGeneratedColumn; +export const PrimaryIdAutoGenerated = process.env.DATABASE?.startsWith("mongodb") ? ObjectIdColumn : PrimaryGeneratedColumn; @Entity("migrations") export class Migration extends BaseClassWithoutId { diff --git a/src/util/entities/Note.ts b/src/util/entities/Note.ts index 36017c5e..b3ac45ee 100644 --- a/src/util/entities/Note.ts +++ b/src/util/entities/Note.ts @@ -15,4 +15,4 @@ export class Note extends BaseClass { @Column() content: string; -} \ No newline at end of file +} diff --git a/src/util/entities/ReadState.ts b/src/util/entities/ReadState.ts index b915573b..77d2c08a 100644 --- a/src/util/entities/ReadState.ts +++ b/src/util/entities/ReadState.ts @@ -1,7 +1,6 @@ import { Column, Entity, Index, JoinColumn, ManyToOne, RelationId } from "typeorm"; import { BaseClass } from "./BaseClass"; import { Channel } from "./Channel"; -import { Message } from "./Message"; import { User } from "./User"; // for read receipts @@ -17,7 +16,7 @@ export class ReadState extends BaseClass { @JoinColumn({ name: "channel_id" }) @ManyToOne(() => Channel, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) channel: Channel; @@ -27,14 +26,14 @@ export class ReadState extends BaseClass { @JoinColumn({ name: "user_id" }) @ManyToOne(() => User, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) user: User; // fully read marker @Column({ nullable: true }) - last_message_id: string; - + last_message_id: string; + // public read receipt @Column({ nullable: true }) public_ack: string; diff --git a/src/util/entities/Recipient.ts b/src/util/entities/Recipient.ts index a945f938..fc9e629b 100644 --- a/src/util/entities/Recipient.ts +++ b/src/util/entities/Recipient.ts @@ -9,7 +9,7 @@ export class Recipient extends BaseClass { @JoinColumn({ name: "channel_id" }) @ManyToOne(() => require("./Channel").Channel, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) channel: import("./Channel").Channel; @@ -19,7 +19,7 @@ export class Recipient extends BaseClass { @JoinColumn({ name: "user_id" }) @ManyToOne(() => require("./User").User, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) user: import("./User").User; diff --git a/src/util/entities/Relationship.ts b/src/util/entities/Relationship.ts index c3592c76..b55d9e64 100644 --- a/src/util/entities/Relationship.ts +++ b/src/util/entities/Relationship.ts @@ -6,7 +6,7 @@ export enum RelationshipType { outgoing = 4, incoming = 3, blocked = 2, - friends = 1, + friends = 1 } @Entity("relationships") @@ -18,7 +18,7 @@ export class Relationship extends BaseClass { @JoinColumn({ name: "from_id" }) @ManyToOne(() => User, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) from: User; @@ -28,7 +28,7 @@ export class Relationship extends BaseClass { @JoinColumn({ name: "to_id" }) @ManyToOne(() => User, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) to: User; @@ -43,7 +43,7 @@ export class Relationship extends BaseClass { id: this.to?.id || this.to_id, type: this.type, nickname: this.nickname, - user: this.to?.toPublicUser(), + user: this.to?.toPublicUser() }; } } diff --git a/src/util/entities/Role.ts b/src/util/entities/Role.ts index 4b721b5b..b1fd9bb1 100644 --- a/src/util/entities/Role.ts +++ b/src/util/entities/Role.ts @@ -11,7 +11,7 @@ export class Role extends BaseClass { @JoinColumn({ name: "guild_id" }) @ManyToOne(() => Guild, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) guild: Guild; diff --git a/src/util/entities/Session.ts b/src/util/entities/Session.ts index 969efa89..0cb4c309 100644 --- a/src/util/entities/Session.ts +++ b/src/util/entities/Session.ts @@ -1,8 +1,8 @@ -import { User } from "./User"; -import { BaseClass } from "./BaseClass"; import { Column, Entity, JoinColumn, ManyToOne, RelationId } from "typeorm"; -import { Status } from "../interfaces/Status"; import { Activity } from "../interfaces/Activity"; +import { Status } from "../interfaces/Status"; +import { BaseClass } from "./BaseClass"; +import { User } from "./User"; //TODO we need to remove all sessions on server start because if the server crashes without closing websockets it won't delete them @@ -14,7 +14,7 @@ export class Session extends BaseClass { @JoinColumn({ name: "user_id" }) @ManyToOne(() => User, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) user: User; @@ -37,10 +37,4 @@ export class Session extends BaseClass { status: Status; //TODO enum } -export const PrivateSessionProjection: (keyof Session)[] = [ - "user_id", - "session_id", - "activities", - "client_info", - "status", -]; +export const PrivateSessionProjection: (keyof Session)[] = ["user_id", "session_id", "activities", "client_info", "status"]; diff --git a/src/util/entities/Sticker.ts b/src/util/entities/Sticker.ts index 37bc6fbe..69836e62 100644 --- a/src/util/entities/Sticker.ts +++ b/src/util/entities/Sticker.ts @@ -1,18 +1,18 @@ import { Column, Entity, JoinColumn, ManyToOne, RelationId } from "typeorm"; -import { User } from "./User"; import { BaseClass } from "./BaseClass"; import { Guild } from "./Guild"; +import { User } from "./User"; export enum StickerType { STANDARD = 1, - GUILD = 2, + GUILD = 2 } export enum StickerFormatType { GIF = 0, // gif is a custom format type and not in discord spec PNG = 1, APNG = 2, - LOTTIE = 3, + LOTTIE = 3 } @Entity("stickers") @@ -36,7 +36,7 @@ export class Sticker extends BaseClass { @JoinColumn({ name: "pack_id" }) @ManyToOne(() => require("./StickerPack").StickerPack, { onDelete: "CASCADE", - nullable: true, + nullable: true }) pack: import("./StickerPack").StickerPack; @@ -45,7 +45,7 @@ export class Sticker extends BaseClass { @JoinColumn({ name: "guild_id" }) @ManyToOne(() => Guild, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) guild?: Guild; @@ -54,7 +54,7 @@ export class Sticker extends BaseClass { @JoinColumn({ name: "user_id" }) @ManyToOne(() => User, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) user?: User; diff --git a/src/util/entities/StickerPack.ts b/src/util/entities/StickerPack.ts index ec8c69a2..4619af34 100644 --- a/src/util/entities/StickerPack.ts +++ b/src/util/entities/StickerPack.ts @@ -1,4 +1,4 @@ -import { Column, Entity, JoinColumn, ManyToOne, OneToMany, OneToOne, RelationId } from "typeorm"; +import { Column, Entity, JoinColumn, ManyToOne, OneToMany, RelationId } from "typeorm"; import { Sticker } from "."; import { BaseClass } from "./BaseClass"; @@ -15,7 +15,7 @@ export class StickerPack extends BaseClass { @OneToMany(() => Sticker, (sticker: Sticker) => sticker.pack, { cascade: true, - orphanedRowAction: "delete", + orphanedRowAction: "delete" }) stickers: Sticker[]; diff --git a/src/util/entities/Team.ts b/src/util/entities/Team.ts index 22140b7f..1d2d7002 100644 --- a/src/util/entities/Team.ts +++ b/src/util/entities/Team.ts @@ -1,4 +1,4 @@ -import { Column, Entity, JoinColumn, ManyToMany, ManyToOne, OneToMany, RelationId } from "typeorm"; +import { Column, Entity, JoinColumn, ManyToOne, OneToMany, RelationId } from "typeorm"; import { BaseClass } from "./BaseClass"; import { TeamMember } from "./TeamMember"; import { User } from "./User"; @@ -10,7 +10,7 @@ export class Team extends BaseClass { @JoinColumn({ name: "member_ids" }) @OneToMany(() => TeamMember, (member: TeamMember) => member.team, { - orphanedRowAction: "delete", + orphanedRowAction: "delete" }) members: TeamMember[]; diff --git a/src/util/entities/TeamMember.ts b/src/util/entities/TeamMember.ts index b726e1e8..d11ebf95 100644 --- a/src/util/entities/TeamMember.ts +++ b/src/util/entities/TeamMember.ts @@ -4,7 +4,7 @@ import { User } from "./User"; export enum TeamMemberState { INVITED = 1, - ACCEPTED = 2, + ACCEPTED = 2 } @Entity("team_members") @@ -21,7 +21,7 @@ export class TeamMember extends BaseClass { @JoinColumn({ name: "team_id" }) @ManyToOne(() => require("./Team").Team, (team: import("./Team").Team) => team.members, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) team: import("./Team").Team; @@ -31,7 +31,7 @@ export class TeamMember extends BaseClass { @JoinColumn({ name: "user_id" }) @ManyToOne(() => User, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) user: User; } diff --git a/src/util/entities/User.ts b/src/util/entities/User.ts index 5432f298..1237b676 100644 --- a/src/util/entities/User.ts +++ b/src/util/entities/User.ts @@ -1,11 +1,11 @@ import { Column, Entity, FindOneOptions, FindOptionsSelectByString, JoinColumn, OneToMany, OneToOne } from "typeorm"; +import { Member, Session, UserSettings } from "."; +import { Config, FieldErrors, Snowflake, trimSpecial } from ".."; +import { BitField } from "../util/BitField"; import { OrmUtils } from "../util/imports/OrmUtils"; import { BaseClass } from "./BaseClass"; -import { BitField } from "../util/BitField"; -import { Relationship } from "./Relationship"; import { ConnectedAccount } from "./ConnectedAccount"; -import { Config, FieldErrors, Snowflake, trimSpecial } from ".."; -import { Member, Session, UserSettings } from "."; +import { Relationship } from "./Relationship"; export enum PublicUserEnum { username, @@ -17,7 +17,7 @@ export enum PublicUserEnum { banner, bio, bot, - premium_since, + premium_since } export type PublicUserKeys = keyof typeof PublicUserEnum; @@ -31,17 +31,15 @@ export enum PrivateUserEnum { premium, premium_type, disabled, - settings, + settings // locale } export type PrivateUserKeys = keyof typeof PrivateUserEnum | PublicUserKeys; -export const PublicUserProjection = Object.values(PublicUserEnum).filter( - (x) => typeof x === "string" -) as PublicUserKeys[]; +export const PublicUserProjection = Object.values(PublicUserEnum).filter((x) => typeof x === "string") as PublicUserKeys[]; export const PrivateUserProjection = [ ...PublicUserProjection, - ...Object.values(PrivateUserEnum).filter((x) => typeof x === "string"), + ...Object.values(PrivateUserEnum).filter((x) => typeof x === "string") ] as PrivateUserKeys[]; // Private user data that should never get sent to the client @@ -148,14 +146,14 @@ export class User extends BaseClass { @JoinColumn({ name: "relationship_ids" }) @OneToMany(() => Relationship, (relationship: Relationship) => relationship.from, { cascade: true, - orphanedRowAction: "delete", + orphanedRowAction: "delete" }) relationships: Relationship[]; @JoinColumn({ name: "connected_account_ids" }) @OneToMany(() => ConnectedAccount, (account: ConnectedAccount) => account.user, { cascade: true, - orphanedRowAction: "delete", + orphanedRowAction: "delete" }) connected_accounts: ConnectedAccount[]; @@ -168,8 +166,7 @@ export class User extends BaseClass { @Column({ type: "simple-array", select: false }) fingerprints: string[] = []; // array of fingerprints -> used to prevent multiple accounts - - @OneToOne(()=> UserSettings, { + @OneToOne(() => UserSettings, { cascade: true, orphanedRowAction: "delete", eager: false @@ -185,7 +182,7 @@ export class User extends BaseClass { notes: { [key: string]: string } = {}; //key is ID of user async save(): Promise<any> { - if(!this.settings) this.settings = new UserSettings(); + if (!this.settings) this.settings = new UserSettings(); this.settings.id = this.id; //await this.settings.save(); return super.save(); @@ -203,7 +200,7 @@ export class User extends BaseClass { return await User.findOneOrFail({ where: { id: user_id }, select: [...PublicUserProjection, ...((opts?.select as FindOptionsSelectByString<User>) || [])], - ...opts, + ...opts }); } @@ -241,7 +238,7 @@ export class User extends BaseClass { username, password, date_of_birth, - req, + req }: { username: string; password?: string; @@ -258,8 +255,8 @@ export class User extends BaseClass { throw FieldErrors({ username: { code: "USERNAME_TOO_MANY_USERS", - message: req?.t("auth:register.USERNAME_TOO_MANY_USERS"), - }, + message: req?.t("auth:register.USERNAME_TOO_MANY_USERS") + } }); } @@ -276,7 +273,7 @@ export class User extends BaseClass { email: email, data: { hash: password, - valid_tokens_since: new Date(), + valid_tokens_since: new Date() }, settings: { ...new UserSettings(), locale: language } }); @@ -319,6 +316,6 @@ export class UserFlags extends BitField { VERIFIED_BOT: BigInt(1) << BigInt(16), EARLY_VERIFIED_BOT_DEVELOPER: BigInt(1) << BigInt(17), CERTIFIED_MODERATOR: BigInt(1) << BigInt(18), - BOT_HTTP_INTERACTIONS: BigInt(1) << BigInt(19), + BOT_HTTP_INTERACTIONS: BigInt(1) << BigInt(19) }; } diff --git a/src/util/entities/UserGroup.ts b/src/util/entities/UserGroup.ts index 709b9d0b..08d68a4e 100644 --- a/src/util/entities/UserGroup.ts +++ b/src/util/entities/UserGroup.ts @@ -1,7 +1,6 @@ -import { Column, Entity, JoinColumn, ManyToOne, RelationId } from "typeorm"; +import { Column, Entity, JoinColumn, ManyToOne } from "typeorm"; import { BaseClass } from "./BaseClass"; -import { Guild } from "./Guild"; import { User } from "./User"; @Entity("groups") @@ -11,11 +10,11 @@ export class UserGroup extends BaseClass { @Column() hoist: boolean; - + @JoinColumn({ name: "controller", referencedColumnName: "id" }) @ManyToOne(() => User) controller?: User; - + @Column() mentionable_by?: string; @@ -27,11 +26,10 @@ export class UserGroup extends BaseClass { @Column({ nullable: true }) icon: string; - + @Column({ nullable: true }) parent?: string; - - @Column({ type: "simple-array", nullable: true}) - associciations: string[]; + @Column({ type: "simple-array", nullable: true }) + associciations: string[]; } diff --git a/src/util/entities/UserSettings.ts b/src/util/entities/UserSettings.ts index ef6f95af..9fa18a4d 100644 --- a/src/util/entities/UserSettings.ts +++ b/src/util/entities/UserSettings.ts @@ -1,119 +1,119 @@ -import { Column, Entity, JoinColumn } from "typeorm"; +import { Column, Entity } from "typeorm"; import { BaseClassWithoutId, PrimaryIdColumn } from "."; @Entity("user_settings") export class UserSettings extends BaseClassWithoutId { - @PrimaryIdColumn() + @PrimaryIdColumn() id: string; @Column({ nullable: true }) - afk_timeout: number = 3600; - - @Column({ nullable: true }) - allow_accessibility_detection: boolean = true; - - @Column({ nullable: true }) - animate_emoji: boolean = true; - - @Column({ nullable: true }) - animate_stickers: number = 0; - - @Column({ nullable: true }) - contact_sync_enabled: boolean = false; - - @Column({ nullable: true }) - convert_emoticons: boolean = false; - - @Column({ nullable: true, type: "simple-json" }) - custom_status: CustomStatus | null = null; - - @Column({ nullable: true }) - default_guilds_restricted: boolean = false; - - @Column({ nullable: true }) - detect_platform_accounts: boolean = false; - - @Column({ nullable: true }) - developer_mode: boolean = true; - - @Column({ nullable: true }) - disable_games_tab: boolean = true; - - @Column({ nullable: true }) - enable_tts_command: boolean = false; - - @Column({ nullable: true }) - explicit_content_filter: number = 0; - - @Column({ nullable: true, type: "simple-json" }) - friend_source_flags: FriendSourceFlags = { all: true }; - - @Column({ nullable: true }) - gateway_connected: boolean = false; - - @Column({ nullable: true }) - gif_auto_play: boolean = false; - - @Column({ nullable: true, type: "simple-json" }) - guild_folders: GuildFolder[] = []; // every top guild is displayed as a "folder" - - @Column({ nullable: true, type: "simple-json" }) - guild_positions: string[] = []; // guild ids ordered by position - - @Column({ nullable: true }) - inline_attachment_media: boolean = true; - - @Column({ nullable: true }) - inline_embed_media: boolean = true; - - @Column({ nullable: true }) - locale: string = "en-US"; // en_US - - @Column({ nullable: true }) - message_display_compact: boolean = false; - - @Column({ nullable: true }) - native_phone_integration_enabled: boolean = true; - - @Column({ nullable: true }) - render_embeds: boolean = true; - - @Column({ nullable: true }) - render_reactions: boolean = true; - - @Column({ nullable: true, type: "simple-json" }) - restricted_guilds: string[] = []; - - @Column({ nullable: true }) - show_current_game: boolean = true; - - @Column({ nullable: true }) - status: "online" | "offline" | "dnd" | "idle" | "invisible" = "online"; - - @Column({ nullable: true }) - stream_notifications_enabled: boolean = false; - - @Column({ nullable: true }) - theme: "dark" | "white" = "dark"; // dark - - @Column({ nullable: true }) - timezone_offset: number = 0; // e.g -60 + afk_timeout: number = 3600; + + @Column({ nullable: true }) + allow_accessibility_detection: boolean = true; + + @Column({ nullable: true }) + animate_emoji: boolean = true; + + @Column({ nullable: true }) + animate_stickers: number = 0; + + @Column({ nullable: true }) + contact_sync_enabled: boolean = false; + + @Column({ nullable: true }) + convert_emoticons: boolean = false; + + @Column({ nullable: true, type: "simple-json" }) + custom_status: CustomStatus | null = null; + + @Column({ nullable: true }) + default_guilds_restricted: boolean = false; + + @Column({ nullable: true }) + detect_platform_accounts: boolean = false; + + @Column({ nullable: true }) + developer_mode: boolean = true; + + @Column({ nullable: true }) + disable_games_tab: boolean = true; + + @Column({ nullable: true }) + enable_tts_command: boolean = false; + + @Column({ nullable: true }) + explicit_content_filter: number = 0; + + @Column({ nullable: true, type: "simple-json" }) + friend_source_flags: FriendSourceFlags = { all: true }; + + @Column({ nullable: true }) + gateway_connected: boolean = false; + + @Column({ nullable: true }) + gif_auto_play: boolean = false; + + @Column({ nullable: true, type: "simple-json" }) + guild_folders: GuildFolder[] = []; // every top guild is displayed as a "folder" + + @Column({ nullable: true, type: "simple-json" }) + guild_positions: string[] = []; // guild ids ordered by position + + @Column({ nullable: true }) + inline_attachment_media: boolean = true; + + @Column({ nullable: true }) + inline_embed_media: boolean = true; + + @Column({ nullable: true }) + locale: string = "en-US"; // en_US + + @Column({ nullable: true }) + message_display_compact: boolean = false; + + @Column({ nullable: true }) + native_phone_integration_enabled: boolean = true; + + @Column({ nullable: true }) + render_embeds: boolean = true; + + @Column({ nullable: true }) + render_reactions: boolean = true; + + @Column({ nullable: true, type: "simple-json" }) + restricted_guilds: string[] = []; + + @Column({ nullable: true }) + show_current_game: boolean = true; + + @Column({ nullable: true }) + status: "online" | "offline" | "dnd" | "idle" | "invisible" = "online"; + + @Column({ nullable: true }) + stream_notifications_enabled: boolean = false; + + @Column({ nullable: true }) + theme: "dark" | "white" = "dark"; // dark + + @Column({ nullable: true }) + timezone_offset: number = 0; // e.g -60 } interface CustomStatus { - emoji_id?: string; - emoji_name?: string; - expires_at?: number; - text?: string; + emoji_id?: string; + emoji_name?: string; + expires_at?: number; + text?: string; } interface GuildFolder { - color: number; - guild_ids: string[]; - id: number; - name: string; + color: number; + guild_ids: string[]; + id: number; + name: string; } -interface FriendSourceFlags { - all: boolean -} \ No newline at end of file +interface FriendSourceFlags { + all: boolean; +} diff --git a/src/util/entities/VoiceState.ts b/src/util/entities/VoiceState.ts index 75748a01..baf2c687 100644 --- a/src/util/entities/VoiceState.ts +++ b/src/util/entities/VoiceState.ts @@ -2,8 +2,8 @@ import { Column, Entity, JoinColumn, ManyToOne, RelationId } from "typeorm"; import { BaseClass } from "./BaseClass"; import { Channel } from "./Channel"; import { Guild } from "./Guild"; -import { User } from "./User"; import { Member } from "./Member"; +import { User } from "./User"; //https://gist.github.com/vassjozsef/e482c65df6ee1facaace8b3c9ff66145#file-voice_state-ex @Entity("voice_states") @@ -14,7 +14,7 @@ export class VoiceState extends BaseClass { @JoinColumn({ name: "guild_id" }) @ManyToOne(() => Guild, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) guild?: Guild; @@ -24,7 +24,7 @@ export class VoiceState extends BaseClass { @JoinColumn({ name: "channel_id" }) @ManyToOne(() => Channel, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) channel: Channel; @@ -34,7 +34,7 @@ export class VoiceState extends BaseClass { @JoinColumn({ name: "user_id" }) @ManyToOne(() => User, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) user: User; diff --git a/src/util/entities/Webhook.ts b/src/util/entities/Webhook.ts index 89538417..3d94ddb6 100644 --- a/src/util/entities/Webhook.ts +++ b/src/util/entities/Webhook.ts @@ -7,7 +7,7 @@ import { User } from "./User"; export enum WebhookType { Incoming = 1, - ChannelFollower = 2, + ChannelFollower = 2 } @Entity("webhooks") @@ -30,7 +30,7 @@ export class Webhook extends BaseClass { @JoinColumn({ name: "guild_id" }) @ManyToOne(() => Guild, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) guild: Guild; @@ -40,7 +40,7 @@ export class Webhook extends BaseClass { @JoinColumn({ name: "channel_id" }) @ManyToOne(() => Channel, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) channel: Channel; @@ -50,7 +50,7 @@ export class Webhook extends BaseClass { @JoinColumn({ name: "application_id" }) @ManyToOne(() => Application, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) application: Application; @@ -60,7 +60,7 @@ export class Webhook extends BaseClass { @JoinColumn({ name: "user_id" }) @ManyToOne(() => User, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) user: User; @@ -70,7 +70,7 @@ export class Webhook extends BaseClass { @JoinColumn({ name: "source_guild_id" }) @ManyToOne(() => Guild, { - onDelete: "CASCADE", + onDelete: "CASCADE" }) source_guild: Guild; } diff --git a/src/util/entities/index.ts b/src/util/entities/index.ts index c6f12022..2b91c2ba 100644 --- a/src/util/entities/index.ts +++ b/src/util/entities/index.ts @@ -1,10 +1,12 @@ export * from "./Application"; export * from "./Attachment"; export * from "./AuditLog"; +export * from "./BackupCodes"; export * from "./Ban"; export * from "./BaseClass"; export * from "./Categories"; export * from "./Channel"; +export * from "./ClientRelease"; export * from "./Config"; export * from "./ConnectedAccount"; export * from "./Emoji"; @@ -13,6 +15,7 @@ export * from "./Invite"; export * from "./Member"; export * from "./Message"; export * from "./Migration"; +export * from "./Note"; export * from "./RateLimit"; export * from "./ReadState"; export * from "./Recipient"; @@ -25,9 +28,6 @@ export * from "./Team"; export * from "./TeamMember"; export * from "./Template"; export * from "./User"; +export * from "./UserSettings"; export * from "./VoiceState"; export * from "./Webhook"; -export * from "./ClientRelease"; -export * from "./BackupCodes"; -export * from "./Note"; -export * from "./UserSettings"; diff --git a/src/util/index.ts b/src/util/index.ts index d944dc49..b26ed278 100644 --- a/src/util/index.ts +++ b/src/util/index.ts @@ -1,9 +1,9 @@ import "reflect-metadata"; -export * from "./util/index"; export * from "./config/index"; -export * from "./interfaces/index"; -export * from "./entities/index"; export * from "./dtos/index"; +export * from "./entities/index"; +export * from "./interfaces/index"; +export * from "./schemas"; +export * from "./util/index"; export * from "./util/MFA"; -export * from "./schemas"; \ No newline at end of file diff --git a/src/util/interfaces/Activity.ts b/src/util/interfaces/Activity.ts index 43984afd..3b36b4a6 100644 --- a/src/util/interfaces/Activity.ts +++ b/src/util/interfaces/Activity.ts @@ -40,5 +40,5 @@ export enum ActivityType { STREAMING = 1, LISTENING = 2, CUSTOM = 4, - COMPETING = 5, + COMPETING = 5 } diff --git a/src/util/interfaces/Event.ts b/src/util/interfaces/Event.ts index be66c62f..f97f4615 100644 --- a/src/util/interfaces/Event.ts +++ b/src/util/interfaces/Event.ts @@ -1,19 +1,19 @@ -import { PublicUser, User } from "../entities/User"; +import { Activity, Status } from "."; +import { Sticker, UserSettings } from ".."; +import { ApplicationCommand } from "../entities/Application"; import { Channel } from "../entities/Channel"; -import { Guild } from "../entities/Guild"; -import { Member, PublicMember, UserGuildSettings } from "../entities/Member"; +import { ConnectedAccount } from "../entities/ConnectedAccount"; import { Emoji } from "../entities/Emoji"; -import { Role } from "../entities/Role"; +import { Guild } from "../entities/Guild"; import { Invite } from "../entities/Invite"; +import { PublicMember, UserGuildSettings } from "../entities/Member"; import { Message, PartialEmoji } from "../entities/Message"; +import { RelationshipType } from "../entities/Relationship"; +import { Role } from "../entities/Role"; +import { PublicUser, User } from "../entities/User"; import { VoiceState } from "../entities/VoiceState"; -import { ApplicationCommand } from "../entities/Application"; import { Interaction } from "./Interaction"; -import { ConnectedAccount } from "../entities/ConnectedAccount"; -import { Relationship, RelationshipType } from "../entities/Relationship"; import { Presence } from "./Presence"; -import { Sticker, UserSettings } from ".."; -import { Activity, Status } from "."; export interface Event { guild_id?: string; @@ -580,7 +580,7 @@ export enum EVENTEnum { ApplicationCommandCreate = "APPLICATION_COMMAND_CREATE", ApplicationCommandUpdate = "APPLICATION_COMMAND_UPDATE", ApplicationCommandDelete = "APPLICATION_COMMAND_DELETE", - SessionsReplace = "SESSIONS_REPLACE", + SessionsReplace = "SESSIONS_REPLACE" } export type EVENT = diff --git a/src/util/interfaces/Interaction.ts b/src/util/interfaces/Interaction.ts index 5d3aae24..c53a1ed4 100644 --- a/src/util/interfaces/Interaction.ts +++ b/src/util/interfaces/Interaction.ts @@ -14,7 +14,7 @@ export interface Interaction { export enum InteractionType { SelfCommand = 0, Ping = 1, - ApplicationCommand = 2, + ApplicationCommand = 2 } export enum InteractionResponseType { @@ -23,7 +23,7 @@ export enum InteractionResponseType { Acknowledge = 2, ChannelMessage = 3, ChannelMessageWithSource = 4, - AcknowledgeWithSource = 5, + AcknowledgeWithSource = 5 } export interface InteractionApplicationCommandCallbackData { diff --git a/src/util/interfaces/Presence.ts b/src/util/interfaces/Presence.ts index 7663891a..5b66139e 100644 --- a/src/util/interfaces/Presence.ts +++ b/src/util/interfaces/Presence.ts @@ -1,6 +1,6 @@ -import { ClientStatus, Status } from "./Status"; -import { Activity } from "./Activity"; import { PublicUser } from "../entities/User"; +import { Activity } from "./Activity"; +import { ClientStatus, Status } from "./Status"; export interface Presence { user: PublicUser; diff --git a/src/util/interfaces/index.ts b/src/util/interfaces/index.ts index ab7fa429..a074030e 100644 --- a/src/util/interfaces/index.ts +++ b/src/util/interfaces/index.ts @@ -1,5 +1,5 @@ export * from "./Activity"; -export * from "./Presence"; -export * from "./Interaction"; export * from "./Event"; +export * from "./Interaction"; +export * from "./Presence"; export * from "./Status"; diff --git a/src/util/migrations/mariadb/1659901151025-initial.ts b/src/util/migrations/mariadb/1659901151025-initial.ts index d15e0add..1e1f64db 100644 --- a/src/util/migrations/mariadb/1659901151025-initial.ts +++ b/src/util/migrations/mariadb/1659901151025-initial.ts @@ -1,17 +1,17 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class initial1659901151025 implements MigrationInterface { - name = 'initial1659901151025' + name = "initial1659901151025"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` CREATE TABLE \`config\` ( \`key\` varchar(255) NOT NULL, \`value\` text NULL, PRIMARY KEY (\`key\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`relationships\` ( \`id\` varchar(255) NOT NULL, \`from_id\` varchar(255) NOT NULL, @@ -22,7 +22,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`connected_accounts\` ( \`id\` varchar(255) NOT NULL, \`user_id\` varchar(255) NULL, @@ -37,7 +37,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`users\` ( \`id\` varchar(255) NOT NULL, \`username\` varchar(255) NOT NULL, @@ -74,7 +74,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`backup_codes\` ( \`id\` varchar(255) NOT NULL, \`code\` varchar(255) NOT NULL, @@ -84,7 +84,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`bans\` ( \`id\` varchar(255) NOT NULL, \`user_id\` varchar(255) NULL, @@ -95,7 +95,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`recipients\` ( \`id\` varchar(255) NOT NULL, \`channel_id\` varchar(255) NOT NULL, @@ -104,7 +104,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`roles\` ( \`id\` varchar(255) NOT NULL, \`guild_id\` varchar(255) NULL, @@ -121,7 +121,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`members\` ( \`index\` int NOT NULL AUTO_INCREMENT, \`id\` varchar(255) NOT NULL, @@ -139,7 +139,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`index\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`webhooks\` ( \`id\` varchar(255) NOT NULL, \`type\` int NOT NULL, @@ -154,7 +154,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`stickers\` ( \`id\` varchar(255) NOT NULL, \`name\` varchar(255) NOT NULL, @@ -169,7 +169,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`attachments\` ( \`id\` varchar(255) NOT NULL, \`filename\` varchar(255) NOT NULL, @@ -183,7 +183,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`messages\` ( \`id\` varchar(255) NOT NULL, \`channel_id\` varchar(255) NULL, @@ -214,7 +214,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`read_states\` ( \`id\` varchar(255) NOT NULL, \`channel_id\` varchar(255) NOT NULL, @@ -228,7 +228,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`invites\` ( \`code\` varchar(255) NOT NULL, \`temporary\` tinyint NOT NULL, @@ -246,7 +246,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`code\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`voice_states\` ( \`id\` varchar(255) NOT NULL, \`guild_id\` varchar(255) NULL, @@ -265,7 +265,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`channels\` ( \`id\` varchar(255) NOT NULL, \`created_at\` datetime NOT NULL, @@ -290,7 +290,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`emojis\` ( \`id\` varchar(255) NOT NULL, \`animated\` tinyint NOT NULL, @@ -305,7 +305,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`templates\` ( \`id\` varchar(255) NOT NULL, \`code\` varchar(255) NOT NULL, @@ -321,7 +321,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`guilds\` ( \`id\` varchar(255) NOT NULL, \`afk_channel_id\` varchar(255) NULL, @@ -364,7 +364,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`team_members\` ( \`id\` varchar(255) NOT NULL, \`membership_state\` int NOT NULL, @@ -374,7 +374,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`teams\` ( \`id\` varchar(255) NOT NULL, \`icon\` varchar(255) NULL, @@ -383,7 +383,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`applications\` ( \`id\` varchar(255) NOT NULL, \`name\` varchar(255) NOT NULL, @@ -406,7 +406,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`audit_logs\` ( \`id\` varchar(255) NOT NULL, \`user_id\` varchar(255) NULL, @@ -418,7 +418,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`categories\` ( \`id\` int NOT NULL, \`name\` varchar(255) NULL, @@ -427,7 +427,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`rate_limits\` ( \`id\` varchar(255) NOT NULL, \`executor_id\` varchar(255) NOT NULL, @@ -437,7 +437,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`sessions\` ( \`id\` varchar(255) NOT NULL, \`user_id\` varchar(255) NULL, @@ -448,7 +448,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`sticker_packs\` ( \`id\` varchar(255) NOT NULL, \`name\` varchar(255) NOT NULL, @@ -459,7 +459,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`client_release\` ( \`id\` varchar(255) NOT NULL, \`name\` varchar(255) NOT NULL, @@ -472,7 +472,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`notes\` ( \`id\` varchar(255) NOT NULL, \`content\` varchar(255) NOT NULL, @@ -482,7 +482,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`member_roles\` ( \`index\` int NOT NULL, \`role_id\` varchar(255) NOT NULL, @@ -491,7 +491,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`index\`, \`role_id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`message_user_mentions\` ( \`messagesId\` varchar(255) NOT NULL, \`usersId\` varchar(255) NOT NULL, @@ -500,7 +500,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`messagesId\`, \`usersId\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`message_role_mentions\` ( \`messagesId\` varchar(255) NOT NULL, \`rolesId\` varchar(255) NOT NULL, @@ -509,7 +509,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`messagesId\`, \`rolesId\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`message_channel_mentions\` ( \`messagesId\` varchar(255) NOT NULL, \`channelsId\` varchar(255) NOT NULL, @@ -518,7 +518,7 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`messagesId\`, \`channelsId\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`message_stickers\` ( \`messagesId\` varchar(255) NOT NULL, \`stickersId\` varchar(255) NOT NULL, @@ -527,299 +527,299 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`messagesId\`, \`stickersId\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`relationships\` ADD CONSTRAINT \`FK_9af4194bab1250b1c584ae4f1d7\` FOREIGN KEY (\`from_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`relationships\` ADD CONSTRAINT \`FK_9c7f6b98a9843b76dce1b0c878b\` FOREIGN KEY (\`to_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`connected_accounts\` ADD CONSTRAINT \`FK_f47244225a6a1eac04a3463dd90\` FOREIGN KEY (\`user_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`backup_codes\` ADD CONSTRAINT \`FK_70066ea80d2f4b871beda32633b\` FOREIGN KEY (\`user_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`bans\` ADD CONSTRAINT \`FK_5999e8e449f80a236ff72023559\` FOREIGN KEY (\`user_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`bans\` ADD CONSTRAINT \`FK_9d3ab7dd180ebdd245cdb66ecad\` FOREIGN KEY (\`guild_id\`) REFERENCES \`guilds\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`bans\` ADD CONSTRAINT \`FK_07ad88c86d1f290d46748410d58\` FOREIGN KEY (\`executor_id\`) REFERENCES \`users\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`recipients\` ADD CONSTRAINT \`FK_2f18ee1ba667f233ae86c0ea60e\` FOREIGN KEY (\`channel_id\`) REFERENCES \`channels\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`recipients\` ADD CONSTRAINT \`FK_6157e8b6ba4e6e3089616481fe2\` FOREIGN KEY (\`user_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`roles\` ADD CONSTRAINT \`FK_c32c1ab1c4dc7dcb0278c4b1b8b\` FOREIGN KEY (\`guild_id\`) REFERENCES \`guilds\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`members\` ADD CONSTRAINT \`FK_28b53062261b996d9c99fa12404\` FOREIGN KEY (\`id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`members\` ADD CONSTRAINT \`FK_16aceddd5b89825b8ed6029ad1c\` FOREIGN KEY (\`guild_id\`) REFERENCES \`guilds\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`webhooks\` ADD CONSTRAINT \`FK_487a7af59d189f744fe394368fc\` FOREIGN KEY (\`guild_id\`) REFERENCES \`guilds\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`webhooks\` ADD CONSTRAINT \`FK_df528cf77e82f8032230e7e37d8\` FOREIGN KEY (\`channel_id\`) REFERENCES \`channels\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`webhooks\` ADD CONSTRAINT \`FK_c3e5305461931763b56aa905f1c\` FOREIGN KEY (\`application_id\`) REFERENCES \`applications\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`webhooks\` ADD CONSTRAINT \`FK_0d523f6f997c86e052c49b1455f\` FOREIGN KEY (\`user_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`webhooks\` ADD CONSTRAINT \`FK_3a285f4f49c40e0706d3018bc9f\` FOREIGN KEY (\`source_guild_id\`) REFERENCES \`guilds\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`stickers\` ADD CONSTRAINT \`FK_e7cfa5cefa6661b3fb8fda8ce69\` FOREIGN KEY (\`pack_id\`) REFERENCES \`sticker_packs\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`stickers\` ADD CONSTRAINT \`FK_193d551d852aca5347ef5c9f205\` FOREIGN KEY (\`guild_id\`) REFERENCES \`guilds\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`stickers\` ADD CONSTRAINT \`FK_8f4ee73f2bb2325ff980502e158\` FOREIGN KEY (\`user_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`attachments\` ADD CONSTRAINT \`FK_623e10eec51ada466c5038979e3\` FOREIGN KEY (\`message_id\`) REFERENCES \`messages\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`messages\` ADD CONSTRAINT \`FK_86b9109b155eb70c0a2ca3b4b6d\` FOREIGN KEY (\`channel_id\`) REFERENCES \`channels\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`messages\` ADD CONSTRAINT \`FK_b193588441b085352a4c0109423\` FOREIGN KEY (\`guild_id\`) REFERENCES \`guilds\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`messages\` ADD CONSTRAINT \`FK_05535bc695e9f7ee104616459d3\` FOREIGN KEY (\`author_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`messages\` ADD CONSTRAINT \`FK_b0525304f2262b7014245351c76\` FOREIGN KEY (\`member_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`messages\` ADD CONSTRAINT \`FK_f83c04bcf1df4e5c0e7a52ed348\` FOREIGN KEY (\`webhook_id\`) REFERENCES \`webhooks\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`messages\` ADD CONSTRAINT \`FK_5d3ec1cb962de6488637fd779d6\` FOREIGN KEY (\`application_id\`) REFERENCES \`applications\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`messages\` ADD CONSTRAINT \`FK_61a92bb65b302a76d9c1fcd3174\` FOREIGN KEY (\`message_reference_id\`) REFERENCES \`messages\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`read_states\` ADD CONSTRAINT \`FK_40da2fca4e0eaf7a23b5bfc5d34\` FOREIGN KEY (\`channel_id\`) REFERENCES \`channels\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`read_states\` ADD CONSTRAINT \`FK_195f92e4dd1254a4e348c043763\` FOREIGN KEY (\`user_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`invites\` ADD CONSTRAINT \`FK_3f4939aa1461e8af57fea3fb05d\` FOREIGN KEY (\`guild_id\`) REFERENCES \`guilds\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`invites\` ADD CONSTRAINT \`FK_6a15b051fe5050aa00a4b9ff0f6\` FOREIGN KEY (\`channel_id\`) REFERENCES \`channels\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`invites\` ADD CONSTRAINT \`FK_15c35422032e0b22b4ada95f48f\` FOREIGN KEY (\`inviter_id\`) REFERENCES \`users\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`invites\` ADD CONSTRAINT \`FK_11a0d394f8fc649c19ce5f16b59\` FOREIGN KEY (\`target_user_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`voice_states\` ADD CONSTRAINT \`FK_03779ef216d4b0358470d9cb748\` FOREIGN KEY (\`guild_id\`) REFERENCES \`guilds\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`voice_states\` ADD CONSTRAINT \`FK_9f8d389866b40b6657edd026dd4\` FOREIGN KEY (\`channel_id\`) REFERENCES \`channels\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`voice_states\` ADD CONSTRAINT \`FK_5fe1d5f931a67e85039c640001b\` FOREIGN KEY (\`user_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`channels\` ADD CONSTRAINT \`FK_c253dafe5f3a03ec00cd8fb4581\` FOREIGN KEY (\`guild_id\`) REFERENCES \`guilds\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`channels\` ADD CONSTRAINT \`FK_3274522d14af40540b1a883fc80\` FOREIGN KEY (\`parent_id\`) REFERENCES \`channels\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`channels\` ADD CONSTRAINT \`FK_3873ed438575cce703ecff4fc7b\` FOREIGN KEY (\`owner_id\`) REFERENCES \`users\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`emojis\` ADD CONSTRAINT \`FK_4b988e0db89d94cebcf07f598cc\` FOREIGN KEY (\`guild_id\`) REFERENCES \`guilds\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`emojis\` ADD CONSTRAINT \`FK_fa7ddd5f9a214e28ce596548421\` FOREIGN KEY (\`user_id\`) REFERENCES \`users\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`templates\` ADD CONSTRAINT \`FK_d7374b7f8f5fbfdececa4fb62e1\` FOREIGN KEY (\`creator_id\`) REFERENCES \`users\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`templates\` ADD CONSTRAINT \`FK_445d00eaaea0e60a017a5ed0c11\` FOREIGN KEY (\`source_guild_id\`) REFERENCES \`guilds\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`guilds\` ADD CONSTRAINT \`FK_f591a66b8019d87b0fe6c12dad6\` FOREIGN KEY (\`afk_channel_id\`) REFERENCES \`channels\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`guilds\` ADD CONSTRAINT \`FK_e2a2f873a64a5cf62526de42325\` FOREIGN KEY (\`template_id\`) REFERENCES \`templates\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`guilds\` ADD CONSTRAINT \`FK_fc1a451727e3643ca572a3bb394\` FOREIGN KEY (\`owner_id\`) REFERENCES \`users\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`guilds\` ADD CONSTRAINT \`FK_8d450b016dc8bec35f36729e4b0\` FOREIGN KEY (\`public_updates_channel_id\`) REFERENCES \`channels\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`guilds\` ADD CONSTRAINT \`FK_95828668aa333460582e0ca6396\` FOREIGN KEY (\`rules_channel_id\`) REFERENCES \`channels\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`guilds\` ADD CONSTRAINT \`FK_cfc3d3ad260f8121c95b31a1fce\` FOREIGN KEY (\`system_channel_id\`) REFERENCES \`channels\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`guilds\` ADD CONSTRAINT \`FK_9d1d665379eefde7876a17afa99\` FOREIGN KEY (\`widget_channel_id\`) REFERENCES \`channels\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`team_members\` ADD CONSTRAINT \`FK_fdad7d5768277e60c40e01cdcea\` FOREIGN KEY (\`team_id\`) REFERENCES \`teams\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`team_members\` ADD CONSTRAINT \`FK_c2bf4967c8c2a6b845dadfbf3d4\` FOREIGN KEY (\`user_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`teams\` ADD CONSTRAINT \`FK_13f00abf7cb6096c43ecaf8c108\` FOREIGN KEY (\`owner_user_id\`) REFERENCES \`users\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD CONSTRAINT \`FK_e57508958bf92b9d9d25231b5e8\` FOREIGN KEY (\`owner_id\`) REFERENCES \`users\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD CONSTRAINT \`FK_a36ed02953077f408d0f3ebc424\` FOREIGN KEY (\`team_id\`) REFERENCES \`teams\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD CONSTRAINT \`FK_e5bf78cdbbe9ba91062d74c5aba\` FOREIGN KEY (\`guild_id\`) REFERENCES \`guilds\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`audit_logs\` ADD CONSTRAINT \`FK_3cd01cd3ae7aab010310d96ac8e\` FOREIGN KEY (\`target_id\`) REFERENCES \`users\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`audit_logs\` ADD CONSTRAINT \`FK_bd2726fd31b35443f2245b93ba0\` FOREIGN KEY (\`user_id\`) REFERENCES \`users\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`sessions\` ADD CONSTRAINT \`FK_085d540d9f418cfbdc7bd55bb19\` FOREIGN KEY (\`user_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`sticker_packs\` ADD CONSTRAINT \`FK_448fafba4355ee1c837bbc865f1\` FOREIGN KEY (\`coverStickerId\`) REFERENCES \`stickers\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`notes\` ADD CONSTRAINT \`FK_f9e103f8ae67cb1787063597925\` FOREIGN KEY (\`owner_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`notes\` ADD CONSTRAINT \`FK_23e08e5b4481711d573e1abecdc\` FOREIGN KEY (\`target_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`member_roles\` ADD CONSTRAINT \`FK_5d7ddc8a5f9c167f548625e772e\` FOREIGN KEY (\`index\`) REFERENCES \`members\`(\`index\`) ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`member_roles\` ADD CONSTRAINT \`FK_e9080e7a7997a0170026d5139c1\` FOREIGN KEY (\`role_id\`) REFERENCES \`roles\`(\`id\`) ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`message_user_mentions\` ADD CONSTRAINT \`FK_a343387fc560ef378760681c236\` FOREIGN KEY (\`messagesId\`) REFERENCES \`messages\`(\`id\`) ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`message_user_mentions\` ADD CONSTRAINT \`FK_b831eb18ceebd28976239b1e2f8\` FOREIGN KEY (\`usersId\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`message_role_mentions\` ADD CONSTRAINT \`FK_a8242cf535337a490b0feaea0b4\` FOREIGN KEY (\`messagesId\`) REFERENCES \`messages\`(\`id\`) ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`message_role_mentions\` ADD CONSTRAINT \`FK_29d63eb1a458200851bc37d074b\` FOREIGN KEY (\`rolesId\`) REFERENCES \`roles\`(\`id\`) ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`message_channel_mentions\` ADD CONSTRAINT \`FK_2a27102ecd1d81b4582a4360921\` FOREIGN KEY (\`messagesId\`) REFERENCES \`messages\`(\`id\`) ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`message_channel_mentions\` ADD CONSTRAINT \`FK_bdb8c09e1464cabf62105bf4b9d\` FOREIGN KEY (\`channelsId\`) REFERENCES \`channels\`(\`id\`) ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`message_stickers\` ADD CONSTRAINT \`FK_40bb6f23e7cc133292e92829d28\` FOREIGN KEY (\`messagesId\`) REFERENCES \`messages\`(\`id\`) ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`message_stickers\` ADD CONSTRAINT \`FK_e22a70819d07659c7a71c112a1f\` FOREIGN KEY (\`stickersId\`) REFERENCES \`stickers\`(\`id\`) ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`query-result-cache\` ( \`id\` int NOT NULL AUTO_INCREMENT, \`identifier\` varchar(255) NULL, @@ -830,390 +830,389 @@ export class initial1659901151025 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` DROP TABLE \`query-result-cache\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`message_stickers\` DROP FOREIGN KEY \`FK_e22a70819d07659c7a71c112a1f\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`message_stickers\` DROP FOREIGN KEY \`FK_40bb6f23e7cc133292e92829d28\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`message_channel_mentions\` DROP FOREIGN KEY \`FK_bdb8c09e1464cabf62105bf4b9d\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`message_channel_mentions\` DROP FOREIGN KEY \`FK_2a27102ecd1d81b4582a4360921\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`message_role_mentions\` DROP FOREIGN KEY \`FK_29d63eb1a458200851bc37d074b\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`message_role_mentions\` DROP FOREIGN KEY \`FK_a8242cf535337a490b0feaea0b4\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`message_user_mentions\` DROP FOREIGN KEY \`FK_b831eb18ceebd28976239b1e2f8\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`message_user_mentions\` DROP FOREIGN KEY \`FK_a343387fc560ef378760681c236\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`member_roles\` DROP FOREIGN KEY \`FK_e9080e7a7997a0170026d5139c1\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`member_roles\` DROP FOREIGN KEY \`FK_5d7ddc8a5f9c167f548625e772e\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`notes\` DROP FOREIGN KEY \`FK_23e08e5b4481711d573e1abecdc\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`notes\` DROP FOREIGN KEY \`FK_f9e103f8ae67cb1787063597925\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`sticker_packs\` DROP FOREIGN KEY \`FK_448fafba4355ee1c837bbc865f1\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`sessions\` DROP FOREIGN KEY \`FK_085d540d9f418cfbdc7bd55bb19\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`audit_logs\` DROP FOREIGN KEY \`FK_bd2726fd31b35443f2245b93ba0\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`audit_logs\` DROP FOREIGN KEY \`FK_3cd01cd3ae7aab010310d96ac8e\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP FOREIGN KEY \`FK_e5bf78cdbbe9ba91062d74c5aba\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP FOREIGN KEY \`FK_a36ed02953077f408d0f3ebc424\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP FOREIGN KEY \`FK_e57508958bf92b9d9d25231b5e8\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`teams\` DROP FOREIGN KEY \`FK_13f00abf7cb6096c43ecaf8c108\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`team_members\` DROP FOREIGN KEY \`FK_c2bf4967c8c2a6b845dadfbf3d4\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`team_members\` DROP FOREIGN KEY \`FK_fdad7d5768277e60c40e01cdcea\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`guilds\` DROP FOREIGN KEY \`FK_9d1d665379eefde7876a17afa99\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`guilds\` DROP FOREIGN KEY \`FK_cfc3d3ad260f8121c95b31a1fce\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`guilds\` DROP FOREIGN KEY \`FK_95828668aa333460582e0ca6396\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`guilds\` DROP FOREIGN KEY \`FK_8d450b016dc8bec35f36729e4b0\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`guilds\` DROP FOREIGN KEY \`FK_fc1a451727e3643ca572a3bb394\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`guilds\` DROP FOREIGN KEY \`FK_e2a2f873a64a5cf62526de42325\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`guilds\` DROP FOREIGN KEY \`FK_f591a66b8019d87b0fe6c12dad6\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`templates\` DROP FOREIGN KEY \`FK_445d00eaaea0e60a017a5ed0c11\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`templates\` DROP FOREIGN KEY \`FK_d7374b7f8f5fbfdececa4fb62e1\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`emojis\` DROP FOREIGN KEY \`FK_fa7ddd5f9a214e28ce596548421\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`emojis\` DROP FOREIGN KEY \`FK_4b988e0db89d94cebcf07f598cc\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`channels\` DROP FOREIGN KEY \`FK_3873ed438575cce703ecff4fc7b\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`channels\` DROP FOREIGN KEY \`FK_3274522d14af40540b1a883fc80\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`channels\` DROP FOREIGN KEY \`FK_c253dafe5f3a03ec00cd8fb4581\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`voice_states\` DROP FOREIGN KEY \`FK_5fe1d5f931a67e85039c640001b\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`voice_states\` DROP FOREIGN KEY \`FK_9f8d389866b40b6657edd026dd4\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`voice_states\` DROP FOREIGN KEY \`FK_03779ef216d4b0358470d9cb748\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`invites\` DROP FOREIGN KEY \`FK_11a0d394f8fc649c19ce5f16b59\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`invites\` DROP FOREIGN KEY \`FK_15c35422032e0b22b4ada95f48f\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`invites\` DROP FOREIGN KEY \`FK_6a15b051fe5050aa00a4b9ff0f6\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`invites\` DROP FOREIGN KEY \`FK_3f4939aa1461e8af57fea3fb05d\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`read_states\` DROP FOREIGN KEY \`FK_195f92e4dd1254a4e348c043763\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`read_states\` DROP FOREIGN KEY \`FK_40da2fca4e0eaf7a23b5bfc5d34\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`messages\` DROP FOREIGN KEY \`FK_61a92bb65b302a76d9c1fcd3174\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`messages\` DROP FOREIGN KEY \`FK_5d3ec1cb962de6488637fd779d6\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`messages\` DROP FOREIGN KEY \`FK_f83c04bcf1df4e5c0e7a52ed348\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`messages\` DROP FOREIGN KEY \`FK_b0525304f2262b7014245351c76\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`messages\` DROP FOREIGN KEY \`FK_05535bc695e9f7ee104616459d3\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`messages\` DROP FOREIGN KEY \`FK_b193588441b085352a4c0109423\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`messages\` DROP FOREIGN KEY \`FK_86b9109b155eb70c0a2ca3b4b6d\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`attachments\` DROP FOREIGN KEY \`FK_623e10eec51ada466c5038979e3\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`stickers\` DROP FOREIGN KEY \`FK_8f4ee73f2bb2325ff980502e158\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`stickers\` DROP FOREIGN KEY \`FK_193d551d852aca5347ef5c9f205\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`stickers\` DROP FOREIGN KEY \`FK_e7cfa5cefa6661b3fb8fda8ce69\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`webhooks\` DROP FOREIGN KEY \`FK_3a285f4f49c40e0706d3018bc9f\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`webhooks\` DROP FOREIGN KEY \`FK_0d523f6f997c86e052c49b1455f\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`webhooks\` DROP FOREIGN KEY \`FK_c3e5305461931763b56aa905f1c\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`webhooks\` DROP FOREIGN KEY \`FK_df528cf77e82f8032230e7e37d8\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`webhooks\` DROP FOREIGN KEY \`FK_487a7af59d189f744fe394368fc\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`members\` DROP FOREIGN KEY \`FK_16aceddd5b89825b8ed6029ad1c\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`members\` DROP FOREIGN KEY \`FK_28b53062261b996d9c99fa12404\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`roles\` DROP FOREIGN KEY \`FK_c32c1ab1c4dc7dcb0278c4b1b8b\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`recipients\` DROP FOREIGN KEY \`FK_6157e8b6ba4e6e3089616481fe2\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`recipients\` DROP FOREIGN KEY \`FK_2f18ee1ba667f233ae86c0ea60e\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`bans\` DROP FOREIGN KEY \`FK_07ad88c86d1f290d46748410d58\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`bans\` DROP FOREIGN KEY \`FK_9d3ab7dd180ebdd245cdb66ecad\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`bans\` DROP FOREIGN KEY \`FK_5999e8e449f80a236ff72023559\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`backup_codes\` DROP FOREIGN KEY \`FK_70066ea80d2f4b871beda32633b\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`connected_accounts\` DROP FOREIGN KEY \`FK_f47244225a6a1eac04a3463dd90\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`relationships\` DROP FOREIGN KEY \`FK_9c7f6b98a9843b76dce1b0c878b\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`relationships\` DROP FOREIGN KEY \`FK_9af4194bab1250b1c584ae4f1d7\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`IDX_e22a70819d07659c7a71c112a1\` ON \`message_stickers\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`IDX_40bb6f23e7cc133292e92829d2\` ON \`message_stickers\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`message_stickers\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`IDX_bdb8c09e1464cabf62105bf4b9\` ON \`message_channel_mentions\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`IDX_2a27102ecd1d81b4582a436092\` ON \`message_channel_mentions\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`message_channel_mentions\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`IDX_29d63eb1a458200851bc37d074\` ON \`message_role_mentions\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`IDX_a8242cf535337a490b0feaea0b\` ON \`message_role_mentions\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`message_role_mentions\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`IDX_b831eb18ceebd28976239b1e2f\` ON \`message_user_mentions\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`IDX_a343387fc560ef378760681c23\` ON \`message_user_mentions\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`message_user_mentions\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`IDX_e9080e7a7997a0170026d5139c\` ON \`member_roles\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`IDX_5d7ddc8a5f9c167f548625e772\` ON \`member_roles\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`member_roles\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`IDX_74e6689b9568cc965b8bfc9150\` ON \`notes\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`notes\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`client_release\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`sticker_packs\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`sessions\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`rate_limits\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`categories\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`audit_logs\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`applications\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`teams\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`team_members\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`guilds\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`IDX_be38737bf339baf63b1daeffb5\` ON \`templates\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`templates\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`emojis\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`channels\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`voice_states\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`invites\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`IDX_0abf8b443321bd3cf7f81ee17a\` ON \`read_states\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`read_states\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`IDX_3ed7a60fb7dbe04e1ba9332a8b\` ON \`messages\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`IDX_05535bc695e9f7ee104616459d\` ON \`messages\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`IDX_86b9109b155eb70c0a2ca3b4b6\` ON \`messages\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`messages\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`attachments\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`stickers\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`webhooks\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`IDX_bb2bf9386ac443afbbbf9f12d3\` ON \`members\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`members\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`roles\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`recipients\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`bans\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`backup_codes\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`users\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`connected_accounts\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`IDX_a0b2ff0a598df0b0d055934a17\` ON \`relationships\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`relationships\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`config\` `); - } - + } } diff --git a/src/util/migrations/mariadb/1659921859145-premium_since_as_date.ts b/src/util/migrations/mariadb/1659921859145-premium_since_as_date.ts index de173cfe..549d6b9f 100644 --- a/src/util/migrations/mariadb/1659921859145-premium_since_as_date.ts +++ b/src/util/migrations/mariadb/1659921859145-premium_since_as_date.ts @@ -1,26 +1,25 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class premiumSinceAsDate1659921859145 implements MigrationInterface { - name = 'premiumSinceAsDate1659921859145' + name = "premiumSinceAsDate1659921859145"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE \`members\` DROP COLUMN \`premium_since\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`members\` ADD \`premium_since\` datetime NULL `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE \`members\` DROP COLUMN \`premium_since\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`members\` ADD \`premium_since\` bigint NULL `); - } - + } } diff --git a/src/util/migrations/mariadb/1660130586602-updated-applications.ts b/src/util/migrations/mariadb/1660130586602-updated-applications.ts index ec574416..fea076db 100644 --- a/src/util/migrations/mariadb/1660130586602-updated-applications.ts +++ b/src/util/migrations/mariadb/1660130586602-updated-applications.ts @@ -1,185 +1,184 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class updatedApplications1660130586602 implements MigrationInterface { - name = 'updatedApplications1660130586602' + name = "updatedApplications1660130586602"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE \`applications\` DROP FOREIGN KEY \`FK_e5bf78cdbbe9ba91062d74c5aba\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`rpc_origins\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`primary_sku_id\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`slug\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`guild_id\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`type\` text NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`hook\` tinyint NOT NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`redirect_uris\` text NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`rpc_application_state\` int NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`store_application_state\` int NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`verification_state\` int NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`interactions_endpoint_url\` varchar(255) NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`integration_public\` tinyint NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`integration_require_code_grant\` tinyint NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`discoverability_state\` int NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`discovery_eligibility_flags\` int NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`tags\` text NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`install_params\` text NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`bot_user_id\` varchar(255) NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD UNIQUE INDEX \`IDX_2ce5a55796fe4c2f77ece57a64\` (\`bot_user_id\`) `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` CHANGE \`description\` \`description\` varchar(255) NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`flags\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`flags\` int NOT NULL `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX \`REL_2ce5a55796fe4c2f77ece57a64\` ON \`applications\` (\`bot_user_id\`) `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD CONSTRAINT \`FK_2ce5a55796fe4c2f77ece57a647\` FOREIGN KEY (\`bot_user_id\`) REFERENCES \`users\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE \`applications\` DROP FOREIGN KEY \`FK_2ce5a55796fe4c2f77ece57a647\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`REL_2ce5a55796fe4c2f77ece57a64\` ON \`applications\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`flags\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`flags\` varchar(255) NOT NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` CHANGE \`description\` \`description\` varchar(255) NOT NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP INDEX \`IDX_2ce5a55796fe4c2f77ece57a64\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`bot_user_id\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`install_params\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`tags\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`discovery_eligibility_flags\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`discoverability_state\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`integration_require_code_grant\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`integration_public\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`interactions_endpoint_url\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`verification_state\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`store_application_state\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`rpc_application_state\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`redirect_uris\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`hook\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` DROP COLUMN \`type\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`guild_id\` varchar(255) NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`slug\` varchar(255) NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`primary_sku_id\` varchar(255) NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD \`rpc_origins\` text NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`applications\` ADD CONSTRAINT \`FK_e5bf78cdbbe9ba91062d74c5aba\` FOREIGN KEY (\`guild_id\`) REFERENCES \`guilds\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - } - + } } diff --git a/src/util/migrations/mariadb/1660131942703-apps_nullable_team.ts b/src/util/migrations/mariadb/1660131942703-apps_nullable_team.ts index ac445772..c76d9af4 100644 --- a/src/util/migrations/mariadb/1660131942703-apps_nullable_team.ts +++ b/src/util/migrations/mariadb/1660131942703-apps_nullable_team.ts @@ -1,18 +1,17 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class appsNullableTeam1660131942703 implements MigrationInterface { - name = 'appsNullableTeam1660131942703' + name = "appsNullableTeam1660131942703"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` DROP INDEX \`IDX_2ce5a55796fe4c2f77ece57a64\` ON \`applications\` `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` CREATE UNIQUE INDEX \`IDX_2ce5a55796fe4c2f77ece57a64\` ON \`applications\` (\`bot_user_id\`) `); - } - + } } diff --git a/src/util/migrations/mariadb/1660540527213-sync_migrations.ts b/src/util/migrations/mariadb/1660540527213-sync_migrations.ts index 8cc1d2f1..594e4472 100644 --- a/src/util/migrations/mariadb/1660540527213-sync_migrations.ts +++ b/src/util/migrations/mariadb/1660540527213-sync_migrations.ts @@ -1,16 +1,16 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class syncMigrations1660540527213 implements MigrationInterface { - name = 'syncMigrations1660540527213' + name = "syncMigrations1660540527213"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE \`invites\` DROP FOREIGN KEY \`FK_15c35422032e0b22b4ada95f48f\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`users\` CHANGE \`settings\` \`settingsId\` text NOT NULL `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE \`user_settings\` ( \`id\` varchar(255) NOT NULL, \`afk_timeout\` int NULL, @@ -47,81 +47,80 @@ export class syncMigrations1660540527213 implements MigrationInterface { PRIMARY KEY (\`id\`) ) ENGINE = InnoDB `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`channels\` ADD \`flags\` int NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`channels\` ADD \`default_thread_rate_limit_per_user\` int NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`guilds\` ADD \`premium_progress_bar_enabled\` tinyint NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`users\` DROP COLUMN \`settingsId\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`users\` ADD \`settingsId\` varchar(255) NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`users\` ADD UNIQUE INDEX \`IDX_76ba283779c8441fd5ff819c8c\` (\`settingsId\`) `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX \`REL_76ba283779c8441fd5ff819c8c\` ON \`users\` (\`settingsId\`) `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`users\` ADD CONSTRAINT \`FK_76ba283779c8441fd5ff819c8cf\` FOREIGN KEY (\`settingsId\`) REFERENCES \`user_settings\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`invites\` ADD CONSTRAINT \`FK_15c35422032e0b22b4ada95f48f\` FOREIGN KEY (\`inviter_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE \`invites\` DROP FOREIGN KEY \`FK_15c35422032e0b22b4ada95f48f\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`users\` DROP FOREIGN KEY \`FK_76ba283779c8441fd5ff819c8cf\` `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX \`REL_76ba283779c8441fd5ff819c8c\` ON \`users\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`users\` DROP INDEX \`IDX_76ba283779c8441fd5ff819c8c\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`users\` DROP COLUMN \`settingsId\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`users\` ADD \`settingsId\` text NOT NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`guilds\` DROP COLUMN \`premium_progress_bar_enabled\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`channels\` DROP COLUMN \`default_thread_rate_limit_per_user\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`channels\` DROP COLUMN \`flags\` `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE \`user_settings\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`users\` CHANGE \`settingsId\` \`settings\` text NOT NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`invites\` ADD CONSTRAINT \`FK_15c35422032e0b22b4ada95f48f\` FOREIGN KEY (\`inviter_id\`) REFERENCES \`users\`(\`id\`) ON DELETE NO ACTION ON UPDATE NO ACTION `); - } - + } } diff --git a/src/util/migrations/mariadb/1660549252130-fix_nullables.ts b/src/util/migrations/mariadb/1660549252130-fix_nullables.ts index c9456b54..d9ea2e77 100644 --- a/src/util/migrations/mariadb/1660549252130-fix_nullables.ts +++ b/src/util/migrations/mariadb/1660549252130-fix_nullables.ts @@ -1,30 +1,29 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class fixNullables1660549252130 implements MigrationInterface { - name = 'fixNullables1660549252130' + name = "fixNullables1660549252130"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` DROP INDEX \`IDX_76ba283779c8441fd5ff819c8c\` ON \`users\` `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`users\` CHANGE \`bio\` \`bio\` varchar(255) NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`users\` CHANGE \`mfa_enabled\` \`mfa_enabled\` tinyint NULL `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE \`users\` CHANGE \`mfa_enabled\` \`mfa_enabled\` tinyint NOT NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE \`users\` CHANGE \`bio\` \`bio\` varchar(255) NOT NULL `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX \`IDX_76ba283779c8441fd5ff819c8c\` ON \`users\` (\`settingsId\`) `); - } - + } } diff --git a/src/util/migrations/postgres/1659899687168-initial.ts b/src/util/migrations/postgres/1659899687168-initial.ts index 4ffb897d..dc89a572 100644 --- a/src/util/migrations/postgres/1659899687168-initial.ts +++ b/src/util/migrations/postgres/1659899687168-initial.ts @@ -1,17 +1,17 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class initial1659899687168 implements MigrationInterface { - name = 'initial1659899687168' + name = "initial1659899687168"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` CREATE TABLE "config" ( "key" character varying NOT NULL, "value" text, CONSTRAINT "PK_26489c99ddbb4c91631ef5cc791" PRIMARY KEY ("key") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "relationships" ( "id" character varying NOT NULL, "from_id" character varying NOT NULL, @@ -21,10 +21,10 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_ba20e2f5cf487408e08e4dcecaf" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_a0b2ff0a598df0b0d055934a17" ON "relationships" ("from_id", "to_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "connected_accounts" ( "id" character varying NOT NULL, "user_id" character varying, @@ -39,7 +39,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_70416f1da0be645bb31da01c774" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "users" ( "id" character varying NOT NULL, "username" character varying NOT NULL, @@ -76,7 +76,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_a3ffb1c0c8416b9fc6f907b7433" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "backup_codes" ( "id" character varying NOT NULL, "code" character varying NOT NULL, @@ -86,7 +86,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_34ab957382dbc57e8fb53f1638f" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "bans" ( "id" character varying NOT NULL, "user_id" character varying, @@ -97,7 +97,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_a4d6f261bffa4615c62d756566a" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "recipients" ( "id" character varying NOT NULL, "channel_id" character varying NOT NULL, @@ -106,7 +106,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_de8fc5a9c364568f294798fe1e9" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "roles" ( "id" character varying NOT NULL, "guild_id" character varying, @@ -123,7 +123,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_c1433d71a4838793a49dcad46ab" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "members" ( "index" SERIAL NOT NULL, "id" character varying NOT NULL, @@ -140,10 +140,10 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_b4a6b8c2478e5df990909c6cf6a" PRIMARY KEY ("index") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_bb2bf9386ac443afbbbf9f12d3" ON "members" ("id", "guild_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "webhooks" ( "id" character varying NOT NULL, "type" integer NOT NULL, @@ -158,7 +158,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_9e8795cfc899ab7bdaa831e8527" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "stickers" ( "id" character varying NOT NULL, "name" character varying NOT NULL, @@ -173,7 +173,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_e1dafa4063a5532645cc2810374" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "attachments" ( "id" character varying NOT NULL, "filename" character varying NOT NULL, @@ -187,7 +187,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_5e1f050bcff31e3084a1d662412" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "messages" ( "id" character varying NOT NULL, "channel_id" character varying, @@ -215,16 +215,16 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_18325f38ae6de43878487eff986" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_86b9109b155eb70c0a2ca3b4b6" ON "messages" ("channel_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_05535bc695e9f7ee104616459d" ON "messages" ("author_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_3ed7a60fb7dbe04e1ba9332a8b" ON "messages" ("channel_id", "id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "read_states" ( "id" character varying NOT NULL, "channel_id" character varying NOT NULL, @@ -237,10 +237,10 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_e6956a804978f01b713b1ed58e2" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_0abf8b443321bd3cf7f81ee17a" ON "read_states" ("channel_id", "user_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "invites" ( "code" character varying NOT NULL, "temporary" boolean NOT NULL, @@ -258,7 +258,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_33fd8a248db1cd832baa8aa25bf" PRIMARY KEY ("code") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "voice_states" ( "id" character varying NOT NULL, "guild_id" character varying, @@ -277,7 +277,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_ada09a50c134fad1369b510e3ce" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "channels" ( "id" character varying NOT NULL, "created_at" TIMESTAMP NOT NULL, @@ -302,7 +302,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_bc603823f3f741359c2339389f9" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "emojis" ( "id" character varying NOT NULL, "animated" boolean NOT NULL, @@ -317,7 +317,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_9adb96a675f555c6169bad7ba62" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "templates" ( "id" character varying NOT NULL, "code" character varying NOT NULL, @@ -333,7 +333,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_515948649ce0bbbe391de702ae5" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "guilds" ( "id" character varying NOT NULL, "afk_channel_id" character varying, @@ -376,7 +376,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_e7e7f2a51bd6d96a9ac2aa560f9" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "team_members" ( "id" character varying NOT NULL, "membership_state" integer NOT NULL, @@ -386,7 +386,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_ca3eae89dcf20c9fd95bf7460aa" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "teams" ( "id" character varying NOT NULL, "icon" character varying, @@ -395,7 +395,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_7e5523774a38b08a6236d322403" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "applications" ( "id" character varying NOT NULL, "name" character varying NOT NULL, @@ -418,7 +418,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_938c0a27255637bde919591888f" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "audit_logs" ( "id" character varying NOT NULL, "user_id" character varying, @@ -430,7 +430,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_1bb179d048bbc581caa3b013439" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "categories" ( "id" integer NOT NULL, "name" character varying, @@ -439,7 +439,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_24dbc6126a28ff948da33e97d3b" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "rate_limits" ( "id" character varying NOT NULL, "executor_id" character varying NOT NULL, @@ -449,7 +449,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_3b4449f1f5fc167d921ee619f65" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "sessions" ( "id" character varying NOT NULL, "user_id" character varying, @@ -460,7 +460,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_3238ef96f18b355b671619111bc" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "sticker_packs" ( "id" character varying NOT NULL, "name" character varying NOT NULL, @@ -471,7 +471,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_a27381efea0f876f5d3233af655" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "client_release" ( "id" character varying NOT NULL, "name" character varying NOT NULL, @@ -484,7 +484,7 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_4c4ea258342d2d6ba1be0a71a43" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "notes" ( "id" character varying NOT NULL, "content" character varying NOT NULL, @@ -494,364 +494,364 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_af6206538ea96c4e77e9f400c3d" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "member_roles" ( "index" integer NOT NULL, "role_id" character varying NOT NULL, CONSTRAINT "PK_951c1d72a0fd1da8760b4a1fd66" PRIMARY KEY ("index", "role_id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_5d7ddc8a5f9c167f548625e772" ON "member_roles" ("index") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_e9080e7a7997a0170026d5139c" ON "member_roles" ("role_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "message_user_mentions" ( "messagesId" character varying NOT NULL, "usersId" character varying NOT NULL, CONSTRAINT "PK_9b9b6e245ad47a48dbd7605d4fb" PRIMARY KEY ("messagesId", "usersId") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_a343387fc560ef378760681c23" ON "message_user_mentions" ("messagesId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_b831eb18ceebd28976239b1e2f" ON "message_user_mentions" ("usersId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "message_role_mentions" ( "messagesId" character varying NOT NULL, "rolesId" character varying NOT NULL, CONSTRAINT "PK_74dba92cc300452a6e14b83ed44" PRIMARY KEY ("messagesId", "rolesId") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_a8242cf535337a490b0feaea0b" ON "message_role_mentions" ("messagesId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_29d63eb1a458200851bc37d074" ON "message_role_mentions" ("rolesId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "message_channel_mentions" ( "messagesId" character varying NOT NULL, "channelsId" character varying NOT NULL, CONSTRAINT "PK_85cb45351497cd9d06a79ced65e" PRIMARY KEY ("messagesId", "channelsId") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_2a27102ecd1d81b4582a436092" ON "message_channel_mentions" ("messagesId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_bdb8c09e1464cabf62105bf4b9" ON "message_channel_mentions" ("channelsId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "message_stickers" ( "messagesId" character varying NOT NULL, "stickersId" character varying NOT NULL, CONSTRAINT "PK_ed820c4093d0b8cd1d2bcf66087" PRIMARY KEY ("messagesId", "stickersId") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_40bb6f23e7cc133292e92829d2" ON "message_stickers" ("messagesId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_e22a70819d07659c7a71c112a1" ON "message_stickers" ("stickersId") `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "relationships" ADD CONSTRAINT "FK_9af4194bab1250b1c584ae4f1d7" FOREIGN KEY ("from_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "relationships" ADD CONSTRAINT "FK_9c7f6b98a9843b76dce1b0c878b" FOREIGN KEY ("to_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "connected_accounts" ADD CONSTRAINT "FK_f47244225a6a1eac04a3463dd90" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "backup_codes" ADD CONSTRAINT "FK_70066ea80d2f4b871beda32633b" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "bans" ADD CONSTRAINT "FK_5999e8e449f80a236ff72023559" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "bans" ADD CONSTRAINT "FK_9d3ab7dd180ebdd245cdb66ecad" FOREIGN KEY ("guild_id") REFERENCES "guilds"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "bans" ADD CONSTRAINT "FK_07ad88c86d1f290d46748410d58" FOREIGN KEY ("executor_id") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "recipients" ADD CONSTRAINT "FK_2f18ee1ba667f233ae86c0ea60e" FOREIGN KEY ("channel_id") REFERENCES "channels"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "recipients" ADD CONSTRAINT "FK_6157e8b6ba4e6e3089616481fe2" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "roles" ADD CONSTRAINT "FK_c32c1ab1c4dc7dcb0278c4b1b8b" FOREIGN KEY ("guild_id") REFERENCES "guilds"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "members" ADD CONSTRAINT "FK_28b53062261b996d9c99fa12404" FOREIGN KEY ("id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "members" ADD CONSTRAINT "FK_16aceddd5b89825b8ed6029ad1c" FOREIGN KEY ("guild_id") REFERENCES "guilds"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "webhooks" ADD CONSTRAINT "FK_487a7af59d189f744fe394368fc" FOREIGN KEY ("guild_id") REFERENCES "guilds"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "webhooks" ADD CONSTRAINT "FK_df528cf77e82f8032230e7e37d8" FOREIGN KEY ("channel_id") REFERENCES "channels"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "webhooks" ADD CONSTRAINT "FK_c3e5305461931763b56aa905f1c" FOREIGN KEY ("application_id") REFERENCES "applications"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "webhooks" ADD CONSTRAINT "FK_0d523f6f997c86e052c49b1455f" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "webhooks" ADD CONSTRAINT "FK_3a285f4f49c40e0706d3018bc9f" FOREIGN KEY ("source_guild_id") REFERENCES "guilds"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "stickers" ADD CONSTRAINT "FK_e7cfa5cefa6661b3fb8fda8ce69" FOREIGN KEY ("pack_id") REFERENCES "sticker_packs"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "stickers" ADD CONSTRAINT "FK_193d551d852aca5347ef5c9f205" FOREIGN KEY ("guild_id") REFERENCES "guilds"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "stickers" ADD CONSTRAINT "FK_8f4ee73f2bb2325ff980502e158" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "attachments" ADD CONSTRAINT "FK_623e10eec51ada466c5038979e3" FOREIGN KEY ("message_id") REFERENCES "messages"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "messages" ADD CONSTRAINT "FK_86b9109b155eb70c0a2ca3b4b6d" FOREIGN KEY ("channel_id") REFERENCES "channels"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "messages" ADD CONSTRAINT "FK_b193588441b085352a4c0109423" FOREIGN KEY ("guild_id") REFERENCES "guilds"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "messages" ADD CONSTRAINT "FK_05535bc695e9f7ee104616459d3" FOREIGN KEY ("author_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "messages" ADD CONSTRAINT "FK_b0525304f2262b7014245351c76" FOREIGN KEY ("member_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "messages" ADD CONSTRAINT "FK_f83c04bcf1df4e5c0e7a52ed348" FOREIGN KEY ("webhook_id") REFERENCES "webhooks"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "messages" ADD CONSTRAINT "FK_5d3ec1cb962de6488637fd779d6" FOREIGN KEY ("application_id") REFERENCES "applications"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "messages" ADD CONSTRAINT "FK_61a92bb65b302a76d9c1fcd3174" FOREIGN KEY ("message_reference_id") REFERENCES "messages"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "read_states" ADD CONSTRAINT "FK_40da2fca4e0eaf7a23b5bfc5d34" FOREIGN KEY ("channel_id") REFERENCES "channels"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "read_states" ADD CONSTRAINT "FK_195f92e4dd1254a4e348c043763" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "invites" ADD CONSTRAINT "FK_3f4939aa1461e8af57fea3fb05d" FOREIGN KEY ("guild_id") REFERENCES "guilds"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "invites" ADD CONSTRAINT "FK_6a15b051fe5050aa00a4b9ff0f6" FOREIGN KEY ("channel_id") REFERENCES "channels"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "invites" ADD CONSTRAINT "FK_15c35422032e0b22b4ada95f48f" FOREIGN KEY ("inviter_id") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "invites" ADD CONSTRAINT "FK_11a0d394f8fc649c19ce5f16b59" FOREIGN KEY ("target_user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "voice_states" ADD CONSTRAINT "FK_03779ef216d4b0358470d9cb748" FOREIGN KEY ("guild_id") REFERENCES "guilds"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "voice_states" ADD CONSTRAINT "FK_9f8d389866b40b6657edd026dd4" FOREIGN KEY ("channel_id") REFERENCES "channels"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "voice_states" ADD CONSTRAINT "FK_5fe1d5f931a67e85039c640001b" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "channels" ADD CONSTRAINT "FK_c253dafe5f3a03ec00cd8fb4581" FOREIGN KEY ("guild_id") REFERENCES "guilds"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "channels" ADD CONSTRAINT "FK_3274522d14af40540b1a883fc80" FOREIGN KEY ("parent_id") REFERENCES "channels"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "channels" ADD CONSTRAINT "FK_3873ed438575cce703ecff4fc7b" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "emojis" ADD CONSTRAINT "FK_4b988e0db89d94cebcf07f598cc" FOREIGN KEY ("guild_id") REFERENCES "guilds"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "emojis" ADD CONSTRAINT "FK_fa7ddd5f9a214e28ce596548421" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "templates" ADD CONSTRAINT "FK_d7374b7f8f5fbfdececa4fb62e1" FOREIGN KEY ("creator_id") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "templates" ADD CONSTRAINT "FK_445d00eaaea0e60a017a5ed0c11" FOREIGN KEY ("source_guild_id") REFERENCES "guilds"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "guilds" ADD CONSTRAINT "FK_f591a66b8019d87b0fe6c12dad6" FOREIGN KEY ("afk_channel_id") REFERENCES "channels"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "guilds" ADD CONSTRAINT "FK_e2a2f873a64a5cf62526de42325" FOREIGN KEY ("template_id") REFERENCES "templates"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "guilds" ADD CONSTRAINT "FK_fc1a451727e3643ca572a3bb394" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "guilds" ADD CONSTRAINT "FK_8d450b016dc8bec35f36729e4b0" FOREIGN KEY ("public_updates_channel_id") REFERENCES "channels"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "guilds" ADD CONSTRAINT "FK_95828668aa333460582e0ca6396" FOREIGN KEY ("rules_channel_id") REFERENCES "channels"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "guilds" ADD CONSTRAINT "FK_cfc3d3ad260f8121c95b31a1fce" FOREIGN KEY ("system_channel_id") REFERENCES "channels"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "guilds" ADD CONSTRAINT "FK_9d1d665379eefde7876a17afa99" FOREIGN KEY ("widget_channel_id") REFERENCES "channels"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "team_members" ADD CONSTRAINT "FK_fdad7d5768277e60c40e01cdcea" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "team_members" ADD CONSTRAINT "FK_c2bf4967c8c2a6b845dadfbf3d4" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "teams" ADD CONSTRAINT "FK_13f00abf7cb6096c43ecaf8c108" FOREIGN KEY ("owner_user_id") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD CONSTRAINT "FK_e57508958bf92b9d9d25231b5e8" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD CONSTRAINT "FK_a36ed02953077f408d0f3ebc424" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD CONSTRAINT "FK_e5bf78cdbbe9ba91062d74c5aba" FOREIGN KEY ("guild_id") REFERENCES "guilds"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "audit_logs" ADD CONSTRAINT "FK_3cd01cd3ae7aab010310d96ac8e" FOREIGN KEY ("target_id") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "audit_logs" ADD CONSTRAINT "FK_bd2726fd31b35443f2245b93ba0" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "sessions" ADD CONSTRAINT "FK_085d540d9f418cfbdc7bd55bb19" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "sticker_packs" ADD CONSTRAINT "FK_448fafba4355ee1c837bbc865f1" FOREIGN KEY ("coverStickerId") REFERENCES "stickers"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "notes" ADD CONSTRAINT "FK_f9e103f8ae67cb1787063597925" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "notes" ADD CONSTRAINT "FK_23e08e5b4481711d573e1abecdc" FOREIGN KEY ("target_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "member_roles" ADD CONSTRAINT "FK_5d7ddc8a5f9c167f548625e772e" FOREIGN KEY ("index") REFERENCES "members"("index") ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "member_roles" ADD CONSTRAINT "FK_e9080e7a7997a0170026d5139c1" FOREIGN KEY ("role_id") REFERENCES "roles"("id") ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_user_mentions" ADD CONSTRAINT "FK_a343387fc560ef378760681c236" FOREIGN KEY ("messagesId") REFERENCES "messages"("id") ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_user_mentions" ADD CONSTRAINT "FK_b831eb18ceebd28976239b1e2f8" FOREIGN KEY ("usersId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_role_mentions" ADD CONSTRAINT "FK_a8242cf535337a490b0feaea0b4" FOREIGN KEY ("messagesId") REFERENCES "messages"("id") ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_role_mentions" ADD CONSTRAINT "FK_29d63eb1a458200851bc37d074b" FOREIGN KEY ("rolesId") REFERENCES "roles"("id") ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_channel_mentions" ADD CONSTRAINT "FK_2a27102ecd1d81b4582a4360921" FOREIGN KEY ("messagesId") REFERENCES "messages"("id") ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_channel_mentions" ADD CONSTRAINT "FK_bdb8c09e1464cabf62105bf4b9d" FOREIGN KEY ("channelsId") REFERENCES "channels"("id") ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_stickers" ADD CONSTRAINT "FK_40bb6f23e7cc133292e92829d28" FOREIGN KEY ("messagesId") REFERENCES "messages"("id") ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_stickers" ADD CONSTRAINT "FK_e22a70819d07659c7a71c112a1f" FOREIGN KEY ("stickersId") REFERENCES "stickers"("id") ON DELETE CASCADE ON UPDATE CASCADE `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "query-result-cache" ( "id" SERIAL NOT NULL, "identifier" character varying, @@ -862,384 +862,383 @@ export class initial1659899687168 implements MigrationInterface { CONSTRAINT "PK_6a98f758d8bfd010e7e10ffd3d3" PRIMARY KEY ("id") ) `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` DROP TABLE "query-result-cache" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_stickers" DROP CONSTRAINT "FK_e22a70819d07659c7a71c112a1f" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_stickers" DROP CONSTRAINT "FK_40bb6f23e7cc133292e92829d28" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_channel_mentions" DROP CONSTRAINT "FK_bdb8c09e1464cabf62105bf4b9d" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_channel_mentions" DROP CONSTRAINT "FK_2a27102ecd1d81b4582a4360921" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_role_mentions" DROP CONSTRAINT "FK_29d63eb1a458200851bc37d074b" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_role_mentions" DROP CONSTRAINT "FK_a8242cf535337a490b0feaea0b4" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_user_mentions" DROP CONSTRAINT "FK_b831eb18ceebd28976239b1e2f8" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_user_mentions" DROP CONSTRAINT "FK_a343387fc560ef378760681c236" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "member_roles" DROP CONSTRAINT "FK_e9080e7a7997a0170026d5139c1" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "member_roles" DROP CONSTRAINT "FK_5d7ddc8a5f9c167f548625e772e" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "notes" DROP CONSTRAINT "FK_23e08e5b4481711d573e1abecdc" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "notes" DROP CONSTRAINT "FK_f9e103f8ae67cb1787063597925" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "sticker_packs" DROP CONSTRAINT "FK_448fafba4355ee1c837bbc865f1" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "sessions" DROP CONSTRAINT "FK_085d540d9f418cfbdc7bd55bb19" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "audit_logs" DROP CONSTRAINT "FK_bd2726fd31b35443f2245b93ba0" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "audit_logs" DROP CONSTRAINT "FK_3cd01cd3ae7aab010310d96ac8e" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP CONSTRAINT "FK_e5bf78cdbbe9ba91062d74c5aba" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP CONSTRAINT "FK_a36ed02953077f408d0f3ebc424" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP CONSTRAINT "FK_e57508958bf92b9d9d25231b5e8" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "teams" DROP CONSTRAINT "FK_13f00abf7cb6096c43ecaf8c108" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "team_members" DROP CONSTRAINT "FK_c2bf4967c8c2a6b845dadfbf3d4" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "team_members" DROP CONSTRAINT "FK_fdad7d5768277e60c40e01cdcea" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "guilds" DROP CONSTRAINT "FK_9d1d665379eefde7876a17afa99" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "guilds" DROP CONSTRAINT "FK_cfc3d3ad260f8121c95b31a1fce" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "guilds" DROP CONSTRAINT "FK_95828668aa333460582e0ca6396" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "guilds" DROP CONSTRAINT "FK_8d450b016dc8bec35f36729e4b0" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "guilds" DROP CONSTRAINT "FK_fc1a451727e3643ca572a3bb394" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "guilds" DROP CONSTRAINT "FK_e2a2f873a64a5cf62526de42325" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "guilds" DROP CONSTRAINT "FK_f591a66b8019d87b0fe6c12dad6" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "templates" DROP CONSTRAINT "FK_445d00eaaea0e60a017a5ed0c11" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "templates" DROP CONSTRAINT "FK_d7374b7f8f5fbfdececa4fb62e1" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "emojis" DROP CONSTRAINT "FK_fa7ddd5f9a214e28ce596548421" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "emojis" DROP CONSTRAINT "FK_4b988e0db89d94cebcf07f598cc" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "channels" DROP CONSTRAINT "FK_3873ed438575cce703ecff4fc7b" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "channels" DROP CONSTRAINT "FK_3274522d14af40540b1a883fc80" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "channels" DROP CONSTRAINT "FK_c253dafe5f3a03ec00cd8fb4581" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "voice_states" DROP CONSTRAINT "FK_5fe1d5f931a67e85039c640001b" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "voice_states" DROP CONSTRAINT "FK_9f8d389866b40b6657edd026dd4" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "voice_states" DROP CONSTRAINT "FK_03779ef216d4b0358470d9cb748" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "invites" DROP CONSTRAINT "FK_11a0d394f8fc649c19ce5f16b59" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "invites" DROP CONSTRAINT "FK_15c35422032e0b22b4ada95f48f" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "invites" DROP CONSTRAINT "FK_6a15b051fe5050aa00a4b9ff0f6" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "invites" DROP CONSTRAINT "FK_3f4939aa1461e8af57fea3fb05d" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "read_states" DROP CONSTRAINT "FK_195f92e4dd1254a4e348c043763" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "read_states" DROP CONSTRAINT "FK_40da2fca4e0eaf7a23b5bfc5d34" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "messages" DROP CONSTRAINT "FK_61a92bb65b302a76d9c1fcd3174" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "messages" DROP CONSTRAINT "FK_5d3ec1cb962de6488637fd779d6" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "messages" DROP CONSTRAINT "FK_f83c04bcf1df4e5c0e7a52ed348" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "messages" DROP CONSTRAINT "FK_b0525304f2262b7014245351c76" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "messages" DROP CONSTRAINT "FK_05535bc695e9f7ee104616459d3" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "messages" DROP CONSTRAINT "FK_b193588441b085352a4c0109423" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "messages" DROP CONSTRAINT "FK_86b9109b155eb70c0a2ca3b4b6d" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "attachments" DROP CONSTRAINT "FK_623e10eec51ada466c5038979e3" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "stickers" DROP CONSTRAINT "FK_8f4ee73f2bb2325ff980502e158" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "stickers" DROP CONSTRAINT "FK_193d551d852aca5347ef5c9f205" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "stickers" DROP CONSTRAINT "FK_e7cfa5cefa6661b3fb8fda8ce69" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "webhooks" DROP CONSTRAINT "FK_3a285f4f49c40e0706d3018bc9f" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "webhooks" DROP CONSTRAINT "FK_0d523f6f997c86e052c49b1455f" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "webhooks" DROP CONSTRAINT "FK_c3e5305461931763b56aa905f1c" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "webhooks" DROP CONSTRAINT "FK_df528cf77e82f8032230e7e37d8" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "webhooks" DROP CONSTRAINT "FK_487a7af59d189f744fe394368fc" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "members" DROP CONSTRAINT "FK_16aceddd5b89825b8ed6029ad1c" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "members" DROP CONSTRAINT "FK_28b53062261b996d9c99fa12404" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "roles" DROP CONSTRAINT "FK_c32c1ab1c4dc7dcb0278c4b1b8b" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "recipients" DROP CONSTRAINT "FK_6157e8b6ba4e6e3089616481fe2" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "recipients" DROP CONSTRAINT "FK_2f18ee1ba667f233ae86c0ea60e" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "bans" DROP CONSTRAINT "FK_07ad88c86d1f290d46748410d58" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "bans" DROP CONSTRAINT "FK_9d3ab7dd180ebdd245cdb66ecad" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "bans" DROP CONSTRAINT "FK_5999e8e449f80a236ff72023559" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "backup_codes" DROP CONSTRAINT "FK_70066ea80d2f4b871beda32633b" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "connected_accounts" DROP CONSTRAINT "FK_f47244225a6a1eac04a3463dd90" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "relationships" DROP CONSTRAINT "FK_9c7f6b98a9843b76dce1b0c878b" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "relationships" DROP CONSTRAINT "FK_9af4194bab1250b1c584ae4f1d7" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "public"."IDX_e22a70819d07659c7a71c112a1" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "public"."IDX_40bb6f23e7cc133292e92829d2" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "message_stickers" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "public"."IDX_bdb8c09e1464cabf62105bf4b9" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "public"."IDX_2a27102ecd1d81b4582a436092" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "message_channel_mentions" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "public"."IDX_29d63eb1a458200851bc37d074" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "public"."IDX_a8242cf535337a490b0feaea0b" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "message_role_mentions" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "public"."IDX_b831eb18ceebd28976239b1e2f" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "public"."IDX_a343387fc560ef378760681c23" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "message_user_mentions" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "public"."IDX_e9080e7a7997a0170026d5139c" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "public"."IDX_5d7ddc8a5f9c167f548625e772" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "member_roles" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "notes" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "client_release" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "sticker_packs" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "sessions" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "rate_limits" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "categories" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "audit_logs" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "applications" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "teams" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "team_members" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "guilds" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "templates" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "emojis" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "channels" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "voice_states" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "invites" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "public"."IDX_0abf8b443321bd3cf7f81ee17a" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "read_states" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "public"."IDX_3ed7a60fb7dbe04e1ba9332a8b" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "public"."IDX_05535bc695e9f7ee104616459d" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "public"."IDX_86b9109b155eb70c0a2ca3b4b6" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "messages" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "attachments" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "stickers" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "webhooks" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "public"."IDX_bb2bf9386ac443afbbbf9f12d3" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "members" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "roles" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "recipients" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "bans" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "backup_codes" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "users" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "connected_accounts" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "public"."IDX_a0b2ff0a598df0b0d055934a17" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "relationships" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "config" `); - } - + } } diff --git a/src/util/migrations/postgres/1659921826567-premium_since_as_date.ts b/src/util/migrations/postgres/1659921826567-premium_since_as_date.ts index ac1e2edb..7543ce85 100644 --- a/src/util/migrations/postgres/1659921826567-premium_since_as_date.ts +++ b/src/util/migrations/postgres/1659921826567-premium_since_as_date.ts @@ -1,26 +1,25 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class premiumSinceAsDate1659921826567 implements MigrationInterface { - name = 'premiumSinceAsDate1659921826567' + name = "premiumSinceAsDate1659921826567"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "members" DROP COLUMN "premium_since" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "members" ADD "premium_since" TIMESTAMP `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "members" DROP COLUMN "premium_since" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "members" ADD "premium_since" bigint `); - } - + } } diff --git a/src/util/migrations/postgres/1660130561959-updated-applications.ts b/src/util/migrations/postgres/1660130561959-updated-applications.ts index 8fab54c7..3d47d6d3 100644 --- a/src/util/migrations/postgres/1660130561959-updated-applications.ts +++ b/src/util/migrations/postgres/1660130561959-updated-applications.ts @@ -1,182 +1,181 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class updatedApplications1660130561959 implements MigrationInterface { - name = 'updatedApplications1660130561959' + name = "updatedApplications1660130561959"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "applications" DROP CONSTRAINT "FK_e5bf78cdbbe9ba91062d74c5aba" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "rpc_origins" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "primary_sku_id" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "slug" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "guild_id" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "type" text `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "hook" boolean NOT NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "redirect_uris" text `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "rpc_application_state" integer `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "store_application_state" integer `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "verification_state" integer `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "interactions_endpoint_url" character varying `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "integration_public" boolean `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "integration_require_code_grant" boolean `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "discoverability_state" integer `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "discovery_eligibility_flags" integer `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "tags" text `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "install_params" text `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "bot_user_id" character varying `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD CONSTRAINT "UQ_2ce5a55796fe4c2f77ece57a647" UNIQUE ("bot_user_id") `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ALTER COLUMN "description" DROP NOT NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "flags" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "flags" integer NOT NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD CONSTRAINT "FK_2ce5a55796fe4c2f77ece57a647" FOREIGN KEY ("bot_user_id") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "applications" DROP CONSTRAINT "FK_2ce5a55796fe4c2f77ece57a647" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "flags" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "flags" character varying NOT NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ALTER COLUMN "description" SET NOT NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP CONSTRAINT "UQ_2ce5a55796fe4c2f77ece57a647" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "bot_user_id" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "install_params" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "tags" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "discovery_eligibility_flags" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "discoverability_state" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "integration_require_code_grant" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "integration_public" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "interactions_endpoint_url" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "verification_state" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "store_application_state" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "rpc_application_state" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "redirect_uris" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "hook" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" DROP COLUMN "type" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "guild_id" character varying `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "slug" character varying `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "primary_sku_id" character varying `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD "rpc_origins" text `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" ADD CONSTRAINT "FK_e5bf78cdbbe9ba91062d74c5aba" FOREIGN KEY ("guild_id") REFERENCES "guilds"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - } - + } } diff --git a/src/util/migrations/postgres/1660257815436-CodeCleanup2.ts b/src/util/migrations/postgres/1660257815436-CodeCleanup2.ts index 511c2f5a..3e4167e9 100644 --- a/src/util/migrations/postgres/1660257815436-CodeCleanup2.ts +++ b/src/util/migrations/postgres/1660257815436-CodeCleanup2.ts @@ -1,10 +1,10 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class CodeCleanup21660257815436 implements MigrationInterface { - name = 'CodeCleanup21660257815436' + name = "CodeCleanup21660257815436"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` CREATE TABLE "user_settings" ( "id" character varying NOT NULL, "afk_timeout" integer, @@ -41,19 +41,18 @@ export class CodeCleanup21660257815436 implements MigrationInterface { CONSTRAINT "PK_00f004f5922a0744d174530d639" PRIMARY KEY ("id") ) `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "guilds" ADD "premium_progress_bar_enabled" boolean `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "guilds" DROP COLUMN "premium_progress_bar_enabled" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "user_settings" `); - } - + } } diff --git a/src/util/migrations/postgres/1660258372154-CodeCleanup3.ts b/src/util/migrations/postgres/1660258372154-CodeCleanup3.ts index e2823a54..3071b59f 100644 --- a/src/util/migrations/postgres/1660258372154-CodeCleanup3.ts +++ b/src/util/migrations/postgres/1660258372154-CodeCleanup3.ts @@ -1,19 +1,18 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class CodeCleanup31660258372154 implements MigrationInterface { - name = 'CodeCleanup31660258372154' + name = "CodeCleanup31660258372154"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "users" DROP COLUMN "settings" `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "users" ADD "settings" text NOT NULL `); - } - + } } diff --git a/src/util/migrations/postgres/1660260565996-CodeCleanup4.ts b/src/util/migrations/postgres/1660260565996-CodeCleanup4.ts index 0aaf7197..c2e9aa85 100644 --- a/src/util/migrations/postgres/1660260565996-CodeCleanup4.ts +++ b/src/util/migrations/postgres/1660260565996-CodeCleanup4.ts @@ -1,33 +1,32 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class CodeCleanup41660260565996 implements MigrationInterface { - name = 'CodeCleanup41660260565996' + name = "CodeCleanup41660260565996"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "users" ADD "settingsId" character varying `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "users" ADD CONSTRAINT "UQ_76ba283779c8441fd5ff819c8cf" UNIQUE ("settingsId") `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "users" ADD CONSTRAINT "FK_76ba283779c8441fd5ff819c8cf" FOREIGN KEY ("settingsId") REFERENCES "user_settings"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "users" DROP CONSTRAINT "FK_76ba283779c8441fd5ff819c8cf" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "users" DROP CONSTRAINT "UQ_76ba283779c8441fd5ff819c8cf" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "users" DROP COLUMN "settingsId" `); - } - + } } diff --git a/src/util/migrations/postgres/1660265907544-CodeCleanup5.ts b/src/util/migrations/postgres/1660265907544-CodeCleanup5.ts index 157d686a..0f098e1f 100644 --- a/src/util/migrations/postgres/1660265907544-CodeCleanup5.ts +++ b/src/util/migrations/postgres/1660265907544-CodeCleanup5.ts @@ -1,26 +1,25 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class CodeCleanup51660265907544 implements MigrationInterface { - name = 'CodeCleanup51660265907544' + name = "CodeCleanup51660265907544"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "channels" ADD "flags" integer `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "channels" ADD "default_thread_rate_limit_per_user" integer `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "channels" DROP COLUMN "default_thread_rate_limit_per_user" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "channels" DROP COLUMN "flags" `); - } - + } } diff --git a/src/util/migrations/postgres/1660416055566-InvitersAreDeletable.ts b/src/util/migrations/postgres/1660416055566-InvitersAreDeletable.ts index e6101318..e8321ede 100644 --- a/src/util/migrations/postgres/1660416055566-InvitersAreDeletable.ts +++ b/src/util/migrations/postgres/1660416055566-InvitersAreDeletable.ts @@ -1,26 +1,25 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class InvitersAreDeletable1660416055566 implements MigrationInterface { - name = 'InvitersAreDeletable1660416055566' + name = "InvitersAreDeletable1660416055566"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "invites" DROP CONSTRAINT "FK_15c35422032e0b22b4ada95f48f" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "invites" ADD CONSTRAINT "FK_15c35422032e0b22b4ada95f48f" FOREIGN KEY ("inviter_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "invites" DROP CONSTRAINT "FK_15c35422032e0b22b4ada95f48f" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "invites" ADD CONSTRAINT "FK_15c35422032e0b22b4ada95f48f" FOREIGN KEY ("inviter_id") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION `); - } - + } } diff --git a/src/util/migrations/postgres/1660549242936-fix_nullables.ts b/src/util/migrations/postgres/1660549242936-fix_nullables.ts index b9a0194d..07fd52f7 100644 --- a/src/util/migrations/postgres/1660549242936-fix_nullables.ts +++ b/src/util/migrations/postgres/1660549242936-fix_nullables.ts @@ -1,30 +1,29 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class fixNullables1660549242936 implements MigrationInterface { - name = 'fixNullables1660549242936' + name = "fixNullables1660549242936"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "users" ALTER COLUMN "bio" DROP NOT NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "users" ALTER COLUMN "mfa_enabled" DROP NOT NULL `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "users" ALTER COLUMN "mfa_enabled" SET NOT NULL `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "users" ALTER COLUMN "bio" SET NOT NULL `); - } - + } } diff --git a/src/util/migrations/sqlite/1659899662635-initial.ts b/src/util/migrations/sqlite/1659899662635-initial.ts index f82e7b0d..dffaa51d 100644 --- a/src/util/migrations/sqlite/1659899662635-initial.ts +++ b/src/util/migrations/sqlite/1659899662635-initial.ts @@ -1,13 +1,13 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class initial1659899662635 implements MigrationInterface { - name = 'initial1659899662635' + name = "initial1659899662635"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` CREATE TABLE "config" ("key" varchar PRIMARY KEY NOT NULL, "value" text) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "relationships" ( "id" varchar PRIMARY KEY NOT NULL, "from_id" varchar NOT NULL, @@ -16,10 +16,10 @@ export class initial1659899662635 implements MigrationInterface { "type" integer NOT NULL ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_a0b2ff0a598df0b0d055934a17" ON "relationships" ("from_id", "to_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "connected_accounts" ( "id" varchar PRIMARY KEY NOT NULL, "user_id" varchar, @@ -33,7 +33,7 @@ export class initial1659899662635 implements MigrationInterface { "visibility" integer NOT NULL ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "users" ( "id" varchar PRIMARY KEY NOT NULL, "username" varchar NOT NULL, @@ -69,7 +69,7 @@ export class initial1659899662635 implements MigrationInterface { "notes" text NOT NULL ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "backup_codes" ( "id" varchar PRIMARY KEY NOT NULL, "code" varchar NOT NULL, @@ -78,7 +78,7 @@ export class initial1659899662635 implements MigrationInterface { "user_id" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "bans" ( "id" varchar PRIMARY KEY NOT NULL, "user_id" varchar, @@ -88,7 +88,7 @@ export class initial1659899662635 implements MigrationInterface { "reason" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "recipients" ( "id" varchar PRIMARY KEY NOT NULL, "channel_id" varchar NOT NULL, @@ -96,7 +96,7 @@ export class initial1659899662635 implements MigrationInterface { "closed" boolean NOT NULL DEFAULT (0) ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "roles" ( "id" varchar PRIMARY KEY NOT NULL, "guild_id" varchar, @@ -112,7 +112,7 @@ export class initial1659899662635 implements MigrationInterface { "tags" text ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "members" ( "index" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "id" varchar NOT NULL, @@ -128,10 +128,10 @@ export class initial1659899662635 implements MigrationInterface { "joined_by" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_bb2bf9386ac443afbbbf9f12d3" ON "members" ("id", "guild_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "webhooks" ( "id" varchar PRIMARY KEY NOT NULL, "type" integer NOT NULL, @@ -145,7 +145,7 @@ export class initial1659899662635 implements MigrationInterface { "source_guild_id" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "stickers" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -159,7 +159,7 @@ export class initial1659899662635 implements MigrationInterface { "format_type" integer NOT NULL ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "attachments" ( "id" varchar PRIMARY KEY NOT NULL, "filename" varchar NOT NULL, @@ -172,7 +172,7 @@ export class initial1659899662635 implements MigrationInterface { "message_id" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "messages" ( "id" varchar PRIMARY KEY NOT NULL, "channel_id" varchar, @@ -199,16 +199,16 @@ export class initial1659899662635 implements MigrationInterface { "message_reference_id" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_86b9109b155eb70c0a2ca3b4b6" ON "messages" ("channel_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_05535bc695e9f7ee104616459d" ON "messages" ("author_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_3ed7a60fb7dbe04e1ba9332a8b" ON "messages" ("channel_id", "id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "read_states" ( "id" varchar PRIMARY KEY NOT NULL, "channel_id" varchar NOT NULL, @@ -220,10 +220,10 @@ export class initial1659899662635 implements MigrationInterface { "mention_count" integer ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_0abf8b443321bd3cf7f81ee17a" ON "read_states" ("channel_id", "user_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "invites" ( "code" varchar PRIMARY KEY NOT NULL, "temporary" boolean NOT NULL, @@ -240,7 +240,7 @@ export class initial1659899662635 implements MigrationInterface { "vanity_url" boolean ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "voice_states" ( "id" varchar PRIMARY KEY NOT NULL, "guild_id" varchar, @@ -258,7 +258,7 @@ export class initial1659899662635 implements MigrationInterface { "request_to_speak_timestamp" datetime ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "channels" ( "id" varchar PRIMARY KEY NOT NULL, "created_at" datetime NOT NULL, @@ -282,7 +282,7 @@ export class initial1659899662635 implements MigrationInterface { "retention_policy_id" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "emojis" ( "id" varchar PRIMARY KEY NOT NULL, "animated" boolean NOT NULL, @@ -296,7 +296,7 @@ export class initial1659899662635 implements MigrationInterface { "groups" text ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "templates" ( "id" varchar PRIMARY KEY NOT NULL, "code" varchar NOT NULL, @@ -311,7 +311,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "UQ_be38737bf339baf63b1daeffb55" UNIQUE ("code") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "guilds" ( "id" varchar PRIMARY KEY NOT NULL, "afk_channel_id" varchar, @@ -353,7 +353,7 @@ export class initial1659899662635 implements MigrationInterface { "parent" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "team_members" ( "id" varchar PRIMARY KEY NOT NULL, "membership_state" integer NOT NULL, @@ -362,7 +362,7 @@ export class initial1659899662635 implements MigrationInterface { "user_id" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "teams" ( "id" varchar PRIMARY KEY NOT NULL, "icon" varchar, @@ -370,7 +370,7 @@ export class initial1659899662635 implements MigrationInterface { "owner_user_id" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "applications" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -392,7 +392,7 @@ export class initial1659899662635 implements MigrationInterface { "guild_id" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "audit_logs" ( "id" varchar PRIMARY KEY NOT NULL, "user_id" varchar, @@ -403,7 +403,7 @@ export class initial1659899662635 implements MigrationInterface { "target_id" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "categories" ( "id" integer PRIMARY KEY NOT NULL, "name" varchar, @@ -411,7 +411,7 @@ export class initial1659899662635 implements MigrationInterface { "is_primary" boolean ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "rate_limits" ( "id" varchar PRIMARY KEY NOT NULL, "executor_id" varchar NOT NULL, @@ -420,7 +420,7 @@ export class initial1659899662635 implements MigrationInterface { "expires_at" datetime NOT NULL ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "sessions" ( "id" varchar PRIMARY KEY NOT NULL, "user_id" varchar, @@ -430,7 +430,7 @@ export class initial1659899662635 implements MigrationInterface { "status" varchar NOT NULL ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "sticker_packs" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -440,7 +440,7 @@ export class initial1659899662635 implements MigrationInterface { "coverStickerId" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "client_release" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -452,7 +452,7 @@ export class initial1659899662635 implements MigrationInterface { "notes" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "notes" ( "id" varchar PRIMARY KEY NOT NULL, "content" varchar NOT NULL, @@ -461,75 +461,75 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "UQ_74e6689b9568cc965b8bfc9150b" UNIQUE ("owner_id", "target_id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "member_roles" ( "index" integer NOT NULL, "role_id" varchar NOT NULL, PRIMARY KEY ("index", "role_id") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_5d7ddc8a5f9c167f548625e772" ON "member_roles" ("index") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_e9080e7a7997a0170026d5139c" ON "member_roles" ("role_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "message_user_mentions" ( "messagesId" varchar NOT NULL, "usersId" varchar NOT NULL, PRIMARY KEY ("messagesId", "usersId") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_a343387fc560ef378760681c23" ON "message_user_mentions" ("messagesId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_b831eb18ceebd28976239b1e2f" ON "message_user_mentions" ("usersId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "message_role_mentions" ( "messagesId" varchar NOT NULL, "rolesId" varchar NOT NULL, PRIMARY KEY ("messagesId", "rolesId") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_a8242cf535337a490b0feaea0b" ON "message_role_mentions" ("messagesId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_29d63eb1a458200851bc37d074" ON "message_role_mentions" ("rolesId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "message_channel_mentions" ( "messagesId" varchar NOT NULL, "channelsId" varchar NOT NULL, PRIMARY KEY ("messagesId", "channelsId") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_2a27102ecd1d81b4582a436092" ON "message_channel_mentions" ("messagesId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_bdb8c09e1464cabf62105bf4b9" ON "message_channel_mentions" ("channelsId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "message_stickers" ( "messagesId" varchar NOT NULL, "stickersId" varchar NOT NULL, PRIMARY KEY ("messagesId", "stickersId") ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_40bb6f23e7cc133292e92829d2" ON "message_stickers" ("messagesId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_e22a70819d07659c7a71c112a1" ON "message_stickers" ("stickersId") `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_a0b2ff0a598df0b0d055934a17" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_relationships" ( "id" varchar PRIMARY KEY NOT NULL, "from_id" varchar NOT NULL, @@ -540,7 +540,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_9c7f6b98a9843b76dce1b0c878b" FOREIGN KEY ("to_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_relationships"("id", "from_id", "to_id", "nickname", "type") SELECT "id", "from_id", @@ -549,17 +549,17 @@ export class initial1659899662635 implements MigrationInterface { "type" FROM "relationships" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "relationships" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_relationships" RENAME TO "relationships" `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_a0b2ff0a598df0b0d055934a17" ON "relationships" ("from_id", "to_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_connected_accounts" ( "id" varchar PRIMARY KEY NOT NULL, "user_id" varchar, @@ -574,7 +574,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_f47244225a6a1eac04a3463dd90" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_connected_accounts"( "id", "user_id", @@ -599,14 +599,14 @@ export class initial1659899662635 implements MigrationInterface { "visibility" FROM "connected_accounts" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "connected_accounts" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_connected_accounts" RENAME TO "connected_accounts" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_backup_codes" ( "id" varchar PRIMARY KEY NOT NULL, "code" varchar NOT NULL, @@ -616,7 +616,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_70066ea80d2f4b871beda32633b" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_backup_codes"("id", "code", "consumed", "expired", "user_id") SELECT "id", "code", @@ -625,14 +625,14 @@ export class initial1659899662635 implements MigrationInterface { "user_id" FROM "backup_codes" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "backup_codes" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_backup_codes" RENAME TO "backup_codes" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_bans" ( "id" varchar PRIMARY KEY NOT NULL, "user_id" varchar, @@ -645,7 +645,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_07ad88c86d1f290d46748410d58" FOREIGN KEY ("executor_id") REFERENCES "users" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_bans"( "id", "user_id", @@ -662,14 +662,14 @@ export class initial1659899662635 implements MigrationInterface { "reason" FROM "bans" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "bans" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_bans" RENAME TO "bans" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_recipients" ( "id" varchar PRIMARY KEY NOT NULL, "channel_id" varchar NOT NULL, @@ -679,7 +679,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_6157e8b6ba4e6e3089616481fe2" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_recipients"("id", "channel_id", "user_id", "closed") SELECT "id", "channel_id", @@ -687,14 +687,14 @@ export class initial1659899662635 implements MigrationInterface { "closed" FROM "recipients" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "recipients" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_recipients" RENAME TO "recipients" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_roles" ( "id" varchar PRIMARY KEY NOT NULL, "guild_id" varchar, @@ -711,7 +711,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_c32c1ab1c4dc7dcb0278c4b1b8b" FOREIGN KEY ("guild_id") REFERENCES "guilds" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_roles"( "id", "guild_id", @@ -740,17 +740,17 @@ export class initial1659899662635 implements MigrationInterface { "tags" FROM "roles" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "roles" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_roles" RENAME TO "roles" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_bb2bf9386ac443afbbbf9f12d3" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_members" ( "index" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "id" varchar NOT NULL, @@ -768,7 +768,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_16aceddd5b89825b8ed6029ad1c" FOREIGN KEY ("guild_id") REFERENCES "guilds" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_members"( "index", "id", @@ -797,17 +797,17 @@ export class initial1659899662635 implements MigrationInterface { "joined_by" FROM "members" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "members" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_members" RENAME TO "members" `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_bb2bf9386ac443afbbbf9f12d3" ON "members" ("id", "guild_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_webhooks" ( "id" varchar PRIMARY KEY NOT NULL, "type" integer NOT NULL, @@ -826,7 +826,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_3a285f4f49c40e0706d3018bc9f" FOREIGN KEY ("source_guild_id") REFERENCES "guilds" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_webhooks"( "id", "type", @@ -851,14 +851,14 @@ export class initial1659899662635 implements MigrationInterface { "source_guild_id" FROM "webhooks" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "webhooks" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_webhooks" RENAME TO "webhooks" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_stickers" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -875,7 +875,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_8f4ee73f2bb2325ff980502e158" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_stickers"( "id", "name", @@ -900,14 +900,14 @@ export class initial1659899662635 implements MigrationInterface { "format_type" FROM "stickers" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "stickers" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_stickers" RENAME TO "stickers" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_attachments" ( "id" varchar PRIMARY KEY NOT NULL, "filename" varchar NOT NULL, @@ -921,7 +921,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_623e10eec51ada466c5038979e3" FOREIGN KEY ("message_id") REFERENCES "messages" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_attachments"( "id", "filename", @@ -944,23 +944,23 @@ export class initial1659899662635 implements MigrationInterface { "message_id" FROM "attachments" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "attachments" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_attachments" RENAME TO "attachments" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_86b9109b155eb70c0a2ca3b4b6" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_05535bc695e9f7ee104616459d" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_3ed7a60fb7dbe04e1ba9332a8b" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_messages" ( "id" varchar PRIMARY KEY NOT NULL, "channel_id" varchar, @@ -994,7 +994,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_61a92bb65b302a76d9c1fcd3174" FOREIGN KEY ("message_reference_id") REFERENCES "messages" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_messages"( "id", "channel_id", @@ -1045,26 +1045,26 @@ export class initial1659899662635 implements MigrationInterface { "message_reference_id" FROM "messages" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "messages" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_messages" RENAME TO "messages" `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_86b9109b155eb70c0a2ca3b4b6" ON "messages" ("channel_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_05535bc695e9f7ee104616459d" ON "messages" ("author_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_3ed7a60fb7dbe04e1ba9332a8b" ON "messages" ("channel_id", "id") `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_0abf8b443321bd3cf7f81ee17a" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_read_states" ( "id" varchar PRIMARY KEY NOT NULL, "channel_id" varchar NOT NULL, @@ -1078,7 +1078,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_195f92e4dd1254a4e348c043763" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_read_states"( "id", "channel_id", @@ -1099,17 +1099,17 @@ export class initial1659899662635 implements MigrationInterface { "mention_count" FROM "read_states" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "read_states" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_read_states" RENAME TO "read_states" `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_0abf8b443321bd3cf7f81ee17a" ON "read_states" ("channel_id", "user_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_invites" ( "code" varchar PRIMARY KEY NOT NULL, "temporary" boolean NOT NULL, @@ -1130,7 +1130,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_11a0d394f8fc649c19ce5f16b59" FOREIGN KEY ("target_user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_invites"( "code", "temporary", @@ -1161,14 +1161,14 @@ export class initial1659899662635 implements MigrationInterface { "vanity_url" FROM "invites" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "invites" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_invites" RENAME TO "invites" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_voice_states" ( "id" varchar PRIMARY KEY NOT NULL, "guild_id" varchar, @@ -1189,7 +1189,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_5fe1d5f931a67e85039c640001b" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_voice_states"( "id", "guild_id", @@ -1222,14 +1222,14 @@ export class initial1659899662635 implements MigrationInterface { "request_to_speak_timestamp" FROM "voice_states" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "voice_states" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_voice_states" RENAME TO "voice_states" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_channels" ( "id" varchar PRIMARY KEY NOT NULL, "created_at" datetime NOT NULL, @@ -1256,7 +1256,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_3873ed438575cce703ecff4fc7b" FOREIGN KEY ("owner_id") REFERENCES "users" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_channels"( "id", "created_at", @@ -1301,14 +1301,14 @@ export class initial1659899662635 implements MigrationInterface { "retention_policy_id" FROM "channels" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "channels" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_channels" RENAME TO "channels" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_emojis" ( "id" varchar PRIMARY KEY NOT NULL, "animated" boolean NOT NULL, @@ -1324,7 +1324,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_fa7ddd5f9a214e28ce596548421" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_emojis"( "id", "animated", @@ -1349,14 +1349,14 @@ export class initial1659899662635 implements MigrationInterface { "groups" FROM "emojis" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "emojis" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_emojis" RENAME TO "emojis" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_templates" ( "id" varchar PRIMARY KEY NOT NULL, "code" varchar NOT NULL, @@ -1373,7 +1373,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_445d00eaaea0e60a017a5ed0c11" FOREIGN KEY ("source_guild_id") REFERENCES "guilds" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_templates"( "id", "code", @@ -1398,14 +1398,14 @@ export class initial1659899662635 implements MigrationInterface { "serialized_source_guild" FROM "templates" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "templates" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_templates" RENAME TO "templates" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_guilds" ( "id" varchar PRIMARY KEY NOT NULL, "afk_channel_id" varchar, @@ -1454,7 +1454,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_9d1d665379eefde7876a17afa99" FOREIGN KEY ("widget_channel_id") REFERENCES "channels" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_guilds"( "id", "afk_channel_id", @@ -1535,14 +1535,14 @@ export class initial1659899662635 implements MigrationInterface { "parent" FROM "guilds" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "guilds" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_guilds" RENAME TO "guilds" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_team_members" ( "id" varchar PRIMARY KEY NOT NULL, "membership_state" integer NOT NULL, @@ -1553,7 +1553,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_c2bf4967c8c2a6b845dadfbf3d4" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_team_members"( "id", "membership_state", @@ -1568,14 +1568,14 @@ export class initial1659899662635 implements MigrationInterface { "user_id" FROM "team_members" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "team_members" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_team_members" RENAME TO "team_members" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_teams" ( "id" varchar PRIMARY KEY NOT NULL, "icon" varchar, @@ -1584,7 +1584,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_13f00abf7cb6096c43ecaf8c108" FOREIGN KEY ("owner_user_id") REFERENCES "users" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_teams"("id", "icon", "name", "owner_user_id") SELECT "id", "icon", @@ -1592,14 +1592,14 @@ export class initial1659899662635 implements MigrationInterface { "owner_user_id" FROM "teams" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "teams" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_teams" RENAME TO "teams" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_applications" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -1624,7 +1624,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_e5bf78cdbbe9ba91062d74c5aba" FOREIGN KEY ("guild_id") REFERENCES "guilds" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_applications"( "id", "name", @@ -1665,14 +1665,14 @@ export class initial1659899662635 implements MigrationInterface { "guild_id" FROM "applications" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "applications" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_applications" RENAME TO "applications" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_audit_logs" ( "id" varchar PRIMARY KEY NOT NULL, "user_id" varchar, @@ -1685,7 +1685,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_bd2726fd31b35443f2245b93ba0" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_audit_logs"( "id", "user_id", @@ -1704,14 +1704,14 @@ export class initial1659899662635 implements MigrationInterface { "target_id" FROM "audit_logs" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "audit_logs" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_audit_logs" RENAME TO "audit_logs" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_sessions" ( "id" varchar PRIMARY KEY NOT NULL, "user_id" varchar, @@ -1722,7 +1722,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_085d540d9f418cfbdc7bd55bb19" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_sessions"( "id", "user_id", @@ -1739,14 +1739,14 @@ export class initial1659899662635 implements MigrationInterface { "status" FROM "sessions" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "sessions" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_sessions" RENAME TO "sessions" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_sticker_packs" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -1757,7 +1757,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_448fafba4355ee1c837bbc865f1" FOREIGN KEY ("coverStickerId") REFERENCES "stickers" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_sticker_packs"( "id", "name", @@ -1774,14 +1774,14 @@ export class initial1659899662635 implements MigrationInterface { "coverStickerId" FROM "sticker_packs" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "sticker_packs" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_sticker_packs" RENAME TO "sticker_packs" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_notes" ( "id" varchar PRIMARY KEY NOT NULL, "content" varchar NOT NULL, @@ -1792,7 +1792,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "FK_23e08e5b4481711d573e1abecdc" FOREIGN KEY ("target_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_notes"("id", "content", "owner_id", "target_id") SELECT "id", "content", @@ -1800,20 +1800,20 @@ export class initial1659899662635 implements MigrationInterface { "target_id" FROM "notes" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "notes" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_notes" RENAME TO "notes" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_5d7ddc8a5f9c167f548625e772" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_e9080e7a7997a0170026d5139c" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_member_roles" ( "index" integer NOT NULL, "role_id" varchar NOT NULL, @@ -1822,32 +1822,32 @@ export class initial1659899662635 implements MigrationInterface { PRIMARY KEY ("index", "role_id") ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_member_roles"("index", "role_id") SELECT "index", "role_id" FROM "member_roles" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "member_roles" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_member_roles" RENAME TO "member_roles" `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_5d7ddc8a5f9c167f548625e772" ON "member_roles" ("index") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_e9080e7a7997a0170026d5139c" ON "member_roles" ("role_id") `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_a343387fc560ef378760681c23" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_b831eb18ceebd28976239b1e2f" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_message_user_mentions" ( "messagesId" varchar NOT NULL, "usersId" varchar NOT NULL, @@ -1856,32 +1856,32 @@ export class initial1659899662635 implements MigrationInterface { PRIMARY KEY ("messagesId", "usersId") ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_message_user_mentions"("messagesId", "usersId") SELECT "messagesId", "usersId" FROM "message_user_mentions" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "message_user_mentions" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_message_user_mentions" RENAME TO "message_user_mentions" `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_a343387fc560ef378760681c23" ON "message_user_mentions" ("messagesId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_b831eb18ceebd28976239b1e2f" ON "message_user_mentions" ("usersId") `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_a8242cf535337a490b0feaea0b" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_29d63eb1a458200851bc37d074" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_message_role_mentions" ( "messagesId" varchar NOT NULL, "rolesId" varchar NOT NULL, @@ -1890,32 +1890,32 @@ export class initial1659899662635 implements MigrationInterface { PRIMARY KEY ("messagesId", "rolesId") ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_message_role_mentions"("messagesId", "rolesId") SELECT "messagesId", "rolesId" FROM "message_role_mentions" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "message_role_mentions" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_message_role_mentions" RENAME TO "message_role_mentions" `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_a8242cf535337a490b0feaea0b" ON "message_role_mentions" ("messagesId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_29d63eb1a458200851bc37d074" ON "message_role_mentions" ("rolesId") `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_2a27102ecd1d81b4582a436092" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_bdb8c09e1464cabf62105bf4b9" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_message_channel_mentions" ( "messagesId" varchar NOT NULL, "channelsId" varchar NOT NULL, @@ -1924,32 +1924,32 @@ export class initial1659899662635 implements MigrationInterface { PRIMARY KEY ("messagesId", "channelsId") ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_message_channel_mentions"("messagesId", "channelsId") SELECT "messagesId", "channelsId" FROM "message_channel_mentions" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "message_channel_mentions" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_message_channel_mentions" RENAME TO "message_channel_mentions" `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_2a27102ecd1d81b4582a436092" ON "message_channel_mentions" ("messagesId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_bdb8c09e1464cabf62105bf4b9" ON "message_channel_mentions" ("channelsId") `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_40bb6f23e7cc133292e92829d2" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_e22a70819d07659c7a71c112a1" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_message_stickers" ( "messagesId" varchar NOT NULL, "stickersId" varchar NOT NULL, @@ -1958,26 +1958,26 @@ export class initial1659899662635 implements MigrationInterface { PRIMARY KEY ("messagesId", "stickersId") ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_message_stickers"("messagesId", "stickersId") SELECT "messagesId", "stickersId" FROM "message_stickers" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "message_stickers" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_message_stickers" RENAME TO "message_stickers" `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_40bb6f23e7cc133292e92829d2" ON "message_stickers" ("messagesId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_e22a70819d07659c7a71c112a1" ON "message_stickers" ("stickersId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "query-result-cache" ( "id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "identifier" varchar, @@ -1987,177 +1987,177 @@ export class initial1659899662635 implements MigrationInterface { "result" text NOT NULL ) `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` DROP TABLE "query-result-cache" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_e22a70819d07659c7a71c112a1" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_40bb6f23e7cc133292e92829d2" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_stickers" RENAME TO "temporary_message_stickers" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "message_stickers" ( "messagesId" varchar NOT NULL, "stickersId" varchar NOT NULL, PRIMARY KEY ("messagesId", "stickersId") ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "message_stickers"("messagesId", "stickersId") SELECT "messagesId", "stickersId" FROM "temporary_message_stickers" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_message_stickers" `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_e22a70819d07659c7a71c112a1" ON "message_stickers" ("stickersId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_40bb6f23e7cc133292e92829d2" ON "message_stickers" ("messagesId") `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_bdb8c09e1464cabf62105bf4b9" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_2a27102ecd1d81b4582a436092" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_channel_mentions" RENAME TO "temporary_message_channel_mentions" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "message_channel_mentions" ( "messagesId" varchar NOT NULL, "channelsId" varchar NOT NULL, PRIMARY KEY ("messagesId", "channelsId") ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "message_channel_mentions"("messagesId", "channelsId") SELECT "messagesId", "channelsId" FROM "temporary_message_channel_mentions" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_message_channel_mentions" `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_bdb8c09e1464cabf62105bf4b9" ON "message_channel_mentions" ("channelsId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_2a27102ecd1d81b4582a436092" ON "message_channel_mentions" ("messagesId") `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_29d63eb1a458200851bc37d074" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_a8242cf535337a490b0feaea0b" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_role_mentions" RENAME TO "temporary_message_role_mentions" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "message_role_mentions" ( "messagesId" varchar NOT NULL, "rolesId" varchar NOT NULL, PRIMARY KEY ("messagesId", "rolesId") ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "message_role_mentions"("messagesId", "rolesId") SELECT "messagesId", "rolesId" FROM "temporary_message_role_mentions" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_message_role_mentions" `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_29d63eb1a458200851bc37d074" ON "message_role_mentions" ("rolesId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_a8242cf535337a490b0feaea0b" ON "message_role_mentions" ("messagesId") `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_b831eb18ceebd28976239b1e2f" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_a343387fc560ef378760681c23" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "message_user_mentions" RENAME TO "temporary_message_user_mentions" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "message_user_mentions" ( "messagesId" varchar NOT NULL, "usersId" varchar NOT NULL, PRIMARY KEY ("messagesId", "usersId") ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "message_user_mentions"("messagesId", "usersId") SELECT "messagesId", "usersId" FROM "temporary_message_user_mentions" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_message_user_mentions" `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_b831eb18ceebd28976239b1e2f" ON "message_user_mentions" ("usersId") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_a343387fc560ef378760681c23" ON "message_user_mentions" ("messagesId") `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_e9080e7a7997a0170026d5139c" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_5d7ddc8a5f9c167f548625e772" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "member_roles" RENAME TO "temporary_member_roles" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "member_roles" ( "index" integer NOT NULL, "role_id" varchar NOT NULL, PRIMARY KEY ("index", "role_id") ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "member_roles"("index", "role_id") SELECT "index", "role_id" FROM "temporary_member_roles" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_member_roles" `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_e9080e7a7997a0170026d5139c" ON "member_roles" ("role_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_5d7ddc8a5f9c167f548625e772" ON "member_roles" ("index") `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "notes" RENAME TO "temporary_notes" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "notes" ( "id" varchar PRIMARY KEY NOT NULL, "content" varchar NOT NULL, @@ -2166,7 +2166,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "UQ_74e6689b9568cc965b8bfc9150b" UNIQUE ("owner_id", "target_id") ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "notes"("id", "content", "owner_id", "target_id") SELECT "id", "content", @@ -2174,14 +2174,14 @@ export class initial1659899662635 implements MigrationInterface { "target_id" FROM "temporary_notes" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_notes" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "sticker_packs" RENAME TO "temporary_sticker_packs" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "sticker_packs" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -2191,7 +2191,7 @@ export class initial1659899662635 implements MigrationInterface { "coverStickerId" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "sticker_packs"( "id", "name", @@ -2208,14 +2208,14 @@ export class initial1659899662635 implements MigrationInterface { "coverStickerId" FROM "temporary_sticker_packs" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_sticker_packs" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "sessions" RENAME TO "temporary_sessions" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "sessions" ( "id" varchar PRIMARY KEY NOT NULL, "user_id" varchar, @@ -2225,7 +2225,7 @@ export class initial1659899662635 implements MigrationInterface { "status" varchar NOT NULL ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "sessions"( "id", "user_id", @@ -2242,14 +2242,14 @@ export class initial1659899662635 implements MigrationInterface { "status" FROM "temporary_sessions" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_sessions" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "audit_logs" RENAME TO "temporary_audit_logs" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "audit_logs" ( "id" varchar PRIMARY KEY NOT NULL, "user_id" varchar, @@ -2260,7 +2260,7 @@ export class initial1659899662635 implements MigrationInterface { "target_id" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "audit_logs"( "id", "user_id", @@ -2279,14 +2279,14 @@ export class initial1659899662635 implements MigrationInterface { "target_id" FROM "temporary_audit_logs" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_audit_logs" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" RENAME TO "temporary_applications" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "applications" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -2308,7 +2308,7 @@ export class initial1659899662635 implements MigrationInterface { "guild_id" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "applications"( "id", "name", @@ -2349,14 +2349,14 @@ export class initial1659899662635 implements MigrationInterface { "guild_id" FROM "temporary_applications" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_applications" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "teams" RENAME TO "temporary_teams" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "teams" ( "id" varchar PRIMARY KEY NOT NULL, "icon" varchar, @@ -2364,7 +2364,7 @@ export class initial1659899662635 implements MigrationInterface { "owner_user_id" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "teams"("id", "icon", "name", "owner_user_id") SELECT "id", "icon", @@ -2372,14 +2372,14 @@ export class initial1659899662635 implements MigrationInterface { "owner_user_id" FROM "temporary_teams" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_teams" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "team_members" RENAME TO "temporary_team_members" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "team_members" ( "id" varchar PRIMARY KEY NOT NULL, "membership_state" integer NOT NULL, @@ -2388,7 +2388,7 @@ export class initial1659899662635 implements MigrationInterface { "user_id" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "team_members"( "id", "membership_state", @@ -2403,14 +2403,14 @@ export class initial1659899662635 implements MigrationInterface { "user_id" FROM "temporary_team_members" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_team_members" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "guilds" RENAME TO "temporary_guilds" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "guilds" ( "id" varchar PRIMARY KEY NOT NULL, "afk_channel_id" varchar, @@ -2452,7 +2452,7 @@ export class initial1659899662635 implements MigrationInterface { "parent" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "guilds"( "id", "afk_channel_id", @@ -2533,14 +2533,14 @@ export class initial1659899662635 implements MigrationInterface { "parent" FROM "temporary_guilds" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_guilds" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "templates" RENAME TO "temporary_templates" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "templates" ( "id" varchar PRIMARY KEY NOT NULL, "code" varchar NOT NULL, @@ -2555,7 +2555,7 @@ export class initial1659899662635 implements MigrationInterface { CONSTRAINT "UQ_be38737bf339baf63b1daeffb55" UNIQUE ("code") ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "templates"( "id", "code", @@ -2580,14 +2580,14 @@ export class initial1659899662635 implements MigrationInterface { "serialized_source_guild" FROM "temporary_templates" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_templates" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "emojis" RENAME TO "temporary_emojis" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "emojis" ( "id" varchar PRIMARY KEY NOT NULL, "animated" boolean NOT NULL, @@ -2601,7 +2601,7 @@ export class initial1659899662635 implements MigrationInterface { "groups" text ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "emojis"( "id", "animated", @@ -2626,14 +2626,14 @@ export class initial1659899662635 implements MigrationInterface { "groups" FROM "temporary_emojis" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_emojis" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "channels" RENAME TO "temporary_channels" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "channels" ( "id" varchar PRIMARY KEY NOT NULL, "created_at" datetime NOT NULL, @@ -2657,7 +2657,7 @@ export class initial1659899662635 implements MigrationInterface { "retention_policy_id" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "channels"( "id", "created_at", @@ -2702,14 +2702,14 @@ export class initial1659899662635 implements MigrationInterface { "retention_policy_id" FROM "temporary_channels" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_channels" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "voice_states" RENAME TO "temporary_voice_states" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "voice_states" ( "id" varchar PRIMARY KEY NOT NULL, "guild_id" varchar, @@ -2727,7 +2727,7 @@ export class initial1659899662635 implements MigrationInterface { "request_to_speak_timestamp" datetime ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "voice_states"( "id", "guild_id", @@ -2760,14 +2760,14 @@ export class initial1659899662635 implements MigrationInterface { "request_to_speak_timestamp" FROM "temporary_voice_states" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_voice_states" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "invites" RENAME TO "temporary_invites" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "invites" ( "code" varchar PRIMARY KEY NOT NULL, "temporary" boolean NOT NULL, @@ -2784,7 +2784,7 @@ export class initial1659899662635 implements MigrationInterface { "vanity_url" boolean ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "invites"( "code", "temporary", @@ -2815,17 +2815,17 @@ export class initial1659899662635 implements MigrationInterface { "vanity_url" FROM "temporary_invites" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_invites" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_0abf8b443321bd3cf7f81ee17a" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "read_states" RENAME TO "temporary_read_states" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "read_states" ( "id" varchar PRIMARY KEY NOT NULL, "channel_id" varchar NOT NULL, @@ -2837,7 +2837,7 @@ export class initial1659899662635 implements MigrationInterface { "mention_count" integer ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "read_states"( "id", "channel_id", @@ -2858,26 +2858,26 @@ export class initial1659899662635 implements MigrationInterface { "mention_count" FROM "temporary_read_states" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_read_states" `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_0abf8b443321bd3cf7f81ee17a" ON "read_states" ("channel_id", "user_id") `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_3ed7a60fb7dbe04e1ba9332a8b" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_05535bc695e9f7ee104616459d" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_86b9109b155eb70c0a2ca3b4b6" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "messages" RENAME TO "temporary_messages" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "messages" ( "id" varchar PRIMARY KEY NOT NULL, "channel_id" varchar, @@ -2904,7 +2904,7 @@ export class initial1659899662635 implements MigrationInterface { "message_reference_id" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "messages"( "id", "channel_id", @@ -2955,23 +2955,23 @@ export class initial1659899662635 implements MigrationInterface { "message_reference_id" FROM "temporary_messages" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_messages" `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_3ed7a60fb7dbe04e1ba9332a8b" ON "messages" ("channel_id", "id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_05535bc695e9f7ee104616459d" ON "messages" ("author_id") `); - await queryRunner.query(` + await queryRunner.query(` CREATE INDEX "IDX_86b9109b155eb70c0a2ca3b4b6" ON "messages" ("channel_id") `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "attachments" RENAME TO "temporary_attachments" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "attachments" ( "id" varchar PRIMARY KEY NOT NULL, "filename" varchar NOT NULL, @@ -2984,7 +2984,7 @@ export class initial1659899662635 implements MigrationInterface { "message_id" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "attachments"( "id", "filename", @@ -3007,14 +3007,14 @@ export class initial1659899662635 implements MigrationInterface { "message_id" FROM "temporary_attachments" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_attachments" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "stickers" RENAME TO "temporary_stickers" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "stickers" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -3028,7 +3028,7 @@ export class initial1659899662635 implements MigrationInterface { "format_type" integer NOT NULL ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "stickers"( "id", "name", @@ -3053,14 +3053,14 @@ export class initial1659899662635 implements MigrationInterface { "format_type" FROM "temporary_stickers" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_stickers" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "webhooks" RENAME TO "temporary_webhooks" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "webhooks" ( "id" varchar PRIMARY KEY NOT NULL, "type" integer NOT NULL, @@ -3074,7 +3074,7 @@ export class initial1659899662635 implements MigrationInterface { "source_guild_id" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "webhooks"( "id", "type", @@ -3099,17 +3099,17 @@ export class initial1659899662635 implements MigrationInterface { "source_guild_id" FROM "temporary_webhooks" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_webhooks" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_bb2bf9386ac443afbbbf9f12d3" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "members" RENAME TO "temporary_members" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "members" ( "index" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "id" varchar NOT NULL, @@ -3125,7 +3125,7 @@ export class initial1659899662635 implements MigrationInterface { "joined_by" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "members"( "index", "id", @@ -3154,17 +3154,17 @@ export class initial1659899662635 implements MigrationInterface { "joined_by" FROM "temporary_members" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_members" `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_bb2bf9386ac443afbbbf9f12d3" ON "members" ("id", "guild_id") `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "roles" RENAME TO "temporary_roles" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "roles" ( "id" varchar PRIMARY KEY NOT NULL, "guild_id" varchar, @@ -3180,7 +3180,7 @@ export class initial1659899662635 implements MigrationInterface { "tags" text ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "roles"( "id", "guild_id", @@ -3209,14 +3209,14 @@ export class initial1659899662635 implements MigrationInterface { "tags" FROM "temporary_roles" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_roles" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "recipients" RENAME TO "temporary_recipients" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "recipients" ( "id" varchar PRIMARY KEY NOT NULL, "channel_id" varchar NOT NULL, @@ -3224,7 +3224,7 @@ export class initial1659899662635 implements MigrationInterface { "closed" boolean NOT NULL DEFAULT (0) ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "recipients"("id", "channel_id", "user_id", "closed") SELECT "id", "channel_id", @@ -3232,14 +3232,14 @@ export class initial1659899662635 implements MigrationInterface { "closed" FROM "temporary_recipients" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_recipients" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "bans" RENAME TO "temporary_bans" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "bans" ( "id" varchar PRIMARY KEY NOT NULL, "user_id" varchar, @@ -3249,7 +3249,7 @@ export class initial1659899662635 implements MigrationInterface { "reason" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "bans"( "id", "user_id", @@ -3266,14 +3266,14 @@ export class initial1659899662635 implements MigrationInterface { "reason" FROM "temporary_bans" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_bans" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "backup_codes" RENAME TO "temporary_backup_codes" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "backup_codes" ( "id" varchar PRIMARY KEY NOT NULL, "code" varchar NOT NULL, @@ -3282,7 +3282,7 @@ export class initial1659899662635 implements MigrationInterface { "user_id" varchar ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "backup_codes"("id", "code", "consumed", "expired", "user_id") SELECT "id", "code", @@ -3291,14 +3291,14 @@ export class initial1659899662635 implements MigrationInterface { "user_id" FROM "temporary_backup_codes" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_backup_codes" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "connected_accounts" RENAME TO "temporary_connected_accounts" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "connected_accounts" ( "id" varchar PRIMARY KEY NOT NULL, "user_id" varchar, @@ -3312,7 +3312,7 @@ export class initial1659899662635 implements MigrationInterface { "visibility" integer NOT NULL ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "connected_accounts"( "id", "user_id", @@ -3337,17 +3337,17 @@ export class initial1659899662635 implements MigrationInterface { "visibility" FROM "temporary_connected_accounts" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_connected_accounts" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_a0b2ff0a598df0b0d055934a17" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "relationships" RENAME TO "temporary_relationships" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "relationships" ( "id" varchar PRIMARY KEY NOT NULL, "from_id" varchar NOT NULL, @@ -3356,7 +3356,7 @@ export class initial1659899662635 implements MigrationInterface { "type" integer NOT NULL ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "relationships"("id", "from_id", "to_id", "nickname", "type") SELECT "id", "from_id", @@ -3365,165 +3365,164 @@ export class initial1659899662635 implements MigrationInterface { "type" FROM "temporary_relationships" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_relationships" `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_a0b2ff0a598df0b0d055934a17" ON "relationships" ("from_id", "to_id") `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_e22a70819d07659c7a71c112a1" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_40bb6f23e7cc133292e92829d2" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "message_stickers" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_bdb8c09e1464cabf62105bf4b9" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_2a27102ecd1d81b4582a436092" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "message_channel_mentions" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_29d63eb1a458200851bc37d074" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_a8242cf535337a490b0feaea0b" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "message_role_mentions" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_b831eb18ceebd28976239b1e2f" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_a343387fc560ef378760681c23" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "message_user_mentions" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_e9080e7a7997a0170026d5139c" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_5d7ddc8a5f9c167f548625e772" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "member_roles" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "notes" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "client_release" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "sticker_packs" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "sessions" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "rate_limits" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "categories" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "audit_logs" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "applications" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "teams" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "team_members" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "guilds" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "templates" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "emojis" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "channels" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "voice_states" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "invites" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_0abf8b443321bd3cf7f81ee17a" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "read_states" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_3ed7a60fb7dbe04e1ba9332a8b" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_05535bc695e9f7ee104616459d" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_86b9109b155eb70c0a2ca3b4b6" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "messages" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "attachments" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "stickers" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "webhooks" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_bb2bf9386ac443afbbbf9f12d3" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "members" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "roles" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "recipients" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "bans" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "backup_codes" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "users" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "connected_accounts" `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_a0b2ff0a598df0b0d055934a17" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "relationships" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "config" `); - } - + } } diff --git a/src/util/migrations/sqlite/1659921722863-premium_since_as_date.ts b/src/util/migrations/sqlite/1659921722863-premium_since_as_date.ts index 788be625..b6307ee9 100644 --- a/src/util/migrations/sqlite/1659921722863-premium_since_as_date.ts +++ b/src/util/migrations/sqlite/1659921722863-premium_since_as_date.ts @@ -1,13 +1,13 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class premiumSinceAsDate1659921722863 implements MigrationInterface { - name = 'premiumSinceAsDate1659921722863' + name = "premiumSinceAsDate1659921722863"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` DROP INDEX "IDX_bb2bf9386ac443afbbbf9f12d3" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_members" ( "index" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "id" varchar NOT NULL, @@ -25,7 +25,7 @@ export class premiumSinceAsDate1659921722863 implements MigrationInterface { CONSTRAINT "FK_28b53062261b996d9c99fa12404" FOREIGN KEY ("id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_members"( "index", "id", @@ -54,20 +54,20 @@ export class premiumSinceAsDate1659921722863 implements MigrationInterface { "joined_by" FROM "members" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "members" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_members" RENAME TO "members" `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_bb2bf9386ac443afbbbf9f12d3" ON "members" ("id", "guild_id") `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_bb2bf9386ac443afbbbf9f12d3" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_members" ( "index" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "id" varchar NOT NULL, @@ -85,7 +85,7 @@ export class premiumSinceAsDate1659921722863 implements MigrationInterface { CONSTRAINT "FK_28b53062261b996d9c99fa12404" FOREIGN KEY ("id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_members"( "index", "id", @@ -114,27 +114,27 @@ export class premiumSinceAsDate1659921722863 implements MigrationInterface { "joined_by" FROM "members" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "members" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_members" RENAME TO "members" `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_bb2bf9386ac443afbbbf9f12d3" ON "members" ("id", "guild_id") `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` DROP INDEX "IDX_bb2bf9386ac443afbbbf9f12d3" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "members" RENAME TO "temporary_members" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "members" ( "index" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "id" varchar NOT NULL, @@ -152,7 +152,7 @@ export class premiumSinceAsDate1659921722863 implements MigrationInterface { CONSTRAINT "FK_28b53062261b996d9c99fa12404" FOREIGN KEY ("id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "members"( "index", "id", @@ -181,20 +181,20 @@ export class premiumSinceAsDate1659921722863 implements MigrationInterface { "joined_by" FROM "temporary_members" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_members" `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_bb2bf9386ac443afbbbf9f12d3" ON "members" ("id", "guild_id") `); - await queryRunner.query(` + await queryRunner.query(` DROP INDEX "IDX_bb2bf9386ac443afbbbf9f12d3" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "members" RENAME TO "temporary_members" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "members" ( "index" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "id" varchar NOT NULL, @@ -212,7 +212,7 @@ export class premiumSinceAsDate1659921722863 implements MigrationInterface { CONSTRAINT "FK_28b53062261b996d9c99fa12404" FOREIGN KEY ("id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "members"( "index", "id", @@ -241,12 +241,11 @@ export class premiumSinceAsDate1659921722863 implements MigrationInterface { "joined_by" FROM "temporary_members" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_members" `); - await queryRunner.query(` + await queryRunner.query(` CREATE UNIQUE INDEX "IDX_bb2bf9386ac443afbbbf9f12d3" ON "members" ("id", "guild_id") `); - } - + } } diff --git a/src/util/migrations/sqlite/1660130536131-updated-applications.ts b/src/util/migrations/sqlite/1660130536131-updated-applications.ts index b8cbcc33..bcb1c929 100644 --- a/src/util/migrations/sqlite/1660130536131-updated-applications.ts +++ b/src/util/migrations/sqlite/1660130536131-updated-applications.ts @@ -1,10 +1,10 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class updatedApplications1660130536131 implements MigrationInterface { - name = 'updatedApplications1660130536131' + name = "updatedApplications1660130536131"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` CREATE TABLE "temporary_applications" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -28,7 +28,7 @@ export class updatedApplications1660130536131 implements MigrationInterface { CONSTRAINT "FK_e57508958bf92b9d9d25231b5e8" FOREIGN KEY ("owner_id") REFERENCES "users" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_applications"( "id", "name", @@ -69,14 +69,14 @@ export class updatedApplications1660130536131 implements MigrationInterface { "guild_id" FROM "applications" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "applications" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_applications" RENAME TO "applications" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_applications" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -96,7 +96,7 @@ export class updatedApplications1660130536131 implements MigrationInterface { CONSTRAINT "FK_e57508958bf92b9d9d25231b5e8" FOREIGN KEY ("owner_id") REFERENCES "users" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_applications"( "id", "name", @@ -129,14 +129,14 @@ export class updatedApplications1660130536131 implements MigrationInterface { "team_id" FROM "applications" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "applications" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_applications" RENAME TO "applications" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_applications" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -171,7 +171,7 @@ export class updatedApplications1660130536131 implements MigrationInterface { CONSTRAINT "FK_e57508958bf92b9d9d25231b5e8" FOREIGN KEY ("owner_id") REFERENCES "users" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_applications"( "id", "name", @@ -204,14 +204,14 @@ export class updatedApplications1660130536131 implements MigrationInterface { "team_id" FROM "applications" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "applications" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_applications" RENAME TO "applications" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_applications" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -246,7 +246,7 @@ export class updatedApplications1660130536131 implements MigrationInterface { CONSTRAINT "FK_e57508958bf92b9d9d25231b5e8" FOREIGN KEY ("owner_id") REFERENCES "users" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_applications"( "id", "name", @@ -307,14 +307,14 @@ export class updatedApplications1660130536131 implements MigrationInterface { "bot_user_id" FROM "applications" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "applications" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_applications" RENAME TO "applications" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_applications" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -350,7 +350,7 @@ export class updatedApplications1660130536131 implements MigrationInterface { CONSTRAINT "FK_2ce5a55796fe4c2f77ece57a647" FOREIGN KEY ("bot_user_id") REFERENCES "users" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_applications"( "id", "name", @@ -411,21 +411,21 @@ export class updatedApplications1660130536131 implements MigrationInterface { "bot_user_id" FROM "applications" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "applications" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_applications" RENAME TO "applications" `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "applications" RENAME TO "temporary_applications" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "applications" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -460,7 +460,7 @@ export class updatedApplications1660130536131 implements MigrationInterface { CONSTRAINT "FK_e57508958bf92b9d9d25231b5e8" FOREIGN KEY ("owner_id") REFERENCES "users" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "applications"( "id", "name", @@ -521,14 +521,14 @@ export class updatedApplications1660130536131 implements MigrationInterface { "bot_user_id" FROM "temporary_applications" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_applications" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" RENAME TO "temporary_applications" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "applications" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -563,7 +563,7 @@ export class updatedApplications1660130536131 implements MigrationInterface { CONSTRAINT "FK_e57508958bf92b9d9d25231b5e8" FOREIGN KEY ("owner_id") REFERENCES "users" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "applications"( "id", "name", @@ -624,14 +624,14 @@ export class updatedApplications1660130536131 implements MigrationInterface { "bot_user_id" FROM "temporary_applications" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_applications" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" RENAME TO "temporary_applications" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "applications" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -651,7 +651,7 @@ export class updatedApplications1660130536131 implements MigrationInterface { CONSTRAINT "FK_e57508958bf92b9d9d25231b5e8" FOREIGN KEY ("owner_id") REFERENCES "users" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "applications"( "id", "name", @@ -684,14 +684,14 @@ export class updatedApplications1660130536131 implements MigrationInterface { "team_id" FROM "temporary_applications" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_applications" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" RENAME TO "temporary_applications" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "applications" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -715,7 +715,7 @@ export class updatedApplications1660130536131 implements MigrationInterface { CONSTRAINT "FK_e57508958bf92b9d9d25231b5e8" FOREIGN KEY ("owner_id") REFERENCES "users" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "applications"( "id", "name", @@ -748,14 +748,14 @@ export class updatedApplications1660130536131 implements MigrationInterface { "team_id" FROM "temporary_applications" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_applications" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "applications" RENAME TO "temporary_applications" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "applications" ( "id" varchar PRIMARY KEY NOT NULL, "name" varchar NOT NULL, @@ -780,7 +780,7 @@ export class updatedApplications1660130536131 implements MigrationInterface { CONSTRAINT "FK_e57508958bf92b9d9d25231b5e8" FOREIGN KEY ("owner_id") REFERENCES "users" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "applications"( "id", "name", @@ -821,9 +821,8 @@ export class updatedApplications1660130536131 implements MigrationInterface { "guild_id" FROM "temporary_applications" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_applications" `); - } - + } } diff --git a/src/util/migrations/sqlite/1660257576211-CodeCleanup1.ts b/src/util/migrations/sqlite/1660257576211-CodeCleanup1.ts index 5a61db0d..95410544 100644 --- a/src/util/migrations/sqlite/1660257576211-CodeCleanup1.ts +++ b/src/util/migrations/sqlite/1660257576211-CodeCleanup1.ts @@ -1,10 +1,10 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class CodeCleanup11660257576211 implements MigrationInterface { - name = 'CodeCleanup11660257576211' + name = "CodeCleanup11660257576211"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` CREATE TABLE "user_settings" ( "id" varchar PRIMARY KEY NOT NULL, "afk_timeout" integer, @@ -40,7 +40,7 @@ export class CodeCleanup11660257576211 implements MigrationInterface { "timezone_offset" integer ) `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_guilds" ( "id" varchar PRIMARY KEY NOT NULL, "afk_channel_id" varchar, @@ -90,7 +90,7 @@ export class CodeCleanup11660257576211 implements MigrationInterface { CONSTRAINT "FK_f591a66b8019d87b0fe6c12dad6" FOREIGN KEY ("afk_channel_id") REFERENCES "channels" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_guilds"( "id", "afk_channel_id", @@ -171,21 +171,21 @@ export class CodeCleanup11660257576211 implements MigrationInterface { "parent" FROM "guilds" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "guilds" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_guilds" RENAME TO "guilds" `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "guilds" RENAME TO "temporary_guilds" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "guilds" ( "id" varchar PRIMARY KEY NOT NULL, "afk_channel_id" varchar, @@ -234,7 +234,7 @@ export class CodeCleanup11660257576211 implements MigrationInterface { CONSTRAINT "FK_f591a66b8019d87b0fe6c12dad6" FOREIGN KEY ("afk_channel_id") REFERENCES "channels" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "guilds"( "id", "afk_channel_id", @@ -315,12 +315,11 @@ export class CodeCleanup11660257576211 implements MigrationInterface { "parent" FROM "temporary_guilds" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_guilds" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "user_settings" `); - } - + } } diff --git a/src/util/migrations/sqlite/1660257795259-CodeCleanup2.ts b/src/util/migrations/sqlite/1660257795259-CodeCleanup2.ts index 53698256..b21e190c 100644 --- a/src/util/migrations/sqlite/1660257795259-CodeCleanup2.ts +++ b/src/util/migrations/sqlite/1660257795259-CodeCleanup2.ts @@ -1,10 +1,10 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class CodeCleanup21660257795259 implements MigrationInterface { - name = 'CodeCleanup21660257795259' + name = "CodeCleanup21660257795259"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` CREATE TABLE "temporary_guilds" ( "id" varchar PRIMARY KEY NOT NULL, "afk_channel_id" varchar, @@ -54,7 +54,7 @@ export class CodeCleanup21660257795259 implements MigrationInterface { CONSTRAINT "FK_9d1d665379eefde7876a17afa99" FOREIGN KEY ("widget_channel_id") REFERENCES "channels" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_guilds"( "id", "afk_channel_id", @@ -137,14 +137,14 @@ export class CodeCleanup21660257795259 implements MigrationInterface { "premium_progress_bar_enabled" FROM "guilds" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "guilds" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_guilds" RENAME TO "guilds" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_guilds" ( "id" varchar PRIMARY KEY NOT NULL, "afk_channel_id" varchar, @@ -194,7 +194,7 @@ export class CodeCleanup21660257795259 implements MigrationInterface { CONSTRAINT "FK_9d1d665379eefde7876a17afa99" FOREIGN KEY ("widget_channel_id") REFERENCES "channels" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_guilds"( "id", "afk_channel_id", @@ -277,21 +277,21 @@ export class CodeCleanup21660257795259 implements MigrationInterface { "premium_progress_bar_enabled" FROM "guilds" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "guilds" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_guilds" RENAME TO "guilds" `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "guilds" RENAME TO "temporary_guilds" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "guilds" ( "id" varchar PRIMARY KEY NOT NULL, "afk_channel_id" varchar, @@ -341,7 +341,7 @@ export class CodeCleanup21660257795259 implements MigrationInterface { CONSTRAINT "FK_9d1d665379eefde7876a17afa99" FOREIGN KEY ("widget_channel_id") REFERENCES "channels" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "guilds"( "id", "afk_channel_id", @@ -424,14 +424,14 @@ export class CodeCleanup21660257795259 implements MigrationInterface { "premium_progress_bar_enabled" FROM "temporary_guilds" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_guilds" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "guilds" RENAME TO "temporary_guilds" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "guilds" ( "id" varchar PRIMARY KEY NOT NULL, "afk_channel_id" varchar, @@ -481,7 +481,7 @@ export class CodeCleanup21660257795259 implements MigrationInterface { CONSTRAINT "FK_9d1d665379eefde7876a17afa99" FOREIGN KEY ("widget_channel_id") REFERENCES "channels" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "guilds"( "id", "afk_channel_id", @@ -564,9 +564,8 @@ export class CodeCleanup21660257795259 implements MigrationInterface { "premium_progress_bar_enabled" FROM "temporary_guilds" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_guilds" `); - } - + } } diff --git a/src/util/migrations/sqlite/1660258351379-CodeCleanup3.ts b/src/util/migrations/sqlite/1660258351379-CodeCleanup3.ts index 13fba6dd..b19864fa 100644 --- a/src/util/migrations/sqlite/1660258351379-CodeCleanup3.ts +++ b/src/util/migrations/sqlite/1660258351379-CodeCleanup3.ts @@ -1,10 +1,10 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class CodeCleanup31660258351379 implements MigrationInterface { - name = 'CodeCleanup31660258351379' + name = "CodeCleanup31660258351379"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` CREATE TABLE "temporary_users" ( "id" varchar PRIMARY KEY NOT NULL, "username" varchar NOT NULL, @@ -39,7 +39,7 @@ export class CodeCleanup31660258351379 implements MigrationInterface { "notes" text NOT NULL ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_users"( "id", "username", @@ -106,21 +106,21 @@ export class CodeCleanup31660258351379 implements MigrationInterface { "notes" FROM "users" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "users" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_users" RENAME TO "users" `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "users" RENAME TO "temporary_users" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "users" ( "id" varchar PRIMARY KEY NOT NULL, "username" varchar NOT NULL, @@ -156,7 +156,7 @@ export class CodeCleanup31660258351379 implements MigrationInterface { "notes" text NOT NULL ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "users"( "id", "username", @@ -223,9 +223,8 @@ export class CodeCleanup31660258351379 implements MigrationInterface { "notes" FROM "temporary_users" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_users" `); - } - + } } diff --git a/src/util/migrations/sqlite/1660260672914-CodeCleanup4.ts b/src/util/migrations/sqlite/1660260672914-CodeCleanup4.ts index 33f4df03..ed284bc8 100644 --- a/src/util/migrations/sqlite/1660260672914-CodeCleanup4.ts +++ b/src/util/migrations/sqlite/1660260672914-CodeCleanup4.ts @@ -1,10 +1,10 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class CodeCleanup41660260672914 implements MigrationInterface { - name = 'CodeCleanup41660260672914' + name = "CodeCleanup41660260672914"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` CREATE TABLE "temporary_users" ( "id" varchar PRIMARY KEY NOT NULL, "username" varchar NOT NULL, @@ -41,7 +41,7 @@ export class CodeCleanup41660260672914 implements MigrationInterface { CONSTRAINT "UQ_b1dd13b6ed980004a795ca184a6" UNIQUE ("settingsId") ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_users"( "id", "username", @@ -108,14 +108,14 @@ export class CodeCleanup41660260672914 implements MigrationInterface { "notes" FROM "users" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "users" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_users" RENAME TO "users" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_users" ( "id" varchar PRIMARY KEY NOT NULL, "username" varchar NOT NULL, @@ -153,7 +153,7 @@ export class CodeCleanup41660260672914 implements MigrationInterface { CONSTRAINT "FK_76ba283779c8441fd5ff819c8cf" FOREIGN KEY ("settingsId") REFERENCES "user_settings" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_users"( "id", "username", @@ -222,21 +222,21 @@ export class CodeCleanup41660260672914 implements MigrationInterface { "settingsId" FROM "users" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "users" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_users" RENAME TO "users" `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "users" RENAME TO "temporary_users" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "users" ( "id" varchar PRIMARY KEY NOT NULL, "username" varchar NOT NULL, @@ -273,7 +273,7 @@ export class CodeCleanup41660260672914 implements MigrationInterface { CONSTRAINT "UQ_b1dd13b6ed980004a795ca184a6" UNIQUE ("settingsId") ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "users"( "id", "username", @@ -342,14 +342,14 @@ export class CodeCleanup41660260672914 implements MigrationInterface { "settingsId" FROM "temporary_users" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_users" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "users" RENAME TO "temporary_users" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "users" ( "id" varchar PRIMARY KEY NOT NULL, "username" varchar NOT NULL, @@ -384,7 +384,7 @@ export class CodeCleanup41660260672914 implements MigrationInterface { "notes" text NOT NULL ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "users"( "id", "username", @@ -451,9 +451,8 @@ export class CodeCleanup41660260672914 implements MigrationInterface { "notes" FROM "temporary_users" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_users" `); - } - + } } diff --git a/src/util/migrations/sqlite/1660416010862-InvitersAreDeletable.ts b/src/util/migrations/sqlite/1660416010862-InvitersAreDeletable.ts index 9b29e119..a05082c6 100644 --- a/src/util/migrations/sqlite/1660416010862-InvitersAreDeletable.ts +++ b/src/util/migrations/sqlite/1660416010862-InvitersAreDeletable.ts @@ -1,10 +1,10 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class InvitersAreDeletable1660416010862 implements MigrationInterface { - name = 'InvitersAreDeletable1660416010862' + name = "InvitersAreDeletable1660416010862"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` CREATE TABLE "temporary_invites" ( "code" varchar PRIMARY KEY NOT NULL, "temporary" boolean NOT NULL, @@ -24,7 +24,7 @@ export class InvitersAreDeletable1660416010862 implements MigrationInterface { CONSTRAINT "FK_3f4939aa1461e8af57fea3fb05d" FOREIGN KEY ("guild_id") REFERENCES "guilds" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_invites"( "code", "temporary", @@ -55,14 +55,14 @@ export class InvitersAreDeletable1660416010862 implements MigrationInterface { "vanity_url" FROM "invites" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "invites" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_invites" RENAME TO "invites" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "temporary_invites" ( "code" varchar PRIMARY KEY NOT NULL, "temporary" boolean NOT NULL, @@ -83,7 +83,7 @@ export class InvitersAreDeletable1660416010862 implements MigrationInterface { CONSTRAINT "FK_15c35422032e0b22b4ada95f48f" FOREIGN KEY ("inviter_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_invites"( "code", "temporary", @@ -114,21 +114,21 @@ export class InvitersAreDeletable1660416010862 implements MigrationInterface { "vanity_url" FROM "invites" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "invites" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_invites" RENAME TO "invites" `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "invites" RENAME TO "temporary_invites" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "invites" ( "code" varchar PRIMARY KEY NOT NULL, "temporary" boolean NOT NULL, @@ -148,7 +148,7 @@ export class InvitersAreDeletable1660416010862 implements MigrationInterface { CONSTRAINT "FK_3f4939aa1461e8af57fea3fb05d" FOREIGN KEY ("guild_id") REFERENCES "guilds" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "invites"( "code", "temporary", @@ -179,14 +179,14 @@ export class InvitersAreDeletable1660416010862 implements MigrationInterface { "vanity_url" FROM "temporary_invites" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_invites" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "invites" RENAME TO "temporary_invites" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "invites" ( "code" varchar PRIMARY KEY NOT NULL, "temporary" boolean NOT NULL, @@ -207,7 +207,7 @@ export class InvitersAreDeletable1660416010862 implements MigrationInterface { CONSTRAINT "FK_3f4939aa1461e8af57fea3fb05d" FOREIGN KEY ("guild_id") REFERENCES "guilds" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "invites"( "code", "temporary", @@ -238,9 +238,8 @@ export class InvitersAreDeletable1660416010862 implements MigrationInterface { "vanity_url" FROM "temporary_invites" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_invites" `); - } - + } } diff --git a/src/util/migrations/sqlite/1660538628956-sync_migrations.ts b/src/util/migrations/sqlite/1660538628956-sync_migrations.ts index 9cdc064f..95c59d28 100644 --- a/src/util/migrations/sqlite/1660538628956-sync_migrations.ts +++ b/src/util/migrations/sqlite/1660538628956-sync_migrations.ts @@ -1,10 +1,10 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class syncMigrations1660538628956 implements MigrationInterface { - name = 'syncMigrations1660538628956' + name = "syncMigrations1660538628956"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` CREATE TABLE "temporary_channels" ( "id" varchar PRIMARY KEY NOT NULL, "created_at" datetime NOT NULL, @@ -33,7 +33,7 @@ export class syncMigrations1660538628956 implements MigrationInterface { CONSTRAINT "FK_c253dafe5f3a03ec00cd8fb4581" FOREIGN KEY ("guild_id") REFERENCES "guilds" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_channels"( "id", "created_at", @@ -78,21 +78,21 @@ export class syncMigrations1660538628956 implements MigrationInterface { "retention_policy_id" FROM "channels" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "channels" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_channels" RENAME TO "channels" `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "channels" RENAME TO "temporary_channels" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "channels" ( "id" varchar PRIMARY KEY NOT NULL, "created_at" datetime NOT NULL, @@ -119,7 +119,7 @@ export class syncMigrations1660538628956 implements MigrationInterface { CONSTRAINT "FK_c253dafe5f3a03ec00cd8fb4581" FOREIGN KEY ("guild_id") REFERENCES "guilds" ("id") ON DELETE CASCADE ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "channels"( "id", "created_at", @@ -164,9 +164,8 @@ export class syncMigrations1660538628956 implements MigrationInterface { "retention_policy_id" FROM "temporary_channels" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_channels" `); - } - + } } diff --git a/src/util/migrations/sqlite/1660549233583-fix_nullables.ts b/src/util/migrations/sqlite/1660549233583-fix_nullables.ts index 68f650c7..fa60bdc1 100644 --- a/src/util/migrations/sqlite/1660549233583-fix_nullables.ts +++ b/src/util/migrations/sqlite/1660549233583-fix_nullables.ts @@ -1,10 +1,10 @@ import { MigrationInterface, QueryRunner } from "typeorm"; export class fixNullables1660549233583 implements MigrationInterface { - name = 'fixNullables1660549233583' + name = "fixNullables1660549233583"; - public async up(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async up(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` CREATE TABLE "temporary_users" ( "id" varchar PRIMARY KEY NOT NULL, "username" varchar NOT NULL, @@ -42,7 +42,7 @@ export class fixNullables1660549233583 implements MigrationInterface { CONSTRAINT "FK_76ba283779c8441fd5ff819c8cf" FOREIGN KEY ("settingsId") REFERENCES "user_settings" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "temporary_users"( "id", "username", @@ -111,21 +111,21 @@ export class fixNullables1660549233583 implements MigrationInterface { "settingsId" FROM "users" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "users" `); - await queryRunner.query(` + await queryRunner.query(` ALTER TABLE "temporary_users" RENAME TO "users" `); - } + } - public async down(queryRunner: QueryRunner): Promise<void> { - await queryRunner.query(` + public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(` ALTER TABLE "users" RENAME TO "temporary_users" `); - await queryRunner.query(` + await queryRunner.query(` CREATE TABLE "users" ( "id" varchar PRIMARY KEY NOT NULL, "username" varchar NOT NULL, @@ -163,7 +163,7 @@ export class fixNullables1660549233583 implements MigrationInterface { CONSTRAINT "FK_76ba283779c8441fd5ff819c8cf" FOREIGN KEY ("settingsId") REFERENCES "user_settings" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION ) `); - await queryRunner.query(` + await queryRunner.query(` INSERT INTO "users"( "id", "username", @@ -232,9 +232,8 @@ export class fixNullables1660549233583 implements MigrationInterface { "settingsId" FROM "temporary_users" `); - await queryRunner.query(` + await queryRunner.query(` DROP TABLE "temporary_users" `); - } - + } } diff --git a/src/util/schemas/ActivitySchema.ts b/src/util/schemas/ActivitySchema.ts index e18f66c8..d94557ea 100644 --- a/src/util/schemas/ActivitySchema.ts +++ b/src/util/schemas/ActivitySchema.ts @@ -11,7 +11,7 @@ export const ActivitySchema = { $created_at: Date, $timestamps: { $start: Number, - $end: Number, + $end: Number }, $application_id: String, $details: String, @@ -19,28 +19,28 @@ export const ActivitySchema = { $emoji: { $name: String, $id: String, - $animated: Boolean, + $animated: Boolean }, $party: { $id: String, - $size: [Number, Number], + $size: [Number, Number] }, $assets: { $large_image: String, $large_text: String, $small_image: String, - $small_text: String, + $small_text: String }, $secrets: { $join: String, $spectate: String, - $match: String, + $match: String }, $instance: Boolean, - $flags: String, - }, + $flags: String + } ], - $since: Number, // unix time (in milliseconds) of when the client went idle, or null if the client is not idle + $since: Number // unix time (in milliseconds) of when the client went idle, or null if the client is not idle }; export interface ActivitySchema { diff --git a/src/util/schemas/BanCreateSchema.ts b/src/util/schemas/BanCreateSchema.ts index 64b02943..834577dc 100644 --- a/src/util/schemas/BanCreateSchema.ts +++ b/src/util/schemas/BanCreateSchema.ts @@ -1,4 +1,3 @@ - export interface BanCreateSchema { delete_message_days?: string; reason?: string; diff --git a/src/util/schemas/BanModeratorSchema.ts b/src/util/schemas/BanModeratorSchema.ts index b497d319..afb76433 100644 --- a/src/util/schemas/BanModeratorSchema.ts +++ b/src/util/schemas/BanModeratorSchema.ts @@ -1,4 +1,3 @@ - export interface BanModeratorSchema { id: string; user_id: string; diff --git a/src/util/schemas/BanRegistrySchema.ts b/src/util/schemas/BanRegistrySchema.ts index 661f934f..501f94dc 100644 --- a/src/util/schemas/BanRegistrySchema.ts +++ b/src/util/schemas/BanRegistrySchema.ts @@ -1,4 +1,3 @@ - export interface BanRegistrySchema { id: string; user_id: string; diff --git a/src/util/schemas/BulkDeleteSchema.ts b/src/util/schemas/BulkDeleteSchema.ts index 26f88374..bfc4df65 100644 --- a/src/util/schemas/BulkDeleteSchema.ts +++ b/src/util/schemas/BulkDeleteSchema.ts @@ -1,4 +1,3 @@ - export interface BulkDeleteSchema { messages: string[]; } diff --git a/src/util/schemas/ChannelModifySchema.ts b/src/util/schemas/ChannelModifySchema.ts index 3cfcf7d2..f5babef0 100644 --- a/src/util/schemas/ChannelModifySchema.ts +++ b/src/util/schemas/ChannelModifySchema.ts @@ -1,6 +1,5 @@ import { ChannelPermissionOverwriteType, ChannelType } from ".."; - export interface ChannelModifySchema { /** * @maxLength 100 @@ -26,4 +25,4 @@ export interface ChannelModifySchema { default_auto_archive_duration?: number; flags?: number; default_thread_rate_limit_per_user?: number; -} \ No newline at end of file +} diff --git a/src/util/schemas/ChannelPermissionOverwriteSchema.ts b/src/util/schemas/ChannelPermissionOverwriteSchema.ts index fe9ba860..e8bc13bb 100644 --- a/src/util/schemas/ChannelPermissionOverwriteSchema.ts +++ b/src/util/schemas/ChannelPermissionOverwriteSchema.ts @@ -2,4 +2,4 @@ import { ChannelPermissionOverwrite } from "@fosscord/util"; // TODO: Only permissions your bot has in the guild or channel can be allowed/denied (unless your bot has a MANAGE_ROLES overwrite in the channel) -export interface ChannelPermissionOverwriteSchema extends ChannelPermissionOverwrite { } +export interface ChannelPermissionOverwriteSchema extends ChannelPermissionOverwrite {} diff --git a/src/util/schemas/ChannelReorderSchema.ts b/src/util/schemas/ChannelReorderSchema.ts index 3715f59e..95c2eba9 100644 --- a/src/util/schemas/ChannelReorderSchema.ts +++ b/src/util/schemas/ChannelReorderSchema.ts @@ -1 +1 @@ -export type ChannelReorderSchema = { id: string; position?: number; lock_permissions?: boolean; parent_id?: string }[]; \ No newline at end of file +export type ChannelReorderSchema = { id: string; position?: number; lock_permissions?: boolean; parent_id?: string }[]; diff --git a/src/util/schemas/DmChannelCreateSchema.ts b/src/util/schemas/DmChannelCreateSchema.ts index d5afc6d7..1b0fe86d 100644 --- a/src/util/schemas/DmChannelCreateSchema.ts +++ b/src/util/schemas/DmChannelCreateSchema.ts @@ -1,4 +1,3 @@ - export interface DmChannelCreateSchema { name?: string; recipients: string[]; diff --git a/src/util/schemas/EmojiCreateSchema.ts b/src/util/schemas/EmojiCreateSchema.ts index d50c419c..34084713 100644 --- a/src/util/schemas/EmojiCreateSchema.ts +++ b/src/util/schemas/EmojiCreateSchema.ts @@ -1,4 +1,3 @@ - export interface EmojiCreateSchema { name?: string; image: string; diff --git a/src/util/schemas/EmojiModifySchema.ts b/src/util/schemas/EmojiModifySchema.ts index 5529dbd5..05d2d395 100644 --- a/src/util/schemas/EmojiModifySchema.ts +++ b/src/util/schemas/EmojiModifySchema.ts @@ -1,4 +1,3 @@ - export interface EmojiModifySchema { name?: string; roles?: string[]; diff --git a/src/util/schemas/GuildTemplateCreateSchema.ts b/src/util/schemas/GuildTemplateCreateSchema.ts index 1579001e..59db8428 100644 --- a/src/util/schemas/GuildTemplateCreateSchema.ts +++ b/src/util/schemas/GuildTemplateCreateSchema.ts @@ -1,4 +1,3 @@ - export interface GuildTemplateCreateSchema { name: string; avatar?: string | null; diff --git a/src/util/schemas/GuildUpdateWelcomeScreenSchema.ts b/src/util/schemas/GuildUpdateWelcomeScreenSchema.ts index b1e36920..c8b8ba4e 100644 --- a/src/util/schemas/GuildUpdateWelcomeScreenSchema.ts +++ b/src/util/schemas/GuildUpdateWelcomeScreenSchema.ts @@ -1,4 +1,3 @@ - export interface GuildUpdateWelcomeScreenSchema { welcome_channels?: { channel_id: string; diff --git a/src/util/schemas/IdentifySchema.ts b/src/util/schemas/IdentifySchema.ts index f3d60fb3..bb5ae0c8 100644 --- a/src/util/schemas/IdentifySchema.ts +++ b/src/util/schemas/IdentifySchema.ts @@ -41,10 +41,10 @@ export const IdentifySchema = { $highest_last_message_id: String, $read_state_version: Number, $user_guild_settings_version: Number, - $user_settings_version: undefined, + $user_settings_version: undefined }, $v: Number, - $version: Number, + $version: Number }; export interface IdentifySchema { diff --git a/src/util/schemas/InviteCreateSchema.ts b/src/util/schemas/InviteCreateSchema.ts index 7f6af338..cac11147 100644 --- a/src/util/schemas/InviteCreateSchema.ts +++ b/src/util/schemas/InviteCreateSchema.ts @@ -1,4 +1,3 @@ - export interface InviteCreateSchema { target_user_id?: string; target_type?: string; diff --git a/src/util/schemas/LazyRequestSchema.ts b/src/util/schemas/LazyRequestSchema.ts index 1fe658bb..fbed5c5b 100644 --- a/src/util/schemas/LazyRequestSchema.ts +++ b/src/util/schemas/LazyRequestSchema.ts @@ -15,5 +15,5 @@ export const LazyRequest = { $typing: Boolean, $threads: Boolean, $members: [] as any[], - $thread_member_lists: [] as any[], + $thread_member_lists: [] as any[] }; diff --git a/src/util/schemas/LoginSchema.ts b/src/util/schemas/LoginSchema.ts index 358019a8..dc889d94 100644 --- a/src/util/schemas/LoginSchema.ts +++ b/src/util/schemas/LoginSchema.ts @@ -1,4 +1,3 @@ - export interface LoginSchema { login: string; password: string; diff --git a/src/util/schemas/MemberChangeSchema.ts b/src/util/schemas/MemberChangeSchema.ts index a75c0ea0..db434538 100644 --- a/src/util/schemas/MemberChangeSchema.ts +++ b/src/util/schemas/MemberChangeSchema.ts @@ -1,4 +1,3 @@ - export interface MemberChangeSchema { roles?: string[]; } diff --git a/src/util/schemas/MemberNickChangeSchema.ts b/src/util/schemas/MemberNickChangeSchema.ts index e6a6a007..d863038c 100644 --- a/src/util/schemas/MemberNickChangeSchema.ts +++ b/src/util/schemas/MemberNickChangeSchema.ts @@ -1,4 +1,3 @@ - export interface MemberNickChangeSchema { nick: string; } diff --git a/src/util/schemas/MessageCreateSchema.ts b/src/util/schemas/MessageCreateSchema.ts index 7b1cc7b9..bf3470bb 100644 --- a/src/util/schemas/MessageCreateSchema.ts +++ b/src/util/schemas/MessageCreateSchema.ts @@ -1,6 +1,5 @@ import { Embed } from "@fosscord/util"; - export interface MessageCreateSchema { type?: number; content?: string; diff --git a/src/util/schemas/MfaCodesSchema.ts b/src/util/schemas/MfaCodesSchema.ts index 53230841..ac05b9a4 100644 --- a/src/util/schemas/MfaCodesSchema.ts +++ b/src/util/schemas/MfaCodesSchema.ts @@ -1,4 +1,3 @@ - export interface MfaCodesSchema { password: string; regenerate?: boolean; diff --git a/src/util/schemas/ModifyGuildStickerSchema.ts b/src/util/schemas/ModifyGuildStickerSchema.ts index 6f24e4ce..159cc44f 100644 --- a/src/util/schemas/ModifyGuildStickerSchema.ts +++ b/src/util/schemas/ModifyGuildStickerSchema.ts @@ -1,4 +1,3 @@ - export interface ModifyGuildStickerSchema { /** * @minLength 2 diff --git a/src/util/schemas/PruneSchema.ts b/src/util/schemas/PruneSchema.ts index eebac763..bea5e2b4 100644 --- a/src/util/schemas/PruneSchema.ts +++ b/src/util/schemas/PruneSchema.ts @@ -1,4 +1,3 @@ - export interface PruneSchema { /** * @min 0 diff --git a/src/util/schemas/PurgeSchema.ts b/src/util/schemas/PurgeSchema.ts index 0eeef6f2..f5ab0a20 100644 --- a/src/util/schemas/PurgeSchema.ts +++ b/src/util/schemas/PurgeSchema.ts @@ -1,4 +1,3 @@ - export interface PurgeSchema { before: string; after: string; diff --git a/src/util/schemas/RegisterSchema.ts b/src/util/schemas/RegisterSchema.ts index e53330d2..9bbd9db5 100644 --- a/src/util/schemas/RegisterSchema.ts +++ b/src/util/schemas/RegisterSchema.ts @@ -1,4 +1,3 @@ - export interface RegisterSchema { /** * @minLength 2 diff --git a/src/util/schemas/RelationshipPostSchema.ts b/src/util/schemas/RelationshipPostSchema.ts index 40093700..774c67f6 100644 --- a/src/util/schemas/RelationshipPostSchema.ts +++ b/src/util/schemas/RelationshipPostSchema.ts @@ -1,4 +1,3 @@ - export interface RelationshipPostSchema { discriminator: string; username: string; diff --git a/src/util/schemas/RelationshipPutSchema.ts b/src/util/schemas/RelationshipPutSchema.ts index f46966e0..0a7f9720 100644 --- a/src/util/schemas/RelationshipPutSchema.ts +++ b/src/util/schemas/RelationshipPutSchema.ts @@ -1,6 +1,5 @@ import { RelationshipType } from "@fosscord/util"; - export interface RelationshipPutSchema { type?: RelationshipType; } diff --git a/src/util/schemas/RoleModifySchema.ts b/src/util/schemas/RoleModifySchema.ts index d08a5022..f3f4a20e 100644 --- a/src/util/schemas/RoleModifySchema.ts +++ b/src/util/schemas/RoleModifySchema.ts @@ -1,4 +1,3 @@ - export interface RoleModifySchema { name?: string; permissions?: string; diff --git a/src/util/schemas/RolePositionUpdateSchema.ts b/src/util/schemas/RolePositionUpdateSchema.ts index 1019d504..993d1ae0 100644 --- a/src/util/schemas/RolePositionUpdateSchema.ts +++ b/src/util/schemas/RolePositionUpdateSchema.ts @@ -1,4 +1,4 @@ export type RolePositionUpdateSchema = { id: string; position: number; -}[]; \ No newline at end of file +}[]; diff --git a/src/util/schemas/TemplateCreateSchema.ts b/src/util/schemas/TemplateCreateSchema.ts index 72c19f68..160934f5 100644 --- a/src/util/schemas/TemplateCreateSchema.ts +++ b/src/util/schemas/TemplateCreateSchema.ts @@ -1,4 +1,3 @@ - export interface TemplateCreateSchema { name: string; description?: string; diff --git a/src/util/schemas/TemplateModifySchema.ts b/src/util/schemas/TemplateModifySchema.ts index 2231a1d2..f9c9d14b 100644 --- a/src/util/schemas/TemplateModifySchema.ts +++ b/src/util/schemas/TemplateModifySchema.ts @@ -1,4 +1,3 @@ - export interface TemplateModifySchema { name: string; description?: string; diff --git a/src/util/schemas/TotpDisableSchema.ts b/src/util/schemas/TotpDisableSchema.ts index b73db64e..51446e1c 100644 --- a/src/util/schemas/TotpDisableSchema.ts +++ b/src/util/schemas/TotpDisableSchema.ts @@ -1,4 +1,3 @@ - export interface TotpDisableSchema { code: string; } diff --git a/src/util/schemas/TotpEnableSchema.ts b/src/util/schemas/TotpEnableSchema.ts index 44d9ebac..4e3551d9 100644 --- a/src/util/schemas/TotpEnableSchema.ts +++ b/src/util/schemas/TotpEnableSchema.ts @@ -1,4 +1,3 @@ - export interface TotpEnableSchema { password: string; code?: string; diff --git a/src/util/schemas/TotpSchema.ts b/src/util/schemas/TotpSchema.ts index fe54735e..941a92ec 100644 --- a/src/util/schemas/TotpSchema.ts +++ b/src/util/schemas/TotpSchema.ts @@ -1,4 +1,3 @@ - export interface TotpSchema { code: string; ticket: string; diff --git a/src/util/schemas/UserModifySchema.ts b/src/util/schemas/UserModifySchema.ts index 659f5841..d69f83f4 100644 --- a/src/util/schemas/UserModifySchema.ts +++ b/src/util/schemas/UserModifySchema.ts @@ -1,4 +1,3 @@ - export interface UserModifySchema { /** * @minLength 1 diff --git a/src/util/schemas/UserSettingsSchema.ts b/src/util/schemas/UserSettingsSchema.ts index b497dff2..eb9b316d 100644 --- a/src/util/schemas/UserSettingsSchema.ts +++ b/src/util/schemas/UserSettingsSchema.ts @@ -1,4 +1,3 @@ import { UserSettings } from "@fosscord/util"; - -export interface UserSettingsSchema extends Partial<UserSettings> { } +export interface UserSettingsSchema extends Partial<UserSettings> {} diff --git a/src/util/schemas/VanityUrlSchema.ts b/src/util/schemas/VanityUrlSchema.ts index de32695a..4dd9b9da 100644 --- a/src/util/schemas/VanityUrlSchema.ts +++ b/src/util/schemas/VanityUrlSchema.ts @@ -1,4 +1,3 @@ - export interface VanityUrlSchema { /** * @minLength 1 diff --git a/src/util/schemas/VoiceStateUpdateSchema.ts b/src/util/schemas/VoiceStateUpdateSchema.ts index 02bb141b..ea286b1a 100644 --- a/src/util/schemas/VoiceStateUpdateSchema.ts +++ b/src/util/schemas/VoiceStateUpdateSchema.ts @@ -3,7 +3,7 @@ export const VoiceStateUpdateSchema = { $channel_id: String, self_mute: Boolean, self_deaf: Boolean, - self_video: Boolean, + self_video: Boolean }; //TODO need more testing when community guild and voice stage channel are working @@ -15,4 +15,4 @@ export interface VoiceStateUpdateSchema { self_mute?: boolean; self_deaf?: boolean; self_video?: boolean; -} \ No newline at end of file +} diff --git a/src/util/schemas/WidgetModifySchema.ts b/src/util/schemas/WidgetModifySchema.ts index 390efc30..26d4504f 100644 --- a/src/util/schemas/WidgetModifySchema.ts +++ b/src/util/schemas/WidgetModifySchema.ts @@ -1,4 +1,3 @@ - export interface WidgetModifySchema { enabled: boolean; // whether the widget is enabled channel_id: string; // the widget channel id diff --git a/src/util/util/ApiError.ts b/src/util/util/ApiError.ts index f1a9b4f6..c133e6e7 100644 --- a/src/util/util/ApiError.ts +++ b/src/util/util/ApiError.ts @@ -9,8 +9,7 @@ export class ApiError extends Error { } withDefaultParams(): ApiError { - if (this.defaultParams) - return new ApiError(applyParamsToString(this.message, this.defaultParams), this.code, this.httpStatus); + if (this.defaultParams) return new ApiError(applyParamsToString(this.message, this.defaultParams), this.code, this.httpStatus); return this; } diff --git a/src/util/util/AutoUpdate.ts b/src/util/util/AutoUpdate.ts index 7d020106..08418040 100644 --- a/src/util/util/AutoUpdate.ts +++ b/src/util/util/AutoUpdate.ts @@ -1,12 +1,12 @@ -import fetch from "node-fetch"; -import ProxyAgent from 'proxy-agent'; -import readline from "readline"; import fs from "fs/promises"; +import fetch from "node-fetch"; import path from "path"; +import ProxyAgent from "proxy-agent"; +import readline from "readline"; const rl = readline.createInterface({ input: process.stdin, - output: process.stdout, + output: process.stdout }); export function enableAutoUpdate(opts: { diff --git a/src/util/util/BitField.ts b/src/util/util/BitField.ts index 9bdbf6d7..306bfb32 100644 --- a/src/util/util/BitField.ts +++ b/src/util/util/BitField.ts @@ -140,7 +140,7 @@ export class BitField { if (typeof bit === "string" && typeof FLAGS[bit] !== "undefined") return FLAGS[bit]; if (bit === "0") return BigInt(0); //special case: 0 if (typeof bit === "string") return BigInt(bit); //last ditch effort... - if(/--debug|--inspect/.test(process.execArgv.join(' '))) debugger; //if you're here, we have an invalid bitfield... if bit is 0, thats fine, I guess... + if (/--debug|--inspect/.test(process.execArgv.join(" "))) debugger; //if you're here, we have an invalid bitfield... if bit is 0, thats fine, I guess... throw new RangeError("BITFIELD_INVALID: " + bit); } } diff --git a/src/util/util/Categories.ts b/src/util/util/Categories.ts index a3c69da7..cd706a8a 100644 --- a/src/util/util/Categories.ts +++ b/src/util/util/Categories.ts @@ -1 +1 @@ -//TODO: populate default discord categories + init, get and set methods \ No newline at end of file +//TODO: populate default discord categories + init, get and set methods diff --git a/src/util/util/Config.ts b/src/util/util/Config.ts index e0fb2a81..6d43b24c 100644 --- a/src/util/util/Config.ts +++ b/src/util/util/Config.ts @@ -1,7 +1,7 @@ -import { ConfigEntity } from "../entities/Config"; import fs from "fs"; -import { ConfigValue } from "../config"; import { OrmUtils } from "."; +import { ConfigValue } from "../config"; +import { ConfigEntity } from "../entities/Config"; // TODO: yaml instead of json const overridePath = process.env.CONFIG_PATH ?? ""; @@ -15,27 +15,28 @@ let pairs: ConfigEntity[]; export const Config = { init: async function init() { if (config) return config; - console.log('[Config] Loading configuration...') + console.log("[Config] Loading configuration..."); pairs = await ConfigEntity.find(); config = pairsToConfig(pairs); //config = (config || {}).merge(new ConfigValue()); - config = OrmUtils.mergeDeep(new ConfigValue(), config) + config = OrmUtils.mergeDeep(new ConfigValue(), config); - if(process.env.CONFIG_PATH) + if (process.env.CONFIG_PATH) try { const overrideConfig = JSON.parse(fs.readFileSync(overridePath, { encoding: "utf8" })); config = overrideConfig.merge(config); } catch (error) { fs.writeFileSync(overridePath, JSON.stringify(config, null, 4)); } - return this.set(config); }, get: function get() { - if(!config) { - if(/--debug|--inspect/.test(process.execArgv.join(' '))) - console.log("Oops.. trying to get config without config existing... Returning defaults... (Is the database still initialising?)"); + if (!config) { + if (/--debug|--inspect/.test(process.execArgv.join(" "))) + console.log( + "Oops.. trying to get config without config existing... Returning defaults... (Is the database still initialising?)" + ); return new ConfigValue(); } return config; @@ -45,7 +46,7 @@ export const Config = { config = val.merge(config); return applyConfig(config); - }, + } }; function applyConfig(val: ConfigValue) { @@ -60,9 +61,8 @@ function applyConfig(val: ConfigValue) { pair.value = obj; return pair.save(); } - if(process.env.CONFIG_PATH) { - if(/--debug|--inspect/.test(process.execArgv.join(' '))) - console.log(`Writing config: ${process.env.CONFIG_PATH}`) + if (process.env.CONFIG_PATH) { + if (/--debug|--inspect/.test(process.execArgv.join(" "))) console.log(`Writing config: ${process.env.CONFIG_PATH}`); fs.writeFileSync(overridePath, JSON.stringify(val, null, 4)); } diff --git a/src/util/util/Constants.ts b/src/util/util/Constants.ts index a5d3fcd2..f7aff26a 100644 --- a/src/util/util/Constants.ts +++ b/src/util/util/Constants.ts @@ -6,7 +6,7 @@ export const WSCodes = { 4010: "SHARDING_INVALID", 4011: "SHARDING_REQUIRED", 4013: "INVALID_INTENTS", - 4014: "DISALLOWED_INTENTS", + 4014: "DISALLOWED_INTENTS" }; /** @@ -31,7 +31,7 @@ export const WsStatus = { DISCONNECTED: 5, WAITING_FOR_GUILDS: 6, IDENTIFYING: 7, - RESUMING: 8, + RESUMING: 8 }; /** @@ -48,7 +48,7 @@ export const VoiceStatus = { CONNECTING: 1, AUTHENTICATING: 2, RECONNECTING: 3, - DISCONNECTED: 4, + DISCONNECTED: 4 }; export const OPCodes = { @@ -63,7 +63,7 @@ export const OPCodes = { REQUEST_GUILD_MEMBERS: 8, INVALID_SESSION: 9, HELLO: 10, - HEARTBEAT_ACK: 11, + HEARTBEAT_ACK: 11 }; export const VoiceOPCodes = { @@ -75,7 +75,7 @@ export const VoiceOPCodes = { SPEAKING: 5, HELLO: 8, CLIENT_CONNECT: 12, - CLIENT_DISCONNECT: 13, + CLIENT_DISCONNECT: 13 }; export const Events = { @@ -133,7 +133,7 @@ export const Events = { SHARD_READY: "shardReady", SHARD_RESUME: "shardResume", INVALIDATED: "invalidated", - RAW: "raw", + RAW: "raw" }; export const ShardEvents = { @@ -142,7 +142,7 @@ export const ShardEvents = { INVALID_SESSION: "invalidSession", READY: "ready", RESUMED: "resumed", - ALL_READY: "allReady", + ALL_READY: "allReady" }; /** @@ -234,7 +234,7 @@ export const WSEvents = keyMirror([ "TYPING_START", "VOICE_STATE_UPDATE", "VOICE_SERVER_UPDATE", - "WEBHOOKS_UPDATE", + "WEBHOOKS_UPDATE" ]); /** @@ -277,7 +277,7 @@ export const MessageTypes = [ null, null, null, - "REPLY", + "REPLY" ]; /** @@ -286,9 +286,7 @@ export const MessageTypes = [ * * REPLY * @typedef {string} SystemMessageType */ -export const SystemMessageTypes = MessageTypes.filter( - (type: string | null) => type && type !== "DEFAULT" && type !== "REPLY" -); +export const SystemMessageTypes = MessageTypes.filter((type: string | null) => type && type !== "DEFAULT" && type !== "REPLY"); /** * <info>Bots cannot set a `CUSTOM_STATUS`, it is only for custom statuses received from users</info> @@ -310,12 +308,12 @@ export const ChannelTypes = { GROUP: 3, CATEGORY: 4, NEWS: 5, - STORE: 6, + STORE: 6 }; export const ClientApplicationAssetTypes = { SMALL: 1, - BIG: 2, + BIG: 2 }; export const Colors = { @@ -347,7 +345,7 @@ export const Colors = { BLURPLE: 0x7289da, GREYPLE: 0x99aab5, DARK_BUT_NOT_BLACK: 0x2c2f33, - NOT_QUITE_BLACK: 0x23272a, + NOT_QUITE_BLACK: 0x23272a }; /** @@ -556,14 +554,8 @@ export const DiscordApiErrors = { UNKNOWN_GUILD_SCHEDULED_EVENT_USER: new ApiError("Unknown Guild Scheduled Event User", 10071), BOT_PROHIBITED_ENDPOINT: new ApiError("Bots cannot use this endpoint", 20001), BOT_ONLY_ENDPOINT: new ApiError("Only bots can use this endpoint", 20002), - EXPLICIT_CONTENT_CANNOT_BE_SENT_TO_RECIPIENT: new ApiError( - "Explicit content cannot be sent to the desired recipient(s)", - 20009 - ), - ACTION_NOT_AUTHORIZED_ON_APPLICATION: new ApiError( - "You are not authorized to perform this action on this application", - 20012 - ), + EXPLICIT_CONTENT_CANNOT_BE_SENT_TO_RECIPIENT: new ApiError("Explicit content cannot be sent to the desired recipient(s)", 20009), + ACTION_NOT_AUTHORIZED_ON_APPLICATION: new ApiError("You are not authorized to perform this action on this application", 20012), SLOWMODE_RATE_LIMIT: new ApiError("This action cannot be performed due to slowmode rate limit", 20016), ONLY_OWNER: new ApiError("Only the owner of this account can perform this action", 20018), ANNOUNCEMENT_RATE_LIMITS: new ApiError("This message cannot be edited due to announcement rate limits", 20022), @@ -576,40 +568,25 @@ export const DiscordApiErrors = { MAXIMUM_GUILDS: new ApiError("Maximum number of guilds reached ({})", 30001, undefined, ["100"]), MAXIMUM_FRIENDS: new ApiError("Maximum number of friends reached ({})", 30002, undefined, ["1000"]), MAXIMUM_PINS: new ApiError("Maximum number of pins reached for the channel ({})", 30003, undefined, ["50"]), - MAXIMUM_NUMBER_OF_RECIPIENTS_REACHED: new ApiError("Maximum number of recipients reached ({})", 30004, undefined, [ - "10", - ]), + MAXIMUM_NUMBER_OF_RECIPIENTS_REACHED: new ApiError("Maximum number of recipients reached ({})", 30004, undefined, ["10"]), MAXIMUM_ROLES: new ApiError("Maximum number of guild roles reached ({})", 30005, undefined, ["250"]), MAXIMUM_WEBHOOKS: new ApiError("Maximum number of webhooks reached ({})", 30007, undefined, ["10"]), MAXIMUM_NUMBER_OF_EMOJIS_REACHED: new ApiError("Maximum number of emojis reached", 30008), MAXIMUM_REACTIONS: new ApiError("Maximum number of reactions reached ({})", 30010, undefined, ["20"]), MAXIMUM_CHANNELS: new ApiError("Maximum number of guild channels reached ({})", 30013, undefined, ["500"]), - MAXIMUM_ATTACHMENTS: new ApiError("Maximum number of attachments in a message reached ({})", 30015, undefined, [ - "10", - ]), + MAXIMUM_ATTACHMENTS: new ApiError("Maximum number of attachments in a message reached ({})", 30015, undefined, ["10"]), MAXIMUM_INVITES: new ApiError("Maximum number of invites reached ({})", 30016, undefined, ["1000"]), MAXIMUM_ANIMATED_EMOJIS: new ApiError("Maximum number of animated emojis reached", 30018), MAXIMUM_SERVER_MEMBERS: new ApiError("Maximum number of server members reached", 30019), - MAXIMUM_SERVER_CATEGORIES: new ApiError( - "Maximum number of server categories has been reached ({})", - 30030, - undefined, - ["5"] - ), + MAXIMUM_SERVER_CATEGORIES: new ApiError("Maximum number of server categories has been reached ({})", 30030, undefined, ["5"]), GUILD_ALREADY_HAS_TEMPLATE: new ApiError("Guild already has a template", 30031), MAXIMUM_THREAD_PARTICIPANTS: new ApiError("Max number of thread participants has been reached", 30033), - MAXIMUM_BANS_FOR_NON_GUILD_MEMBERS: new ApiError( - "Maximum number of bans for non-guild members have been exceeded", - 30035 - ), + MAXIMUM_BANS_FOR_NON_GUILD_MEMBERS: new ApiError("Maximum number of bans for non-guild members have been exceeded", 30035), MAXIMUM_BANS_FETCHES: new ApiError("Maximum number of bans fetches has been reached", 30037), MAXIMUM_STICKERS: new ApiError("Maximum number of stickers reached", 30039), MAXIMUM_PRUNE_REQUESTS: new ApiError("Maximum number of prune requests has been reached. Try again later", 30040), UNAUTHORIZED: new ApiError("Unauthorized. Provide a valid token and try again", 40001), - ACCOUNT_VERIFICATION_REQUIRED: new ApiError( - "You need to verify your account in order to perform this action", - 40002 - ), + ACCOUNT_VERIFICATION_REQUIRED: new ApiError("You need to verify your account in order to perform this action", 40002), OPENING_DIRECT_MESSAGES_TOO_FAST: new ApiError("You are opening direct messages too fast", 40003), REQUEST_ENTITY_TOO_LARGE: new ApiError("Request entity too large. Try sending something smaller in size", 40005), FEATURE_TEMPORARILY_DISABLED: new ApiError("This feature has been temporarily disabled server-side", 40006), @@ -625,10 +602,7 @@ export const DiscordApiErrors = { CANNOT_SEND_EMPTY_MESSAGE: new ApiError("Cannot send an empty message", 50006), CANNOT_MESSAGE_USER: new ApiError("Cannot send messages to this user", 50007), CANNOT_SEND_MESSAGES_IN_VOICE_CHANNEL: new ApiError("Cannot send messages in a voice channel", 50008), - CHANNEL_VERIFICATION_LEVEL_TOO_HIGH: new ApiError( - "Channel verification level is too high for you to gain access", - 50009 - ), + CHANNEL_VERIFICATION_LEVEL_TOO_HIGH: new ApiError("Channel verification level is too high for you to gain access", 50009), OAUTH2_APPLICATION_BOT_ABSENT: new ApiError("OAuth2 application does not have a bot", 50010), MAXIMUM_OAUTH2_APPLICATIONS: new ApiError("OAuth2 application limit reached", 50011), INVALID_OAUTH_STATE: new ApiError("Invalid OAuth2 state", 50012), @@ -641,10 +615,7 @@ export const DiscordApiErrors = { undefined, ["2", "100"] ), - CANNOT_PIN_MESSAGE_IN_OTHER_CHANNEL: new ApiError( - "A message can only be pinned to the channel it was sent in", - 50019 - ), + CANNOT_PIN_MESSAGE_IN_OTHER_CHANNEL: new ApiError("A message can only be pinned to the channel it was sent in", 50019), INVALID_OR_TAKEN_INVITE_CODE: new ApiError("Invite code was either invalid or taken", 50020), CANNOT_EXECUTE_ON_SYSTEM_MESSAGE: new ApiError("Cannot execute action on a system message", 50021), CANNOT_EXECUTE_ON_THIS_CHANNEL_TYPE: new ApiError("Cannot execute action on this channel type", 50024), @@ -658,34 +629,22 @@ export const DiscordApiErrors = { "Invalid form body (returned for both application/json and multipart/form-data bodies), or invalid Content-Type provided", 50035 ), - INVITE_ACCEPTED_TO_GUILD_NOT_CONTAINING_BOT: new ApiError( - "An invite was accepted to a guild the application's bot is not in", - 50036 - ), + INVITE_ACCEPTED_TO_GUILD_NOT_CONTAINING_BOT: new ApiError("An invite was accepted to a guild the application's bot is not in", 50036), INVALID_API_VERSION: new ApiError("Invalid API version provided", 50041), FILE_EXCEEDS_MAXIMUM_SIZE: new ApiError("File uploaded exceeds the maximum size", 50045), INVALID_FILE_UPLOADED: new ApiError("Invalid file uploaded", 50046), CANNOT_SELF_REDEEM_GIFT: new ApiError("Cannot self-redeem this gift", 50054), PAYMENT_SOURCE_REQUIRED: new ApiError("Payment source required to redeem gift", 50070), - CANNOT_DELETE_COMMUNITY_REQUIRED_CHANNEL: new ApiError( - "Cannot delete a channel required for Community guilds", - 50074 - ), + CANNOT_DELETE_COMMUNITY_REQUIRED_CHANNEL: new ApiError("Cannot delete a channel required for Community guilds", 50074), INVALID_STICKER_SENT: new ApiError("Invalid sticker sent", 50081), CANNOT_EDIT_ARCHIVED_THREAD: new ApiError( "Tried to perform an operation on an archived thread, such as editing a message or adding a user to the thread", 50083 ), INVALID_THREAD_NOTIFICATION_SETTINGS: new ApiError("Invalid thread notification settings", 50084), - BEFORE_EARLIER_THAN_THREAD_CREATION_DATE: new ApiError( - "before value is earlier than the thread creation date", - 50085 - ), + BEFORE_EARLIER_THAN_THREAD_CREATION_DATE: new ApiError("before value is earlier than the thread creation date", 50085), SERVER_NOT_AVAILABLE_IN_YOUR_LOCATION: new ApiError("This server is not available in your location", 50095), - SERVER_NEEDS_MONETIZATION_ENABLED: new ApiError( - "This server needs monetization enabled in order to perform this action", - 50097 - ), + SERVER_NEEDS_MONETIZATION_ENABLED: new ApiError("This server needs monetization enabled in order to perform this action", 50097), TWO_FACTOR_REQUIRED: new ApiError("Two factor is required for this operation", 60003), NO_USERS_WITH_DISCORDTAG_EXIST: new ApiError("No users with DiscordTag exist", 80004), REACTION_BLOCKED: new ApiError("Reaction was blocked", 90001), @@ -694,33 +653,17 @@ export const DiscordApiErrors = { THREAD_ALREADY_CREATED_FOR_THIS_MESSAGE: new ApiError("A thread has already been created for this message", 160004), THREAD_IS_LOCKED: new ApiError("Thread is locked", 160005), MAXIMUM_NUMBER_OF_ACTIVE_THREADS: new ApiError("Maximum number of active threads reached", 160006), - MAXIMUM_NUMBER_OF_ACTIVE_ANNOUNCEMENT_THREADS: new ApiError( - "Maximum number of active announcement threads reached", - 160007 - ), + MAXIMUM_NUMBER_OF_ACTIVE_ANNOUNCEMENT_THREADS: new ApiError("Maximum number of active announcement threads reached", 160007), INVALID_JSON_FOR_UPLOADED_LOTTIE_FILE: new ApiError("Invalid JSON for uploaded Lottie file", 170001), - LOTTIES_CANNOT_CONTAIN_RASTERIZED_IMAGES: new ApiError( - "Uploaded Lotties cannot contain rasterized images such as PNG or JPEG", - 170002 - ), + LOTTIES_CANNOT_CONTAIN_RASTERIZED_IMAGES: new ApiError("Uploaded Lotties cannot contain rasterized images such as PNG or JPEG", 170002), STICKER_MAXIMUM_FRAMERATE: new ApiError("Sticker maximum framerate exceeded", 170003), - STICKER_MAXIMUM_FRAME_COUNT: new ApiError("Sticker frame count exceeds maximum of {} frames", 170004, undefined, [ - "1000", - ]), + STICKER_MAXIMUM_FRAME_COUNT: new ApiError("Sticker frame count exceeds maximum of {} frames", 170004, undefined, ["1000"]), LOTTIE_ANIMATION_MAXIMUM_DIMENSIONS: new ApiError("Lottie animation maximum dimensions exceeded", 170005), - STICKER_FRAME_RATE_TOO_SMALL_OR_TOO_LARGE: new ApiError( - "Sticker frame rate is either too small or too large", - 170006 - ), - STICKER_ANIMATION_DURATION_MAXIMUM: new ApiError( - "Sticker animation duration exceeds maximum of {} seconds", - 170007, - undefined, - ["5"] - ), + STICKER_FRAME_RATE_TOO_SMALL_OR_TOO_LARGE: new ApiError("Sticker frame rate is either too small or too large", 170006), + STICKER_ANIMATION_DURATION_MAXIMUM: new ApiError("Sticker animation duration exceeds maximum of {} seconds", 170007, undefined, ["5"]), //Other errors - UNKNOWN_VOICE_STATE: new ApiError("Unknown Voice State", 10065, 404), + UNKNOWN_VOICE_STATE: new ApiError("Unknown Voice State", 10065, 404) }; /** @@ -746,7 +689,7 @@ export const FosscordApiErrors = { CANNOT_BACKFILL_TO_THE_FUTURE: new ApiError("You cannot backfill messages in the future", 55003), CANNOT_GRANT_PERMISSIONS_EXCEEDING_RIGHTS: new ApiError("You cannot grant permissions exceeding your own rights", 50050), ROUTES_LOOPING: new ApiError("Loops in the route definition ({})", 50060, undefined, [""]), - CANNOT_REMOVE_ROUTE: new ApiError("Cannot remove message route while it is in effect and being used", 50061), + CANNOT_REMOVE_ROUTE: new ApiError("Cannot remove message route while it is in effect and being used", 50061) }; /** @@ -765,11 +708,7 @@ export const DefaultMessageNotifications = ["ALL", "MENTIONS", "MUTED"]; * * INSERTED (Fosscord extension) * @typedef {string} MembershipStates */ -export const MembershipStates = [ - "INSERTED", - "INVITED", - "ACCEPTED", -]; +export const MembershipStates = ["INSERTED", "INVITED", "ACCEPTED"]; /** * The value set for a webhook's type: @@ -778,15 +717,10 @@ export const MembershipStates = [ * * Custom (Fosscord extension) * @typedef {string} WebhookTypes */ -export const WebhookTypes = [ - "Custom", - "Incoming", - "Channel Follower", -]; +export const WebhookTypes = ["Custom", "Incoming", "Channel Follower"]; function keyMirror(arr: string[]) { let tmp = Object.create(null); for (const value of arr) tmp[value] = value; return tmp; } - diff --git a/src/util/util/Database.ts b/src/util/util/Database.ts index 84ce473d..8509879d 100644 --- a/src/util/util/Database.ts +++ b/src/util/util/Database.ts @@ -1,13 +1,12 @@ +import { config } from "dotenv"; +import fs from "fs"; import path from "path"; +import { green, red, yellow } from "picocolors"; +import { exit } from "process"; import "reflect-metadata"; -import { DataSource, createConnection, DataSourceOptions, PrimaryColumn, PrimaryGeneratedColumn } from "typeorm"; +import { DataSource, DataSourceOptions, PrimaryColumn, PrimaryGeneratedColumn } from "typeorm"; import * as Models from "../entities"; -import { Migration } from "../entities/Migration"; -import { yellow, green, red } from "picocolors"; -import fs from "fs"; -import { exit } from "process"; import { BaseClass, BaseClassWithoutId } from "../entities"; -import { config } from "dotenv"; // UUID extension option is only supported with postgres // We want to generate all id's with Snowflakes that's why we have our own BaseEntity class @@ -18,15 +17,15 @@ let dataSource: DataSource; export async function getOrInitialiseDatabase(): Promise<DataSource> { //if (dataSource) return dataSource; // prevent initalizing multiple times - if(dataSource.isInitialized) return dataSource; - + if (dataSource.isInitialized) return dataSource; + await dataSource.initialize(); console.log(`[Database] ${green("Connected!")}`); await dataSource.runMigrations(); console.log(`[Database] ${green("Up to date!")}`); - if("DB_MIGRATE" in process.env) { - console.log("DB_MIGRATE specified, exiting!") + if ("DB_MIGRATE" in process.env) { + console.log("DB_MIGRATE specified, exiting!"); exit(0); } return dataSource; @@ -40,35 +39,48 @@ function getDataSourceOptions(): DataSourceOptions { config(); //get connection string and check for migrations const dbConnectionString = process.env.DATABASE || path.join(process.cwd(), "database.db"); - const type = dbConnectionString.includes("://") ? dbConnectionString.split(":")[0]?.replace("+srv", "") : "sqlite" as any; + const type = dbConnectionString.includes("://") ? dbConnectionString.split(":")[0]?.replace("+srv", "") : ("sqlite" as any); const isSqlite = type.includes("sqlite"); const migrationsExist = fs.existsSync(path.join(__dirname, "..", "migrations", type)); //read env vars const synchronizeInsteadOfMigrations = "DB_UNSAFE" in process.env; const verboseDb = "DB_VERBOSE" in process.env; - - if(isSqlite) + + if (isSqlite) console.log(`[Database] ${red(`You are running sqlite! Please keep in mind that we recommend setting up a dedicated database!`)}`); - if(verboseDb) - console.log(`[Database] ${red(`Verbose database logging is enabled, this might impact performance! Unset DB_VERBOSE to disable.`)}`); + if (verboseDb) + console.log( + `[Database] ${red(`Verbose database logging is enabled, this might impact performance! Unset DB_VERBOSE to disable.`)}` + ); - if(synchronizeInsteadOfMigrations){ - console.log(`[Database] ${red(`Unsafe database upgrades are enabled! We are not responsible for broken databases! Unset DB_UNSAFE to disable.`)}`); - } - else if(!migrationsExist) { + if (synchronizeInsteadOfMigrations) { + console.log( + `[Database] ${red( + `Unsafe database upgrades are enabled! We are not responsible for broken databases! Unset DB_UNSAFE to disable.` + )}` + ); + } else if (!migrationsExist) { console.log(`[Database] ${red(`Database engine not supported! Set UNSAFE_DB to bypass.`)}`); console.log(`[Database] ${red(`Please mention this to Fosscord developers, and provide this info:`)}`); - console.log(`[Database]\n${red(JSON.stringify({ - db_type: type, - migrations_exist: migrationsExist - }, null, 4))}`); + console.log( + `[Database]\n${red( + JSON.stringify( + { + db_type: type, + migrations_exist: migrationsExist + }, + null, + 4 + ) + )}` + ); - if(!("DB_MIGRATE" in process.env)) exit(1); + if (!("DB_MIGRATE" in process.env)) exit(1); } console.log(`[Database] ${yellow(`Configuring data source to use ${type} database...`)}`); return { type, - charset: 'utf8mb4', + charset: "utf8mb4", url: isSqlite ? undefined : dbConnectionString, database: isSqlite ? dbConnectionString : undefined, // @ts-ignore @@ -77,7 +89,7 @@ function getDataSourceOptions(): DataSourceOptions { synchronize: synchronizeInsteadOfMigrations, logging: verboseDb, cache: { - duration: 1000 * 3, // cache all find queries for 3 seconds + duration: 1000 * 3 // cache all find queries for 3 seconds }, bigNumberStrings: false, supportBigNumbers: true, @@ -87,17 +99,12 @@ function getDataSourceOptions(): DataSourceOptions { //migrationsRun: false, cli: { migrationsDir: `src/migrations/${type}` - }, + } } as DataSourceOptions; } function shouldIncludeEntity(name: string): boolean { - return ![ - BaseClassWithoutId, - PrimaryColumn, - BaseClass, - PrimaryGeneratedColumn - ].map(x=>x.name).includes(name); + return ![BaseClassWithoutId, PrimaryColumn, BaseClass, PrimaryGeneratedColumn].map((x) => x.name).includes(name); } export default dataSource = new DataSource(getDataSourceOptions()); diff --git a/src/util/util/Email.ts b/src/util/util/Email.ts index 6885da33..c98ccff0 100644 --- a/src/util/util/Email.ts +++ b/src/util/util/Email.ts @@ -15,7 +15,7 @@ export function adjustEmail(email?: string): string | undefined { // replace .dots and +alternatives -> Gmail Dot Trick https://support.google.com/mail/answer/7436150 and https://generator.email/blog/gmail-generator let v = user.replace(/[.]|(\+.*)/g, "") + "@gmail.com"; } - + if (domain === "google.com") { // replace .dots and +alternatives -> Google Staff GMail Dot Trick let v = user.replace(/[.]|(\+.*)/g, "") + "@google.com"; diff --git a/src/util/util/Event.ts b/src/util/util/Event.ts index 90c24347..383e4e50 100644 --- a/src/util/util/Event.ts +++ b/src/util/util/Event.ts @@ -1,7 +1,7 @@ import { Channel } from "amqplib"; -import { RabbitMQ } from "./RabbitMQ"; import EventEmitter from "events"; import { EVENT, Event } from "../interfaces"; +import { RabbitMQ } from "./RabbitMQ"; export const events = new EventEmitter(); export async function emitEvent(payload: Omit<Event, "created_at">) { @@ -79,12 +79,7 @@ export async function listenEvent(event: string, callback: (event: EventOpts) => } } -async function rabbitListen( - channel: Channel, - id: string, - callback: (event: EventOpts) => any, - opts?: { acknowledge?: boolean } -) { +async function rabbitListen(channel: Channel, id: string, callback: (event: EventOpts) => any, opts?: { acknowledge?: boolean }) { await channel.assertExchange(id, "fanout", { durable: false }); const q = await channel.assertQueue("", { exclusive: true, autoDelete: true }); @@ -109,12 +104,12 @@ async function rabbitListen( channel.ack(opts); }, channel, - cancel, + cancel }); // rabbitCh.ack(opts); }, { - noAck: !opts?.acknowledge, + noAck: !opts?.acknowledge } ); diff --git a/src/util/util/FieldError.ts b/src/util/util/FieldError.ts index 49968e1a..bdffd618 100644 --- a/src/util/util/FieldError.ts +++ b/src/util/util/FieldError.ts @@ -6,9 +6,9 @@ export function FieldErrors(fields: Record<string, { code?: string; message: str _errors: [ { message, - code: code || "BASE_TYPE_INVALID", - }, - ], + code: code || "BASE_TYPE_INVALID" + } + ] })) ); } diff --git a/src/util/util/Intents.ts b/src/util/util/Intents.ts index 1e840b76..db4c9e28 100644 --- a/src/util/util/Intents.ts +++ b/src/util/util/Intents.ts @@ -22,13 +22,12 @@ export class Intents extends BitField { GUILD_POLICY_EXECUTION: BigInt(1) << BigInt(21), // guild policy execution LIVE_MESSAGE_COMPOSITION: BigInt(1) << BigInt(32), // allow composing messages using the gateway GUILD_ROUTES: BigInt(1) << BigInt(41), // message routes affecting the guild - DIRECT_MESSAGES_THREADS: BigInt(1) << BigInt(42), // direct message threads + DIRECT_MESSAGES_THREADS: BigInt(1) << BigInt(42), // direct message threads JUMBO_EVENTS: BigInt(1) << BigInt(43), // jumbo events (size limits to be defined later) LOBBIES: BigInt(1) << BigInt(44), // lobbies - INSTANCE_ROUTES: BigInt(1) << BigInt(60), // all message route changes + INSTANCE_ROUTES: BigInt(1) << BigInt(60), // all message route changes INSTANCE_GUILD_CHANGES: BigInt(1) << BigInt(61), // all guild create, guild object patch, split, merge and delete events INSTANCE_POLICY_UPDATES: BigInt(1) << BigInt(62), // all instance policy updates INSTANCE_USER_UPDATES: BigInt(1) << BigInt(63) // all instance user updates }; } - diff --git a/src/util/util/InvisibleCharacters.ts b/src/util/util/InvisibleCharacters.ts index 2b014e14..4c809e48 100644 --- a/src/util/util/InvisibleCharacters.ts +++ b/src/util/util/InvisibleCharacters.ts @@ -1,56 +1,56 @@ -// List from https://invisible-characters.com/ -export const InvisibleCharacters = [ - '\u{9}', //Tab - '\u{20}', //Space - '\u{ad}', //Soft hyphen - '\u{34f}', //Combining grapheme joiner - '\u{61c}', //Arabic letter mark - '\u{115f}', //Hangul choseong filler - '\u{1160}', //Hangul jungseong filler - '\u{17b4}', //Khmer vowel inherent AQ - '\u{17b5}', //Khmer vowel inherent AA - '\u{180e}', //Mongolian vowel separator - '\u{2000}', //En quad - '\u{2001}', //Em quad - '\u{2002}', //En space - '\u{2003}', //Em space - '\u{2004}', //Three-per-em space - '\u{2005}', //Four-per-em space - '\u{2006}', //Six-per-em space - '\u{2007}', //Figure space - '\u{2008}', //Punctuation space - '\u{2009}', //Thin space - '\u{200a}', //Hair space - '\u{200b}', //Zero width space - '\u{200c}', //Zero width non-joiner - '\u{200d}', //Zero width joiner - '\u{200e}', //Left-to-right mark - '\u{200f}', //Right-to-left mark - '\u{202f}', //Narrow no-break space - '\u{205f}', //Medium mathematical space - '\u{2060}', //Word joiner - '\u{2061}', //Function application - '\u{2062}', //Invisible times - '\u{2063}', //Invisible separator - '\u{2064}', //Invisible plus - '\u{206a}', //Inhibit symmetric swapping - '\u{206b}', //Activate symmetric swapping - '\u{206c}', //Inhibit arabic form shaping - '\u{206d}', //Activate arabic form shaping - '\u{206e}', //National digit shapes - '\u{206f}', //Nominal digit shapes - '\u{3000}', //Ideographic space - '\u{2800}', //Braille pattern blank - '\u{3164}', //Hangul filler - '\u{feff}', //Zero width no-break space - '\u{ffa0}', //Haldwidth hangul filler - '\u{1d159}', //Musical symbol null notehead - '\u{1d173}', //Musical symbol begin beam - '\u{1d174}', //Musical symbol end beam - '\u{1d175}', //Musical symbol begin tie - '\u{1d176}', //Musical symbol end tie - '\u{1d177}', //Musical symbol begin slur - '\u{1d178}', //Musical symbol end slur - '\u{1d179}', //Musical symbol begin phrase - '\u{1d17a}' //Musical symbol end phrase -]; \ No newline at end of file +// List from https://invisible-characters.com/ +export const InvisibleCharacters = [ + "\u{9}", //Tab + "\u{20}", //Space + "\u{ad}", //Soft hyphen + "\u{34f}", //Combining grapheme joiner + "\u{61c}", //Arabic letter mark + "\u{115f}", //Hangul choseong filler + "\u{1160}", //Hangul jungseong filler + "\u{17b4}", //Khmer vowel inherent AQ + "\u{17b5}", //Khmer vowel inherent AA + "\u{180e}", //Mongolian vowel separator + "\u{2000}", //En quad + "\u{2001}", //Em quad + "\u{2002}", //En space + "\u{2003}", //Em space + "\u{2004}", //Three-per-em space + "\u{2005}", //Four-per-em space + "\u{2006}", //Six-per-em space + "\u{2007}", //Figure space + "\u{2008}", //Punctuation space + "\u{2009}", //Thin space + "\u{200a}", //Hair space + "\u{200b}", //Zero width space + "\u{200c}", //Zero width non-joiner + "\u{200d}", //Zero width joiner + "\u{200e}", //Left-to-right mark + "\u{200f}", //Right-to-left mark + "\u{202f}", //Narrow no-break space + "\u{205f}", //Medium mathematical space + "\u{2060}", //Word joiner + "\u{2061}", //Function application + "\u{2062}", //Invisible times + "\u{2063}", //Invisible separator + "\u{2064}", //Invisible plus + "\u{206a}", //Inhibit symmetric swapping + "\u{206b}", //Activate symmetric swapping + "\u{206c}", //Inhibit arabic form shaping + "\u{206d}", //Activate arabic form shaping + "\u{206e}", //National digit shapes + "\u{206f}", //Nominal digit shapes + "\u{3000}", //Ideographic space + "\u{2800}", //Braille pattern blank + "\u{3164}", //Hangul filler + "\u{feff}", //Zero width no-break space + "\u{ffa0}", //Haldwidth hangul filler + "\u{1d159}", //Musical symbol null notehead + "\u{1d173}", //Musical symbol begin beam + "\u{1d174}", //Musical symbol end beam + "\u{1d175}", //Musical symbol begin tie + "\u{1d176}", //Musical symbol end tie + "\u{1d177}", //Musical symbol begin slur + "\u{1d178}", //Musical symbol end slur + "\u{1d179}", //Musical symbol begin phrase + "\u{1d17a}" //Musical symbol end phrase +]; diff --git a/src/util/util/MFA.ts b/src/util/util/MFA.ts index 2e47b2fc..a2afcad6 100644 --- a/src/util/util/MFA.ts +++ b/src/util/util/MFA.ts @@ -6,12 +6,12 @@ export function generateMfaBackupCodes(user_id: string) { for (let i = 0; i < 10; i++) { const code = BackupCode.create({ user: { id: user_id }, - code: crypto.randomBytes(4).toString("hex"), // 8 characters + code: crypto.randomBytes(4).toString("hex"), // 8 characters consumed: false, - expired: false, + expired: false }); backup_codes.push(code); } return backup_codes; -} \ No newline at end of file +} diff --git a/src/util/util/MessageFlags.ts b/src/util/util/MessageFlags.ts index b59295c4..c5d5d02a 100644 --- a/src/util/util/MessageFlags.ts +++ b/src/util/util/MessageFlags.ts @@ -15,6 +15,6 @@ export class MessageFlags extends BitField { INTERACTION_WAIT: BigInt(1) << BigInt(7), // discord.com calls this LOADING // FAILED_TO_MENTION_SOME_ROLES_IN_THREAD: BigInt(1) << BigInt(8) SCRIPT_WAIT: BigInt(1) << BigInt(24), // waiting for the self command to complete - IMPORT_WAIT: BigInt(1) << BigInt(25), // latest message of a bulk import, waiting for the rest of the channel to be backfilled + IMPORT_WAIT: BigInt(1) << BigInt(25) // latest message of a bulk import, waiting for the rest of the channel to be backfilled }; } diff --git a/src/util/util/Permissions.ts b/src/util/util/Permissions.ts index c7400303..b8d0d8ae 100644 --- a/src/util/util/Permissions.ts +++ b/src/util/util/Permissions.ts @@ -1,8 +1,8 @@ // https://github.com/discordjs/discord.js/blob/master/src/util/Permissions.js // Apache License Version 2.0 Copyright 2015 - 2021 Amish Shah +import { HTTPError } from ".."; import { Channel, ChannelPermissionOverwrite, Guild, Member, Role } from "../entities"; import { BitField, BitFieldResolvable, BitFlag } from "./BitField"; -import { HTTPError } from ".."; export type PermissionResolvable = bigint | number | Permissions | PermissionResolvable[] | PermissionString; @@ -59,7 +59,7 @@ export class Permissions extends BitField { MANAGE_THREADS: BitFlag(34), USE_PUBLIC_THREADS: BitFlag(35), USE_PRIVATE_THREADS: BitFlag(36), - USE_EXTERNAL_STICKERS: BitFlag(37), + USE_EXTERNAL_STICKERS: BitFlag(37) /** * CUSTOM PERMISSIONS ideas: @@ -123,7 +123,7 @@ export class Permissions extends BitField { static finalPermission({ user, guild, - channel, + channel }: { user: { id: string; roles: string[] }; guild: { roles: Role[] }; @@ -163,7 +163,7 @@ export class Permissions extends BitField { "USE_EXTERNAL_EMOJIS", "CONNECT", "SPEAK", - "MANAGE_CHANNELS", + "MANAGE_CHANNELS" ]); } @@ -213,8 +213,8 @@ export async function getPermission( "owner_id", "guild_id", // @ts-ignore - ...(opts.channel_select || []), - ], + ...(opts.channel_select || []) + ] }); if (channel.guild_id) guild_id = channel.guild_id; // derive guild_id from the channel } @@ -226,9 +226,9 @@ export async function getPermission( "id", "owner_id", // @ts-ignore - ...(opts.guild_select || []), + ...(opts.guild_select || []) ], - relations: opts.guild_relations, + relations: opts.guild_relations }); if (guild.owner_id === user_id) return new Permissions(Permissions.FLAGS.ADMINISTRATOR); @@ -240,8 +240,8 @@ export async function getPermission( "roles", "index", // @ts-ignore - ...(opts.member_select || []), - ], + ...(opts.member_select || []) + ] }); } @@ -252,16 +252,16 @@ export async function getPermission( let permission = Permissions.finalPermission({ user: { id: user_id, - roles: member?.roles.map((x) => x.id) || [], + roles: member?.roles.map((x) => x.id) || [] }, guild: { - roles: member?.roles || [], + roles: member?.roles || [] }, channel: { overwrites: channel?.permission_overwrites, owner_id: channel?.owner_id, - recipient_ids, - }, + recipient_ids + } }); const obj = new Permissions(permission); diff --git a/src/util/util/RabbitMQ.ts b/src/util/util/RabbitMQ.ts index 0f5eb6aa..638b805b 100644 --- a/src/util/util/RabbitMQ.ts +++ b/src/util/util/RabbitMQ.ts @@ -1,4 +1,4 @@ -import amqp, { Connection, Channel } from "amqplib"; +import { Channel, Connection } from "amqplib"; // import Config from "./Config"; export const RabbitMQ: { connection: Connection | null; channel: Channel | null; init: () => Promise<void> } = { @@ -15,5 +15,5 @@ export const RabbitMQ: { connection: Connection | null; channel: Channel | null; // console.log(`[RabbitMQ] connected`); // this.channel = await this.connection.createChannel(); // console.log(`[RabbitMQ] channel created`); - }, + } }; diff --git a/src/util/util/Rights.ts b/src/util/util/Rights.ts index 1c3906fb..51bb098c 100644 --- a/src/util/util/Rights.ts +++ b/src/util/util/Rights.ts @@ -1,6 +1,6 @@ -import { BitField, BitFieldResolvable, BitFlag } from "./BitField"; -import { User } from "../entities"; import { HTTPError } from ".."; +import { User } from "../entities"; +import { BitField, BitFieldResolvable, BitFlag } from "./BitField"; export type RightResolvable = bigint | number | Rights | RightResolvable[] | RightString; @@ -51,7 +51,7 @@ export class Rights extends BitField { CREDITABLE: BitFlag(32), // can receive money from monetisation related features KICK_BAN_MEMBERS: BitFlag(33), // can kick or ban guild or group DM members in the guilds/groups that they have KICK_MEMBERS, or BAN_MEMBERS - SELF_LEAVE_GROUPS: BitFlag(34), + SELF_LEAVE_GROUPS: BitFlag(34), // can leave the guilds or group DMs that they joined on their own (one can always leave a guild or group DMs they have been force-added) PRESENCE: BitFlag(35), // inverts the presence confidentiality default (OPERATOR's presence is not routed by default, others' are) for a given user @@ -79,15 +79,16 @@ export class Rights extends BitField { // @ts-ignore throw new HTTPError(`You are missing the following rights ${permission}`, 403); } - } const ALL_RIGHTS = Object.values(Rights.FLAGS).reduce((total, val) => total | val, BigInt(0)); -export async function getRights( user_id: string +export async function getRights( + user_id: string /**, opts: { in_behalf?: (keyof User)[]; - } = {} **/) { + } = {} **/ +) { let user = await User.findOneOrFail({ where: { id: user_id } }); return new Rights(user.rights); -} +} diff --git a/src/util/util/Snowflake.ts b/src/util/util/Snowflake.ts index 0ef178fe..89f4f0c3 100644 --- a/src/util/util/Snowflake.ts +++ b/src/util/util/Snowflake.ts @@ -83,14 +83,15 @@ export class Snowflake { return dec; } - static generateWorkerProcess() { // worker process - returns a number + static generateWorkerProcess() { + // worker process - returns a number let time = BigInt(Date.now() - Snowflake.EPOCH) << BigInt(22); let worker = Snowflake.workerId << 17n; let process = Snowflake.processId << 12n; let increment = Snowflake.INCREMENT++; return BigInt(time | worker | process | increment); } - + static generate() { return Snowflake.generateWorkerProcess().toString(); } @@ -117,13 +118,13 @@ export class Snowflake { workerID: parseInt(BINARY.substring(42, 47), 2), processID: parseInt(BINARY.substring(47, 52), 2), increment: parseInt(BINARY.substring(52, 64), 2), - binary: BINARY, + binary: BINARY }; Object.defineProperty(res, "date", { get: function get() { return new Date(this.timestamp); }, - enumerable: true, + enumerable: true }); return res; } diff --git a/src/util/util/Token.ts b/src/util/util/Token.ts index 5a3922d1..d192a13a 100644 --- a/src/util/util/Token.ts +++ b/src/util/util/Token.ts @@ -1,6 +1,6 @@ import jwt, { VerifyOptions } from "jsonwebtoken"; -import { Config } from "./Config"; import { User } from "../entities"; +import { Config } from "./Config"; export const JWTOptions: VerifyOptions = { algorithms: ["HS256"] }; @@ -11,18 +11,17 @@ export function checkToken(token: string, jwtSecret: string): Promise<any> { in fosscord, even with instances that have bot distinction; we won't enforce "Bot" prefix, as we don't really have separate pathways for bots **/ - + jwt.verify(token, jwtSecret, JWTOptions, async (err, decoded: any) => { if (err || !decoded) return rej("Invalid Token"); const user = await User.findOne({ where: { id: decoded.id }, - select: ["data", "bot", "disabled", "deleted", "rights"] + select: ["data", "bot", "disabled", "deleted", "rights"] }); if (!user) return rej("Invalid Token"); // we need to round it to seconds as it saved as seconds in jwt iat and valid_tokens_since is stored in milliseconds - if (decoded.iat * 1000 < new Date(user.data.valid_tokens_since).setSeconds(0, 0)) - return rej("Invalid Token"); + if (decoded.iat * 1000 < new Date(user.data.valid_tokens_since).setSeconds(0, 0)) return rej("Invalid Token"); if (user.disabled) return rej("User disabled"); if (user.deleted) return rej("User not found"); @@ -40,7 +39,7 @@ export async function generateToken(id: string) { { id: id, iat }, Config.get().security.jwtSecret, { - algorithm, + algorithm }, (err, token) => { if (err) return rej(err); diff --git a/src/util/util/TraverseDirectory.ts b/src/util/util/TraverseDirectory.ts index 3d0d6279..6f60e73b 100644 --- a/src/util/util/TraverseDirectory.ts +++ b/src/util/util/TraverseDirectory.ts @@ -1,13 +1,10 @@ import { Server, traverseDirectory } from "lambert-server"; //if we're using ts-node, use ts files instead of js -const extension = Symbol.for("ts-node.register.instance") in process ? "ts" : "js" +const extension = Symbol.for("ts-node.register.instance") in process ? "ts" : "js"; -const DEFAULT_FILTER = new RegExp("^([^\.].*)(?<!\.d)\.(" + extension + ")$"); +const DEFAULT_FILTER = new RegExp("^([^.].*)(?<!.d).(" + extension + ")$"); export function registerRoutes(server: Server, root: string) { - return traverseDirectory( - { dirname: root, recursive: true, filter: DEFAULT_FILTER }, - server.registerRoute.bind(server, root) - ); + return traverseDirectory({ dirname: root, recursive: true, filter: DEFAULT_FILTER }, server.registerRoute.bind(server, root)); } diff --git a/src/util/util/cdn.ts b/src/util/util/cdn.ts index 9cfe4896..5573b848 100644 --- a/src/util/util/cdn.ts +++ b/src/util/util/cdn.ts @@ -1,9 +1,7 @@ import FormData from "form-data"; +import fetch from "node-fetch"; import { HTTPError } from ".."; import { Config } from "./Config"; -import multer from "multer"; -import fetch from "node-fetch" -import { nodeModuleNameResolver } from "typescript"; export async function uploadFile(path: string, file?: Express.Multer.File) { if (!file?.buffer) throw new HTTPError("Missing file in body"); @@ -11,16 +9,16 @@ export async function uploadFile(path: string, file?: Express.Multer.File) { const form = new FormData(); form.append("file", file.buffer, { contentType: file.mimetype, - filename: file.originalname, + filename: file.originalname }); const response = await fetch(`${Config.get().cdn.endpointPrivate || "http://localhost:3003"}${path}`, { headers: { signature: Config.get().security.requestSignature, - ...form.getHeaders(), + ...form.getHeaders() }, method: "POST", - body: form, + body: form }); const result = await response.json(); @@ -46,9 +44,9 @@ export async function handleFile(path: string, body?: string): Promise<string | export async function deleteFile(path: string) { const response = await fetch(`${Config.get().cdn.endpointPrivate || "http://localhost:3003"}${path}`, { headers: { - signature: Config.get().security.requestSignature, + signature: Config.get().security.requestSignature }, - method: "DELETE", + method: "DELETE" }); const result = await response.json(); diff --git a/src/util/util/imports/Checks.ts b/src/util/util/imports/Checks.ts index 19a84171..bd3c6343 100644 --- a/src/util/util/imports/Checks.ts +++ b/src/util/util/imports/Checks.ts @@ -30,11 +30,7 @@ export class Email { return !!this.email.match(EMAIL_REGEX); } } -export function instanceOf( - type: any, - value: any, - { path = "", optional = false }: { path?: string; optional?: boolean } = {} -): boolean { +export function instanceOf(type: any, value: any, { path = "", optional = false }: { path?: string; optional?: boolean } = {}): boolean { if (!type) return true; // no type was specified if (value == null) { @@ -110,7 +106,7 @@ export function instanceOf( return instanceOf(type[key], value[newKey], { path: `${path}.${newKey}`, - optional: OPTIONAL, + optional: OPTIONAL }); }); } else if (typeof type === "number" || typeof type === "string" || typeof type === "boolean") { diff --git a/src/util/util/imports/HTTPError.ts b/src/util/util/imports/HTTPError.ts index 56a7dd55..70ba92a8 100644 --- a/src/util/util/imports/HTTPError.ts +++ b/src/util/util/imports/HTTPError.ts @@ -2,4 +2,4 @@ export class HTTPError extends Error { constructor(message: string, public code: number = 400) { super(message); } -} \ No newline at end of file +} diff --git a/src/util/util/imports/OrmUtils.ts b/src/util/util/imports/OrmUtils.ts index 91d88172..0556994b 100644 --- a/src/util/util/imports/OrmUtils.ts +++ b/src/util/util/imports/OrmUtils.ts @@ -1,113 +1,96 @@ //source: https://github.com/typeorm/typeorm/blob/master/src/util/OrmUtils.ts export class OrmUtils { - // Checks if it's an object made by Object.create(null), {} or new Object() - private static isPlainObject(item: any) { - if (item === null || item === undefined) { - return false - } - - return !item.constructor || item.constructor === Object - } - - private static mergeArrayKey( - target: any, - key: number, - value: any, - memo: Map<any, any>, - ) { - // Have we seen this before? Prevent infinite recursion. - if (memo.has(value)) { - target[key] = memo.get(value) - return - } - - if (value instanceof Promise) { - // Skip promises entirely. - // This is a hold-over from the old code & is because we don't want to pull in - // the lazy fields. Ideally we'd remove these promises via another function first - // but for now we have to do it here. - return - } - - if (!this.isPlainObject(value) && !Array.isArray(value)) { - target[key] = value - return - } - - if (!target[key]) { - target[key] = Array.isArray(value) ? [] : {} - } - - memo.set(value, target[key]) - this.merge(target[key], value, memo) - memo.delete(value) - } - - private static mergeObjectKey( - target: any, - key: string, - value: any, - memo: Map<any, any>, - ) { - // Have we seen this before? Prevent infinite recursion. - if (memo.has(value)) { - Object.assign(target, { [key]: memo.get(value) }) - return - } - - if (value instanceof Promise) { - // Skip promises entirely. - // This is a hold-over from the old code & is because we don't want to pull in - // the lazy fields. Ideally we'd remove these promises via another function first - // but for now we have to do it here. - return - } - - if (!this.isPlainObject(value) && !Array.isArray(value)) { - Object.assign(target, { [key]: value }) - return - } - - if (!target[key]) { - Object.assign(target, { [key]: value }) - } - - memo.set(value, target[key]) - this.merge(target[key], value, memo) - memo.delete(value) - } - - private static merge( - target: any, - source: any, - memo: Map<any, any> = new Map(), - ): any { - if (Array.isArray(target) && Array.isArray(source)) { - for (let key = 0; key < source.length; key++) { - this.mergeArrayKey(target, key, source[key], memo) - } - } - else { - for (const key of Object.keys(source)) { - this.mergeObjectKey(target, key, source[key], memo) - } - } - - - } - - /** - * Deep Object.assign. - */ - static mergeDeep(target: any, ...sources: any[]): any { - if (!sources.length) { - return target - } - - for (const source of sources) { - OrmUtils.merge(target, source) - } - - return target - } -} \ No newline at end of file + // Checks if it's an object made by Object.create(null), {} or new Object() + private static isPlainObject(item: any) { + if (item === null || item === undefined) { + return false; + } + + return !item.constructor || item.constructor === Object; + } + + private static mergeArrayKey(target: any, key: number, value: any, memo: Map<any, any>) { + // Have we seen this before? Prevent infinite recursion. + if (memo.has(value)) { + target[key] = memo.get(value); + return; + } + + if (value instanceof Promise) { + // Skip promises entirely. + // This is a hold-over from the old code & is because we don't want to pull in + // the lazy fields. Ideally we'd remove these promises via another function first + // but for now we have to do it here. + return; + } + + if (!this.isPlainObject(value) && !Array.isArray(value)) { + target[key] = value; + return; + } + + if (!target[key]) { + target[key] = Array.isArray(value) ? [] : {}; + } + + memo.set(value, target[key]); + this.merge(target[key], value, memo); + memo.delete(value); + } + + private static mergeObjectKey(target: any, key: string, value: any, memo: Map<any, any>) { + // Have we seen this before? Prevent infinite recursion. + if (memo.has(value)) { + Object.assign(target, { [key]: memo.get(value) }); + return; + } + + if (value instanceof Promise) { + // Skip promises entirely. + // This is a hold-over from the old code & is because we don't want to pull in + // the lazy fields. Ideally we'd remove these promises via another function first + // but for now we have to do it here. + return; + } + + if (!this.isPlainObject(value) && !Array.isArray(value)) { + Object.assign(target, { [key]: value }); + return; + } + + if (!target[key]) { + Object.assign(target, { [key]: value }); + } + + memo.set(value, target[key]); + this.merge(target[key], value, memo); + memo.delete(value); + } + + private static merge(target: any, source: any, memo: Map<any, any> = new Map()): any { + if (Array.isArray(target) && Array.isArray(source)) { + for (let key = 0; key < source.length; key++) { + this.mergeArrayKey(target, key, source[key], memo); + } + } else { + for (const key of Object.keys(source)) { + this.mergeObjectKey(target, key, source[key], memo); + } + } + } + + /** + * Deep Object.assign. + */ + static mergeDeep(target: any, ...sources: any[]): any { + if (!sources.length) { + return target; + } + + for (const source of sources) { + OrmUtils.merge(target, source); + } + + return target; + } +} diff --git a/src/util/util/imports/index.ts b/src/util/util/imports/index.ts index 18c47a3b..120cff11 100644 --- a/src/util/util/imports/index.ts +++ b/src/util/util/imports/index.ts @@ -1,3 +1,3 @@ -export * from './Checks'; -export * from './HTTPError'; -export * from './OrmUtils'; \ No newline at end of file +export * from "./Checks"; +export * from "./HTTPError"; +export * from "./OrmUtils"; diff --git a/src/util/util/index.ts b/src/util/util/index.ts index 9e6059fa..11f0b72a 100644 --- a/src/util/util/index.ts +++ b/src/util/util/index.ts @@ -1,8 +1,6 @@ export * from "./ApiError"; +export * from "./Array"; export * from "./BitField"; -export * from "./Token"; -export * from "./imports/HTTPError"; -export * from "./imports/OrmUtils"; //export * from "./Categories"; export * from "./cdn"; export * from "./Config"; @@ -11,7 +9,11 @@ export * from "./Database"; export * from "./Email"; export * from "./Event"; export * from "./FieldError"; +export * from "./imports/HTTPError"; +export * from "./imports/index"; +export * from "./imports/OrmUtils"; export * from "./Intents"; +export * from "./InvisibleCharacters"; export * from "./MessageFlags"; export * from "./Permissions"; export * from "./RabbitMQ"; @@ -19,8 +21,5 @@ export * from "./Regex"; export * from "./Rights"; export * from "./Snowflake"; export * from "./String"; -export * from "./Array"; +export * from "./Token"; export * from "./TraverseDirectory"; -export * from "./InvisibleCharacters"; - -export * from "./imports/index"; |