feat(pkit-compat): some steps towards recognizing proxies, not entirely there yet

This commit is contained in:
Rye committed 2026-03-26 07:38:37 +01:00
1 parent 3f706fe63a
commit 5f22d86a04
7 files changed
+379 -35

No files matched your search

+19 -4
View File
@@ -161,7 +161,8 @@ import {
import { Microphone, Stop } from '@phosphor-icons/react';
import { getSupportedAudioExtension } from '$plugins/voice-recorder-kit/supportedCodec';
import { sanitizeCustomHtml } from '$utils/sanitize';
import { PluralKitCommandMessageHandler } from '$plugins/pluralkit-handler/pluralkitMessageHandler';
import { PKitCommandMessageHandler } from '$plugins/pluralkit-handler/PKitCommandMessageHandler';
import { PKitProxyMessageHandler } from '$plugins/pluralkit-handler/PKitProxyMessageHandler';
import { SchedulePickerDialog } from './schedule-send';
import * as css from './schedule-send/SchedulePickerDialog.css';
import {
@@ -265,9 +266,15 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
* handle pluralkit-style messages
*/
const pluralkitCmdMessageHandler = useMemo(
() => new PluralKitCommandMessageHandler(mx, room),
() => new PKitCommandMessageHandler(mx, room),
[mx, room]
);
const pluralkitProxyMessageHandler = useMemo(() => new PKitProxyMessageHandler(mx), [mx]);
useEffect(() => {
pluralkitProxyMessageHandler.init();
}, [pluralkitProxyMessageHandler]);
const pkCompatEnable = useSetting(settingsAtom, 'pkCompat');
const emojiBtnRef = useRef<HTMLButtonElement>(null);
const micBtnRef = useRef<HTMLButtonElement>(null);
const roomToParents = useAtomValue(roomToParentsAtom);
@@ -718,7 +725,8 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
return;
}
if (PluralKitCommandMessageHandler.isPKCommand(plainText)) {
// check if its a pk command
if (pkCompatEnable && PKitCommandMessageHandler.isPKCommand(plainText)) {
pluralkitCmdMessageHandler.handleMessage(plainText);
}
@@ -778,8 +786,13 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
* This allows the server to apply the correct profile-based transformations (e.g. font size adjustments) when processing the message,
* and also allows clients to display an accurate preview of how the message will look with the profile applied while it's being composed.
*/
const perMessageProfile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId);
const perMessageProfile =
pkCompatEnable && pluralkitProxyMessageHandler.isAProxiedMessage(plainText)
? await pluralkitProxyMessageHandler.getPmpBasedOnMessage(plainText)
: await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId);
if (pkCompatEnable && pluralkitProxyMessageHandler.isAProxiedMessage(plainText))
plainText = pluralkitProxyMessageHandler.stripProxyFromMessage(plainText) ?? plainText;
if (perMessageProfile) {
content['com.beeper.per_message_profile'] =
convertPerMessageProfileToBeeperFormat(perMessageProfile);
@@ -909,6 +922,8 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
roomId,
isMarkdown,
canSendReaction,
pkCompatEnable,
pluralkitProxyMessageHandler,
replyDraft,
silentReply,
scheduledTime,
+191 -4
View File
@@ -1,7 +1,8 @@
import { AccountDataCompatVersion, AccountDataEvent } from '$types/matrix/accountData';
import { PronounSet } from '$utils/pronouns';
import { MatrixClient } from 'matrix-js-sdk';
const ACCOUNT_DATA_PREFIX = 'fyi.cisnt.permessageprofile';
const ACCOUNT_DATA_PREFIX = AccountDataEvent.SablePerProfileMessageProfiles;
/**
* a per message profile
@@ -26,6 +27,7 @@ export type PerMessageProfile = {
* @see PronounSet for the format of the pronouns, and how to parse them from a string input
*/
pronouns?: PronounSet[];
compat?: AccountDataCompatVersion;
};
/**
@@ -96,6 +98,7 @@ type PerMessageProfileIndex = {
* a list of all profile ids, used to list all profiles when the user wants to manage them.
*/
profileIds: string[];
compat: AccountDataCompatVersion;
};
/**
@@ -106,6 +109,64 @@ type PerMessageProfileRoomAssociation = {
validUntil?: number;
};
/**
* associating a profile by proxy
* @author Rye
*/
export type PerMessageProfileProxyAssociation = {
/**
* the profile associated with the proxy
*/
profileId: string;
/**
* regex (string representation of it) to handle the proxy
*/
regexString: string;
/**
* optional parameter to save when the proxy was added
*/
setAt?: number;
};
export type InternalPerMessageProfileProxyAssociation = {
/**
* the profile associated with the proxy
*/
profileId: string;
/**
* regex to handle the proxy
*/
regex: RegExp;
/**
* optional parameter to save when the proxy was added
*/
setAt?: number;
};
export function parsePerMessageProfileProxyAssociation(
assoc: PerMessageProfileProxyAssociation
): InternalPerMessageProfileProxyAssociation {
return {
profileId: assoc.profileId,
// we need to remove artifacts from the toString conversion
regex: new RegExp(assoc.regexString.slice(1, -1)),
setAt: assoc.setAt,
} satisfies InternalPerMessageProfileProxyAssociation;
}
type PerMessageProfileProxyAssociationWrapper = {
/**
* the associations saved in the wrapper
*/
associations:
| Map<string, PerMessageProfileProxyAssociation>
| Record<string, PerMessageProfileProxyAssociation>;
/**
* optional parameter to save compatibility information
*/
compat?: AccountDataCompatVersion;
};
/**
* the shape of the account data for room associations, which is a wrapper around a list of associations.
* This is used to store the associations in account data, and allows us to easily add additional fields in the future if needed without breaking the existing data structure.
@@ -120,9 +181,14 @@ type PerMessageProfileRoomAssociationWrapper = {
associations:
| Map<string, PerMessageProfileRoomAssociation>
| Record<string, PerMessageProfileRoomAssociation>;
compat?: AccountDataCompatVersion;
};
// Helper to always get a Map from wrapper
/**
* unwrap a profile-room-associations-wrapper
* @param wrapper the wrapper to unwrap
* @returns unwrapped map for profile-room-associations
*/
function getAssociationsMap(
wrapper?: PerMessageProfileRoomAssociationWrapper
): Map<string, PerMessageProfileRoomAssociation> {
@@ -138,6 +204,33 @@ function associationsMapToObject(
return Object.fromEntries(map);
}
/**
* helper function (similar to getAssociationsMap for Room associations)
* @param wrapper the wrapper to unwrap
* @returns unwrapped map of proxy associations
*/
function getProxyAssociationMap(
wrapper?: PerMessageProfileProxyAssociationWrapper
): Map<string, PerMessageProfileProxyAssociation> {
if (!wrapper?.associations) return new Map();
if (wrapper.associations instanceof Map) return wrapper.associations;
return new Map(Object.entries(wrapper.associations));
}
function proxyAssociationsMapToObject(
map: Map<string, PerMessageProfileProxyAssociation>
): Record<string, PerMessageProfileProxyAssociation> {
return Object.fromEntries(map);
}
/**
* getting a profile from the account data where the profile matches a given id
*
* @export
* @param {MatrixClient} mx the matrix client
* @param {string} id the profile id
* @return {*} {(Promise<PerMessageProfile | undefined>)} the profile, with the profile Id, if it exists
*/
export async function getPerMessageProfileById(
mx: MatrixClient,
id: string
@@ -146,6 +239,13 @@ export async function getPerMessageProfileById(
return profile ? (profile.getContent() as unknown as PerMessageProfile) : undefined;
}
/**
* getting an array of all PerMessageProfile's saved in the account data
*
* @export
* @param {MatrixClient} mx the matrix client
* @return {*} {Promise<PerMessageProfile[]>} a array containing all per-message-profiles saved
*/
export async function getAllPerMessageProfiles(mx: MatrixClient): Promise<PerMessageProfile[]> {
const profileData = mx.getAccountData(`${ACCOUNT_DATA_PREFIX}.index` as any);
const profileIds = (profileData?.getContent() as PerMessageProfileIndex)?.profileIds || [];
@@ -153,17 +253,33 @@ export async function getAllPerMessageProfiles(mx: MatrixClient): Promise<PerMes
return profiles.filter((profile): profile is PerMessageProfile => profile !== undefined);
}
/**
* add or update a pmp
* @param mx the matrix client
* @param profile the profile to add/update
* @returns void
*/
export function addOrUpdatePerMessageProfile(mx: MatrixClient, profile: PerMessageProfile) {
const profileListIndex = mx.getAccountData(`${ACCOUNT_DATA_PREFIX}.index` as any);
const profileWithCompat = {
...profile,
compat: {
version: 1,
compatDate: '2026-03-26',
} satisfies AccountDataCompatVersion,
} satisfies PerMessageProfile;
if (profileListIndex?.getContent()?.profileIds.includes(profile.id)) {
// profile already exists, just update it
return mx.setAccountData(`${ACCOUNT_DATA_PREFIX}.${profile.id}` as any, profile as any);
return mx.setAccountData(
`${ACCOUNT_DATA_PREFIX}.${profile.id}` as any,
profileWithCompat as any
);
}
// profile doesn't exist, add it to the index and then add the profile data
const newProfileIds = [...(profileListIndex?.getContent()?.profileIds || []), profile.id];
return Promise.all([
mx.setAccountData(`${ACCOUNT_DATA_PREFIX}.index` as any, { profileIds: newProfileIds } as any),
mx.setAccountData(`${ACCOUNT_DATA_PREFIX}.${profile.id}` as any, profile as any),
mx.setAccountData(`${ACCOUNT_DATA_PREFIX}.${profile.id}` as any, profileWithCompat as any),
]);
}
@@ -235,6 +351,77 @@ export async function setCurrentlyUsedPerMessageProfileIdForRoom(
}
/**
*
* @param mx the matrix client
* @param profileId the profile id which the prefix should be attached to
* @param proxy the prefix to use as index
* @param proxyRegExp the regex we can use to match the prefix
* @param reset wheather to delete the prefix
*/
export async function associateProxyWithProfile(
mx: MatrixClient,
profileId: string | undefined,
proxy: string,
proxyRegExp: RegExp,
reset: boolean
) {
const associations = getProxyAssociationMap(
mx.getAccountData(`${ACCOUNT_DATA_PREFIX}.proxyassociation` as any)?.getContent()
);
if (reset) associations.delete(proxy);
if (!profileId) throw new Error('profileId might not be undefined');
if (profileId)
associations.set(proxy, {
profileId,
regexString: proxyRegExp.toString(),
} satisfies PerMessageProfileProxyAssociation);
mx.setAccountData(
`${ACCOUNT_DATA_PREFIX}.proxyassociation` as any,
{ associations: proxyAssociationsMapToObject(associations) } as any
);
}
/**
* get a profile based on a proxy
* @param mx the matrix client
* @param proxy the proxy to look for
* @returns the profile, if any, associated with the prefix
*/
export async function getProfileAssociatedWithProxy(
mx: MatrixClient,
proxy: string
): Promise<PerMessageProfile | undefined> {
const profileId = getAssociationsMap(
mx.getAccountData(`${ACCOUNT_DATA_PREFIX}.proxyassociation` as any)?.getContent()
).get(proxy)?.profileId;
if (!profileId) return undefined;
return getPerMessageProfileById(mx, profileId);
}
/**
*
*
* @export
* @param {MatrixClient} mx the matrix client
* @return {*} {Promise<PerMessageProfileProxyAssociation[]>}
*/
export async function getAllPerMessageProfileProxies(
mx: MatrixClient
): Promise<PerMessageProfileProxyAssociation[]> {
const cont: PerMessageProfileProxyAssociationWrapper | undefined = mx
.getAccountData(`${ACCOUNT_DATA_PREFIX}.proxyassociation` as any)
?.getContent();
if (!cont) return [];
const pmap = getProxyAssociationMap(cont);
const parr = new Array<PerMessageProfileProxyAssociation>();
pmap.values().forEach((v) => parr.push(v));
return parr;
}
/**
*
* drops all room associations for a profile, used when deleting a profile to make sure there are no dangling associations left that point to a non existing profile, which could cause issues when trying to apply the profile to a message in a room that still has an association for the deleted profile.
*
* @param {MatrixClient} mx the matrix client
@@ -1,5 +1,6 @@
import {
addOrUpdatePerMessageProfile,
associateProxyWithProfile,
getAllPerMessageProfiles,
getPerMessageProfileById,
PerMessageProfile,
@@ -9,9 +10,24 @@ import { MatrixClient, Room } from 'matrix-js-sdk';
const pkMemberRenameRegex = /^(pk;member)\s+"?([\w\s]+)"?\s*rename\s+"?([\w\s]+)"?$/;
const pkMemberNewRegex = /^(pk;member)\s+new\s+"?([\w\s]+)"?$/;
const pkMemberNewProxy = /^(pk;member)\s+"?([\w\s]+)"?\s+proxy\s+(.*text.*)$/;
const helpTextPkMemberNew = 'To create a new persona: pk;member new Yumi';
const helpTextPkMemberRename = 'To rename a persona: pk;member "Rain Deer" rename "Micky Mouse"';
const helpTextPkMemberNewProxy = 'To create a persona: pk;member Yumi proxy [text]';
/**
* build a regex to recognize proxies
* a template can be for example `[text]` or `f:text`
*
* @param {string} template
* @return {*} {RegExp}
*/
function buildRegex(template: string): RegExp {
const [before, after] = template.split('text');
const pattern = `${RegExp.escape(before)}(.+)${RegExp.escape(after)}`;
return new RegExp(`^${pattern}$`);
}
/**
* a class to use as PluralKit command message handler
@@ -20,7 +36,7 @@ const helpTextPkMemberRename = 'To rename a persona: pk;member "Rain Deer" renam
* @class PluralKitCommandMessageHandler
* @author Rye
*/
export class PluralKitCommandMessageHandler {
export class PKitCommandMessageHandler {
private readonly mx: MatrixClient;
private message = '';
@@ -46,9 +62,14 @@ export class PluralKitCommandMessageHandler {
}
const memberName = cmdParts[2];
const generatedID = crypto.randomUUID();
sendFeedback(
`adding new member has been created with id: ${generatedID} and name ${memberName}`,
this.room,
this.mx.getSafeUserId()
);
addOrUpdatePerMessageProfile(this.mx, { id: generatedID, name: memberName });
sendFeedback(
`new member has been created with id: ${generatedID} and name ${memberName}`,
`added new member has been created with id: ${generatedID} and name ${memberName}`,
this.room,
this.mx.getSafeUserId()
);
@@ -80,7 +101,7 @@ export class PluralKitCommandMessageHandler {
)?.id;
if (!pmpId) {
sendFeedback(
`Persona with name "${oldName}" doesn't exist in your records, ${helpTextPkMemberRename}`,
`Persona with name "${oldName}" doesn't exist in your records, ${helpTextPkMemberNew}`,
this.room,
this.mx.getSafeUserId()
);
@@ -106,6 +127,27 @@ export class PluralKitCommandMessageHandler {
this.mx.getSafeUserId()
);
addOrUpdatePerMessageProfile(this.mx, pmp);
} else if (pkMemberNewProxy.test(this.message)) {
const cmdParts = pkMemberNewProxy.exec(this.message);
if (!cmdParts) return;
const name = cmdParts[2];
const matchAgainst = cmdParts[3];
const pmpId = (await getAllPerMessageProfiles(this.mx)).find((pmp) => pmp.name === name)?.id;
if (!pmpId) {
sendFeedback(
`Persona with name "${name}" doesn't exist in your records, ${helpTextPkMemberNew}`,
this.room,
this.mx.getSafeUserId()
);
return;
}
const matchAgainstRegExp = buildRegex(matchAgainst);
associateProxyWithProfile(this.mx, pmpId, matchAgainst, matchAgainstRegExp, false);
sendFeedback(
`Persona with name "${name}" (${pmpId}) is now associated with ${matchAgainst}`,
this.room,
this.mx.getSafeUserId()
);
} else {
// default to looking up member info
const listOfProfiles: PerMessageProfile[] = await getAllPerMessageProfiles(this.mx);
@@ -113,7 +155,7 @@ export class PluralKitCommandMessageHandler {
.map((pmp: PerMessageProfile) => `${pmp.id}: ${pmp.name ? pmp.name : '(empty name)'}`)
.join('\n');
sendFeedback(
`You currently have the following persona set up:\n${stringListOfProfiles}\n\n${helpTextPkMemberNew}\n${helpTextPkMemberRename}`,
`You currently have the following persona set up:\n${stringListOfProfiles}\n\n${helpTextPkMemberNew}\n${helpTextPkMemberRename}\n${helpTextPkMemberNewProxy}`,
this.room,
this.mx.getSafeUserId()
);
@@ -129,7 +171,12 @@ export class PluralKitCommandMessageHandler {
return message.startsWith('pk;');
}
public async handleMessage(message: string) {
/**
* handle a message, which might be a pk command
* @param message the message we want to handle
* @returns void
*/
public async handleMessage(message: string): Promise<void> {
this.message = message;
if (!this.message.startsWith('pk')) return;
if (this.message.startsWith('pk;member')) await this.memberHandler();
@@ -0,0 +1,91 @@
import {
getAllPerMessageProfileProxies,
getPerMessageProfileById,
InternalPerMessageProfileProxyAssociation,
parsePerMessageProfileProxyAssociation,
PerMessageProfile,
} from '$hooks/usePerMessageProfile';
import { MatrixClient } from 'matrix-js-sdk';
/**
* proxy message handler
* @author Rye
*/
export class PKitProxyMessageHandler {
/**
* the matrix client we use, we init that in the constructor
*
* @private
* @type {MatrixClient}
* @memberof PKitProxyMessageHandler
*/
private readonly mx: MatrixClient;
/**
* a list of proxies; is not initialized in the constructor
* @private
* @type {PerMessageProfileProxyAssociation[]}
* @memberof PKitProxyMessageHandler
*/
private proxiesAssocs: InternalPerMessageProfileProxyAssociation[];
private succInit: boolean;
/**
* a pk proxy message handler
* @param mx the matrix client
*/
public constructor(mx: MatrixClient) {
this.mx = mx;
this.proxiesAssocs = [];
this.succInit = false;
}
/**
* initialize the handler, as this is not necessarily fast, it shouldn't happen in the constructor
*/
public async init(): Promise<void> {
try {
this.proxiesAssocs = (await getAllPerMessageProfileProxies(this.mx)).map((p) =>
parsePerMessageProfileProxyAssociation(p)
);
this.succInit = true;
} catch (err) {
this.succInit = false;
throw new Error(`failed to init pmp proxy handler: ${String(err)}`);
}
}
/**
* you should probably check this before running `getPmpBasedOnMessage`, as this is faster
* @param message the message to check
*/
public isAProxiedMessage(message: string): boolean {
if (!this.succInit) throw new Error('PK proxy message handler is not initialized');
return this.proxiesAssocs.some((assoc) => assoc.regex.test(message));
}
/**
* get PmP based on message
* @param message the message to look at
* @returns the matching Per-Message-Profile, if any
*/
public async getPmpBasedOnMessage(message: string): Promise<PerMessageProfile | undefined> {
if (!this.succInit) await this.init();
// check if the message matches our formats
// maybe a bit unsafe, as we are evaluating regex that aren't necessarily by us, could be _maybe_ manipulated
const profileId = this.proxiesAssocs.find((assoc) => assoc.regex.test(message))?.profileId;
if (!profileId) return undefined;
return getPerMessageProfileById(this.mx, profileId);
}
public stripProxyFromMessage(message: string): string | undefined {
if (!this.succInit) throw new Error('PK proxy message handler is not initialized');
let m;
this.proxiesAssocs.forEach((assoc) => {
const match = assoc.regex.exec(message);
if (match?.at(1)) m = match.at(1);
});
return m;
}
}
@@ -1,53 +1,43 @@
/**
* the {@link https://pluralkit.me/api/models/#system-model data model for a pluralkit system}
* @since 1.10.0
* @author Rye <[email protected]>
*/
export type PluralKitSystem = {
/**
* id is freeform string
* @since 1.10.0
*/
id: string;
/**
* uuid of a system
* @since 1.10.0
*/
uuid: string;
name?: string;
/**
* description for a system
* @since 1.10.0
*/
description?: string;
/**
* tag for a system
* @since 1.10.0
*/
tag?: string;
/**
* the pronouns of a system
* @since 1.10.0
*/
pronouns?: string;
/**
* Attention this is a http url not a mxc url, you need to consider that.
* @since 1.10.0
*/
avatar_url?: string;
/**
* this is a http url, so you have to download it and upload it to your homeserver
* @since 1.10.0
*/
banner?: string;
/**
* The color of a system
* @since 1.10.0
*/
color?: string;
/**
* Date string in ISO 8601 format, e.g. "2024-01-01T00:00:00Z" (assumingly)
* @since 1.10.0
*/
created: string;
};
@@ -59,64 +49,52 @@ export type PluralKitProxyTag = {
/**
* the {@link https://pluralkit.me/api/models/#member-model Data model for a system member}
* @since 1.10.0
* @author Rye <[email protected]>
*/
export type PluralKitMember = {
/**
* a freeform id demarking a member of a system
* @since 1.10.0
*/
id: string;
/**
* uuid of a member
* @since 1.10.0
*/
uuid: string;
/**
* the name a member of a system uses
* @since 1.10.0
*/
name: string;
/**
* the display name a member of a system uses
* @since 1.10.0
*/
display_name?: string;
/**
* the color a member of a system uses
* @since 1.10.0
*/
color?: string;
/**
* pronouns the member of a system uses
* @since 1.10.0
*/
pronouns?: string;
/**
* this is a http url, so you have to download it and upload it to your homeserver
* @since 1.10.0
*/
avatar_url?: string;
/**
* probably won't be really usable in our usecase
* @since 1.10.0
*/
webhook_avatar_url?: string;
/**
* this is a http url, so you have to download it and upload it to your homeserver
* @since 1.10.0
*/
banner?: string;
/**
* a description of a member of a system
* this could be as long as 1000 chars
* @since 1.10.0
*/
description?: string;
/**
* date when it was created
* @since 1.10.0
*/
created: string;
proxy_tags: Array<PluralKitProxyTag>;
+5
View File
@@ -99,6 +99,10 @@ export interface Settings {
alwaysShowCallButton: boolean;
faviconForMentionsOnly: boolean;
highlightMentions: boolean;
/**
* whether to enable pk compat
*/
pkCompat: boolean;
// furry stuff
renderAnimals: boolean;
@@ -182,6 +186,7 @@ const defaultSettings: Settings = {
alwaysShowCallButton: false,
faviconForMentionsOnly: false,
highlightMentions: true,
pkCompat: false,
// furry stuff
renderAnimals: true,
+21
View File
@@ -21,6 +21,9 @@ export enum AccountDataEvent {
// Sable account data
SableNicknames = 'moe.sable.app.nicknames',
SablePinStatus = 'moe.sable.app.pins_read_marker',
// because of a mistake hasn't been renamed in time
SablePerProfileMessageProfiles = 'fyi.cisnt.permessageprofile',
}
export type MDirectContent = Record<string, string[]>;
@@ -50,6 +53,24 @@ export type SecretContent = {
mac: string;
};
/**
* type to save compatibility information
*/
export type AccountDataCompatVersion = {
/**
* a simple version number, for example 1
*/
version: number;
/**
* the date where it was added
*/
compatDate: string;
/**
* version number which is the oldest compatible, this attribute is optional
*/
incompatBefore?: number;
};
export type SecretAccountData = {
encrypted: Record<string, SecretContent>;
};