summary refs log tree commit diff
path: root/src/api/routes/guilds/#guild_id/widget.json.ts
blob: aae5581fa103efd56616f6a9cd9045f319b7255b (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
/*
	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 { randomString, route } from "@spacebar/api";
import { Channel, Config, DiscordApiErrors, Guild, Invite, Member, Permissions } from "@spacebar/util";
import { Request, Response, Router } from "express";
import { ChannelType, GuildWidgetJsonResponse } from "@spacebar/schemas";

const router: Router = Router({ mergeParams: true });

// Undocumented API notes:
// An invite is created for the widget_channel_id on request (only if an existing one created by the widget doesn't already exist)
// This invite created doesn't include an inviter object like user created ones and has a default expiry of 24 hours
// Missing user object information is intentional (https://github.com/discord/discord-api-docs/issues/1287)
// channels returns voice channel objects where @everyone has the CONNECT permission
// members (max 100 returned) is a sample of all members, and bots par invisible status, there exists some alphabetical distribution pattern between the members returned

// https://discord.com/developers/docs/resources/guild#get-guild-widget
const expiryTime = 1000 * 60 * 5; // 5 minutes
const jsonDataCache = new Map<string, { data: Promise<GuildWidgetJsonResponse>; expiry: Date }>();

router.get(
    "/",
    route({
        responses: {
            200: {
                body: "GuildWidgetJsonResponse",
            },
            404: {
                body: "APIErrorResponse",
            },
        },
    }),
    async (req: Request, res: Response) => {
        const { guild_id } = req.params;

        let cacheEntry = jsonDataCache.get(guild_id);
        if (!cacheEntry || cacheEntry.expiry.getTime() < Date.now()) {
            // Create new cache entry
            const dataPromise = getWidgetJsonData(guild_id);
            cacheEntry = {
                data: dataPromise,
                expiry: new Date(Date.now() + expiryTime),
            };
            console.log("[Widget] Caching widget data for guild", guild_id);
            jsonDataCache.set(guild_id, cacheEntry);
        }

        const cacheRemainingSeconds = Math.floor((cacheEntry.expiry.getTime() - Date.now()) / 1000);
        res.set("Cache-Control", `public, max-age=${cacheRemainingSeconds}, s-maxage=${cacheRemainingSeconds}, immutable`);
        return res.json(await cacheEntry.data);
    },
);

async function getWidgetJsonData(guild_id: string) {
    const guild = await Guild.findOneOrFail({
        where: { id: guild_id },
        select: {
            channel_ordering: true,
            widget_channel_id: true,
            widget_enabled: true,
            presence_count: true,
            name: true,
        },
    });
    if (!guild.widget_enabled) throw DiscordApiErrors.EMBED_DISABLED;

    // Fetch existing widget invite for widget channel
    let invite = await Invite.findOne({
        where: { channel_id: guild.widget_channel_id },
    });

    if (guild.widget_channel_id && !invite) {
        // Create invite for channel if none exists
        // TODO: Refactor invite create code to a shared function
        const max_age = 86400; // 24 hours
        const expires_at = new Date(max_age * 1000 + Date.now());

        invite = await Invite.create({
            code: randomString(),
            temporary: false,
            uses: 0,
            max_uses: 0,
            max_age: max_age,
            expires_at,
            created_at: new Date(),
            guild_id,
            channel_id: guild.widget_channel_id,
            flags: 0,
        }).save();
    }

    // Fetch voice channels, and the @everyone permissions object
    const channels: { id: string; name: string; position: number }[] = [];

    (await Channel.getOrderedChannels(guild.id, guild)).filter((doc) => {
        if (doc.type !== ChannelType.GUILD_VOICE) return false;
        // Only return voice channels where @everyone has the CONNECT permission
        if (doc.permission_overwrites === undefined || Permissions.channelPermission(doc.permission_overwrites, Permissions.FLAGS.CONNECT) === Permissions.FLAGS.CONNECT) {
            channels.push({
                id: doc.id,
                name: doc.name ?? "Unknown channel",
                position: doc.position ?? 0,
            });
        }
    });

    // Fetch members
    // TODO: Understand how Discord's max 100 random member sample works, and apply to here (see top of this file)
    const members = await Member.find({ where: { guild_id: guild_id }, relations: { user: { sessions: true } } });
    const minLastSeen = Date.now() - 1000 * 60 * 5;
    const onlineMembers = members.filter((m) => m.user.sessions.filter((s) => (s.last_seen?.getTime() ?? 0) > minLastSeen).length > 0);
    const memberData = onlineMembers
        .map((x) => {
            return {
                id: x.id,
                username: x.user.username,
				global_name: x.user.global_name,
                discriminator: x.user.discriminator,
                avatar: null,
                status: "online", // TODO
                avatar_url: x.avatar
                    ? `${Config.get().cdn.endpointPublic}/guilds/${guild_id}/users/${x.id}/avatars/${x.avatar}.png`
                    : x.user.avatar
                      ? `${Config.get().cdn.endpointPublic}/avatars/${x.id}/${x.user.avatar}.png`
                      : `${Config.get().cdn.endpointPublic}/embed/avatars/${BigInt(x.id) % 6n}.png`,
            };
        })
        .sort((a, b) => Number(BigInt(a.id) - BigInt(b.id)));

    // Construct object to respond with
    return {
        id: guild_id,
        name: guild.name,
        instant_invite: invite?.code,
        channels: channels,
        members: memberData,
        member_count: members.length,
        presence_count: guild.presence_count || onlineMembers.length,
    } as GuildWidgetJsonResponse;
}

export default router;