diff --git a/scripts/setup.js b/scripts/setup.js index 191ca3e..3969705 100644 --- a/scripts/setup.js +++ b/scripts/setup.js @@ -364,8 +364,8 @@ function defineEchoHandler() { // set profile data on homeserver... console.log("⏩ Updating Matrix profile... (If you've joined lots of rooms, this is slow. Please allow at least 30 seconds.)") - await api.profileSetDisplayname(mxid, "Out Of Your Element (bot)") - await api.profileSetAvatarUrl(mxid, avatarUrl) + await api.setProfileKey(mxid, "displayname", "Out Of Your Element (bot)", "all") + await api.setProfileKey(mxid, "avatar_url", avatarUrl, "all") console.log("✅ Matrix profile updated...") console.log("Good to go. I hope you enjoy Out Of Your Element.") diff --git a/src/d2m/actions/register-pk-user.js b/src/d2m/actions/register-pk-user.js index d127f21..5af41c6 100644 --- a/src/d2m/actions/register-pk-user.js +++ b/src/d2m/actions/register-pk-user.js @@ -162,7 +162,7 @@ async function syncUser(messageID, author, roomID, shouldActuallySync) { if (shouldActuallySync) { // Build current profile data and sync if the hash has changed const content = await memberToStateContent(pkMessage, author) - await registerUser._sendSyncUser(roomID, mxid, content, null) + await registerUser._sendSyncUser(roomID, mxid, null, content, null) } return mxid diff --git a/src/d2m/actions/register-plu-ral-user.js b/src/d2m/actions/register-plu-ral-user.js index 5830ce8..2433daf 100644 --- a/src/d2m/actions/register-plu-ral-user.js +++ b/src/d2m/actions/register-plu-ral-user.js @@ -162,7 +162,7 @@ async function syncUser(channelID, messageID, author, roomID, shouldActuallySync if (shouldActuallySync) { // Build current profile data and sync if the hash has changed const content = await memberToStateContent(pluRalMessage, author) - await registerUser._sendSyncUser(roomID, mxid, content, null) + await registerUser._sendSyncUser(roomID, mxid, null, content, null) } return mxid diff --git a/src/d2m/actions/register-user.js b/src/d2m/actions/register-user.js index db04c8e..67c58de 100644 --- a/src/d2m/actions/register-user.js +++ b/src/d2m/actions/register-user.js @@ -24,8 +24,6 @@ let hasher = null // @ts-ignore require("xxhash-wasm")().then(h => hasher = h) -const supportsMsc4069 = api.versions().then(v => !!v?.unstable_features?.["org.matrix.msc4069"]).catch(() => false) - /** * A sim is an account that is being simulated by the bridge to copy events from the other side. * @param {DiscordTypes.APIUser} user @@ -107,16 +105,24 @@ async function userToGlobalProfile(user) { globalProfile.avatar_url = await file.uploadDiscordFileToMxc(avatarPath) } + if (user.accent_color !== null && user.accent_color !== undefined) { + const encoded = `#${user.accent_color.toString(16).padStart(6, "0")}` + globalProfile["eu.she-a.color"] = { + on_light: encoded, + on_dark: encoded + } + } + return globalProfile } /** * @param {DiscordTypes.APIUser} user * @param {Omit | undefined} member - * @param {string} guildID - * @returns {Promise} + * @param {DiscordTypes.APIGuild} guild + * @returns {Promise} */ -async function memberToStateContent(user, member, guildID) { +async function memberToStateContent(user, member, guild) { let displayname = user.username if (user.global_name) displayname = user.global_name if (member?.nick) displayname = member.nick @@ -135,12 +141,21 @@ async function memberToStateContent(user, member, guildID) { } // const avatarPath = file.userAvatar(user) // the user avatar only - const avatarPath = file.memberAvatar(guildID, user, member) // the member avatar or the user avatar + const avatarPath = file.memberAvatar(guild.id, user, member) // the member avatar or the user avatar if (avatarPath) { content["moe.cadence.ooye.member"].avatar = avatarPath content.avatar_url = await file.uploadDiscordFileToMxc(avatarPath) } + const colorRole = member ? guild.roles.find(role => role.colors.primary_color && member.roles.includes(role.id)) : undefined + if (colorRole) { + const encoded = `#${colorRole.colors.primary_color.toString(16).padStart(6, "0")}` + content["eu.she-a.color"] = { + "on_dark": encoded, + "on_light": encoded + } + } + return content } @@ -221,12 +236,12 @@ function _hashProfileContent(content, powerLevel) { */ async function syncUser(user, member, channel, guild, roomID, interactionMetadata) { const mxid = await ensureSimJoined(user, roomID) - const content = await memberToStateContent(user, member, guild.id) + const content = await memberToStateContent(user, member, guild) const powerLevel = memberToPowerLevel(user, member, guild, channel) - await _sendSyncUser(roomID, mxid, content, powerLevel, { + await _sendSyncUser(roomID, mxid, user, content, powerLevel, { // do not overwrite pre-existing data if we already have data and `member` is not accessible, because this would replace good data with bad data allowOverwrite: !!member, - globalProfile: await userToGlobalProfile(user) + updateGlobalProfile: true, }) const appInstalledByUser = user.bot && interactionMetadata?.authorizing_integration_owners?.[DiscordTypes.ApplicationIntegrationType.UserInstall] @@ -240,11 +255,12 @@ async function syncUser(user, member, channel, guild, roomID, interactionMetadat /** * @param {string} roomID * @param {string} mxid - * @param {{displayname: string, avatar_url?: string}} content + * @param {DiscordTypes.APIUser | null} user + * @param {Awaited>} content * @param {number | null} powerLevel - * @param {{allowOverwrite?: boolean, globalProfile?: {displayname: string, avatar_url?: string}}} [options] + * @param {{allowOverwrite?: boolean, updateGlobalProfile?: boolean}} [options] */ -async function _sendSyncUser(roomID, mxid, content, powerLevel, options) { +async function _sendSyncUser(roomID, mxid, user, content, powerLevel, options) { const currentHash = _hashProfileContent(content, powerLevel ?? 0) const existingHash = select("sim_member", "hashed_profile_content", {room_id: roomID, mxid}).safeIntegers().pluck().get() // console.log(roomID, mxid, existingHash, currentHash) @@ -260,10 +276,27 @@ async function _sendSyncUser(roomID, mxid, content, powerLevel, options) { if (powerLevel != null) { actions.push(mxUtils.setUserPower(roomID, mxid, powerLevel, api)) } + // Update global profile (if supported by server) - if (await supportsMsc4069) { - actions.push(api.profileSetDisplayname(mxid, options?.globalProfile?.displayname || content.displayname, true)) - actions.push(api.profileSetAvatarUrl(mxid, options?.globalProfile?.avatar_url || content.avatar_url, true)) + const support = await api.mscSupport + if (user && options?.updateGlobalProfile && (support.msc4069 || support.msc4466)) { + // When the user has a role color, don't update the profile accent color because it won't change the message's appearance. + // Since user.accent_color is (currently) the only thing the full profile is needed for, skip the API call in that case. + const needFullProfile = !content["eu.she-a.color"] + const globalProfile = await (needFullProfile ? discord.snow.user.getUser(user.id) : Promise.resolve(user)) + .then(userToGlobalProfile).catch(e => ({})) + for (const key of Object.keys(globalProfile)) { + actions.push(api.setProfileKey(mxid, key, globalProfile[key], "none")) + } + if (needFullProfile) { + // don't delete keys if some profile fields from Discord might be missing + const oldProfile = await api.getProfile(mxid).catch(e => ({})) + for (const key of Object.keys(oldProfile)) { + if (!globalProfile[key]) { + actions.push(api.deleteProfileKey(mxid, key, "none")) + } + } + } } await Promise.all(actions) // Update cached hash @@ -308,4 +341,3 @@ module.exports.syncUser = syncUser module.exports._sendSyncUser = _sendSyncUser module.exports.syncAllUsersInRoom = syncAllUsersInRoom module.exports._memberToPowerLevel = memberToPowerLevel -module.exports.supportsMsc4069 = supportsMsc4069 diff --git a/src/d2m/actions/register-webhook-user.js b/src/d2m/actions/register-webhook-user.js index 4dc3c3f..36bc0ea 100644 --- a/src/d2m/actions/register-webhook-user.js +++ b/src/d2m/actions/register-webhook-user.js @@ -121,7 +121,7 @@ async function syncUser(author, roomID, shouldActuallySync) { if (shouldActuallySync) { // Build current profile data and sync if the hash has changed const content = await authorToStateContent(author) - await registerUser._sendSyncUser(roomID, mxid, content, null) + await registerUser._sendSyncUser(roomID, mxid, null, content, null) } return mxid diff --git a/src/d2m/discord-packets.js b/src/d2m/discord-packets.js index 8317e0c..006a91a 100644 --- a/src/d2m/discord-packets.js +++ b/src/d2m/discord-packets.js @@ -93,6 +93,10 @@ async function onPacket(client, message, listen) { client.channels.set(thread.id, thread) } + for (const guild of client.guilds.values()) { + guild.roles.sort((a, b) => b.position - a.position) + } + if (listen === "full") { try { // Wait for guilds to be connected and homeserver to be online. If this is the last guild, a different code path is used to trigger the homeserver check. @@ -156,6 +160,8 @@ async function onPacket(client, message, listen) { // Role doesn't already exist. guild.roles.push(...newRoles) } + // lower position values mean lower priority (`@everyone` has position 0) + guild.roles.sort((a, b) => b.position - a.position) } } else if (message.t === "GUILD_MEMBER_UPDATE") { diff --git a/src/matrix/api.js b/src/matrix/api.js index 9b667fc..6813454 100644 --- a/src/matrix/api.js +++ b/src/matrix/api.js @@ -421,32 +421,35 @@ async function sendTyping(roomID, isTyping, mxid, duration) { /** * @param {string} mxid - * @param {string} displayname - * @param {boolean} [inhibitPropagate] + * @param {string} key + * @param {object} content + * @param {"none" | "unchanged" | "all"} [propagateTo] */ -async function profileSetDisplayname(mxid, displayname, inhibitPropagate) { +async function setProfileKey(mxid, key, content, propagateTo) { const params = {} - if (inhibitPropagate) params["org.matrix.msc4069.propagate"] = false - await mreq.mreq("PUT", path(route`/client/v3/profile/${mxid}/displayname`, mxid, params), { - displayname - }) + if (key === "displayname" || key === "avatar_url") { + const support = await mscSupport + if (support["msc4466"]) { params["computer.gingershaped.msc4466.propagate_to"] = propagateTo ?? "none" } + if (propagateTo !== "all" && support["msc4069"]) { params["org.matrix.msc4069.propagate"] = false } + } + const body = {} + body[key] = content + await mreq.mreq("PUT", path(route`/client/v3/profile/${mxid}/${key}`, mxid, params), body) } /** * @param {string} mxid - * @param {string | null | undefined} avatar_url - * @param {boolean} [inhibitPropagate] + * @param {string} key + * @param {"none" | "unchanged" | "all"} [propagateTo] */ -async function profileSetAvatarUrl(mxid, avatar_url, inhibitPropagate) { +async function deleteProfileKey(mxid, key, propagateTo) { const params = {} - if (inhibitPropagate) params["org.matrix.msc4069.propagate"] = false - if (avatar_url) { - await mreq.mreq("PUT", path(route`/client/v3/profile/${mxid}/avatar_url`, mxid, params), { - avatar_url - }) - } else { - await mreq.mreq("DELETE", path(route`/client/v3/profile/${mxid}/avatar_url`, mxid, params)) + if (key === "displayname" || key === "avatar_url") { + const support = await mscSupport + if (support["msc4466"]) { params["computer.gingershaped.msc4466.propagate_to"] = propagateTo ?? "none" } + if (propagateTo !== "all" && support["msc4069"]) { params["org.matrix.msc4069.propagate"] = false } } + await mreq.mreq("DELETE", path(route`/client/v3/profile/${mxid}/${key}`, mxid, params)) } async function ping() { @@ -475,6 +478,19 @@ const urlPreviewEnabled = sync.remember(() => ({ fulfilled(this.cache ??= capabilities().then(c => c.capabilities?.["io.element.msc4452.preview_url"]?.enabled)) } })) +const mscSupport = sync.remember(() => ({ + /** @type {Promise<{"msc4069": boolean, "msc4466": boolean}>?} */ + cache: null, + then(/** @type {(_: NonNullable) => any} */ fulfilled) { + fulfilled(this.cache ??= versions().then(v => ({ + msc4069: !!v?.unstable_features?.["org.matrix.msc4069"], + msc4466: !!v?.unstable_features?.["computer.gingershaped.msc4466"], + })).catch(() => ({ + msc4069: false, + msc4466: false, + }))) + } +})) /** * @param {string} url @@ -671,10 +687,11 @@ module.exports.sendState = sendState module.exports.sendEvent = sendEvent module.exports.redactEvent = redactEvent module.exports.sendTyping = sendTyping -module.exports.profileSetDisplayname = profileSetDisplayname -module.exports.profileSetAvatarUrl = profileSetAvatarUrl +module.exports.setProfileKey = setProfileKey +module.exports.deleteProfileKey = deleteProfileKey module.exports.ping = ping module.exports.previewUrlIfEnabled = previewUrlIfEnabled +module.exports.mscSupport = mscSupport module.exports.getMedia = getMedia module.exports.sendReadReceipt = sendReadReceipt module.exports.ackEvent = ackEvent