summary refs log tree commit diff
path: root/src/webrtc/events/Connection.ts
blob: d8b4d68306230ea02034dd77b4d44b57bdadadcf (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
/*
	Spacebar: A FOSS re-implementation and extension of the Discord.com backend.
	Copyright (C) 2023 Spacebar and Spacebar 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 { CLOSECODES, Send, setHeartbeat, WebSocket } from "@fosscord/gateway";
import { IncomingMessage } from "http";
import { URL } from "url";
import WS from "ws";
import { VoiceOPCodes } from "../util";
import { onClose } from "./Close";
import { onMessage } from "./Message";

// TODO: check rate limit
// TODO: specify rate limit in config
// TODO: check msg max size

export async function Connection(
	this: WS.Server,
	socket: WebSocket,
	request: IncomingMessage,
) {
	try {
		socket.on("close", onClose.bind(socket));
		socket.on("message", onMessage.bind(socket));
		console.log("[WebRTC] new connection", request.url);

		if (process.env.WS_LOGEVENTS) {
			[
				"close",
				"error",
				"upgrade",
				//"message",
				"open",
				"ping",
				"pong",
				"unexpected-response",
			].forEach((x) => {
				socket.on(x, (y) => console.log("[WebRTC]", x, y));
			});
		}

		const { searchParams } = new URL(`http://localhost${request.url}`);

		socket.encoding = "json";
		socket.version = Number(searchParams.get("v")) || 5;
		if (socket.version < 3)
			return socket.close(CLOSECODES.Unknown_error, "invalid version");

		setHeartbeat(socket);

		socket.readyTimeout = setTimeout(() => {
			return socket.close(CLOSECODES.Session_timed_out);
		}, 1000 * 30);

		await Send(socket, {
			op: VoiceOPCodes.HELLO,
			d: {
				heartbeat_interval: 1000 * 30,
			},
		});
	} catch (error) {
		console.error("[WebRTC]", error);
		return socket.close(CLOSECODES.Unknown_error);
	}
}