diff options
author | Flam3rboy <34555296+Flam3rboy@users.noreply.github.com> | 2021-10-10 11:03:32 +0200 |
---|---|---|
committer | Flam3rboy <34555296+Flam3rboy@users.noreply.github.com> | 2021-10-10 11:03:32 +0200 |
commit | dc85a79498941e4f38bf0e4e1bee4d83b6e35e80 (patch) | |
tree | 416dc2035ed9a0aff3db772044256a64bfa79b19 | |
parent | :art: clean up dependencies (diff) | |
download | server-dc85a79498941e4f38bf0e4e1bee4d83b6e35e80.tar.xz |
:art: clean up imports + classes
-rw-r--r-- | .gitignore | 4 | ||||
-rw-r--r-- | api/src/Server.ts | 3 | ||||
-rw-r--r-- | api/src/routes/channels/#channel_id/invites.ts | 2 | ||||
-rw-r--r-- | api/src/routes/channels/#channel_id/messages/index.ts | 3 | ||||
-rw-r--r-- | api/src/test/jwt.ts | 37 | ||||
-rw-r--r-- | api/src/test/jwt2.ts | 13 | ||||
-rw-r--r-- | api/src/test/password_test.ts | 12 | ||||
-rw-r--r-- | gateway/src/events/Connection.ts | 3 | ||||
-rw-r--r-- | gateway/src/opcodes/LazyRequest.ts | 10 | ||||
-rw-r--r-- | util/src/entities/BaseClass.ts | 58 | ||||
-rw-r--r-- | util/src/entities/Message.ts | 3 | ||||
-rw-r--r-- | util/src/entities/RateLimit.ts | 3 | ||||
-rw-r--r-- | util/src/entities/User.ts | 9 | ||||
-rw-r--r-- | util/src/entities/Webhook.ts | 3 | ||||
-rw-r--r-- | util/src/index.ts | 6 |
15 files changed, 23 insertions, 146 deletions
diff --git a/.gitignore b/.gitignore index f67723af..a09d215a 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,6 @@ node_modules api/assets/*.js api/assets/*.css database.db -tsconfig.tsbuildinfo \ No newline at end of file +tsconfig.tsbuildinfo +files/ +.env \ No newline at end of file diff --git a/api/src/Server.ts b/api/src/Server.ts index 12c1d6b4..19e3d245 100644 --- a/api/src/Server.ts +++ b/api/src/Server.ts @@ -1,13 +1,10 @@ -import { OptionsJson } from "body-parser"; import "missing-native-js-functions"; -import { Connection } from "mongoose"; import { Server, ServerOptions } from "lambert-server"; import { Authentication, CORS } from "./middlewares/"; import { Config, initDatabase, initEvent } from "@fosscord/util"; import { ErrorHandler } from "./middlewares/ErrorHandler"; import { BodyParser } from "./middlewares/BodyParser"; import { Router, Request, Response, NextFunction } from "express"; -import mongoose from "mongoose"; import path from "path"; import { initRateLimits } from "./middlewares/RateLimit"; import TestClient from "./middlewares/TestClient"; diff --git a/api/src/routes/channels/#channel_id/invites.ts b/api/src/routes/channels/#channel_id/invites.ts index 22420983..6d2c625d 100644 --- a/api/src/routes/channels/#channel_id/invites.ts +++ b/api/src/routes/channels/#channel_id/invites.ts @@ -2,7 +2,7 @@ import { Router, Request, Response } from "express"; import { HTTPError } from "lambert-server"; import { route } from "@fosscord/api"; import { random } from "@fosscord/api"; -import { getPermission, Channel, Invite, InviteCreateEvent, emitEvent, User, Guild, PublicInviteRelation } from "@fosscord/util"; +import { Channel, Invite, InviteCreateEvent, emitEvent, User, Guild, PublicInviteRelation } from "@fosscord/util"; import { isTextChannel } from "./messages"; const router: Router = Router(); diff --git a/api/src/routes/channels/#channel_id/messages/index.ts b/api/src/routes/channels/#channel_id/messages/index.ts index 4ec31417..26bb9e5d 100644 --- a/api/src/routes/channels/#channel_id/messages/index.ts +++ b/api/src/routes/channels/#channel_id/messages/index.ts @@ -22,7 +22,7 @@ const router: Router = Router(); export default router; -function isTextChannel(type: ChannelType): boolean { +export function isTextChannel(type: ChannelType): boolean { switch (type) { case ChannelType.GUILD_STORE: case ChannelType.GUILD_VOICE: @@ -39,7 +39,6 @@ function isTextChannel(type: ChannelType): boolean { return true; } } -module.exports.isTextChannel = isTextChannel; export interface MessageCreateSchema { content?: string; diff --git a/api/src/test/jwt.ts b/api/src/test/jwt.ts deleted file mode 100644 index bdad513b..00000000 --- a/api/src/test/jwt.ts +++ /dev/null @@ -1,37 +0,0 @@ -const jwa = require("jwa"); - -var STR64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""); - -function base64url(string: string, encoding: string) { - // @ts-ignore - return Buffer.from(string, encoding).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); -} - -function to64String(input: number, current = ""): string { - if (input < 0 && current.length == 0) { - input = input * -1; - } - var modify = input % 64; - var remain = Math.floor(input / 64); - var result = STR64[modify] + current; - return remain <= 0 ? result : to64String(remain, result); -} - -function to64Parse(input: string) { - var result = 0; - var toProc = input.split(""); - var e; - for (e in toProc) { - result = result * 64 + STR64.indexOf(toProc[e]); - } - return result; -} - -// @ts-ignore -const start = `${base64url("311129357362135041")}.${to64String(Date.now())}`; -const signature = jwa("HS256").sign(start, `test`); -const token = `${start}.${signature}`; -console.log(token); - -// MzExMTI5MzU3MzYyMTM1MDQx.XdQb_rA.907VgF60kocnOTl32MSUWGSSzbAytQ0jbt36KjLaxuY -// MzExMTI5MzU3MzYyMTM1MDQx.XdQbaPy.4vGx4L7IuFJGsRe6IL3BeybLIvbx4Vauvx12pwNsy2U diff --git a/api/src/test/jwt2.ts b/api/src/test/jwt2.ts deleted file mode 100644 index e231233d..00000000 --- a/api/src/test/jwt2.ts +++ /dev/null @@ -1,13 +0,0 @@ -import jwt from "jsonwebtoken"; - -const algorithm = "HS256"; -const iat = Math.floor(Date.now() / 1000); - -// @ts-ignore -const token = jwt.sign({ id: "311129357362135041" }, "secret", { - algorithm, -}); -console.log(token); - -const decoded = jwt.verify(token, "secret", { algorithms: [algorithm] }); -console.log(decoded); diff --git a/api/src/test/password_test.ts b/api/src/test/password_test.ts deleted file mode 100644 index 983b18ae..00000000 --- a/api/src/test/password_test.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { checkPassword } from "@fosscord/api"; - -console.log(checkPassword("123456789012345")); -// -> 0.25 -console.log(checkPassword("ABCDEFGHIJKLMOPQ")); -// -> 0.25 -console.log(checkPassword("ABC123___...123")); -// -> -console.log(checkPassword("")); -// -> -// console.log(checkPassword("")); -// // -> diff --git a/gateway/src/events/Connection.ts b/gateway/src/events/Connection.ts index c1a6b618..2cf22f7d 100644 --- a/gateway/src/events/Connection.ts +++ b/gateway/src/events/Connection.ts @@ -24,6 +24,7 @@ export async function Connection( request: IncomingMessage ) { try { + // @ts-ignore socket.on("close", Close); // @ts-ignore socket.on("message", Message); @@ -68,12 +69,10 @@ export async function Connection( }); socket.readyTimeout = setTimeout(() => { - Session.delete({ session_id: socket.session_id }); //should we await? return socket.close(CLOSECODES.Session_timed_out); }, 1000 * 30); } catch (error) { console.error(error); - Session.delete({ session_id: socket.session_id }); //should we await? return socket.close(CLOSECODES.Unknown_error); } } diff --git a/gateway/src/opcodes/LazyRequest.ts b/gateway/src/opcodes/LazyRequest.ts index d37e32da..f5fd561a 100644 --- a/gateway/src/opcodes/LazyRequest.ts +++ b/gateway/src/opcodes/LazyRequest.ts @@ -41,6 +41,7 @@ export async function onLazyRequest(this: WebSocket, { d }: Payload) { const items = []; for (const role of roles) { + // @ts-ignore const [role_members, other_members] = partition(members, (m: Member) => m.roles.find((r) => r.id === role.id) ); @@ -53,9 +54,12 @@ export async function onLazyRequest(this: WebSocket, { d }: Payload) { groups.push(group); for (const member of role_members) { - member.roles = member.roles.filter((x) => x.id !== guild_id); + member.roles = member.roles.filter((x: Role) => x.id !== guild_id); items.push({ - member: { ...member, roles: member.roles.map((x) => x.id) }, + member: { + ...member, + roles: member.roles.map((x: Role) => x.id), + }, }); } members = other_members; @@ -84,7 +88,9 @@ export async function onLazyRequest(this: WebSocket, { d }: Payload) { } function partition<T>(array: T[], isValid: Function) { + // @ts-ignore return array.reduce( + // @ts-ignore ([pass, fail], elem) => { return isValid(elem) ? [[...pass, elem], fail] diff --git a/util/src/entities/BaseClass.ts b/util/src/entities/BaseClass.ts index beccf04b..43b69c76 100644 --- a/util/src/entities/BaseClass.ts +++ b/util/src/entities/BaseClass.ts @@ -1,19 +1,8 @@ import "reflect-metadata"; -import { - BaseEntity, - BeforeInsert, - BeforeUpdate, - EntityMetadata, - FindConditions, - ObjectIdColumn, - PrimaryColumn, -} from "typeorm"; +import { BaseEntity, EntityMetadata, FindConditions, ObjectIdColumn, PrimaryColumn } from "typeorm"; import { Snowflake } from "../util/Snowflake"; import "missing-native-js-functions"; -// TODO use class-validator https://typeorm.io/#/validation with class annotators (isPhone/isEmail) combined with types from typescript-json-schema -// btw. we don't use class-validator for everything, because we need to explicitly set the type instead of deriving it from typescript also it doesn't easily support nested objects - export class BaseClassWithoutId extends BaseEntity { constructor(props?: any) { super(); @@ -38,11 +27,12 @@ export class BaseClassWithoutId extends BaseEntity { .concat(this.metadata.relations.map((x) => x.propertyName)) ); // will not include relational properties + console.log(properties); for (const key in props) { if (!properties.has(key)) continue; // @ts-ignore - const setter = this[`set${key.capitalize()}`]; + const setter = this[`set${key.capitalize()}`]; // use setter function if it exists if (setter) { setter.call(this, props[key]); @@ -53,12 +43,6 @@ export class BaseClassWithoutId extends BaseEntity { } } - @BeforeUpdate() - @BeforeInsert() - validate() { - return this; - } - toJSON(): any { return Object.fromEntries( this.metadata.columns // @ts-ignore @@ -76,42 +60,6 @@ export class BaseClassWithoutId extends BaseEntity { const repository = this.getRepository(); return repository.decrement(conditions, propertyPath, value); } - - // static async delete<T>(criteria: FindConditions<T>, options?: RemoveOptions) { - // if (!criteria) throw new Error("You need to specify delete criteria"); - - // const repository = this.getRepository(); - // const promises = repository.metadata.relations.map(async (x) => { - // if (x.orphanedRowAction !== "delete") return; - - // const foreignKey = - // x.foreignKeys.find((key) => key.entityMetadata === repository.metadata) || - // x.inverseRelation?.foreignKeys[0]; // find foreign key for this entity - // if (!foreignKey) { - // throw new Error( - // `Foreign key not found for entity ${repository.metadata.name} in relation ${x.propertyName}` - // ); - // } - // const id = (criteria as any)[foreignKey.referencedColumnNames[0]]; - // if (!id) throw new Error("id missing in criteria options " + foreignKey.referencedColumnNames); - - // if (x.relationType === "many-to-many") { - // return getConnection() - // .createQueryBuilder() - // .relation(this, x.propertyName) - // .of(id) - // .remove({ [foreignKey.columnNames[0]]: id }); - // } else if ( - // x.relationType === "one-to-one" || - // x.relationType === "many-to-one" || - // x.relationType === "one-to-many" - // ) { - // return (x.inverseEntityMetadata.target as any).delete({ [foreignKey.columnNames[0]]: id }); - // } - // }); - // await Promise.all(promises); - // return super.delete(criteria, options); - // } } export const PrimaryIdColumn = process.env.DATABASE?.startsWith("mongodb") ? ObjectIdColumn : PrimaryColumn; diff --git a/util/src/entities/Message.ts b/util/src/entities/Message.ts index 04c3c7aa..c7f7a1d1 100644 --- a/util/src/entities/Message.ts +++ b/util/src/entities/Message.ts @@ -46,9 +46,6 @@ export enum MessageType { @Entity("messages") export class Message extends BaseClass { - @Column() - id: string; - @Column({ nullable: true }) @RelationId((message: Message) => message.channel) channel_id: string; diff --git a/util/src/entities/RateLimit.ts b/util/src/entities/RateLimit.ts index fa9c32c1..f5916f6b 100644 --- a/util/src/entities/RateLimit.ts +++ b/util/src/entities/RateLimit.ts @@ -3,9 +3,6 @@ import { BaseClass } from "./BaseClass"; @Entity("rate_limits") export class RateLimit extends BaseClass { - @Column() - id: "global" | "error" | string; // channel_239842397 | guild_238927349823 | webhook_238923423498 - @Column() // no relation as it also executor_id: string; diff --git a/util/src/entities/User.ts b/util/src/entities/User.ts index 97564af3..662ab031 100644 --- a/util/src/entities/User.ts +++ b/util/src/entities/User.ts @@ -198,7 +198,7 @@ export class User extends BaseClass { // randomly generates a discriminator between 1 and 9999 and checks max five times if it already exists // if it all five times already exists, abort with USERNAME_TOO_MANY_USERS error // else just continue - // TODO: is there any better way to generate a random discriminator only once, without checking if it already exists in the mongodb database? + // TODO: is there any better way to generate a random discriminator only once, without checking if it already exists in the database? for (let tries = 0; tries < 5; tries++) { discriminator = Math.randomIntBetween(1, 9999).toString().padStart(4, "0"); exists = await User.findOne({ where: { discriminator, username: username }, select: ["id"] }); @@ -219,7 +219,7 @@ export class User extends BaseClass { // if nsfw_allowed is null/undefined it'll require date_of_birth to set it to true/false const language = req.language === "en" ? "en-US" : req.language || "en-US"; - const user = await new User({ + const user = new User({ created_at: new Date(), username: username, discriminator, @@ -246,7 +246,10 @@ export class User extends BaseClass { }, settings: { ...defaultSettings, locale: language }, fingerprints: [], - }).save(); + }); + + console.log(user); + await user.save(); if (Config.get().guild.autoJoin.enabled) { for (const guild of Config.get().guild.autoJoin.guilds || []) { diff --git a/util/src/entities/Webhook.ts b/util/src/entities/Webhook.ts index 8382435f..9d8609ae 100644 --- a/util/src/entities/Webhook.ts +++ b/util/src/entities/Webhook.ts @@ -12,9 +12,6 @@ export enum WebhookType { @Entity("webhooks") export class Webhook extends BaseClass { - @Column() - id: string; - @Column({ type: "simple-enum", enum: WebhookType }) type: WebhookType; diff --git a/util/src/index.ts b/util/src/index.ts index fc00d46b..ae0f7e54 100644 --- a/util/src/index.ts +++ b/util/src/index.ts @@ -1,12 +1,6 @@ import "reflect-metadata"; -// export * as Constants from "../util/Constants"; export * from "./util/index"; export * from "./interfaces/index"; export * from "./entities/index"; export * from "./dtos/index"; - -// import Config from "../util/Config"; -// import db, { MongooseCache, toObject } from "./util/Database"; - -// export { Config }; |