category subspaces #113

Open
mschae wants to merge 9 commits from mschae/out-of-your-element:category-subspaces into main
3 changed files with 187 additions and 27 deletions
Showing only changes of commit f156b18b1c - Show all commits

bridge category as subspace

mschae23 2026-11-18 00:18:18 +01:00
Signed by untrusted user: mschae
GPG key ID: A87721D300DE88AB

View file

@ -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,34 @@ 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
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 +109,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 +171,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 everyoneCanCreatePolls = dUtils.hasPermission(everyonePermissions, DiscordTypes.PermissionFlagsBits.SendPolls)
if (everyoneCanSend && !everyoneCanCreatePolls) pollStartPowerLevel["org.matrix.msc3381.poll.start"] = 10
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) eventPowerLevels["org.matrix.msc3381.poll.start"] = 10
}
const spacePowerDetails = await mUtils.getEffectivePower(guildSpaceID, [], di.api)
spacePowerDetails.powerLevels.users ??= {}
@ -143,7 +197,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 +215,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 +254,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 +302,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 +311,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 +485,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
@ -549,9 +599,10 @@ async function unbridgeChannel(channel, guildID, messageBeforeLeave = "This room
* @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()
@ -559,6 +610,15 @@ async function _syncSpaceMember(channel, spaceID, roomID, guild_id) {
return []
}
let oldSpaceID
let oldSpaceKState
if (tryRemoveFromOld) {
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)
let spaceEventContent = {}
if (
@ -572,10 +632,28 @@ async function _syncSpaceMember(channel, spaceID, roomID, guild_id) {
via: [reg.ooye.server_name]
}
}
const actions = []
const spaceDiff = ks.diffKState(spaceKState, {
[`m.space.child/${roomID}`]: spaceEventContent
})
return ks.applyKStateDiffToRoom(spaceID, spaceDiff)
actions.push(ks.applyKStateDiffToRoom(spaceID, spaceDiff))
if (tryRemoveFromOld) {
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) {

View 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)
}
}
})()
}

View file

@ -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: {