Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions TelegramDownloader/ClientApp/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. `<DeleteProgressHost/>` (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).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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,
Expand All @@ -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) {
Expand All @@ -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) {
Expand Down Expand Up @@ -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)
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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]);
Expand Down Expand Up @@ -73,6 +75,7 @@ export default function ChannelPage() {
}
})
}
describeEntry={describeEntry}
className="flex-1"
/>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -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 });
});
});
122 changes: 122 additions & 0 deletions TelegramDownloader/ClientApp/apps/web/src/features/files/audioInfo.ts
Original file line number Diff line number Diff line change
@@ -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<string, AudioInfo | null>;
}

export const useAudioInfo = create<AudioInfoState>()(() => ({ byKey: {} }));

const inflight = new Set<string>();

/** 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<T>(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<void> {
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<string, AudioInfo | null> = {};
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: {} });
}
Loading
Loading