add per message profile management commands and functionality

This commit is contained in:
Rye committed 2026-03-16 18:44:41 +01:00
1 parent ed689792ee
commit 2a83578ad7
2 files changed
+162

No files matched your search

+81
View File
@@ -35,6 +35,12 @@ import { parsePronounsInput } from '$utils/pronouns';
import { useRoomNavigate } from './useRoomNavigate';
import { enrichWidgetUrl } from './useRoomWidgets';
import { useUserProfile } from './useUserProfile';
import {
addOrUpdatePerMessageProfile,
deletePerMessageProfile,
PerMessageProfile,
setCurrentlyUsedPerMessageProfileIdForRoom,
} from './usePerMessageProfile';
export const SHRUG = '¯\\_(ツ)_/¯';
export const TABLEFLIP = '(╯°□°)╯︵ ┻━┻';
@@ -232,6 +238,9 @@ export enum Command {
Font = 'font',
SFont = 'sfont',
AddWidget = 'addwidget',
AddPerMessageProfileToAccount = 'addpmp',
DeletePerMessageProfileFromAccount = 'delpmp',
UsePerMessageProfile = 'usepmp',
Pronoun = 'pronoun',
SPronoun = 'spronoun',
Rainbow = 'rainbow',
@@ -471,6 +480,78 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
);
},
},
[Command.AddPerMessageProfileToAccount]: {
name: Command.AddPerMessageProfileToAccount,
description:
'Add or update a per message profile to your account. Example: /addpmp profileId name=Profile Name avatarUrl=mxc://xyzabc',
exe: async (payload) => {
const [profileId, ...profileParts] = splitWithSpace(payload);
if (profileId === 'index') {
// "index" is reserved for the profile index, reject it as a profile id
return;
}
const pmp: PerMessageProfile = {
id: profileId,
name: profileParts.find((p) => p.startsWith('name='))?.substring(5) || '',
avatarUrl: profileParts.find((p) => p.startsWith('avatarUrl='))?.substring(10),
};
await addOrUpdatePerMessageProfile(mx, pmp);
},
},
[Command.DeletePerMessageProfileFromAccount]: {
name: Command.DeletePerMessageProfileFromAccount,
description: 'Delete a per message profile from your account. Example: /delpmp profileId',
exe: async (payload) => {
const [profileId] = splitWithSpace(payload);
if (profileId === 'index') {
// "index" is reserved for the profile index, reject it as a profile id
return;
}
await deletePerMessageProfile(mx, profileId);
},
},
[Command.UsePerMessageProfile]: {
name: Command.UsePerMessageProfile,
description:
'Use a per message profile for this room once, or until reset. Example: /usepmp profileId [once,reset,or duration like 1h30m]',
exe: async (payload) => {
// this command doesn't need to do anything, the composer will pick it up and apply the profile to the message being composed
const profileId: string = splitWithSpace(payload)[0];
const durationStr: string | undefined = splitWithSpace(payload)[1];
let validUntil: number | undefined;
const sendFeedback = (msg: string) => {
const localNotice = new MatrixEvent({
type: 'm.room.message',
content: { msgtype: 'm.notice', body: msg },
event_id: `~nullptr-widget-${Date.now()}`,
room_id: room.roomId,
sender: mx.getSafeUserId(),
});
(room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
};
if (durationStr === 'reset') {
setCurrentlyUsedPerMessageProfileIdForRoom(mx, room.roomId, undefined, undefined, true)
.then(() => {
sendFeedback('Per message profile reset for this room.');
})
.catch(() => {
sendFeedback('Failed to reset per message profile for this room.');
});
return;
}
await setCurrentlyUsedPerMessageProfileIdForRoom(mx, room.roomId, profileId, validUntil)
.then(() => {
sendFeedback(
`Per message profile "${profileId}" will be used for messages in this room for the until ${
durationStr ?? 'reset'
}.`
);
})
.catch(() => {
sendFeedback('Failed to set per message profile for this room.');
});
},
},
[Command.MyRoomAvatar]: {
name: Command.MyRoomAvatar,
description: 'Change profile picture in current room. Example /myroomavatar mxc://xyzabc',
+81
View File
@@ -27,6 +27,23 @@ type PerMessageProfileIndex = {
profileIds: string[];
};
type PerMessageProfileRoomAssociation = {
/**
* the id of the profile to use for messages in this room. This is used to apply a profile to all messages in a room without having to set the profile for each message individually.
*/
profileId: string;
/**
* the id of the room this association applies to.
* This is used to apply a profile to all messages in a room without having to set the profile for each message individually.
*/
roomId: string;
validUntil?: number; // timestamp in ms until which this association is valid, after which it should be ignored and removed. If not set, the association is valid indefinitely until changed or removed.
};
type PerMessageProfileRoomAssociationWrapper = {
associations: PerMessageProfileRoomAssociation[];
};
export function getPerMessageProfileById(
mx: MatrixClient,
id: string
@@ -63,3 +80,67 @@ export function addOrUpdatePerMessageProfile(mx: MatrixClient, profile: PerMessa
export function deletePerMessageProfile(mx: MatrixClient, id: string) {
return mx.setAccountData(`fyi.cisnt.permessageprofile.${id}` as any, {});
}
/**
* gets the per message profile to be used for messages in a room
* @param mx matrix client
* @param roomId the room id you are querying for
* @returns the profile to be used
*/
export function getCurrentlyUsedPerMessageProfileIdForRoom(
mx: MatrixClient,
roomId: string
): PerMessageProfile | undefined {
const accountData = mx.getAccountData(`fyi.cisnt.permessageprofile.roomassociation` as any);
const content = accountData?.getContent()?.associations as
| PerMessageProfileRoomAssociation[]
| undefined;
if (!Array.isArray(content)) {
// If content is not an array, return undefined
return undefined;
}
const profileId = content
.filter(
(assoc: PerMessageProfileRoomAssociation) =>
!assoc.validUntil || assoc.validUntil > Date.now()
)
.find((assoc: PerMessageProfileRoomAssociation) => assoc.roomId === roomId)?.profileId;
console.warn('getCurrentlyUsedPerMessageProfileIdForRoom', { profileId, roomId });
return profileId ? getPerMessageProfileById(mx, profileId) : undefined;
}
/**
* sets the per message profile to be used for messages in a room. This is done by setting account data with a list of room associations, which is then checked when sending a message to apply the profile to the message if the room matches an association. The associations can also have an optional expiration time, after which they will be ignored and removed.
* @param mx matrix client
* @param roomId the room id your querying for
* @param profileId the profile id you are querying for
* @param validUntil the timestamp until the pmp association is valid
* @param reset if true, the association for the room will be removed, if false and profileId is undefined, the association will be set to undefined but not removed, meaning it will still be visible in the list of associations but won't have any effect. This is useful for resetting the association without losing the information of which profile was associated before.
* @returns promose that resolves when the association has been set
*/
export function setCurrentlyUsedPerMessageProfileIdForRoom(
mx: MatrixClient,
roomId: string,
profileId: string | undefined,
validUntil?: number,
reset?: boolean
) {
const accountData = mx.getAccountData(`fyi.cisnt.permessageprofile.roomassociation` as any);
const content = accountData?.getContent();
const associations: PerMessageProfileRoomAssociation[] = Array.isArray(content) ? content : [];
if (profileId) {
associations.push({ roomId, profileId, validUntil } satisfies PerMessageProfileRoomAssociation);
} else if (reset) {
associations.filter((assoc) => assoc.roomId !== roomId);
}
const wrapper: PerMessageProfileRoomAssociationWrapper = {
associations,
};
return mx.setAccountData(`fyi.cisnt.permessageprofile.roomassociation` as any, wrapper as any);
}