diff --git a/TelegramDownloader/ClientApp/ARCHITECTURE.md b/TelegramDownloader/ClientApp/ARCHITECTURE.md index 93cc662..8243cd9 100644 --- a/TelegramDownloader/ClientApp/ARCHITECTURE.md +++ b/TelegramDownloader/ClientApp/ARCHITECTURE.md @@ -226,6 +226,14 @@ not import TFM code. TFM providers and actions live in the app: providers' `list`) and the listings are invalidated when it ends. `` (layout, bottom left of the content) lazy-loads the stacked cards; the transfers popover lists the running ones under "Other operations". + `files/cue/`: cue sheets (an album in one audio file). Opening a `.cue` shows its tracks + (`GET .../files/{id}/cue`, `GET /api/v1/local/cue`); each track is queued as an `AudioTrack` + with a `clip` (`start`/`end` in seconds of the file). The engine plays clips in file time and + shows track time (`player/clip.ts`); consecutive clips of one file continue without reloading. + `files/audioInfo.ts`: the channel provider asks `POST .../files/audio-info` (capability + `files.audioInfo`, batches of 500, in the background) for the audio files it lists; the rows show + "Performer – Title · duration" through the file manager's `describeEntry`, and `toTrack()` uses + title/artist/duration/cover as the initial metadata of queued tracks. - `features/channels/`: channel provider (`createChannelProvider`, also used read only for shared collections with `collectionId`), TFM actions, header (refresh with live progress, export/import index, WebDAV, statistics, delete index, link to the chat view). diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/channels/lib/channelActions.ts b/TelegramDownloader/ClientApp/apps/web/src/features/channels/lib/channelActions.ts index fa461ef..9822794 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/channels/lib/channelActions.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/features/channels/lib/channelActions.ts @@ -50,7 +50,7 @@ export function channelActions({ channelId, channelName, collectionId, openDialo order: 11, run: (entries) => openDialog({ type: 'download', entries }) }, - ...mediaActions({ channelId, sourceName: channelName }) + ...mediaActions({ channelId, collectionId, sourceName: channelName }) ]; if (!own) return actions; diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/channels/lib/channelProvider.ts b/TelegramDownloader/ClientApp/apps/web/src/features/channels/lib/channelProvider.ts index 4fa5011..8db3a43 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/channels/lib/channelProvider.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/features/channels/lib/channelProvider.ts @@ -1,5 +1,6 @@ -import type { FileEntry, FileSystemProvider, Page, ProviderCapabilities } from '@tfm/file-manager'; +import { entryMediaKind, type FileEntry, type FileSystemProvider, type Page, type ProviderCapabilities } from '@tfm/file-manager'; import { toast } from '@tfm/ui'; +import { getAudioInfo, loadAudioInfo } from '@/features/files/audioInfo'; import { downloadUrls, uploadBody, xhrUpload } from '@/features/files/browser'; import { withoutPendingDeletes } from '@/features/files/deletes/deleteStore'; import { startDelete } from '@/features/files/deletes/deleteTracker'; @@ -53,6 +54,13 @@ export function createChannelProvider({ channelId, rootName, collectionId }: Cha const id = channelProviderId(channelId, collectionId); + // Telegram's title/performer/duration/cover of the audio files shown, in the background + const withAudioInfo = (items: FileEntry[]) => { + const audio = items.filter((e) => e.kind === 'file' && entryMediaKind(e) === 'audio').map((e) => e.id); + if (audio.length) void loadAudioInfo(channelId, audio, collectionId); + return items; + }; + return { id, rootName, @@ -74,7 +82,7 @@ export function createChannelProvider({ channelId, rootName, collectionId }: Cha ); let items = withoutPendingDeletes(id, res.contents.items.map(toEntry)); if (options?.filter?.kind) items = items.filter((e) => e.kind === options.filter?.kind); - return page(items, res.page); + return page(withAudioInfo(items), res.page); }, async search(path, query, options) { @@ -91,7 +99,7 @@ export function createChannelProvider({ channelId, rootName, collectionId }: Cha }, options?.signal ); - return page(withoutPendingDeletes(id, res.items.map(toEntry)), res.page); + return page(withAudioInfo(withoutPendingDeletes(id, res.items.map(toEntry))), res.page); }, async createFolder(parentPath, name) { @@ -134,6 +142,7 @@ export function createChannelProvider({ channelId, rootName, collectionId }: Cha }, previewUrl: (entry) => (entry.kind === 'file' ? dtoOf(entry).contentUrl ?? undefined : undefined), - thumbnailUrl: (entry) => dtoOf(entry)?.thumbnailUrl ?? undefined + // Audio files show the cover Telegram keeps for them, once the details have arrived + thumbnailUrl: (entry) => dtoOf(entry)?.thumbnailUrl ?? (entry.kind === 'file' ? getAudioInfo(channelId, entry.id, collectionId)?.coverUrl : undefined) }; } diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/channels/pages/ChannelPage.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/channels/pages/ChannelPage.tsx index 5b60bdc..54c3eeb 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/channels/pages/ChannelPage.tsx +++ b/TelegramDownloader/ClientApp/apps/web/src/features/channels/pages/ChannelPage.tsx @@ -6,6 +6,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react'; import { useNavigate, useParams } from 'react-router'; import { DownloadToServerDialog } from '@/features/files/DownloadToServerDialog'; import { confirmDelete, fmLocale, reportError, reportSuccess } from '@/features/files/fileManagerOptions'; +import { useEntryDescriber } from '@/features/files/describeEntry'; import { openMedia } from '@/features/files/media'; import { fileManagerStrings } from '@/features/files/strings'; import { useRoutePath } from '@/features/files/useRoutePath'; @@ -39,6 +40,7 @@ export default function ChannelPage() { }, [detail.data?.name]); const provider = useMemo(() => createChannelProvider({ channelId, rootName: name }), [channelId, name]); + const describeEntry = useEntryDescriber(channelId); const navigate = useNavigate(); const openMessage = useCallback((messageId: number) => void navigate(`/chat/${encodeURIComponent(channelId)}?message=${messageId}`), [channelId, navigate]); const actions = useMemo(() => channelActions({ channelId, channelName: name, openDialog: setDialog, openMessage }), [channelId, name, openMessage]); @@ -73,6 +75,7 @@ export default function ChannelPage() { } }) } + describeEntry={describeEntry} className="flex-1" /> ); diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/audioInfo.test.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/audioInfo.test.ts new file mode 100644 index 0000000..ffe0b64 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/audioInfo.test.ts @@ -0,0 +1,92 @@ +import type { ApiAudioInfoDto } from '@tfm/api-client'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('@/lib/api', () => ({ api: { files: { audioInfo: vi.fn() }, system: { capabilities: vi.fn() } } })); + +const { api } = await import('@/lib/api'); +const { resetServerFeatures } = await import('@/lib/serverFeatures'); +const info = await import('./audioInfo'); +const { describeEntry } = await import('./describeEntry'); +const { toTrack, toEntry } = await import('./entries'); + +const audioInfo = vi.mocked(api.files.audioInfo); +const capabilities = vi.mocked(api.system.capabilities); + +const answer = (ids: string[]): ApiAudioInfoDto[] => + ids.map((id) => ({ fileId: id, title: `T ${id}`, performer: 'P', duration: 200, hasCover: true, coverUrl: `/thumb/${id}` })); + +beforeEach(() => { + info.__resetAudioInfoForTests(); + resetServerFeatures(); + audioInfo.mockReset(); + capabilities.mockReset(); + capabilities.mockResolvedValue({ apiVersion: 1, serverVersion: 'x', features: ['files.audioInfo'] }); + audioInfo.mockImplementation(async (_c, body) => answer(body.fileIds)); +}); + +afterEach(() => vi.clearAllMocks()); + +describe('audio info', () => { + it('splits the ids into batches of 500', () => { + const ids = Array.from({ length: 1201 }, (_, i) => `f${i}`); + expect(info.batches(ids).map((b) => b.length)).toEqual([500, 500, 201]); + }); + + it('asks in batches, merges the answers and caches them per channel', async () => { + const ids = Array.from({ length: 501 }, (_, i) => `f${i}`); + await info.loadAudioInfo('42', ids); + expect(audioInfo).toHaveBeenCalledTimes(2); + expect(audioInfo.mock.calls[0][1].fileIds).toHaveLength(500); + expect(audioInfo.mock.calls[1][1].fileIds).toEqual(['f500']); + expect(info.getAudioInfo('42', 'f7')).toEqual({ title: 'T f7', performer: 'P', duration: 200, coverUrl: '/thumb/f7' }); + expect(info.getAudioInfo('43', 'f7')).toBeUndefined(); // another channel + + await info.loadAudioInfo('42', ['f1', 'f2', 'new']); + expect(audioInfo).toHaveBeenCalledTimes(3); + expect(audioInfo.mock.calls[2][1].fileIds).toEqual(['new']); // only what is not known + }); + + it('keeps collections apart and sends their id', async () => { + await info.loadAudioInfo('42', ['a'], 'col'); + expect(audioInfo.mock.calls[0][1]).toEqual({ fileIds: ['a'], collectionId: 'col' }); + expect(info.getAudioInfo('42', 'a', 'col')?.title).toBe('T a'); + expect(info.getAudioInfo('42', 'a')).toBeUndefined(); + }); + + it('remembers files Telegram has nothing for, and ignores failures', async () => { + audioInfo.mockResolvedValueOnce([{ fileId: 'a', hasCover: false }]); + await info.loadAudioInfo('42', ['a', 'b']); + expect(info.getAudioInfo('42', 'a')).toBeNull(); + expect(info.getAudioInfo('42', 'b')).toBeNull(); // missing from the answer + + audioInfo.mockRejectedValueOnce(new Error('boom')); + await expect(info.loadAudioInfo('42', ['c'])).resolves.toBeUndefined(); + expect(info.getAudioInfo('42', 'c')).toBeUndefined(); // asked again later + }); + + it('does not call an older server without the capability', async () => { + capabilities.mockResolvedValue({ apiVersion: 1, serverVersion: 'x', features: [] }); + await info.loadAudioInfo('42', ['a']); + expect(audioInfo).not.toHaveBeenCalled(); + expect(info.getAudioInfo('42', 'a')).toBeNull(); + }); + + it('labels and describes audio rows', async () => { + expect(info.audioInfoLabel({ title: 'Song', performer: 'Band' })).toBe('Band – Song'); + expect(info.audioInfoLabel({ title: 'Song' })).toBe('Song'); + const song = toEntry({ id: 's', name: 'Album.flac', path: '/', isFile: true, size: 1, category: 'Audio', type: '.flac' } as never); + const cue = toEntry({ id: 'c', name: 'album.cue', path: '/', isFile: true, size: 1, category: 'Document', type: '.cue' } as never); + const other = toEntry({ id: 'o', name: 'other.mp3', path: '/', isFile: true, size: 1, category: 'Audio', type: '.mp3' } as never); + const entries = [song, cue, other]; + expect(describeEntry(song, entries, { title: 'Song', performer: 'Band', duration: 225 })).toEqual({ subtitle: 'Band – Song', meta: ['3:45'], badge: 'CUE' }); + expect(describeEntry(cue, entries, undefined)).toEqual({ subtitle: undefined, meta: undefined, badge: 'CUE' }); + expect(describeEntry(other, entries, null)).toBeUndefined(); + }); + + it('queued tracks start with the Telegram details', async () => { + await info.loadAudioInfo('42', ['s']); + const song = toEntry({ id: 's', name: 'track01.mp3', path: '/', isFile: true, size: 1, category: 'Audio', type: '.mp3', contentUrl: '/c/s' } as never); + expect(toTrack(song, { channelId: '42' })).toMatchObject({ title: 'T s', artist: 'P', durationSeconds: 200, coverUrl: '/thumb/s', url: '/c/s' }); + expect(toTrack(song, { channelId: '99' })).toMatchObject({ title: 'track01', artist: undefined }); + }); +}); diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/audioInfo.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/audioInfo.ts new file mode 100644 index 0000000..37a5e92 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/audioInfo.ts @@ -0,0 +1,122 @@ +import type { ApiAudioInfoDto } from '@tfm/api-client'; +import { create } from 'zustand'; +import { api } from '@/lib/api'; +import { hasServerFeature } from '@/lib/serverFeatures'; + +/** + * The title, performer, duration and cover Telegram keeps for audio + * documents (`POST /api/v1/channels/{id}/files/audio-info`), read without + * downloading the files. The channel listings ask for the audio files they + * show, in the background; the rows and the tracks queued from them use the + * answers. Kept in memory per channel (or shared collection) + file id. + */ + +export const AUDIO_INFO_FEATURE = 'files.audioInfo'; +/** Most ids one request may carry (the server limit). */ +export const AUDIO_INFO_BATCH = 500; + +export interface AudioInfo { + title?: string; + performer?: string; + /** Seconds. */ + duration?: number; + coverUrl?: string; +} + +interface AudioInfoState { + /** null = asked, Telegram has nothing for the file. */ + byKey: Record; +} + +export const useAudioInfo = create()(() => ({ byKey: {} })); + +const inflight = new Set(); + +/** Cache scope of a channel, or of a shared collection of it. */ +export function audioInfoScope(channelId: string, collectionId?: string): string { + return collectionId ? `${channelId}@${collectionId}` : channelId; +} + +/** Store key of a file. */ +export function audioInfoKey(scope: string, fileId: string): string { + return `${scope}:${fileId}`; +} + +/** What is known of a file: details, null (nothing) or undefined (not asked yet). */ +export function getAudioInfo(channelId: string, fileId: string, collectionId?: string): AudioInfo | null | undefined { + return useAudioInfo.getState().byKey[audioInfoKey(audioInfoScope(channelId, collectionId), fileId)]; +} + +/** The useful part of an answer, or null when Telegram has nothing. */ +export function toAudioInfo(dto: ApiAudioInfoDto): AudioInfo | null { + const info: AudioInfo = {}; + if (dto.title?.trim()) info.title = dto.title.trim(); + if (dto.performer?.trim()) info.performer = dto.performer.trim(); + if (dto.duration && dto.duration > 0) info.duration = dto.duration; + if (dto.hasCover && dto.coverUrl) info.coverUrl = dto.coverUrl; + return Object.keys(info).length ? info : null; +} + +/** "Performer – Title", or whichever of the two is known. */ +export function audioInfoLabel(info: AudioInfo | null | undefined): string | undefined { + if (!info) return undefined; + if (info.performer && info.title) return `${info.performer} – ${info.title}`; + return info.title ?? info.performer; +} + +/** Splits `items` into chunks of at most `size`. */ +export function batches(items: T[], size = AUDIO_INFO_BATCH): T[][] { + const out: T[][] = []; + for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size)); + return out; +} + +/** + * Asks the server for the details of the files not known yet (in batches of + * 500) and merges the answers into the store. Never throws: a failed batch + * is simply asked again by a later listing. Ids missing from an answer are + * remembered as "nothing". + */ +export async function loadAudioInfo(channelId: string, fileIds: string[], collectionId?: string): Promise { + if (!channelId || fileIds.length === 0) return; + const scope = audioInfoScope(channelId, collectionId); + const known = useAudioInfo.getState().byKey; + const wanted = [...new Set(fileIds)].filter((id) => { + const key = audioInfoKey(scope, id); + return !(key in known) && !inflight.has(key); + }); + if (wanted.length === 0) return; + wanted.forEach((id) => inflight.add(audioInfoKey(scope, id))); + try { + if (!(await hasServerFeature(AUDIO_INFO_FEATURE))) { + // An older server: remember "nothing" so the listings stop asking + merge(scope, wanted, []); + return; + } + await Promise.all( + batches(wanted).map(async (ids) => { + try { + const answer = await api.files.audioInfo(channelId, { fileIds: ids, collectionId }); + merge(scope, ids, answer ?? []); + } catch { + // Ignored: the listing works without the details + } + }) + ); + } finally { + wanted.forEach((id) => inflight.delete(audioInfoKey(scope, id))); + } +} + +function merge(scope: string, asked: string[], answer: ApiAudioInfoDto[]): void { + const update: Record = {}; + for (const id of asked) update[audioInfoKey(scope, id)] = null; + for (const dto of answer) if (dto?.fileId) update[audioInfoKey(scope, dto.fileId)] = toAudioInfo(dto); + useAudioInfo.setState((s) => ({ byKey: { ...s.byKey, ...update } })); +} + +/** Test helper: forget everything. */ +export function __resetAudioInfoForTests(): void { + inflight.clear(); + useAudioInfo.setState({ byKey: {} }); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/CueSheetDialog.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/CueSheetDialog.tsx new file mode 100644 index 0000000..00e6afd --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/CueSheetDialog.tsx @@ -0,0 +1,136 @@ +import { useQuery } from '@tanstack/react-query'; +import { Button, cn, Dialog, DialogContent, IconButton, Skeleton } from '@tfm/ui'; +import { AlertTriangle, ListEnd, ListVideo, Play } from 'lucide-react'; +import { useMemo } from 'react'; +import { formatTime } from '@/features/player/format'; +import { enqueueAudio, playAudio } from '@/features/player/public'; +import { t } from '@/i18n'; +import { api, errorMessage } from '@/lib/api'; +import { cueRows, playableFrom, type CueRow } from './cueModel'; +import { closeCueSheet, useCueSheet, type CueRequest } from './cueStore'; + +function fetchSheet(request: CueRequest, signal: AbortSignal) { + if (request.local) return api.local.cue({ path: request.id }, signal); + return api.files.cue(request.channelId ?? '', request.id, { collectionId: request.collectionId }, signal); +} + +/** A cue sheet as an album: its tracks, play all / from a track, add to the queue. */ +export default function CueSheetDialog() { + const request = useCueSheet((s) => s.request); + const { data: sheet, error, isLoading } = useQuery({ + queryKey: ['files', 'cue', request?.local ? 'local' : (request?.channelId ?? ''), request?.collectionId ?? '', request?.id ?? ''], + queryFn: ({ signal }) => fetchSheet(request as CueRequest, signal), + enabled: !!request, + staleTime: 60_000 + }); + const rows = useMemo(() => (sheet && request ? cueRows(sheet, request) : []), [sheet, request]); + const playable = useMemo(() => playableFrom(rows), [rows]); + + if (!request) return null; + + const play = (fromNumber?: number) => { + const { tracks, index } = playableFrom(rows, fromNumber); + if (tracks.length === 0) return; + playAudio(tracks, index); + closeCueSheet(); + }; + const enqueue = (tracks: CueRow['track'][], position: 'next' | 'end') => { + const list = tracks.filter((x): x is NonNullable => !!x); + if (list.length) enqueueAudio(list, position); + }; + + const description = sheet + ? [sheet.performer, sheet.date, sheet.genre, t('{count} tracks', { count: sheet.tracks.length })].filter(Boolean).join(' · ') + : request.name; + + return ( + !open && closeCueSheet()}> + + + + + } + > + {error ? ( +
+ + + {t('Could not read the cue sheet')} + {errorMessage(error)} + +
+ ) : null} + + {sheet && sheet.missingFiles.length > 0 && ( +

+ + {t('Audio files not found next to the cue sheet: {names}', { names: sheet.missingFiles.join(', ') })} +

+ )} + +
    + {isLoading && + Array.from({ length: 6 }, (_, i) => ( +
  1. + +
  2. + ))} + {sheet && rows.length === 0 &&
  3. {t('The cue sheet has no tracks')}
  4. } + {rows.map((row) => { + const missing = !row.track; + return ( +
  5. + + {!missing && ( + + enqueue([row.track], 'next')}> + + + enqueue([row.track], 'end')}> + + + + )} +
  6. + ); + })} +
