diff --git a/src/app/features/albums/AlbumView.tsx b/src/app/features/albums/AlbumView.tsx index c8961f0d..28e0c477 100644 --- a/src/app/features/albums/AlbumView.tsx +++ b/src/app/features/albums/AlbumView.tsx @@ -1,18 +1,36 @@ -import React, { useMemo, useState } from 'react'; +import React, { useEffect, useMemo, useState } from 'react'; import { Box, Scroll, Text } from 'folds'; -import { Room } from 'matrix-js-sdk'; +import { Room, RoomEvent } from 'matrix-js-sdk'; +import { MediaControl } from '../../components/media'; +import { AudioContent } from '../../components/message'; import { RenderMessageContent } from '../../components/RenderMessageContent'; +import { IAudioContent } from '../../../types/matrix/common'; import { LINKIFY_OPTS, getReactCustomHtmlParser } from '../../plugins/react-custom-html-parser'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; import { useSetting } from '../../state/hooks/settings'; import { settingsAtom } from '../../state/settings'; +import { markAsRead } from '../../utils/notifications'; +import { getBlobSafeMimeType } from '../../utils/mimeTypes'; import { timeDayMonYear } from '../../utils/time'; import { getMemberDisplayName } from '../../utils/room'; import { Album, AlbumFile } from './buildAlbums'; import { useAlbums } from './useAlbums'; import * as css from './AlbumView.css'; +/** + * Audio goes straight to AudioContent, skipping the chat Attachment frame and file-type badge: the + * title above it is the only label and the transport controls sit on the scene. Anything that is + * not playable audio falls through to the stock renderer (a file download). + */ +const playableAudio = (content: Record) => { + const c = content as IAudioContent; + const url = c.file?.url ?? c.url; + const mimeType = getBlobSafeMimeType(c.info?.mimetype ?? ''); + if (!c.info || typeof url !== 'string' || !mimeType.startsWith('audio')) return undefined; + return { info: c.info, url, mimeType, encInfo: c.file }; +}; + type FileRowProps = { room: Room; file: AlbumFile; author: string }; function FileRow({ room, file, author }: FileRowProps) { const mx = useMatrixClient(); @@ -23,32 +41,56 @@ function FileRow({ room, file, author }: FileRowProps) { getReactCustomHtmlParser(mx, room.roomId, { linkifyOpts: LINKIFY_OPTS, useAuthentication }), [mx, room.roomId, useAuthentication] ); + const audio = file.kind === 'audio' ? playableAudio(file.content) : undefined; return ( {file.name} - () => file.content as T} - mediaAutoLoad={mediaAutoLoad} - htmlReactParserOptions={htmlReactParserOptions} - linkifyOpts={LINKIFY_OPTS} - /> + {audio ? ( + } /> + ) : ( + () => file.content as T} + mediaAutoLoad={mediaAutoLoad} + htmlReactParserOptions={htmlReactParserOptions} + linkifyOpts={LINKIFY_OPTS} + /> + )} ); } const countLabel = (n: number) => `${n} ${n === 1 ? 'file' : 'files'}`; -export function AlbumView({ room }: { room: Room }) { +/** The zone never mounts RoomTimeline, so it sends the read receipt the timeline would. */ +function useMarkZoneRead(room: Room) { + const mx = useMatrixClient(); + const [hideActivity] = useSetting(settingsAtom, 'hideActivity'); + useEffect(() => { + const mark = () => { + markAsRead(mx, room.roomId, hideActivity).catch(() => undefined); + }; + mark(); + room.on(RoomEvent.Timeline, mark); + return () => { + room.off(RoomEvent.Timeline, mark); + }; + }, [mx, room, hideActivity]); +} + +type AlbumViewProps = { room: Room; onTimeline: () => void }; +export function AlbumView({ room, onTimeline }: AlbumViewProps) { + useMarkZoneRead(room); const { loading, error, albums } = useAlbums(room); const [dateFormat] = useSetting(settingsAtom, 'dateFormatString'); const [openId, setOpenId] = useState(); const open: Album | undefined = albums.find((a) => a.id === openId); const authorOf = (a: Album) => getMemberDisplayName(room, a.author) ?? a.author; + const encrypted = room.hasEncryptionStateEvent(); let body: React.ReactNode; if (loading) body = Loading albums…; @@ -72,7 +114,9 @@ export function AlbumView({ room }: { room: Room }) { ); - } else if (albums.length === 0) body = No albums yet.; + } else if (encrypted) + body = This zone is encrypted, so its albums cannot be listed here.; + else if (albums.length === 0) body = No albums yet.; else { body = albums.map((a) => ( + ); } diff --git a/src/app/features/albums/buildAlbums.test.ts b/src/app/features/albums/buildAlbums.test.ts index f589ba30..68ab6fc3 100644 --- a/src/app/features/albums/buildAlbums.test.ts +++ b/src/app/features/albums/buildAlbums.test.ts @@ -122,4 +122,41 @@ describe('buildAlbums', () => { ]); expect(a).toMatchObject({ title: '', author: '', ts: 0, count: 1 }); }); + + it('does not read inherited object keys as file kinds', () => { + const a = one(root('$r', 1), [ + reply('$c', 1, 'constructor'), + reply('$p', 2, '__proto__'), + reply('$t', 3, 'toString'), + ]); + expect(a.count).toBe(0); + }); + + it('skips events that are not room messages even if their content looks like media', () => { + const reaction = { ...reply('$x', 5, 'm.audio'), type: 'm.reaction' }; + const a = one(root('$r', 1), [reaction, reply('$ok', 6, 'm.audio')]); + expect(a.files.map((f) => f.id)).toEqual(['$ok']); + expect(buildAlbums([{ root: root('$g', 1, { type: 'm.reaction' }), replies: [] }])).toEqual([]); + }); + + it('skips events without an event id', () => { + const anon: ZoneEvent = { type: 'm.room.message', content: { msgtype: 'm.audio', body: 'a' } }; + expect(one(root('$r', 1), [anon]).count).toBe(0); + expect( + buildAlbums([{ root: { content: { msgtype: 'm.text', body: 'x' } }, replies: [] }]) + ).toEqual([]); + }); + + it('titles an edited album by its latest edit', () => { + const edited = root('$r', 1, { + unsigned: { + 'm.relations': { + 'm.replace': { content: { 'm.new_content': { msgtype: 'm.text', body: 'renamed' } } }, + }, + }, + }); + expect(one(edited, []).title).toBe('renamed'); + const emptyEdit = root('$q', 1, { unsigned: { 'm.relations': { 'm.replace': {} } } }); + expect(one(emptyEdit, []).title).toBe('album $q'); + }); }); diff --git a/src/app/features/albums/buildAlbums.ts b/src/app/features/albums/buildAlbums.ts index f104c19e..1f8c944e 100644 --- a/src/app/features/albums/buildAlbums.ts +++ b/src/app/features/albums/buildAlbums.ts @@ -35,12 +35,13 @@ export type Album = { count: number; }; -const KIND_OF_MSGTYPE: Record = { - 'm.audio': 'audio', - 'm.image': 'image', - 'm.video': 'video', - 'm.file': 'file', -}; +// A Map, not an object: msgtype is server-supplied and "constructor" must not name a kind. +const KIND_OF_MSGTYPE = new Map([ + ['m.audio', 'audio'], + ['m.image', 'image'], + ['m.video', 'video'], + ['m.file', 'file'], +]); // A redacted event keeps its id but loses its content and gains unsigned.redacted_because. const live = ( @@ -55,7 +56,7 @@ const asString = (v: unknown): string => (typeof v === 'string' ? v : ''); const toFile = (e: ZoneEvent): AlbumFile | undefined => { if (!live(e)) return undefined; - const kind = KIND_OF_MSGTYPE[e.content.msgtype as string]; + const kind = KIND_OF_MSGTYPE.get(e.content.msgtype as string); if (!kind) return undefined; return { id: e.event_id, @@ -66,6 +67,15 @@ const toFile = (e: ZoneEvent): AlbumFile | undefined => { }; }; +// An edited root carries its latest edit under unsigned["m.relations"]["m.replace"]; the title is +// that edit's m.new_content.body, else the original body. +const titleOf = (root: ZoneEvent & { content: Record }): string => { + const relations = root.unsigned?.['m.relations'] as Record | undefined; + const edit = relations?.['m.replace'] as ZoneEvent | undefined; + const edited = (edit?.content?.['m.new_content'] as Record | undefined)?.body; + return asString(edited) || asString(root.content.body); +}; + const toAlbum = ({ root, replies }: AlbumInput): Album | undefined => { if (!live(root)) return undefined; const seen = new Set(); @@ -79,7 +89,7 @@ const toAlbum = ({ root, replies }: AlbumInput): Album | undefined => { .sort((a, b) => a.ts - b.ts); return { id: root.event_id, - title: asString(root.content.body), + title: titleOf(root), author: root.sender ?? '', ts: root.origin_server_ts ?? 0, cover: files.find((f) => f.kind === 'image'), diff --git a/src/app/features/albums/isFileZone.test.ts b/src/app/features/albums/isFileZone.test.ts index 295fd60b..0e55269f 100644 --- a/src/app/features/albums/isFileZone.test.ts +++ b/src/app/features/albums/isFileZone.test.ts @@ -9,6 +9,8 @@ describe('isFileZone', () => { }); it('is false for other create types and for plain rooms', () => { expect(isFileZone({ ...room, createType: 'm.space' }, {})).toBe(false); + expect(isFileZone({ ...room, createType: 'org.gamecult.other' }, {})).toBe(false); + expect(isFileZone({ ...room, createType: 'org.gamecult.file_zone.x' }, {})).toBe(false); expect(isFileZone(room, {})).toBe(false); expect(isFileZone(room, { fileZoneRooms: [] })).toBe(false); }); diff --git a/src/app/features/albums/mapLimit.test.ts b/src/app/features/albums/mapLimit.test.ts new file mode 100644 index 00000000..24898cb0 --- /dev/null +++ b/src/app/features/albums/mapLimit.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest'; +import { mapLimit } from './mapLimit'; + +describe('mapLimit', () => { + it('keeps result order and never exceeds the limit', async () => { + let inFlight = 0; + let peak = 0; + const out = await mapLimit([5, 1, 4, 2, 3, 0], 2, async (n) => { + inFlight += 1; + peak = Math.max(peak, inFlight); + await new Promise((r) => { + setTimeout(r, n); + }); + inFlight -= 1; + return n * 10; + }); + expect(out).toEqual([50, 10, 40, 20, 30, 0]); + expect(peak).toBe(2); + }); + it('handles an empty list and rejects when a call rejects', async () => { + expect(await mapLimit([], 3, async (n) => n)).toEqual([]); + await expect( + mapLimit([1, 2], 2, async (n) => { + if (n === 2) throw new Error('boom'); + return n; + }) + ).rejects.toThrow('boom'); + }); +}); diff --git a/src/app/features/albums/mapLimit.ts b/src/app/features/albums/mapLimit.ts new file mode 100644 index 00000000..e850add0 --- /dev/null +++ b/src/app/features/albums/mapLimit.ts @@ -0,0 +1,19 @@ +/** Like Promise.all(items.map(fn)) but with at most `limit` calls in flight; result order kept. */ +export const mapLimit = async ( + items: T[], + limit: number, + fn: (item: T) => Promise +): Promise => { + const out = new Array(items.length); + let next = 0; + const worker = async () => { + while (next < items.length) { + const i = next; + next += 1; + // eslint-disable-next-line no-await-in-loop + out[i] = await fn(items[i]); + } + }; + await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker)); + return out; +}; diff --git a/src/app/features/albums/useAlbums.ts b/src/app/features/albums/useAlbums.ts index e883c838..a01f1efb 100644 --- a/src/app/features/albums/useAlbums.ts +++ b/src/app/features/albums/useAlbums.ts @@ -1,15 +1,23 @@ import { useQuery } from '@tanstack/react-query'; import { ClientPrefix, Method, Room } from 'matrix-js-sdk'; +import { StateEvent } from '../../../types/matrix/room'; +import { useStateEvent } from '../../hooks/useStateEvent'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useClientConfig } from '../../hooks/useClientConfig'; import { Album, ZoneEvent, buildAlbums } from './buildAlbums'; import { isFileZone } from './isFileZone'; +import { mapLimit } from './mapLimit'; + +const REPLY_FETCHES_IN_FLIGHT = 6; +const REFRESH_MS = 30_000; type Chunk = { chunk?: ZoneEvent[] }; /** True when the room is the file zone: by its create type, or listed in the client config. */ export const useIsFileZone = (room: Room): boolean => { const config = useClientConfig(); + // Subscribes to alias changes (alt aliases live in the same event). + useStateEvent(room, StateEvent.RoomCanonicalAlias); const createType = room.currentState.getStateEvents('m.room.create', '')?.getContent().type; return isFileZone( { @@ -41,24 +49,25 @@ export const useAlbums = (room: Room): AlbumsState => { }); const room_ = encodeURIComponent(roomId); const roots = (await get(`/rooms/${room_}/threads`, { limit: '100' })).chunk ?? []; - const inputs = await Promise.all( - roots.map(async (root: ZoneEvent) => ({ - root, - replies: - ( - await get( - `/rooms/${room_}/relations/${encodeURIComponent(root.event_id ?? '')}/m.thread`, - { limit: '100', dir: 'f' } - ) - ).chunk ?? [], - })) - ); + const inputs = await mapLimit(roots, REPLY_FETCHES_IN_FLIGHT, async (root: ZoneEvent) => ({ + root, + replies: + ( + await get( + `/rooms/${room_}/relations/${encodeURIComponent(root.event_id ?? '')}/m.thread`, + { limit: '100', dir: 'f' } + ) + ).chunk ?? [], + })); return buildAlbums(inputs); }, + retry: 1, + refetchInterval: REFRESH_MS, }); return { loading: query.isLoading, - error: query.error as Error | null, + // A failed refetch keeps the albums already loaded; the error shows only when there are none. + error: query.data ? null : (query.error as Error | null), albums: query.data ?? [], }; }; diff --git a/src/app/features/albums/zoneView.test.ts b/src/app/features/albums/zoneView.test.ts new file mode 100644 index 00000000..9774fb25 --- /dev/null +++ b/src/app/features/albums/zoneView.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from 'vitest'; +import { zoneView } from './zoneView'; + +describe('zoneView', () => { + it('opens albums by default and the timeline for an event deep link', () => { + expect(zoneView(undefined, undefined)).toBe('albums'); + expect(zoneView(undefined, '$e')).toBe('timeline'); + }); + it('lets the user go back to albums or on to the timeline whatever the link said', () => { + expect(zoneView('albums', '$e')).toBe('albums'); + expect(zoneView('timeline', undefined)).toBe('timeline'); + }); +}); diff --git a/src/app/features/albums/zoneView.ts b/src/app/features/albums/zoneView.ts new file mode 100644 index 00000000..2532bcc5 --- /dev/null +++ b/src/app/features/albums/zoneView.ts @@ -0,0 +1,5 @@ +export type ZoneView = 'albums' | 'timeline'; + +/** The view a file-zone room shows: the user's choice, else the timeline for an event deep link, else albums. */ +export const zoneView = (choice: ZoneView | undefined, eventId: string | undefined): ZoneView => + choice ?? (eventId ? 'timeline' : 'albums'); diff --git a/src/app/features/room/RoomView.tsx b/src/app/features/room/RoomView.tsx index 4ead415d..b61f54de 100644 --- a/src/app/features/room/RoomView.tsx +++ b/src/app/features/room/RoomView.tsx @@ -1,4 +1,4 @@ -import React, { useCallback, useRef } from 'react'; +import React, { useCallback, useRef, useState } from 'react'; import { Box, Text, config } from 'folds'; import { EventType } from 'matrix-js-sdk'; import { ReactEditor } from 'slate-react'; @@ -24,7 +24,9 @@ import { useRoomPermissions } from '../../hooks/useRoomPermissions'; import { useRoomCreators } from '../../hooks/useRoomCreators'; import { useRoom } from '../../hooks/useRoom'; import { AlbumView } from '../albums/AlbumView'; +import * as albumCss from '../albums/AlbumView.css'; import { useIsFileZone } from '../albums/useAlbums'; +import { ZoneView, zoneView } from '../albums/zoneView'; const FN_KEYS_REGEX = /^F\d+$/; const shouldFocusMessageField = (evt: KeyboardEvent): boolean => { @@ -66,7 +68,12 @@ export function RoomView({ eventId }: { eventId?: string }) { const room = useRoom(); const { roomId } = room; const editor = useEditor(); - const fileZone = useIsFileZone(room); + const isZone = useIsFileZone(room); + // A zone shows its albums; the timeline stays one tap away, and an event deep link opens it. + const [choice, setChoice] = useState<{ roomId: string; view: ZoneView }>(); + const fileZone = + isZone && + zoneView(choice && choice.roomId === roomId ? choice.view : undefined, eventId) === 'albums'; const mx = useMatrixClient(); @@ -98,7 +105,11 @@ export function RoomView({ eventId }: { eventId?: string }) { if (fileZone) { return ( - + setChoice({ roomId, view: 'timeline' })} + /> ); } @@ -106,6 +117,15 @@ export function RoomView({ eventId }: { eventId?: string }) { return ( + {isZone && ( + + )}