d2m username colors #107
7 changed files with 95 additions and 40 deletions
|
|
@ -364,8 +364,8 @@ function defineEchoHandler() {
|
||||||
|
|
||||||
// set profile data on homeserver...
|
// 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.)")
|
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.setProfileKey(mxid, "displayname", "Out Of Your Element (bot)", "all")
|
||||||
await api.profileSetAvatarUrl(mxid, avatarUrl)
|
await api.setProfileKey(mxid, "avatar_url", avatarUrl, "all")
|
||||||
console.log("✅ Matrix profile updated...")
|
console.log("✅ Matrix profile updated...")
|
||||||
|
|
||||||
console.log("Good to go. I hope you enjoy Out Of Your Element.")
|
console.log("Good to go. I hope you enjoy Out Of Your Element.")
|
||||||
|
|
|
||||||
|
|
@ -162,7 +162,7 @@ async function syncUser(messageID, author, roomID, shouldActuallySync) {
|
||||||
if (shouldActuallySync) {
|
if (shouldActuallySync) {
|
||||||
// Build current profile data and sync if the hash has changed
|
// Build current profile data and sync if the hash has changed
|
||||||
const content = await memberToStateContent(pkMessage, author)
|
const content = await memberToStateContent(pkMessage, author)
|
||||||
await registerUser._sendSyncUser(roomID, mxid, content, null)
|
await registerUser._sendSyncUser(roomID, mxid, null, content, null)
|
||||||
}
|
}
|
||||||
|
|
||||||
return mxid
|
return mxid
|
||||||
|
|
|
||||||
|
|
@ -162,7 +162,7 @@ async function syncUser(channelID, messageID, author, roomID, shouldActuallySync
|
||||||
if (shouldActuallySync) {
|
if (shouldActuallySync) {
|
||||||
// Build current profile data and sync if the hash has changed
|
// Build current profile data and sync if the hash has changed
|
||||||
const content = await memberToStateContent(pluRalMessage, author)
|
const content = await memberToStateContent(pluRalMessage, author)
|
||||||
await registerUser._sendSyncUser(roomID, mxid, content, null)
|
await registerUser._sendSyncUser(roomID, mxid, null, content, null)
|
||||||
}
|
}
|
||||||
|
|
||||||
return mxid
|
return mxid
|
||||||
|
|
|
||||||
|
|
@ -24,8 +24,6 @@ let hasher = null
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
require("xxhash-wasm")().then(h => hasher = h)
|
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.
|
* A sim is an account that is being simulated by the bridge to copy events from the other side.
|
||||||
* @param {DiscordTypes.APIUser} user
|
* @param {DiscordTypes.APIUser} user
|
||||||
|
|
@ -107,16 +105,24 @@ async function userToGlobalProfile(user) {
|
||||||
globalProfile.avatar_url = await file.uploadDiscordFileToMxc(avatarPath)
|
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
|
return globalProfile
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {DiscordTypes.APIUser} user
|
* @param {DiscordTypes.APIUser} user
|
||||||
* @param {Omit<DiscordTypes.APIGuildMember, "user"> | undefined} member
|
* @param {Omit<DiscordTypes.APIGuildMember, "user"> | undefined} member
|
||||||
* @param {string} guildID
|
* @param {DiscordTypes.APIGuild} guild
|
||||||
* @returns {Promise<Ty.Event.M_Room_Member>}
|
* @returns {Promise<Ty.Event.M_Room_Member & {"eu.she-a.color"?: {on_light: string, on_dark: string}}>}
|
||||||
*/
|
*/
|
||||||
async function memberToStateContent(user, member, guildID) {
|
async function memberToStateContent(user, member, guild) {
|
||||||
let displayname = user.username
|
let displayname = user.username
|
||||||
if (user.global_name) displayname = user.global_name
|
if (user.global_name) displayname = user.global_name
|
||||||
if (member?.nick) displayname = member.nick
|
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.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) {
|
if (avatarPath) {
|
||||||
content["moe.cadence.ooye.member"].avatar = avatarPath
|
content["moe.cadence.ooye.member"].avatar = avatarPath
|
||||||
content.avatar_url = await file.uploadDiscordFileToMxc(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
|
return content
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -221,12 +236,12 @@ function _hashProfileContent(content, powerLevel) {
|
||||||
*/
|
*/
|
||||||
async function syncUser(user, member, channel, guild, roomID, interactionMetadata) {
|
async function syncUser(user, member, channel, guild, roomID, interactionMetadata) {
|
||||||
const mxid = await ensureSimJoined(user, roomID)
|
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)
|
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
|
// 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,
|
allowOverwrite: !!member,
|
||||||
globalProfile: await userToGlobalProfile(user)
|
updateGlobalProfile: true,
|
||||||
})
|
})
|
||||||
|
|
||||||
const appInstalledByUser = user.bot && interactionMetadata?.authorizing_integration_owners?.[DiscordTypes.ApplicationIntegrationType.UserInstall]
|
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} roomID
|
||||||
* @param {string} mxid
|
* @param {string} mxid
|
||||||
* @param {{displayname: string, avatar_url?: string}} content
|
* @param {DiscordTypes.APIUser | null} user
|
||||||
|
* @param {Awaited<ReturnType<memberToStateContent>>} content
|
||||||
* @param {number | null} powerLevel
|
* @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 currentHash = _hashProfileContent(content, powerLevel ?? 0)
|
||||||
const existingHash = select("sim_member", "hashed_profile_content", {room_id: roomID, mxid}).safeIntegers().pluck().get()
|
const existingHash = select("sim_member", "hashed_profile_content", {room_id: roomID, mxid}).safeIntegers().pluck().get()
|
||||||
// console.log(roomID, mxid, existingHash, currentHash)
|
// console.log(roomID, mxid, existingHash, currentHash)
|
||||||
|
|
@ -260,10 +276,27 @@ async function _sendSyncUser(roomID, mxid, content, powerLevel, options) {
|
||||||
if (powerLevel != null) {
|
if (powerLevel != null) {
|
||||||
actions.push(mxUtils.setUserPower(roomID, mxid, powerLevel, api))
|
actions.push(mxUtils.setUserPower(roomID, mxid, powerLevel, api))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update global profile (if supported by server)
|
// Update global profile (if supported by server)
|
||||||
if (await supportsMsc4069) {
|
const support = await api.mscSupport
|
||||||
actions.push(api.profileSetDisplayname(mxid, options?.globalProfile?.displayname || content.displayname, true))
|
if (user && options?.updateGlobalProfile && (support.msc4069 || support.msc4466)) {
|
||||||
actions.push(api.profileSetAvatarUrl(mxid, options?.globalProfile?.avatar_url || content.avatar_url, true))
|
// 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)
|
await Promise.all(actions)
|
||||||
// Update cached hash
|
// Update cached hash
|
||||||
|
|
@ -308,4 +341,3 @@ module.exports.syncUser = syncUser
|
||||||
module.exports._sendSyncUser = _sendSyncUser
|
module.exports._sendSyncUser = _sendSyncUser
|
||||||
module.exports.syncAllUsersInRoom = syncAllUsersInRoom
|
module.exports.syncAllUsersInRoom = syncAllUsersInRoom
|
||||||
module.exports._memberToPowerLevel = memberToPowerLevel
|
module.exports._memberToPowerLevel = memberToPowerLevel
|
||||||
module.exports.supportsMsc4069 = supportsMsc4069
|
|
||||||
|
|
|
||||||
|
|
@ -121,7 +121,7 @@ async function syncUser(author, roomID, shouldActuallySync) {
|
||||||
if (shouldActuallySync) {
|
if (shouldActuallySync) {
|
||||||
// Build current profile data and sync if the hash has changed
|
// Build current profile data and sync if the hash has changed
|
||||||
const content = await authorToStateContent(author)
|
const content = await authorToStateContent(author)
|
||||||
await registerUser._sendSyncUser(roomID, mxid, content, null)
|
await registerUser._sendSyncUser(roomID, mxid, null, content, null)
|
||||||
}
|
}
|
||||||
|
|
||||||
return mxid
|
return mxid
|
||||||
|
|
|
||||||
|
|
@ -93,6 +93,10 @@ async function onPacket(client, message, listen) {
|
||||||
client.channels.set(thread.id, thread)
|
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") {
|
if (listen === "full") {
|
||||||
try {
|
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.
|
// 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.
|
// Role doesn't already exist.
|
||||||
guild.roles.push(...newRoles)
|
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") {
|
} else if (message.t === "GUILD_MEMBER_UPDATE") {
|
||||||
|
|
|
||||||
|
|
@ -421,32 +421,35 @@ async function sendTyping(roomID, isTyping, mxid, duration) {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {string} mxid
|
* @param {string} mxid
|
||||||
* @param {string} displayname
|
* @param {string} key
|
||||||
* @param {boolean} [inhibitPropagate]
|
* @param {object} content
|
||||||
|
* @param {"none" | "unchanged" | "all"} [propagateTo]
|
||||||
*/
|
*/
|
||||||
async function profileSetDisplayname(mxid, displayname, inhibitPropagate) {
|
async function setProfileKey(mxid, key, content, propagateTo) {
|
||||||
const params = {}
|
const params = {}
|
||||||
if (inhibitPropagate) params["org.matrix.msc4069.propagate"] = false
|
if (key === "displayname" || key === "avatar_url") {
|
||||||
await mreq.mreq("PUT", path(route`/client/v3/profile/${mxid}/displayname`, mxid, params), {
|
const support = await mscSupport
|
||||||
displayname
|
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} mxid
|
||||||
* @param {string | null | undefined} avatar_url
|
* @param {string} key
|
||||||
* @param {boolean} [inhibitPropagate]
|
* @param {"none" | "unchanged" | "all"} [propagateTo]
|
||||||
*/
|
*/
|
||||||
async function profileSetAvatarUrl(mxid, avatar_url, inhibitPropagate) {
|
async function deleteProfileKey(mxid, key, propagateTo) {
|
||||||
const params = {}
|
const params = {}
|
||||||
if (inhibitPropagate) params["org.matrix.msc4069.propagate"] = false
|
if (key === "displayname" || key === "avatar_url") {
|
||||||
if (avatar_url) {
|
const support = await mscSupport
|
||||||
await mreq.mreq("PUT", path(route`/client/v3/profile/${mxid}/avatar_url`, mxid, params), {
|
if (support["msc4466"]) { params["computer.gingershaped.msc4466.propagate_to"] = propagateTo ?? "none" }
|
||||||
avatar_url
|
if (propagateTo !== "all" && support["msc4069"]) { params["org.matrix.msc4069.propagate"] = false }
|
||||||
})
|
|
||||||
} else {
|
|
||||||
await mreq.mreq("DELETE", path(route`/client/v3/profile/${mxid}/avatar_url`, mxid, params))
|
|
||||||
}
|
}
|
||||||
|
await mreq.mreq("DELETE", path(route`/client/v3/profile/${mxid}/${key}`, mxid, params))
|
||||||
}
|
}
|
||||||
|
|
||||||
async function ping() {
|
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))
|
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<typeof this.cache>) => 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
|
* @param {string} url
|
||||||
|
|
@ -671,10 +687,11 @@ module.exports.sendState = sendState
|
||||||
module.exports.sendEvent = sendEvent
|
module.exports.sendEvent = sendEvent
|
||||||
module.exports.redactEvent = redactEvent
|
module.exports.redactEvent = redactEvent
|
||||||
module.exports.sendTyping = sendTyping
|
module.exports.sendTyping = sendTyping
|
||||||
module.exports.profileSetDisplayname = profileSetDisplayname
|
module.exports.setProfileKey = setProfileKey
|
||||||
module.exports.profileSetAvatarUrl = profileSetAvatarUrl
|
module.exports.deleteProfileKey = deleteProfileKey
|
||||||
module.exports.ping = ping
|
module.exports.ping = ping
|
||||||
module.exports.previewUrlIfEnabled = previewUrlIfEnabled
|
module.exports.previewUrlIfEnabled = previewUrlIfEnabled
|
||||||
|
module.exports.mscSupport = mscSupport
|
||||||
module.exports.getMedia = getMedia
|
module.exports.getMedia = getMedia
|
||||||
module.exports.sendReadReceipt = sendReadReceipt
|
module.exports.sendReadReceipt = sendReadReceipt
|
||||||
module.exports.ackEvent = ackEvent
|
module.exports.ackEvent = ackEvent
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue