diff --git a/.changeset/add_message_forwarding.md b/.changeset/add_message_forwarding.md new file mode 100644 index 00000000..38849d7c --- /dev/null +++ b/.changeset/add_message_forwarding.md @@ -0,0 +1,5 @@ +--- +sable: minor +--- + +Add message forwarding with metadata diff --git a/src/app/components/message/MsgTypeRenderers.tsx b/src/app/components/message/MsgTypeRenderers.tsx index e45f0b9a..275cfefe 100644 --- a/src/app/components/message/MsgTypeRenderers.tsx +++ b/src/app/components/message/MsgTypeRenderers.tsx @@ -31,6 +31,7 @@ import { MessageUnsupportedContent, } from './content'; import { MessageTextBody } from './layout'; +import { unwrapForwardedContent } from './modals/MessageForward'; export function MBadEncrypted() { return ( @@ -86,6 +87,10 @@ export function MText({ edited, content, renderBody, renderUrlsPreview, style }: typeof content.formatted_body === 'string' ? content.formatted_body : undefined; const trimmedBody = useMemo(() => trimReplyFromBody(body), [body]); + const unwrappedForwardedContent = useMemo( + () => unwrapForwardedContent(customBody ?? body), + [customBody, body] + ); const safeCustomBody = useMemo(() => { if (!customBody) return undefined; @@ -96,6 +101,10 @@ export function MText({ edited, content, renderBody, renderUrlsPreview, style }: return customBody; }, [customBody]); + const isForwarded = useMemo(() => { + const forwardMeta = content['moe.sable.message.forward']; + return typeof forwardMeta === 'object'; + }, [content]); const isJumbo = useMemo(() => { if (!trimmedBody || trimmedBody.length >= 500) return false; if (!JUMBO_EMOJI_REG.test(trimmedBody)) return false; @@ -113,6 +122,19 @@ export function MText({ edited, content, renderBody, renderUrlsPreview, style }: const urlsMatch = renderUrlsPreview && trimmedBody.match(URL_REG); const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined; + if (isForwarded && unwrappedForwardedContent) { + return ( + + {renderBody({ + body: trimmedBody, + customBody: unwrappedForwardedContent, + })} + {edited && } + {renderUrlsPreview && urls && urls.length > 0 && renderUrlsPreview(urls)} + + ); + } + return ( <> )} + {modal.type === ModalType.Forward && ( + + + + )} + {modal.type === ModalType.Source && ( diff --git a/src/app/components/message/modals/MessageForward.tsx b/src/app/components/message/modals/MessageForward.tsx new file mode 100644 index 00000000..d113cbec --- /dev/null +++ b/src/app/components/message/modals/MessageForward.tsx @@ -0,0 +1,285 @@ +// Modal for message forwarding, which allows users to select a room to forward the message to + +import { useMatrixClient } from '$hooks/useMatrixClient'; +import { modalAtom, ModalType } from '$state/modal'; +import { + Box, + Button, + Dialog, + Header, + Icon, + Icons, + IconButton, + MenuItem, + Text, + config, + Scroll, + as, +} from 'folds'; +import { useAtomValue, useSetAtom } from 'jotai'; +import { JoinRule, MatrixEvent, Room } from '$types/matrix-sdk'; +import { useEffect, useMemo, useState } from 'react'; +import { allRoomsAtom } from '$state/room-list/roomList'; +import { useAllJoinedRoomsSet, useGetRoom } from '$hooks/useGetRoom'; +import { factoryRoomIdByActivity } from '$utils/sort'; +import * as css from '$features/room/message/styles.css'; +import { sanitizeCustomHtml } from '$utils/sanitize'; +import { getStateEvents } from '$utils/room'; +import { StateEvent } from '$types/matrix/room'; + +// Message forwarding component +export const MessageForwardItem = as<'button', MessageForwardItemProps>( + ({ room, mEvent, onClose, ...props }: MessageForwardItemProps) => { + const setModal = useSetAtom(modalAtom); + + const handleClick = () => { + setModal({ + type: ModalType.Forward, + room, + mEvent, + }); + onClose?.(); + }; + + return ( + } + radii="300" + {...props} + onClick={handleClick} + > + + Forward + + + ); + } +); + +export const unwrapForwardedContent = (content: string) => { + // unwrap the content of a forwarded message if it was wrapped in a blockquote with the data-forward-marker attribute + const parser = new DOMParser(); + const doc = parser.parseFromString(content, 'text/html'); + const forwardMarker = doc.querySelector('[data-forward-marker]'); + if (forwardMarker) { + const blockquote = forwardMarker.querySelector('blockquote'); + if (blockquote) { + return blockquote.innerHTML; + } + } + return content; +}; + +type MessageForwardInternalProps = { + room: Room; + mEvent: MatrixEvent; + onClose: () => void; +}; + +type ForwardMeta = { + v: 1; + is_forwarded: true; + original_timestamp: number; + original_room_id?: string; + original_event_id?: string; + // to mark that event_id and room_id are not present + original_event_private: boolean; +}; + +export function MessageForwardInternal({ room, mEvent, onClose }: MessageForwardInternalProps) { + const mx = useMatrixClient(); + + const [isTargetSelected, setIsTargetSelected] = useState(false); + const [isForwardSuccess, setIsForwardSuccess] = useState(false); + const [isForwardError, setIsForwardError] = useState(false); + const [targetRoomId, setTargetRoomId] = useState(null); + + // detect if it's a public room or not + const joinRule = room.getJoinRule() ?? JoinRule.Invite; + + const parentSpaceIds = getStateEvents(room, StateEvent.SpaceParent) + .map((e) => e.getStateKey()) + .filter((id): id is string => Boolean(id)); + + const isInPublicSpace = parentSpaceIds.some((spaceId) => { + const space = mx.getRoom(spaceId); + return Boolean(space?.isSpaceRoom()) && space?.getJoinRule() === JoinRule.Public; + }); + + // A room is private if its join rule is Invite (or other non-public/non-knock/non-restricted), + // or it's Restricted but NOT inside a public space. + const isPrivate = + joinRule === JoinRule.Invite || + (joinRule === JoinRule.Restricted && !isInPublicSpace) || + (joinRule !== JoinRule.Public && + joinRule !== JoinRule.Knock && + joinRule !== JoinRule.Restricted); + + const allRooms = useAtomValue(allRoomsAtom); + const allJoinedRooms = useAllJoinedRoomsSet(); + const getRoom = useGetRoom(allJoinedRooms); + // possible targets to forward the message to + const forwardTargets = useMemo( + () => + allRooms + .filter((id) => id !== room.roomId) + .filter((id) => { + const target = getRoom(id); + return !!target && !target.isSpaceRoom() && target.maySendMessage(); + }) + .sort(factoryRoomIdByActivity(mx)), + [allRooms, room.roomId, getRoom, mx] + ); + + useEffect(() => { + if (isForwardSuccess) { + setTimeout(() => { + // close the modal if the message was forwarded successfully + onClose(); + }, 2000); + } + }, [isForwardSuccess, onClose]); + + // actually forward the message to the selected room + const handleForwardClick = () => { + if (!targetRoomId) return; + + const targetRoom = getRoom(targetRoomId); + const eventId = mEvent.getId(); + if (!targetRoom || !eventId) return; + + type SendEventType = Parameters[2]; + type SendEventContent = Parameters[3]; + + const eventType = mEvent.getType() as SendEventType; + // using reference relation to indicate that this is a forwarded message, + // which allows clients to display it as such + + const bodyModifText = `(Forwarded message from ${isPrivate ? 'a private room' : (getRoom(room.roomId)?.name ?? 'a room')})`; + let newBodyPlain = ''; + let newBodyHtml = ''; + // transform if msgtype is m.text + if (mEvent.getContent().msgtype === 'm.text') { + const original = mEvent.getContent().body; + newBodyPlain = `${bodyModifText}\n\n${original + .split('\n') + .map((l: string) => `> ${l}`) + .join('\n')}`; + const safeHtml = sanitizeCustomHtml(original).replace(/\n/g, '
'); + newBodyHtml = + `
` + + `

${sanitizeCustomHtml(bodyModifText)}

` + + `
${safeHtml}
` + + `
`; + } + let content; + // handle privacy stuff + if (isPrivate) { + // if the message is from a private room, we should strip any media or mentions to avoid leaking information to the target room + // we can still include the original message content in the body of the message, so we'll just use a fallback text/plain content with the original message body + content = { + ...mEvent.getContent(), + body: newBodyPlain, + format: 'org.matrix.custom.html', + formatted_body: newBodyHtml, + 'moe.sable.message.forward': { + v: 1, + is_forwarded: true, + original_timestamp: mEvent.getTs(), + original_event_private: true, + } satisfies ForwardMeta, + }; + } else { + content = { + ...mEvent.getContent(), + body: newBodyPlain, + format: 'org.matrix.custom.html', + formatted_body: newBodyHtml, + 'm.relates_to': { + rel_type: 'm.reference', + event_id: eventId, + }, + 'moe.sable.message.forward': { + v: 1, + is_forwarded: true, + original_timestamp: mEvent.getTs(), + original_room_id: room.roomId, + original_event_id: eventId, + original_event_private: false, + } satisfies ForwardMeta, + }; + } + + try { + mx.sendEvent(targetRoom.roomId, null, eventType, content as unknown as SendEventContent).then( + () => setIsForwardSuccess(true) + ); + } catch { + setIsForwardSuccess(false); + setIsForwardError(true); + } + }; + + return ( + +
+ + Forward Message + + + + +
+ + + + {forwardTargets.map((roomId) => { + const target = getRoom(roomId); + if (!target) return null; + return ( + { + setIsTargetSelected(true); + setTargetRoomId(roomId); + }} + variant={targetRoomId === roomId ? 'Success' : 'Surface'} + aria-pressed={targetRoomId === roomId} + size="400" + radii="400" + > + {target.name} + + ); + })} + + + {isTargetSelected && targetRoomId && ( + + )} + {isForwardError && ( + + Failed to forward message. Please try again. + + )} + +
+ ); +} + +type MessageForwardItemProps = { + room: Room; + mEvent: MatrixEvent; + onClose?: () => void; +}; diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 74f60593..4ea606b8 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -132,7 +132,7 @@ import { useGetMemberPowerTag } from '$hooks/useMemberPowerTag'; import { profilesCacheAtom } from '$state/userRoomProfile'; import { ClientSideHoverFreeze } from '$components/ClientSideHoverFreeze'; import * as css from './RoomTimeline.css'; -import { EncryptedContent, Event, Message, Reactions } from './message'; +import { EncryptedContent, Event, ForwardedMessageProps, Message, Reactions } from './message'; const TimelineFloat = as<'div', css.TimelineFloatVariants>( ({ position, className, ...props }, ref) => ( @@ -1338,6 +1338,29 @@ export function RoomTimeline({ const senderDisplayName = getMemberDisplayName(room, senderId, nicknames) ?? getMxIdLocalPart(senderId) ?? senderId; + // determine if message is forwarded by checking for the presence of the 'moe.sable.message.forward' key in the event content + const forwardContent = safeContent['moe.sable.message.forward'] as + | { + original_timestamp?: unknown; + original_room_id?: string; + original_event_id?: string; + original_event_private?: boolean; + } + | undefined; + + const messageForwardedProps: ForwardedMessageProps | undefined = forwardContent + ? { + isForwarded: true, + originalTimestamp: + typeof forwardContent.original_timestamp === 'number' + ? forwardContent.original_timestamp + : mEvent.getTs(), + originalRoomId: forwardContent.original_room_id ?? room.roomId, + originalEventId: forwardContent.original_event_id ?? '', + originalEventPrivate: forwardContent.original_event_private ?? false, + } + : undefined; + return ( void; onDeleteFailedSend?: (event: MatrixEvent) => void; + messageForwardedProps?: ForwardedMessageProps; }; function useMobileDoubleTap(callback: () => void, delay = 300) { @@ -329,6 +341,7 @@ function MessageInternal( sendStatus, onResend, onDeleteFailedSend, + messageForwardedProps, ...props }: MessageProps & { className?: string; children?: ReactNode }, ref: any @@ -469,6 +482,8 @@ function MessageInternal( const isFailedSend = sendStatus === EventStatus.NOT_SENT; const canResend = isFailedSend && senderId === mx.getUserId() && !!onResend; const canDeleteFailedSend = isFailedSend && senderId === mx.getUserId() && !!onDeleteFailedSend; + // handle clicks on mentions in the message body (e.g. jump to original message from a forwarded message notice) + const mentionClickHandler = useMentionClickHandler(room.roomId); const handleResendClick: MouseEventHandler = useCallback( (evt) => { @@ -500,6 +515,35 @@ function MessageInternal( [css.MessageFailed]: isFailedSend, })} > + {messageForwardedProps?.isForwarded && ( + + + Forwarded{' '} + {messageForwardedProps.originalEventPrivate ? 'private message' : 'from another room'}{' '} + {!messageForwardedProps.originalEventPrivate && ( + + jump to original + + )} + + + )} {reply} {edit && onEditId ? ( )} + {canPinEvent && ( )} @@ -1105,6 +1150,7 @@ export const Event = as<'div', EventProps>( )} + {((!mEvent.isRedacted() && canDelete && !stateEvent) || (mEvent.getSender() !== mx.getUserId() && !stateEvent)) && ( diff --git a/src/app/state/modal.ts b/src/app/state/modal.ts index 1d16cfe8..c4f4cf79 100644 --- a/src/app/state/modal.ts +++ b/src/app/state/modal.ts @@ -3,6 +3,8 @@ import { MatrixEvent, Room, Relations } from '$types/matrix-sdk'; export enum ModalType { Delete = 'delete', + // for forwarding a message to another room, not to be confused with the "share" action which is for sharing a message to another app + Forward = 'forward', Report = 'report', Source = 'source', Reactions = 'reactions', @@ -11,6 +13,7 @@ export enum ModalType { export type ModalState = | { type: ModalType.Delete; room: Room; mEvent: MatrixEvent } + | { type: ModalType.Forward; room: Room; mEvent: MatrixEvent } | { type: ModalType.Report; room: Room; mEvent: MatrixEvent } | { type: ModalType.Source; room: Room; mEvent: MatrixEvent } | { type: ModalType.Reactions; room: Room; relations: Relations }