Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6ae4d7adc0 |
@@ -1,4 +1,4 @@
|
||||
import React, { forwardRef, useCallback, useEffect, useState } from 'react';
|
||||
import React, { forwardRef, useCallback } from 'react';
|
||||
import { Dialog, Header, config, Box, Text, Button, Spinner, color } from 'folds';
|
||||
import { useAtom } from 'jotai';
|
||||
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
|
||||
@@ -9,8 +9,6 @@ import { useMatrixClient } from '../hooks/useMatrixClient';
|
||||
import { useModalStyle } from '../hooks/useModalStyle';
|
||||
import { useCrossSigningActive } from '../hooks/useCrossSigning';
|
||||
import { InfoCard } from './info-card';
|
||||
import { ScheduledMessage } from '../state/scheduledMessages';
|
||||
import { cancelScheduledMessage, fetchScheduledMessages } from '../utils/scheduledMessages';
|
||||
import {
|
||||
useDeviceVerificationStatus,
|
||||
VerificationStatus,
|
||||
@@ -38,36 +36,17 @@ export const LogoutDialog = forwardRef<HTMLDivElement, LogoutDialogProps>(
|
||||
|
||||
const [callEmbed, setCallEmbed] = useAtom(callEmbedAtom);
|
||||
|
||||
// [Gitea #322] Scheduled messages live on the server and still send after
|
||||
// logout, where no client would show them. Say so, and offer to cancel.
|
||||
const [scheduled, setScheduled] = useState<ScheduledMessage[]>([]);
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
fetchScheduledMessages(mx)
|
||||
.then((list) => alive && setScheduled(list))
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [mx]);
|
||||
|
||||
const [logoutState, logout] = useAsyncCallback<void, Error, [boolean?]>(
|
||||
useCallback(
|
||||
async (cancelScheduled?: boolean) => {
|
||||
if (cancelScheduled) {
|
||||
await Promise.all(scheduled.map((m) => cancelScheduledMessage(mx, m.delayId)));
|
||||
}
|
||||
// [Gitea #29] Logging out mid-call must hang up first, or the MatrixRTC
|
||||
// membership (expires: 4 h) stays behind as a ghost participant and
|
||||
// everyone else sees you "in call" until it times out.
|
||||
if (callEmbed && callEmbed.joined && !callEmbed.disposed) {
|
||||
await hangupCallAndWait(mx, callEmbed);
|
||||
setCallEmbed(undefined);
|
||||
}
|
||||
await logoutClient(mx);
|
||||
},
|
||||
[mx, callEmbed, setCallEmbed, scheduled],
|
||||
),
|
||||
const [logoutState, logout] = useAsyncCallback<void, Error, []>(
|
||||
useCallback(async () => {
|
||||
// [Gitea #29] Logging out mid-call must hang up first, or the MatrixRTC
|
||||
// membership (expires: 4 h) stays behind as a ghost participant and
|
||||
// everyone else sees you "in call" until it times out.
|
||||
if (callEmbed && callEmbed.joined && !callEmbed.disposed) {
|
||||
await hangupCallAndWait(mx, callEmbed);
|
||||
setCallEmbed(undefined);
|
||||
}
|
||||
await logoutClient(mx);
|
||||
}, [mx, callEmbed, setCallEmbed]),
|
||||
);
|
||||
|
||||
const ongoingLogout = logoutState.status === AsyncStatus.Loading;
|
||||
@@ -114,13 +93,6 @@ export const LogoutDialog = forwardRef<HTMLDivElement, LogoutDialogProps>(
|
||||
description="Enable device verification or export your encrypted data from settings to avoid losing access to your messages."
|
||||
/>
|
||||
))}
|
||||
{scheduled.length > 0 && (
|
||||
<InfoCard
|
||||
variant="Warning"
|
||||
title={`${scheduled.length} scheduled message${scheduled.length === 1 ? '' : 's'}`}
|
||||
description="Scheduled messages still send after you log out. Cancel them now if you don't want them sent."
|
||||
/>
|
||||
)}
|
||||
<Text priority="400">You’re about to log out. Are you sure?</Text>
|
||||
{logoutState.status === AsyncStatus.Error && (
|
||||
<Text style={{ color: color.Critical.Main }} size="T300">
|
||||
@@ -130,24 +102,12 @@ export const LogoutDialog = forwardRef<HTMLDivElement, LogoutDialogProps>(
|
||||
<Box direction="Column" gap="200">
|
||||
<Button
|
||||
variant="Critical"
|
||||
onClick={() => logout()}
|
||||
onClick={logout}
|
||||
disabled={ongoingLogout}
|
||||
before={ongoingLogout && <Spinner variant="Critical" fill="Solid" size="200" />}
|
||||
>
|
||||
<Text size="B400">
|
||||
{scheduled.length > 0 ? 'Logout and keep scheduled messages' : 'Logout'}
|
||||
</Text>
|
||||
<Text size="B400">Logout</Text>
|
||||
</Button>
|
||||
{scheduled.length > 0 && (
|
||||
<Button
|
||||
variant="Critical"
|
||||
fill="Soft"
|
||||
onClick={() => logout(true)}
|
||||
disabled={ongoingLogout}
|
||||
>
|
||||
<Text size="B400">Cancel scheduled messages and logout</Text>
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="Secondary" fill="Soft" onClick={handleClose} disabled={ongoingLogout}>
|
||||
<Text size="B400">Cancel</Text>
|
||||
</Button>
|
||||
|
||||
@@ -4,12 +4,7 @@ import { IContent } from 'matrix-js-sdk';
|
||||
import { Box, Button, Icon, IconButton, Icons, Text, color, config } from 'folds';
|
||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||
import { scheduledMessagesAtom, ScheduledMessage } from '../../state/scheduledMessages';
|
||||
import {
|
||||
cancelScheduledMessage,
|
||||
fetchScheduledMessages,
|
||||
groupScheduledByRoom,
|
||||
sendScheduledMessageNow,
|
||||
} from '../../utils/scheduledMessages';
|
||||
import { cancelScheduledMessage, sendScheduledMessageNow } from '../../utils/scheduledMessages';
|
||||
import { ScheduleMessageModal } from './ScheduleMessageModal';
|
||||
import { useTimestampFormatter } from '../../hooks/useTimestampFormatter';
|
||||
import { formatFriendlyDateTime } from '../../utils/datetimeInput';
|
||||
@@ -31,26 +26,6 @@ export function ScheduledMessagesTray({ roomId }: ScheduledMessagesTrayProps) {
|
||||
|
||||
const messages = useMemo(() => scheduledMessages.get(roomId) ?? [], [scheduledMessages, roomId]);
|
||||
|
||||
// [Gitea #322] The server is the source of truth: messages scheduled on
|
||||
// another device (or before a logout) show up here and can be cancelled.
|
||||
// localStorage is only a cache for the first paint; on error we keep it.
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
const load = () => {
|
||||
fetchScheduledMessages(mx)
|
||||
.then((list) => {
|
||||
if (alive) setScheduledMessages(groupScheduledByRoom(list));
|
||||
})
|
||||
.catch(() => undefined);
|
||||
};
|
||||
load();
|
||||
window.addEventListener('focus', load);
|
||||
return () => {
|
||||
alive = false;
|
||||
window.removeEventListener('focus', load);
|
||||
};
|
||||
}, [mx, roomId, setScheduledMessages]);
|
||||
|
||||
// Remove scheduled messages whose time has passed
|
||||
useEffect(() => {
|
||||
if (messages.length === 0) return undefined;
|
||||
|
||||
+185
-134
@@ -255,6 +255,8 @@ function HomeCustomSection({
|
||||
return (localName ?? matrixName).toLowerCase().includes(query);
|
||||
});
|
||||
}, [mx, section.rooms, closed, roomsWithUnreadSet, selectedRoomId, filterQuery]);
|
||||
// [Gitea #289] While filtering, a section with no matches is hidden.
|
||||
if (filterQuery.trim() && items.length === 0) return null;
|
||||
// Sections are user-curated and small, so they render plainly — no
|
||||
// virtualizer per section (a late-mounted one never measured its scroller).
|
||||
return (
|
||||
@@ -443,6 +445,26 @@ export function Home() {
|
||||
});
|
||||
}, [mx, sortedRooms, filterQuery]);
|
||||
|
||||
// [Gitea #289] While filtering, hide empty sections; with no match at all,
|
||||
// say so instead of leaving bare headers.
|
||||
const filtering = filterQuery.trim().length > 0;
|
||||
const customSectionMatch = useMemo(() => {
|
||||
if (!filtering) return true;
|
||||
const query = filterQuery.toLowerCase();
|
||||
const localNames = getLocalRoomNamesContent(mx);
|
||||
return customSections.some((section) =>
|
||||
section.rooms.some((rId) =>
|
||||
(localNames.rooms[rId] ?? mx.getRoom(rId)?.name ?? '').toLowerCase().includes(query),
|
||||
),
|
||||
);
|
||||
}, [mx, customSections, filtering, filterQuery]);
|
||||
const noFilterMatch =
|
||||
filtering &&
|
||||
!customSectionMatch &&
|
||||
filteredFavoriteRooms.length === 0 &&
|
||||
filteredRooms.length === 0 &&
|
||||
filteredLowPriorityRooms.length === 0;
|
||||
|
||||
const favVirtualizer = useVirtualizer({
|
||||
count: filteredFavoriteRooms.length,
|
||||
getScrollElement: () => scrollRef.current,
|
||||
@@ -580,7 +602,7 @@ export function Home() {
|
||||
/>
|
||||
</Box>
|
||||
</NavCategory>
|
||||
{favoriteRooms.length > 0 && (
|
||||
{favoriteRooms.length > 0 && (!filtering || filteredFavoriteRooms.length > 0) && (
|
||||
<NavCategory>
|
||||
<NavCategoryHeader>
|
||||
<RoomNavCategoryButton
|
||||
@@ -629,142 +651,171 @@ export function Home() {
|
||||
notificationPreferences={notificationPreferences}
|
||||
/>
|
||||
))}
|
||||
<NavCategory>
|
||||
<NavCategoryHeader>
|
||||
<RoomNavCategoryButton
|
||||
closed={closedCategories.has(DEFAULT_CATEGORY_ID)}
|
||||
data-category-id={DEFAULT_CATEGORY_ID}
|
||||
onClick={handleCategoryClick}
|
||||
{noFilterMatch && (
|
||||
<NavCategory>
|
||||
<Box
|
||||
direction="Column"
|
||||
alignItems="Center"
|
||||
gap="200"
|
||||
style={{ padding: config.space.S400 }}
|
||||
>
|
||||
Rooms
|
||||
</RoomNavCategoryButton>
|
||||
{!closedCategories.has(DEFAULT_CATEGORY_ID) && (
|
||||
<>
|
||||
<IconButton
|
||||
aria-expanded={!!sortMenuAnchor}
|
||||
aria-haspopup="menu"
|
||||
variant="Background"
|
||||
fill="None"
|
||||
size="300"
|
||||
radii="300"
|
||||
onClick={(evt: React.MouseEvent<HTMLButtonElement>) => {
|
||||
const cords = evt.currentTarget.getBoundingClientRect();
|
||||
setSortMenuAnchor((current) => (current ? undefined : cords));
|
||||
}}
|
||||
aria-label="Sort rooms"
|
||||
>
|
||||
<Icon src={Icons.Sort} size="100" />
|
||||
</IconButton>
|
||||
<PopOut
|
||||
anchor={sortMenuAnchor}
|
||||
position="Bottom"
|
||||
align="End"
|
||||
offset={6}
|
||||
content={
|
||||
<FocusTrap
|
||||
focusTrapOptions={{
|
||||
initialFocus: false,
|
||||
onDeactivate: () => setSortMenuAnchor(undefined),
|
||||
clickOutsideDeactivates: true,
|
||||
isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown',
|
||||
isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp',
|
||||
escapeDeactivates: stopPropagation,
|
||||
}}
|
||||
>
|
||||
<Menu style={{ maxWidth: toRem(180), width: '100vw' }}>
|
||||
<Box
|
||||
direction="Column"
|
||||
gap="100"
|
||||
style={{ padding: config.space.S100 }}
|
||||
>
|
||||
<MenuItem
|
||||
onClick={() => {
|
||||
setHomeRoomSort('recent');
|
||||
setSortMenuAnchor(undefined);
|
||||
}}
|
||||
size="300"
|
||||
after={
|
||||
homeRoomSort === 'recent' ? (
|
||||
<Icon size="100" src={Icons.Check} />
|
||||
) : undefined
|
||||
}
|
||||
radii="300"
|
||||
<Text size="T300" priority="300" align="Center">
|
||||
No rooms match “{filterQuery.trim()}”
|
||||
</Text>
|
||||
<Button
|
||||
size="300"
|
||||
variant="Secondary"
|
||||
fill="Soft"
|
||||
radii="300"
|
||||
onClick={() => setFilterQuery('')}
|
||||
>
|
||||
<Text size="B300">Clear filter</Text>
|
||||
</Button>
|
||||
</Box>
|
||||
</NavCategory>
|
||||
)}
|
||||
{(!filtering || filteredRooms.length > 0) && (
|
||||
<NavCategory>
|
||||
<NavCategoryHeader>
|
||||
<RoomNavCategoryButton
|
||||
closed={closedCategories.has(DEFAULT_CATEGORY_ID)}
|
||||
data-category-id={DEFAULT_CATEGORY_ID}
|
||||
onClick={handleCategoryClick}
|
||||
>
|
||||
Rooms
|
||||
</RoomNavCategoryButton>
|
||||
{!closedCategories.has(DEFAULT_CATEGORY_ID) && (
|
||||
<>
|
||||
<IconButton
|
||||
aria-expanded={!!sortMenuAnchor}
|
||||
aria-haspopup="menu"
|
||||
variant="Background"
|
||||
fill="None"
|
||||
size="300"
|
||||
radii="300"
|
||||
onClick={(evt: React.MouseEvent<HTMLButtonElement>) => {
|
||||
const cords = evt.currentTarget.getBoundingClientRect();
|
||||
setSortMenuAnchor((current) => (current ? undefined : cords));
|
||||
}}
|
||||
aria-label="Sort rooms"
|
||||
>
|
||||
<Icon src={Icons.Sort} size="100" />
|
||||
</IconButton>
|
||||
<PopOut
|
||||
anchor={sortMenuAnchor}
|
||||
position="Bottom"
|
||||
align="End"
|
||||
offset={6}
|
||||
content={
|
||||
<FocusTrap
|
||||
focusTrapOptions={{
|
||||
initialFocus: false,
|
||||
onDeactivate: () => setSortMenuAnchor(undefined),
|
||||
clickOutsideDeactivates: true,
|
||||
isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown',
|
||||
isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp',
|
||||
escapeDeactivates: stopPropagation,
|
||||
}}
|
||||
>
|
||||
<Menu style={{ maxWidth: toRem(180), width: '100vw' }}>
|
||||
<Box
|
||||
direction="Column"
|
||||
gap="100"
|
||||
style={{ padding: config.space.S100 }}
|
||||
>
|
||||
<Text style={{ flexGrow: 1 }} as="span" size="T300" truncate>
|
||||
Recent Activity
|
||||
</Text>
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
onClick={() => {
|
||||
setHomeRoomSort('alpha');
|
||||
setSortMenuAnchor(undefined);
|
||||
}}
|
||||
size="300"
|
||||
after={
|
||||
homeRoomSort === 'alpha' ? (
|
||||
<Icon size="100" src={Icons.Check} />
|
||||
) : undefined
|
||||
}
|
||||
radii="300"
|
||||
>
|
||||
<Text style={{ flexGrow: 1 }} as="span" size="T300" truncate>
|
||||
A → Z
|
||||
</Text>
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
onClick={() => {
|
||||
setHomeRoomSort('unread');
|
||||
setSortMenuAnchor(undefined);
|
||||
}}
|
||||
size="300"
|
||||
after={
|
||||
homeRoomSort === 'unread' ? (
|
||||
<Icon size="100" src={Icons.Check} />
|
||||
) : undefined
|
||||
}
|
||||
radii="300"
|
||||
>
|
||||
<Text style={{ flexGrow: 1 }} as="span" size="T300" truncate>
|
||||
Unread First
|
||||
</Text>
|
||||
</MenuItem>
|
||||
</Box>
|
||||
</Menu>
|
||||
</FocusTrap>
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</NavCategoryHeader>
|
||||
<div
|
||||
style={{
|
||||
position: 'relative',
|
||||
height: virtualizer.getTotalSize(),
|
||||
}}
|
||||
>
|
||||
{virtualizer.getVirtualItems().map((vItem) => {
|
||||
const roomId = filteredRooms[vItem.index];
|
||||
const room = mx.getRoom(roomId);
|
||||
if (!room) return null;
|
||||
const selected = selectedRoomId === roomId;
|
||||
|
||||
return (
|
||||
<VirtualTile virtualItem={vItem} key={roomId} ref={virtualizer.measureElement}>
|
||||
<RoomNavItem
|
||||
room={room}
|
||||
selected={selected}
|
||||
linkPath={getHomeRoomPath(getCanonicalAliasOrRoomId(mx, roomId))}
|
||||
notificationMode={getRoomNotificationMode(
|
||||
notificationPreferences,
|
||||
room.roomId,
|
||||
)}
|
||||
<MenuItem
|
||||
onClick={() => {
|
||||
setHomeRoomSort('recent');
|
||||
setSortMenuAnchor(undefined);
|
||||
}}
|
||||
size="300"
|
||||
after={
|
||||
homeRoomSort === 'recent' ? (
|
||||
<Icon size="100" src={Icons.Check} />
|
||||
) : undefined
|
||||
}
|
||||
radii="300"
|
||||
>
|
||||
<Text style={{ flexGrow: 1 }} as="span" size="T300" truncate>
|
||||
Recent Activity
|
||||
</Text>
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
onClick={() => {
|
||||
setHomeRoomSort('alpha');
|
||||
setSortMenuAnchor(undefined);
|
||||
}}
|
||||
size="300"
|
||||
after={
|
||||
homeRoomSort === 'alpha' ? (
|
||||
<Icon size="100" src={Icons.Check} />
|
||||
) : undefined
|
||||
}
|
||||
radii="300"
|
||||
>
|
||||
<Text style={{ flexGrow: 1 }} as="span" size="T300" truncate>
|
||||
A → Z
|
||||
</Text>
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
onClick={() => {
|
||||
setHomeRoomSort('unread');
|
||||
setSortMenuAnchor(undefined);
|
||||
}}
|
||||
size="300"
|
||||
after={
|
||||
homeRoomSort === 'unread' ? (
|
||||
<Icon size="100" src={Icons.Check} />
|
||||
) : undefined
|
||||
}
|
||||
radii="300"
|
||||
>
|
||||
<Text style={{ flexGrow: 1 }} as="span" size="T300" truncate>
|
||||
Unread First
|
||||
</Text>
|
||||
</MenuItem>
|
||||
</Box>
|
||||
</Menu>
|
||||
</FocusTrap>
|
||||
}
|
||||
/>
|
||||
</VirtualTile>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</NavCategory>
|
||||
{lowPriorityRooms.length > 0 && (
|
||||
</>
|
||||
)}
|
||||
</NavCategoryHeader>
|
||||
<div
|
||||
style={{
|
||||
position: 'relative',
|
||||
height: virtualizer.getTotalSize(),
|
||||
}}
|
||||
>
|
||||
{virtualizer.getVirtualItems().map((vItem) => {
|
||||
const roomId = filteredRooms[vItem.index];
|
||||
const room = mx.getRoom(roomId);
|
||||
if (!room) return null;
|
||||
const selected = selectedRoomId === roomId;
|
||||
|
||||
return (
|
||||
<VirtualTile
|
||||
virtualItem={vItem}
|
||||
key={roomId}
|
||||
ref={virtualizer.measureElement}
|
||||
>
|
||||
<RoomNavItem
|
||||
room={room}
|
||||
selected={selected}
|
||||
linkPath={getHomeRoomPath(getCanonicalAliasOrRoomId(mx, roomId))}
|
||||
notificationMode={getRoomNotificationMode(
|
||||
notificationPreferences,
|
||||
room.roomId,
|
||||
)}
|
||||
/>
|
||||
</VirtualTile>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</NavCategory>
|
||||
)}
|
||||
{lowPriorityRooms.length > 0 && (!filtering || filteredLowPriorityRooms.length > 0) && (
|
||||
<NavCategory>
|
||||
<NavCategoryHeader>
|
||||
<RoomNavCategoryButton
|
||||
|
||||
@@ -21,8 +21,8 @@ const internalAtom = atomWithStorage<Record<string, ScheduledMessage[]>>(
|
||||
/**
|
||||
* Global atom: Map<roomId, ScheduledMessage[]>
|
||||
* Stores all locally-tracked scheduled messages across rooms.
|
||||
* Loaded from the server's MSC4140 `GET /delayed_events` when the tray mounts
|
||||
* (Gitea #322); localStorage is a cache for the first paint.
|
||||
* MSC4140 has no list endpoint, so we track them ourselves.
|
||||
* Backed by localStorage so scheduled messages survive page refreshes.
|
||||
*/
|
||||
export const scheduledMessagesAtom = atom(
|
||||
(get): Map<string, ScheduledMessage[]> => new Map(Object.entries(get(internalAtom))),
|
||||
|
||||
@@ -6,8 +6,6 @@ import {
|
||||
scheduleMessage,
|
||||
cancelScheduledMessage,
|
||||
restartScheduledMessage,
|
||||
parseDelayedEvents,
|
||||
groupScheduledByRoom,
|
||||
} from './scheduledMessages';
|
||||
|
||||
// Minimal MatrixClient stub: records every authedRequest call and returns a
|
||||
@@ -121,61 +119,3 @@ test('cancel/restart url-encode the delay id', async () => {
|
||||
await cancelScheduledMessage(mx, 'a/b c');
|
||||
assert.equal(calls[0][1], '/delayed_events/a%2Fb%20c');
|
||||
});
|
||||
|
||||
test('parseDelayedEvents: Synapse shape, messages only, sendAt from running_since + delay (#322)', () => {
|
||||
const res = {
|
||||
delayed_events: [
|
||||
{
|
||||
delay_id: 'syd_a',
|
||||
room_id: '!r:x',
|
||||
type: 'm.room.message',
|
||||
content: { msgtype: 'm.text', body: 'hi' },
|
||||
delay: 60000,
|
||||
running_since: 1000,
|
||||
},
|
||||
{
|
||||
delay_id: 'syd_call',
|
||||
room_id: '!r:x',
|
||||
type: 'org.matrix.msc3401.call.member',
|
||||
state_key: '_@a:x_D',
|
||||
content: {},
|
||||
delay: 8000,
|
||||
running_since: 1000,
|
||||
},
|
||||
{ delay_id: 'syd_bad', room_id: '!r:x', type: 'm.room.message', content: {} },
|
||||
null,
|
||||
],
|
||||
};
|
||||
assert.deepEqual(parseDelayedEvents(res), [
|
||||
{ delayId: 'syd_a', roomId: '!r:x', content: { msgtype: 'm.text', body: 'hi' }, sendAt: 61000 },
|
||||
]);
|
||||
});
|
||||
|
||||
test('parseDelayedEvents: MSC `scheduled` shape and garbage', () => {
|
||||
const item = {
|
||||
delay_id: 'd',
|
||||
room_id: '!r:x',
|
||||
type: 'm.room.message',
|
||||
content: { body: 'b' },
|
||||
delay_ms: 5,
|
||||
delayed_since_ts: 10,
|
||||
};
|
||||
assert.equal(parseDelayedEvents({ scheduled: [item] })[0].sendAt, 15);
|
||||
assert.deepEqual(parseDelayedEvents(undefined), []);
|
||||
assert.deepEqual(parseDelayedEvents({ delayed_events: 'nope' }), []);
|
||||
});
|
||||
|
||||
test('groupScheduledByRoom: groups and sorts by sendAt', () => {
|
||||
const m = (delayId: string, roomId: string, sendAt: number) => ({
|
||||
delayId,
|
||||
roomId,
|
||||
content: {},
|
||||
sendAt,
|
||||
});
|
||||
const g = groupScheduledByRoom([m('b', '!1', 20), m('a', '!1', 10), m('c', '!2', 5)]);
|
||||
assert.deepEqual(
|
||||
g.get('!1')?.map((x) => x.delayId),
|
||||
['a', 'b'],
|
||||
);
|
||||
assert.equal(g.get('!2')?.length, 1);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { IContent, MatrixClient, Method } from 'matrix-js-sdk';
|
||||
import type { ScheduledMessage } from '../state/scheduledMessages';
|
||||
|
||||
/**
|
||||
* Schedule a message via MSC4140 (delayed messages).
|
||||
@@ -77,61 +76,3 @@ export async function sendScheduledMessageNow(mx: MatrixClient, delayId: string)
|
||||
{ prefix: '/_matrix/client/unstable/org.matrix.msc4140' },
|
||||
);
|
||||
}
|
||||
|
||||
type DelayedEventItem = {
|
||||
delay_id?: unknown;
|
||||
room_id?: unknown;
|
||||
type?: unknown;
|
||||
state_key?: unknown;
|
||||
content?: unknown;
|
||||
delay?: unknown;
|
||||
delay_ms?: unknown;
|
||||
running_since?: unknown;
|
||||
delayed_since_ts?: unknown;
|
||||
};
|
||||
|
||||
/**
|
||||
* [Gitea #322] Pure: the user's pending scheduled messages from an MSC4140
|
||||
* `GET /delayed_events` response. Synapse answers `{ delayed_events: [...] }`;
|
||||
* the current MSC shape is `{ scheduled: [...] }`. Call-membership delayed
|
||||
* events share the endpoint, so only non-state `m.room.message`s are kept.
|
||||
*/
|
||||
export function parseDelayedEvents(res: unknown): ScheduledMessage[] {
|
||||
if (!res || typeof res !== 'object') return [];
|
||||
const r = res as { delayed_events?: unknown; scheduled?: unknown };
|
||||
const list = Array.isArray(r.delayed_events) ? r.delayed_events : r.scheduled;
|
||||
if (!Array.isArray(list)) return [];
|
||||
const out: ScheduledMessage[] = [];
|
||||
list.forEach((raw: DelayedEventItem) => {
|
||||
if (!raw || typeof raw !== 'object') return;
|
||||
if (raw.type !== 'm.room.message' || raw.state_key !== undefined) return;
|
||||
if (typeof raw.delay_id !== 'string' || typeof raw.room_id !== 'string') return;
|
||||
if (!raw.content || typeof raw.content !== 'object') return;
|
||||
const delay = Number(raw.delay ?? raw.delay_ms);
|
||||
const since = Number(raw.running_since ?? raw.delayed_since_ts);
|
||||
if (!Number.isFinite(delay) || !Number.isFinite(since)) return;
|
||||
out.push({
|
||||
delayId: raw.delay_id,
|
||||
roomId: raw.room_id,
|
||||
content: raw.content as IContent,
|
||||
sendAt: since + delay,
|
||||
});
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The user's pending scheduled messages, as the server has them. */
|
||||
export async function fetchScheduledMessages(mx: MatrixClient): Promise<ScheduledMessage[]> {
|
||||
const res = await mx.http.authedRequest(Method.Get, '/delayed_events', undefined, undefined, {
|
||||
prefix: '/_matrix/client/unstable/org.matrix.msc4140',
|
||||
});
|
||||
return parseDelayedEvents(res);
|
||||
}
|
||||
|
||||
/** Group by room, the shape of `scheduledMessagesAtom`. */
|
||||
export function groupScheduledByRoom(msgs: ScheduledMessage[]): Map<string, ScheduledMessage[]> {
|
||||
const map = new Map<string, ScheduledMessage[]>();
|
||||
msgs.forEach((m) => map.set(m.roomId, [...(map.get(m.roomId) ?? []), m]));
|
||||
map.forEach((list) => list.sort((a, b) => a.sendAt - b.sendAt));
|
||||
return map;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user