diff options
Diffstat (limited to 'util/src/util')
-rw-r--r-- | util/src/util/ApiError.ts | 28 | ||||
-rw-r--r-- | util/src/util/Array.ts | 3 | ||||
-rw-r--r-- | util/src/util/AutoUpdate.ts | 84 | ||||
-rw-r--r-- | util/src/util/BitField.ts | 147 | ||||
-rw-r--r-- | util/src/util/Categories.ts | 1 | ||||
-rw-r--r-- | util/src/util/Config.ts | 81 | ||||
-rw-r--r-- | util/src/util/Constants.ts | 792 | ||||
-rw-r--r-- | util/src/util/Database.ts | 72 | ||||
-rw-r--r-- | util/src/util/Email.ts | 25 | ||||
-rw-r--r-- | util/src/util/Event.ts | 122 | ||||
-rw-r--r-- | util/src/util/FieldError.ts | 25 | ||||
-rw-r--r-- | util/src/util/Intents.ts | 34 | ||||
-rw-r--r-- | util/src/util/InvisibleCharacters.ts | 56 | ||||
-rw-r--r-- | util/src/util/MessageFlags.ts | 20 | ||||
-rw-r--r-- | util/src/util/Permissions.ts | 281 | ||||
-rw-r--r-- | util/src/util/RabbitMQ.ts | 19 | ||||
-rw-r--r-- | util/src/util/Regex.ts | 7 | ||||
-rw-r--r-- | util/src/util/Rights.ts | 102 | ||||
-rw-r--r-- | util/src/util/Snowflake.ts | 130 | ||||
-rw-r--r-- | util/src/util/String.ts | 7 | ||||
-rw-r--r-- | util/src/util/Token.ts | 51 | ||||
-rw-r--r-- | util/src/util/TraverseDirectory.ts | 13 | ||||
-rw-r--r-- | util/src/util/cdn.ts | 56 | ||||
-rw-r--r-- | util/src/util/index.ts | 22 |
24 files changed, 0 insertions, 2178 deletions
diff --git a/util/src/util/ApiError.ts b/util/src/util/ApiError.ts deleted file mode 100644 index f1a9b4f6..00000000 --- a/util/src/util/ApiError.ts +++ /dev/null @@ -1,28 +0,0 @@ -export class ApiError extends Error { - constructor( - readonly message: string, - public readonly code: number, - public readonly httpStatus: number = 400, - public readonly defaultParams?: string[] - ) { - super(message); - } - - withDefaultParams(): ApiError { - if (this.defaultParams) - return new ApiError(applyParamsToString(this.message, this.defaultParams), this.code, this.httpStatus); - return this; - } - - withParams(...params: (string | number)[]): ApiError { - return new ApiError(applyParamsToString(this.message, params), this.code, this.httpStatus); - } -} - -export function applyParamsToString(s: string, params: (string | number)[]): string { - let newString = s; - params.forEach((a) => { - newString = newString.replace("{}", "" + a); - }); - return newString; -} diff --git a/util/src/util/Array.ts b/util/src/util/Array.ts deleted file mode 100644 index 5a45d1b5..00000000 --- a/util/src/util/Array.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function containsAll(arr: any[], target: any[]) { - return target.every((v) => arr.includes(v)); -} diff --git a/util/src/util/AutoUpdate.ts b/util/src/util/AutoUpdate.ts deleted file mode 100644 index 531bd8b7..00000000 --- a/util/src/util/AutoUpdate.ts +++ /dev/null @@ -1,84 +0,0 @@ -import "missing-native-js-functions"; -import fetch from "node-fetch"; -import ProxyAgent from 'proxy-agent'; -import readline from "readline"; -import fs from "fs/promises"; -import path from "path"; - -const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout, -}); - -export function enableAutoUpdate(opts: { - checkInterval: number | boolean; - packageJsonLink: string; - path: string; - downloadUrl: string; - downloadType?: "zip"; -}) { - if (!opts.checkInterval) return; - var interval = 1000 * 60 * 60 * 24; - if (typeof opts.checkInterval === "number") opts.checkInterval = 1000 * interval; - - const i = setInterval(async () => { - const currentVersion = await getCurrentVersion(opts.path); - const latestVersion = await getLatestVersion(opts.packageJsonLink); - if (currentVersion !== latestVersion) { - clearInterval(i); - console.log(`[Auto Update] Current version (${currentVersion}) is out of date, updating ...`); - await download(opts.downloadUrl, opts.path); - } - }, interval); - setImmediate(async () => { - const currentVersion = await getCurrentVersion(opts.path); - const latestVersion = await getLatestVersion(opts.packageJsonLink); - if (currentVersion !== latestVersion) { - rl.question( - `[Auto Update] Current version (${currentVersion}) is out of date, would you like to update? (yes/no)`, - (answer) => { - if (answer.toBoolean()) { - console.log(`[Auto update] updating ...`); - download(opts.downloadUrl, opts.path); - } else { - console.log(`[Auto update] aborted`); - } - } - ); - } - }); -} - -async function download(url: string, dir: string) { - try { - // TODO: use file stream instead of buffer (to prevent crash because of high memory usage for big files) - // TODO check file hash - const agent = new ProxyAgent(); - const response = await fetch(url, { agent }); - const buffer = await response.buffer(); - const tempDir = await fs.mkdtemp("fosscord"); - fs.writeFile(path.join(tempDir, "Fosscord.zip"), buffer); - } catch (error) { - console.error(`[Auto Update] download failed`, error); - } -} - -async function getCurrentVersion(dir: string) { - try { - const content = await fs.readFile(path.join(dir, "package.json"), { encoding: "utf8" }); - return JSON.parse(content).version; - } catch (error) { - throw new Error("[Auto update] couldn't get current version in " + dir); - } -} - -async function getLatestVersion(url: string) { - try { - const agent = new ProxyAgent(); - const response = await fetch(url, { agent }); - const content = await response.json(); - return content.version; - } catch (error) { - throw new Error("[Auto update] check failed for " + url); - } -} diff --git a/util/src/util/BitField.ts b/util/src/util/BitField.ts deleted file mode 100644 index fb887e05..00000000 --- a/util/src/util/BitField.ts +++ /dev/null @@ -1,147 +0,0 @@ -"use strict"; - -// https://github.com/discordjs/discord.js/blob/master/src/util/BitField.js -// Apache License Version 2.0 Copyright 2015 - 2021 Amish Shah - -export type BitFieldResolvable = number | BigInt | BitField | string | BitFieldResolvable[]; - -/** - * Data structure that makes it easy to interact with a bitfield. - */ -export class BitField { - public bitfield: bigint = BigInt(0); - - public static FLAGS: Record<string, bigint> = {}; - - constructor(bits: BitFieldResolvable = 0) { - this.bitfield = BitField.resolve.call(this, bits); - } - - /** - * Checks whether the bitfield has a bit, or any of multiple bits. - */ - any(bit: BitFieldResolvable): boolean { - return (this.bitfield & BitField.resolve.call(this, bit)) !== BigInt(0); - } - - /** - * Checks if this bitfield equals another - */ - equals(bit: BitFieldResolvable): boolean { - return this.bitfield === BitField.resolve.call(this, bit); - } - - /** - * Checks whether the bitfield has a bit, or multiple bits. - */ - has(bit: BitFieldResolvable): boolean { - if (Array.isArray(bit)) return bit.every((p) => this.has(p)); - const BIT = BitField.resolve.call(this, bit); - return (this.bitfield & BIT) === BIT; - } - - /** - * Gets all given bits that are missing from the bitfield. - */ - missing(bits: BitFieldResolvable) { - if (!Array.isArray(bits)) bits = new BitField(bits).toArray(); - return bits.filter((p) => !this.has(p)); - } - - /** - * Freezes these bits, making them immutable. - */ - freeze(): Readonly<BitField> { - return Object.freeze(this); - } - - /** - * Adds bits to these ones. - * @param {...BitFieldResolvable} [bits] Bits to add - * @returns {BitField} These bits or new BitField if the instance is frozen. - */ - add(...bits: BitFieldResolvable[]): BitField { - let total = BigInt(0); - for (const bit of bits) { - total |= BitField.resolve.call(this, bit); - } - if (Object.isFrozen(this)) return new BitField(this.bitfield | total); - this.bitfield |= total; - return this; - } - - /** - * Removes bits from these. - * @param {...BitFieldResolvable} [bits] Bits to remove - */ - remove(...bits: BitFieldResolvable[]) { - let total = BigInt(0); - for (const bit of bits) { - total |= BitField.resolve.call(this, bit); - } - if (Object.isFrozen(this)) return new BitField(this.bitfield & ~total); - this.bitfield &= ~total; - return this; - } - - /** - * Gets an object mapping field names to a {@link boolean} indicating whether the - * bit is available. - * @param {...*} hasParams Additional parameters for the has method, if any - */ - serialize() { - const serialized: Record<string, boolean> = {}; - for (const [flag, bit] of Object.entries(BitField.FLAGS)) serialized[flag] = this.has(bit); - return serialized; - } - - /** - * Gets an {@link Array} of bitfield names based on the bits available. - */ - toArray(): string[] { - return Object.keys(BitField.FLAGS).filter((bit) => this.has(bit)); - } - - toJSON() { - return this.bitfield; - } - - valueOf() { - return this.bitfield; - } - - *[Symbol.iterator]() { - yield* this.toArray(); - } - - /** - * Data that can be resolved to give a bitfield. This can be: - * * A bit number (this can be a number literal or a value taken from {@link BitField.FLAGS}) - * * An instance of BitField - * * An Array of BitFieldResolvable - * @typedef {number|BitField|BitFieldResolvable[]} BitFieldResolvable - */ - - /** - * Resolves bitfields to their numeric form. - * @param {BitFieldResolvable} [bit=0] - bit(s) to resolve - * @returns {number} - */ - static resolve(bit: BitFieldResolvable = BigInt(0)): bigint { - // @ts-ignore - const FLAGS = this.FLAGS || this.constructor?.FLAGS; - if ((typeof bit === "number" || typeof bit === "bigint") && bit >= BigInt(0)) return BigInt(bit); - if (bit instanceof BitField) return bit.bitfield; - if (Array.isArray(bit)) { - // @ts-ignore - const resolve = this.constructor?.resolve || this.resolve; - return bit.map((p) => resolve.call(this, p)).reduce((prev, p) => BigInt(prev) | BigInt(p), BigInt(0)); - } - if (typeof bit === "string" && typeof FLAGS[bit] !== "undefined") return FLAGS[bit]; - throw new RangeError("BITFIELD_INVALID: " + bit); - } -} - -export function BitFlag(x: bigint | number) { - return BigInt(1) << BigInt(x); -} diff --git a/util/src/util/Categories.ts b/util/src/util/Categories.ts deleted file mode 100644 index a3c69da7..00000000 --- a/util/src/util/Categories.ts +++ /dev/null @@ -1 +0,0 @@ -//TODO: populate default discord categories + init, get and set methods \ No newline at end of file diff --git a/util/src/util/Config.ts b/util/src/util/Config.ts deleted file mode 100644 index 31b8d97c..00000000 --- a/util/src/util/Config.ts +++ /dev/null @@ -1,81 +0,0 @@ -import "missing-native-js-functions"; -import { ConfigValue, ConfigEntity, DefaultConfigOptions } from "../entities/Config"; -import path from "path"; -import fs from "fs"; - -// TODO: yaml instead of json -// const overridePath = path.join(process.cwd(), "config.json"); - -var config: ConfigValue; -var pairs: ConfigEntity[]; - -// TODO: use events to inform about config updates -// Config keys are separated with _ - -export const Config = { - init: async function init() { - if (config) return config; - pairs = await ConfigEntity.find(); - config = pairsToConfig(pairs); - config = (config || {}).merge(DefaultConfigOptions); - - // 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() { - return config; - }, - set: function set(val: Partial<ConfigValue>) { - if (!config || !val) return; - config = val.merge(config); - - return applyConfig(config); - }, -}; - -function applyConfig(val: ConfigValue) { - async function apply(obj: any, key = ""): Promise<any> { - if (typeof obj === "object" && obj !== null) - return Promise.all(Object.keys(obj).map((k) => apply(obj[k], key ? `${key}_${k}` : k))); - - let pair = pairs.find((x) => x.key === key); - if (!pair) pair = new ConfigEntity(); - - pair.key = key; - pair.value = obj; - return pair.save(); - } - // fs.writeFileSync(overridePath, JSON.stringify(val, null, 4)); - - return apply(val); -} - -function pairsToConfig(pairs: ConfigEntity[]) { - var value: any = {}; - - pairs.forEach((p) => { - const keys = p.key.split("_"); - let obj = value; - let prev = ""; - let prevObj = obj; - let i = 0; - - for (const key of keys) { - if (!isNaN(Number(key)) && !prevObj[prev]?.length) prevObj[prev] = obj = []; - if (i++ === keys.length - 1) obj[key] = p.value; - else if (!obj[key]) obj[key] = {}; - - prev = key; - prevObj = obj; - obj = obj[key]; - } - }); - - return value as ConfigValue; -} diff --git a/util/src/util/Constants.ts b/util/src/util/Constants.ts deleted file mode 100644 index a5d3fcd2..00000000 --- a/util/src/util/Constants.ts +++ /dev/null @@ -1,792 +0,0 @@ -import { ApiError } from "./ApiError"; - -export const WSCodes = { - 1000: "WS_CLOSE_REQUESTED", - 4004: "TOKEN_INVALID", - 4010: "SHARDING_INVALID", - 4011: "SHARDING_REQUIRED", - 4013: "INVALID_INTENTS", - 4014: "DISALLOWED_INTENTS", -}; - -/** - * The current status of the client. Here are the available statuses: - * * READY: 0 - * * CONNECTING: 1 - * * RECONNECTING: 2 - * * IDLE: 3 - * * NEARLY: 4 - * * DISCONNECTED: 5 - * * WAITING_FOR_GUILDS: 6 - * * IDENTIFYING: 7 - * * RESUMING: 8 - * @typedef {number} Status - */ -export const WsStatus = { - READY: 0, - CONNECTING: 1, - RECONNECTING: 2, - IDLE: 3, - NEARLY: 4, - DISCONNECTED: 5, - WAITING_FOR_GUILDS: 6, - IDENTIFYING: 7, - RESUMING: 8, -}; - -/** - * The current status of a voice connection. Here are the available statuses: - * * CONNECTED: 0 - * * CONNECTING: 1 - * * AUTHENTICATING: 2 - * * RECONNECTING: 3 - * * DISCONNECTED: 4 - * @typedef {number} VoiceStatus - */ -export const VoiceStatus = { - CONNECTED: 0, - CONNECTING: 1, - AUTHENTICATING: 2, - RECONNECTING: 3, - DISCONNECTED: 4, -}; - -export const OPCodes = { - DISPATCH: 0, - HEARTBEAT: 1, - IDENTIFY: 2, - STATUS_UPDATE: 3, - VOICE_STATE_UPDATE: 4, - VOICE_GUILD_PING: 5, - RESUME: 6, - RECONNECT: 7, - REQUEST_GUILD_MEMBERS: 8, - INVALID_SESSION: 9, - HELLO: 10, - HEARTBEAT_ACK: 11, -}; - -export const VoiceOPCodes = { - IDENTIFY: 0, - SELECT_PROTOCOL: 1, - READY: 2, - HEARTBEAT: 3, - SESSION_DESCRIPTION: 4, - SPEAKING: 5, - HELLO: 8, - CLIENT_CONNECT: 12, - CLIENT_DISCONNECT: 13, -}; - -export const Events = { - RATE_LIMIT: "rateLimit", - CLIENT_READY: "ready", - GUILD_CREATE: "guildCreate", - GUILD_DELETE: "guildDelete", - GUILD_UPDATE: "guildUpdate", - GUILD_UNAVAILABLE: "guildUnavailable", - GUILD_AVAILABLE: "guildAvailable", - GUILD_MEMBER_ADD: "guildMemberAdd", - GUILD_MEMBER_REMOVE: "guildMemberRemove", - GUILD_MEMBER_UPDATE: "guildMemberUpdate", - GUILD_MEMBER_AVAILABLE: "guildMemberAvailable", - GUILD_MEMBER_SPEAKING: "guildMemberSpeaking", - GUILD_MEMBERS_CHUNK: "guildMembersChunk", - GUILD_INTEGRATIONS_UPDATE: "guildIntegrationsUpdate", - GUILD_ROLE_CREATE: "roleCreate", - GUILD_ROLE_DELETE: "roleDelete", - INVITE_CREATE: "inviteCreate", - INVITE_DELETE: "inviteDelete", - GUILD_ROLE_UPDATE: "roleUpdate", - GUILD_EMOJI_CREATE: "emojiCreate", - GUILD_EMOJI_DELETE: "emojiDelete", - GUILD_EMOJI_UPDATE: "emojiUpdate", - GUILD_BAN_ADD: "guildBanAdd", - GUILD_BAN_REMOVE: "guildBanRemove", - CHANNEL_CREATE: "channelCreate", - CHANNEL_DELETE: "channelDelete", - CHANNEL_UPDATE: "channelUpdate", - CHANNEL_PINS_UPDATE: "channelPinsUpdate", - MESSAGE_CREATE: "message", - MESSAGE_DELETE: "messageDelete", - MESSAGE_UPDATE: "messageUpdate", - MESSAGE_BULK_DELETE: "messageDeleteBulk", - MESSAGE_REACTION_ADD: "messageReactionAdd", - MESSAGE_REACTION_REMOVE: "messageReactionRemove", - MESSAGE_REACTION_REMOVE_ALL: "messageReactionRemoveAll", - MESSAGE_REACTION_REMOVE_EMOJI: "messageReactionRemoveEmoji", - USER_UPDATE: "userUpdate", - PRESENCE_UPDATE: "presenceUpdate", - VOICE_SERVER_UPDATE: "voiceServerUpdate", - VOICE_STATE_UPDATE: "voiceStateUpdate", - VOICE_BROADCAST_SUBSCRIBE: "subscribe", - VOICE_BROADCAST_UNSUBSCRIBE: "unsubscribe", - TYPING_START: "typingStart", - TYPING_STOP: "typingStop", - WEBHOOKS_UPDATE: "webhookUpdate", - ERROR: "error", - WARN: "warn", - DEBUG: "debug", - SHARD_DISCONNECT: "shardDisconnect", - SHARD_ERROR: "shardError", - SHARD_RECONNECTING: "shardReconnecting", - SHARD_READY: "shardReady", - SHARD_RESUME: "shardResume", - INVALIDATED: "invalidated", - RAW: "raw", -}; - -export const ShardEvents = { - CLOSE: "close", - DESTROYED: "destroyed", - INVALID_SESSION: "invalidSession", - READY: "ready", - RESUMED: "resumed", - ALL_READY: "allReady", -}; - -/** - * The type of Structure allowed to be a partial: - * * USER - * * CHANNEL (only affects DMChannels) - * * GUILD_MEMBER - * * MESSAGE - * * REACTION - * <warn>Partials require you to put checks in place when handling data, read the Partials topic listed in the - * sidebar for more information.</warn> - * @typedef {string} PartialType - */ -export const PartialTypes = keyMirror(["USER", "CHANNEL", "GUILD_MEMBER", "MESSAGE", "REACTION"]); - -/** - * The type of a websocket message event, e.g. `MESSAGE_CREATE`. Here are the available events: - * * READY - * * RESUMED - * * GUILD_CREATE - * * GUILD_DELETE - * * GUILD_UPDATE - * * INVITE_CREATE - * * INVITE_DELETE - * * GUILD_MEMBER_ADD - * * GUILD_MEMBER_REMOVE - * * GUILD_MEMBER_UPDATE - * * GUILD_MEMBERS_CHUNK - * * GUILD_INTEGRATIONS_UPDATE - * * GUILD_ROLE_CREATE - * * GUILD_ROLE_DELETE - * * GUILD_ROLE_UPDATE - * * GUILD_BAN_ADD - * * GUILD_BAN_REMOVE - * * GUILD_EMOJIS_UPDATE - * * CHANNEL_CREATE - * * CHANNEL_DELETE - * * CHANNEL_UPDATE - * * CHANNEL_PINS_UPDATE - * * MESSAGE_CREATE - * * MESSAGE_DELETE - * * MESSAGE_UPDATE - * * MESSAGE_DELETE_BULK - * * MESSAGE_REACTION_ADD - * * MESSAGE_REACTION_REMOVE - * * MESSAGE_REACTION_REMOVE_ALL - * * MESSAGE_REACTION_REMOVE_EMOJI - * * USER_UPDATE - * * PRESENCE_UPDATE - * * TYPING_START - * * VOICE_STATE_UPDATE - * * VOICE_SERVER_UPDATE - * * WEBHOOKS_UPDATE - * @typedef {string} WSEventType - */ -export const WSEvents = keyMirror([ - "READY", - "RESUMED", - "GUILD_CREATE", - "GUILD_DELETE", - "GUILD_UPDATE", - "INVITE_CREATE", - "INVITE_DELETE", - "GUILD_MEMBER_ADD", - "GUILD_MEMBER_REMOVE", - "GUILD_MEMBER_UPDATE", - "GUILD_MEMBERS_CHUNK", - "GUILD_INTEGRATIONS_UPDATE", - "GUILD_ROLE_CREATE", - "GUILD_ROLE_DELETE", - "GUILD_ROLE_UPDATE", - "GUILD_BAN_ADD", - "GUILD_BAN_REMOVE", - "GUILD_EMOJIS_UPDATE", - "CHANNEL_CREATE", - "CHANNEL_DELETE", - "CHANNEL_UPDATE", - "CHANNEL_PINS_UPDATE", - "MESSAGE_CREATE", - "MESSAGE_DELETE", - "MESSAGE_UPDATE", - "MESSAGE_DELETE_BULK", - "MESSAGE_REACTION_ADD", - "MESSAGE_REACTION_REMOVE", - "MESSAGE_REACTION_REMOVE_ALL", - "MESSAGE_REACTION_REMOVE_EMOJI", - "USER_UPDATE", - "PRESENCE_UPDATE", - "TYPING_START", - "VOICE_STATE_UPDATE", - "VOICE_SERVER_UPDATE", - "WEBHOOKS_UPDATE", -]); - -/** - * The type of a message, e.g. `DEFAULT`. Here are the available types: - * * DEFAULT - * * RECIPIENT_ADD - * * RECIPIENT_REMOVE - * * CALL - * * CHANNEL_NAME_CHANGE - * * CHANNEL_ICON_CHANGE - * * PINS_ADD - * * GUILD_MEMBER_JOIN - * * USER_PREMIUM_GUILD_SUBSCRIPTION - * * USER_PREMIUM_GUILD_SUBSCRIPTION_TIER_1 - * * USER_PREMIUM_GUILD_SUBSCRIPTION_TIER_2 - * * USER_PREMIUM_GUILD_SUBSCRIPTION_TIER_3 - * * CHANNEL_FOLLOW_ADD - * * GUILD_DISCOVERY_DISQUALIFIED - * * GUILD_DISCOVERY_REQUALIFIED - * * REPLY - * @typedef {string} MessageType - */ -export const MessageTypes = [ - "DEFAULT", - "RECIPIENT_ADD", - "RECIPIENT_REMOVE", - "CALL", - "CHANNEL_NAME_CHANGE", - "CHANNEL_ICON_CHANGE", - "PINS_ADD", - "GUILD_MEMBER_JOIN", - "USER_PREMIUM_GUILD_SUBSCRIPTION", - "USER_PREMIUM_GUILD_SUBSCRIPTION_TIER_1", - "USER_PREMIUM_GUILD_SUBSCRIPTION_TIER_2", - "USER_PREMIUM_GUILD_SUBSCRIPTION_TIER_3", - "CHANNEL_FOLLOW_ADD", - null, - "GUILD_DISCOVERY_DISQUALIFIED", - "GUILD_DISCOVERY_REQUALIFIED", - null, - null, - null, - "REPLY", -]; - -/** - * The types of messages that are `System`. The available types are `MessageTypes` excluding: - * * DEFAULT - * * REPLY - * @typedef {string} SystemMessageType - */ -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> - * The type of an activity of a users presence, e.g. `PLAYING`. Here are the available types: - * * PLAYING - * * STREAMING - * * LISTENING - * * WATCHING - * * CUSTOM_STATUS - * * COMPETING - * @typedef {string} ActivityType - */ -export const ActivityTypes = ["PLAYING", "STREAMING", "LISTENING", "WATCHING", "CUSTOM_STATUS", "COMPETING"]; - -export const ChannelTypes = { - TEXT: 0, - DM: 1, - VOICE: 2, - GROUP: 3, - CATEGORY: 4, - NEWS: 5, - STORE: 6, -}; - -export const ClientApplicationAssetTypes = { - SMALL: 1, - BIG: 2, -}; - -export const Colors = { - DEFAULT: 0x000000, - WHITE: 0xffffff, - AQUA: 0x1abc9c, - GREEN: 0x2ecc71, - BLUE: 0x3498db, - YELLOW: 0xffff00, - PURPLE: 0x9b59b6, - LUMINOUS_VIVID_PINK: 0xe91e63, - GOLD: 0xf1c40f, - ORANGE: 0xe67e22, - RED: 0xe74c3c, - GREY: 0x95a5a6, - NAVY: 0x34495e, - DARK_AQUA: 0x11806a, - DARK_GREEN: 0x1f8b4c, - DARK_BLUE: 0x206694, - DARK_PURPLE: 0x71368a, - DARK_VIVID_PINK: 0xad1457, - DARK_GOLD: 0xc27c0e, - DARK_ORANGE: 0xa84300, - DARK_RED: 0x992d22, - DARK_GREY: 0x979c9f, - DARKER_GREY: 0x7f8c8d, - LIGHT_GREY: 0xbcc0c0, - DARK_NAVY: 0x2c3e50, - BLURPLE: 0x7289da, - GREYPLE: 0x99aab5, - DARK_BUT_NOT_BLACK: 0x2c2f33, - NOT_QUITE_BLACK: 0x23272a, -}; - -/** - * The value set for the explicit content filter levels for a guild: - * * DISABLED - * * MEMBERS_WITHOUT_ROLES - * * ALL_MEMBERS - * @typedef {string} ExplicitContentFilterLevel - */ -export const ExplicitContentFilterLevels = ["DISABLED", "MEMBERS_WITHOUT_ROLES", "ALL_MEMBERS"]; - -/** - * The value set for the verification levels for a guild: - * * NONE - * * LOW - * * MEDIUM - * * HIGH - * * VERY_HIGH - * @typedef {string} VerificationLevel - */ -export const VerificationLevels = ["NONE", "LOW", "MEDIUM", "HIGH", "VERY_HIGH"]; - -/** - * An error encountered while performing an API request. Here are the potential errors: - * * GENERAL_ERROR - * * UNKNOWN_ACCOUNT - * * UNKNOWN_APPLICATION - * * UNKNOWN_CHANNEL - * * UNKNOWN_GUILD - * * UNKNOWN_INTEGRATION - * * UNKNOWN_INVITE - * * UNKNOWN_MEMBER - * * UNKNOWN_MESSAGE - * * UNKNOWN_OVERWRITE - * * UNKNOWN_PROVIDER - * * UNKNOWN_ROLE - * * UNKNOWN_TOKEN - * * UNKNOWN_USER - * * UNKNOWN_EMOJI - * * UNKNOWN_WEBHOOK - * * UNKNOWN_WEBHOOK_SERVICE - * * UNKNOWN_SESSION - * * UNKNOWN_BAN - * * UNKNOWN_SKU - * * UNKNOWN_STORE_LISTING - * * UNKNOWN_ENTITLEMENT - * * UNKNOWN_BUILD - * * UNKNOWN_LOBBY - * * UNKNOWN_BRANCH - * * UNKNOWN_STORE_DIRECTORY_LAYOUT - * * UNKNOWN_REDISTRIBUTABLE - * * UNKNOWN_GIFT_CODE - * * UNKNOWN_STREAM - * * UNKNOWN_PREMIUM_SERVER_SUBSCRIBE_COOLDOWN - * * UNKNOWN_GUILD_TEMPLATE - * * UNKNOWN_DISCOVERABLE_SERVER_CATEGORY - * * UNKNOWN_STICKER - * * UNKNOWN_INTERACTION - * * UNKNOWN_APPLICATION_COMMAND - * * UNKNOWN_APPLICATION_COMMAND_PERMISSIONS - * * UNKNOWN_STAGE_INSTANCE - * * UNKNOWN_GUILD_MEMBER_VERIFICATION_FORM - * * UNKNOWN_GUILD_WELCOME_SCREEN - * * UNKNOWN_GUILD_SCHEDULED_EVENT - * * UNKNOWN_GUILD_SCHEDULED_EVENT_USER - * * BOT_PROHIBITED_ENDPOINT - * * BOT_ONLY_ENDPOINT - * * EXPLICIT_CONTENT_CANNOT_BE_SENT_TO_RECIPIENT - * * ACTION_NOT_AUTHORIZED_ON_APPLICATION - * * SLOWMODE_RATE_LIMIT - * * ONLY_OWNER - * * ANNOUNCEMENT_RATE_LIMITS - * * CHANNEL_WRITE_RATELIMIT - * * WORDS_NOT_ALLOWED - * * GUILD_PREMIUM_LEVEL_TOO_LOW - * * MAXIMUM_GUILDS - * * MAXIMUM_FRIENDS - * * MAXIMUM_PINS - * * MAXIMUM_NUMBER_OF_RECIPIENTS_REACHED - * * MAXIMUM_ROLES - * * MAXIMUM_WEBHOOKS - * * MAXIMUM_NUMBER_OF_EMOJIS_REACHED - * * MAXIMUM_REACTIONS - * * MAXIMUM_CHANNELS - * * MAXIMUM_ATTACHMENTS - * * MAXIMUM_INVITES - * * MAXIMUM_ANIMATED_EMOJIS - * * MAXIMUM_SERVER_MEMBERS - * * MAXIMUM_SERVER_CATEGORIES - * * GUILD_ALREADY_HAS_TEMPLATE - * * MAXIMUM_THREAD_PARTICIPANTS - * * MAXIMUM_BANS_FOR_NON_GUILD_MEMBERS - * * MAXIMUM_BANS_FETCHES - * * MAXIMUM_STICKERS - * * MAXIMUM_PRUNE_REQUESTS - * * UNAUTHORIZED - * * ACCOUNT_VERIFICATION_REQUIRED - * * OPENING_DIRECT_MESSAGES_TOO_FAST - * * REQUEST_ENTITY_TOO_LARGE - * * FEATURE_TEMPORARILY_DISABLED - * * USER_BANNED - * * TARGET_USER_IS_NOT_CONNECTED_TO_VOICE - * * ALREADY_CROSSPOSTED - * * APPLICATION_COMMAND_ALREADY_EXISTS - * * MISSING_ACCESS - * * INVALID_ACCOUNT_TYPE - * * CANNOT_EXECUTE_ON_DM - * * EMBED_DISABLED - * * CANNOT_EDIT_MESSAGE_BY_OTHER - * * CANNOT_SEND_EMPTY_MESSAGE - * * CANNOT_MESSAGE_USER - * * CANNOT_SEND_MESSAGES_IN_VOICE_CHANNEL - * * CHANNEL_VERIFICATION_LEVEL_TOO_HIGH - * * OAUTH2_APPLICATION_BOT_ABSENT - * * MAXIMUM_OAUTH2_APPLICATIONS - * * INVALID_OAUTH_STATE - * * MISSING_PERMISSIONS - * * INVALID_AUTHENTICATION_TOKEN - * * NOTE_TOO_LONG - * * INVALID_BULK_DELETE_QUANTITY - * * CANNOT_PIN_MESSAGE_IN_OTHER_CHANNEL - * * INVALID_OR_TAKEN_INVITE_CODE - * * CANNOT_EXECUTE_ON_SYSTEM_MESSAGE - * * CANNOT_EXECUTE_ON_THIS_CHANNEL_TYPE - * * INVALID_OAUTH_TOKEN - * * MISSING_REQUIRED_OAUTH2_SCOPE - * * INVALID_WEBHOOK_TOKEN_PROVIDED - * * INVALID_ROLE - * * INVALID_RECIPIENT - * * BULK_DELETE_MESSAGE_TOO_OLD - * * INVALID_FORM_BODY - * * INVITE_ACCEPTED_TO_GUILD_NOT_CONTAINING_BOT - * * INVALID_API_VERSION - * * FILE_EXCEEDS_MAXIMUM_SIZE - * * INVALID_FILE_UPLOADED - * * CANNOT_SELF_REDEEM_GIFT - * * PAYMENT_SOURCE_REQUIRED - * * CANNOT_DELETE_COMMUNITY_REQUIRED_CHANNEL - * * INVALID_STICKER_SENT - * * CANNOT_EDIT_ARCHIVED_THREAD - * * INVALID_THREAD_NOTIFICATION_SETTINGS - * * BEFORE_EARLIER_THAN_THREAD_CREATION_DATE - * * SERVER_NOT_AVAILABLE_IN_YOUR_LOCATION - * * SERVER_NEEDS_MONETIZATION_ENABLED - * * TWO_FACTOR_REQUIRED - * * NO_USERS_WITH_DISCORDTAG_EXIST - * * REACTION_BLOCKED - * * RESOURCE_OVERLOADED - * * STAGE_ALREADY_OPEN - * * THREAD_ALREADY_CREATED_FOR_THIS_MESSAGE - * * THREAD_IS_LOCKED - * * MAXIMUM_NUMBER_OF_ACTIVE_THREADS - * * MAXIMUM_NUMBER_OF_ACTIVE_ANNOUNCEMENT_THREADS - * * INVALID_JSON_FOR_UPLOADED_LOTTIE_FILE - * * LOTTIES_CANNOT_CONTAIN_RASTERIZED_IMAGES - * * STICKER_MAXIMUM_FRAMERATE - * * STICKER_MAXIMUM_FRAME_COUNT - * * LOTTIE_ANIMATION_MAXIMUM_DIMENSIONS - * * STICKER_FRAME_RATE_TOO_SMALL_OR_TOO_LARGE - * * STICKER_ANIMATION_DURATION_MAXIMUM - * * UNKNOWN_VOICE_STATE - * @typedef {string} APIError - */ -export const DiscordApiErrors = { - //https://discord.com/developers/docs/topics/opcodes-and-status-codes#json-json-error-codes - GENERAL_ERROR: new ApiError("General error (such as a malformed request body, amongst other things)", 0), - UNKNOWN_ACCOUNT: new ApiError("Unknown account", 10001), - UNKNOWN_APPLICATION: new ApiError("Unknown application", 10002), - UNKNOWN_CHANNEL: new ApiError("Unknown channel", 10003), - UNKNOWN_GUILD: new ApiError("Unknown guild", 10004), - UNKNOWN_INTEGRATION: new ApiError("Unknown integration", 10005), - UNKNOWN_INVITE: new ApiError("Unknown invite", 10006), - UNKNOWN_MEMBER: new ApiError("Unknown member", 10007), - UNKNOWN_MESSAGE: new ApiError("Unknown message", 10008), - UNKNOWN_OVERWRITE: new ApiError("Unknown permission overwrite", 10009), - UNKNOWN_PROVIDER: new ApiError("Unknown provider", 10010), - UNKNOWN_ROLE: new ApiError("Unknown role", 10011), - UNKNOWN_TOKEN: new ApiError("Unknown token", 10012), - UNKNOWN_USER: new ApiError("Unknown user", 10013), - UNKNOWN_EMOJI: new ApiError("Unknown emoji", 10014), - UNKNOWN_WEBHOOK: new ApiError("Unknown webhook", 10015), - UNKNOWN_WEBHOOK_SERVICE: new ApiError("Unknown webhook service", 10016), - UNKNOWN_SESSION: new ApiError("Unknown session", 10020), - UNKNOWN_BAN: new ApiError("Unknown ban", 10026), - UNKNOWN_SKU: new ApiError("Unknown SKU", 10027), - UNKNOWN_STORE_LISTING: new ApiError("Unknown Store Listing", 10028), - UNKNOWN_ENTITLEMENT: new ApiError("Unknown entitlement", 10029), - UNKNOWN_BUILD: new ApiError("Unknown build", 10030), - UNKNOWN_LOBBY: new ApiError("Unknown lobby", 10031), - UNKNOWN_BRANCH: new ApiError("Unknown branch", 10032), - UNKNOWN_STORE_DIRECTORY_LAYOUT: new ApiError("Unknown store directory layout", 10033), - UNKNOWN_REDISTRIBUTABLE: new ApiError("Unknown redistributable", 10036), - UNKNOWN_GIFT_CODE: new ApiError("Unknown gift code", 10038), - UNKNOWN_STREAM: new ApiError("Unknown stream", 10049), - UNKNOWN_PREMIUM_SERVER_SUBSCRIBE_COOLDOWN: new ApiError("Unknown premium server subscribe cooldown", 10050), - UNKNOWN_GUILD_TEMPLATE: new ApiError("Unknown guild template", 10057), - UNKNOWN_DISCOVERABLE_SERVER_CATEGORY: new ApiError("Unknown discoverable server category", 10059), - UNKNOWN_STICKER: new ApiError("Unknown sticker", 10060), - UNKNOWN_INTERACTION: new ApiError("Unknown interaction", 10062), - UNKNOWN_APPLICATION_COMMAND: new ApiError("Unknown application command", 10063), - UNKNOWN_APPLICATION_COMMAND_PERMISSIONS: new ApiError("Unknown application command permissions", 10066), - UNKNOWN_STAGE_INSTANCE: new ApiError("Unknown Stage Instance", 10067), - UNKNOWN_GUILD_MEMBER_VERIFICATION_FORM: new ApiError("Unknown Guild Member Verification Form", 10068), - UNKNOWN_GUILD_WELCOME_SCREEN: new ApiError("Unknown Guild Welcome Screen", 10069), - UNKNOWN_GUILD_SCHEDULED_EVENT: new ApiError("Unknown Guild Scheduled Event", 10070), - 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 - ), - 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), - CHANNEL_WRITE_RATELIMIT: new ApiError("The channel you are writing has hit the write rate limit", 20028), - WORDS_NOT_ALLOWED: new ApiError( - "Your Stage topic, server name, server description, or channel names contain words that are not allowed", - 20031 - ), - GUILD_PREMIUM_LEVEL_TOO_LOW: new ApiError("Guild premium subscription level too low", 20035), - 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_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_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"] - ), - 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_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 - ), - 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), - USER_BANNED: new ApiError("The user is banned from this guild", 40007), - TARGET_USER_IS_NOT_CONNECTED_TO_VOICE: new ApiError("Target user is not connected to voice", 40032), - ALREADY_CROSSPOSTED: new ApiError("This message has already been crossposted", 40033), - APPLICATION_COMMAND_ALREADY_EXISTS: new ApiError("An application command with that name already exists", 40041), - MISSING_ACCESS: new ApiError("Missing access", 50001), - INVALID_ACCOUNT_TYPE: new ApiError("Invalid account type", 50002), - CANNOT_EXECUTE_ON_DM: new ApiError("Cannot execute action on a DM channel", 50003), - EMBED_DISABLED: new ApiError("Guild widget disabled", 50004), - CANNOT_EDIT_MESSAGE_BY_OTHER: new ApiError("Cannot edit a message authored by another user", 50005), - 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 - ), - 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), - MISSING_PERMISSIONS: new ApiError("You lack permissions to perform that action ({})", 50013, undefined, [""]), - INVALID_AUTHENTICATION_TOKEN: new ApiError("Invalid authentication token provided", 50014), - NOTE_TOO_LONG: new ApiError("Note was too long", 50015), - INVALID_BULK_DELETE_QUANTITY: new ApiError( - "Provided too few or too many messages to delete. Must provide at least {} and fewer than {} messages to delete", - 50016, - 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 - ), - 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), - INVALID_OAUTH_TOKEN: new ApiError("Invalid OAuth2 access token provided", 50025), - MISSING_REQUIRED_OAUTH2_SCOPE: new ApiError("Missing required OAuth2 scope", 50026), - INVALID_WEBHOOK_TOKEN_PROVIDED: new ApiError("Invalid webhook token provided", 50027), - INVALID_ROLE: new ApiError("Invalid role", 50028), - INVALID_RECIPIENT: new ApiError("Invalid Recipient(s)", 50033), - BULK_DELETE_MESSAGE_TOO_OLD: new ApiError("A message provided was too old to bulk delete", 50034), - INVALID_FORM_BODY: new ApiError( - "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 - ), - 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 - ), - 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 - ), - 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 - ), - 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), - RESOURCE_OVERLOADED: new ApiError("API resource is currently overloaded. Try again a little later", 130000), - STAGE_ALREADY_OPEN: new ApiError("The Stage is already open", 150006), - 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 - ), - 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 - ), - 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", - ]), - 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"] - ), - - //Other errors - UNKNOWN_VOICE_STATE: new ApiError("Unknown Voice State", 10065, 404), -}; - -/** - * An error encountered while performing an API request (Fosscord only). Here are the potential errors: - */ -export const FosscordApiErrors = { - MANUALLY_TRIGGERED_ERROR: new ApiError("This is an artificial error", 1, 500), - PREMIUM_DISABLED_FOR_GUILD: new ApiError("This guild cannot be boosted", 25001), - NO_FURTHER_PREMIUM: new ApiError("This guild does not receive further boosts", 25002), - GUILD_PREMIUM_DISABLED_FOR_YOU: new ApiError("This guild cannot be boosted by you", 25003, 403), - CANNOT_FRIEND_SELF: new ApiError("Cannot friend oneself", 25009), - USER_SPECIFIC_INVITE_WRONG_RECIPIENT: new ApiError("This invite is not meant for you", 25010), - USER_SPECIFIC_INVITE_FAILED: new ApiError("Failed to invite user", 25011), - CANNOT_MODIFY_USER_GROUP: new ApiError("This user cannot manipulate this group", 25050, 403), - CANNOT_REMOVE_SELF_FROM_GROUP: new ApiError("This user cannot remove oneself from user group", 25051), - CANNOT_BAN_OPERATOR: new ApiError("Non-OPERATOR cannot ban OPERATOR from instance", 25052), - CANNOT_LEAVE_GUILD: new ApiError("You are not allowed to leave guilds that you joined by yourself", 25059, 403), - EDITS_DISABLED: new ApiError("You are not allowed to edit your own messages", 25060, 403), - DELETE_MESSAGE_DISABLED: new ApiError("You are not allowed to delete your own messages", 25061, 403), - FEATURE_PERMANENTLY_DISABLED: new ApiError("This feature has been disabled server-side", 45006, 501), - MISSING_RIGHTS: new ApiError("You lack rights to perform that action ({})", 50013, undefined, [""]), - CANNOT_REPLACE_BY_BACKFILL: new ApiError("Cannot backfill to message ID that already exists", 55002, 409), - 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), -}; - -/** - * The value set for a guild's default message notifications, e.g. `ALL`. Here are the available types: - * * ALL - * * MENTIONS - * * MUTED (Fosscord extension) - * @typedef {string} DefaultMessageNotifications - */ -export const DefaultMessageNotifications = ["ALL", "MENTIONS", "MUTED"]; - -/** - * The value set for a team members's membership state: - * * INVITED - * * ACCEPTED - * * INSERTED (Fosscord extension) - * @typedef {string} MembershipStates - */ -export const MembershipStates = [ - "INSERTED", - "INVITED", - "ACCEPTED", -]; - -/** - * The value set for a webhook's type: - * * Incoming - * * Channel Follower - * * Custom (Fosscord extension) - * @typedef {string} WebhookTypes - */ -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/util/src/util/Database.ts b/util/src/util/Database.ts deleted file mode 100644 index 9ab5d14c..00000000 --- a/util/src/util/Database.ts +++ /dev/null @@ -1,72 +0,0 @@ -import path from "path"; -import "reflect-metadata"; -import { Connection, createConnection } from "typeorm"; -import * as Models from "../entities"; -import { Migration } from "../entities/Migration"; -import { yellow, green, red } from "picocolors"; - -// 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 - -var promise: Promise<any>; -var dbConnection: Connection | undefined; -let dbConnectionString = process.env.DATABASE || path.join(process.cwd(), "database.db"); - -export function initDatabase(): Promise<Connection> { - if (promise) return promise; // prevent initalizing multiple times - - const type = dbConnectionString.includes("://") ? dbConnectionString.split(":")[0]?.replace("+srv", "") : "sqlite"; - const isSqlite = type.includes("sqlite"); - - console.log(`[Database] ${yellow(`connecting to ${type} db`)}`); - if(isSqlite) { - console.log(`[Database] ${red(`You are running sqlite! Please keep in mind that we recommend setting up a dedicated database!`)}`); - } - // @ts-ignore - promise = createConnection({ - type, - charset: 'utf8mb4', - url: isSqlite ? undefined : dbConnectionString, - database: isSqlite ? dbConnectionString : undefined, - // @ts-ignore - entities: Object.values(Models).filter((x) => x.constructor.name !== "Object" && x.name), - synchronize: type !== "mongodb", - logging: false, - cache: { - duration: 1000 * 3, // cache all find queries for 3 seconds - }, - bigNumberStrings: false, - supportBigNumbers: true, - name: "default", - migrations: [path.join(__dirname, "..", "migrations", "*.js")], - }); - - promise.then(async (connection: Connection) => { - dbConnection = connection; - - // run migrations, and if it is a new fresh database, set it to the last migration - if (connection.migrations.length) { - if (!(await Migration.findOne({}))) { - let i = 0; - - await Migration.insert( - connection.migrations.map((x) => ({ - id: i++, - name: x.name, - timestamp: Date.now(), - })) - ); - } - } - await connection.runMigrations(); - console.log(`[Database] ${green("connected")}`); - }); - - return promise; -} - -export { dbConnection }; - -export function closeDatabase() { - dbConnection?.close(); -} diff --git a/util/src/util/Email.ts b/util/src/util/Email.ts deleted file mode 100644 index 6885da33..00000000 --- a/util/src/util/Email.ts +++ /dev/null @@ -1,25 +0,0 @@ -export const EMAIL_REGEX = - /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; - -export function adjustEmail(email?: string): string | undefined { - if (!email) return email; - // body parser already checked if it is a valid email - const parts = <RegExpMatchArray>email.match(EMAIL_REGEX); - // @ts-ignore - if (!parts || parts.length < 5) return undefined; - const domain = parts[5]; - const user = parts[1]; - - // TODO: check accounts with uncommon email domains - if (domain === "gmail.com" || domain === "googlemail.com") { - // 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"; - } - - return email; -} diff --git a/util/src/util/Event.ts b/util/src/util/Event.ts deleted file mode 100644 index bb624051..00000000 --- a/util/src/util/Event.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { Channel } from "amqplib"; -import { RabbitMQ } from "./RabbitMQ"; -import EventEmitter from "events"; -import { EVENT, Event } from "../interfaces"; -export const events = new EventEmitter(); - -export async function emitEvent(payload: Omit<Event, "created_at">) { - const id = (payload.channel_id || payload.user_id || payload.guild_id) as string; - if (!id) return console.error("event doesn't contain any id", payload); - - if (RabbitMQ.connection) { - const data = typeof payload.data === "object" ? JSON.stringify(payload.data) : payload.data; // use rabbitmq for event transmission - await RabbitMQ.channel?.assertExchange(id, "fanout", { durable: false }); - - // assertQueue isn't needed, because a queue will automatically created if it doesn't exist - const successful = RabbitMQ.channel?.publish(id, "", Buffer.from(`${data}`), { type: payload.event }); - if (!successful) throw new Error("failed to send event"); - } else if (process.env.EVENT_TRANSMISSION === "process") { - process.send?.({ type: "event", event: payload, id } as ProcessEvent); - } else { - events.emit(id, payload); - } -} - -export async function initEvent() { - await RabbitMQ.init(); // does nothing if rabbitmq is not setup - if (RabbitMQ.connection) { - } else { - // use event emitter - // use process messages - } -} - -export interface EventOpts extends Event { - acknowledge?: Function; - channel?: Channel; - cancel: Function; -} - -export interface ListenEventOpts { - channel?: Channel; - acknowledge?: boolean; -} - -export interface ProcessEvent { - type: "event"; - event: Event; - id: string; -} - -export async function listenEvent(event: string, callback: (event: EventOpts) => any, opts?: ListenEventOpts) { - if (RabbitMQ.connection) { - // @ts-ignore - return rabbitListen(opts?.channel || RabbitMQ.channel, event, callback, { acknowledge: opts?.acknowledge }); - } else if (process.env.EVENT_TRANSMISSION === "process") { - const cancel = () => { - process.removeListener("message", listener); - process.setMaxListeners(process.getMaxListeners() - 1); - }; - - const listener = (msg: ProcessEvent) => { - msg.type === "event" && msg.id === event && callback({ ...msg.event, cancel }); - }; - - process.addListener("message", listener); - process.setMaxListeners(process.getMaxListeners() + 1); - - return cancel; - } else { - const listener = (opts: any) => callback({ ...opts, cancel }); - const cancel = () => { - events.removeListener(event, listener); - events.setMaxListeners(events.getMaxListeners() - 1); - }; - events.setMaxListeners(events.getMaxListeners() + 1); - events.addListener(event, listener); - - return cancel; - } -} - -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 }); - - const cancel = () => { - channel.cancel(q.queue); - channel.unbindQueue(q.queue, id, ""); - }; - - channel.bindQueue(q.queue, id, ""); - channel.consume( - q.queue, - (opts) => { - if (!opts) return; - - const data = JSON.parse(opts.content.toString()); - const event = opts.properties.type as EVENT; - - callback({ - event, - data, - acknowledge() { - channel.ack(opts); - }, - channel, - cancel, - }); - // rabbitCh.ack(opts); - }, - { - noAck: !opts?.acknowledge, - } - ); - - return cancel; -} diff --git a/util/src/util/FieldError.ts b/util/src/util/FieldError.ts deleted file mode 100644 index 406b33e8..00000000 --- a/util/src/util/FieldError.ts +++ /dev/null @@ -1,25 +0,0 @@ -import "missing-native-js-functions"; - -export function FieldErrors(fields: Record<string, { code?: string; message: string }>) { - return new FieldError( - 50035, - "Invalid Form Body", - fields.map(({ message, code }) => ({ - _errors: [ - { - message, - code: code || "BASE_TYPE_INVALID", - }, - ], - })) - ); -} - -// TODO: implement Image data type: Data URI scheme that supports JPG, GIF, and PNG formats. An example Data URI format is: data:image/jpeg;base64,BASE64_ENCODED_JPEG_IMAGE_DATA -// Ensure you use the proper content type (image/jpeg, image/png, image/gif) that matches the image data being provided. - -export class FieldError extends Error { - constructor(public code: string | number, public message: string, public errors?: any) { - super(message); - } -} diff --git a/util/src/util/Intents.ts b/util/src/util/Intents.ts deleted file mode 100644 index 1e840b76..00000000 --- a/util/src/util/Intents.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { BitField } from "./BitField"; - -export class Intents extends BitField { - static FLAGS = { - GUILDS: BigInt(1) << BigInt(0), // guilds and guild merge-split events affecting the user - GUILD_MEMBERS: BigInt(1) << BigInt(1), // memberships - GUILD_BANS: BigInt(1) << BigInt(2), // bans and ban lists - GUILD_EMOJIS: BigInt(1) << BigInt(3), // custom emojis - GUILD_INTEGRATIONS: BigInt(1) << BigInt(4), // applications - GUILD_WEBHOOKS: BigInt(1) << BigInt(5), // webhooks - GUILD_INVITES: BigInt(1) << BigInt(6), // mass invites (no user can receive user specific invites of another user) - GUILD_VOICE_STATES: BigInt(1) << BigInt(7), // voice updates - GUILD_PRESENCES: BigInt(1) << BigInt(8), // presence updates - GUILD_MESSAGES_METADATA: BigInt(1) << BigInt(9), // guild message metadata - GUILD_MESSAGE_REACTIONS: BigInt(1) << BigInt(10), // guild message reactions - GUILD_MESSAGE_TYPING: BigInt(1) << BigInt(11), // guild channel typing notifications - DIRECT_MESSAGES: BigInt(1) << BigInt(12), // DM or orphan channels - DIRECT_MESSAGE_REACTIONS: BigInt(1) << BigInt(13), // DM or orphan channel message reactions - DIRECT_MESSAGE_TYPING: BigInt(1) << BigInt(14), // DM typing notifications - GUILD_MESSAGES_CONTENT: BigInt(1) << BigInt(15), // guild message content - GUILD_POLICIES: BigInt(1) << BigInt(20), // guild policies - 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 - 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_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/util/src/util/InvisibleCharacters.ts b/util/src/util/InvisibleCharacters.ts deleted file mode 100644 index 2b014e14..00000000 --- a/util/src/util/InvisibleCharacters.ts +++ /dev/null @@ -1,56 +0,0 @@ -// 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 diff --git a/util/src/util/MessageFlags.ts b/util/src/util/MessageFlags.ts deleted file mode 100644 index b59295c4..00000000 --- a/util/src/util/MessageFlags.ts +++ /dev/null @@ -1,20 +0,0 @@ -// based on https://github.com/discordjs/discord.js/blob/master/src/util/MessageFlags.js -// Apache License Version 2.0 Copyright 2015 - 2021 Amish Shah, 2022 Erkin Alp Güney - -import { BitField } from "./BitField"; - -export class MessageFlags extends BitField { - static FLAGS = { - CROSSPOSTED: BigInt(1) << BigInt(0), - IS_CROSSPOST: BigInt(1) << BigInt(1), - SUPPRESS_EMBEDS: BigInt(1) << BigInt(2), - // SOURCE_MESSAGE_DELETED: BigInt(1) << BigInt(3), // fosscord will delete them from destination too, making this redundant - URGENT: BigInt(1) << BigInt(4), - // HAS_THREAD: BigInt(1) << BigInt(5) // does not apply to fosscord due to infrastructural differences - PRIVATE_ROUTE: BigInt(1) << BigInt(6), // it that has been routed to only some of the users that can see the channel - 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 - }; -} diff --git a/util/src/util/Permissions.ts b/util/src/util/Permissions.ts deleted file mode 100644 index e5459ab5..00000000 --- a/util/src/util/Permissions.ts +++ /dev/null @@ -1,281 +0,0 @@ -// https://github.com/discordjs/discord.js/blob/master/src/util/Permissions.js -// Apache License Version 2.0 Copyright 2015 - 2021 Amish Shah -import { Channel, ChannelPermissionOverwrite, Guild, Member, Role } from "../entities"; -import { BitField } from "./BitField"; -import "missing-native-js-functions"; -import { BitFieldResolvable, BitFlag } from "./BitField"; - -var HTTPError: any; - -try { - HTTPError = require("lambert-server").HTTPError; -} catch (e) { - HTTPError = Error; -} - -export type PermissionResolvable = bigint | number | Permissions | PermissionResolvable[] | PermissionString; - -type PermissionString = keyof typeof Permissions.FLAGS; - -// BigInt doesn't have a bit limit (https://stackoverflow.com/questions/53335545/whats-the-biggest-bigint-value-in-js-as-per-spec) -const CUSTOM_PERMISSION_OFFSET = BigInt(1) << BigInt(64); // 27 permission bits left for discord to add new ones - -export class Permissions extends BitField { - cache: PermissionCache = {}; - - constructor(bits: BitFieldResolvable = 0) { - super(bits); - if (this.bitfield & Permissions.FLAGS.ADMINISTRATOR) { - this.bitfield = ALL_PERMISSIONS; - } - } - - static FLAGS = { - CREATE_INSTANT_INVITE: BitFlag(0), - KICK_MEMBERS: BitFlag(1), - BAN_MEMBERS: BitFlag(2), - ADMINISTRATOR: BitFlag(3), - MANAGE_CHANNELS: BitFlag(4), - MANAGE_GUILD: BitFlag(5), - ADD_REACTIONS: BitFlag(6), - VIEW_AUDIT_LOG: BitFlag(7), - PRIORITY_SPEAKER: BitFlag(8), - STREAM: BitFlag(9), - VIEW_CHANNEL: BitFlag(10), - SEND_MESSAGES: BitFlag(11), - SEND_TTS_MESSAGES: BitFlag(12), - MANAGE_MESSAGES: BitFlag(13), - EMBED_LINKS: BitFlag(14), - ATTACH_FILES: BitFlag(15), - READ_MESSAGE_HISTORY: BitFlag(16), - MENTION_EVERYONE: BitFlag(17), - USE_EXTERNAL_EMOJIS: BitFlag(18), - VIEW_GUILD_INSIGHTS: BitFlag(19), - CONNECT: BitFlag(20), - SPEAK: BitFlag(21), - MUTE_MEMBERS: BitFlag(22), - DEAFEN_MEMBERS: BitFlag(23), - MOVE_MEMBERS: BitFlag(24), - USE_VAD: BitFlag(25), - CHANGE_NICKNAME: BitFlag(26), - MANAGE_NICKNAMES: BitFlag(27), - MANAGE_ROLES: BitFlag(28), - MANAGE_WEBHOOKS: BitFlag(29), - MANAGE_EMOJIS_AND_STICKERS: BitFlag(30), - USE_APPLICATION_COMMANDS: BitFlag(31), - REQUEST_TO_SPEAK: BitFlag(32), - // TODO: what is permission 33? - MANAGE_THREADS: BitFlag(34), - USE_PUBLIC_THREADS: BitFlag(35), - USE_PRIVATE_THREADS: BitFlag(36), - USE_EXTERNAL_STICKERS: BitFlag(37), - - /** - * CUSTOM PERMISSIONS ideas: - * - allow user to dm members - * - allow user to pin messages (without MANAGE_MESSAGES) - * - allow user to publish messages (without MANAGE_MESSAGES) - */ - // CUSTOM_PERMISSION: BigInt(1) << BigInt(0) + CUSTOM_PERMISSION_OFFSET - }; - - any(permission: PermissionResolvable, checkAdmin = true) { - return (checkAdmin && super.any(Permissions.FLAGS.ADMINISTRATOR)) || super.any(permission); - } - - /** - * Checks whether the bitfield has a permission, or multiple permissions. - */ - has(permission: PermissionResolvable, checkAdmin = true) { - return (checkAdmin && super.has(Permissions.FLAGS.ADMINISTRATOR)) || super.has(permission); - } - - /** - * Checks whether the bitfield has a permission, or multiple permissions, but throws an Error if user fails to match auth criteria. - */ - hasThrow(permission: PermissionResolvable) { - if (this.has(permission) && this.has("VIEW_CHANNEL")) return true; - // @ts-ignore - throw new HTTPError(`You are missing the following permissions ${permission}`, 403); - } - - overwriteChannel(overwrites: ChannelPermissionOverwrite[]) { - if (!overwrites) return this; - if (!this.cache) throw new Error("permission chache not available"); - overwrites = overwrites.filter((x) => { - if (x.type === 0 && this.cache.roles?.some((r) => r.id === x.id)) return true; - if (x.type === 1 && x.id == this.cache.user_id) return true; - return false; - }); - return new Permissions(Permissions.channelPermission(overwrites, this.bitfield)); - } - - static channelPermission(overwrites: ChannelPermissionOverwrite[], init?: bigint) { - // TODO: do not deny any permissions if admin - return overwrites.reduce((permission, overwrite) => { - // apply disallowed permission - // * permission: current calculated permission (e.g. 010) - // * deny contains all denied permissions (e.g. 011) - // * allow contains all explicitly allowed permisions (e.g. 100) - return (permission & ~BigInt(overwrite.deny)) | BigInt(overwrite.allow); - // ~ operator inverts deny (e.g. 011 -> 100) - // & operator only allows 1 for both ~deny and permission (e.g. 010 & 100 -> 000) - // | operators adds both together (e.g. 000 + 100 -> 100) - }, init || BigInt(0)); - } - - static rolePermission(roles: Role[]) { - // adds all permissions of all roles together (Bit OR) - return roles.reduce((permission, role) => permission | BigInt(role.permissions), BigInt(0)); - } - - static finalPermission({ - user, - guild, - channel, - }: { - user: { id: string; roles: string[] }; - guild: { roles: Role[] }; - channel?: { - overwrites?: ChannelPermissionOverwrite[]; - recipient_ids?: string[] | null; - owner_id?: string; - }; - }) { - if (user.id === "0") return new Permissions("ADMINISTRATOR"); // system user id - - let roles = guild.roles.filter((x) => user.roles.includes(x.id)); - let permission = Permissions.rolePermission(roles); - - if (channel?.overwrites) { - let overwrites = channel.overwrites.filter((x) => { - if (x.type === 0 && user.roles.includes(x.id)) return true; - if (x.type === 1 && x.id == user.id) return true; - return false; - }); - permission = Permissions.channelPermission(overwrites, permission); - } - - if (channel?.recipient_ids) { - if (channel?.owner_id === user.id) return new Permissions("ADMINISTRATOR"); - if (channel.recipient_ids.includes(user.id)) { - // Default dm permissions - return new Permissions([ - "VIEW_CHANNEL", - "SEND_MESSAGES", - "STREAM", - "ADD_REACTIONS", - "EMBED_LINKS", - "ATTACH_FILES", - "READ_MESSAGE_HISTORY", - "MENTION_EVERYONE", - "USE_EXTERNAL_EMOJIS", - "CONNECT", - "SPEAK", - "MANAGE_CHANNELS", - ]); - } - - return new Permissions(); - } - - return new Permissions(permission); - } -} - -const ALL_PERMISSIONS = Object.values(Permissions.FLAGS).reduce((total, val) => total | val, BigInt(0)); - -export type PermissionCache = { - channel?: Channel | undefined; - member?: Member | undefined; - guild?: Guild | undefined; - roles?: Role[] | undefined; - user_id?: string; -}; - -export async function getPermission( - user_id?: string, - guild_id?: string, - channel_id?: string, - opts: { - guild_select?: (keyof Guild)[]; - guild_relations?: string[]; - channel_select?: (keyof Channel)[]; - channel_relations?: string[]; - member_select?: (keyof Member)[]; - member_relations?: string[]; - } = {} -) { - if (!user_id) throw new HTTPError("User not found"); - var channel: Channel | undefined; - var member: Member | undefined; - var guild: Guild | undefined; - - if (channel_id) { - channel = await Channel.findOneOrFail({ - where: { id: channel_id }, - relations: ["recipients", ...(opts.channel_relations || [])], - select: [ - "id", - "recipients", - "permission_overwrites", - "owner_id", - "guild_id", - // @ts-ignore - ...(opts.channel_select || []), - ], - }); - if (channel.guild_id) guild_id = channel.guild_id; // derive guild_id from the channel - } - - if (guild_id) { - guild = await Guild.findOneOrFail({ - where: { id: guild_id }, - select: [ - "id", - "owner_id", - // @ts-ignore - ...(opts.guild_select || []), - ], - relations: opts.guild_relations, - }); - if (guild.owner_id === user_id) return new Permissions(Permissions.FLAGS.ADMINISTRATOR); - - member = await Member.findOneOrFail({ - where: { guild_id, id: user_id }, - relations: ["roles", ...(opts.member_relations || [])], - select: [ - "id", - "roles", - // @ts-ignore - ...(opts.member_select || []), - ], - }); - } - - let recipient_ids: any = channel?.recipients?.map((x) => x.user_id); - if (!recipient_ids?.length) recipient_ids = null; - - // TODO: remove guild.roles and convert recipient_ids to recipients - var permission = Permissions.finalPermission({ - user: { - id: user_id, - roles: member?.roles.map((x) => x.id) || [], - }, - guild: { - roles: member?.roles || [], - }, - channel: { - overwrites: channel?.permission_overwrites, - owner_id: channel?.owner_id, - recipient_ids, - }, - }); - - const obj = new Permissions(permission); - - // pass cache to permission for possible future getPermission calls - obj.cache = { guild, member, channel, roles: member?.roles, user_id }; - - return obj; -} diff --git a/util/src/util/RabbitMQ.ts b/util/src/util/RabbitMQ.ts deleted file mode 100644 index 0f5eb6aa..00000000 --- a/util/src/util/RabbitMQ.ts +++ /dev/null @@ -1,19 +0,0 @@ -import amqp, { Connection, Channel } from "amqplib"; -// import Config from "./Config"; - -export const RabbitMQ: { connection: Connection | null; channel: Channel | null; init: () => Promise<void> } = { - connection: null, - channel: null, - init: async function () { - return; - // const host = Config.get().rabbitmq.host; - // if (!host) return; - // console.log(`[RabbitMQ] connect: ${host}`); - // this.connection = await amqp.connect(host, { - // timeout: 1000 * 60, - // }); - // console.log(`[RabbitMQ] connected`); - // this.channel = await this.connection.createChannel(); - // console.log(`[RabbitMQ] channel created`); - }, -}; diff --git a/util/src/util/Regex.ts b/util/src/util/Regex.ts deleted file mode 100644 index 83fc9fe8..00000000 --- a/util/src/util/Regex.ts +++ /dev/null @@ -1,7 +0,0 @@ -export const DOUBLE_WHITE_SPACE = /\s\s+/g; -export const SPECIAL_CHAR = /[@#`:\r\n\t\f\v\p{C}]/gu; -export const CHANNEL_MENTION = /<#(\d+)>/g; -export const USER_MENTION = /<@!?(\d+)>/g; -export const ROLE_MENTION = /<@&(\d+)>/g; -export const EVERYONE_MENTION = /@everyone/g; -export const HERE_MENTION = /@here/g; diff --git a/util/src/util/Rights.ts b/util/src/util/Rights.ts deleted file mode 100644 index b28c75b7..00000000 --- a/util/src/util/Rights.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { BitField } from "./BitField"; -import "missing-native-js-functions"; -import { BitFieldResolvable, BitFlag } from "./BitField"; -import { User } from "../entities"; - -var HTTPError: any; - -try { - HTTPError = require("lambert-server").HTTPError; -} catch (e) { - HTTPError = Error; -} - -export type RightResolvable = bigint | number | Rights | RightResolvable[] | RightString; - -type RightString = keyof typeof Rights.FLAGS; -// TODO: just like roles for members, users should have privilidges which combine multiple rights into one and make it easy to assign - -export class Rights extends BitField { - constructor(bits: BitFieldResolvable = 0) { - super(bits); - if (this.bitfield & Rights.FLAGS.OPERATOR) { - this.bitfield = ALL_RIGHTS; - } - } - - static FLAGS = { - OPERATOR: BitFlag(0), // has all rights - MANAGE_APPLICATIONS: BitFlag(1), - MANAGE_GUILDS: BitFlag(2), - MANAGE_MESSAGES: BitFlag(3), // Can't see other messages but delete/edit them in channels that they can see - MANAGE_RATE_LIMITS: BitFlag(4), - MANAGE_ROUTING: BitFlag(5), // can create custom message routes to any channel/guild - MANAGE_TICKETS: BitFlag(6), // can respond to and resolve support tickets - MANAGE_USERS: BitFlag(7), - ADD_MEMBERS: BitFlag(8), // can manually add any members in their guilds - BYPASS_RATE_LIMITS: BitFlag(9), - CREATE_APPLICATIONS: BitFlag(10), - CREATE_CHANNELS: BitFlag(11), // can create guild channels or threads in the guilds that they have permission - CREATE_DMS: BitFlag(12), - CREATE_DM_GROUPS: BitFlag(13), // can create group DMs or custom orphan channels - CREATE_GUILDS: BitFlag(14), - CREATE_INVITES: BitFlag(15), // can create mass invites in the guilds that they have CREATE_INSTANT_INVITE - CREATE_ROLES: BitFlag(16), - CREATE_TEMPLATES: BitFlag(17), - CREATE_WEBHOOKS: BitFlag(18), - JOIN_GUILDS: BitFlag(19), - PIN_MESSAGES: BitFlag(20), - SELF_ADD_REACTIONS: BitFlag(21), - SELF_DELETE_MESSAGES: BitFlag(22), - SELF_EDIT_MESSAGES: BitFlag(23), - SELF_EDIT_NAME: BitFlag(24), - SEND_MESSAGES: BitFlag(25), - USE_ACTIVITIES: BitFlag(26), // use (game) activities in voice channels (e.g. Watch together) - USE_VIDEO: BitFlag(27), - USE_VOICE: BitFlag(28), - INVITE_USERS: BitFlag(29), // can create user-specific invites in the guilds that they have INVITE_USERS - SELF_DELETE_DISABLE: BitFlag(30), // can disable/delete own account - DEBTABLE: BitFlag(31), // can use pay-to-use features - 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), - // 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 - SELF_ADD_DISCOVERABLE: BitFlag(36), // can mark discoverable guilds that they have permissions to mark as discoverable - MANAGE_GUILD_DIRECTORY: BitFlag(37), // can change anything in the primary guild directory - POGGERS: BitFlag(38), // can send confetti, screenshake, random user mention (@someone) - USE_ACHIEVEMENTS: BitFlag(39), // can use achievements and cheers - INITIATE_INTERACTIONS: BitFlag(40), // can initiate interactions - RESPOND_TO_INTERACTIONS: BitFlag(41), // can respond to interactions - SEND_BACKDATED_EVENTS: BitFlag(42), // can send backdated events - USE_MASS_INVITES: BitFlag(43), // added per @xnacly's request — can accept mass invites - ACCEPT_INVITES: BitFlag(44) // added per @xnacly's request — can accept user-specific invites and DM requests - }; - - any(permission: RightResolvable, checkOperator = true) { - return (checkOperator && super.any(Rights.FLAGS.OPERATOR)) || super.any(permission); - } - - has(permission: RightResolvable, checkOperator = true) { - return (checkOperator && super.has(Rights.FLAGS.OPERATOR)) || super.has(permission); - } - - hasThrow(permission: RightResolvable) { - if (this.has(permission)) return true; - // @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 - /**, opts: { - in_behalf?: (keyof User)[]; - } = {} **/) { - let user = await User.findOneOrFail({ where: { id: user_id } }); - return new Rights(user.rights); -} diff --git a/util/src/util/Snowflake.ts b/util/src/util/Snowflake.ts deleted file mode 100644 index 134d526e..00000000 --- a/util/src/util/Snowflake.ts +++ /dev/null @@ -1,130 +0,0 @@ -// @ts-nocheck -import * as cluster from "cluster"; - -// https://github.com/discordjs/discord.js/blob/master/src/util/Snowflake.js -// Apache License Version 2.0 Copyright 2015 - 2021 Amish Shah -("use strict"); - -// Discord epoch (2015-01-01T00:00:00.000Z) - -/** - * A container for useful snowflake-related methods. - */ -export class Snowflake { - static readonly EPOCH = 1420070400000; - static INCREMENT = 0n; // max 4095 - static processId = BigInt(process.pid % 31); // max 31 - static workerId = BigInt((cluster.worker?.id || 0) % 31); // max 31 - - constructor() { - throw new Error(`The ${this.constructor.name} class may not be instantiated.`); - } - - /** - * A Twitter-like snowflake, except the epoch is 2015-01-01T00:00:00.000Z - * ``` - * If we have a snowflake '266241948824764416' we can represent it as binary: - * - * 64 22 17 12 0 - * 000000111011000111100001101001000101000000 00001 00000 000000000000 - * number of ms since Discord epoch worker pid increment - * ``` - * @typedef {string} Snowflake - */ - - /** - * Transforms a snowflake from a decimal string to a bit string. - * @param {Snowflake} num Snowflake to be transformed - * @returns {string} - * @private - */ - static idToBinary(num) { - let bin = ""; - let high = parseInt(num.slice(0, -10)) || 0; - let low = parseInt(num.slice(-10)); - while (low > 0 || high > 0) { - bin = String(low & 1) + bin; - low = Math.floor(low / 2); - if (high > 0) { - low += 5000000000 * (high % 2); - high = Math.floor(high / 2); - } - } - return bin; - } - - /** - * Transforms a snowflake from a bit string to a decimal string. - * @param {string} num Bit string to be transformed - * @returns {Snowflake} - * @private - */ - static binaryToID(num) { - let dec = ""; - - while (num.length > 50) { - const high = parseInt(num.slice(0, -32), 2); - const low = parseInt((high % 10).toString(2) + num.slice(-32), 2); - - dec = (low % 10).toString() + dec; - num = - Math.floor(high / 10).toString(2) + - Math.floor(low / 10) - .toString(2) - .padStart(32, "0"); - } - - num = parseInt(num, 2); - while (num > 0) { - dec = (num % 10).toString() + dec; - num = Math.floor(num / 10); - } - - return dec; - } - - static generateWorkerProcess() { // worker process - returns a number - var time = BigInt(Date.now() - Snowflake.EPOCH) << BigInt(22); - var worker = Snowflake.workerId << 17n; - var process = Snowflake.processId << 12n; - var increment = Snowflake.INCREMENT++; - return BigInt(time | worker | process | increment); - } - - static generate() { - return Snowflake.generateWorkerProcess().toString(); - } - /** - * A deconstructed snowflake. - * @typedef {Object} DeconstructedSnowflake - * @property {number} timestamp Timestamp the snowflake was created - * @property {Date} date Date the snowflake was created - * @property {number} workerID Worker ID in the snowflake - * @property {number} processID Process ID in the snowflake - * @property {number} increment Increment in the snowflake - * @property {string} binary Binary representation of the snowflake - */ - - /** - * Deconstructs a Discord snowflake. - * @param {Snowflake} snowflake Snowflake to deconstruct - * @returns {DeconstructedSnowflake} Deconstructed snowflake - */ - static deconstruct(snowflake) { - const BINARY = Snowflake.idToBinary(snowflake).toString(2).padStart(64, "0"); - const res = { - timestamp: parseInt(BINARY.substring(0, 42), 2) + Snowflake.EPOCH, - workerID: parseInt(BINARY.substring(42, 47), 2), - processID: parseInt(BINARY.substring(47, 52), 2), - increment: parseInt(BINARY.substring(52, 64), 2), - binary: BINARY, - }; - Object.defineProperty(res, "date", { - get: function get() { - return new Date(this.timestamp); - }, - enumerable: true, - }); - return res; - } -} diff --git a/util/src/util/String.ts b/util/src/util/String.ts deleted file mode 100644 index 55f11e8d..00000000 --- a/util/src/util/String.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { SPECIAL_CHAR } from "./Regex"; - -export function trimSpecial(str?: string): string { - // @ts-ignore - if (!str) return; - return str.replace(SPECIAL_CHAR, "").trim(); -} diff --git a/util/src/util/Token.ts b/util/src/util/Token.ts deleted file mode 100644 index 500ace45..00000000 --- a/util/src/util/Token.ts +++ /dev/null @@ -1,51 +0,0 @@ -import jwt, { VerifyOptions } from "jsonwebtoken"; -import { Config } from "./Config"; -import { User } from "../entities"; - -export const JWTOptions: VerifyOptions = { algorithms: ["HS256"] }; - -export function checkToken(token: string, jwtSecret: string): Promise<any> { - return new Promise((res, rej) => { - token = token.replace("Bot ", ""); - /** - 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( - { id: decoded.id }, - { 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 (user.disabled) return rej("User disabled"); - if (user.deleted) return rej("User not found"); - - return res({ decoded, user }); - }); - }); -} - -export async function generateToken(id: string) { - const iat = Math.floor(Date.now() / 1000); - const algorithm = "HS256"; - - return new Promise((res, rej) => { - jwt.sign( - { id: id, iat }, - Config.get().security.jwtSecret, - { - algorithm, - }, - (err, token) => { - if (err) return rej(err); - return res(token); - } - ); - }); -} diff --git a/util/src/util/TraverseDirectory.ts b/util/src/util/TraverseDirectory.ts deleted file mode 100644 index 3d0d6279..00000000 --- a/util/src/util/TraverseDirectory.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 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) - ); -} diff --git a/util/src/util/cdn.ts b/util/src/util/cdn.ts deleted file mode 100644 index ea950cd1..00000000 --- a/util/src/util/cdn.ts +++ /dev/null @@ -1,56 +0,0 @@ -import FormData from "form-data"; -import { HTTPError } from "lambert-server"; -import fetch from "node-fetch"; -import { Config } from "./Config"; -import multer from "multer"; - -export async function uploadFile(path: string, file?: Express.Multer.File) { - if (!file?.buffer) throw new HTTPError("Missing file in body"); - - const form = new FormData(); - form.append("file", file.buffer, { - contentType: file.mimetype, - filename: file.originalname, - }); - - const response = await fetch(`${Config.get().cdn.endpointPrivate || "http://localhost:3003"}${path}`, { - headers: { - signature: Config.get().security.requestSignature, - ...form.getHeaders(), - }, - method: "POST", - body: form, - }); - const result = await response.json(); - - if (response.status !== 200) throw result; - return result; -} - -export async function handleFile(path: string, body?: string): Promise<string | undefined> { - if (!body || !body.startsWith("data:")) return undefined; - try { - const mimetype = body.split(":")[1].split(";")[0]; - const buffer = Buffer.from(body.split(",")[1], "base64"); - - // @ts-ignore - const { id } = await uploadFile(path, { buffer, mimetype, originalname: "banner" }); - return id; - } catch (error) { - console.error(error); - throw new HTTPError("Invalid " + path); - } -} - -export async function deleteFile(path: string) { - const response = await fetch(`${Config.get().cdn.endpointPrivate || "http://localhost:3003"}${path}`, { - headers: { - signature: Config.get().security.requestSignature, - }, - method: "DELETE", - }); - const result = await response.json(); - - if (response.status !== 200) throw result; - return result; -} diff --git a/util/src/util/index.ts b/util/src/util/index.ts deleted file mode 100644 index f7a273cb..00000000 --- a/util/src/util/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -export * from "./ApiError"; -export * from "./BitField"; -export * from "./Token"; -//export * from "./Categories"; -export * from "./cdn"; -export * from "./Config"; -export * from "./Constants"; -export * from "./Database"; -export * from "./Email"; -export * from "./Event"; -export * from "./FieldError"; -export * from "./Intents"; -export * from "./MessageFlags"; -export * from "./Permissions"; -export * from "./RabbitMQ"; -export * from "./Regex"; -export * from "./Rights"; -export * from "./Snowflake"; -export * from "./String"; -export * from "./Array"; -export * from "./TraverseDirectory"; -export * from "./InvisibleCharacters"; \ No newline at end of file |