summary refs log tree commit diff
path: root/src/gateway/opcodes
diff options
context:
space:
mode:
authorMadeline <46743919+MaddyUnderStars@users.noreply.github.com>2023-01-20 18:10:47 +1100
committerGitHub <noreply@github.com>2023-01-20 18:10:47 +1100
commit084dc0be08555891cad4c2bb984822a62ec5ec9f (patch)
treeed2ca0fafefa2224ae32761f955f63935422a97d /src/gateway/opcodes
parentfix: route file regex (#956) (diff)
downloadserver-084dc0be08555891cad4c2bb984822a62ec5ec9f.tar.xz
Add ESLint (#941)
* Add eslint, switch to lint-staged for precommit

* Fix all ESLint errors

* Update GH workflow to check prettier and eslint
Diffstat (limited to 'src/gateway/opcodes')
-rw-r--r--src/gateway/opcodes/Heartbeat.ts4
-rw-r--r--src/gateway/opcodes/Identify.ts46
-rw-r--r--src/gateway/opcodes/LazyRequest.ts67
-rw-r--r--src/gateway/opcodes/RequestGuildMembers.ts4
-rw-r--r--src/gateway/opcodes/Resume.ts4
-rw-r--r--src/gateway/opcodes/VoiceStateUpdate.ts1
-rw-r--r--src/gateway/opcodes/index.ts4
-rw-r--r--src/gateway/opcodes/instanceOf.ts2
8 files changed, 68 insertions, 64 deletions
diff --git a/src/gateway/opcodes/Heartbeat.ts b/src/gateway/opcodes/Heartbeat.ts
index b7f21a56..77c8671f 100644
--- a/src/gateway/opcodes/Heartbeat.ts
+++ b/src/gateway/opcodes/Heartbeat.ts
@@ -16,11 +16,11 @@
 	along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
 
-import { Payload, WebSocket } from "@fosscord/gateway";
+import { WebSocket } from "@fosscord/gateway";
 import { setHeartbeat } from "../util/Heartbeat";
 import { Send } from "../util/Send";
 
-export async function onHeartbeat(this: WebSocket, data: Payload) {
+export async function onHeartbeat(this: WebSocket) {
 	// TODO: validate payload
 
 	setHeartbeat(this);
diff --git a/src/gateway/opcodes/Identify.ts b/src/gateway/opcodes/Identify.ts
index 8d762967..030ca66e 100644
--- a/src/gateway/opcodes/Identify.ts
+++ b/src/gateway/opcodes/Identify.ts
@@ -42,13 +42,13 @@ import {
 	UserGuildSettings,
 	ReadyGuildDTO,
 	Guild,
+	UserTokenData,
 } from "@fosscord/util";
 import { Send } from "../util/Send";
 import { CLOSECODES, OPCODES } from "../util/Constants";
-import { genSessionId } from "../util/SessionUtils";
 import { setupListener } from "../listener/listener";
 // import experiments from "./experiments.json";
-const experiments: any = [];
+const experiments: unknown[] = [];
 import { check } from "./instanceOf";
 import { Recipient } from "@fosscord/util";
 
@@ -56,6 +56,8 @@ import { Recipient } from "@fosscord/util";
 // TODO: check privileged intents, if defined in the config
 // TODO: check if already identified
 
+// TODO: Refactor identify ( and lazyrequest, tbh )
+
 export async function onIdentify(this: WebSocket, data: Payload) {
 	clearTimeout(this.readyTimeout);
 	// TODO: is this needed now that we use `json-bigint`?
@@ -65,15 +67,16 @@ export async function onIdentify(this: WebSocket, data: Payload) {
 
 	const identify: IdentifySchema = data.d;
 
+	let decoded: UserTokenData["decoded"];
 	try {
 		const { jwtSecret } = Config.get().security;
-		var { decoded } = await checkToken(identify.token, jwtSecret); // will throw an error if invalid
+		decoded = (await checkToken(identify.token, jwtSecret)).decoded; // will throw an error if invalid
 	} catch (error) {
 		console.error("invalid token", error);
 		return this.close(CLOSECODES.Authentication_failed);
 	}
 	this.user_id = decoded.id;
-	let session_id = this.session_id;
+	const session_id = this.session_id;
 
 	const [user, read_states, members, recipients, session, application] =
 		await Promise.all([
@@ -144,7 +147,7 @@ export async function onIdentify(this: WebSocket, data: Payload) {
 			return this.close(CLOSECODES.Invalid_shard);
 		}
 	}
-	var users: PublicUser[] = [];
+	let users: PublicUser[] = [];
 
 	const merged_members = members.map((x: Member) => {
 		return [
@@ -156,18 +159,18 @@ export async function onIdentify(this: WebSocket, data: Payload) {
 			},
 		];
 	}) as PublicMember[][];
-	let guilds = members.map((x) => ({ ...x.guild, joined_at: x.joined_at }));
+	// TODO: This type is bad.
+	let guilds: Partial<Guild>[] = members.map((x) => ({
+		...x.guild,
+		joined_at: x.joined_at,
+	}));
 
 	const pending_guilds: typeof guilds = [];
-	// @ts-ignore
-	guilds = guilds.map((guild) => {
-		if (user.bot) {
+	if (user.bot)
+		guilds = guilds.map((guild) => {
 			pending_guilds.push(guild);
 			return { id: guild.id, unavailable: true };
-		}
-
-		return guild;
-	});
+		});
 
 	// TODO: Rewrite this. Perhaps a DTO?
 	const user_guild_settings_entries = members.map((x) => ({
@@ -180,24 +183,25 @@ export async function onIdentify(this: WebSocket, data: Payload) {
 			...y[1],
 			channel_id: y[0],
 		})),
-	})) as any as UserGuildSettings[];
+	})) as unknown as UserGuildSettings[];
 
 	const channels = recipients.map((x) => {
+		// eslint-disable-next-line @typescript-eslint/ban-ts-comment
 		//@ts-ignore
-		x.channel.recipients = x.channel.recipients?.map((x) =>
+		x.channel.recipients = x.channel.recipients.map((x) =>
 			x.user.toPublicUser(),
 		);
 		//TODO is this needed? check if users in group dm that are not friends are sent in the READY event
 		users = users.concat(x.channel.recipients as unknown as User[]);
 		if (x.channel.isDm()) {
-			x.channel.recipients = x.channel.recipients!.filter(
+			x.channel.recipients = x.channel.recipients?.filter(
 				(x) => x.id !== this.user_id,
 			);
 		}
 		return x.channel;
 	});
 
-	for (let relation of user.relationships) {
+	for (const relation of user.relationships) {
 		const related_user = relation.to;
 		const public_related_user = {
 			username: related_user.username,
@@ -236,7 +240,7 @@ export async function onIdentify(this: WebSocket, data: Payload) {
 		} as PresenceUpdateEvent);
 	});
 
-	read_states.forEach((s: any) => {
+	read_states.forEach((s: Partial<ReadState>) => {
 		s.id = s.channel_id;
 		delete s.user_id;
 		delete s.channel_id;
@@ -275,10 +279,11 @@ export async function onIdentify(this: WebSocket, data: Payload) {
 		}, //TODO: check this code!
 		user: privateUser,
 		user_settings: user.settings,
+		// eslint-disable-next-line @typescript-eslint/ban-ts-comment
 		// @ts-ignore
-		guilds: guilds.map((x) => {
+		guilds: guilds.map((x: Guild & { joined_at: Date }) => {
 			return {
-				...new ReadyGuildDTO(x as Guild & { joined_at: Date }).toJSON(),
+				...new ReadyGuildDTO(x).toJSON(),
 				guild_hashes: {},
 				joined_at: x.joined_at,
 			};
@@ -307,6 +312,7 @@ export async function onIdentify(this: WebSocket, data: Payload) {
 		},
 		country_code: user.settings.locale,
 		friend_suggestion_count: 0, // TODO
+		// eslint-disable-next-line @typescript-eslint/ban-ts-comment
 		// @ts-ignore
 		experiments: experiments, // TODO
 		guild_join_requests: [], // TODO what is this?
diff --git a/src/gateway/opcodes/LazyRequest.ts b/src/gateway/opcodes/LazyRequest.ts
index d4b612b8..93524058 100644
--- a/src/gateway/opcodes/LazyRequest.ts
+++ b/src/gateway/opcodes/LazyRequest.ts
@@ -46,24 +46,25 @@ async function getMembers(guild_id: string, range: [number, number]) {
 
 	let members: Member[] = [];
 	try {
-		members = await getDatabase()!
-			.getRepository(Member)
-			.createQueryBuilder("member")
-			.where("member.guild_id = :guild_id", { guild_id })
-			.leftJoinAndSelect("member.roles", "role")
-			.leftJoinAndSelect("member.user", "user")
-			.leftJoinAndSelect("user.sessions", "session")
-			.addSelect("user.settings")
-			.addSelect(
-				"CASE WHEN session.status = 'offline' THEN 0 ELSE 1 END",
-				"_status",
-			)
-			.orderBy("role.position", "DESC")
-			.addOrderBy("_status", "DESC")
-			.addOrderBy("user.username", "ASC")
-			.offset(Number(range[0]) || 0)
-			.limit(Number(range[1]) || 100)
-			.getMany();
+		members =
+			(await getDatabase()
+				?.getRepository(Member)
+				.createQueryBuilder("member")
+				.where("member.guild_id = :guild_id", { guild_id })
+				.leftJoinAndSelect("member.roles", "role")
+				.leftJoinAndSelect("member.user", "user")
+				.leftJoinAndSelect("user.sessions", "session")
+				.addSelect("user.settings")
+				.addSelect(
+					"CASE WHEN session.status = 'offline' THEN 0 ELSE 1 END",
+					"_status",
+				)
+				.orderBy("role.position", "DESC")
+				.addOrderBy("_status", "DESC")
+				.addOrderBy("user.username", "ASC")
+				.offset(Number(range[0]) || 0)
+				.limit(Number(range[1]) || 100)
+				.getMany()) ?? [];
 	} catch (e) {
 		console.error(`LazyRequest`, e);
 	}
@@ -77,7 +78,7 @@ async function getMembers(guild_id: string, range: [number, number]) {
 		};
 	}
 
-	const groups = [] as any[];
+	const groups = [];
 	const items = [];
 	const member_roles = members
 		.map((m) => m.roles)
@@ -93,10 +94,9 @@ async function getMembers(guild_id: string, range: [number, number]) {
 	const offlineItems = [];
 
 	for (const role of member_roles) {
-		// @ts-ignore
-		const [role_members, other_members]: Member[][] = partition(
+		const [role_members, other_members] = partition(
 			members,
-			(m: Member) => m.roles.find((r) => r.id === role.id),
+			(m: Member) => !!m.roles.find((r) => r.id === role.id),
 		);
 		const group = {
 			count: role_members.length,
@@ -126,7 +126,7 @@ async function getMembers(guild_id: string, range: [number, number]) {
 					(a.activities.length - b.activities.length) * 2
 				);
 			});
-			var session: Session | undefined = sessions.first();
+			const session: Session | undefined = sessions.first();
 
 			if (session?.status == "offline") {
 				session.status = member?.user?.settings?.status || "online";
@@ -189,7 +189,9 @@ async function getMembers(guild_id: string, range: [number, number]) {
 export async function onLazyRequest(this: WebSocket, { d }: Payload) {
 	// TODO: check data
 	check.call(this, LazyRequestSchema, d);
+	// eslint-disable-next-line @typescript-eslint/no-unused-vars
 	const { guild_id, typing, channels, activities } = d as LazyRequestSchema;
+	if (!channels) throw new Error("Must provide channel ranges");
 
 	const channel_id = Object.keys(channels || {}).first();
 	if (!channel_id) return;
@@ -197,7 +199,7 @@ export async function onLazyRequest(this: WebSocket, { d }: Payload) {
 	const permissions = await getPermission(this.user_id, guild_id, channel_id);
 	permissions.hasThrow("VIEW_CHANNEL");
 
-	const ranges = channels![channel_id];
+	const ranges = channels[channel_id];
 	if (!Array.isArray(ranges)) throw new Error("Not a valid Array");
 
 	const member_count = await Member.count({ where: { guild_id } });
@@ -244,15 +246,10 @@ 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]
-				: [pass, [...fail, elem]];
-		},
-		[[], []],
-	);
+/* https://stackoverflow.com/a/50636286 */
+function partition<T>(array: T[], filter: (elem: T) => boolean) {
+	const pass: T[] = [],
+		fail: T[] = [];
+	array.forEach((e) => (filter(e) ? pass : fail).push(e));
+	return [pass, fail];
 }
diff --git a/src/gateway/opcodes/RequestGuildMembers.ts b/src/gateway/opcodes/RequestGuildMembers.ts
index d669b30e..7822813b 100644
--- a/src/gateway/opcodes/RequestGuildMembers.ts
+++ b/src/gateway/opcodes/RequestGuildMembers.ts
@@ -16,8 +16,8 @@
 	along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
 
-import { Payload, WebSocket } from "@fosscord/gateway";
+import { WebSocket } from "@fosscord/gateway";
 
-export function onRequestGuildMembers(this: WebSocket, data: Payload) {
+export function onRequestGuildMembers(this: WebSocket) {
 	// return this.close(CLOSECODES.Unknown_error);
 }
diff --git a/src/gateway/opcodes/Resume.ts b/src/gateway/opcodes/Resume.ts
index d4bd5320..a8650cc4 100644
--- a/src/gateway/opcodes/Resume.ts
+++ b/src/gateway/opcodes/Resume.ts
@@ -16,10 +16,10 @@
 	along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
 
-import { WebSocket, Payload } from "@fosscord/gateway";
+import { WebSocket } from "@fosscord/gateway";
 import { Send } from "../util/Send";
 
-export async function onResume(this: WebSocket, data: Payload) {
+export async function onResume(this: WebSocket) {
 	console.log("Got Resume -> cancel not implemented");
 	await Send(this, {
 		op: 9,
diff --git a/src/gateway/opcodes/VoiceStateUpdate.ts b/src/gateway/opcodes/VoiceStateUpdate.ts
index 5ee02e82..d300d7b7 100644
--- a/src/gateway/opcodes/VoiceStateUpdate.ts
+++ b/src/gateway/opcodes/VoiceStateUpdate.ts
@@ -99,6 +99,7 @@ export async function onVoiceStateUpdate(this: WebSocket, data: Payload) {
 		voiceState.token = genVoiceToken();
 	voiceState.session_id = this.session_id;
 
+	// eslint-disable-next-line @typescript-eslint/no-unused-vars
 	const { id, ...newObj } = voiceState;
 
 	await Promise.all([
diff --git a/src/gateway/opcodes/index.ts b/src/gateway/opcodes/index.ts
index 05e8964b..1e32f1e6 100644
--- a/src/gateway/opcodes/index.ts
+++ b/src/gateway/opcodes/index.ts
@@ -25,7 +25,7 @@ import { onRequestGuildMembers } from "./RequestGuildMembers";
 import { onResume } from "./Resume";
 import { onVoiceStateUpdate } from "./VoiceStateUpdate";
 
-export type OPCodeHandler = (this: WebSocket, data: Payload) => any;
+export type OPCodeHandler = (this: WebSocket, data: Payload) => unknown;
 
 export default {
 	1: onHeartbeat,
@@ -40,4 +40,4 @@ export default {
 	// 10: Hello
 	// 13: Dm_update
 	14: onLazyRequest,
-};
+} as { [key: number]: OPCodeHandler };
diff --git a/src/gateway/opcodes/instanceOf.ts b/src/gateway/opcodes/instanceOf.ts
index 17de0a67..6c23cb08 100644
--- a/src/gateway/opcodes/instanceOf.ts
+++ b/src/gateway/opcodes/instanceOf.ts
@@ -20,7 +20,7 @@ import { instanceOf } from "lambert-server";
 import { WebSocket } from "@fosscord/gateway";
 import { CLOSECODES } from "../util/Constants";
 
-export function check(this: WebSocket, schema: any, data: any) {
+export function check(this: WebSocket, schema: unknown, data: unknown) {
 	try {
 		const error = instanceOf(schema, data, { path: "body" });
 		if (error !== true) {