From af68657ec42a040a98ad01e19135f6b9b58a3024 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Tue, 24 Sep 2024 17:21:35 +1200 Subject: [PATCH 001/228] Make ensureRoom/syncRoom check if autocreatable --- docs/self-service-room-creation-rules.md | 6 +++--- src/d2m/actions/create-room.js | 26 +++++++++++++++++++++--- src/db/orm-defs.d.ts | 2 +- 3 files changed, 27 insertions(+), 7 deletions(-) diff --git a/docs/self-service-room-creation-rules.md b/docs/self-service-room-creation-rules.md index 6292fe7..1638f09 100644 --- a/docs/self-service-room-creation-rules.md +++ b/docs/self-service-room-creation-rules.md @@ -63,8 +63,8 @@ Pressing buttons on web or using the /invite command on a guild will insert a ro So here's all the technical changes needed to support self-service in v3: -- New guild_active table showing whether, and how, a guild is bridged +- New guild_active table showing whether, and how, a guild is bridged. - When /invite command is used, INSERT OR IGNORE INTO state 1 and ensureRoom + ensureSpace. - When bot is added through "easy mode" web button, REPLACE INTO state 1 and ensureSpace. -- When bot is added through "self-service" web button, REPLACE INTO state 2. -- Event dispatcher will only ensureRoom if the guild_active state is 1 +- When bot is added through "self-service" web button, REPLACE INTO state 0. +- Event dispatcher will only ensureRoom if the guild_active state is 1. diff --git a/src/d2m/actions/create-room.js b/src/d2m/actions/create-room.js index 509d0ff..9be489b 100644 --- a/src/d2m/actions/create-room.js +++ b/src/d2m/actions/create-room.js @@ -279,6 +279,17 @@ function channelToGuild(channel) { return guild } +/** + * @param {string} channelID + * @param {string} guildID + */ +function existsOrAutocreatable(channelID, guildID) { + const existing = select("channel_room", ["room_id", "thread_parent"], {channel_id: channelID}).get() + if (existing) return existing + const autocreate = select("guild_active", "autocreate", {guild_id: guildID}).pluck().get() + return autocreate +} + /* Ensure flow: 1. Get IDs @@ -297,6 +308,7 @@ function channelToGuild(channel) { */ /** + * Create room and/or sync room data. Please check that a channel_room entry exists or autocreate = 1 before calling this. * @param {string} channelID * @param {boolean} shouldActuallySync false if just need to ensure room exists (which is a quick database check), true if also want to sync room data when it does exist (slow) * @returns {Promise} room ID @@ -311,9 +323,17 @@ async function _syncRoom(channelID, shouldActuallySync) { await inflightRoomCreate.get(channelID) // just waiting, and then doing a new db query afterwards, is the simplest way of doing it } - const existing = select("channel_room", ["room_id", "thread_parent"], {channel_id: channelID}).get() + const existing = existsOrAutocreatable(channelID, guild.id) + + if (existing === 0) { + throw new Error("refusing to create a new matrix room when autocreate is deactivated") + } if (!existing) { + throw new Error("refusing to craete a new matrix room when there is no guild_active entry") + } + + if (existing === 1) { const creation = (async () => { const {spaceID, privacyLevel, channelKState} = await channelToKState(channel, guild, {api}) const roomID = await createRoom(channel, guild, spaceID, channelKState, privacyLevel) @@ -353,12 +373,12 @@ async function _syncRoom(channelID, shouldActuallySync) { return roomID } -/** Ensures the room exists. If it doesn't, creates the room with an accurate initial state. */ +/** Ensures the room exists. If it doesn't, creates the room with an accurate initial state. Please check that a channel_room entry exists or guild autocreate = 1 before calling this. */ function ensureRoom(channelID) { return _syncRoom(channelID, false) } -/** Actually syncs. Gets all room state from the homeserver in order to diff, and uploads the icon to mxc if it has changed. */ +/** Actually syncs. Gets all room state from the homeserver in order to diff, and uploads the icon to mxc if it has changed. Please check that a channel_room entry exists or guild autocreate = 1 before calling this. */ function syncRoom(channelID) { return _syncRoom(channelID, true) } diff --git a/src/db/orm-defs.d.ts b/src/db/orm-defs.d.ts index 02003af..b1e6b79 100644 --- a/src/db/orm-defs.d.ts +++ b/src/db/orm-defs.d.ts @@ -35,7 +35,7 @@ export type Models = { guild_active: { guild_id: string - autocreate: number + autocreate: 0 | 1 } lottie: { From 8915e8d96c9fb401d1972996cec318f9f68187d0 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Tue, 24 Sep 2024 17:21:55 +1200 Subject: [PATCH 002/228] Make invite INSERT OR IGNORE autocreate entry --- src/discord/interactions/invite.js | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/discord/interactions/invite.js b/src/discord/interactions/invite.js index 689ea1a..ce80e99 100644 --- a/src/discord/interactions/invite.js +++ b/src/discord/interactions/invite.js @@ -4,6 +4,10 @@ const DiscordTypes = require("discord-api-types/v10") const assert = require("assert/strict") const {discord, sync, db, select, from} = require("../../passthrough") +/** @type {import("../../d2m/actions/create-room")} */ +const createRoom = sync.require("../../d2m/actions/create-room") +/** @type {import("../../d2m/actions/create-space")} */ +const createSpace = sync.require("../../d2m/actions/create-space") /** @type {import("../../matrix/api")} */ const api = sync.require("../../matrix/api") @@ -12,17 +16,6 @@ const api = sync.require("../../matrix/api") * @returns {Promise} */ async function _interact({data, channel, guild_id}) { - // Check guild is bridged - const spaceID = select("guild_space", "space_id", {guild_id}).pluck().get() - const roomID = select("channel_room", "room_id", {channel_id: channel.id}).pluck().get() - if (!spaceID || !roomID) return { - type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, - data: { - content: "This server isn't bridged to Matrix, so you can't invite Matrix users.", - flags: DiscordTypes.MessageFlags.Ephemeral - } - } - // Get named MXID /** @type {DiscordTypes.APIApplicationCommandInteractionDataStringOption[] | undefined} */ // @ts-ignore const options = data.options @@ -36,6 +29,13 @@ async function _interact({data, channel, guild_id}) { } } + // Ensure guild and room are bridged + db.prepare("INSERT OR IGNORE INTO guild_active (guild_id, autocreate) VALUES (?, 1)").run(guild_id) + const roomID = await createRoom.ensureRoom(channel.id) + assert(roomID) + const spaceID = select("guild_space", "space_id", {guild_id}).pluck().get() + assert(spaceID) + // Check for existing invite to the space let spaceMember try { From 3af31385f06e10ebd2bfbc1e050a53702739b560 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Wed, 25 Sep 2024 01:08:29 +1200 Subject: [PATCH 003/228] Use $url resolver in channelToKState --- src/d2m/actions/create-room.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/d2m/actions/create-room.js b/src/d2m/actions/create-room.js index 9be489b..2ea9c91 100644 --- a/src/d2m/actions/create-room.js +++ b/src/d2m/actions/create-room.js @@ -180,7 +180,7 @@ async function channelToKState(channel, guild, di) { network: { id: guild.id, displayname: guild.name, - avatar_url: await file.uploadDiscordFileToMxc(file.guildIcon(guild)) + avatar_url: {$url: file.guildIcon(guild)} }, channel: { id: channel.id, From 312ea69d7381bcd16c112ae12432dfb0a8787cf0 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Wed, 25 Sep 2024 01:54:01 +1200 Subject: [PATCH 004/228] Fix page duplicating when clicking toggle switch --- src/web/pug/guild.pug | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/web/pug/guild.pug b/src/web/pug/guild.pug index b5449a4..2130aff 100644 --- a/src/web/pug/guild.pug +++ b/src/web/pug/guild.pug @@ -139,7 +139,7 @@ block body p.s-description If you want, OOYE can automatically create new Matrix rooms and link them when a new Discord channel is spoken in. - let value = select("guild_active", "autocreate", {guild_id}).pluck().get() input(type="hidden" name="guild_id" value=guild_id) - input.s-toggle-switch.order-last#autocreate(name="autocreate" type="checkbox" hx-post="/api/autocreate" hx-indicator="#autocreate-loading" hx-disabled-elt="this" checked=value) + input.s-toggle-switch.order-last#autocreate(name="autocreate" type="checkbox" hx-post="/api/autocreate" hx-indicator="#autocreate-loading" hx-disabled-elt="this" hx-swap="none" checked=value) .is-loading#autocreate-loading h3.mt32.fs-category Manually link channels From b0a0e62a8626782a38dbc29cde3b130f9264a7a2 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Wed, 25 Sep 2024 01:58:26 +1200 Subject: [PATCH 005/228] Adapt createRoom/space/invite to self-service --- docs/self-service-room-creation-rules.md | 4 + package-lock.json | 12 +-- src/d2m/actions/create-room.js | 99 ++++++++++++++++-------- src/d2m/actions/create-space.js | 3 + src/discord/interactions/invite.js | 22 ++++-- test/data.js | 2 +- 6 files changed, 96 insertions(+), 46 deletions(-) diff --git a/docs/self-service-room-creation-rules.md b/docs/self-service-room-creation-rules.md index 1638f09..c47ca14 100644 --- a/docs/self-service-room-creation-rules.md +++ b/docs/self-service-room-creation-rules.md @@ -61,6 +61,8 @@ So there will be 3 states of whether a guild is self-service or not. At first, i Pressing buttons on web or using the /invite command on a guild will insert a row into guild_active, allowing it to be bridged. +One more thing. Before v3, when a Matrix room was autocreated it would autocreate the space as well, if it needed to. But now, since nothing will be created until the user takes an action, the guild will always be created directly in response to a request. So room creation can now trust that the guild exists already. + So here's all the technical changes needed to support self-service in v3: - New guild_active table showing whether, and how, a guild is bridged. @@ -68,3 +70,5 @@ So here's all the technical changes needed to support self-service in v3: - When bot is added through "easy mode" web button, REPLACE INTO state 1 and ensureSpace. - When bot is added through "self-service" web button, REPLACE INTO state 0. - Event dispatcher will only ensureRoom if the guild_active state is 1. +- createRoom can trust that the space exists because we check that in a calling function. +- createRoom will only create other dependencies if the guild is autocreate. diff --git a/package-lock.json b/package-lock.json index 178690a..45de4cc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1217,9 +1217,9 @@ ] }, "node_modules/better-sqlite3": { - "version": "11.2.1", - "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-11.2.1.tgz", - "integrity": "sha512-Xbt1d68wQnUuFIEVsbt6V+RG30zwgbtCGQ4QOcXVrOH0FE4eHk64FWZ9NUfRHS4/x1PXqwz/+KOrnXD7f0WieA==", + "version": "11.3.0", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-11.3.0.tgz", + "integrity": "sha512-iHt9j8NPYF3oKCNOO5ZI4JwThjt3Z6J6XrcwG85VNMVzv1ByqrHWv5VILEbCMFWDsoHhXvQ7oC8vgRXFAKgl9w==", "hasInstallScript": true, "license": "MIT", "dependencies": { @@ -1633,9 +1633,9 @@ } }, "node_modules/discord-api-types": { - "version": "0.37.98", - "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.98.tgz", - "integrity": "sha512-xsH4UwmnCQl4KjAf01/p9ck9s+/vDqzHbUxPOBzo8fcVUa/hQG6qInD7Cr44KAuCM+xCxGJFSAUx450pBrX0+g==", + "version": "0.37.101", + "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.101.tgz", + "integrity": "sha512-2wizd94t7G3A8U5Phr3AiuL4gSvhqistDwWnlk1VLTit8BI1jWUncFqFQNdPbHqS3661+Nx/iEyIwtVjPuBP3w==", "license": "MIT" }, "node_modules/doctypes": { diff --git a/src/d2m/actions/create-room.js b/src/d2m/actions/create-room.js index 2ea9c91..75696f2 100644 --- a/src/d2m/actions/create-room.js +++ b/src/d2m/actions/create-room.js @@ -15,8 +15,6 @@ const api = sync.require("../../matrix/api") const ks = sync.require("../../matrix/kstate") /** @type {import("../../discord/utils")} */ const utils = sync.require("../../discord/utils") -/** @type {import("./create-space")}) */ -const createSpace = sync.require("./create-space") // watch out for the require loop /** * There are 3 levels of room privacy: @@ -95,27 +93,21 @@ function convertNameAndTopic(channel, guild, customName) { async function channelToKState(channel, guild, di) { // @ts-ignore const parentChannel = discord.channels.get(channel.parent_id) - /** Used for membership/permission checks. */ - let guildSpaceID - /** Used as the literal parent on Matrix, for categorisation. Will be the same as `guildSpaceID` unless it's a forum channel's thread, in which case a different space is used to group those threads. */ - let parentSpaceID - let privacyLevel - if (parentChannel?.type === DiscordTypes.ChannelType.GuildForum) { // it's a forum channel's thread, so use a different space to group those threads - guildSpaceID = await createSpace.ensureSpace(guild) - parentSpaceID = await ensureRoom(channel.parent_id) - privacyLevel = select("guild_space", "privacy_level", {space_id: guildSpaceID}).pluck().get() - } else { // otherwise use the guild's space like usual - parentSpaceID = await createSpace.ensureSpace(guild) - guildSpaceID = parentSpaceID - privacyLevel = select("guild_space", "privacy_level", {space_id: parentSpaceID}).pluck().get() - } - assert(typeof parentSpaceID === "string") - assert(typeof guildSpaceID === "string") - assert(typeof privacyLevel === "number") + const guildRow = select("guild_space", ["space_id", "privacy_level"], {guild_id: guild.id}).get() + assert(guildRow) - const row = select("channel_room", ["nick", "custom_avatar"], {channel_id: channel.id}).get() - const customName = row?.nick - const customAvatar = row?.custom_avatar + /** Used for membership/permission checks. */ + let guildSpaceID = guildRow.space_id + /** Used as the literal parent on Matrix, for categorisation. Will be the same as `guildSpaceID` unless it's a forum channel's thread, in which case a different space is used to group those threads. */ + let parentSpaceID = guildSpaceID + if (parentChannel?.type === DiscordTypes.ChannelType.GuildForum) { + parentSpaceID = await ensureRoom(channel.parent_id) + assert(typeof parentSpaceID === "string") + } + + const channelRow = select("channel_room", ["nick", "custom_avatar"], {channel_id: channel.id}).get() + const customName = channelRow?.nick + const customAvatar = channelRow?.custom_avatar const [convertedName, convertedTopic] = convertNameAndTopic(channel, guild, customName) const avatarEventContent = {} @@ -125,6 +117,7 @@ async function channelToKState(channel, guild, di) { avatarEventContent.url = {$url: file.guildIcon(guild)} } + const privacyLevel = guildRow.privacy_level let history_visibility = PRIVACY_ENUMS.ROOM_HISTORY_VISIBILITY[privacyLevel] if (channel["thread_metadata"]) history_visibility = "world_readable" @@ -280,16 +273,60 @@ function channelToGuild(channel) { } /** - * @param {string} channelID + * This function handles whether it's allowed to bridge messages in this channel, and if so, where to. + * This has to account for whether self-service is enabled for the guild or not. + * This also has to account for different channel types, like forum channels (which need the + * parent forum to already exist, and ignore the self-service setting), or thread channels (which + * need the parent channel to already exist, and ignore the self-service setting). + * @param {DiscordTypes.APIGuildTextChannel | DiscordTypes.APIThreadChannel} channel text channel or thread * @param {string} guildID + * @returns obj if bridged; 1 if autocreatable; null/undefined if guild is not bridged; 0 if self-service and not autocreatable thread */ -function existsOrAutocreatable(channelID, guildID) { - const existing = select("channel_room", ["room_id", "thread_parent"], {channel_id: channelID}).get() +function existsOrAutocreatable(channel, guildID) { + // 1. If the channel is already linked somewhere, it's always okay to bridge to that destination, no matter what. Yippee! + const existing = select("channel_room", ["room_id", "thread_parent"], {channel_id: channel.id}).get() if (existing) return existing + + // 2. If the guild is an autocreate guild, it's always okay to bridge to that destination, and + // we'll need to create any dependent resources recursively. const autocreate = select("guild_active", "autocreate", {guild_id: guildID}).pluck().get() + if (autocreate === 1) return autocreate + + // 3. If the guild is not approved for bridging yet, we can't bridge there. + // They need to decide one way or another whether it's self-service before we can continue. + if (autocreate == null) return autocreate + + // 4. If we got here, the guild is in self-service mode. + // New channels won't be able to create new rooms. But forum threads or channel threads could be fine. + if ([DiscordTypes.ChannelType.PublicThread, DiscordTypes.ChannelType.PrivateThread, DiscordTypes.ChannelType.AnnouncementThread].includes(channel.type)) { + // In self-service mode, threads rely on the parent resource already existing. + /** @type {DiscordTypes.APIGuildTextChannel} */ // @ts-ignore + const parent = discord.channels.get(channel.parent_id) + assert(parent) + const parentExisting = existsOrAutocreatable(parent, guildID) + if (parentExisting) return 1 // Autocreatable + } + + // 5. If we got here, the guild is in self-service mode and the channel is truly not bridged. return autocreate } +/** + * @param {DiscordTypes.APIGuildTextChannel | DiscordTypes.APIThreadChannel} channel text channel or thread + * @param {string} guildID + * @returns obj if bridged; 1 if autocreatable. (throws if not autocreatable) + */ +function assertExistsOrAutocreatable(channel, guildID) { + const existing = existsOrAutocreatable(channel, guildID) + if (existing === 0) { + throw new Error(`Guild ${guildID} is self-service, so won't create a Matrix room for channel ${channel.id}`) + } + if (!existing) { + throw new Error(`Guild ${guildID} is not bridged, so won't create a Matrix room for channel ${channel.id}`) + } + return existing +} + /* Ensure flow: 1. Get IDs @@ -323,15 +360,7 @@ async function _syncRoom(channelID, shouldActuallySync) { await inflightRoomCreate.get(channelID) // just waiting, and then doing a new db query afterwards, is the simplest way of doing it } - const existing = existsOrAutocreatable(channelID, guild.id) - - if (existing === 0) { - throw new Error("refusing to create a new matrix room when autocreate is deactivated") - } - - if (!existing) { - throw new Error("refusing to craete a new matrix room when there is no guild_active entry") - } + const existing = assertExistsOrAutocreatable(channel, guild.id) if (existing === 1) { const creation = (async () => { @@ -475,3 +504,5 @@ module.exports.postApplyPowerLevels = postApplyPowerLevels module.exports._convertNameAndTopic = convertNameAndTopic module.exports._unbridgeRoom = _unbridgeRoom module.exports.unbridgeDeletedChannel = unbridgeDeletedChannel +module.exports.assertExistsOrAutocreatable = assertExistsOrAutocreatable +module.exports.existsOrAutocreatable = existsOrAutocreatable diff --git a/src/d2m/actions/create-space.js b/src/d2m/actions/create-space.js index ec1677e..0c3d5e3 100644 --- a/src/d2m/actions/create-space.js +++ b/src/d2m/actions/create-space.js @@ -92,6 +92,9 @@ async function _syncSpace(guild, shouldActuallySync) { const row = select("guild_space", ["space_id", "privacy_level"], {guild_id: guild.id}).get() if (!row) { + const autocreate = select("guild_active", "autocreate", {guild_id: guild.id}).pluck().get() + assert.equal(autocreate, 1, `refusing to implicitly create guild ${guild.id}. set the guild_active data first before calling ensureSpace/syncSpace.`) + const creation = (async () => { const guildKState = await guildToKState(guild, createRoom.DEFAULT_PRIVACY_LEVEL) // New spaces will have to use the default privacy level; we obviously can't look up the existing entry const spaceID = await createSpace(guild, guildKState) diff --git a/src/discord/interactions/invite.js b/src/discord/interactions/invite.js index ce80e99..3b39d9d 100644 --- a/src/discord/interactions/invite.js +++ b/src/discord/interactions/invite.js @@ -1,6 +1,7 @@ // @ts-check const DiscordTypes = require("discord-api-types/v10") +const Ty = require("../../types") const assert = require("assert/strict") const {discord, sync, db, select, from} = require("../../passthrough") @@ -12,7 +13,7 @@ const createSpace = sync.require("../../d2m/actions/create-space") const api = sync.require("../../matrix/api") /** - * @param {DiscordTypes.APIChatInputApplicationCommandGuildInteraction} interaction + * @param {DiscordTypes.APIChatInputApplicationCommandGuildInteraction & {channel: DiscordTypes.APIGuildTextChannel}} interaction * @returns {Promise} */ async function _interact({data, channel, guild_id}) { @@ -29,12 +30,23 @@ async function _interact({data, channel, guild_id}) { } } + const guild = discord.guilds.get(guild_id) + assert(guild) + // Ensure guild and room are bridged db.prepare("INSERT OR IGNORE INTO guild_active (guild_id, autocreate) VALUES (?, 1)").run(guild_id) + const existing = createRoom.existsOrAutocreatable(channel, guild_id) + if (existing === 0) return { + type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, + data: { + content: "This channel isn't bridged, so you can't invite Matrix users yet. Try turning on automatic room-creation or link a Matrix room in the website.", + flags: DiscordTypes.MessageFlags.Ephemeral + } + } + assert(existing) // can't be null or undefined as we just inserted the guild_active row + + const spaceID = await createSpace.ensureSpace(guild) const roomID = await createRoom.ensureRoom(channel.id) - assert(roomID) - const spaceID = select("guild_space", "space_id", {guild_id}).pluck().get() - assert(spaceID) // Check for existing invite to the space let spaceMember @@ -115,7 +127,7 @@ async function _interactButton({channel, message}) { } } -/** @param {DiscordTypes.APIChatInputApplicationCommandGuildInteraction} interaction */ +/** @param {DiscordTypes.APIChatInputApplicationCommandGuildInteraction & {channel: DiscordTypes.APIGuildTextChannel}} interaction */ async function interact(interaction) { await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, await _interact(interaction)) } diff --git a/test/data.js b/test/data.js index c8217c2..eb2c42a 100644 --- a/test/data.js +++ b/test/data.js @@ -58,7 +58,7 @@ module.exports = { network: { id: "112760669178241024", displayname: "Psychonauts 3", - avatar_url: "mxc://cadence.moe/zKXGZhmImMHuGQZWJEFKJbsF" + avatar_url: {$url: "/icons/112760669178241024/a_f83622e09ead74f0c5c527fe241f8f8c.png?size=1024"} }, channel: { id: "112760669178241024", From 419d61cf82b3a7872ee2b26a21ec560b582998dd Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Thu, 26 Sep 2024 02:34:30 +1200 Subject: [PATCH 006/228] Sync webhook profiles to Matrix --- src/d2m/actions/register-user.js | 29 +++++++++++++++++++++++++++++ src/d2m/actions/send-message.js | 18 +++++++++--------- src/d2m/converters/user-to-mxid.js | 2 +- 3 files changed, 39 insertions(+), 10 deletions(-) diff --git a/src/d2m/actions/register-user.js b/src/d2m/actions/register-user.js index b914d41..94daa34 100644 --- a/src/d2m/actions/register-user.js +++ b/src/d2m/actions/register-user.js @@ -208,6 +208,34 @@ async function syncUser(user, member, channel, guild, roomID) { return mxid } +/** + * Sync profile data for a webhook user. The _ooye_webhook name will always be reused. + * 1. Join the sim to the room if needed + * 2. Make an object of what the new room member state content would be, including uploading the profile picture if it hasn't been done before + * 4. Compare against the previously known state content, which is helpfully stored in the database + * 5. If the state content has changed, send it to Matrix and update it in the database for next time + * @param {DiscordTypes.APIUser} user + * @param {DiscordTypes.APIGuildChannel} channel + * @param {DiscordTypes.APIGuild} guild + * @param {string} roomID + * @returns {Promise} mxid of the updated sim + */ +async function syncWebhook(user, channel, guild, roomID) { + const mxid = await ensureSimJoined(user, roomID) + // @ts-ignore + const content = await memberToStateContent(user, {}, guild.id) + const currentHash = _hashProfileContent(content, 0) + const existingHash = select("sim_member", "hashed_profile_content", {room_id: roomID, mxid}).safeIntegers().pluck().get() + // only do the actual sync if the hash has changed since we last looked + if (existingHash !== currentHash) { + // Update room member state + await api.sendState(roomID, "m.room.member", mxid, content, mxid) + // Update cached hash + db.prepare("UPDATE sim_member SET hashed_profile_content = ? WHERE room_id = ? AND mxid = ?").run(currentHash, roomID, mxid) + } + return mxid +} + /** * @param {string} roomID */ @@ -244,4 +272,5 @@ module.exports._hashProfileContent = _hashProfileContent module.exports.ensureSim = ensureSim module.exports.ensureSimJoined = ensureSimJoined module.exports.syncUser = syncUser +module.exports.syncWebhook = syncWebhook module.exports.syncAllUsersInRoom = syncAllUsersInRoom diff --git a/src/d2m/actions/send-message.js b/src/d2m/actions/send-message.js index 6d100d4..ac3378c 100644 --- a/src/d2m/actions/send-message.js +++ b/src/d2m/actions/send-message.js @@ -28,20 +28,20 @@ async function sendMessage(message, channel, guild, row) { const roomID = await createRoom.ensureRoom(message.channel_id) let senderMxid = null - if (!dUtils.isWebhookMessage(message)) { - if (message.author.id === discord.application.id) { - // no need to sync the bot's own user - } else if (message.member) { // available on a gateway message create event - senderMxid = await registerUser.syncUser(message.author, message.member, channel, guild, roomID) - } else { // well, good enough... - senderMxid = await registerUser.ensureSimJoined(message.author, roomID) - } - } else if (row && row.speedbump_webhook_id === message.webhook_id) { + if (row && row.speedbump_webhook_id === message.webhook_id) { // Handle the PluralKit public instance if (row.speedbump_id === "466378653216014359") { const pkMessage = await registerPkUser.fetchMessage(message.id) senderMxid = await registerPkUser.syncUser(message.author, pkMessage, roomID) } + } else if (message.author.id === discord.application.id) { + // no need to sync the bot's own user + } else if (dUtils.isWebhookMessage(message)) { + senderMxid = await registerUser.syncWebhook(message.author, channel, guild, roomID) + } else if (message.member) { // available on a gateway message create event + senderMxid = await registerUser.syncUser(message.author, message.member, channel, guild, roomID) + } else { // well, good enough... + senderMxid = await registerUser.ensureSimJoined(message.author, roomID) } const events = await messageToEvent.messageToEvent(message, guild, {}, {api}) diff --git a/src/d2m/converters/user-to-mxid.js b/src/d2m/converters/user-to-mxid.js index a619b36..3d7d834 100644 --- a/src/d2m/converters/user-to-mxid.js +++ b/src/d2m/converters/user-to-mxid.js @@ -60,7 +60,7 @@ function* generateLocalpartAlternatives(preferences) { */ function userToSimName(user) { if (!SPECIAL_USER_MAPPINGS.has(user.id)) { // skip this check for known special users - assert.notEqual(user.discriminator, "0000", `cannot create user for a webhook: ${JSON.stringify(user)}`) + if (user.discriminator === "0000") return "webhook" } // 1. Is sim user already registered? From 8743910c35954212fc9cf1ac1640b97ab4894718 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Thu, 26 Sep 2024 09:47:21 +1200 Subject: [PATCH 007/228] Rename seed.js to setup; add npm script for it --- package.json | 1 + readme.md | 8 ++++---- scripts/{seed.js => setup.js} | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) rename scripts/{seed.js => setup.js} (99%) mode change 100755 => 100644 diff --git a/package.json b/package.json index ba02a83..6b4484d 100644 --- a/package.json +++ b/package.json @@ -61,6 +61,7 @@ }, "scripts": { "start": "node start.js", + "setup": "node scripts/setup.js", "addbot": "node addbot.js", "test": "cross-env FORCE_COLOR=true supertape --no-check-assertions-count --format tap test/test.js | tap-dot", "test-slow": "cross-env FORCE_COLOR=true supertape --no-check-assertions-count --format tap --no-worker test/test.js -- --slow | tap-dot", diff --git a/readme.md b/readme.md index 992d0de..daebb1e 100644 --- a/readme.md +++ b/readme.md @@ -81,9 +81,9 @@ Follow these steps: 1. Install dependencies: `npm install` -1. Run `node scripts/seed.js` to check your setup and set the bot's initial state. It will prompt you for information. You only need to run this once ever. +1. Run `npm run setup` to check your setup and set the bot's initial state. It will prompt you for information. You only need to run this once ever. -1. Start the bridge: `npm start` +1. Start the bridge: `npm run start` 1. Add the bot to a server - use any *one* of the following commands for an invite link: * (in the REPL) `addbot` @@ -152,8 +152,8 @@ To get into the rooms on your Matrix account, use the `/invite [your mxid here]` │   └── *.js * Various files you can run once if you need them. └── scripts - * First time running a new bridge? Run this file to plant a seed, which will flourish into state for the bridge: - ├── seed.js + * First time running a new bridge? Run this file to set up prerequisites on the Matrix server: + ├── setup.js * Hopefully you won't need the rest of these. Code quality varies wildly. └── *.js diff --git a/scripts/seed.js b/scripts/setup.js old mode 100755 new mode 100644 similarity index 99% rename from scripts/seed.js rename to scripts/setup.js index f20afb7..2fb2dd0 --- a/scripts/seed.js +++ b/scripts/setup.js @@ -305,7 +305,7 @@ async function validateHomeserverOrigin(serverUrlPrompt, url) { } // Otherwise, it's the user's problem if (!guild) { - return die(`Error: The bot needs to upload some emojis. Please say where to upload them to. Run seed.js again with --emoji-guild=GUILD_ID`) + return die(`Error: The bot needs to upload some emojis. Please say where to upload them to. Run setup again with --emoji-guild=GUILD_ID`) } // Upload those emojis to the chosen location db.prepare("REPLACE INTO auto_emoji (name, emoji_id, guild_id) VALUES ('_', '_', ?)").run(guild.id) From 69c93ca9d9ae4272f6716f71d1532bb04300be51 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Thu, 26 Sep 2024 09:59:13 +1200 Subject: [PATCH 008/228] Automatically set up content_length_workaround --- src/matrix/mreq.js | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/matrix/mreq.js b/src/matrix/mreq.js index 4707ae6..cdcf405 100644 --- a/src/matrix/mreq.js +++ b/src/matrix/mreq.js @@ -5,7 +5,7 @@ const mixin = require("@cloudrac3r/mixin-deep") const stream = require("stream") const getStream = require("get-stream") -const {reg} = require("./read-registration.js") +const {reg, writeRegistration} = require("./read-registration.js") const baseUrl = `${reg.ooye.server_origin}/_matrix` @@ -45,13 +45,15 @@ async function mreq(method, url, body, extra = {}) { const root = await res.json() if (!res.ok || root.errcode) { - if (root.error?.includes("Content-Length")) { - console.error(`OOYE cannot stream uploads to Synapse. Please choose one of these workarounds:` - + `\n * Run an nginx reverse proxy to Synapse, and point registration.yaml's` - + `\n \`server_origin\` to nginx` - + `\n * Set \`content_length_workaround: true\` in registration.yaml (this will` - + `\n halve the speed of bridging d->m files)`) - throw new Error("Synapse is not accepting stream uploads, see the message above.") + if (root.error?.includes("Content-Length") || !reg.ooye.content_length_workaround) { + reg.ooye.content_length_workaround = true + const root = await mreq(method, url, body, extra) + console.error("OOYE cannot stream uploads to Synapse. The `content_length_workaround` option" + + "\nhas been activated in registration.yaml, which works around the problem, but" + + "\nhalves the speed of bridging d->m files. A better way to resolve this problem" + + "\nis to run an nginx reverse proxy to Synapse and re-run OOYE setup.") + writeRegistration(reg) + return root } delete opts.headers.Authorization throw new MatrixServerError(root, {baseUrl, url, ...opts}) From d629e666db1e01453041cd4668cfc6e71ee54d81 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sun, 29 Sep 2024 00:21:48 +1200 Subject: [PATCH 009/228] Fis messages being double-redacted --- src/m2d/actions/redact.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/m2d/actions/redact.js b/src/m2d/actions/redact.js index ffbb261..5a12d5a 100644 --- a/src/m2d/actions/redact.js +++ b/src/m2d/actions/redact.js @@ -13,7 +13,7 @@ const utils = sync.require("../converters/utils") */ async function deleteMessage(event) { const rows = from("event_message").join("message_channel", "message_id").select("channel_id", "message_id").where({event_id: event.redacts}).all() - db.prepare("DELETE FROM event_message WHERE event_id = ?").run(event.event_id) + db.prepare("DELETE FROM event_message WHERE event_id = ?").run(event.redacts) for (const row of rows) { db.prepare("DELETE FROM message_channel WHERE message_id = ?").run(row.message_id) await discord.snow.channel.deleteMessage(row.channel_id, row.message_id, event.content.reason) From bac2deb32f88344c24861fb46ff407867b91d9e1 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sun, 29 Sep 2024 03:11:59 +1300 Subject: [PATCH 010/228] Check existsOrAutocreatable before dispatching --- src/d2m/actions/create-room.js | 2 +- src/d2m/event-dispatcher.js | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/d2m/actions/create-room.js b/src/d2m/actions/create-room.js index 75696f2..2d8d1af 100644 --- a/src/d2m/actions/create-room.js +++ b/src/d2m/actions/create-room.js @@ -504,5 +504,5 @@ module.exports.postApplyPowerLevels = postApplyPowerLevels module.exports._convertNameAndTopic = convertNameAndTopic module.exports._unbridgeRoom = _unbridgeRoom module.exports.unbridgeDeletedChannel = unbridgeDeletedChannel -module.exports.assertExistsOrAutocreatable = assertExistsOrAutocreatable module.exports.existsOrAutocreatable = existsOrAutocreatable +module.exports.assertExistsOrAutocreatable = assertExistsOrAutocreatable diff --git a/src/d2m/event-dispatcher.js b/src/d2m/event-dispatcher.js index 1806ee6..af8eedf 100644 --- a/src/d2m/event-dispatcher.js +++ b/src/d2m/event-dispatcher.js @@ -191,7 +191,7 @@ module.exports = { async onThreadCreate(client, thread) { const channelID = thread.parent_id || undefined const parentRoomID = select("channel_room", "room_id", {channel_id: channelID}).pluck().get() - if (!parentRoomID) return // Not interested in a thread if we aren't interested in its wider channel + if (!parentRoomID) return // Not interested in a thread if we aren't interested in its wider channel (won't autocreate) const threadRoomID = await createRoom.syncRoom(thread.id) // Create room (will share the same inflight as the initial message to the thread) await announceThread.announceThread(parentRoomID, threadRoomID, thread) }, @@ -249,6 +249,7 @@ module.exports = { if (message.author.username === "Deleted User") return // Nothing we can do for deleted users. const channel = client.channels.get(message.channel_id) if (!channel || !("guild_id" in channel) || !channel.guild_id) return // Nothing we can do in direct messages. + const guild = client.guilds.get(channel.guild_id) assert(guild) @@ -259,11 +260,13 @@ module.exports = { if (dUtils.isEphemeralMessage(message)) return // Ephemeral messages are for the eyes of the receiver only! + if (!createRoom.existsOrAutocreatable(channel, guild.id)) return // Check that the sending-to room exists or is autocreatable + const {affected, row} = await speedbump.maybeDoSpeedbump(message.channel_id, message.id) if (affected) return // @ts-ignore - await sendMessage.sendMessage(message, channel, guild, row), + await sendMessage.sendMessage(message, channel, guild, row) retrigger.messageFinishedBridging(message.id) }, @@ -278,7 +281,7 @@ module.exports = { // Otherwise, if there are embeds, then the system generated URL preview embeds. if (!(typeof data.content === "string" || "embeds" in data)) return - // Deal with Eventual Consistency(TM) + // Check that the sending-to room exists, and deal with Eventual Consistency(TM) if (retrigger.eventNotFoundThenRetrigger(data.id, module.exports.onMessageUpdate, client, data)) return if (data.webhook_id) { @@ -295,11 +298,11 @@ module.exports = { /** @type {DiscordTypes.GatewayMessageCreateDispatchData} */ // @ts-ignore const message = data - const channel = client.channels.get(message.channel_id) if (!channel || !("guild_id" in channel) || !channel.guild_id) return // Nothing we can do in direct messages. const guild = client.guilds.get(channel.guild_id) assert(guild) + // @ts-ignore await editMessage.editMessage(message, guild, row) }, From 034f8d6b554c9273f43fcbfdaedfbff0813d0d34 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sun, 29 Sep 2024 03:27:40 +1300 Subject: [PATCH 011/228] Code coverage reporting --- package.json | 2 +- src/db/migrations/0002-optimise-profile-content.up.js | 1 + src/db/orm-defs.d.ts | 1 + src/db/orm.js | 2 +- src/db/orm.test.js | 5 +++++ 5 files changed, 9 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 6b4484d..857e2d2 100644 --- a/package.json +++ b/package.json @@ -65,6 +65,6 @@ "addbot": "node addbot.js", "test": "cross-env FORCE_COLOR=true supertape --no-check-assertions-count --format tap test/test.js | tap-dot", "test-slow": "cross-env FORCE_COLOR=true supertape --no-check-assertions-count --format tap --no-worker test/test.js -- --slow | tap-dot", - "cover": "c8 -o test/coverage --skip-full -x db/migrations -x matrix/file.js -x matrix/api.js -x matrix/mreq.js -x d2m/converters/rlottie-wasm.js -r html -r text supertape --no-check-assertions-count --format fail --no-worker test/test.js -- --slow" + "cover": "c8 -o test/coverage --skip-full -x db/migrations -x src/matrix/file.js -x src/matrix/api.js -x src/matrix/mreq.js -x src/d2m/converters/rlottie-wasm.js -r html -r text supertape --no-check-assertions-count --format fail --no-worker test/test.js -- --slow" } } diff --git a/src/db/migrations/0002-optimise-profile-content.up.js b/src/db/migrations/0002-optimise-profile-content.up.js index a8619cf..5b540cb 100644 --- a/src/db/migrations/0002-optimise-profile-content.up.js +++ b/src/db/migrations/0002-optimise-profile-content.up.js @@ -3,6 +3,7 @@ module.exports = async function(db) { const contents = db.prepare("SELECT distinct hashed_profile_content FROM sim_member WHERE hashed_profile_content IS NOT NULL").pluck().all() const stmt = db.prepare("UPDATE sim_member SET hashed_profile_content = ? WHERE hashed_profile_content = ?") db.transaction(() => { + /* c8 ignore next 6 */ for (let s of contents) { let b = Buffer.isBuffer(s) ? Uint8Array.from(s) : Uint8Array.from(Buffer.from(s)) const unsignedHash = hasher.h64Raw(b) diff --git a/src/db/orm-defs.d.ts b/src/db/orm-defs.d.ts index b1e6b79..c235e99 100644 --- a/src/db/orm-defs.d.ts +++ b/src/db/orm-defs.d.ts @@ -124,3 +124,4 @@ export type PickTypeOf> = T extends { [k in K]?: any } ? export type Merge = {[x in AllKeys]: PickTypeOf} export type Nullable = {[k in keyof T]: T[k] | null} export type Numberish = {[k in keyof T]: T[k] extends number ? (number | bigint) : T[k]} +export type ValueOrArray = {[k in keyof T]: T[k][] | T[k]} diff --git a/src/db/orm.js b/src/db/orm.js index 646012b..4d9b6f1 100644 --- a/src/db/orm.js +++ b/src/db/orm.js @@ -8,7 +8,7 @@ const U = require("./orm-defs") * @template {keyof U.Models[Table]} Col * @param {Table} table * @param {Col[] | Col} cols - * @param {Partial>} where + * @param {Partial>>} where * @param {string} [e] */ function select(table, cols, where = {}, e = "") { diff --git a/src/db/orm.test.js b/src/db/orm.test.js index a53cc66..278723a 100644 --- a/src/db/orm.test.js +++ b/src/db/orm.test.js @@ -30,6 +30,11 @@ test("orm: select: all, where and pluck works on multiple columns", t => { t.deepEqual(names, ["cadence [they]"]) }) +test("orm: select: in array works", t => { + const ids = select("emoji", "emoji_id", {name: ["online", "upstinky"]}).pluck().all() + t.deepEqual(ids, ["288858540888686602", "606664341298872324"]) +}) + test("orm: from: get pluck works", t => { const guildID = from("guild_space").pluck("guild_id").and("WHERE space_id = ?").get("!jjWAGMeQdNrVZSSfvz:cadence.moe") t.equal(guildID, data.guild.general.id) From cf756cb0af195618d6fb3d5f506b595910aa234d Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sun, 29 Sep 2024 03:58:51 +1300 Subject: [PATCH 012/228] Create space as needed in oauth flow I have manually tested this with both web flows, the link flow, the /invite command, and the toggle switch, and they all work. --- src/web/pug/guild.pug | 2 +- src/web/pug/includes/template.pug | 3 ++- src/web/routes/invite.js | 16 +++++++++------- src/web/routes/oauth.js | 11 ++++++++--- 4 files changed, 20 insertions(+), 12 deletions(-) diff --git a/src/web/pug/guild.pug b/src/web/pug/guild.pug index 960f30b..1e27f2e 100644 --- a/src/web/pug/guild.pug +++ b/src/web/pug/guild.pug @@ -137,7 +137,7 @@ block body label.s-label.fl-grow1(for="autocreate") | Create new Matrix rooms automatically p.s-description If you want, OOYE can automatically create new Matrix rooms and link them when an unlinked Discord channel is spoken in. - - let value = select("guild_active", "autocreate", {guild_id}).pluck().get() + - let value = !!select("guild_active", "autocreate", {guild_id}).pluck().get() input(type="hidden" name="guild_id" value=guild_id) input.s-toggle-switch.order-last#autocreate(name="autocreate" type="checkbox" hx-post="/api/autocreate" hx-indicator="#autocreate-loading" hx-disabled-elt="this" hx-swap="none" checked=value) .is-loading#autocreate-loading diff --git a/src/web/pug/includes/template.pug b/src/web/pug/includes/template.pug index c117056..94b5e92 100644 --- a/src/web/pug/includes/template.pug +++ b/src/web/pug/includes/template.pug @@ -13,6 +13,7 @@ doctype html html(lang="en") head title Out Of Your Element + link(rel="stylesheet" type="text/css" href="/static/stacks.min.css") meta(name="htmx-config" content='{"indicatorClass":"is-loading"}') @@ -52,7 +53,7 @@ html(lang="en") li(role="menuitem") a.s-topbar--item.s-user-card.d-flex.p4(href=`/guild?guild_id=${guild.id}`) +guild(guild) - .mx-auto.w100.wmx9.py24#content + .mx-auto.w100.wmx9.py24.px8#content block body script. document.querySelectorAll("[popovertarget]").forEach(e => { diff --git a/src/web/routes/invite.js b/src/web/routes/invite.js index eec7a3c..94fa367 100644 --- a/src/web/routes/invite.js +++ b/src/web/routes/invite.js @@ -9,6 +9,8 @@ const {LRUCache} = require("lru-cache") const {discord, as, sync, select} = require("../../passthrough") /** @type {import("../pug-sync")} */ const pugSync = sync.require("../pug-sync") +/** @type {import("../../d2m/actions/create-space")} */ +const createSpace = sync.require("../../d2m/actions/create-space") const {reg} = require("../../matrix/read-registration") /** @type {import("../../matrix/api")} */ @@ -71,20 +73,20 @@ as.router.post("/api/invite", defineEventHandler(async event => { } // Check guild is bridged - const spaceID = select("guild_space", "space_id", {guild_id: guild_id}).pluck().get() - if (!spaceID) throw createError({status: 428, message: "Server not bridged", data: "You can only invite Matrix users to servers that are bridged to Matrix."}) + const guild = discord.guilds.get(guild_id) + assert(guild) + const spaceID = await createSpace.ensureSpace(guild) // Check for existing invite to the space let spaceMember try { spaceMember = await api.getStateEvent(spaceID, "m.room.member", parsedBody.mxid) } catch (e) {} - if (spaceMember && (spaceMember.membership === "invite" || spaceMember.membership === "join")) { - return sendRedirect(event, `/guild?guild_id=${guild_id}`, 302) - } - // Invite - await api.inviteToRoom(spaceID, parsedBody.mxid) + if (!spaceMember || spaceMember.membership !== "invite" || spaceMember.membership !== "join") { + // Invite + await api.inviteToRoom(spaceID, parsedBody.mxid) + } // Permissions if (parsedBody.permissions === "moderator") { diff --git a/src/web/routes/oauth.js b/src/web/routes/oauth.js index f3078ad..2f12dd1 100644 --- a/src/web/routes/oauth.js +++ b/src/web/routes/oauth.js @@ -7,7 +7,7 @@ const {SnowTransfer} = require("snowtransfer") const DiscordTypes = require("discord-api-types/v10") const fetch = require("node-fetch") -const {as} = require("../../passthrough") +const {as, db} = require("../../passthrough") const {id} = require("../../../addbot") const {reg} = require("../../matrix/read-registration") @@ -77,14 +77,19 @@ as.router.get("/oauth", defineEventHandler(async event => { const client = new SnowTransfer(`Bearer ${parsedToken.data.access_token}`) try { const guilds = await client.user.getGuilds() - const managedGuilds = guilds.filter(g => BigInt(g.permissions) & DiscordTypes.PermissionFlagsBits.ManageGuild).map(g => g.id) + var managedGuilds = guilds.filter(g => BigInt(g.permissions) & DiscordTypes.PermissionFlagsBits.ManageGuild).map(g => g.id) await session.update({managedGuilds}) } catch (e) { throw createError({status: 502, message: "API call failed", data: e.message}) } + // Set auto-create for the guild + // @ts-ignore + if (managedGuilds.includes(parsedQuery.data.guild_id)) { + db.prepare("INSERT OR IGNORE INTO guild_active (guild_id, autocreate) VALUES (?, ?)").run(parsedQuery.data.guild_id, +!session.data.selfService) + } + if (parsedQuery.data.guild_id) { - // TODO: we probably need to create a matrix space and database entry immediately here so that self-service settings apply and so matrix users can be invited return sendRedirect(event, `/guild?guild_id=${parsedQuery.data.guild_id}`, 302) } From 5dbd79cf3920f8ebffb1753158e716bf28193f1d Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sun, 29 Sep 2024 04:40:38 +1300 Subject: [PATCH 013/228] Prompt to add redirect URI in setup --- scripts/setup.js | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/scripts/setup.js b/scripts/setup.js index 0fae913..a3902be 100644 --- a/scripts/setup.js +++ b/scripts/setup.js @@ -148,10 +148,15 @@ async function validateHomeserverOrigin(serverUrlPrompt, url) { } } }) + bridgeOriginResponse.bridge_origin = bridgeOriginResponse.bridge_origin.replace(/\/+$/, "") // remove trailing slash await server.close() console.log("What is your Discord bot token?") + /** @type {SnowTransfer} */ // @ts-ignore + let snow = null + /** @type {{id: string, redirect_uris: string[]}} */ // @ts-ignore + let client = null /** @type {{discord_token: string}} */ const discordTokenResponse = await prompt({ type: "input", @@ -160,8 +165,8 @@ async function validateHomeserverOrigin(serverUrlPrompt, url) { validate: async token => { process.stdout.write(magenta(" checking, please wait...")) try { - const snow = new SnowTransfer(token) - await snow.user.getSelf() + snow = new SnowTransfer(token) + client = await snow.requestHandler.request(`/applications/@me`, {}, "get") return true } catch (e) { return e.message @@ -170,6 +175,7 @@ async function validateHomeserverOrigin(serverUrlPrompt, url) { }) console.log("What is your Discord client secret?") + console.log(`You can find it on the application page: https://discord.com/developers/applications/${client.id}/oauth2`) /** @type {{discord_client_secret: string}} */ const clientSecretResponse = await prompt({ type: "input", @@ -177,6 +183,25 @@ async function validateHomeserverOrigin(serverUrlPrompt, url) { message: "Client secret" }) + const expectedUri = `${bridgeOriginResponse.bridge_origin}/oauth` + if (!client.redirect_uris.includes(expectedUri)) { + console.log(`On the same application page, go to the Redirects section, and add this URI: ${cyan(expectedUri)}`) + await prompt({ + type: "invisible", + name: "redirect_uri", + message: "Press Enter when you've added it", + validate: async token => { + process.stdout.write(magenta("checking, please wait...")) + client = await snow.requestHandler.request(`/applications/@me`, {}, "get") + if (client.redirect_uris.includes(expectedUri)) { + return true + } else { + return "Redirect URI has not been added yet" + } + } + }) + } + const template = getTemplateRegistration(serverNameResponse.server_name) reg = { ...template, From 65170c128254732d23519eb1c169c78c89959b5c Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 30 Sep 2024 00:37:10 +1300 Subject: [PATCH 014/228] Registration YAML sample no longer needed --- registration.example.yaml | 25 ------------------------- 1 file changed, 25 deletions(-) delete mode 100644 registration.example.yaml diff --git a/registration.example.yaml b/registration.example.yaml deleted file mode 100644 index d38f5ae..0000000 --- a/registration.example.yaml +++ /dev/null @@ -1,25 +0,0 @@ -id: de8c56117637cb5d9f4ac216f612dc2adb1de4c09ae8d13553f28c33a28147c7 -hs_token: [a unique 64 character hex string] -as_token: [a unique 64 character hex string] -url: http://localhost:6693 -sender_localpart: _ooye_bot -protocols: - - discord -namespaces: - users: - - exclusive: true - regex: '@_ooye_.*' - aliases: - - exclusive: true - regex: '#_ooye_.*' -rate_limited: false -ooye: - namespace_prefix: _ooye_ - max_file_size: 5000000 - server_name: [the part after the colon in your matrix id, like cadence.moe] - server_origin: [the full protocol and domain of your actual matrix server's location, with no trailing slash, like https://matrix.cadence.moe] - content_length_workaround: false - include_user_id_in_mxid: false - invite: - # uncomment this to auto-invite the named user to newly created spaces and mark them as admin (PL 100) everywhere - # - '@cadence:cadence.moe' From bad8c5b8c249f9060aea44d903f1ca47cbadf8b0 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 30 Sep 2024 00:51:55 +1300 Subject: [PATCH 015/228] Test invite interaction & code coverage --- scripts/setup.js | 6 +- src/db/orm.test.js | 10 ++ src/discord/interactions/bridge.js | 115 ------------ src/discord/interactions/invite.js | 14 +- src/discord/interactions/invite.test.js | 228 ++++++++++++++++++++++++ src/discord/register-interactions.js | 17 -- src/discord/utils.js | 2 +- src/discord/utils.test.js | 73 ++++++++ src/matrix/power.test.js | 12 -- src/matrix/read-registration.js | 6 +- src/matrix/read-registration.test.js | 21 ++- src/types.d.ts | 7 +- test/data.js | 49 ++++- test/ooye-test-data.sql | 3 + test/test.js | 5 +- 15 files changed, 407 insertions(+), 161 deletions(-) delete mode 100644 src/discord/interactions/bridge.js create mode 100644 src/discord/interactions/invite.test.js delete mode 100644 src/matrix/power.test.js diff --git a/scripts/setup.js b/scripts/setup.js index a3902be..13c2492 100644 --- a/scripts/setup.js +++ b/scripts/setup.js @@ -7,6 +7,7 @@ const sqlite = require("better-sqlite3") const {scheduler} = require("timers/promises") const {isDeepStrictEqual} = require("util") const {createServer} = require("http") +const {join} = require("path") const {prompt} = require("enquirer") const Input = require("enquirer/lib/prompts/input") @@ -208,7 +209,6 @@ async function validateHomeserverOrigin(serverUrlPrompt, url) { url: bridgeOriginResponse.bridge_origin, ooye: { ...template.ooye, - ...serverNameResponse, ...bridgeOriginResponse, server_origin: serverOrigin, ...discordTokenResponse, @@ -335,8 +335,8 @@ async function validateHomeserverOrigin(serverUrlPrompt, url) { } // Upload those emojis to the chosen location db.prepare("REPLACE INTO auto_emoji (name, emoji_id, guild_id) VALUES ('_', '_', ?)").run(guild.id) - await uploadAutoEmoji(discord.snow, guild, "L1", "docs/img/L1.png") - await uploadAutoEmoji(discord.snow, guild, "L2", "docs/img/L2.png") + await uploadAutoEmoji(discord.snow, guild, "L1", join(__dirname, "../docs/img/L1.png")) + await uploadAutoEmoji(discord.snow, guild, "L2", join(__dirname, "../docs/img/L2.png")) } console.log("✅ Emojis are ready...") diff --git a/src/db/orm.test.js b/src/db/orm.test.js index 278723a..a8f10f4 100644 --- a/src/db/orm.test.js +++ b/src/db/orm.test.js @@ -58,3 +58,13 @@ test("orm: from: join direction works", t => { const hasNoOwnerInner = from("sim").join("sim_proxy", "user_id", "inner").select("user_id", "proxy_owner_id").where({sim_name: "crunch_god"}).get() t.deepEqual(hasNoOwnerInner, undefined) }) + +test("orm: select unsafe works (to select complex column names that can't be type verified)", t => { + const results = from("member_cache") + .join("member_power", "mxid") + .join("channel_room", "room_id") // only include rooms that are bridged + .and("where member_power.room_id = '*' and member_cache.power_level != member_power.power_level") + .selectUnsafe("mxid", "member_cache.room_id", "member_power.power_level") + .all() + t.equal(results[0].power_level, 100) +}) diff --git a/src/discord/interactions/bridge.js b/src/discord/interactions/bridge.js deleted file mode 100644 index 1fbc57e..0000000 --- a/src/discord/interactions/bridge.js +++ /dev/null @@ -1,115 +0,0 @@ -// @ts-check - -const DiscordTypes = require("discord-api-types/v10") -const Ty = require("../../types") -const {discord, sync, db, select, from, as} = require("../../passthrough") -const assert = require("assert/strict") - -/** @type {import("../../matrix/api")} */ -const api = sync.require("../../matrix/api") - -/** @type {Map>} spaceID -> list of rooms */ -const cache = new Map() -/** @type {Map} roomID -> spaceID */ -const reverseCache = new Map() - -// Manage clearing the cache -sync.addTemporaryListener(as, "type:m.room.name", /** @param {Ty.Event.StateOuter} event */ async event => { - if (event.state_key !== "") return - const roomID = event.room_id - const spaceID = reverseCache.get(roomID) - if (!spaceID) return - const childRooms = await cache.get(spaceID) - if (!childRooms) return - if (event.content.name) { - const found = childRooms.find(r => r.value === roomID) - if (!found) return - found.name = event.content.name - } else { - cache.set(spaceID, Promise.resolve(childRooms.filter(r => r.value !== roomID))) - reverseCache.delete(roomID) - } -}) - -// Manage adding to the cache -async function getCachedHierarchy(spaceID) { - return cache.get(spaceID) || (() => { - const entry = (async () => { - const result = await api.getFullHierarchy(spaceID) - /** @type {{name: string, value: string}[]} */ - const childRooms = [] - for (const room of result) { - if (room.name && !room.name.match(/^\[[⛓️🔊]\]/) && room.room_type !== "m.space") { - childRooms.push({name: room.name, value: room.room_id}) - reverseCache.set(room.room_id, spaceID) - } - } - return childRooms - })() - cache.set(spaceID, entry) - return entry - })() -} - -/** @param {DiscordTypes.APIApplicationCommandAutocompleteGuildInteraction} interaction */ -async function interactAutocomplete({id, token, data, guild_id}) { - const spaceID = select("guild_space", "space_id", {guild_id}).pluck().get() - if (!spaceID) { - return discord.snow.interaction.createInteractionResponse(id, token, { - type: DiscordTypes.InteractionResponseType.ApplicationCommandAutocompleteResult, - data: { - choices: [ - { - name: `Error: This server needs to be bridged somewhere first...`, - value: "baby" - } - ] - } - }) - } - - let rooms = await getCachedHierarchy(spaceID) - // @ts-ignore - rooms = rooms.filter(r => r.name.includes(data.options[0].value)) - - await discord.snow.interaction.createInteractionResponse(id, token, { - type: DiscordTypes.InteractionResponseType.ApplicationCommandAutocompleteResult, - data: { - choices: rooms - } - }) -} - -/** @param {DiscordTypes.APIChatInputApplicationCommandGuildInteraction} interaction */ -async function interactSubmit({id, token, data, guild_id}) { - const spaceID = select("guild_space", "space_id", {guild_id}).pluck().get() - if (!spaceID) { - return discord.snow.interaction.createInteractionResponse(id, token, { - type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, - data: { - content: "Error: This server needs to be bridged somewhere first...", - flags: DiscordTypes.MessageFlags.Ephemeral - } - }) - } - - return discord.snow.interaction.createInteractionResponse(id, token, { - type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, - data: { - content: "Valid input. This would do something but it isn't implemented yet.", - flags: DiscordTypes.MessageFlags.Ephemeral - } - }) -} - -/** @param {DiscordTypes.APIGuildInteraction} interaction */ -async function interact(interaction) { - if (interaction.type === DiscordTypes.InteractionType.ApplicationCommandAutocomplete) { - return interactAutocomplete(interaction) - } else if (interaction.type === DiscordTypes.InteractionType.ApplicationCommand) { - // @ts-ignore - return interactSubmit(interaction) - } -} - -module.exports.interact = interact diff --git a/src/discord/interactions/invite.js b/src/discord/interactions/invite.js index 3b39d9d..bacf465 100644 --- a/src/discord/interactions/invite.js +++ b/src/discord/interactions/invite.js @@ -14,13 +14,14 @@ const api = sync.require("../../matrix/api") /** * @param {DiscordTypes.APIChatInputApplicationCommandGuildInteraction & {channel: DiscordTypes.APIGuildTextChannel}} interaction + * @param {{api: typeof api}} di * @returns {Promise} */ -async function _interact({data, channel, guild_id}) { +async function _interact({data, channel, guild_id}, {api}) { // Get named MXID /** @type {DiscordTypes.APIApplicationCommandInteractionDataStringOption[] | undefined} */ // @ts-ignore const options = data.options - const input = options?.[0].value || "" + const input = options?.[0]?.value || "" const mxid = input.match(/@([^:]+):([a-z0-9:-]+\.[a-z0-9.:-]+)/)?.[0] if (!mxid) return { type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, @@ -110,9 +111,10 @@ async function _interact({data, channel, guild_id}) { /** * @param {DiscordTypes.APIMessageComponentGuildInteraction} interaction + * @param {{api: typeof api}} di * @returns {Promise} */ -async function _interactButton({channel, message}) { +async function _interactButton({channel, message}, {api}) { const mxid = message.content.match(/`(@(?:[^:]+):(?:[a-z0-9:-]+\.[a-z0-9.:-]+))`/)?.[1] assert(mxid) const roomID = select("channel_room", "room_id", {channel_id: channel.id}).pluck().get() @@ -127,14 +129,16 @@ async function _interactButton({channel, message}) { } } +/* c8 ignore start */ + /** @param {DiscordTypes.APIChatInputApplicationCommandGuildInteraction & {channel: DiscordTypes.APIGuildTextChannel}} interaction */ async function interact(interaction) { - await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, await _interact(interaction)) + await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, await _interact(interaction, {api})) } /** @param {DiscordTypes.APIMessageComponentGuildInteraction} interaction */ async function interactButton(interaction) { - await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, await _interactButton(interaction)) + await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, await _interactButton(interaction, {api})) } module.exports.interact = interact diff --git a/src/discord/interactions/invite.test.js b/src/discord/interactions/invite.test.js new file mode 100644 index 0000000..431ff60 --- /dev/null +++ b/src/discord/interactions/invite.test.js @@ -0,0 +1,228 @@ +const {test} = require("supertape") +const DiscordTypes = require("discord-api-types/v10") +const {db, discord} = require("../../passthrough") +const {MatrixServerError} = require("../../matrix/mreq") +const {_interact, _interactButton} = require("./invite") + +test("invite: checks for missing matrix ID", async t => { + const msg = await _interact({ + data: { + options: [] + }, + channel: discord.channels.get("0"), + guild_id: "112760669178241024" + }, {}) + t.equal(msg.data.content, "You have to say the Matrix ID of the person you want to invite. Matrix IDs look like this: `@username:example.org`") +}) + +test("invite: checks for invalid matrix ID", async t => { + const msg = await _interact({ + data: { + options: [{ + name: "user", + type: DiscordTypes.ApplicationCommandOptionType.String, + value: "@cadence" + }] + }, + channel: discord.channels.get("0"), + guild_id: "112760669178241024" + }, {}) + t.equal(msg.data.content, "You have to say the Matrix ID of the person you want to invite. Matrix IDs look like this: `@username:example.org`") +}) + +test("invite: checks if channel exists or is autocreatable", async t => { + db.prepare("UPDATE guild_active SET autocreate = 0").run() + const msg = await _interact({ + data: { + options: [{ + name: "user", + type: DiscordTypes.ApplicationCommandOptionType.String, + value: "@cadence:cadence.moe" + }] + }, + channel: discord.channels.get("498323546729086986"), + guild_id: "112760669178241024" + }, {}) + t.equal(msg.data.content, "This channel isn't bridged, so you can't invite Matrix users yet. Try turning on automatic room-creation or link a Matrix room in the website.") + db.prepare("UPDATE guild_active SET autocreate = 1").run() +}) + +test("invite: checks if user is already invited to space", async t => { + let called = 0 + const msg = await _interact({ + data: { + options: [{ + name: "user", + type: DiscordTypes.ApplicationCommandOptionType.String, + value: "@cadence:cadence.moe" + }] + }, + channel: discord.channels.get("112760669178241024"), + guild_id: "112760669178241024" + }, { + api: { + getStateEvent: async (roomID, type, stateKey) => { + called++ + t.equal(roomID, "!jjWAGMeQdNrVZSSfvz:cadence.moe") // space ID + t.equal(type, "m.room.member") + t.equal(stateKey, "@cadence:cadence.moe") + return { + displayname: "cadence", + membership: "invite" + } + } + } + }) + t.equal(msg.data.content, "`@cadence:cadence.moe` already has an invite, which they haven't accepted yet.") + t.equal(called, 1) +}) + +test("invite: invites if user is not in space", async t => { + let called = 0 + const msg = await _interact({ + data: { + options: [{ + name: "user", + type: DiscordTypes.ApplicationCommandOptionType.String, + value: "@cadence:cadence.moe" + }] + }, + channel: discord.channels.get("112760669178241024"), + guild_id: "112760669178241024" + }, { + api: { + getStateEvent: async (roomID, type, stateKey) => { + called++ + t.equal(roomID, "!jjWAGMeQdNrVZSSfvz:cadence.moe") // space ID + t.equal(type, "m.room.member") + t.equal(stateKey, "@cadence:cadence.moe") + throw new MatrixServerError("State event doesn't exist or something") + }, + inviteToRoom: async (roomID, mxid) => { + called++ + t.equal(roomID, "!jjWAGMeQdNrVZSSfvz:cadence.moe") // space ID + t.equal(mxid, "@cadence:cadence.moe") + } + } + }) + t.equal(msg.data.content, "You invited `@cadence:cadence.moe` to the server.") + t.equal(called, 2) +}) + +test("invite: prompts to invite to room (if never joined)", async t => { + let called = 0 + const msg = await _interact({ + data: { + options: [{ + name: "user", + type: DiscordTypes.ApplicationCommandOptionType.String, + value: "@cadence:cadence.moe" + }] + }, + channel: discord.channels.get("112760669178241024"), + guild_id: "112760669178241024" + }, { + api: { + getStateEvent: async (roomID, type, stateKey) => { + called++ + t.equal(type, "m.room.member") + t.equal(stateKey, "@cadence:cadence.moe") + if (roomID === "!jjWAGMeQdNrVZSSfvz:cadence.moe") { // space ID + return { + displayname: "cadence", + membership: "join" + } + } else { + throw new MatrixServerError("State event doesn't exist or something") + } + } + } + }) + t.equal(msg.data.content, "`@cadence:cadence.moe` is already in this server. Would you like to additionally invite them to this specific channel?") + t.equal(called, 2) +}) + +test("invite: prompts to invite to room (if left)", async t => { + let called = 0 + const msg = await _interact({ + data: { + options: [{ + name: "user", + type: DiscordTypes.ApplicationCommandOptionType.String, + value: "@cadence:cadence.moe" + }] + }, + channel: discord.channels.get("112760669178241024"), + guild_id: "112760669178241024" + }, { + api: { + getStateEvent: async (roomID, type, stateKey) => { + called++ + t.equal(type, "m.room.member") + t.equal(stateKey, "@cadence:cadence.moe") + if (roomID === "!jjWAGMeQdNrVZSSfvz:cadence.moe") { // space ID + return { + displayname: "cadence", + membership: "join" + } + } else { + return { + displayname: "cadence", + membership: "leave" + } + } + } + } + }) + t.equal(msg.data.content, "`@cadence:cadence.moe` is already in this server. Would you like to additionally invite them to this specific channel?") + t.equal(called, 2) +}) + +test("invite button: invites to room when button clicked", async t => { + let called = 0 + const msg = await _interactButton({ + channel: discord.channels.get("112760669178241024"), + message: { + content: "`@cadence:cadence.moe` is already in this server. Would you like to additionally invite them to this specific channel?" + } + }, { + api: { + inviteToRoom: async (roomID, mxid) => { + called++ + t.equal(roomID, "!kLRqKKUQXcibIMtOpl:cadence.moe") // room ID + t.equal(mxid, "@cadence:cadence.moe") + } + } + }) + t.equal(msg.data.content, "You invited `@cadence:cadence.moe` to the channel.") + t.equal(called, 1) +}) + +test("invite: no-op if in room and space", async t => { + let called = 0 + const msg = await _interact({ + data: { + options: [{ + name: "user", + type: DiscordTypes.ApplicationCommandOptionType.String, + value: "@cadence:cadence.moe" + }] + }, + channel: discord.channels.get("112760669178241024"), + guild_id: "112760669178241024" + }, { + api: { + getStateEvent: async (roomID, type, stateKey) => { + called++ + t.equal(type, "m.room.member") + t.equal(stateKey, "@cadence:cadence.moe") + return { + displayname: "cadence", + membership: "join" + } + } + } + }) + t.equal(msg.data.content, "`@cadence:cadence.moe` is already in this server and this channel.") + t.equal(called, 2) +}) diff --git a/src/discord/register-interactions.js b/src/discord/register-interactions.js index cd9203f..7b1e52d 100644 --- a/src/discord/register-interactions.js +++ b/src/discord/register-interactions.js @@ -7,7 +7,6 @@ const {id} = require("../../addbot") const matrixInfo = sync.require("./interactions/matrix-info.js") const invite = sync.require("./interactions/invite.js") const permissions = sync.require("./interactions/permissions.js") -const bridge = sync.require("./interactions/bridge.js") const reactions = sync.require("./interactions/reactions.js") const privacy = sync.require("./interactions/privacy.js") @@ -39,20 +38,6 @@ discord.snow.interaction.bulkOverwriteApplicationCommands(id, [{ name: "user" } ] -}, { - name: "bridge", - contexts: [DiscordTypes.InteractionContextType.Guild], - type: DiscordTypes.ApplicationCommandType.ChatInput, - description: "Start bridging this channel to a Matrix room", - default_member_permissions: String(DiscordTypes.PermissionFlagsBits.ManageChannels), - options: [ - { - type: DiscordTypes.ApplicationCommandOptionType.String, - description: "Destination room to bridge to", - name: "room", - autocomplete: true - } - ] }, { name: "privacy", contexts: [DiscordTypes.InteractionContextType.Guild], @@ -94,8 +79,6 @@ async function dispatchInteraction(interaction) { await permissions.interact(interaction) } else if (interactionId === "permissions_edit") { await permissions.interactEdit(interaction) - } else if (interactionId === "bridge") { - await bridge.interact(interaction) } else if (interactionId === "Reactions") { await reactions.interact(interaction) } else if (interactionId === "privacy") { diff --git a/src/discord/utils.js b/src/discord/utils.js index dc96ff8..dea05ae 100644 --- a/src/discord/utils.js +++ b/src/discord/utils.js @@ -113,7 +113,7 @@ function isWebhookMessage(message) { * @param {Pick} message */ function isEphemeralMessage(message) { - return message.flags && (message.flags & DiscordTypes.MessageFlags.Ephemeral) + return Boolean(message.flags && (message.flags & DiscordTypes.MessageFlags.Ephemeral)) } /** @param {string} snowflake */ diff --git a/src/discord/utils.test.js b/src/discord/utils.test.js index 7c5f0c8..7900440 100644 --- a/src/discord/utils.test.js +++ b/src/discord/utils.test.js @@ -84,6 +84,67 @@ test("getPermissions: channel overwrite to allow role works", t => { t.equal((permissions & want), want) }) +test("getPermissions: channel overwrite to allow user works", t => { + const guildRoles = [ + { + version: 1695412489043, + unicode_emoji: null, + tags: {}, + position: 0, + permissions: "559623605571137", + name: "@everyone", + mentionable: false, + managed: false, + id: "1154868424724463687", + icon: null, + hoist: false, + flags: 0, + color: 0 + }, + { + version: 1695412604262, + unicode_emoji: null, + tags: { bot_id: "466378653216014359" }, + position: 1, + permissions: "536995904", + name: "PluralKit", + mentionable: false, + managed: true, + id: "1154868908336099444", + icon: null, + hoist: false, + flags: 0, + color: 0 + }, + { + version: 1698778936921, + unicode_emoji: null, + tags: {}, + position: 1, + permissions: "536870912", + name: "web hookers", + mentionable: false, + managed: false, + id: "1168988246680801360", + icon: null, + hoist: false, + flags: 0, + color: 0 + } + ] + const userRoles = [] + const userID = "353373325575323648" + const overwrites = [ + { type: 0, id: "1154868908336099444", deny: "0", allow: "1024" }, + { type: 0, id: "1154868424724463687", deny: "1024", allow: "0" }, + { type: 0, id: "1168988246680801360", deny: "0", allow: "1024" }, + { type: 1, id: "353373325575323648", deny: "0", allow: "1024" } + ] + const permissions = utils.getPermissions(userRoles, guildRoles, userID, overwrites) + const want = BigInt(1 << 10 | 1 << 16) + t.equal((permissions & want), want) +}) + test("hasSomePermissions: detects the permission", t => { const userPermissions = DiscordTypes.PermissionFlagsBits.MentionEveryone | DiscordTypes.PermissionFlagsBits.BanMembers const canRemoveMembers = utils.hasSomePermissions(userPermissions, ["KickMembers", "BanMembers"]) @@ -107,3 +168,15 @@ test("hasAllPermissions: doesn't detect not the permissions", t => { const canRemoveMembers = utils.hasAllPermissions(userPermissions, ["KickMembers", "BanMembers"]) t.equal(canRemoveMembers, false) }) + +test("isEphemeralMessage: detects ephemeral message", t => { + t.equal(utils.isEphemeralMessage(data.special_message.ephemeral_message), true) +}) + +test("isEphemeralMessage: doesn't detect normal message", t => { + t.equal(utils.isEphemeralMessage(data.message.simple_plaintext), false) +}) + +test("getPublicUrlForCdn: no-op on non-discord URL", t => { + t.equal(utils.getPublicUrlForCdn("https://cadence.moe"), "https://cadence.moe") +}) diff --git a/src/matrix/power.test.js b/src/matrix/power.test.js deleted file mode 100644 index 5423c4f..0000000 --- a/src/matrix/power.test.js +++ /dev/null @@ -1,12 +0,0 @@ -// @ts-check - -const {test} = require("supertape") -const power = require("./power") - -test("power: get affected rooms", t => { - t.deepEqual(power._getAffectedRooms(), [{ - mxid: "@test_auto_invite:example.org", - power_level: 100, - room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe", - }]) -}) diff --git a/src/matrix/read-registration.js b/src/matrix/read-registration.js index 9fb0535..d126851 100644 --- a/src/matrix/read-registration.js +++ b/src/matrix/read-registration.js @@ -9,7 +9,7 @@ const registrationFilePath = path.join(process.cwd(), "registration.yaml") /** @param {import("../types").AppServiceRegistrationConfig} reg */ function checkRegistration(reg) { - reg["ooye"].invite = (reg.ooye.invite || []).filter(mxid => mxid.endsWith(`:${reg.ooye.server_name}`)) // one day I will understand why typescript disagrees with dot notation on this line + reg["ooye"].invite = reg.ooye.invite.filter(mxid => mxid.endsWith(`:${reg.ooye.server_name}`)) // one day I will understand why typescript disagrees with dot notation on this line assert(reg.ooye?.max_file_size) assert(reg.ooye?.namespace_prefix) assert(reg.ooye?.server_name) @@ -19,6 +19,7 @@ function checkRegistration(reg) { assert.match(reg.url, /^https?:/, "url must start with http:// or https://") } +/* c8 ignore next 4 */ /** @param {import("../types").AppServiceRegistrationConfig} reg */ function writeRegistration(reg) { fs.writeFileSync(registrationFilePath, JSON.stringify(reg, null, 2)) @@ -52,6 +53,7 @@ function getTemplateRegistration(serverName) { socket: 6693, ooye: { namespace_prefix, + server_name: serverName, max_file_size: 5000000, content_length_workaround: false, include_user_id_in_mxid: false, @@ -66,6 +68,8 @@ function readRegistration() { try { const content = fs.readFileSync(registrationFilePath, "utf8") result = JSON.parse(content) + result.ooye.invite ||= [] + /* c8 ignore next */ } catch (e) {} return result } diff --git a/src/matrix/read-registration.test.js b/src/matrix/read-registration.test.js index 80ac09f..5fb3b55 100644 --- a/src/matrix/read-registration.test.js +++ b/src/matrix/read-registration.test.js @@ -1,5 +1,8 @@ +// @ts-check + +const tryToCatch = require("try-to-catch") const {test} = require("supertape") -const {reg} = require("./read-registration") +const {reg, checkRegistration, getTemplateRegistration} = require("./read-registration") test("reg: has necessary parameters", t => { const propertiesToCheck = ["sender_localpart", "id", "as_token", "ooye"] @@ -8,3 +11,19 @@ test("reg: has necessary parameters", t => { propertiesToCheck ) }) + +test("check: passes on sample", t => { + checkRegistration(reg) + t.pass("all assertions passed") +}) + +test("check: fails on template as template is missing some required values that are gathered during setup", t => { + let err + try { + // @ts-ignore + checkRegistration(getTemplateRegistration("cadence.moe")) + } catch (e) { + err = e + } + t.ok(err, "one of the assertions failed as expected") +}) diff --git a/src/types.d.ts b/src/types.d.ts index 62d9b30..576bb59 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -55,9 +55,10 @@ export type InitialAppServiceRegistrationConfig = { socket?: string | number, ooye: { namespace_prefix: string - max_file_size: number, - content_length_workaround: boolean, - invite: string[], + server_name: string + max_file_size: number + content_length_workaround: boolean + invite: string[] include_user_id_in_mxid: boolean } } diff --git a/test/data.js b/test/data.js index eb2c42a..9dc2d72 100644 --- a/test/data.js +++ b/test/data.js @@ -4128,7 +4128,54 @@ module.exports = { guild_id: "112760669178241024" }, position: 0 - } + }, + ephemeral_message: { + webhook_id: "684280192553844747", + type: 20, + tts: false, + timestamp: "2024-09-29T11:22:04.865000+00:00", + position: 0, + pinned: false, + nonce: "1289910062243905536", + mentions: [], + mention_roles: [], + mention_everyone: false, + interaction_metadata: { + user: {baby: true}, + type: 2, + name: "invite", + id: "1289910063691206717", + command_type: 1, + authorizing_integration_owners: {baby: true} + }, + interaction: { + user: {baby: true}, + type: 2, + name: "invite", + id: "1289910063691206717" + }, + id: "1289910064995504182", + flags: 64, + embeds: [], + edited_timestamp: null, + content: "`@cadence:cadence.moe` is already in this server and this channel.", + components: [], + channel_id: "1100319550446252084", + author: { + username: "Matrix Bridge", + public_flags: 0, + id: "684280192553844747", + global_name: null, + discriminator: "5728", + clan: null, + bot: true, + avatar_decoration_data: null, + avatar: "48ae3c24f2a6ec5c60c41bdabd904018" + }, + attachments: [], + application_id: "684280192553844747" + }, + shard_id: 0 }, interaction_message: { thinking_interaction_without_bot_user: { diff --git a/test/ooye-test-data.sql b/test/ooye-test-data.sql index 2c23561..b6f0951 100644 --- a/test/ooye-test-data.sql +++ b/test/ooye-test-data.sql @@ -3,6 +3,9 @@ BEGIN TRANSACTION; INSERT INTO guild_space (guild_id, space_id, privacy_level) VALUES ('112760669178241024', '!jjWAGMeQdNrVZSSfvz:cadence.moe', 0); +INSERT INTO guild_active (guild_id, autocreate) VALUES +('112760669178241024', 1); + INSERT INTO channel_room (channel_id, room_id, name, nick, thread_parent, custom_avatar) VALUES ('112760669178241024', '!kLRqKKUQXcibIMtOpl:cadence.moe', 'heave', 'main', NULL, NULL), ('497161350934560778', '!CzvdIdUQXgUjDVKxeU:cadence.moe', 'amanda-spam', NULL, NULL, NULL), diff --git a/test/test.js b/test/test.js index 281df29..07146ab 100644 --- a/test/test.js +++ b/test/test.js @@ -23,8 +23,8 @@ reg.id = "baby" // don't actually take authenticated actions on the server reg.as_token = "baby" reg.hs_token = "baby" reg.ooye.bridge_origin = "https://bridge.example.org" -reg.ooye.invite = [] +/** @type {import("heatsync").default} */ // @ts-ignore const sync = new HeatSync({watchFS: false}) const discord = { @@ -35,6 +35,7 @@ const discord = { id: "684280192553844747" }, channels: new Map([ + [data.channel.general.id, data.channel.general], ["497161350934560778", { guild_id: "497159726455455754" }], @@ -117,7 +118,6 @@ file._actuallyUploadDiscordFileToMxc = function(url, res) { throw new Error(`Not require("../src/matrix/kstate.test") require("../src/matrix/api.test") require("../src/matrix/file.test") - require("../src/matrix/power.test") require("../src/matrix/read-registration.test") require("../src/matrix/txnid.test") require("../src/d2m/actions/create-room.test") @@ -136,4 +136,5 @@ file._actuallyUploadDiscordFileToMxc = function(url, res) { throw new Error(`Not require("../src/m2d/converters/event-to-message.test") require("../src/m2d/converters/utils.test") require("../src/m2d/converters/emoji-sheet.test") + require("../src/discord/interactions/invite.test") })() From 61803c3838d494782ae4b3edea70f72f1bbcb8f3 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 30 Sep 2024 01:18:56 +1300 Subject: [PATCH 016/228] Add tests for matrix info interaction --- src/discord/interactions/matrix-info.js | 36 ++++++---- src/discord/interactions/matrix-info.test.js | 76 ++++++++++++++++++++ test/test.js | 1 + 3 files changed, 101 insertions(+), 12 deletions(-) create mode 100644 src/discord/interactions/matrix-info.test.js diff --git a/src/discord/interactions/matrix-info.js b/src/discord/interactions/matrix-info.js index fac3804..f7bc31a 100644 --- a/src/discord/interactions/matrix-info.js +++ b/src/discord/interactions/matrix-info.js @@ -6,46 +6,58 @@ const {discord, sync, db, select, from} = require("../../passthrough") /** @type {import("../../matrix/api")} */ const api = sync.require("../../matrix/api") -/** @param {DiscordTypes.APIContextMenuGuildInteraction} interaction */ -/** @param {DiscordTypes.APIMessageApplicationCommandGuildInteraction} interaction */ -async function interact({id, token, guild_id, channel, data}) { +/** + * @param {DiscordTypes.APIMessageApplicationCommandGuildInteraction} interaction + * @param {{api: typeof api}} di + * @returns {Promise} + */ +async function _interact({guild_id, data}, {api}) { const message = from("event_message").join("message_channel", "message_id").join("channel_room", "channel_id") - .select("name", "nick", "source", "room_id", "event_id").where({message_id: data.target_id}).get() + .select("name", "nick", "source", "channel_id", "room_id", "event_id").where({message_id: data.target_id, part: 0}).get() if (!message) { - return discord.snow.interaction.createInteractionResponse(id, token, { + return { type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, data: { content: "This message hasn't been bridged to Matrix.", flags: DiscordTypes.MessageFlags.Ephemeral } - }) + } } const idInfo = `\n-# Room ID: \`${message.room_id}\`\n-# Event ID: \`${message.event_id}\`` + const roomName = message.nick || message.name if (message.source === 1) { // from Discord const userID = data.resolved.messages[data.target_id].author.id - return discord.snow.interaction.createInteractionResponse(id, token, { + return { type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, data: { - content: `Bridged <@${userID}> https://discord.com/channels/${guild_id}/${channel.id}/${data.target_id} on Discord to [${message.nick || message.name}]() on Matrix.` + content: `Bridged <@${userID}> https://discord.com/channels/${guild_id}/${message.channel_id}/${data.target_id} on Discord to [${roomName}]() on Matrix.` + idInfo, flags: DiscordTypes.MessageFlags.Ephemeral } - }) + } } // from Matrix const event = await api.getEvent(message.room_id, message.event_id) - return discord.snow.interaction.createInteractionResponse(id, token, { + return { type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, data: { - content: `Bridged [${event.sender}]()'s message in [${message.nick || message.name}]() on Matrix to https://discord.com/channels/${guild_id}/${channel.id}/${data.target_id} on Discord.` + content: `Bridged [${event.sender}]()'s message in [${roomName}]() on Matrix to https://discord.com/channels/${guild_id}/${message.channel_id}/${data.target_id} on Discord.` + idInfo, flags: DiscordTypes.MessageFlags.Ephemeral } - }) + } +} + +/* c8 ignore start */ + +/** @param {DiscordTypes.APIMessageApplicationCommandGuildInteraction} interaction */ +async function interact(interaction) { + await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, await _interact(interaction, {api})) } module.exports.interact = interact +module.exports._interact = _interact diff --git a/src/discord/interactions/matrix-info.test.js b/src/discord/interactions/matrix-info.test.js new file mode 100644 index 0000000..f4d0f52 --- /dev/null +++ b/src/discord/interactions/matrix-info.test.js @@ -0,0 +1,76 @@ +const {test} = require("supertape") +const data = require("../../../test/data") +const DiscordTypes = require("discord-api-types/v10") +const {db, discord} = require("../../passthrough") +const {MatrixServerError} = require("../../matrix/mreq") +const {_interact, _interactButton} = require("./matrix-info") + +test("matrix info: checks if message has bridged", async t => { + const msg = await _interact({ + data: { + target_id: "0" + }, + guild_id: "112760669178241024" + }, {}) + t.equal(msg.data.content, "This message hasn't been bridged to Matrix.") +}) + +test("matrix info: shows info for discord source message", async t => { + const msg = await _interact({ + data: { + target_id: "1141619794500649020", + resolved: { + messages: { + "1141619794500649020": data.message_update.edit_by_webhook + } + } + }, + guild_id: "497159726455455754" + }, {}) + t.equal( + msg.data.content, + "Bridged <@700285844094845050> https://discord.com/channels/497159726455455754/497161350934560778/1141619794500649020 on Discord to [amanda-spam]() on Matrix." + + "\n-# Room ID: `!CzvdIdUQXgUjDVKxeU:cadence.moe`" + + "\n-# Event ID: `$zXSlyI78DQqQwwfPUSzZ1b-nXzbUrCDljJgnGDdoI10`" + ) +}) + +test("matrix info: shows info for matrix source message", async t => { + let called = 0 + const msg = await _interact({ + data: { + target_id: "1128118177155526666", + resolved: { + messages: { + "1141501302736695316": data.message.simple_reply_to_matrix_user + } + } + }, + guild_id: "112760669178241024" + }, { + api: { + async getEvent(roomID, eventID) { + called++ + t.equal(roomID, "!kLRqKKUQXcibIMtOpl:cadence.moe") + t.equal(eventID, "$Ij3qo7NxMA4VPexlAiIx2CB9JbsiGhJeyt-2OvkAUe4") + return { + event_id: eventID, + room_id: roomID, + type: "m.room.message", + content: { + msgtype: "m.text", + body: "so can you reply to my webhook uwu" + }, + sender: "@cadence:cadence.moe" + } + } + } + }) + t.equal( + msg.data.content, + "Bridged [@cadence:cadence.moe]()'s message in [main]() on Matrix to https://discord.com/channels/112760669178241024/112760669178241024/1128118177155526666 on Discord." + + "\n-# Room ID: `!kLRqKKUQXcibIMtOpl:cadence.moe`" + + "\n-# Event ID: `$Ij3qo7NxMA4VPexlAiIx2CB9JbsiGhJeyt-2OvkAUe4`" + ) + t.equal(called, 1) +}) diff --git a/test/test.js b/test/test.js index 07146ab..e0736c8 100644 --- a/test/test.js +++ b/test/test.js @@ -137,4 +137,5 @@ file._actuallyUploadDiscordFileToMxc = function(url, res) { throw new Error(`Not require("../src/m2d/converters/utils.test") require("../src/m2d/converters/emoji-sheet.test") require("../src/discord/interactions/invite.test") + require("../src/discord/interactions/matrix-info.test") })() From 33915a595da748217bc349b541c2b1369a707792 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 30 Sep 2024 01:42:12 +1300 Subject: [PATCH 017/228] Add tests for reactions interaction --- addbot.js | 1 + src/discord/interactions/matrix-info.test.js | 7 +- src/discord/interactions/reactions.js | 29 +++++-- src/discord/interactions/reactions.test.js | 87 ++++++++++++++++++++ test/addbot.test.js | 8 ++ test/test.js | 3 + 6 files changed, 121 insertions(+), 14 deletions(-) create mode 100644 src/discord/interactions/reactions.test.js create mode 100644 test/addbot.test.js diff --git a/addbot.js b/addbot.js index e13c829..ef1cc63 100755 --- a/addbot.js +++ b/addbot.js @@ -9,6 +9,7 @@ function addbot() { return `Open this link to add the bot to a Discord server:\nhttps://discord.com/oauth2/authorize?client_id=${id}&scope=bot&permissions=1610883072 ` } +/* c8 ignore next 3 */ if (process.argv.find(a => a.endsWith("addbot") || a.endsWith("addbot.js"))) { console.log(addbot()) } diff --git a/src/discord/interactions/matrix-info.test.js b/src/discord/interactions/matrix-info.test.js index f4d0f52..5d0206e 100644 --- a/src/discord/interactions/matrix-info.test.js +++ b/src/discord/interactions/matrix-info.test.js @@ -1,11 +1,8 @@ const {test} = require("supertape") const data = require("../../../test/data") -const DiscordTypes = require("discord-api-types/v10") -const {db, discord} = require("../../passthrough") -const {MatrixServerError} = require("../../matrix/mreq") -const {_interact, _interactButton} = require("./matrix-info") +const {_interact} = require("./matrix-info") -test("matrix info: checks if message has bridged", async t => { +test("matrix info: checks if message is bridged", async t => { const msg = await _interact({ data: { target_id: "0" diff --git a/src/discord/interactions/reactions.js b/src/discord/interactions/reactions.js index 67f3a68..0a6d5a6 100644 --- a/src/discord/interactions/reactions.js +++ b/src/discord/interactions/reactions.js @@ -8,19 +8,22 @@ const api = sync.require("../../matrix/api") /** @type {import("../../m2d/converters/utils")} */ const utils = sync.require("../../m2d/converters/utils") -/** @param {DiscordTypes.APIContextMenuGuildInteraction} interaction */ -/** @param {DiscordTypes.APIMessageApplicationCommandGuildInteraction} interaction */ -async function interact({id, token, data}) { +/** + * @param {DiscordTypes.APIMessageApplicationCommandGuildInteraction} interaction + * @param {{api: typeof api}} di + * @returns {Promise} + */ +async function _interact({data}, {api}) { const row = from("event_message").join("message_channel", "message_id").join("channel_room", "channel_id") .select("event_id", "room_id").where({message_id: data.target_id}).get() if (!row) { - return discord.snow.interaction.createInteractionResponse(id, token, { + return { type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, data: { content: "This message hasn't been bridged to Matrix.", flags: DiscordTypes.MessageFlags.Ephemeral } - }) + } } const reactions = await api.getFullRelations(row.room_id, row.event_id, "m.annotation") @@ -37,22 +40,30 @@ async function interact({id, token, data}) { } if (inverted.size === 0) { - return discord.snow.interaction.createInteractionResponse(id, token, { + return { type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, data: { content: "Nobody from Matrix reacted to this message.", flags: DiscordTypes.MessageFlags.Ephemeral } - }) + } } - return discord.snow.interaction.createInteractionResponse(id, token, { + return { type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, data: { content: [...inverted.entries()].map(([key, value]) => `${key} ⮞ ${value.join(" ⬩ ")}`).join("\n"), flags: DiscordTypes.MessageFlags.Ephemeral } - }) + } +} + +/* c8 ignore start */ + +/** @param {DiscordTypes.APIMessageApplicationCommandGuildInteraction} interaction */ +async function interact(interaction) { + await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, await _interact(interaction, {api})) } module.exports.interact = interact +module.exports._interact = _interact diff --git a/src/discord/interactions/reactions.test.js b/src/discord/interactions/reactions.test.js new file mode 100644 index 0000000..c6de054 --- /dev/null +++ b/src/discord/interactions/reactions.test.js @@ -0,0 +1,87 @@ +const {test} = require("supertape") +const data = require("../../../test/data") +const DiscordTypes = require("discord-api-types/v10") +const {db, discord} = require("../../passthrough") +const {MatrixServerError} = require("../../matrix/mreq") +const {_interact} = require("./reactions") + +test("reactions: checks if message is bridged", async t => { + const msg = await _interact({ + data: { + target_id: "0" + } + }, {}) + t.equal(msg.data.content, "This message hasn't been bridged to Matrix.") +}) + +test("reactions: different response if nobody reacted", async t => { + const msg = await _interact({ + data: { + target_id: "1126786462646550579" + } + }, { + api: { + async getFullRelations(roomID, eventID) { + t.equal(roomID, "!kLRqKKUQXcibIMtOpl:cadence.moe") + t.equal(eventID, "$X16nfVks1wsrhq4E9SSLiqrf2N8KD0erD0scZG7U5xg") + return [] + } + } + }) + t.equal(msg.data.content, "Nobody from Matrix reacted to this message.") +}) + +test("reactions: shows reactions if there are some, ignoring discord users", async t => { + let called = 1 + const msg = await _interact({ + data: { + target_id: "1126786462646550579" + } + }, { + api: { + async getFullRelations(roomID, eventID) { + t.equal(roomID, "!kLRqKKUQXcibIMtOpl:cadence.moe") + t.equal(eventID, "$X16nfVks1wsrhq4E9SSLiqrf2N8KD0erD0scZG7U5xg") + return [{ + sender: "@cadence:cadence.moe", + content: { + "m.relates_to": { + key: "🐈", + rel_type: "m.annotation" + } + } + }, { + sender: "@rnl:cadence.moe", + content: { + "m.relates_to": { + key: "🐈", + rel_type: "m.annotation" + } + } + }, { + sender: "@cadence:cadence.moe", + content: { + "m.relates_to": { + key: "🐈‍⬛", + rel_type: "m.annotation" + } + } + }, { + sender: "@_ooye_rnl:cadence.moe", + content: { + "m.relates_to": { + key: "🐈", + rel_type: "m.annotation" + } + } + }] + } + } + }) + t.equal( + msg.data.content, + "🐈 ⮞ cadence [they] ⬩ @rnl:cadence.moe" + + "\n🐈‍⬛ ⮞ cadence [they]" + ) + t.equal(called, 1) +}) diff --git a/test/addbot.test.js b/test/addbot.test.js new file mode 100644 index 0000000..17c6dda --- /dev/null +++ b/test/addbot.test.js @@ -0,0 +1,8 @@ +// @ts-check + +const {addbot} = require("../addbot") +const {test} = require("supertape") + +test("addbot: returns message and invite link", t => { + t.equal(addbot(), `Open this link to add the bot to a Discord server:\nhttps://discord.com/oauth2/authorize?client_id=684280192553844747&scope=bot&permissions=1610883072 `) +}) diff --git a/test/test.js b/test/test.js index e0736c8..6695494 100644 --- a/test/test.js +++ b/test/test.js @@ -17,6 +17,7 @@ const passthrough = require("../src/passthrough") const db = new sqlite(":memory:") const {reg} = require("../src/matrix/read-registration") +reg.ooye.discord_token = "Njg0MjgwMTkyNTUzODQ0NzQ3.Xl3zlw.baby" reg.ooye.server_origin = "https://matrix.cadence.moe" // so that tests will pass even when hard-coded reg.ooye.server_name = "cadence.moe" reg.id = "baby" // don't actually take authenticated actions on the server @@ -113,6 +114,7 @@ file._actuallyUploadDiscordFileToMxc = function(url, res) { throw new Error(`Not db.exec(fs.readFileSync(join(__dirname, "ooye-test-data.sql"), "utf8")) + require("./addbot.test") require("../src/db/orm.test") require("../src/discord/utils.test") require("../src/matrix/kstate.test") @@ -138,4 +140,5 @@ file._actuallyUploadDiscordFileToMxc = function(url, res) { throw new Error(`Not require("../src/m2d/converters/emoji-sheet.test") require("../src/discord/interactions/invite.test") require("../src/discord/interactions/matrix-info.test") + require("../src/discord/interactions/reactions.test") })() From f5853ccf951eb7b08b74b6e24b6d48e0f2acdf44 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 30 Sep 2024 01:45:38 +1300 Subject: [PATCH 018/228] Fix check for enabling content_length_workaround --- src/matrix/mreq.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/matrix/mreq.js b/src/matrix/mreq.js index cdcf405..8a76b11 100644 --- a/src/matrix/mreq.js +++ b/src/matrix/mreq.js @@ -45,7 +45,7 @@ async function mreq(method, url, body, extra = {}) { const root = await res.json() if (!res.ok || root.errcode) { - if (root.error?.includes("Content-Length") || !reg.ooye.content_length_workaround) { + if (root.error?.includes("Content-Length") && !reg.ooye.content_length_workaround) { reg.ooye.content_length_workaround = true const root = await mreq(method, url, body, extra) console.error("OOYE cannot stream uploads to Synapse. The `content_length_workaround` option" From f77602afa6171f0841432c16f4e4a9c874db91a5 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 30 Sep 2024 16:26:12 +1300 Subject: [PATCH 019/228] Add tests for privacy interaction --- src/discord/interactions/privacy.js | 49 ++++++++++---- src/discord/interactions/privacy.test.js | 86 ++++++++++++++++++++++++ test/test.js | 1 + 3 files changed, 122 insertions(+), 14 deletions(-) create mode 100644 src/discord/interactions/privacy.test.js diff --git a/src/discord/interactions/privacy.js b/src/discord/interactions/privacy.js index bb8c6c9..8227b5a 100644 --- a/src/discord/interactions/privacy.js +++ b/src/discord/interactions/privacy.js @@ -3,32 +3,38 @@ const DiscordTypes = require("discord-api-types/v10") const {discord, sync, db, select} = require("../../passthrough") const {id: botID} = require("../../../addbot") +const {InteractionMethods} = require("snowtransfer") /** @type {import("../../d2m/actions/create-space")} */ const createSpace = sync.require("../../d2m/actions/create-space") /** * @param {DiscordTypes.APIChatInputApplicationCommandGuildInteraction} interaction + * @param {{createSpace: typeof createSpace}} di + * @returns {AsyncGenerator<{[k in keyof InteractionMethods]?: Parameters[2]}>} */ -async function interact({id, token, data, guild_id}) { +async function* _interact({data, guild_id}, {createSpace}) { // Check guild is bridged const current = select("guild_space", "privacy_level", {guild_id}).pluck().get() - if (current == null) return { - type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, - data: { - content: "This server isn't bridged to Matrix, so you can't set the Matrix privacy level.", - flags: DiscordTypes.MessageFlags.Ephemeral - } + InteractionMethods.prototype.createInteractionResponse + if (current == null) { + return yield {createInteractionResponse: { + type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, + data: { + content: "This server isn't bridged to Matrix, so you can't set the Matrix privacy level.", + flags: DiscordTypes.MessageFlags.Ephemeral + } + }} } // Get input level /** @type {DiscordTypes.APIApplicationCommandInteractionDataStringOption[] | undefined} */ // @ts-ignore const options = data.options - const input = options?.[0].value || "" + const input = options?.[0]?.value || "" const levels = ["invite", "link", "directory"] const level = levels.findIndex(x => input === x) if (level === -1) { - return discord.snow.interaction.createInteractionResponse(id, token, { + return yield {createInteractionResponse: { type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, data: { content: "**Usage: `/privacy `**. This will set who can join the space on Matrix-side. There are three levels:" @@ -38,22 +44,37 @@ async function interact({id, token, data, guild_id}) { + `\n**Current privacy level: \`${levels[current]}\`**`, flags: DiscordTypes.MessageFlags.Ephemeral } - }) + }} } - await discord.snow.interaction.createInteractionResponse(id, token, { + yield {createInteractionResponse: { type: DiscordTypes.InteractionResponseType.DeferredChannelMessageWithSource, data: { flags: DiscordTypes.MessageFlags.Ephemeral } - }) + }} db.prepare("UPDATE guild_space SET privacy_level = ? WHERE guild_id = ?").run(level, guild_id) await createSpace.syncSpaceFully(guild_id) // this is inefficient but OK to call infrequently on user request - await discord.snow.interaction.editOriginalInteractionResponse(botID, token, { + yield {editOriginalInteractionResponse: { content: `Privacy level updated to \`${levels[level]}\`.` - }) + }} +} + +/* c8 ignore start */ + +/** @param {DiscordTypes.APIChatInputApplicationCommandGuildInteraction} interaction */ +async function interact(interaction) { + for await (const response of _interact(interaction, {createSpace})) { + if (response.createInteractionResponse) { + // TODO: Test if it is reasonable to remove `await` from these calls. Or zip these calls with the next interaction iteration and use Promise.all. + await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, response.createInteractionResponse) + } else if (response.editOriginalInteractionResponse) { + await discord.snow.interaction.editOriginalInteractionResponse(botID, interaction.token, response.editOriginalInteractionResponse) + } + } } module.exports.interact = interact +module.exports._interact = _interact diff --git a/src/discord/interactions/privacy.test.js b/src/discord/interactions/privacy.test.js new file mode 100644 index 0000000..a94bbc7 --- /dev/null +++ b/src/discord/interactions/privacy.test.js @@ -0,0 +1,86 @@ +const {test} = require("supertape") +const DiscordTypes = require("discord-api-types/v10") +const {select, db} = require("../../passthrough") +const {_interact} = require("./privacy") + +/** + * @template T + * @param {AsyncIterable} ai + * @returns {Promise} + */ +async function fromAsync(ai) { + const result = [] + for await (const value of ai) { + result.push(value) + } + return result +} + +test("privacy: checks if guild is bridged", async t => { + const msgs = await fromAsync(_interact({ + data: { + options: [] + }, + guild_id: "0" + }, {})) + t.equal(msgs.length, 1) + t.equal(msgs[0].createInteractionResponse.data.content, "This server isn't bridged to Matrix, so you can't set the Matrix privacy level.") +}) + +test("privacy: reports usage if there is no parameter", async t => { + const msgs = await fromAsync(_interact({ + data: { + options: [] + }, + guild_id: "112760669178241024" + }, {})) + t.equal(msgs.length, 1) + t.match(msgs[0].createInteractionResponse.data.content, /Usage: `\/privacy/) +}) + +test("privacy: reports usage for invalid parameter", async t => { + const msgs = await fromAsync(_interact({ + data: { + options: [ + { + name: "level", + type: DiscordTypes.ApplicationCommandOptionType.String, + value: "info" + } + ] + }, + guild_id: "112760669178241024" + }, {})) + t.equal(msgs.length, 1) + t.match(msgs[0].createInteractionResponse.data.content, /Usage: `\/privacy/) +}) + +test("privacy: updates setting and calls syncSpace for valid parameter", async t => { + let called = 0 + const msgs = await fromAsync(_interact({ + data: { + options: [ + { + name: "level", + type: DiscordTypes.ApplicationCommandOptionType.String, + value: "directory" + } + ] + }, + guild_id: "112760669178241024" + }, { + createSpace: { + async syncSpaceFully(guildID) { + called++ + t.equal(guildID, "112760669178241024") + } + } + })) + t.equal(msgs.length, 2) + t.equal(msgs[0].createInteractionResponse.type, DiscordTypes.InteractionResponseType.DeferredChannelMessageWithSource) + t.equal(msgs[1].editOriginalInteractionResponse.content, "Privacy level updated to `directory`.") + t.equal(called, 1) + t.equal(select("guild_space", "privacy_level", {guild_id: "112760669178241024"}).pluck().get(), 2) + // Undo database changes + db.prepare("UPDATE guild_space SET privacy_level = 0 WHERE guild_id = ?").run("112760669178241024") +}) diff --git a/test/test.js b/test/test.js index 6695494..c6ab1bb 100644 --- a/test/test.js +++ b/test/test.js @@ -140,5 +140,6 @@ file._actuallyUploadDiscordFileToMxc = function(url, res) { throw new Error(`Not require("../src/m2d/converters/emoji-sheet.test") require("../src/discord/interactions/invite.test") require("../src/discord/interactions/matrix-info.test") + require("../src/discord/interactions/privacy.test") require("../src/discord/interactions/reactions.test") })() From b79b010568859aa0c28539275a9c83ef931c3db1 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 30 Sep 2024 16:46:20 +1300 Subject: [PATCH 020/228] Update heatsync dependency --- package-lock.json | 8 ++++---- package.json | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package-lock.json b/package-lock.json index 45de4cc..7fe7cb0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -29,7 +29,7 @@ "entities": "^5.0.0", "get-stream": "^6.0.1", "h3": "^1.12.0", - "heatsync": "^2.5.3", + "heatsync": "^2.5.5", "lru-cache": "^10.4.3", "minimist": "^1.2.8", "node-fetch": "^2.6.7", @@ -1929,9 +1929,9 @@ } }, "node_modules/heatsync": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/heatsync/-/heatsync-2.5.4.tgz", - "integrity": "sha512-KzsM+wR0MIykD80kCHNZCpNvFY4uC1Yze8R37eehJyGIvEepJd+7ubczh6FVoBFtK0nVEszt5Hl8AbzUvb+vMQ==", + "version": "2.5.5", + "resolved": "https://registry.npmjs.org/heatsync/-/heatsync-2.5.5.tgz", + "integrity": "sha512-Sy2/X2a69W2W1xgp7GBY81naHtWXxwV8N6uzPTJLQXgq4oTMJeL6F/AUlGS+fUa/Pt5ioxzi7gvd8THMJ3GpyA==", "dependencies": { "backtracker": "^4.0.0" } diff --git a/package.json b/package.json index 857e2d2..68a4583 100644 --- a/package.json +++ b/package.json @@ -38,7 +38,7 @@ "entities": "^5.0.0", "get-stream": "^6.0.1", "h3": "^1.12.0", - "heatsync": "^2.5.3", + "heatsync": "^2.5.5", "lru-cache": "^10.4.3", "minimist": "^1.2.8", "node-fetch": "^2.6.7", From d72b162fe7e53cb7f95d34d3a1054fbeeb960408 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 30 Sep 2024 17:24:26 +1300 Subject: [PATCH 021/228] Mobile design --- src/web/pug/home.pug | 2 +- src/web/pug/includes/template.pug | 2 +- src/web/pug/invite.pug | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/web/pug/home.pug b/src/web/pug/home.pug index 1ad787d..6cd7d29 100644 --- a/src/web/pug/home.pug +++ b/src/web/pug/home.pug @@ -4,7 +4,7 @@ block body .s-page-title.mb24 h1.s-page-title--header Bridge a Discord server - .d-grid.grid__2.g24 + .d-grid.g24.grid__2(class="sm:grid__1") .s-card.bs-md.d-flex.fd-column h2 Easy mode p Add the bot to your Discord server. diff --git a/src/web/pug/includes/template.pug b/src/web/pug/includes/template.pug index 94b5e92..8bb4415 100644 --- a/src/web/pug/includes/template.pug +++ b/src/web/pug/includes/template.pug @@ -53,7 +53,7 @@ html(lang="en") li(role="menuitem") a.s-topbar--item.s-user-card.d-flex.p4(href=`/guild?guild_id=${guild.id}`) +guild(guild) - .mx-auto.w100.wmx9.py24.px8#content + .mx-auto.w100.wmx9.py24.px8.fs-body1#content block body script. document.querySelectorAll("[popovertarget]").forEach(e => { diff --git a/src/web/pug/invite.pug b/src/web/pug/invite.pug index e346880..52b3ab2 100644 --- a/src/web/pug/invite.pug +++ b/src/web/pug/invite.pug @@ -3,7 +3,7 @@ extends includes/template.pug block body if !isValid .s-empty-state.wmx4.p48 - != icons.Spots.SpotAlertXL + != icons.Spots.SpotExpireXL p This QR code has expired. p Refresh the guild management page to generate a new one. From 3662ee5db61f71e892f7938034abbd9027df186a Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 30 Sep 2024 22:50:19 +1300 Subject: [PATCH 022/228] Fix interaction updates --- src/d2m/converters/message-to-event.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/d2m/converters/message-to-event.js b/src/d2m/converters/message-to-event.js index 582b26c..3466b4c 100644 --- a/src/d2m/converters/message-to-event.js +++ b/src/d2m/converters/message-to-event.js @@ -236,8 +236,11 @@ async function messageToEvent(message, guild, options = {}, di) { const interaction = message.interaction_metadata || message.interaction if (message.type === DiscordTypes.MessageType.ChatInputCommand && interaction && "name" in interaction) { // Commands are sent by the responding bot. Need to attach the metadata of the person using the command at the top. - if (message.content) message.content = `\n${message.content}` - message.content = `> ↪️ <@${interaction.user.id}> used \`/${interaction.name}\`${message.content}` + let content = message.content + if (content) content = `\n${content}` + else if ((message.flags || 0) & DiscordTypes.MessageFlags.Loading) content = " — interaction loading..." + content = `> ↪️ <@${interaction.user.id}> used \`/${interaction.name}\`${content}` + message = {...message, content} // editToChanges reuses the object so we can't mutate it. have to clone it } /** From 9f9d1f615edf7cd636fa48b15c57f41733a67268 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 30 Sep 2024 23:35:09 +1300 Subject: [PATCH 023/228] Test coverage for all interactions --- src/discord/interactions/invite.js | 2 +- src/discord/interactions/matrix-info.js | 2 +- src/discord/interactions/permissions.js | 72 +++++-- src/discord/interactions/permissions.test.js | 199 +++++++++++++++++++ src/discord/interactions/privacy.js | 1 - src/discord/interactions/reactions.js | 2 +- src/discord/interactions/reactions.test.js | 4 - test/test.js | 1 + 8 files changed, 255 insertions(+), 28 deletions(-) create mode 100644 src/discord/interactions/permissions.test.js diff --git a/src/discord/interactions/invite.js b/src/discord/interactions/invite.js index bacf465..b35f44f 100644 --- a/src/discord/interactions/invite.js +++ b/src/discord/interactions/invite.js @@ -3,7 +3,7 @@ const DiscordTypes = require("discord-api-types/v10") const Ty = require("../../types") const assert = require("assert/strict") -const {discord, sync, db, select, from} = require("../../passthrough") +const {discord, sync, db, select} = require("../../passthrough") /** @type {import("../../d2m/actions/create-room")} */ const createRoom = sync.require("../../d2m/actions/create-room") diff --git a/src/discord/interactions/matrix-info.js b/src/discord/interactions/matrix-info.js index f7bc31a..b7551f1 100644 --- a/src/discord/interactions/matrix-info.js +++ b/src/discord/interactions/matrix-info.js @@ -1,7 +1,7 @@ // @ts-check const DiscordTypes = require("discord-api-types/v10") -const {discord, sync, db, select, from} = require("../../passthrough") +const {discord, sync, from} = require("../../passthrough") /** @type {import("../../matrix/api")} */ const api = sync.require("../../matrix/api") diff --git a/src/discord/interactions/permissions.js b/src/discord/interactions/permissions.js index e010b1b..fea9ce0 100644 --- a/src/discord/interactions/permissions.js +++ b/src/discord/interactions/permissions.js @@ -2,34 +2,41 @@ const DiscordTypes = require("discord-api-types/v10") const Ty = require("../../types") -const {discord, sync, db, select, from} = require("../../passthrough") +const {discord, sync, select, from} = require("../../passthrough") const assert = require("assert/strict") +const {id: botID} = require("../../../addbot") +const {InteractionMethods} = require("snowtransfer") /** @type {import("../../matrix/api")} */ const api = sync.require("../../matrix/api") /** * @param {DiscordTypes.APIContextMenuGuildInteraction} interaction - * @returns {Promise} + * @param {{api: typeof api}} di + * @returns {AsyncGenerator<{[k in keyof InteractionMethods]?: Parameters[2]}>} */ -async function _interact({data, channel, guild_id}) { - const row = select("event_message", ["event_id", "source"], {message_id: data.target_id}).get() - assert(row) +async function* _interact({data, guild_id}, {api}) { + // Get message info + const row = from("event_message") + .join("message_channel", "message_id") + .select("event_id", "source", "channel_id") + .where({message_id: data.target_id}) + .get() // Can't operate on Discord users - if (row.source === 1) { // discord - return { + if (!row || row.source === 1) { // not bridged or sent by a discord user + return yield {createInteractionResponse: { type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, data: { - content: `This command is only meaningful for Matrix users.`, + content: `The permissions command can only be used on Matrix users.`, flags: DiscordTypes.MessageFlags.Ephemeral } - } + }} } // Get the message sender, the person that will be inspected/edited const eventID = row.event_id - const roomID = select("channel_room", "room_id", {channel_id: channel.id}).pluck().get() + const roomID = select("channel_room", "room_id", {channel_id: row.channel_id}).pluck().get() assert(roomID) const event = await api.getEvent(roomID, eventID) const sender = event.sender @@ -45,16 +52,16 @@ async function _interact({data, channel, guild_id}) { // Administrators equal to the bot cannot be demoted if (userPower >= 100) { - return { + return yield {createInteractionResponse: { type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, data: { content: `\`${sender}\` has administrator permissions. This cannot be edited.`, flags: DiscordTypes.MessageFlags.Ephemeral } - } + }} } - return { + yield {createInteractionResponse: { type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, data: { content: `Showing permissions for \`${sender}\`. Click to edit.`, @@ -82,13 +89,15 @@ async function _interact({data, channel, guild_id}) { } ] } - } + }} } /** * @param {DiscordTypes.APIMessageComponentSelectMenuInteraction} interaction + * @param {{api: typeof api}} di + * @returns {AsyncGenerator<{[k in keyof InteractionMethods]?: Parameters[2]}>} */ -async function interactEdit({data, id, token, guild_id, message}) { +async function* _interactEdit({data, guild_id, message}, {api}) { // Get the person that will be inspected/edited const mxid = message.content.match(/`(@(?:[^:]+):(?:[a-z0-9:-]+\.[a-z0-9.:-]+))`/)?.[1] assert(mxid) @@ -96,13 +105,13 @@ async function interactEdit({data, id, token, guild_id, message}) { const permission = data.values[0] const power = permission === "moderator" ? 50 : 0 - await discord.snow.interaction.createInteractionResponse(id, token, { + yield {createInteractionResponse: { type: DiscordTypes.InteractionResponseType.UpdateMessage, data: { content: `Updating \`${mxid}\` to **${permission}**, please wait...`, components: [] } - }) + }} // Get the space, where the power levels will be inspected/edited const spaceID = select("guild_space", "space_id", {guild_id}).pluck().get() @@ -112,17 +121,40 @@ async function interactEdit({data, id, token, guild_id, message}) { await api.setUserPowerCascade(spaceID, mxid, power) // ACK - await discord.snow.interaction.editOriginalInteractionResponse(discord.application.id, token, { + yield {editOriginalInteractionResponse: { content: `Updated \`${mxid}\` to **${permission}**.`, components: [] - }) + }} } + +/* c8 ignore start */ + /** @param {DiscordTypes.APIContextMenuGuildInteraction} interaction */ async function interact(interaction) { - await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, await _interact(interaction)) + for await (const response of _interact(interaction, {api})) { + if (response.createInteractionResponse) { + // TODO: Test if it is reasonable to remove `await` from these calls. Or zip these calls with the next interaction iteration and use Promise.all. + await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, response.createInteractionResponse) + } else if (response.editOriginalInteractionResponse) { + await discord.snow.interaction.editOriginalInteractionResponse(botID, interaction.token, response.editOriginalInteractionResponse) + } + } +} + +/** @param {DiscordTypes.APIMessageComponentSelectMenuInteraction} interaction */ +async function interactEdit(interaction) { + for await (const response of _interactEdit(interaction, {api})) { + if (response.createInteractionResponse) { + // TODO: Test if it is reasonable to remove `await` from these calls. Or zip these calls with the next interaction iteration and use Promise.all. + await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, response.createInteractionResponse) + } else if (response.editOriginalInteractionResponse) { + await discord.snow.interaction.editOriginalInteractionResponse(botID, interaction.token, response.editOriginalInteractionResponse) + } + } } module.exports.interact = interact module.exports.interactEdit = interactEdit module.exports._interact = _interact +module.exports._interactEdit = _interactEdit diff --git a/src/discord/interactions/permissions.test.js b/src/discord/interactions/permissions.test.js new file mode 100644 index 0000000..64cda80 --- /dev/null +++ b/src/discord/interactions/permissions.test.js @@ -0,0 +1,199 @@ +const {test} = require("supertape") +const DiscordTypes = require("discord-api-types/v10") +const {select, db} = require("../../passthrough") +const {_interact, _interactEdit} = require("./permissions") + +/** + * @template T + * @param {AsyncIterable} ai + * @returns {Promise} + */ +async function fromAsync(ai) { + const result = [] + for await (const value of ai) { + result.push(value) + } + return result +} + +test("permissions: checks if message is bridged", async t => { + const msgs = await fromAsync(_interact({ + data: { + target_id: "0" + }, + guild_id: "0" + }, {})) + t.equal(msgs.length, 1) + t.equal(msgs[0].createInteractionResponse.data.content, "The permissions command can only be used on Matrix users.") +}) + +test("permissions: checks if message is sent by a matrix user", async t => { + const msgs = await fromAsync(_interact({ + data: { + target_id: "1126786462646550579" + }, + guild_id: "112760669178241024" + }, {})) + t.equal(msgs.length, 1) + t.equal(msgs[0].createInteractionResponse.data.content, "The permissions command can only be used on Matrix users.") +}) + +test("permissions: reports permissions of selected matrix user (implicit default)", async t => { + let called = 0 + const msgs = await fromAsync(_interact({ + data: { + target_id: "1128118177155526666" + }, + guild_id: "112760669178241024" + }, { + api: { + async getEvent(roomID, eventID) { + called++ + t.equal(roomID, "!kLRqKKUQXcibIMtOpl:cadence.moe") // room ID + t.equal(eventID, "$Ij3qo7NxMA4VPexlAiIx2CB9JbsiGhJeyt-2OvkAUe4") + return { + sender: "@cadence:cadence.moe" + } + }, + async getStateEvent(roomID, type, key) { + called++ + t.equal(roomID, "!jjWAGMeQdNrVZSSfvz:cadence.moe") // space ID + t.equal(type, "m.room.power_levels") + t.equal(key, "") + return { + users: {} + } + } + } + })) + t.equal(msgs.length, 1) + t.equal(msgs[0].createInteractionResponse.data.content, "Showing permissions for `@cadence:cadence.moe`. Click to edit.") + t.deepEqual(msgs[0].createInteractionResponse.data.components[0].components[0].options[0], {label: "Default", value: "default", default: true}) + t.equal(called, 2) +}) + +test("permissions: reports permissions of selected matrix user (moderator)", async t => { + let called = 0 + const msgs = await fromAsync(_interact({ + data: { + target_id: "1128118177155526666" + }, + guild_id: "112760669178241024" + }, { + api: { + async getEvent(roomID, eventID) { + called++ + t.equal(roomID, "!kLRqKKUQXcibIMtOpl:cadence.moe") // room ID + t.equal(eventID, "$Ij3qo7NxMA4VPexlAiIx2CB9JbsiGhJeyt-2OvkAUe4") + return { + sender: "@cadence:cadence.moe" + } + }, + async getStateEvent(roomID, type, key) { + called++ + t.equal(roomID, "!jjWAGMeQdNrVZSSfvz:cadence.moe") // space ID + t.equal(type, "m.room.power_levels") + t.equal(key, "") + return { + users: { + "@cadence:cadence.moe": 50 + } + } + } + } + })) + t.equal(msgs.length, 1) + t.equal(msgs[0].createInteractionResponse.data.content, "Showing permissions for `@cadence:cadence.moe`. Click to edit.") + t.deepEqual(msgs[0].createInteractionResponse.data.components[0].components[0].options[1], {label: "Moderator", value: "moderator", default: true}) + t.equal(called, 2) +}) + +test("permissions: reports permissions of selected matrix user (admin)", async t => { + let called = 0 + const msgs = await fromAsync(_interact({ + data: { + target_id: "1128118177155526666" + }, + guild_id: "112760669178241024" + }, { + api: { + async getEvent(roomID, eventID) { + called++ + t.equal(roomID, "!kLRqKKUQXcibIMtOpl:cadence.moe") // room ID + t.equal(eventID, "$Ij3qo7NxMA4VPexlAiIx2CB9JbsiGhJeyt-2OvkAUe4") + return { + sender: "@cadence:cadence.moe" + } + }, + async getStateEvent(roomID, type, key) { + called++ + t.equal(roomID, "!jjWAGMeQdNrVZSSfvz:cadence.moe") // space ID + t.equal(type, "m.room.power_levels") + t.equal(key, "") + return { + users: { + "@cadence:cadence.moe": 100 + } + } + } + } + })) + t.equal(msgs.length, 1) + t.equal(msgs[0].createInteractionResponse.data.content, "`@cadence:cadence.moe` has administrator permissions. This cannot be edited.") + t.notOk(msgs[0].createInteractionResponse.data.components) + t.equal(called, 2) +}) + +test("permissions: can update user to moderator", async t => { + let called = 0 + const msgs = await fromAsync(_interactEdit({ + data: { + target_id: "1128118177155526666", + values: ["moderator"] + }, + message: { + content: "Showing permissions for `@cadence:cadence.moe`. Click to edit." + }, + guild_id: "112760669178241024" + }, { + api: { + async setUserPowerCascade(roomID, mxid, power) { + called++ + t.equal(roomID, "!jjWAGMeQdNrVZSSfvz:cadence.moe") // space ID + t.equal(mxid, "@cadence:cadence.moe") + t.equal(power, 50) + } + } + })) + t.equal(msgs.length, 2) + t.equal(msgs[0].createInteractionResponse.data.content, "Updating `@cadence:cadence.moe` to **moderator**, please wait...") + t.equal(msgs[1].editOriginalInteractionResponse.content, "Updated `@cadence:cadence.moe` to **moderator**.") + t.equal(called, 1) +}) + +test("permissions: can update user to default", async t => { + let called = 0 + const msgs = await fromAsync(_interactEdit({ + data: { + target_id: "1128118177155526666", + values: ["default"] + }, + message: { + content: "Showing permissions for `@cadence:cadence.moe`. Click to edit." + }, + guild_id: "112760669178241024" + }, { + api: { + async setUserPowerCascade(roomID, mxid, power) { + called++ + t.equal(roomID, "!jjWAGMeQdNrVZSSfvz:cadence.moe") // space ID + t.equal(mxid, "@cadence:cadence.moe") + t.equal(power, 0) + } + } + })) + t.equal(msgs.length, 2) + t.equal(msgs[0].createInteractionResponse.data.content, "Updating `@cadence:cadence.moe` to **default**, please wait...") + t.equal(msgs[1].editOriginalInteractionResponse.content, "Updated `@cadence:cadence.moe` to **default**.") + t.equal(called, 1) +}) diff --git a/src/discord/interactions/privacy.js b/src/discord/interactions/privacy.js index 8227b5a..841167e 100644 --- a/src/discord/interactions/privacy.js +++ b/src/discord/interactions/privacy.js @@ -16,7 +16,6 @@ const createSpace = sync.require("../../d2m/actions/create-space") async function* _interact({data, guild_id}, {createSpace}) { // Check guild is bridged const current = select("guild_space", "privacy_level", {guild_id}).pluck().get() - InteractionMethods.prototype.createInteractionResponse if (current == null) { return yield {createInteractionResponse: { type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, diff --git a/src/discord/interactions/reactions.js b/src/discord/interactions/reactions.js index 0a6d5a6..1a5a9ca 100644 --- a/src/discord/interactions/reactions.js +++ b/src/discord/interactions/reactions.js @@ -1,7 +1,7 @@ // @ts-check const DiscordTypes = require("discord-api-types/v10") -const {discord, sync, db, select, from} = require("../../passthrough") +const {discord, sync, select, from} = require("../../passthrough") /** @type {import("../../matrix/api")} */ const api = sync.require("../../matrix/api") diff --git a/src/discord/interactions/reactions.test.js b/src/discord/interactions/reactions.test.js index c6de054..6e29f57 100644 --- a/src/discord/interactions/reactions.test.js +++ b/src/discord/interactions/reactions.test.js @@ -1,8 +1,4 @@ const {test} = require("supertape") -const data = require("../../../test/data") -const DiscordTypes = require("discord-api-types/v10") -const {db, discord} = require("../../passthrough") -const {MatrixServerError} = require("../../matrix/mreq") const {_interact} = require("./reactions") test("reactions: checks if message is bridged", async t => { diff --git a/test/test.js b/test/test.js index c6ab1bb..ee63834 100644 --- a/test/test.js +++ b/test/test.js @@ -140,6 +140,7 @@ file._actuallyUploadDiscordFileToMxc = function(url, res) { throw new Error(`Not require("../src/m2d/converters/emoji-sheet.test") require("../src/discord/interactions/invite.test") require("../src/discord/interactions/matrix-info.test") + require("../src/discord/interactions/permissions.test") require("../src/discord/interactions/privacy.test") require("../src/discord/interactions/reactions.test") })() From 086e8cdc25eca11515de725b666a14bdcde470bb Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Thu, 3 Oct 2024 03:26:49 +1300 Subject: [PATCH 024/228] Add privacy level controls on web --- src/web/pug/guild.pug | 59 +++++++++++++++++++++++++++++-- src/web/pug/includes/template.pug | 4 +++ src/web/routes/guild-settings.js | 26 ++++++++++++-- 3 files changed, 85 insertions(+), 4 deletions(-) diff --git a/src/web/pug/guild.pug b/src/web/pug/guild.pug index 1e27f2e..250b23b 100644 --- a/src/web/pug/guild.pug +++ b/src/web/pug/guild.pug @@ -95,8 +95,11 @@ block body src.searchParams.set("data", `https://bridge.cadence.moe/invite?nonce=${nonce}`) img(width=size height=size src=src.toString()) - h2.mt48.fs-headline1 Linked channels + h2.mt48.fs-headline1 Moderation + h2.mt48.fs-headline1 Matrix setup + + h3.mt32.fs-category Linked channels - function getPosition(channel) { let position = 0 @@ -139,9 +142,61 @@ block body p.s-description If you want, OOYE can automatically create new Matrix rooms and link them when an unlinked Discord channel is spoken in. - let value = !!select("guild_active", "autocreate", {guild_id}).pluck().get() input(type="hidden" name="guild_id" value=guild_id) - input.s-toggle-switch.order-last#autocreate(name="autocreate" type="checkbox" hx-post="/api/autocreate" hx-indicator="#autocreate-loading" hx-disabled-elt="this" hx-swap="none" checked=value) + input.s-toggle-switch.order-last#autocreate(name="autocreate" type="checkbox" hx-post="/api/autocreate" hx-indicator="#autocreate-loading" hx-disabled-elt="this" checked=value) .is-loading#autocreate-loading + h3.mt32.fs-category Privacy level + .s-card + - let p = select("guild_space", "privacy_level", {guild_id}).pluck().get() + form(hx-post="/api/privacy-level" hx-trigger="change" hx-indicator="#privacy-level-loading" hx-disabled-elt="this") + input(type="hidden" name="guild_id" value=guild_id) + .d-flex.ai-center.mb4 + label.s-label.fl-grow1 + | How people can join on Matrix + span.is-loading#privacy-level-loading + .s-toggle-switch.s-toggle-switch__multiple.s-toggle-switch__incremental.d-grid.gx16.ai-center(style="grid-template-columns: auto 1fr") + input(type="radio" name="level" value="directory" id="privacy-level-directory" checked=(p === 2)) + label.d-flex.gx8.jc-center.grid--row-start3(for="privacy-level-directory") + != icons.Icons.IconPlusSm + != icons.Icons.IconInternationalSm + .fl-grow1 Directory + + input(type="radio" name="level" value="link" id="privacy-level-link" checked=(p === 1)) + label.d-flex.gx8.jc-center.grid--row-start2(for="privacy-level-link") + != icons.Icons.IconPlusSm + != icons.Icons.IconLinkSm + .fl-grow1 Link + + input(type="radio" name="level" value="invite" id="privacy-level-invite" checked=(p === 0)) + label.d-flex.gx8.jc-center.grid--row-start1(for="privacy-level-invite") + svg.svg-icon(width="14" height="14" viewBox="0 0 14 14") + != icons.Icons.IconLockSm + .fl-grow1 Invite + + p.s-description.m0 In-app direct invite from another user; /invite on Discord; web form + p.s-description.m0 Shareable invite links, like Discord + p.s-description.m0 Publicly listed in directory, like Discord server discovery + + + //- + fieldset.s-check-group + legend.s-label How people can join on Matrix + .s-check-control + input.s-radio(type="radio" name="privacy-level" id="privacy-level-invite" value="invite" checked) + label.s-label(for="privacy-level-invite") + | Invite + p.s-description In-app direct invite on Matrix; invite command on Discord; invite form on web + .s-check-control + input.s-radio(type="radio" name="privacy-level" id="privacy-level-link" value="link") + label.s-label(for="privacy-level-link") + | Link + p.s-description All of the above, and shareable invite links (like Discord) + .s-check-control + input.s-radio(type="radio" name="privacy-level" id="privacy-level-directory" value="directory") + label.s-label(for="privacy-level-directory") + | Public + p.s-description All of the above, and publicly visible in the Matrix space directory (like Server Discovery) + h3.mt32.fs-category Manually link channels form.d-flex.g16.ai-start(method="post" action="/api/link") .fl-grow2.s-btn-group.fd-column.w40 diff --git a/src/web/pug/includes/template.pug b/src/web/pug/includes/template.pug index 8bb4415..8345d76 100644 --- a/src/web/pug/includes/template.pug +++ b/src/web/pug/includes/template.pug @@ -26,6 +26,10 @@ html(lang="en") --theme-dark-primary-color-s: 53%; --theme-dark-primary-color-l: 63%; } + .s-toggle-switch.s-toggle-switch__multiple.s-toggle-switch__incremental input[type="radio"]:checked ~ label:not(.s-toggle-switch--label-off) { + --_ts-multiple-bg: var(--green-400); + --_ts-multiple-fc: var(--white); + } body.themed.theme-system header.s-topbar .s-topbar--skip-link(href="#content") Skip to main content diff --git a/src/web/routes/guild-settings.js b/src/web/routes/guild-settings.js index 7940853..1c33854 100644 --- a/src/web/routes/guild-settings.js +++ b/src/web/routes/guild-settings.js @@ -1,15 +1,25 @@ // @ts-check +const assert = require("assert/strict") const {z} = require("zod") const {defineEventHandler, sendRedirect, useSession, createError, readValidatedBody} = require("h3") -const {as, db} = require("../../passthrough") +const {as, db, sync} = require("../../passthrough") const {reg} = require("../../matrix/read-registration") +/** @type {import("../../d2m/actions/create-space")} */ +const createSpace = sync.require("../../d2m/actions/create-space") + +/** @type {["invite", "link", "directory"]} */ +const levels = ["invite", "link", "directory"] const schema = { autocreate: z.object({ guild_id: z.string(), autocreate: z.string().optional() + }), + privacyLevel: z.object({ + guild_id: z.string(), + level: z.enum(levels) }) } @@ -19,5 +29,17 @@ as.router.post("/api/autocreate", defineEventHandler(async event => { if (!(session.data.managedGuilds || []).includes(parsedBody.guild_id)) throw createError({status: 403, message: "Forbidden", data: "Can't change settings for a guild you don't have Manage Server permissions in"}) db.prepare("UPDATE guild_active SET autocreate = ? WHERE guild_id = ?").run(+!!parsedBody.autocreate, parsedBody.guild_id) - return sendRedirect(event, `/guild?guild_id=${parsedBody.guild_id}`, 302) + return null // 204 +})) + +as.router.post("/api/privacy-level", defineEventHandler(async event => { + const parsedBody = await readValidatedBody(event, schema.privacyLevel.parse) + const session = await useSession(event, {password: reg.as_token}) + if (!(session.data.managedGuilds || []).includes(parsedBody.guild_id)) throw createError({status: 403, message: "Forbidden", data: "Can't change settings for a guild you don't have Manage Server permissions in"}) + + const i = levels.indexOf(parsedBody.level) + assert.notEqual(i, -1) + db.prepare("UPDATE guild_space SET privacy_level = ? WHERE guild_id = ?").run(i, parsedBody.guild_id) + await createSpace.syncSpaceFully(parsedBody.guild_id) // this is inefficient but OK to call infrequently on user request + return null // 204 })) From 4287a329f511fba40727606ea60d266303e0fc83 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Thu, 3 Oct 2024 17:21:42 +1300 Subject: [PATCH 025/228] Display list of unlinked rooms --- src/matrix/api.js | 12 ++++++++++++ src/web/pug/guild.pug | 17 ++++++++++++----- src/web/routes/invite.js | 18 +++++++++++------- 3 files changed, 35 insertions(+), 12 deletions(-) diff --git a/src/matrix/api.js b/src/matrix/api.js index 4866495..f640efe 100644 --- a/src/matrix/api.js +++ b/src/matrix/api.js @@ -123,6 +123,17 @@ function getJoinedMembers(roomID) { return mreq.mreq("GET", `/client/v3/rooms/${roomID}/joined_members`) } +/** + * "Get the list of members for this room." This includes joined, invited, knocked, left, and banned members unless a filter is provided. + * The endpoint also supports `at` and `not_membership` URL parameters, but they are not exposed in this wrapper yet. + * @param {string} roomID + * @param {"join" | "invite" | "knock" | "leave" | "ban"} [membership] The kind of membership to filter for. Only one choice allowed. + * @returns {Promise<{chunk: Ty.Event.Outer[]}>} + */ +function getMembers(roomID, membership) { + return mreq.mreq("GET", `/client/v3/rooms/${roomID}/members`, {membership}) +} + /** * @param {string} roomID * @param {{from?: string, limit?: any}} pagination @@ -339,6 +350,7 @@ module.exports.getEventForTimestamp = getEventForTimestamp module.exports.getAllState = getAllState module.exports.getStateEvent = getStateEvent module.exports.getJoinedMembers = getJoinedMembers +module.exports.getMembers = getMembers module.exports.getHierarchy = getHierarchy module.exports.getFullHierarchy = getFullHierarchy module.exports.getRelations = getRelations diff --git a/src/web/pug/guild.pug b/src/web/pug/guild.pug index 250b23b..68b1e56 100644 --- a/src/web/pug/guild.pug +++ b/src/web/pug/guild.pug @@ -121,6 +121,9 @@ block body let unlinkedChannelIDs = channelIDs.filter(c => !linkedChannelIDs.includes(c)) let unlinkedChannels = unlinkedChannelIDs.map(c => discord.channels.get(c)).filter(c => [0, 5].includes(c.type)) unlinkedChannels.sort((a, b) => getPosition(a) - getPosition(b)) + + let linkedRoomIDs = linkedChannels.map(c => c.room_id) + let unlinkedRooms = rooms.filter(r => !linkedRoomIDs.includes(r.room_id)) .s-card.bs-sm.p0 .s-table-container table.s-table.s-table__bx-simple @@ -147,7 +150,6 @@ block body h3.mt32.fs-category Privacy level .s-card - - let p = select("guild_space", "privacy_level", {guild_id}).pluck().get() form(hx-post="/api/privacy-level" hx-trigger="change" hx-indicator="#privacy-level-loading" hx-disabled-elt="this") input(type="hidden" name="guild_id" value=guild_id) .d-flex.ai-center.mb4 @@ -155,19 +157,19 @@ block body | How people can join on Matrix span.is-loading#privacy-level-loading .s-toggle-switch.s-toggle-switch__multiple.s-toggle-switch__incremental.d-grid.gx16.ai-center(style="grid-template-columns: auto 1fr") - input(type="radio" name="level" value="directory" id="privacy-level-directory" checked=(p === 2)) + input(type="radio" name="level" value="directory" id="privacy-level-directory" checked=(privacy_level === 2)) label.d-flex.gx8.jc-center.grid--row-start3(for="privacy-level-directory") != icons.Icons.IconPlusSm != icons.Icons.IconInternationalSm .fl-grow1 Directory - input(type="radio" name="level" value="link" id="privacy-level-link" checked=(p === 1)) + input(type="radio" name="level" value="link" id="privacy-level-link" checked=(privacy_level === 1)) label.d-flex.gx8.jc-center.grid--row-start2(for="privacy-level-link") != icons.Icons.IconPlusSm != icons.Icons.IconLinkSm .fl-grow1 Link - input(type="radio" name="level" value="invite" id="privacy-level-invite" checked=(p === 0)) + input(type="radio" name="level" value="invite" id="privacy-level-invite" checked=(privacy_level === 0)) label.d-flex.gx8.jc-center.grid--row-start1(for="privacy-level-invite") svg.svg-icon(width="14" height="14" viewBox="0 0 14 14") != icons.Icons.IconLockSm @@ -207,7 +209,12 @@ block body else .s-empty-state.p8 All Discord channels are linked. .fl-grow1.s-btn-group.fd-column.w30 - .s-empty-state.p8 I don't know how to get the Matrix room list yet... + each room in unlinkedRooms + input.s-btn--radio(type="radio" name="matrix" id=room.room_id value=room.room_id) + label.s-btn.s-btn__muted.ta-left.truncate(for=room.room_id) + +matrix(room, true) + else + .s-empty-state.p8 All Matrix rooms are linked. div button.s-btn.s-btn__icon.s-btn__filled != icons.Icons.IconLink diff --git a/src/web/routes/invite.js b/src/web/routes/invite.js index 94fa367..0837de0 100644 --- a/src/web/routes/invite.js +++ b/src/web/routes/invite.js @@ -36,14 +36,18 @@ const validNonce = new LRUCache({max: 200}) as.router.get("/guild", defineEventHandler(async event => { const {guild_id} = await getValidatedQuery(event, schema.guild.parse) - const nonce = randomUUID() - if (guild_id) { - // Security note: the nonce alone is valid for updating the guild - // We have not verified the user has sufficient permissions in the guild at generation time - // These permissions are checked later during page rendering and the generated nonce is only revealed if the permissions are sufficient - validNonce.set(nonce, guild_id) + const session = await useSession(event, {password: reg.as_token}) + const row = select("guild_space", ["space_id", "privacy_level"], {guild_id}).get() + if (!guild_id || !row || !discord.guilds.has(guild_id) || !session.data.managedGuilds || !session.data.managedGuilds.includes(guild_id)) { + return pugSync.render(event, "guild.pug", {guild_id}) } - return pugSync.render(event, "guild.pug", {nonce}) + + const nonce = randomUUID() + validNonce.set(nonce, guild_id) + const mods = await api.getStateEvent(row.space_id, "m.room.power_levels", "") + const banned = await api.getMembers(row.space_id, "ban") + const rooms = await api.getFullHierarchy(row.space_id) + return pugSync.render(event, "guild.pug", {guild_id, nonce, mods, banned, rooms, ...row}) })) as.router.get("/invite", defineEventHandler(async event => { From 5a86c07eb9f2a2a64dfb2870711e88cb0d2b0fa3 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Fri, 4 Oct 2024 02:21:57 +1300 Subject: [PATCH 026/228] Host QR codes locally --- package-lock.json | 7 +++++++ package.json | 1 + readme.md | 1 + src/matrix/api.js | 2 +- src/web/pug/guild.pug | 15 ++++++++++----- src/web/routes/qr.js | 19 +++++++++++++++++++ src/web/server.js | 1 + 7 files changed, 40 insertions(+), 6 deletions(-) create mode 100644 src/web/routes/qr.js diff --git a/package-lock.json b/package-lock.json index 7fe7cb0..1189af7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -38,6 +38,7 @@ "snowtransfer": "^0.10.5", "stream-mime-type": "^1.0.2", "try-to-catch": "^3.0.1", + "uqr": "^0.1.2", "xxhash-wasm": "^1.0.2", "zod": "^3.23.8" }, @@ -3237,6 +3238,12 @@ "pathe": "^1.1.2" } }, + "node_modules/uqr": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/uqr/-/uqr-0.1.2.tgz", + "integrity": "sha512-MJu7ypHq6QasgF5YRTjqscSzQp/W11zoUk6kvmlH+fmWEs63Y0Eib13hYFwAzagRJcVY8WVnlV+eBDUGMJ5IbA==", + "license": "MIT" + }, "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", diff --git a/package.json b/package.json index 68a4583..fb7fbc9 100644 --- a/package.json +++ b/package.json @@ -47,6 +47,7 @@ "snowtransfer": "^0.10.5", "stream-mime-type": "^1.0.2", "try-to-catch": "^3.0.1", + "uqr": "^0.1.2", "xxhash-wasm": "^1.0.2", "zod": "^3.23.8" }, diff --git a/readme.md b/readme.md index daebb1e..f88b6ea 100644 --- a/readme.md +++ b/readme.md @@ -195,5 +195,6 @@ Total transitive production dependencies: 147 * (0) prettier-bytes: It does what I want and has no dependencies. * (2) snowtransfer: Discord API library with bring-your-own-caching that I trust. * (0) try-to-catch: Not strictly necessary, but it's already pulled in by supertape, so I may as well. +* (0) uqr: QR code SVG generator. Used on the website to scan in an invite link. * (0) xxhash-wasm: Used where cryptographically secure hashing is not required. * (0) zod: Input validation for the web server. It's popular and easy to use. diff --git a/src/matrix/api.js b/src/matrix/api.js index f640efe..7f6be01 100644 --- a/src/matrix/api.js +++ b/src/matrix/api.js @@ -131,7 +131,7 @@ function getJoinedMembers(roomID) { * @returns {Promise<{chunk: Ty.Event.Outer[]}>} */ function getMembers(roomID, membership) { - return mreq.mreq("GET", `/client/v3/rooms/${roomID}/members`, {membership}) + return mreq.mreq("GET", `/client/v3/rooms/${roomID}/members`, undefined, {membership}) } /** diff --git a/src/web/pug/guild.pug b/src/web/pug/guild.pug index 68b1e56..acc1acb 100644 --- a/src/web/pug/guild.pug +++ b/src/web/pug/guild.pug @@ -45,6 +45,8 @@ mixin matrix(row, radio=false, badge="") else .s-user-card--link.fs-body1 a(href=`https://matrix.to/#/${row.room_id}`)= row.nick || row.name + if row.join_rule === "invite" + +badge-private block body if !guild_id && session.data.managedGuilds @@ -91,9 +93,9 @@ block body div - let size = 105 - let src = new URL(`https://api.qrserver.com/v1/create-qr-code/?qzone=1&format=svg&size=${size}x${size}`) - src.searchParams.set("data", `https://bridge.cadence.moe/invite?nonce=${nonce}`) - img(width=size height=size src=src.toString()) + let p = new URLSearchParams() + p.set("data", `https://bridge.cadence.moe/invite?nonce=${nonce}`) + img(width=size height=size src=`/qr?${p}`) h2.mt48.fs-headline1 Moderation @@ -123,7 +125,10 @@ block body unlinkedChannels.sort((a, b) => getPosition(a) - getPosition(b)) let linkedRoomIDs = linkedChannels.map(c => c.room_id) - let unlinkedRooms = rooms.filter(r => !linkedRoomIDs.includes(r.room_id)) + let unlinkedRooms = rooms.filter(r => !linkedRoomIDs.includes(r.room_id) && !r.room_type) + // https://discord.com/developers/docs/topics/threads#active-archived-threads + // need to filter out linked archived threads from unlinkedRooms, will just do that by comparing against the name + unlinkedRooms = unlinkedRooms.filter(r => !r.name.match(/^\[(🔒)?⛓️\]/)) .s-card.bs-sm.p0 .s-table-container table.s-table.s-table__bx-simple @@ -175,7 +180,7 @@ block body != icons.Icons.IconLockSm .fl-grow1 Invite - p.s-description.m0 In-app direct invite from another user; /invite on Discord; web form + p.s-description.m0 In-app direct invite from another user p.s-description.m0 Shareable invite links, like Discord p.s-description.m0 Publicly listed in directory, like Discord server discovery diff --git a/src/web/routes/qr.js b/src/web/routes/qr.js new file mode 100644 index 0000000..314b66a --- /dev/null +++ b/src/web/routes/qr.js @@ -0,0 +1,19 @@ +// @ts-check + +const {z} = require("zod") +const {defineEventHandler, getValidatedQuery} = require("h3") + +const {as} = require("../../passthrough") + +const uqr = require("uqr") + +const schema = { + qr: z.object({ + data: z.string().max(128) + }) +} + +as.router.get("/qr", defineEventHandler(async event => { + const {data} = await getValidatedQuery(event, schema.qr.parse) + return new Response(uqr.renderSVG(data, {pixelSize: 3}), {headers: {"content-type": "image/svg+xml"}}) +})) diff --git a/src/web/server.js b/src/web/server.js index 387439f..d1b4cb8 100644 --- a/src/web/server.js +++ b/src/web/server.js @@ -26,6 +26,7 @@ sync.require("./routes/download-discord") sync.require("./routes/invite") sync.require("./routes/guild-settings") sync.require("./routes/oauth") +sync.require("./routes/qr") // Files From 6f7ed829b80d3886ab2f1739f433b8a4258eee48 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sat, 5 Oct 2024 02:23:58 +1300 Subject: [PATCH 027/228] Create and populate guild_id column --- scripts/setup.js | 1 - scripts/start-server.js | 1 - src/d2m/discord-packets.js | 45 ++++++++++++------- .../0015-add-guild-id-to-channel-room.sql | 5 +++ start.js | 1 - test/test.js | 1 - 6 files changed, 33 insertions(+), 21 deletions(-) create mode 100644 src/db/migrations/0015-add-guild-id-to-channel-room.sql diff --git a/scripts/setup.js b/scripts/setup.js index 13c2492..f1817b7 100644 --- a/scripts/setup.js +++ b/scripts/setup.js @@ -39,7 +39,6 @@ const passthrough = require("../src/passthrough") const db = new sqlite("ooye.db") const migrate = require("../src/db/migrate") -/** @type {import("heatsync").default} */ // @ts-ignore const sync = new HeatSync({watchFS: false}) Object.assign(passthrough, {sync, db}) diff --git a/scripts/start-server.js b/scripts/start-server.js index 430b3ba..f09c458 100755 --- a/scripts/start-server.js +++ b/scripts/start-server.js @@ -12,7 +12,6 @@ const {reg} = require("../src/matrix/read-registration") const passthrough = require("../src/passthrough") const db = new sqlite("ooye.db") -/** @type {import("heatsync").default} */ // @ts-ignore const sync = new HeatSync() Object.assign(passthrough, {sync, db}) diff --git a/src/d2m/discord-packets.js b/src/d2m/discord-packets.js index f619f2b..5956ac5 100644 --- a/src/d2m/discord-packets.js +++ b/src/d2m/discord-packets.js @@ -4,7 +4,11 @@ const DiscordTypes = require("discord-api-types/v10") const passthrough = require("../passthrough") -const { sync } = passthrough +const {sync, db} = passthrough + +function populateGuildID(guildID, channelID) { + db.prepare("UPDATE channel_room SET guild_id = ? WHERE channel_id = ?").run(guildID, channelID) +} const utils = { /** @@ -36,13 +40,16 @@ const utils = { channel.guild_id = message.d.id arr.push(channel.id) client.channels.set(channel.id, channel) + populateGuildID(message.d.id, channel.id) } for (const thread of message.d.threads || []) { // @ts-ignore thread.guild_id = message.d.id arr.push(thread.id) client.channels.set(thread.id, thread) + populateGuildID(message.d.id, thread.id) } + if (listen === "full") { eventDispatcher.checkMissedExpressions(message.d) eventDispatcher.checkMissedPins(client, message.d) @@ -91,7 +98,11 @@ const utils = { } else if (message.t === "THREAD_CREATE") { client.channels.set(message.d.id, message.d) - + if (message.d["guild_id"]) { + populateGuildID(message.d["guild_id"], message.d.id) + const channels = client.guildChannelMap.get(message.d["guild_id"]) + if (channels && !channels.includes(message.d.id)) channels.push(message.d.id) + } } else if (message.t === "CHANNEL_UPDATE" || message.t === "THREAD_UPDATE") { client.channels.set(message.d.id, message.d) @@ -113,21 +124,21 @@ const utils = { client.guildChannelMap.delete(message.d.id) - } else if (message.t === "CHANNEL_CREATE" || message.t === "CHANNEL_DELETE") { - if (message.t === "CHANNEL_CREATE") { - client.channels.set(message.d.id, message.d) - if (message.d["guild_id"]) { // obj[prop] notation can be used to access a property without typescript complaining that it doesn't exist on all values something can have - const channels = client.guildChannelMap.get(message.d["guild_id"]) - if (channels && !channels.includes(message.d.id)) channels.push(message.d.id) - } - } else { - client.channels.delete(message.d.id) - if (message.d["guild_id"]) { - const channels = client.guildChannelMap.get(message.d["guild_id"]) - if (channels) { - const previous = channels.indexOf(message.d.id) - if (previous !== -1) channels.splice(previous, 1) - } + } else if (message.t === "CHANNEL_CREATE") { + client.channels.set(message.d.id, message.d) + if (message.d["guild_id"]) { // obj[prop] notation can be used to access a property without typescript complaining that it doesn't exist on all values something can have + populateGuildID(message.d["guild_id"], message.d.id) + const channels = client.guildChannelMap.get(message.d["guild_id"]) + if (channels && !channels.includes(message.d.id)) channels.push(message.d.id) + } + + } else if (message.t === "CHANNEL_DELETE") { + client.channels.delete(message.d.id) + if (message.d["guild_id"]) { + const channels = client.guildChannelMap.get(message.d["guild_id"]) + if (channels) { + const previous = channels.indexOf(message.d.id) + if (previous !== -1) channels.splice(previous, 1) } } } diff --git a/src/db/migrations/0015-add-guild-id-to-channel-room.sql b/src/db/migrations/0015-add-guild-id-to-channel-room.sql new file mode 100644 index 0000000..81342e4 --- /dev/null +++ b/src/db/migrations/0015-add-guild-id-to-channel-room.sql @@ -0,0 +1,5 @@ +BEGIN TRANSACTION; + +ALTER TABLE channel_room ADD COLUMN guild_id TEXT; + +COMMIT; diff --git a/start.js b/start.js index be434f0..4ee547b 100755 --- a/start.js +++ b/start.js @@ -9,7 +9,6 @@ const {reg} = require("./src/matrix/read-registration") const passthrough = require("./src/passthrough") const db = new sqlite("ooye.db") -/** @type {import("heatsync").default} */ // @ts-ignore const sync = new HeatSync() Object.assign(passthrough, {sync, db}) diff --git a/test/test.js b/test/test.js index ee63834..5f20a80 100644 --- a/test/test.js +++ b/test/test.js @@ -25,7 +25,6 @@ reg.as_token = "baby" reg.hs_token = "baby" reg.ooye.bridge_origin = "https://bridge.example.org" -/** @type {import("heatsync").default} */ // @ts-ignore const sync = new HeatSync({watchFS: false}) const discord = { From da5525a5429fe04ecd11350b07958bf2a8c5e72c Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 14 Oct 2024 13:09:30 +1300 Subject: [PATCH 028/228] Make invite interaction async Fix potential lag issues --- src/discord/interactions/invite.js | 84 ++++++++++++------------- src/discord/interactions/invite.test.js | 61 +++++++++++------- 2 files changed, 79 insertions(+), 66 deletions(-) diff --git a/src/discord/interactions/invite.js b/src/discord/interactions/invite.js index b35f44f..0afc6d8 100644 --- a/src/discord/interactions/invite.js +++ b/src/discord/interactions/invite.js @@ -1,8 +1,9 @@ // @ts-check const DiscordTypes = require("discord-api-types/v10") -const Ty = require("../../types") const assert = require("assert/strict") +const {InteractionMethods} = require("snowtransfer") +const {id: botID} = require("../../../addbot") const {discord, sync, db, select} = require("../../passthrough") /** @type {import("../../d2m/actions/create-room")} */ @@ -15,21 +16,21 @@ const api = sync.require("../../matrix/api") /** * @param {DiscordTypes.APIChatInputApplicationCommandGuildInteraction & {channel: DiscordTypes.APIGuildTextChannel}} interaction * @param {{api: typeof api}} di - * @returns {Promise} + * @returns {AsyncGenerator<{[k in keyof InteractionMethods]?: Parameters[2]}>} */ -async function _interact({data, channel, guild_id}, {api}) { +async function* _interact({data, channel, guild_id}, {api}) { // Get named MXID /** @type {DiscordTypes.APIApplicationCommandInteractionDataStringOption[] | undefined} */ // @ts-ignore const options = data.options const input = options?.[0]?.value || "" const mxid = input.match(/@([^:]+):([a-z0-9:-]+\.[a-z0-9.:-]+)/)?.[0] - if (!mxid) return { + if (!mxid) return yield {createInteractionResponse: { type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, data: { content: "You have to say the Matrix ID of the person you want to invite. Matrix IDs look like this: `@username:example.org`", flags: DiscordTypes.MessageFlags.Ephemeral } - } + }} const guild = discord.guilds.get(guild_id) assert(guild) @@ -37,15 +38,22 @@ async function _interact({data, channel, guild_id}, {api}) { // Ensure guild and room are bridged db.prepare("INSERT OR IGNORE INTO guild_active (guild_id, autocreate) VALUES (?, 1)").run(guild_id) const existing = createRoom.existsOrAutocreatable(channel, guild_id) - if (existing === 0) return { + if (existing === 0) return yield {createInteractionResponse: { type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, data: { content: "This channel isn't bridged, so you can't invite Matrix users yet. Try turning on automatic room-creation or link a Matrix room in the website.", flags: DiscordTypes.MessageFlags.Ephemeral } - } + }} assert(existing) // can't be null or undefined as we just inserted the guild_active row + yield {createInteractionResponse: { + type: DiscordTypes.InteractionResponseType.DeferredChannelMessageWithSource, + data: { + flags: DiscordTypes.MessageFlags.Ephemeral + } + }} + const spaceID = await createSpace.ensureSpace(guild) const roomID = await createRoom.ensureRoom(channel.id) @@ -55,24 +63,17 @@ async function _interact({data, channel, guild_id}, {api}) { spaceMember = await api.getStateEvent(spaceID, "m.room.member", mxid) } catch (e) {} if (spaceMember && spaceMember.membership === "invite") { - return { - type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, - data: { - content: `\`${mxid}\` already has an invite, which they haven't accepted yet.`, - flags: DiscordTypes.MessageFlags.Ephemeral - } - } + return yield {editOriginalInteractionResponse: { + content: `\`${mxid}\` already has an invite, which they haven't accepted yet.`, + }} } // Invite Matrix user if not in space if (!spaceMember || spaceMember.membership !== "join") { await api.inviteToRoom(spaceID, mxid) - return { - type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, - data: { - content: `You invited \`${mxid}\` to the server.` - } - } + return yield {editOriginalInteractionResponse: { + content: `You invited \`${mxid}\` to the server.` + }} } // The Matrix user *is* in the space, maybe we want to invite them to this channel? @@ -81,32 +82,24 @@ async function _interact({data, channel, guild_id}, {api}) { roomMember = await api.getStateEvent(roomID, "m.room.member", mxid) } catch (e) {} if (!roomMember || (roomMember.membership !== "join" && roomMember.membership !== "invite")) { - return { - type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, - data: { - content: `\`${mxid}\` is already in this server. Would you like to additionally invite them to this specific channel?`, - flags: DiscordTypes.MessageFlags.Ephemeral, + return yield {editOriginalInteractionResponse: { + content: `\`${mxid}\` is already in this server. Would you like to additionally invite them to this specific channel?`, + components: [{ + type: DiscordTypes.ComponentType.ActionRow, components: [{ - type: DiscordTypes.ComponentType.ActionRow, - components: [{ - type: DiscordTypes.ComponentType.Button, - custom_id: "invite_channel", - style: DiscordTypes.ButtonStyle.Primary, - label: "Sure", - }] + type: DiscordTypes.ComponentType.Button, + custom_id: "invite_channel", + style: DiscordTypes.ButtonStyle.Primary, + label: "Sure", }] - } - } + }] + }} } // The Matrix user *is* in the space and in the channel. - return { - type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, - data: { - content: `\`${mxid}\` is already in this server and this channel.`, - flags: DiscordTypes.MessageFlags.Ephemeral - } - } + return yield {editOriginalInteractionResponse: { + content: `\`${mxid}\` is already in this server and this channel.`, + }} } /** @@ -133,7 +126,14 @@ async function _interactButton({channel, message}, {api}) { /** @param {DiscordTypes.APIChatInputApplicationCommandGuildInteraction & {channel: DiscordTypes.APIGuildTextChannel}} interaction */ async function interact(interaction) { - await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, await _interact(interaction, {api})) + for await (const response of _interact(interaction, {api})) { + if (response.createInteractionResponse) { + // TODO: Test if it is reasonable to remove `await` from these calls. Or zip these calls with the next interaction iteration and use Promise.all. + await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, response.createInteractionResponse) + } else if (response.editOriginalInteractionResponse) { + await discord.snow.interaction.editOriginalInteractionResponse(botID, interaction.token, response.editOriginalInteractionResponse) + } + } } /** @param {DiscordTypes.APIMessageComponentGuildInteraction} interaction */ diff --git a/src/discord/interactions/invite.test.js b/src/discord/interactions/invite.test.js index 431ff60..1890b76 100644 --- a/src/discord/interactions/invite.test.js +++ b/src/discord/interactions/invite.test.js @@ -4,19 +4,32 @@ const {db, discord} = require("../../passthrough") const {MatrixServerError} = require("../../matrix/mreq") const {_interact, _interactButton} = require("./invite") +/** + * @template T + * @param {AsyncIterable} ai + * @returns {Promise} + */ +async function fromAsync(ai) { + const result = [] + for await (const value of ai) { + result.push(value) + } + return result +} + test("invite: checks for missing matrix ID", async t => { - const msg = await _interact({ + const msgs = await fromAsync(_interact({ data: { options: [] }, channel: discord.channels.get("0"), guild_id: "112760669178241024" - }, {}) - t.equal(msg.data.content, "You have to say the Matrix ID of the person you want to invite. Matrix IDs look like this: `@username:example.org`") + }, {})) + t.equal(msgs[0].createInteractionResponse.data.content, "You have to say the Matrix ID of the person you want to invite. Matrix IDs look like this: `@username:example.org`") }) test("invite: checks for invalid matrix ID", async t => { - const msg = await _interact({ + const msgs = await fromAsync(_interact({ data: { options: [{ name: "user", @@ -26,13 +39,13 @@ test("invite: checks for invalid matrix ID", async t => { }, channel: discord.channels.get("0"), guild_id: "112760669178241024" - }, {}) - t.equal(msg.data.content, "You have to say the Matrix ID of the person you want to invite. Matrix IDs look like this: `@username:example.org`") + }, {})) + t.equal(msgs[0].createInteractionResponse.data.content, "You have to say the Matrix ID of the person you want to invite. Matrix IDs look like this: `@username:example.org`") }) test("invite: checks if channel exists or is autocreatable", async t => { db.prepare("UPDATE guild_active SET autocreate = 0").run() - const msg = await _interact({ + const msgs = await fromAsync(_interact({ data: { options: [{ name: "user", @@ -42,14 +55,14 @@ test("invite: checks if channel exists or is autocreatable", async t => { }, channel: discord.channels.get("498323546729086986"), guild_id: "112760669178241024" - }, {}) - t.equal(msg.data.content, "This channel isn't bridged, so you can't invite Matrix users yet. Try turning on automatic room-creation or link a Matrix room in the website.") + }, {})) + t.equal(msgs[0].createInteractionResponse.data.content, "This channel isn't bridged, so you can't invite Matrix users yet. Try turning on automatic room-creation or link a Matrix room in the website.") db.prepare("UPDATE guild_active SET autocreate = 1").run() }) test("invite: checks if user is already invited to space", async t => { let called = 0 - const msg = await _interact({ + const msgs = await fromAsync(_interact({ data: { options: [{ name: "user", @@ -72,14 +85,14 @@ test("invite: checks if user is already invited to space", async t => { } } } - }) - t.equal(msg.data.content, "`@cadence:cadence.moe` already has an invite, which they haven't accepted yet.") + })) + t.equal(msgs[1].editOriginalInteractionResponse.content, "`@cadence:cadence.moe` already has an invite, which they haven't accepted yet.") t.equal(called, 1) }) test("invite: invites if user is not in space", async t => { let called = 0 - const msg = await _interact({ + const msgs = await fromAsync(_interact({ data: { options: [{ name: "user", @@ -104,14 +117,14 @@ test("invite: invites if user is not in space", async t => { t.equal(mxid, "@cadence:cadence.moe") } } - }) - t.equal(msg.data.content, "You invited `@cadence:cadence.moe` to the server.") + })) + t.equal(msgs[1].editOriginalInteractionResponse.content, "You invited `@cadence:cadence.moe` to the server.") t.equal(called, 2) }) test("invite: prompts to invite to room (if never joined)", async t => { let called = 0 - const msg = await _interact({ + const msgs = await fromAsync(_interact({ data: { options: [{ name: "user", @@ -137,14 +150,14 @@ test("invite: prompts to invite to room (if never joined)", async t => { } } } - }) - t.equal(msg.data.content, "`@cadence:cadence.moe` is already in this server. Would you like to additionally invite them to this specific channel?") + })) + t.equal(msgs[1].editOriginalInteractionResponse.content, "`@cadence:cadence.moe` is already in this server. Would you like to additionally invite them to this specific channel?") t.equal(called, 2) }) test("invite: prompts to invite to room (if left)", async t => { let called = 0 - const msg = await _interact({ + const msgs = await fromAsync(_interact({ data: { options: [{ name: "user", @@ -173,8 +186,8 @@ test("invite: prompts to invite to room (if left)", async t => { } } } - }) - t.equal(msg.data.content, "`@cadence:cadence.moe` is already in this server. Would you like to additionally invite them to this specific channel?") + })) + t.equal(msgs[1].editOriginalInteractionResponse.content, "`@cadence:cadence.moe` is already in this server. Would you like to additionally invite them to this specific channel?") t.equal(called, 2) }) @@ -200,7 +213,7 @@ test("invite button: invites to room when button clicked", async t => { test("invite: no-op if in room and space", async t => { let called = 0 - const msg = await _interact({ + const msgs = await fromAsync(_interact({ data: { options: [{ name: "user", @@ -222,7 +235,7 @@ test("invite: no-op if in room and space", async t => { } } } - }) - t.equal(msg.data.content, "`@cadence:cadence.moe` is already in this server and this channel.") + })) + t.equal(msgs[1].editOriginalInteractionResponse.content, "`@cadence:cadence.moe` is already in this server and this channel.") t.equal(called, 2) }) From c127923f4dc462a4f7e9be5a29cb5f50b6858c89 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Fri, 18 Oct 2024 16:35:47 +1300 Subject: [PATCH 029/228] Make the link button do something --- src/web/pug/guild.pug | 9 +++--- src/web/routes/link.js | 63 ++++++++++++++++++++++++++++++++++++++++++ src/web/server.js | 3 +- 3 files changed, 70 insertions(+), 5 deletions(-) create mode 100644 src/web/routes/link.js diff --git a/src/web/pug/guild.pug b/src/web/pug/guild.pug index acc1acb..1d03b68 100644 --- a/src/web/pug/guild.pug +++ b/src/web/pug/guild.pug @@ -205,7 +205,7 @@ block body p.s-description All of the above, and publicly visible in the Matrix space directory (like Server Discovery) h3.mt32.fs-category Manually link channels - form.d-flex.g16.ai-start(method="post" action="/api/link") + form.d-flex.g16.ai-start(hx-post="/api/privacy-level" hx-trigger="submit" hx-disabled-elt="this") .fl-grow2.s-btn-group.fd-column.w40 each channel in unlinkedChannels input.s-btn--radio(type="radio" name="discord" id=channel.id value=channel.id) @@ -220,7 +220,8 @@ block body +matrix(room, true) else .s-empty-state.p8 All Matrix rooms are linked. + input(type="hidden" name="guild_id" value=guild_id) div - button.s-btn.s-btn__icon.s-btn__filled - != icons.Icons.IconLink - = ` Connect` + button.s-btn.s-btn__icon.s-btn__filled.htmx-indicator + != icons.Icons.IconMerge + = ` Link` diff --git a/src/web/routes/link.js b/src/web/routes/link.js new file mode 100644 index 0000000..90cfd53 --- /dev/null +++ b/src/web/routes/link.js @@ -0,0 +1,63 @@ +// @ts-check + +const {z} = require("zod") +const {defineEventHandler, useSession, createError, readValidatedBody} = require("h3") +const Ty = require("../../types") + +const {discord, db, as, sync, select, from} = require("../../passthrough") +/** @type {import("../../d2m/actions/create-space")} */ +const createSpace = sync.require("../../d2m/actions/create-space") +/** @type {import("../../d2m/actions/create-room")} */ +const createRoom = sync.require("../../d2m/actions/create-room") +const {reg} = require("../../matrix/read-registration") + +/** @type {import("../../matrix/api")} */ +const api = sync.require("../../matrix/api") + +const schema = { + link: z.object({ + guild_id: z.string(), + matrix: z.string(), + discord: z.string() + }) +} + +as.router.post("/api/link", defineEventHandler(async event => { + const parsedBody = await readValidatedBody(event, schema.link.parse) + const session = await useSession(event, {password: reg.as_token}) + + // Check guild ID or nonce + const guildID = parsedBody.guild_id + if (!(session.data.managedGuilds || []).includes(guildID)) throw createError({status: 403, message: "Forbidden", data: "Can't edit a guild you don't have Manage Server permissions in"}) + + // Check guild is bridged + const guild = discord.guilds.get(guildID) + if (!guild) throw createError({status: 400, message: "Bad Request", data: "Discord guild does not exist or bot has not joined it"}) + const spaceID = await createSpace.ensureSpace(guild) + + // Check channel exists + const channel = discord.channels.get(parsedBody.discord) + if (!channel) throw createError({status: 400, message: "Bad Request", data: "Discord channel does not exist"}) + + // Check channel and room are not already bridged + const row = from("channel_room").select("channel_id", "room_id").and("WHERE channel_id = ? OR room_id = ?").get(parsedBody.discord, parsedBody.matrix) + if (row) throw createError({status: 400, message: "Bad Request", data: `Channel ID ${row.channel_id} and room ID ${row.room_id} are already bridged and cannot be reused`}) + + // Check room exists and bridge is joined and bridge has PL 100 + const self = `@${reg.sender_localpart}:${reg.ooye.server_name}` + /** @type {Ty.Event.M_Room_Member} */ + const memberEvent = await api.getStateEvent(parsedBody.matrix, "m.room.member", self) + if (memberEvent.membership !== "join") throw createError({status: 400, message: "Bad Request", data: "Matrix room does not exist"}) + /** @type {Ty.Event.M_Power_Levels} */ + const powerLevelsStateContent = await api.getStateEvent(parsedBody.matrix, "m.room.power_levels", "") + const selfPowerLevel = powerLevelsStateContent.users?.[self] || powerLevelsStateContent.users_default || 0 + if (selfPowerLevel < (powerLevelsStateContent.state_default || 50) || selfPowerLevel < 100) throw createError({status: 400, message: "Bad Request", data: "OOYE needs power level 100 (admin) in the target Matrix room"}) + + // Insert database entry + db.prepare("INSERT INTO channel_room (channel_id, room_id, name, guild_id) VALUES (?, ?, ?, ?)").run(parsedBody.discord, parsedBody.matrix, channel.name, guildID) + + // Sync room data and space child + createRoom.syncRoom(parsedBody.discord) + + return null // 204 +})) diff --git a/src/web/server.js b/src/web/server.js index d1b4cb8..f9f12a1 100644 --- a/src/web/server.js +++ b/src/web/server.js @@ -23,8 +23,9 @@ pugSync.createRoute(as.router, "/ok", "ok.pug") sync.require("./routes/download-matrix") sync.require("./routes/download-discord") -sync.require("./routes/invite") sync.require("./routes/guild-settings") +sync.require("./routes/invite") +sync.require("./routes/link") sync.require("./routes/oauth") sync.require("./routes/qr") From 4167a01ed1cdeb7df2c588504f1628b62bfdb476 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Fri, 25 Oct 2024 16:51:20 +1300 Subject: [PATCH 030/228] Add test template for forwarded message --- src/d2m/converters/message-to-event.test.js | 12 ++++ test/data.js | 61 +++++++++++++++++++++ 2 files changed, 73 insertions(+) diff --git a/src/d2m/converters/message-to-event.test.js b/src/d2m/converters/message-to-event.test.js index 415f48d..20630d6 100644 --- a/src/d2m/converters/message-to-event.test.js +++ b/src/d2m/converters/message-to-event.test.js @@ -1014,3 +1014,15 @@ test("message2event: @everyone within a link", async t => { "m.mentions": {} }]) }) + +test("message2event: forwarded image", async t => { + const events = await messageToEvent(data.message.forwarded_image) + t.deepEqual(events, [{ + $type: "m.room.message", + msgtype: "m.text", + body: "https://github.com/@everyone", + format: "org.matrix.custom.html", + formatted_body: `https://github.com/@everyone`, + "m.mentions": {} + }]) +}) diff --git a/test/data.js b/test/data.js index 9dc2d72..6b49108 100644 --- a/test/data.js +++ b/test/data.js @@ -2129,6 +2129,67 @@ module.exports = { mention_everyone: false, tts: false } + }, + forwarded_image: { type: 0, + content: "", + mentions: [], + mention_roles: [], + attachments: [], + embeds: [], + timestamp: "2024-10-16T22:25:01.973000+00:00", + edited_timestamp: null, + flags: 16384, + components: [], + id: "1296237495993892916", + channel_id: "112760669178241024", + author: { + id: "113340068197859328", + username: "kumaccino", + avatar: "a8829abe66866d7797b36f0bfac01086", + discriminator: "0", + public_flags: 128, + flags: 128, + banner: null, + accent_color: null, + global_name: "kumaccino", + avatar_decoration_data: null, + banner_color: null, + clan: null + }, + pinned: false, + mention_everyone: false, + tts: false, + message_reference: { + type: 1, + channel_id: "1019762340922663022", + message_id: "1019779830469894234" + }, + position: 0, + message_snapshots: [ + { + message: { + type: 0, + content: "", + mentions: [], + mention_roles: [], + attachments: [ + { + id: "1296237494987133070", + filename: "100km.gif", + size: 2965649, + url: "https://cdn.discordapp.com/attachments/112760669178241024/1296237494987133070/100km.gif?ex=67118ebd&is=67103d3d&hm=8ed76d424f92f11366989f2ebc713d4f8206706ef712571e934da45b59944f77&", proxy_url: "https://media.discordapp.net/attachments/112760669178241024/1296237494987133070/100km.gif?ex=67118ebd&is=67103d3d&hm=8ed76d424f92f11366989f2ebc713d4f8206706ef712571e934da45b59944f77&", width: 300, + height: 300, + content_type: "image/gif" + } + ], + embeds: [], + timestamp: "2022-09-15T01:20:58.177000+00:00", + edited_timestamp: null, + flags: 0, + components: [] + } + } + ] } }, pk_message: { From e5f7c7fdcb2fb2f3bddfce70793383f6eaf147e5 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Thu, 31 Oct 2024 11:53:34 +1300 Subject: [PATCH 031/228] Proxy discord attachment links within embeds --- src/d2m/converters/message-to-event.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/d2m/converters/message-to-event.js b/src/d2m/converters/message-to-event.js index 3466b4c..c141e29 100644 --- a/src/d2m/converters/message-to-event.js +++ b/src/d2m/converters/message-to-event.js @@ -602,9 +602,9 @@ async function messageToEvent(message, guild, options = {}, di) { let chosenImage = embed.image?.url // the thumbnail seems to be used for "article" type but displayed big at the bottom by discord if (embed.type === "article" && embed.thumbnail?.url && !chosenImage) chosenImage = embed.thumbnail.url - if (chosenImage) rep.addParagraph(`📸 ${chosenImage}`) + if (chosenImage) rep.addParagraph(`📸 ${dUtils.getPublicUrlForCdn(chosenImage)}`) - if (embed.video?.url) rep.addParagraph(`🎞️ ${embed.video.url}`) + if (embed.video?.url) rep.addParagraph(`🎞️ ${dUtils.getPublicUrlForCdn(embed.video.url)}`) if (embed.footer?.text) rep.addLine(`— ${embed.footer.text}`, tag`— ${embed.footer.text}`) let {body, formatted_body: html} = rep.get() From cce432aeeed0367a33c2ccbc7835d86f5d92d68f Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Thu, 31 Oct 2024 11:55:54 +1300 Subject: [PATCH 032/228] Compatibility: send {} with room joins Now compatible with the spec and with condu(wu)it. --- src/matrix/api.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/matrix/api.js b/src/matrix/api.js index 7f6be01..79dd7f0 100644 --- a/src/matrix/api.js +++ b/src/matrix/api.js @@ -60,7 +60,7 @@ async function createRoom(content) { */ async function joinRoom(roomIDOrAlias, mxid) { /** @type {Ty.R.RoomJoined} */ - const root = await mreq.mreq("POST", path(`/client/v3/join/${roomIDOrAlias}`, mxid)) + const root = await mreq.mreq("POST", path(`/client/v3/join/${roomIDOrAlias}`, mxid), {}) return root.room_id } From ac165845d72e34b3e72ea7816e3dad6656ccbb44 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Thu, 31 Oct 2024 14:42:15 +1300 Subject: [PATCH 033/228] Remove unused parameter --- src/d2m/converters/message-to-event.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/d2m/converters/message-to-event.js b/src/d2m/converters/message-to-event.js index c141e29..cf8d4c2 100644 --- a/src/d2m/converters/message-to-event.js +++ b/src/d2m/converters/message-to-event.js @@ -428,8 +428,7 @@ async function messageToEvent(message, guild, options = {}, di) { return {body, html} } - // FIXME: What was the scanMentions parameter supposed to activate? It's unused. - async function addTextEvent(body, html, msgtype, {scanMentions}) { + async function addTextEvent(body, html, msgtype) { // Star * prefix for fallback edits if (options.includeEditFallbackStar) { body = "* " + body @@ -530,7 +529,7 @@ async function messageToEvent(message, guild, options = {}, di) { // Text content appears first const {body, html} = await transformContent(message.content) - await addTextEvent(body, html, msgtype, {scanMentions: true}) + await addTextEvent(body, html, msgtype) } // Then attachments @@ -612,7 +611,7 @@ async function messageToEvent(message, guild, options = {}, di) { html = `
${html}
` // Send as m.notice to apply the usual automated/subtle appearance, showing this wasn't actually typed by the person - await addTextEvent(body, html, "m.notice", {scanMentions: false}) + await addTextEvent(body, html, "m.notice") } // Then stickers From 49948ae2c1460ad9af0447485a753a1ea2d4d00d Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Thu, 31 Oct 2024 17:34:25 +1300 Subject: [PATCH 034/228] Support forwarded messages --- src/d2m/converters/message-to-event.js | 59 ++++++++++++++++++++- src/d2m/converters/message-to-event.test.js | 33 +++++++++--- test/ooye-test-data.sql | 3 +- 3 files changed, 84 insertions(+), 11 deletions(-) diff --git a/src/d2m/converters/message-to-event.js b/src/d2m/converters/message-to-event.js index cf8d4c2..195bddd 100644 --- a/src/d2m/converters/message-to-event.js +++ b/src/d2m/converters/message-to-event.js @@ -428,6 +428,12 @@ async function messageToEvent(message, guild, options = {}, di) { return {body, html} } + /** + * After converting Discord content to Matrix plaintext and HTML content, post-process the bodies and push the resulting text event + * @param {string} body matrix event plaintext body + * @param {string} html matrix event HTML body + * @param {string} msgtype matrix event msgtype (maybe m.text or m.notice) + */ async function addTextEvent(body, html, msgtype) { // Star * prefix for fallback edits if (options.includeEditFallbackStar) { @@ -436,7 +442,7 @@ async function messageToEvent(message, guild, options = {}, di) { } const flags = message.flags || 0 - if (flags & 2) { + if (flags & DiscordTypes.MessageFlags.IsCrosspost) { body = `[🔀 ${message.author.username}]\n` + body html = `🔀 ${message.author.username}
` + html } @@ -508,7 +514,57 @@ async function messageToEvent(message, guild, options = {}, di) { message.content = "changed the channel name to **" + message.content + "**" } + // Forwarded content appears first + if (message.message_reference?.type === DiscordTypes.MessageReferenceType.Forward && message.message_snapshots?.length) { + // Forwarded notice + const eventID = select("event_message", "event_id", {message_id: message.message_reference.message_id}).pluck().get() + const room = select("channel_room", ["room_id", "name", "nick"], {channel_id: message.message_reference.channel_id}).get() + const forwardedNotice = new mxUtils.MatrixStringBuilder() + if (eventID && room) { + const via = await getViaServersMemo(room.room_id) + forwardedNotice.addLine( + `[🔀 Forwarded from #${room.nick || room.name}]`, + tag`🔀 Forwarded from ${room.nick || room.name}` + ) + } else if (room) { + const via = await getViaServersMemo(room.room_id) + forwardedNotice.addLine( + `[🔀 Forwarded from #${room.nick || room.name}]`, + tag`🔀 Forwarded from ${room.nick || room.name}` + ) + } else { + forwardedNotice.addLine( + `[🔀 Forwarded message]`, + tag`🔀 Forwarded message` + ) + } + // Forwarded content + // @ts-ignore + const forwardedEvents = await messageToEvent(message.message_snapshots[0].message, guild, {includeReplyFallback: false, includeEditFallbackStar: false}, di) + + // Indent + for (const event of forwardedEvents) { + if (["m.text", "m.notice"].includes(event.msgtype)) { + event.msgtype = "m.notice" + event.body = event.body.split("\n").map(l => "» " + l).join("\n") + event.formatted_body = `
${event.formatted_body}
` + } + } + + // Try to merge the forwarded content with the forwarded notice + let {body, formatted_body} = forwardedNotice.get() + if (forwardedEvents.length >= 1 && ["m.text", "m.notice"].includes(forwardedEvents[0].msgtype)) { // Try to merge the forwarded content and the forwarded notice + forwardedNotice.add("\n", "
") + forwardedEvents[0].body = body + forwardedEvents[0].body + forwardedEvents[0].formatted_body = formatted_body + forwardedEvents[0].formatted_body + } else { + await addTextEvent(body, formatted_body, "m.notice") + } + events.push(...forwardedEvents) + } + + // Then text content if (message.content) { // Mentions scenario 3: scan the message content for written @mentions of matrix users. Allows for up to one space between @ and mention. const matches = [...message.content.matchAll(/@ ?([a-z0-9._]+)\b/gi)] @@ -527,7 +583,6 @@ async function messageToEvent(message, guild, options = {}, di) { } } - // Text content appears first const {body, html} = await transformContent(message.content) await addTextEvent(body, html, msgtype) } diff --git a/src/d2m/converters/message-to-event.test.js b/src/d2m/converters/message-to-event.test.js index 20630d6..7213bb8 100644 --- a/src/d2m/converters/message-to-event.test.js +++ b/src/d2m/converters/message-to-event.test.js @@ -1017,12 +1017,29 @@ test("message2event: @everyone within a link", async t => { test("message2event: forwarded image", async t => { const events = await messageToEvent(data.message.forwarded_image) - t.deepEqual(events, [{ - $type: "m.room.message", - msgtype: "m.text", - body: "https://github.com/@everyone", - format: "org.matrix.custom.html", - formatted_body: `https://github.com/@everyone`, - "m.mentions": {} - }]) + t.deepEqual(events, [ + { + $type: "m.room.message", + body: "[🔀 Forwarded message]", + format: "org.matrix.custom.html", + formatted_body: "🔀 Forwarded message", + "m.mentions": {}, + msgtype: "m.notice", + }, + { + $type: "m.room.message", + body: "100km.gif", + external_url: "https://bridge.example.org/download/discordcdn/112760669178241024/1296237494987133070/100km.gif", + filename: "100km.gif", + info: { + h: 300, + mimetype: "image/gif", + size: 2965649, + w: 300, + }, + "m.mentions": {}, + msgtype: "m.image", + url: "mxc://cadence.moe/qDAotmebTfEIfsAIVCEZptLh", + }, + ]) }) diff --git a/test/ooye-test-data.sql b/test/ooye-test-data.sql index b6f0951..7e22e9f 100644 --- a/test/ooye-test-data.sql +++ b/test/ooye-test-data.sql @@ -123,7 +123,8 @@ INSERT INTO file (discord_url, mxc_url) VALUES ('https://cdn.discordapp.com/emojis/288858540888686602.png', 'mxc://cadence.moe/mwZaCtRGAQQyOItagDeCocEO'), ('https://cdn.discordapp.com/attachments/112760669178241024/1197621094786531358/Ins_1960637570.mp4', 'mxc://cadence.moe/kMqLycqMURhVpwleWkmASpnU'), ('https://cdn.discordapp.com/attachments/1099031887500034088/1112476845502365786/voice-message.ogg', 'mxc://cadence.moe/MRRPDggXQMYkrUjTpxQbmcxB'), -('https://cdn.discordapp.com/attachments/122155380120748034/1174514575220158545/the.yml', 'mxc://cadence.moe/HnQIYQmmlIKwOQsbFsIGpzPP'); +('https://cdn.discordapp.com/attachments/122155380120748034/1174514575220158545/the.yml', 'mxc://cadence.moe/HnQIYQmmlIKwOQsbFsIGpzPP'), +('https://cdn.discordapp.com/attachments/112760669178241024/1296237494987133070/100km.gif', 'mxc://cadence.moe/qDAotmebTfEIfsAIVCEZptLh'); INSERT INTO emoji (emoji_id, name, animated, mxc_url) VALUES ('230201364309868544', 'hippo', 0, 'mxc://cadence.moe/qWmbXeRspZRLPcjseyLmeyXC'), From b23b81819208aef58124eadf6e14211d97f4bb34 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Thu, 31 Oct 2024 17:34:50 +1300 Subject: [PATCH 035/228] Use attachment proxy for external_url --- .../message-to-event.embeds.test.js | 2 +- src/d2m/converters/message-to-event.js | 22 +++++++++---------- src/d2m/converters/message-to-event.test.js | 14 ++++++------ 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/src/d2m/converters/message-to-event.embeds.test.js b/src/d2m/converters/message-to-event.embeds.test.js index ef7e9b8..4d76624 100644 --- a/src/d2m/converters/message-to-event.embeds.test.js +++ b/src/d2m/converters/message-to-event.embeds.test.js @@ -67,7 +67,7 @@ test("message2event embeds: image embed and attachment", async t => { msgtype: "m.image", url: "mxc://cadence.moe/zAXdQriaJuLZohDDmacwWWDR", body: "Screenshot_20231001_034036.jpg", - external_url: "https://cdn.discordapp.com/attachments/176333891320283136/1157854643037163610/Screenshot_20231001_034036.jpg?ex=651a1faa&is=6518ce2a&hm=eb5ca80a3fa7add8765bf404aea2028a28a2341e4a62435986bcdcf058da82f3&", + external_url: "https://bridge.example.org/download/discordcdn/176333891320283136/1157854643037163610/Screenshot_20231001_034036.jpg", filename: "Screenshot_20231001_034036.jpg", info: { h: 1170, diff --git a/src/d2m/converters/message-to-event.js b/src/d2m/converters/message-to-event.js index 195bddd..73106cd 100644 --- a/src/d2m/converters/message-to-event.js +++ b/src/d2m/converters/message-to-event.js @@ -103,7 +103,7 @@ const embedTitleParser = markdown.markdownEngine.parserFor({ * @param {DiscordTypes.APIAttachment} attachment */ async function attachmentToEvent(mentions, attachment) { - const publicURL = dUtils.getPublicUrlForCdn(attachment.url) + const external_url = dUtils.getPublicUrlForCdn(attachment.url) const emoji = attachment.content_type?.startsWith("image/jp") ? "📸" : attachment.content_type?.startsWith("image/") ? "🖼️" @@ -117,9 +117,9 @@ async function attachmentToEvent(mentions, attachment) { $type: "m.room.message", "m.mentions": mentions, msgtype: "m.text", - body: `${emoji} Uploaded SPOILER file: ${publicURL} (${pb(attachment.size)})`, + body: `${emoji} Uploaded SPOILER file: ${external_url} (${pb(attachment.size)})`, format: "org.matrix.custom.html", - formatted_body: `
${emoji} Uploaded SPOILER file: ${publicURL} (${pb(attachment.size)})
` + formatted_body: `
${emoji} Uploaded SPOILER file: ${external_url} (${pb(attachment.size)})
` } } // for large files, always link them instead of uploading so I don't use up all the space in the content repo @@ -128,9 +128,9 @@ async function attachmentToEvent(mentions, attachment) { $type: "m.room.message", "m.mentions": mentions, msgtype: "m.text", - body: `${emoji} Uploaded file: ${publicURL} (${pb(attachment.size)})`, + body: `${emoji} Uploaded file: ${external_url} (${pb(attachment.size)})`, format: "org.matrix.custom.html", - formatted_body: `${emoji} Uploaded file: ${attachment.filename} (${pb(attachment.size)})` + formatted_body: `${emoji} Uploaded file: ${attachment.filename} (${pb(attachment.size)})` } } else if (attachment.content_type?.startsWith("image/") && attachment.width && attachment.height) { return { @@ -138,7 +138,7 @@ async function attachmentToEvent(mentions, attachment) { "m.mentions": mentions, msgtype: "m.image", url: await file.uploadDiscordFileToMxc(attachment.url), - external_url: attachment.url, + external_url, body: attachment.description || attachment.filename, filename: attachment.filename, info: { @@ -154,7 +154,7 @@ async function attachmentToEvent(mentions, attachment) { "m.mentions": mentions, msgtype: "m.video", url: await file.uploadDiscordFileToMxc(attachment.url), - external_url: attachment.url, + external_url, body: attachment.description || attachment.filename, filename: attachment.filename, info: { @@ -170,7 +170,7 @@ async function attachmentToEvent(mentions, attachment) { "m.mentions": mentions, msgtype: "m.audio", url: await file.uploadDiscordFileToMxc(attachment.url), - external_url: attachment.url, + external_url, body: attachment.description || attachment.filename, filename: attachment.filename, info: { @@ -185,7 +185,7 @@ async function attachmentToEvent(mentions, attachment) { "m.mentions": mentions, msgtype: "m.file", url: await file.uploadDiscordFileToMxc(attachment.url), - external_url: attachment.url, + external_url, body: attachment.description || attachment.filename, filename: attachment.filename, info: { @@ -197,8 +197,8 @@ async function attachmentToEvent(mentions, attachment) { } /** - * @param {import("discord-api-types/v10").APIMessage} message - * @param {import("discord-api-types/v10").APIGuild} guild + * @param {DiscordTypes.APIMessage} message + * @param {DiscordTypes.APIGuild} guild * @param {{includeReplyFallback?: boolean, includeEditFallbackStar?: boolean}} options default values: * - includeReplyFallback: true * - includeEditFallbackStar: false diff --git a/src/d2m/converters/message-to-event.test.js b/src/d2m/converters/message-to-event.test.js index 7213bb8..115d99a 100644 --- a/src/d2m/converters/message-to-event.test.js +++ b/src/d2m/converters/message-to-event.test.js @@ -337,7 +337,7 @@ test("message2event: attachment with no content", async t => { msgtype: "m.image", url: "mxc://cadence.moe/qXoZktDqNtEGuOCZEADAMvhM", body: "image.png", - external_url: "https://cdn.discordapp.com/attachments/497161332244742154/1124628646431297546/image.png", + external_url: "https://bridge.example.org/download/discordcdn/497161332244742154/1124628646431297546/image.png", filename: "image.png", info: { mimetype: "image/png", @@ -373,7 +373,7 @@ test("message2event: stickers", async t => { msgtype: "m.image", url: "mxc://cadence.moe/ZDCNYnkPszxGKgObUIFmvjus", body: "image.png", - external_url: "https://cdn.discordapp.com/attachments/122155380120748034/1106366167486038016/image.png", + external_url: "https://bridge.example.org/download/discordcdn/122155380120748034/1106366167486038016/image.png", filename: "image.png", info: { mimetype: "image/png", @@ -427,7 +427,7 @@ test("message2event: skull webp attachment with content", async t => { mimetype: "image/webp", size: 74290 }, - external_url: "https://cdn.discordapp.com/attachments/112760669178241024/1128084747910918195/skull.webp", + external_url: "https://bridge.example.org/download/discordcdn/112760669178241024/1128084747910918195/skull.webp", filename: "skull.webp", url: "mxc://cadence.moe/sDxWmDErBhYBxtDcJQgBETes" }]) @@ -461,7 +461,7 @@ test("message2event: reply to skull webp attachment with content", async t => { mimetype: "image/jpeg", size: 85906 }, - external_url: "https://cdn.discordapp.com/attachments/112760669178241024/1128084851023675515/RDT_20230704_0936184915846675925224905.jpg", + external_url: "https://bridge.example.org/download/discordcdn/112760669178241024/1128084851023675515/RDT_20230704_0936184915846675925224905.jpg", filename: "RDT_20230704_0936184915846675925224905.jpg", url: "mxc://cadence.moe/WlAbFSiNRIHPDEwKdyPeGywa" }]) @@ -551,7 +551,7 @@ test("message2event: reply with a video", async t => { body: "Ins_1960637570.mp4", filename: "Ins_1960637570.mp4", url: "mxc://cadence.moe/kMqLycqMURhVpwleWkmASpnU", - external_url: "https://cdn.discordapp.com/attachments/112760669178241024/1197621094786531358/Ins_1960637570.mp4?ex=65bbee8f&is=65a9798f&hm=ae14f7824c3d526c5e11c162e012e1ee405fd5776e1e9302ed80ccd86503cfda&", + external_url: "https://bridge.example.org/download/discordcdn/112760669178241024/1197621094786531358/Ins_1960637570.mp4", info: { h: 854, mimetype: "video/mp4", @@ -572,7 +572,7 @@ test("message2event: voice message", async t => { t.deepEqual(events, [{ $type: "m.room.message", body: "voice-message.ogg", - external_url: "https://cdn.discordapp.com/attachments/1099031887500034088/1112476845502365786/voice-message.ogg?ex=65c92d4c&is=65b6b84c&hm=0654bab5027474cbe23875954fa117cf44d8914c144cd151879590fa1baf8b1c&", + external_url: "https://bridge.example.org/download/discordcdn/1099031887500034088/1112476845502365786/voice-message.ogg", filename: "voice-message.ogg", info: { duration: 3960.0000381469727, @@ -595,7 +595,7 @@ test("message2event: misc file", async t => { }, { $type: "m.room.message", body: "the.yml", - external_url: "https://cdn.discordapp.com/attachments/122155380120748034/1174514575220158545/the.yml?ex=65cd6270&is=65baed70&hm=8c5f1b571784e3c7f99628492298815884e351ae0dc7c2ae40dd22d97caf27d9&", + external_url: "https://bridge.example.org/download/discordcdn/122155380120748034/1174514575220158545/the.yml", filename: "the.yml", info: { mimetype: "text/plain; charset=utf-8", From 1b539cfa64d39a793ae4727bae3355f556abcd73 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Fri, 1 Nov 2024 16:39:56 +1300 Subject: [PATCH 036/228] Forwarding text messages --- src/d2m/converters/message-to-event.js | 5 +- src/d2m/converters/message-to-event.test.js | 58 ++++++++++++++++ test/data.js | 74 +++++++++++++++++++++ test/ooye-test-data.sql | 6 +- 4 files changed, 138 insertions(+), 5 deletions(-) diff --git a/src/d2m/converters/message-to-event.js b/src/d2m/converters/message-to-event.js index 73106cd..afdb4b8 100644 --- a/src/d2m/converters/message-to-event.js +++ b/src/d2m/converters/message-to-event.js @@ -555,9 +555,8 @@ async function messageToEvent(message, guild, options = {}, di) { // Try to merge the forwarded content with the forwarded notice let {body, formatted_body} = forwardedNotice.get() if (forwardedEvents.length >= 1 && ["m.text", "m.notice"].includes(forwardedEvents[0].msgtype)) { // Try to merge the forwarded content and the forwarded notice - forwardedNotice.add("\n", "
") - forwardedEvents[0].body = body + forwardedEvents[0].body - forwardedEvents[0].formatted_body = formatted_body + forwardedEvents[0].formatted_body + forwardedEvents[0].body = body + "\n" + forwardedEvents[0].body + forwardedEvents[0].formatted_body = formatted_body + "
" + forwardedEvents[0].formatted_body } else { await addTextEvent(body, formatted_body, "m.notice") } diff --git a/src/d2m/converters/message-to-event.test.js b/src/d2m/converters/message-to-event.test.js index 115d99a..4ae342c 100644 --- a/src/d2m/converters/message-to-event.test.js +++ b/src/d2m/converters/message-to-event.test.js @@ -1043,3 +1043,61 @@ test("message2event: forwarded image", async t => { }, ]) }) + +test("message2event: constructed forwarded message", async t => { + const events = await messageToEvent(data.message.constructed_forwarded_message, {}, {}, { + api: { + async getJoinedMembers(roomID) { + return { + joined: { + "@_ooye_bot:cadence.moe": {display_name: null, avatar_url: null}, + "@user:matrix.org": {display_name: null, avatar_url: null} + } + } + } + } + }) + t.deepEqual(events, [ + { + $type: "m.room.message", + body: "[🔀 Forwarded from #wonderland]" + + "\n» What's cooking, good looking? :hipposcope:", + format: "org.matrix.custom.html", + formatted_body: `🔀 Forwarded from wonderland` + + `
What's cooking, good looking? :hipposcope:
`, + "m.mentions": {}, + msgtype: "m.notice", + }, + { + $type: "m.room.message", + body: "100km.gif", + external_url: "https://bridge.example.org/download/discordcdn/112760669178241024/1296237494987133070/100km.gif", + filename: "100km.gif", + info: { + h: 300, + mimetype: "image/gif", + size: 2965649, + w: 300, + }, + "m.mentions": {}, + msgtype: "m.image", + url: "mxc://cadence.moe/qDAotmebTfEIfsAIVCEZptLh", + }, + { + $type: "m.room.message", + body: "» | ## This man" + + "\n» | " + + "\n» | ## This man is 100 km away from your house" + + "\n» | " + + "\n» | ### Distance away" + + "\n» | 99 km" + + "\n» | " + + "\n» | ### Distance away" + + "\n» | 98 km", + format: "org.matrix.custom.html", + formatted_body: "

This man

This man is 100 km away from your house

Distance away
99 km

Distance away
98 km

", + "m.mentions": {}, + msgtype: "m.notice" + } + ]) +}) diff --git a/test/data.js b/test/data.js index 6b49108..8adc459 100644 --- a/test/data.js +++ b/test/data.js @@ -2190,6 +2190,80 @@ module.exports = { } } ] + }, + constructed_forwarded_message: { type: 0, + content: "", + mentions: [], + mention_roles: [], + attachments: [], + embeds: [], + timestamp: "2024-10-16T22:25:01.973000+00:00", + edited_timestamp: null, + flags: 16384, + components: [], + id: "1296237495993892916", + channel_id: "112760669178241024", + author: { + id: "113340068197859328", + username: "kumaccino", + avatar: "a8829abe66866d7797b36f0bfac01086", + discriminator: "0", + public_flags: 128, + flags: 128, + banner: null, + accent_color: null, + global_name: "kumaccino", + avatar_decoration_data: null, + banner_color: null, + clan: null + }, + pinned: false, + mention_everyone: false, + tts: false, + message_reference: { + type: 1, + channel_id: "176333891320283136", + message_id: "1191567971970191490" + }, + position: 0, + message_snapshots: [ + { + message: { + type: 0, + content: "What's cooking, good looking? <:hipposcope:393635038903926784>", + mentions: [], + mention_roles: [], + attachments: [ + { + id: "1296237494987133070", + filename: "100km.gif", + size: 2965649, + url: "https://cdn.discordapp.com/attachments/112760669178241024/1296237494987133070/100km.gif?ex=67118ebd&is=67103d3d&hm=8ed76d424f92f11366989f2ebc713d4f8206706ef712571e934da45b59944f77&", proxy_url: "https://media.discordapp.net/attachments/112760669178241024/1296237494987133070/100km.gif?ex=67118ebd&is=67103d3d&hm=8ed76d424f92f11366989f2ebc713d4f8206706ef712571e934da45b59944f77&", width: 300, + height: 300, + content_type: "image/gif" + } + ], + embeds: [{ + type: "rich", + title: "This man is 100 km away from your house", + author: { + name: "This man" + }, + fields: [{ + name: "Distance away", + value: "99 km" + }, { + name: "Distance away", + value: "98 km" + }] + }], + timestamp: "2022-09-15T01:20:58.177000+00:00", + edited_timestamp: null, + flags: 0, + components: [] + } + } + ] } }, pk_message: { diff --git a/test/ooye-test-data.sql b/test/ooye-test-data.sql index 7e22e9f..af7ea7b 100644 --- a/test/ooye-test-data.sql +++ b/test/ooye-test-data.sql @@ -64,7 +64,8 @@ INSERT INTO message_channel (message_id, channel_id) VALUES ('1273204543739396116', '687028734322147344'), ('1273743950028607530', '1100319550446252084'), ('1278002262400176128', '1100319550446252084'), -('1278001833876525057', '1100319550446252084'); +('1278001833876525057', '1100319550446252084'), +('1191567971970191490', '176333891320283136'); INSERT INTO event_message (event_id, event_type, event_subtype, message_id, part, reaction_part, source) VALUES ('$X16nfVks1wsrhq4E9SSLiqrf2N8KD0erD0scZG7U5xg', 'm.room.message', 'm.text', '1126786462646550579', 0, 0, 1), @@ -103,7 +104,8 @@ INSERT INTO event_message (event_id, event_type, event_subtype, message_id, part ('$qmyjr-ISJtnOM5WTWLI0fT7uSlqRLgpyin2d2NCglCU', 'm.room.message', 'm.text', '1273204543739396116', 0, 0, 0), ('$W1nsDhNIojWrcQOdnOD9RaEvrz2qyZErQoNhPRs1nK4', 'm.room.message', 'm.text', '1273743950028607530', 0, 0, 0), ('$UTqiL3Zj3FC4qldxRLggN1fhygpKl8sZ7XGY5f9MNbF', 'm.room.message', 'm.text', '1278002262400176128', 0, 0, 1), -('$aLVZyiC3HlOu-prCSIaXlQl68I8leUdnPFiCwkgn6qM', 'm.room.message', 'm.text', '1278001833876525057', 0, 0, 1); +('$aLVZyiC3HlOu-prCSIaXlQl68I8leUdnPFiCwkgn6qM', 'm.room.message', 'm.text', '1278001833876525057', 0, 0, 1), +('$tBIT8mO7XTTCgIINyiAIy6M2MSoPAdJenRl_RLyYuaE', 'm.room.message', 'm.text', '1191567971970191490', 0, 0, 1); INSERT INTO file (discord_url, mxc_url) VALUES ('https://cdn.discordapp.com/attachments/497161332244742154/1124628646431297546/image.png', 'mxc://cadence.moe/qXoZktDqNtEGuOCZEADAMvhM'), From 0d8b9d570546121b6818eee50c1afda873f07ba0 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Fri, 1 Nov 2024 16:50:28 +1300 Subject: [PATCH 037/228] Forwarded messages code coverage and plaintext fix --- src/d2m/converters/message-to-event.js | 31 ++++++------ src/d2m/converters/message-to-event.test.js | 35 +++++++++++++- test/data.js | 52 +++++++++++++++++++++ 3 files changed, 103 insertions(+), 15 deletions(-) diff --git a/src/d2m/converters/message-to-event.js b/src/d2m/converters/message-to-event.js index afdb4b8..251ce90 100644 --- a/src/d2m/converters/message-to-event.js +++ b/src/d2m/converters/message-to-event.js @@ -199,9 +199,10 @@ async function attachmentToEvent(mentions, attachment) { /** * @param {DiscordTypes.APIMessage} message * @param {DiscordTypes.APIGuild} guild - * @param {{includeReplyFallback?: boolean, includeEditFallbackStar?: boolean}} options default values: + * @param {{includeReplyFallback?: boolean, includeEditFallbackStar?: boolean, alwaysReturnFormattedBody?: boolean}} options default values: * - includeReplyFallback: true * - includeEditFallbackStar: false + * - alwaysReturnFormattedBody: false - formatted_body will be skipped if it is the same as body because the message is plaintext. if you want the formatted_body to be returned anyway, for example to merge it with another message, then set this to true. * @param {{api: import("../../matrix/api")}} di simple-as-nails dependency injection for the matrix API */ async function messageToEvent(message, guild, options = {}, di) { @@ -496,7 +497,7 @@ async function messageToEvent(message, guild, options = {}, di) { const isPlaintext = body === html - if (!isPlaintext) { + if (!isPlaintext || options.alwaysReturnFormattedBody) { Object.assign(newTextMessageEvent, { format: "org.matrix.custom.html", formatted_body: html @@ -520,18 +521,20 @@ async function messageToEvent(message, guild, options = {}, di) { const eventID = select("event_message", "event_id", {message_id: message.message_reference.message_id}).pluck().get() const room = select("channel_room", ["room_id", "name", "nick"], {channel_id: message.message_reference.channel_id}).get() const forwardedNotice = new mxUtils.MatrixStringBuilder() - if (eventID && room) { + if (room) { + const roomName = room && (room.nick || room.name) const via = await getViaServersMemo(room.room_id) - forwardedNotice.addLine( - `[🔀 Forwarded from #${room.nick || room.name}]`, - tag`🔀 Forwarded from ${room.nick || room.name}` - ) - } else if (room) { - const via = await getViaServersMemo(room.room_id) - forwardedNotice.addLine( - `[🔀 Forwarded from #${room.nick || room.name}]`, - tag`🔀 Forwarded from ${room.nick || room.name}` - ) + if (eventID) { + forwardedNotice.addLine( + `[🔀 Forwarded from #${roomName}]`, + tag`🔀 Forwarded from ${roomName}` + ) + } else { + forwardedNotice.addLine( + `[🔀 Forwarded from #${roomName}]`, + tag`🔀 Forwarded from ${roomName}` + ) + } } else { forwardedNotice.addLine( `[🔀 Forwarded message]`, @@ -541,7 +544,7 @@ async function messageToEvent(message, guild, options = {}, di) { // Forwarded content // @ts-ignore - const forwardedEvents = await messageToEvent(message.message_snapshots[0].message, guild, {includeReplyFallback: false, includeEditFallbackStar: false}, di) + const forwardedEvents = await messageToEvent(message.message_snapshots[0].message, guild, {includeReplyFallback: false, includeEditFallbackStar: false, alwaysReturnFormattedBody: true}, di) // Indent for (const event of forwardedEvents) { diff --git a/src/d2m/converters/message-to-event.test.js b/src/d2m/converters/message-to-event.test.js index 4ae342c..50f0908 100644 --- a/src/d2m/converters/message-to-event.test.js +++ b/src/d2m/converters/message-to-event.test.js @@ -1047,7 +1047,7 @@ test("message2event: forwarded image", async t => { test("message2event: constructed forwarded message", async t => { const events = await messageToEvent(data.message.constructed_forwarded_message, {}, {}, { api: { - async getJoinedMembers(roomID) { + async getJoinedMembers() { return { joined: { "@_ooye_bot:cadence.moe": {display_name: null, avatar_url: null}, @@ -1101,3 +1101,36 @@ test("message2event: constructed forwarded message", async t => { } ]) }) + +test("message2event: constructed forwarded text", async t => { + const events = await messageToEvent(data.message.constructed_forwarded_text, {}, {}, { + api: { + async getJoinedMembers() { + return { + joined: { + "@_ooye_bot:cadence.moe": {display_name: null, avatar_url: null}, + "@user:matrix.org": {display_name: null, avatar_url: null} + } + } + } + } + }) + t.deepEqual(events, [ + { + $type: "m.room.message", + body: "[🔀 Forwarded from #amanda-spam]" + + "\n» What's cooking, good looking?", + format: "org.matrix.custom.html", + formatted_body: `🔀 Forwarded from amanda-spam` + + `
What's cooking, good looking?
`, + "m.mentions": {}, + msgtype: "m.notice", + }, + { + $type: "m.room.message", + body: "What's cooking everybody ‼️", + "m.mentions": {}, + msgtype: "m.text", + } + ]) +}) diff --git a/test/data.js b/test/data.js index 8adc459..1c7983a 100644 --- a/test/data.js +++ b/test/data.js @@ -2264,6 +2264,58 @@ module.exports = { } } ] + }, + constructed_forwarded_text: { type: 0, + content: "What's cooking everybody ‼️", + mentions: [], + mention_roles: [], + attachments: [], + embeds: [], + timestamp: "2024-10-16T22:25:01.973000+00:00", + edited_timestamp: null, + flags: 16384, + components: [], + id: "1296237495993892916", + channel_id: "112760669178241024", + author: { + id: "113340068197859328", + username: "kumaccino", + avatar: "a8829abe66866d7797b36f0bfac01086", + discriminator: "0", + public_flags: 128, + flags: 128, + banner: null, + accent_color: null, + global_name: "kumaccino", + avatar_decoration_data: null, + banner_color: null, + clan: null + }, + pinned: false, + mention_everyone: false, + tts: false, + message_reference: { + type: 1, + channel_id: "497161350934560778", + message_id: "0" + }, + position: 0, + message_snapshots: [ + { + message: { + type: 0, + content: "What's cooking, good looking?", + mentions: [], + mention_roles: [], + attachments: [], + embeds: [], + timestamp: "2022-09-15T01:20:58.177000+00:00", + edited_timestamp: null, + flags: 0, + components: [] + } + } + ] } }, pk_message: { From 14115c0e063010ad40bce866893b80cff3bdee03 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Fri, 1 Nov 2024 17:25:11 +1300 Subject: [PATCH 038/228] Attempt retrigger after speedbump --- src/d2m/event-dispatcher.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/d2m/event-dispatcher.js b/src/d2m/event-dispatcher.js index af8eedf..c68e11a 100644 --- a/src/d2m/event-dispatcher.js +++ b/src/d2m/event-dispatcher.js @@ -281,9 +281,6 @@ module.exports = { // Otherwise, if there are embeds, then the system generated URL preview embeds. if (!(typeof data.content === "string" || "embeds" in data)) return - // Check that the sending-to room exists, and deal with Eventual Consistency(TM) - if (retrigger.eventNotFoundThenRetrigger(data.id, module.exports.onMessageUpdate, client, data)) return - if (data.webhook_id) { const row = select("webhook", "webhook_id", {webhook_id: data.webhook_id}).pluck().get() if (row) return // The message was sent by the bridge's own webhook on discord. We don't want to reflect this back, so just drop it. @@ -295,6 +292,9 @@ module.exports = { const {affected, row} = await speedbump.maybeDoSpeedbump(data.channel_id, data.id) if (affected) return + // Check that the sending-to room exists, and deal with Eventual Consistency(TM) + if (retrigger.eventNotFoundThenRetrigger(data.id, module.exports.onMessageUpdate, client, data)) return + /** @type {DiscordTypes.GatewayMessageCreateDispatchData} */ // @ts-ignore const message = data From 15e5b17b0d3a532034dec98990aba0b6b25befbc Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sat, 2 Nov 2024 19:22:30 +1300 Subject: [PATCH 039/228] When inviting bot, check it has bot scope --- src/discord/interactions/invite.js | 15 ++++++++++++--- src/discord/interactions/invite.test.js | 15 +++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/discord/interactions/invite.js b/src/discord/interactions/invite.js index 0afc6d8..8940363 100644 --- a/src/discord/interactions/invite.js +++ b/src/discord/interactions/invite.js @@ -12,6 +12,8 @@ const createRoom = sync.require("../../d2m/actions/create-room") const createSpace = sync.require("../../d2m/actions/create-space") /** @type {import("../../matrix/api")} */ const api = sync.require("../../matrix/api") +/** @type {import("../../matrix/read-registration")} */ +const {reg} = sync.require("../../matrix/read-registration") /** * @param {DiscordTypes.APIChatInputApplicationCommandGuildInteraction & {channel: DiscordTypes.APIGuildTextChannel}} interaction @@ -19,6 +21,16 @@ const api = sync.require("../../matrix/api") * @returns {AsyncGenerator<{[k in keyof InteractionMethods]?: Parameters[2]}>} */ async function* _interact({data, channel, guild_id}, {api}) { + // Check guild exists - it might not exist if the application was added with applications.commands scope and not bot scope + const guild = discord.guilds.get(guild_id) + if (!guild) return yield {createInteractionResponse: { + type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, + data: { + content: `I can't perform actions in this server because there is no bot presence in the server. You should try re-adding this bot to the server, making sure that it has bot scope (not just commands).\nIf you add the bot from ${reg.ooye.bridge_origin} this should work automatically.`, + flags: DiscordTypes.MessageFlags.Ephemeral + } + }} + // Get named MXID /** @type {DiscordTypes.APIApplicationCommandInteractionDataStringOption[] | undefined} */ // @ts-ignore const options = data.options @@ -32,9 +44,6 @@ async function* _interact({data, channel, guild_id}, {api}) { } }} - const guild = discord.guilds.get(guild_id) - assert(guild) - // Ensure guild and room are bridged db.prepare("INSERT OR IGNORE INTO guild_active (guild_id, autocreate) VALUES (?, 1)").run(guild_id) const existing = createRoom.existsOrAutocreatable(channel, guild_id) diff --git a/src/discord/interactions/invite.test.js b/src/discord/interactions/invite.test.js index 1890b76..8290718 100644 --- a/src/discord/interactions/invite.test.js +++ b/src/discord/interactions/invite.test.js @@ -43,6 +43,21 @@ test("invite: checks for invalid matrix ID", async t => { t.equal(msgs[0].createInteractionResponse.data.content, "You have to say the Matrix ID of the person you want to invite. Matrix IDs look like this: `@username:example.org`") }) +test("invite: checks if guild exists", async t => { // it might not exist if the application was added with applications.commands scope and not bot scope + const msgs = await fromAsync(_interact({ + data: { + options: [{ + name: "user", + type: DiscordTypes.ApplicationCommandOptionType.String, + value: "@cadence:cadence.moe" + }] + }, + channel: discord.channels.get("0"), + guild_id: "0" + }, {})) + t.match(msgs[0].createInteractionResponse.data.content, /there is no bot presence in the server/) +}) + test("invite: checks if channel exists or is autocreatable", async t => { db.prepare("UPDATE guild_active SET autocreate = 0").run() const msgs = await fromAsync(_interact({ From 07d6eb3c1272c2526a4749724c07c4fd530893d4 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sat, 2 Nov 2024 20:35:52 +1300 Subject: [PATCH 040/228] Fix existingPartZero assertion error --- src/d2m/actions/retrigger.js | 33 +++++++++++++++++++++++---- src/d2m/converters/edit-to-changes.js | 30 ++++++++++++++---------- src/d2m/event-dispatcher.js | 2 +- 3 files changed, 47 insertions(+), 18 deletions(-) diff --git a/src/d2m/actions/retrigger.js b/src/d2m/actions/retrigger.js index 030ffbf..aa79a79 100644 --- a/src/d2m/actions/retrigger.js +++ b/src/d2m/actions/retrigger.js @@ -12,6 +12,7 @@ function debugRetrigger(message) { } } +const paused = new Set() const emitter = new EventEmitter() /** @@ -25,13 +26,15 @@ const emitter = new EventEmitter() * @returns {boolean} false if the event was found and the function will be ignored, true if the event was not found and the function will be retriggered */ function eventNotFoundThenRetrigger(messageID, fn, ...rest) { - const eventID = select("event_message", "event_id", {message_id: messageID}).pluck().get() - if (eventID) { - debugRetrigger(`[retrigger] OK mid <-> eid = ${messageID} <-> ${eventID}`) - return false // event was found so don't retrigger + if (!paused.has(messageID)) { + const eventID = select("event_message", "event_id", {message_id: messageID}).pluck().get() + if (eventID) { + debugRetrigger(`[retrigger] OK mid <-> eid = ${messageID} <-> ${eventID}`) + return false // event was found so don't retrigger + } } - debugRetrigger(`[retrigger] WAIT mid <-> eid = ${messageID} <-> ${eventID}`) + debugRetrigger(`[retrigger] WAIT mid = ${messageID}`) emitter.once(messageID, () => { debugRetrigger(`[retrigger] TRIGGER mid = ${messageID}`) fn(...rest) @@ -46,6 +49,25 @@ function eventNotFoundThenRetrigger(messageID, fn, ...rest) { return true // event was not found, then retrigger } +/** + * Anything calling retrigger during the callback will be paused and retriggered after the callback resolves. + * @template T + * @param {string} messageID + * @param {Promise} promise + * @returns {Promise} + */ +async function pauseChanges(messageID, promise) { + try { + debugRetrigger(`[retrigger] PAUSE mid = ${messageID}`) + paused.add(messageID) + return await promise + } finally { + debugRetrigger(`[retrigger] RESUME mid = ${messageID}`) + paused.delete(messageID) + messageFinishedBridging(messageID) + } +} + /** * Triggers any pending operations that were waiting on the corresponding event ID. * @param {string} messageID @@ -59,3 +81,4 @@ function messageFinishedBridging(messageID) { module.exports.eventNotFoundThenRetrigger = eventNotFoundThenRetrigger module.exports.messageFinishedBridging = messageFinishedBridging +module.exports.pauseChanges = pauseChanges diff --git a/src/d2m/converters/edit-to-changes.js b/src/d2m/converters/edit-to-changes.js index f93c510..c38c24e 100644 --- a/src/d2m/converters/edit-to-changes.js +++ b/src/d2m/converters/edit-to-changes.js @@ -122,35 +122,41 @@ async function editToChanges(message, guild, api) { eventsToReplace = eventsToReplace.filter(eventCanBeEdited) // We want to maintain exactly one part = 0 and one reaction_part = 0 database row at all times. + // This would be disrupted if existing events that are (reaction_)part = 0 will be redacted. + // If that is the case, pick a different existing or newly sent event to be (reaction_)part = 0. /** @type {({column: string, eventID: string, value?: number} | {column: string, nextEvent: true})[]} */ const promotions = [] for (const column of ["part", "reaction_part"]) { const candidatesForParts = unchangedEvents.concat(eventsToReplace) // If no events with part = 0 exist (or will exist), we need to do some management. if (!candidatesForParts.some(e => e.old[column] === 0)) { + // Try to find an existing event to promote. Bigger order is better. if (candidatesForParts.length) { - // We can choose an existing event to promote. Bigger order is better. const order = e => 2*+(e.event_type === "m.room.message") + 1*+(e.old.event_subtype === "m.text") candidatesForParts.sort((a, b) => order(b) - order(a)) if (column === "part") { promotions.push({column, eventID: candidatesForParts[0].old.event_id}) // part should be the first one + } else if (eventsToSend.length) { + promotions.push({column, nextEvent: true}) // reaction_part should be the last one } else { promotions.push({column, eventID: candidatesForParts[candidatesForParts.length - 1].old.event_id}) // reaction_part should be the last one } - } else { - // No existing events to promote, but new events are being sent. Whatever gets sent will be the next part = 0. + } + // Or, if there are no existing events to promote and new events will be sent, whatever gets sent will be the next part = 0. + else { promotions.push({column, nextEvent: true}) } } - // If adding events, try to keep reactions attached to the bottom of the group (unless reactions have already been added) - if (eventsToSend.length && !promotions.length) { - const existingReaction = select("reaction", "message_id", {message_id: message.id}).pluck().get() - if (!existingReaction) { - const existingPartZero = candidatesForParts.find(p => p.old.reaction_part === 0) - assert(existingPartZero) // will exist because a reaction_part=0 always exists and no events are being removed - promotions.push({column: "reaction_part", eventID: existingPartZero.old.event_id, value: 1}) // update the current reaction_part to 1 - promotions.push({column: "reaction_part", nextEvent: true}) // the newly created event will have reaction_part = 0 - } + } + + // If adding events, try to keep reactions attached to the bottom of the group (unless reactions have already been added) + if (eventsToSend.length && !promotions.length) { + const existingReaction = select("reaction", "message_id", {message_id: message.id}).pluck().get() + if (!existingReaction) { + const existingPartZero = unchangedEvents.concat(eventsToReplace).find(p => p.old.reaction_part === 0) + assert(existingPartZero) // will exist because a reaction_part=0 always exists and no events are being removed + promotions.push({column: "reaction_part", eventID: existingPartZero.old.event_id, value: 1}) // update the current reaction_part to 1 + promotions.push({column: "reaction_part", nextEvent: true}) // the newly created event will have reaction_part = 0 } } diff --git a/src/d2m/event-dispatcher.js b/src/d2m/event-dispatcher.js index c68e11a..c84d6a8 100644 --- a/src/d2m/event-dispatcher.js +++ b/src/d2m/event-dispatcher.js @@ -304,7 +304,7 @@ module.exports = { assert(guild) // @ts-ignore - await editMessage.editMessage(message, guild, row) + await retrigger.pauseChanges(message.id, editMessage.editMessage(message, guild, row)) }, /** From a63d173a9a2cdc03c129e5f8bb4e0ed57b290d3d Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 25 Nov 2024 16:30:10 +1300 Subject: [PATCH 041/228] Remove redundant/invalid checks from setup --- scripts/setup.js | 13 +------------ src/m2d/converters/utils.js | 4 +--- 2 files changed, 2 insertions(+), 15 deletions(-) diff --git a/scripts/setup.js b/scripts/setup.js index f1817b7..a8b068b 100644 --- a/scripts/setup.js +++ b/scripts/setup.js @@ -230,7 +230,6 @@ async function validateHomeserverOrigin(serverUrlPrompt, url) { // Done with user prompts, reg is now guaranteed to be valid const api = require("../src/matrix/api") const file = require("../src/matrix/file") - const utils = require("../src/m2d/converters/utils") const DiscordClient = require("../src/d2m/discord-client") const discord = new DiscordClient(reg.ooye.discord_token, "no") passthrough.discord = discord @@ -267,21 +266,11 @@ async function validateHomeserverOrigin(serverUrlPrompt, url) { const mxid = `@${reg.sender_localpart}:${reg.ooye.server_name}` - // ensure registration is correctly set... - assert(reg.sender_localpart.startsWith(reg.ooye.namespace_prefix), "appservice's localpart must be in the namespace it controls") - assert(utils.eventSenderIsFromDiscord(mxid), "appservice's mxid must be in the namespace it controls") - assert(reg.ooye.server_origin.match(/^https?:\/\//), "server origin must start with http or https") - assert.notEqual(reg.ooye.server_origin.slice(-1), "/", "server origin must not end in slash") - const botID = Buffer.from(reg.ooye.discord_token.split(".")[0], "base64").toString() - assert(botID.match(/^[0-9]{10,}$/), "discord token must follow the correct format") - assert.match(reg.url, /^https?:/, "url must start with http:// or https://") - - console.log("✅ Configuration looks good...") - // database ddl... await migrate.migrate(db) // add initial rows to database, like adding the bot to sim... + const botID = Buffer.from(reg.ooye.discord_token.split(".")[0], "base64").toString() db.prepare("INSERT OR IGNORE INTO sim (user_id, sim_name, localpart, mxid) VALUES (?, ?, ?, ?)").run(botID, reg.sender_localpart.slice(reg.ooye.namespace_prefix.length), reg.sender_localpart, mxid) console.log("✅ Database is ready...") diff --git a/src/m2d/converters/utils.js b/src/m2d/converters/utils.js index c538627..17cb0fd 100644 --- a/src/m2d/converters/utils.js +++ b/src/m2d/converters/utils.js @@ -30,9 +30,7 @@ const NEWLINE_ELEMENTS = BLOCK_ELEMENTS.concat(["BR"]) */ function eventSenderIsFromDiscord(sender) { // If it's from a user in the bridge's namespace, then it originated from discord - // This includes messages sent by the appservice's bot user, because that is what's used for webhooks - // TODO: It would be nice if bridge system messages wouldn't trigger this check and could be bridged from matrix to discord, while webhook reflections would remain ignored... - // TODO that only applies to the above todo: But you'd have to watch out for the /icon command, where the bridge bot would set the room avatar, and that shouldn't be reflected into the room a second time. + // This could include messages sent by the appservice's bot user, because that is what's used for webhooks if (userRegex.some(x => sender.match(x))) { return true } From 7ff2a38cdb651e7421073f6ec3b0963832e18689 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Tue, 26 Nov 2024 12:17:31 +1300 Subject: [PATCH 042/228] Move room linking logic out of template --- src/web/pug/guild.pug | 26 -------------------------- src/web/routes/invite.js | 36 +++++++++++++++++++++++++++++++++++- 2 files changed, 35 insertions(+), 27 deletions(-) diff --git a/src/web/pug/guild.pug b/src/web/pug/guild.pug index 1d03b68..29ad9ad 100644 --- a/src/web/pug/guild.pug +++ b/src/web/pug/guild.pug @@ -102,33 +102,7 @@ block body h2.mt48.fs-headline1 Matrix setup h3.mt32.fs-category Linked channels - - - function getPosition(channel) { - let position = 0 - let looking = channel - while (looking.parent_id) { - looking = discord.channels.get(looking.parent_id) - position = looking.position * 1000 - } - if (channel.position) position += channel.position - return position - } - let channelIDs = discord.guildChannelMap.get(guild_id) - let linkedChannels = select("channel_room", ["channel_id", "room_id", "name", "nick"], {channel_id: channelIDs}).all() - let linkedChannelsWithDetails = linkedChannels.map(c => ({channel: discord.channels.get(c.channel_id), ...c})).filter(c => c.channel) - let linkedChannelIDs = linkedChannelsWithDetails.map(c => c.channel_id) - linkedChannelsWithDetails.sort((a, b) => getPosition(a.channel) - getPosition(b.channel)) - - let unlinkedChannelIDs = channelIDs.filter(c => !linkedChannelIDs.includes(c)) - let unlinkedChannels = unlinkedChannelIDs.map(c => discord.channels.get(c)).filter(c => [0, 5].includes(c.type)) - unlinkedChannels.sort((a, b) => getPosition(a) - getPosition(b)) - - let linkedRoomIDs = linkedChannels.map(c => c.room_id) - let unlinkedRooms = rooms.filter(r => !linkedRoomIDs.includes(r.room_id) && !r.room_type) - // https://discord.com/developers/docs/topics/threads#active-archived-threads - // need to filter out linked archived threads from unlinkedRooms, will just do that by comparing against the name - unlinkedRooms = unlinkedRooms.filter(r => !r.name.match(/^\[(🔒)?⛓️\]/)) .s-card.bs-sm.p0 .s-table-container table.s-table.s-table__bx-simple diff --git a/src/web/routes/invite.js b/src/web/routes/invite.js index 0837de0..5ccf1f0 100644 --- a/src/web/routes/invite.js +++ b/src/web/routes/invite.js @@ -34,6 +34,39 @@ const schema = { /** @type {LRUCache} nonce to guild id */ const validNonce = new LRUCache({max: 200}) +function getChannelRoomsLinks(guildID, rooms) { + function getPosition(channel) { + let position = 0 + let looking = channel + while (looking.parent_id) { + looking = discord.channels.get(looking.parent_id) + position = looking.position * 1000 + } + if (channel.position) position += channel.position + return position + } + + let channelIDs = discord.guildChannelMap.get(guildID) + assert(channelIDs) + + let linkedChannels = select("channel_room", ["channel_id", "room_id", "name", "nick"], {channel_id: channelIDs}).all() + let linkedChannelsWithDetails = linkedChannels.map(c => ({channel: discord.channels.get(c.channel_id), ...c})).filter(c => c.channel) + let linkedChannelIDs = linkedChannelsWithDetails.map(c => c.channel_id) + linkedChannelsWithDetails.sort((a, b) => getPosition(a.channel) - getPosition(b.channel)) + + let unlinkedChannelIDs = channelIDs.filter(c => !linkedChannelIDs.includes(c)) + let unlinkedChannels = unlinkedChannelIDs.map(c => discord.channels.get(c)).filter(c => [0, 5].includes(c.type)) + unlinkedChannels.sort((a, b) => getPosition(a) - getPosition(b)) + + let linkedRoomIDs = linkedChannels.map(c => c.room_id) + let unlinkedRooms = rooms.filter(r => !linkedRoomIDs.includes(r.room_id) && !r.room_type) + // https://discord.com/developers/docs/topics/threads#active-archived-threads + // need to filter out linked archived threads from unlinkedRooms, will just do that by comparing against the name + unlinkedRooms = unlinkedRooms.filter(r => !r.name.match(/^\[(🔒)?⛓️\]/)) + + return {linkedChannelsWithDetails, unlinkedChannels, unlinkedRooms} +} + as.router.get("/guild", defineEventHandler(async event => { const {guild_id} = await getValidatedQuery(event, schema.guild.parse) const session = await useSession(event, {password: reg.as_token}) @@ -47,7 +80,8 @@ as.router.get("/guild", defineEventHandler(async event => { const mods = await api.getStateEvent(row.space_id, "m.room.power_levels", "") const banned = await api.getMembers(row.space_id, "ban") const rooms = await api.getFullHierarchy(row.space_id) - return pugSync.render(event, "guild.pug", {guild_id, nonce, mods, banned, rooms, ...row}) + const links = getChannelRoomsLinks(guild_id, rooms) + return pugSync.render(event, "guild.pug", {guild_id, nonce, mods, banned, rooms, ...links, ...row}) })) as.router.get("/invite", defineEventHandler(async event => { From 559d9329f25c35a3618d774927d5297cf4efb904 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sat, 30 Nov 2024 22:56:22 +1300 Subject: [PATCH 043/228] Fix voice messages not being delivered --- src/d2m/converters/message-to-event.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/d2m/converters/message-to-event.js b/src/d2m/converters/message-to-event.js index 251ce90..f2720bd 100644 --- a/src/d2m/converters/message-to-event.js +++ b/src/d2m/converters/message-to-event.js @@ -176,7 +176,7 @@ async function attachmentToEvent(mentions, attachment) { info: { mimetype: attachment.content_type, size: attachment.size, - duration: attachment.duration_secs ? attachment.duration_secs * 1000 : undefined + duration: attachment.duration_secs ? Math.round(attachment.duration_secs * 1000) : undefined } } } else { From bded9296afe11c30526cecbd184683c0d99112bd Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 2 Dec 2024 12:29:16 +1300 Subject: [PATCH 044/228] Fix guild page being broken when unlinked --- src/web/routes/invite.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/web/routes/invite.js b/src/web/routes/invite.js index 5ccf1f0..0f94fa7 100644 --- a/src/web/routes/invite.js +++ b/src/web/routes/invite.js @@ -55,7 +55,7 @@ function getChannelRoomsLinks(guildID, rooms) { linkedChannelsWithDetails.sort((a, b) => getPosition(a.channel) - getPosition(b.channel)) let unlinkedChannelIDs = channelIDs.filter(c => !linkedChannelIDs.includes(c)) - let unlinkedChannels = unlinkedChannelIDs.map(c => discord.channels.get(c)).filter(c => [0, 5].includes(c.type)) + let unlinkedChannels = unlinkedChannelIDs.map(c => discord.channels.get(c)).filter(c => c && [0, 5].includes(c.type)) unlinkedChannels.sort((a, b) => getPosition(a) - getPosition(b)) let linkedRoomIDs = linkedChannels.map(c => c.room_id) @@ -72,7 +72,8 @@ as.router.get("/guild", defineEventHandler(async event => { const session = await useSession(event, {password: reg.as_token}) const row = select("guild_space", ["space_id", "privacy_level"], {guild_id}).get() if (!guild_id || !row || !discord.guilds.has(guild_id) || !session.data.managedGuilds || !session.data.managedGuilds.includes(guild_id)) { - return pugSync.render(event, "guild.pug", {guild_id}) + const links = getChannelRoomsLinks(guild_id, []) + return pugSync.render(event, "guild.pug", {guild_id, ...links}) } const nonce = randomUUID() From a35860cb15888839b4c06ed2bc20a516a2de6cda Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 2 Dec 2024 12:43:00 +1300 Subject: [PATCH 045/228] Handle more guild page situations --- src/web/routes/invite.js | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/web/routes/invite.js b/src/web/routes/invite.js index 0f94fa7..83973c0 100644 --- a/src/web/routes/invite.js +++ b/src/web/routes/invite.js @@ -5,6 +5,7 @@ const {z} = require("zod") const {defineEventHandler, sendRedirect, useSession, createError, getValidatedQuery, readValidatedBody} = require("h3") const {randomUUID} = require("crypto") const {LRUCache} = require("lru-cache") +const Ty = require("../../types") const {discord, as, sync, select} = require("../../passthrough") /** @type {import("../pug-sync")} */ @@ -34,6 +35,10 @@ const schema = { /** @type {LRUCache} nonce to guild id */ const validNonce = new LRUCache({max: 200}) +/** + * @param {string} guildID + * @param {Ty.R.Hierarchy[]} rooms + */ function getChannelRoomsLinks(guildID, rooms) { function getPosition(channel) { let position = 0 @@ -62,7 +67,7 @@ function getChannelRoomsLinks(guildID, rooms) { let unlinkedRooms = rooms.filter(r => !linkedRoomIDs.includes(r.room_id) && !r.room_type) // https://discord.com/developers/docs/topics/threads#active-archived-threads // need to filter out linked archived threads from unlinkedRooms, will just do that by comparing against the name - unlinkedRooms = unlinkedRooms.filter(r => !r.name.match(/^\[(🔒)?⛓️\]/)) + unlinkedRooms = unlinkedRooms.filter(r => r.name && !r.name.match(/^\[(🔒)?⛓️\]/)) return {linkedChannelsWithDetails, unlinkedChannels, unlinkedRooms} } @@ -71,18 +76,27 @@ as.router.get("/guild", defineEventHandler(async event => { const {guild_id} = await getValidatedQuery(event, schema.guild.parse) const session = await useSession(event, {password: reg.as_token}) const row = select("guild_space", ["space_id", "privacy_level"], {guild_id}).get() - if (!guild_id || !row || !discord.guilds.has(guild_id) || !session.data.managedGuilds || !session.data.managedGuilds.includes(guild_id)) { - const links = getChannelRoomsLinks(guild_id, []) - return pugSync.render(event, "guild.pug", {guild_id, ...links}) + + // Permission problems + if (!guild_id || !discord.guilds.has(guild_id) || !session.data.managedGuilds || !session.data.managedGuilds.includes(guild_id)) { + return pugSync.render(event, "guild.pug", {guild_id}) } const nonce = randomUUID() validNonce.set(nonce, guild_id) + + // Unlinked guild + if (!row) { + const links = getChannelRoomsLinks(guild_id, []) + return pugSync.render(event, "guild.pug", {guild_id, nonce, ...links}) + } + + // Linked guild const mods = await api.getStateEvent(row.space_id, "m.room.power_levels", "") const banned = await api.getMembers(row.space_id, "ban") const rooms = await api.getFullHierarchy(row.space_id) const links = getChannelRoomsLinks(guild_id, rooms) - return pugSync.render(event, "guild.pug", {guild_id, nonce, mods, banned, rooms, ...links, ...row}) + return pugSync.render(event, "guild.pug", {guild_id, nonce, mods, banned, ...links, ...row}) })) as.router.get("/invite", defineEventHandler(async event => { From 88a232fb4a27875cd02bbf1f4a3e9fbd8cb9192c Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 2 Dec 2024 15:06:10 +1300 Subject: [PATCH 046/228] Cope if the username is already registered --- scripts/setup.js | 10 +--------- src/matrix/api.js | 19 +++++++++++++------ 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/scripts/setup.js b/scripts/setup.js index a8b068b..8db46a7 100644 --- a/scripts/setup.js +++ b/scripts/setup.js @@ -276,15 +276,7 @@ async function validateHomeserverOrigin(serverUrlPrompt, url) { console.log("✅ Database is ready...") // ensure appservice bot user is registered... - try { - await api.register(reg.sender_localpart) - } catch (e) { - if (e.errcode === "M_USER_IN_USE" || e.data?.error === "Internal server error") { - // "Internal server error" is the only OK error because older versions of Synapse say this if you try to register the same username twice. - } else { - throw e - } - } + await api.register(reg.sender_localpart) // upload initial images... const avatarUrl = await file.uploadDiscordFileToMxc("https://cadence.moe/friends/out_of_your_element.png") diff --git a/src/matrix/api.js b/src/matrix/api.js index 79dd7f0..a75f959 100644 --- a/src/matrix/api.js +++ b/src/matrix/api.js @@ -35,14 +35,21 @@ function path(p, mxid, otherParams = {}) { /** * @param {string} username - * @returns {Promise} */ -function register(username) { +async function register(username) { console.log(`[api] register: ${username}`) - return mreq.mreq("POST", "/client/v3/register", { - type: "m.login.application_service", - username - }) + try { + await mreq.mreq("POST", "/client/v3/register", { + type: "m.login.application_service", + username + }) + } catch (e) { + if (e.errcode === "M_USER_IN_USE" || e.data?.error === "Internal server error") { + // "Internal server error" is the only OK error because older versions of Synapse say this if you try to register the same username twice. + } else { + throw e + } + } } /** From e00ce22aadacc018846128182cfa67fae45fa5c4 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 2 Dec 2024 15:42:32 +1300 Subject: [PATCH 047/228] Replace into guild_active from homepage Allow user to change their mind about auto-create by redoing oauth flow. --- src/web/routes/oauth.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/web/routes/oauth.js b/src/web/routes/oauth.js index 2f12dd1..82aebe4 100644 --- a/src/web/routes/oauth.js +++ b/src/web/routes/oauth.js @@ -86,7 +86,7 @@ as.router.get("/oauth", defineEventHandler(async event => { // Set auto-create for the guild // @ts-ignore if (managedGuilds.includes(parsedQuery.data.guild_id)) { - db.prepare("INSERT OR IGNORE INTO guild_active (guild_id, autocreate) VALUES (?, ?)").run(parsedQuery.data.guild_id, +!session.data.selfService) + db.prepare("REPLACE INTO guild_active (guild_id, autocreate) VALUES (?, ?)").run(parsedQuery.data.guild_id, +!session.data.selfService) } if (parsedQuery.data.guild_id) { From 4f040e40d6f1d621f60e35305eaa056ba917001c Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 2 Dec 2024 16:33:18 +1300 Subject: [PATCH 048/228] Autocreate space if autocreating the room --- docs/self-service-room-creation-rules.md | 3 --- src/d2m/actions/create-room.js | 9 +++++---- src/d2m/actions/create-space.js | 2 +- src/d2m/converters/message-to-event.test.js | 2 +- 4 files changed, 7 insertions(+), 9 deletions(-) diff --git a/docs/self-service-room-creation-rules.md b/docs/self-service-room-creation-rules.md index c47ca14..70892fc 100644 --- a/docs/self-service-room-creation-rules.md +++ b/docs/self-service-room-creation-rules.md @@ -61,8 +61,6 @@ So there will be 3 states of whether a guild is self-service or not. At first, i Pressing buttons on web or using the /invite command on a guild will insert a row into guild_active, allowing it to be bridged. -One more thing. Before v3, when a Matrix room was autocreated it would autocreate the space as well, if it needed to. But now, since nothing will be created until the user takes an action, the guild will always be created directly in response to a request. So room creation can now trust that the guild exists already. - So here's all the technical changes needed to support self-service in v3: - New guild_active table showing whether, and how, a guild is bridged. @@ -70,5 +68,4 @@ So here's all the technical changes needed to support self-service in v3: - When bot is added through "easy mode" web button, REPLACE INTO state 1 and ensureSpace. - When bot is added through "self-service" web button, REPLACE INTO state 0. - Event dispatcher will only ensureRoom if the guild_active state is 1. -- createRoom can trust that the space exists because we check that in a calling function. - createRoom will only create other dependencies if the guild is autocreate. diff --git a/src/d2m/actions/create-room.js b/src/d2m/actions/create-room.js index 2d8d1af..ece8ef7 100644 --- a/src/d2m/actions/create-room.js +++ b/src/d2m/actions/create-room.js @@ -15,6 +15,8 @@ const api = sync.require("../../matrix/api") const ks = sync.require("../../matrix/kstate") /** @type {import("../../discord/utils")} */ const utils = sync.require("../../discord/utils") +/** @type {import("./create-space")} */ +const createSpace = sync.require("./create-space") /** * There are 3 levels of room privacy: @@ -93,11 +95,9 @@ function convertNameAndTopic(channel, guild, customName) { async function channelToKState(channel, guild, di) { // @ts-ignore const parentChannel = discord.channels.get(channel.parent_id) - const guildRow = select("guild_space", ["space_id", "privacy_level"], {guild_id: guild.id}).get() - assert(guildRow) /** Used for membership/permission checks. */ - let guildSpaceID = guildRow.space_id + const guildSpaceID = await createSpace.ensureSpace(guild) /** Used as the literal parent on Matrix, for categorisation. Will be the same as `guildSpaceID` unless it's a forum channel's thread, in which case a different space is used to group those threads. */ let parentSpaceID = guildSpaceID if (parentChannel?.type === DiscordTypes.ChannelType.GuildForum) { @@ -117,7 +117,8 @@ async function channelToKState(channel, guild, di) { avatarEventContent.url = {$url: file.guildIcon(guild)} } - const privacyLevel = guildRow.privacy_level + const privacyLevel = select("guild_space", "privacy_level", {guild_id: guild.id}).pluck().get() + assert(privacyLevel != null) // already ensured the space exists let history_visibility = PRIVACY_ENUMS.ROOM_HISTORY_VISIBILITY[privacyLevel] if (channel["thread_metadata"]) history_visibility = "world_readable" diff --git a/src/d2m/actions/create-space.js b/src/d2m/actions/create-space.js index 0c3d5e3..04d1413 100644 --- a/src/d2m/actions/create-space.js +++ b/src/d2m/actions/create-space.js @@ -93,7 +93,7 @@ async function _syncSpace(guild, shouldActuallySync) { if (!row) { const autocreate = select("guild_active", "autocreate", {guild_id: guild.id}).pluck().get() - assert.equal(autocreate, 1, `refusing to implicitly create guild ${guild.id}. set the guild_active data first before calling ensureSpace/syncSpace.`) + assert.equal(autocreate, 1, `refusing to implicitly create a space for guild ${guild.id}. set the guild_active data first before calling ensureSpace/syncSpace.`) const creation = (async () => { const guildKState = await guildToKState(guild, createRoom.DEFAULT_PRIVACY_LEVEL) // New spaces will have to use the default privacy level; we obviously can't look up the existing entry diff --git a/src/d2m/converters/message-to-event.test.js b/src/d2m/converters/message-to-event.test.js index 50f0908..6f77744 100644 --- a/src/d2m/converters/message-to-event.test.js +++ b/src/d2m/converters/message-to-event.test.js @@ -575,7 +575,7 @@ test("message2event: voice message", async t => { external_url: "https://bridge.example.org/download/discordcdn/1099031887500034088/1112476845502365786/voice-message.ogg", filename: "voice-message.ogg", info: { - duration: 3960.0000381469727, + duration: 3960, mimetype: "audio/ogg", size: 10584, }, From bf01db13d66f4251dda4f20f3ef16a44f593d4ab Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Tue, 3 Dec 2024 01:11:53 +1300 Subject: [PATCH 049/228] Check server before checking well-known --- scripts/setup.js | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/scripts/setup.js b/scripts/setup.js index 8db46a7..2782ad8 100644 --- a/scripts/setup.js +++ b/scripts/setup.js @@ -68,10 +68,7 @@ async function uploadAutoEmoji(snow, guild, name, filename) { return emoji } -async function validateHomeserverOrigin(serverUrlPrompt, url) { - if (!url.match(/^https?:\/\//)) return "Must be a URL" - if (url.match(/\/$/)) return "Must not end with a slash" - process.stdout.write(magenta(" checking, please wait...")) +async function suggestWellKnown(serverUrlPrompt, url, otherwise) { try { var json = await fetch(`${url}/.well-known/matrix/client`).then(res => res.json()) let baseURL = json["m.homeserver"].base_url.replace(/\/$/, "") @@ -80,19 +77,28 @@ async function validateHomeserverOrigin(serverUrlPrompt, url) { return `Did you mean: ${bold(baseURL)}? (Enter to accept)` } } catch (e) {} + return otherwise +} + +async function validateHomeserverOrigin(serverUrlPrompt, url) { + if (!url.match(/^https?:\/\//)) return "Must be a URL" + if (url.match(/\/$/)) return "Must not end with a slash" + process.stdout.write(magenta(" checking, please wait...")) try { var res = await fetch(`${url}/_matrix/client/versions`) + if (res.status !== 200) { + return suggestWellKnown(serverUrlPrompt, url, `There is no Matrix server at that URL (${url}/_matrix/client/versions returned ${res.status})`) + } } catch (e) { return e.message } - if (res.status !== 200) return `There is no Matrix server at that URL (${url}/_matrix/client/versions returned ${res.status})` try { var json = await res.json() if (!Array.isArray(json?.versions) || !json.versions.includes("v1.11")) { return `OOYE needs Matrix version v1.11, but ${url} doesn't support this` } } catch (e) { - return `There is no Matrix server at that URL (${url}/_matrix/client/versions is not JSON)` + return suggestWellKnown(serverUrlPrompt, url, `There is no Matrix server at that URL (${url}/_matrix/client/versions is not JSON)`) } return true } From 53379a962dbfd63265338e384121d77451ae4fed Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sat, 7 Dec 2024 19:20:01 +1300 Subject: [PATCH 050/228] This has never actually occurred --- src/m2d/converters/event-to-message.js | 1 - 1 file changed, 1 deletion(-) diff --git a/src/m2d/converters/event-to-message.js b/src/m2d/converters/event-to-message.js index 346d8c9..ebbe9e1 100644 --- a/src/m2d/converters/event-to-message.js +++ b/src/m2d/converters/event-to-message.js @@ -600,7 +600,6 @@ async function eventToMessage(event, guild, di) { contentPreview = ": " + contentPreviewChunks[0] if (contentPreviewChunks.length > 1) contentPreview = contentPreview.replace(/[,.']$/, "") + "..." } else { - console.log("Unable to generate reply preview for this replied-to event because we stripped all of it:", repliedToEvent) contentPreview = "" } } From c599dff5907d9579676e5a03fe1fdf0934f56114 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Tue, 24 Dec 2024 01:06:19 +1300 Subject: [PATCH 051/228] Tests and coverage for web --- package.json | 2 +- src/types.d.ts | 4 +- src/web/pug-sync.js | 2 + src/web/pug/guild.pug | 241 ++++++++++-------------- src/web/pug/guild_access_denied.pug | 22 +++ src/web/routes/download-discord.js | 14 +- src/web/routes/download-discord.test.js | 49 +++++ src/web/routes/download-matrix.js | 15 +- src/web/routes/download-matrix.test.js | 36 ++++ src/web/routes/{invite.js => guild.js} | 31 +-- src/web/routes/guild.test.js | 199 +++++++++++++++++++ src/web/routes/qr.test.js | 17 ++ src/web/server.js | 3 +- src/web/server.test.js | 32 ++++ test/ooye-test-data.sql | 12 +- test/test.js | 16 +- test/web.js | 69 +++++++ 17 files changed, 593 insertions(+), 171 deletions(-) create mode 100644 src/web/pug/guild_access_denied.pug create mode 100644 src/web/routes/download-discord.test.js create mode 100644 src/web/routes/download-matrix.test.js rename src/web/routes/{invite.js => guild.js} (85%) create mode 100644 src/web/routes/guild.test.js create mode 100644 src/web/routes/qr.test.js create mode 100644 src/web/server.test.js create mode 100644 test/web.js diff --git a/package.json b/package.json index fb7fbc9..e79a6b0 100644 --- a/package.json +++ b/package.json @@ -64,7 +64,7 @@ "start": "node start.js", "setup": "node scripts/setup.js", "addbot": "node addbot.js", - "test": "cross-env FORCE_COLOR=true supertape --no-check-assertions-count --format tap test/test.js | tap-dot", + "test": "cross-env FORCE_COLOR=true supertape --no-check-assertions-count --format tap --no-worker test/test.js | tap-dot", "test-slow": "cross-env FORCE_COLOR=true supertape --no-check-assertions-count --format tap --no-worker test/test.js -- --slow | tap-dot", "cover": "c8 -o test/coverage --skip-full -x db/migrations -x src/matrix/file.js -x src/matrix/api.js -x src/matrix/mreq.js -x src/d2m/converters/rlottie-wasm.js -r html -r text supertape --no-check-assertions-count --format fail --no-worker test/test.js -- --slow" } diff --git a/src/types.d.ts b/src/types.d.ts index 576bb59..178a560 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -114,7 +114,7 @@ export namespace Event { sender: string content: T origin_server_ts: number - unsigned: any + unsigned?: any event_id: string } @@ -137,7 +137,7 @@ export namespace Event { content: any state_key: string origin_server_ts: number - unsigned: any + unsigned?: any event_id: string user_id: string age: number diff --git a/src/web/pug-sync.js b/src/web/pug-sync.js index 32e7acc..aa1a945 100644 --- a/src/web/pug-sync.js +++ b/src/web/pug-sync.js @@ -42,6 +42,7 @@ function render(event, filename, locals) { {session} // Session is always session because it has to be trusted )) }) + /* c8 ignore start */ } catch (e) { pugCache.set(path, async (event) => { setResponseStatus(event, 500, "Internal Template Error") @@ -49,6 +50,7 @@ function render(event, filename, locals) { return e.toString() }) } + /* c8 ignore stop */ } if (!pugCache.has(path)) { diff --git a/src/web/pug/guild.pug b/src/web/pug/guild.pug index 29ad9ad..481ad01 100644 --- a/src/web/pug/guild.pug +++ b/src/web/pug/guild.pug @@ -11,7 +11,7 @@ mixin badge-private | Private mixin discord(channel, radio=false) - - let permissions = dUtils.getPermissions([], discord.guilds.get(channel.guild_id).roles, "", channel.permission_overwrites) + - let permissions = dUtils.getPermissions([], discord.guilds.get(channel.guild_id).roles, null, channel.permission_overwrites) .s-user-card.s-user-card__small if !dUtils.hasPermission(permissions, DiscordTypes.PermissionFlagsBits.ViewChannel) != icons.Icons.IconLock @@ -49,153 +49,110 @@ mixin matrix(row, radio=false, badge="") +badge-private block body - if !guild_id && session.data.managedGuilds - .s-empty-state.wmx4.p48 - != icons.Spots.SpotEmptyXL - p Select a server from the top right corner to continue. - p If the server you're looking for isn't there, try #[a(href="/oauth?action=add") logging in again.] + .s-page-title.mb24 + h1.s-page-title--header= guild.name - else if !session.data.managedGuilds - .s-empty-state.wmx4.p48 - != icons.Spots.SpotEmptyXL - p You need to log in to manage your servers. - a.s-btn.s-btn__icon.s-btn__filled(href="/oauth") - != icons.Icons.IconDiscord - = ` Log in with Discord` + .d-flex.g16 + .fl-grow1 + h2.fs-headline1 Invite a Matrix user - else if !discord.guilds.has(guild_id) || !session.data.managedGuilds || !session.data.managedGuilds.includes(guild_id) - .s-empty-state.wmx4.p48 - != icons.Spots.SpotAlertXL - p Either the selected server doesn't exist, or you don't have the Manage Server permission on Discord. - p If you've checked your permissions, try #[a(href="/oauth") logging in again.] - - else - - let guild = discord.guilds.get(guild_id) - - .s-page-title.mb24 - h1.s-page-title--header= guild.name - - .d-flex.g16 - .fl-grow1 - h2.fs-headline1 Invite a Matrix user - - form.d-grid.g-af-column.gy4.gx8.jc-start(method="post" action="/api/invite" style="grid-template-rows: repeat(2, auto)") - label.s-label(for="mxid") Matrix ID - input.fl-grow1.s-input.wmx3#mxid(name="mxid" required placeholder="@user:example.org") - label.s-label(for="permissions") Permissions - .s-select - select#permissions(name="permissions") - option(value="default") Default - option(value="moderator") Moderator - input(type="hidden" name="guild_id" value=guild_id) - .grid--row-start2 - button.s-btn.s-btn__filled.htmx-indicator Invite - div - - - let size = 105 - let p = new URLSearchParams() - p.set("data", `https://bridge.cadence.moe/invite?nonce=${nonce}`) - img(width=size height=size src=`/qr?${p}`) - - h2.mt48.fs-headline1 Moderation - - h2.mt48.fs-headline1 Matrix setup - - h3.mt32.fs-category Linked channels - - .s-card.bs-sm.p0 - .s-table-container - table.s-table.s-table__bx-simple - each row in linkedChannelsWithDetails - tr - td.w40: +discord(row.channel) - td.p2: button.s-btn.s-btn__muted.s-btn__xs!= icons.Icons.IconLinkSm - td: +matrix(row) - else - tr - td(colspan="3") - .s-empty-state No channels linked between Discord and Matrix yet... - - h3.mt32.fs-category Auto-create - .s-card - form.d-flex.ai-center.g8 - label.s-label.fl-grow1(for="autocreate") - | Create new Matrix rooms automatically - p.s-description If you want, OOYE can automatically create new Matrix rooms and link them when an unlinked Discord channel is spoken in. - - let value = !!select("guild_active", "autocreate", {guild_id}).pluck().get() + form.d-grid.g-af-column.gy4.gx8.jc-start(method="post" action="/api/invite" style="grid-template-rows: repeat(2, auto)") + label.s-label(for="mxid") Matrix ID + input.fl-grow1.s-input.wmx3#mxid(name="mxid" required placeholder="@user:example.org") + label.s-label(for="permissions") Permissions + .s-select + select#permissions(name="permissions") + option(value="default") Default + option(value="moderator") Moderator input(type="hidden" name="guild_id" value=guild_id) - input.s-toggle-switch.order-last#autocreate(name="autocreate" type="checkbox" hx-post="/api/autocreate" hx-indicator="#autocreate-loading" hx-disabled-elt="this" checked=value) - .is-loading#autocreate-loading + .grid--row-start2 + button.s-btn.s-btn__filled.htmx-indicator Invite + div + - + let size = 105 + let p = new URLSearchParams() + p.set("data", `https://bridge.cadence.moe/invite?nonce=${nonce}`) + img(width=size height=size src=`/qr?${p}`) - h3.mt32.fs-category Privacy level - .s-card - form(hx-post="/api/privacy-level" hx-trigger="change" hx-indicator="#privacy-level-loading" hx-disabled-elt="this") - input(type="hidden" name="guild_id" value=guild_id) - .d-flex.ai-center.mb4 - label.s-label.fl-grow1 - | How people can join on Matrix - span.is-loading#privacy-level-loading - .s-toggle-switch.s-toggle-switch__multiple.s-toggle-switch__incremental.d-grid.gx16.ai-center(style="grid-template-columns: auto 1fr") - input(type="radio" name="level" value="directory" id="privacy-level-directory" checked=(privacy_level === 2)) - label.d-flex.gx8.jc-center.grid--row-start3(for="privacy-level-directory") - != icons.Icons.IconPlusSm - != icons.Icons.IconInternationalSm - .fl-grow1 Directory + h2.mt48.fs-headline1 Moderation - input(type="radio" name="level" value="link" id="privacy-level-link" checked=(privacy_level === 1)) - label.d-flex.gx8.jc-center.grid--row-start2(for="privacy-level-link") - != icons.Icons.IconPlusSm - != icons.Icons.IconLinkSm - .fl-grow1 Link + h2.mt48.fs-headline1 Matrix setup - input(type="radio" name="level" value="invite" id="privacy-level-invite" checked=(privacy_level === 0)) - label.d-flex.gx8.jc-center.grid--row-start1(for="privacy-level-invite") - svg.svg-icon(width="14" height="14" viewBox="0 0 14 14") - != icons.Icons.IconLockSm - .fl-grow1 Invite + h3.mt32.fs-category Linked channels - p.s-description.m0 In-app direct invite from another user - p.s-description.m0 Shareable invite links, like Discord - p.s-description.m0 Publicly listed in directory, like Discord server discovery - - - //- - fieldset.s-check-group - legend.s-label How people can join on Matrix - .s-check-control - input.s-radio(type="radio" name="privacy-level" id="privacy-level-invite" value="invite" checked) - label.s-label(for="privacy-level-invite") - | Invite - p.s-description In-app direct invite on Matrix; invite command on Discord; invite form on web - .s-check-control - input.s-radio(type="radio" name="privacy-level" id="privacy-level-link" value="link") - label.s-label(for="privacy-level-link") - | Link - p.s-description All of the above, and shareable invite links (like Discord) - .s-check-control - input.s-radio(type="radio" name="privacy-level" id="privacy-level-directory" value="directory") - label.s-label(for="privacy-level-directory") - | Public - p.s-description All of the above, and publicly visible in the Matrix space directory (like Server Discovery) - - h3.mt32.fs-category Manually link channels - form.d-flex.g16.ai-start(hx-post="/api/privacy-level" hx-trigger="submit" hx-disabled-elt="this") - .fl-grow2.s-btn-group.fd-column.w40 - each channel in unlinkedChannels - input.s-btn--radio(type="radio" name="discord" id=channel.id value=channel.id) - label.s-btn.s-btn__muted.ta-left.truncate(for=channel.id) - +discord(channel, true, "Announcement") + .s-card.bs-sm.p0 + .s-table-container + table.s-table.s-table__bx-simple + each row in linkedChannelsWithDetails + tr + td.w40: +discord(row.channel) + td.p2: button.s-btn.s-btn__muted.s-btn__xs!= icons.Icons.IconLinkSm + td: +matrix(row) else - .s-empty-state.p8 All Discord channels are linked. - .fl-grow1.s-btn-group.fd-column.w30 - each room in unlinkedRooms - input.s-btn--radio(type="radio" name="matrix" id=room.room_id value=room.room_id) - label.s-btn.s-btn__muted.ta-left.truncate(for=room.room_id) - +matrix(room, true) - else - .s-empty-state.p8 All Matrix rooms are linked. + tr + td(colspan="3") + .s-empty-state No channels linked between Discord and Matrix yet... + + h3.mt32.fs-category Auto-create + .s-card + form.d-flex.ai-center.g8 + label.s-label.fl-grow1(for="autocreate") + | Create new Matrix rooms automatically + p.s-description If you want, OOYE can automatically create new Matrix rooms and link them when an unlinked Discord channel is spoken in. + - let value = !!select("guild_active", "autocreate", {guild_id}).pluck().get() input(type="hidden" name="guild_id" value=guild_id) - div - button.s-btn.s-btn__icon.s-btn__filled.htmx-indicator - != icons.Icons.IconMerge - = ` Link` + input.s-toggle-switch.order-last#autocreate(name="autocreate" type="checkbox" hx-post="/api/autocreate" hx-indicator="#autocreate-loading" hx-disabled-elt="this" checked=value) + .is-loading#autocreate-loading + + h3.mt32.fs-category Privacy level + .s-card + form(hx-post="/api/privacy-level" hx-trigger="change" hx-indicator="#privacy-level-loading" hx-disabled-elt="this") + input(type="hidden" name="guild_id" value=guild_id) + .d-flex.ai-center.mb4 + label.s-label.fl-grow1 + | How people can join on Matrix + span.is-loading#privacy-level-loading + .s-toggle-switch.s-toggle-switch__multiple.s-toggle-switch__incremental.d-grid.gx16.ai-center(style="grid-template-columns: auto 1fr") + input(type="radio" name="level" value="directory" id="privacy-level-directory" checked=(privacy_level === 2)) + label.d-flex.gx8.jc-center.grid--row-start3(for="privacy-level-directory") + != icons.Icons.IconPlusSm + != icons.Icons.IconInternationalSm + .fl-grow1 Directory + + input(type="radio" name="level" value="link" id="privacy-level-link" checked=(privacy_level === 1)) + label.d-flex.gx8.jc-center.grid--row-start2(for="privacy-level-link") + != icons.Icons.IconPlusSm + != icons.Icons.IconLinkSm + .fl-grow1 Link + + input(type="radio" name="level" value="invite" id="privacy-level-invite" checked=(privacy_level === 0)) + label.d-flex.gx8.jc-center.grid--row-start1(for="privacy-level-invite") + svg.svg-icon(width="14" height="14" viewBox="0 0 14 14") + != icons.Icons.IconLockSm + .fl-grow1 Invite + + p.s-description.m0 In-app direct invite from another user + p.s-description.m0 Shareable invite links, like Discord + p.s-description.m0 Publicly listed in directory, like Discord server discovery + + h3.mt32.fs-category Manually link channels + form.d-flex.g16.ai-start(hx-post="/api/privacy-level" hx-trigger="submit" hx-disabled-elt="this") + .fl-grow2.s-btn-group.fd-column.w40 + each channel in unlinkedChannels + input.s-btn--radio(type="radio" name="discord" id=channel.id value=channel.id) + label.s-btn.s-btn__muted.ta-left.truncate(for=channel.id) + +discord(channel, true, "Announcement") + else + .s-empty-state.p8 All Discord channels are linked. + .fl-grow1.s-btn-group.fd-column.w30 + each room in unlinkedRooms + input.s-btn--radio(type="radio" name="matrix" id=room.room_id value=room.room_id) + label.s-btn.s-btn__muted.ta-left.truncate(for=room.room_id) + +matrix(room, true) + else + .s-empty-state.p8 All Matrix rooms are linked. + input(type="hidden" name="guild_id" value=guild_id) + div + button.s-btn.s-btn__icon.s-btn__filled.htmx-indicator + != icons.Icons.IconMerge + = ` Link` diff --git a/src/web/pug/guild_access_denied.pug b/src/web/pug/guild_access_denied.pug new file mode 100644 index 0000000..2305605 --- /dev/null +++ b/src/web/pug/guild_access_denied.pug @@ -0,0 +1,22 @@ +extends includes/template.pug + +block body + if !session.data.managedGuilds + .s-empty-state.wmx4.p48 + != icons.Spots.SpotEmptyXL + p You need to log in to manage your servers. + a.s-btn.s-btn__icon.s-btn__filled(href="/oauth") + != icons.Icons.IconDiscord + = ` Log in with Discord` + + else if !guild_id + .s-empty-state.wmx4.p48 + != icons.Spots.SpotEmptyXL + p Select a server from the top right corner to continue. + p If the server you're looking for isn't there, try #[a(href="/oauth?action=add") logging in again.] + + else if !discord.guilds.has(guild_id) || !session.data.managedGuilds.includes(guild_id) + .s-empty-state.wmx4.p48 + != icons.Spots.SpotAlertXL + p Either the selected server doesn't exist, or you don't have the Manage Server permission on Discord. + p If you've checked your permissions, try #[a(href="/oauth") logging in again.] diff --git a/src/web/routes/download-discord.js b/src/web/routes/download-discord.js index ee64074..bbf33b0 100644 --- a/src/web/routes/download-discord.js +++ b/src/web/routes/download-discord.js @@ -1,7 +1,7 @@ // @ts-check const assert = require("assert/strict") -const {defineEventHandler, getValidatedRouterParams, sendRedirect, createError} = require("h3") +const {defineEventHandler, getValidatedRouterParams, sendRedirect, createError, H3Event} = require("h3") const {z} = require("zod") /** @type {import("xxhash-wasm").XXHashAPI} */ // @ts-ignore @@ -19,6 +19,15 @@ const schema = { }) } +/** + * @param {H3Event} event + * @returns {import("snowtransfer").SnowTransfer} + */ +function getSnow(event) { + /* c8 ignore next */ + return event.context.snow || discord.snow +} + /** @type {Map>} */ const cache = new Map() @@ -56,7 +65,8 @@ function defineMediaProxyHandler(domain) { if (!timeUntilExpiry(refreshed)) promise = undefined } if (!promise) { - promise = discord.snow.channel.refreshAttachmentURLs([url]).then(x => x.refreshed_urls[0].refreshed) + const snow = getSnow(event) + promise = snow.channel.refreshAttachmentURLs([url]).then(x => x.refreshed_urls[0].refreshed) cache.set(url, promise) refreshed = await promise const time = timeUntilExpiry(refreshed) diff --git a/src/web/routes/download-discord.test.js b/src/web/routes/download-discord.test.js new file mode 100644 index 0000000..b0b0077 --- /dev/null +++ b/src/web/routes/download-discord.test.js @@ -0,0 +1,49 @@ +// @ts-check + +const tryToCatch = require("try-to-catch") +const {test} = require("supertape") +const {router} = require("../../../test/web") +const {MatrixServerError} = require("../../matrix/mreq") + +const snow = { + channel: { + async refreshAttachmentURLs(attachments) { + if (typeof attachments === "string") attachments = [attachments] + return { + refreshed_urls: attachments.map(a => ({ + original: a, + refreshed: a + `?ex=${Math.floor(Date.now() / 1000 + 3600).toString(16)}` + })) + } + } + } +} + +test("web download discord: access denied if not a known attachment", async t => { + const [error] = await tryToCatch(() => + router.test("get", "/download/discordcdn/:channel_id/:attachment_id/:file_name", { + params: { + channel_id: "1", + attachment_id: "2", + file_name: "image.png" + }, + snow + }) + ) + t.ok(error) +}) + +test("web download discord: works if a known attachment", async t => { + const event = {} + await router.test("get", "/download/discordcdn/:channel_id/:attachment_id/:file_name", { + params: { + channel_id: "655216173696286746", + attachment_id: "1314358913482621010", + file_name: "image.png" + }, + event, + snow + }) + t.equal(event.node.res.statusCode, 302) + t.match(event.node.res.getHeader("location"), /https:\/\/cdn.discordapp.com\/attachments\/655216173696286746\/1314358913482621010\/image\.png\?ex=/) +}) diff --git a/src/web/routes/download-matrix.js b/src/web/routes/download-matrix.js index f996716..8f790c5 100644 --- a/src/web/routes/download-matrix.js +++ b/src/web/routes/download-matrix.js @@ -1,7 +1,7 @@ // @ts-check const assert = require("assert/strict") -const {defineEventHandler, getValidatedRouterParams, setResponseStatus, setResponseHeader, sendStream, createError} = require("h3") +const {defineEventHandler, getValidatedRouterParams, setResponseStatus, setResponseHeader, sendStream, createError, H3Event} = require("h3") const {z} = require("zod") /** @type {import("xxhash-wasm").XXHashAPI} */ // @ts-ignore @@ -11,9 +11,6 @@ require("xxhash-wasm")().then(h => hasher = h) const {sync, as, select} = require("../../passthrough") -/** @type {import("../../matrix/api")} */ -const api = sync.require("../../matrix/api") - const schema = { params: z.object({ server_name: z.string(), @@ -21,6 +18,15 @@ const schema = { }) } +/** + * @param {H3Event} event + * @returns {import("../../matrix/api")} + */ +function getAPI(event) { + /* c8 ignore next */ + return event.context.api || sync.require("../../matrix/api") +} + as.router.get(`/download/matrix/:server_name/:media_id`, defineEventHandler(async event => { const params = await getValidatedRouterParams(event, schema.params.parse) @@ -36,6 +42,7 @@ as.router.get(`/download/matrix/:server_name/:media_id`, defineEventHandler(asyn }) } + const api = getAPI(event) const res = await api.getMedia(`mxc://${params.server_name}/${params.media_id}`) const contentType = res.headers.get("content-type") diff --git a/src/web/routes/download-matrix.test.js b/src/web/routes/download-matrix.test.js new file mode 100644 index 0000000..d44271a --- /dev/null +++ b/src/web/routes/download-matrix.test.js @@ -0,0 +1,36 @@ +// @ts-check + +const tryToCatch = require("try-to-catch") +const {test} = require("supertape") +const {router} = require("../../../test/web") +const fetch = require("node-fetch") + +test("web download matrix: access denied if not a known attachment", async t => { + const [error] = await tryToCatch(() => + router.test("get", "/download/matrix/:server_name/:media_id", { + params: { + server_name: "cadence.moe", + media_id: "1" + } + }) + ) + t.ok(error) +}) + +test("web download matrix: works if a known attachment", async t => { + const event = {} + await router.test("get", "/download/matrix/:server_name/:media_id", { + params: { + server_name: "cadence.moe", + media_id: "KrwlqopRyMxnEBcWDgpJZPxh", + }, + event, + api: { + async getMedia(mxc, init) { + return new fetch.Response("", {status: 200, headers: {"content-type": "image/png"}}) + } + } + }) + t.equal(event.node.res.statusCode, 200) + t.equal(event.node.res.getHeader("content-type"), "image/png") +}) diff --git a/src/web/routes/invite.js b/src/web/routes/guild.js similarity index 85% rename from src/web/routes/invite.js rename to src/web/routes/guild.js index 83973c0..fe24483 100644 --- a/src/web/routes/invite.js +++ b/src/web/routes/guild.js @@ -2,7 +2,7 @@ const assert = require("assert/strict") const {z} = require("zod") -const {defineEventHandler, sendRedirect, useSession, createError, getValidatedQuery, readValidatedBody} = require("h3") +const {H3Event, defineEventHandler, sendRedirect, useSession, createError, getValidatedQuery, readValidatedBody} = require("h3") const {randomUUID} = require("crypto") const {LRUCache} = require("lru-cache") const Ty = require("../../types") @@ -14,9 +14,6 @@ const pugSync = sync.require("../pug-sync") const createSpace = sync.require("../../d2m/actions/create-space") const {reg} = require("../../matrix/read-registration") -/** @type {import("../../matrix/api")} */ -const api = sync.require("../../matrix/api") - const schema = { guild: z.object({ guild_id: z.string().optional() @@ -32,6 +29,15 @@ const schema = { }) } +/** + * @param {H3Event} event + * @returns {import("../../matrix/api")} + */ +function getAPI(event) { + /* c8 ignore next */ + return event.context.api || sync.require("../../matrix/api") +} + /** @type {LRUCache} nonce to guild id */ const validNonce = new LRUCache({max: 200}) @@ -76,10 +82,12 @@ as.router.get("/guild", defineEventHandler(async event => { const {guild_id} = await getValidatedQuery(event, schema.guild.parse) const session = await useSession(event, {password: reg.as_token}) const row = select("guild_space", ["space_id", "privacy_level"], {guild_id}).get() + // @ts-ignore + const guild = discord.guilds.get(guild_id) // Permission problems - if (!guild_id || !discord.guilds.has(guild_id) || !session.data.managedGuilds || !session.data.managedGuilds.includes(guild_id)) { - return pugSync.render(event, "guild.pug", {guild_id}) + if (!guild_id || !guild || !session.data.managedGuilds || !session.data.managedGuilds.includes(guild_id)) { + return pugSync.render(event, "guild_access_denied.pug", {guild_id}) } const nonce = randomUUID() @@ -92,11 +100,12 @@ as.router.get("/guild", defineEventHandler(async event => { } // Linked guild + const api = getAPI(event) const mods = await api.getStateEvent(row.space_id, "m.room.power_levels", "") const banned = await api.getMembers(row.space_id, "ban") const rooms = await api.getFullHierarchy(row.space_id) const links = getChannelRoomsLinks(guild_id, rooms) - return pugSync.render(event, "guild.pug", {guild_id, nonce, mods, banned, ...links, ...row}) + return pugSync.render(event, "guild.pug", {guild, guild_id, nonce, mods, banned, ...links, ...row}) })) as.router.get("/invite", defineEventHandler(async event => { @@ -110,6 +119,7 @@ as.router.get("/invite", defineEventHandler(async event => { as.router.post("/api/invite", defineEventHandler(async event => { const parsedBody = await readValidatedBody(event, schema.invite.parse) const session = await useSession(event, {password: reg.as_token}) + const api = getAPI(event) // Check guild ID or nonce if (parsedBody.guild_id) { @@ -136,15 +146,14 @@ as.router.post("/api/invite", defineEventHandler(async event => { spaceMember = await api.getStateEvent(spaceID, "m.room.member", parsedBody.mxid) } catch (e) {} - if (!spaceMember || spaceMember.membership !== "invite" || spaceMember.membership !== "join") { + if (!spaceMember || !["invite", "join"].includes(spaceMember.membership)) { // Invite await api.inviteToRoom(spaceID, parsedBody.mxid) } // Permissions - if (parsedBody.permissions === "moderator") { - await api.setUserPowerCascade(spaceID, parsedBody.mxid, 50) - } + const powerLevel = parsedBody.permissions === "moderator" ? 50 : 0 + await api.setUserPowerCascade(spaceID, parsedBody.mxid, powerLevel) if (parsedBody.guild_id) { return sendRedirect(event, `/guild?guild_id=${guild_id}`, 302) diff --git a/src/web/routes/guild.test.js b/src/web/routes/guild.test.js new file mode 100644 index 0000000..b5b4080 --- /dev/null +++ b/src/web/routes/guild.test.js @@ -0,0 +1,199 @@ +// @ts-check + +const tryToCatch = require("try-to-catch") +const {test} = require("supertape") +const {router} = require("../../../test/web") +const {MatrixServerError} = require("../../matrix/mreq") + +let nonce + +test("web guild: access denied when not logged in", async t => { + const content = await router.test("get", "/guild?guild_id=112760669178241024", { + sessionData: { + }, + }) + t.match(content, /You need to log in to manage your servers./) +}) + +test("web guild: asks to select guild if not selected", async t => { + const content = await router.test("get", "/guild", { + sessionData: { + managedGuilds: [] + }, + }) + t.match(content, /Select a server from the top right corner to continue./) +}) + +test("web guild: access denied when guild id messed up", async t => { + const content = await router.test("get", "/guild?guild_id=1", { + sessionData: { + managedGuilds: [] + }, + }) + t.match(content, /the selected server doesn't exist/) +}) + + + + +test("web invite: access denied with invalid nonce", async t => { + const content = await router.test("get", "/invite?nonce=1") + t.match(content, /This QR code has expired./) +}) + +test("web guild: can view guild", async t => { + const content = await router.test("get", "/guild?guild_id=112760669178241024", { + sessionData: { + managedGuilds: ["112760669178241024"] + }, + api: { + async getStateEvent(roomID, type, key) { + return {} + }, + async getMembers(roomID, membership) { + return {chunk: []} + }, + async getFullHierarchy(roomID) { + return [] + } + } + }) + t.match(content, / { + const content = await router.test("get", `/invite?nonce=${nonce}`) + t.match(content, /Invite a Matrix user/) +}) + + + + +test("api invite: access denied with nothing", async t => { + const [error] = await tryToCatch(() => + router.test("post", `/api/invite`, { + body: { + mxid: "@cadence:cadence.moe", + permissions: "moderator" + } + }) + ) + t.equal(error.message, "Missing guild ID") +}) + +test("api invite: access denied when not in guild", async t => { + const [error] = await tryToCatch(() => + router.test("post", `/api/invite`, { + body: { + mxid: "@cadence:cadence.moe", + permissions: "moderator", + guild_id: "112760669178241024" + } + }) + ) + t.equal(error.message, "Forbidden") +}) + +test("api invite: can invite with valid nonce", async t => { + let called = 0 + const [error] = await tryToCatch(() => + router.test("post", `/api/invite`, { + body: { + mxid: "@cadence:cadence.moe", + permissions: "moderator", + nonce + }, + api: { + async getStateEvent(roomID, type, key) { + called++ + return {membership: "leave"} + }, + async inviteToRoom(roomID, mxidToInvite, mxid) { + t.equal(roomID, "!jjWAGMeQdNrVZSSfvz:cadence.moe") + called++ + }, + async setUserPowerCascade(roomID, mxid, power) { + t.equal(power, 50) // moderator + called++ + } + } + }) + ) + t.notOk(error) + t.equal(called, 3) +}) + +test("api invite: access denied when nonce has been used", async t => { + const [error] = await tryToCatch(() => + router.test("post", `/api/invite`, { + body: { + mxid: "@cadence:cadence.moe", + permissions: "moderator", + nonce + } + }) + ) + t.equal(error.message, "Nonce expired") +}) + +test("api invite: can invite to a moderated guild", async t => { + let called = 0 + const [error] = await tryToCatch(() => + router.test("post", `/api/invite`, { + body: { + mxid: "@cadence:cadence.moe", + permissions: "default", + guild_id: "112760669178241024" + }, + sessionData: { + managedGuilds: ["112760669178241024"] + }, + api: { + async getStateEvent(roomID, type, key) { + called++ + throw new MatrixServerError({errcode: "M_NOT_FOUND", error: "Event not found or something"}) + }, + async inviteToRoom(roomID, mxidToInvite, mxid) { + t.equal(roomID, "!jjWAGMeQdNrVZSSfvz:cadence.moe") + called++ + }, + async setUserPowerCascade(roomID, mxid, power) { + t.equal(power, 0) + called++ + } + } + }) + ) + t.notOk(error) + t.equal(called, 3) +}) + +test("api invite: does not reinvite joined users", async t => { + let called = 0 + const [error] = await tryToCatch(() => + router.test("post", `/api/invite`, { + body: { + mxid: "@cadence:cadence.moe", + permissions: "default", + guild_id: "112760669178241024" + }, + sessionData: { + managedGuilds: ["112760669178241024"] + }, + api: { + async getStateEvent(roomID, type, key) { + called++ + return {membership: "join"} + }, + async setUserPowerCascade(roomID, mxid, power) { + t.equal(power, 0) + called++ + } + } + }) + ) + t.notOk(error) + t.equal(called, 2) +}) diff --git a/src/web/routes/qr.test.js b/src/web/routes/qr.test.js new file mode 100644 index 0000000..5b17f87 --- /dev/null +++ b/src/web/routes/qr.test.js @@ -0,0 +1,17 @@ +const {test} = require("supertape") +const {router} = require("../../../test/web") +const getStream = require("get-stream") + +test("web qr: returns svg", async t => { + /** @type {Response} */ + const res = await router.test("get", "/qr?data=hello+world", { + params: { + server_name: "cadence.moe", + media_id: "1" + } + }) + t.equal(res.status, 200) + t.equal(res.headers.get("content-type"), "image/svg+xml") + const content = await getStream(res.body) + t.match(content, / { + t.match(await router.test("get", "/", {}), /Add the bot to your Discord server./) +}) + +test("web server: can get htmx", async t => { + t.match(await router.test("get", "/static/htmx.min.js", {}), /htmx=/) +}) + +test("web server: can get css", async t => { + t.match(await router.test("get", "/static/stacks.min.css", {}), /--stacks-/) +}) + +test("web server: can get icon", async t => { + const content = await router.test("get", "/icon.png", {}) + t.ok(content instanceof Buffer) +}) + +test("web server: compresses static resources", async t => { + const content = await router.test("get", "/static/stacks.min.css", { + headers: { + "accept-encoding": "gzip" + } + }) + t.ok(content instanceof ReadableStream) +}) diff --git a/test/ooye-test-data.sql b/test/ooye-test-data.sql index af7ea7b..38fed25 100644 --- a/test/ooye-test-data.sql +++ b/test/ooye-test-data.sql @@ -163,9 +163,13 @@ INSERT INTO member_power (mxid, room_id, power_level) VALUES INSERT INTO lottie (sticker_id, mxc_url) VALUES ('860171525772279849', 'mxc://cadence.moe/ZtvvVbwMIdUZeovWVyGVFCeR'); -INSERT INTO "auto_emoji" ("name","emoji_id","guild_id") VALUES -('L1','1144820033948762203','529176156398682115'), -('L2','1144820084079087647','529176156398682115'), -('_','_','529176156398682115'); +INSERT INTO auto_emoji (name, emoji_id, guild_id) VALUES +('L1', '1144820033948762203', '529176156398682115'), +('L2', '1144820084079087647', '529176156398682115'), +('_', '_', '529176156398682115'); + +INSERT INTO media_proxy (permitted_hash) VALUES +(-429802515645771439), +(4558604729745184757); COMMIT; diff --git a/test/test.js b/test/test.js index 5f20a80..9e595ae 100644 --- a/test/test.js +++ b/test/test.js @@ -20,9 +20,9 @@ const {reg} = require("../src/matrix/read-registration") reg.ooye.discord_token = "Njg0MjgwMTkyNTUzODQ0NzQ3.Xl3zlw.baby" reg.ooye.server_origin = "https://matrix.cadence.moe" // so that tests will pass even when hard-coded reg.ooye.server_name = "cadence.moe" -reg.id = "baby" // don't actually take authenticated actions on the server -reg.as_token = "baby" -reg.hs_token = "baby" +reg.id = "baby" +reg.as_token = "don't actually take authenticated actions on the server" +reg.hs_token = "don't actually take authenticated actions on the server" reg.ooye.bridge_origin = "https://bridge.example.org" const sync = new HeatSync({watchFS: false}) @@ -31,6 +31,9 @@ const discord = { guilds: new Map([ [data.guild.general.id, data.guild.general] ]), + guildChannelMap: new Map([ + [data.guild.general.id, [data.channel.general.id]], + ]), application: { id: "684280192553844747" }, @@ -97,7 +100,7 @@ file._actuallyUploadDiscordFileToMxc = function(url, res) { throw new Error(`Not ]) }, {timeout: 60000}) } - /* c8 ignore end */ + /* c8 ignore stop */ const p = migrate.migrate(db) test("migrate: migration works", async t => { @@ -142,4 +145,9 @@ file._actuallyUploadDiscordFileToMxc = function(url, res) { throw new Error(`Not require("../src/discord/interactions/permissions.test") require("../src/discord/interactions/privacy.test") require("../src/discord/interactions/reactions.test") + require("../src/web/server.test") + require("../src/web/routes/download-discord.test") + require("../src/web/routes/download-matrix.test") + require("../src/web/routes/guild.test") + require("../src/web/routes/qr.test") })() diff --git a/test/web.js b/test/web.js new file mode 100644 index 0000000..e22a97c --- /dev/null +++ b/test/web.js @@ -0,0 +1,69 @@ +const passthrough = require("../src/passthrough") +const h3 = require("h3") +const http = require("http") +const {SnowTransfer} = require("snowtransfer") + +class Router { + constructor() { + /** @type {Map} */ + this.routes = new Map() + for (const method of ["get", "post", "put", "patch", "delete"]) { + this[method] = function(url, handler) { + const key = `${method} ${url}` + this.routes.set(`${key}`, handler) + } + } + } + + /** + * @param {string} method + * @param {string} inputUrl + * @param {{event?: any, params?: any, body?: any, sessionData?: any, api?: Partial, snow?: {[k in keyof SnowTransfer]?: Partial}, headers?: any}} [options] + */ + test(method, inputUrl, options = {}) { + const url = new URL(inputUrl, "http://a") + const key = `${method} ${options.route || url.pathname}` + /* c8 ignore next */ + if (!this.routes.has(key)) throw new Error(`Route not found: "${key}"`) + + const req = { + method: method.toUpperCase(), + headers: options.headers || {}, + url + } + const event = options.event || {} + + if (typeof options.body === "object" && options.body.constructor === Object) { + options.body = JSON.stringify(options.body) + req.headers["content-type"] = "application/json" + } + + return this.routes.get(key)(Object.assign(event, { + method: method.toUpperCase(), + path: `${url.pathname}${url.search}`, + _requestBody: options.body, + node: { + req, + res: new http.ServerResponse(req) + }, + context: { + api: options.api, + params: options.params, + snow: options.snow, + sessions: { + h3: { + id: "h3", + createdAt: 0, + data: options.sessionData || {} + } + } + } + })) + } +} + +const router = new Router() + +passthrough.as = {router} + +module.exports.router = router From 75140a5b588ffbdd1503861c4fce08f0d826f13a Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Tue, 24 Dec 2024 01:16:02 +1300 Subject: [PATCH 052/228] Allow creating admins on web --- src/matrix/api.js | 9 +++++---- src/web/pug/guild.pug | 1 + src/web/pug/invite.pug | 1 + src/web/routes/guild.js | 7 +++++-- 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/matrix/api.js b/src/matrix/api.js index a75f959..532e326 100644 --- a/src/matrix/api.js +++ b/src/matrix/api.js @@ -301,14 +301,15 @@ async function setUserPower(roomID, mxid, power) { /** * Set a user's power level for a whole room hierarchy. - * @param {string} roomID + * @param {string} spaceID * @param {string} mxid * @param {number} power */ -async function setUserPowerCascade(roomID, mxid, power) { - assert(roomID[0] === "!") +async function setUserPowerCascade(spaceID, mxid, power) { + assert(spaceID[0] === "!") assert(mxid[0] === "@") - const rooms = await getFullHierarchy(roomID) + const rooms = await getFullHierarchy(spaceID) + await setUserPower(spaceID, mxid, power) for (const room of rooms) { await setUserPower(room.room_id, mxid, power) } diff --git a/src/web/pug/guild.pug b/src/web/pug/guild.pug index 481ad01..d9ece95 100644 --- a/src/web/pug/guild.pug +++ b/src/web/pug/guild.pug @@ -64,6 +64,7 @@ block body select#permissions(name="permissions") option(value="default") Default option(value="moderator") Moderator + option(value="admin") Admin input(type="hidden" name="guild_id" value=guild_id) .grid--row-start2 button.s-btn.s-btn__filled.htmx-indicator Invite diff --git a/src/web/pug/invite.pug b/src/web/pug/invite.pug index 52b3ab2..7f7ff2e 100644 --- a/src/web/pug/invite.pug +++ b/src/web/pug/invite.pug @@ -27,6 +27,7 @@ block body select#permissions(name="permissions") option(value="default") Default option(value="moderator") Moderator + option(value="admin") Admin input(type="hidden" name="nonce" value=nonce) div button.s-btn.s-btn__filled.htmx-indicator Invite diff --git a/src/web/routes/guild.js b/src/web/routes/guild.js index fe24483..716314c 100644 --- a/src/web/routes/guild.js +++ b/src/web/routes/guild.js @@ -20,7 +20,7 @@ const schema = { }), invite: z.object({ mxid: z.string().regex(/@([^:]+):([a-z0-9:-]+\.[a-z0-9.:-]+)/), - permissions: z.enum(["default", "moderator"]), + permissions: z.enum(["default", "moderator", "admin"]), guild_id: z.string().optional(), nonce: z.string().optional() }), @@ -152,7 +152,10 @@ as.router.post("/api/invite", defineEventHandler(async event => { } // Permissions - const powerLevel = parsedBody.permissions === "moderator" ? 50 : 0 + const powerLevel = + ( parsedBody.permissions === "admin" ? 100 + : parsedBody.permissions === "moderator" ? 50 + : 0) await api.setUserPowerCascade(spaceID, parsedBody.mxid, powerLevel) if (parsedBody.guild_id) { From 8a6b8ee32a40f89eb4f629abbd244a7b37900434 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Tue, 24 Dec 2024 01:20:42 +1300 Subject: [PATCH 053/228] Allow creating admins from interaction menu --- src/discord/interactions/permissions.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/discord/interactions/permissions.js b/src/discord/interactions/permissions.js index fea9ce0..0a573e3 100644 --- a/src/discord/interactions/permissions.js +++ b/src/discord/interactions/permissions.js @@ -82,6 +82,10 @@ async function* _interact({data, guild_id}, {api}) { label: "Moderator", value: "moderator", default: userPower >= 50 && userPower < 100 + }, { + label: "Admin (you cannot undo this!)", + value: "admin", + default: userPower === 100 } ] } @@ -103,7 +107,10 @@ async function* _interactEdit({data, guild_id, message}, {api}) { assert(mxid) const permission = data.values[0] - const power = permission === "moderator" ? 50 : 0 + const power = + ( permission === "admin" ? 100 + : permission === "moderator" ? 50 + : 0) yield {createInteractionResponse: { type: DiscordTypes.InteractionResponseType.UpdateMessage, From 20b575c5f7c6e74310ccd415c52ca2b30c82e961 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Tue, 24 Dec 2024 01:25:09 +1300 Subject: [PATCH 054/228] Mention PluralKit support on the readme --- readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/readme.md b/readme.md index f88b6ea..40161d6 100644 --- a/readme.md +++ b/readme.md @@ -41,6 +41,7 @@ Most features you'd expect in both directions, plus a little extra spice: * Custom emoji list syncing * Custom emojis in messages * Custom room names/avatars can be applied on Matrix-side +* PluralKit members have persistent user accounts * Larger files from Discord are linked instead of reuploaded to Matrix (links don't expire) * Simulated user accounts are named @the_persons_username rather than @112233445566778899 From 0fe02dce22c3a8f9321a09af750e65bdc5620590 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sat, 28 Dec 2024 20:01:27 +1300 Subject: [PATCH 055/228] Fix web page exploding for unlinked guilds Now it should at least show something, though features like invite won't work correctly. More work needed. --- src/web/routes/guild.js | 2 +- src/web/routes/guild.test.js | 27 +++++++++++++--- test/data.js | 63 ++++++++++++++++++++++++++++++++++++ test/test.js | 4 ++- 4 files changed, 90 insertions(+), 6 deletions(-) diff --git a/src/web/routes/guild.js b/src/web/routes/guild.js index 716314c..6916d56 100644 --- a/src/web/routes/guild.js +++ b/src/web/routes/guild.js @@ -96,7 +96,7 @@ as.router.get("/guild", defineEventHandler(async event => { // Unlinked guild if (!row) { const links = getChannelRoomsLinks(guild_id, []) - return pugSync.render(event, "guild.pug", {guild_id, nonce, ...links}) + return pugSync.render(event, "guild.pug", {guild, guild_id, nonce, ...links}) } // Linked guild diff --git a/src/web/routes/guild.test.js b/src/web/routes/guild.test.js index b5b4080..f89dfee 100644 --- a/src/web/routes/guild.test.js +++ b/src/web/routes/guild.test.js @@ -33,15 +33,34 @@ test("web guild: access denied when guild id messed up", async t => { t.match(content, /the selected server doesn't exist/) }) - - - test("web invite: access denied with invalid nonce", async t => { const content = await router.test("get", "/invite?nonce=1") t.match(content, /This QR code has expired./) }) -test("web guild: can view guild", async t => { + + +test("web guild: can view unbridged guild", async t => { + const content = await router.test("get", "/guild?guild_id=66192955777486848", { + sessionData: { + managedGuilds: ["66192955777486848"] + }, + api: { + async getStateEvent(roomID, type, key) { + return {} + }, + async getMembers(roomID, membership) { + return {chunk: []} + }, + async getFullHierarchy(roomID) { + return [] + } + } + }) + t.match(content, / { const content = await router.test("get", "/guild?guild_id=112760669178241024", { sessionData: { managedGuilds: ["112760669178241024"] diff --git a/test/data.js b/test/data.js index 1c7983a..3133d27 100644 --- a/test/data.js +++ b/test/data.js @@ -189,6 +189,69 @@ module.exports = { max_stage_video_channel_users: 300, system_channel_flags: 0|0, safety_alerts_channel_id: null + }, + fna: { + application_id: null, + roles: [], + activity_instances: [], + banner: null, + stickers: [], + joined_at: "2020-04-25T07:36:09.644000+00:00", + default_message_notifications: 1, + afk_timeout: 60, + clan: null, + hub_type: null, + afk_channel_id: "216367750216548362", + discovery_splash: null, + splash: null, + explicit_content_filter: 0, + max_members: 500000, + premium_subscription_count: 0, + voice_states: [], + id: "66192955777486848", + premium_tier: 0, + name: "Function & Arg", + premium_progress_bar_enabled: false, + icon: "8bfeb3237cd8697d1d1cd5c626ca8cea", + large: true, + verification_level: 0, + public_updates_channel_id: null, + stage_instances: [], + rules_channel_id: null, + emojis: [], + owner_id: "66186356581208064", + threads: [], + max_stage_video_channel_users: 50, + description: null, + unavailable: false, + features: [ + "CHANNEL_ICON_EMOJIS_GENERATED", + "NEW_THREAD_PERMISSIONS", + "THREADS_ENABLED", + "SOUNDBOARD" + ], + latest_onboarding_question_id: null, + max_video_channel_users: 25, + home_header: null, + mfa_level: 0, + system_channel_id: null, + guild_scheduled_events: [], + nsfw_level: 0, + vanity_url_code: null, + member_count: 966, + presences: [], + application_command_counts: {}, + system_channel_flags: 0, + preferred_locale: "en-US", + region: "deprecated", + inventory_settings: null, + soundboard_sounds: [], + version: 1711491959939, + incidents_data: null, + embedded_activities: [], + nsfw: false, + safety_alerts_channel_id: null, + lazy: true } }, user: { diff --git a/test/test.js b/test/test.js index 9e595ae..241b7a1 100644 --- a/test/test.js +++ b/test/test.js @@ -29,10 +29,12 @@ const sync = new HeatSync({watchFS: false}) const discord = { guilds: new Map([ - [data.guild.general.id, data.guild.general] + [data.guild.general.id, data.guild.general], + [data.guild.fna.id, data.guild.fna], ]), guildChannelMap: new Map([ [data.guild.general.id, [data.channel.general.id]], + [data.guild.fna.id, []], ]), application: { id: "684280192553844747" From d7063916a58fdcbd0c57643f0db48e83d5fa1876 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sun, 5 Jan 2025 19:02:55 +1300 Subject: [PATCH 056/228] During setup, echo any unrecognised requests --- scripts/setup.js | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/scripts/setup.js b/scripts/setup.js index 2782ad8..109c012 100644 --- a/scripts/setup.js +++ b/scripts/setup.js @@ -103,6 +103,13 @@ async function validateHomeserverOrigin(serverUrlPrompt, url) { return true } +function defineEchoHandler() { + return defineEventHandler(event => { + return "Out Of Your Element is listening.\n" + + `Received a ${event.method} request on path ${event.path}\n` + }) +} + ;(async () => { // create registration file with prompts... if (!reg) { @@ -127,7 +134,7 @@ async function validateHomeserverOrigin(serverUrlPrompt, url) { const serverOrigin = await serverOriginPrompt.run() const app = createApp() - app.use(defineEventHandler(() => "Out Of Your Element is listening.\n")) + app.use(defineEchoHandler()) const server = createServer(toNodeListener(app)) await server.listen(6693) @@ -147,7 +154,7 @@ async function validateHomeserverOrigin(serverUrlPrompt, url) { const res = await fetch(url) if (res.status !== 200) return `Server returned status code ${res.status}` const text = await res.text() - if (text !== "Out Of Your Element is listening.\n") return `Server does not point to OOYE` + if (!text.startsWith("Out Of Your Element is listening.")) return `Server does not point to OOYE` return true } catch (e) { return e.message @@ -241,6 +248,7 @@ async function validateHomeserverOrigin(serverUrlPrompt, url) { passthrough.discord = discord const {as} = require("../src/matrix/appservice") + as.router.use("/**", defineEchoHandler()) console.log("⏳ Waiting until homeserver registration works... (Ctrl+C to cancel)") let itWorks = false From 97043d90cc333224194ab52106e9dd3cec13d9fc Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sun, 5 Jan 2025 19:27:40 +1300 Subject: [PATCH 057/228] await it a bit further up the chain --- src/d2m/actions/create-space.js | 4 ++-- src/d2m/event-dispatcher.js | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/d2m/actions/create-space.js b/src/d2m/actions/create-space.js index 04d1413..acd0d8f 100644 --- a/src/d2m/actions/create-space.js +++ b/src/d2m/actions/create-space.js @@ -235,8 +235,8 @@ async function syncSpaceExpressions(data, checkBeforeSync) { api.sendState(spaceID, "im.ponies.room_emotes", eventKey, content) } - update(spaceID, "emojis", "moe.cadence.ooye.pack.emojis", expression.emojisToState) - update(spaceID, "stickers", "moe.cadence.ooye.pack.stickers", expression.stickersToState) + await update(spaceID, "emojis", "moe.cadence.ooye.pack.emojis", expression.emojisToState) + await update(spaceID, "stickers", "moe.cadence.ooye.pack.stickers", expression.stickersToState) } module.exports.createSpace = createSpace diff --git a/src/d2m/event-dispatcher.js b/src/d2m/event-dispatcher.js index c84d6a8..943e40e 100644 --- a/src/d2m/event-dispatcher.js +++ b/src/d2m/event-dispatcher.js @@ -179,7 +179,7 @@ module.exports = { */ async checkMissedExpressions(guild) { const data = {guild_id: guild.id, ...guild} - createSpace.syncSpaceExpressions(data, true) + await createSpace.syncSpaceExpressions(data, true) }, /** From 6411279efd151801be16145ce6447ad84b353b92 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 6 Jan 2025 15:31:34 +1300 Subject: [PATCH 058/228] Use relative paths on web --- package-lock.json | 12 +++++++++--- package.json | 1 + src/web/pug-sync.js | 5 +++-- src/web/pug/guild.pug | 2 +- src/web/pug/guild_access_denied.pug | 6 +++--- src/web/pug/home.pug | 4 ++-- src/web/pug/includes/template.pug | 12 ++++++------ 7 files changed, 25 insertions(+), 17 deletions(-) diff --git a/package-lock.json b/package-lock.json index 1189af7..1852245 100644 --- a/package-lock.json +++ b/package-lock.json @@ -27,6 +27,7 @@ "domino": "^2.1.6", "enquirer": "^2.4.1", "entities": "^5.0.0", + "get-relative-path": "^1.0.2", "get-stream": "^6.0.1", "h3": "^1.12.0", "heatsync": "^2.5.5", @@ -1535,9 +1536,9 @@ } }, "node_modules/cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", "dev": true, "dependencies": { "path-key": "^3.1.0", @@ -1843,6 +1844,11 @@ "node": "6.* || 8.* || >= 10.*" } }, + "node_modules/get-relative-path": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/get-relative-path/-/get-relative-path-1.0.2.tgz", + "integrity": "sha512-dGkopYfmB4sXMTcZslq5SojEYakpdCSj/SVSHLhv7D6RBHzvDtd/3Q8lTEOAhVKxPPeAHu/YYkENbbz3PaH+8w==" + }, "node_modules/get-source": { "version": "2.0.12", "resolved": "https://registry.npmjs.org/get-source/-/get-source-2.0.12.tgz", diff --git a/package.json b/package.json index e79a6b0..1705c02 100644 --- a/package.json +++ b/package.json @@ -36,6 +36,7 @@ "domino": "^2.1.6", "enquirer": "^2.4.1", "entities": "^5.0.0", + "get-relative-path": "^1.0.2", "get-stream": "^6.0.1", "h3": "^1.12.0", "heatsync": "^2.5.5", diff --git a/src/web/pug-sync.js b/src/web/pug-sync.js index aa1a945..057fd0a 100644 --- a/src/web/pug-sync.js +++ b/src/web/pug-sync.js @@ -3,11 +3,11 @@ const assert = require("assert/strict") const fs = require("fs") const {join} = require("path") +const getRelativePath = require("get-relative-path") const h3 = require("h3") const {defineEventHandler, defaultContentType, setResponseStatus, useSession, getQuery} = h3 const {compileFile} = require("@cloudrac3r/pug") -const {as} = require("../passthrough") const {reg} = require("../matrix/read-registration") // Pug @@ -35,11 +35,12 @@ function render(event, filename, locals) { pugCache.set(path, async (event, locals) => { defaultContentType(event, "text/html; charset=utf-8") const session = await useSession(event, {password: reg.as_token}) + const rel = x => getRelativePath(event.path, x) return template(Object.assign({}, getQuery(event), // Query parameters can be easily accessed on the top level but don't allow them to overwrite anything globals, // Globals locals, // Explicit locals overwrite globals in case we need to DI something - {session} // Session is always session because it has to be trusted + {session, event, rel} // These are assigned last so they overwrite everything else. It would be catastrophically bad if they can't be trusted. )) }) /* c8 ignore start */ diff --git a/src/web/pug/guild.pug b/src/web/pug/guild.pug index d9ece95..9f12d38 100644 --- a/src/web/pug/guild.pug +++ b/src/web/pug/guild.pug @@ -73,7 +73,7 @@ block body let size = 105 let p = new URLSearchParams() p.set("data", `https://bridge.cadence.moe/invite?nonce=${nonce}`) - img(width=size height=size src=`/qr?${p}`) + img(width=size height=size src=rel(`/qr?${p}`)) h2.mt48.fs-headline1 Moderation diff --git a/src/web/pug/guild_access_denied.pug b/src/web/pug/guild_access_denied.pug index 2305605..2b47e08 100644 --- a/src/web/pug/guild_access_denied.pug +++ b/src/web/pug/guild_access_denied.pug @@ -5,7 +5,7 @@ block body .s-empty-state.wmx4.p48 != icons.Spots.SpotEmptyXL p You need to log in to manage your servers. - a.s-btn.s-btn__icon.s-btn__filled(href="/oauth") + a.s-btn.s-btn__icon.s-btn__filled(href=rel("/oauth")) != icons.Icons.IconDiscord = ` Log in with Discord` @@ -13,10 +13,10 @@ block body .s-empty-state.wmx4.p48 != icons.Spots.SpotEmptyXL p Select a server from the top right corner to continue. - p If the server you're looking for isn't there, try #[a(href="/oauth?action=add") logging in again.] + p If the server you're looking for isn't there, try #[a(href=rel("/oauth?action=add")) logging in again.] else if !discord.guilds.has(guild_id) || !session.data.managedGuilds.includes(guild_id) .s-empty-state.wmx4.p48 != icons.Spots.SpotAlertXL p Either the selected server doesn't exist, or you don't have the Manage Server permission on Discord. - p If you've checked your permissions, try #[a(href="/oauth") logging in again.] + p If you've checked your permissions, try #[a(href=rel("/oauth")) logging in again.] diff --git a/src/web/pug/home.pug b/src/web/pug/home.pug index 6cd7d29..a906423 100644 --- a/src/web/pug/home.pug +++ b/src/web/pug/home.pug @@ -10,7 +10,7 @@ block body p Add the bot to your Discord server. p It will automatically create new Matrix rooms for you. .fl-grow1 - a.s-btn.s-btn__filled.s-btn__icon(href="/oauth?action=add") + a.s-btn.s-btn__filled.s-btn__icon(href=rel("/oauth?action=add")) != icons.Icons.IconPlus = ` Add to server` .s-card.bs-md.d-flex.fd-column @@ -19,6 +19,6 @@ block body p Choose this option if you already have a community set up on Matrix. p Or, choose this if you're migrating from a different bridge. .fl-grow1 - a.s-btn.s-btn__outlined.s-btn__icon(href="/oauth?action=add-self-service") + a.s-btn.s-btn__outlined.s-btn__icon(href=rel("/oauth?action=add-self-service")) != icons.Icons.IconUnorderedList = ` Set up self-service` diff --git a/src/web/pug/includes/template.pug b/src/web/pug/includes/template.pug index 8345d76..6a0fb76 100644 --- a/src/web/pug/includes/template.pug +++ b/src/web/pug/includes/template.pug @@ -14,7 +14,7 @@ html(lang="en") head title Out Of Your Element - link(rel="stylesheet" type="text/css" href="/static/stacks.min.css") + link(rel="stylesheet" type="text/css" href=rel("/static/stacks.min.css")) meta(name="htmx-config" content='{"indicatorClass":"is-loading"}') style. @@ -34,13 +34,13 @@ html(lang="en") header.s-topbar .s-topbar--skip-link(href="#content") Skip to main content .s-topbar--container.wmx9 - a.s-topbar--logo(href="/") - img.s-avatar.s-avatar__32(src="/icon.png") + a.s-topbar--logo(href=rel("/")) + img.s-avatar.s-avatar__32(src=rel("/icon.png")) nav.s-topbar--navigation ul.s-topbar--content li.ps-relative if !session.data.managedGuilds || session.data.managedGuilds.length === 0 - a.s-btn.s-btn__icon.as-center(href="/oauth") + a.s-btn.s-btn__icon.as-center(href=rel("/oauth")) != icons.Icons.IconDiscord = ` Log in` else if guild_id && session.data.managedGuilds.includes(guild_id) && discord.guilds.has(guild_id) @@ -55,7 +55,7 @@ html(lang="en") ul.s-menu(role="menu") each guild in (session.data.managedGuilds || []).map(id => discord.guilds.get(id)).filter(g => g) li(role="menuitem") - a.s-topbar--item.s-user-card.d-flex.p4(href=`/guild?guild_id=${guild.id}`) + a.s-topbar--item.s-user-card.d-flex.p4(href=rel(`/guild?guild_id=${guild.id}`)) +guild(guild) .mx-auto.w100.wmx9.py24.px8.fs-body1#content block body @@ -68,4 +68,4 @@ html(lang="en") document.styleSheets[0].insertRule(t) }) }) - script(src="/static/htmx.min.js") + script(src=rel("/static/htmx.min.js")) From 16ac99781c509a98b266337f1e3ac509be14bbb6 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 6 Jan 2025 17:19:33 +1300 Subject: [PATCH 059/228] Better feedback after interrupting/resuming setup --- scripts/setup.js | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/scripts/setup.js b/scripts/setup.js index 109c012..1fbbcff 100644 --- a/scripts/setup.js +++ b/scripts/setup.js @@ -230,11 +230,20 @@ function defineEchoHandler() { registration.reg = reg checkRegistration(reg) writeRegistration(reg) - console.log(`✅ Registration file saved as ${registrationFilePath}`) + console.log(`✅ Your responses have been saved as ${registrationFilePath}`) } else { - console.log(`✅ Valid registration file found at ${registrationFilePath}`) + try { + checkRegistration(reg) + console.log(`✅ Skipped questions - reusing data from ${registrationFilePath}`) + } catch (e) { + console.log(`❌ Failed to reuse data from ${registrationFilePath}`) + console.log("Consider deleting this file. You can re-run setup to safely make a new one.") + console.log("") + console.log(e.toString().replace(/^ *\n/gm, "")) + process.exit(1) + } } - console.log(` In ${cyan("Synapse")}, you need to add it to homeserver.yaml and ${cyan("restart Synapse")}.`) + console.log(` In ${cyan("Synapse")}, you need to reference that file in your homeserver.yaml and ${cyan("restart Synapse")}.`) console.log(" https://element-hq.github.io/synapse/latest/application_services.html") console.log(` In ${cyan("Conduit")}, you need to send the file contents to the #admins room.`) console.log(" https://docs.conduit.rs/appservices.html") @@ -249,7 +258,12 @@ function defineEchoHandler() { const {as} = require("../src/matrix/appservice") as.router.use("/**", defineEchoHandler()) - console.log("⏳ Waiting until homeserver registration works... (Ctrl+C to cancel)") + + console.log("⏳ Waiting for you to register the file with your homeserver... (Ctrl+C to cancel)") + process.once("SIGINT", () => { + console.log("(Ctrl+C) Quit early. Please re-run setup later and allow it to complete.") + process.exit(1) + }) let itWorks = false let lastError = null From 84d61a11184e0542ff5659d13794ff81a9d85f94 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 6 Jan 2025 21:12:05 +1300 Subject: [PATCH 060/228] Use relative path for post-oauth redirect --- src/web/routes/oauth.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/web/routes/oauth.js b/src/web/routes/oauth.js index 82aebe4..12c991d 100644 --- a/src/web/routes/oauth.js +++ b/src/web/routes/oauth.js @@ -6,6 +6,7 @@ const {defineEventHandler, getValidatedQuery, sendRedirect, getQuery, useSession const {SnowTransfer} = require("snowtransfer") const DiscordTypes = require("discord-api-types/v10") const fetch = require("node-fetch") +const getRelativePath = require("get-relative-path") const {as, db} = require("../../passthrough") const {id} = require("../../../addbot") @@ -90,8 +91,8 @@ as.router.get("/oauth", defineEventHandler(async event => { } if (parsedQuery.data.guild_id) { - return sendRedirect(event, `/guild?guild_id=${parsedQuery.data.guild_id}`, 302) + return sendRedirect(event, getRelativePath(event.path, `/guild?guild_id=${parsedQuery.data.guild_id}`), 302) } - return sendRedirect(event, "/", 302) + return sendRedirect(event, getRelativePath(event.path, "/"), 302) })) From 4c62124cee94fa28d4c1dbddf4403beb09e04f07 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 6 Jan 2025 21:53:48 +1300 Subject: [PATCH 061/228] Improve invite QR generation --- src/web/pug/guild.pug | 6 +----- src/web/routes/guild.js | 12 ++++++++++-- src/web/routes/guild.test.js | 2 +- src/web/routes/qr.js | 19 ------------------- src/web/routes/qr.test.js | 17 ----------------- src/web/server.js | 1 - test/test.js | 1 - 7 files changed, 12 insertions(+), 46 deletions(-) delete mode 100644 src/web/routes/qr.js delete mode 100644 src/web/routes/qr.test.js diff --git a/src/web/pug/guild.pug b/src/web/pug/guild.pug index 9f12d38..536ea4c 100644 --- a/src/web/pug/guild.pug +++ b/src/web/pug/guild.pug @@ -69,11 +69,7 @@ block body .grid--row-start2 button.s-btn.s-btn__filled.htmx-indicator Invite div - - - let size = 105 - let p = new URLSearchParams() - p.set("data", `https://bridge.cadence.moe/invite?nonce=${nonce}`) - img(width=size height=size src=rel(`/qr?${p}`)) + != svg h2.mt48.fs-headline1 Moderation diff --git a/src/web/routes/guild.js b/src/web/routes/guild.js index 6916d56..5944131 100644 --- a/src/web/routes/guild.js +++ b/src/web/routes/guild.js @@ -6,6 +6,7 @@ const {H3Event, defineEventHandler, sendRedirect, useSession, createError, getVa const {randomUUID} = require("crypto") const {LRUCache} = require("lru-cache") const Ty = require("../../types") +const uqr = require("uqr") const {discord, as, sync, select} = require("../../passthrough") /** @type {import("../pug-sync")} */ @@ -93,10 +94,17 @@ as.router.get("/guild", defineEventHandler(async event => { const nonce = randomUUID() validNonce.set(nonce, guild_id) + const data = `${reg.ooye.bridge_origin}/invite?nonce=${nonce}` + // necessary to scale the svg pixel-perfectly on the page + // https://github.com/unjs/uqr/blob/244952a8ba2d417f938071b61e11fb1ff95d6e75/src/svg.ts#L24 + const generatedSvg = uqr.renderSVG(data, {pixelSize: 3}) + const svg = generatedSvg.replace(/viewBox="0 0 ([0-9]+) ([0-9]+)"/, `data-nonce="${nonce}" width="$1" height="$2" $&`) + assert.notEqual(svg, generatedSvg) + // Unlinked guild if (!row) { const links = getChannelRoomsLinks(guild_id, []) - return pugSync.render(event, "guild.pug", {guild, guild_id, nonce, ...links}) + return pugSync.render(event, "guild.pug", {guild, guild_id, svg, ...links}) } // Linked guild @@ -105,7 +113,7 @@ as.router.get("/guild", defineEventHandler(async event => { const banned = await api.getMembers(row.space_id, "ban") const rooms = await api.getFullHierarchy(row.space_id) const links = getChannelRoomsLinks(guild_id, rooms) - return pugSync.render(event, "guild.pug", {guild, guild_id, nonce, mods, banned, ...links, ...row}) + return pugSync.render(event, "guild.pug", {guild, guild_id, svg, mods, banned, ...links, ...row}) })) as.router.get("/invite", defineEventHandler(async event => { diff --git a/src/web/routes/guild.test.js b/src/web/routes/guild.test.js index f89dfee..3952d14 100644 --- a/src/web/routes/guild.test.js +++ b/src/web/routes/guild.test.js @@ -78,7 +78,7 @@ test("web guild: can view bridged guild", async t => { } }) t.match(content, / { - const {data} = await getValidatedQuery(event, schema.qr.parse) - return new Response(uqr.renderSVG(data, {pixelSize: 3}), {headers: {"content-type": "image/svg+xml"}}) -})) diff --git a/src/web/routes/qr.test.js b/src/web/routes/qr.test.js deleted file mode 100644 index 5b17f87..0000000 --- a/src/web/routes/qr.test.js +++ /dev/null @@ -1,17 +0,0 @@ -const {test} = require("supertape") -const {router} = require("../../../test/web") -const getStream = require("get-stream") - -test("web qr: returns svg", async t => { - /** @type {Response} */ - const res = await router.test("get", "/qr?data=hello+world", { - params: { - server_name: "cadence.moe", - media_id: "1" - } - }) - t.equal(res.status, 200) - t.equal(res.headers.get("content-type"), "image/svg+xml") - const content = await getStream(res.body) - t.match(content, / Date: Tue, 7 Jan 2025 12:23:39 +1300 Subject: [PATCH 062/228] Sync pins back from Matrix to Discord --- src/m2d/actions/update-pins.js | 25 ++++++++++++++++++++++++ src/m2d/converters/diff-pins.js | 17 ++++++++++++++++ src/m2d/converters/diff-pins.test.js | 11 +++++++++++ src/m2d/event-dispatcher.js | 29 ++++++++++++++++++++++++++++ src/types.d.ts | 4 ++++ test/test.js | 1 + 6 files changed, 87 insertions(+) create mode 100644 src/m2d/actions/update-pins.js create mode 100644 src/m2d/converters/diff-pins.js create mode 100644 src/m2d/converters/diff-pins.test.js diff --git a/src/m2d/actions/update-pins.js b/src/m2d/actions/update-pins.js new file mode 100644 index 0000000..976e496 --- /dev/null +++ b/src/m2d/actions/update-pins.js @@ -0,0 +1,25 @@ +// @ts-check + +const {sync, from, discord} = require("../../passthrough") + +/** @type {import("../converters/diff-pins")} */ +const diffPins = sync.require("../converters/diff-pins") + +/** + * @param {string[]} pins + * @param {string[]} prev + */ +async function updatePins(pins, prev) { + const diff = diffPins.diffPins(pins, prev) + for (const [event_id, added] of diff) { + const row = from("event_message").join("message_channel", "message_id").where({event_id}).select("channel_id", "message_id").get() + if (!row) continue + if (added) { + discord.snow.channel.addChannelPinnedMessage(row.channel_id, row.message_id, "Message pinned on Matrix") + } else { + discord.snow.channel.removeChannelPinnedMessage(row.channel_id, row.message_id, "Message unpinned on Matrix") + } + } +} + +module.exports.updatePins = updatePins diff --git a/src/m2d/converters/diff-pins.js b/src/m2d/converters/diff-pins.js new file mode 100644 index 0000000..e6e038b --- /dev/null +++ b/src/m2d/converters/diff-pins.js @@ -0,0 +1,17 @@ +// @ts-check + +/** + * @param {string[]} pins + * @param {string[]} prev + * @returns {[string, boolean][]} + */ +function diffPins(pins, prev) { + /** @type {[string, boolean][]} */ + const result = [] + return result.concat( + prev.filter(id => !pins.includes(id)).map(id => [id, false]), // removed + pins.filter(id => !prev.includes(id)).map(id => [id, true]) // added + ) +} + +module.exports.diffPins = diffPins diff --git a/src/m2d/converters/diff-pins.test.js b/src/m2d/converters/diff-pins.test.js new file mode 100644 index 0000000..edb9c47 --- /dev/null +++ b/src/m2d/converters/diff-pins.test.js @@ -0,0 +1,11 @@ +// @ts-check + +const {test} = require("supertape") +const diffPins = require("./diff-pins") + +test("diff pins: diff is as expected", t => { + t.deepEqual( + diffPins.diffPins(["same", "new"], ["same", "old"]), + [["old", false], ["new", true]] + ) +}) diff --git a/src/m2d/event-dispatcher.js b/src/m2d/event-dispatcher.js index 301dcc4..d5d6ed3 100644 --- a/src/m2d/event-dispatcher.js +++ b/src/m2d/event-dispatcher.js @@ -14,6 +14,8 @@ const sendEvent = sync.require("./actions/send-event") const addReaction = sync.require("./actions/add-reaction") /** @type {import("./actions/redact")} */ const redact = sync.require("./actions/redact") +/** @type {import("./actions/update-pins")}) */ +const updatePins = sync.require("./actions/update-pins") /** @type {import("../matrix/matrix-command-handler")} */ const matrixCommandHandler = sync.require("../matrix/matrix-command-handler") /** @type {import("./converters/utils")} */ @@ -159,6 +161,33 @@ async event => { db.prepare("UPDATE channel_room SET nick = ? WHERE room_id = ?").run(name, event.room_id) })) +sync.addTemporaryListener(as, "type:m.room.pinned_events", guard("m.room.pinned_events", +/** + * @param {Ty.Event.StateOuter} event + */ +async event => { + if (event.state_key !== "") return + if (utils.eventSenderIsFromDiscord(event.sender)) return + const pins = event.content.pinned + if (!Array.isArray(pins)) return + let prev = event.unsigned?.prev_content?.pinned + if (!Array.isArray(prev)) { + if (pins.length === 1) { + /* + In edge cases, prev_content isn't guaranteed to be provided by the server. + If prev_content is missing, we can't diff. Better safe than sorry: we'd like to ignore the change rather than wiping the whole channel's pins on Discord. + However, that would mean if the first ever pin came from Matrix-side, it would be ignored, because there would be no prev_content (it's the first pinned event!) + So to handle that edge case, we assume that if there's exactly 1 entry in `pinned`, this is the first ever pin and it should go through. + */ + prev = [] + } else { + return + } + } + + await updatePins.updatePins(pins, prev) +})) + sync.addTemporaryListener(as, "type:m.room.member", guard("m.room.member", /** * @param {Ty.Event.StateOuter} event diff --git a/src/types.d.ts b/src/types.d.ts index 178a560..b99046b 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -241,6 +241,10 @@ export namespace Event { name?: string } + export type M_Room_PinnedEvents = { + pinned: string[] + } + export type M_Power_Levels = { /** The level required to ban a user. Defaults to 50 if unspecified. */ ban?: number, diff --git a/test/test.js b/test/test.js index 089a0dd..591b64b 100644 --- a/test/test.js +++ b/test/test.js @@ -139,6 +139,7 @@ file._actuallyUploadDiscordFileToMxc = function(url, res) { throw new Error(`Not require("../src/d2m/converters/remove-reaction.test") require("../src/d2m/converters/thread-to-announcement.test") require("../src/d2m/converters/user-to-mxid.test") + require("../src/m2d/converters/diff-pins.test") require("../src/m2d/converters/event-to-message.test") require("../src/m2d/converters/utils.test") require("../src/m2d/converters/emoji-sheet.test") From dcb7dda6f121bd733e7417d4597747a6f624691e Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Tue, 7 Jan 2025 15:04:43 +1300 Subject: [PATCH 063/228] Setup now checks for privileged intents --- scripts/setup.js | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/scripts/setup.js b/scripts/setup.js index 1fbbcff..3491106 100644 --- a/scripts/setup.js +++ b/scripts/setup.js @@ -15,6 +15,7 @@ const fetch = require("node-fetch").default const {magenta, bold, cyan} = require("ansi-colors") const HeatSync = require("heatsync") const {SnowTransfer} = require("snowtransfer") +const DiscordTypes = require("discord-api-types/v10") const {createApp, defineEventHandler, toNodeListener} = require("h3") const args = require("minimist")(process.argv.slice(2), {string: ["emoji-guild"]}) @@ -166,9 +167,10 @@ function defineEchoHandler() { await server.close() console.log("What is your Discord bot token?") + console.log("Go to https://discord.com/developers, create or pick an app, go to the Bot section, and reset the token.") /** @type {SnowTransfer} */ // @ts-ignore let snow = null - /** @type {{id: string, redirect_uris: string[]}} */ // @ts-ignore + /** @type {{id: string, flags: number, redirect_uris: string[]}} */ // @ts-ignore let client = null /** @type {{discord_token: string}} */ const discordTokenResponse = await prompt({ @@ -187,8 +189,27 @@ function defineEchoHandler() { } }) + const mandatoryIntentFlags = DiscordTypes.ApplicationFlags.GatewayMessageContent | DiscordTypes.ApplicationFlags.GatewayMessageContentLimited + if (!(client.flags & mandatoryIntentFlags)) { + console.log(`On that same page, scroll down to Privileged Gateway Intents and enable all switches.`) + await prompt({ + type: "invisible", + name: "intents", + message: "Press Enter when you've enabled them", + validate: async token => { + process.stdout.write(magenta("checking, please wait...")) + client = await snow.requestHandler.request(`/applications/@me`, {}, "get") + if (client.flags & mandatoryIntentFlags) { + return true + } else { + return "Switches have not been enabled yet" + } + } + }) + } + console.log("What is your Discord client secret?") - console.log(`You can find it on the application page: https://discord.com/developers/applications/${client.id}/oauth2`) + console.log(`You can find it in the application's OAuth2 section: https://discord.com/developers/applications/${client.id}/oauth2`) /** @type {{discord_client_secret: string}} */ const clientSecretResponse = await prompt({ type: "input", @@ -198,7 +219,7 @@ function defineEchoHandler() { const expectedUri = `${bridgeOriginResponse.bridge_origin}/oauth` if (!client.redirect_uris.includes(expectedUri)) { - console.log(`On the same application page, go to the Redirects section, and add this URI: ${cyan(expectedUri)}`) + console.log(`On that same page, scroll down to Redirects and add this URI: ${cyan(expectedUri)}`) await prompt({ type: "invisible", name: "redirect_uri", From 2009e23689cddaa58aa9f556747ea109700d8f25 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Wed, 8 Jan 2025 01:01:32 +1300 Subject: [PATCH 064/228] Docs: Why does the bridge have a website? --- docs/why-does-the-bridge-have-a-website.md | 103 +++++++++++++++++++++ readme.md | 1 + 2 files changed, 104 insertions(+) create mode 100644 docs/why-does-the-bridge-have-a-website.md diff --git a/docs/why-does-the-bridge-have-a-website.md b/docs/why-does-the-bridge-have-a-website.md new file mode 100644 index 0000000..c60b62c --- /dev/null +++ b/docs/why-does-the-bridge-have-a-website.md @@ -0,0 +1,103 @@ +# Why does the bridge have a website? + +## It's essential for making images work + +Matrix has a feature called [Authenticated Media](https://matrix.org/blog/2024/06/26/sunsetting-unauthenticated-media/), where uploaded media (like user avatars and uploaded files) is restricted to Matrix users only. This means Discord users wouldn't be able to see important parts of the conversation. + +To keep things working for Discord users, OOYE's web server can act as a proxy files that were uploaded on Matrix-side. This will automatically take effect when needed, so Discord users shouldn't notice any issues. + +## Why now? + +I knew a web interface had a lot of potential, but I was reluctant to add one because it would make the initial setup more complicated. However, when authenticated media forced my hand, I saw an opportunity to introduce new useful features. Hopefully you'll agree that it's worth it! + +# What else does it do? + +## Makes it easy to invite the bot + +The home page of the website has buttons to add the bridge bot to a Discord server. If you are primarly a Matrix user and you want somebody else (who may be less technical) to add the bot to their own Discord server, this should make it a lot more intuitive for them. + +## Makes it easy to invite yourself or others + +After your hypothetical less-technical friend adds the bot to their Discord server, you need to generate an invite for your Matrix account on Matrix-side. Without the website, you might need to guide them through running a /invite command with your user ID. With the website, they don't have to do anything extra. You can use your phone to scan the QR code on their screen, which lets you invite your user ID in your own time. + +You can also set the person's permissions when you invite them, so you can easily bootstrap the Matrix side with your trusted ones as moderators. + +## To link channels and rooms + +Without a website, to link Discord channels to existing Matrix rooms, you'd need to run a /link command with the internal IDs of each room. This is tedious and error-prone, especially if you want to set up a lot of channels. With the web interface, you can see a list of all the available rooms and click them to link them together. + +## To change settings + +Important settings, like whether the Matrix rooms should be private or publicly accessible, can be configured by clicking buttons rather than memorising commands. Changes take effect immediately. + +# Permissions + +## Bot invites + +Anybody who can access the home page can use the buttons to add your bot - but even without the website, they can already do this by manually constructing a URL. If you want to make it so _only you_ can add your bot to servers, you need to edit [your Discord application](https://discord.com/developers/applications), go to the Bot section, and turn off the switch that says Public Bot. + +## Server settings + +If you have either the Administrator or Manage Server permissions in a Discord server, you can use the website to manage that server, including linking channels and changing settings. + +# Initial setup + +The website is built in to OOYE and is always running as part of the bridge. For authenticated media proxy to work, you'll need to make the web server accessible on the public internet over HTTPS, presumably using a reverse proxy. + +When you use `npm run setup` as part of OOYE's initial setup, it will guide you through this process, and it will do a thorough self-test to make sure it's configured correctly. If you get stuck or want a configuration template, check the notes below. + +## Reverse proxy + +When OOYE is running, the web server runs on port 6693. (To use a different port or a UNIX socket, edit registration.yaml's `socket` setting and restart.) + +It doesn't have to have its own dedicated domain name, you can also use a sub-path on an existing domain, like the domain of your Matrix homeserver. See the end of this document for more information. + +You are likely already using a reverse proxy for running your homeserver, so this should just be a configuration change. + +## Example configuration for nginx, dedicated domain name + +Replace `bridge.cadence.moe` with the hostname you're using. + +```nix +server { + listen 80; + listen [::]:80; + server_name bridge.cadence.moe; + + return 301 https://bridge.cadence.moe$request_uri; +} + +server { + listen 443 ssl http2; + listen [::]:443 ssl http2; + server_name bridge.cadence.moe; + + # ssl parameters here... + client_max_body_size 5M; + + location / { + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always; + proxy_pass http://127.0.0.1:6693; + } +} +``` + +## Example configuration for nginx, sharing a domain name + +Same as above, but change the following: + +- `location / {` -> `location /ooye/ {` (any sub-path you want; you MUST use a trailing slash or it won't work) +- `proxy_pass http://127.0.0.1:6693;` -> `proxy_pass http://127.0.0.1:6693/;` (you MUST use a trailing slash on this too or it won't work) + +## Example configuration for Caddy, dedicated domain name + +```nix +bridge.cadence.moe { + log { + output file /var/log/caddy/access.log + format console + } + encode gzip + reverse_proxy 127.0.0.1:6693 +} +``` diff --git a/readme.md b/readme.md index 40161d6..3770f9c 100644 --- a/readme.md +++ b/readme.md @@ -72,6 +72,7 @@ You'll need: * Administrative access to a homeserver * Discord bot +* Domain name for the bridge's website ([more info](https://gitdab.com/cadence/out-of-your-element/src/branch/main/docs/why-does-the-bridge-have-a-website.md) Follow these steps: From 3e5034cff585dd6f133dd25fc112d7f96b13a3af Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Wed, 8 Jan 2025 01:07:46 +1300 Subject: [PATCH 065/228] Remove read receipts visibility client hint This is a failed experiment that is long past its time. It needs to go. --- src/d2m/actions/create-room.js | 3 --- test/data.js | 1 - 2 files changed, 4 deletions(-) diff --git a/src/d2m/actions/create-room.js b/src/d2m/actions/create-room.js index ece8ef7..e99fc93 100644 --- a/src/d2m/actions/create-room.js +++ b/src/d2m/actions/create-room.js @@ -162,9 +162,6 @@ async function channelToKState(channel, guild, di) { }, users: {...spacePower, ...globalAdminPower} }, - "chat.schildi.hide_ui/read_receipts": { - hidden: true - }, [`uk.half-shot.bridge/moe.cadence.ooye://discord/${guild.id}/${channel.id}`]: { bridgebot: `@${reg.sender_localpart}:${reg.ooye.server_name}`, protocol: { diff --git a/test/data.js b/test/data.js index 3133d27..75a961c 100644 --- a/test/data.js +++ b/test/data.js @@ -48,7 +48,6 @@ module.exports = { room: 0 } }, - "chat.schildi.hide_ui/read_receipts": {hidden: true}, "uk.half-shot.bridge/moe.cadence.ooye://discord/112760669178241024/112760669178241024": { bridgebot: "@_ooye_bot:cadence.moe", protocol: { From 93cacba2833294d172615752968ee284227fd150 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Wed, 8 Jan 2025 01:25:17 +1300 Subject: [PATCH 066/228] Make sure client hint change applies Will eventually remove it fully in v4. --- src/d2m/actions/create-room.js | 2 ++ test/data.js | 1 + 2 files changed, 3 insertions(+) diff --git a/src/d2m/actions/create-room.js b/src/d2m/actions/create-room.js index e99fc93..8f8ac00 100644 --- a/src/d2m/actions/create-room.js +++ b/src/d2m/actions/create-room.js @@ -162,6 +162,8 @@ async function channelToKState(channel, guild, di) { }, users: {...spacePower, ...globalAdminPower} }, + "chat.schildi.hide_ui/read_receipts": { + }, [`uk.half-shot.bridge/moe.cadence.ooye://discord/${guild.id}/${channel.id}`]: { bridgebot: `@${reg.sender_localpart}:${reg.ooye.server_name}`, protocol: { diff --git a/test/data.js b/test/data.js index 75a961c..b92ae1b 100644 --- a/test/data.js +++ b/test/data.js @@ -48,6 +48,7 @@ module.exports = { room: 0 } }, + "chat.schildi.hide_ui/read_receipts": {}, "uk.half-shot.bridge/moe.cadence.ooye://discord/112760669178241024/112760669178241024": { bridgebot: "@_ooye_bot:cadence.moe", protocol: { From 7e6548eb90851795a3abd663a5faf346dde08eb7 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Wed, 8 Jan 2025 01:31:31 +1300 Subject: [PATCH 067/228] Ack bridged Matrix events May provide reassurance that the bridge is currently working. Half-Shot's bridge has always done this. --- src/m2d/event-dispatcher.js | 3 +++ src/matrix/api.js | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/m2d/event-dispatcher.js b/src/m2d/event-dispatcher.js index d5d6ed3..c7c725e 100644 --- a/src/m2d/event-dispatcher.js +++ b/src/m2d/event-dispatcher.js @@ -104,6 +104,7 @@ async event => { // @ts-ignore await matrixCommandHandler.execute(event) } + await api.ackEvent(event) })) sync.addTemporaryListener(as, "type:m.sticker", guard("m.sticker", @@ -113,6 +114,7 @@ sync.addTemporaryListener(as, "type:m.sticker", guard("m.sticker", async event => { if (utils.eventSenderIsFromDiscord(event.sender)) return const messageResponses = await sendEvent.sendEvent(event) + await api.ackEvent(event) })) sync.addTemporaryListener(as, "type:m.reaction", guard("m.reaction", @@ -137,6 +139,7 @@ sync.addTemporaryListener(as, "type:m.room.redaction", guard("m.room.redaction", async event => { if (utils.eventSenderIsFromDiscord(event.sender)) return await redact.handle(event) + await api.ackEvent(event) })) sync.addTemporaryListener(as, "type:m.room.avatar", guard("m.room.avatar", diff --git a/src/matrix/api.js b/src/matrix/api.js index 532e326..abf264e 100644 --- a/src/matrix/api.js +++ b/src/matrix/api.js @@ -347,6 +347,26 @@ function getMedia(mxc, init = {}) { }) } +/** + * Updates the m.read receipt in roomID to point to eventID. + * This doesn't modify m.fully_read, which matches [the behaviour of matrix-bot-sdk.](https://github.com/element-hq/matrix-bot-sdk/blob/e72a4c498e00c6c339a791630c45d00a351f56a8/src/MatrixClient.ts#L1227) + * @param {string} roomID + * @param {string} eventID + * @param {string?} [mxid] + */ +async function sendReadReceipt(roomID, eventID, mxid) { + await mreq.mreq("POST", path(`/client/v3/rooms/${roomID}/receipt/m.read/${eventID}`, mxid), {}) +} + +/** + * Acknowledge an event as read by calling api.sendReadReceipt on it. + * @param {Ty.Event.Outer} event + * @param {string?} [mxid] + */ +async function ackEvent(event, mxid) { + await sendReadReceipt(event.room_id, event.event_id, mxid) +} + module.exports.path = path module.exports.register = register module.exports.createRoom = createRoom @@ -373,3 +393,5 @@ module.exports.setUserPower = setUserPower module.exports.setUserPowerCascade = setUserPowerCascade module.exports.ping = ping module.exports.getMedia = getMedia +module.exports.sendReadReceipt = sendReadReceipt +module.exports.ackEvent = ackEvent From fb18c0fe0b311baea311fb373a8921b14ed5b26a Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Wed, 8 Jan 2025 02:05:28 +1300 Subject: [PATCH 068/228] Ensure 1 pin = 1 pin even when message is split --- src/m2d/actions/update-pins.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/m2d/actions/update-pins.js b/src/m2d/actions/update-pins.js index 976e496..46074c6 100644 --- a/src/m2d/actions/update-pins.js +++ b/src/m2d/actions/update-pins.js @@ -12,7 +12,7 @@ const diffPins = sync.require("../converters/diff-pins") async function updatePins(pins, prev) { const diff = diffPins.diffPins(pins, prev) for (const [event_id, added] of diff) { - const row = from("event_message").join("message_channel", "message_id").where({event_id}).select("channel_id", "message_id").get() + const row = from("event_message").join("message_channel", "message_id").where({event_id, part: 0}).select("channel_id", "message_id").get() if (!row) continue if (added) { discord.snow.channel.addChannelPinnedMessage(row.channel_id, row.message_id, "Message pinned on Matrix") From 0c1b4c5e8e10a69c9198344d9d44c158458dc1e5 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Wed, 8 Jan 2025 09:37:30 +1300 Subject: [PATCH 069/228] Remove unhelpful guard preventing d->m pin syncing --- src/d2m/actions/update-pins.js | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/d2m/actions/update-pins.js b/src/d2m/actions/update-pins.js index 5d98501..bce3f88 100644 --- a/src/d2m/actions/update-pins.js +++ b/src/d2m/actions/update-pins.js @@ -25,11 +25,9 @@ function convertTimestamp(timestamp) { async function updatePins(channelID, roomID, convertedTimestamp) { const pins = await discord.snow.channel.getChannelPinnedMessages(channelID) const eventIDs = pinsToList.pinsToList(pins) - if (pins.length === eventIDs.length || eventIDs.length) { - await api.sendState(roomID, "m.room.pinned_events", "", { - pinned: eventIDs - }) - } + await api.sendState(roomID, "m.room.pinned_events", "", { + pinned: eventIDs + }) db.prepare("UPDATE channel_room SET last_bridged_pin_timestamp = ? WHERE channel_id = ?").run(convertedTimestamp || 0, channelID) } From 6e55061760e2b297fef2cd10a7ff6fa106ef61d6 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Wed, 8 Jan 2025 11:31:43 +1300 Subject: [PATCH 070/228] Use kstate for d->m pins updates --- src/d2m/actions/create-room.js | 34 ++++++--------------------------- src/d2m/actions/create-space.js | 8 ++++---- src/d2m/actions/update-pins.js | 14 +++++++++----- src/m2d/event-dispatcher.js | 1 + src/matrix/api.js | 2 +- src/matrix/kstate.js | 26 +++++++++++++++++++++++++ src/matrix/power.js | 5 ++--- src/web/pug/guild.pug | 2 +- 8 files changed, 50 insertions(+), 42 deletions(-) diff --git a/src/d2m/actions/create-room.js b/src/d2m/actions/create-room.js index 8f8ac00..eeba7aa 100644 --- a/src/d2m/actions/create-room.js +++ b/src/d2m/actions/create-room.js @@ -39,26 +39,6 @@ const DEFAULT_PRIVACY_LEVEL = 0 /** @type {Map>} channel ID -> Promise */ const inflightRoomCreate = new Map() -/** - * Async because it gets all room state from the homeserver. - * @param {string} roomID - */ -async function roomToKState(roomID) { - const root = await api.getAllState(roomID) - return ks.stateToKState(root) -} - -/** - * @param {string} roomID - * @param {any} kstate - */ -async function applyKStateDiffToRoom(roomID, kstate) { - const events = await ks.kstateToState(kstate) - return Promise.all(events.map(({type, state_key, content}) => - api.sendState(roomID, type, state_key, content) - )) -} - /** * @param {{id: string, name: string, topic?: string?, type: number, parent_id?: string?}} channel * @param {{id: string}} guild @@ -253,9 +233,9 @@ async function postApplyPowerLevels(kstate, callback) { // Now *really* apply the power level overrides on top of what Synapse *really* set if (powerLevelContent) { - const newRoomKState = await roomToKState(roomID) + const newRoomKState = await ks.roomToKState(roomID) const newRoomPowerLevelsDiff = ks.diffKState(newRoomKState, {"m.room.power_levels/": powerLevelContent}) - await applyKStateDiffToRoom(roomID, newRoomPowerLevelsDiff) + await ks.applyKStateDiffToRoom(roomID, newRoomPowerLevelsDiff) } return roomID @@ -384,7 +364,7 @@ async function _syncRoom(channelID, shouldActuallySync) { const {spaceID, channelKState} = await channelToKState(channel, guild, {api}) // calling this in both branches because we don't want to calculate this if not syncing // sync channel state to room - const roomKState = await roomToKState(roomID) + const roomKState = await ks.roomToKState(roomID) if (+roomKState["m.room.create/"].room_version <= 8) { // join_rule `restricted` is not available in room version < 8 and not working properly in version == 8 // read more: https://spec.matrix.org/v1.8/rooms/v9/ @@ -392,7 +372,7 @@ async function _syncRoom(channelID, shouldActuallySync) { channelKState["m.room.join_rules/"] = {join_rule: "public"} } const roomDiff = ks.diffKState(roomKState, channelKState) - const roomApply = applyKStateDiffToRoom(roomID, roomDiff) + const roomApply = ks.applyKStateDiffToRoom(roomID, roomDiff) db.prepare("UPDATE channel_room SET name = ? WHERE room_id = ?").run(channel.name, roomID) // sync room as space member @@ -462,7 +442,7 @@ async function unbridgeDeletedChannel(channel, guildID) { * @returns {Promise} */ async function _syncSpaceMember(channel, spaceID, roomID) { - const spaceKState = await roomToKState(spaceID) + const spaceKState = await ks.roomToKState(spaceID) let spaceEventContent = {} if ( channel.type !== DiscordTypes.ChannelType.PrivateThread // private threads do not belong in the space (don't offer people something they can't join) @@ -475,7 +455,7 @@ async function _syncSpaceMember(channel, spaceID, roomID) { const spaceDiff = ks.diffKState(spaceKState, { [`m.space.child/${roomID}`]: spaceEventContent }) - return applyKStateDiffToRoom(spaceID, spaceDiff) + return ks.applyKStateDiffToRoom(spaceID, spaceDiff) } async function createAllForGuild(guildID) { @@ -498,8 +478,6 @@ module.exports.ensureRoom = ensureRoom module.exports.syncRoom = syncRoom module.exports.createAllForGuild = createAllForGuild module.exports.channelToKState = channelToKState -module.exports.roomToKState = roomToKState -module.exports.applyKStateDiffToRoom = applyKStateDiffToRoom module.exports.postApplyPowerLevels = postApplyPowerLevels module.exports._convertNameAndTopic = convertNameAndTopic module.exports._unbridgeRoom = _unbridgeRoom diff --git a/src/d2m/actions/create-space.js b/src/d2m/actions/create-space.js index acd0d8f..edd3ba3 100644 --- a/src/d2m/actions/create-space.js +++ b/src/d2m/actions/create-space.js @@ -116,9 +116,9 @@ async function _syncSpace(guild, shouldActuallySync) { const guildKState = await guildToKState(guild, privacy_level) // calling this in both branches because we don't want to calculate this if not syncing // sync guild state to space - const spaceKState = await createRoom.roomToKState(spaceID) + const spaceKState = await ks.roomToKState(spaceID) const spaceDiff = ks.diffKState(spaceKState, guildKState) - await createRoom.applyKStateDiffToRoom(spaceID, spaceDiff) + await ks.applyKStateDiffToRoom(spaceID, spaceDiff) // guild icon was changed, so room avatars need to be updated as well as the space ones // doing it this way rather than calling syncRoom for great efficiency gains @@ -183,9 +183,9 @@ async function syncSpaceFully(guildID) { const guildKState = await guildToKState(guild, privacy_level) // sync guild state to space - const spaceKState = await createRoom.roomToKState(spaceID) + const spaceKState = await ks.roomToKState(spaceID) const spaceDiff = ks.diffKState(spaceKState, guildKState) - await createRoom.applyKStateDiffToRoom(spaceID, spaceDiff) + await ks.applyKStateDiffToRoom(spaceID, spaceDiff) const childRooms = await api.getFullHierarchy(spaceID) diff --git a/src/d2m/actions/update-pins.js b/src/d2m/actions/update-pins.js index bce3f88..692081a 100644 --- a/src/d2m/actions/update-pins.js +++ b/src/d2m/actions/update-pins.js @@ -6,6 +6,8 @@ const {discord, sync, db} = passthrough const pinsToList = sync.require("../converters/pins-to-list") /** @type {import("../../matrix/api")} */ const api = sync.require("../../matrix/api") +/** @type {import("../../matrix/kstate")} */ +const ks = sync.require("../../matrix/kstate") /** * @template {string | null | undefined} T @@ -23,11 +25,13 @@ function convertTimestamp(timestamp) { * @param {number?} convertedTimestamp */ async function updatePins(channelID, roomID, convertedTimestamp) { - const pins = await discord.snow.channel.getChannelPinnedMessages(channelID) - const eventIDs = pinsToList.pinsToList(pins) - await api.sendState(roomID, "m.room.pinned_events", "", { - pinned: eventIDs - }) + const discordPins = await discord.snow.channel.getChannelPinnedMessages(channelID) + const pinned = pinsToList.pinsToList(discordPins) + + const kstate = await ks.roomToKState(roomID) + const diff = ks.diffKState(kstate, {"m.room.pinned_events/": {pinned}}) + await ks.applyKStateDiffToRoom(roomID, diff) + db.prepare("UPDATE channel_room SET last_bridged_pin_timestamp = ? WHERE channel_id = ?").run(convertedTimestamp || 0, channelID) } diff --git a/src/m2d/event-dispatcher.js b/src/m2d/event-dispatcher.js index c7c725e..a270293 100644 --- a/src/m2d/event-dispatcher.js +++ b/src/m2d/event-dispatcher.js @@ -189,6 +189,7 @@ async event => { } await updatePins.updatePins(pins, prev) + await api.ackEvent(event) })) sync.addTemporaryListener(as, "type:m.room.member", guard("m.room.member", diff --git a/src/matrix/api.js b/src/matrix/api.js index abf264e..f9d3e08 100644 --- a/src/matrix/api.js +++ b/src/matrix/api.js @@ -6,7 +6,7 @@ const assert = require("assert").strict const fetch = require("node-fetch").default const passthrough = require("../passthrough") -const { discord, sync, db } = passthrough +const {sync} = passthrough /** @type {import("./mreq")} */ const mreq = sync.require("./mreq") /** @type {import("./txnid")} */ diff --git a/src/matrix/kstate.js b/src/matrix/kstate.js index 67bb063..11155f5 100644 --- a/src/matrix/kstate.js +++ b/src/matrix/kstate.js @@ -8,6 +8,8 @@ const passthrough = require("../passthrough") const {sync} = passthrough /** @type {import("./file")} */ const file = sync.require("./file") +/** @type {import("./api")} */ +const api = sync.require("./api") /** Mutates the input. Not recursive - can only include or exclude entire state events. */ function kstateStripConditionals(kstate) { @@ -102,8 +104,32 @@ function diffKState(actual, target) { return diff } +/* c8 ignore start */ + +/** + * Async because it gets all room state from the homeserver. + * @param {string} roomID + */ +async function roomToKState(roomID) { + const root = await api.getAllState(roomID) + return stateToKState(root) +} + +/** + * @param {string} roomID + * @param {any} kstate + */ +async function applyKStateDiffToRoom(roomID, kstate) { + const events = await kstateToState(kstate) + return Promise.all(events.map(({type, state_key, content}) => + api.sendState(roomID, type, state_key, content) + )) +} + module.exports.kstateStripConditionals = kstateStripConditionals module.exports.kstateUploadMxc = kstateUploadMxc module.exports.kstateToState = kstateToState module.exports.stateToKState = stateToKState module.exports.diffKState = diffKState +module.exports.roomToKState = roomToKState +module.exports.applyKStateDiffToRoom = applyKStateDiffToRoom diff --git a/src/matrix/power.js b/src/matrix/power.js index 3e613dd..d323d17 100644 --- a/src/matrix/power.js +++ b/src/matrix/power.js @@ -3,7 +3,6 @@ const {db, from} = require("../passthrough") const {reg} = require("./read-registration") const ks = require("./kstate") -const {applyKStateDiffToRoom, roomToKState} = require("../d2m/actions/create-room") /** Apply global power level requests across ALL rooms where the member cache entry exists but the power level has not been applied yet. */ function _getAffectedRooms() { @@ -23,9 +22,9 @@ async function applyPower() { const rows = _getAffectedRooms() for (const row of rows) { - const kstate = await roomToKState(row.room_id) + const kstate = await ks.roomToKState(row.room_id) const diff = ks.diffKState(kstate, {"m.room.power_levels/": {users: {[row.mxid]: row.power_level}}}) - await applyKStateDiffToRoom(row.room_id, diff) + await ks.applyKStateDiffToRoom(row.room_id, diff) // There is a listener on m.room.power_levels to do this same update, // but we update it here anyway since the homeserver does not always deliver the event round-trip. db.prepare("UPDATE member_cache SET power_level = ? WHERE room_id = ? AND mxid = ?").run(row.power_level, row.room_id, row.mxid) diff --git a/src/web/pug/guild.pug b/src/web/pug/guild.pug index 536ea4c..ab61430 100644 --- a/src/web/pug/guild.pug +++ b/src/web/pug/guild.pug @@ -11,7 +11,7 @@ mixin badge-private | Private mixin discord(channel, radio=false) - - let permissions = dUtils.getPermissions([], discord.guilds.get(channel.guild_id).roles, null, channel.permission_overwrites) + - let permissions = dUtils.getPermissions([], guild.roles, null, channel.permission_overwrites) .s-user-card.s-user-card__small if !dUtils.hasPermission(permissions, DiscordTypes.PermissionFlagsBits.ViewChannel) != icons.Icons.IconLock From ad1aa2c0f663f0936bb95e123cf5ccb0369d808a Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Wed, 8 Jan 2025 13:56:59 +1300 Subject: [PATCH 071/228] Resolve Matrix room aliases to Discord channels --- src/m2d/converters/event-to-message.js | 14 ++- src/m2d/converters/event-to-message.test.js | 127 ++++++++++++++++++++ src/matrix/api.js | 11 ++ src/types.d.ts | 5 + 4 files changed, 155 insertions(+), 2 deletions(-) diff --git a/src/m2d/converters/event-to-message.js b/src/m2d/converters/event-to-message.js index ebbe9e1..b52717d 100644 --- a/src/m2d/converters/event-to-message.js +++ b/src/m2d/converters/event-to-message.js @@ -330,9 +330,9 @@ async function uploadEndOfMessageSpriteSheet(content, attachments, pendingFiles, */ async function handleRoomOrMessageLinks(input, di) { let offset = 0 - for (const match of [...input.matchAll(/("?https:\/\/matrix.to\/#\/(![^"/, ?)]+)(?:\/(\$[^"/ ?)]+))?(?:\?[^",:!? )]*?)?)(">|[,<\n )]|$)/g)]) { + for (const match of [...input.matchAll(/("?https:\/\/matrix.to\/#\/((?:#|%23|!)[^"/, ?)]+)(?:\/(\$[^"/ ?)]+))?(?:\?[^",:!? )]*?)?)(">|[,<\n )]|$)/g)]) { assert(typeof match.index === "number") - const [_, attributeValue, roomID, eventID, endMarker] = match + let [_, attributeValue, roomID, eventID, endMarker] = match let result const resultType = endMarker === '">' ? "html" : "plain" @@ -350,6 +350,16 @@ async function handleRoomOrMessageLinks(input, di) { // Don't process links that are part of the reply fallback, they'll be removed entirely by turndown if (input.slice(match.index + match[0].length + offset).startsWith("In reply to")) continue + // Resolve room alias to room ID if needed + roomID = decodeURIComponent(roomID) + if (roomID[0] === "#") { + try { + roomID = await di.api.getAlias(roomID) + } catch (e) { + continue // Room alias is unresolvable, so it can't be converted + } + } + const channelID = select("channel_room", "channel_id", {room_id: roomID}).pluck().get() if (!channelID) continue if (!eventID) { diff --git a/src/m2d/converters/event-to-message.test.js b/src/m2d/converters/event-to-message.test.js index a97fd26..145e9ec 100644 --- a/src/m2d/converters/event-to-message.test.js +++ b/src/m2d/converters/event-to-message.test.js @@ -2957,6 +2957,133 @@ test("event2message: mentioning bridged rooms works (plaintext body)", async t = ) }) +test("event2message: mentioning bridged rooms by alias works", async t => { + let called = 0 + t.deepEqual( + await eventToMessage({ + content: { + msgtype: "m.text", + body: "wrong body", + format: "org.matrix.custom.html", + formatted_body: `I'm just worm-farm testing channel mentions` + }, + event_id: "$g07oYSZFWBkxohNEfywldwgcWj1hbhDzQ1sBAKvqOOU", + origin_server_ts: 1688301929913, + room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe", + sender: "@cadence:cadence.moe", + type: "m.room.message", + unsigned: { + age: 405299 + } + }, {}, { + api: { + async getAlias(alias) { + called++ + t.equal(alias, "#worm-farm:cadence.moe") + return "!BnKuBPCvyfOkhcUjEu:cadence.moe" + } + } + }), + { + ensureJoined: [], + messagesToDelete: [], + messagesToEdit: [], + messagesToSend: [{ + username: "cadence [they]", + content: "I'm just <#1100319550446252084> testing channel mentions", + avatar_url: undefined, + allowed_mentions: { + parse: ["users", "roles"] + } + }] + } + ) + t.equal(called, 1) +}) + +test("event2message: mentioning bridged rooms by alias works (plaintext body)", async t => { + let called = 0 + t.deepEqual( + await eventToMessage({ + content: { + msgtype: "m.text", + body: `I'm just https://matrix.to/#/#worm-farm:cadence.moe?via=cadence.moe testing channel mentions` + }, + event_id: "$g07oYSZFWBkxohNEfywldwgcWj1hbhDzQ1sBAKvqOOU", + origin_server_ts: 1688301929913, + room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe", + sender: "@cadence:cadence.moe", + type: "m.room.message", + unsigned: { + age: 405299 + } + }, {}, { + api: { + async getAlias(alias) { + called++ + t.equal(alias, "#worm-farm:cadence.moe") + return "!BnKuBPCvyfOkhcUjEu:cadence.moe" + } + } + }), + { + ensureJoined: [], + messagesToDelete: [], + messagesToEdit: [], + messagesToSend: [{ + username: "cadence [they]", + content: "I'm just <#1100319550446252084> testing channel mentions", + avatar_url: undefined, + allowed_mentions: { + parse: ["users", "roles"] + } + }] + } + ) + t.equal(called, 1) +}) + +test("event2message: mentioning bridged rooms by alias skips the link when alias is unresolvable", async t => { + let called = 0 + t.deepEqual( + await eventToMessage({ + content: { + msgtype: "m.text", + body: `I'm just https://matrix.to/#/#worm-farm:cadence.moe?via=cadence.moe and https://matrix.to/#/!BnKuBPCvyfOkhcUjEu:cadence.moe?via=cadence.moe testing channel mentions` + }, + event_id: "$g07oYSZFWBkxohNEfywldwgcWj1hbhDzQ1sBAKvqOOU", + origin_server_ts: 1688301929913, + room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe", + sender: "@cadence:cadence.moe", + type: "m.room.message", + unsigned: { + age: 405299 + } + }, {}, { + api: { + async getAlias(alias) { + called++ + throw new MatrixServerError("Alias doesn't exist or something") + } + } + }), + { + ensureJoined: [], + messagesToDelete: [], + messagesToEdit: [], + messagesToSend: [{ + username: "cadence [they]", + content: "I'm just and <#1100319550446252084> testing channel mentions", + avatar_url: undefined, + allowed_mentions: { + parse: ["users", "roles"] + } + }] + } + ) + t.equal(called, 1) +}) + test("event2message: mentioning known bridged events works (plaintext body)", async t => { t.deepEqual( await eventToMessage({ diff --git a/src/matrix/api.js b/src/matrix/api.js index f9d3e08..c2b2384 100644 --- a/src/matrix/api.js +++ b/src/matrix/api.js @@ -367,6 +367,16 @@ async function ackEvent(event, mxid) { await sendReadReceipt(event.room_id, event.event_id, mxid) } +/** + * Resolve a room alias to a room ID. + * @param {string} alias + */ +async function getAlias(alias) { + /** @type {Ty.R.ResolvedRoom} */ + const root = await mreq.mreq("GET", `/client/v3/directory/room/${encodeURIComponent(alias)}`) + return root.room_id +} + module.exports.path = path module.exports.register = register module.exports.createRoom = createRoom @@ -395,3 +405,4 @@ module.exports.ping = ping module.exports.getMedia = getMedia module.exports.sendReadReceipt = sendReadReceipt module.exports.ackEvent = ackEvent +module.exports.getAlias = getAlias diff --git a/src/types.d.ts b/src/types.d.ts index b99046b..3298c40 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -336,6 +336,11 @@ export namespace R { room_id: string room_type?: string } + + export type ResolvedRoom = { + room_id: string + servers: string[] + } } export type Pagination = { From 551dbd0c42b5dad0b3835fad57aedfde967bbb51 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Wed, 8 Jan 2025 14:51:32 +1300 Subject: [PATCH 072/228] Add dependency justification --- readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 3770f9c..6f2f477 100644 --- a/readme.md +++ b/readme.md @@ -161,7 +161,7 @@ To get into the rooms on your Matrix account, use the `/invite [your mxid here]` ## Dependency justification -Total transitive production dependencies: 147 +Total transitive production dependencies: 148 ### 🦕 @@ -188,6 +188,7 @@ Total transitive production dependencies: 147 * (0) domino: DOM implementation that's already pulled in by turndown. * (1) enquirer: Interactive prompting for the initial setup rather than forcing users to edit YAML non-interactively. * (0) entities: Looks fine. No dependencies. +* (0) get-relative-path: Looks fine. No dependencies. * (0) get-stream: Only needed if content_length_workaround is true. * (1) heatsync: Module hot-reloader that I trust. * (1) js-yaml: Will be removed in the future after registration.yaml is converted to JSON. From c6708d4dbda2137a1c8358dee2a2eadecc43efb5 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sun, 12 Jan 2025 12:50:32 +1300 Subject: [PATCH 073/228] Fix channel linking form URL --- src/web/pug/guild.pug | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/web/pug/guild.pug b/src/web/pug/guild.pug index ab61430..34178bf 100644 --- a/src/web/pug/guild.pug +++ b/src/web/pug/guild.pug @@ -133,7 +133,7 @@ block body p.s-description.m0 Publicly listed in directory, like Discord server discovery h3.mt32.fs-category Manually link channels - form.d-flex.g16.ai-start(hx-post="/api/privacy-level" hx-trigger="submit" hx-disabled-elt="this") + form.d-flex.g16.ai-start(hx-post="/api/link" hx-trigger="submit" hx-disabled-elt="this") .fl-grow2.s-btn-group.fd-column.w40 each channel in unlinkedChannels input.s-btn--radio(type="radio" name="discord" id=channel.id value=channel.id) From a3e94a215a76e646e906400c8d62a82b8a99851f Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sun, 12 Jan 2025 13:05:16 +1300 Subject: [PATCH 074/228] Hide error if sendTyping request fails --- src/d2m/actions/send-message.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/d2m/actions/send-message.js b/src/d2m/actions/send-message.js index 6d100d4..be785bb 100644 --- a/src/d2m/actions/send-message.js +++ b/src/d2m/actions/send-message.js @@ -48,7 +48,7 @@ async function sendMessage(message, channel, guild, row) { const eventIDs = [] if (events.length) { db.prepare("REPLACE INTO message_channel (message_id, channel_id) VALUES (?, ?)").run(message.id, message.channel_id) - if (senderMxid) api.sendTyping(roomID, false, senderMxid) + if (senderMxid) api.sendTyping(roomID, false, senderMxid).catch(() => {}) } for (const event of events) { const part = event === events[0] ? 0 : 1 From 85269ea1530a0cc8af0e0ccd0c9507ff6ff31b7c Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sun, 12 Jan 2025 13:11:51 +1300 Subject: [PATCH 075/228] Hopefully prevent checkMissed errors from crashing --- src/d2m/actions/create-space.js | 2 +- src/d2m/discord-packets.js | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/d2m/actions/create-space.js b/src/d2m/actions/create-space.js index edd3ba3..ce86789 100644 --- a/src/d2m/actions/create-space.js +++ b/src/d2m/actions/create-space.js @@ -232,7 +232,7 @@ async function syncSpaceExpressions(data, checkBeforeSync) { } if (isDeepStrictEqual(existing, content)) return } - api.sendState(spaceID, "im.ponies.room_emotes", eventKey, content) + await api.sendState(spaceID, "im.ponies.room_emotes", eventKey, content) } await update(spaceID, "emojis", "moe.cadence.ooye.pack.emojis", expression.emojisToState) diff --git a/src/d2m/discord-packets.js b/src/d2m/discord-packets.js index 5956ac5..2e97671 100644 --- a/src/d2m/discord-packets.js +++ b/src/d2m/discord-packets.js @@ -51,9 +51,14 @@ const utils = { } if (listen === "full") { - eventDispatcher.checkMissedExpressions(message.d) - eventDispatcher.checkMissedPins(client, message.d) - eventDispatcher.checkMissedMessages(client, message.d) + try { + await eventDispatcher.checkMissedExpressions(message.d) + await eventDispatcher.checkMissedPins(client, message.d) + await eventDispatcher.checkMissedMessages(client, message.d) + } catch (e) { + console.error("Failed to sync missed events. To retry, please fix this error and restart OOYE:") + console.error(e) + } } } else if (message.t === "GUILD_UPDATE") { From de57bdaf3c65e21ea97d4225107eb65968977912 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sun, 12 Jan 2025 13:32:39 +1300 Subject: [PATCH 076/228] Await syncRoom after linking --- src/web/routes/link.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/web/routes/link.js b/src/web/routes/link.js index 90cfd53..e63c01b 100644 --- a/src/web/routes/link.js +++ b/src/web/routes/link.js @@ -57,7 +57,7 @@ as.router.post("/api/link", defineEventHandler(async event => { db.prepare("INSERT INTO channel_room (channel_id, room_id, name, guild_id) VALUES (?, ?, ?, ?)").run(parsedBody.discord, parsedBody.matrix, channel.name, guildID) // Sync room data and space child - createRoom.syncRoom(parsedBody.discord) + await createRoom.syncRoom(parsedBody.discord) return null // 204 })) From f3b0d01400caaf5dcda28bcf75463fa79e8d53a9 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sun, 12 Jan 2025 13:51:57 +1300 Subject: [PATCH 077/228] Fix fish reaction --- src/m2d/converters/emoji.js | 1 + 1 file changed, 1 insertion(+) diff --git a/src/m2d/converters/emoji.js b/src/m2d/converters/emoji.js index bb6a3b0..66a690c 100644 --- a/src/m2d/converters/emoji.js +++ b/src/m2d/converters/emoji.js @@ -42,6 +42,7 @@ function encodeEmoji(input, shortcode) { "%E2%9D%93", // ❓ "%F0%9F%8F%86", // 🏆️ "%F0%9F%93%9A", // 📚️ + "%F0%9F%90%9F", // 🐟️ ] discordPreferredEncoding = From 1e4952f1b871adaa7ba722b383bf1576d4794b76 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sun, 12 Jan 2025 14:31:32 +1300 Subject: [PATCH 078/228] Add anti-timeout system to reactions interaction --- src/discord/interactions/reactions.js | 45 +++++++++++++--------- src/discord/interactions/reactions.test.js | 34 +++++++++++----- 2 files changed, 51 insertions(+), 28 deletions(-) diff --git a/src/discord/interactions/reactions.js b/src/discord/interactions/reactions.js index 1a5a9ca..13dbd69 100644 --- a/src/discord/interactions/reactions.js +++ b/src/discord/interactions/reactions.js @@ -2,6 +2,8 @@ const DiscordTypes = require("discord-api-types/v10") const {discord, sync, select, from} = require("../../passthrough") +const {id: botID} = require("../../../addbot") +const {InteractionMethods} = require("snowtransfer") /** @type {import("../../matrix/api")} */ const api = sync.require("../../matrix/api") @@ -11,21 +13,28 @@ const utils = sync.require("../../m2d/converters/utils") /** * @param {DiscordTypes.APIMessageApplicationCommandGuildInteraction} interaction * @param {{api: typeof api}} di - * @returns {Promise} + * @returns {AsyncGenerator<{[k in keyof InteractionMethods]?: Parameters[2]}>} */ -async function _interact({data}, {api}) { +async function* _interact({data}, {api}) { const row = from("event_message").join("message_channel", "message_id").join("channel_room", "channel_id") .select("event_id", "room_id").where({message_id: data.target_id}).get() if (!row) { - return { + return yield {createInteractionResponse: { type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, data: { content: "This message hasn't been bridged to Matrix.", flags: DiscordTypes.MessageFlags.Ephemeral } - } + }} } + yield {createInteractionResponse: { + type: DiscordTypes.InteractionResponseType.DeferredChannelMessageWithSource, + data: { + flags: DiscordTypes.MessageFlags.Ephemeral + } + }} + const reactions = await api.getFullRelations(row.room_id, row.event_id, "m.annotation") /** @type {Map} */ @@ -40,29 +49,27 @@ async function _interact({data}, {api}) { } if (inverted.size === 0) { - return { - type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, - data: { - content: "Nobody from Matrix reacted to this message.", - flags: DiscordTypes.MessageFlags.Ephemeral - } - } + return yield {editOriginalInteractionResponse: { + content: "Nobody from Matrix reacted to this message.", + }} } - return { - type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, - data: { - content: [...inverted.entries()].map(([key, value]) => `${key} ⮞ ${value.join(" ⬩ ")}`).join("\n"), - flags: DiscordTypes.MessageFlags.Ephemeral - } - } + return yield {editOriginalInteractionResponse: { + content: [...inverted.entries()].map(([key, value]) => `${key} ⮞ ${value.join(" ⬩ ")}`).join("\n"), + }} } /* c8 ignore start */ /** @param {DiscordTypes.APIMessageApplicationCommandGuildInteraction} interaction */ async function interact(interaction) { - await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, await _interact(interaction, {api})) + for await (const response of _interact(interaction, {api})) { + if (response.createInteractionResponse) { + await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, response.createInteractionResponse) + } else if (response.editOriginalInteractionResponse) { + await discord.snow.interaction.editOriginalInteractionResponse(botID, interaction.token, response.editOriginalInteractionResponse) + } + } } module.exports.interact = interact diff --git a/src/discord/interactions/reactions.test.js b/src/discord/interactions/reactions.test.js index 6e29f57..50ddeca 100644 --- a/src/discord/interactions/reactions.test.js +++ b/src/discord/interactions/reactions.test.js @@ -1,17 +1,31 @@ const {test} = require("supertape") const {_interact} = require("./reactions") +/** + * @template T + * @param {AsyncIterable} ai + * @returns {Promise} + */ +async function fromAsync(ai) { + const result = [] + for await (const value of ai) { + result.push(value) + } + return result +} + test("reactions: checks if message is bridged", async t => { - const msg = await _interact({ + const msgs = await fromAsync(_interact({ data: { target_id: "0" } - }, {}) - t.equal(msg.data.content, "This message hasn't been bridged to Matrix.") + }, {})) + t.equal(msgs.length, 1) + t.equal(msgs[0].createInteractionResponse.data.content, "This message hasn't been bridged to Matrix.") }) test("reactions: different response if nobody reacted", async t => { - const msg = await _interact({ + const msgs = await fromAsync(_interact({ data: { target_id: "1126786462646550579" } @@ -23,13 +37,14 @@ test("reactions: different response if nobody reacted", async t => { return [] } } - }) - t.equal(msg.data.content, "Nobody from Matrix reacted to this message.") + })) + t.equal(msgs.length, 2) + t.equal(msgs[1].editOriginalInteractionResponse.content, "Nobody from Matrix reacted to this message.") }) test("reactions: shows reactions if there are some, ignoring discord users", async t => { let called = 1 - const msg = await _interact({ + const msgs = await fromAsync(_interact({ data: { target_id: "1126786462646550579" } @@ -73,9 +88,10 @@ test("reactions: shows reactions if there are some, ignoring discord users", asy }] } } - }) + })) + t.equal(msgs.length, 2) t.equal( - msg.data.content, + msgs[1].editOriginalInteractionResponse.content, "🐈 ⮞ cadence [they] ⬩ @rnl:cadence.moe" + "\n🐈‍⬛ ⮞ cadence [they]" ) From 6bb31deeaf55fa01a74eb0bef44cbd17892d6677 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Thu, 16 Jan 2025 08:40:26 +1300 Subject: [PATCH 079/228] Ignore missed messages if channel was just added --- src/d2m/event-dispatcher.js | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/d2m/event-dispatcher.js b/src/d2m/event-dispatcher.js index 943e40e..a80c451 100644 --- a/src/d2m/event-dispatcher.js +++ b/src/d2m/event-dispatcher.js @@ -103,13 +103,19 @@ module.exports = { async checkMissedMessages(client, guild) { if (guild.unavailable) return const bridgedChannels = select("channel_room", "channel_id").pluck().all() - const prepared = select("event_message", "event_id", {}, "WHERE message_id = ?").pluck() + const preparedExists = db.prepare("SELECT channel_id FROM message_channel WHERE channel_id = ? LIMIT 1") + const preparedGet = select("event_message", "event_id", {}, "WHERE message_id = ?").pluck() for (const channel of guild.channels.concat(guild.threads)) { if (!bridgedChannels.includes(channel.id)) continue if (!("last_message_id" in channel) || !channel.last_message_id) continue - const latestWasBridged = prepared.get(channel.last_message_id) + + // Skip if channel is already up-to-date + const latestWasBridged = preparedGet.get(channel.last_message_id) if (latestWasBridged) continue + // Skip if channel was just added to the bridge (there's no place to resume from if it's brand new) + if (!preparedExists.get(channel.id)) continue + // Permissions check const member = guild.members.find(m => m.user?.id === client.user.id) if (!member) return @@ -131,7 +137,7 @@ module.exports = { } } let latestBridgedMessageIndex = messages.findIndex(m => { - return prepared.get(m.id) + return preparedGet.get(m.id) }) // console.log(`[check missed messages] got ${messages.length} messages; last message that IS bridged is at position ${latestBridgedMessageIndex} in the channel`) if (latestBridgedMessageIndex === -1) latestBridgedMessageIndex = 1 // rather than crawling the ENTIRE channel history, let's just bridge the most recent 1 message to make it up to date. From 931cacea6ac7d0277f428d417c17ffb9f6bcb608 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Thu, 16 Jan 2025 08:44:13 +1300 Subject: [PATCH 080/228] Don't add channels/threads to the public directory --- src/d2m/actions/create-room.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/d2m/actions/create-room.js b/src/d2m/actions/create-room.js index eeba7aa..42d5714 100644 --- a/src/d2m/actions/create-room.js +++ b/src/d2m/actions/create-room.js @@ -26,7 +26,7 @@ const createSpace = sync.require("./create-space") */ const PRIVACY_ENUMS = { PRESET: ["private_chat", "public_chat", "public_chat"], - VISIBILITY: ["private", "private", "public"], + VISIBILITY: ["private", "private", "private"], SPACE_HISTORY_VISIBILITY: ["invited", "world_readable", "world_readable"], // copying from element client ROOM_HISTORY_VISIBILITY: ["shared", "shared", "world_readable"], // any events sent after are visible, but for world_readable anybody can read without even joining GUEST_ACCESS: ["can_join", "forbidden", "forbidden"], // whether guests can join space if other conditions are met From 8ad299b04c3a926c6372ff82f77a6cbb9c1837c3 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Fri, 17 Jan 2025 11:33:29 +1300 Subject: [PATCH 081/228] Add foreign keys to database --- docs/foreign-keys.md | 98 ++++++++++++ src/d2m/actions/create-room.js | 7 + src/d2m/actions/delete-message.js | 2 - src/d2m/actions/edit-message.js | 2 +- src/d2m/actions/send-message.js | 2 +- src/db/migrate.js | 5 +- src/db/migrations/0016-foreign-keys.sql | 164 ++++++++++++++++++++ src/m2d/actions/redact.js | 1 - src/m2d/actions/send-event.js | 3 +- src/m2d/converters/event-to-message.js | 8 +- src/m2d/converters/event-to-message.test.js | 90 ++++++++--- src/m2d/event-dispatcher.js | 29 ++-- src/web/routes/oauth.js | 3 +- test/ooye-test-data.sql | 49 +++--- 14 files changed, 398 insertions(+), 65 deletions(-) create mode 100644 docs/foreign-keys.md create mode 100644 src/db/migrations/0016-foreign-keys.sql diff --git a/docs/foreign-keys.md b/docs/foreign-keys.md new file mode 100644 index 0000000..9940ed0 --- /dev/null +++ b/docs/foreign-keys.md @@ -0,0 +1,98 @@ +# Foreign keys in the Out Of Your Element database + +Historically, Out Of Your Element did not use foreign keys in the database, but since I found a need for them, I have decided to add them. Referential integrity is probably valuable as well. + +The need is that unlinking a channel and room using the web interface should clear up all related entries from `message_channel`, `event_message`, `reaction`, etc. Without foreign keys, this requires multiple DELETEs with tricky queries. With foreign keys and ON DELETE CASCADE, this just works. + +## Quirks + +* **REPLACE INTO** internally causes a DELETE followed by an INSERT, and the DELETE part **will trigger any ON DELETE CASCADE** foreign key conditions on the table, even when the primary key being replaced is the same. + * ```sql + CREATE TABLE discord_channel (channel_id TEXT NOT NULL, name TEXT NOT NULL, PRIMARY KEY (channel_id)); + CREATE TABLE discord_message (message_id TEXT NOT NULL, channel_id TEXT NOT NULL, PRIMARY KEY (message_id), + FOREIGN KEY (channel_id) REFERENCES discord_channel (channel_id) ON DELETE CASCADE); + INSERT INTO discord_channel (channel_id, name) VALUES ("c_1", "place"); + INSERT INTO discord_message (message_id, channel_id) VALUES ("m_2", "c_1"); -- i love my message + REPLACE INTO discord_channel (channel_id, name) VALUES ("c_1", "new place"); -- replace into time + -- i love my message + SELECT * FROM discord_message; -- where is my message + ``` +* In SQLite, `pragma foreign_keys = on` must be set **for each connection** after it's established. I've added this at the start of `migrate.js`, which is called by all database connections. + * Pragma? Pragma keys +* Whenever a child row is inserted, SQLite will look up a row from the parent table to ensure referential integrity. This means **the parent table should be sufficiently keyed or indexed on columns referenced by foreign keys**, or SQLite won't let you do it, with a cryptic error message later on during DML. Due to normal forms, foreign keys naturally tend to reference the parent table's primary key, which is indexed, so that's okay. But still keep this in mind, since many of OOYE's tables effectively have two primary keys, for the Discord and Matrix IDs. A composite primary key doesn't count, even when it's the first column. A unique index counts. + +## Where keys + +Here are some tables that could potentially have foreign keys added between them, and my thought process of whether foreign keys would be a good idea: + +* `guild_active` <--(PK guild_id FK)-- `channel_room` ✅ + * Could be good for referential integrity. + * Linking to guild_space would be pretty scary in case the guild was being relinked to a different space - since rooms aren't tied to a space, this wouldn't actually disturb anything. So I pick guild_active instead. +* `channel_room` <--(PK channel_id FK)-- `message_channel` ✅ + * Seems useful as we want message records to be deleted when a channel is unlinked. +* `message_channel` <--(PK message_id PK)-- `event_message` ✅ + * Seems useful as we want event information to be deleted when a channel is unlinked. +* `guild_active` <--(PK guild_id PK)-- `guild_space` ✅ + * All bridged guilds should have a corresponding guild_active entry, so referential integrity would be useful here to make sure we haven't got any weird states. +* `channel_room` <--(**C** room_id PK)-- `member_cache` ✅ + * Seems useful as we want to clear the member cache when a channel is unlinked. + * There is no index on `channel_room.room_id` right now. It would be good to create this index. Will just make it UNIQUE in the table definition. +* `message_channel` <--(PK message_id FK)-- `reaction` ✅ + * Seems useful as we want to clear the reactions cache when a channel is unlinked. +* `sim` <--(**C** mxid FK)-- `sim_member` + * OOYE inner joins on this. + * Sims are never deleted so if this was added it would only be used for enforcing referential integrity. + * The storage cost of the additional index on `sim` would not be worth the benefits. +* `channel_room` <--(**C** room_id PK)-- `sim_member` + * If a room is being permanently unlinked, it may be useful to see a populated member list. If it's about to be relinked to another channel, we want to keep the sims in the room for more speed and to avoid spamming state events into the timeline. + * Either way, the sims should remain in the room even after it's been unlinked. So no referential integrity is desirable here. +* `sim` <--(PK user_id PK)-- `sim_proxy` + * OOYE left joins on this. In normal operation, this relationship might not exist. +* `channel_room` <--(PK channel_id PK)-- `webhook` ✅ + * Seems useful. Webhooks should be deleted from Discord just before the channel is unlinked. That should be mirrored in the database too. + +## Occurrences of REPLACE INTO/DELETE FROM + +* `edit-message.js` — `REPLACE INTO message_channel` + * Scary! Changed to INSERT OR IGNORE +* `send-message.js` — `REPLACE INTO message_channel` + * Changed to INSERT OR IGNORE +* `add-reaction.js` — `REPLACE INTO reaction` +* `channel-webhook.js` — `REPLACE INTO webhook` +* `send-event.js` — `REPLACE INTO message_channel` + * Seems incorrect? Maybe?? Originally added in fcbb045. Changed to INSERT +* `event-to-message.js` — `REPLACE INTO member_cache` +* `oauth.js` — `REPLACE INTO guild_active` + * Very scary!! Changed to INSERT .. ON CONFLICT DO UPDATE +* `create-room.js` — `DELETE FROM channel_room` + * Please cascade +* `delete-message.js` + * Removed redundant DELETEs +* `edit-message.js` — `DELETE FROM event_message` +* `register-pk-user.js` — `DELETE FROM sim` + * It's a failsafe during creation +* `register-user.js` — `DELETE FROM sim` + * It's a failsafe during creation +* `remove-reaction.js` — `DELETE FROM reaction` +* `event-dispatcher.js` — `DELETE FROM member_cache` +* `redact.js` — `DELETE FROM event_message` + * Removed this redundant DELETE +* `send-event.js` — `DELETE FROM event_message` + * Removed this redundant DELETE + +## How keys + +SQLite does not have a complete ALTER TABLE command, so I have to DROP and CREATE. According to [the docs](https://www.sqlite.org/lang_altertable.html), the correct strategy is: + +1. (Not applicable) *If foreign key constraints are enabled, disable them using PRAGMA foreign_keys=OFF.* +2. Start a transaction. +3. (Not applicable) *Remember the format of all indexes, triggers, and views associated with table X. This information will be needed in step 8 below. One way to do this is to run a query like the following: SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'.* +4. Use CREATE TABLE to construct a new table "new_X" that is in the desired revised format of table X. Make sure that the name "new_X" does not collide with any existing table name, of course. +5. Transfer content from X into new_X using a statement like: INSERT INTO new_X SELECT ... FROM X. +6. Drop the old table X: DROP TABLE X. +7. Change the name of new_X to X using: ALTER TABLE new_X RENAME TO X. +8. (Not applicable) *Use CREATE INDEX, CREATE TRIGGER, and CREATE VIEW to reconstruct indexes, triggers, and views associated with table X. Perhaps use the old format of the triggers, indexes, and views saved from step 3 above as a guide, making changes as appropriate for the alteration.* +9. (Not applicable) *If any views refer to table X in a way that is affected by the schema change, then drop those views using DROP VIEW and recreate them with whatever changes are necessary to accommodate the schema change using CREATE VIEW.* +10. If foreign key constraints were originally enabled then run PRAGMA foreign_key_check to verify that the schema change did not break any foreign key constraints. +11. Commit the transaction started in step 2. +12. (Not applicable) *If foreign keys constraints were originally enabled, reenable them now.* diff --git a/src/d2m/actions/create-room.js b/src/d2m/actions/create-room.js index 42d5714..64e2b68 100644 --- a/src/d2m/actions/create-room.js +++ b/src/d2m/actions/create-room.js @@ -430,6 +430,13 @@ async function unbridgeDeletedChannel(channel, guildID) { // leave room await api.leaveRoom(roomID) + // delete webhook on discord + const webhook = select("webhook", ["webhook_id", "webhook_token"], {channel_id: channel.id}).get() + if (webhook) { + await discord.snow.webhook.deleteWebhook(webhook.webhook_id, webhook.webhook_token) + db.prepare("DELETE FROM webhook WHERE channel_id = ?").run(channel.id) + } + // delete room from database db.prepare("DELETE FROM channel_room WHERE room_id = ? AND channel_id = ?").run(roomID, channel.id) } diff --git a/src/d2m/actions/delete-message.js b/src/d2m/actions/delete-message.js index bc8adfb..e9e0b08 100644 --- a/src/d2m/actions/delete-message.js +++ b/src/d2m/actions/delete-message.js @@ -16,7 +16,6 @@ async function deleteMessage(data) { const eventsToRedact = select("event_message", "event_id", {message_id: data.id}).pluck().all() db.prepare("DELETE FROM message_channel WHERE message_id = ?").run(data.id) - db.prepare("DELETE FROM event_message WHERE message_id = ?").run(data.id) for (const eventID of eventsToRedact) { // Unfortunately, we can't specify a sender to do the redaction as, unless we find out that info via the audit logs await api.redactEvent(row.room_id, eventID) @@ -35,7 +34,6 @@ async function deleteMessageBulk(data) { const sids = JSON.stringify(data.ids) const eventsToRedact = from("event_message").pluck("event_id").and("WHERE message_id IN (SELECT value FROM json_each(?))").all(sids) db.prepare("DELETE FROM message_channel WHERE message_id IN (SELECT value FROM json_each(?))").run(sids) - db.prepare("DELETE FROM event_message WHERE message_id IN (SELECT value FROM json_each(?))").run(sids) for (const eventID of eventsToRedact) { // Awaiting will make it go slower, but since this could be a long-running operation either way, we want to leave rate limit capacity for other operations await api.redactEvent(roomID, eventID) diff --git a/src/d2m/actions/edit-message.js b/src/d2m/actions/edit-message.js index d85f925..85b1a14 100644 --- a/src/d2m/actions/edit-message.js +++ b/src/d2m/actions/edit-message.js @@ -61,7 +61,7 @@ async function editMessage(message, guild, row) { // 4. Send all the things. if (eventsToSend.length) { - db.prepare("REPLACE INTO message_channel (message_id, channel_id) VALUES (?, ?)").run(message.id, message.channel_id) + db.prepare("INSERT OR IGNORE INTO message_channel (message_id, channel_id) VALUES (?, ?)").run(message.id, message.channel_id) } for (const content of eventsToSend) { const eventType = content.$type diff --git a/src/d2m/actions/send-message.js b/src/d2m/actions/send-message.js index be785bb..743c15a 100644 --- a/src/d2m/actions/send-message.js +++ b/src/d2m/actions/send-message.js @@ -47,7 +47,7 @@ async function sendMessage(message, channel, guild, row) { const events = await messageToEvent.messageToEvent(message, guild, {}, {api}) const eventIDs = [] if (events.length) { - db.prepare("REPLACE INTO message_channel (message_id, channel_id) VALUES (?, ?)").run(message.id, message.channel_id) + db.prepare("INSERT OR IGNORE INTO message_channel (message_id, channel_id) VALUES (?, ?)").run(message.id, message.channel_id) if (senderMxid) api.sendTyping(roomID, false, senderMxid).catch(() => {}) } for (const event of events) { diff --git a/src/db/migrate.js b/src/db/migrate.js index 7c1faf9..46d0c14 100644 --- a/src/db/migrate.js +++ b/src/db/migrate.js @@ -6,7 +6,8 @@ const {join} = require("path") async function migrate(db) { let files = fs.readdirSync(join(__dirname, "migrations")) files = files.sort() - db.prepare("CREATE TABLE IF NOT EXISTS migration (filename TEXT NOT NULL)").run() + db.prepare("CREATE TABLE IF NOT EXISTS migration (filename TEXT NOT NULL, PRIMARY KEY (filename)) WITHOUT ROWID").run() + /** @type {string} */ let progress = db.prepare("SELECT * FROM migration").pluck().get() if (!progress) { progress = "" @@ -37,6 +38,8 @@ async function migrate(db) { if (migrationRan) { console.log("Database migrations all done.") } + + db.pragma("foreign_keys = on") } module.exports.migrate = migrate diff --git a/src/db/migrations/0016-foreign-keys.sql b/src/db/migrations/0016-foreign-keys.sql new file mode 100644 index 0000000..c41f329 --- /dev/null +++ b/src/db/migrations/0016-foreign-keys.sql @@ -0,0 +1,164 @@ +-- /docs/foreign-keys.md + +-- 2 +BEGIN TRANSACTION; + +-- *** channel_room *** + +-- 4 +-- adding UNIQUE to room_id here will auto-generate the usable index we wanted +CREATE TABLE "new_channel_room" ( + "channel_id" TEXT NOT NULL, + "room_id" TEXT NOT NULL UNIQUE, + "name" TEXT NOT NULL, + "nick" TEXT, + "thread_parent" TEXT, + "custom_avatar" TEXT, + "last_bridged_pin_timestamp" INTEGER, + "speedbump_id" TEXT, + "speedbump_checked" INTEGER, + "speedbump_webhook_id" TEXT, + "guild_id" TEXT, + PRIMARY KEY("channel_id"), + FOREIGN KEY("guild_id") REFERENCES "guild_active"("guild_id") ON DELETE CASCADE +) WITHOUT ROWID; +-- 5 +INSERT INTO new_channel_room (channel_id, room_id, name, nick, thread_parent, custom_avatar, last_bridged_pin_timestamp, speedbump_id, speedbump_checked, speedbump_webhook_id, guild_id) SELECT channel_id, room_id, name, nick, thread_parent, custom_avatar, last_bridged_pin_timestamp, speedbump_id, speedbump_checked, speedbump_webhook_id, guild_id FROM channel_room; +-- 6 +DROP TABLE channel_room; +-- 7 +ALTER TABLE new_channel_room RENAME TO channel_room; + +-- *** message_channel *** + +-- 4 +CREATE TABLE "new_message_channel" ( + "message_id" TEXT NOT NULL, + "channel_id" TEXT NOT NULL, + PRIMARY KEY("message_id"), + FOREIGN KEY("channel_id") REFERENCES "channel_room"("channel_id") ON DELETE CASCADE +) WITHOUT ROWID; +-- 5 +-- don't copy any orphaned messages +INSERT INTO new_message_channel (message_id, channel_id) SELECT message_id, channel_id FROM message_channel WHERE channel_id IN (SELECT channel_id FROM channel_room); +-- 6 +DROP TABLE message_channel; +-- 7 +ALTER TABLE new_message_channel RENAME TO message_channel; + +-- *** event_message *** + +-- clean up any orphaned events +DELETE FROM event_message WHERE message_id NOT IN (SELECT message_id FROM message_channel); +-- 4 +CREATE TABLE "new_event_message" ( + "event_id" TEXT NOT NULL, + "event_type" TEXT, + "event_subtype" TEXT, + "message_id" TEXT NOT NULL, + "part" INTEGER NOT NULL, + "reaction_part" INTEGER NOT NULL, + "source" INTEGER NOT NULL, + PRIMARY KEY("message_id","event_id"), + FOREIGN KEY("message_id") REFERENCES "message_channel"("message_id") ON DELETE CASCADE +) WITHOUT ROWID; +-- 5 +INSERT INTO new_event_message (event_id, event_type, event_subtype, message_id, part, reaction_part, source) SELECT event_id, event_type, event_subtype, message_id, part, reaction_part, source FROM event_message; +-- 6 +DROP TABLE event_message; +-- 7 +ALTER TABLE new_event_message RENAME TO event_message; + +-- *** guild_space *** + +-- 4 +CREATE TABLE "new_guild_space" ( + "guild_id" TEXT NOT NULL, + "space_id" TEXT NOT NULL, + "privacy_level" INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY("guild_id"), + FOREIGN KEY("guild_id") REFERENCES "guild_active"("guild_id") ON DELETE CASCADE +) WITHOUT ROWID; +-- 5 +INSERT INTO new_guild_space (guild_id, space_id, privacy_level) SELECT guild_id, space_id, privacy_level FROM guild_space; +-- 6 +DROP TABLE guild_space; +-- 7 +ALTER TABLE new_guild_space RENAME TO guild_space; + +-- *** member_cache *** + +-- 4 +CREATE TABLE "new_member_cache" ( + "room_id" TEXT NOT NULL, + "mxid" TEXT NOT NULL, + "displayname" TEXT, + "avatar_url" TEXT, power_level INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY("room_id","mxid"), + FOREIGN KEY("room_id") REFERENCES "channel_room"("room_id") ON DELETE CASCADE +) WITHOUT ROWID; +-- 5 +INSERT INTO new_member_cache (room_id, mxid, displayname, avatar_url) SELECT room_id, mxid, displayname, avatar_url FROM member_cache WHERE room_id IN (SELECT room_id FROM channel_room); +-- 6 +DROP TABLE member_cache; +-- 7 +ALTER TABLE new_member_cache RENAME TO member_cache; + +-- *** reaction *** + +-- 4 +CREATE TABLE "new_reaction" ( + "hashed_event_id" INTEGER NOT NULL, + "message_id" TEXT NOT NULL, + "encoded_emoji" TEXT NOT NULL, + PRIMARY KEY("hashed_event_id"), + FOREIGN KEY("message_id") REFERENCES "message_channel"("message_id") ON DELETE CASCADE +) WITHOUT ROWID; +-- 5 +INSERT INTO new_reaction (hashed_event_id, message_id, encoded_emoji) SELECT hashed_event_id, message_id, encoded_emoji FROM reaction WHERE message_id IN (SELECT message_id FROM message_channel); +-- 6 +DROP TABLE reaction; +-- 7 +ALTER TABLE new_reaction RENAME TO reaction; + +-- *** webhook *** + +-- 4 +-- using RESTRICT instead of CASCADE as a reminder that the webhooks also need to be deleted using the Discord API, it can't just be entirely automatic +CREATE TABLE "new_webhook" ( + "channel_id" TEXT NOT NULL, + "webhook_id" TEXT NOT NULL, + "webhook_token" TEXT NOT NULL, + PRIMARY KEY("channel_id"), + FOREIGN KEY("channel_id") REFERENCES "channel_room"("channel_id") ON DELETE RESTRICT +) WITHOUT ROWID; +-- 5 +INSERT INTO new_webhook (channel_id, webhook_id, webhook_token) SELECT channel_id, webhook_id, webhook_token FROM webhook WHERE channel_id IN (SELECT channel_id FROM channel_room); +-- 6 +DROP TABLE webhook; +-- 7 +ALTER TABLE new_webhook RENAME TO webhook; + +-- *** sim *** + +-- 4 +-- while we're at it, rebuild this table to give it WITHOUT ROWID, remove UNIQUE, and drop the localpart column. no foreign keys needed +CREATE TABLE "new_sim" ( + "user_id" TEXT NOT NULL, + "sim_name" TEXT NOT NULL, + "mxid" TEXT NOT NULL, + PRIMARY KEY("user_id") +) WITHOUT ROWID; +-- 5 +INSERT INTO new_sim (user_id, sim_name, mxid) SELECT user_id, sim_name, mxid FROM sim; +-- 6 +DROP TABLE sim; +-- 7 +ALTER TABLE new_sim RENAME TO sim; + +-- *** end *** + +-- 10 +PRAGMA foreign_key_check; +-- 11 +COMMIT; diff --git a/src/m2d/actions/redact.js b/src/m2d/actions/redact.js index 5a12d5a..1f6cef8 100644 --- a/src/m2d/actions/redact.js +++ b/src/m2d/actions/redact.js @@ -13,7 +13,6 @@ const utils = sync.require("../converters/utils") */ async function deleteMessage(event) { const rows = from("event_message").join("message_channel", "message_id").select("channel_id", "message_id").where({event_id: event.redacts}).all() - db.prepare("DELETE FROM event_message WHERE event_id = ?").run(event.redacts) for (const row of rows) { db.prepare("DELETE FROM message_channel WHERE message_id = ?").run(row.message_id) await discord.snow.channel.deleteMessage(row.channel_id, row.message_id, event.content.reason) diff --git a/src/m2d/actions/send-event.js b/src/m2d/actions/send-event.js index 0a270a0..35fcfda 100644 --- a/src/m2d/actions/send-event.js +++ b/src/m2d/actions/send-event.js @@ -102,14 +102,13 @@ async function sendEvent(event) { for (const id of messagesToDelete) { db.prepare("DELETE FROM message_channel WHERE message_id = ?").run(id) - db.prepare("DELETE FROM event_message WHERE message_id = ?").run(id) await channelWebhook.deleteMessageWithWebhook(channelID, id, threadID) } for (const message of messagesToSend) { const reactionPart = messagesToEdit.length === 0 && message === messagesToSend[messagesToSend.length - 1] ? 0 : 1 const messageResponse = await channelWebhook.sendMessageWithWebhook(channelID, message, threadID) - db.prepare("REPLACE INTO message_channel (message_id, channel_id) VALUES (?, ?)").run(messageResponse.id, threadID || channelID) + db.prepare("INSERT INTO message_channel (message_id, channel_id) VALUES (?, ?)").run(messageResponse.id, threadID || channelID) db.prepare("INSERT INTO event_message (event_id, event_type, event_subtype, message_id, part, reaction_part, source) VALUES (?, ?, ?, ?, ?, ?, 0)").run(event.event_id, event.type, event.content["msgtype"] || null, messageResponse.id, eventPart, reactionPart) // source 0 = matrix eventPart = 1 diff --git a/src/m2d/converters/event-to-message.js b/src/m2d/converters/event-to-message.js index b52717d..c498f1e 100644 --- a/src/m2d/converters/event-to-message.js +++ b/src/m2d/converters/event-to-message.js @@ -258,7 +258,13 @@ async function getMemberFromCacheOrHomeserver(roomID, mxid, api) { const row = select("member_cache", ["displayname", "avatar_url"], {room_id: roomID, mxid}).get() if (row) return row return api.getStateEvent(roomID, "m.room.member", mxid).then(event => { - db.prepare("REPLACE INTO member_cache (room_id, mxid, displayname, avatar_url) VALUES (?, ?, ?, ?)").run(roomID, mxid, event?.displayname || null, event?.avatar_url || null) + const displayname = event?.displayname || null + const avatar_url = event?.avatar_url || null + db.prepare("INSERT INTO member_cache (room_id, mxid, displayname, avatar_url) VALUES (?, ?, ?, ?) ON CONFLICT DO UPDATE SET displayname = ?, avatar_url = ?").run( + roomID, mxid, + displayname, avatar_url, + displayname, avatar_url + ) return event }).catch(() => { return {displayname: null, avatar_url: null} diff --git a/src/m2d/converters/event-to-message.test.js b/src/m2d/converters/event-to-message.test.js index 145e9ec..0dc9110 100644 --- a/src/m2d/converters/event-to-message.test.js +++ b/src/m2d/converters/event-to-message.test.js @@ -559,7 +559,7 @@ test("event2message: lists are bridged correctly", async t => { "transaction_id": "m1692967313951.441" }, "event_id": "$l-xQPY5vNJo3SNxU9d8aOWNVD1glMslMyrp4M_JEF70", - "room_id": "!BpMdOUkWWhFxmTrENV:cadence.moe" + "room_id": "!kLRqKKUQXcibIMtOpl:cadence.moe" }), { ensureJoined: [], @@ -662,7 +662,7 @@ test("event2message: code block contents are formatted correctly and not escaped formatted_body: "
input = input.replace(/(<\\/?([^ >]+)[^>]*>)?\\n(<\\/?([^ >]+)[^>]*>)?/g,\n_input_ = input = input.replace(/(<\\/?([^ >]+)[^>]*>)?\\n(<\\/?([^ >]+)[^>]*>)?/g,\n
\n

input = input.replace(/(<\\/?([^ >]+)[^>]*>)?\\n(<\\/?([^ >]+)[^>]*>)?/g,

\n" }, event_id: "$pGkWQuGVmrPNByrFELxhzI6MCBgJecr5I2J3z88Gc2s", - room_id: "!BpMdOUkWWhFxmTrENV:cadence.moe" + room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe" }), { ensureJoined: [], @@ -692,7 +692,7 @@ test("event2message: code blocks use double backtick as delimiter when necessary formatted_body: "backtick in ` the middle, backtick at the edge`" }, event_id: "$pGkWQuGVmrPNByrFELxhzI6MCBgJecr5I2J3z88Gc2s", - room_id: "!BpMdOUkWWhFxmTrENV:cadence.moe" + room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe" }), { ensureJoined: [], @@ -722,7 +722,7 @@ test("event2message: inline code is converted to code block if it contains both formatted_body: "` one two ``" }, event_id: "$pGkWQuGVmrPNByrFELxhzI6MCBgJecr5I2J3z88Gc2s", - room_id: "!BpMdOUkWWhFxmTrENV:cadence.moe" + room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe" }), { ensureJoined: [], @@ -752,7 +752,7 @@ test("event2message: code blocks are uploaded as attachments instead if they con formatted_body: 'So if you run code like this
System.out.println("```");
it should print a markdown formatted code block' }, event_id: "$pGkWQuGVmrPNByrFELxhzI6MCBgJecr5I2J3z88Gc2s", - room_id: "!BpMdOUkWWhFxmTrENV:cadence.moe" + room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe" }), { ensureJoined: [], @@ -784,7 +784,7 @@ test("event2message: code blocks are uploaded as attachments instead if they con formatted_body: 'So if you run code like this
System.out.println("```");
it should print a markdown formatted code block' }, event_id: "$pGkWQuGVmrPNByrFELxhzI6MCBgJecr5I2J3z88Gc2s", - room_id: "!BpMdOUkWWhFxmTrENV:cadence.moe" + room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe" }), { ensureJoined: [], @@ -821,7 +821,7 @@ test("event2message: characters are encoded properly in code blocks", async t => + '\n' }, event_id: "$pGkWQuGVmrPNByrFELxhzI6MCBgJecr5I2J3z88Gc2s", - room_id: "!BpMdOUkWWhFxmTrENV:cadence.moe" + room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe" }), { ensureJoined: [], @@ -902,7 +902,7 @@ test("event2message: lists have appropriate line breaks", async t => { 'm.mentions': {}, msgtype: 'm.text' }, - room_id: '!cBxtVRxDlZvSVhJXVK:cadence.moe', + room_id: '!TqlyQmifxGUggEmdBN:cadence.moe', sender: '@Milan:tchncs.de', type: 'm.room.message', }), @@ -943,7 +943,7 @@ test("event2message: ordered list start attribute works", async t => { 'm.mentions': {}, msgtype: 'm.text' }, - room_id: '!cBxtVRxDlZvSVhJXVK:cadence.moe', + room_id: '!TqlyQmifxGUggEmdBN:cadence.moe', sender: '@Milan:tchncs.de', type: 'm.room.message', }), @@ -1088,7 +1088,7 @@ test("event2message: rich reply to a rich reply to a multi-line message should c content: { body: "> <@cadence:cadence.moe> I just checked in a fix that will probably work, can you try reproducing this on the latest `main` branch and see if I fixed it?\n\nwill try later (tomorrow if I don't forgor)", format: "org.matrix.custom.html", - formatted_body: "
In reply to @cadence:cadence.moe
I just checked in a fix that will probably work, can you try reproducing this on the latest main branch and see if I fixed it?
will try later (tomorrow if I don't forgor)", + formatted_body: "
In reply to @cadence:cadence.moe
I just checked in a fix that will probably work, can you try reproducing this on the latest main branch and see if I fixed it?
will try later (tomorrow if I don't forgor)", "m.relates_to": { "m.in_reply_to": { event_id: "$A0Rj559NKOh2VndCZSTJXcvgi42gZWVfVQt73wA2Hn0" @@ -1111,7 +1111,7 @@ test("event2message: rich reply to a rich reply to a multi-line message should c "msgtype": "m.text", "body": "> <@solonovamax:matrix.org> multipart messages will be deleted if the message is edited to require less space\n> \n> \n> steps to reproduce:\n> \n> 1. send a message that is longer than 2000 characters (discord character limit)\n> - bot will split message into two messages on discord\n> 2. edit message to be under 2000 characters (discord character limit)\n> - bot will delete one of the messages on discord, and then edit the other one to include the edited content\n> - the bot will *then* delete the message on matrix (presumably) because one of the messages on discord was deleted (by \n\nI just checked in a fix that will probably work, can you try reproducing this on the latest `main` branch and see if I fixed it?", "format": "org.matrix.custom.html", - "formatted_body": "
In reply to @solonovamax:matrix.org

multipart messages will be deleted if the message is edited to require less space

\n

steps to reproduce:

\n
    \n
  1. send a message that is longer than 2000 characters (discord character limit)
  2. \n
\n
    \n
  • bot will split message into two messages on discord
  • \n
\n
    \n
  1. edit message to be under 2000 characters (discord character limit)
  2. \n
\n
    \n
  • bot will delete one of the messages on discord, and then edit the other one to include the edited content
  • \n
  • the bot will then delete the message on matrix (presumably) because one of the messages on discord was deleted (by
  • \n
\n
I just checked in a fix that will probably work, can you try reproducing this on the latest main branch and see if I fixed it?", + "formatted_body": "
In reply to @solonovamax:matrix.org

multipart messages will be deleted if the message is edited to require less space

\n

steps to reproduce:

\n
    \n
  1. send a message that is longer than 2000 characters (discord character limit)
  2. \n
\n
    \n
  • bot will split message into two messages on discord
  • \n
\n
    \n
  1. edit message to be under 2000 characters (discord character limit)
  2. \n
\n
    \n
  • bot will delete one of the messages on discord, and then edit the other one to include the edited content
  • \n
  • the bot will then delete the message on matrix (presumably) because one of the messages on discord was deleted (by
  • \n
\n
I just checked in a fix that will probably work, can you try reproducing this on the latest main branch and see if I fixed it?", "m.relates_to": { "m.in_reply_to": { "event_id": "$u4OD19vd2GETkOyhgFVla92oDKI4ojwBf2-JeVCG7EI" @@ -1123,7 +1123,7 @@ test("event2message: rich reply to a rich reply to a multi-line message should c "age": 19069564 }, "event_id": "$A0Rj559NKOh2VndCZSTJXcvgi42gZWVfVQt73wA2Hn0", - "room_id": "!cBxtVRxDlZvSVhJXVK:cadence.moe" + "room_id": "!TqlyQmifxGUggEmdBN:cadence.moe" }) }, snow: { @@ -3476,6 +3476,56 @@ test("event2message: colon after mentions is stripped", async t => { }) test("event2message: caches the member if the member is not known", async t => { + let called = 0 + t.deepEqual( + await eventToMessage({ + content: { + body: "testing the member state cache", + msgtype: "m.text" + }, + event_id: "$g07oYSZFWBkxohNEfywldwgcWj1hbhDzQ1sBAKvqOOU", + origin_server_ts: 1688301929913, + room_id: "!qzDBLKlildpzrrOnFZ:cadence.moe", + sender: "@should_be_newly_cached:cadence.moe", + type: "m.room.message", + unsigned: { + age: 405299 + } + }, {}, { + api: { + getStateEvent: async (roomID, type, stateKey) => { + called++ + t.equal(roomID, "!qzDBLKlildpzrrOnFZ:cadence.moe") + t.equal(type, "m.room.member") + t.equal(stateKey, "@should_be_newly_cached:cadence.moe") + return { + avatar_url: "mxc://cadence.moe/this_is_the_avatar" + } + } + } + }), + { + ensureJoined: [], + messagesToDelete: [], + messagesToEdit: [], + messagesToSend: [{ + username: "should_be_newly_cached", + content: "testing the member state cache", + avatar_url: "https://bridge.example.org/download/matrix/cadence.moe/this_is_the_avatar", + allowed_mentions: { + parse: ["users", "roles"] + } + }] + } + ) + + t.deepEqual(select("member_cache", ["avatar_url", "displayname", "mxid"], {room_id: "!qzDBLKlildpzrrOnFZ:cadence.moe"}).all(), [ + {avatar_url: "mxc://cadence.moe/this_is_the_avatar", displayname: null, mxid: "@should_be_newly_cached:cadence.moe"} + ]) + t.equal(called, 1, "getStateEvent should be called once") +}) + +test("event2message: does not cache the member if the room is not known", async t => { let called = 0 t.deepEqual( await eventToMessage({ @@ -3511,7 +3561,7 @@ test("event2message: caches the member if the member is not known", async t => { messagesToSend: [{ username: "should_be_newly_cached", content: "testing the member state cache", - avatar_url: "https://bridge.example.org/download/matrix/cadence.moe/this_is_the_avatar", + avatar_url: undefined, allowed_mentions: { parse: ["users", "roles"] } @@ -3519,9 +3569,7 @@ test("event2message: caches the member if the member is not known", async t => { } ) - t.deepEqual(select("member_cache", ["avatar_url", "displayname", "mxid"], {room_id: "!should_be_newly_cached:cadence.moe"}).all(), [ - {avatar_url: "mxc://cadence.moe/this_is_the_avatar", displayname: null, mxid: "@should_be_newly_cached:cadence.moe"} - ]) + t.deepEqual(select("member_cache", ["avatar_url", "displayname", "mxid"], {room_id: "!should_be_newly_cached:cadence.moe"}).all(), []) t.equal(called, 1, "getStateEvent should be called once") }) @@ -3580,7 +3628,7 @@ test("event2message: overly long usernames are shifted into the message content" }, event_id: "$g07oYSZFWBkxohNEfywldwgcWj1hbhDzQ1sBAKvqOOU", origin_server_ts: 1688301929913, - room_id: "!should_be_newly_cached_2:cadence.moe", + room_id: "!cqeGDbPiMFAhLsqqqq:cadence.moe", sender: "@should_be_newly_cached_2:cadence.moe", type: "m.room.message", unsigned: { @@ -3590,7 +3638,7 @@ test("event2message: overly long usernames are shifted into the message content" api: { getStateEvent: async (roomID, type, stateKey) => { called++ - t.equal(roomID, "!should_be_newly_cached_2:cadence.moe") + t.equal(roomID, "!cqeGDbPiMFAhLsqqqq:cadence.moe") t.equal(type, "m.room.member") t.equal(stateKey, "@should_be_newly_cached_2:cadence.moe") return { @@ -3613,7 +3661,7 @@ test("event2message: overly long usernames are shifted into the message content" }] } ) - t.deepEqual(select("member_cache", ["avatar_url", "displayname", "mxid"], {room_id: "!should_be_newly_cached_2:cadence.moe"}).all(), [ + t.deepEqual(select("member_cache", ["avatar_url", "displayname", "mxid"], {room_id: "!cqeGDbPiMFAhLsqqqq:cadence.moe"}).all(), [ {avatar_url: null, displayname: "I am BLACK I am WHITE I am SHORT I am LONG I am EVERYTHING YOU THINK IS IMPORTANT and I DON'T MATTER", mxid: "@should_be_newly_cached_2:cadence.moe"} ]) t.equal(called, 1, "getStateEvent should be called once") @@ -3628,7 +3676,7 @@ test("event2message: overly long usernames are not treated specially when the ms }, event_id: "$g07oYSZFWBkxohNEfywldwgcWj1hbhDzQ1sBAKvqOOU", origin_server_ts: 1688301929913, - room_id: "!should_be_newly_cached_2:cadence.moe", + room_id: "!cqeGDbPiMFAhLsqqqq:cadence.moe", sender: "@should_be_newly_cached_2:cadence.moe", type: "m.room.message", unsigned: { @@ -4477,7 +4525,7 @@ slow()("event2message: all unknown chess emojis are reuploaded as a sprite sheet formatted_body: "testing \":chess_good_move:\"\":chess_incorrect:\"\":chess_blund:\"\":chess_brilliant_move:\"\":chess_blundest:\"\":chess_draw_black:\"\":chess_good_move:\"\":chess_incorrect:\"\":chess_blund:\"\":chess_brilliant_move:\"\":chess_blundest:\"\":chess_draw_black:\"" }, event_id: "$Me6iE8C8CZyrDEOYYrXKSYRuuh_25Jj9kZaNrf7LKr4", - room_id: "!maggESguZBqGBZtSnr:cadence.moe" + room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe" }, {}, {mxcDownloader: mockGetAndConvertEmoji}) const testResult = { content: messages.messagesToSend[0].content, diff --git a/src/m2d/event-dispatcher.js b/src/m2d/event-dispatcher.js index a270293..6cbd6c6 100644 --- a/src/m2d/event-dispatcher.js +++ b/src/m2d/event-dispatcher.js @@ -199,18 +199,29 @@ sync.addTemporaryListener(as, "type:m.room.member", guard("m.room.member", async event => { if (event.state_key[0] !== "@") return if (utils.eventSenderIsFromDiscord(event.state_key)) return + if (event.content.membership === "leave" || event.content.membership === "ban") { // Member is gone - db.prepare("DELETE FROM member_cache WHERE room_id = ? and mxid = ?").run(event.room_id, event.state_key) - } else { - // Member is here - db.prepare("INSERT INTO member_cache (room_id, mxid, displayname, avatar_url) VALUES (?, ?, ?, ?) ON CONFLICT DO UPDATE SET displayname = ?, avatar_url = ?") - .run( - event.room_id, event.state_key, - event.content.displayname || null, event.content.avatar_url || null, - event.content.displayname || null, event.content.avatar_url || null - ) + return db.prepare("DELETE FROM member_cache WHERE room_id = ? and mxid = ?").run(event.room_id, event.state_key) } + + const room = select("channel_room", "room_id", {room_id: event.room_id}) + if (!room) return // don't cache members in unbridged rooms + + // Member is here + let powerLevel = 0 + try { + /** @type {Ty.Event.M_Power_Levels} */ + const powerLevelsEvent = await api.getStateEvent(event.room_id, "m.room.power_levels", "") + powerLevel = powerLevelsEvent.users?.[event.state_key] ?? powerLevelsEvent.users_default ?? 0 + } catch (e) {} + const displayname = event.content.displayname || null + const avatar_url = event.content.avatar_url + db.prepare("INSERT INTO member_cache (room_id, mxid, displayname, avatar_url, power_level) VALUES (?, ?, ?, ?, ?) ON CONFLICT DO UPDATE SET displayname = ?, avatar_url = ?, power_level = ?").run( + event.room_id, event.state_key, + displayname, avatar_url, powerLevel, + displayname, avatar_url, powerLevel + ) })) sync.addTemporaryListener(as, "type:m.room.power_levels", guard("m.room.power_levels", diff --git a/src/web/routes/oauth.js b/src/web/routes/oauth.js index 12c991d..1a3753f 100644 --- a/src/web/routes/oauth.js +++ b/src/web/routes/oauth.js @@ -87,7 +87,8 @@ as.router.get("/oauth", defineEventHandler(async event => { // Set auto-create for the guild // @ts-ignore if (managedGuilds.includes(parsedQuery.data.guild_id)) { - db.prepare("REPLACE INTO guild_active (guild_id, autocreate) VALUES (?, ?)").run(parsedQuery.data.guild_id, +!session.data.selfService) + const autocreateInteger = +!session.data.selfService + db.prepare("INSERT INTO guild_active (guild_id, autocreate) VALUES (?, ?) ON CONFLICT DO UPDATE SET autocreate = ?").run(parsedQuery.data.guild_id, autocreateInteger, autocreateInteger) } if (parsedQuery.data.guild_id) { diff --git a/test/ooye-test-data.sql b/test/ooye-test-data.sql index 38fed25..757ef9b 100644 --- a/test/ooye-test-data.sql +++ b/test/ooye-test-data.sql @@ -1,13 +1,14 @@ BEGIN TRANSACTION; -INSERT INTO guild_space (guild_id, space_id, privacy_level) VALUES -('112760669178241024', '!jjWAGMeQdNrVZSSfvz:cadence.moe', 0); - INSERT INTO guild_active (guild_id, autocreate) VALUES ('112760669178241024', 1); +INSERT INTO guild_space (guild_id, space_id, privacy_level) VALUES +('112760669178241024', '!jjWAGMeQdNrVZSSfvz:cadence.moe', 0); + INSERT INTO channel_room (channel_id, room_id, name, nick, thread_parent, custom_avatar) VALUES ('112760669178241024', '!kLRqKKUQXcibIMtOpl:cadence.moe', 'heave', 'main', NULL, NULL), +('687028734322147344', '!fGgIymcYWOqjbSRUdV:cadence.moe', 'slow-news-day', NULL, NULL, NULL), ('497161350934560778', '!CzvdIdUQXgUjDVKxeU:cadence.moe', 'amanda-spam', NULL, NULL, NULL), ('160197704226439168', '!hYnGGlPHlbujVVfktC:cadence.moe', 'the-stanley-parable-channel', 'bots', NULL, NULL), ('1100319550446252084', '!BnKuBPCvyfOkhcUjEu:cadence.moe', 'worm-farm', NULL, NULL, NULL), @@ -18,25 +19,25 @@ INSERT INTO channel_room (channel_id, room_id, name, nick, thread_parent, custom ('489237891895768942', '!tnedrGVYKFNUdnegvf:tchncs.de', 'ex-room-doesnt-exist-any-more', NULL, NULL, NULL), ('1160894080998461480', '!TqlyQmifxGUggEmdBN:cadence.moe', 'ooyexperiment', NULL, NULL, NULL); -INSERT INTO sim (user_id, sim_name, localpart, mxid) VALUES -('0', 'bot', '_ooye_bot', '@_ooye_bot:cadence.moe'), -('820865262526005258', 'crunch_god', '_ooye_crunch_god', '@_ooye_crunch_god:cadence.moe'), -('771520384671416320', 'bojack_horseman', '_ooye_bojack_horseman', '@_ooye_bojack_horseman:cadence.moe'), -('112890272819507200', '.wing.', '_ooye_.wing.', '@_ooye_.wing.:cadence.moe'), -('114147806469554185', 'extremity', '_ooye_extremity', '@_ooye_extremity:cadence.moe'), -('111604486476181504', 'kyuugryphon', '_ooye_kyuugryphon', '@_ooye_kyuugryphon:cadence.moe'), -('1109360903096369153', 'amanda', '_ooye_amanda', '@_ooye_amanda:cadence.moe'), -('43d378d5-1183-47dc-ab3c-d14e21c3fe58', '_pk_zoego', '_ooye__pk_zoego', '@_ooye__pk_zoego:cadence.moe'), -('320067006521147393', 'papiophidian', '_ooye_papiophidian', '@_ooye_papiophidian:cadence.moe'), -('772659086046658620', 'cadence', '_ooye_cadence', '@_ooye_cadence:cadence.moe'); - -INSERT INTO sim_proxy (user_id, proxy_owner_id, displayname) VALUES -('43d378d5-1183-47dc-ab3c-d14e21c3fe58', '196188877885538304', 'Azalea &flwr; 🌺'); +INSERT INTO sim (user_id, sim_name, mxid) VALUES +('0', 'bot', '@_ooye_bot:cadence.moe'), +('820865262526005258', 'crunch_god', '@_ooye_crunch_god:cadence.moe'), +('771520384671416320', 'bojack_horseman', '@_ooye_bojack_horseman:cadence.moe'), +('112890272819507200', '.wing.', '@_ooye_.wing.:cadence.moe'), +('114147806469554185', 'extremity', '@_ooye_extremity:cadence.moe'), +('111604486476181504', 'kyuugryphon', '@_ooye_kyuugryphon:cadence.moe'), +('1109360903096369153', 'amanda', '@_ooye_amanda:cadence.moe'), +('43d378d5-1183-47dc-ab3c-d14e21c3fe58', '_pk_zoego', '@_ooye__pk_zoego:cadence.moe'), +('320067006521147393', 'papiophidian', '@_ooye_papiophidian:cadence.moe'), +('772659086046658620', 'cadence', '@_ooye_cadence:cadence.moe'); INSERT INTO sim_member (mxid, room_id, hashed_profile_content) VALUES ('@_ooye_bojack_horseman:cadence.moe', '!hYnGGlPHlbujVVfktC:cadence.moe', NULL), ('@_ooye_cadence:cadence.moe', '!BnKuBPCvyfOkhcUjEu:cadence.moe', NULL); +INSERT INTO sim_proxy (user_id, proxy_owner_id, displayname) VALUES +('43d378d5-1183-47dc-ab3c-d14e21c3fe58', '196188877885538304', 'Azalea &flwr; 🌺'); + INSERT INTO message_channel (message_id, channel_id) VALUES ('1106366167788044450', '122155380120748034'), ('1106366167788044451', '122155380120748034'), @@ -65,7 +66,8 @@ INSERT INTO message_channel (message_id, channel_id) VALUES ('1273743950028607530', '1100319550446252084'), ('1278002262400176128', '1100319550446252084'), ('1278001833876525057', '1100319550446252084'), -('1191567971970191490', '176333891320283136'); +('1191567971970191490', '176333891320283136'), +('1144874214311067708', '687028734322147344'); INSERT INTO event_message (event_id, event_type, event_subtype, message_id, part, reaction_part, source) VALUES ('$X16nfVks1wsrhq4E9SSLiqrf2N8KD0erD0scZG7U5xg', 'm.room.message', 'm.text', '1126786462646550579', 0, 0, 1), @@ -140,19 +142,16 @@ INSERT INTO emoji (emoji_id, name, animated, mxc_url) VALUES INSERT INTO member_cache (room_id, mxid, displayname, avatar_url, power_level) VALUES ('!kLRqKKUQXcibIMtOpl:cadence.moe', '@cadence:cadence.moe', 'cadence [they]', NULL, 0), -('!BpMdOUkWWhFxmTrENV:cadence.moe', '@cadence:cadence.moe', 'cadence [they]', 'malformed mxc', 0), +('!kLRqKKUQXcibIMtOpl:cadence.moe', '@test_auto_invite:example.org', NULL, NULL, 0), ('!fGgIymcYWOqjbSRUdV:cadence.moe', '@cadence:cadence.moe', 'cadence [they]', 'mxc://cadence.moe/azCAhThKTojXSZJRoWwZmhvU', 0), ('!fGgIymcYWOqjbSRUdV:cadence.moe', '@rnl:cadence.moe', 'RNL', NULL, 0), ('!BnKuBPCvyfOkhcUjEu:cadence.moe', '@cadence:cadence.moe', 'cadence [they]', 'mxc://cadence.moe/azCAhThKTojXSZJRoWwZmhvU', 0), -('!maggESguZBqGBZtSnr:cadence.moe', '@cadence:cadence.moe', 'cadence [they]', 'mxc://cadence.moe/azCAhThKTojXSZJRoWwZmhvU', 0), +('!BnKuBPCvyfOkhcUjEu:cadence.moe', '@ami:the-apothecary.club', 'Ami (she/her)', NULL, 0), ('!CzvdIdUQXgUjDVKxeU:cadence.moe', '@cadence:cadence.moe', 'cadence [they]', 'mxc://cadence.moe/azCAhThKTojXSZJRoWwZmhvU', 0), -('!cBxtVRxDlZvSVhJXVK:cadence.moe', '@Milan:tchncs.de', 'Milan', NULL, 0), +('!TqlyQmifxGUggEmdBN:cadence.moe', '@Milan:tchncs.de', 'Milan', NULL, 0), ('!TqlyQmifxGUggEmdBN:cadence.moe', '@ampflower:matrix.org', 'Ampflower 🌺', 'mxc://cadence.moe/PRfhXYBTOalvgQYtmCLeUXko', 0), ('!TqlyQmifxGUggEmdBN:cadence.moe', '@aflower:syndicated.gay', 'Rose', 'mxc://syndicated.gay/ZkBUPXCiXTjdJvONpLJmcbKP', 0), -('!TqlyQmifxGUggEmdBN:cadence.moe', '@cadence:cadence.moe', 'cadence [they]', NULL, 0), -('!BnKuBPCvyfOkhcUjEu:cadence.moe', '@ami:the-apothecary.club', 'Ami (she/her)', NULL, 0), -('!kLRqKKUQXcibIMtOpl:cadence.moe', '@test_auto_invite:example.org', NULL, NULL, 0), -('!BpMdOUkWWhFxmTrENV:cadence.moe', '@test_auto_invite:example.org', NULL, NULL, 100); +('!TqlyQmifxGUggEmdBN:cadence.moe', '@cadence:cadence.moe', 'cadence [they]', NULL, 0); INSERT INTO reaction (hashed_event_id, message_id, encoded_emoji) VALUES (5162930312280790092, '1141501302736695317', '%F0%9F%90%88'); From 14574b4e2c31f451af069e029ce0db69219451b1 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Fri, 17 Jan 2025 11:40:34 +1300 Subject: [PATCH 082/228] Support alternate Discord hosts --- src/d2m/discord-client.js | 10 +++++++--- src/types.d.ts | 2 ++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/d2m/discord-client.js b/src/d2m/discord-client.js index bffb904..37b3eac 100644 --- a/src/d2m/discord-client.js +++ b/src/d2m/discord-client.js @@ -1,10 +1,14 @@ // @ts-check -const { SnowTransfer } = require("snowtransfer") -const { Client: CloudStorm } = require("cloudstorm") +const {Endpoints, SnowTransfer} = require("snowtransfer") +const {reg} = require("../matrix/read-registration") +const {Client: CloudStorm} = require("cloudstorm") + +// @ts-ignore +Endpoints.BASE_HOST = reg.ooye.discord_origin || "https://discord.com"; Endpoints.CDN_URL = reg.ooye.discord_cdn_origin || "https://cdn.discordapp.com" const passthrough = require("../passthrough") -const { sync } = passthrough +const {sync} = passthrough /** @type {import("./discord-packets")} */ const discordPackets = sync.require("./discord-packets") diff --git a/src/types.d.ts b/src/types.d.ts index 3298c40..84aad44 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -28,6 +28,8 @@ export type AppServiceRegistrationConfig = { content_length_workaround: boolean include_user_id_in_mxid: boolean invite: string[] + discord_origin?: string + discord_cdn_origin?: string } old_bridge?: { as_token: string From f42eb6495fba503401f84575751258d9ff9cafa0 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Fri, 17 Jan 2025 18:05:34 +1300 Subject: [PATCH 083/228] New unicode emoji processor --- scripts/emoji-surrogates-statistics.js | 77 + src/d2m/actions/remove-reaction.js | 2 +- src/m2d/actions/add-reaction.js | 2 +- src/m2d/converters/emoji.js | 128 +- src/m2d/converters/emoji.test.js | 52 + src/m2d/converters/emojis.txt | 3799 ++++++++++++++++++++++++ test/test.js | 1 + 7 files changed, 4015 insertions(+), 46 deletions(-) create mode 100644 scripts/emoji-surrogates-statistics.js create mode 100644 src/m2d/converters/emoji.test.js create mode 100644 src/m2d/converters/emojis.txt diff --git a/scripts/emoji-surrogates-statistics.js b/scripts/emoji-surrogates-statistics.js new file mode 100644 index 0000000..29abce3 --- /dev/null +++ b/scripts/emoji-surrogates-statistics.js @@ -0,0 +1,77 @@ +// @ts-check + +const fs = require("fs") +const {join} = require("path") +const s = fs.readFileSync(join(__dirname, "..", "src", "m2d", "converters", "emojis.txt"), "utf8").split("\n").map(x => encodeURIComponent(x)) +const searchPattern = "%EF%B8%8F" + +/** + * adapted from es.map.group-by.js in core-js + * @template K,V + * @param {V[]} items + * @param {(item: V) => K} fn + * @returns {Map} + */ +function groupBy(items, fn) { + var map = new Map(); + for (const value of items) { + var key = fn(value); + if (!map.has(key)) map.set(key, [value]); + else map.get(key).push(value); + } + return map; +} + +/** + * @param {number[]} items + * @param {number} width + */ +function xhistogram(items, width) { + const chars = " ▏▎▍▌▋▊▉" + const max = items.reduce((a, c) => c > a ? c : a, 0) + return items.map(v => { + const p = v / max * (width-1) + return ( + Array(Math.floor(p)).fill("█").join("") /* whole part */ + + chars[Math.ceil((p % 1) * (chars.length-1))] /* decimal part */ + ).padEnd(width) + }) +} + +/** + * @param {number[]} items + * @param {[number, number]} xrange + */ +function yhistogram(items, xrange, printHeader = false) { + const chars = "░▁_▂▃▄▅▆▇█" + const ones = "₀₁₂₃₄₅₆₇₈₉" + const tens = "0123456789" + const xy = [] + let max = 0 + /** value (x) -> frequency (y) */ + const grouped = groupBy(items, x => x) + for (let i = xrange[0]; i <= xrange[1]; i++) { + if (printHeader) { + if (i === -1) process.stdout.write("-") + else if (i.toString().at(-1) === "0") process.stdout.write(tens[i/10]) + else process.stdout.write(ones[i%10]) + } + const y = grouped.get(i)?.length ?? 0 + if (y > max) max = y + xy.push(y) + } + if (printHeader) console.log() + return xy.map(y => chars[Math.ceil(y / max * (chars.length-1))]).join("") +} + +const grouped = groupBy(s, x => x.length) +const sortedGroups = [...grouped.entries()].sort((a, b) => b[0] - a[0]) +let length = 0 +const lengthHistogram = xhistogram(sortedGroups.map(v => v[1].length), 10) +for (let i = 0; i < sortedGroups.length; i++) { + const [k, v] = sortedGroups[i] + const l = lengthHistogram[i] + const h = yhistogram(v.map(x => x.indexOf(searchPattern)), [-1, k - searchPattern.length], i === 0) + if (i === 0) length = h.length + 1 + console.log(`${h.padEnd(length, i % 2 === 0 ? "⸱" : " ")}length ${k.toString().padEnd(3)} ${l} ${v.length}`) +} diff --git a/src/d2m/actions/remove-reaction.js b/src/d2m/actions/remove-reaction.js index d991f08..6f922cb 100644 --- a/src/d2m/actions/remove-reaction.js +++ b/src/d2m/actions/remove-reaction.js @@ -53,7 +53,7 @@ async function removeReaction(data, reactions) { */ async function removeEmojiReaction(data, reactions) { const key = await emojiToKey.emojiToKey(data.emoji) - const discordPreferredEncoding = emoji.encodeEmoji(key, undefined) + const discordPreferredEncoding = await emoji.encodeEmoji(key, undefined) db.prepare("DELETE FROM reaction WHERE message_id = ? AND encoded_emoji = ?").run(data.message_id, discordPreferredEncoding) return converter.removeEmojiReaction(data, reactions, key) diff --git a/src/m2d/actions/add-reaction.js b/src/m2d/actions/add-reaction.js index cfd471b..d54bf77 100644 --- a/src/m2d/actions/add-reaction.js +++ b/src/m2d/actions/add-reaction.js @@ -20,7 +20,7 @@ async function addReaction(event) { if (!messageID) return // Nothing can be done if the parent message was never bridged. const key = event.content["m.relates_to"].key - const discordPreferredEncoding = emoji.encodeEmoji(key, event.content.shortcode) + const discordPreferredEncoding = await emoji.encodeEmoji(key, event.content.shortcode) if (!discordPreferredEncoding) return await discord.snow.channel.createReaction(channelID, messageID, discordPreferredEncoding) // acting as the discord bot itself diff --git a/src/m2d/converters/emoji.js b/src/m2d/converters/emoji.js index 66a690c..63e53a9 100644 --- a/src/m2d/converters/emoji.js +++ b/src/m2d/converters/emoji.js @@ -1,58 +1,98 @@ // @ts-check -const assert = require("assert").strict -const Ty = require("../../types") +const fsp = require("fs").promises +const {join} = require("path") +const emojisp = fsp.readFile(join(__dirname, "emojis.txt"), "utf8").then(content => content.split("\n")) const passthrough = require("../../passthrough") -const {sync, select} = passthrough +const {select} = passthrough + /** * @param {string} input * @param {string | null | undefined} shortcode * @returns {string?} */ -function encodeEmoji(input, shortcode) { - let discordPreferredEncoding - if (input.startsWith("mxc://")) { - // Custom emoji - let row = select("emoji", ["emoji_id", "name"], {mxc_url: input}).get() - if (!row && shortcode) { - // Use the name to try to find a known emoji with the same name. - const name = shortcode.replace(/^:|:$/g, "") - row = select("emoji", ["emoji_id", "name"], {name: name}).get() - } - if (!row) { - // We don't have this emoji and there's no realistic way to just-in-time upload a new emoji somewhere. - // Sucks! - return null - } - // Cool, we got an exact or a candidate emoji. - discordPreferredEncoding = encodeURIComponent(`${row.name}:${row.emoji_id}`) - } else { - // Default emoji - // https://github.com/discord/discord-api-docs/issues/2723#issuecomment-807022205 ???????????? - const encoded = encodeURIComponent(input) - const encodedTrimmed = encoded.replace(/%EF%B8%8F/g, "") - - const forceTrimmedList = [ - "%F0%9F%91%8D", // 👍 - "%F0%9F%91%8E", // 👎️ - "%E2%AD%90", // ⭐ - "%F0%9F%90%88", // 🐈 - "%E2%9D%93", // ❓ - "%F0%9F%8F%86", // 🏆️ - "%F0%9F%93%9A", // 📚️ - "%F0%9F%90%9F", // 🐟️ - ] - - discordPreferredEncoding = - ( forceTrimmedList.includes(encodedTrimmed) ? encodedTrimmed - : encodedTrimmed !== encoded && [...input].length === 2 ? encoded - : encodedTrimmed) - - console.log("add reaction from matrix:", input, encoded, encodedTrimmed, "chosen:", discordPreferredEncoding) +function encodeCustomEmoji(input, shortcode) { + // Custom emoji + let row = select("emoji", ["emoji_id", "name"], {mxc_url: input}).get() + if (!row && shortcode) { + // Use the name to try to find a known emoji with the same name. + const name = shortcode.replace(/^:|:$/g, "") + row = select("emoji", ["emoji_id", "name"], {name: name}).get() + } + if (!row) { + // We don't have this emoji and there's no realistic way to just-in-time upload a new emoji somewhere. Sucks! + return null + } + return encodeURIComponent(`${row.name}:${row.emoji_id}`) +} + +/** + * @param {string} input + * @returns {Promise} URL encoded! + */ +async function encodeDefaultEmoji(input) { + // Default emoji + + // Shortcut: If there are ASCII letters then it's not an emoji, it's a freeform Matrix text reaction. + // (Regional indicator letters are not ASCII. ASCII digits might be part of an emoji.) + if (input.match(/[A-Za-z]/)) return null + + // Check against the dataset + const emojis = await emojisp + const encoded = encodeURIComponent(input) + + // Best case scenario: they reacted with an exact replica of a valid emoji. + if (emojis.includes(input)) return encoded + + // Maybe it has some extraneous \ufe0f or \ufe0e (at the end or in the middle), and it'll be valid if they're removed. + const trimmed = input.replace(/\ufe0e|\ufe0f/g, "") + const trimmedEncoded = encodeURIComponent(trimmed) + if (trimmed !== input) { + if (emojis.includes(trimmed)) return trimmedEncoded + } + + // Okay, well, maybe it was already missing one and it actually needs an extra \ufe0f, and it'll be valid if that's added. + else { + const appended = input + "\ufe0f" + const appendedEncoded = encodeURIComponent(appended) + if (emojis.includes(appended)) return appendedEncoded + } + + // Hmm, so adding or removing that from the end didn't help, but maybe there needs to be one in the middle? We can try some heuristics. + // These heuristics come from executing scripts/emoji-surrogates-statistics.js. + if (trimmedEncoded.length <= 21 && trimmed.match(/^[*#0-9]/)) { // ->19: Keycap digit? 0️⃣ 1️⃣ 2️⃣ 3️⃣ 4️⃣ 5️⃣ 6️⃣ 7️⃣ 8️⃣ 9️⃣ *️⃣ #️⃣ + const keycap = trimmed[0] + "\ufe0f" + trimmed.slice(1) + if (emojis.includes(keycap)) return encodeURIComponent(keycap) + } else if (trimmedEncoded.length === 27 && trimmed[0] === "⛹") { // ->45: ⛹️‍♀️ ⛹️‍♂️ + const balling = trimmed[0] + "\ufe0f" + trimmed.slice(1) + "\ufe0f" + if (emojis.includes(balling)) return encodeURIComponent(balling) + } else if (trimmedEncoded.length === 30) { // ->39: ⛓️‍💥 ❤️‍🩹 ❤️‍🔥 or ->48: 🏳️‍⚧️ 🏌️‍♀️ 🕵️‍♀️ 🏋️‍♀️ and gender variants + const thriving = trimmed[0] + "\ufe0f" + trimmed.slice(1) + if (emojis.includes(thriving)) return encodeURIComponent(thriving) + const powerful = trimmed.slice(0, 2) + "\ufe0f" + trimmed.slice(2) + "\ufe0f" + if (emojis.includes(powerful)) return encodeURIComponent(powerful) + } else if (trimmedEncoded.length === 51 && trimmed[3] === "❤") { // ->60: 👩‍❤️‍👨 👩‍❤️‍👩 👨‍❤️‍👨 + const yellowRomance = trimmed.slice(0, 3) + "❤\ufe0f" + trimmed.slice(4) + if (emojis.includes(yellowRomance)) return encodeURIComponent(yellowRomance) + } + + // there are a few more longer ones but I got bored + return null +} + +/** + * @param {string} input + * @param {string | null | undefined} shortcode + * @returns {Promise} + */ +async function encodeEmoji(input, shortcode) { + if (input.startsWith("mxc://")) { + return encodeCustomEmoji(input, shortcode) + } else { + return encodeDefaultEmoji(input) } - return discordPreferredEncoding } module.exports.encodeEmoji = encodeEmoji diff --git a/src/m2d/converters/emoji.test.js b/src/m2d/converters/emoji.test.js new file mode 100644 index 0000000..ad9846b --- /dev/null +++ b/src/m2d/converters/emoji.test.js @@ -0,0 +1,52 @@ +// @ts-check + +const {test} = require("supertape") +const {encodeEmoji} = require("./emoji") + +test("emoji: valid", async t => { + t.equal(await encodeEmoji("🦄", null), "%F0%9F%A6%84") +}) + +test("emoji: freeform text", async t => { + t.equal(await encodeEmoji("ha", null), null) +}) + +test("emoji: suspicious unicode", async t => { + t.equal(await encodeEmoji("Ⓐ", null), null) +}) + +test("emoji: needs u+fe0f added", async t => { + t.equal(await encodeEmoji("☺", null), "%E2%98%BA%EF%B8%8F") +}) + +test("emoji: needs u+fe0f removed", async t => { + t.equal(await encodeEmoji("⭐️", null), "%E2%AD%90") +}) + +test("emoji: number key needs u+fe0f in the middle", async t => { + t.equal(await encodeEmoji("3⃣", null), "3%EF%B8%8F%E2%83%A3") +}) + +test("emoji: hash key needs u+fe0f in the middle", async t => { + t.equal(await encodeEmoji("#⃣", null), "%23%EF%B8%8F%E2%83%A3") +}) + +test("emoji: broken chains needs u+fe0f in the middle", async t => { + t.equal(await encodeEmoji("⛓‍💥", null), "%E2%9B%93%EF%B8%8F%E2%80%8D%F0%9F%92%A5") +}) + +test("emoji: balling needs u+fe0f in the middle", async t => { + t.equal(await encodeEmoji("⛹‍♀", null), "%E2%9B%B9%EF%B8%8F%E2%80%8D%E2%99%80%EF%B8%8F") +}) + +test("emoji: trans flag needs u+fe0f in the middle", async t => { + t.equal(await encodeEmoji("🏳‍⚧", null), "%F0%9F%8F%B3%EF%B8%8F%E2%80%8D%E2%9A%A7%EF%B8%8F") +}) + +test("emoji: spy needs u+fe0f in the middle", async t => { + t.equal(await encodeEmoji("🕵‍♀", null), "%F0%9F%95%B5%EF%B8%8F%E2%80%8D%E2%99%80%EF%B8%8F") +}) + +test("emoji: couple needs u+fe0f in the middle", async t => { + t.equal(await encodeEmoji("👩‍❤‍👩", null), "%F0%9F%91%A9%E2%80%8D%E2%9D%A4%EF%B8%8F%E2%80%8D%F0%9F%91%A9") +}) diff --git a/src/m2d/converters/emojis.txt b/src/m2d/converters/emojis.txt new file mode 100644 index 0000000..32c3f15 --- /dev/null +++ b/src/m2d/converters/emojis.txt @@ -0,0 +1,3799 @@ +😀 +😃 +😄 +😁 +😆 +🥹 +😅 +😂 +🤣 +🥲 +☺️ +😊 +😇 +🙂 +🙃 +😉 +😌 +😍 +🥰 +😘 +😗 +😙 +😚 +😋 +😛 +😝 +😜 +🤪 +🤨 +🧐 +🤓 +😎 +🥸 +🤩 +🥳 +😏 +😒 +😞 +😔 +😟 +😕 +🙁 +☹️ +😣 +😖 +😫 +😩 +🥺 +😢 +😭 +😤 +😠 +😡 +🤬 +🤯 +😳 +🥵 +🥶 +😶‍🌫️ +😱 +😨 +😰 +😥 +😓 +🤗 +🤔 +🫣 +🤭 +🫢 +🫡 +🤫 +🫠 +🤥 +😶 +🫥 +😐 +🫤 +😑 +🫨 +🙂‍↔️ +🙂‍↕️ +😬 +🙄 +😯 +😦 +😧 +😮 +😲 +🥱 +😴 +🤤 +😪 +😮‍💨 +😵 +😵‍💫 +🤐 +🥴 +🤢 +🤮 +🤧 +😷 +🤒 +🤕 +🤑 +🤠 +😈 +👿 +👹 +👺 +🤡 +💩 +👻 +💀 +☠️ +👽 +👾 +🤖 +🎃 +😺 +😸 +😹 +😻 +😼 +😽 +🙀 +😿 +😾 +🤝🏻 +🫱🏻‍🫲🏼 +🫱🏻‍🫲🏽 +🫱🏻‍🫲🏾 +🫱🏻‍🫲🏿 +🫱🏼‍🫲🏻 +🤝🏼 +🫱🏼‍🫲🏽 +🫱🏼‍🫲🏾 +🫱🏼‍🫲🏿 +🫱🏽‍🫲🏻 +🫱🏽‍🫲🏼 +🤝🏽 +🫱🏽‍🫲🏾 +🫱🏽‍🫲🏿 +🫱🏾‍🫲🏻 +🫱🏾‍🫲🏼 +🫱🏾‍🫲🏽 +🤝🏾 +🫱🏾‍🫲🏿 +🫱🏿‍🫲🏻 +🫱🏿‍🫲🏼 +🫱🏿‍🫲🏽 +🫱🏿‍🫲🏾 +🤝🏿 +🤝 +🫶🏻 +🫶🏼 +🫶🏽 +🫶🏾 +🫶🏿 +🫶 +🤲🏻 +🤲🏼 +🤲🏽 +🤲🏾 +🤲🏿 +🤲 +👐🏻 +👐🏼 +👐🏽 +👐🏾 +👐🏿 +👐 +🙌🏻 +🙌🏼 +🙌🏽 +🙌🏾 +🙌🏿 +🙌 +👏🏻 +👏🏼 +👏🏽 +👏🏾 +👏🏿 +👏 +👍🏻 +👍🏼 +👍🏽 +👍🏾 +👍🏿 +👍 +👎🏻 +👎🏼 +👎🏽 +👎🏾 +👎🏿 +👎 +👊🏻 +👊🏼 +👊🏽 +👊🏾 +👊🏿 +👊 +✊🏻 +✊🏼 +✊🏽 +✊🏾 +✊🏿 +✊ +🤛🏻 +🤛🏼 +🤛🏽 +🤛🏾 +🤛🏿 +🤛 +🤜🏻 +🤜🏼 +🤜🏽 +🤜🏾 +🤜🏿 +🤜 +🫷🏻 +🫷🏼 +🫷🏽 +🫷🏾 +🫷🏿 +🫷 +🫸🏻 +🫸🏼 +🫸🏽 +🫸🏾 +🫸🏿 +🫸 +🤞🏻 +🤞🏼 +🤞🏽 +🤞🏾 +🤞🏿 +🤞 +✌🏻 +✌🏼 +✌🏽 +✌🏾 +✌🏿 +✌️ +🫰🏻 +🫰🏼 +🫰🏽 +🫰🏾 +🫰🏿 +🫰 +🤟🏻 +🤟🏼 +🤟🏽 +🤟🏾 +🤟🏿 +🤟 +🤘🏻 +🤘🏼 +🤘🏽 +🤘🏾 +🤘🏿 +🤘 +👌🏻 +👌🏼 +👌🏽 +👌🏾 +👌🏿 +👌 +🤌🏼 +🤌🏻 +🤌🏽 +🤌🏾 +🤌🏿 +🤌 +🤏🏻 +🤏🏼 +🤏🏽 +🤏🏾 +🤏🏿 +🤏 +🫳🏻 +🫳🏼 +🫳🏽 +🫳🏾 +🫳🏿 +🫳 +🫴🏻 +🫴🏼 +🫴🏽 +🫴🏾 +🫴🏿 +🫴 +👈🏻 +👈🏼 +👈🏽 +👈🏾 +👈🏿 +👈 +👉🏻 +👉🏼 +👉🏽 +👉🏾 +👉🏿 +👉 +👆🏻 +👆🏼 +👆🏽 +👆🏾 +👆🏿 +👆 +👇🏻 +👇🏼 +👇🏽 +👇🏾 +👇🏿 +👇 +☝🏻 +☝🏼 +☝🏽 +☝🏾 +☝🏿 +☝️ +✋🏻 +✋🏼 +✋🏽 +✋🏾 +✋🏿 +✋ +🤚🏻 +🤚🏼 +🤚🏽 +🤚🏾 +🤚🏿 +🤚 +🖐🏻 +🖐🏼 +🖐🏽 +🖐🏾 +🖐🏿 +🖐️ +🖖🏻 +🖖🏼 +🖖🏽 +🖖🏾 +🖖🏿 +🖖 +👋🏻 +👋🏼 +👋🏽 +👋🏾 +👋🏿 +👋 +🤙🏻 +🤙🏼 +🤙🏽 +🤙🏾 +🤙🏿 +🤙 +🫲🏻 +🫲🏼 +🫲🏽 +🫲🏾 +🫲🏿 +🫲 +🫱🏻 +🫱🏼 +🫱🏽 +🫱🏾 +🫱🏿 +🫱 +💪🏻 +💪🏼 +💪🏽 +💪🏾 +💪🏿 +💪 +🦾 +🖕🏻 +🖕🏼 +🖕🏽 +🖕🏾 +🖕🏿 +🖕 +✍🏻 +✍🏼 +✍🏽 +✍🏾 +✍🏿 +✍️ +🙏🏻 +🙏🏼 +🙏🏽 +🙏🏾 +🙏🏿 +🙏 +🫵🏻 +🫵🏼 +🫵🏽 +🫵🏾 +🫵🏿 +🫵 +🦶🏻 +🦶🏼 +🦶🏽 +🦶🏾 +🦶🏿 +🦶 +🦵🏻 +🦵🏼 +🦵🏽 +🦵🏾 +🦵🏿 +🦵 +🦿 +💄 +💋 +👄 +🫦 +🦷 +👅 +👂🏻 +👂🏼 +👂🏽 +👂🏾 +👂🏿 +👂 +🦻🏻 +🦻🏼 +🦻🏽 +🦻🏾 +🦻🏿 +🦻 +👃🏻 +👃🏼 +👃🏽 +👃🏾 +👃🏿 +👃 +👣 +👁️ +👀 +🫀 +🫁 +🧠 +🗣️ +👤 +👥 +🫂 +👶🏻 +👶🏼 +👶🏽 +👶🏾 +👶🏿 +👶 +🧒🏻 +🧒🏼 +🧒🏽 +🧒🏾 +🧒🏿 +🧒 +👧🏻 +👧🏼 +👧🏽 +👧🏾 +👧🏿 +👧 +👦🏻 +👦🏼 +👦🏽 +👦🏾 +👦🏿 +👦 +🧑🏻 +🧑🏼 +🧑🏽 +🧑🏾 +🧑🏿 +🧑 +👩🏻 +👩🏼 +👩🏽 +👩🏾 +👩🏿 +👩 +👨🏻 +👨🏼 +👨🏽 +👨🏾 +👨🏿 +👨 +🧑🏻‍🦱 +🧑🏼‍🦱 +🧑🏽‍🦱 +🧑🏾‍🦱 +🧑🏿‍🦱 +🧑‍🦱 +👩🏻‍🦱 +👩🏼‍🦱 +👩🏽‍🦱 +👩🏾‍🦱 +👩🏿‍🦱 +👩‍🦱 +👨🏻‍🦱 +👨🏼‍🦱 +👨🏽‍🦱 +👨🏾‍🦱 +👨🏿‍🦱 +👨‍🦱 +🧑🏻‍🦰 +🧑🏼‍🦰 +🧑🏽‍🦰 +🧑🏾‍🦰 +🧑🏿‍🦰 +🧑‍🦰 +👩🏻‍🦰 +👩🏼‍🦰 +👩🏽‍🦰 +👩🏾‍🦰 +👩🏿‍🦰 +👩‍🦰 +👨🏻‍🦰 +👨🏼‍🦰 +👨🏽‍🦰 +👨🏾‍🦰 +👨🏿‍🦰 +👨‍🦰 +👱🏻 +👱🏼 +👱🏽 +👱🏾 +👱🏿 +👱 +👱🏻‍♀️ +👱🏼‍♀️ +👱🏽‍♀️ +👱🏾‍♀️ +👱🏿‍♀️ +👱‍♀️ +👱🏻‍♂️ +👱🏼‍♂️ +👱🏽‍♂️ +👱🏾‍♂️ +👱🏿‍♂️ +👱‍♂️ +🧑🏻‍🦳 +🧑🏼‍🦳 +🧑🏽‍🦳 +🧑🏾‍🦳 +🧑🏿‍🦳 +🧑‍🦳 +👩🏻‍🦳 +👩🏼‍🦳 +👩🏽‍🦳 +👩🏾‍🦳 +👩🏿‍🦳 +👩‍🦳 +👨🏻‍🦳 +👨🏼‍🦳 +👨🏽‍🦳 +👨🏾‍🦳 +👨🏿‍🦳 +👨‍🦳 +🧑🏻‍🦲 +🧑🏼‍🦲 +🧑🏽‍🦲 +🧑🏾‍🦲 +🧑🏿‍🦲 +🧑‍🦲 +👩🏻‍🦲 +👩🏼‍🦲 +👩🏽‍🦲 +👩🏾‍🦲 +👩🏿‍🦲 +👩‍🦲 +👨🏻‍🦲 +👨🏼‍🦲 +👨🏽‍🦲 +👨🏾‍🦲 +👨🏿‍🦲 +👨‍🦲 +🧔🏻 +🧔🏼 +🧔🏽 +🧔🏾 +🧔🏿 +🧔 +🧔🏻‍♀️ +🧔🏼‍♀️ +🧔🏽‍♀️ +🧔🏾‍♀️ +🧔🏿‍♀️ +🧔‍♀️ +🧔🏻‍♂️ +🧔🏼‍♂️ +🧔🏽‍♂️ +🧔🏾‍♂️ +🧔🏿‍♂️ +🧔‍♂️ +🧓🏻 +🧓🏼 +🧓🏽 +🧓🏾 +🧓🏿 +🧓 +👵🏻 +👵🏼 +👵🏽 +👵🏾 +👵🏿 +👵 +👴🏻 +👴🏼 +👴🏽 +👴🏾 +👴🏿 +👴 +👲🏻 +👲🏼 +👲🏽 +👲🏾 +👲🏿 +👲 +👳🏻 +👳🏼 +👳🏽 +👳🏾 +👳🏿 +👳 +👳🏻‍♀️ +👳🏼‍♀️ +👳🏽‍♀️ +👳🏾‍♀️ +👳🏿‍♀️ +👳‍♀️ +👳🏻‍♂️ +👳🏼‍♂️ +👳🏽‍♂️ +👳🏾‍♂️ +👳🏿‍♂️ +👳‍♂️ +🧕🏻 +🧕🏼 +🧕🏽 +🧕🏾 +🧕🏿 +🧕 +👮🏻 +👮🏼 +👮🏽 +👮🏾 +👮🏿 +👮 +👮🏻‍♀️ +👮🏼‍♀️ +👮🏽‍♀️ +👮🏾‍♀️ +👮🏿‍♀️ +👮‍♀️ +👮🏻‍♂️ +👮🏼‍♂️ +👮🏽‍♂️ +👮🏾‍♂️ +👮🏿‍♂️ +👮‍♂️ +👷🏻 +👷🏼 +👷🏽 +👷🏾 +👷🏿 +👷 +👷🏻‍♀️ +👷🏼‍♀️ +👷🏽‍♀️ +👷🏾‍♀️ +👷🏿‍♀️ +👷‍♀️ +👷🏻‍♂️ +👷🏼‍♂️ +👷🏽‍♂️ +👷🏾‍♂️ +👷🏿‍♂️ +👷‍♂️ +💂🏻 +💂🏼 +💂🏽 +💂🏾 +💂🏿 +💂 +💂🏻‍♀️ +💂🏼‍♀️ +💂🏽‍♀️ +💂🏾‍♀️ +💂🏿‍♀️ +💂‍♀️ +💂🏻‍♂️ +💂🏼‍♂️ +💂🏽‍♂️ +💂🏾‍♂️ +💂🏿‍♂️ +💂‍♂️ +🕵🏻 +🕵🏼 +🕵🏽 +🕵🏾 +🕵🏿 +🕵️ +🕵🏻‍♀️ +🕵🏼‍♀️ +🕵🏽‍♀️ +🕵🏾‍♀️ +🕵🏿‍♀️ +🕵️‍♀️ +🕵🏻‍♂️ +🕵🏼‍♂️ +🕵🏽‍♂️ +🕵🏾‍♂️ +🕵🏿‍♂️ +🕵️‍♂️ +🧑🏻‍⚕️ +🧑🏼‍⚕️ +🧑🏽‍⚕️ +🧑🏾‍⚕️ +🧑🏿‍⚕️ +🧑‍⚕️ +👩🏻‍⚕️ +👩🏼‍⚕️ +👩🏽‍⚕️ +👩🏾‍⚕️ +👩🏿‍⚕️ +👩‍⚕️ +👨🏻‍⚕️ +👨🏼‍⚕️ +👨🏽‍⚕️ +👨🏾‍⚕️ +👨🏿‍⚕️ +👨‍⚕️ +🧑🏻‍🌾 +🧑🏼‍🌾 +🧑🏽‍🌾 +🧑🏾‍🌾 +🧑🏿‍🌾 +🧑‍🌾 +👩🏻‍🌾 +👩🏼‍🌾 +👩🏽‍🌾 +👩🏾‍🌾 +👩🏿‍🌾 +👩‍🌾 +👨🏻‍🌾 +👨🏼‍🌾 +👨🏽‍🌾 +👨🏾‍🌾 +👨🏿‍🌾 +👨‍🌾 +🧑🏻‍🍳 +🧑🏼‍🍳 +🧑🏽‍🍳 +🧑🏾‍🍳 +🧑🏿‍🍳 +🧑‍🍳 +👩🏻‍🍳 +👩🏼‍🍳 +👩🏽‍🍳 +👩🏾‍🍳 +👩🏿‍🍳 +👩‍🍳 +👨🏻‍🍳 +👨🏼‍🍳 +👨🏽‍🍳 +👨🏾‍🍳 +👨🏿‍🍳 +👨‍🍳 +🧑🏻‍🎓 +🧑🏼‍🎓 +🧑🏽‍🎓 +🧑🏾‍🎓 +🧑🏿‍🎓 +🧑‍🎓 +👩🏻‍🎓 +👩🏼‍🎓 +👩🏽‍🎓 +👩🏾‍🎓 +👩🏿‍🎓 +👩‍🎓 +👨🏻‍🎓 +👨🏼‍🎓 +👨🏽‍🎓 +👨🏾‍🎓 +👨🏿‍🎓 +👨‍🎓 +🧑🏻‍🎤 +🧑🏼‍🎤 +🧑🏽‍🎤 +🧑🏾‍🎤 +🧑🏿‍🎤 +🧑‍🎤 +👩🏻‍🎤 +👩🏼‍🎤 +👩🏽‍🎤 +👩🏾‍🎤 +👩🏿‍🎤 +👩‍🎤 +👨🏻‍🎤 +👨🏼‍🎤 +👨🏽‍🎤 +👨🏾‍🎤 +👨🏿‍🎤 +👨‍🎤 +🧑🏻‍🏫 +🧑🏼‍🏫 +🧑🏽‍🏫 +🧑🏾‍🏫 +🧑🏿‍🏫 +🧑‍🏫 +👩🏻‍🏫 +👩🏼‍🏫 +👩🏽‍🏫 +👩🏾‍🏫 +👩🏿‍🏫 +👩‍🏫 +👨🏻‍🏫 +👨🏼‍🏫 +👨🏽‍🏫 +👨🏾‍🏫 +👨🏿‍🏫 +👨‍🏫 +🧑🏻‍🏭 +🧑🏼‍🏭 +🧑🏽‍🏭 +🧑🏾‍🏭 +🧑🏿‍🏭 +🧑‍🏭 +👩🏻‍🏭 +👩🏼‍🏭 +👩🏽‍🏭 +👩🏾‍🏭 +👩🏿‍🏭 +👩‍🏭 +👨🏻‍🏭 +👨🏼‍🏭 +👨🏽‍🏭 +👨🏾‍🏭 +👨🏿‍🏭 +👨‍🏭 +🧑🏻‍💻 +🧑🏼‍💻 +🧑🏽‍💻 +🧑🏾‍💻 +🧑🏿‍💻 +🧑‍💻 +👩🏻‍💻 +👩🏼‍💻 +👩🏽‍💻 +👩🏾‍💻 +👩🏿‍💻 +👩‍💻 +👨🏻‍💻 +👨🏼‍💻 +👨🏽‍💻 +👨🏾‍💻 +👨🏿‍💻 +👨‍💻 +🧑🏻‍💼 +🧑🏼‍💼 +🧑🏽‍💼 +🧑🏾‍💼 +🧑🏿‍💼 +🧑‍💼 +👩🏻‍💼 +👩🏼‍💼 +👩🏽‍💼 +👩🏾‍💼 +👩🏿‍💼 +👩‍💼 +👨🏻‍💼 +👨🏼‍💼 +👨🏽‍💼 +👨🏾‍💼 +👨🏿‍💼 +👨‍💼 +🧑🏻‍🔧 +🧑🏼‍🔧 +🧑🏽‍🔧 +🧑🏾‍🔧 +🧑🏿‍🔧 +🧑‍🔧 +👩🏻‍🔧 +👩🏼‍🔧 +👩🏽‍🔧 +👩🏾‍🔧 +👩🏿‍🔧 +👩‍🔧 +👨🏻‍🔧 +👨🏼‍🔧 +👨🏽‍🔧 +👨🏾‍🔧 +👨🏿‍🔧 +👨‍🔧 +🧑🏻‍🔬 +🧑🏼‍🔬 +🧑🏽‍🔬 +🧑🏾‍🔬 +🧑🏿‍🔬 +🧑‍🔬 +👩🏻‍🔬 +👩🏼‍🔬 +👩🏽‍🔬 +👩🏾‍🔬 +👩🏿‍🔬 +👩‍🔬 +👨🏻‍🔬 +👨🏼‍🔬 +👨🏽‍🔬 +👨🏾‍🔬 +👨🏿‍🔬 +👨‍🔬 +🧑🏻‍🎨 +🧑🏼‍🎨 +🧑🏽‍🎨 +🧑🏾‍🎨 +🧑🏿‍🎨 +🧑‍🎨 +👩🏻‍🎨 +👩🏼‍🎨 +👩🏽‍🎨 +👩🏾‍🎨 +👩🏿‍🎨 +👩‍🎨 +👨🏻‍🎨 +👨🏼‍🎨 +👨🏽‍🎨 +👨🏾‍🎨 +👨🏿‍🎨 +👨‍🎨 +🧑🏻‍🚒 +🧑🏼‍🚒 +🧑🏽‍🚒 +🧑🏾‍🚒 +🧑🏿‍🚒 +🧑‍🚒 +👩🏻‍🚒 +👩🏼‍🚒 +👩🏽‍🚒 +👩🏾‍🚒 +👩🏿‍🚒 +👩‍🚒 +👨🏻‍🚒 +👨🏼‍🚒 +👨🏽‍🚒 +👨🏾‍🚒 +👨🏿‍🚒 +👨‍🚒 +🧑🏻‍✈️ +🧑🏼‍✈️ +🧑🏽‍✈️ +🧑🏾‍✈️ +🧑🏿‍✈️ +🧑‍✈️ +👩🏻‍✈️ +👩🏼‍✈️ +👩🏽‍✈️ +👩🏾‍✈️ +👩🏿‍✈️ +👩‍✈️ +👨🏻‍✈️ +👨🏼‍✈️ +👨🏽‍✈️ +👨🏾‍✈️ +👨🏿‍✈️ +👨‍✈️ +🧑🏻‍🚀 +🧑🏼‍🚀 +🧑🏽‍🚀 +🧑🏾‍🚀 +🧑🏿‍🚀 +🧑‍🚀 +👩🏻‍🚀 +👩🏼‍🚀 +👩🏽‍🚀 +👩🏾‍🚀 +👩🏿‍🚀 +👩‍🚀 +👨🏻‍🚀 +👨🏼‍🚀 +👨🏽‍🚀 +👨🏾‍🚀 +👨🏿‍🚀 +👨‍🚀 +🧑🏻‍⚖️ +🧑🏼‍⚖️ +🧑🏽‍⚖️ +🧑🏾‍⚖️ +🧑🏿‍⚖️ +🧑‍⚖️ +👩🏻‍⚖️ +👩🏼‍⚖️ +👩🏽‍⚖️ +👩🏾‍⚖️ +👩🏿‍⚖️ +👩‍⚖️ +👨🏻‍⚖️ +👨🏼‍⚖️ +👨🏽‍⚖️ +👨🏾‍⚖️ +👨🏿‍⚖️ +👨‍⚖️ +👰🏻 +👰🏼 +👰🏽 +👰🏾 +👰🏿 +👰 +👰🏻‍♀️ +👰🏼‍♀️ +👰🏽‍♀️ +👰🏾‍♀️ +👰🏿‍♀️ +👰‍♀️ +👰🏻‍♂️ +👰🏼‍♂️ +👰🏽‍♂️ +👰🏾‍♂️ +👰🏿‍♂️ +👰‍♂️ +🤵🏻 +🤵🏼 +🤵🏽 +🤵🏾 +🤵🏿 +🤵 +🤵🏻‍♀️ +🤵🏼‍♀️ +🤵🏽‍♀️ +🤵🏾‍♀️ +🤵🏿‍♀️ +🤵‍♀️ +🤵🏻‍♂️ +🤵🏼‍♂️ +🤵🏽‍♂️ +🤵🏾‍♂️ +🤵🏿‍♂️ +🤵‍♂️ +🫅🏻 +🫅🏼 +🫅🏽 +🫅🏾 +🫅🏿 +🫅 +👸🏻 +👸🏼 +👸🏽 +👸🏾 +👸🏿 +👸 +🤴🏻 +🤴🏼 +🤴🏽 +🤴🏾 +🤴🏿 +🤴 +🦸🏻 +🦸🏼 +🦸🏽 +🦸🏾 +🦸🏿 +🦸 +🦸🏻‍♀️ +🦸🏼‍♀️ +🦸🏽‍♀️ +🦸🏾‍♀️ +🦸🏿‍♀️ +🦸‍♀️ +🦸🏻‍♂️ +🦸🏼‍♂️ +🦸🏽‍♂️ +🦸🏾‍♂️ +🦸🏿‍♂️ +🦸‍♂️ +🦹🏻 +🦹🏼 +🦹🏽 +🦹🏾 +🦹🏿 +🦹 +🦹🏻‍♀️ +🦹🏼‍♀️ +🦹🏽‍♀️ +🦹🏾‍♀️ +🦹🏿‍♀️ +🦹‍♀️ +🦹🏻‍♂️ +🦹🏼‍♂️ +🦹🏽‍♂️ +🦹🏾‍♂️ +🦹🏿‍♂️ +🦹‍♂️ +🥷🏻 +🥷🏼 +🥷🏽 +🥷🏾 +🥷🏿 +🥷 +🧑🏻‍🎄 +🧑🏼‍🎄 +🧑🏽‍🎄 +🧑🏾‍🎄 +🧑🏿‍🎄 +🧑‍🎄 +🤶🏻 +🤶🏼 +🤶🏽 +🤶🏾 +🤶🏿 +🤶 +🎅🏻 +🎅🏼 +🎅🏽 +🎅🏾 +🎅🏿 +🎅 +🧙🏻 +🧙🏼 +🧙🏽 +🧙🏾 +🧙🏿 +🧙 +🧙🏻‍♀️ +🧙🏼‍♀️ +🧙🏽‍♀️ +🧙🏾‍♀️ +🧙🏿‍♀️ +🧙‍♀️ +🧙🏻‍♂️ +🧙🏼‍♂️ +🧙🏽‍♂️ +🧙🏾‍♂️ +🧙🏿‍♂️ +🧙‍♂️ +🧝🏻 +🧝🏼 +🧝🏽 +🧝🏾 +🧝🏿 +🧝 +🧝🏻‍♀️ +🧝🏼‍♀️ +🧝🏽‍♀️ +🧝🏾‍♀️ +🧝🏿‍♀️ +🧝‍♀️ +🧝🏻‍♂️ +🧝🏼‍♂️ +🧝🏽‍♂️ +🧝🏾‍♂️ +🧝🏿‍♂️ +🧝‍♂️ +🧌 +🧛🏻 +🧛🏼 +🧛🏽 +🧛🏾 +🧛🏿 +🧛 +🧛🏻‍♀️ +🧛🏼‍♀️ +🧛🏽‍♀️ +🧛🏾‍♀️ +🧛🏿‍♀️ +🧛‍♀️ +🧛🏻‍♂️ +🧛🏼‍♂️ +🧛🏽‍♂️ +🧛🏾‍♂️ +🧛🏿‍♂️ +🧛‍♂️ +🧟 +🧟‍♀️ +🧟‍♂️ +🧞 +🧞‍♀️ +🧞‍♂️ +🧜🏻 +🧜🏼 +🧜🏽 +🧜🏾 +🧜🏿 +🧜 +🧜🏻‍♀️ +🧜🏼‍♀️ +🧜🏽‍♀️ +🧜🏾‍♀️ +🧜🏿‍♀️ +🧜‍♀️ +🧜🏻‍♂️ +🧜🏼‍♂️ +🧜🏽‍♂️ +🧜🏾‍♂️ +🧜🏿‍♂️ +🧜‍♂️ +🧚🏻 +🧚🏼 +🧚🏽 +🧚🏾 +🧚🏿 +🧚 +🧚🏻‍♀️ +🧚🏼‍♀️ +🧚🏽‍♀️ +🧚🏾‍♀️ +🧚🏿‍♀️ +🧚‍♀️ +🧚🏻‍♂️ +🧚🏼‍♂️ +🧚🏽‍♂️ +🧚🏾‍♂️ +🧚🏿‍♂️ +🧚‍♂️ +👼🏻 +👼🏼 +👼🏽 +👼🏾 +👼🏿 +👼 +🫄🏻 +🫄🏼 +🫄🏽 +🫄🏾 +🫄🏿 +🫄 +🤰🏻 +🤰🏼 +🤰🏽 +🤰🏾 +🤰🏿 +🤰 +🫃🏻 +🫃🏼 +🫃🏽 +🫃🏾 +🫃🏿 +🫃 +🤱🏻 +🤱🏼 +🤱🏽 +🤱🏾 +🤱🏿 +🤱 +🧑🏻‍🍼 +🧑🏼‍🍼 +🧑🏽‍🍼 +🧑🏾‍🍼 +🧑🏿‍🍼 +🧑‍🍼 +👩🏻‍🍼 +👩🏼‍🍼 +👩🏽‍🍼 +👩🏾‍🍼 +👩🏿‍🍼 +👩‍🍼 +👨🏻‍🍼 +👨🏼‍🍼 +👨🏽‍🍼 +👨🏾‍🍼 +👨🏿‍🍼 +👨‍🍼 +🙇🏻 +🙇🏼 +🙇🏽 +🙇🏾 +🙇🏿 +🙇 +🙇🏻‍♀️ +🙇🏼‍♀️ +🙇🏽‍♀️ +🙇🏾‍♀️ +🙇🏿‍♀️ +🙇‍♀️ +🙇🏻‍♂️ +🙇🏼‍♂️ +🙇🏽‍♂️ +🙇🏾‍♂️ +🙇🏿‍♂️ +🙇‍♂️ +💁🏻 +💁🏼 +💁🏽 +💁🏾 +💁🏿 +💁 +💁🏻‍♀️ +💁🏼‍♀️ +💁🏽‍♀️ +💁🏾‍♀️ +💁🏿‍♀️ +💁‍♀️ +💁🏻‍♂️ +💁🏼‍♂️ +💁🏽‍♂️ +💁🏾‍♂️ +💁🏿‍♂️ +💁‍♂️ +🙅🏻 +🙅🏼 +🙅🏽 +🙅🏾 +🙅🏿 +🙅 +🙅🏻‍♀️ +🙅🏼‍♀️ +🙅🏽‍♀️ +🙅🏾‍♀️ +🙅🏿‍♀️ +🙅‍♀️ +🙅🏻‍♂️ +🙅🏼‍♂️ +🙅🏽‍♂️ +🙅🏾‍♂️ +🙅🏿‍♂️ +🙅‍♂️ +🙆🏻 +🙆🏼 +🙆🏽 +🙆🏾 +🙆🏿 +🙆 +🙆🏻‍♀️ +🙆🏼‍♀️ +🙆🏽‍♀️ +🙆🏾‍♀️ +🙆🏿‍♀️ +🙆‍♀️ +🙆🏻‍♂️ +🙆🏼‍♂️ +🙆🏽‍♂️ +🙆🏾‍♂️ +🙆🏿‍♂️ +🙆‍♂️ +🙋🏻 +🙋🏼 +🙋🏽 +🙋🏾 +🙋🏿 +🙋 +🙋🏻‍♀️ +🙋🏼‍♀️ +🙋🏽‍♀️ +🙋🏾‍♀️ +🙋🏿‍♀️ +🙋‍♀️ +🙋🏻‍♂️ +🙋🏼‍♂️ +🙋🏽‍♂️ +🙋🏾‍♂️ +🙋🏿‍♂️ +🙋‍♂️ +🧏🏻 +🧏🏼 +🧏🏽 +🧏🏾 +🧏🏿 +🧏 +🧏🏻‍♀️ +🧏🏼‍♀️ +🧏🏽‍♀️ +🧏🏾‍♀️ +🧏🏿‍♀️ +🧏‍♀️ +🧏🏻‍♂️ +🧏🏼‍♂️ +🧏🏽‍♂️ +🧏🏾‍♂️ +🧏🏿‍♂️ +🧏‍♂️ +🤦🏻 +🤦🏼 +🤦🏽 +🤦🏾 +🤦🏿 +🤦 +🤦🏻‍♀️ +🤦🏼‍♀️ +🤦🏽‍♀️ +🤦🏾‍♀️ +🤦🏿‍♀️ +🤦‍♀️ +🤦🏻‍♂️ +🤦🏼‍♂️ +🤦🏽‍♂️ +🤦🏾‍♂️ +🤦🏿‍♂️ +🤦‍♂️ +🤷🏻 +🤷🏼 +🤷🏽 +🤷🏾 +🤷🏿 +🤷 +🤷🏻‍♀️ +🤷🏼‍♀️ +🤷🏽‍♀️ +🤷🏾‍♀️ +🤷🏿‍♀️ +🤷‍♀️ +🤷🏻‍♂️ +🤷🏼‍♂️ +🤷🏽‍♂️ +🤷🏾‍♂️ +🤷🏿‍♂️ +🤷‍♂️ +🙎🏻 +🙎🏼 +🙎🏽 +🙎🏾 +🙎🏿 +🙎 +🙎🏻‍♀️ +🙎🏼‍♀️ +🙎🏽‍♀️ +🙎🏾‍♀️ +🙎🏿‍♀️ +🙎‍♀️ +🙎🏻‍♂️ +🙎🏼‍♂️ +🙎🏽‍♂️ +🙎🏾‍♂️ +🙎🏿‍♂️ +🙎‍♂️ +🙍🏻 +🙍🏼 +🙍🏽 +🙍🏾 +🙍🏿 +🙍 +🙍🏻‍♀️ +🙍🏼‍♀️ +🙍🏽‍♀️ +🙍🏾‍♀️ +🙍🏿‍♀️ +🙍‍♀️ +🙍🏻‍♂️ +🙍🏼‍♂️ +🙍🏽‍♂️ +🙍🏾‍♂️ +🙍🏿‍♂️ +🙍‍♂️ +💇🏻 +💇🏼 +💇🏽 +💇🏾 +💇🏿 +💇 +💇🏻‍♀️ +💇🏼‍♀️ +💇🏽‍♀️ +💇🏾‍♀️ +💇🏿‍♀️ +💇‍♀️ +💇🏻‍♂️ +💇🏼‍♂️ +💇🏽‍♂️ +💇🏾‍♂️ +💇🏿‍♂️ +💇‍♂️ +💆🏻 +💆🏼 +💆🏽 +💆🏾 +💆🏿 +💆 +💆🏻‍♀️ +💆🏼‍♀️ +💆🏽‍♀️ +💆🏾‍♀️ +💆🏿‍♀️ +💆‍♀️ +💆🏻‍♂️ +💆🏼‍♂️ +💆🏽‍♂️ +💆🏾‍♂️ +💆🏿‍♂️ +💆‍♂️ +🧖🏻 +🧖🏼 +🧖🏽 +🧖🏾 +🧖🏿 +🧖 +🧖🏻‍♀️ +🧖🏼‍♀️ +🧖🏽‍♀️ +🧖🏾‍♀️ +🧖🏿‍♀️ +🧖‍♀️ +🧖🏻‍♂️ +🧖🏼‍♂️ +🧖🏽‍♂️ +🧖🏾‍♂️ +🧖🏿‍♂️ +🧖‍♂️ +💅🏻 +💅🏼 +💅🏽 +💅🏾 +💅🏿 +💅 +🤳🏻 +🤳🏼 +🤳🏽 +🤳🏾 +🤳🏿 +🤳 +💃🏻 +💃🏼 +💃🏽 +💃🏾 +💃🏿 +💃 +🕺🏻 +🕺🏼 +🕺🏽 +🕺🏿 +🕺🏾 +🕺 +👯 +👯‍♀️ +👯‍♂️ +🕴🏻 +🕴🏼 +🕴🏽 +🕴🏾 +🕴🏿 +🕴️ +🧑🏻‍🦽 +🧑🏼‍🦽 +🧑🏽‍🦽 +🧑🏾‍🦽 +🧑🏿‍🦽 +🧑‍🦽 +👩🏻‍🦽 +👩🏼‍🦽 +👩🏽‍🦽 +👩🏾‍🦽 +👩🏿‍🦽 +👩‍🦽 +👨🏻‍🦽 +👨🏼‍🦽 +👨🏽‍🦽 +👨🏾‍🦽 +👨🏿‍🦽 +👨‍🦽 +🧑🏻‍🦽‍➡️ +🧑🏼‍🦽‍➡️ +🧑🏽‍🦽‍➡️ +🧑🏾‍🦽‍➡️ +🧑🏿‍🦽‍➡️ +🧑‍🦽‍➡️ +👨🏼‍🦽‍➡️ +👨🏻‍🦽‍➡️ +👨🏽‍🦽‍➡️ +👨🏾‍🦽‍➡️ +👨🏿‍🦽‍➡️ +👨‍🦽‍➡️ +👩🏻‍🦽‍➡️ +👩🏼‍🦽‍➡️ +👩🏽‍🦽‍➡️ +👩🏾‍🦽‍➡️ +👩🏿‍🦽‍➡️ +👩‍🦽‍➡️ +🧑🏻‍🦼 +🧑🏼‍🦼 +🧑🏽‍🦼 +🧑🏾‍🦼 +🧑🏿‍🦼 +🧑‍🦼 +👩🏻‍🦼 +👩🏼‍🦼 +👩🏽‍🦼 +👩🏾‍🦼 +👩🏿‍🦼 +👩‍🦼 +👨🏻‍🦼 +👨🏼‍🦼 +👨🏽‍🦼 +👨🏾‍🦼 +👨🏿‍🦼 +👨‍🦼 +🧑🏻‍🦼‍➡️ +🧑🏼‍🦼‍➡️ +🧑🏽‍🦼‍➡️ +🧑🏾‍🦼‍➡️ +🧑🏿‍🦼‍➡️ +🧑‍🦼‍➡️ +👨🏻‍🦼‍➡️ +👨🏼‍🦼‍➡️ +👨🏽‍🦼‍➡️ +👨🏾‍🦼‍➡️ +👨🏿‍🦼‍➡️ +👨‍🦼‍➡️ +👩🏻‍🦼‍➡️ +👩🏼‍🦼‍➡️ +👩🏽‍🦼‍➡️ +👩🏾‍🦼‍➡️ +👩🏿‍🦼‍➡️ +👩‍🦼‍➡️ +🚶🏻 +🚶🏼 +🚶🏽 +🚶🏾 +🚶🏿 +🚶 +🚶🏻‍♀️ +🚶🏼‍♀️ +🚶🏽‍♀️ +🚶🏾‍♀️ +🚶🏿‍♀️ +🚶‍♀️ +🚶🏻‍♂️ +🚶🏼‍♂️ +🚶🏽‍♂️ +🚶🏾‍♂️ +🚶🏿‍♂️ +🚶‍♂️ +🚶🏻‍➡️ +🚶🏼‍➡️ +🚶🏽‍➡️ +🚶🏾‍➡️ +🚶🏿‍➡️ +🚶‍➡️ +🚶🏻‍♀️‍➡️ +🚶🏼‍♀️‍➡️ +🚶🏽‍♀️‍➡️ +🚶🏾‍♀️‍➡️ +🚶🏿‍♀️‍➡️ +🚶‍♀️‍➡️ +🚶🏻‍♂️‍➡️ +🚶🏼‍♂️‍➡️ +🚶🏽‍♂️‍➡️ +🚶🏾‍♂️‍➡️ +🚶🏿‍♂️‍➡️ +🚶‍♂️‍➡️ +🧑🏻‍🦯 +🧑🏼‍🦯 +🧑🏽‍🦯 +🧑🏾‍🦯 +🧑🏿‍🦯 +🧑‍🦯 +👩🏻‍🦯 +👩🏼‍🦯 +👩🏽‍🦯 +👩🏾‍🦯 +👩🏿‍🦯 +👩‍🦯 +👨🏻‍🦯 +👨🏼‍🦯 +👨🏽‍🦯 +👨🏾‍🦯 +👨🏿‍🦯 +👨‍🦯 +🧑🏻‍🦯‍➡️ +🧑🏼‍🦯‍➡️ +🧑🏽‍🦯‍➡️ +🧑🏾‍🦯‍➡️ +🧑🏿‍🦯‍➡️ +🧑‍🦯‍➡️ +👨🏻‍🦯‍➡️ +👨🏼‍🦯‍➡️ +👨🏽‍🦯‍➡️ +👨🏾‍🦯‍➡️ +👨🏿‍🦯‍➡️ +👨‍🦯‍➡️ +👩🏻‍🦯‍➡️ +👩🏼‍🦯‍➡️ +👩🏽‍🦯‍➡️ +👩🏾‍🦯‍➡️ +👩🏿‍🦯‍➡️ +👩‍🦯‍➡️ +🧎🏻 +🧎🏼 +🧎🏽 +🧎🏾 +🧎🏿 +🧎 +🧎🏻‍♀️ +🧎🏼‍♀️ +🧎🏽‍♀️ +🧎🏾‍♀️ +🧎🏿‍♀️ +🧎‍♀️ +🧎🏻‍♂️ +🧎🏼‍♂️ +🧎🏽‍♂️ +🧎🏾‍♂️ +🧎🏿‍♂️ +🧎‍♂️ +🧎🏻‍➡️ +🧎🏼‍➡️ +🧎🏽‍➡️ +🧎🏾‍➡️ +🧎🏿‍➡️ +🧎‍➡️ +🧎🏻‍♀️‍➡️ +🧎🏼‍♀️‍➡️ +🧎🏽‍♀️‍➡️ +🧎🏾‍♀️‍➡️ +🧎🏿‍♀️‍➡️ +🧎‍♀️‍➡️ +🧎🏻‍♂️‍➡️ +🧎🏼‍♂️‍➡️ +🧎🏽‍♂️‍➡️ +🧎🏾‍♂️‍➡️ +🧎🏿‍♂️‍➡️ +🧎‍♂️‍➡️ +🏃🏻 +🏃🏼 +🏃🏽 +🏃🏾 +🏃🏿 +🏃 +🏃🏻‍♀️ +🏃🏼‍♀️ +🏃🏽‍♀️ +🏃🏾‍♀️ +🏃🏿‍♀️ +🏃‍♀️ +🏃🏻‍♂️ +🏃🏼‍♂️ +🏃🏽‍♂️ +🏃🏾‍♂️ +🏃🏿‍♂️ +🏃‍♂️ +🏃🏻‍➡️ +🏃🏼‍➡️ +🏃🏽‍➡️ +🏃🏾‍➡️ +🏃🏿‍➡️ +🏃‍➡️ +🏃🏻‍♀️‍➡️ +🏃🏼‍♀️‍➡️ +🏃🏽‍♀️‍➡️ +🏃🏾‍♀️‍➡️ +🏃🏿‍♀️‍➡️ +🏃‍♀️‍➡️ +🏃🏻‍♂️‍➡️ +🏃🏼‍♂️‍➡️ +🏃🏽‍♂️‍➡️ +🏃🏾‍♂️‍➡️ +🏃🏿‍♂️‍➡️ +🏃‍♂️‍➡️ +🧍🏻 +🧍🏼 +🧍🏽 +🧍🏾 +🧍🏿 +🧍 +🧍🏻‍♀️ +🧍🏼‍♀️ +🧍🏽‍♀️ +🧍🏾‍♀️ +🧍🏿‍♀️ +🧍‍♀️ +🧍🏻‍♂️ +🧍🏼‍♂️ +🧍🏽‍♂️ +🧍🏾‍♂️ +🧍🏿‍♂️ +🧍‍♂️ +🧑🏻‍🤝‍🧑🏻 +🧑🏻‍🤝‍🧑🏼 +🧑🏻‍🤝‍🧑🏽 +🧑🏻‍🤝‍🧑🏾 +🧑🏻‍🤝‍🧑🏿 +🧑🏼‍🤝‍🧑🏻 +🧑🏼‍🤝‍🧑🏼 +🧑🏼‍🤝‍🧑🏽 +🧑🏼‍🤝‍🧑🏾 +🧑🏼‍🤝‍🧑🏿 +🧑🏽‍🤝‍🧑🏻 +🧑🏽‍🤝‍🧑🏼 +🧑🏽‍🤝‍🧑🏽 +🧑🏽‍🤝‍🧑🏾 +🧑🏽‍🤝‍🧑🏿 +🧑🏾‍🤝‍🧑🏻 +🧑🏾‍🤝‍🧑🏼 +🧑🏾‍🤝‍🧑🏽 +🧑🏾‍🤝‍🧑🏾 +🧑🏾‍🤝‍🧑🏿 +🧑🏿‍🤝‍🧑🏻 +🧑🏿‍🤝‍🧑🏼 +🧑🏿‍🤝‍🧑🏽 +🧑🏿‍🤝‍🧑🏾 +🧑🏿‍🤝‍🧑🏿 +🧑‍🤝‍🧑 +👫🏻 +👩🏻‍🤝‍👨🏼 +👩🏻‍🤝‍👨🏽 +👩🏻‍🤝‍👨🏾 +👩🏻‍🤝‍👨🏿 +👩🏼‍🤝‍👨🏻 +👫🏼 +👩🏼‍🤝‍👨🏽 +👩🏼‍🤝‍👨🏾 +👩🏼‍🤝‍👨🏿 +👩🏽‍🤝‍👨🏻 +👩🏽‍🤝‍👨🏼 +👫🏽 +👩🏽‍🤝‍👨🏾 +👩🏽‍🤝‍👨🏿 +👩🏾‍🤝‍👨🏻 +👩🏾‍🤝‍👨🏼 +👩🏾‍🤝‍👨🏽 +👫🏾 +👩🏾‍🤝‍👨🏿 +👩🏿‍🤝‍👨🏻 +👩🏿‍🤝‍👨🏼 +👩🏿‍🤝‍👨🏽 +👩🏿‍🤝‍👨🏾 +👫🏿 +👫 +👭🏻 +👩🏻‍🤝‍👩🏼 +👩🏻‍🤝‍👩🏽 +👩🏻‍🤝‍👩🏾 +👩🏻‍🤝‍👩🏿 +👩🏼‍🤝‍👩🏻 +👭🏼 +👩🏼‍🤝‍👩🏽 +👩🏼‍🤝‍👩🏾 +👩🏼‍🤝‍👩🏿 +👩🏽‍🤝‍👩🏻 +👩🏽‍🤝‍👩🏼 +👭🏽 +👩🏽‍🤝‍👩🏾 +👩🏽‍🤝‍👩🏿 +👩🏾‍🤝‍👩🏻 +👩🏾‍🤝‍👩🏼 +👩🏾‍🤝‍👩🏽 +👭🏾 +👩🏾‍🤝‍👩🏿 +👩🏿‍🤝‍👩🏻 +👩🏿‍🤝‍👩🏼 +👩🏿‍🤝‍👩🏽 +👩🏿‍🤝‍👩🏾 +👭🏿 +👭 +👬🏻 +👨🏻‍🤝‍👨🏼 +👨🏻‍🤝‍👨🏽 +👨🏻‍🤝‍👨🏾 +👨🏻‍🤝‍👨🏿 +👨🏼‍🤝‍👨🏻 +👬🏼 +👨🏼‍🤝‍👨🏽 +👨🏼‍🤝‍👨🏾 +👨🏼‍🤝‍👨🏿 +👨🏽‍🤝‍👨🏻 +👨🏽‍🤝‍👨🏼 +👬🏽 +👨🏽‍🤝‍👨🏾 +👨🏽‍🤝‍👨🏿 +👨🏾‍🤝‍👨🏻 +👨🏾‍🤝‍👨🏼 +👨🏾‍🤝‍👨🏽 +👬🏾 +👨🏾‍🤝‍👨🏿 +👨🏿‍🤝‍👨🏻 +👨🏿‍🤝‍👨🏼 +👨🏿‍🤝‍👨🏽 +👨🏿‍🤝‍👨🏾 +👬🏿 +👬 +💑🏻 +🧑🏻‍❤️‍🧑🏼 +🧑🏻‍❤️‍🧑🏽 +🧑🏻‍❤️‍🧑🏾 +🧑🏻‍❤️‍🧑🏿 +🧑🏼‍❤️‍🧑🏻 +💑🏼 +🧑🏼‍❤️‍🧑🏽 +🧑🏼‍❤️‍🧑🏾 +🧑🏼‍❤️‍🧑🏿 +🧑🏽‍❤️‍🧑🏻 +🧑🏽‍❤️‍🧑🏼 +💑🏽 +🧑🏽‍❤️‍🧑🏾 +🧑🏽‍❤️‍🧑🏿 +🧑🏾‍❤️‍🧑🏻 +🧑🏾‍❤️‍🧑🏼 +🧑🏾‍❤️‍🧑🏽 +💑🏾 +🧑🏾‍❤️‍🧑🏿 +🧑🏿‍❤️‍🧑🏻 +🧑🏿‍❤️‍🧑🏼 +🧑🏿‍❤️‍🧑🏽 +🧑🏿‍❤️‍🧑🏾 +💑🏿 +💑 +👩🏻‍❤️‍👨🏻 +👩🏻‍❤️‍👨🏼 +👩🏻‍❤️‍👨🏽 +👩🏻‍❤️‍👨🏾 +👩🏻‍❤️‍👨🏿 +👩🏼‍❤️‍👨🏻 +👩🏼‍❤️‍👨🏼 +👩🏼‍❤️‍👨🏽 +👩🏼‍❤️‍👨🏾 +👩🏼‍❤️‍👨🏿 +👩🏽‍❤️‍👨🏻 +👩🏽‍❤️‍👨🏼 +👩🏽‍❤️‍👨🏽 +👩🏽‍❤️‍👨🏾 +👩🏽‍❤️‍👨🏿 +👩🏾‍❤️‍👨🏻 +👩🏾‍❤️‍👨🏼 +👩🏾‍❤️‍👨🏽 +👩🏾‍❤️‍👨🏾 +👩🏾‍❤️‍👨🏿 +👩🏿‍❤️‍👨🏻 +👩🏿‍❤️‍👨🏼 +👩🏿‍❤️‍👨🏽 +👩🏿‍❤️‍👨🏾 +👩🏿‍❤️‍👨🏿 +👩‍❤️‍👨 +👩🏻‍❤️‍👩🏻 +👩🏻‍❤️‍👩🏼 +👩🏻‍❤️‍👩🏽 +👩🏻‍❤️‍👩🏾 +👩🏻‍❤️‍👩🏿 +👩🏼‍❤️‍👩🏻 +👩🏼‍❤️‍👩🏼 +👩🏼‍❤️‍👩🏽 +👩🏼‍❤️‍👩🏾 +👩🏼‍❤️‍👩🏿 +👩🏽‍❤️‍👩🏻 +👩🏽‍❤️‍👩🏼 +👩🏽‍❤️‍👩🏽 +👩🏽‍❤️‍👩🏾 +👩🏽‍❤️‍👩🏿 +👩🏾‍❤️‍👩🏻 +👩🏾‍❤️‍👩🏼 +👩🏾‍❤️‍👩🏽 +👩🏾‍❤️‍👩🏾 +👩🏾‍❤️‍👩🏿 +👩🏿‍❤️‍👩🏻 +👩🏿‍❤️‍👩🏼 +👩🏿‍❤️‍👩🏽 +👩🏿‍❤️‍👩🏾 +👩🏿‍❤️‍👩🏿 +👩‍❤️‍👩 +👨🏻‍❤️‍👨🏻 +👨🏻‍❤️‍👨🏼 +👨🏻‍❤️‍👨🏽 +👨🏻‍❤️‍👨🏾 +👨🏻‍❤️‍👨🏿 +👨🏼‍❤️‍👨🏻 +👨🏼‍❤️‍👨🏼 +👨🏼‍❤️‍👨🏽 +👨🏼‍❤️‍👨🏾 +👨🏼‍❤️‍👨🏿 +👨🏽‍❤️‍👨🏻 +👨🏽‍❤️‍👨🏼 +👨🏽‍❤️‍👨🏽 +👨🏽‍❤️‍👨🏾 +👨🏽‍❤️‍👨🏿 +👨🏾‍❤️‍👨🏻 +👨🏾‍❤️‍👨🏼 +👨🏾‍❤️‍👨🏽 +👨🏾‍❤️‍👨🏾 +👨🏾‍❤️‍👨🏿 +👨🏿‍❤️‍👨🏻 +👨🏿‍❤️‍👨🏼 +👨🏿‍❤️‍👨🏽 +👨🏿‍❤️‍👨🏾 +👨🏿‍❤️‍👨🏿 +👨‍❤️‍👨 +💏🏻 +🧑🏻‍❤️‍💋‍🧑🏼 +🧑🏻‍❤️‍💋‍🧑🏽 +🧑🏻‍❤️‍💋‍🧑🏾 +🧑🏻‍❤️‍💋‍🧑🏿 +🧑🏼‍❤️‍💋‍🧑🏻 +💏🏼 +🧑🏼‍❤️‍💋‍🧑🏽 +🧑🏼‍❤️‍💋‍🧑🏾 +🧑🏼‍❤️‍💋‍🧑🏿 +🧑🏽‍❤️‍💋‍🧑🏻 +🧑🏽‍❤️‍💋‍🧑🏼 +💏🏽 +🧑🏽‍❤️‍💋‍🧑🏾 +🧑🏽‍❤️‍💋‍🧑🏿 +🧑🏾‍❤️‍💋‍🧑🏻 +🧑🏾‍❤️‍💋‍🧑🏼 +🧑🏾‍❤️‍💋‍🧑🏽 +💏🏾 +🧑🏾‍❤️‍💋‍🧑🏿 +🧑🏿‍❤️‍💋‍🧑🏻 +🧑🏿‍❤️‍💋‍🧑🏼 +🧑🏿‍❤️‍💋‍🧑🏽 +🧑🏿‍❤️‍💋‍🧑🏾 +💏🏿 +💏 +👩🏻‍❤️‍💋‍👨🏻 +👩🏻‍❤️‍💋‍👨🏼 +👩🏻‍❤️‍💋‍👨🏽 +👩🏻‍❤️‍💋‍👨🏾 +👩🏻‍❤️‍💋‍👨🏿 +👩🏼‍❤️‍💋‍👨🏻 +👩🏼‍❤️‍💋‍👨🏼 +👩🏼‍❤️‍💋‍👨🏽 +👩🏼‍❤️‍💋‍👨🏾 +👩🏼‍❤️‍💋‍👨🏿 +👩🏽‍❤️‍💋‍👨🏻 +👩🏽‍❤️‍💋‍👨🏼 +👩🏽‍❤️‍💋‍👨🏽 +👩🏽‍❤️‍💋‍👨🏾 +👩🏽‍❤️‍💋‍👨🏿 +👩🏾‍❤️‍💋‍👨🏻 +👩🏾‍❤️‍💋‍👨🏼 +👩🏾‍❤️‍💋‍👨🏽 +👩🏾‍❤️‍💋‍👨🏾 +👩🏾‍❤️‍💋‍👨🏿 +👩🏿‍❤️‍💋‍👨🏻 +👩🏿‍❤️‍💋‍👨🏼 +👩🏿‍❤️‍💋‍👨🏽 +👩🏿‍❤️‍💋‍👨🏾 +👩🏿‍❤️‍💋‍👨🏿 +👩‍❤️‍💋‍👨 +👩🏻‍❤️‍💋‍👩🏻 +👩🏻‍❤️‍💋‍👩🏼 +👩🏻‍❤️‍💋‍👩🏽 +👩🏻‍❤️‍💋‍👩🏾 +👩🏻‍❤️‍💋‍👩🏿 +👩🏼‍❤️‍💋‍👩🏻 +👩🏼‍❤️‍💋‍👩🏼 +👩🏼‍❤️‍💋‍👩🏽 +👩🏼‍❤️‍💋‍👩🏾 +👩🏼‍❤️‍💋‍👩🏿 +👩🏽‍❤️‍💋‍👩🏻 +👩🏽‍❤️‍💋‍👩🏼 +👩🏽‍❤️‍💋‍👩🏽 +👩🏽‍❤️‍💋‍👩🏾 +👩🏽‍❤️‍💋‍👩🏿 +👩🏾‍❤️‍💋‍👩🏻 +👩🏾‍❤️‍💋‍👩🏼 +👩🏾‍❤️‍💋‍👩🏽 +👩🏾‍❤️‍💋‍👩🏾 +👩🏾‍❤️‍💋‍👩🏿 +👩🏿‍❤️‍💋‍👩🏻 +👩🏿‍❤️‍💋‍👩🏼 +👩🏿‍❤️‍💋‍👩🏽 +👩🏿‍❤️‍💋‍👩🏾 +👩🏿‍❤️‍💋‍👩🏿 +👩‍❤️‍💋‍👩 +👨🏻‍❤️‍💋‍👨🏻 +👨🏻‍❤️‍💋‍👨🏼 +👨🏻‍❤️‍💋‍👨🏽 +👨🏻‍❤️‍💋‍👨🏾 +👨🏻‍❤️‍💋‍👨🏿 +👨🏼‍❤️‍💋‍👨🏻 +👨🏼‍❤️‍💋‍👨🏼 +👨🏼‍❤️‍💋‍👨🏽 +👨🏼‍❤️‍💋‍👨🏾 +👨🏼‍❤️‍💋‍👨🏿 +👨🏽‍❤️‍💋‍👨🏻 +👨🏽‍❤️‍💋‍👨🏼 +👨🏽‍❤️‍💋‍👨🏽 +👨🏽‍❤️‍💋‍👨🏾 +👨🏽‍❤️‍💋‍👨🏿 +👨🏾‍❤️‍💋‍👨🏻 +👨🏾‍❤️‍💋‍👨🏼 +👨🏾‍❤️‍💋‍👨🏽 +👨🏾‍❤️‍💋‍👨🏾 +👨🏾‍❤️‍💋‍👨🏿 +👨🏿‍❤️‍💋‍👨🏻 +👨🏿‍❤️‍💋‍👨🏼 +👨🏿‍❤️‍💋‍👨🏽 +👨🏿‍❤️‍💋‍👨🏾 +👨🏿‍❤️‍💋‍👨🏿 +👨‍❤️‍💋‍👨 +🧑‍🧑‍🧒‍🧒 +🧑‍🧑‍🧒 +🧑‍🧒‍🧒 +🧑‍🧒 +👪 +👨‍👩‍👦 +👨‍👩‍👧 +👨‍👩‍👧‍👦 +👨‍👩‍👦‍👦 +👨‍👩‍👧‍👧 +👩‍👩‍👦 +👩‍👩‍👧 +👩‍👩‍👧‍👦 +👩‍👩‍👦‍👦 +👩‍👩‍👧‍👧 +👨‍👨‍👦 +👨‍👨‍👧 +👨‍👨‍👧‍👦 +👨‍👨‍👦‍👦 +👨‍👨‍👧‍👧 +👩‍👦 +👩‍👧 +👩‍👧‍👦 +👩‍👦‍👦 +👩‍👧‍👧 +👨‍👦 +👨‍👧 +👨‍👧‍👦 +👨‍👦‍👦 +👨‍👧‍👧 +🪢 +🧶 +🧵 +🪡 +🧥 +🥼 +🦺 +👚 +👕 +👖 +🩲 +🩳 +👔 +👗 +👙 +🩱 +👘 +🥻 +🩴 +🥿 +👠 +👡 +👢 +👞 +👟 +🥾 +🧦 +🧤 +🧣 +🎩 +🧢 +👒 +🎓 +⛑️ +🪖 +👑 +💍 +👝 +👛 +👜 +💼 +🎒 +🧳 +👓 +🕶️ +🥽 +🌂 +🐶 +🐱 +🐭 +🐹 +🐰 +🦊 +🐻 +🐼 +🐻‍❄️ +🐨 +🐯 +🦁 +🐮 +🐷 +🐽 +🐸 +🐵 +🙈 +🙉 +🙊 +🐒 +🐔 +🐧 +🐦 +🐤 +🐣 +🐥 +🪿 +🦆 +🐦‍⬛ +🦅 +🦉 +🦇 +🐺 +🐗 +🐴 +🦄 +🫎 +🐝 +🪱 +🐛 +🦋 +🐌 +🐞 +🐜 +🪰 +🪲 +🪳 +🦟 +🦗 +🕷️ +🕸️ +🦂 +🐢 +🐍 +🦎 +🦖 +🦕 +🐙 +🦑 +🪼 +🦐 +🦞 +🦀 +🐡 +🐠 +🐟 +🐬 +🐳 +🐋 +🦈 +🦭 +🐊 +🐅 +🐆 +🦓 +🦍 +🦧 +🦣 +🐘 +🦛 +🦏 +🐪 +🐫 +🦒 +🦘 +🦬 +🐃 +🐂 +🐄 +🫏 +🐎 +🐖 +🐏 +🐑 +🦙 +🐐 +🦌 +🐕 +🐩 +🦮 +🐕‍🦺 +🐈 +🐈‍⬛ +🪶 +🪽 +🐓 +🦃 +🦤 +🦚 +🦜 +🦢 +🦩 +🕊️ +🐇 +🦝 +🦨 +🦡 +🦫 +🦦 +🦥 +🐁 +🐀 +🐿️ +🦔 +🐾 +🐉 +🐲 +🐦‍🔥 +🌵 +🎄 +🌲 +🌳 +🌴 +🪵 +🌱 +🌿 +☘️ +🍀 +🎍 +🪴 +🎋 +🍃 +🍂 +🍁 +🪺 +🪹 +🍄 +🍄‍🟫 +🐚 +🪸 +🪨 +🌾 +💐 +🌷 +🌹 +🥀 +🪻 +🪷 +🌺 +🌸 +🌼 +🌻 +🌞 +🌝 +🌛 +🌜 +🌚 +🌕 +🌖 +🌗 +🌘 +🌑 +🌒 +🌓 +🌔 +🌙 +🌎 +🌍 +🌏 +🪐 +💫 +⭐ +🌟 +✨ +⚡ +☄️ +💥 +🔥 +🌪️ +🌈 +☀️ +🌤️ +⛅ +🌥️ +☁️ +🌦️ +🌧️ +⛈️ +🌩️ +🌨️ +❄️ +☃️ +⛄ +🌬️ +💨 +💧 +💦 +🫧 +☔ +☂️ +🌊 +🌫️ +🍏 +🍎 +🍐 +🍊 +🍋 +🍋‍🟩 +🍌 +🍉 +🍇 +🍓 +🫐 +🍈 +🍒 +🍑 +🥭 +🍍 +🥥 +🥝 +🍅 +🍆 +🥑 +🫛 +🥦 +🥬 +🥒 +🌶️ +🫑 +🌽 +🥕 +🫒 +🧄 +🧅 +🥔 +🍠 +🫚 +🥐 +🥯 +🍞 +🥖 +🥨 +🧀 +🥚 +🍳 +🧈 +🥞 +🧇 +🥓 +🥩 +🍗 +🍖 +🦴 +🌭 +🍔 +🍟 +🍕 +🫓 +🥪 +🥙 +🧆 +🌮 +🌯 +🫔 +🥗 +🥘 +🫕 +🥫 +🫙 +🍝 +🍜 +🍲 +🍛 +🍣 +🍱 +🥟 +🦪 +🍤 +🍙 +🍚 +🍘 +🍥 +🥠 +🥮 +🍢 +🍡 +🍧 +🍨 +🍦 +🥧 +🧁 +🍰 +🎂 +🍮 +🍭 +🍬 +🍫 +🍿 +🍩 +🍪 +🌰 +🥜 +🫘 +🍯 +🥛 +🫗 +🍼 +🫖 +☕ +🍵 +🧉 +🧃 +🥤 +🧋 +🍶 +🍺 +🍻 +🥂 +🍷 +🥃 +🍸 +🍹 +🍾 +🧊 +🥄 +🍴 +🍽️ +🥣 +🥡 +🥢 +🧂 +⚽ +🏀 +🏈 +⚾ +🥎 +🎾 +🏐 +🏉 +🥏 +🎱 +🪀 +🏓 +🏸 +🏒 +🏑 +🥍 +🏏 +🪃 +🥅 +⛳ +🪁 +🛝 +🏹 +🎣 +🤿 +🥊 +🥋 +🎽 +🛹 +🛼 +🛷 +⛸️ +🥌 +🎿 +⛷️ +🏂🏻 +🏂🏼 +🏂🏽 +🏂🏾 +🏂🏿 +🏂 +🪂 +🏋🏻 +🏋🏼 +🏋🏽 +🏋🏾 +🏋🏿 +🏋️ +🏋🏻‍♀️ +🏋🏼‍♀️ +🏋🏽‍♀️ +🏋🏾‍♀️ +🏋🏿‍♀️ +🏋️‍♀️ +🏋🏻‍♂️ +🏋🏼‍♂️ +🏋🏽‍♂️ +🏋🏾‍♂️ +🏋🏿‍♂️ +🏋️‍♂️ +🤼 +🤼‍♀️ +🤼‍♂️ +🤸🏻 +🤸🏼 +🤸🏽 +🤸🏾 +🤸🏿 +🤸 +🤸🏻‍♀️ +🤸🏼‍♀️ +🤸🏽‍♀️ +🤸🏾‍♀️ +🤸🏿‍♀️ +🤸‍♀️ +🤸🏻‍♂️ +🤸🏼‍♂️ +🤸🏽‍♂️ +🤸🏾‍♂️ +🤸🏿‍♂️ +🤸‍♂️ +⛹🏻 +⛹🏼 +⛹🏽 +⛹🏾 +⛹🏿 +⛹️ +⛹🏻‍♀️ +⛹🏼‍♀️ +⛹🏽‍♀️ +⛹🏾‍♀️ +⛹🏿‍♀️ +⛹️‍♀️ +⛹🏻‍♂️ +⛹🏼‍♂️ +⛹🏽‍♂️ +⛹🏾‍♂️ +⛹🏿‍♂️ +⛹️‍♂️ +🤺 +🤾🏻 +🤾🏼 +🤾🏽 +🤾🏾 +🤾🏿 +🤾 +🤾🏻‍♀️ +🤾🏼‍♀️ +🤾🏽‍♀️ +🤾🏾‍♀️ +🤾🏿‍♀️ +🤾‍♀️ +🤾🏻‍♂️ +🤾🏼‍♂️ +🤾🏽‍♂️ +🤾🏾‍♂️ +🤾🏿‍♂️ +🤾‍♂️ +🏌🏻 +🏌🏼 +🏌🏽 +🏌🏾 +🏌🏿 +🏌️ +🏌🏻‍♀️ +🏌🏼‍♀️ +🏌🏽‍♀️ +🏌🏾‍♀️ +🏌🏿‍♀️ +🏌️‍♀️ +🏌🏻‍♂️ +🏌🏼‍♂️ +🏌🏽‍♂️ +🏌🏾‍♂️ +🏌🏿‍♂️ +🏌️‍♂️ +🏇🏻 +🏇🏼 +🏇🏽 +🏇🏾 +🏇🏿 +🏇 +🧘🏻 +🧘🏼 +🧘🏽 +🧘🏾 +🧘🏿 +🧘 +🧘🏻‍♀️ +🧘🏼‍♀️ +🧘🏽‍♀️ +🧘🏾‍♀️ +🧘🏿‍♀️ +🧘‍♀️ +🧘🏻‍♂️ +🧘🏼‍♂️ +🧘🏽‍♂️ +🧘🏾‍♂️ +🧘🏿‍♂️ +🧘‍♂️ +🏄🏻 +🏄🏼 +🏄🏽 +🏄🏾 +🏄🏿 +🏄 +🏄🏻‍♀️ +🏄🏼‍♀️ +🏄🏽‍♀️ +🏄🏾‍♀️ +🏄🏿‍♀️ +🏄‍♀️ +🏄🏻‍♂️ +🏄🏼‍♂️ +🏄🏽‍♂️ +🏄🏾‍♂️ +🏄🏿‍♂️ +🏄‍♂️ +🏊🏻 +🏊🏼 +🏊🏽 +🏊🏾 +🏊🏿 +🏊 +🏊🏻‍♀️ +🏊🏼‍♀️ +🏊🏽‍♀️ +🏊🏾‍♀️ +🏊🏿‍♀️ +🏊‍♀️ +🏊🏻‍♂️ +🏊🏼‍♂️ +🏊🏽‍♂️ +🏊🏾‍♂️ +🏊🏿‍♂️ +🏊‍♂️ +🤽🏻 +🤽🏼 +🤽🏽 +🤽🏾 +🤽🏿 +🤽 +🤽🏻‍♀️ +🤽🏼‍♀️ +🤽🏽‍♀️ +🤽🏾‍♀️ +🤽🏿‍♀️ +🤽‍♀️ +🤽🏻‍♂️ +🤽🏼‍♂️ +🤽🏽‍♂️ +🤽🏾‍♂️ +🤽🏿‍♂️ +🤽‍♂️ +🚣🏻 +🚣🏼 +🚣🏽 +🚣🏾 +🚣🏿 +🚣 +🚣🏻‍♀️ +🚣🏼‍♀️ +🚣🏽‍♀️ +🚣🏾‍♀️ +🚣🏿‍♀️ +🚣‍♀️ +🚣🏻‍♂️ +🚣🏼‍♂️ +🚣🏽‍♂️ +🚣🏾‍♂️ +🚣🏿‍♂️ +🚣‍♂️ +🧗🏻 +🧗🏼 +🧗🏽 +🧗🏾 +🧗🏿 +🧗 +🧗🏻‍♀️ +🧗🏼‍♀️ +🧗🏽‍♀️ +🧗🏾‍♀️ +🧗🏿‍♀️ +🧗‍♀️ +🧗🏻‍♂️ +🧗🏼‍♂️ +🧗🏽‍♂️ +🧗🏾‍♂️ +🧗🏿‍♂️ +🧗‍♂️ +🚵🏻 +🚵🏼 +🚵🏽 +🚵🏾 +🚵🏿 +🚵 +🚵🏻‍♀️ +🚵🏼‍♀️ +🚵🏽‍♀️ +🚵🏾‍♀️ +🚵🏿‍♀️ +🚵‍♀️ +🚵🏻‍♂️ +🚵🏼‍♂️ +🚵🏽‍♂️ +🚵🏾‍♂️ +🚵🏿‍♂️ +🚵‍♂️ +🚴🏻 +🚴🏼 +🚴🏽 +🚴🏾 +🚴🏿 +🚴 +🚴🏻‍♀️ +🚴🏼‍♀️ +🚴🏽‍♀️ +🚴🏾‍♀️ +🚴🏿‍♀️ +🚴‍♀️ +🚴🏻‍♂️ +🚴🏼‍♂️ +🚴🏽‍♂️ +🚴🏾‍♂️ +🚴🏿‍♂️ +🚴‍♂️ +🏆 +🥇 +🥈 +🥉 +🏅 +🎖️ +🏵️ +🎗️ +🎫 +🎟️ +🎪 +🤹🏻 +🤹🏼 +🤹🏽 +🤹🏾 +🤹🏿 +🤹 +🤹🏻‍♀️ +🤹🏼‍♀️ +🤹🏽‍♀️ +🤹🏾‍♀️ +🤹🏿‍♀️ +🤹‍♀️ +🤹🏻‍♂️ +🤹🏼‍♂️ +🤹🏽‍♂️ +🤹🏾‍♂️ +🤹🏿‍♂️ +🤹‍♂️ +🎭 +🩰 +🎨 +🎬 +🎤 +🎧 +🎼 +🎹 +🪇 +🥁 +🪘 +🎷 +🎺 +🪗 +🎸 +🪕 +🎻 +🪈 +🎲 +♟️ +🎯 +🎳 +🎮 +🎰 +🧩 +🚗 +🚕 +🚙 +🛻 +🚐 +🚌 +🚎 +🏎️ +🚓 +🚑 +🚒 +🚚 +🚛 +🚜 +🦯 +🦽 +🦼 +🩼 +🛴 +🚲 +🛵 +🏍️ +🛺 +🛞 +🚨 +🚔 +🚍 +🚘 +🚖 +🚡 +🚠 +🚟 +🚃 +🚋 +🚞 +🚝 +🚄 +🚅 +🚈 +🚂 +🚆 +🚇 +🚊 +🚉 +✈️ +🛫 +🛬 +🛩️ +💺 +🛰️ +🚀 +🛸 +🚁 +🛶 +⛵ +🚤 +🛥️ +🛳️ +⛴️ +🚢 +🛟 +⚓ +🪝 +⛽ +🚧 +🚦 +🚥 +🚏 +🗺️ +🗿 +🗽 +🗼 +🏰 +🏯 +🏟️ +🎡 +🎢 +🎠 +⛲ +⛱️ +🏖️ +🏝️ +🏜️ +🌋 +⛰️ +🏔️ +🗻 +🏕️ +⛺ +🏠 +🏡 +🏘️ +🏚️ +🛖 +🏗️ +🏭 +🏢 +🏬 +🏣 +🏤 +🏥 +🏦 +🏨 +🏪 +🏫 +🏩 +💒 +🏛️ +⛪ +🕌 +🕍 +🛕 +🕋 +⛩️ +🛤️ +🛣️ +🗾 +🎑 +🏞️ +🌅 +🌄 +🌠 +🎇 +🎆 +🌇 +🌆 +🏙️ +🌃 +🌌 +🌉 +🌁 +⌚ +📱 +📲 +💻 +⌨️ +🖥️ +🖨️ +🖱️ +🖲️ +🕹️ +🗜️ +💽 +💾 +💿 +📀 +📼 +📷 +📸 +📹 +🎥 +📽️ +🎞️ +📞 +☎️ +📟 +📠 +📺 +📻 +🎙️ +🎚️ +🎛️ +🧭 +⏱️ +⏲️ +⏰ +🕰️ +⌛ +⏳ +📡 +🔋 +🪫 +🔌 +💡 +🔦 +🕯️ +🪔 +🧯 +🛢️ +💸 +💵 +💴 +💶 +💷 +🪙 +💰 +💳 +🪪 +💎 +⚖️ +🪜 +🧰 +🪛 +🔧 +🔨 +⚒️ +🛠️ +⛏️ +🪚 +🔩 +⚙️ +🪤 +🧱 +⛓️ +🔗 +⛓️‍💥 +🧲 +🔫 +💣 +🧨 +🪓 +🔪 +🗡️ +⚔️ +🛡️ +🚬 +⚰️ +🪦 +⚱️ +🏺 +🔮 +📿 +🧿 +🪬 +💈 +⚗️ +🔭 +🔬 +🕳️ +🩻 +🩹 +🩺 +💊 +💉 +🩸 +🧬 +🦠 +🧫 +🧪 +🌡️ +🧹 +🪠 +🧺 +🧻 +🚽 +🚰 +🚿 +🛁 +🛀🏻 +🛀🏼 +🛀🏽 +🛀🏾 +🛀🏿 +🛀 +🧼 +🪥 +🪒 +🪮 +🧽 +🪣 +🧴 +🛎️ +🔑 +🗝️ +🚪 +🪑 +🛋️ +🛏️ +🛌🏻 +🛌🏼 +🛌🏽 +🛌🏾 +🛌🏿 +🛌 +🧸 +🪆 +🖼️ +🪞 +🪟 +🛍️ +🛒 +🎁 +🎈 +🎏 +🎀 +🪄 +🪅 +🎊 +🎉 +🎎 +🪭 +🏮 +🎐 +🪩 +🧧 +✉️ +📩 +📨 +📧 +💌 +📥 +📤 +📦 +🏷️ +🪧 +📪 +📫 +📬 +📭 +📮 +📯 +📜 +📃 +📄 +📑 +🧾 +📊 +📈 +📉 +🗒️ +🗓️ +📆 +📅 +🗑️ +📇 +🗃️ +🗳️ +🗄️ +📋 +📁 +📂 +🗂️ +🗞️ +📰 +📓 +📔 +📒 +📕 +📗 +📘 +📙 +📚 +📖 +🔖 +🧷 +📎 +🖇️ +📐 +📏 +🧮 +📌 +📍 +✂️ +🖊️ +🖋️ +✒️ +🖌️ +🖍️ +📝 +✏️ +🔍 +🔎 +🔏 +🔐 +🔒 +🔓 +🩷 +❤️ +🧡 +💛 +💚 +🩵 +💙 +💜 +🖤 +🩶 +🤍 +🤎 +💔 +❣️ +💕 +💞 +💓 +💗 +💖 +💘 +💝 +❤️‍🩹 +❤️‍🔥 +💟 +☮️ +✝️ +☪️ +🕉️ +☸️ +🪯 +✡️ +🔯 +🕎 +☯️ +☦️ +🛐 +⛎ +♈ +♉ +♊ +♋ +♌ +♍ +♎ +♏ +♐ +♑ +♒ +♓ +🆔 +⚛️ +🉑 +☢️ +☣️ +📴 +📳 +🈶 +🈚 +🈸 +🈺 +🈷️ +✴️ +🆚 +💮 +🉐 +㊙️ +㊗️ +🈴 +🈵 +🈹 +🈲 +🅰️ +🅱️ +🆎 +🆑 +🅾️ +🆘 +❌ +⭕ +🛑 +⛔ +📛 +🚫 +💯 +💢 +♨️ +🚷 +🚯 +🚳 +🚱 +🔞 +📵 +🚭 +❗ +❕ +❓ +❔ +‼️ +⁉️ +🔅 +🔆 +〽️ +⚠️ +🚸 +🔱 +⚜️ +🔰 +♻️ +✅ +🈯 +💹 +❇️ +✳️ +❎ +🌐 +💠 +Ⓜ️ +🌀 +💤 +🏧 +🚾 +♿ +🅿️ +🛗 +🈳 +🈂️ +🛂 +🛃 +🛄 +🛅 +🛜 +🚹 +🚺 +🚼 +🚻 +🚮 +🎦 +📶 +🈁 +🔣 +ℹ️ +🔤 +🔡 +🔠 +🆖 +🆗 +🆙 +🆒 +🆕 +🆓 +0️⃣ +1️⃣ +2️⃣ +3️⃣ +4️⃣ +5️⃣ +6️⃣ +7️⃣ +8️⃣ +9️⃣ +🔟 +🔢 +#️⃣ +*️⃣ +⏏️ +▶️ +⏸️ +⏯️ +⏹️ +⏺️ +⏭️ +⏮️ +⏩ +⏪ +⏫ +⏬ +◀️ +🔼 +🔽 +➡️ +⬅️ +⬆️ +⬇️ +↗️ +↘️ +↙️ +↖️ +↕️ +↔️ +↪️ +↩️ +⤴️ +⤵️ +🔀 +🔁 +🔂 +🔄 +🔃 +🎵 +🎶 +➕ +➖ +➗ +✖️ +🟰 +♾️ +💲 +💱 +™️ +©️ +®️ +〰️ +➰ +➿ +🔚 +🔙 +🔛 +🔝 +🔜 +✔️ +☑️ +🔘 +⚪ +⚫ +🔴 +🔵 +🟤 +🟣 +🟢 +🟡 +🟠 +🔺 +🔻 +🔸 +🔹 +🔶 +🔷 +🔳 +🔲 +▪️ +▫️ +◾ +◽ +◼️ +◻️ +⬛ +⬜ +🟧 +🟦 +🟥 +🟫 +🟪 +🟩 +🟨 +🔈 +🔇 +🔉 +🔊 +🔔 +🔕 +📣 +📢 +🗨️ +👁‍🗨 +💬 +💭 +🗯️ +♠️ +♣️ +♥️ +♦️ +🃏 +🎴 +🀄 +🕐 +🕑 +🕒 +🕓 +🕔 +🕕 +🕖 +🕗 +🕘 +🕙 +🕚 +🕛 +🕜 +🕝 +🕞 +🕟 +🕠 +🕡 +🕢 +🕣 +🕤 +🕥 +🕦 +🕧 +♀️ +♂️ +⚧ +⚕️ +🇿 +🇾 +🇽 +🇼 +🇻 +🇺 +🇹 +🇸 +🇷 +🇶 +🇵 +🇴 +🇳 +🇲 +🇱 +🇰 +🇯 +🇮 +🇭 +🇬 +🇫 +🇪 +🇩 +🇨 +🇧 +🇦 +🏳️ +🏴 +🏴‍☠️ +🏁 +🚩 +🏳️‍🌈 +🏳️‍⚧️ +🇺🇳 +🇦🇫 +🇦🇽 +🇦🇱 +🇩🇿 +🇦🇸 +🇦🇩 +🇦🇴 +🇦🇮 +🇦🇶 +🇦🇬 +🇦🇷 +🇦🇲 +🇦🇼 +🇦🇺 +🇦🇹 +🇦🇿 +🇧🇸 +🇧🇭 +🇧🇩 +🇧🇧 +🇧🇾 +🇧🇪 +🇧🇿 +🇧🇯 +🇧🇲 +🇧🇹 +🇧🇴 +🇧🇦 +🇧🇼 +🇧🇷 +🇮🇴 +🇻🇬 +🇧🇳 +🇧🇬 +🇧🇫 +🇧🇮 +🇰🇭 +🇨🇲 +🇨🇦 +🇮🇨 +🇨🇻 +🇧🇶 +🇰🇾 +🇨🇫 +🇹🇩 +🇨🇱 +🇨🇳 +🇨🇽 +🇨🇨 +🇨🇴 +🇰🇲 +🇨🇬 +🇨🇩 +🇨🇰 +🇨🇷 +🇨🇮 +🇭🇷 +🇨🇺 +🇨🇼 +🇨🇾 +🇨🇿 +🇩🇰 +🇩🇯 +🇩🇲 +🇩🇴 +🇪🇨 +🇪🇬 +🇸🇻 +🇬🇶 +🇪🇷 +🇪🇪 +🇪🇹 +🇪🇺 +🇫🇰 +🇫🇴 +🇫🇯 +🇫🇮 +🇫🇷 +🇬🇫 +🇵🇫 +🇹🇫 +🇬🇦 +🇬🇲 +🇬🇪 +🇩🇪 +🇬🇭 +🇬🇮 +🇬🇷 +🇬🇱 +🇬🇩 +🇬🇵 +🇬🇺 +🇬🇹 +🇬🇬 +🇬🇳 +🇬🇼 +🇬🇾 +🇭🇹 +🇭🇳 +🇭🇰 +🇭🇺 +🇮🇸 +🇮🇳 +🇮🇩 +🇮🇷 +🇮🇶 +🇮🇪 +🇮🇲 +🇮🇱 +🇮🇹 +🇯🇲 +🇯🇵 +🎌 +🇯🇪 +🇯🇴 +🇰🇿 +🇰🇪 +🇰🇮 +🇽🇰 +🇰🇼 +🇰🇬 +🇱🇦 +🇱🇻 +🇱🇧 +🇱🇸 +🇱🇷 +🇱🇾 +🇱🇮 +🇱🇹 +🇱🇺 +🇲🇴 +🇲🇰 +🇲🇬 +🇲🇼 +🇲🇾 +🇲🇻 +🇲🇱 +🇲🇹 +🇲🇭 +🇲🇶 +🇲🇷 +🇲🇺 +🇾🇹 +🇲🇽 +🇫🇲 +🇲🇩 +🇲🇨 +🇲🇳 +🇲🇪 +🇲🇸 +🇲🇦 +🇲🇿 +🇲🇲 +🇳🇦 +🇳🇷 +🇳🇵 +🇳🇱 +🇳🇨 +🇳🇿 +🇳🇮 +🇳🇪 +🇳🇬 +🇳🇺 +🇳🇫 +🇰🇵 +🇲🇵 +🇳🇴 +🇴🇲 +🇵🇰 +🇵🇼 +🇵🇸 +🇵🇦 +🇵🇬 +🇵🇾 +🇵🇪 +🇵🇭 +🇵🇳 +🇵🇱 +🇵🇹 +🇵🇷 +🇶🇦 +🇷🇪 +🇷🇴 +🇷🇺 +🇷🇼 +🇼🇸 +🇸🇲 +🇸🇹 +🇸🇦 +🇸🇳 +🇷🇸 +🇸🇨 +🇸🇱 +🇸🇬 +🇸🇽 +🇸🇰 +🇸🇮 +🇬🇸 +🇸🇧 +🇸🇴 +🇿🇦 +🇰🇷 +🇸🇸 +🇪🇸 +🇱🇰 +🇧🇱 +🇸🇭 +🇰🇳 +🇱🇨 +🇵🇲 +🇻🇨 +🇸🇩 +🇸🇷 +🇸🇿 +🇸🇪 +🇨🇭 +🇸🇾 +🇹🇼 +🇹🇯 +🇹🇿 +🇹🇭 +🇹🇱 +🇹🇬 +🇹🇰 +🇹🇴 +🇹🇹 +🇹🇳 +🇹🇷 +🇹🇲 +🇹🇨 +🇻🇮 +🇹🇻 +🇺🇬 +🇺🇦 +🇦🇪 +🇬🇧 +🏴󠁧󠁢󠁥󠁮󠁧󠁿 +🏴󠁧󠁢󠁳󠁣󠁴󠁿 +🏴󠁧󠁢󠁷󠁬󠁳󠁿 +🇺🇸 +🇺🇾 +🇺🇿 +🇻🇺 +🇻🇦 +🇻🇪 +🇻🇳 +🇼🇫 +🇪🇭 +🇾🇪 +🇿🇲 +🇿🇼 +🇦🇨 +🇧🇻 +🇨🇵 +🇪🇦 +🇩🇬 +🇭🇲 +🇲🇫 +🇸🇯 +🇹🇦 +🇺🇲 \ No newline at end of file diff --git a/test/test.js b/test/test.js index 591b64b..69e3d48 100644 --- a/test/test.js +++ b/test/test.js @@ -141,6 +141,7 @@ file._actuallyUploadDiscordFileToMxc = function(url, res) { throw new Error(`Not require("../src/d2m/converters/user-to-mxid.test") require("../src/m2d/converters/diff-pins.test") require("../src/m2d/converters/event-to-message.test") + require("../src/m2d/converters/emoji.test") require("../src/m2d/converters/utils.test") require("../src/m2d/converters/emoji-sheet.test") require("../src/discord/interactions/invite.test") From 5b06d5984ac91d830f161fbbcf72b6ba5ff9d11e Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 20 Jan 2025 02:33:24 +1300 Subject: [PATCH 084/228] Do cache space members in member_cache --- scripts/setup.js | 4 ++-- src/d2m/actions/register-pk-user.js | 2 +- src/d2m/actions/register-user.js | 2 +- src/d2m/converters/user-to-mxid.js | 2 +- src/db/migrations/0016-foreign-keys.sql | 23 +++------------------ src/m2d/converters/event-to-message.js | 19 ++++++++++------- src/m2d/converters/event-to-message.test.js | 14 ++++++------- src/m2d/event-dispatcher.js | 4 ++-- test/ooye-test-data.sql | 22 ++++++++++---------- 9 files changed, 40 insertions(+), 52 deletions(-) diff --git a/scripts/setup.js b/scripts/setup.js index 3491106..6ee8c19 100644 --- a/scripts/setup.js +++ b/scripts/setup.js @@ -319,8 +319,8 @@ function defineEchoHandler() { await migrate.migrate(db) // add initial rows to database, like adding the bot to sim... - const botID = Buffer.from(reg.ooye.discord_token.split(".")[0], "base64").toString() - db.prepare("INSERT OR IGNORE INTO sim (user_id, sim_name, localpart, mxid) VALUES (?, ?, ?, ?)").run(botID, reg.sender_localpart.slice(reg.ooye.namespace_prefix.length), reg.sender_localpart, mxid) + const client = await discord.snow.user.getSelf() + db.prepare("INSERT INTO sim (user_id, username, sim_name, mxid) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING").run(client.id, client.username, reg.sender_localpart.slice(reg.ooye.namespace_prefix.length), mxid) console.log("✅ Database is ready...") diff --git a/src/d2m/actions/register-pk-user.js b/src/d2m/actions/register-pk-user.js index 411fcf8..7083006 100644 --- a/src/d2m/actions/register-pk-user.js +++ b/src/d2m/actions/register-pk-user.js @@ -33,7 +33,7 @@ async function createSim(pkMessage) { const mxid = `@${localpart}:${reg.ooye.server_name}` // Save chosen name in the database forever - db.prepare("INSERT INTO sim (user_id, sim_name, localpart, mxid) VALUES (?, ?, ?, ?)").run(pkMessage.member.uuid, simName, localpart, mxid) + db.prepare("INSERT INTO sim (user_id, username, sim_name, mxid) VALUES (?, ?, ?, ?)").run(pkMessage.member.uuid, simName, simName, mxid) // Register matrix user with that name try { diff --git a/src/d2m/actions/register-user.js b/src/d2m/actions/register-user.js index b914d41..c3bd16c 100644 --- a/src/d2m/actions/register-user.js +++ b/src/d2m/actions/register-user.js @@ -33,7 +33,7 @@ async function createSim(user) { // Save chosen name in the database forever // Making this database change right away so that in a concurrent registration, the 2nd registration will already have generated a different localpart because it can see this row when it generates - db.prepare("INSERT INTO sim (user_id, sim_name, localpart, mxid) VALUES (?, ?, ?, ?)").run(user.id, simName, localpart, mxid) + db.prepare("INSERT INTO sim (user_id, username, sim_name, mxid) VALUES (?, ?, ?, ?)").run(user.id, user.username, simName, mxid) // Register matrix user with that name try { diff --git a/src/d2m/converters/user-to-mxid.js b/src/d2m/converters/user-to-mxid.js index a619b36..e0ab137 100644 --- a/src/d2m/converters/user-to-mxid.js +++ b/src/d2m/converters/user-to-mxid.js @@ -64,7 +64,7 @@ function userToSimName(user) { } // 1. Is sim user already registered? - const existing = select("sim", "sim_name", {user_id: user.id}).pluck().get() + const existing = select("sim", "user_id", {user_id: user.id}).pluck().get() assert.equal(existing, null, "Shouldn't try to create a new name for an existing sim") // 2. Register based on username (could be new or old format) diff --git a/src/db/migrations/0016-foreign-keys.sql b/src/db/migrations/0016-foreign-keys.sql index c41f329..7a2b26c 100644 --- a/src/db/migrations/0016-foreign-keys.sql +++ b/src/db/migrations/0016-foreign-keys.sql @@ -86,24 +86,6 @@ DROP TABLE guild_space; -- 7 ALTER TABLE new_guild_space RENAME TO guild_space; --- *** member_cache *** - --- 4 -CREATE TABLE "new_member_cache" ( - "room_id" TEXT NOT NULL, - "mxid" TEXT NOT NULL, - "displayname" TEXT, - "avatar_url" TEXT, power_level INTEGER NOT NULL DEFAULT 0, - PRIMARY KEY("room_id","mxid"), - FOREIGN KEY("room_id") REFERENCES "channel_room"("room_id") ON DELETE CASCADE -) WITHOUT ROWID; --- 5 -INSERT INTO new_member_cache (room_id, mxid, displayname, avatar_url) SELECT room_id, mxid, displayname, avatar_url FROM member_cache WHERE room_id IN (SELECT room_id FROM channel_room); --- 6 -DROP TABLE member_cache; --- 7 -ALTER TABLE new_member_cache RENAME TO member_cache; - -- *** reaction *** -- 4 @@ -142,15 +124,16 @@ ALTER TABLE new_webhook RENAME TO webhook; -- *** sim *** -- 4 --- while we're at it, rebuild this table to give it WITHOUT ROWID, remove UNIQUE, and drop the localpart column. no foreign keys needed +-- while we're at it, rebuild this table to give it WITHOUT ROWID, remove UNIQUE, and replace the localpart column with username. no foreign keys needed CREATE TABLE "new_sim" ( "user_id" TEXT NOT NULL, + "username" TEXT NOT NULL, "sim_name" TEXT NOT NULL, "mxid" TEXT NOT NULL, PRIMARY KEY("user_id") ) WITHOUT ROWID; -- 5 -INSERT INTO new_sim (user_id, sim_name, mxid) SELECT user_id, sim_name, mxid FROM sim; +INSERT INTO new_sim (user_id, username, sim_name, mxid) SELECT user_id, sim_name, sim_name, mxid FROM sim; -- 6 DROP TABLE sim; -- 7 diff --git a/src/m2d/converters/event-to-message.js b/src/m2d/converters/event-to-message.js index c498f1e..9a17817 100644 --- a/src/m2d/converters/event-to-message.js +++ b/src/m2d/converters/event-to-message.js @@ -258,13 +258,18 @@ async function getMemberFromCacheOrHomeserver(roomID, mxid, api) { const row = select("member_cache", ["displayname", "avatar_url"], {room_id: roomID, mxid}).get() if (row) return row return api.getStateEvent(roomID, "m.room.member", mxid).then(event => { - const displayname = event?.displayname || null - const avatar_url = event?.avatar_url || null - db.prepare("INSERT INTO member_cache (room_id, mxid, displayname, avatar_url) VALUES (?, ?, ?, ?) ON CONFLICT DO UPDATE SET displayname = ?, avatar_url = ?").run( - roomID, mxid, - displayname, avatar_url, - displayname, avatar_url - ) + const room = select("channel_room", "room_id", {room_id: roomID}).get() + if (room) { + // save the member to the cache so we don't have to check with the homeserver next time + // the cache will be kept in sync by the `m.room.member` event listener + const displayname = event?.displayname || null + const avatar_url = event?.avatar_url || null + db.prepare("INSERT INTO member_cache (room_id, mxid, displayname, avatar_url) VALUES (?, ?, ?, ?) ON CONFLICT DO UPDATE SET displayname = ?, avatar_url = ?").run( + roomID, mxid, + displayname, avatar_url, + displayname, avatar_url + ) + } return event }).catch(() => { return {displayname: null, avatar_url: null} diff --git a/src/m2d/converters/event-to-message.test.js b/src/m2d/converters/event-to-message.test.js index 0dc9110..cc3d19a 100644 --- a/src/m2d/converters/event-to-message.test.js +++ b/src/m2d/converters/event-to-message.test.js @@ -3535,8 +3535,8 @@ test("event2message: does not cache the member if the room is not known", async }, event_id: "$g07oYSZFWBkxohNEfywldwgcWj1hbhDzQ1sBAKvqOOU", origin_server_ts: 1688301929913, - room_id: "!should_be_newly_cached:cadence.moe", - sender: "@should_be_newly_cached:cadence.moe", + room_id: "!not_real:cadence.moe", + sender: "@should_not_be_cached:cadence.moe", type: "m.room.message", unsigned: { age: 405299 @@ -3545,9 +3545,9 @@ test("event2message: does not cache the member if the room is not known", async api: { getStateEvent: async (roomID, type, stateKey) => { called++ - t.equal(roomID, "!should_be_newly_cached:cadence.moe") + t.equal(roomID, "!not_real:cadence.moe") t.equal(type, "m.room.member") - t.equal(stateKey, "@should_be_newly_cached:cadence.moe") + t.equal(stateKey, "@should_not_be_cached:cadence.moe") return { avatar_url: "mxc://cadence.moe/this_is_the_avatar" } @@ -3559,9 +3559,9 @@ test("event2message: does not cache the member if the room is not known", async messagesToDelete: [], messagesToEdit: [], messagesToSend: [{ - username: "should_be_newly_cached", + username: "should_not_be_cached", content: "testing the member state cache", - avatar_url: undefined, + avatar_url: "https://bridge.example.org/download/matrix/cadence.moe/this_is_the_avatar", allowed_mentions: { parse: ["users", "roles"] } @@ -3569,7 +3569,7 @@ test("event2message: does not cache the member if the room is not known", async } ) - t.deepEqual(select("member_cache", ["avatar_url", "displayname", "mxid"], {room_id: "!should_be_newly_cached:cadence.moe"}).all(), []) + t.deepEqual(select("member_cache", ["avatar_url", "displayname", "mxid"], {room_id: "!not_real:cadence.moe"}).all(), []) t.equal(called, 1, "getStateEvent should be called once") }) diff --git a/src/m2d/event-dispatcher.js b/src/m2d/event-dispatcher.js index 6cbd6c6..fc2a558 100644 --- a/src/m2d/event-dispatcher.js +++ b/src/m2d/event-dispatcher.js @@ -205,8 +205,8 @@ async event => { return db.prepare("DELETE FROM member_cache WHERE room_id = ? and mxid = ?").run(event.room_id, event.state_key) } - const room = select("channel_room", "room_id", {room_id: event.room_id}) - if (!room) return // don't cache members in unbridged rooms + const exists = select("channel_room", "room_id", {room_id: event.room_id}) ?? select("guild_space", "space_id", {space_id: event.room_id}) + if (!exists) return // don't cache members in unbridged rooms // Member is here let powerLevel = 0 diff --git a/test/ooye-test-data.sql b/test/ooye-test-data.sql index 757ef9b..4a7d2f4 100644 --- a/test/ooye-test-data.sql +++ b/test/ooye-test-data.sql @@ -19,17 +19,17 @@ INSERT INTO channel_room (channel_id, room_id, name, nick, thread_parent, custom ('489237891895768942', '!tnedrGVYKFNUdnegvf:tchncs.de', 'ex-room-doesnt-exist-any-more', NULL, NULL, NULL), ('1160894080998461480', '!TqlyQmifxGUggEmdBN:cadence.moe', 'ooyexperiment', NULL, NULL, NULL); -INSERT INTO sim (user_id, sim_name, mxid) VALUES -('0', 'bot', '@_ooye_bot:cadence.moe'), -('820865262526005258', 'crunch_god', '@_ooye_crunch_god:cadence.moe'), -('771520384671416320', 'bojack_horseman', '@_ooye_bojack_horseman:cadence.moe'), -('112890272819507200', '.wing.', '@_ooye_.wing.:cadence.moe'), -('114147806469554185', 'extremity', '@_ooye_extremity:cadence.moe'), -('111604486476181504', 'kyuugryphon', '@_ooye_kyuugryphon:cadence.moe'), -('1109360903096369153', 'amanda', '@_ooye_amanda:cadence.moe'), -('43d378d5-1183-47dc-ab3c-d14e21c3fe58', '_pk_zoego', '@_ooye__pk_zoego:cadence.moe'), -('320067006521147393', 'papiophidian', '@_ooye_papiophidian:cadence.moe'), -('772659086046658620', 'cadence', '@_ooye_cadence:cadence.moe'); +INSERT INTO sim (user_id, username, sim_name, mxid) VALUES +('0', 'Matrix Bridge', 'bot', '@_ooye_bot:cadence.moe'), +('820865262526005258', 'Crunch God', 'crunch_god', '@_ooye_crunch_god:cadence.moe'), +('771520384671416320', 'Bojack Horseman', 'bojack_horseman', '@_ooye_bojack_horseman:cadence.moe'), +('112890272819507200', 'wing', '.wing.', '@_ooye_.wing.:cadence.moe'), +('114147806469554185', 'extremity', 'extremity', '@_ooye_extremity:cadence.moe'), +('111604486476181504', 'kyuugryphon', 'kyuugryphon', '@_ooye_kyuugryphon:cadence.moe'), +('1109360903096369153', 'Amanda', 'amanda', '@_ooye_amanda:cadence.moe'), +('43d378d5-1183-47dc-ab3c-d14e21c3fe58', '_pk_zoego', '_pk_zoego', '@_ooye__pk_zoego:cadence.moe'), +('320067006521147393', 'papiophidian', 'papiophidian', '@_ooye_papiophidian:cadence.moe'), +('772659086046658620', 'cadence.worm', 'cadence', '@_ooye_cadence:cadence.moe'); INSERT INTO sim_member (mxid, room_id, hashed_profile_content) VALUES ('@_ooye_bojack_horseman:cadence.moe', '!hYnGGlPHlbujVVfktC:cadence.moe', NULL), From eadefef6a357840c9cf44d30ca92e459f2c831b9 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Tue, 21 Jan 2025 15:08:12 +1300 Subject: [PATCH 085/228] Clean up member_cache when unbridging --- src/d2m/actions/create-room.js | 1 + 1 file changed, 1 insertion(+) diff --git a/src/d2m/actions/create-room.js b/src/d2m/actions/create-room.js index 64e2b68..e0d019f 100644 --- a/src/d2m/actions/create-room.js +++ b/src/d2m/actions/create-room.js @@ -438,6 +438,7 @@ async function unbridgeDeletedChannel(channel, guildID) { } // delete room from database + db.prepare("DELETE FROM member_cache WHERE room_id = ?").run(roomID) db.prepare("DELETE FROM channel_room WHERE room_id = ? AND channel_id = ?").run(roomID, channel.id) } From a579b509d31c2fce0d49d343e834e96a38e31043 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Tue, 28 Jan 2025 16:08:43 +1300 Subject: [PATCH 086/228] Catch PK API network errors --- src/d2m/actions/register-pk-user.js | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/d2m/actions/register-pk-user.js b/src/d2m/actions/register-pk-user.js index 7083006..ce1665c 100644 --- a/src/d2m/actions/register-pk-user.js +++ b/src/d2m/actions/register-pk-user.js @@ -146,15 +146,20 @@ async function fetchMessage(messageID) { // Their backend is weird. Sometimes it says "message not found" (code 20006) on the first try, so we make multiple attempts. let attempts = 0 do { - var res = await fetch(`https://api.pluralkit.me/v2/messages/${messageID}`) - if (res.ok) return res.json() + try { + var res = await fetch(`https://api.pluralkit.me/v2/messages/${messageID}`) + if (res.ok) return res.json() + var errorGetter = res.json + } catch (e) { + // Catch any network issues too. + errorGetter = e.toString + } // I think the backend needs some time to update. - await new Promise(resolve => setTimeout(resolve, 2000)) + await new Promise(resolve => setTimeout(resolve, 1500)) } while (++attempts < 3) - const errorMessage = await res.json() - throw new Error(`PK API returned an error after ${attempts} tries: ${JSON.stringify(errorMessage)}`) + throw new Error(`PK API returned an error after ${attempts} tries: ${JSON.stringify(await errorGetter())}`) } module.exports._memberToStateContent = memberToStateContent From 6fe8c60f116cfc3eb3b306d99fe0d0823e7b8951 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Thu, 30 Jan 2025 15:34:29 +1300 Subject: [PATCH 087/228] Add analyze of new data --- src/db/migrations/0017-analyze.sql | 225 +++++++++++++++++++++++++++++ 1 file changed, 225 insertions(+) create mode 100644 src/db/migrations/0017-analyze.sql diff --git a/src/db/migrations/0017-analyze.sql b/src/db/migrations/0017-analyze.sql new file mode 100644 index 0000000..802fca2 --- /dev/null +++ b/src/db/migrations/0017-analyze.sql @@ -0,0 +1,225 @@ +-- https://www.sqlite.org/lang_analyze.html + +BEGIN TRANSACTION; + +ANALYZE sqlite_schema; + +DELETE FROM "sqlite_stat1"; +INSERT INTO "sqlite_stat1" ("tbl","idx","stat") VALUES ('sim','sim','625 1'), + ('reaction','reaction','3242 1'), + ('channel_room','channel_room','389 1'), + ('channel_room','sqlite_autoindex_channel_room_1','389 1'), + ('media_proxy','media_proxy','5068 1'), + ('sim_proxy','sim_proxy','36 1'), + ('webhook','webhook','155 1'), + ('member_cache','member_cache','784 3 1'), + ('member_power','member_power','1 1 1'), + ('file','file','21862 1'), + ('message_channel','message_channel','366884 1'), + ('lottie','lottie','19 1'), + ('event_message','event_message','382920 1 1'), + ('migration',NULL,'1'), + ('sim_member','sim_member','2871 7 1'), + ('guild_space','guild_space','32 1'), + ('guild_active','guild_active','34 1'), + ('emoji','emoji','2563 1'), + ('auto_emoji','auto_emoji','3 1'); + +DELETE FROM "sqlite_stat4"; +INSERT INTO "sqlite_stat4" ("tbl","idx","neq","nlt","ndlt","sample") VALUES ('sim','sim','1','69','69',X'0231313137363631373038303932333039353039'), + ('sim','sim','1','139','139',X'0231313530383936363934333439373931323332'), + ('sim','sim','1','209','209',X'0231323231383737363334373737323139303732'), + ('sim','sim','1','279','279',X'0231333039313431353735353334313136383636'), + ('sim','sim','1','349','349',X'0231333935343433383235363034313635363434'), + ('sim','sim','1','419','419',X'0231353335363239373830383338353134373030'), + ('sim','sim','1','489','489',X'0231363930333339333730353930363636383034'), + ('sim','sim','1','559','559',X'0231383535353736303637393137323137383133'), + ('reaction','reaction','1','360','360',X'020699d5faceefb5fb4f'), + ('reaction','reaction','1','721','721',X'0206b61095e98b6b2fb1'), + ('reaction','reaction','1','1082','1082',X'0206d1dcb418603a5eaa'), + ('reaction','reaction','1','1443','1443',X'0206ef9fc42b9df746ad'), + ('reaction','reaction','1','1804','1804',X'02060f38c1f98f130605'), + ('reaction','reaction','1','2165','2165',X'02062b53df6dab7b1067'), + ('reaction','reaction','1','2526','2526',X'020645dd7e7f60c4aac7'), + ('reaction','reaction','1','2887','2887',X'0206658d2fe735805979'), + ('channel_room','channel_room','1','43','43',X'023331313434393131333330393139333231363330'), + ('channel_room','channel_room','1','87','87',X'023331313835343033343830303934303335393738'), + ('channel_room','channel_room','1','131','131',X'023331323139353036353836343139303638393839'), + ('channel_room','channel_room','1','175','175',X'023331323336353538333034323331303334393630'), + ('channel_room','channel_room','1','219','219',X'023331323933373932323135333930323234343235'), + ('channel_room','channel_room','1','263','263',X'023331333333323139363936393333323038303937'), + ('channel_room','channel_room','1','307','307',X'0231343835363635393733363433333738363938'), + ('channel_room','channel_room','1','351','351',X'0231373039303432313039353632323234363731'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','6 6','6 6',X'034b3321416a6c4c49464e6248646474424a6d4d73503a636164656e63652e6d6f6531313531333434383735363139343833373233'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','34 34','34 34',X'034b3321474b4a63424a6b527a47634e4855686c50613a636164656e63652e6d6f6531303237393433323532323237323630343637'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','43 43','43 43',X'034b3121484b50534d62736d694673506d6268414f513a636164656e63652e6d6f65313931343837343839393433343034353434'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','58 58','58 58',X'034b33214a4479425a685545706874784f6e6f6569513a636164656e63652e6d6f6531323937323836373434353633313236333532'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','87 87','87 87',X'034b33214e544d724e686e715271695755654d494d523a636164656e63652e6d6f6531323235323434353738393939373031353536'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','108 108','108 108',X'034b332151444e44796656674e7657565345656876713a636164656e63652e6d6f6531313432333134303935353535363435343830'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','131 131','131 131',X'034b3121544171536b575752654b43506f584c6a75483a636164656e63652e6d6f65383737303730363531343733363631393532'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','175 175','175 175',X'034b3321594249486864714e697255585941587845563a636164656e63652e6d6f6531323335303831373939353936373639333730'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','177 177','177 177',X'034b3321594b46454e79716667696951686956496b533a636164656e63652e6d6f6531323934363237303431343530333933373034'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','186 186','186 186',X'034b3321596f54644f55766a53765349767266716c653a636164656e63652e6d6f6531323734313936373733383435333430323933'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','202 202','202 202',X'034b3121625877616673695372655647676470535a463a636164656e63652e6d6f65373339303137363739373936343336393932'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','208 208','208 208',X'034b3321634a4b6843764943795377717a47634551423a636164656e63652e6d6f6531323732363632303331323238373331343834'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','219 219','219 219',X'034b3121656455786a56647a6755765844554951434b3a636164656e63652e6d6f65343937313631333530393334353630373738'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','242 242','242 242',X'034b31216a4d746e6e6f51414e4278466a486458494d3a636164656e63652e6d6f65373634353135323932303539323731313939'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','263 263','263 263',X'034b31216c7a776870666a5a6e59797468656a7453483a636164656e63652e6d6f65383838343831373132383438343030343534'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','264 264','264 264',X'034b33216d454c5846716a426958726d7558796943723a636164656e63652e6d6f6531313936393134373631303430393234373432'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','268 268','268 268',X'034b33216d557765577571546761574a767769576a653a636164656e63652e6d6f6531323936373131393236333032333830303834'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','291 291','291 291',X'034b3321704761494e45534643587a634e42497a724e3a636164656e63652e6d6f6531303237343531333333333533313532353232'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','306 306','306 306',X'034b3321717646656248564f4b6876454e54494563763a636164656e63652e6d6f6531323737373238383139323232303230313436'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','307 307','307 307',X'034b332171767370666d716f476449634a66794c506c3a636164656e63652e6d6f6531323936393138333638393539343633343735'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','351 351','351 351',X'034b3321774e7a7741724a47796f4c5168426f544e4b3a636164656e63652e6d6f6531303238303436373930333435333739383930'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','368 368','368 368',X'034b3321794e6d504c7765654a69756570725a677a733a636164656e63652e6d6f6531323531393631373233373731313632363234'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','376 376','376 376',X'034b3121796a4879795772466f704c66646878564e423a636164656e63652e6d6f65333336313537353037303734353233313336'), + ('channel_room','sqlite_autoindex_channel_room_1','1 1','379 379','379 379',X'034b31217a4c4f6b62766b44587551465948594555673a636164656e63652e6d6f65393933383838313433373030393330363331'), + ('media_proxy','media_proxy','1','563','563',X'02069e6054680b610946'), + ('media_proxy','media_proxy','1','1127','1127',X'0206bb489b717c9320e4'), + ('media_proxy','media_proxy','1','1691','1691',X'0206d75f602775b7a27c'), + ('media_proxy','media_proxy','1','2255','2255',X'0206f2c705ddca4e2b14'), + ('media_proxy','media_proxy','1','2819','2819',X'02061060db7a5151967b'), + ('media_proxy','media_proxy','1','3383','3383',X'02062cc47366f7550d22'), + ('media_proxy','media_proxy','1','3947','3947',X'020647d275ec0d781fc7'), + ('media_proxy','media_proxy','1','4511','4511',X'02066402024a7ea38249'), + ('sim_proxy','sim_proxy','1','4','4',X'025531316564343731342d636635652d346333372d393331382d376136353266383732636634'), + ('sim_proxy','sim_proxy','1','9','9',X'025533346636333932642d323263372d346337382d393063372d326536323734313535613266'), + ('sim_proxy','sim_proxy','1','14','14',X'025535396662363131392d626133392d346565382d393738612d386432376366303631393633'), + ('sim_proxy','sim_proxy','1','19','19',X'025539373066366536332d646234632d346531342d383063362d336639343938643961363665'), + ('sim_proxy','sim_proxy','1','24','24',X'025561636231613335642d313336662d343362332d626365622d326566646634616265306436'), + ('sim_proxy','sim_proxy','1','29','29',X'025563316635623735392d336136342d343633342d623634632d643461656436316539656632'), + ('sim_proxy','sim_proxy','1','34','34',X'025566323230373135632d633436332d343532622d626233612d373662646662306365353537'), + ('webhook','webhook','1','17','17',X'023331313532383834313435343038373230393936'), + ('webhook','webhook','1','35','35',X'023331313939303936333434333830343631313138'), + ('webhook','webhook','1','53','53',X'023331323331383036353337373032353736313938'), + ('webhook','webhook','1','71','71',X'023331323933373836383939343238383036363536'), + ('webhook','webhook','1','89','89',X'023331333132363031353130363535353537373132'), + ('webhook','webhook','1','107','107',X'0231323937323734313733303636333133373339'), + ('webhook','webhook','1','125','125',X'0231353239313736313536333938363832313137'), + ('webhook','webhook','1','143','143',X'0231363837303238373334333232313437333434'), + ('member_cache','member_cache','4 1','73 74','48 74',X'034b3921496f4866536e67625a6762747061747a494e3a636164656e63652e6d6f65406875636b6c65746f6e3a636164656e63652e6d6f65'), + ('member_cache','member_cache','2 1','86 87','57 87',X'034b2d214b5169714663546e764f6f4f424475746a7a3a636164656e63652e6d6f6540726e6c3a636164656e63652e6d6f65'), + ('member_cache','member_cache','4 1','101 104','68 104',X'034b43214e446249714e704a795076664b526e4e63723a636164656e63652e6d6f6540776f756e6465645f77617272696f723a6d61747269782e6f7267'), + ('member_cache','member_cache','4 1','110 113','73 113',X'034b3b214f485844457370624d485348716c4445614f3a636164656e63652e6d6f6540717561647261646963616c3a6d61747269782e6f7267'), + ('member_cache','member_cache','5 1','171 175','111 175',X'034b3b215450616f6a5454444446444847776c7276743a636164656e63652e6d6f6540766962656973766572796f3a6d61747269782e6f7267'), + ('member_cache','member_cache','39 1','180 208','116 208',X'034b4d2154716c79516d69667847556767456d64424e3a636164656e63652e6d6f6540726f626c6b796f6772653a6372616674696e67636f6d72616465732e6e6574'), + ('member_cache','member_cache','4 1','231 231','126 231',X'034b3b2156624f77675559777146614e4c5345644e413a636164656e63652e6d6f654061666c6f7765723a73796e646963617465642e676179'), + ('member_cache','member_cache','9 1','262 263','141 263',X'034b3b21594b46454e79716667696951686956496b533a636164656e63652e6d6f654062656e6d61633a636861742e62656e6d61632e78797a'), + ('member_cache','member_cache','3 1','283 283','149 283',X'034b35215a615a4d78456f52724d6d4e49554d79446c3a636164656e63652e6d6f6540636164656e63653a636164656e63652e6d6f65'), + ('member_cache','member_cache','88 1','307 351','166 351',X'034b3b2163427874565278446c5a765356684a58564b3a636164656e63652e6d6f65406a61736b617274683a736c656570696e672e746f776e'), + ('member_cache','member_cache','11 1','408 415','177 415',X'034b5121654856655270706e6c6f57587177704a6e553a636164656e63652e6d6f65406a61636b736f6e6368656e3636363a6a61636b736f6e6368656e3636362e636f6d'), + ('member_cache','member_cache','7 1','423 424','181 424',X'034b4b2165724f7079584e465a486a48724568784e583a636164656e63652e6d6f6540616d796973636f6f6c7a3a6d61747269782e6174697573616d792e636f6d'), + ('member_cache','member_cache','96 1','436 439','187 439',X'034b4b21676865544b5a7451666c444e7070684c49673a636164656e63652e6d6f6540616c65783a73706163652e67616d65727374617665726e2e6f6e6c696e65'), + ('member_cache','member_cache','96 1','436 527','187 527',X'034b3121676865544b5a7451666c444e7070684c49673a636164656e63652e6d6f654078796c6f626f6c3a616d6265722e74656c'), + ('member_cache','member_cache','10 1','546 555','197 555',X'0351312169537958674e7851634575586f587073536e3a707573737468656361742e6f726740797562697175653a6e6f70652e63686174'), + ('member_cache','member_cache','13 1','594 601','224 601',X'034b2b216c7570486a715444537a774f744d59476d493a636164656e63652e6d6f6540656c6c69753a68617368692e7265'), + ('member_cache','member_cache','2 1','614 615','229 615',X'034b2f216d584978494644676c4861734e53427371773a636164656e63652e6d6f654077696e673a666561746865722e6f6e6c'), + ('member_cache','member_cache','4 1','616 619','230 619',X'034b2f216d616767455367755a427147425a74536e723a636164656e63652e6d6f654077696e673a666561746865722e6f6e6c'), + ('member_cache','member_cache','4 1','659 660','259 660',X'034b332172454f73706e5971644f414c4149466e69563a636164656e63652e6d6f6540656c797369613a636164656e63652e6d6f65'), + ('member_cache','member_cache','4 1','699 701','284 701',X'034b3521766e717a56767678534a586c5a504f5276533a636164656e63652e6d6f6540636164656e63653a636164656e63652e6d6f65'), + ('member_cache','member_cache','1 1','703 703','285 703',X'034b3521767165714c474851616842464a56566779483a636164656e63652e6d6f654063696465723a6361746769726c2e636c6f7564'), + ('member_cache','member_cache','4 1','705 705','287 705',X'034b35217750454472596b77497a6f744e66706e57503a636164656e63652e6d6f6540636164656e63653a636164656e63652e6d6f65'), + ('member_cache','member_cache','35 1','709 709','288 709',X'034b2d2177574f667376757356486f4e4e567242585a3a636164656e63652e6d6f654061613a6361747669626572732e6d65'), + ('member_cache','member_cache','14 1','747 749','291 749',X'034b3721776c534544496a44676c486d42474b7254703a636164656e63652e6d6f654062616461746e616d65733a62616461742e646576'), + ('member_power','member_power','1 1','0 0','0 0',X'03350f40636164656e63653a636164656e63652e6d6f652a'), + ('file','file','1','2429','2429',X'03815f68747470733a2f2f63646e2e646973636f72646170702e636f6d2f6174746163686d656e74732f313039393033313838373530303033343038382f313333313336303134333238333036303833372f50584c5f32303235303132315f3230323934323137372e6a7067'), + ('file','file','1','4859','4859',X'03817568747470733a2f2f63646e2e646973636f72646170702e636f6d2f6174746163686d656e74732f313134353832313533383832323637323436362f313330323232393131303834373936373331352f53637265656e73686f745f32303234313130325f3034313332365f5265646469742e6a7067'), + ('file','file','1','7289','7289',X'03815968747470733a2f2f63646e2e646973636f72646170702e636f6d2f6174746163686d656e74732f313231393439383932363436363636323433302f313239373634363930353038353636313234362f494d475f32303234313032305f3135323230302e6a7067'), + ('file','file','1','9719','9719',X'03814168747470733a2f2f63646e2e646973636f72646170702e636f6d2f6174746163686d656e74732f3135393136353731343139343735393638302f313236383537333933363531343337313635392f494d475f353433362e6a7067'), + ('file','file','1','12149','12149',X'03813b68747470733a2f2f63646e2e646973636f72646170702e636f6d2f6174746163686d656e74732f3236363736373539303634313233383032372f313237323430333931313939383730313630392f696d6167652e706e67'), + ('file','file','1','14579','14579',X'03816b68747470733a2f2f63646e2e646973636f72646170702e636f6d2f6174746163686d656e74732f3539383730363933323736303434343936392f313237373532343532343330383632373437372f45585445524e414c5f454449545f323032345f4d5f64726166745f322e646f6378'), + ('file','file','1','17009','17009',X'03815768747470733a2f2f63646e2e646973636f72646170702e636f6d2f6174746163686d656e74732f3635353231363137333639363238363734362f313333333630333132383634313036303938342f323032352d30312d32375f31372e30312e31352e706e67'), + ('file','file','1','19439','19439',X'027f68747470733a2f2f63646e2e646973636f72646170702e636f6d2f656d6f6a69732f313230323936303730343936313931323836322e706e67'), + ('message_channel','message_channel','1','40764','40764',X'023331313630333434353733303030383232383735'), + ('message_channel','message_channel','1','81529','81529',X'023331313830323437393130343238393837343333'), + ('message_channel','message_channel','1','122294','122294',X'023331313938303533383732383337363131363230'), + ('message_channel','message_channel','1','163059','163059',X'023331323237373739373330333839303738303537'), + ('message_channel','message_channel','1','203824','203824',X'023331323437303438333039303031313538373137'), + ('message_channel','message_channel','1','244589','244589',X'023331323635363939353734333034303830303034'), + ('message_channel','message_channel','1','285354','285354',X'023331323835343637363238323434313732383234'), + ('message_channel','message_channel','1','326119','326119',X'023331333038373932333935313031333736353732'), + ('lottie','lottie','1','2','2',X'0231373439303534363630373639323138363331'), + ('lottie','lottie','1','5','5',X'0231373534313037353339323030363731373635'), + ('lottie','lottie','1','8','8',X'0231373936313430363338303933343433303932'), + ('lottie','lottie','1','11','11',X'0231373936313431373032363935343835353030'), + ('lottie','lottie','1','14','14',X'0231383136303837373932323931323832393434'), + ('lottie','lottie','1','17','17',X'0231383233393736313032393736323930383636'), + ('event_message','event_message','11 1','14788 14796','14356 14796',X'03336531313532303033373639343137303839303434246d44714a474b3530424a715170394273684e534d64365f3768494354776e70362d793130786d6669766563'), + ('event_message','event_message','11 1','33806 33815','32914 33815',X'033365313135373630333638373035373836363736322459526f7139484b376e55677a397668796f6e3053424a49497978497a5750734e4f6e39756f765644664d45'), + ('event_message','event_message','1 1','42546 42546','41335 42546',X'03336531313630363236383737353835363938393237245033436e4f6d6a35462d6939454e4e79586b70796f5679306b74324a654464764276326e746d33566a4355'), + ('event_message','event_message','2 1','85093 85093','81999 85093',X'0333653131383039393939363531323930343831303424496748666562784533746e623047412d534f7176594a354e4e55385735706c68523159676854636a554734'), + ('event_message','event_message','11 1','116157 116165','111525 116165',X'03336531313933363837333730363137333237363536245a32305734766c737079566e387a6e2d526a6f64694a51745f5a7851644f5f33744e415169453755356477'), + ('event_message','event_message','1 1','127640 127640','122328 127640',X'0333653132303132353637313733373633303332323624702d626f415672476a4b45327a7158664f3738387a5a597a376a42624648717431334d386464705467476f'), + ('event_message','event_message','16 1','140270 140281','134379 140281',X'03336531323039333735363534373138343830343235246c374a4f7543526b7756306d627a69356e5843496b4538416a6951374f67473455456c2d7053445a516649'), + ('event_message','event_message','11 1','162065 162071','154933 162071',X'0333653132323434383135393033313937373537373424674c77513179796e4b6d5859496b5a597a4a55627a66557a55552d714c4b5f524f454e4250325f6e44766b'), + ('event_message','event_message','1 1','170187 170187','162530 170187',X'0333653132323937373533363839343532373038333424656c6c76416a544a5847627936767249767470677a555572787231716f5a75536e50525f474b4e35455945'), + ('event_message','event_message','11 1','178736 178736','170762 178736',X'03336531323333353238303533323338333337353537242d39304668552d36455373594b6435484d7237666d6a414a5f6a576149616e356c4776384e655436564959'), + ('event_message','event_message','10 1','180317 180325','172228 180325',X'03336531323334363237303030393333383130323637246a4679416449665a4f54432d2d735971715472473735374c7a50504f34386439657963485477686d797751'), + ('event_message','event_message','1 1','212734 212734','203278 212734',X'03336531323438303131373930303633373637363734246557493950456f4d576b614b4d33416a7030782d6d455f6c4b4a6c495f6d6d44686f6379464b5170534f59'), + ('event_message','event_message','11 1','228100 228103','217856 228103',X'033365313235333734353736363733373132313336322447326a7a746e5977716a3676304a7a4168576e30725950596470667a5f496f76426771574a4876434c516b'), + ('event_message','event_message','11 1','240172 240181','229123 240181',X'033365313235393239383538323233303630313735382472635679454c5a76647453547a37366f3669434a4f614a316a756f683835535778494d546c5072517a676f'), + ('event_message','event_message','10 1','240259 240264','229132 240264',X'0333653132353933303030343035333535373235323024535849376a465f696e71424d714c4f564b347659746852644b31724747502d435a5f355a354f6b774e3751'), + ('event_message','event_message','2 1','255280 255281','243230 255281',X'03336531323636373837343338353137343234313738246e6e4e576f526a54495757723441463770625454746b7a73784c4d336b312d6d6645665031496b43586e59'), + ('event_message','event_message','1 1','297828 297828','283436 297828',X'0333653132383637303937353334363834323032313024544342465970356f39767a2d4f6b2d33654f4e433772426d354966615934476b48536e58445257474f4767'), + ('event_message','event_message','1 1','340375 340375','323489 340375',X'033365313330393336363936343530353934303030392431664536386d2d50546e786d5474345458584c35754847594139353779396c76582d50797150496d395f30'), + ('event_message','event_message','11 1','343791 343799','326730 343799',X'03336531333131353731333337393331363537323737246731767241315269725951592d3933304f6973587142372d6961686e34684e492d6462374952714176616b'), + ('event_message','event_message','10 1','363207 363216','344868 363216',X'0333653133323434393732323633393438393834393524784f78636e4749364269545941734d7a4f7557316f526e68356b675378544e30466442386a3037695f4f67'), + ('event_message','event_message','10 1','363219 363219','344871 363219',X'033365313332343439373532363733323039393732352432586f7938567937643843375a47767472657966326b4c4f4159397546386b4755364c3642435f446b6d77'), + ('event_message','event_message','10 1','363340 363343','344918 363343',X'03336531333234353037313732333634373530393830244f46645731396649534176706d34646c36367a2d5543337236432d436354506e34752d63444f7036733345'), + ('event_message','event_message','11 1','369452 369456','350712 369456',X'0333653133323736353831313733343439323336383024574d774330644574417277375f4562554a534465546532577174506d3747584347774570646c4f79326d30'), + ('event_message','event_message','10 1','372353 372356','353425 372356',X'0333653133323933313737353039313234353035373224366259364d313472667163486d5854476349716d4a4366467471796839794472375a6a487463715a6d4f34'), + ('sim_member','sim_member','225 1','0 12','0 12',X'034b4721414956694e775a64636b4652764c4f4567433a636164656e63652e6d6f65405f6f6f79655f616b6972615f6e6965723a636164656e63652e6d6f65'), + ('sim_member','sim_member','2 1','319 319','14 319',X'034b43214456706f6e54524d56456570486378744c423a636164656e63652e6d6f65405f6f6f79655f656e746f6c6f6d613a636164656e63652e6d6f65'), + ('sim_member','sim_member','68 1','391 440','26 440',X'034b4921457a54624a496c496d45534f746b4e644e4a3a636164656e63652e6d6f65405f6f6f79655f73617475726461797465643a636164656e63652e6d6f65'), + ('sim_member','sim_member','8 1','638 639','59 639',X'034b3f21497a4f675169446e757346516977796d614c3a636164656e63652e6d6f65405f6f6f79655f636f6f6b69653a636164656e63652e6d6f65'), + ('sim_member','sim_member','31 1','743 771','86 771',X'034b49214d5071594e414a62576b72474f544a7461703a636164656e63652e6d6f65405f6f6f79655f746865666f6f6c323239343a636164656e63652e6d6f65'), + ('sim_member','sim_member','26 1','774 787','87 787',X'034b49214d687950614b4250506f496c7365794d6d743a636164656e63652e6d6f65405f6f6f79655f6b79757567727970686f6e3a636164656e63652e6d6f65'), + ('sim_member','sim_member','27 1','877 881','104 881',X'034b45215063734371724f466a48476f41424270414c3a636164656e63652e6d6f65405f6f6f79655f62696c6c795f626f623a636164656e63652e6d6f65'), + ('sim_member','sim_member','16 1','956 959','117 959',X'034b43215158526f4a777a63506d5047546d454b454d3a636164656e63652e6d6f65405f6f6f79655f626f7472616334723a636164656e63652e6d6f65'), + ('sim_member','sim_member','32 1','997 1012','121 1012',X'034b3f215170676c734e587a4c7751594d4c6c734f503a636164656e63652e6d6f65405f6f6f79655f6a75746f6d693a636164656e63652e6d6f65'), + ('sim_member','sim_member','7 1','1274 1279','157 1279',X'034b4121554d6f6e68556765644d47585a78466658753a636164656e63652e6d6f65405f6f6f79655f6d696e696d75733a636164656e63652e6d6f65'), + ('sim_member','sim_member','27 1','1415 1439','188 1439',X'034b3d21595868717249786d586e47736961796a59783a636164656e63652e6d6f65405f6f6f79655f73746161663a636164656e63652e6d6f65'), + ('sim_member','sim_member','16 1','1597 1599','217 1599',X'034b512163466a4479477274466d48796d794c6652453a636164656e63652e6d6f65405f6f6f79655f626f6a61636b5f686f7273656d616e3a636164656e63652e6d6f65'), + ('sim_member','sim_member','27 1','1758 1761','248 1761',X'034b3d2168665a74624d656f5355564e424850736a743a636164656e63652e6d6f65405f6f6f79655f617a7572653a636164656e63652e6d6f65'), + ('sim_member','sim_member','25 1','1865 1886','270 1886',X'034b3f216b4c52714b4b555158636962494d744f706c3a636164656e63652e6d6f65405f6f6f79655f7361796f72693a636164656e63652e6d6f65'), + ('sim_member','sim_member','19 1','1918 1919','276 1919',X'034b3d216b68497350756c465369736d43646c596e493a636164656e63652e6d6f65405f6f6f79655f617a7572653a636164656e63652e6d6f65'), + ('sim_member','sim_member','33 1','1986 2015','286 2015',X'034b3d216d5451744d736a534c4f646c576f7265594d3a636164656e63652e6d6f65405f6f6f79655f73746161663a636164656e63652e6d6f65'), + ('sim_member','sim_member','37 1','2027 2028','289 2028',X'034b4d216d616767455367755a427147425a74536e723a636164656e63652e6d6f65405f6f6f79655f2e7265616c2e706572736f6e2e3a636164656e63652e6d6f65'), + ('sim_member','sim_member','28 1','2117 2130','297 2130',X'034b3f216e4e595a794b6f4e70797859417a50466f733a636164656e63652e6d6f65405f6f6f79655f6a75746f6d693a636164656e63652e6d6f65'), + ('sim_member','sim_member','20 1','2230 2239','310 2239',X'034b41217046504c7270594879487a784e4c69594b413a636164656e63652e6d6f65405f6f6f79655f686578676f61743a636164656e63652e6d6f65'), + ('sim_member','sim_member','30 1','2381 2398','332 2398',X'034b3b21717a44626c4b6c69444c577a52524f6e465a3a636164656e63652e6d6f65405f6f6f79655f6d6e696b3a636164656e63652e6d6f65'), + ('sim_member','sim_member','38 1','2490 2518','344 2518',X'034b3d2173445250714549546e4f4e57474176496b423a636164656e63652e6d6f65405f6f6f79655f727974686d3a636164656e63652e6d6f65'), + ('sim_member','sim_member','11 1','2555 2559','358 2559',X'034b4321746751436d526b426e6474516362687150583a636164656e63652e6d6f65405f6f6f79655f6a6f7365707065793a636164656e63652e6d6f65'), + ('sim_member','sim_member','47 1','2633 2666','377 2666',X'034b4b217750454472596b77497a6f744e66706e57503a636164656e63652e6d6f65405f6f6f79655f6e61706f6c656f6e333038393a636164656e63652e6d6f65'), + ('sim_member','sim_member','52 1','2817 2837','414 2837',X'034b43217a66654e574d744b4f764f48766f727979563a636164656e63652e6d6f65405f6f6f79655f696e736f676e69613a636164656e63652e6d6f65'), + ('guild_space','guild_space','1','3','3',X'0231313132373630363639313738323431303234'), + ('guild_space','guild_space','1','7','7',X'023331313534383638343234373234343633363837'), + ('guild_space','guild_space','1','11','11',X'023331323139303338323637383430393235383138'), + ('guild_space','guild_space','1','15','15',X'023331323839353939363232353930383930313335'), + ('guild_space','guild_space','1','19','19',X'0231323733383737363437323234393935383431'), + ('guild_space','guild_space','1','23','23',X'0231353239313736313536333938363832313135'), + ('guild_space','guild_space','1','27','27',X'0231373535303134333534373334313533383138'), + ('guild_space','guild_space','1','31','31',X'0231393933383838313432343535323130303834'), + ('guild_active','guild_active','1','3','3',X'0231313132373630363639313738323431303234'), + ('guild_active','guild_active','1','7','7',X'023331313534383638343234373234343633363837'), + ('guild_active','guild_active','1','11','11',X'023331323139303338323637383430393235383138'), + ('guild_active','guild_active','1','15','15',X'023331323839353939363232353930383930313335'), + ('guild_active','guild_active','1','19','19',X'023331333333323139363936393333323038303934'), + ('guild_active','guild_active','1','23','23',X'0231343735353939303338353336373434393630'), + ('guild_active','guild_active','1','27','27',X'022f3636313932393535373737343836383438'), + ('guild_active','guild_active','1','31','31',X'0231383737303635303431393930353136373637'), + ('emoji','emoji','1','284','284',X'023331313132323031303430303637303339333332'), + ('emoji','emoji','1','569','569',X'023331323334393032303131393436383630363638'), + ('emoji','emoji','1','854','854',X'0231323735313734373438353034313935303732'), + ('emoji','emoji','1','1139','1139',X'0231333837343730383630303134393737303235'), + ('emoji','emoji','1','1424','1424',X'0231353435363639393734303130383838313932'), + ('emoji','emoji','1','1709','1709',X'0231363339313034333030393139393437323634'), + ('emoji','emoji','1','1994','1994',X'0231373532363932363230303638373832313231'), + ('emoji','emoji','1','2279','2279',X'0231383935343737353331303434363138323430'), + ('auto_emoji','auto_emoji','1','0','0',X'02114c31'), + ('auto_emoji','auto_emoji','1','1','1',X'02114c32'), + ('auto_emoji','auto_emoji','1','2','2',X'020f5f'); + +ANALYZE sqlite_schema; + +COMMIT; From d4a50cb8aaf6637bbdab6db676fd54cf32d10fba Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Thu, 30 Jan 2025 22:25:25 +1300 Subject: [PATCH 088/228] Do not run as root --- readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 6f2f477..1f01d01 100644 --- a/readme.md +++ b/readme.md @@ -62,7 +62,7 @@ Only necessary data and columns are queried from the database. We only contact t File uploads (like avatars from bridged members) are checked locally and deduplicated. Only brand new files are uploaded to the homeserver. This saves loads of space in the homeserver's media repo, especially for Synapse. -Switching to [WAL mode](https://www.sqlite.org/wal.html) could improve your database access speed even more. Run `node scripts/wal.js` if you want to switch to WAL mode. This will also enable `synchronous = NORMAL`. +Switching to [WAL mode](https://www.sqlite.org/wal.html) could improve your database access speed even more. Run `node scripts/wal.js` if you want to switch to WAL mode. (This will also enable `synchronous = NORMAL`.) # Setup @@ -78,6 +78,8 @@ Follow these steps: 1. [Get Node.js version 20 or later](https://nodejs.org/en/download/prebuilt-installer) +1. Switch to a normal user account. (i.e. do not run any of the following commands as root or sudo.) + 1. Clone this repo and checkout a specific tag. (Development happens on main. Stable versions are tagged.) * The latest release tag is ![](https://img.shields.io/gitea/v/release/cadence/out-of-your-element?gitea_url=https%3A%2F%2Fgitdab.com&style=flat-square&label=%20&color=black). From 5c0e83065809c1828c0aec8a22ff0dbe51381492 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Fri, 31 Jan 2025 15:07:48 +1300 Subject: [PATCH 089/228] Display XHR errors --- src/web/pug/includes/template.pug | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/web/pug/includes/template.pug b/src/web/pug/includes/template.pug index 6a0fb76..17b7847 100644 --- a/src/web/pug/includes/template.pug +++ b/src/web/pug/includes/template.pug @@ -57,8 +57,10 @@ html(lang="en") li(role="menuitem") a.s-topbar--item.s-user-card.d-flex.p4(href=rel(`/guild?guild_id=${guild.id}`)) +guild(guild) + //- Body .mx-auto.w100.wmx9.py24.px8.fs-body1#content block body + //- Guild list popover script. document.querySelectorAll("[popovertarget]").forEach(e => { e.addEventListener("click", () => { @@ -69,3 +71,19 @@ html(lang="en") }) }) script(src=rel("/static/htmx.min.js")) + //- Error dialog + aside.s-modal#server-error(aria-hidden="true") + .s-modal--dialog + h1.s-modal--header Server error + pre.overflow-auto#server-error-content + button.s-modal--close.s-btn.s-btn__muted(aria-label="Close" type="button" onclick="hideError()")!= icons.Icons.IconClearSm + .s-modal--footer + button.s-btn.s-btn__outlined.s-btn__muted(type="button" onclick="hideError()") OK + script. + function hideError() { + document.getElementById("server-error").setAttribute("aria-hidden", "true") + } + document.body.addEventListener("htmx:responseError", event => { + document.getElementById("server-error").setAttribute("aria-hidden", "false") + document.getElementById("server-error-content").textContent = event.detail.xhr.responseText + }) From b1b9124052d7ef8ba6563cd8aa4f29226fe9ad4a Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Fri, 31 Jan 2025 15:09:01 +1300 Subject: [PATCH 090/228] Fully support unlinking channels --- docs/foreign-keys.md | 2 +- src/d2m/actions/create-room.js | 74 ++++++++++++++++++++++++---------- src/web/pug/guild.pug | 5 ++- src/web/routes/link.js | 29 ++++++++++++- 4 files changed, 84 insertions(+), 26 deletions(-) diff --git a/docs/foreign-keys.md b/docs/foreign-keys.md index 9940ed0..1e5e21c 100644 --- a/docs/foreign-keys.md +++ b/docs/foreign-keys.md @@ -45,7 +45,7 @@ Here are some tables that could potentially have foreign keys added between them * The storage cost of the additional index on `sim` would not be worth the benefits. * `channel_room` <--(**C** room_id PK)-- `sim_member` * If a room is being permanently unlinked, it may be useful to see a populated member list. If it's about to be relinked to another channel, we want to keep the sims in the room for more speed and to avoid spamming state events into the timeline. - * Either way, the sims should remain in the room even after it's been unlinked. So no referential integrity is desirable here. + * Either way, the sims could remain in the room even after it's been unlinked. So no referential integrity is desirable here. * `sim` <--(PK user_id PK)-- `sim_proxy` * OOYE left joins on this. In normal operation, this relationship might not exist. * `channel_room` <--(PK channel_id PK)-- `webhook` ✅ diff --git a/src/d2m/actions/create-room.js b/src/d2m/actions/create-room.js index e0d019f..690ca2a 100644 --- a/src/d2m/actions/create-room.js +++ b/src/d2m/actions/create-room.js @@ -6,7 +6,7 @@ const Ty = require("../../types") const {reg} = require("../../matrix/read-registration") const passthrough = require("../../passthrough") -const {discord, sync, db, select} = passthrough +const {discord, sync, db, select, from} = passthrough /** @type {import("../../matrix/file")} */ const file = sync.require("../../matrix/file") /** @type {import("../../matrix/api")} */ @@ -14,7 +14,9 @@ const api = sync.require("../../matrix/api") /** @type {import("../../matrix/kstate")} */ const ks = sync.require("../../matrix/kstate") /** @type {import("../../discord/utils")} */ -const utils = sync.require("../../discord/utils") +const dUtils = sync.require("../../discord/utils") +/** @type {import("../../m2d/converters/utils")} */ +const mUtils = sync.require("../../m2d/converters/utils") /** @type {import("./create-space")} */ const createSpace = sync.require("./create-space") @@ -114,8 +116,8 @@ async function channelToKState(channel, guild, di) { join_rules = {join_rule: PRIVACY_ENUMS.ROOM_JOIN_RULES[privacyLevel]} } - const everyonePermissions = utils.getPermissions([], guild.roles, undefined, channel.permission_overwrites) - const everyoneCanMentionEveryone = utils.hasAllPermissions(everyonePermissions, ["MentionEveryone"]) + const everyonePermissions = dUtils.getPermissions([], guild.roles, undefined, channel.permission_overwrites) + const everyoneCanMentionEveryone = dUtils.hasAllPermissions(everyonePermissions, ["MentionEveryone"]) const globalAdmins = select("member_power", ["mxid", "power_level"], {room_id: "*"}).all() const globalAdminPower = globalAdmins.reduce((a, c) => (a[c.mxid] = c.power_level, a), {}) @@ -392,7 +394,7 @@ function syncRoom(channelID) { return _syncRoom(channelID, true) } -async function _unbridgeRoom(channelID) { +async function unbridgeChannel(channelID) { /** @ts-ignore @type {DiscordTypes.APIGuildChannel} */ const channel = discord.channels.get(channelID) assert.ok(channel) @@ -407,12 +409,8 @@ async function _unbridgeRoom(channelID) { async function unbridgeDeletedChannel(channel, guildID) { const roomID = select("channel_room", "room_id", {channel_id: channel.id}).pluck().get() assert.ok(roomID) - const spaceID = select("guild_space", "space_id", {guild_id: guildID}).pluck().get() - assert.ok(spaceID) - - // remove room from being a space member - await api.sendState(roomID, "m.space.parent", spaceID, {}) - await api.sendState(spaceID, "m.space.child", roomID, {}) + const row = from("guild_space").join("guild_active", "guild_id").select("space_id", "autocreate").get() + assert.ok(row) // remove declaration that the room is bridged await api.sendState(roomID, "uk.half-shot.bridge", `moe.cadence.ooye://discord/${guildID}/${channel.id}`, {}) @@ -421,15 +419,6 @@ async function unbridgeDeletedChannel(channel, guildID) { await api.sendState(roomID, "m.room.topic", "", {topic: channel.topic || ""}) } - // send a notification in the room - await api.sendEvent(roomID, "m.room.message", { - msgtype: "m.notice", - body: "⚠️ This room was removed from the bridge." - }) - - // leave room - await api.leaveRoom(roomID) - // delete webhook on discord const webhook = select("webhook", ["webhook_id", "webhook_token"], {channel_id: channel.id}).get() if (webhook) { @@ -439,7 +428,48 @@ async function unbridgeDeletedChannel(channel, guildID) { // delete room from database db.prepare("DELETE FROM member_cache WHERE room_id = ?").run(roomID) - db.prepare("DELETE FROM channel_room WHERE room_id = ? AND channel_id = ?").run(roomID, channel.id) + db.prepare("DELETE FROM channel_room WHERE room_id = ? AND channel_id = ?").run(roomID, channel.id) // cascades to most other tables, like messages + + // demote admins in room + /** @type {Ty.Event.M_Power_Levels} */ + const powerLevelContent = await api.getStateEvent(roomID, "m.room.power_levels", "") + powerLevelContent.users ??= {} + const bot = `@${reg.sender_localpart}:${reg.ooye.server_name}` + for (const mxid of Object.keys(powerLevelContent.users)) { + if (mUtils.eventSenderIsFromDiscord(mxid) && mxid !== bot) { + delete powerLevelContent.users[mxid] + await api.sendState(roomID, "m.room.power_levels", "", powerLevelContent, mxid) + } + } + + // send a notification in the room + await api.sendEvent(roomID, "m.room.message", { + msgtype: "m.notice", + body: "⚠️ This room was removed from the bridge." + }) + + // if it is an easy mode room, clean up the room from the managed space and make it clear it's not being bridged + // (don't do this for self-service rooms, because they might continue to be used on Matrix or linked somewhere else later) + if (row.autocreate === 1) { + // remove room from being a space member + await api.sendState(roomID, "m.space.parent", row.space_id, {}) + await api.sendState(row.space_id, "m.space.child", roomID, {}) + + // leave room + await api.leaveRoom(roomID) + } + + // if it is a self-service room, remove sim members + // (the room can be used with less clutter and the member list makes sense if it's bridged somewhere else) + if (row.autocreate === 0) { + // remove sim members + const members = select("sim_member", "mxid", {room_id: roomID}).pluck().all() + const preparedDelete = db.prepare("DELETE FROM sim_member WHERE room_id = ? AND mxid = ?") + for (const mxid of members) { + await api.leaveRoom(roomID, mxid) + preparedDelete.run(roomID, mxid) + } + } } /** @@ -488,7 +518,7 @@ module.exports.createAllForGuild = createAllForGuild module.exports.channelToKState = channelToKState module.exports.postApplyPowerLevels = postApplyPowerLevels module.exports._convertNameAndTopic = convertNameAndTopic -module.exports._unbridgeRoom = _unbridgeRoom +module.exports.unbridgeChannel = unbridgeChannel module.exports.unbridgeDeletedChannel = unbridgeDeletedChannel module.exports.existsOrAutocreatable = existsOrAutocreatable module.exports.assertExistsOrAutocreatable = assertExistsOrAutocreatable diff --git a/src/web/pug/guild.pug b/src/web/pug/guild.pug index 34178bf..51b2c99 100644 --- a/src/web/pug/guild.pug +++ b/src/web/pug/guild.pug @@ -78,12 +78,13 @@ block body h3.mt32.fs-category Linked channels .s-card.bs-sm.p0 - .s-table-container + form.s-table-container(method="post" action="/api/unlink" hx-post="/api/unlink" hx-trigger="submit" hx-disabled-elt="this" hx-confirm="Unlink these channels?\nIt may take a moment to clean up Matrix resources.") + input(type="hidden" name="guild_id" value=guild_id) table.s-table.s-table__bx-simple each row in linkedChannelsWithDetails tr td.w40: +discord(row.channel) - td.p2: button.s-btn.s-btn__muted.s-btn__xs!= icons.Icons.IconLinkSm + td.p2: button.s-btn.s-btn__muted.s-btn__xs(name="channel_id" value=row.channel.id)!= icons.Icons.IconLinkSm td: +matrix(row) else tr diff --git a/src/web/routes/link.js b/src/web/routes/link.js index e63c01b..52c750c 100644 --- a/src/web/routes/link.js +++ b/src/web/routes/link.js @@ -1,7 +1,7 @@ // @ts-check const {z} = require("zod") -const {defineEventHandler, useSession, createError, readValidatedBody} = require("h3") +const {defineEventHandler, useSession, createError, readValidatedBody, setResponseHeader} = require("h3") const Ty = require("../../types") const {discord, db, as, sync, select, from} = require("../../passthrough") @@ -19,6 +19,10 @@ const schema = { guild_id: z.string(), matrix: z.string(), discord: z.string() + }), + unlink: z.object({ + guild_id: z.string(), + channel_id: z.string() }) } @@ -61,3 +65,26 @@ as.router.post("/api/link", defineEventHandler(async event => { return null // 204 })) + +as.router.post("/api/unlink", defineEventHandler(async event => { + const {channel_id, guild_id} = await readValidatedBody(event, schema.unlink.parse) + const session = await useSession(event, {password: reg.as_token}) + + // Check guild ID or nonce + if (!(session.data.managedGuilds || []).includes(guild_id)) throw createError({status: 403, message: "Forbidden", data: "Can't edit a guild you don't have Manage Server permissions in"}) + + // Check channel is part of this guild + const channel = discord.channels.get(channel_id) + if (!channel) throw createError({status: 400, message: "Bad Request", data: `Channel ID ${channel_id} does not exist`}) + if (!("guild_id" in channel) || channel.guild_id !== guild_id) throw createError({status: 400, message: "Bad Request", data: `Channel ID ${channel_id} is not part of guild ${guild_id}`}) + + // Check channel is currently bridged + const row = select("channel_room", "channel_id", {channel_id: channel_id}).get() + if (!row) throw createError({status: 400, message: "Bad Request", data: `Channel ID ${channel_id} is not currently bridged`}) + + // Do it + await createRoom.unbridgeDeletedChannel(channel, guild_id) + + setResponseHeader(event, "HX-Refresh", "true") + return null // 204 +})) From a459ee1d1cce03b6d7dc5fe8dd872f8c81a28fee Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Fri, 31 Jan 2025 16:42:15 +1300 Subject: [PATCH 091/228] Use htmx.js instead of htmx.min.js This wastes 30 kB gzipped, which I think is acceptable in exchange for having method names in the debugger. --- src/web/pug/includes/template.pug | 178 +- src/web/server.js | 4 +- src/web/static/htmx.js | 5261 +++++++++++++++++++++++++++++ src/web/static/htmx.min.js | 1 - 4 files changed, 5352 insertions(+), 92 deletions(-) create mode 100644 src/web/static/htmx.js delete mode 100644 src/web/static/htmx.min.js diff --git a/src/web/pug/includes/template.pug b/src/web/pug/includes/template.pug index 17b7847..909244f 100644 --- a/src/web/pug/includes/template.pug +++ b/src/web/pug/includes/template.pug @@ -1,89 +1,89 @@ -mixin guild(guild) - span.s-avatar.s-avatar__32.s-user-card--avatar - if guild.icon - img.s-avatar--image(src=`https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.png?size=32`) - else - .s-avatar--letter.bg-silver-400.bar-md(aria-hidden="true")= guild.name[0] - .s-user-card--info.ai-start - strong= guild.name - ul.s-user-card--awards - li #{discord.guildChannelMap.get(guild.id).filter(c => [0, 5, 15, 16].includes(discord.channels.get(c).type)).length} channels - -doctype html -html(lang="en") - head - title Out Of Your Element - - link(rel="stylesheet" type="text/css" href=rel("/static/stacks.min.css")) - - meta(name="htmx-config" content='{"indicatorClass":"is-loading"}') - style. - .themed { - --theme-base-primary-color-h: 266; - --theme-base-primary-color-s: 53%; - --theme-base-primary-color-l: 63%; - --theme-dark-primary-color-h: 266; - --theme-dark-primary-color-s: 53%; - --theme-dark-primary-color-l: 63%; - } - .s-toggle-switch.s-toggle-switch__multiple.s-toggle-switch__incremental input[type="radio"]:checked ~ label:not(.s-toggle-switch--label-off) { - --_ts-multiple-bg: var(--green-400); - --_ts-multiple-fc: var(--white); - } - body.themed.theme-system - header.s-topbar - .s-topbar--skip-link(href="#content") Skip to main content - .s-topbar--container.wmx9 - a.s-topbar--logo(href=rel("/")) - img.s-avatar.s-avatar__32(src=rel("/icon.png")) - nav.s-topbar--navigation - ul.s-topbar--content - li.ps-relative - if !session.data.managedGuilds || session.data.managedGuilds.length === 0 - a.s-btn.s-btn__icon.as-center(href=rel("/oauth")) - != icons.Icons.IconDiscord - = ` Log in` - else if guild_id && session.data.managedGuilds.includes(guild_id) && discord.guilds.has(guild_id) - button.s-topbar--item.s-btn.s-btn__muted.s-user-card(popovertarget="guilds") - +guild(discord.guilds.get(guild_id)) - else if session.data.managedGuilds - button.s-topbar--item.s-btn.s-btn__muted.s-btn__dropdown.pr24.s-user-card.s-label(popovertarget="guilds") - | Your servers - #guilds(popover data-popper-placement="bottom" style="display: revert; width: revert;").s-popover.overflow-visible - .s-popover--arrow.s-popover--arrow__tc - .s-popover--content.overflow-y-auto.overflow-x-hidden - ul.s-menu(role="menu") - each guild in (session.data.managedGuilds || []).map(id => discord.guilds.get(id)).filter(g => g) - li(role="menuitem") - a.s-topbar--item.s-user-card.d-flex.p4(href=rel(`/guild?guild_id=${guild.id}`)) - +guild(guild) - //- Body - .mx-auto.w100.wmx9.py24.px8.fs-body1#content - block body - //- Guild list popover - script. - document.querySelectorAll("[popovertarget]").forEach(e => { - e.addEventListener("click", () => { - const rect = e.getBoundingClientRect() - const t = `:popover-open { position: absolute; top: ${Math.floor(rect.bottom)}px; left: ${Math.floor(rect.left + rect.width / 2)}px; width: ${Math.floor(rect.width)}px; transform: translateX(-50%); box-sizing: content-box; margin: 0 }` - // console.log(t) - document.styleSheets[0].insertRule(t) - }) - }) - script(src=rel("/static/htmx.min.js")) - //- Error dialog - aside.s-modal#server-error(aria-hidden="true") - .s-modal--dialog - h1.s-modal--header Server error - pre.overflow-auto#server-error-content - button.s-modal--close.s-btn.s-btn__muted(aria-label="Close" type="button" onclick="hideError()")!= icons.Icons.IconClearSm - .s-modal--footer - button.s-btn.s-btn__outlined.s-btn__muted(type="button" onclick="hideError()") OK - script. - function hideError() { - document.getElementById("server-error").setAttribute("aria-hidden", "true") - } - document.body.addEventListener("htmx:responseError", event => { - document.getElementById("server-error").setAttribute("aria-hidden", "false") - document.getElementById("server-error-content").textContent = event.detail.xhr.responseText - }) +mixin guild(guild) + span.s-avatar.s-avatar__32.s-user-card--avatar + if guild.icon + img.s-avatar--image(src=`https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.png?size=32`) + else + .s-avatar--letter.bg-silver-400.bar-md(aria-hidden="true")= guild.name[0] + .s-user-card--info.ai-start + strong= guild.name + ul.s-user-card--awards + li #{discord.guildChannelMap.get(guild.id).filter(c => [0, 5, 15, 16].includes(discord.channels.get(c).type)).length} channels + +doctype html +html(lang="en") + head + title Out Of Your Element + + link(rel="stylesheet" type="text/css" href=rel("/static/stacks.min.css")) + + meta(name="htmx-config" content='{"indicatorClass":"is-loading"}') + style. + .themed { + --theme-base-primary-color-h: 266; + --theme-base-primary-color-s: 53%; + --theme-base-primary-color-l: 63%; + --theme-dark-primary-color-h: 266; + --theme-dark-primary-color-s: 53%; + --theme-dark-primary-color-l: 63%; + } + .s-toggle-switch.s-toggle-switch__multiple.s-toggle-switch__incremental input[type="radio"]:checked ~ label:not(.s-toggle-switch--label-off) { + --_ts-multiple-bg: var(--green-400); + --_ts-multiple-fc: var(--white); + } + body.themed.theme-system + header.s-topbar + .s-topbar--skip-link(href="#content") Skip to main content + .s-topbar--container.wmx9 + a.s-topbar--logo(href=rel("/")) + img.s-avatar.s-avatar__32(src=rel("/icon.png")) + nav.s-topbar--navigation + ul.s-topbar--content + li.ps-relative + if !session.data.managedGuilds || session.data.managedGuilds.length === 0 + a.s-btn.s-btn__icon.as-center(href=rel("/oauth")) + != icons.Icons.IconDiscord + = ` Log in` + else if guild_id && session.data.managedGuilds.includes(guild_id) && discord.guilds.has(guild_id) + button.s-topbar--item.s-btn.s-btn__muted.s-user-card(popovertarget="guilds") + +guild(discord.guilds.get(guild_id)) + else if session.data.managedGuilds + button.s-topbar--item.s-btn.s-btn__muted.s-btn__dropdown.pr24.s-user-card.s-label(popovertarget="guilds") + | Your servers + #guilds(popover data-popper-placement="bottom" style="display: revert; width: revert;").s-popover.overflow-visible + .s-popover--arrow.s-popover--arrow__tc + .s-popover--content.overflow-y-auto.overflow-x-hidden + ul.s-menu(role="menu") + each guild in (session.data.managedGuilds || []).map(id => discord.guilds.get(id)).filter(g => g) + li(role="menuitem") + a.s-topbar--item.s-user-card.d-flex.p4(href=rel(`/guild?guild_id=${guild.id}`)) + +guild(guild) + //- Body + .mx-auto.w100.wmx9.py24.px8.fs-body1#content + block body + //- Guild list popover + script. + document.querySelectorAll("[popovertarget]").forEach(e => { + e.addEventListener("click", () => { + const rect = e.getBoundingClientRect() + const t = `:popover-open { position: absolute; top: ${Math.floor(rect.bottom)}px; left: ${Math.floor(rect.left + rect.width / 2)}px; width: ${Math.floor(rect.width)}px; transform: translateX(-50%); box-sizing: content-box; margin: 0 }` + // console.log(t) + document.styleSheets[0].insertRule(t) + }) + }) + script(src=rel("/static/htmx.js")) + //- Error dialog + aside.s-modal#server-error(aria-hidden="true") + .s-modal--dialog + h1.s-modal--header Server error + pre.overflow-auto#server-error-content + button.s-modal--close.s-btn.s-btn__muted(aria-label="Close" type="button" onclick="hideError()")!= icons.Icons.IconClearSm + .s-modal--footer + button.s-btn.s-btn__outlined.s-btn__muted(type="button" onclick="hideError()") OK + script. + function hideError() { + document.getElementById("server-error").setAttribute("aria-hidden", "true") + } + document.body.addEventListener("htmx:responseError", event => { + document.getElementById("server-error").setAttribute("aria-hidden", "false") + document.getElementById("server-error-content").textContent = event.detail.xhr.responseText + }) diff --git a/src/web/server.js b/src/web/server.js index 9373947..39c0a68 100644 --- a/src/web/server.js +++ b/src/web/server.js @@ -49,12 +49,12 @@ as.router.get("/static/stacks.min.css", defineEventHandler({ } })) -as.router.get("/static/htmx.min.js", defineEventHandler({ +as.router.get("/static/htmx.js", defineEventHandler({ onBeforeResponse: compressResponse, handler: async event => { handleCacheHeaders(event, {maxAge: 86400}) defaultContentType(event, "text/javascript") - return fs.promises.readFile(join(__dirname, "static", "htmx.min.js"), "utf-8") + return fs.promises.readFile(join(__dirname, "static", "htmx.js"), "utf-8") } })) diff --git a/src/web/static/htmx.js b/src/web/static/htmx.js new file mode 100644 index 0000000..370cc0f --- /dev/null +++ b/src/web/static/htmx.js @@ -0,0 +1,5261 @@ +var htmx = (function() { + 'use strict' + + // Public API + const htmx = { + // Tsc madness here, assigning the functions directly results in an invalid TypeScript output, but reassigning is fine + /* Event processing */ + /** @type {typeof onLoadHelper} */ + onLoad: null, + /** @type {typeof processNode} */ + process: null, + /** @type {typeof addEventListenerImpl} */ + on: null, + /** @type {typeof removeEventListenerImpl} */ + off: null, + /** @type {typeof triggerEvent} */ + trigger: null, + /** @type {typeof ajaxHelper} */ + ajax: null, + /* DOM querying helpers */ + /** @type {typeof find} */ + find: null, + /** @type {typeof findAll} */ + findAll: null, + /** @type {typeof closest} */ + closest: null, + /** + * Returns the input values that would resolve for a given element via the htmx value resolution mechanism + * + * @see https://htmx.org/api/#values + * + * @param {Element} elt the element to resolve values on + * @param {HttpVerb} type the request type (e.g. **get** or **post**) non-GET's will include the enclosing form of the element. Defaults to **post** + * @returns {Object} + */ + values: function(elt, type) { + const inputValues = getInputValues(elt, type || 'post') + return inputValues.values + }, + /* DOM manipulation helpers */ + /** @type {typeof removeElement} */ + remove: null, + /** @type {typeof addClassToElement} */ + addClass: null, + /** @type {typeof removeClassFromElement} */ + removeClass: null, + /** @type {typeof toggleClassOnElement} */ + toggleClass: null, + /** @type {typeof takeClassForElement} */ + takeClass: null, + /** @type {typeof swap} */ + swap: null, + /* Extension entrypoints */ + /** @type {typeof defineExtension} */ + defineExtension: null, + /** @type {typeof removeExtension} */ + removeExtension: null, + /* Debugging */ + /** @type {typeof logAll} */ + logAll: null, + /** @type {typeof logNone} */ + logNone: null, + /* Debugging */ + /** + * The logger htmx uses to log with + * + * @see https://htmx.org/api/#logger + */ + logger: null, + /** + * A property holding the configuration htmx uses at runtime. + * + * Note that using a [meta tag](https://htmx.org/docs/#config) is the preferred mechanism for setting these properties. + * + * @see https://htmx.org/api/#config + */ + config: { + /** + * Whether to use history. + * @type boolean + * @default true + */ + historyEnabled: true, + /** + * The number of pages to keep in **localStorage** for history support. + * @type number + * @default 10 + */ + historyCacheSize: 10, + /** + * @type boolean + * @default false + */ + refreshOnHistoryMiss: false, + /** + * The default swap style to use if **[hx-swap](https://htmx.org/attributes/hx-swap)** is omitted. + * @type HtmxSwapStyle + * @default 'innerHTML' + */ + defaultSwapStyle: 'innerHTML', + /** + * The default delay between receiving a response from the server and doing the swap. + * @type number + * @default 0 + */ + defaultSwapDelay: 0, + /** + * The default delay between completing the content swap and settling attributes. + * @type number + * @default 20 + */ + defaultSettleDelay: 20, + /** + * If true, htmx will inject a small amount of CSS into the page to make indicators invisible unless the **htmx-indicator** class is present. + * @type boolean + * @default true + */ + includeIndicatorStyles: true, + /** + * The class to place on indicators when a request is in flight. + * @type string + * @default 'htmx-indicator' + */ + indicatorClass: 'htmx-indicator', + /** + * The class to place on triggering elements when a request is in flight. + * @type string + * @default 'htmx-request' + */ + requestClass: 'htmx-request', + /** + * The class to temporarily place on elements that htmx has added to the DOM. + * @type string + * @default 'htmx-added' + */ + addedClass: 'htmx-added', + /** + * The class to place on target elements when htmx is in the settling phase. + * @type string + * @default 'htmx-settling' + */ + settlingClass: 'htmx-settling', + /** + * The class to place on target elements when htmx is in the swapping phase. + * @type string + * @default 'htmx-swapping' + */ + swappingClass: 'htmx-swapping', + /** + * Allows the use of eval-like functionality in htmx, to enable **hx-vars**, trigger conditions & script tag evaluation. Can be set to **false** for CSP compatibility. + * @type boolean + * @default true + */ + allowEval: true, + /** + * If set to false, disables the interpretation of script tags. + * @type boolean + * @default true + */ + allowScriptTags: true, + /** + * If set, the nonce will be added to inline scripts. + * @type string + * @default '' + */ + inlineScriptNonce: '', + /** + * If set, the nonce will be added to inline styles. + * @type string + * @default '' + */ + inlineStyleNonce: '', + /** + * The attributes to settle during the settling phase. + * @type string[] + * @default ['class', 'style', 'width', 'height'] + */ + attributesToSettle: ['class', 'style', 'width', 'height'], + /** + * Allow cross-site Access-Control requests using credentials such as cookies, authorization headers or TLS client certificates. + * @type boolean + * @default false + */ + withCredentials: false, + /** + * @type number + * @default 0 + */ + timeout: 0, + /** + * The default implementation of **getWebSocketReconnectDelay** for reconnecting after unexpected connection loss by the event code **Abnormal Closure**, **Service Restart** or **Try Again Later**. + * @type {'full-jitter' | ((retryCount:number) => number)} + * @default "full-jitter" + */ + wsReconnectDelay: 'full-jitter', + /** + * The type of binary data being received over the WebSocket connection + * @type BinaryType + * @default 'blob' + */ + wsBinaryType: 'blob', + /** + * @type string + * @default '[hx-disable], [data-hx-disable]' + */ + disableSelector: '[hx-disable], [data-hx-disable]', + /** + * @type {'auto' | 'instant' | 'smooth'} + * @default 'instant' + */ + scrollBehavior: 'instant', + /** + * If the focused element should be scrolled into view. + * @type boolean + * @default false + */ + defaultFocusScroll: false, + /** + * If set to true htmx will include a cache-busting parameter in GET requests to avoid caching partial responses by the browser + * @type boolean + * @default false + */ + getCacheBusterParam: false, + /** + * If set to true, htmx will use the View Transition API when swapping in new content. + * @type boolean + * @default false + */ + globalViewTransitions: false, + /** + * htmx will format requests with these methods by encoding their parameters in the URL, not the request body + * @type {(HttpVerb)[]} + * @default ['get', 'delete'] + */ + methodsThatUseUrlParams: ['get', 'delete'], + /** + * If set to true, disables htmx-based requests to non-origin hosts. + * @type boolean + * @default false + */ + selfRequestsOnly: true, + /** + * If set to true htmx will not update the title of the document when a title tag is found in new content + * @type boolean + * @default false + */ + ignoreTitle: false, + /** + * Whether the target of a boosted element is scrolled into the viewport. + * @type boolean + * @default true + */ + scrollIntoViewOnBoost: true, + /** + * The cache to store evaluated trigger specifications into. + * You may define a simple object to use a never-clearing cache, or implement your own system using a [proxy object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy) + * @type {Object|null} + * @default null + */ + triggerSpecsCache: null, + /** @type boolean */ + disableInheritance: false, + /** @type HtmxResponseHandlingConfig[] */ + responseHandling: [ + { code: '204', swap: false }, + { code: '[23]..', swap: true }, + { code: '[45]..', swap: false, error: true } + ], + /** + * Whether to process OOB swaps on elements that are nested within the main response element. + * @type boolean + * @default true + */ + allowNestedOobSwaps: true + }, + /** @type {typeof parseInterval} */ + parseInterval: null, + /** @type {typeof internalEval} */ + _: null, + version: '2.0.4' + } + // Tsc madness part 2 + htmx.onLoad = onLoadHelper + htmx.process = processNode + htmx.on = addEventListenerImpl + htmx.off = removeEventListenerImpl + htmx.trigger = triggerEvent + htmx.ajax = ajaxHelper + htmx.find = find + htmx.findAll = findAll + htmx.closest = closest + htmx.remove = removeElement + htmx.addClass = addClassToElement + htmx.removeClass = removeClassFromElement + htmx.toggleClass = toggleClassOnElement + htmx.takeClass = takeClassForElement + htmx.swap = swap + htmx.defineExtension = defineExtension + htmx.removeExtension = removeExtension + htmx.logAll = logAll + htmx.logNone = logNone + htmx.parseInterval = parseInterval + htmx._ = internalEval + + const internalAPI = { + addTriggerHandler, + bodyContains, + canAccessLocalStorage, + findThisElement, + filterValues, + swap, + hasAttribute, + getAttributeValue, + getClosestAttributeValue, + getClosestMatch, + getExpressionVars, + getHeaders, + getInputValues, + getInternalData, + getSwapSpecification, + getTriggerSpecs, + getTarget, + makeFragment, + mergeObjects, + makeSettleInfo, + oobSwap, + querySelectorExt, + settleImmediately, + shouldCancel, + triggerEvent, + triggerErrorEvent, + withExtensions + } + + const VERBS = ['get', 'post', 'put', 'delete', 'patch'] + const VERB_SELECTOR = VERBS.map(function(verb) { + return '[hx-' + verb + '], [data-hx-' + verb + ']' + }).join(', ') + + //= =================================================================== + // Utilities + //= =================================================================== + + /** + * Parses an interval string consistent with the way htmx does. Useful for plugins that have timing-related attributes. + * + * Caution: Accepts an int followed by either **s** or **ms**. All other values use **parseFloat** + * + * @see https://htmx.org/api/#parseInterval + * + * @param {string} str timing string + * @returns {number|undefined} + */ + function parseInterval(str) { + if (str == undefined) { + return undefined + } + + let interval = NaN + if (str.slice(-2) == 'ms') { + interval = parseFloat(str.slice(0, -2)) + } else if (str.slice(-1) == 's') { + interval = parseFloat(str.slice(0, -1)) * 1000 + } else if (str.slice(-1) == 'm') { + interval = parseFloat(str.slice(0, -1)) * 1000 * 60 + } else { + interval = parseFloat(str) + } + return isNaN(interval) ? undefined : interval + } + + /** + * @param {Node} elt + * @param {string} name + * @returns {(string | null)} + */ + function getRawAttribute(elt, name) { + return elt instanceof Element && elt.getAttribute(name) + } + + /** + * @param {Element} elt + * @param {string} qualifiedName + * @returns {boolean} + */ + // resolve with both hx and data-hx prefixes + function hasAttribute(elt, qualifiedName) { + return !!elt.hasAttribute && (elt.hasAttribute(qualifiedName) || + elt.hasAttribute('data-' + qualifiedName)) + } + + /** + * + * @param {Node} elt + * @param {string} qualifiedName + * @returns {(string | null)} + */ + function getAttributeValue(elt, qualifiedName) { + return getRawAttribute(elt, qualifiedName) || getRawAttribute(elt, 'data-' + qualifiedName) + } + + /** + * @param {Node} elt + * @returns {Node | null} + */ + function parentElt(elt) { + const parent = elt.parentElement + if (!parent && elt.parentNode instanceof ShadowRoot) return elt.parentNode + return parent + } + + /** + * @returns {Document} + */ + function getDocument() { + return document + } + + /** + * @param {Node} elt + * @param {boolean} global + * @returns {Node|Document} + */ + function getRootNode(elt, global) { + return elt.getRootNode ? elt.getRootNode({ composed: global }) : getDocument() + } + + /** + * @param {Node} elt + * @param {(e:Node) => boolean} condition + * @returns {Node | null} + */ + function getClosestMatch(elt, condition) { + while (elt && !condition(elt)) { + elt = parentElt(elt) + } + + return elt || null + } + + /** + * @param {Element} initialElement + * @param {Element} ancestor + * @param {string} attributeName + * @returns {string|null} + */ + function getAttributeValueWithDisinheritance(initialElement, ancestor, attributeName) { + const attributeValue = getAttributeValue(ancestor, attributeName) + const disinherit = getAttributeValue(ancestor, 'hx-disinherit') + var inherit = getAttributeValue(ancestor, 'hx-inherit') + if (initialElement !== ancestor) { + if (htmx.config.disableInheritance) { + if (inherit && (inherit === '*' || inherit.split(' ').indexOf(attributeName) >= 0)) { + return attributeValue + } else { + return null + } + } + if (disinherit && (disinherit === '*' || disinherit.split(' ').indexOf(attributeName) >= 0)) { + return 'unset' + } + } + return attributeValue + } + + /** + * @param {Element} elt + * @param {string} attributeName + * @returns {string | null} + */ + function getClosestAttributeValue(elt, attributeName) { + let closestAttr = null + getClosestMatch(elt, function(e) { + return !!(closestAttr = getAttributeValueWithDisinheritance(elt, asElement(e), attributeName)) + }) + if (closestAttr !== 'unset') { + return closestAttr + } + } + + /** + * @param {Node} elt + * @param {string} selector + * @returns {boolean} + */ + function matches(elt, selector) { + // @ts-ignore: non-standard properties for browser compatibility + // noinspection JSUnresolvedVariable + const matchesFunction = elt instanceof Element && (elt.matches || elt.matchesSelector || elt.msMatchesSelector || elt.mozMatchesSelector || elt.webkitMatchesSelector || elt.oMatchesSelector) + return !!matchesFunction && matchesFunction.call(elt, selector) + } + + /** + * @param {string} str + * @returns {string} + */ + function getStartTag(str) { + const tagMatcher = /<([a-z][^\/\0>\x20\t\r\n\f]*)/i + const match = tagMatcher.exec(str) + if (match) { + return match[1].toLowerCase() + } else { + return '' + } + } + + /** + * @param {string} resp + * @returns {Document} + */ + function parseHTML(resp) { + const parser = new DOMParser() + return parser.parseFromString(resp, 'text/html') + } + + /** + * @param {DocumentFragment} fragment + * @param {Node} elt + */ + function takeChildrenFor(fragment, elt) { + while (elt.childNodes.length > 0) { + fragment.append(elt.childNodes[0]) + } + } + + /** + * @param {HTMLScriptElement} script + * @returns {HTMLScriptElement} + */ + function duplicateScript(script) { + const newScript = getDocument().createElement('script') + forEach(script.attributes, function(attr) { + newScript.setAttribute(attr.name, attr.value) + }) + newScript.textContent = script.textContent + newScript.async = false + if (htmx.config.inlineScriptNonce) { + newScript.nonce = htmx.config.inlineScriptNonce + } + return newScript + } + + /** + * @param {HTMLScriptElement} script + * @returns {boolean} + */ + function isJavaScriptScriptNode(script) { + return script.matches('script') && (script.type === 'text/javascript' || script.type === 'module' || script.type === '') + } + + /** + * we have to make new copies of script tags that we are going to insert because + * SOME browsers (not saying who, but it involves an element and an animal) don't + * execute scripts created in