aboutsummaryrefslogtreecommitdiff
path: root/src/lib/common/moderation.ts
blob: c8779fc37e00143d98a4eff204dea0ea5493695a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import { Snowflake } from 'discord-api-types';
import {
	ActivePunishment,
	ActivePunishmentType,
	BushGuildMember,
	BushGuildMemberResolvable,
	BushGuildResolvable,
	Guild,
	ModLog,
	ModLogType
} from '..';

export class Moderation {
	/**
	 * Checks if a moderator can perform a moderation action on another user.
	 * @param moderator - The person trying to perform the action.
	 * @param victim - The person getting punished.
	 * @param type - The type of punishment - used to format the response.
	 * @param checkModerator - Whether or not to check if the victim is a moderator.
	 */
	public static async permissionCheck(
		moderator: BushGuildMember,
		victim: BushGuildMember,
		type: 'mute' | 'unmute' | 'warn' | 'kick' | 'ban' | 'unban' | 'add a punishment role to' | 'remove a punishment role from',
		checkModerator = true,
		force = false
	): Promise<true | string> {
		if (force) return true;

		// If the victim is not in the guild anymore it will be undefined
		if ((!victim || !victim.guild) && !['ban', 'unban'].includes(type)) return true;

		if (moderator.guild.id !== victim.guild.id) {
			throw new Error('moderator and victim not in same guild');
		}

		const isOwner = moderator.guild.ownerId === moderator.id;
		if (moderator.id === victim.id && !type.startsWith('un')) {
			return `${util.emojis.error} You cannot ${type} yourself.`;
		}
		if (
			moderator.roles.highest.position <= victim.roles.highest.position &&
			!isOwner &&
			!(type.startsWith('un') && moderator.id === victim.id)
		) {
			return `${util.emojis.error} You cannot ${type} **${victim.user.tag}** because they have higher or equal role hierarchy as you do.`;
		}
		if (
			victim.roles.highest.position >= victim.guild.me!.roles.highest.position &&
			!(type.startsWith('un') && moderator.id === victim.id)
		) {
			return `${util.emojis.error} You cannot ${type} **${victim.user.tag}** because they have higher or equal role hierarchy as I do.`;
		}
		if (checkModerator && victim.permissions.has('MANAGE_MESSAGES') && !(type.startsWith('un') && moderator.id === victim.id)) {
			if (await moderator.guild.hasFeature('modsCanPunishMods')) {
				return true;
			} else {
				return `${util.emojis.error} You cannot ${type} **${victim.user.tag}** because they are a moderator.`;
			}
		}
		return true;
	}

	public static async createModLogEntry(
		options: {
			type: ModLogType;
			user: BushGuildMemberResolvable;
			moderator: BushGuildMemberResolvable;
			reason: string | undefined | null;
			duration?: number;
			guild: BushGuildResolvable;
			pseudo?: boolean;
			evidence?: string;
		},
		getCaseNumber = false
	): Promise<{ log: ModLog | null; caseNum: number | null }> {
		const user = (await util.resolveNonCachedUser(options.user))!.id;
		const moderator = (await util.resolveNonCachedUser(options.moderator))!.id;
		const guild = client.guilds.resolveId(options.guild)!;
		// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
		const duration = options.duration || undefined;

		// If guild does not exist create it so the modlog can reference a guild.
		await Guild.findOrCreate({
			where: {
				id: guild
			},
			defaults: {
				id: guild
			}
		});

		const modLogEntry = ModLog.build({
			type: options.type,
			user,
			moderator,
			reason: options.reason,
			duration: duration,
			guild,
			pseudo: options.pseudo ?? false,
			evidence: options.evidence
		});
		const saveResult: ModLog | null = await modLogEntry.save().catch(async (e) => {
			await util.handleError('createModLogEntry', e);
			return null;
		});

		if (!getCaseNumber) return { log: saveResult, caseNum: null };

		const caseNum = (await ModLog.findAll({ where: { type: options.type, user: user, guild: guild, hidden: 'false' } }))
			?.length;
		return { log: saveResult, caseNum };
	}

	public static async createPunishmentEntry(options: {
		type: 'mute' | 'ban' | 'role' | 'block';
		user: BushGuildMemberResolvable;
		duration: number | undefined;
		guild: BushGuildResolvable;
		modlog: string;
		extraInfo?: Snowflake;
	}): Promise<ActivePunishment | null> {
		const expires = options.duration ? new Date(+new Date() + options.duration ?? 0) : undefined;
		const user = (await util.resolveNonCachedUser(options.user))!.id;
		const guild = client.guilds.resolveId(options.guild)!;
		const type = this.#findTypeEnum(options.type)!;

		const entry = ActivePunishment.build(
			options.extraInfo
				? { user, type, guild, expires, modlog: options.modlog, extraInfo: options.extraInfo }
				: { user, type, guild, expires, modlog: options.modlog }
		);
		return await entry.save().catch(async (e) => {
			await util.handleError('createPunishmentEntry', e);
			return null;
		});
	}

	public static async removePunishmentEntry(options: {
		type: 'mute' | 'ban' | 'role' | 'block';
		user: BushGuildMemberResolvable;
		guild: BushGuildResolvable;
		extraInfo?: Snowflake;
	}): Promise<boolean> {
		const user = await util.resolveNonCachedUser(options.user);
		const guild = client.guilds.resolveId(options.guild);
		const type = this.#findTypeEnum(options.type);

		if (!user || !guild) return false;

		let success = true;

		const entries = await ActivePunishment.findAll({
			// finding all cases of a certain type incase there were duplicates or something
			where: options.extraInfo
				? { user: user.id, guild: guild, type, extraInfo: options.extraInfo }
				: { user: user.id, guild: guild, type }
		}).catch(async (e) => {
			await util.handleError('removePunishmentEntry', e);
			success = false;
		});
		if (entries) {
			// eslint-disable-next-line @typescript-eslint/no-misused-promises
			entries.forEach(async (entry) => {
				await entry.destroy().catch(async (e) => {
					await util.handleError('removePunishmentEntry', e);
				});
				success = false;
			});
		}
		return success;
	}

	static #findTypeEnum(type: 'mute' | 'ban' | 'role' | 'block') {
		const typeMap = {
			['mute']: ActivePunishmentType.MUTE,
			['ban']: ActivePunishmentType.BAN,
			['role']: ActivePunishmentType.ROLE,
			['block']: ActivePunishmentType.BLOCK
		};
		return typeMap[type];
	}
}