summary refs log tree commit diff
path: root/src/gateway/opcodes/Identify.ts
blob: 030ca66ee27dc7825264760553fa877fc91943ea (plain) (blame)
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/*
	Fosscord: A FOSS re-implementation and extension of the Discord.com backend.
	Copyright (C) 2023 Fosscord and Fosscord Contributors
	
	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published
	by the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.
	
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.
	
	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

import { WebSocket, Payload } from "@fosscord/gateway";
import {
	checkToken,
	Intents,
	Member,
	ReadyEventData,
	User,
	Session,
	EVENTEnum,
	Config,
	PublicMember,
	PublicUser,
	PrivateUserProjection,
	ReadState,
	Application,
	emitEvent,
	SessionsReplace,
	PrivateSessionProjection,
	MemberPrivateProjection,
	PresenceUpdateEvent,
	UserSettings,
	IdentifySchema,
	DefaultUserGuildSettings,
	UserGuildSettings,
	ReadyGuildDTO,
	Guild,
	UserTokenData,
} from "@fosscord/util";
import { Send } from "../util/Send";
import { CLOSECODES, OPCODES } from "../util/Constants";
import { setupListener } from "../listener/listener";
// import experiments from "./experiments.json";
const experiments: unknown[] = [];
import { check } from "./instanceOf";
import { Recipient } from "@fosscord/util";

// TODO: user sharding
// 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`?
	if (typeof data.d?.client_state?.highest_last_message_id === "number")
		data.d.client_state.highest_last_message_id += "";
	check.call(this, IdentifySchema, data.d);

	const identify: IdentifySchema = data.d;

	let decoded: UserTokenData["decoded"];
	try {
		const { jwtSecret } = Config.get().security;
		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;
	const session_id = this.session_id;

	const [user, read_states, members, recipients, session, application] =
		await Promise.all([
			User.findOneOrFail({
				where: { id: this.user_id },
				relations: ["relationships", "relationships.to", "settings"],
				select: [...PrivateUserProjection, "relationships"],
			}),
			ReadState.find({ where: { user_id: this.user_id } }),
			Member.find({
				where: { id: this.user_id },
				select: MemberPrivateProjection,
				relations: [
					"guild",
					"guild.channels",
					"guild.emojis",
					"guild.roles",
					"guild.stickers",
					"user",
					"roles",
				],
			}),
			Recipient.find({
				where: { user_id: this.user_id, closed: false },
				relations: [
					"channel",
					"channel.recipients",
					"channel.recipients.user",
				],
				// TODO: public user selection
			}),
			// save the session and delete it when the websocket is closed
			Session.create({
				user_id: this.user_id,
				session_id: session_id,
				// TODO: check if status is only one of: online, dnd, offline, idle
				status: identify.presence?.status || "offline", //does the session always start as online?
				client_info: {
					//TODO read from identity
					client: "desktop",
					os: identify.properties?.os,
					version: 0,
				},
				activities: [],
			}).save(),
			Application.findOne({ where: { id: this.user_id } }),
		]);

	if (!user) return this.close(CLOSECODES.Authentication_failed);
	if (!user.settings) {
		user.settings = new UserSettings();
		await user.settings.save();
	}

	if (!identify.intents) identify.intents = BigInt("0x6ffffffff");
	this.intents = new Intents(identify.intents);
	if (identify.shard) {
		this.shard_id = identify.shard[0];
		this.shard_count = identify.shard[1];
		if (
			this.shard_count == null ||
			this.shard_id == null ||
			this.shard_id >= this.shard_count ||
			this.shard_id < 0 ||
			this.shard_count <= 0
		) {
			console.log(identify.shard);
			return this.close(CLOSECODES.Invalid_shard);
		}
	}
	let users: PublicUser[] = [];

	const merged_members = members.map((x: Member) => {
		return [
			{
				...x,
				roles: x.roles.map((x) => x.id),
				settings: undefined,
				guild: undefined,
			},
		];
	}) as PublicMember[][];
	// TODO: This type is bad.
	let guilds: Partial<Guild>[] = members.map((x) => ({
		...x.guild,
		joined_at: x.joined_at,
	}));

	const pending_guilds: typeof guilds = [];
	if (user.bot)
		guilds = guilds.map((guild) => {
			pending_guilds.push(guild);
			return { id: guild.id, unavailable: true };
		});

	// TODO: Rewrite this. Perhaps a DTO?
	const user_guild_settings_entries = members.map((x) => ({
		...DefaultUserGuildSettings,
		...x.settings,
		guild_id: x.guild.id,
		channel_overrides: Object.entries(
			x.settings.channel_overrides ?? {},
		).map((y) => ({
			...y[1],
			channel_id: y[0],
		})),
	})) 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.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) => x.id !== this.user_id,
			);
		}
		return x.channel;
	});

	for (const relation of user.relationships) {
		const related_user = relation.to;
		const public_related_user = {
			username: related_user.username,
			discriminator: related_user.discriminator,
			id: related_user.id,
			public_flags: related_user.public_flags,
			avatar: related_user.avatar,
			bot: related_user.bot,
			bio: related_user.bio,
			premium_since: user.premium_since,
			premium_type: user.premium_type,
			accent_color: related_user.accent_color,
		};
		users.push(public_related_user);
	}

	setImmediate(async () => {
		// run in seperate "promise context" because ready payload is not dependent on those events
		emitEvent({
			event: "SESSIONS_REPLACE",
			user_id: this.user_id,
			data: await Session.find({
				where: { user_id: this.user_id },
				select: PrivateSessionProjection,
			}),
		} as SessionsReplace);
		emitEvent({
			event: "PRESENCE_UPDATE",
			user_id: this.user_id,
			data: {
				user: await User.getPublicUser(this.user_id),
				activities: session.activities,
				client_status: session?.client_info,
				status: session.status,
			},
		} as PresenceUpdateEvent);
	});

	read_states.forEach((s: Partial<ReadState>) => {
		s.id = s.channel_id;
		delete s.user_id;
		delete s.channel_id;
	});

	const privateUser = {
		avatar: user.avatar,
		mobile: user.mobile,
		desktop: user.desktop,
		discriminator: user.discriminator,
		email: user.email,
		flags: user.flags,
		id: user.id,
		mfa_enabled: user.mfa_enabled,
		nsfw_allowed: user.nsfw_allowed,
		phone: user.phone,
		premium: user.premium,
		premium_type: user.premium_type,
		public_flags: user.public_flags,
		premium_usage_flags: user.premium_usage_flags,
		purchased_flags: user.purchased_flags,
		username: user.username,
		verified: user.verified,
		bot: user.bot,
		accent_color: user.accent_color,
		banner: user.banner,
		bio: user.bio,
		premium_since: user.premium_since,
	};

	const d: ReadyEventData = {
		v: 9,
		application: {
			id: application?.id ?? "",
			flags: application?.flags ?? 0,
		}, //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: Guild & { joined_at: Date }) => {
			return {
				...new ReadyGuildDTO(x).toJSON(),
				guild_hashes: {},
				joined_at: x.joined_at,
			};
		}),
		guild_experiments: [], // TODO
		geo_ordered_rtc_regions: [], // TODO
		relationships: user.relationships.map((x) => x.toPublicRelationship()),
		read_state: {
			entries: read_states,
			partial: false,
			version: 304128,
		},
		user_guild_settings: {
			entries: user_guild_settings_entries,
			partial: false, // TODO partial
			version: 642,
		},
		private_channels: channels,
		session_id: session_id,
		analytics_token: "", // TODO
		connected_accounts: [], // TODO
		consents: {
			personalization: {
				consented: false, // TODO
			},
		},
		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?
		users: users.filter((x) => x).unique(),
		merged_members: merged_members,
		// shard // TODO: only for user sharding
		sessions: [], // TODO:
	};

	// TODO: send real proper data structure
	await Send(this, {
		op: OPCODES.Dispatch,
		t: EVENTEnum.Ready,
		s: this.sequence++,
		d,
	});

	await Promise.all(
		pending_guilds.map((guild) =>
			Send(this, {
				op: OPCODES.Dispatch,
				t: EVENTEnum.GuildCreate,
				s: this.sequence++,
				d: guild,
			})?.catch(console.error),
		),
	);

	//TODO send READY_SUPPLEMENTAL
	//TODO send GUILD_MEMBER_LIST_UPDATE
	//TODO send SESSIONS_REPLACE
	//TODO send VOICE_STATE_UPDATE to let the client know if another device is already connected to a voice channel

	await setupListener.call(this);

	// console.log(`${this.ipAddress} identified as ${d.user.id}`);
}