category subspaces #113
11 changed files with 430 additions and 56 deletions
60
scripts/full-space-sync.js
Normal file
60
scripts/full-space-sync.js
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
#!/usr/bin/env node
|
||||
// @ts-check
|
||||
|
||||
const {guild: guild_id} = require("minimist")(process.argv.slice(2), {string: ["guild"]})
|
||||
if (!guild_id) {
|
||||
console.error("Usage: ./scripts/full-space-sync.js --guild=<guild ID here>")
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const sqlite = require("better-sqlite3")
|
||||
const HeatSync = require("heatsync")
|
||||
|
||||
const {reg} = require("../src/matrix/read-registration")
|
||||
const passthrough = require("../src/passthrough")
|
||||
|
||||
const sync = new HeatSync({watchFS: false})
|
||||
const db = new sqlite("ooye.db")
|
||||
Object.assign(passthrough, {sync, db})
|
||||
|
||||
const DiscordTypes = require("discord-api-types/v10")
|
||||
const DiscordClient = require("../src/d2m/discord-client")
|
||||
|
||||
const discord = new DiscordClient(reg.ooye.discord_token, "half")
|
||||
passthrough.discord = discord
|
||||
|
||||
const {as} = require("../src/matrix/appservice")
|
||||
passthrough.as = as
|
||||
|
||||
const orm = sync.require("../src/db/orm")
|
||||
passthrough.from = orm.from
|
||||
passthrough.select = orm.select
|
||||
|
||||
/** @type {import("../src/d2m/event-dispatcher")}*/
|
||||
const eventDispatcher = sync.require("../src/d2m/event-dispatcher")
|
||||
|
||||
/** @type {import("../src/d2m/actions/create-space")}) */
|
||||
const createSpace = sync.require("../src/d2m/actions/create-space")
|
||||
|
||||
;(async () => {
|
||||
await discord.cloud.connect()
|
||||
console.log("Connected, waiting for data about requested guild...")
|
||||
|
||||
discord.cloud.on("event", event)
|
||||
})()
|
||||
|
||||
/**
|
||||
* @param {import("cloudstorm").IGatewayMessage} event
|
||||
*/
|
||||
async function event(event) {
|
||||
if (event.t !== "GUILD_CREATE") return
|
||||
if (event.d.id !== guild_id) return
|
||||
|
||||
try {
|
||||
await createSpace.syncSpaceFully(guild_id)
|
||||
process.exit(0)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
process.exit(1) // won't exit automatically on thrown error due to living discord connection, so manual exit is necessary
|
||||
}
|
||||
}
|
||||
|
|
@ -41,6 +41,7 @@ const PRIVACY_ENUMS = {
|
|||
const DEFAULT_PRIVACY_LEVEL = 0
|
||||
|
||||
const READ_ONLY_ROOM_EVENTS_DEFAULT_POWER = 50
|
||||
const SPACE_ROOM_EVENTS_DEFAULT_POWER = 100
|
||||
|
||||
/** @type {Map<string, Promise<string>>} channel ID -> Promise<room ID> */
|
||||
const inflightRoomCreate = sync.remember(() => new Map())
|
||||
|
|
@ -73,6 +74,39 @@ function convertNameAndTopic(channel, guild, customName) {
|
|||
return [chosenName, convertedTopic];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {DiscordTypes.APIGuild} guild
|
||||
* @param {DiscordTypes.APIGuildTextChannel | DiscordTypes.APIThreadChannel} channel
|
||||
* @param {DiscordTypes.APIChannel} parentChannel
|
||||
* @param {boolean} autocreate
|
||||
* @return boolean
|
||||
*/
|
||||
async function shouldMakeCategorySpace(guild, channel, parentChannel, autocreate) {
|
||||
if (parentChannel?.type === DiscordTypes.ChannelType.GuildForum) return true
|
||||
if (!autocreate || parentChannel.type !== DiscordTypes.ChannelType.GuildCategory) return false
|
||||
|
||||
// if there is already a bridged room for the parent channel, don't revert it
|
||||
// this can happen when manually linking categories in the web UI for default guilds
|
||||
const parentRoom = select("channel_room", "room_id", {room_id: parentChannel.id}).pluck().get()
|
||||
if (parentRoom) return true
|
||||
|
||||
const defaultRoles = select("role_default", "role_id", {guild_id: guild.id}).pluck().all()
|
||||
/** @type {DiscordTypes.APIChannel[]} */
|
||||
// @ts-ignore
|
||||
const guildChannels = discord.guildChannelMap.get(guild.id)?.map(id => discord.channels.get(id))
|
||||
.filter(ch => ch?.["permission_overwrites"] && dUtils.hasPermission(dUtils.getPermissions(guild.id, defaultRoles, guild.roles, undefined, ch?.["permission_overwrites"]), DiscordTypes.PermissionFlagsBits.ViewChannel)) ?? []
|
||||
const categories = guildChannels.filter(ch => ch.type === DiscordTypes.ChannelType.GuildCategory && guildChannels.find(ch2 => ch2["parent_id"] === ch.id))
|
||||
|
||||
if (categories.length <= 1) return false
|
||||
if (categories.length >= 3) return true
|
||||
|
||||
const otherCategory = categories[0].id === parentChannel.id ? categories[1] : categories[0]
|
||||
const voiceCategory = channel.type === DiscordTypes.ChannelType.GuildVoice ? parentChannel : otherCategory
|
||||
|
||||
if (guildChannels.find(ch => ch["parent_id"] === voiceCategory.id && ![DiscordTypes.ChannelType.GuildVoice, DiscordTypes.ChannelType.GuildStageVoice].includes(ch.type))) return true
|
||||
else return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Async because it may create the guild and/or upload the guild icon to mxc.
|
||||
* @param {DiscordTypes.APIGuildTextChannel | DiscordTypes.APIThreadChannel} channel
|
||||
|
|
@ -80,23 +114,39 @@ function convertNameAndTopic(channel, guild, customName) {
|
|||
* @param {{api: {getStateEvent: typeof api.getStateEvent, getStateEventOuter: typeof api.getStateEventOuter}}} di simple-as-nails dependency injection for the matrix API
|
||||
*/
|
||||
async function channelToKState(channel, guild, di) {
|
||||
// @ts-ignore
|
||||
const parentChannel = discord.channels.get(channel.parent_id)
|
||||
|
||||
/** Used for membership/permission checks. */
|
||||
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. */
|
||||
/**
|
||||
* Used as the literal parent on Matrix, for categorisation.
|
||||
*
|
||||
* 1. If the channel is a forum thread, a forum space is used as the parent.
|
||||
* 2. Autocreate only: if the channel is in a category, a category space is used as the parent.
|
||||
* 2b. (For future expansion: place threads into a special space.)
|
||||
* 3. Otherwise, the guild space is used as the parent.
|
||||
*/
|
||||
let parentSpaceID = guildSpaceID
|
||||
if (parentChannel?.type === DiscordTypes.ChannelType.GuildForum) {
|
||||
parentSpaceID = await ensureRoom(channel.parent_id)
|
||||
|
||||
// Don't add a space parent if it's self service
|
||||
// (The person setting up self-service has already put it in their preferred space to be able to get this far.)
|
||||
const autocreate = select("guild_active", "autocreate", {guild_id: guild.id}).pluck().get()
|
||||
|
||||
const isThread = [DiscordTypes.ChannelType.PrivateThread, DiscordTypes.ChannelType.PublicThread, DiscordTypes.ChannelType.AnnouncementThread].includes(channel.type)
|
||||
// @ts-ignore @type {DiscordTypes.APIChannel}
|
||||
let parentChannel = discord.channels.get(channel.parent_id)
|
||||
if (isThread && parentChannel && parentChannel.type !== DiscordTypes.ChannelType.GuildForum) {
|
||||
parentChannel = discord.channels.get(parentChannel["parent_id"])
|
||||
}
|
||||
if (parentChannel && await shouldMakeCategorySpace(guild, channel, parentChannel, !!autocreate)) {
|
||||
parentSpaceID = await ensureRoom(parentChannel.id)
|
||||
assert(typeof parentSpaceID === "string")
|
||||
}
|
||||
|
||||
const channelRow = select("channel_room", ["nick", "custom_avatar", "custom_topic"], {channel_id: channel.id}).get()
|
||||
const channelRow = select("channel_room", ["nick", "custom_avatar", "custom_topic", "parent_space_id"], {channel_id: channel.id}).get()
|
||||
const customName = channelRow?.nick
|
||||
const customAvatar = channelRow?.custom_avatar
|
||||
const hasCustomTopic = channelRow?.custom_topic
|
||||
const [convertedName, convertedTopic] = convertNameAndTopic(channel, guild, customName)
|
||||
const currentParentSpaceID = channelRow?.parent_space_id
|
||||
|
||||
const avatarEventContent = {}
|
||||
if (customAvatar) {
|
||||
|
|
@ -126,9 +176,18 @@ async function channelToKState(channel, guild, di) {
|
|||
const everyoneCanSend = dUtils.hasPermission(everyonePermissions, DiscordTypes.PermissionFlagsBits.SendMessages)
|
||||
const everyoneCanMentionEveryone = dUtils.hasPermission(everyonePermissions, DiscordTypes.PermissionFlagsBits.MentionEveryone)
|
||||
|
||||
const pollStartPowerLevel = {}
|
||||
const eventPowerLevels = {
|
||||
"m.room.redaction": 0, // only affects redactions of own events, required to be able to un-react
|
||||
}
|
||||
const isCategorySpace = [DiscordTypes.ChannelType.GuildCategory, DiscordTypes.ChannelType.GuildForum].includes(channel.type)
|
||||
|
||||
if (!isCategorySpace) {
|
||||
eventPowerLevels["m.reaction"] = 0
|
||||
eventPowerLevels["org.matrix.msc3381.poll.response"] = 0
|
||||
|
||||
const everyoneCanCreatePolls = dUtils.hasPermission(everyonePermissions, DiscordTypes.PermissionFlagsBits.SendPolls)
|
||||
if (everyoneCanSend && !everyoneCanCreatePolls) pollStartPowerLevel["org.matrix.msc3381.poll.start"] = 10
|
||||
if (everyoneCanSend && !everyoneCanCreatePolls) eventPowerLevels["org.matrix.msc3381.poll.start"] = 10
|
||||
}
|
||||
|
||||
const spacePowerDetails = await mUtils.getEffectivePower(guildSpaceID, [], di.api)
|
||||
spacePowerDetails.powerLevels.users ??= {}
|
||||
|
|
@ -143,7 +202,7 @@ async function channelToKState(channel, guild, di) {
|
|||
const creationContent = {}
|
||||
creationContent.additional_creators = additionalCreatorsUnique
|
||||
|
||||
if (channel.type === DiscordTypes.ChannelType.GuildForum) creationContent.type = "m.space"
|
||||
if (isCategorySpace) creationContent.type = "m.space"
|
||||
|
||||
/** @type {any} */
|
||||
const channelKState = {
|
||||
|
|
@ -161,13 +220,8 @@ async function channelToKState(channel, guild, di) {
|
|||
"m.room.join_rules/": join_rules,
|
||||
/** @type {Ty.Event.M_Power_Levels} */
|
||||
"m.room.power_levels/": {
|
||||
events_default: everyoneCanSend ? 0 : READ_ONLY_ROOM_EVENTS_DEFAULT_POWER,
|
||||
events: {
|
||||
"m.reaction": 0,
|
||||
"org.matrix.msc3381.poll.response": 0,
|
||||
"m.room.redaction": 0, // only affects redactions of own events, required to be able to un-react
|
||||
...pollStartPowerLevel
|
||||
},
|
||||
events_default: isCategorySpace ? SPACE_ROOM_EVENTS_DEFAULT_POWER : everyoneCanSend ? 0 : READ_ONLY_ROOM_EVENTS_DEFAULT_POWER,
|
||||
events: eventPowerLevels,
|
||||
notifications: {
|
||||
room: everyoneCanMentionEveryone ? 0 : 20
|
||||
},
|
||||
|
|
@ -205,13 +259,14 @@ async function channelToKState(channel, guild, di) {
|
|||
}
|
||||
}
|
||||
|
||||
// Don't add a space parent if it's self service
|
||||
// (The person setting up self-service has already put it in their preferred space to be able to get this far.)
|
||||
const autocreate = select("guild_active", "autocreate", {guild_id: guild.id}).pluck().get()
|
||||
if (autocreate === 0 && ![DiscordTypes.ChannelType.PrivateThread, DiscordTypes.ChannelType.PublicThread, DiscordTypes.ChannelType.AnnouncementThread].includes(channel.type)) {
|
||||
delete channelKState[`m.space.parent/${parentSpaceID}`]
|
||||
}
|
||||
|
||||
if (autocreate && currentParentSpaceID && currentParentSpaceID !== parentSpaceID) {
|
||||
channelKState[`m.space.parent/${currentParentSpaceID}`] = {}
|
||||
}
|
||||
|
||||
return {spaceID: parentSpaceID, privacyLevel, channelKState}
|
||||
}
|
||||
|
||||
|
|
@ -252,7 +307,7 @@ async function createRoom(channel, guild, spaceID, kstate, privacyLevel) {
|
|||
const roomCreate = await api.getStateEventOuter(roomID, "m.room.create", "")
|
||||
|
||||
db.transaction(() => {
|
||||
db.prepare("INSERT INTO channel_room (channel_id, room_id, name, nick, thread_parent, guild_id) VALUES (?, ?, ?, NULL, ?, ?)").run(channel.id, roomID, channel.name, threadParent, guild.id)
|
||||
db.prepare("INSERT INTO channel_room (channel_id, room_id, name, nick, thread_parent, guild_id, parent_space_id) VALUES (?, ?, ?, NULL, ?, ?, ?)").run(channel.id, roomID, channel.name, threadParent, guild.id, spaceID)
|
||||
db.prepare("INSERT INTO historical_channel_room (reference_channel_id, room_id, upgraded_timestamp) VALUES (?, ?, 0)").run(channel.id, roomID)
|
||||
})()
|
||||
|
||||
|
|
@ -261,7 +316,7 @@ async function createRoom(channel, guild, spaceID, kstate, privacyLevel) {
|
|||
const roomID = roomCreate.room_id
|
||||
|
||||
// Put the newly created child into the space
|
||||
await _syncSpaceMember(channel, spaceID, roomID, guild.id)
|
||||
await _syncSpaceMember(channel, spaceID, roomID, guild.id, false)
|
||||
|
||||
return roomID
|
||||
}
|
||||
|
|
@ -435,7 +490,7 @@ async function _syncRoom(channelID, shouldActuallySync) {
|
|||
db.prepare("UPDATE channel_room SET name = ? WHERE channel_id = ?").run(channel.name, channel.id)
|
||||
|
||||
// sync room as space member
|
||||
const spaceApply = _syncSpaceMember(channel, spaceID, roomID, guild.id)
|
||||
const spaceApply = _syncSpaceMember(channel, spaceID, roomID, guild.id, true)
|
||||
await Promise.all([roomApply, spaceApply])
|
||||
|
||||
return roomID
|
||||
|
|
@ -455,12 +510,16 @@ function syncRoom(channelID) {
|
|||
* @param {{id: string, topic?: string?}} channel channel-ish (just needs an id, topic is optional)
|
||||
* @param {string} guildID
|
||||
* @param {string} messageBeforeLeave
|
||||
* @param {boolean} all whether all rooms are being unbridged (if not, an effort should be made to fix other rooms
|
||||
* depending on this one, like a category is being unbridged)
|
||||
*/
|
||||
async function unbridgeChannel(channel, guildID, messageBeforeLeave = "This room was removed from the bridge.") {
|
||||
const roomID = select("channel_room", "room_id", {channel_id: channel.id}).pluck().get()
|
||||
assert.ok(roomID)
|
||||
async function unbridgeChannel(channel, guildID, all, messageBeforeLeave = "This room was removed from the bridge.") {
|
||||
const channelRoomRow = select("channel_room", ["room_id", "parent_space_id"], {channel_id: channel.id}).get()
|
||||
assert.ok(channelRoomRow)
|
||||
const roomID = channelRoomRow.room_id
|
||||
const row = from("guild_space").join("guild_active", "guild_id").select("space_id", "autocreate").where({guild_id: guildID}).get()
|
||||
assert.ok(row)
|
||||
const parentSpaceID = channelRoomRow.parent_space_id ?? row.space_id
|
||||
|
||||
let botInRoom = true
|
||||
|
||||
|
|
@ -487,6 +546,27 @@ async function unbridgeChannel(channel, guildID, messageBeforeLeave = "This room
|
|||
db.prepare("DELETE FROM webhook WHERE channel_id = ?").run(channel.id)
|
||||
}
|
||||
|
||||
// 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", parentSpaceID, {})
|
||||
await api.sendState(parentSpaceID, "m.space.child", roomID, {})
|
||||
|
||||
if (!all && roomID !== row.space_id) {
|
||||
const childrenRoomIDs = select("channel_room", "room_id", {parent_space_id: roomID}).pluck().all()
|
||||
for (const childrenRoomID of childrenRoomIDs) {
|
||||
const parentState = await api.getStateEvent(childrenRoomID, "m.space.parent", roomID) ?? {via: [reg.ooye.server_name]}
|
||||
const childState = await api.getStateEvent(roomID, "m.space.child", childrenRoomID) ?? {via: [reg.ooye.server_name]}
|
||||
delete childState["order"]
|
||||
|
||||
await api.sendState(childrenRoomID, "m.space.parent", roomID, {})
|
||||
await api.sendState(childrenRoomID, "m.space.parent", roomID, parentState)
|
||||
await api.sendState(parentSpaceID, "m.space.child", childrenRoomID, childState)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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) // cascades to most other tables, like messages and historical rooms
|
||||
|
|
@ -518,14 +598,6 @@ async function unbridgeChannel(channel, guildID, messageBeforeLeave = "This room
|
|||
body: `⚠️ ${messageBeforeLeave}`
|
||||
})
|
||||
|
||||
// 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, {})
|
||||
}
|
||||
|
||||
// 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) {
|
||||
|
|
@ -543,23 +615,78 @@ async function unbridgeChannel(channel, guildID, messageBeforeLeave = "This room
|
|||
await api.leaveRoom(roomID)
|
||||
}
|
||||
|
||||
const BASE26ALPHABET = "abcdefghijklmnopqrstuvwxyz"
|
||||
const BASE26PAIRMAX = 26*26-1
|
||||
|
||||
/**
|
||||
* Helper function for _encodeOrder
|
||||
*
|
||||
* @param {number | null | undefined} order
|
||||
* @returns {string}
|
||||
*/
|
||||
function _toBase26Pair(order) {
|
||||
if (order == null || !isFinite(order)) return " "
|
||||
else if (order < 0) order = 0
|
||||
else if (order > BASE26PAIRMAX) order = BASE26PAIRMAX
|
||||
|
||||
const lower = order % 26;
|
||||
const upper = (order - lower) / 26
|
||||
|
||||
return `${BASE26ALPHABET.at(upper)}${BASE26ALPHABET.at(lower)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a set of discord numeric channel order parameters to a single matrix space ordering string
|
||||
*
|
||||
* We abuse the lexiographic ordering scheme used by matrix to cheaply bridge the channel ordering:
|
||||
* - The order string is 2 characters for channels and 4 characters for threads.
|
||||
* - Each pair of 2 characters is treated as a single base26 number (alphabet: a-z)
|
||||
* - The first pair is the order number of the channel
|
||||
* - The second (optional) pair is the order of the thread
|
||||
* - If not present, it is omitted - this orders threads right after the parent channel
|
||||
*
|
||||
* @param {number} channelOrder channel position
|
||||
* @param {number | null | undefined} threadOrder thread position
|
||||
* @returns {string}
|
||||
*/
|
||||
function _encodeOrder(channelOrder, threadOrder) {
|
||||
const channelPair = _toBase26Pair(channelOrder)
|
||||
const threadPair = threadOrder == null ? "" : _toBase26Pair(threadOrder)
|
||||
|
||||
return `${channelPair}${threadPair}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Async because it gets all space state from the homeserver, then if necessary sends one state event back.
|
||||
* @param {DiscordTypes.APIGuildTextChannel} channel
|
||||
* @param {string} spaceID
|
||||
* @param {string} roomID
|
||||
* @param {string} guild_id
|
||||
* @returns {Promise<string[]>}
|
||||
* @param {boolean} tryRemoveFromOld
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
async function _syncSpaceMember(channel, spaceID, roomID, guild_id) {
|
||||
async function _syncSpaceMember(channel, spaceID, roomID, guild_id, tryRemoveFromOld) {
|
||||
// If space is self-service then only permit changes to space parenting for threads
|
||||
// (The person setting up self-service has already put it in their preferred space to be able to get this far.)
|
||||
const autocreate = select("guild_active", "autocreate", {guild_id}).pluck().get()
|
||||
if (autocreate === 0 && ![DiscordTypes.ChannelType.PrivateThread, DiscordTypes.ChannelType.PublicThread, DiscordTypes.ChannelType.AnnouncementThread].includes(channel.type)) {
|
||||
const isThread = [DiscordTypes.ChannelType.PrivateThread, DiscordTypes.ChannelType.PublicThread, DiscordTypes.ChannelType.AnnouncementThread].includes(channel.type)
|
||||
if (autocreate === 0 && !isThread) {
|
||||
return []
|
||||
}
|
||||
|
||||
let oldSpaceID
|
||||
let oldSpaceKState
|
||||
if (tryRemoveFromOld && autocreate) {
|
||||
oldSpaceID = select("channel_room", "parent_space_id", {channel_id: channel.id}).pluck().get()
|
||||
if (oldSpaceID) {
|
||||
oldSpaceKState = await ks.roomToKState(oldSpaceID)
|
||||
}
|
||||
}
|
||||
|
||||
const spaceKState = await ks.roomToKState(spaceID)
|
||||
const childStateKey = `m.space.child/${roomID}`
|
||||
const currentChildEvent = spaceKState[childStateKey] ?? oldSpaceKState?.[childStateKey]
|
||||
/** @type {{via?: any, suggested?: any, order?: string}} */
|
||||
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)
|
||||
|
|
@ -571,11 +698,60 @@ async function _syncSpaceMember(channel, spaceID, roomID, guild_id) {
|
|||
spaceEventContent = {
|
||||
via: [reg.ooye.server_name]
|
||||
}
|
||||
|
||||
// let admins mark rooms as suggested on the [m] side without us removing the flag
|
||||
const currentSuggested = currentChildEvent?.suggested
|
||||
if (currentSuggested != null) {
|
||||
spaceEventContent.suggested = currentSuggested
|
||||
}
|
||||
|
||||
if (autocreate === 0) {
|
||||
// a. don't mess with room ordering in self-service spaces
|
||||
// b. don't transfer the order value from another space
|
||||
const currentOrder = spaceKState[childStateKey]?.order
|
||||
if (currentOrder != null) {
|
||||
spaceEventContent.order = currentOrder
|
||||
}
|
||||
} else {
|
||||
// bridge the discord channel order
|
||||
/** @ts-ignore @type {DiscordTypes.APIThreadChannel | undefined} */
|
||||
const thread = isThread && channel.parent_id != null ? channel : undefined
|
||||
/** @ts-ignore @type {DiscordTypes.APIGuildTextChannel | undefined} */
|
||||
const channelForReal = isThread && channel.parent_id != null ? discord.channels.get(channel.parent_id) : channel
|
||||
|
||||
// we actually don't have the thread's position - put 0 here for now, matrix will sort it automatically by timestamp
|
||||
const threadPosition = thread == null ? null : 0
|
||||
let channelPosition = channelForReal?.position ?? 0
|
||||
|
||||
// since voice channels are always ordered after all text channels on discord,
|
||||
// offset the order by half of the available range - this should be enough in most cases
|
||||
if (channel.type === DiscordTypes.ChannelType.GuildVoice) channelPosition += 13*26
|
||||
|
||||
spaceEventContent.order = _encodeOrder(channelPosition, threadPosition)
|
||||
}
|
||||
}
|
||||
|
||||
const actions = []
|
||||
const spaceDiff = ks.diffKState(spaceKState, {
|
||||
[`m.space.child/${roomID}`]: spaceEventContent
|
||||
[childStateKey]: spaceEventContent
|
||||
})
|
||||
return ks.applyKStateDiffToRoom(spaceID, spaceDiff)
|
||||
actions.push(ks.applyKStateDiffToRoom(spaceID, spaceDiff))
|
||||
|
||||
if (tryRemoveFromOld && autocreate) {
|
||||
if (oldSpaceID) {
|
||||
if (oldSpaceID !== spaceID) {
|
||||
const oldSpaceDiff = ks.diffKState(oldSpaceKState, {
|
||||
[`m.space.child/${roomID}`]: {}
|
||||
})
|
||||
actions.push(ks.applyKStateDiffToRoom(oldSpaceID, oldSpaceDiff).then(() =>
|
||||
db.prepare("UPDATE channel_room SET parent_space_id = ? WHERE channel_id = ?").run(spaceID, channel.id)))
|
||||
}
|
||||
} else {
|
||||
db.prepare("UPDATE channel_room SET parent_space_id = ? WHERE channel_id = ?").run(spaceID, channel.id)
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.all(actions)
|
||||
}
|
||||
|
||||
async function createAllForGuild(guildID) {
|
||||
|
|
|
|||
|
|
@ -208,7 +208,7 @@ async function syncSpaceFully(guildID) {
|
|||
if (discord.channels.has(channelID)) {
|
||||
await createRoom.syncRoom(channelID)
|
||||
} else {
|
||||
await createRoom.unbridgeChannel({id: channelID}, guildID)
|
||||
await createRoom.unbridgeChannel({id: channelID}, guildID, false)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -238,7 +238,7 @@ module.exports = {
|
|||
if (!spaceID) return
|
||||
|
||||
if (data.role.id === data.guild_id) { // @everyone role changed - find a way to do this more efficiently in the future to handle many role updates
|
||||
await createSpace.syncSpaceFully(guild)
|
||||
await createSpace.syncSpaceFully(data.guild_id)
|
||||
}
|
||||
},
|
||||
|
||||
|
|
@ -288,7 +288,7 @@ module.exports = {
|
|||
if (!guildID) return // channel must have been a DM channel or something
|
||||
const roomID = select("channel_room", "room_id", {channel_id: channel.id}).pluck().get()
|
||||
if (!roomID) return // channel wasn't being bridged in the first place
|
||||
await createRoom.unbridgeChannel(channel, guildID)
|
||||
await createRoom.unbridgeChannel(channel, guildID, false)
|
||||
},
|
||||
|
||||
/**
|
||||
|
|
|
|||
81
src/db/migrations/0044-category-space.js
Normal file
81
src/db/migrations/0044-category-space.js
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
/*
|
||||
1. In auto-create spaces, all bridged rooms should be the direct child of the guild space right now. So the guild
|
||||
space's ID will be set in the `parent_space_id` column (which will be used for category subspaces after this
|
||||
migration).
|
||||
2. Do nothing for rooms in self-service spaces.
|
||||
*/
|
||||
|
||||
const DiscordTypes = require("discord-api-types/v10")
|
||||
const {discord} = require("../../passthrough")
|
||||
|
||||
const ones = "₀₁₂₃₄₅₆₇₈₉"
|
||||
const tens = "0123456789"
|
||||
|
||||
/* c8 ignore start */
|
||||
|
||||
module.exports = async function(db) {
|
||||
|
||||
/** @type {{name: string, channel_id: string, autocreate: 1 | 0, space_id: string}[]} */
|
||||
const rows = db.prepare("SELECT name, channel_id, autocreate, space_id FROM channel_room INNER JOIN guild_active USING (guild_id) INNER JOIN guild_space USING (guild_id)").all()
|
||||
|
||||
/** @type {Map<string, string>} channel or thread ID -> guild ID */
|
||||
const cache = new Map()
|
||||
|
||||
// Process channels
|
||||
process.stdout.write(` loading metadata for ${rows.length} channels/threads... `)
|
||||
for (let counter = 1; counter <= rows.length; counter++) {
|
||||
process.stdout.write(counter % 10 === 0 ? tens[(counter/10)%10] : ones[counter%10])
|
||||
const row = rows[counter-1]
|
||||
const id = row.channel_id
|
||||
if (row.autocreate === 0 || cache.has(id)) continue
|
||||
|
||||
/** @type {DiscordTypes.APIChannel} */
|
||||
let channel
|
||||
/** @type {DiscordTypes.APIChannel | null} */
|
||||
let parentChannel
|
||||
try {
|
||||
channel = await discord.snow.channel.getChannel(id)
|
||||
if (channel && channel.parent_id) parentChannel = await discord.snow.channel.getChannel(channel.parent_id)
|
||||
} catch (e) {
|
||||
cache.set(id, `failed:failed to fetch channel from Discord: ${id}`)
|
||||
continue
|
||||
}
|
||||
|
||||
let space_id = row.space_id
|
||||
|
||||
if (parentChannel?.type === DiscordTypes.ChannelType.GuildForum) {
|
||||
/** @type {{room_id: string} | undefined} */
|
||||
const forum_row = db.prepare("SELECT room_id FROM channel_room WHERE channel_id = ?").get(parentChannel.id)
|
||||
if (forum_row) {
|
||||
space_id = forum_row.room_id
|
||||
} else {
|
||||
cache.set(id, `failed:failed to get space ID of forum space for thread ${id}`)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
cache.set(id, space_id)
|
||||
}
|
||||
|
||||
// Update channels and threads
|
||||
process.stdout.write("\n")
|
||||
db.transaction(() => {
|
||||
db.prepare("ALTER TABLE channel_room ADD COLUMN parent_space_id TEXT").run()
|
||||
|
||||
// Fill in missing data
|
||||
for (const row of rows) {
|
||||
const space_id = cache.get(row.channel_id)
|
||||
if (space_id.startsWith("failed:")) {
|
||||
console.log(space_id.substring("failed:".length))
|
||||
continue
|
||||
} else if (space_id) {
|
||||
console.log(`updating channel ${row.channel_id} to space ID: ${space_id}`)
|
||||
db.prepare("UPDATE channel_room SET parent_space_id = ? WHERE channel_id = ?").run(space_id, row.channel_id)
|
||||
} else {
|
||||
console.log(`unbridging channel ${row.channel_id} because there is no guild_space row for it`)
|
||||
// db.prepare("DELETE FROM webhook WHERE channel_id = ?").run(row.channel_id)
|
||||
// db.prepare("DELETE FROM channel_room WHERE channel_id = ?").run(row.channel_id)
|
||||
}
|
||||
}
|
||||
})()
|
||||
}
|
||||
1
src/db/orm-defs.d.ts
vendored
1
src/db/orm-defs.d.ts
vendored
|
|
@ -22,6 +22,7 @@ export type Models = {
|
|||
guild_id: string
|
||||
custom_topic: number
|
||||
room_mention_role: string | null
|
||||
parent_space_id: string | null
|
||||
}
|
||||
|
||||
channel_speedbump: {
|
||||
|
|
|
|||
|
|
@ -483,7 +483,7 @@ async event => {
|
|||
if (!channelID) return
|
||||
const channel = discord.channels.get(channelID)
|
||||
if (!channel) return
|
||||
await createRoom.unbridgeChannel(channel, channel["guild_id"], "Encrypted rooms are not supported. This room was removed from the bridge.")
|
||||
await createRoom.unbridgeChannel(channel, channel["guild_id"], false, "Encrypted rooms are not supported. This room was removed from the bridge.")
|
||||
}))
|
||||
|
||||
sync.addTemporaryListener(as, "ephemeral_type:m.typing", guard("m.typing",
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@ mixin discord(channel, radio=false)
|
|||
!= icons.Icons.IconPhone
|
||||
else if channel.type === 11 || channel.type === 12
|
||||
!= icons.Icons.IconCollection
|
||||
else if channel.type === 4
|
||||
!= icons.Icons.IconCollection
|
||||
else
|
||||
include includes/hash.svg
|
||||
.s-user-card--info.ws-nowrap
|
||||
|
|
@ -288,6 +290,30 @@ block body
|
|||
!= icons.Icons.IconMerge
|
||||
= ` Link`
|
||||
|
||||
if space_id
|
||||
h3.mt32.fs-category Manually link categories
|
||||
form.d-flex.g16.ai-start(hx-post=rel("/api/link") hx-trigger="submit" hx-disabled-elt="input, button" hx-indicator="#link-button")
|
||||
.fl-grow2.s-btn-group.fd-column.w40
|
||||
each channel in unlinkedCategories
|
||||
input.s-btn--radio(type="radio" name="discord" required 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 No Discord categories available.
|
||||
.fl-grow1.s-btn-group.fd-column.w30
|
||||
each room in unlinkedSubspaces
|
||||
input.s-btn--radio(type="radio" name="matrix" required 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 No Matrix subspaces available.
|
||||
input(type="hidden" name="guild_id" value=guild_id)
|
||||
input(type="hidden" name="type" value="category")
|
||||
div
|
||||
button.s-btn.s-btn__icon.s-btn__filled#link-button
|
||||
!= icons.Icons.IconMerge
|
||||
= ` Link`
|
||||
|
||||
h3.mt32.fs-category Unlink server
|
||||
form.s-card.d-flex.gx16.ai-center(method="post" action=rel("/api/unlink-space"))
|
||||
input(type="hidden" name="guild_id" value=guild.id)
|
||||
|
|
|
|||
|
|
@ -99,6 +99,7 @@ function getChannelRoomsLinks(guild, rooms, roles) {
|
|||
let channelIDs = discord.guildChannelMap.get(guild.id)
|
||||
assert(channelIDs)
|
||||
|
||||
let linkedGuildSpaceID = select("guild_space", "space_id", {guild_id: guild.id}).pluck().get()
|
||||
let linkedChannels = select("channel_room", ["channel_id", "room_id", "name", "nick", "room_mention_role"], {channel_id: channelIDs}).all()
|
||||
let linkedChannelsWithDetails = linkedChannels.map(c => ({
|
||||
// @ts-ignore
|
||||
|
|
@ -112,6 +113,7 @@ function getChannelRoomsLinks(guild, rooms, roles) {
|
|||
let unlinkedChannelIDs = channelIDs.filter(c => !linkedChannelIDs.includes(c))
|
||||
/** @type {DiscordTypes.APIGuildChannel[]} */ // @ts-ignore
|
||||
let unlinkedChannels = unlinkedChannelIDs.map(c => discord.channels.get(c))
|
||||
let unlinkedCategories = dUtils.filterTo(unlinkedChannels, c => !c || c.type !== DiscordTypes.ChannelType.GuildCategory)
|
||||
let removedWrongTypeChannels = dUtils.filterTo(unlinkedChannels, c => c && [0, 5].includes(c.type))
|
||||
let removedPrivateChannels = dUtils.filterTo(unlinkedChannels, c => {
|
||||
const permissions = dUtils.getPermissions(guild.id, roles, guild.roles, botID, c["permission_overwrites"])
|
||||
|
|
@ -122,6 +124,7 @@ function getChannelRoomsLinks(guild, rooms, roles) {
|
|||
let linkedRoomIDs = linkedChannels.map(c => c.room_id)
|
||||
let unlinkedRooms = [...rooms]
|
||||
let removedLinkedRooms = dUtils.filterTo(unlinkedRooms, r => !linkedRoomIDs.includes(r.room_id))
|
||||
let unlinkedSubspaces = dUtils.filterTo(unlinkedRooms, r => r.room_id === linkedGuildSpaceID || r.room_type !== "m.space")
|
||||
let removedWrongTypeRooms = dUtils.filterTo(unlinkedRooms, r => !r.room_type)
|
||||
let removedEncryptedRooms = dUtils.filterTo(unlinkedRooms, r => !r.encryption && !r["im.nheko.summary.encryption"])
|
||||
// https://discord.com/developers/docs/topics/threads#active-archived-threads
|
||||
|
|
@ -129,7 +132,7 @@ function getChannelRoomsLinks(guild, rooms, roles) {
|
|||
let removedArchivedThreadRooms = dUtils.filterTo(unlinkedRooms, r => r.name && !r.name.match(/^\[(🔒)?⛓️\]/))
|
||||
|
||||
return {
|
||||
linkedChannelsWithDetails, unlinkedChannels, unlinkedRooms,
|
||||
linkedChannelsWithDetails, unlinkedChannels, unlinkedCategories, unlinkedRooms, unlinkedSubspaces,
|
||||
removedUncachedChannels, removedWrongTypeChannels, removedPrivateChannels, removedLinkedRooms, removedWrongTypeRooms, removedArchivedThreadRooms, removedEncryptedRooms
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -58,7 +58,8 @@ const schema = {
|
|||
link: z.object({
|
||||
guild_id: z.string(),
|
||||
matrix: z.string(),
|
||||
discord: z.string()
|
||||
discord: z.string(),
|
||||
type: z.enum(["category"]).optional()
|
||||
}),
|
||||
unlink: z.object({
|
||||
guild_id: z.string(),
|
||||
|
|
@ -73,8 +74,9 @@ const schema = {
|
|||
* @param {H3Event} event
|
||||
* @param {string} channel_id
|
||||
* @param {string} guild_id
|
||||
* @param {boolean} all
|
||||
*/
|
||||
async function validateAndUnbridgeChannel(event, channel_id, guild_id) {
|
||||
async function validateAndUnbridgeChannel(event, channel_id, guild_id, all) {
|
||||
const createRoom = getCreateRoom(event)
|
||||
|
||||
// Check channel is currently bridged
|
||||
|
|
@ -93,7 +95,7 @@ async function validateAndUnbridgeChannel(event, channel_id, guild_id) {
|
|||
}
|
||||
|
||||
// Do it
|
||||
await createRoom.unbridgeChannel(channel, guild_id)
|
||||
await createRoom.unbridgeChannel(channel, guild_id, all)
|
||||
}
|
||||
|
||||
as.router.post("/api/link-space", defineEventHandler(async event => {
|
||||
|
|
@ -175,21 +177,36 @@ as.router.post("/api/link", defineEventHandler(async event => {
|
|||
const row = from("channel_room").select("channel_id", "room_id").and("WHERE channel_id = ? OR room_id = ?").get(channel.id, parsedBody.matrix)
|
||||
if (row) throw createError({status: 400, message: "Bad Request", data: `Channel ID ${row.channel_id} or room ID ${parsedBody.matrix} are already bridged and cannot be reused`})
|
||||
|
||||
const channelType = parsedBody.type
|
||||
|
||||
// Check room is part of the guild's space
|
||||
let foundRoom = false
|
||||
/** @type {string[]?} */
|
||||
let foundVia = null
|
||||
/** @type {string | null} */
|
||||
let foundParentSpaceID = null
|
||||
/** @type {string[]} */
|
||||
let foundCategoryChildrenRoomIDs = []
|
||||
for await (const room of api.generateFullHierarchy(spaceID)) {
|
||||
// When finding a space during iteration, look at space's children state, because we need a `via` to join the room (when we find it later)
|
||||
for (const state of room.children_state) {
|
||||
if (state.type === "m.space.child" && state.state_key === parsedBody.matrix) {
|
||||
foundVia = state.content.via
|
||||
foundParentSpaceID = room.room_id
|
||||
}
|
||||
}
|
||||
|
||||
// When finding a room during iteration, see if it was the requested room (to confirm that the room is in the space)
|
||||
if (room.room_id === parsedBody.matrix && !room.room_type) {
|
||||
if (room.room_id === parsedBody.matrix && (!channelType && !room.room_type || channelType === "category" && room.room_type === "m.space")) {
|
||||
foundRoom = true
|
||||
|
||||
if (channelType === "category") {
|
||||
for (const state of room.children_state) {
|
||||
if (state.type === "m.space.child" && state.content.via) {
|
||||
foundCategoryChildrenRoomIDs.push(state.state_key)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (foundRoom && foundVia) break
|
||||
|
|
@ -221,13 +238,19 @@ as.router.post("/api/link", defineEventHandler(async event => {
|
|||
const avatar = await api.getStateEvent(parsedBody.matrix, "m.room.avatar", "").then(content => content.url || null).catch(() => null)
|
||||
const topic = await api.getStateEvent(parsedBody.matrix, "m.room.topic", "").then(content => content.topic || null).catch(() => null)
|
||||
db.transaction(() => {
|
||||
db.prepare("INSERT INTO channel_room (channel_id, room_id, name, guild_id, nick, custom_avatar, custom_topic) VALUES (?, ?, ?, ?, ?, ?, ?)").run(channel.id, parsedBody.matrix, channel.name, guildID, nick, avatar, topic)
|
||||
db.prepare("INSERT INTO channel_room (channel_id, room_id, name, guild_id, nick, custom_avatar, custom_topic, parent_space_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(channel.id, parsedBody.matrix, channel.name, guildID, channel.name === nick ? null : nick, avatar, topic, foundParentSpaceID)
|
||||
db.prepare("INSERT INTO historical_channel_room (reference_channel_id, room_id, upgraded_timestamp) VALUES (?, ?, 0)").run(channel.id, parsedBody.matrix)
|
||||
})()
|
||||
|
||||
// Sync room data and space child
|
||||
await createRoom.syncRoom(parsedBody.discord)
|
||||
|
||||
if (channelType === "category") {
|
||||
for (const childRoomID of foundCategoryChildrenRoomIDs) {
|
||||
db.prepare("UPDATE channel_room SET parent_space_id = ? WHERE room_id = ?").run(parsedBody.matrix, childRoomID)
|
||||
}
|
||||
}
|
||||
|
||||
// Send a notification in the room
|
||||
if (channel.type === DiscordTypes.ChannelType.GuildText) {
|
||||
await api.sendEvent(parsedBody.matrix, "m.room.message", {
|
||||
|
|
@ -252,7 +275,7 @@ as.router.post("/api/unlink", defineEventHandler(async event => {
|
|||
const guild = discord.guilds.get(guild_id)
|
||||
if (!guild) throw createError({status: 400, message: "Bad Request", data: "Discord guild does not exist or bot has not joined it"})
|
||||
|
||||
await validateAndUnbridgeChannel(event, channel_id, guild_id)
|
||||
await validateAndUnbridgeChannel(event, channel_id, guild_id, false)
|
||||
|
||||
setResponseHeader(event, "HX-Refresh", "true")
|
||||
return null // 204
|
||||
|
|
@ -283,7 +306,7 @@ as.router.post("/api/unlink-space", defineEventHandler(async event => {
|
|||
// Unlink all rooms
|
||||
const linkedChannels = select("channel_room", ["channel_id", "room_id", "name", "nick"], {guild_id: guild_id}).all()
|
||||
for (const channel of linkedChannels) {
|
||||
await validateAndUnbridgeChannel(event, channel.channel_id, guild_id)
|
||||
await validateAndUnbridgeChannel(event, channel.channel_id, guild_id, true)
|
||||
}
|
||||
|
||||
// Verify all rooms were unlinked
|
||||
|
|
|
|||
|
|
@ -666,9 +666,10 @@ test("web unlink room: successfully calls unbridgeChannel when the channel does
|
|||
guild_id: "665289423482519565"
|
||||
},
|
||||
createRoom: {
|
||||
async unbridgeChannel(channel) {
|
||||
async unbridgeChannel(channel, guildID, all) {
|
||||
called++
|
||||
t.equal(channel.id, "665310973967597573")
|
||||
t.equal(all, false)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
|
@ -686,9 +687,10 @@ test("web unlink room: successfully calls unbridgeChannel when the channel does
|
|||
guild_id: "112760669178241024"
|
||||
},
|
||||
createRoom: {
|
||||
async unbridgeChannel(channel) {
|
||||
async unbridgeChannel(channel, guildID, all) {
|
||||
called++
|
||||
t.equal(channel.id, "489237891895768942")
|
||||
t.equal(all, false)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
|
@ -766,10 +768,11 @@ test("web unlink space: correctly abort unlinking if some linked channels remain
|
|||
guild_id: "665289423482519565",
|
||||
},
|
||||
createRoom: {
|
||||
async unbridgeChannel(channel, guildID) {
|
||||
async unbridgeChannel(channel, guildID, all) {
|
||||
unbridgedChannel = true
|
||||
t.ok(["1438284564815548418", "665310973967597573"].includes(channel.id))
|
||||
t.equal(guildID, "665289423482519565")
|
||||
t.equal(all, true)
|
||||
// Do not actually delete the link from DB, should trigger error later in check
|
||||
}
|
||||
},
|
||||
|
|
@ -811,10 +814,11 @@ test("web unlink space: successfully calls unbridgeChannel on linked channels in
|
|||
guild_id: "665289423482519565",
|
||||
},
|
||||
createRoom: {
|
||||
async unbridgeChannel(channel, guildID) {
|
||||
async unbridgeChannel(channel, guildID, all) {
|
||||
unbridgedChannel = true
|
||||
t.ok(["1438284564815548418", "665310973967597573"].includes(channel.id))
|
||||
t.equal(guildID, "665289423482519565")
|
||||
t.equal(all, true)
|
||||
|
||||
// In order to not simulate channel deletion and not trigger the post unlink channels, pre-unlink space check
|
||||
db.prepare("DELETE FROM channel_room WHERE channel_id = ?").run(channel.id)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue