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
2 changes: 2 additions & 0 deletions TelegramDownloader/ClientApp/apps/web/src/app/routes.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Navigate, type RouteObject } from 'react-router';
import { TelegramGate, WebAuthGate } from '@/auth/gates';
import { routes as appsRoutes } from '@/features/apps/routes';
import { routes as audiobooksRoutes } from '@/features/audiobooks/routes';
import { routes as channelsRoutes } from '@/features/channels/routes';
import { routes as chatRoutes } from '@/features/chat/routes';
import { routes as devUiRoutes } from '@/features/dev-ui/routes';
Expand Down Expand Up @@ -44,6 +45,7 @@ export const appRoutes: RouteObject[] = [
...transfersRoutes,
...playlistsRoutes,
...libraryRoutes,
...audiobooksRoutes,
...searchRoutes,
...chatRoutes,
...settingsRoutes,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import type { ApiAudiobookDto } from '@tfm/api-client';
import { cn } from '@tfm/ui';
import { Check, Play } from 'lucide-react';
import { Link } from 'react-router';
import { formatLength } from '@/features/player/public';
import { t } from '@/i18n';
import { authorsLabel, inProgress, progressPercent, seriesLabel } from '../model';
import { playBookById } from '../playback';
import { BookCover } from './BookCover';

export function BookProgress({ percent, className }: { percent: number; className?: string }) {
if (percent <= 0) return null;
return (
<div className={cn('h-1 w-full overflow-hidden rounded-full bg-black/40', className)} role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(percent)} aria-label={t('Listened')}>
<div className="h-full rounded-full bg-primary" style={{ width: `${percent}%` }} />
</div>
);
}

