✨ update util

This commit is contained in:
Flam3rboy
2021-08-29 00:03:58 +02:00
parent e99008a1a5
commit 766dcc24aa
35 changed files with 853 additions and 6515 deletions
+8 -8
View File
@@ -8,13 +8,13 @@ export class Application extends BaseClass {
@Column()
name: string;
@Column()
@Column({ nullable: true })
icon?: string;
@Column()
description: string;
@Column("simple-array")
@Column({ type: "simple-array", nullable: true })
rpc_origins?: string[];
@Column()
@@ -23,16 +23,16 @@ export class Application extends BaseClass {
@Column()
bot_require_code_grant: boolean;
@Column()
@Column({ nullable: true })
terms_of_service_url?: string;
@Column()
@Column({ nullable: true })
privacy_policy_url?: string;
@Column()
owner_id: string;
@Column()
@Column({ nullable: true })
summary?: string;
@Column()
@@ -52,13 +52,13 @@ export class Application extends BaseClass {
@ManyToOne(() => Guild, (guild: Guild) => guild.id)
guild: Guild; // if this application is a game sold, this field will be the guild to which it has been linked
@Column()
@Column({ nullable: true })
primary_sku_id?: string; // if this application is a game sold, this field will be the id of the "Game SKU" that is created,
@Column()
@Column({ nullable: true })
slug?: string; // if this application is a game sold, this field will be the URL slug that links to the store page
@Column()
@Column({ nullable: true })
cover_image?: string; // the application's default rich presence invite cover image hash
@Column()
+4 -4
View File
@@ -46,7 +46,7 @@ export class AuditLogEntry extends BaseClass {
@RelationId((auditlog: AuditLogEntry) => auditlog.target)
target_id: string;
@JoinColumn({ name: "user_id" })
@JoinColumn({ name: "target_id" })
@ManyToOne(() => User, (user: User) => user.id)
target?: User;
@@ -63,7 +63,7 @@ export class AuditLogEntry extends BaseClass {
})
action_type: AuditLogEvents;
@Column("simple-json")
@Column({ type: "simple-json", nullable: true })
options?: {
delete_member_days?: string;
members_removed?: string;
@@ -76,10 +76,10 @@ export class AuditLogEntry extends BaseClass {
};
@Column()
@Column("simple-json")
@Column({ type: "simple-json" })
changes: AuditLogChange[];
@Column()
@Column({ nullable: true })
reason?: string;
}
+1 -1
View File
@@ -29,6 +29,6 @@ export class Ban extends BaseClass {
@Column()
ip: string;
@Column()
@Column({ nullable: true })
reason?: string;
}
+24 -22
View File
@@ -1,34 +1,26 @@
import "reflect-metadata";
import { BaseEntity, BeforeInsert, BeforeUpdate, PrimaryColumn } from "typeorm";
import {
BaseEntity,
BeforeInsert,
BeforeUpdate,
EntityMetadata,
FindConditions,
FindManyOptions,
PrimaryColumn,
} from "typeorm";
import { Snowflake } from "../util/Snowflake";
import Ajv, { ValidateFunction } from "ajv";
import schema from "./schema.json";
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
const ajv = new Ajv({
removeAdditional: "all",
useDefaults: true,
coerceTypes: true,
// @ts-ignore
validateFormats: false,
allowUnionTypes: true,
});
export class BaseClass extends BaseEntity {
@PrimaryColumn()
id: string;
// @ts-ignore
constructor(props?: any, public opts: { id?: string } = {}) {
constructor(public props?: any, public opts: { id?: string } = {}) {
super();
this.assign(props);
if (!this.construct.schema) {
this.construct.schema = ajv.compile({ ...schema, $ref: `#/definitions/${this.construct.name}` });
}
this.id = this.opts.id || Snowflake.generate();
}
@@ -38,19 +30,20 @@ export class BaseClass extends BaseEntity {
}
get metadata() {
return this.construct.getRepository().metadata;
return this.construct.getRepository().metadata as EntityMetadata;
}
assign(props: any) {
if (!props || typeof props !== "object") return;
delete props.id;
delete props.opts;
delete props.props;
const properties = new Set(this.metadata.columns.map((x: any) => x.propertyName));
// will not include relational properties (e.g. @RelationId @ManyToMany)
for (const key in props) {
if (this.hasOwnProperty(key)) continue;
if (!properties.has(key)) continue;
// @ts-ignore
const setter = this[`set${key.capitalize()}`];
@@ -66,8 +59,7 @@ export class BaseClass extends BaseEntity {
@BeforeUpdate()
@BeforeInsert()
validate() {
const valid = this.construct.schema(this.toJSON());
if (!valid) throw ajv.errors;
this.assign(this.props);
return this;
}
@@ -75,4 +67,14 @@ export class BaseClass extends BaseEntity {
// @ts-ignore
return Object.fromEntries(this.metadata.columns.map((x) => [x.propertyName, this[x.propertyName]]));
}
static increment<T extends BaseClass>(conditions: FindConditions<T>, propertyPath: string, value: number | string) {
const repository = this.getRepository();
return repository.increment(conditions, propertyPath, value);
}
static decrement<T extends BaseClass>(conditions: FindConditions<T>, propertyPath: string, value: number | string) {
const repository = this.getRepository();
return repository.decrement(conditions, propertyPath, value);
}
}
+7 -7
View File
@@ -60,25 +60,25 @@ export class Channel extends BaseClass {
@ManyToOne(() => User, (user: User) => user.id)
owner: User;
@Column()
@Column({ nullable: true })
last_pin_timestamp?: number;
@Column()
@Column({ nullable: true })
default_auto_archive_duration?: number;
@Column()
position: number;
@Column("simple-json")
@Column({ type: "simple-json" })
permission_overwrites: ChannelPermissionOverwrite[];
@Column()
@Column({ nullable: true })
video_quality_mode?: number;
@Column()
@Column({ nullable: true })
bitrate?: number;
@Column()
@Column({ nullable: true })
user_limit?: number;
@Column()
@@ -87,7 +87,7 @@ export class Channel extends BaseClass {
@Column()
rate_limit_per_user: number;
@Column()
@Column({ nullable: true })
topic?: string;
}
+1 -1
View File
@@ -5,7 +5,7 @@ import { Snowflake } from "../util/Snowflake";
@Entity("config")
export class ConfigEntity extends BaseClass {
@Column("simple-json")
@Column({ type: "simple-json" })
value: ConfigValue;
}
+14 -6
View File
@@ -1,21 +1,29 @@
import { Column, Entity } from "typeorm";
import { Column, Entity, JoinColumn, ManyToOne, RelationId } from "typeorm";
import { BaseClass } from "./BaseClass";
import { User } from "./User";
@Entity("connected_accounts")
export class ConnectedAccount extends BaseClass {
@Column()
@RelationId((account: ConnectedAccount) => account.user)
user_id: string;
@JoinColumn({ name: "user_id" })
@ManyToOne(() => User, (user: User) => user.connected_accounts)
user: User;
@Column({ select: false })
access_token: string;
@Column()
@Column({ select: false })
friend_sync: boolean;
@Column()
name: string;
@Column()
@Column({ select: false })
revoked: boolean;
@Column()
@Column({ select: false })
show_activity: boolean;
@Column()
@@ -24,6 +32,6 @@ export class ConnectedAccount extends BaseClass {
@Column()
verifie: boolean;
@Column()
@Column({ select: false })
visibility: number;
}
+1 -4
View File
@@ -9,7 +9,7 @@ export class Emoji extends BaseClass {
animated: boolean;
@Column()
available: boolean;
available: boolean; // whether this emoji can be used, may be false due to loss of Server Boosts
@Column()
guild_id: string;
@@ -27,9 +27,6 @@ export class Emoji extends BaseClass {
@Column()
require_colons: boolean;
@Column()
url: string;
@RelationId((emoji: Emoji) => emoji.roles)
role_ids: string[];
+26 -26
View File
@@ -17,51 +17,51 @@ export class Guild extends BaseClass {
@ManyToOne(() => Channel, (channel: Channel) => channel.id)
afk_channel?: Channel;
@Column()
@Column({ nullable: true })
afk_timeout?: number;
// * commented out -> use owner instead
// application id of the guild creator if it is bot-created
// @Column()
// @Column({ nullable: true })
// application?: string;
@Column()
@Column({ nullable: true })
banner?: string;
@Column()
@Column({ nullable: true })
default_message_notifications?: number;
@Column()
@Column({ nullable: true })
description?: string;
@Column()
@Column({ nullable: true })
discovery_splash?: string;
@Column()
@Column({ nullable: true })
explicit_content_filter?: number;
@Column("simple-array")
@Column({ type: "simple-array" })
features: string[];
@Column()
@Column({ nullable: true })
icon?: string;
@Column()
@Column({ nullable: true })
large?: boolean;
@Column()
@Column({ nullable: true })
max_members?: number; // e.g. default 100.000
@Column()
@Column({ nullable: true })
max_presences?: number;
@Column()
@Column({ nullable: true })
max_video_channel_users?: number; // ? default: 25, is this max 25 streaming or watching
@Column()
@Column({ nullable: true })
member_count?: number;
@Column()
@Column({ nullable: true })
presence_count?: number; // users online
@RelationId((guild: Guild) => guild.members)
@@ -99,7 +99,7 @@ export class Guild extends BaseClass {
@ManyToMany(() => VoiceState, (voicestate: VoiceState) => voicestate.id)
voice_states: VoiceState[];
@Column()
@Column({ nullable: true })
mfa_level?: number;
@Column()
@@ -112,13 +112,13 @@ export class Guild extends BaseClass {
@ManyToOne(() => User, (user: User) => user.id)
owner: User;
@Column()
@Column({ nullable: true })
preferred_locale?: string; // only community guilds can choose this
@Column()
@Column({ nullable: true })
premium_subscription_count?: number;
@Column()
@Column({ nullable: true })
premium_tier?: number; // nitro boost level
@RelationId((guild: Guild) => guild.public_updates_channel)
@@ -135,10 +135,10 @@ export class Guild extends BaseClass {
@ManyToOne(() => Channel, (channel: Channel) => channel.id)
rules_channel?: string;
@Column()
@Column({ nullable: true })
region?: string;
@Column()
@Column({ nullable: true })
splash?: string;
@RelationId((guild: Guild) => guild.system_channel)
@@ -148,10 +148,10 @@ export class Guild extends BaseClass {
@ManyToMany(() => Channel, (channel: Channel) => channel.id)
system_channel?: Channel;
@Column()
@Column({ nullable: true })
system_channel_flags?: number;
@Column()
@Column({ nullable: true })
unavailable?: boolean;
@RelationId((guild: Guild) => guild.vanity_url)
@@ -161,10 +161,10 @@ export class Guild extends BaseClass {
@OneToOne(() => Invite, (invite: Invite) => invite.code)
vanity_url?: Invite;
@Column()
@Column({ nullable: true })
verification_level?: number;
@Column("simple-json")
@Column({ type: "simple-json" })
welcome_screen: {
enabled: boolean;
description: string;
@@ -183,6 +183,6 @@ export class Guild extends BaseClass {
@ManyToOne(() => Channel, (channel: Channel) => channel.id)
widget_channel?: Channel;
@Column()
@Column({ nullable: true })
widget_enabled?: boolean;
}
+3 -3
View File
@@ -1,4 +1,4 @@
import { Column, Entity, JoinColumn, ManyToOne, RelationId } from "typeorm";
import { Column, Entity, JoinColumn, ManyToOne, PrimaryColumn, RelationId } from "typeorm";
import { BaseClass } from "./BaseClass";
import { Channel } from "./Channel";
import { Guild } from "./Guild";
@@ -6,7 +6,7 @@ import { User } from "./User";
@Entity("invites")
export class Invite extends BaseClass {
@Column()
@PrimaryColumn()
code: string;
@Column()
@@ -55,6 +55,6 @@ export class Invite extends BaseClass {
@ManyToOne(() => User, (user: User) => user.id)
target_user?: string; // could be used for "User specific invites" https://github.com/fosscord/fosscord/issues/62
@Column()
@Column({ nullable: true })
target_user_type?: number;
}
+215 -21
View File
@@ -1,7 +1,17 @@
import { PublicUser, User } from "./User";
import { BaseClass } from "./BaseClass";
import { Column, Entity, JoinColumn, ManyToOne, RelationId } from "typeorm";
import { Column, Entity, JoinColumn, ManyToMany, ManyToOne, RelationId } from "typeorm";
import { Guild } from "./Guild";
import { Config, emitEvent } from "../util";
import {
GuildCreateEvent,
GuildDeleteEvent,
GuildMemberAddEvent,
GuildMemberRemoveEvent,
GuildMemberUpdateEvent,
} from "../interfaces";
import { HTTPError } from "lambert-server";
import { Role } from "./Role";
@Entity("members")
export class Member extends BaseClass {
@@ -19,16 +29,20 @@ export class Member extends BaseClass {
@ManyToOne(() => Guild, (guild: Guild) => guild.id)
guild: Guild;
@Column()
@Column({ nullable: true })
nick?: string;
@Column("simple-array")
roles: string[];
@RelationId((member: Member) => member.roles)
role_ids: string[];
@JoinColumn({ name: "role_ids" })
@ManyToMany(() => Role)
roles: Role[];
@Column()
joined_at: Date;
@Column()
@Column({ nullable: true })
premium_since?: number;
@Column()
@@ -40,12 +54,180 @@ export class Member extends BaseClass {
@Column()
pending: boolean;
@Column("simple-json")
@Column({ type: "simple-json" })
settings: UserGuildSettings;
// TODO: update
@Column("simple-json")
@Column({ type: "simple-json" })
read_state: Record<string, string | null>;
static async IsInGuildOrFail(user_id: string, guild_id: string) {
if (await Member.count({ id: user_id, guild_id })) return true;
throw new HTTPError("You are not member of this guild", 403);
}
static async removeFromGuild(user_id: string, guild_id: string) {
const guild = await Guild.findOneOrFail({ select: ["owner_id"], where: { id: guild_id } });
if (guild.owner_id === user_id) throw new Error("The owner cannot be removed of the guild");
const member = await Member.findOneOrFail({ where: { id: user_id, guild_id }, relations: ["user"] });
// use promise all to execute all promises at the same time -> save time
return Promise.all([
Member.delete({
id: user_id,
guild_id: guild_id,
}),
Guild.decrement({ id: guild_id }, "member_count", -1),
emitEvent({
event: "GUILD_DELETE",
data: {
id: guild_id,
},
user_id: user_id,
} as GuildDeleteEvent),
emitEvent({
event: "GUILD_MEMBER_REMOVE",
data: {
guild_id: guild_id,
user: member.user,
},
guild_id: guild_id,
} as GuildMemberRemoveEvent),
]);
}
static async addRole(user_id: string, guild_id: string, role_id: string) {
const [member] = await Promise.all([
Member.findOneOrFail({
where: { id: user_id, guild_id: guild_id },
relations: ["user"], // we don't want to load the role objects just the ids
}),
await Role.findOneOrFail({ id: role_id, guild_id: guild_id }),
]);
member.role_ids.push(role_id);
member.save();
await emitEvent({
event: "GUILD_MEMBER_UPDATE",
data: {
guild_id: guild_id,
user: member.user,
roles: member.role_ids,
},
guild_id: guild_id,
} as GuildMemberUpdateEvent);
}
static async removeRole(user_id: string, guild_id: string, role_id: string) {
const [member] = await Promise.all([
Member.findOneOrFail({
where: { id: user_id, guild_id: guild_id },
relations: ["user"], // we don't want to load the role objects just the ids
}),
await Role.findOneOrFail({ id: role_id, guild_id: guild_id }),
]);
member.role_ids.remove(role_id);
member.save();
await emitEvent({
event: "GUILD_MEMBER_UPDATE",
data: {
guild_id: guild_id,
user: member.user,
roles: member.role_ids,
},
guild_id: guild_id,
} as GuildMemberUpdateEvent);
}
static async changeNickname(user_id: string, guild_id: string, nickname: string) {
const member = await Member.findOneOrFail({
where: {
id: user_id,
guild_id: guild_id,
},
relations: ["user"],
});
member.nick = nickname;
await Promise.all([
member.save(),
emitEvent({
event: "GUILD_MEMBER_UPDATE",
data: {
guild_id: guild_id,
user: member.user,
nick: nickname,
},
guild_id: guild_id,
} as GuildMemberUpdateEvent),
]);
}
static async addToGuild(user_id: string, guild_id: string) {
const user = await User.getPublicUser(user_id);
const { maxGuilds } = Config.get().limits.user;
const guild_count = await Member.count({ id: user_id });
if (guild_count >= maxGuilds) {
throw new HTTPError(`You are at the ${maxGuilds} server limit.`, 403);
}
const guild = await Guild.findOneOrFail(guild_id, {
relations: ["channels", "emojis", "members", "roles", "stickers"],
});
if (await Member.count({ id: user.id, guild_id }))
throw new HTTPError("You are already a member of this guild", 400);
const member = {
id: user_id,
guild_id: guild_id,
nick: undefined,
roles: [guild_id], // @everyone role
joined_at: new Date(),
premium_since: undefined,
deaf: false,
mute: false,
pending: false,
};
// @ts-ignore
guild.joined_at = member.joined_at;
await Promise.all([
new Member({
...member,
read_state: {},
settings: {
channel_overrides: [],
message_notifications: 0,
mobile_push: true,
mute_config: null,
muted: false,
suppress_everyone: false,
suppress_roles: false,
version: 0,
},
}).save(),
Guild.increment({ id: guild_id }, "member_count", 1),
emitEvent({
event: "GUILD_MEMBER_ADD",
data: {
...member,
user,
guild_id: guild_id,
},
guild_id: guild_id,
} as GuildMemberAddEvent),
emitEvent({
event: "GUILD_CREATE",
data: guild,
user_id,
} as GuildCreateEvent),
]);
}
}
export interface UserGuildSettings {
@@ -69,19 +251,31 @@ export interface MuteConfig {
selected_time_window: number;
}
// @ts-ignore
export interface PublicMember extends Omit<Member, "settings" | "id" | "read_state"> {
user: PublicUser;
}
export type PublicMemberKeys =
| "id"
| "guild_id"
| "nick"
| "roles"
| "joined_at"
| "pending"
| "deaf"
| "mute"
| "premium_since";
export const PublicMemberProjection = {
id: true,
guild_id: true,
nick: true,
roles: true,
joined_at: true,
pending: true,
deaf: true,
mute: true,
premium_since: true,
export const PublicMemberProjection: PublicMemberKeys[] = [
"id",
"guild_id",
"nick",
"roles",
"joined_at",
"pending",
"deaf",
"mute",
"premium_since",
];
// @ts-ignore
export type PublicMember = Pick<Member, Omit<PublicMemberKeys, "roles">> & {
user: PublicUser;
roles: string[]; // only role ids not objects
};
+27 -18
View File
@@ -17,6 +17,7 @@ import {
import { BaseClass } from "./BaseClass";
import { Guild } from "./Guild";
import { Webhook } from "./Webhook";
import { Sticker } from "./Sticker";
export enum MessageType {
DEFAULT = 0,
@@ -51,7 +52,7 @@ export class Message extends BaseClass {
channel: Channel;
@RelationId((message: Message) => message.guild)
guild_id: string;
guild_id?: string;
@JoinColumn({ name: "guild_id" })
@ManyToOne(() => Guild, (guild: Guild) => guild.id)
@@ -85,7 +86,7 @@ export class Message extends BaseClass {
@ManyToOne(() => Application, (application: Application) => application.id)
application?: Application;
@Column()
@Column({ nullable: true })
content?: string;
@Column()
@@ -96,18 +97,18 @@ export class Message extends BaseClass {
@UpdateDateColumn()
edited_timestamp?: Date;
@Column()
@Column({ nullable: true })
tts?: boolean;
@Column()
@Column({ nullable: true })
mention_everyone?: boolean;
@RelationId((message: Message) => message.mention_users)
@RelationId((message: Message) => message.mentions)
mention_user_ids: string[];
@JoinColumn({ name: "mention_user_ids" })
@ManyToMany(() => User, (user: User) => user.id)
mention_users: User[];
mentions: User[];
@RelationId((message: Message) => message.mention_roles)
mention_role_ids: string[];
@@ -123,44 +124,52 @@ export class Message extends BaseClass {
@ManyToMany(() => Channel, (channel: Channel) => channel.id)
mention_channels: Channel[];
@Column("simple-json")
@Column({ type: "simple-json" })
attachments: Attachment[];
@Column("simple-json")
@Column({ type: "simple-json" })
embeds: Embed[];
@Column("simple-json")
@Column({ type: "simple-json" })
reactions: Reaction[];
@Column({ type: "text" })
@Column({ type: "text", nullable: true })
nonce?: string | number;
@Column()
@Column({ nullable: true })
pinned?: boolean;
@Column({ type: "simple-enum", enum: MessageType })
type: MessageType;
@Column("simple-json")
@Column({ type: "simple-json", nullable: true })
activity?: {
type: number;
party_id: string;
};
@Column({ type: "bigint" })
@Column({ type: "bigint", nullable: true })
flags?: bigint;
@Column("simple-json")
stickers?: any[];
@RelationId((message: Message) => message.stickers)
sticker_ids: string[];
@Column("simple-json")
@JoinColumn({ name: "sticker_ids" })
@ManyToMany(() => Sticker, (sticker: Sticker) => sticker.id)
stickers?: Sticker[];
@Column({ type: "simple-json", nullable: true })
message_reference?: {
message_id: string;
channel_id?: string;
guild_id?: string;
};
@Column("simple-json")
@JoinColumn({ name: "message_reference_id" })
@ManyToOne(() => Message, (message: Message) => message.id)
referenced_message?: Message;
@Column({ type: "simple-json", nullable: true })
interaction?: {
id: string;
type: InteractionType;
@@ -169,7 +178,7 @@ export class Message extends BaseClass {
// user: User; // TODO: autopopulate user
};
@Column("simple-json")
@Column({ type: "simple-json" })
components: MessageComponent[];
}
+1 -1
View File
@@ -31,7 +31,7 @@ export class ReadState extends BaseClass {
@ManyToOne(() => Message, (message: Message) => message.id)
last_message?: Message;
@Column()
@Column({ nullable: true })
last_pin_timestamp?: Date;
@Column()
+3 -3
View File
@@ -1,4 +1,4 @@
import { Column, Entity, JoinColumn, ManyToOne, OneToMany, RelationId } from "typeorm";
import { Column, Entity, JoinColumn, ManyToOne, RelationId } from "typeorm";
import { BaseClass } from "./BaseClass";
import { User } from "./User";
@@ -15,10 +15,10 @@ export class Relationship extends BaseClass {
user_id: string;
@JoinColumn({ name: "user_id" })
@ManyToOne(() => User, (user: User) => user.id)
@ManyToOne(() => User, (user: User) => user.relationships)
user: User;
@Column()
@Column({ nullable: true })
nickname?: string;
@Column({ type: "simple-enum", enum: RelationshipType })
+1 -1
View File
@@ -32,7 +32,7 @@ export class Role extends BaseClass {
@Column()
position: number;
@Column({ type: "simple-json" })
@Column({ type: "simple-json", nullable: true })
tags?: {
bot_id?: string;
integration_id?: string;
+42
View File
@@ -0,0 +1,42 @@
import { Column, Entity, JoinColumn, ManyToOne } from "typeorm";
import { BaseClass } from "./BaseClass";
import { Guild } from "./Guild";
export enum StickerType {
STANDARD = 1,
GUILD = 2,
}
export enum StickerFormatType {
PNG = 1,
APNG = 2,
LOTTIE = 3,
}
@Entity("stickers")
export class Sticker extends BaseClass {
@Column()
name: string;
@Column({ nullable: true })
description?: string;
@Column()
tags: string;
@Column()
pack_id: string;
@Column({ nullable: true })
guild_id?: string;
@JoinColumn({ name: "guild_id" })
@ManyToOne(() => Guild, (guild: Guild) => guild.id)
guild?: Guild;
@Column({ type: "simple-enum", enum: StickerType })
type: StickerType;
@Column({ type: "simple-enum", enum: StickerFormatType })
format_type: StickerFormatType;
}
+1 -1
View File
@@ -5,7 +5,7 @@ import { User } from "./User";
@Entity("teams")
export class Team extends BaseClass {
@Column()
@Column({ nullable: true })
icon?: string;
@RelationId((team: Team) => team.members)
+1 -1
View File
@@ -12,7 +12,7 @@ export class TeamMember extends BaseClass {
@Column({ type: "simple-enum", enum: TeamMemberState })
membership_state: TeamMemberState;
@Column("simple-array")
@Column({ type: "simple-array" })
permissions: string[];
@RelationId((member: TeamMember) => member.team)
+3 -3
View File
@@ -11,10 +11,10 @@ export class Template extends BaseClass {
@Column()
name: string;
@Column()
@Column({ nullable: true })
description?: string;
@Column()
@Column({ nullable: true })
usage_count?: number;
@RelationId((template: Template) => template.creator)
@@ -37,6 +37,6 @@ export class Template extends BaseClass {
@ManyToOne(() => Guild, (guild: Guild) => guild.id)
source_guild: Guild;
@Column("simple-json")
@Column({ type: "simple-json" })
serialized_source_guild: Guild;
}
+99 -69
View File
@@ -1,22 +1,34 @@
import { Column, Entity, JoinColumn, OneToMany, RelationId } from "typeorm";
import { Column, Entity, FindOneOptions, JoinColumn, OneToMany, RelationId } from "typeorm";
import { BaseClass } from "./BaseClass";
import { BitField } from "../util/BitField";
import { Relationship } from "./Relationship";
import { ConnectedAccount } from "./ConnectedAccount";
import { HTTPError } from "lambert-server";
import { Guild } from "./Guild";
export const PublicUserProjection = {
username: true,
discriminator: true,
id: true,
public_flags: true,
avatar: true,
accent_color: true,
banner: true,
bio: true,
bot: true,
};
type PublicUserKeys =
| "username"
| "discriminator"
| "id"
| "public_flags"
| "avatar"
| "accent_color"
| "banner"
| "bio"
| "bot";
export const PublicUserProjection: PublicUserKeys[] = [
"username",
"discriminator",
"id",
"public_flags",
"avatar",
"accent_color",
"banner",
"bio",
"bot",
];
// Private user data that should never get sent to the client
export type PublicUser = Pick<User, PublicUserKeys>;
@Entity("users")
export class User extends BaseClass {
@@ -30,115 +42,145 @@ export class User extends BaseClass {
const number = Number(val);
if (isNaN(number)) throw new Error("invalid discriminator");
if (number <= 0 || number > 10000) throw new Error("discriminator must be between 1 and 9999");
this.discriminator = val.toString();
this.discriminator = val.toString().padStart(4, "0");
}
@Column()
@Column({ nullable: true })
avatar?: string; // hash of the user avatar
@Column()
accent_color?: number; // banner color of user
@Column({ nullable: true })
accent_color?: number = 0; // banner color of user
@Column()
@Column({ nullable: true })
banner?: string; // hash of the user banner
@Column()
@Column({ nullable: true })
phone?: string; // phone number of the user
@Column()
desktop: boolean; // if the user has desktop app installed
desktop: boolean = false; // if the user has desktop app installed
@Column()
mobile: boolean; // if the user has mobile app installed
mobile: boolean = false; // if the user has mobile app installed
@Column()
premium: boolean; // if user bought nitro
premium: boolean = false; // if user bought nitro
@Column()
premium_type: number; // nitro level
premium_type: number = 0; // nitro level
@Column()
bot: boolean; // if user is bot
bot: boolean = false; // if user is bot
@Column()
bio: string; // short description of the user (max 190 chars -> should be configurable)
bio: string = ""; // short description of the user (max 190 chars -> should be configurable)
@Column()
system: boolean; // shouldn't be used, the api sents this field type true, if the generated message comes from a system generated author
system: boolean = false; // shouldn't be used, the api sents this field type true, if the generated message comes from a system generated author
@Column()
nsfw_allowed: boolean; // if the user is older than 18 (resp. Config)
nsfw_allowed: boolean = false; // if the user is older than 18 (resp. Config)
@Column()
mfa_enabled: boolean; // if multi factor authentication is enabled
mfa_enabled: boolean = false; // if multi factor authentication is enabled
@Column()
created_at: Date; // registration date
created_at: Date = new Date(); // registration date
@Column()
verified: boolean; // if the user is offically verified
verified: boolean = false; // if the user is offically verified
@Column()
disabled: boolean; // if the account is disabled
disabled: boolean = false; // if the account is disabled
@Column()
deleted: boolean; // if the user was deleted
deleted: boolean = false; // if the user was deleted
@Column()
@Column({ nullable: true })
email?: string; // email of the user
@Column({ type: "bigint" })
flags: bigint; // UserFlags
flags: bigint = BigInt(0); // UserFlags
@Column({ type: "bigint" })
public_flags: bigint;
@RelationId((user: User) => user.guilds)
guild_ids: string[]; // array of guild ids the user is part of
@JoinColumn({ name: "guild_ids" })
@OneToMany(() => Guild, (guild: Guild) => guild.id)
guilds: Guild[];
public_flags: bigint = BigInt(0);
@RelationId((user: User) => user.relationships)
relationship_ids: string[]; // array of guild ids the user is part of
@JoinColumn({ name: "relationship_ids" })
@OneToMany(() => User, (user: User) => user.id)
@OneToMany(() => Relationship, (relationship: Relationship) => relationship.user, { cascade: true })
relationships: Relationship[];
@RelationId((user: User) => user.connected_accounts)
connected_account_ids: string[]; // array of guild ids the user is part of
@JoinColumn({ name: "connected_account_ids" })
@OneToMany(() => ConnectedAccount, (account: ConnectedAccount) => account.id)
@OneToMany(() => ConnectedAccount, (account: ConnectedAccount) => account.user)
connected_accounts: ConnectedAccount[];
@Column({ type: "simple-json", select: false })
data: {
valid_tokens_since: Date; // all tokens with a previous issue date are invalid
hash: string; // hash of the password, salt is saved in password (bcrypt)
};
hash?: string; // hash of the password, salt is saved in password (bcrypt)
} = { valid_tokens_since: new Date() };
@Column({ type: "simple-array" })
fingerprints: string[]; // array of fingerprints -> used to prevent multiple accounts
fingerprints: string[] = []; // array of fingerprints -> used to prevent multiple accounts
@Column("simple-json")
settings: UserSettings;
@Column({ type: "simple-json" })
settings: UserSettings = defaultSettings;
static async getPublicUser(user_id: string, additional_fields?: any) {
const user = await User.findOne(
{ id: user_id },
{
...PublicUserProjection,
...additional_fields,
}
);
static async getPublicUser(user_id: string, opts?: FindOneOptions<User>) {
const user = await User.findOne(user_id, {
...opts,
select: [...PublicUserProjection, ...(opts?.select || [])],
});
if (!user) throw new HTTPError("User not found", 404);
return user;
}
}
export const defaultSettings: UserSettings = {
afk_timeout: 300,
allow_accessibility_detection: true,
animate_emoji: true,
animate_stickers: 0,
contact_sync_enabled: false,
convert_emoticons: false,
custom_status: {
emoji_id: undefined,
emoji_name: undefined,
expires_at: undefined,
text: undefined,
},
default_guilds_restricted: false,
detect_platform_accounts: true,
developer_mode: false,
disable_games_tab: false,
enable_tts_command: true,
explicit_content_filter: 0,
friend_source_flags: { all: true },
gateway_connected: false,
gif_auto_play: true,
guild_folders: [],
guild_positions: [],
inline_attachment_media: true,
inline_embed_media: true,
locale: "en",
message_display_compact: false,
native_phone_integration_enabled: true,
render_embeds: true,
render_reactions: true,
restricted_guilds: [],
show_current_game: true,
status: "offline",
stream_notifications_enabled: true,
theme: "dark",
timezone_offset: 0,
// timezone_offset: // TODO: timezone from request
};
export interface UserSettings {
afk_timeout: number;
allow_accessibility_detection: boolean;
@@ -184,18 +226,6 @@ export interface UserSettings {
timezone_offset: number; // e.g -60
}
// Private user data that should never get sent to the client
export interface PublicUser {
id: string;
discriminator: string;
username: string;
avatar?: string;
accent_color?: number;
banner?: string;
public_flags: bigint;
bot: boolean;
}
export class UserFlags extends BitField {
static FLAGS = {
DISCORD_EMPLOYEE: BigInt(1) << BigInt(0),
+1 -1
View File
@@ -42,7 +42,7 @@ export class VoiceState extends BaseClass {
@Column()
self_mute: boolean;
@Column()
@Column({ nullable: true })
self_stream?: boolean;
@Column()
+3 -3
View File
@@ -18,13 +18,13 @@ export class Webhook extends BaseClass {
@Column({ type: "simple-enum", enum: WebhookType })
type: WebhookType;
@Column()
@Column({ nullable: true })
name?: string;
@Column()
@Column({ nullable: true })
avatar?: string;
@Column()
@Column({ nullable: true })
token?: string;
@RelationId((webhook: Webhook) => webhook.guild)
File diff suppressed because it is too large Load Diff