summary refs log tree commit diff
path: root/src/gateway/opcodes/StreamWatch.ts
blob: 5237e766f36690e37f86952cb234c15ec47dfe4b (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
/*
	Spacebar: A FOSS re-implementation and extension of the Discord.com backend.
	Copyright (C) 2026 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 { Not } from "typeorm";
import { Stream, StreamSession } from "@spacebar/database";
import { genVoiceToken, parseStreamKey, Payload, WebSocket } from "@spacebar/gateway";
import { Config, emitEvent, StreamCreateEvent, StreamServerUpdateEvent } from "@spacebar/util";
import { StreamWatchSchema } from "@spacebar/schemas";
import { check } from "./instanceOf";

export async function onStreamWatch(this: WebSocket, data: Payload) {
    const startTime = Date.now();
    check.call(this, StreamWatchSchema, data.d);
    const body = data.d as StreamWatchSchema;

    // TODO: apply perms: check if user is allowed to watch

    let parsedKey: {
        type: "guild" | "call";
        channelId: string;
        guildId?: string;
        userId: string;
    };

    try {
        parsedKey = parseStreamKey(body.stream_key);
    } catch (e) {
        return this.rawSocket.close(4000, "Invalid stream key");
    }

    const { type, channelId, guildId, userId } = parsedKey;

    const stream = await Stream.findOne({
        where: { channel_id: channelId, owner_id: userId },
        relations: { channel: true },
    });

    if (!stream) return this.rawSocket.close(4000, "Invalid stream key");

    if (type === "guild" && stream.channel.guild_id != guildId) return this.rawSocket.close(4000, "Invalid stream key");

    const regions = Config.get().regions;
    const guildRegion = regions.available.find((r) => r.endpoint === stream.endpoint);

    if (!guildRegion) return this.rawSocket.close(4000, "Unknown region");

    const streamSession = StreamSession.create({
        stream_id: stream.id,
        user_id: this.user_id,
        session_id: this.session_id,
        token: genVoiceToken(),
    });

    await streamSession.save();

    // get the viewers: stream session tokens for this stream that have been used but not including stream owner
    const viewers = await StreamSession.find({
        where: {
            stream_id: stream.id,
            used: true,
            user_id: Not(stream.owner_id),
        },
    });

    await emitEvent({
        event: "STREAM_CREATE",
        data: {
            stream_key: body.stream_key,
            rtc_server_id: stream.id, // for voice connections in guilds it is guild_id, for dm voice calls it seems to be DM channel id, for GoLive streams a generated number
            viewer_ids: viewers.map((v) => v.user_id),
            region: guildRegion.name,
            paused: false,
        },
        channel_id: channelId,
        user_id: this.user_id,
    } satisfies StreamCreateEvent);

    await emitEvent({
        event: "STREAM_SERVER_UPDATE",
        data: {
            token: streamSession.token,
            stream_key: body.stream_key,
            guild_id: null, // not sure why its always null
            endpoint: stream.endpoint,
        },
        user_id: this.user_id,
    } satisfies StreamServerUpdateEvent);

    console.log(`[Gateway/${this.user_id}] STREAM_WATCH for user ${this.user_id} in channel ${channelId} with stream key ${body.stream_key} in ${Date.now() - startTime}ms`);
}