/** Cover card of a book: opens it; the play button resumes it. */
export function BookCard({ book, className, showProgressText }: { book: ApiAudiobookDto; className?: string; showProgressText?: boolean }) {
const percent = progressPercent(book.progress);
const left = book.progress && inProgress(book.progress) ? Math.max(0, book.durationMs - book.progress.positionMs) : 0;
const series = seriesLabel(book.series[0]);
return (
<div className={cn('group relative flex flex-col gap-2', className)}>
<Link to={`/audiobooks/${encodeURIComponent(book.id)}`} className="flex flex-col gap-2 rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring" title={book.title}>
<div className="relative overflow-hidden rounded-xl shadow-soft ring-1 ring-white/5 transition-[transform,box-shadow] duration-300 group-hover:-translate-y-1 group-hover:shadow-elevated">
<BookCover src={book.coverUrl} title={book.title} className="w-full" />
{book.progress?.finished && (
<span className="absolute right-2 top-2 flex size-6 items-center justify-center rounded-full bg-primary text-on-accent shadow-soft" title={t('Finished')}>
<Check className="size-3.5" strokeWidth={3} />
</span>
)}
<div className="absolute inset-x-2 bottom-2">
<BookProgress percent={book.progress?.finished ? 0 : percent} />
</div>
</div>
<div className="min-w-0 px-0.5">
<p className="truncate text-sm font-medium text-fg">{book.title}</p>
<p className="truncate text-xs text-fg-subtle">{authorsLabel(book) || series || ' '}</p>
{showProgressText && left > 0 && <p className="truncate text-xs text-fg-muted">{t('{time} left', { time: formatLength(left) })}</p>}
</div>
</Link>
<button
type="button"
onClick={() => void playBookById(book.id)}
aria-label={inProgress(book.progress) ? t('Continue listening to {title}', { title: book.title }) : t('Play {title}', { title: book.title })}
className="absolute left-1/2 top-[calc(50%-1.5rem)] flex size-12 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full bg-fg/90 text-bg opacity-0 shadow-elevated transition-opacity focus-visible:opacity-100 group-hover:opacity-100"
>
<Play className="size-5 translate-x-px fill-current" />
</button>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { cn } from '@tfm/ui';
import { BookAudio } from 'lucide-react';
import { useState } from 'react';

/** Square cover of a book, lazy loaded, with a soft placeholder when there is none (or it fails). */
export function BookCover({ src, title, className, eager }: { src: string | null | undefined; title: string; className?: string; eager?: boolean }) {
const [failed, setFailed] = useState<string | null>(null);
const show = src && failed !== src;
return (
<div className={cn('relative aspect-square overflow-hidden bg-gradient-to-br from-accent-900/60 to-surface-2', className)}>
{show ? (
<img src={src} alt="" loading={eager ? 'eager' : 'lazy'} decoding="async" onError={() => setFailed(src)} className="size-full object-cover" />
) : (
<div className="flex size-full flex-col items-center justify-center gap-2 p-3 text-center text-fg-muted">
<BookAudio className="size-1/4 opacity-60" aria-hidden />
<span className="line-clamp-3 text-xs font-medium">{title}</span>
</div>
)}
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import type { ApiAudiobookDetailDto, ApiBookCandidateDto } from '@tfm/api-client';
import { Badge, Button, Dialog, DialogContent, EmptyState, Input, Skeleton } from '@tfm/ui';
import { useQuery } from '@tanstack/react-query';
import { ArrowUpRight, Search } from 'lucide-react';
import { useState, type FormEvent } from 'react';
import { formatLength } from '@/features/player/public';
import { t } from '@/i18n';
import { api, errorMessage } from '@/lib/api';
import { audiobookKeys, useBookAction } from '../queries';
import { BookCover } from './BookCover';

function Candidate({ c, onPick, picking }: { c: ApiBookCandidateDto; onPick: () => void; picking: boolean }) {
return (
<li className="flex gap-3 rounded-xl border border-border p-3">
<BookCover src={c.coverUrl} title={c.title} className="w-16 shrink-0 rounded-lg" />
<div className="min-w-0 flex-1">
<p className="font-medium text-fg">
{c.title}
{c.subtitle && <span className="text-fg-muted"> · {c.subtitle}</span>}
</p>
<p className="truncate text-sm text-fg-muted">{c.authors.join(', ')}</p>
{c.narrators.length > 0 && <p className="truncate text-xs text-fg-subtle">{t('Narrated by {names}', { names: c.narrators.join(', ') })}</p>}
<p className="mt-1 flex flex-wrap items-center gap-2 text-xs text-fg-subtle">
<Badge tone="neutral">{c.providerName}</Badge>
{c.year && <span>{c.year}</span>}
{c.durationMs ? <span>{formatLength(c.durationMs)}</span> : null}
{c.series[0] && <span>{c.series[0].sequence ? `${c.series[0].name} #${c.series[0].sequence}` : c.series[0].name}</span>}
{c.score !== null && <span className="tabular-nums">{Math.round(c.score * 100)}%</span>}
{c.link && (
<a href={c.link} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-0.5 text-accent-400 hover:text-accent-300">
{t('See at the source')} <ArrowUpRight className="size-3" />
</a>
)}
</p>
</div>
<Button size="sm" className="self-center" onClick={onPick} loading={picking}>
{t('This one')}
</Button>
</li>
);
}

/** Searches the book sources and identifies the book with the result picked. */
export function IdentifyBookDialog({ book, onClose }: { book: ApiAudiobookDetailDto; onClose: () => void }) {
const [title, setTitle] = useState(book.parsed.title || book.title);
const [author, setAuthor] = useState(book.parsed.author ?? book.authors[0] ?? '');
const [query, setQuery] = useState({ q: title, author });
const results = useQuery({
queryKey: audiobookKeys.search(book.id, query.q, query.author),
queryFn: ({ signal }) => api.audiobooks.search({ q: query.q, author: query.author || undefined, bookId: book.id }, signal),
enabled: query.q.trim().length > 0,
staleTime: 5 * 60_000
});
const [picking, setPicking] = useState<string | null>(null);
const identify = useBookAction((c: ApiBookCandidateDto) => api.audiobooks.identify(book.id, c.provider, c.providerId), t('Book identified'));

const submit = (e: FormEvent) => {
e.preventDefault();
setQuery({ q: title.trim(), author: author.trim() });
};

return (
<Dialog open onOpenChange={(o) => !o && onClose()}>
<DialogContent size="lg" title={t('Identify the book')} description={t('Folder: {path}', { path: book.folderPath })}>
<form onSubmit={submit} className="flex flex-wrap items-end gap-2">
<Input aria-label={t('Title')} placeholder={t('Title')} value={title} onChange={(e) => setTitle(e.target.value)} className="min-w-48 flex-[2]" />
<Input aria-label={t('Author')} placeholder={t('Author')} value={author} onChange={(e) => setAuthor(e.target.value)} className="min-w-40 flex-1" />
<Button type="submit" icon={<Search />}>
{t('Search')}
</Button>
</form>
<div className="mt-4 max-h-[55vh] overflow-y-auto">
{results.isFetching && !results.data ? (
<div className="flex flex-col gap-2">
{Array.from({ length: 4 }, (_, i) => (
<Skeleton key={i} className="h-24 rounded-xl" />
))}
</div>
) : results.isError ? (
<p className="text-sm text-danger">{errorMessage(results.error)}</p>
) : (results.data ?? []).length === 0 ? (
<EmptyState title={t('No results')} description={t('Try with fewer words, or only the title.')} />
) : (
<ul className="flex flex-col gap-2">
{results.data!.map((c) => (
<Candidate
key={`${c.provider}:${c.providerId}`}
c={c}
picking={picking === `${c.provider}:${c.providerId}` && identify.isPending}
onPick={() => {
setPicking(`${c.provider}:${c.providerId}`);
identify.mutate(c, { onSuccess: onClose });
}}
/>
))}
</ul>
)}
</div>
</DialogContent>
</Dialog>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import type { ApiAudiobookDetailDto } from '@tfm/api-client';
import { describe, expect, it } from 'vitest';
import { chapterAt, progressPercent, resumePosition, seriesLabel, toPlayable } from './model';

const progress = (o: Partial<NonNullable<ApiAudiobookDetailDto['progress']>>) => ({
positionMs: 0,
durationMs: 100,
progress: 0,
finished: false,
finishedAt: null,
speed: null,
startedAt: '',
lastPlayedAt: '',
...o
});

describe('audiobooks model', () => {
it('resumes where it was left, or from the start when finished', () => {
expect(resumePosition(progress({ positionMs: 5000 }))).toBe(5000);
expect(resumePosition(progress({ positionMs: 5000, finished: true }))).toBe(0);
expect(resumePosition(null)).toBe(0);
});

it('shows a finished book as complete', () => {
expect(progressPercent(progress({ progress: 0.25 }))).toBe(25);
expect(progressPercent(progress({ finished: true, progress: 0.2 }))).toBe(100);
});

it('labels series with their number', () => {
expect(seriesLabel({ name: 'Mistborn', sequence: '2' })).toBe('Mistborn, book 2');
expect(seriesLabel({ name: 'Mistborn', sequence: null })).toBe('Mistborn');
});

it('finds the chapter of a position', () => {
expect(chapterAt([{ startMs: 0 }, { startMs: 100 }], 150)).toBe(1);
expect(chapterAt([], 150)).toBe(-1);
});

it('turns a book into the player queue', () => {
const { book, tracks } = toPlayable({
id: 'b1',
title: 'Dune',
authors: ['Frank Herbert'],
coverUrl: 'c.jpg',
durationMs: 300,
channelId: 7,
chapters: [{ index: 0, title: 'Uno', startMs: 0, endMs: 300 }],
tracks: [
{ index: 0, fileId: 'f1', fileName: '01.mp3', title: null, size: 1, durationMs: 100, startMs: 0, isSplit: false, messageId: 1, contentUrl: 'u1', playbackUrl: 'p1' },
{ index: 1, fileId: 'f2', fileName: '02.mp3', title: 'Dos', size: 1, durationMs: 200, startMs: 100, isSplit: false, messageId: 2, contentUrl: 'u2', playbackUrl: 'p2' }
]
} as unknown as ApiAudiobookDetailDto);
expect(book.trackStarts).toEqual([0, 100]);
expect(tracks.map((t) => [t.url, t.title, t.book?.startMs, t.channelId])).toEqual([
['p1', '01.mp3', 0, '7'],
['p2', 'Dos', 100, '7']
]);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import type { ApiAudiobookDetailDto, ApiAudiobookDto, ApiAudiobookProgressDto, AudiobookSeriesRef } from '@tfm/api-client';
import { ApiErrorCodes, isApiError } from '@tfm/api-client';
import type { AudioTrack, PlayableBook } from '@/features/player/public';
import { t } from '@/i18n';

/** Pure helpers of the audiobooks feature (no React, no API). */

export function isAudiobooksDisabled(error: unknown): boolean {
return isApiError(error) && error.code === ApiErrorCodes.AudiobooksDisabled;
}

/** 0-100 of a book's progress (100 when finished). */
export function progressPercent(progress: ApiAudiobookProgressDto | null | undefined): number {
if (!progress) return 0;
if (progress.finished) return 100;
return Math.max(0, Math.min(100, progress.progress * 100));
}

export function inProgress(progress: ApiAudiobookProgressDto | null | undefined): boolean {
return !!progress && !progress.finished && progress.positionMs > 0;
}

/** "Saga, 2" / "Saga". */
export function seriesLabel(series: AudiobookSeriesRef | undefined): string | null {
if (!series) return null;
return series.sequence ? t('{series}, book {number}', { series: series.name, number: series.sequence }) : series.name;
}

export function authorsLabel(book: Pick<ApiAudiobookDto, 'authors'>): string {
return book.authors.join(', ');
}

/** Where "Play" starts: the saved position, or the start when there is none or the book was finished. */
export function resumePosition(progress: ApiAudiobookProgressDto | null | undefined): number {
if (!progress || progress.finished) return 0;
return Math.max(0, progress.positionMs);
}

/** The book as the player takes it: chapters, track starts and the tracks of the queue. */
export function toPlayable(book: ApiAudiobookDetailDto): { book: PlayableBook; tracks: AudioTrack[] } {
const author = authorsLabel(book) || undefined;
const playable: PlayableBook = {
id: book.id,
title: book.title,
author,
coverUrl: book.coverUrl ?? undefined,
durationMs: book.durationMs,
chapters: book.chapters.map((c) => ({ title: c.title, startMs: c.startMs, endMs: c.endMs })),
trackStarts: book.tracks.map((tr) => tr.startMs)
};
const tracks: AudioTrack[] = book.tracks.map((tr) => ({
id: `${book.channelId}:${tr.fileId}`,
title: tr.title || tr.fileName,
artist: author,
album: book.title,
source: book.title,
url: tr.playbackUrl,
coverUrl: book.coverUrl ?? undefined,
channelId: String(book.channelId),
fileId: tr.fileId,
size: tr.size,
durationSeconds: tr.durationMs > 0 ? tr.durationMs / 1000 : undefined,
book: { id: book.id, startMs: tr.startMs }
}));
return { book: playable, tracks };
}

export function statusLabel(status: string): string {
if (status === 'matched') return t('Identified');
if (status === 'review') return t('To review');
if (status === 'unmatched') return t('Not identified');
if (status === 'ignored') return t('Ignored');
return status;
}

/** The chapter at a position of the book (index), -1 without chapters. */
export function chapterAt(chapters: { startMs: number }[], positionMs: number): number {
let found = -1;
for (let i = 0; i < chapters.length; i++) {
if (chapters[i].startMs <= positionMs + 1) found = i;
else break;
}
return found;
}
Loading
Loading