+
+
+ ); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/CueSheetSlot.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/CueSheetSlot.tsx new file mode 100644 index 0000000..1bc3e73 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/CueSheetSlot.tsx @@ -0,0 +1,15 @@ +import { lazy, Suspense } from 'react'; +import { useCueSheet } from './cueStore'; + +const CueSheetDialog = lazy(() => import('./CueSheetDialog')); + +/** Mounts the cue sheet dialog (lazy) while it is open. Rendered by the player slot. */ +export function CueSheetSlot() { + const open = useCueSheet((s) => s.request !== null); + if (!open) return null; + return ( + + + + ); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueModel.test.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueModel.test.ts new file mode 100644 index 0000000..478f3b7 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueModel.test.ts @@ -0,0 +1,92 @@ +import type { ApiCueSheetDto, ApiFileDto } from '@tfm/api-client'; +import { describe, expect, it, vi } from 'vitest'; + +vi.mock('@/lib/api', () => ({ api: { files: { audioInfo: vi.fn() }, system: { capabilities: vi.fn() } } })); + +const { cueRows, cueTrackToAudio, isCueName, playableFrom } = await import('./cueModel'); + +const file = (id: string, name: string): ApiFileDto => + ({ + id, + name, + path: '/music/', + isFile: true, + size: 300_000_000, + category: 'Audio', + contentUrl: `/api/v1/channels/1/files/${id}/content`, + playbackUrl: `/api/v1/channels/1/files/${id}/content` + }) as ApiFileDto; + +const sheet: ApiCueSheetDto = { + id: 'cue1', + name: 'Album.cue', + title: 'The Album', + performer: 'The Band', + date: '1999', + genre: 'Rock', + missingFiles: ['bonus.wav'], + tracks: [ + { number: 1, title: 'Intro', performer: null, start: 0, end: 62.5, fileName: 'Album.wav', file: file('f1', 'Album.flac') }, + { number: 2, title: '', performer: 'Guest', start: 62.5, end: 300, fileName: 'Album.wav', file: file('f1', 'Album.flac') }, + { number: 3, title: 'Outro', start: 300, end: null, fileName: 'Album.wav', file: file('f1', 'Album.flac') }, + { number: 4, title: 'Bonus', start: 0, end: null, fileName: 'bonus.wav', file: null } + ] +}; + +describe('cue sheet → player tracks', () => { + it('maps a track to a clip of its file', () => { + const track = cueTrackToAudio(sheet, sheet.tracks[0], { channelId: '1', sourceName: 'Music' }); + expect(track).toEqual({ + id: 'cue:cue1#1', + title: 'Intro', + artist: 'The Band', + album: 'The Album', + source: 'Music', + url: '/api/v1/channels/1/files/f1/content', + channelId: '1', + fileId: 'f1', + localPath: undefined, + size: 300_000_000, + clip: { start: 0, end: 62.5 } + }); + }); + + it('falls back to "Track N" and to the track performer, and plays the last track to the end of the file', () => { + const second = cueTrackToAudio(sheet, sheet.tracks[1], { channelId: '1' }); + expect(second?.title).toBe('Track 2'); + expect(second?.artist).toBe('Guest'); + expect(cueTrackToAudio(sheet, sheet.tracks[2], { channelId: '1' })?.clip).toEqual({ start: 300, end: null }); + }); + + it('has no track for a missing file', () => { + expect(cueTrackToAudio(sheet, sheet.tracks[3], { channelId: '1' })).toBeNull(); + }); + + it('local sheets use local paths', () => { + const track = cueTrackToAudio({ ...sheet, id: 'music/Album.cue' }, { ...sheet.tracks[0], file: file('music/Album.flac', 'Album.flac') }, { local: true }); + expect(track?.id).toBe('cue:local:music/Album.cue#1'); + expect(track?.localPath).toBe('music/Album.flac'); + expect(track?.channelId).toBeUndefined(); + expect(track?.fileId).toBeUndefined(); + }); + + it('builds the rows with durations, and the playable queue from a track', () => { + const rows = cueRows(sheet, { channelId: '1' }); + expect(rows.map((r) => [r.number, r.title, r.duration])).toEqual([ + [1, 'Intro', 62.5], + [2, 'Track 2', 237.5], + [3, 'Outro', undefined], + [4, 'Bonus', undefined] + ]); + expect(rows[3].track).toBeNull(); + const all = playableFrom(rows); + expect(all.tracks.map((t) => t.id)).toEqual(['cue:cue1#1', 'cue:cue1#2', 'cue:cue1#3']); + expect(all.index).toBe(0); + expect(playableFrom(rows, 3).index).toBe(2); + }); + + it('recognises cue files', () => { + expect(isCueName('Album.CUE')).toBe(true); + expect(isCueName('Album.cue.txt')).toBe(false); + }); +}); diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueModel.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueModel.ts new file mode 100644 index 0000000..e3dab39 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueModel.ts @@ -0,0 +1,86 @@ +import type { ApiCueSheetDto, ApiCueTrackDto } from '@tfm/api-client'; +import type { AudioTrack } from '@/features/player/public'; +import { t } from '@/i18n'; +import { audioUrlOf } from '../entries'; + +/** Where a cue sheet lives and how its tracks are labelled in the player. */ +export interface CueSource { + /** Channel of the sheet (undefined for local files). */ + channelId?: string; + /** Shared collection the sheet is read from. */ + collectionId?: string; + /** Local files: the URLs of the matched files are local ones. */ + local?: boolean; + /** Label shown by the player under the title (channel name, "Local files"...). */ + sourceName?: string; +} + +/** One row of the cue sheet dialog. */ +export interface CueRow { + number: number; + title: string; + performer?: string; + /** Seconds (end - start); undefined for the last track of a file (its end is the end of the file). */ + duration?: number; + /** The player track, or null when its audio file is missing. */ + track: AudioTrack | null; + /** The file name as written in the sheet (shown for missing files). */ + fileName: string; +} + +const clean = (s: string | null | undefined) => (s?.trim() ? s.trim() : undefined); + +/** "Track 3" when the sheet has no title for it. */ +export function cueTrackTitle(track: Pick): string { + return clean(track.title) ?? t('Track {number}', { number: track.number }); +} + +/** A cue track as a player track: the matched file clipped to the track. */ +export function cueTrackToAudio(sheet: ApiCueSheetDto, track: ApiCueTrackDto, source: CueSource): AudioTrack | null { + const file = track.file; + if (!file) return null; + const url = audioUrlOf(file); + if (!url) return null; + const end = track.end != null && track.end > track.start ? track.end : null; + return { + id: `cue:${source.local ? 'local:' : ''}${sheet.id}#${track.number}`, + title: cueTrackTitle(track), + artist: clean(track.performer) ?? clean(sheet.performer), + album: clean(sheet.title), + source: source.sourceName, + url, + channelId: source.local ? undefined : source.channelId, + fileId: source.local ? undefined : file.id, + localPath: source.local ? file.id : undefined, + size: file.size, + clip: { start: Math.max(0, track.start), end } + }; +} + +/** The rows of a sheet, in its order. */ +export function cueRows(sheet: ApiCueSheetDto, source: CueSource): CueRow[] { + return (sheet.tracks ?? []).map((track) => { + const end = track.end != null && track.end > track.start ? track.end : undefined; + return { + number: track.number, + title: cueTrackTitle(track), + performer: clean(track.performer) ?? clean(sheet.performer), + duration: end !== undefined ? end - track.start : undefined, + track: cueTrackToAudio(sheet, track, source), + fileName: track.fileName + }; + }); +} + +/** The playable tracks of `rows` and where `fromNumber` (a track number) sits among them. */ +export function playableFrom(rows: CueRow[], fromNumber?: number): { tracks: AudioTrack[]; index: number } { + const playable = rows.filter((r) => r.track); + const tracks = playable.map((r) => r.track as AudioTrack); + const index = fromNumber === undefined ? 0 : Math.max(0, playable.findIndex((r) => r.number === fromNumber)); + return { tracks, index }; +} + +/** True for a `.cue` file name. */ +export function isCueName(name: string): boolean { + return /\.cue$/i.test(name); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueStore.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueStore.ts new file mode 100644 index 0000000..adeb6f0 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueStore.ts @@ -0,0 +1,21 @@ +import { create } from 'zustand'; +import type { CueSource } from './cueModel'; + +/** A cue sheet to open: the entry id (channel) or relative path (local) of the `.cue` file. */ +export interface CueRequest extends CueSource { + /** Channel entry id, or the relative path for local files. */ + id: string; + name: string; +} + +/** State of the cue sheet dialog (the dialog itself is lazy). */ +export const useCueSheet = create<{ request: CueRequest | null }>()(() => ({ request: null })); + +/** Opens the cue sheet dialog (tracks of the album, play / queue). */ +export function openCueSheet(request: CueRequest): void { + useCueSheet.setState({ request }); +} + +export function closeCueSheet(): void { + useCueSheet.setState({ request: null }); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/deletes/deleteTracker.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/deletes/deleteTracker.ts index 74e4b18..8f07a2f 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/files/deletes/deleteTracker.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/deletes/deleteTracker.ts @@ -6,6 +6,7 @@ import { api, errorMessage } from '@/lib/api'; import { queryClient } from '@/lib/queryClient'; import { queryKeys } from '@/lib/queryKeys'; import { getEventsHub, useRealtime } from '@/lib/realtime'; +import { resetServerFeatures, serverFeatures } from '@/lib/serverFeatures'; import { isActiveDelete, statusFromProgress, useDeletes, type TrackedDelete } from './deleteStore'; /** @@ -40,20 +41,6 @@ export interface StartDeleteRequest { entries: FileEntry[]; } -let capabilities: Promise> | null = null; - -/** Optional features of the server (an old server answers 404: none). Cached for the session. */ -export function serverFeatures(): Promise> { - capabilities ??= api.system - .capabilities() - .then((c) => new Set(c?.features ?? [])) - .catch(() => { - capabilities = null; // try again next time (it may have been a network blip) - return new Set(); - }); - return capabilities; -} - let nextKey = 1; export async function startDelete(request: StartDeleteRequest): Promise { @@ -262,7 +249,7 @@ export async function pollOnce(now = Date.now()): Promise { /** Test helper: forget the module state. */ export function __resetDeleteTrackerForTests(): void { - capabilities = null; + resetServerFeatures(); hubListening = false; if (pollTimer) clearInterval(pollTimer); pollTimer = null; diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/describeEntry.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/describeEntry.ts new file mode 100644 index 0000000..90e98ff --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/describeEntry.ts @@ -0,0 +1,50 @@ +import { entryMediaKind, type EntryDescription, type FileEntry } from '@tfm/file-manager'; +import { useCallback } from 'react'; +import { formatTime } from '@/features/player/format'; +import { audioInfoKey, audioInfoLabel, audioInfoScope, useAudioInfo, type AudioInfo } from './audioInfo'; +import { isCueName } from './cue/cueModel'; + +const CUE_BADGE = 'CUE'; + +const baseName = (name: string) => { + const i = name.lastIndexOf('.'); + return (i > 0 ? name.slice(0, i) : name).toLowerCase(); +}; + +// Base names of the cue sheets of a listing, computed once per listing array +const cueNamesCache = new WeakMap>(); +function cueBaseNames(entries: FileEntry[]): Set { + let names = cueNamesCache.get(entries); + if (!names) { + names = new Set(entries.filter((e) => e.kind === 'file' && isCueName(e.name)).map((e) => baseName(e.name))); + cueNamesCache.set(entries, names); + } + return names; +} + +/** + * What a row of the listing shows besides the file: "Performer – Title" and + * the duration of Telegram audio, and a "CUE" badge on cue sheets and on the + * audio file a cue sheet of the same name describes. Pure, for the tests. + */ +export function describeEntry(entry: FileEntry, entries: FileEntry[], info: AudioInfo | null | undefined): EntryDescription | undefined { + if (entry.kind !== 'file') return undefined; + const cueBadge = isCueName(entry.name) || (entryMediaKind(entry) === 'audio' && cueBaseNames(entries).has(baseName(entry.name))); + const subtitle = audioInfoLabel(info); + const meta = info?.duration ? [formatTime(info.duration)] : undefined; + if (!cueBadge && !subtitle && !meta) return undefined; + return { subtitle, meta, badge: cueBadge ? CUE_BADGE : undefined }; +} + +/** + * `describeEntry` of a file manager. With a channel it follows the audio + * details store, so the rows update when the details arrive. + */ +export function useEntryDescriber(channelId?: string, collectionId?: string) { + const byKey = useAudioInfo((s) => s.byKey); + const scope = channelId ? audioInfoScope(channelId, collectionId) : null; + return useCallback( + (entry: FileEntry, entries: FileEntry[]) => describeEntry(entry, entries, scope ? byKey[audioInfoKey(scope, entry.id)] : undefined), + [byKey, scope] + ); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/entries.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/entries.ts index 189945e..5eca9e9 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/files/entries.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/entries.ts @@ -1,6 +1,7 @@ import type { ApiFileDto, BrowseFilter, BrowseSortBy } from '@tfm/api-client'; import { entryMediaKind, extensionOf, joinPath, mediaKindOf, normalizePath, type FileEntry, type ListFilter, type MediaKind, type SortSpec } from '@tfm/file-manager'; import type { AudioTrack, ViewerItem } from '@/features/player/public'; +import { getAudioInfo } from './audioInfo'; const CATEGORY_KIND: Record = { Audio: 'audio', @@ -65,18 +66,31 @@ function stripExtension(name: string) { return i > 0 ? name.slice(0, i) : name; } -/** An audio entry as a player track. */ -export function toTrack(entry: FileEntry, source: { channelId?: string; sourceName?: string; local?: boolean }): AudioTrack { +/** Playable URL of an audio DTO (same-origin). */ +export function audioUrlOf(dto: ApiFileDto): string { + return dto.playbackUrl ?? dto.streamUrl ?? dto.contentUrl ?? ''; +} + +/** + * An audio entry as a player track. Channel files take the title, artist, + * duration and cover Telegram keeps for them when the listing already has + * them (`audioInfo.ts`), so the player shows them before the file loads. + */ +export function toTrack(entry: FileEntry, source: { channelId?: string; collectionId?: string; sourceName?: string; local?: boolean }): AudioTrack { const dto = dtoOf(entry); + const info = !source.local && source.channelId ? getAudioInfo(source.channelId, dto.id, source.collectionId) : undefined; return { id: source.local ? `local:${dto.id}` : dto.id, - title: stripExtension(entry.name), + title: info?.title ?? stripExtension(entry.name), + artist: info?.performer, source: source.sourceName, - url: dto.playbackUrl ?? dto.streamUrl ?? dto.contentUrl ?? '', + url: audioUrlOf(dto), + coverUrl: info?.coverUrl, channelId: source.local ? undefined : source.channelId, fileId: source.local ? undefined : dto.id, localPath: source.local ? dto.id : undefined, - size: dto.size + size: dto.size, + durationSeconds: info?.duration }; } diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/media.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/media.ts index 2ea22b7..13ecdba 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/files/media.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/media.ts @@ -1,16 +1,20 @@ import { createElement } from 'react'; import { entryMediaKind, type FileAction, type FileEntry } from '@tfm/file-manager'; import { toast } from '@tfm/ui'; -import { Link2, ListEnd, ListPlus, ListVideo, Play } from 'lucide-react'; +import { Disc3, Link2, ListEnd, ListPlus, ListVideo, Play } from 'lucide-react'; import { enqueueAudio, openViewer, playAudio } from '@/features/player/public'; import { openAddToPlaylist, type PlaylistCandidate } from '@/features/playlists/public'; import { t } from '@/i18n'; import { absoluteUrl, copyText } from './browser'; +import { isCueName } from './cue/cueModel'; +import { openCueSheet } from './cue/cueStore'; import { dtoOf, toTrack, toViewerItem, viewerKind } from './entries'; export interface MediaSource { /** Channel holding the files (undefined for local files). */ channelId?: string; + /** Shared collection the files are read from. */ + collectionId?: string; /** Label shown by the player under the title. */ sourceName?: string; local?: boolean; @@ -22,6 +26,19 @@ export interface MediaSource { } const isAudio = (e: FileEntry) => e.kind === 'file' && entryMediaKind(e) === 'audio'; +const isCue = (e: FileEntry) => e.kind === 'file' && isCueName(e.name); + +/** Opens the tracks of a `.cue` file (an album in one audio file). */ +function openCue(entry: FileEntry, source: MediaSource): void { + openCueSheet({ + id: dtoOf(entry).id, + name: entry.name, + channelId: source.channelId, + collectionId: source.collectionId, + local: source.local, + sourceName: source.sourceName + }); +} /** * Opens a file with the app's player/viewer: audio plays with the folder's @@ -29,6 +46,10 @@ const isAudio = (e: FileEntry) => e.kind === 'file' && entryMediaKind(e) === 'au * PDF and text in the viewer. Returns false for other files. */ export function openMedia(entry: FileEntry, folderEntries: FileEntry[], source: MediaSource): boolean { + if (isCue(entry) && (source.local || source.channelId)) { + openCue(entry, source); + return true; + } const kind = viewerKind(entry); if (kind === 'audio') { const audios = folderEntries.filter(isAudio); @@ -62,6 +83,16 @@ function playlistCandidates(entries: FileEntry[], source: MediaSource): Playlist export function mediaActions(source: MediaSource): FileAction[] { const allAudio = (entries: FileEntry[]) => entries.length > 0 && entries.every(isAudio); return [ + { + id: 'tfm:open-cue', + label: t('Open as an album'), + icon: createElement(Disc3), + selection: 'single', + group: 'a-open', + order: 1, + when: ([e]) => isCue(e) && !!(source.local || source.channelId), + run: ([e]) => openCue(e, source) + }, { id: 'tfm:play', label: t('Play'), diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/local/pages/LocalFilesPage.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/local/pages/LocalFilesPage.tsx index c1775be..c389330 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/local/pages/LocalFilesPage.tsx +++ b/TelegramDownloader/ClientApp/apps/web/src/features/local/pages/LocalFilesPage.tsx @@ -3,6 +3,7 @@ import { CloudUpload, HardDrive } from 'lucide-react'; import { useMemo, useState } from 'react'; import { dtoOf } from '@/features/files/entries'; import { confirmDelete, fmLocale, reportError, reportSuccess } from '@/features/files/fileManagerOptions'; +import { useEntryDescriber } from '@/features/files/describeEntry'; import { mediaActions, openMedia, type MediaSource } from '@/features/files/media'; import { localRel } from '@/features/files/local'; import { fileManagerStrings } from '@/features/files/strings'; @@ -22,6 +23,7 @@ export default function LocalFilesPage() { const singleClickFolders = useUi((s) => s.singleClickFolders); const [uploading, setUploading] = useState(null); const provider = useMemo(() => createLocalProvider(t('Local files')), []); + const describeEntry = useEntryDescriber(); const source: MediaSource = useMemo( () => ({ @@ -76,6 +78,7 @@ export default function LocalFilesPage() { onError={reportError} onSuccess={reportSuccess} onOpen={(entry, fm) => openMedia(entry, fm.entries, source)} + describeEntry={describeEntry} className="mt-2 flex-1" /> setUploading(null)} /> diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/player/PlayerSlot.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/player/PlayerSlot.tsx index 7f059c2..b87bee0 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/player/PlayerSlot.tsx +++ b/TelegramDownloader/ClientApp/apps/web/src/features/player/PlayerSlot.tsx @@ -1,4 +1,5 @@ import { lazy, Suspense, useEffect } from 'react'; +import { CueSheetSlot } from '@/features/files/cue/CueSheetSlot'; import { PlaylistPickerSlot } from '@/features/playlists/PlaylistPickerSlot'; import { selectHasQueue, usePlayer } from './store'; import { useViewer } from './viewerStore'; @@ -43,6 +44,7 @@ export function PlayerSlot() { )} + ); } diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/player/clip.test.ts b/TelegramDownloader/ClientApp/apps/web/src/features/player/clip.test.ts new file mode 100644 index 0000000..e18f479 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/player/clip.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from 'vitest'; +import { clipDuration, clipOf, continuesInSameFile, hasClip, knownDuration, toFileTime, toTrackRanges, toTrackTime } from './clip'; + +describe('clip arithmetic', () => { + it('normalises clips', () => { + expect(clipOf(undefined)).toEqual({ start: 0 }); + expect(clipOf({ clip: { start: 10, end: null } })).toEqual({ start: 10 }); + expect(clipOf({ clip: { start: -1, end: 20 } })).toEqual({ start: 0, end: 20 }); + expect(clipOf({ clip: { start: 30, end: 20 } })).toEqual({ start: 30 }); // an end before the start is ignored + expect(hasClip({})).toBe(false); + expect(hasClip({ clip: { start: 0, end: null } })).toBe(false); + expect(hasClip({ clip: { start: 0, end: 30 } })).toBe(true); + }); + + it('converts between file and track time', () => { + const c = { start: 30, end: 60 }; + expect(clipDuration(c, 100)).toBe(30); + expect(clipDuration({ start: 60 }, 100)).toBe(40); + expect(clipDuration({ start: 60 }, NaN)).toBeNaN(); + expect(toTrackTime(c, 45, 100)).toBe(15); + expect(toTrackTime(c, 10, 100)).toBe(0); + expect(toTrackTime(c, 80, 100)).toBe(30); + expect(toFileTime(c, 5, 100)).toBe(35); + expect(toFileTime(c, 500, 100)).toBe(60); + expect(toFileTime({ start: 60 }, 500, 100)).toBe(100); + }); + + it('knows the duration before loading', () => { + expect(knownDuration({ clip: { start: 30, end: 75 } })).toBe(45); + expect(knownDuration({ durationSeconds: 200 })).toBe(200); + expect(knownDuration({ clip: { start: 50 }, durationSeconds: 200 })).toBe(150); + expect(knownDuration({ clip: { start: 50 } })).toBeUndefined(); + }); + + it('detects contiguous clips of the same file', () => { + const a = { url: 'u', clip: { start: 0, end: 30 } }; + expect(continuesInSameFile(a, { url: 'u', clip: { start: 30.2 } })).toBe(true); + expect(continuesInSameFile(a, { url: 'u', clip: { start: 45 } })).toBe(false); + expect(continuesInSameFile(a, { url: 'v', clip: { start: 30 } })).toBe(false); + expect(continuesInSameFile({ url: 'u', clip: { start: 60 } }, { url: 'u', clip: { start: 60 } })).toBe(false); + expect(continuesInSameFile(a, { url: 'u' })).toBe(false); + }); + + it('maps buffered ranges into the clip', () => { + expect(toTrackRanges({ start: 30, end: 60 }, [{ start: 0, end: 40 }, { start: 55, end: 90 }], 100)).toEqual([ + { start: 0, end: 10 }, + { start: 25, end: 30 } + ]); + const whole = [{ start: 0, end: 10 }]; + expect(toTrackRanges({ start: 0 }, whole, 100)).toBe(whole); + }); +}); diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/player/clip.ts b/TelegramDownloader/ClientApp/apps/web/src/features/player/clip.ts new file mode 100644 index 0000000..192ce06 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/player/clip.ts @@ -0,0 +1,94 @@ +import type { AudioTrack } from './public'; + +/** + * Clip arithmetic of the player: a track can be a slice of its audio file + * (cue sheets: one file, many tracks). The