diff --git a/TelegramDownloader/ClientApp/apps/web/src/app/routes.tsx b/TelegramDownloader/ClientApp/apps/web/src/app/routes.tsx index f27d948..51e2e3e 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/app/routes.tsx +++ b/TelegramDownloader/ClientApp/apps/web/src/app/routes.tsx @@ -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'; @@ -44,6 +45,7 @@ export const appRoutes: RouteObject[] = [ ...transfersRoutes, ...playlistsRoutes, ...libraryRoutes, + ...audiobooksRoutes, ...searchRoutes, ...chatRoutes, ...settingsRoutes, diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/components/BookCard.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/components/BookCard.tsx new file mode 100644 index 0000000..600d54b --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/components/BookCard.tsx @@ -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 ( +
+
+
+ ); +} + +/** 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 ( +
+ +
+ + {book.progress?.finished && ( + + + + )} +
+ +
+
+
+

{book.title}

+

{authorsLabel(book) || series || ' '}

+ {showProgressText && left > 0 &&

{t('{time} left', { time: formatLength(left) })}

} +
+ + +
+ ); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/components/BookCover.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/components/BookCover.tsx new file mode 100644 index 0000000..1682bb2 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/components/BookCover.tsx @@ -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(null); + const show = src && failed !== src; + return ( +
+ {show ? ( + setFailed(src)} className="size-full object-cover" /> + ) : ( +
+ + {title} +
+ )} +
+ ); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/components/IdentifyBookDialog.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/components/IdentifyBookDialog.tsx new file mode 100644 index 0000000..18948ce --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/components/IdentifyBookDialog.tsx @@ -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 ( +
  • + +
    +

    + {c.title} + {c.subtitle && · {c.subtitle}} +

    +

    {c.authors.join(', ')}

    + {c.narrators.length > 0 &&

    {t('Narrated by {names}', { names: c.narrators.join(', ') })}

    } +

    + {c.providerName} + {c.year && {c.year}} + {c.durationMs ? {formatLength(c.durationMs)} : null} + {c.series[0] && {c.series[0].sequence ? `${c.series[0].name} #${c.series[0].sequence}` : c.series[0].name}} + {c.score !== null && {Math.round(c.score * 100)}%} + {c.link && ( + + {t('See at the source')} + + )} +

    +
    + +
  • + ); +} + +/** 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(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 ( + !o && onClose()}> + +
    + setTitle(e.target.value)} className="min-w-48 flex-[2]" /> + setAuthor(e.target.value)} className="min-w-40 flex-1" /> + +
    +
    + {results.isFetching && !results.data ? ( +
    + {Array.from({ length: 4 }, (_, i) => ( + + ))} +
    + ) : results.isError ? ( +

    {errorMessage(results.error)}

    + ) : (results.data ?? []).length === 0 ? ( + + ) : ( +
      + {results.data!.map((c) => ( + { + setPicking(`${c.provider}:${c.providerId}`); + identify.mutate(c, { onSuccess: onClose }); + }} + /> + ))} +
    + )} +
    +
    +
    + ); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/model.test.ts b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/model.test.ts new file mode 100644 index 0000000..fad6b1e --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/model.test.ts @@ -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>) => ({ + 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'] + ]); + }); +}); diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/model.ts b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/model.ts new file mode 100644 index 0000000..388bc7c --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/model.ts @@ -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): 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; +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/pages/AudiobookPage.test.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/pages/AudiobookPage.test.tsx new file mode 100644 index 0000000..a02619d --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/pages/AudiobookPage.test.tsx @@ -0,0 +1,108 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { fireEvent, render, screen } from '@testing-library/react'; +import { TooltipProvider } from '@tfm/ui'; +import { MemoryRouter, Route, Routes } from 'react-router'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('@/lib/api', () => ({ + api: { audiobooks: { get: vi.fn() } }, + errorMessage: (e: unknown) => (e instanceof Error ? e.message : String(e)) +})); +vi.mock('@/features/player/public', async () => ({ + ...(await vi.importActual('@/features/player/book')), + playBook: vi.fn() +})); + +const { api } = await import('@/lib/api'); +const { playBook } = await import('@/features/player/public'); +const { default: AudiobookPage } = await import('./AudiobookPage'); + +const detail = { + id: 'b1', + title: 'El imperio final', + subtitle: null, + authors: ['Brandon Sanderson'], + narrators: ['Narrador'], + series: [{ name: 'Nacidos de la bruma', sequence: '1' }], + year: 2006, + language: 'es', + coverUrl: null, + durationMs: 200_000, + size: 1, + trackCount: 2, + chapterCount: 2, + status: 'matched', + confidence: 1, + locked: false, + provider: 'itunes', + channelId: 5, + folderPath: '/Audiolibros/El imperio final/', + createdAt: '', + progress: { positionMs: 130_000, durationMs: 200_000, progress: 0.65, finished: false, finishedAt: null, speed: 1.5, startedAt: '', lastPlayedAt: '' }, + description: 'Sinopsis.', + publisher: null, + genres: [], + rating: null, + providerId: '1', + externalIds: {}, + matchSource: 'auto', + chapterSource: 'files', + error: null, + parsed: { title: 'El imperio final', author: null, narrator: null, series: null, sequence: null, year: null }, + tracks: [ + { index: 0, fileId: 'f1', fileName: '01.mp3', title: null, size: 1, durationMs: 100_000, startMs: 0, isSplit: false, messageId: 1, contentUrl: 'c1', playbackUrl: 'p1' }, + { index: 1, fileId: 'f2', fileName: '02.mp3', title: null, size: 1, durationMs: 100_000, startMs: 100_000, isSplit: false, messageId: 2, contentUrl: 'c2', playbackUrl: 'p2' } + ], + chapters: [ + { index: 0, title: 'Prólogo', startMs: 0, endMs: 100_000 }, + { index: 1, title: 'La huida', startMs: 100_000, endMs: 200_000 } + ], + bookmarks: [{ id: 'm1', positionMs: 42_000, note: 'Una frase', createdAt: '' }] +}; + +function renderPage() { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + + + + } /> + + + + + ); +} + +beforeEach(() => { + vi.mocked(api.audiobooks.get).mockResolvedValue(detail as never); + vi.mocked(playBook).mockReset(); +}); + +describe('', () => { + it('shows the book, its chapters and bookmarks', async () => { + renderPage(); + expect(await screen.findByRole('heading', { name: 'El imperio final' })).toBeInTheDocument(); + expect(screen.getByText('Narrated by Narrador')).toBeInTheDocument(); + expect(screen.getByText('Nacidos de la bruma, book 1')).toBeInTheDocument(); + expect(screen.getByText('La huida')).toBeInTheDocument(); + expect(screen.getByText('Una frase')).toBeInTheDocument(); + }); + + it('continues where it was left, at the book speed', async () => { + renderPage(); + fireEvent.click(await screen.findByRole('button', { name: /Continue · 2:10/ })); + const [book, tracks, position, speed] = vi.mocked(playBook).mock.calls[0]; + expect(book.trackStarts).toEqual([0, 100_000]); + expect(tracks.map((t) => t.url)).toEqual(['p1', 'p2']); + expect(speed).toBe(1.5); + expect(position).toBe(130_000); + }); + + it('plays a chapter from its start', async () => { + renderPage(); + fireEvent.click(await screen.findByRole('button', { name: /La huida/ })); + expect(vi.mocked(playBook).mock.calls[0][2]).toBe(100_000); + }); +}); diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/pages/AudiobookPage.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/pages/AudiobookPage.tsx new file mode 100644 index 0000000..5cc5f66 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/pages/AudiobookPage.tsx @@ -0,0 +1,333 @@ +import type { ApiAudiobookBookmarkDto, ApiAudiobookDetailDto } from '@tfm/api-client'; +import { + Badge, + Button, + cn, + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, + EmptyState, + IconButton, + Input, + Skeleton +} from '@tfm/ui'; +import { + ArrowLeft, + BookAudio, + Check, + EyeOff, + Eye, + MoreHorizontal, + Pencil, + Play, + RefreshCw, + RotateCcw, + Search, + Trash2, + TriangleAlert, + Undo2 +} from 'lucide-react'; +import { useEffect, useState } from 'react'; +import { Link, useParams } from 'react-router'; +import { formatLength } from '@/features/player/public'; +import { t } from '@/i18n'; +import { api, errorMessage } from '@/lib/api'; +import { BookProgress } from '../components/BookCard'; +import { BookCover } from '../components/BookCover'; +import { IdentifyBookDialog } from '../components/IdentifyBookDialog'; +import { chapterAt, inProgress, isAudiobooksDisabled, progressPercent, resumePosition, seriesLabel, statusLabel } from '../model'; +import { playDetail } from '../playback'; +import { useBook, useBookAction } from '../queries'; + +function clock(ms: number): string { + const s = Math.max(0, Math.floor(ms / 1000)); + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + const sec = s % 60; + return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${String(sec).padStart(2, '0')}` : `${m}:${String(sec).padStart(2, '0')}`; +} + +function Bookmarks({ book }: { book: ApiAudiobookDetailDto }) { + const [editing, setEditing] = useState<{ id: string; note: string } | null>(null); + const save = useBookAction((b: { id: string; note: string }) => api.audiobooks.updateBookmark(book.id, b.id, b.note.trim() || null)); + const remove = useBookAction((b: ApiAudiobookBookmarkDto) => api.audiobooks.deleteBookmark(book.id, b.id), t('Bookmark deleted')); + if (book.bookmarks.length === 0) return

    {t('Add bookmarks from the player while listening.')}

    ; + return ( +
      + {book.bookmarks.map((b) => ( +
    • + playDetail(book, b.positionMs)}> + + + {clock(b.positionMs)} + {editing?.id === b.id ? ( +
      { + e.preventDefault(); + save.mutate(editing, { onSuccess: () => setEditing(null) }); + }} + > + setEditing({ ...editing, note: e.target.value })} className="flex-1" /> + +
      + ) : ( + {b.note ?? {chapterTitleAt(book, b.positionMs)}} + )} + setEditing({ id: b.id, note: b.note ?? '' })}> + + + remove.mutate(b)}> + + +
    • + ))} +
    + ); +} + +function chapterTitleAt(book: ApiAudiobookDetailDto, positionMs: number): string { + const i = chapterAt(book.chapters, positionMs); + return i >= 0 ? book.chapters[i].title : ''; +} + +function Chapters({ book }: { book: ApiAudiobookDetailDto }) { + const current = inProgress(book.progress) ? chapterAt(book.chapters, book.progress!.positionMs) : -1; + if (book.chapters.length <= 1) return

    {t('This book has no chapters.')}

    ; + return ( +
      + {book.chapters.map((c, i) => ( +
    1. + +
    2. + ))} +
    + ); +} + +function Actions({ book, onIdentify }: { book: ApiAudiobookDetailDto; onIdentify: () => void }) { + const finished = !!book.progress?.finished; + const toggleFinished = useBookAction(() => (finished ? api.audiobooks.markNotFinished(book.id) : api.audiobooks.markFinished(book.id))); + const refresh = useBookAction(() => api.audiobooks.refresh(book.id), t('Book read again')); + const ignore = useBookAction(() => (book.status === 'ignored' ? api.audiobooks.unignore(book.id) : api.audiobooks.ignore(book.id))); + const forget = useBookAction(() => api.audiobooks.unidentify(book.id), t('The next scan will identify it again')); + const reset = useBookAction(() => api.audiobooks.resetProgress(book.id)); + const resume = resumePosition(book.progress); + return ( +
    + + {resume > 0 && ( + + )} + + + + + + + + + } onSelect={onIdentify}> + {t('Identify...')} + + } onSelect={() => refresh.mutate(undefined)}> + {t('Read the files and the metadata again')} + + {book.provider && ( + } onSelect={() => forget.mutate(undefined)}> + {t('Forget the identification')} + + )} + {book.progress && ( + } onSelect={() => reset.mutate(undefined)}> + {t('Forget the position')} + + )} + + : } onSelect={() => ignore.mutate(undefined)}> + {book.status === 'ignored' ? t('Show it again') : t('This is not an audiobook')} + + + +
    + ); +} + +/** One audiobook: its details, chapters, bookmarks and files, and playing it. */ +export default function AudiobookPage() { + const { id = '' } = useParams(); + const book = useBook(id); + const [identifying, setIdentifying] = useState(false); + const [moreText, setMoreText] = useState(false); + const data = book.data; + + useEffect(() => { + if (data) document.title = `${data.title} · TFM`; + }, [data]); + + if (book.isPending) { + return ( +
    + +
    + + + +
    +
    + ); + } + if (book.isError || !data) { + return ( +
    + } + title={isAudiobooksDisabled(book.error) ? t('Audiobooks are off') : t('Could not load the book')} + description={errorMessage(book.error)} + action={ + + } + /> +
    + ); + } + + const percent = progressPercent(data.progress); + const left = data.progress && inProgress(data.progress) ? data.durationMs - data.progress.positionMs : 0; + const series = data.series[0]; + const info = [data.year, data.durationMs > 0 ? formatLength(data.durationMs) : null, data.chapters.length > 1 ? t('{count} chapters', { count: data.chapters.length }) : null, data.language?.toUpperCase(), data.publisher] + .filter(Boolean) + .join(' · '); + + return ( +
    +
    + {data.coverUrl && } +
    +
    +
    + + +
    + +
    + {(data.status === 'review' || data.status === 'unmatched' || data.status === 'ignored') && ( +
    + {statusLabel(data.status)} + {data.status !== 'ignored' && ( + + )} +
    + )} +
    +

    {data.title}

    + {data.subtitle &&

    {data.subtitle}

    } +
    + {data.authors.length > 0 && ( +

    + {data.authors.map((a, i) => ( + + {i > 0 && ', '} + + {a} + + + ))} +

    + )} + {data.narrators.length > 0 &&

    {t('Narrated by {names}', { names: data.narrators.join(', ') })}

    } + {series && ( + + {seriesLabel(series)} + + )} + {info &&

    {info}

    } + {data.genres.length > 0 && ( +
    + {data.genres.slice(0, 6).map((g) => ( + + {g} + + ))} +
    + )} + {percent > 0 && ( +
    + +

    + {data.progress?.finished ? t('Finished') : t('{percent}% listened · {time} left', { percent: Math.round(percent), time: formatLength(Math.max(0, left)) })} +

    +
    + )} + setIdentifying(true)} /> +
    +
    + + {data.description && ( +
    +

    {t('Synopsis')}

    +

    {data.description}

    + {data.description.length > 400 && ( + + )} +
    + )} + +
    +
    +

    {t('Chapters')}

    + +
    +
    +
    +

    {t('Bookmarks')}

    + +
    +
    +

    + {t('Files')} +

    +

    {data.folderPath}

    +
      + {data.tracks.map((tr) => ( +
    • + {tr.fileName} + {tr.durationMs > 0 ? clock(tr.durationMs) : '—'} +
    • + ))} +
    + {data.error &&

    {data.error}

    } +
    +
    +
    +
    + {identifying && setIdentifying(false)} />} +
    + ); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/pages/AudiobooksPage.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/pages/AudiobooksPage.tsx new file mode 100644 index 0000000..9cd115f --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/pages/AudiobooksPage.tsx @@ -0,0 +1,358 @@ +import type { ApiAudiobookGroupDto, AudiobooksQuery } from '@tfm/api-client'; +import { Badge, Button, EmptyState, IconButton, Input, SegmentedControl, Select, Skeleton } from '@tfm/ui'; +import { BookAudio, ChevronLeft, ChevronRight, ListChecks, Radar, Search, Settings, TriangleAlert, X } from 'lucide-react'; +import { useEffect, useRef, useState, type ReactNode } from 'react'; +import { Link, useSearchParams } from 'react-router'; +import { t } from '@/i18n'; +import { api, errorMessage } from '@/lib/api'; +import { BookCard } from '../components/BookCard'; +import { BookCover } from '../components/BookCover'; +import { isAudiobooksDisabled } from '../model'; +import { useAuthors, useBookAction, useBooks, useContinueListening, useRecentBooks, useScanState, useSeries } from '../queries'; + +type View = 'home' | 'all' | 'authors' | 'series'; +type SortBy = 'title' | 'author' | 'added' | 'lastPlayed' | 'duration' | 'series'; +type ProgressFilter = 'any' | 'inProgress' | 'finished' | 'notStarted'; + +const GRID = 'grid grid-cols-[repeat(auto-fill,minmax(9.5rem,1fr))] gap-x-4 gap-y-6 sm:grid-cols-[repeat(auto-fill,minmax(11rem,1fr))]'; +const ROW_CARD = 'w-36 shrink-0 snap-start sm:w-44'; + +function Row({ title, children, action }: { title: string; children: ReactNode; action?: ReactNode }) { + const ref = useRef(null); + const scroll = (dir: 1 | -1) => ref.current?.scrollBy({ left: dir * ref.current.clientWidth * 0.85, behavior: 'smooth' }); + return ( +
    +
    +

    {title}

    +
    + {action} + scroll(-1)} className="hidden md:inline-flex"> + + + scroll(1)} className="hidden md:inline-flex"> + + +
    +
    +
    + {children} +
    +
    + ); +} + +function Disabled() { + return ( + } + title={t('Audiobooks are off')} + description={t('Enable them in the settings to find the audiobooks of your channels.')} + action={ + + } + /> + ); +} + +function ScanButton() { + const scan = useScanState(); + const start = useBookAction(() => api.audiobooks.scan({}), t('Audiobook scan started')); + const s = scan.data; + if (s?.running) { + return ( + + {s.booksToProcess > 0 ? t('Scanning {done}/{total}', { done: s.booksProcessed, total: s.booksToProcess }) : t('Scanning...')} + + ); + } + return ( + + ); +} + +function Home({ onSeeAll }: { onSeeAll: () => void }) { + const cont = useContinueListening(); + const recent = useRecentBooks(); + if (recent.isPending) { + return ( +
    + {Array.from({ length: 8 }, (_, i) => ( + + ))} +
    + ); + } + if (recent.isError) { + if (isAudiobooksDisabled(recent.error)) return ; + return ( + } + title={t('Could not load the audiobooks')} + description={errorMessage(recent.error)} + action={} + /> + ); + } + if ((recent.data ?? []).length === 0 && (cont.data ?? []).length === 0) { + return ( + } + title={t('No audiobooks yet')} + description={t('Put them in a folder called Audiolibros or Audiobooks (one folder per book), or mark a folder as Audiobooks in the folder rules of the library settings, then scan. .m4b files are found anywhere.')} + action={} + /> + ); + } + return ( +
    + {(cont.data ?? []).length > 0 && ( + + {cont.data!.map((b) => ( + + ))} + + )} + + {t('See all')} + + + } + > + {(recent.data ?? []).map((b) => ( + + ))} + +
    + ); +} + +function AllBooks({ query }: { query: AudiobooksQuery }) { + const books = useBooks(query); + const items = books.data?.pages.flatMap((p) => p.items) ?? []; + const sentinel = useRef(null); + const { hasNextPage, isFetchingNextPage, fetchNextPage } = books; + useEffect(() => { + const el = sentinel.current; + if (!el || !hasNextPage) return; + const io = new IntersectionObserver((entries) => { + if (entries.some((e) => e.isIntersecting) && !isFetchingNextPage) void fetchNextPage(); + }); + io.observe(el); + return () => io.disconnect(); + }, [hasNextPage, isFetchingNextPage, fetchNextPage]); + + if (books.isError) { + if (isAudiobooksDisabled(books.error)) return ; + return } title={t('Could not load the audiobooks')} description={errorMessage(books.error)} />; + } + if (books.isPending) { + return ( +
    + {Array.from({ length: 12 }, (_, i) => ( + + ))} +
    + ); + } + if (items.length === 0) return } title={t('No books match')} />; + const total = books.data?.pages[0]?.page.totalItems ?? items.length; + return ( +
    +

    {t('{count} books', { count: total })}

    +
    + {items.map((b) => ( + + ))} +
    +
    +
    + ); +} + +function Groups({ groups, loading, error, onPick }: { groups: ApiAudiobookGroupDto[] | undefined; loading: boolean; error: unknown; onPick: (name: string) => void }) { + if (error) return isAudiobooksDisabled(error) ? : } title={t('Could not load the audiobooks')} description={errorMessage(error)} />; + if (loading) { + return ( +
    + {Array.from({ length: 8 }, (_, i) => ( + + ))} +
    + ); + } + if (!groups || groups.length === 0) return } title={t('Nothing here yet')} />; + return ( +
    + {groups.map((g) => ( + + ))} +
    + ); +} + +/** Audiobooks: continue listening, every book (search, sort, filters), authors and series. */ +export default function AudiobooksPage() { + const [params, setParams] = useSearchParams(); + const view = (params.get('view') as View | null) ?? 'home'; + const author = params.get('author') ?? undefined; + const series = params.get('series') ?? undefined; + const sortBy = (params.get('sort') as SortBy | null) ?? (series ? 'series' : 'title'); + const progress = (params.get('progress') as ProgressFilter | null) ?? 'any'; + const [search, setSearch] = useState(params.get('q') ?? ''); + const authors = useAuthors(view === 'authors'); + const seriesList = useSeries(view === 'series'); + + useEffect(() => { + document.title = `${t('Audiobooks')} · TFM`; + }, []); + + // The search goes to the URL after a short pause + useEffect(() => { + const id = setTimeout(() => { + const current = params.get('q') ?? ''; + if (search.trim() === current) return; + const next = new URLSearchParams(params); + if (search.trim()) { + next.set('q', search.trim()); + next.set('view', 'all'); + } else next.delete('q'); + setParams(next, { replace: true }); + }, 400); + return () => clearTimeout(id); + }, [search, params, setParams]); + + const go = (changes: Record) => { + const next = new URLSearchParams(params); + for (const [k, v] of Object.entries(changes)) { + if (v === null) next.delete(k); + else next.set(k, v); + } + setParams(next); + }; + + const query: AudiobooksQuery = { + search: params.get('q') ?? undefined, + author, + series, + sortBy, + progress: progress === 'any' ? undefined : progress + }; + + return ( +
    +
    +
    + +

    {t('Audiobooks')}

    +
    +
    + + + + + + + +
    +
    + +
    + + aria-label={t('View')} + value={view} + onValueChange={(v) => go({ view: v, author: null, series: null, sort: null })} + options={[ + { value: 'home', label: t('Home') }, + { value: 'all', label: t('All') }, + { value: 'authors', label: t('Authors') }, + { value: 'series', label: t('Series') } + ]} + /> + } + trailing={ + search ? ( + setSearch('')}> + + + ) : undefined + } + placeholder={t('Title, author, narrator, series...')} + aria-label={t('Search audiobooks')} + value={search} + onChange={(e) => setSearch(e.target.value)} + className="min-w-56 flex-1 sm:max-w-sm" + /> +
    + + {view === 'all' && ( +
    + {author && ( + + {t('Author: {name}', { name: author })} + + + )} + {series && ( + + {t('Series: {name}', { name: series })} + + + )} + + aria-label={t('Sort by')} + size="sm" + value={sortBy} + onValueChange={(v) => go({ sort: v })} + options={[ + { value: 'title', label: t('Title') }, + { value: 'author', label: t('Author') }, + { value: 'series', label: t('Series order') }, + { value: 'added', label: t('Recently added') }, + { value: 'lastPlayed', label: t('Recently played') }, + { value: 'duration', label: t('Length') } + ]} + className="w-48" + /> + + aria-label={t('Progress')} + size="sm" + value={progress} + onValueChange={(v) => go({ progress: v === 'any' ? null : v })} + options={[ + { value: 'any', label: t('Any progress') }, + { value: 'inProgress', label: t('In progress') }, + { value: 'notStarted', label: t('Not started') }, + { value: 'finished', label: t('Finished') } + ]} + className="w-44" + /> +
    + )} + + {view === 'home' && go({ view: 'all', sort: 'added' })} />} + {view === 'all' && } + {view === 'authors' && go({ view: 'all', author: name, sort: 'series' })} />} + {view === 'series' && go({ view: 'all', series: name, sort: 'series' })} />} +
    + ); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/pages/AudiobooksReviewPage.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/pages/AudiobooksReviewPage.tsx new file mode 100644 index 0000000..0247ed3 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/pages/AudiobooksReviewPage.tsx @@ -0,0 +1,100 @@ +import type { ApiAudiobookDto } from '@tfm/api-client'; +import { Badge, Button, EmptyState, SegmentedControl, Skeleton } from '@tfm/ui'; +import { ArrowLeft, CheckCircle2, Search, TriangleAlert } from 'lucide-react'; +import { useEffect, useState } from 'react'; +import { Link } from 'react-router'; +import { t } from '@/i18n'; +import { api, errorMessage } from '@/lib/api'; +import { BookCover } from '../components/BookCover'; +import { IdentifyBookDialog } from '../components/IdentifyBookDialog'; +import { isAudiobooksDisabled, statusLabel } from '../model'; +import { useBook, useBookAction, useBooks } from '../queries'; + +type Status = 'review' | 'unmatched' | 'ignored'; + +function Identify({ id, onClose }: { id: string; onClose: () => void }) { + const book = useBook(id); + if (!book.data) return null; + return ; +} + +function ReviewRow({ book, onIdentify }: { book: ApiAudiobookDto; onIdentify: () => void }) { + const ignore = useBookAction(() => (book.status === 'ignored' ? api.audiobooks.unignore(book.id) : api.audiobooks.ignore(book.id))); + return ( +
  • + +
    + + {book.title} + +

    {[book.authors.join(', '), book.folderPath].filter(Boolean).join(' · ')}

    +

    + {statusLabel(book.status)} + {book.status === 'review' && {Math.round(book.confidence * 100)}%} +

    +
    + {book.status !== 'ignored' && ( + + )} + +
  • + ); +} + +/** Books whose identification deserves a look, the unidentified ones and the ignored ones. */ +export default function AudiobooksReviewPage() { + const [status, setStatus] = useState('review'); + const [identifying, setIdentifying] = useState(null); + const books = useBooks({ status, sortBy: 'title' }); + const items = books.data?.pages.flatMap((p) => p.items) ?? []; + + useEffect(() => { + document.title = `${t('Review')} · ${t('Audiobooks')} · TFM`; + }, []); + + return ( +
    + +

    {t('Review the audiobooks')}

    + + aria-label={t('Status')} + value={status} + onValueChange={setStatus} + options={[ + { value: 'review', label: t('To review') }, + { value: 'unmatched', label: t('Not identified') }, + { value: 'ignored', label: t('Ignored') } + ]} + /> + {books.isPending ? ( +
    + {Array.from({ length: 5 }, (_, i) => ( + + ))} +
    + ) : books.isError ? ( + } title={isAudiobooksDisabled(books.error) ? t('Audiobooks are off') : t('Could not load the audiobooks')} description={errorMessage(books.error)} /> + ) : items.length === 0 ? ( + } title={t('Nothing to review')} /> + ) : ( +
      + {items.map((b) => ( + setIdentifying(b.id)} /> + ))} +
    + )} + {books.hasNextPage && ( + + )} + {identifying && setIdentifying(null)} />} +
    + ); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/playback.ts b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/playback.ts new file mode 100644 index 0000000..71699a5 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/playback.ts @@ -0,0 +1,25 @@ +import type { ApiAudiobookDetailDto } from '@tfm/api-client'; +import { toast } from '@tfm/ui'; +import { playBook } from '@/features/player/public'; +import { t } from '@/i18n'; +import { api, errorMessage } from '@/lib/api'; +import { resumePosition, toPlayable } from './model'; + +/** Plays a book from `positionMs`, or where it was left. */ +export function playDetail(book: ApiAudiobookDetailDto, positionMs?: number): void { + if (book.tracks.length === 0) { + toast.error(t('This book has no audio files')); + return; + } + const { book: playable, tracks } = toPlayable(book); + playBook(playable, tracks, positionMs ?? resumePosition(book.progress), book.progress?.speed); +} + +/** Loads a book and plays it where it was left (cards, "continue listening"). */ +export async function playBookById(id: string): Promise { + try { + playDetail(await api.audiobooks.get(id)); + } catch (error) { + toast.error(t('Could not play the book'), { description: errorMessage(error) }); + } +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/queries.ts b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/queries.ts new file mode 100644 index 0000000..05af3af --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/queries.ts @@ -0,0 +1,72 @@ +import type { AudiobooksQuery } from '@tfm/api-client'; +import { keepPreviousData, useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { toast } from '@tfm/ui'; +import { t } from '@/i18n'; +import { api, errorMessage } from '@/lib/api'; + +/** Query keys of the audiobooks feature (the player invalidates `['audiobooks']` after saving progress). */ +export const audiobookKeys = { + all: ['audiobooks'] as const, + list: (query: AudiobooksQuery) => ['audiobooks', 'list', query] as const, + continue: ['audiobooks', 'continue'] as const, + recent: ['audiobooks', 'recent'] as const, + authors: ['audiobooks', 'authors'] as const, + series: ['audiobooks', 'series'] as const, + book: (id: string) => ['audiobooks', 'book', id] as const, + scan: ['audiobooks', 'scan'] as const, + search: (bookId: string, q: string, author: string) => ['audiobooks', 'search', bookId, q, author] as const +}; + +export const PAGE_SIZE = 60; + +export function useContinueListening(enabled = true) { + return useQuery({ queryKey: audiobookKeys.continue, queryFn: ({ signal }) => api.audiobooks.continue(20, signal), enabled }); +} + +export function useRecentBooks() { + return useQuery({ queryKey: audiobookKeys.recent, queryFn: ({ signal }) => api.audiobooks.recent(30, signal) }); +} + +export function useBooks(query: AudiobooksQuery, enabled = true) { + return useInfiniteQuery({ + queryKey: audiobookKeys.list(query), + queryFn: ({ pageParam, signal }) => api.audiobooks.list({ ...query, page: pageParam, pageSize: PAGE_SIZE }, signal), + initialPageParam: 1, + getNextPageParam: (last) => (last.page.hasNext ? last.page.page + 1 : undefined), + placeholderData: keepPreviousData, + enabled + }); +} + +export function useAuthors(enabled = true) { + return useQuery({ queryKey: audiobookKeys.authors, queryFn: ({ signal }) => api.audiobooks.authors(signal), enabled, staleTime: 60_000 }); +} + +export function useSeries(enabled = true) { + return useQuery({ queryKey: audiobookKeys.series, queryFn: ({ signal }) => api.audiobooks.series(signal), enabled, staleTime: 60_000 }); +} + +export function useBook(id: string) { + return useQuery({ queryKey: audiobookKeys.book(id), queryFn: ({ signal }) => api.audiobooks.get(id, signal) }); +} + +export function useScanState() { + return useQuery({ + queryKey: audiobookKeys.scan, + queryFn: ({ signal }) => api.audiobooks.scanState(signal), + refetchInterval: (q) => (q.state.data?.running ? 2000 : false) + }); +} + +/** A change to a book (identify, ignore, progress...) that refreshes everything shown of the books. */ +export function useBookAction(fn: (arg: T) => Promise, success?: string) { + const qc = useQueryClient(); + return useMutation({ + mutationFn: fn, + onSuccess: () => { + if (success) toast.success(success); + void qc.invalidateQueries({ queryKey: audiobookKeys.all }); + }, + onError: (error) => toast.error(t('The change could not be saved'), { description: errorMessage(error) }) + }); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/routes.ts b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/routes.ts new file mode 100644 index 0000000..d622861 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/audiobooks/routes.ts @@ -0,0 +1,9 @@ +import type { RouteObject } from 'react-router'; +import { lazyPage } from '@/app/lazyPage'; + +/** Routes of the audiobooks feature (relative to /app). */ +export const routes: RouteObject[] = [ + { path: 'audiobooks', lazy: lazyPage(() => import('./pages/AudiobooksPage')) }, + { path: 'audiobooks/review', lazy: lazyPage(() => import('./pages/AudiobooksReviewPage')) }, + { path: 'audiobooks/:id', lazy: lazyPage(() => import('./pages/AudiobookPage')) } +]; diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/player/book.test.ts b/TelegramDownloader/ClientApp/apps/web/src/features/player/book.test.ts new file mode 100644 index 0000000..d8cfa82 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/player/book.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest'; +import { bookPosition, chapterIndexAt, formatLength, locate, nextChapterStart, previousChapterStart } from './book'; + +const chapters = [ + { title: 'Uno', startMs: 0, endMs: 60_000 }, + { title: 'Dos', startMs: 60_000, endMs: 120_000 }, + { title: 'Tres', startMs: 120_000, endMs: 200_000 } +]; + +describe('book timeline', () => { + it('locates a book position in its track', () => { + expect(locate([0, 100_000, 250_000], 120_000)).toEqual({ index: 1, offsetMs: 20_000 }); + expect(locate([0, 100_000, 250_000], 0)).toEqual({ index: 0, offsetMs: 0 }); + expect(locate([0, 100_000, 250_000], 900_000)).toEqual({ index: 2, offsetMs: 650_000 }); + }); + + it('goes back to the first of several tracks with an unknown duration', () => { + expect(locate([0, 0, 0], 5_000)).toEqual({ index: 0, offsetMs: 5_000 }); + }); + + it('turns a track position into a book position', () => { + expect(bookPosition(100_000, 12.5)).toBe(112_500); + }); + + it('finds the chapter of a position', () => { + expect(chapterIndexAt(chapters, 59_000)).toBe(0); + expect(chapterIndexAt(chapters, 60_000)).toBe(1); + expect(chapterIndexAt([], 10)).toBe(-1); + }); + + it('previous goes to the start of the chapter, or to the one before in its first seconds', () => { + expect(previousChapterStart(chapters, 90_000)).toBe(60_000); + expect(previousChapterStart(chapters, 61_000)).toBe(0); + expect(nextChapterStart(chapters, 61_000)).toBe(120_000); + expect(nextChapterStart(chapters, 150_000)).toBeNull(); + }); + + it('formats lengths', () => { + expect(formatLength(2 * 3600_000 + 5 * 60_000)).toBe('2 h 05 min'); + expect(formatLength(45 * 60_000)).toBe('45 min'); + }); +}); diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/player/book.ts b/TelegramDownloader/ClientApp/apps/web/src/features/player/book.ts new file mode 100644 index 0000000..dad0fa7 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/player/book.ts @@ -0,0 +1,81 @@ +/** + * Audiobooks in the global player (pure: no DOM, no store). A book plays as a + * queue of its tracks; positions are on the *book timeline* (every track one + * after the other, in ms), which is what the server stores and what chapters + * use. These helpers convert between that and (track, seconds in the track). + */ + +export interface BookChapter { + title: string; + startMs: number; + endMs: number; +} + +/** The book being played: what the player needs besides the queue. */ +export interface PlayableBook { + id: string; + title: string; + author?: string; + coverUrl?: string; + durationMs: number; + chapters: BookChapter[]; + /** Where each track starts on the book timeline. */ + trackStarts: number[]; +} + +/** Track and offset (ms) of a book position. Past the end: the end of the last track. */ +export function locate(trackStarts: number[], positionMs: number): { index: number; offsetMs: number } { + if (trackStarts.length === 0) return { index: 0, offsetMs: 0 }; + const p = Math.max(0, positionMs); + let index = 0; + for (let i = 0; i < trackStarts.length; i++) { + if (trackStarts[i] <= p) index = i; + else break; + } + // Tracks whose duration is unknown share their start: take the first of them + while (index > 0 && trackStarts[index - 1] === trackStarts[index]) index--; + return { index, offsetMs: p - trackStarts[index] }; +} + +/** Index of the chapter at a book position, -1 when there are no chapters. */ +export function chapterIndexAt(chapters: BookChapter[], positionMs: number): number { + if (chapters.length === 0) return -1; + let found = 0; + for (let i = 0; i < chapters.length; i++) { + if (chapters[i].startMs <= positionMs + 1) found = i; + else break; + } + return found; +} + +/** Book position of a track position (seconds in the track). */ +export function bookPosition(trackStartMs: number, trackSeconds: number): number { + return Math.max(0, Math.round(trackStartMs + (Number.isFinite(trackSeconds) ? trackSeconds : 0) * 1000)); +} + +/** Where "previous chapter" goes: the start of this chapter, or the previous one within its first 3 s. */ +export function previousChapterStart(chapters: BookChapter[], positionMs: number): number { + const i = chapterIndexAt(chapters, positionMs); + if (i < 0) return 0; + if (positionMs - chapters[i].startMs > 3000 || i === 0) return chapters[i].startMs; + return chapters[i - 1].startMs; +} + +/** Start of the next chapter, or null at the last one. */ +export function nextChapterStart(chapters: BookChapter[], positionMs: number): number | null { + const i = chapterIndexAt(chapters, positionMs); + return i >= 0 && i + 1 < chapters.length ? chapters[i + 1].startMs : null; +} + +/** "2 h 05 min", "45 min", "30 s". */ +export function formatLength(ms: number): string { + const totalMinutes = Math.floor(ms / 60000); + const hours = Math.floor(totalMinutes / 60); + const minutes = totalMinutes % 60; + if (hours > 0) return `${hours} h ${String(minutes).padStart(2, '0')} min`; + if (totalMinutes > 0) return `${totalMinutes} min`; + return `${Math.max(0, Math.round(ms / 1000))} s`; +} + +/** Playback speeds offered for books. */ +export const BOOK_SPEEDS = [0.75, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3]; diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/player/bookStore.ts b/TelegramDownloader/ClientApp/apps/web/src/features/player/bookStore.ts new file mode 100644 index 0000000..cce8430 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/player/bookStore.ts @@ -0,0 +1,17 @@ +import { create } from 'zustand'; +import { persist } from 'zustand/middleware'; +import type { PlayableBook } from './book'; + +/** + * The audiobook the queue belongs to (chapters, track starts), persisted like + * the queue so a restored session keeps its chapters. Tracks of a book carry + * `book.id`; when the current track has no book this is ignored. + */ +interface BookSessionState { + book: PlayableBook | null; + setBook: (book: PlayableBook | null) => void; +} + +export const useBookSession = create()( + persist((set) => ({ book: null, setBook: (book) => set({ book }) }), { name: 'tfm.web.player.book', version: 1 }) +); diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/player/engine.ts b/TelegramDownloader/ClientApp/apps/web/src/features/player/engine.ts index 57c5c55..5a05222 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/player/engine.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/features/player/engine.ts @@ -12,6 +12,8 @@ import { toTrackTime, type ResolvedClip } from './clip'; +import { bookPosition, chapterIndexAt, locate, nextChapterStart, previousChapterStart, type PlayableBook } from './book'; +import { useBookSession } from './bookStore'; import type { AudioTrack } from './public'; import { currentTrack, displayTitle, nextIndex, previousIndex, type QueuedTrack } from './queue'; import { usePlayer, type TimeRange } from './store'; @@ -27,6 +29,9 @@ const SLEEP_FADE_SECONDS = 10; // Never crossfade tracks shorter than this many times the fade length const MIN_CROSSFADE_TRACK_RATIO = 3; const PERSIST_EVERY_MS = 5000; +// Audiobooks: how far back and forward the skip buttons jump +export const BOOK_SKIP_BACK_SECONDS = 15; +export const BOOK_SKIP_FORWARD_SECONDS = 30; const MEDIA_POSITION_EVERY_MS = 5000; export interface NowPlayingInfo { @@ -116,9 +121,11 @@ export class AudioEngine { this.listenDocument(); if (this.mediaSession) this.setupMediaSession(); this.applyVolume(); - // Volume/mute changes from the UI + this.applyRate(); + // Volume/mute/speed changes from the UI this.unsubscribe = usePlayer.subscribe((s, prev) => { if (s.volume !== prev.volume || s.muted !== prev.muted) this.applyVolume(); + if (s.rate !== prev.rate) this.applyRate(); }); } @@ -154,6 +161,82 @@ export class AudioEngine { return clipDuration(this.activeClip(), this.audio.duration); } + // ---------------------------------------------------------------- audiobooks + + /** The book of the loaded track, or null when it is not an audiobook track. */ + private loadedBook(): { book: PlayableBook; startMs: number } | null { + const track = this.loadedTrack(); + const book = useBookSession.getState().book; + if (!track?.book || !book || book.id !== track.book.id) return null; + return { book, startMs: track.book.startMs }; + } + + /** Position on the book timeline (ms), or null when not playing a book. */ + bookPosition(): number | null { + const b = this.loadedBook(); + if (!b) return null; + const p = this.audio.getAttribute('src') ? this.trackPosition() : this.store.position; + return bookPosition(b.startMs, p); + } + + /** Play an audiobook from a position of its timeline. */ + async playBook(book: PlayableBook, tracks: AudioTrack[], positionMs: number, speed?: number | null): Promise { + useBookSession.getState().setBook(book); + usePlayer.setState({ shuffle: false, originalOrder: null, repeat: 'off' }); + this.store.setRate(speed && speed > 0 ? speed : 1); + const { index, offsetMs } = locate(book.trackStarts, positionMs); + this.store.replaceQueue(tracks, Math.min(index, tracks.length - 1)); + const track = currentTrack(this.store); + if (track) await this.load(track, { startAt: offsetMs / 1000 }); + } + + /** Go to a position of the book timeline (another track when needed). */ + async seekBook(positionMs: number): Promise { + const book = useBookSession.getState().book; + const current = currentTrack(this.store); + if (!book || !current?.book || current.book.id !== book.id) return; + const { index, offsetMs } = locate(book.trackStarts, Math.max(0, Math.min(positionMs, book.durationMs || positionMs))); + if (index === this.store.index) { + this.seek(offsetMs / 1000); + return; + } + const wasPlaying = this.isPlaying || this.store.status === 'loading' || this.store.status === 'buffering'; + await this.playAt(index, { startAt: offsetMs / 1000, paused: !wasPlaying }); + } + + async nextChapter(): Promise { + const b = this.loadedBook(); + const at = this.bookPosition(); + if (!b || at === null) return void this.next(); + const target = nextChapterStart(b.book.chapters, at); + if (target !== null) await this.seekBook(target); + } + + async previousChapter(): Promise { + const b = this.loadedBook(); + const at = this.bookPosition(); + if (!b || at === null) return void this.previous(); + await this.seekBook(previousChapterStart(b.book.chapters, at)); + } + + /** Index and title of the chapter being played, or null. */ + currentChapter(): { index: number; title: string; startMs: number; endMs: number } | null { + const b = this.loadedBook(); + const at = this.bookPosition(); + if (!b || at === null) return null; + const i = chapterIndexAt(b.book.chapters, at); + return i < 0 ? null : { index: i, ...b.book.chapters[i] }; + } + + private applyRate(): void { + const rate = this.store.rate || 1; + for (const el of this.elements) { + el.defaultPlaybackRate = rate; + el.playbackRate = rate; + } + this.updatePositionState(); + } + // ---------------------------------------------------------------- volume private master(): number { @@ -331,11 +414,11 @@ export class AudioEngine { ['play', () => this.play()], ['pause', () => this.pause()], ['stop', () => this.pause()], - ['previoustrack', () => void this.previous()], - ['nexttrack', () => void this.next()], + ['previoustrack', () => void (this.loadedBook() ? this.previousChapter() : this.previous())], + ['nexttrack', () => void (this.loadedBook() ? this.nextChapter() : this.next())], ['seekto', (d) => d.seekTime !== undefined && this.seek(d.seekTime)], - ['seekbackward', (d) => this.seekBy(-(d.seekOffset || 10))], - ['seekforward', (d) => this.seekBy(d.seekOffset || 10)] + ['seekbackward', (d) => this.seekBy(-(d.seekOffset || (this.loadedBook() ? BOOK_SKIP_BACK_SECONDS : 10)))], + ['seekforward', (d) => this.seekBy(d.seekOffset || (this.loadedBook() ? BOOK_SKIP_FORWARD_SECONDS : 10))] ]; for (const [action, handler] of handlers) { try { @@ -406,6 +489,8 @@ export class AudioEngine { private assign(el: HTMLAudioElement, url: string): void { el.loop = false; el.src = url; + el.defaultPlaybackRate = this.store.rate || 1; + el.playbackRate = this.store.rate || 1; } /** Stop an element and let go of its source. */ @@ -461,6 +546,8 @@ export class AudioEngine { } private crossfadeSecondsFor(duration: number): number { + // The parts of a book follow each other without a fade + if (this.loadedBook()) return 0; const seconds = this.store.crossfadeSeconds; if (seconds <= 0 || !Number.isFinite(duration)) return 0; return duration >= seconds * MIN_CROSSFADE_TRACK_RATIO ? seconds : 0; @@ -740,6 +827,8 @@ export class AudioEngine { /** Replace the queue and start playing. */ async playQueue(tracks: AudioTrack[], startIndex = 0): Promise { + // Music plays at its speed; a book keeps its own (playBook) + if (!tracks[startIndex]?.book && this.store.rate !== 1) this.store.setRate(1); this.store.replaceQueue(tracks, startIndex); const track = currentTrack(this.store); if (track) await this.load(track); @@ -810,6 +899,14 @@ export class AudioEngine { const s = this.store; if (s.queue.length === 0) return; const i = nextIndex(s, !!options.auto); + if (i < 0 && this.loadedBook()) { + // End of a book: stay at its end, so the progress says it is finished + this.transitioning = false; + this.pause(); + const end = this.trackDuration(); + usePlayer.setState({ position: Number.isFinite(end) ? end : this.store.position, status: 'paused' }); + return; + } if (i < 0) { // End of the queue: stop on the last track, at its start this.transitioning = false; @@ -939,8 +1036,12 @@ export class AudioEngine { // ---------------------------------------------------------------- sleep timer /** Pause after `minutes` (fading out), or at the end of the current track. */ - setSleepTimer(minutes: number | 'track'): void { - if (minutes === 'track') this.store.setSleep(null, true); + setSleepTimer(minutes: number | 'track' | 'chapter'): void { + if (minutes === 'chapter') { + const chapter = this.currentChapter(); + if (chapter) this.store.setSleep(null, false, chapter.endMs); + else this.store.setSleep(null, true); + } else if (minutes === 'track') this.store.setSleep(null, true); else this.store.setSleep(Date.now() + minutes * 60_000, false); } @@ -950,7 +1051,12 @@ export class AudioEngine { } private handleSleepTimer(): void { - const { sleepEndsAt } = this.store; + const { sleepEndsAt, sleepAtBookMs } = this.store; + if (sleepAtBookMs !== null) { + const at = this.bookPosition(); + if (at !== null && at >= sleepAtBookMs - 250) this.finishSleep(); + return; + } if (!sleepEndsAt) return; const remaining = (sleepEndsAt - Date.now()) / 1000; if (remaining <= 0) this.finishSleep(); diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/player/public.ts b/TelegramDownloader/ClientApp/apps/web/src/features/player/public.ts index 37c5cbb..fe6f169 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/player/public.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/features/player/public.ts @@ -6,8 +6,11 @@ * This module is imported from many places, so it stays tiny: the playback * engine and the viewers are loaded with `import()` on first use. */ +import type { PlayableBook } from './book'; import { useViewer } from './viewerStore'; +export type { BookChapter, PlayableBook } from './book'; +export { formatLength } from './book'; export { codeLanguageOf, documentFormatOf, documentViewerKind, type DocumentFormat } from './documentFormats'; /** A playable audio item. URLs must be playable by an
    - setQueueOpen(!queueOpen)} className={cn('lg:hidden', queueOpen && 'text-accent-400')}> + setQueueOpen(!queueOpen)} className={cn('lg:hidden', queueOpen && 'text-accent-400')}> - + {!book && }
    @@ -86,17 +90,24 @@ export default function ExpandedPlayer() {

    {title}

    {[subtitle, album].filter(Boolean).join(' · ')}

    - - candidate && openAddToPlaylist([candidate])}> - - + {book ? ( + + ) : ( + <> + + candidate && openAddToPlaylist([candidate])}> + + + + )}
    - - + {book ? : } + {book ? : }
    - - setQueueOpen(!queueOpen)} className={cn('max-lg:hidden', queueOpen && 'text-accent-400')}> + {book && } + + setQueueOpen(!queueOpen)} className={cn('max-lg:hidden', queueOpen && 'text-accent-400')}>
    @@ -104,8 +115,8 @@ export default function ExpandedPlayer() { {queueOpen && ( )} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/player/ui/PlayerBar.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/player/ui/PlayerBar.tsx index 2619d5f..f664971 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/player/ui/PlayerBar.tsx +++ b/TelegramDownloader/ClientApp/apps/web/src/features/player/ui/PlayerBar.tsx @@ -1,17 +1,20 @@ import { cn, IconButton, Sheet, SheetContent } from '@tfm/ui'; -import { ChevronUp, ListMusic, Maximize2, SkipForward } from 'lucide-react'; +import { ChevronUp, ListMusic, Maximize2, RotateCw, SkipForward } from 'lucide-react'; import { lazy, Suspense } from 'react'; import { t } from '@/i18n'; import '../player.css'; -import { getEngine } from '../engine'; +import { BOOK_SKIP_FORWARD_SECONDS, getEngine } from '../engine'; import { formatTime } from '../format'; import { usePlayer } from '../store'; import { Artwork } from './Artwork'; +import { BookmarkButton, BookSeek, BookTransport, SpeedMenu } from './BookControls'; +import { useBookNow } from './useBookNow'; import { PlayerMoreMenu, PlayPauseButton, SleepTimerMenu, Transport, VolumeControl } from './Controls'; import { FavoriteButton } from './FavoriteButton'; import { QueuePanel } from './QueuePanel'; import { SeekBar } from './SeekBar'; import { useNowPlaying, useSyncMediaSession } from './useNowPlaying'; +import { useBookSync } from './useBookSync'; import { usePlayerSync } from './usePlayerSync'; import { usePlayerShortcuts } from './usePlayerShortcuts'; @@ -52,6 +55,8 @@ export default function PlayerBar() { const { track, title, subtitle, cover, meta } = useNowPlaying(); const tags = { title: meta?.title, artist: meta?.artist, album: meta?.album }; usePlayerSync({ ...tags, qid: track?.qid }); + useBookSync(); + const book = useBookNow(); const expanded = usePlayer((s) => s.expanded); const queueOpen = usePlayer((s) => s.queueOpen); const status = usePlayer((s) => s.status); @@ -83,12 +88,31 @@ export default function PlayerBar() {
    - - + {book ? ( + <> + +
    + +
    + + ) : ( + <> + + + + )}
    - - setQueueOpen(!queueOpen)} className={cn(queueOpen && 'text-accent-400')}> + {book && } + {book && } + + (book ? expand() : setQueueOpen(!queueOpen))} + className={cn(queueOpen && 'text-accent-400')} + > @@ -110,9 +134,15 @@ export default function PlayerBar() { - void getEngine().next()}> - - + {book ? ( + getEngine().seekBy(BOOK_SKIP_FORWARD_SECONDS)}> + + + ) : ( + void getEngine().next()}> + + + )}
    diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/player/ui/useBookNow.ts b/TelegramDownloader/ClientApp/apps/web/src/features/player/ui/useBookNow.ts new file mode 100644 index 0000000..f238967 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/player/ui/useBookNow.ts @@ -0,0 +1,24 @@ +import { bookPosition, chapterIndexAt, type PlayableBook } from '../book'; +import { useBookSession } from '../bookStore'; +import { selectCurrent, usePlayer } from '../store'; + +export interface BookNow { + book: PlayableBook; + /** Position on the book timeline (ms). */ + positionMs: number; + chapterIndex: number; + chapter: PlayableBook['chapters'][number] | null; + /** Where the current track starts on the book timeline. */ + trackStartMs: number; +} + +/** The audiobook being played and where in it, or null when the current track is not a book. */ +export function useBookNow(): BookNow | null { + const track = usePlayer(selectCurrent); + const position = usePlayer((s) => s.position); + const book = useBookSession((s) => s.book); + if (!track?.book || !book || book.id !== track.book.id) return null; + const positionMs = bookPosition(track.book.startMs, position); + const chapterIndex = chapterIndexAt(book.chapters, positionMs); + return { book, positionMs, chapterIndex, chapter: chapterIndex >= 0 ? book.chapters[chapterIndex] : null, trackStartMs: track.book.startMs }; +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/player/ui/useBookSync.ts b/TelegramDownloader/ClientApp/apps/web/src/features/player/ui/useBookSync.ts new file mode 100644 index 0000000..6bb5a17 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/player/ui/useBookSync.ts @@ -0,0 +1,71 @@ +import { useEffect } from 'react'; +import { api } from '@/lib/api'; +import { queryClient } from '@/lib/queryClient'; +import { useBookSession } from '../bookStore'; +import { getEngine } from '../engine'; +import { currentTrack } from '../queue'; +import { usePlayer } from '../store'; + +/** How often the position of a book being played goes to the server. */ +export const BOOK_SYNC_EVERY_MS = 15_000; + +/** + * Mounted once (by the player bar): keeps the server progress of the audiobook + * being played up to date, so every device resumes where it was left. Sends it + * every 15 s while playing, on pause, on a track change and when the page goes + * away (a keepalive request that outlives the page). + */ +export function useBookSync() { + useEffect(() => { + let lastSentAt = 0; + let lastSent: { id: string; positionMs: number; rate: number } | null = null; + + const flush = (reason: 'tick' | 'pause' | 'leave') => { + const book = useBookSession.getState().book; + const state = usePlayer.getState(); + const track = currentTrack(state); + if (!book || track?.book?.id !== book.id) return; + const positionMs = getEngine().bookPosition(); + if (positionMs === null) return; + const rate = state.rate || 1; + if (reason === 'tick' && lastSent && lastSent.id === book.id && lastSent.rate === rate && Math.abs(lastSent.positionMs - positionMs) < 1000) return; + lastSent = { id: book.id, positionMs, rate }; + lastSentAt = Date.now(); + const body = { positionMs, speed: rate }; + if (reason === 'leave') { + // The page may be gone before an ordinary request ends + void fetch(api.audiobooks.progressUrl(book.id), { + method: 'PUT', + keepalive: true, + credentials: 'same-origin', + headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-Requested-With': 'tfm' }, + body: JSON.stringify(body) + }).catch(() => undefined); + return; + } + api.audiobooks + .setProgress(book.id, body) + .then(() => { + if (reason === 'pause') void queryClient.invalidateQueries({ queryKey: ['audiobooks'] }); + }) + .catch(() => undefined); + }; + + const unsubscribe = usePlayer.subscribe((s, prev) => { + if (prev.status === 'playing' && s.status === 'paused') flush('pause'); + else if (s.index !== prev.index && prev.index >= 0) flush('tick'); + else if (s.status === 'playing' && Date.now() - lastSentAt >= BOOK_SYNC_EVERY_MS) flush('tick'); + }); + const onHidden = () => { + if (document.visibilityState === 'hidden') flush('leave'); + }; + const onPageHide = () => flush('leave'); + document.addEventListener('visibilitychange', onHidden); + window.addEventListener('pagehide', onPageHide); + return () => { + unsubscribe(); + document.removeEventListener('visibilitychange', onHidden); + window.removeEventListener('pagehide', onPageHide); + }; + }, []); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/player/ui/useNowPlaying.ts b/TelegramDownloader/ClientApp/apps/web/src/features/player/ui/useNowPlaying.ts index 32f1fea..e33e67a 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/player/ui/useNowPlaying.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/features/player/ui/useNowPlaying.ts @@ -1,4 +1,6 @@ import { useEffect, useMemo } from 'react'; +import { chapterIndexAt, bookPosition } from '../book'; +import { useBookSession } from '../bookStore'; import { hasClip } from '../clip'; import { getEngine } from '../engine'; import { useTrackMeta, type TrackMeta } from '../metadata'; @@ -11,9 +13,27 @@ import { selectCurrent, usePlayer } from '../store'; */ export function useNowPlaying() { const track = usePlayer(selectCurrent); - const fileMeta = useTrackMeta(track); + const book = useBookSession((s) => s.book); + const inBook = !!track?.book && book?.id === track.book.id; + // A book part: the chapter is the title and the book the rest (its files' tags say less) + const chapterIndex = usePlayer((s) => (inBook && book && track?.book ? chapterIndexAt(book.chapters, bookPosition(track.book.startMs, s.position)) : -1)); + const fileMeta = useTrackMeta(inBook ? null : track); const clipped = hasClip(track); - const meta = useMemo(() => (clipped && fileMeta ? { cover: fileMeta.cover } : fileMeta), [clipped, fileMeta]); + const chapterTitle = inBook && book ? (book.chapters[chapterIndex]?.title || book.title) : null; + const meta = useMemo(() => { + if (inBook && book) return { title: chapterTitle ?? book.title, artist: book.author, album: book.title, cover: book.coverUrl }; + return clipped && fileMeta ? { cover: fileMeta.cover } : fileMeta; + }, [inBook, book, chapterTitle, clipped, fileMeta]); + if (inBook && book) { + return { + track, + title: chapterTitle ?? book.title, + subtitle: [book.title, book.author].filter(Boolean).join(' · '), + album: '', + cover: book.coverUrl ?? track?.coverUrl ?? null, + meta + }; + } const cover = meta?.cover ?? track?.coverUrl ?? null; const title = meta?.title || (track ? displayTitle(track) : ''); const subtitle = meta?.artist || track?.artist || track?.source || ''; diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/player/ui/usePlayerSync.ts b/TelegramDownloader/ClientApp/apps/web/src/features/player/ui/usePlayerSync.ts index 5016cd7..bad1c11 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/player/ui/usePlayerSync.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/features/player/ui/usePlayerSync.ts @@ -104,7 +104,8 @@ export function usePlayerSync(tags: TrackTags & { qid?: string }) { return usePlayer.subscribe((s) => { const track = currentTrack(s); if (!tracker.update(track?.qid ?? null, s.position, s.duration, s.status === 'playing')) return; - if (!enabledRef.current || !track) return; + // Audiobooks keep their own progress: their parts are not music plays + if (!enabledRef.current || !track || track.book) return; const tags = tagsRef.current.qid === track.qid ? tagsRef.current : {}; const body = toPlayerTrack(track, tags, s.duration); if (!body) return; diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/settings/catalog.ts b/TelegramDownloader/ClientApp/apps/web/src/features/settings/catalog.ts index aa0dd81..dfef680 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/settings/catalog.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/features/settings/catalog.ts @@ -1,5 +1,6 @@ import { ArrowDownUp, + BookAudio, Bell, Cable, Clapperboard, @@ -36,6 +37,7 @@ export type SectionId = | 'apps' | 'webdav' | 'library' + | 'audiobooks' | 'appearance' | 'about'; @@ -58,6 +60,7 @@ export function sections(): SectionDef[] { { id: 'channels', title: t('Channels'), description: t('Refresh of own channels, images and hidden channels.'), icon: FolderTree, group: 'server' }, { id: 'tasks', title: t('Tasks & auto-resume'), description: t('Keep transfers across restarts.'), icon: ListRestart, group: 'server' }, { id: 'library', title: t('Media library'), description: t('Movies and series: providers, channels, folder rules and scans.'), icon: Clapperboard, group: 'server' }, + { id: 'audiobooks', title: t('Audiobooks'), description: t('Audiobooks in your channels: sources, language and scans.'), icon: BookAudio, group: 'server' }, { id: 'security', title: t('Web security'), description: t('Password of the web interface, passkeys and the local network rule.'), icon: ShieldCheck, group: 'access' }, { id: 'apps', title: t('Apps & API'), description: t('API key for TFM Player, Android and Android TV.'), icon: Smartphone, group: 'access' }, { id: 'webdav', title: t('WebDAV'), description: t('Credentials of the native WebDAV share.'), icon: Network, group: 'access' }, @@ -192,6 +195,19 @@ export function settingDefs(): SettingDef[] { { id: 'libraryFolderRules', section: 'library', label: t('Folder rules'), description: t('Tell the scan what a folder holds when a channel mixes content: series, movies or ignore (extras, trailers). A rule covers every subfolder; the most specific path wins and / is the whole channel. Folders simply named Series, Películas, Cine, Movies… are recognised without a rule. Manual fixes are never undone by a rule.') }, { id: 'libraryScan', section: 'library', label: t('Library scan'), keywords: 'rescan identify' }, + // audiobooks + { + id: 'audiobooksEnabled', + section: 'audiobooks', + label: t('Enable audiobooks'), + description: t('Find audiobooks among the audio files of the library channels: folders under an Audiolibros / Audiobooks folder (or a folder rule of kind Audiobooks) and every .m4b file. They are identified with the book sources below and their listening progress is kept for every device.') + }, + { id: 'audiobookAutoScan', section: 'audiobooks', label: t('Scan after a channel refresh'), description: t('When a channel index is refreshed, look for new audiobooks right away.') }, + { id: 'audiobookLanguage', section: 'audiobooks', label: t('Language of the books'), description: t('Two-letter code (es, en, fr...): picks the Apple Books store and filters Google Books.') }, + { id: 'audibleRegion', section: 'audiobooks', label: t('Audible store'), description: t('The Audible catalogue asked for narrators, series and chapters.') }, + { id: 'audiobookProviders', section: 'audiobooks', label: t('Book sources'), description: t('Every enabled source is asked; the best match sets the book and the others fill what it lacks. Changes are saved at once.'), keywords: 'itunes google open library audible audnexus' }, + { id: 'audiobookScan', section: 'audiobooks', label: t('Audiobook scan'), keywords: 'rescan identify' }, + // appearance { id: 'theme', section: 'appearance', label: t('Theme'), keywords: 'dark light background amoled' }, { id: 'accent', section: 'appearance', label: t('Accent colour'), keywords: 'color' }, diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/settings/model/configForm.ts b/TelegramDownloader/ClientApp/apps/web/src/features/settings/model/configForm.ts index fb4d3ed..adac3f4 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/settings/model/configForm.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/features/settings/model/configForm.ts @@ -22,7 +22,8 @@ type ReadOnlyKeys = | 'mobileApiKey' | 'mobileApiKeySet' | 'webDavPasswordSet' - | 'libraryProviders'; + | 'libraryProviders' + | 'audiobookProviders'; /** Every value of the settings form. */ export type FormValues = Omit & { @@ -56,6 +57,7 @@ export function toFormValues(config: AppConfigDto): FormValues { mobileApiKeySet: _ks, webDavPasswordSet: _w, libraryProviders, + audiobookProviders: _a, ...rest } = config; return { @@ -103,7 +105,7 @@ export function buildPatch(base: FormValues, draft: Draft): UpdateConfigRequest .map((p) => (p.apiKey === null ? { id: p.id, enabled: p.enabled, priority: p.priority } : { id: p.id, enabled: p.enabled, priority: p.priority, apiKey: p.apiKey.trim() })); continue; } - if (key === 'libraryLanguage' || key === 'webDavUser') { + if (key === 'libraryLanguage' || key === 'webDavUser' || key === 'audiobookLanguage') { patch[key] = String(draft[key] ?? '').trim(); continue; } diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/settings/pages/SettingsPage.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/settings/pages/SettingsPage.tsx index 65b39d5..4b99dd9 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/settings/pages/SettingsPage.tsx +++ b/TelegramDownloader/ClientApp/apps/web/src/features/settings/pages/SettingsPage.tsx @@ -11,6 +11,7 @@ import { AboutSection } from '../sections/AboutSection'; import { AppearanceSection } from '../sections/AppearanceSection'; import { AppsSection } from '../sections/AppsSection'; import { ChannelsSection } from '../sections/ChannelsSection'; +import { AudiobooksSection } from '../sections/AudiobooksSection'; import { LibrarySection } from '../sections/LibrarySection'; import { SecuritySection } from '../sections/SecuritySection'; import { @@ -35,6 +36,7 @@ const FORM_SECTIONS: Partial>> channels: ChannelsSection, tasks: TasksSection, library: LibrarySection, + audiobooks: AudiobooksSection, apps: AppsSection, webdav: WebDavSection }; diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/settings/sections/AudiobooksSection.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/settings/sections/AudiobooksSection.tsx new file mode 100644 index 0000000..5c63bff --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/settings/sections/AudiobooksSection.tsx @@ -0,0 +1,210 @@ +import type { ApiBookProviderDto } from '@tfm/api-client'; +import { isApiError } from '@tfm/api-client'; +import { Badge, Button, Checkbox, cn, IconButton, Input, Progress, Select, Switch, toast } from '@tfm/ui'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { ArrowDown, ArrowUp, ArrowUpRight, BookAudio, KeyRound, Radar, Square } from 'lucide-react'; +import { useId, useState } from 'react'; +import { Link } from 'react-router'; +import { t } from '@/i18n'; +import { api, errorMessage } from '@/lib/api'; +import { SettingRow, SettingsGroup, SwitchRow } from '../components/SettingRow'; +import { settingsKeys } from '../model/useSettingsForm'; +import type { FormSectionProps } from './types'; + +const AUDIBLE_REGIONS = ['es', 'us', 'uk', 'de', 'fr', 'it', 'ca', 'au', 'jp', 'in'] as const; +const scanKey = ['settings', 'audiobook-scan'] as const; + +function providerHelp(id: string): string { + if (id === 'itunes') return t('Official and free. Apple Books audiobooks: good covers and descriptions.'); + if (id === 'google') return t('Free; the key is optional (it raises the daily quota). Descriptions and ISBN in many languages.'); + if (id === 'openlibrary') return t('Free and open. Uneven data: useful as a fallback.'); + if (id === 'audible') return t('Narrators, series and chapters. It is not an official API: it may stop working.'); + return ''; +} + +/** The book sources: enabled, order and the optional Google key. Saved at once, not with the Save button. */ +function Providers({ providers }: { providers: ApiBookProviderDto[] }) { + const qc = useQueryClient(); + const [keys, setKeys] = useState>({}); + const save = useMutation({ + mutationFn: (changes: { id: string; enabled?: boolean; priority?: number; apiKey?: string }[]) => api.config.update({ audiobookProviders: changes }), + onSuccess: (config) => { + qc.setQueryData(settingsKeys.config, config); + setKeys({}); + }, + onError: (error) => toast.error(t('Could not save the book sources'), { description: errorMessage(error) }) + }); + const ordered = [...providers].sort((a, b) => a.priority - b.priority); + const move = (index: number, delta: number) => { + const next = [...ordered]; + const [item] = next.splice(index, 1); + next.splice(index + delta, 0, item); + save.mutate(next.map((p, i) => ({ id: p.id, priority: i + 1 }))); + }; + + return ( + +
    + {ordered.map((p, i) => ( +
    +
    +
    +

    + {i + 1}. + {p.name} + {p.apiKeySet && {t('Key set')}} +

    +

    {providerHelp(p.id)}

    + + {p.website.replace(/^https?:\/\//, '')} + +
    +
    + move(i, -1)}> + + + move(i, 1)}> + + + save.mutate([{ id: p.id, enabled: b }])} /> +
    +
    + {p.keyUrl && ( +
    + } + aria-label={t('API key')} + placeholder={p.apiKey ?? t('API key (optional)')} + value={keys[p.id] ?? ''} + onChange={(e) => setKeys({ ...keys, [p.id]: e.target.value })} + className="min-w-56 flex-1" + /> + + {p.apiKeySet && ( + + )} + + {t('Get an API key')} + +
    + )} +
    + ))} +
    +
    + ); +} + +function ScanRow({ enabled, dirty }: { enabled: boolean; dirty: boolean }) { + const qc = useQueryClient(); + const [force, setForce] = useState(false); + const scan = useQuery({ + queryKey: scanKey, + queryFn: ({ signal }) => api.audiobooks.scanState(signal), + refetchInterval: (q) => (q.state.data?.running ? 2000 : false) + }); + const start = useMutation({ + mutationFn: () => api.audiobooks.scan({ force }), + onSuccess: () => { + toast.success(t('Audiobook scan started')); + void qc.invalidateQueries({ queryKey: scanKey }); + }, + onError: (error) => + toast.error(isApiError(error) && error.code === 'already_running' ? t('A scan is already running') : t('Could not start the scan'), { description: errorMessage(error) }) + }); + const cancel = useMutation({ + mutationFn: () => api.audiobooks.cancelScan(), + onSuccess: () => toast(t('Cancelling the scan...')) + }); + const s = scan.data; + const running = !!s?.running; + const percent = s?.booksToProcess ? (s.booksProcessed / s.booksToProcess) * 100 : undefined; + + return ( + {t('Running')} : undefined}> +
    + {s ? ( +
    + {running && } +

    + {t('{found} books · {matched} identified · {review} to review · {unmatched} unidentified', { + found: s.booksFound, + matched: s.matched, + review: s.review, + unmatched: s.unmatched + })} + {running && s.booksToProcess > 0 && ` · ${s.booksProcessed}/${s.booksToProcess}`} +

    + {s.finishedAt && !running &&

    {t('Last scan: {date}', { date: new Date(s.finishedAt).toLocaleString() })}

    } + {s.error &&

    {s.error}

    } +
    + ) : ( +

    {t('No scan yet.')}

    + )} +
    + {running ? ( + + ) : ( + + )} + setForce(c === true)} disabled={running} /> + +
    + {!enabled &&

    {t('Enable audiobooks and save to scan.')}

    } + {enabled && dirty &&

    {t('Save the changes before scanning.')}

    } +
    +
    + ); +} + +/** Settings of the audiobooks: switch, language, Audible store, sources and the scan. */ +export function AudiobooksSection(props: FormSectionProps) { + const { form, values: v } = props; + const langId = useId(); + const regionId = useId(); + const providers = form.config.data?.audiobookProviders ?? []; + const savedEnabled = !!form.config.data?.audiobooksEnabled; + const dirty = form.dirty.some((k) => k === 'audiobooksEnabled' || k === 'audiobookLanguage' || k === 'audibleRegion'); + + return ( +
    + + form.setField('audiobooksEnabled', b)} /> + form.setField('audiobookAutoScan', b)} /> + + form.setField('audiobookLanguage', e.target.value)} className="w-24" /> + + + + @@ -1732,6 +1733,7 @@ private static string FolderRuleKindLabel(string kind) => kind switch { "series" => "Series", + "audiobook" => "Audiobooks", "movie" => "Movies", "ignore" => "Ignore", _ => kind diff --git a/TelegramDownloader/Program.cs b/TelegramDownloader/Program.cs index c2302e8..91e1ade 100644 --- a/TelegramDownloader/Program.cs +++ b/TelegramDownloader/Program.cs @@ -253,6 +253,24 @@ // Posters of the items a scan touched go to the image cache in the background builder.Services.AddHostedService(); builder.Services.AddSingleton(); + +// Audiobooks: books found in the audio files of the library channels, book providers, listening progress +builder.Services.AddHttpClient("books", c => +{ + c.Timeout = TimeSpan.FromSeconds(30); + c.DefaultRequestHeaders.Accept.ParseAdd("application/json"); +}).ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler +{ + AutomaticDecompression = System.Net.DecompressionMethods.All, + PooledConnectionLifetime = TimeSpan.FromMinutes(10) +}); +builder.Services.AddHttpClient(c => c.Timeout = TimeSpan.FromSeconds(30)); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(sp => sp.GetRequiredService()); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(sp => sp.GetRequiredService()); +builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => new TelegramDownloader.Services.Mobile.ChannelSearchIndex( sp.GetRequiredService(), sp.GetRequiredService>())); diff --git a/TelegramDownloader/Services/Audio/AudioAttributes.cs b/TelegramDownloader/Services/Audio/AudioAttributes.cs new file mode 100644 index 0000000..c0953d5 --- /dev/null +++ b/TelegramDownloader/Services/Audio/AudioAttributes.cs @@ -0,0 +1,22 @@ +using TL; + +namespace TelegramDownloader.Services.Audio +{ + /// The audio details Telegram keeps for a document: duration in seconds, title, performer and whether it has a cover. + public sealed record AudioAttributes(int? Duration, string? Title, string? Performer, bool HasCover) + { + public static readonly AudioAttributes None = new(null, null, null, false); + + public static AudioAttributes From(Message message) + { + if (message.media is not MessageMediaDocument { document: TL.Document doc }) return None; + var audio = doc.attributes?.OfType().FirstOrDefault(); + if (audio == null) return None; + return new AudioAttributes( + audio.duration > 0 ? audio.duration : null, + string.IsNullOrWhiteSpace(audio.title) ? null : audio.title.Trim(), + string.IsNullOrWhiteSpace(audio.performer) ? null : audio.performer.Trim(), + doc.thumbs != null && doc.thumbs.Length > 0); + } + } +} diff --git a/TelegramDownloader/Services/Audiobooks/AudiobookGrouper.cs b/TelegramDownloader/Services/Audiobooks/AudiobookGrouper.cs new file mode 100644 index 0000000..ee1cb16 --- /dev/null +++ b/TelegramDownloader/Services/Audiobooks/AudiobookGrouper.cs @@ -0,0 +1,101 @@ +using TelegramDownloader.Models; +using TelegramDownloader.Services.Library; + +namespace TelegramDownloader.Services.Audiobooks +{ + /// The files of one book, found by . + public sealed class BookGroup + { + public required string GroupKey { get; init; } + public required string FolderPath { get; init; } + /// The name the book is read from: the book folder, or the file for single-file books. + public required string Name { get; init; } + /// The folder above, when it says something (an author, a series). + public string? Context { get; init; } + /// In playing order. + public required List Files { get; init; } + } + + /// + /// Decides which audio files of a channel are audiobooks and groups them in + /// books. Pure: no I/O. + /// + /// Audio files under a folder rule audiobook, or under a folder named like + /// one ("Audiolibros", "Audiobooks"...), are audiobooks. .m4b files are, anywhere + /// (but not under an ignore rule). + /// A folder below that root is one book: its files are the chapters, and disc + /// folders ("CD1", "Parte 2") belong to the book above them. + /// Files right in the root, and .m4b files, are books on their own; "Libro + /// parte 1" and "Libro parte 2" are one. + /// + /// + public static class AudiobookGrouper + { + public static List Group(GeneralConfig config, long channelId, IEnumerable docs) + { + var byKey = new Dictionary Files)>(StringComparer.OrdinalIgnoreCase); + foreach (var doc in docs) + { + if (!doc.IsFile || string.IsNullOrEmpty(doc.Name) || !AudiobookNames.IsAudio(doc.Type ?? Path.GetExtension(doc.Name))) continue; + var folder = LibraryFolderRules.Normalize(doc.FilterPath); + var root = RootOf(config, channelId, folder, doc.Type ?? Path.GetExtension(doc.Name)); + if (root == null) continue; + + string key, bookFolder, name; + string? context; + var standalone = folder.Equals(root, StringComparison.OrdinalIgnoreCase) || AudiobookNames.IsBookOnly(doc.Type ?? Path.GetExtension(doc.Name)); + if (standalone) + { + bookFolder = folder; + name = doc.Name; + context = AudiobookNames.FolderName(folder); + key = $"{channelId}:{folder}|{AudiobookNames.PartKey(doc.Name)}"; + } + else + { + bookFolder = folder; + // Disc folders belong to the book above them + while (AudiobookNames.IsDiscFolder(AudiobookNames.FolderName(bookFolder)) && !bookFolder.Equals(root, StringComparison.OrdinalIgnoreCase) + && LibraryFolderRules.IsWithin(AudiobookNames.Parent(bookFolder), root)) + bookFolder = AudiobookNames.Parent(bookFolder); + name = AudiobookNames.FolderName(bookFolder) ?? doc.Name; + context = AudiobookNames.FolderName(AudiobookNames.Parent(bookFolder)); + key = $"{channelId}:{bookFolder}"; + } + + if (!byKey.TryGetValue(key, out var group)) + byKey[key] = group = (bookFolder, name, context, new List()); + group.Files.Add(doc); + } + + return byKey.Select(kv => new BookGroup + { + GroupKey = kv.Key, + FolderPath = kv.Value.Folder, + Name = kv.Value.Name, + Context = AudiobookNames.IsBookFolderName(kv.Value.Context) ? null : kv.Value.Context, + Files = Order(kv.Value.Files) + }).ToList(); + } + + /// Playing order: folder (disc) first, then the file name, numbers as numbers. + public static List Order(IEnumerable files) => + files.OrderBy(f => LibraryFolderRules.Normalize(f.FilterPath), Comparer.Create(AudiobookNames.NaturalCompare)) + .ThenBy(f => f.Name, Comparer.Create(AudiobookNames.NaturalCompare)) + .ToList(); + + /// + /// The audiobook root a file is under: the folder of its audiobook rule, else the + /// deepest audiobook-named folder; for .m4b files, their own folder. Null: not an audiobook. + /// + public static string? RootOf(GeneralConfig config, long channelId, string folder, string? extension) + { + var rule = LibraryFolderRules.ResolveRule(config, channelId, folder); + if (rule?.Kind == LibraryRuleKind.Ignore) return null; + if (rule?.Kind == LibraryRuleKind.Audiobook) return LibraryFolderRules.Normalize(rule.Path); + var named = AudiobookNames.BookRootFromPath(folder); + if (named != null) return named; + return AudiobookNames.IsBookOnly(extension) ? folder : null; + } + } +} diff --git a/TelegramDownloader/Services/Audiobooks/AudiobookMatcher.cs b/TelegramDownloader/Services/Audiobooks/AudiobookMatcher.cs new file mode 100644 index 0000000..5cd230a --- /dev/null +++ b/TelegramDownloader/Services/Audiobooks/AudiobookMatcher.cs @@ -0,0 +1,152 @@ +using TelegramDownloader.Models.Audiobooks; +using TelegramDownloader.Models.Library; +using TelegramDownloader.Services.Library; + +namespace TelegramDownloader.Services.Audiobooks +{ + public sealed record BookMatch(BookCandidate Candidate, double Score) + { + public string Status => LibraryMatcher.StatusFor(Score); + } + + /// Scores book candidates against what the names say. Pure: no I/O. + public static class AudiobookMatcher + { + public static BookMatch? Best(ParsedBook parsed, IReadOnlyList candidates) + { + BookMatch? best = null; + for (int i = 0; i < candidates.Count; i++) + { + // Providers return the most relevant first: earlier wins ties + var score = Math.Min(1.0, Score(parsed, candidates[i]) + 0.01 * (1.0 - (double)i / Math.Max(1, candidates.Count))); + if (best == null || score > best.Score) + best = new BookMatch(candidates[i], score); + } + return best; + } + + public static double Score(ParsedBook parsed, BookCandidate c) + { + var title = MediaNameParser.NormalizeForMatch(parsed.Title); + if (title.Length == 0) return 0; + var candidateTitle = MediaNameParser.NormalizeForMatch(c.Title); + var full = MediaNameParser.NormalizeForMatch($"{c.Title} {c.Subtitle}"); + // "El imperio final (Nacidos de la bruma 1)", "Dune: Las crónicas de Dune 1" + var bare = MediaNameParser.NormalizeForMatch(BareTitle(c.Title)); + + var direct = Math.Max(Math.Max(LibraryMatcher.Similarity(title, candidateTitle), LibraryMatcher.Similarity(title, full)), LibraryMatcher.Similarity(title, bare)); + var author = parsed.Author ?? parsed.Context; + var directAuthor = AuthorFactor(author, c.Authors, parsed.Author != null); + + // "Título - Autor": the parts the other way round + double swapped = 0, swappedAuthor = 0; + if (parsed.Author != null) + { + var other = MediaNameParser.NormalizeForMatch(parsed.Author); + swapped = Math.Max(Math.Max(LibraryMatcher.Similarity(other, candidateTitle), LibraryMatcher.Similarity(other, full)), LibraryMatcher.Similarity(other, bare)); + swappedAuthor = AuthorFactor(parsed.Title, c.Authors, true); + } + + var score = Math.Max(direct * directAuthor, swapped * swappedAuthor); + + // A series and number that agree confirm it + if (parsed.Sequence != null && c.Series.Any(s => s.Sequence != null && Same(s.Sequence, parsed.Sequence))) + score = Math.Min(1.0, score + 0.03); + if (parsed.Year.HasValue && c.Year.HasValue && Math.Abs(parsed.Year.Value - c.Year.Value) <= 1) + score = Math.Min(1.0, score + 0.02); + return score; + } + + private static readonly System.Text.RegularExpressions.Regex Bracketed = new(@"\s*[\(\[][^\)\]]*[\)\]]", System.Text.RegularExpressions.RegexOptions.Compiled); + + /// The title without the series in brackets nor what follows a colon. + public static string BareTitle(string title) + { + var s = Bracketed.Replace(title, string.Empty); + var colon = s.IndexOf(':'); + if (colon > 2) s = s[..colon]; + return s.Trim(); + } + + private static bool Same(string a, string b) => + a.TrimStart('0').Equals(b.TrimStart('0'), StringComparison.OrdinalIgnoreCase); + + /// How much the author agrees: 1 when it does, less when it does not, a little less when unknown. + private static double AuthorFactor(string? wanted, IReadOnlyList authors, bool explicitAuthor) + { + if (string.IsNullOrWhiteSpace(wanted)) return 0.9; + if (authors.Count == 0) return 0.88; + var w = MediaNameParser.NormalizeForMatch(wanted); + var best = 0.0; + foreach (var a in authors) + { + var n = MediaNameParser.NormalizeForMatch(a); + var sim = LibraryMatcher.Similarity(w, n); + // "Sanderson" for "Brandon Sanderson", or the author inside a longer folder name + var tokens = n.Split(' ', StringSplitOptions.RemoveEmptyEntries); + var wanted_ = w.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (tokens.Length > 0 && tokens.Where(t => t.Length > 2).All(t => wanted_.Contains(t))) sim = Math.Max(sim, 0.95); + else if (tokens.Length > 1 && wanted_.Contains(tokens[^1]) && tokens[^1].Length > 3) sim = Math.Max(sim, 0.85); + best = Math.Max(best, sim); + } + if (best >= 0.85) return 1.0; + if (best >= 0.6) return 0.93; + // The parent folder may be a series rather than the author: a mismatch there means little + return explicitAuthor ? 0.72 : 0.88; + } + + /// + /// Fills what lacks from a candidate. With + /// the candidate also sets the identity and the main fields. + /// + public static void Apply(Audiobook book, BookCandidate c, bool primary) + { + if (primary) + { + book.Provider = c.Provider; + book.ProviderId = c.ProviderId; + book.Title = c.Title; + book.Subtitle = c.Subtitle; + if (c.Authors.Count > 0) book.Authors = c.Authors.ToList(); + } + book.ExternalIds[c.Provider] = c.ProviderId; + if (!string.IsNullOrWhiteSpace(c.Asin)) book.ExternalIds.TryAdd("asin", c.Asin); + if (!string.IsNullOrWhiteSpace(c.Isbn)) book.ExternalIds.TryAdd("isbn", c.Isbn); + if (book.Authors.Count == 0 && c.Authors.Count > 0) book.Authors = c.Authors.ToList(); + if (book.Narrators.Count == 0 && c.Narrators.Count > 0) book.Narrators = c.Narrators.ToList(); + if (book.Series.Count == 0 && c.Series.Count > 0) book.Series = c.Series.ToList(); + book.Subtitle ??= c.Subtitle; + book.Publisher ??= c.Publisher; + book.Year ??= c.Year; + book.Language ??= c.Language; + if (book.Genres.Count == 0 && c.Genres.Count > 0) book.Genres = c.Genres.ToList(); + book.Description ??= c.Description; + book.CoverUrl ??= c.CoverUrl; + book.Rating ??= c.Rating; + book.ProviderDurationMs ??= c.DurationMs; + } + + /// Back to what the names say: no provider data. + public static void Clear(Audiobook book) + { + book.Provider = null; + book.ProviderId = null; + book.ExternalIds = new Dictionary(); + book.Title = book.ParsedTitle; + book.Subtitle = null; + book.Authors = book.ParsedAuthor != null ? new List { book.ParsedAuthor } : new List(); + book.Narrators = book.ParsedNarrator != null ? new List { book.ParsedNarrator } : new List(); + book.Series = book.ParsedSeries != null ? new List { new() { Name = book.ParsedSeries, Sequence = book.ParsedSequence } } : new List(); + book.Publisher = null; + book.Year = book.ParsedYear; + book.Language = null; + book.Genres = new List(); + book.Description = null; + book.CoverUrl = null; + book.Rating = null; + book.ProviderDurationMs = null; + book.Confidence = 0; + book.SortTitle = MediaNameParser.SortTitle(book.Title); + } + } +} diff --git a/TelegramDownloader/Services/Audiobooks/AudiobookNames.cs b/TelegramDownloader/Services/Audiobooks/AudiobookNames.cs new file mode 100644 index 0000000..cc8ef6c --- /dev/null +++ b/TelegramDownloader/Services/Audiobooks/AudiobookNames.cs @@ -0,0 +1,267 @@ +using System.Text.RegularExpressions; +using TelegramDownloader.Services.Library; + +namespace TelegramDownloader.Services.Audiobooks +{ + /// What a folder or file name says about a book. + public class ParsedBook + { + public string Title { get; set; } = string.Empty; + public string? Author { get; set; } + public string? Narrator { get; set; } + public string? Series { get; set; } + public string? Sequence { get; set; } + public int? Year { get; set; } + /// The parent folder name, when it is not a generic one: often the author or the series. + public string? Context { get; set; } + + /// The text sent to the providers. + public string Query + { + get + { + var author = Author ?? Context; + return string.IsNullOrWhiteSpace(author) ? Title : $"{Title} {author}"; + } + } + } + + /// + /// Reads audiobook names: "Autor - Título", "Autor - Saga 03 - Título (Narrado por X)", + /// "01. Título"... Pure: no I/O. + /// + public static class AudiobookNames + { + /// Audio formats an audiobook can come in. + public static readonly IReadOnlySet AudioExtensions = new HashSet(StringComparer.OrdinalIgnoreCase) + { + ".mp3", ".m4b", ".m4a", ".aac", ".ogg", ".oga", ".opus", ".flac", ".wma", ".wav", ".mp2" + }; + + /// Formats that only audiobooks use: found anywhere, not only in audiobook folders. + public static readonly IReadOnlySet BookOnlyExtensions = new HashSet(StringComparer.OrdinalIgnoreCase) { ".m4b" }; + + /// Folder names that hold audiobooks. + private static readonly HashSet BookFolderNames = new(StringComparer.OrdinalIgnoreCase) + { + "audiolibros", "audiolibro", "audio libros", "audio libro", "audiobooks", "audiobook", "audio books", "audio book", + "audiolivros", "audiolivro", "livres audio", "livre audio", "audiolibri", "audiolibre", "audiollibres", + "horbucher", "horbuch", "hoerbuecher", "hoerbuch", "luisterboeken", "audiokniga", "audioknigi" + }; + + private static readonly Regex DiscFolder = new(@"^(cd|disc|disco|disk|parte|part|pt|tomo|vol|volumen|volume)[\s._-]*\d{1,3}$", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex PartSuffix = new(@"[\s._-]*[\(\[]?\s*(parte|part|pt|cd|disc|disco|disk|tomo)\.?\s*\d{1,3}\s*(de|of|/)?\s*\d{0,3}\s*[\)\]]?\s*$", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex Narrator = new(@"[\(\[]\s*(narrad[oa]|le[ií]d[oa]|narrador[a]?|voz|lectura|read|narrated|lu|gelesen)\s*(por|by|de|par|von|:)?\s*(?[^\)\]]+?)\s*[\)\]]", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex NarratorTail = new(@"\s+[-–]?\s*(narrad[oa] por|le[ií]d[oa] por|narrated by|read by)\s+(?.+)$", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex YearInBrackets = new(@"[\(\[]\s*(?(19|20)\d{2})\s*[\)\]]", RegexOptions.Compiled); + // [64kbps], (MP3), {Unabridged}, (Audiolibro), (Voz humana)... + private static readonly Regex Noise = new(@"[\(\[\{]\s*(\d{2,3}\s*k(bps)?|mp3|m4b|m4a|aac|flac|opus|unabridged|abridged|integral|completo|audiolibro|audiobook|audio\s*libro|voz\s*humana|castellano|espa[nñ]ol|spanish|latino|english|ingl[eé]s|libro\s*completo|\d+\s*cds?|vbr|cbr|\d+\s*hz)[^\)\]\}]*[\)\]\}]", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex Brackets = new(@"[\[\{][^\]\}]*[\]\}]", RegexOptions.Compiled); + private static readonly Regex LeadingNumber = new(@"^\s*(?\d{1,3}(\.\d)?)\s*[.\-_)–]\s*(?.+)$", RegexOptions.Compiled); + // "Saga 03", "Saga #3", "Saga, Libro 3", "Saga Book 3", "Saga Vol. 2" + private static readonly Regex SeriesWithNumber = new(@"^(?.+?)[\s,]*(#|n[º°o]\.?\s*|libro\s*|book\s*|vol\.?\s*|volumen\s*|tomo\s*|band\s*|livre\s*)?(?\d{1,3}(\.\d)?)$", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex DashSplit = new(@"\s+[-–—]\s+|\s*[-–—]{2,}\s*|_-_", RegexOptions.Compiled); + private static readonly Regex Spaces = new(@"\s+", RegexOptions.Compiled); + + public static bool IsAudio(string? extension) => + !string.IsNullOrEmpty(extension) && AudioExtensions.Contains(extension.StartsWith('.') ? extension : "." + extension); + + public static bool IsBookOnly(string? extension) => + !string.IsNullOrEmpty(extension) && BookOnlyExtensions.Contains(extension.StartsWith('.') ? extension : "." + extension); + + public static bool IsBookFolderName(string? name) => + !string.IsNullOrWhiteSpace(name) && BookFolderNames.Contains(MediaNameParser.NormalizeForMatch(name)); + + public static bool IsDiscFolder(string? name) => !string.IsNullOrWhiteSpace(name) && DiscFolder.IsMatch(name.Trim()); + + /// The deepest folder on the path named like an audiobook folder ("Audiolibros/"), or null. + public static string? BookRootFromPath(string? folderPath) + { + var segments = LibraryFolderRules.Normalize(folderPath).Split('/', StringSplitOptions.RemoveEmptyEntries); + for (int i = segments.Length - 1; i >= 0; i--) + if (IsBookFolderName(segments[i])) + return "/" + string.Join('/', segments.Take(i + 1)) + "/"; + return null; + } + + /// Last segment of a folder path ("/a/b/" → "b"), or null for the root. + public static string? FolderName(string? folderPath) => + LibraryFolderRules.Normalize(folderPath).Split('/', StringSplitOptions.RemoveEmptyEntries).LastOrDefault(); + + /// The parent folder path ("/a/b/" → "/a/"). + public static string Parent(string folderPath) + { + var segments = LibraryFolderRules.Normalize(folderPath).Split('/', StringSplitOptions.RemoveEmptyEntries); + return segments.Length <= 1 ? "/" : "/" + string.Join('/', segments.Take(segments.Length - 1)) + "/"; + } + + public static string StripExtension(string name) + { + var ext = Path.GetExtension(name); + return IsAudio(ext) || ext.Equals(".cue", StringComparison.OrdinalIgnoreCase) ? name[..^ext.Length] : name; + } + + /// A file name without its extension nor a "Parte 2" / "CD1" ending: files with the same key are parts of one book. + public static string PartKey(string fileName) + { + var name = PartSuffix.Replace(StripExtension(fileName), string.Empty); + return MediaNameParser.NormalizeForMatch(name); + } + + /// + /// Reads a book name. is the parent folder name + /// (an author or a series, often), left out when it is a generic one. + /// + public static ParsedBook Parse(string name, string? context = null) + { + var p = new ParsedBook(); + var s = StripExtension(name).Replace('_', ' '); + s = PartSuffix.Replace(s, string.Empty); + + var narrator = Narrator.Match(s); + if (narrator.Success) + { + p.Narrator = Clean(narrator.Groups["n"].Value); + s = s.Remove(narrator.Index, narrator.Length); + } + var year = YearInBrackets.Match(s); + if (year.Success) + { + p.Year = int.Parse(year.Groups["y"].Value); + s = s.Remove(year.Index, year.Length); + } + s = Noise.Replace(s, " "); + s = Brackets.Replace(s, " "); + s = s.Replace("()", " "); + var tail = NarratorTail.Match(s); + if (tail.Success && p.Narrator == null) + { + p.Narrator = Clean(tail.Groups["n"].Value); + s = s[..tail.Index]; + } + s = Spaces.Replace(s, " ").Trim(' ', '-', '.', ',', '–'); + + var parts = DashSplit.Split(s).Select(Clean).Where(x => x.Length > 0).ToList(); + if (parts.Count == 0) parts.Add(s); + + if (parts.Count == 1) + { + p.Title = parts[0]; + } + else if (parts.Count == 2) + { + // "Autor - Título" is the usual order; a number in the first part is a series or an order + if (SeriesWithNumber.Match(parts[0]) is { Success: true } sm && sm.Groups["s"].Value.Trim().Length > 0 && !LooksLikeYear(sm.Groups["n"].Value)) + { + p.Series = Clean(sm.Groups["s"].Value); + p.Sequence = sm.Groups["n"].Value; + p.Title = parts[1]; + } + else if (IsNumber(parts[0])) + { + p.Sequence = parts[0]; + p.Title = parts[1]; + } + else + { + p.Author = parts[0]; + p.Title = parts[1]; + } + } + else + { + p.Author = parts[0]; + p.Title = parts[^1]; + var middle = parts.Skip(1).Take(parts.Count - 2).ToList(); + // "Autor - Saga - 03 - Título" or "Autor - Saga 03 - Título" + if (middle.Count == 2 && IsNumber(middle[1])) + { + p.Series = middle[0]; + p.Sequence = middle[1]; + } + else if (middle.Count == 1 && SeriesWithNumber.Match(middle[0]) is { Success: true } m && m.Groups["s"].Value.Trim().Length > 0) + { + p.Series = Clean(m.Groups["s"].Value); + p.Sequence = m.Groups["n"].Value; + } + else if (middle.Count == 1 && IsNumber(middle[0])) + { + p.Sequence = middle[0]; + } + else + { + p.Series = string.Join(" ", middle); + } + } + + // "03. Título" or "03 - Título" inside a series folder + var lead = LeadingNumber.Match(p.Title); + if (lead.Success && p.Sequence == null) + { + p.Sequence = lead.Groups["n"].Value; + p.Title = Clean(lead.Groups["rest"].Value); + } + if (p.Year == null && Regex.Match(p.Title, @"\s(?(19|20)\d{2})$") is { Success: true } ty && p.Title.Length > 6) + { + p.Year = int.Parse(ty.Groups["y"].Value); + p.Title = p.Title[..ty.Index].Trim(); + } + p.Sequence = p.Sequence?.TrimStart('0') is { Length: > 0 } seq ? seq : p.Sequence; + + if (!string.IsNullOrWhiteSpace(context) && !IsBookFolderName(context) && !IsDiscFolder(context)) + { + var ctx = Parse(context); + p.Context = ctx.Title.Length > 0 ? (ctx.Author == null ? ctx.Title : $"{ctx.Author} {ctx.Title}") : null; + if (p.Sequence != null && p.Series == null && p.Context != null) + p.Series = ctx.Title; + } + return p; + } + + private static bool IsNumber(string s) => Regex.IsMatch(s.Trim(), @"^\d{1,3}(\.\d)?$"); + + private static bool LooksLikeYear(string s) => s.Length == 4; + + private static string Clean(string s) => Spaces.Replace(s, " ").Trim(' ', '-', '.', ',', '–', '_'); + + /// Numbers inside names compare as numbers: "2" before "10". + public static int NaturalCompare(string? a, string? b) + { + a ??= string.Empty; + b ??= string.Empty; + int i = 0, j = 0; + while (i < a.Length && j < b.Length) + { + if (char.IsDigit(a[i]) && char.IsDigit(b[j])) + { + int si = i, sj = j; + while (i < a.Length && char.IsDigit(a[i])) i++; + while (j < b.Length && char.IsDigit(b[j])) j++; + var na = a[si..i].TrimStart('0'); + var nb = b[sj..j].TrimStart('0'); + if (na.Length != nb.Length) return na.Length.CompareTo(nb.Length); + var c = string.CompareOrdinal(na, nb); + if (c != 0) return c; + } + else + { + var c = char.ToLowerInvariant(a[i]).CompareTo(char.ToLowerInvariant(b[j])); + if (c != 0) return c; + i++; + j++; + } + } + return (a.Length - i).CompareTo(b.Length - j); + } + + /// A readable chapter title from a track file name: "03 - La huida.mp3" → "La huida". + public static string ChapterTitleFromFile(string fileName, int index) + { + var s = StripExtension(fileName).Replace('_', ' '); + var lead = LeadingNumber.Match(s); + if (lead.Success) s = lead.Groups["rest"].Value; + s = Clean(s); + return s.Length == 0 || IsNumber(s) ? $"Capítulo {index + 1}" : s; + } + } +} diff --git a/TelegramDownloader/Services/Audiobooks/AudiobookScanService.cs b/TelegramDownloader/Services/Audiobooks/AudiobookScanService.cs new file mode 100644 index 0000000..8b797b7 --- /dev/null +++ b/TelegramDownloader/Services/Audiobooks/AudiobookScanService.cs @@ -0,0 +1,615 @@ +using System.Collections.Concurrent; +using TelegramDownloader.Data; +using TelegramDownloader.Data.db; +using TelegramDownloader.Models; +using TelegramDownloader.Models.Audiobooks; +using TelegramDownloader.Models.Library; +using TelegramDownloader.Services.Audio; +using TelegramDownloader.Services.Library; + +namespace TelegramDownloader.Services.Audiobooks +{ + /// + /// Finds the audiobooks of the channel indexes (see ), + /// reads what Telegram knows of their files (durations, titles, embedded chapters) + /// and identifies them with the enabled book providers. One scan at a time; + /// incremental unless forced; books identified by hand are never re-identified. + /// + public class AudiobookScanService : IHostedService + { + /// Books processed at the same time. + public const int BookParallelism = 3; + /// Files of a book whose embedded chapters are read; more files means one chapter per file. + public const int MaxFilesWithChapters = 12; + /// Most 512 KB blocks read from one file to find its chapters. + public const int ChapterReadBudget = 40; + private static readonly TimeSpan SaveStateInterval = TimeSpan.FromSeconds(2); + + private readonly ILibraryDbService _lib; + private readonly IAudiobookDbService _db; + private readonly IBookProviderSource _providers; + private readonly AudnexusClient _audnexus; + private readonly ITelegramService _telegram; + private readonly ILogger _logger; + private readonly object _sync = new(); + private readonly ConcurrentQueue _pending = new(); + private CancellationTokenSource? _cts; + + public AudiobookScanService(ILibraryDbService lib, IAudiobookDbService db, IBookProviderSource providers, AudnexusClient audnexus, + ITelegramService telegram, ILogger logger) + { + _lib = lib; + _db = db; + _providers = providers; + _audnexus = audnexus; + _telegram = telegram; + _logger = logger; + } + + public AudiobookScanState? Current { get; private set; } + public bool IsRunning => Current?.Running == true; + + #region Hosted service + + public async Task StartAsync(CancellationToken cancellationToken) + { + try + { + await _db.EnsureIndexes(); + var state = await _db.GetScanState(); + if (state is { Running: true }) + { + state.Running = false; + state.FinishedAt = DateTime.UtcNow; + state.Error ??= "Interrupted by a server restart"; + await _db.SaveScanState(state); + } + Current = state; + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Audiobook storage is not available yet"); + } + FileService.ChannelRefreshed += OnChannelRefreshed; + } + + public Task StopAsync(CancellationToken cancellationToken) + { + FileService.ChannelRefreshed -= OnChannelRefreshed; + Cancel(); + return Task.CompletedTask; + } + + private void OnChannelRefreshed(string channelId) + { + var config = GeneralConfigStatic.config; + if (!config.AudiobooksEnabled || !config.AudiobookAutoScan) return; + if (!LibraryScanService.IsChannelSelected(config, channelId)) return; + lock (_sync) + { + if (Start(channelId, false, out _)) return; + if (IsRunning && !_pending.Contains(channelId)) _pending.Enqueue(channelId); + } + } + + #endregion + + #region Start / cancel + + public bool Start(string? channelId, bool force, out string? error) + { + error = null; + lock (_sync) + { + if (IsRunning) + { + error = "An audiobook scan is already running"; + return false; + } + var state = new AudiobookScanState + { + Running = true, + StartedAt = DateTime.UtcNow, + Scope = string.IsNullOrWhiteSpace(channelId) ? "all" : channelId.Trim(), + Force = force + }; + Current = state; + _cts = new CancellationTokenSource(); + var ct = _cts.Token; + _ = Task.Run(() => RunAsync(state, ct), CancellationToken.None); + return true; + } + } + + public void Cancel() + { + lock (_sync) _cts?.Cancel(); + } + + public async Task GetStateAsync() => Current ?? await _db.GetScanState(); + + private async Task RunAsync(AudiobookScanState state, CancellationToken ct) + { + try + { + var config = GeneralConfigStatic.config; + var channels = state.Scope == "all" + ? LibraryScanService.SelectChannels(config, await _lib.GetChannelDatabaseNames()) + : new List { state.Scope }; + await ScanAsync(state, channels, ct); + } + catch (Exception ex) + { + _logger.LogError(ex, "Audiobook scan failed"); + state.Error ??= ex.Message; + state.Running = false; + state.FinishedAt = DateTime.UtcNow; + try { await _db.SaveScanState(state); } catch { } + } + finally + { + lock (_sync) + { + _cts?.Dispose(); + _cts = null; + } + if (_pending.TryDequeue(out var next)) + lock (_sync) Start(next, false, out _); + } + } + + #endregion + + #region Scan + + private sealed class Work + { + public required Audiobook Book { get; init; } + public required ParsedBook Parsed { get; init; } + public bool IsNew { get; init; } + public bool ReadDetails { get; init; } + public bool Identify { get; init; } + } + + private sealed class ScanRun + { + public required AudiobookScanState State { get; init; } + public object Gate { get; } = new(); + public ConcurrentDictionary Excluded { get; } = new(StringComparer.OrdinalIgnoreCase); + public DateTime LastSave { get; set; } = DateTime.UtcNow; + public void Update(Action change) + { + lock (Gate) change(State); + } + } + + public async Task ScanAsync(AudiobookScanState state, List channels, CancellationToken ct) + { + var run = new ScanRun { State = state }; + state.ChannelsTotal = channels.Count; + await _db.SaveScanState(state); + try + { + var work = new List(); + foreach (var channel in channels) + { + ct.ThrowIfCancellationRequested(); + run.Update(st => st.CurrentChannel = channel); + try + { + work.AddRange(await FindChangesAsync(channel, state.Force, run)); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogError(ex, "Audiobook scan of channel {Channel} failed", channel); + run.Update(st => st.Failed++); + } + run.Update(st => st.ChannelsScanned++); + } + run.Update(st => st.BooksToProcess = work.Count); + await Parallel.ForEachAsync(work, new ParallelOptions { MaxDegreeOfParallelism = BookParallelism, CancellationToken = ct }, async (item, token) => + { + try + { + await ProcessAsync(item, run, token); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogWarning(ex, "Could not process the audiobook '{Title}'", item.Book.ParsedTitle); + run.Update(st => st.Failed++); + } + run.Update(st => st.BooksProcessed++); + await SaveProgressAsync(run); + }); + if (!run.Excluded.IsEmpty) + state.Error = string.Join(" ", run.Excluded.Values); + } + catch (OperationCanceledException) + { + state.Cancelled = true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Audiobook scan failed"); + state.Error = ex.Message; + } + finally + { + state.Running = false; + state.CurrentChannel = null; + state.FinishedAt = DateTime.UtcNow; + await _db.SaveScanState(state); + _logger.LogInformation("Audiobook scan finished: {Found} books, {Matched} matched, {Review} to review, {Unmatched} unmatched, {Failed} failed", + state.BooksFound, state.Matched, state.Review, state.Unmatched, state.Failed); + } + } + + private async Task SaveProgressAsync(ScanRun run) + { + AudiobookScanState? copy = null; + lock (run.Gate) + { + if (DateTime.UtcNow - run.LastSave < SaveStateInterval) return; + run.LastSave = DateTime.UtcNow; + copy = run.State.Clone(); + } + try { await _db.SaveScanState(copy); } catch (Exception ex) { _logger.LogDebug(ex, "Could not save the audiobook scan progress"); } + } + + /// Groups the audio files of a channel in books, drops the books that are gone and returns what has to be read or identified. + private async Task> FindChangesAsync(string channelId, bool force, ScanRun run) + { + var result = new List(); + if (!long.TryParse(channelId, out var chId)) return result; + var config = GeneralConfigStatic.config; + var docs = (await _lib.GetChannelVideos(channelId, AudiobookNames.AudioExtensions)).Where(d => d.IsFile && AudiobookNames.IsAudio(d.Type)).ToList(); + var groups = AudiobookGrouper.Group(config, chId, docs); + var existing = (await _db.GetBooksByChannel(chId)).GroupBy(b => b.GroupKey, StringComparer.OrdinalIgnoreCase).ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase); + run.Update(st => st.BooksFound += groups.Count); + + var present = groups.Select(g => g.GroupKey).ToHashSet(StringComparer.OrdinalIgnoreCase); + var gone = existing.Values.Where(b => !present.Contains(b.GroupKey)).ToList(); + if (gone.Count > 0) + { + await _db.DeleteBooks(gone.Select(b => b.Id)); + foreach (var book in gone) await _db.DeleteProgress(book.Id); + run.Update(st => st.BooksRemoved += gone.Count); + } + + foreach (var group in groups) + { + existing.TryGetValue(group.GroupKey, out var old); + var book = old ?? new Audiobook { ChannelId = chId, GroupKey = group.GroupKey, CreatedAt = DateTime.UtcNow }; + var tracksChanged = SetTracks(book, group); + var parsed = AudiobookNames.Parse(group.Name, group.Context); + var nameChanged = book.ParsedTitle != parsed.Title || book.ParsedAuthor != (parsed.Author ?? parsed.Context); + book.FolderPath = group.FolderPath; + book.ParsedTitle = parsed.Title; + book.ParsedAuthor = parsed.Author ?? parsed.Context; + book.ParsedNarrator = parsed.Narrator; + book.ParsedSeries = parsed.Series; + book.ParsedSequence = parsed.Sequence; + book.ParsedYear = parsed.Year; + if (old == null) + AudiobookMatcher.Clear(book); + + var readDetails = old == null || tracksChanged || !book.DetailsRead || force; + var identify = !book.Locked && (old == null || force || nameChanged || book.Status == LibraryFileStatus.Unmatched); + if (!readDetails && !identify) + { + if (old != null && (tracksChanged || nameChanged)) await _db.UpsertBook(book); + continue; + } + result.Add(new Work { Book = book, Parsed = parsed, IsNew = old == null, ReadDetails = readDetails, Identify = identify }); + } + return result; + } + + /// Puts the files of the group as the tracks of the book, keeping what was read of them. True when they changed. + public static bool SetTracks(Audiobook book, BookGroup group) + { + var old = book.Tracks.ToDictionary(t => t.FileId); + var tracks = group.Files.Select(f => + { + old.TryGetValue(f.Id, out var known); + var same = known != null && known.Size == f.Size; + return new AudiobookTrack + { + FileId = f.Id, + MessageId = f.MessageId, + IsSplit = f.isSplit, + FileName = f.Name ?? string.Empty, + Type = f.Type ?? Path.GetExtension(f.Name ?? string.Empty), + FolderPath = LibraryFolderRules.Normalize(f.FilterPath), + Size = f.Size, + DurationMs = same ? known!.DurationMs : 0, + Title = same ? known!.Title : null, + HasCover = same && known!.HasCover + }; + }).ToList(); + var changed = tracks.Count != book.Tracks.Count + || tracks.Zip(book.Tracks).Any(p => p.First.FileId != p.Second.FileId || p.First.Size != p.Second.Size || p.First.FileName != p.Second.FileName); + book.Tracks = tracks; + book.Size = tracks.Sum(t => t.Size); + book.FileDate = group.Files.Count > 0 ? group.Files.Max(f => f.DateCreated) : book.FileDate; + book.DurationMs = tracks.Sum(t => t.DurationMs); + return changed; + } + + private async Task ProcessAsync(Work work, ScanRun run, CancellationToken ct) + { + var book = work.Book; + book.ScannedAt = DateTime.UtcNow; + if (work.ReadDetails) + await ReadDetailsAsync(book, ct); + + if (work.Identify) + { + book.Error = null; + try + { + await IdentifyAsync(book, work.Parsed, run, ct); + } + catch (ProviderException ex) + { + book.Error = ex.Message; + run.Update(st => st.Failed++); + } + } + + if (book.Asin != null && (book.ChapterSource == ChapterSource.None || (book.ChapterSource == ChapterSource.Files && book.Tracks.Count == 1))) + await TryAudnexusAsync(book, ct); + + if (book.Chapters.Count == 0 && book.DurationMs > 0) + book.Chapters = new List { new() { Title = book.Title, StartMs = 0, EndMs = book.DurationMs } }; + book.SortTitle = MediaNameParser.SortTitle(book.Title); + await _db.UpsertBook(book); + run.Update(st => + { + if (work.IsNew) st.BooksNew++; + if (!work.Identify) return; + if (book.Status == LibraryFileStatus.Matched) st.Matched++; + else if (book.Status == LibraryFileStatus.Review) st.Review++; + else if (book.Status == LibraryFileStatus.Unmatched) st.Unmatched++; + }); + } + + #endregion + + #region File details + + /// + /// Durations, titles and covers of the tracks from Telegram, and the chapters: + /// those stored in the files, else one per file. Nothing is downloaded but + /// the pieces of the files the chapters are in. + /// + public async Task ReadDetailsAsync(Audiobook book, CancellationToken ct) + { + if (!_telegram.checkUserLogin()) + { + // Without a session nothing can be read: the next scan tries again + book.DetailsRead = false; + book.Chapters = FileChapters(book); + book.ChapterSource = book.Tracks.Count > 1 ? ChapterSource.Files : ChapterSource.None; + return; + } + + var messages = new Dictionary(); + var ids = book.Tracks.Where(t => t.MessageId is > 0).Select(t => t.MessageId!.Value).Distinct().ToList(); + foreach (var chunk in ids.Chunk(100)) + { + try + { + foreach (var m in await _telegram.getMessagesById(book.ChannelId, chunk)) + messages[m.id] = m; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogDebug(ex, "Could not read the messages of '{Title}'", book.ParsedTitle); + } + } + + var embedded = new Dictionary>(); + var readChapters = book.Tracks.Count <= MaxFilesWithChapters; + foreach (var track in book.Tracks) + { + ct.ThrowIfCancellationRequested(); + if (track.MessageId is not int id || !messages.TryGetValue(id, out var message)) continue; + var attributes = AudioAttributes.From(message); + if (attributes.Duration is int seconds && !track.IsSplit) track.DurationMs = seconds * 1000L; + track.Title = attributes.Title; + track.HasCover = attributes.HasCover; + + if (!readChapters || track.IsSplit || !ChapterReader.CanRead(track.Type)) continue; + try + { + var reader = new RangeReader(track.Size, (offset, count, token) => _telegram.DownloadFileStream(message, offset, count)) { Budget = ChapterReadBudget }; + var found = await ChapterReader.ReadAsync(reader, track.Type, ct); + if (found == null) continue; + if (track.DurationMs <= 0 && found.DurationMs > 0) track.DurationMs = found.DurationMs; + if (found.Chapters.Count > 0) embedded[track.FileId] = found.Chapters; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogDebug(ex, "Could not read the chapters of {File}", track.FileName); + } + } + + book.DurationMs = book.Tracks.Sum(t => t.DurationMs); + var useful = embedded.Values.Any(c => c.Count > 1) || (embedded.Count > 0 && book.Tracks.Count > 1); + if (useful) + { + book.Chapters = Combine(book, embedded); + book.ChapterSource = ChapterSource.Embedded; + } + else + { + book.Chapters = FileChapters(book); + book.ChapterSource = book.Tracks.Count > 1 ? ChapterSource.Files : ChapterSource.None; + } + book.DetailsRead = true; + } + + /// One chapter per file, on the book timeline. + public static List FileChapters(Audiobook book) + { + if (book.Tracks.Count <= 1) return new List(); + var result = new List(); + long start = 0; + for (int i = 0; i < book.Tracks.Count; i++) + { + var t = book.Tracks[i]; + var title = !string.IsNullOrWhiteSpace(t.Title) && !book.Tracks.All(x => x.Title == t.Title) ? t.Title! : AudiobookNames.ChapterTitleFromFile(t.FileName, i); + result.Add(new AudiobookChapter { Title = title, StartMs = start, EndMs = start + t.DurationMs }); + start += t.DurationMs; + } + return result; + } + + /// The chapters of every file one after the other; a file without chapters is one chapter. + public static List Combine(Audiobook book, IReadOnlyDictionary> embedded) + { + var result = new List(); + long offset = 0; + for (int i = 0; i < book.Tracks.Count; i++) + { + var t = book.Tracks[i]; + if (embedded.TryGetValue(t.FileId, out var chapters) && chapters.Count > 0) + { + foreach (var c in chapters) + result.Add(new AudiobookChapter { Title = c.Title, StartMs = offset + c.StartMs, EndMs = offset + Math.Max(c.EndMs, c.StartMs) }); + } + else + { + result.Add(new AudiobookChapter { Title = AudiobookNames.ChapterTitleFromFile(t.FileName, i), StartMs = offset, EndMs = offset + t.DurationMs }); + } + offset += t.DurationMs; + } + return result; + } + + /// The Audible edition chapters, when its runtime is the one of the files. + private async Task TryAudnexusAsync(Audiobook book, CancellationToken ct) + { + try + { + var found = await _audnexus.GetChaptersAsync(book.Asin!, AudibleProvider.NormalizeRegion(GeneralConfigStatic.config.AudibleRegion), ct); + if (found == null || found.Value.Chapters.Count < 2) return; + var runtime = found.Value.RuntimeMs; + if (book.DurationMs <= 0 || Math.Abs(runtime - book.DurationMs) > Math.Max(60_000, book.DurationMs * 0.02)) return; + book.Chapters = found.Value.Chapters; + ChapterReader.Close(book.Chapters, book.DurationMs); + book.ChapterSource = ChapterSource.Audnexus; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogDebug(ex, "Audnexus has no chapters for {Asin}", book.Asin); + } + } + + #endregion + + #region Identification + + private static bool IsRefusal(Exception ex) => ex is ProviderException { StatusCode: 401 or 403 or 429 }; + + /// Asks every enabled provider; the best match sets the book, the other good ones fill its gaps. + private async Task IdentifyAsync(Audiobook book, ParsedBook parsed, ScanRun run, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(parsed.Title)) + { + book.Status = LibraryFileStatus.Unmatched; + return; + } + var matches = new List<(IBookProvider Provider, BookMatch Match)>(); + foreach (var provider in _providers.GetEnabled()) + { + if (run.Excluded.ContainsKey(provider.Id)) continue; + try + { + var match = await FindAsync(provider, parsed, ct); + if (match != null) matches.Add((provider, match)); + } + catch (ProviderException ex) when (IsRefusal(ex) || ex.StatusCode == null) + { + // A provider that refuses or is down is left out of the rest of the scan + if (run.Excluded.TryAdd(provider.Id, $"{ex.Message}. The scan went on without {provider.Descriptor.Name}.")) + _logger.LogWarning("Audiobook scan: {Provider} is left out: {Error}", provider.Id, ex.Message); + } + } + await ApplyMatchesAsync(book, matches, ct); + } + + public static async Task FindAsync(IBookProvider provider, ParsedBook parsed, CancellationToken ct) + { + var author = parsed.Author ?? parsed.Context; + var candidates = await provider.SearchAsync(parsed.Title, author, ct); + var best = AudiobookMatcher.Best(parsed, candidates); + if ((best == null || best.Score < LibraryMatcher.MatchedThreshold) && author != null) + { + // The folder above may be a series and not the author, or the parts may go the other way round + var loose = AudiobookMatcher.Best(parsed, await provider.SearchAsync(parsed.Title, null, ct)); + if (loose != null && (best == null || loose.Score > best.Score)) best = loose; + if (parsed.Author != null && (best == null || best.Score < LibraryMatcher.MatchedThreshold)) + { + var swapped = AudiobookMatcher.Best(parsed, await provider.SearchAsync(parsed.Author, parsed.Title, ct)); + if (swapped != null && (best == null || swapped.Score > best.Score)) best = swapped; + } + } + return best; + } + + /// Sets the book from the matches found, or back to its names when none is good enough. + public async Task ApplyMatchesAsync(Audiobook book, List<(IBookProvider Provider, BookMatch Match)> matches, CancellationToken ct) + { + var best = matches.OrderByDescending(m => m.Match.Score).FirstOrDefault(); + AudiobookMatcher.Clear(book); + if (best.Match == null || best.Match.Score < LibraryMatcher.ReviewThreshold) + { + book.Status = LibraryFileStatus.Unmatched; + book.MatchSource = LibraryMatchSource.Auto; + return; + } + var primary = await DetailedAsync(best.Provider, best.Match.Candidate, ct); + AudiobookMatcher.Apply(book, primary, true); + foreach (var (provider, match) in matches.Where(m => m.Provider != best.Provider && m.Match.Score >= 0.75).OrderByDescending(m => m.Match.Score)) + AudiobookMatcher.Apply(book, match.Candidate, false); + if (book.Description == null) + foreach (var (provider, match) in matches.Where(m => m.Provider != best.Provider && m.Match.Score >= 0.75)) + { + var detailed = await DetailedAsync(provider, match.Candidate, ct); + AudiobookMatcher.Apply(book, detailed, false); + if (book.Description != null) break; + } + if (book.Narrators.Count == 0 && book.ParsedNarrator != null) book.Narrators.Add(book.ParsedNarrator); + if (book.Series.Count == 0 && book.ParsedSeries != null) + book.Series.Add(new AudiobookSeriesRef { Name = book.ParsedSeries, Sequence = book.ParsedSequence }); + book.Status = best.Match.Status; + book.Confidence = best.Match.Score; + book.MatchSource = LibraryMatchSource.Auto; + book.MetadataFetchedAt = DateTime.UtcNow; + } + + /// The candidate with the details only its own page has (Open Library descriptions). + public async Task DetailedAsync(IBookProvider provider, BookCandidate candidate, CancellationToken ct) + { + if (candidate.Description != null) return candidate; + try + { + var full = await provider.GetAsync(candidate.ProviderId, ct); + if (full == null) return candidate; + full.Description ??= candidate.Description; + full.CoverUrl ??= candidate.CoverUrl; + if (full.Authors.Count == 0) full.Authors = candidate.Authors; + return full; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogDebug(ex, "{Provider} has no details for {Id}", provider.Id, candidate.ProviderId); + return candidate; + } + } + + #endregion + } +} diff --git a/TelegramDownloader/Services/Audiobooks/AudiobookService.cs b/TelegramDownloader/Services/Audiobooks/AudiobookService.cs new file mode 100644 index 0000000..d764d75 --- /dev/null +++ b/TelegramDownloader/Services/Audiobooks/AudiobookService.cs @@ -0,0 +1,499 @@ +using TelegramDownloader.Data.db; +using TelegramDownloader.Models; +using TelegramDownloader.Models.Api; +using TelegramDownloader.Models.Audiobooks; +using TelegramDownloader.Models.Library; +using TelegramDownloader.Services.Api; +using TelegramDownloader.Services.Library; + +namespace TelegramDownloader.Services.Audiobooks +{ + /// The audiobook catalogue, listening progress, bookmarks and manual identification. + public class AudiobookService + { + /// Closer than this to the end counts as finished. + public const long FinishedMarginMs = 30_000; + + /// Formats browsers do not play: their tracks are served transcoded. + private static readonly HashSet TranscodedTypes = new(StringComparer.OrdinalIgnoreCase) { ".wma", ".amr", ".ra", ".aiff", ".alac", ".mp2" }; + + private readonly IAudiobookDbService _db; + private readonly IBookProviderSource _providers; + private readonly AudiobookScanService _scan; + + public AudiobookService(IAudiobookDbService db, IBookProviderSource providers, AudiobookScanService scan) + { + _db = db; + _providers = providers; + _scan = scan; + } + + private static GeneralConfig Config => GeneralConfigStatic.config; + + private static List HiddenChannels(bool includeHidden) => + includeHidden || Config.ShowHiddenChannels ? new List() : Config.HiddenChannels ?? new List(); + + #region Catalogue + + /// Default: every book but the ignored ones. Else identified (matched or review), matched, review, unmatched, ignored, all. + /// inProgress, finished, notStarted. + public async Task> ListAsync(string? search, string? author, string? series, string? narrator, string? status, string? progress, + bool includeHidden, string? sortBy, bool sortDescending, string baseUrl) + { + var books = await VisibleAsync(includeHidden, status); + var progressById = (await _db.GetAllProgress()).ToDictionary(p => p.Id); + if (!string.IsNullOrWhiteSpace(author)) + books = books.Where(b => b.Authors.Any(a => Same(a, author))).ToList(); + if (!string.IsNullOrWhiteSpace(narrator)) + books = books.Where(b => b.Narrators.Any(a => Same(a, narrator))).ToList(); + if (!string.IsNullOrWhiteSpace(series)) + books = books.Where(b => b.Series.Any(s => Same(s.Name, series))).ToList(); + if (!string.IsNullOrWhiteSpace(search)) + { + var q = MediaNameParser.NormalizeForMatch(search); + books = books.Where(b => MediaNameParser.NormalizeForMatch(string.Join(' ', new[] { b.Title, b.Subtitle, b.ParsedTitle } + .Concat(b.Authors).Concat(b.Narrators).Concat(b.Series.Select(s => s.Name)))).Contains(q)).ToList(); + } + if (!string.IsNullOrWhiteSpace(progress)) + { + books = progress.Trim().ToLowerInvariant() switch + { + "inprogress" => books.Where(b => progressById.TryGetValue(b.Id, out var p) && !p.Finished && p.PositionMs > 0).ToList(), + "finished" => books.Where(b => progressById.TryGetValue(b.Id, out var p) && p.Finished).ToList(), + "notstarted" => books.Where(b => !progressById.TryGetValue(b.Id, out var p) || (!p.Finished && p.PositionMs == 0)).ToList(), + _ => books + }; + } + + IEnumerable sorted = (sortBy ?? "title").Trim().ToLowerInvariant() switch + { + "author" => books.OrderBy(b => b.PrimaryAuthor ?? "~", StringComparer.OrdinalIgnoreCase).ThenBy(b => SeriesKey(b)).ThenBy(b => b.SortTitle), + "added" => books.OrderByDescending(b => b.CreatedAt), + "duration" => books.OrderBy(b => b.DurationMs), + "year" => books.OrderBy(b => b.Year ?? 0), + "series" => books.OrderBy(b => SeriesKey(b)), + "lastplayed" => books.OrderByDescending(b => progressById.TryGetValue(b.Id, out var p) ? p.LastPlayedAt : DateTime.MinValue), + _ => books.OrderBy(b => b.SortTitle, StringComparer.OrdinalIgnoreCase) + }; + var list = sorted.ToList(); + // "added" and "lastPlayed" are newest first already: descending turns them round + if (sortDescending) list.Reverse(); + return list.Select(b => ToDto(b, progressById.GetValueOrDefault(b.Id), baseUrl)).ToList(); + } + + private static string SeriesKey(Audiobook b) + { + var s = b.Series.FirstOrDefault(); + if (s == null) return "~" + b.SortTitle; + var seq = double.TryParse(s.Sequence, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var n) ? n : 9999; + return $"{s.Name.ToLowerInvariant()}|{seq:00000.00}"; + } + + private static bool Same(string a, string b) => + MediaNameParser.NormalizeForMatch(a) == MediaNameParser.NormalizeForMatch(b); + + private async Task> VisibleAsync(bool includeHidden, string? status = null) + { + var hidden = HiddenChannels(includeHidden); + var books = (await _db.GetAllBooks()).Where(b => !hidden.Contains(b.ChannelId)); + var wanted = string.IsNullOrWhiteSpace(status) ? "active" : status.Trim().ToLowerInvariant(); + return books.Where(b => wanted switch + { + "all" => true, + "active" => b.Status != LibraryFileStatus.Ignored, + "identified" => b.Status is LibraryFileStatus.Matched or LibraryFileStatus.Review, + _ => b.Status == wanted + }).ToList(); + } + + public async Task> ContinueAsync(int limit, bool includeHidden, string baseUrl) + { + var progress = (await _db.GetAllProgress()).Where(p => !p.Finished && p.PositionMs > 0).OrderByDescending(p => p.LastPlayedAt).Take(limit * 2).ToList(); + var books = (await _db.GetBooks(progress.Select(p => p.Id))).ToDictionary(b => b.Id); + var hidden = HiddenChannels(includeHidden); + return progress.Where(p => books.TryGetValue(p.Id, out var b) && !hidden.Contains(b.ChannelId) && b.Status != LibraryFileStatus.Ignored) + .Take(limit).Select(p => ToDto(books[p.Id], p, baseUrl)).ToList(); + } + + public async Task> RecentAsync(int limit, bool includeHidden, string baseUrl) + { + var books = (await VisibleAsync(includeHidden)).OrderByDescending(b => b.CreatedAt).Take(limit).ToList(); + var progress = (await _db.GetAllProgress()).ToDictionary(p => p.Id); + return books.Select(b => ToDto(b, progress.GetValueOrDefault(b.Id), baseUrl)).ToList(); + } + + public async Task> AuthorsAsync(bool includeHidden, string baseUrl) + { + var books = await VisibleAsync(includeHidden); + return books.SelectMany(b => b.Authors.Select(a => (Author: a.Trim(), Book: b))) + .GroupBy(x => MediaNameParser.NormalizeForMatch(x.Author)) + .Where(g => g.Key.Length > 0) + .Select(g => new ApiAudiobookGroupDto + { + Name = g.GroupBy(x => x.Author).OrderByDescending(n => n.Count()).First().Key, + Count = g.Select(x => x.Book.Id).Distinct().Count(), + CoverUrl = g.Select(x => CoverOf(x.Book, baseUrl)).FirstOrDefault(c => c != null), + BookIds = g.Select(x => x.Book).OrderBy(SeriesKey).Select(b => b.Id).Distinct().ToList() + }) + .OrderBy(a => a.Name, StringComparer.OrdinalIgnoreCase).ToList(); + } + + public async Task> SeriesAsync(bool includeHidden, string baseUrl) + { + var books = await VisibleAsync(includeHidden); + return books.SelectMany(b => b.Series.Select(s => (Series: s, Book: b))) + .GroupBy(x => MediaNameParser.NormalizeForMatch(x.Series.Name)) + .Where(g => g.Key.Length > 0) + .Select(g => + { + var ordered = g.OrderBy(x => double.TryParse(x.Series.Sequence, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var n) ? n : 9999) + .ThenBy(x => x.Book.SortTitle).Select(x => x.Book).ToList(); + return new ApiAudiobookGroupDto + { + Name = g.GroupBy(x => x.Series.Name).OrderByDescending(n => n.Count()).First().Key, + Count = ordered.Select(b => b.Id).Distinct().Count(), + CoverUrl = ordered.Select(b => CoverOf(b, baseUrl)).FirstOrDefault(c => c != null), + BookIds = ordered.Select(b => b.Id).Distinct().ToList() + }; + }) + .OrderBy(s => s.Name, StringComparer.OrdinalIgnoreCase).ToList(); + } + + public async Task GetAsync(string id, string baseUrl) + { + var book = await _db.GetBook(id); + if (book == null) return null; + return ToDetail(book, await _db.GetProgress(id), baseUrl); + } + + #endregion + + #region DTOs + + public static string? CoverOf(Audiobook book, string baseUrl) + { + if (!string.IsNullOrWhiteSpace(book.CoverUrl) && LibraryImageService.IsAllowed(book.CoverUrl)) + return LibraryImageService.ProxyUrl(baseUrl, book.CoverUrl, "original"); + var withCover = book.Tracks.FirstOrDefault(t => t.HasCover && t.MessageId.HasValue && !t.IsSplit); + return withCover == null ? null : MediaUrlBuilder.Thumbnail(baseUrl, book.ChannelId.ToString(), withCover.MessageId!.Value); + } + + private static T Fill(T dto, Audiobook b, AudiobookProgress? p, string baseUrl) where T : ApiAudiobookDto + { + dto.Id = b.Id; + dto.Title = string.IsNullOrWhiteSpace(b.Title) ? b.ParsedTitle : b.Title; + dto.Subtitle = b.Subtitle; + dto.Authors = b.Authors.Count > 0 ? b.Authors : b.ParsedAuthor != null ? new List { b.ParsedAuthor } : new List(); + dto.Narrators = b.Narrators; + dto.Series = b.Series; + dto.Year = b.Year; + dto.Language = b.Language; + dto.CoverUrl = CoverOf(b, baseUrl); + dto.DurationMs = b.DurationMs; + dto.Size = b.Size; + dto.TrackCount = b.Tracks.Count; + dto.ChapterCount = b.Chapters.Count; + dto.Status = b.Status; + dto.Confidence = Math.Round(b.Confidence, 3); + dto.Locked = b.Locked; + dto.Provider = b.Provider; + dto.ChannelId = b.ChannelId; + dto.FolderPath = b.FolderPath; + dto.CreatedAt = b.CreatedAt; + dto.Progress = ApiAudiobookProgressDto.From(p); + return dto; + } + + public static ApiAudiobookDto ToDto(Audiobook b, AudiobookProgress? p, string baseUrl) => Fill(new ApiAudiobookDto(), b, p, baseUrl); + + public static ApiAudiobookDetailDto ToDetail(Audiobook b, AudiobookProgress? p, string baseUrl) + { + var dto = Fill(new ApiAudiobookDetailDto(), b, p, baseUrl); + dto.Description = b.Description; + dto.Publisher = b.Publisher; + dto.Genres = b.Genres; + dto.Rating = b.Rating; + dto.ProviderId = b.ProviderId; + dto.ExternalIds = b.ExternalIds; + dto.MatchSource = b.MatchSource; + dto.ChapterSource = b.ChapterSource; + dto.Error = b.Error; + dto.Parsed = new ApiAudiobookParsedDto + { + Title = b.ParsedTitle, + Author = b.ParsedAuthor, + Narrator = b.ParsedNarrator, + Series = b.ParsedSeries, + Sequence = b.ParsedSequence, + Year = b.ParsedYear + }; + var channel = b.ChannelId.ToString(); + long start = 0; + dto.Tracks = b.Tracks.Select((t, i) => + { + var content = MediaUrlBuilder.Content(baseUrl, channel, t.FileId); + var track = new ApiAudiobookTrackDto + { + Index = i, + FileId = t.FileId, + FileName = t.FileName, + Title = t.Title, + Size = t.Size, + DurationMs = t.DurationMs, + StartMs = start, + IsSplit = t.IsSplit, + MessageId = t.MessageId, + ContentUrl = content, + PlaybackUrl = TranscodedTypes.Contains(t.Type) && !t.IsSplit + ? $"{baseUrl}/api/v1/channels/{Uri.EscapeDataString(channel)}/files/{Uri.EscapeDataString(t.FileId)}/transcoded?format=mp3&bitrate=96" + : content + }; + start += t.DurationMs; + return track; + }).ToList(); + dto.Chapters = b.Chapters.Select((c, i) => new ApiAudiobookChapterDto { Index = i, Title = c.Title, StartMs = c.StartMs, EndMs = c.EndMs }).ToList(); + dto.Bookmarks = (p?.Bookmarks ?? new List()).OrderBy(x => x.PositionMs) + .Select(x => new ApiAudiobookBookmarkDto { Id = x.Id, PositionMs = x.PositionMs, Note = x.Note, CreatedAt = x.CreatedAt }).ToList(); + return dto; + } + + public static ApiBookCandidateDto ToCandidate(BookCandidate c, string baseUrl, double? score = null) => new() + { + Provider = c.Provider, + ProviderName = BookProviderRegistry.Describe(c.Provider)?.Name ?? c.Provider, + ProviderId = c.ProviderId, + Title = c.Title, + Subtitle = c.Subtitle, + Authors = c.Authors, + Narrators = c.Narrators, + Series = c.Series, + Year = c.Year, + Language = c.Language, + CoverUrl = c.CoverUrl != null && LibraryImageService.IsAllowed(c.CoverUrl) ? LibraryImageService.ProxyUrl(baseUrl, c.CoverUrl, "original") : null, + DurationMs = c.DurationMs, + Link = c.Link, + Score = score == null ? null : Math.Round(score.Value, 3) + }; + + #endregion + + #region Progress and bookmarks + + public async Task SetProgressAsync(string id, AudiobookProgressRequest request) + { + var book = await _db.GetBook(id); + if (book == null) return null; + var p = await _db.GetProgress(id) ?? new AudiobookProgress { Id = id, StartedAt = DateTime.UtcNow }; + var duration = request.DurationMs is > 0 ? request.DurationMs.Value : book.DurationMs > 0 ? book.DurationMs : p.DurationMs; + p.DurationMs = duration; + p.PositionMs = Math.Max(0, duration > 0 ? Math.Min(request.PositionMs, duration) : request.PositionMs); + var finished = request.Finished ?? (duration > 0 && duration - p.PositionMs <= FinishedMarginMs); + if (finished && !p.Finished) p.FinishedAt = DateTime.UtcNow; + // Listening again from the start keeps the book finished until the client says otherwise + if (!finished && p.Finished && request.Finished == null && p.PositionMs < 60_000) finished = true; + p.Finished = finished; + if (!finished) p.FinishedAt = null; + if (request.Speed is > 0) p.Speed = Math.Clamp(request.Speed.Value, 0.5, 3.5); + p.LastPlayedAt = DateTime.UtcNow; + await _db.UpsertProgress(p); + return p; + } + + public async Task SetFinishedAsync(string id, bool finished) + { + var book = await _db.GetBook(id); + if (book == null) return null; + var p = await _db.GetProgress(id) ?? new AudiobookProgress { Id = id, StartedAt = DateTime.UtcNow }; + p.DurationMs = book.DurationMs > 0 ? book.DurationMs : p.DurationMs; + p.Finished = finished; + p.FinishedAt = finished ? DateTime.UtcNow : null; + p.PositionMs = finished ? p.DurationMs : 0; + p.LastPlayedAt = DateTime.UtcNow; + await _db.UpsertProgress(p); + return p; + } + + /// Forgets the position (bookmarks stay). + public async Task ResetProgressAsync(string id) + { + var p = await _db.GetProgress(id); + if (p == null) return await _db.GetBook(id) != null; + p.PositionMs = 0; + p.Finished = false; + p.FinishedAt = null; + await _db.UpsertProgress(p); + return true; + } + + public async Task AddBookmarkAsync(string id, AudiobookBookmarkRequest request) + { + var book = await _db.GetBook(id); + if (book == null) return null; + var p = await _db.GetProgress(id) ?? new AudiobookProgress { Id = id, DurationMs = book.DurationMs, StartedAt = DateTime.UtcNow, LastPlayedAt = DateTime.UtcNow }; + var bookmark = new AudiobookBookmark { PositionMs = Math.Max(0, request.PositionMs), Note = Blank(request.Note) }; + p.Bookmarks.Add(bookmark); + await _db.UpsertProgress(p); + return bookmark; + } + + public async Task UpdateBookmarkAsync(string id, string bookmarkId, string? note) + { + var p = await _db.GetProgress(id); + var bookmark = p?.Bookmarks.FirstOrDefault(b => b.Id == bookmarkId); + if (bookmark == null) return null; + bookmark.Note = Blank(note); + await _db.UpsertProgress(p!); + return bookmark; + } + + public async Task DeleteBookmarkAsync(string id, string bookmarkId) + { + var p = await _db.GetProgress(id); + if (p == null || p.Bookmarks.RemoveAll(b => b.Id == bookmarkId) == 0) return false; + await _db.UpsertProgress(p); + return true; + } + + private static string? Blank(string? s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim()[..Math.Min(s.Trim().Length, 500)]; + + #endregion + + #region Identification + + /// Searches the enabled providers. With a book, candidates are scored against its names. + public async Task> SearchAsync(string? query, string? author, string? provider, string? bookId, string baseUrl, CancellationToken ct) + { + Audiobook? book = bookId == null ? null : await _db.GetBook(bookId); + var title = string.IsNullOrWhiteSpace(query) ? book?.ParsedTitle : query.Trim(); + if (string.IsNullOrWhiteSpace(title)) return new List(); + author = string.IsNullOrWhiteSpace(author) ? (string.IsNullOrWhiteSpace(query) ? book?.ParsedAuthor : null) : author.Trim(); + var parsed = new ParsedBook { Title = title, Author = author }; + + var providers = _providers.GetEnabled().Where(p => provider == null || p.Id.Equals(provider, StringComparison.OrdinalIgnoreCase)).ToList(); + var tasks = providers.Select(async p => + { + try + { + var found = (await p.SearchAsync(title, author, ct)).ToList(); + if (found.Count == 0 && author != null) found = (await p.SearchAsync(title, null, ct)).ToList(); + return found; + } + catch (ProviderException) + { + return new List(); + } + }).ToList(); + var results = await Task.WhenAll(tasks); + return results.SelectMany(r => r.Take(10)) + .Select(c => (Candidate: c, Score: AudiobookMatcher.Score(parsed, c))) + .OrderByDescending(x => x.Score) + .Select(x => ToCandidate(x.Candidate, baseUrl, x.Score)) + .ToList(); + } + + /// Sets the book to a provider entry chosen by hand; scans never change it again. + public async Task IdentifyAsync(string id, string providerId, string itemId, CancellationToken ct) + { + var book = await _db.GetBook(id); + if (book == null) return null; + var provider = _providers.Get(providerId) ?? throw new ProviderException($"Provider '{providerId}' is not enabled"); + var candidate = await provider.GetAsync(itemId, ct) ?? throw new ProviderException($"{provider.Descriptor.Name} has no book with id {itemId}"); + AudiobookMatcher.Clear(book); + AudiobookMatcher.Apply(book, candidate, true); + if (book.Narrators.Count == 0 && book.ParsedNarrator != null) book.Narrators.Add(book.ParsedNarrator); + book.Status = LibraryFileStatus.Matched; + book.Confidence = 1; + book.MatchSource = LibraryMatchSource.Manual; + book.Locked = true; + book.Error = null; + book.MetadataFetchedAt = DateTime.UtcNow; + book.SortTitle = MediaNameParser.SortTitle(book.Title); + await _db.UpsertBook(book); + return book; + } + + /// Back to the names and to automatic identification on the next scan. + public async Task UnidentifyAsync(string id) + { + var book = await _db.GetBook(id); + if (book == null) return null; + AudiobookMatcher.Clear(book); + book.Status = LibraryFileStatus.Unmatched; + book.MatchSource = LibraryMatchSource.Auto; + book.Locked = false; + await _db.UpsertBook(book); + return book; + } + + public async Task SetIgnoredAsync(string id, bool ignored) + { + var book = await _db.GetBook(id); + if (book == null) return null; + if (ignored) + { + book.Status = LibraryFileStatus.Ignored; + book.Locked = true; + book.MatchSource = LibraryMatchSource.Manual; + } + else + { + book.Locked = false; + book.MatchSource = LibraryMatchSource.Auto; + book.Status = book.Provider != null ? LibraryFileStatus.Review : LibraryFileStatus.Unmatched; + } + await _db.UpsertBook(book); + return book; + } + + /// + /// Reads the files again (durations, chapters) and the metadata: from the same + /// provider entry when the book is identified, else with a new search. + /// + public async Task RefreshAsync(string id, CancellationToken ct) + { + var book = await _db.GetBook(id); + if (book == null) return null; + await _scan.ReadDetailsAsync(book, ct); + if (book.Status == LibraryFileStatus.Ignored) + { + // Nothing to identify + } + else if (book.Provider != null && book.ProviderId != null && _providers.Get(book.Provider) is { } provider) + { + var candidate = await provider.GetAsync(book.ProviderId, ct); + if (candidate != null) + { + var (status, confidence, source, locked) = (book.Status, book.Confidence, book.MatchSource, book.Locked); + AudiobookMatcher.Clear(book); + AudiobookMatcher.Apply(book, candidate, true); + (book.Status, book.Confidence, book.MatchSource, book.Locked) = (status, confidence, source, locked); + book.MetadataFetchedAt = DateTime.UtcNow; + } + } + else if (!book.Locked) + { + var parsed = new ParsedBook { Title = book.ParsedTitle, Author = book.ParsedAuthor, Narrator = book.ParsedNarrator, Series = book.ParsedSeries, Sequence = book.ParsedSequence, Year = book.ParsedYear }; + var matches = new List<(IBookProvider, BookMatch)>(); + foreach (var p in _providers.GetEnabled()) + { + try + { + if (await AudiobookScanService.FindAsync(p, parsed, ct) is { } m) matches.Add((p, m)); + } + catch (ProviderException) + { + // The others may know it + } + } + await _scan.ApplyMatchesAsync(book, matches, ct); + } + if (book.Chapters.Count == 0 && book.DurationMs > 0) + book.Chapters = new List { new() { Title = book.Title, StartMs = 0, EndMs = book.DurationMs } }; + book.SortTitle = MediaNameParser.SortTitle(book.Title); + await _db.UpsertBook(book); + return book; + } + + #endregion + } +} diff --git a/TelegramDownloader/Services/Audiobooks/BookProviders.cs b/TelegramDownloader/Services/Audiobooks/BookProviders.cs new file mode 100644 index 0000000..99e0572 --- /dev/null +++ b/TelegramDownloader/Services/Audiobooks/BookProviders.cs @@ -0,0 +1,610 @@ +using System.Collections.Concurrent; +using System.Text.Json; +using System.Text.RegularExpressions; +using TelegramDownloader.Data.db; +using TelegramDownloader.Models; +using TelegramDownloader.Models.Audiobooks; +using TelegramDownloader.Services.Library; + +namespace TelegramDownloader.Services.Audiobooks +{ + /// A book at a metadata provider, with everything the search gave. + public class BookCandidate + { + public string Provider { get; set; } = string.Empty; + public string ProviderId { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public string? Subtitle { get; set; } + public List Authors { get; set; } = new(); + public List Narrators { get; set; } = new(); + public List Series { get; set; } = new(); + public string? Publisher { get; set; } + public int? Year { get; set; } + public string? Language { get; set; } + public List Genres { get; set; } = new(); + public string? Description { get; set; } + public string? CoverUrl { get; set; } + public double? Rating { get; set; } + public long? DurationMs { get; set; } + public string? Isbn { get; set; } + public string? Asin { get; set; } + /// A page about the book at the provider. + public string? Link { get; set; } + } + + /// A source of book metadata. Implementations keep no state but their HTTP client. + public interface IBookProvider + { + string Id { get; } + ProviderDescriptor Descriptor { get; } + /// Books for a title, and its author when known. Best first. + Task> SearchAsync(string title, string? author, CancellationToken ct); + /// One book by its id at this provider, with every detail (description...). + Task GetAsync(string providerId, CancellationToken ct); + } + + /// Where the scan and the manual actions get their book providers from. + public interface IBookProviderSource + { + /// Enabled providers, preferred first. + IReadOnlyList GetEnabled(); + IBookProvider? Get(string id); + } + + /// The settings a book provider is built with. + public sealed record BookProviderSettings(string ApiKey, string Language, string AudibleRegion); + + /// Base of the book providers: JSON over HTTP with a polite rate. + public abstract class BookProviderBase : HttpJsonSource, IBookProvider + { + protected readonly BookProviderSettings Settings; + + protected BookProviderBase(HttpClient http, BookProviderSettings settings, ILogger logger) : base(http, settings.ApiKey, logger) + { + Settings = settings; + } + + public abstract ProviderDescriptor Descriptor { get; } + protected override string SourceName => Descriptor.Name; + public abstract Task> SearchAsync(string title, string? author, CancellationToken ct); + public abstract Task GetAsync(string providerId, CancellationToken ct); + + protected static string Q(string s) => Uri.EscapeDataString(s.Trim()); + + private static readonly Regex Tags = new("<[^>]+>", RegexOptions.Compiled); + + /// Plain text from the HTML some providers send. + protected static string? PlainText(string? html) + { + if (string.IsNullOrWhiteSpace(html)) return null; + var s = Regex.Replace(html, @"<\s*(br|/p|/div|/li)\s*/?>", "\n", RegexOptions.IgnoreCase); + s = Tags.Replace(s, string.Empty); + s = System.Net.WebUtility.HtmlDecode(s); + s = Regex.Replace(s, @"[ \t]+", " "); + s = Regex.Replace(s, @"\n\s*\n+", "\n\n"); + return Blank(s); + } + + protected static List Strings(JsonElement e, string name) + { + if (!e.TryGetProperty(name, out var p) || p.ValueKind != JsonValueKind.Array) return new List(); + return p.EnumerateArray().Where(x => x.ValueKind == JsonValueKind.String).Select(x => x.GetString()!.Trim()).Where(x => x.Length > 0).Distinct().ToList(); + } + + protected static List Names(JsonElement e, string name) + { + if (!e.TryGetProperty(name, out var p) || p.ValueKind != JsonValueKind.Array) return new List(); + return p.EnumerateArray().Select(x => x.ValueKind == JsonValueKind.Object ? Str(x, "name") : x.ValueKind == JsonValueKind.String ? x.GetString() : null) + .Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x!.Trim()).Distinct().ToList(); + } + + /// ISO 639-1 code of the configured language ("es-ES" → "es"). + protected string Lang => (Settings.Language ?? "es").Split('-', '_')[0].Trim().ToLowerInvariant() is { Length: 2 } l ? l : "es"; + } + + /// The iTunes Search API: official, free and without a key. Audiobooks of the Apple Books store. + public class ITunesBookProvider : BookProviderBase + { + public const string ProviderId = "itunes"; + public static readonly ProviderDescriptor Info = new() + { + Id = ProviderId, + Name = "iTunes (Apple Books)", + Website = "https://www.apple.com/apple-books/", + KeyUrl = string.Empty, + RequiresKey = false, + SupportsImages = true, + SupportsLanguage = true + }; + + public ITunesBookProvider(HttpClient http, BookProviderSettings settings, ILogger logger) : base(http, settings, logger) { } + + public override string Id => ProviderId; + public override ProviderDescriptor Descriptor => Info; + // Apple allows about 20 requests a minute + protected override TimeSpan MinInterval => TimeSpan.FromMilliseconds(3100); + + private string Country => Lang switch + { + "es" or "gl" or "ca" or "eu" => "es", + "en" => "us", + "pt" => "pt", + "ja" => "jp", + "fr" or "de" or "it" or "ru" or "nl" or "pl" or "sv" => Lang, + _ => "us" + }; + + public override async Task> SearchAsync(string title, string? author, CancellationToken ct) + { + var term = string.IsNullOrWhiteSpace(author) ? title : $"{title} {author}"; + var list = await QueryAsync($"https://itunes.apple.com/search?term={Q(term)}&media=audiobook&entity=audiobook&country={Country}&limit=15", ct); + if (list.Count == 0 && !string.IsNullOrWhiteSpace(author)) + list = await QueryAsync($"https://itunes.apple.com/search?term={Q(title)}&media=audiobook&entity=audiobook&country={Country}&limit=15", ct); + return list; + } + + public override async Task GetAsync(string providerId, CancellationToken ct) => + (await QueryAsync($"https://itunes.apple.com/lookup?id={Q(providerId)}&entity=audiobook&country={Country}", ct)).FirstOrDefault(); + + private async Task> QueryAsync(string url, CancellationToken ct) + { + using var doc = await GetJsonAsync(url, ct); + var result = new List(); + if (doc == null || !doc.RootElement.TryGetProperty("results", out var results) || results.ValueKind != JsonValueKind.Array) return result; + foreach (var r in results.EnumerateArray()) + { + var id = r.TryGetProperty("collectionId", out var cid) && cid.ValueKind == JsonValueKind.Number ? cid.GetInt64().ToString() : null; + var name = Str(r, "collectionName"); + if (id == null || string.IsNullOrWhiteSpace(name)) continue; + var cover = Str(r, "artworkUrl100") ?? Str(r, "artworkUrl60"); + result.Add(new BookCandidate + { + Provider = Id, + ProviderId = id, + Title = name.Trim(), + Authors = SplitAuthors(Str(r, "artistName")), + Year = YearOf(Str(r, "releaseDate")), + Genres = Blank(Str(r, "primaryGenreName")) is string g ? new List { g } : new List(), + Description = PlainText(Str(r, "description")), + CoverUrl = cover == null ? null : Regex.Replace(cover, @"/\d+x\d+bb\.", "/600x600bb."), + Language = Lang, + Link = Str(r, "collectionViewUrl") + }); + } + return result; + } + + private static List SplitAuthors(string? artist) => + string.IsNullOrWhiteSpace(artist) ? new List() + : Regex.Split(artist, @"\s*(?:,|&| y | and )\s*").Select(a => a.Trim()).Where(a => a.Length > 1).Distinct().ToList(); + } + + /// The Google Books API: free; the key is optional (a key raises the daily quota). + public class GoogleBooksProvider : BookProviderBase + { + public const string ProviderId = "google"; + public static readonly ProviderDescriptor Info = new() + { + Id = ProviderId, + Name = "Google Books", + Website = "https://books.google.com", + KeyUrl = "https://console.cloud.google.com/apis/library/books.googleapis.com", + RequiresKey = false, + SupportsImages = true, + SupportsLanguage = true + }; + + public GoogleBooksProvider(HttpClient http, BookProviderSettings settings, ILogger logger) : base(http, settings, logger) { } + + public override string Id => ProviderId; + public override ProviderDescriptor Descriptor => Info; + protected override TimeSpan MinInterval => TimeSpan.FromMilliseconds(400); + + private string KeyParam => string.IsNullOrWhiteSpace(ApiKey) ? string.Empty : "&key=" + Q(ApiKey); + + public override async Task> SearchAsync(string title, string? author, CancellationToken ct) + { + var q = string.IsNullOrWhiteSpace(author) ? $"intitle:{title}" : $"intitle:{title} inauthor:{author}"; + var list = await QueryAsync($"https://www.googleapis.com/books/v1/volumes?q={Q(q)}&langRestrict={Lang}&maxResults=15&printType=books{KeyParam}", ct); + if (list.Count == 0) + list = await QueryAsync($"https://www.googleapis.com/books/v1/volumes?q={Q(string.IsNullOrWhiteSpace(author) ? title : $"{title} {author}")}&maxResults=15&printType=books{KeyParam}", ct); + return list; + } + + public override async Task GetAsync(string providerId, CancellationToken ct) + { + using var doc = await GetJsonAsync($"https://www.googleapis.com/books/v1/volumes/{Q(providerId)}?{KeyParam.TrimStart('&')}", ct); + return doc == null ? null : Read(doc.RootElement); + } + + private async Task> QueryAsync(string url, CancellationToken ct) + { + using var doc = await GetJsonAsync(url, ct); + var result = new List(); + if (doc == null || !doc.RootElement.TryGetProperty("items", out var items) || items.ValueKind != JsonValueKind.Array) return result; + foreach (var item in items.EnumerateArray()) + if (Read(item) is { } c) result.Add(c); + return result; + } + + private BookCandidate? Read(JsonElement item) + { + var id = Str(item, "id"); + if (id == null || !item.TryGetProperty("volumeInfo", out var v)) return null; + var title = Str(v, "title"); + if (string.IsNullOrWhiteSpace(title)) return null; + string? isbn = null; + if (v.TryGetProperty("industryIdentifiers", out var ids) && ids.ValueKind == JsonValueKind.Array) + { + var all = ids.EnumerateArray().Select(x => (Type: Str(x, "type"), Value: Str(x, "identifier"))).ToList(); + isbn = all.FirstOrDefault(x => x.Type == "ISBN_13").Value ?? all.FirstOrDefault(x => x.Type == "ISBN_10").Value; + } + string? cover = null; + if (v.TryGetProperty("imageLinks", out var images)) + cover = Str(images, "large") ?? Str(images, "medium") ?? Str(images, "thumbnail") ?? Str(images, "smallThumbnail"); + if (cover != null) + cover = cover.Replace("http://", "https://").Replace("&edge=curl", string.Empty); + return new BookCandidate + { + Provider = Id, + ProviderId = id, + Title = title.Trim(), + Subtitle = Blank(Str(v, "subtitle")), + Authors = Strings(v, "authors"), + Publisher = Blank(Str(v, "publisher")), + Year = YearOf(Str(v, "publishedDate")), + Language = Blank(Str(v, "language")), + Genres = Strings(v, "categories").SelectMany(c => c.Split('/')).Select(c => c.Trim()).Where(c => c.Length > 0).Distinct().ToList(), + Description = PlainText(Str(v, "description")), + CoverUrl = cover, + Rating = Dbl(v, "averageRating"), + Isbn = isbn, + Link = Str(v, "infoLink") + }; + } + } + + /// Open Library: free and open, without a key. Uneven data, good as a fallback. + public class OpenLibraryProvider : BookProviderBase + { + public const string ProviderId = "openlibrary"; + public static readonly ProviderDescriptor Info = new() + { + Id = ProviderId, + Name = "Open Library", + Website = "https://openlibrary.org", + KeyUrl = string.Empty, + RequiresKey = false, + SupportsImages = true, + SupportsLanguage = true + }; + + private const string Fields = "key,title,subtitle,author_name,first_publish_year,isbn,cover_i,language,publisher,subject"; + + public OpenLibraryProvider(HttpClient http, BookProviderSettings settings, ILogger logger) : base(http, settings, logger) { } + + public override string Id => ProviderId; + public override ProviderDescriptor Descriptor => Info; + protected override TimeSpan MinInterval => TimeSpan.FromMilliseconds(1000); + + private string Lang3 => Lang switch + { + "es" => "spa", "en" => "eng", "fr" => "fre", "de" => "ger", "it" => "ita", "pt" => "por", "ru" => "rus", + "gl" => "glg", "ca" => "cat", "eu" => "baq", "nl" => "dut", "ja" => "jpn", "pl" => "pol", _ => "eng" + }; + + public override async Task> SearchAsync(string title, string? author, CancellationToken ct) + { + var url = $"https://openlibrary.org/search.json?title={Q(title)}{(string.IsNullOrWhiteSpace(author) ? string.Empty : "&author=" + Q(author))}&fields={Fields}&limit=10&lang={Lang}"; + var list = await QueryAsync(url, ct); + if (list.Count == 0 && !string.IsNullOrWhiteSpace(author)) + list = await QueryAsync($"https://openlibrary.org/search.json?q={Q(title + " " + author)}&fields={Fields}&limit=10&lang={Lang}", ct); + return list; + } + + public override async Task GetAsync(string providerId, CancellationToken ct) + { + var key = providerId.StartsWith("/works/") ? providerId : "/works/" + providerId; + var found = (await QueryAsync($"https://openlibrary.org/search.json?q={Q("key:" + key)}&fields={Fields}&limit=1&lang={Lang}", ct)).FirstOrDefault(); + if (found == null) return null; + using var work = await GetJsonAsync($"https://openlibrary.org{key}.json", ct); + if (work != null && work.RootElement.TryGetProperty("description", out var d)) + found.Description = PlainText(d.ValueKind == JsonValueKind.String ? d.GetString() : d.ValueKind == JsonValueKind.Object ? Str(d, "value") : null); + return found; + } + + protected override void Authorize(HttpRequestMessage request) => + request.Headers.UserAgent.ParseAdd("TelegramFileManager/1.0 (+https://github.com/mateof/TelegramFileManager)"); + + private async Task> QueryAsync(string url, CancellationToken ct) + { + using var doc = await GetJsonAsync(url, ct); + var result = new List(); + if (doc == null || !doc.RootElement.TryGetProperty("docs", out var docs) || docs.ValueKind != JsonValueKind.Array) return result; + foreach (var d in docs.EnumerateArray()) + { + var key = Str(d, "key"); + var title = Str(d, "title"); + if (key == null || string.IsNullOrWhiteSpace(title)) continue; + var languages = Strings(d, "language"); + var isbns = Strings(d, "isbn"); + result.Add(new BookCandidate + { + Provider = Id, + ProviderId = key.Replace("/works/", string.Empty), + Title = title.Trim(), + Subtitle = Blank(Str(d, "subtitle")), + Authors = Strings(d, "author_name"), + Year = Int(d, "first_publish_year"), + Publisher = Strings(d, "publisher").FirstOrDefault(), + Language = languages.Contains(Lang3) ? Lang : null, + Genres = Strings(d, "subject").Take(5).ToList(), + CoverUrl = Int(d, "cover_i") is int cover && cover > 0 ? $"https://covers.openlibrary.org/b/id/{cover}-L.jpg" : null, + Isbn = isbns.FirstOrDefault(i => i.Length == 13) ?? isbns.FirstOrDefault(), + Link = "https://openlibrary.org" + key + }); + } + return result; + } + } + + /// + /// The Audible catalogue API of a region (audible.es, .com, .co.uk...). Not an + /// official public API, though open and without a key (the one Audiobookshelf + /// uses): best for narrators, series and runtime, and may break someday. + /// + public class AudibleProvider : BookProviderBase + { + public const string ProviderId = "audible"; + public static readonly ProviderDescriptor Info = new() + { + Id = ProviderId, + Name = "Audible", + Website = "https://www.audible.com", + KeyUrl = string.Empty, + RequiresKey = false, + SupportsImages = true, + SupportsLanguage = false + }; + + /// Region code → domain of its store. + public static readonly IReadOnlyDictionary Regions = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["es"] = "es", ["us"] = "com", ["uk"] = "co.uk", ["de"] = "de", ["fr"] = "fr", ["it"] = "it", + ["ca"] = "ca", ["au"] = "com.au", ["jp"] = "co.jp", ["in"] = "in" + }; + + private const string Groups = "contributors,media,product_attrs,product_desc,product_extended_attrs,series,category_ladders,rating"; + + public AudibleProvider(HttpClient http, BookProviderSettings settings, ILogger logger) : base(http, settings, logger) { } + + public override string Id => ProviderId; + public override ProviderDescriptor Descriptor => Info; + protected override TimeSpan MinInterval => TimeSpan.FromMilliseconds(500); + + public static string NormalizeRegion(string? region) => region != null && Regions.ContainsKey(region.Trim()) ? region.Trim().ToLowerInvariant() : "es"; + private string Domain => Regions[NormalizeRegion(Settings.AudibleRegion)]; + public string Region => NormalizeRegion(Settings.AudibleRegion); + + public override async Task> SearchAsync(string title, string? author, CancellationToken ct) + { + var url = $"https://api.audible.{Domain}/1.0/catalog/products?num_results=15&products_sort_by=Relevance&title={Q(title)}" + + (string.IsNullOrWhiteSpace(author) ? string.Empty : "&author=" + Q(author)) + + $"&response_groups={Groups}&image_sizes=500,1024"; + var list = await QueryAsync(url, ct); + if (list.Count == 0 && !string.IsNullOrWhiteSpace(author)) + list = await QueryAsync($"https://api.audible.{Domain}/1.0/catalog/products?num_results=15&products_sort_by=Relevance&keywords={Q(title + " " + author)}&response_groups={Groups}&image_sizes=500,1024", ct); + return list; + } + + public override async Task GetAsync(string providerId, CancellationToken ct) + { + using var doc = await GetJsonAsync($"https://api.audible.{Domain}/1.0/catalog/products/{Q(providerId)}?response_groups={Groups}&image_sizes=500,1024", ct); + return doc != null && doc.RootElement.TryGetProperty("product", out var p) ? Read(p) : null; + } + + private async Task> QueryAsync(string url, CancellationToken ct) + { + using var doc = await GetJsonAsync(url, ct); + var result = new List(); + if (doc == null || !doc.RootElement.TryGetProperty("products", out var products) || products.ValueKind != JsonValueKind.Array) return result; + foreach (var p in products.EnumerateArray()) + if (Read(p) is { } c) result.Add(c); + return result; + } + + private BookCandidate? Read(JsonElement p) + { + var asin = Str(p, "asin"); + var title = Str(p, "title"); + if (asin == null || string.IsNullOrWhiteSpace(title)) return null; + string? cover = null; + if (p.TryGetProperty("product_images", out var images) && images.ValueKind == JsonValueKind.Object) + cover = Str(images, "1024") ?? Str(images, "500"); + var series = new List(); + if (p.TryGetProperty("series", out var s) && s.ValueKind == JsonValueKind.Array) + foreach (var x in s.EnumerateArray()) + if (Blank(Str(x, "title")) is string name) + series.Add(new AudiobookSeriesRef { Name = name, Sequence = Blank(Str(x, "sequence")) }); + var genres = new List(); + if (p.TryGetProperty("category_ladders", out var ladders) && ladders.ValueKind == JsonValueKind.Array) + foreach (var ladder in ladders.EnumerateArray()) + if (ladder.TryGetProperty("ladder", out var steps) && steps.ValueKind == JsonValueKind.Array) + genres.AddRange(Names(ladder, "ladder")); + double? rating = null; + if (p.TryGetProperty("rating", out var r) && r.TryGetProperty("overall_distribution", out var od)) + rating = Dbl(od, "display_average_rating") ?? Dbl(od, "average_rating"); + var minutes = Int(p, "runtime_length_min"); + return new BookCandidate + { + Provider = Id, + ProviderId = asin, + Asin = asin, + Title = title.Trim(), + Subtitle = Blank(Str(p, "subtitle")), + Authors = Names(p, "authors"), + Narrators = Names(p, "narrators"), + Series = series, + Publisher = Blank(Str(p, "publisher_name")), + Year = YearOf(Str(p, "release_date") ?? Str(p, "issue_date")), + Language = LanguageCode(Str(p, "language")), + Genres = genres.Distinct().Take(6).ToList(), + Description = PlainText(Str(p, "publisher_summary") ?? Str(p, "merchandising_summary")), + CoverUrl = cover, + Rating = rating is > 0 ? rating : null, + DurationMs = minutes is > 0 ? minutes.Value * 60_000L : null, + Isbn = Blank(Str(p, "isbn")), + Link = $"https://www.audible.{Domain}/pd/{asin}" + }; + } + + private static string? LanguageCode(string? language) => language?.Trim().ToLowerInvariant() switch + { + null or "" => null, + "spanish" or "español" or "castellano" => "es", + "english" => "en", + "german" => "de", + "french" => "fr", + "italian" => "it", + "portuguese" => "pt", + "japanese" => "ja", + "catalan" => "ca", + "galician" => "gl", + var other => other.Length == 2 ? other : null + }; + } + + /// + /// Audnexus (api.audnex.us): free and open; the chapters of the Audible edition + /// of a book, by its ASIN. + /// + public class AudnexusClient : HttpJsonSource + { + public AudnexusClient(HttpClient http, ILogger logger) : base(http, string.Empty, logger) { } + + public override string Id => "audnexus"; + protected override string SourceName => "Audnexus"; + protected override TimeSpan MinInterval => TimeSpan.FromMilliseconds(400); + + /// Chapters and runtime of an Audible edition; null when unknown. + public async Task<(List Chapters, long RuntimeMs)?> GetChaptersAsync(string asin, string region, CancellationToken ct) + { + using var doc = await GetJsonAsync($"https://api.audnex.us/books/{Uri.EscapeDataString(asin)}/chapters?region={Uri.EscapeDataString(region)}", ct); + if (doc == null || !doc.RootElement.TryGetProperty("chapters", out var list) || list.ValueKind != JsonValueKind.Array) return null; + var chapters = new List(); + foreach (var c in list.EnumerateArray()) + { + var start = c.TryGetProperty("startOffsetMs", out var s) && s.TryGetInt64(out var sv) ? sv : 0; + var length = c.TryGetProperty("lengthMs", out var l) && l.TryGetInt64(out var lv) ? lv : 0; + chapters.Add(new AudiobookChapter { Title = Blank(Str(c, "title")) ?? $"Capítulo {chapters.Count + 1}", StartMs = start, EndMs = start + length }); + } + var runtime = doc.RootElement.TryGetProperty("runtimeLengthMs", out var rt) && rt.TryGetInt64(out var rv) ? rv : chapters.LastOrDefault()?.EndMs ?? 0; + return chapters.Count == 0 ? null : (chapters, runtime); + } + } + + /// + /// Builds the book providers the user enabled, in priority order, with their + /// searches cached in MongoDB for a week. + /// + public class BookProviderRegistry : IBookProviderSource + { + public static readonly IReadOnlyList Known = new[] { ITunesBookProvider.Info, GoogleBooksProvider.Info, OpenLibraryProvider.Info, AudibleProvider.Info }; + /// Enabled out of the box: the official and open ones. Audible is opt-in. + private static readonly HashSet EnabledByDefault = new(StringComparer.OrdinalIgnoreCase) { ITunesBookProvider.ProviderId, GoogleBooksProvider.ProviderId, OpenLibraryProvider.ProviderId }; + private static readonly TimeSpan CacheTtl = TimeSpan.FromDays(7); + + private readonly IHttpClientFactory _httpFactory; + private readonly ILibraryDbService _cache; + private readonly ILoggerFactory _loggerFactory; + private readonly ConcurrentDictionary _instances = new(); + + public BookProviderRegistry(IHttpClientFactory httpFactory, ILibraryDbService cache, ILoggerFactory loggerFactory) + { + _httpFactory = httpFactory; + _cache = cache; + _loggerFactory = loggerFactory; + } + + public static ProviderDescriptor? Describe(string id) => Known.FirstOrDefault(k => k.Id.Equals(id, StringComparison.OrdinalIgnoreCase)); + + /// One entry per known provider, in priority order. + public static List EffectiveConfigs(GeneralConfig config) + { + var list = config.AudiobookProviders ?? new List(); + var result = new List(); + foreach (var known in Known) + { + var existing = list.FirstOrDefault(p => p.Id.Equals(known.Id, StringComparison.OrdinalIgnoreCase)); + result.Add(existing ?? new LibraryProviderConfig { Id = known.Id, Enabled = EnabledByDefault.Contains(known.Id), Priority = result.Count + 1 }); + } + return result.OrderBy(p => p.Priority).ThenBy(p => p.Id).ToList(); + } + + public static BookProviderSettings SettingsFor(GeneralConfig config, LibraryProviderConfig pc) => + new(pc.ApiKey?.Trim() ?? string.Empty, string.IsNullOrWhiteSpace(config.AudiobookLanguage) ? "es" : config.AudiobookLanguage.Trim(), AudibleProvider.NormalizeRegion(config.AudibleRegion)); + + public IReadOnlyList GetEnabled() => GetEnabled(null); + + public IReadOnlyList GetEnabled(GeneralConfig? config) + { + config ??= GeneralConfigStatic.config; + var result = new List(); + foreach (var pc in EffectiveConfigs(config)) + { + if (!pc.Enabled || Describe(pc.Id) == null) continue; + var settings = SettingsFor(config, pc); + var key = $"{pc.Id}|{settings}"; + result.Add(_instances.GetOrAdd(key, _ => new CachedBookProvider(Create(pc.Id, settings), _cache, $"{settings.Language}|{settings.AudibleRegion}"))); + } + return result; + } + + public IBookProvider? Get(string id) => GetEnabled().FirstOrDefault(p => p.Id.Equals(id, StringComparison.OrdinalIgnoreCase)); + + private IBookProvider Create(string id, BookProviderSettings settings) + { + var http = _httpFactory.CreateClient("books"); + var logger = _loggerFactory.CreateLogger("Audiobooks." + id); + return id switch + { + ITunesBookProvider.ProviderId => new ITunesBookProvider(http, settings, logger), + GoogleBooksProvider.ProviderId => new GoogleBooksProvider(http, settings, logger), + OpenLibraryProvider.ProviderId => new OpenLibraryProvider(http, settings, logger), + AudibleProvider.ProviderId => new AudibleProvider(http, settings, logger), + _ => throw new ArgumentException($"Unknown book provider '{id}'") + }; + } + + /// Searches remembered for a week, so rescans and corrections do not repeat them. + private sealed class CachedBookProvider : IBookProvider + { + private readonly IBookProvider _inner; + private readonly ILibraryDbService _cache; + private readonly string _scope; + + public CachedBookProvider(IBookProvider inner, ILibraryDbService cache, string scope) + { + _inner = inner; + _cache = cache; + _scope = scope; + } + + public string Id => _inner.Id; + public ProviderDescriptor Descriptor => _inner.Descriptor; + + public async Task> SearchAsync(string title, string? author, CancellationToken ct) + { + var key = $"book:{Id}:{_scope}:search:{title.ToLowerInvariant()}|{author?.ToLowerInvariant()}"; + var cached = await _cache.GetCached(key); + if (cached != null) + return JsonSerializer.Deserialize>(cached) ?? new List(); + var result = await _inner.SearchAsync(title, author, ct); + await _cache.SetCached(key, JsonSerializer.Serialize(result), CacheTtl); + return result; + } + + public Task GetAsync(string providerId, CancellationToken ct) => _inner.GetAsync(providerId, ct); + } + } +} diff --git a/TelegramDownloader/Services/Audiobooks/ChapterReader.cs b/TelegramDownloader/Services/Audiobooks/ChapterReader.cs new file mode 100644 index 0000000..2f6b6fe --- /dev/null +++ b/TelegramDownloader/Services/Audiobooks/ChapterReader.cs @@ -0,0 +1,475 @@ +using System.Buffers.Binary; +using System.Text; +using TelegramDownloader.Models.Audiobooks; + +namespace TelegramDownloader.Services.Audiobooks +{ + /// + /// Random access to a remote file by aligned blocks (Telegram serves 512 KB + /// pieces), keeping the last ones read, so a parser can jump around without + /// downloading the whole file. + /// + public sealed class RangeReader + { + public const int BlockSize = 512 * 1024; + private const int MaxBlocks = 12; + + private readonly Func> _fetch; + private readonly LinkedList<(long Index, byte[] Data)> _blocks = new(); + + /// Reads up to count bytes at an offset aligned to . + public RangeReader(long length, Func> fetch) + { + Length = length; + _fetch = fetch; + } + + public long Length { get; } + /// Blocks fetched so far: what the parse cost. + public int BlocksFetched { get; private set; } + /// The most blocks a parse may fetch before giving up. + public int Budget { get; set; } = 120; + + public static RangeReader FromBytes(byte[] data) => + new(data.LongLength, (offset, count, _) => Task.FromResult(data.Skip((int)offset).Take(count).ToArray())); + + public async Task ReadAsync(long offset, int count, CancellationToken ct) + { + if (offset < 0 || offset >= Length || count <= 0) return Array.Empty(); + count = (int)Math.Min(count, Length - offset); + var result = new byte[count]; + var done = 0; + while (done < count) + { + var position = offset + done; + var index = position / BlockSize; + var block = await BlockAsync(index, ct); + var inBlock = (int)(position - index * BlockSize); + if (inBlock >= block.Length) break; + var n = Math.Min(count - done, block.Length - inBlock); + Buffer.BlockCopy(block, inBlock, result, done, n); + done += n; + } + return done == count ? result : result[..done]; + } + + private async Task BlockAsync(long index, CancellationToken ct) + { + for (var node = _blocks.First; node != null; node = node.Next) + { + if (node.Value.Index != index) continue; + _blocks.Remove(node); + _blocks.AddFirst(node); + return node.Value.Data; + } + if (BlocksFetched >= Budget) throw new InvalidOperationException("The file needs too many reads to find its chapters"); + BlocksFetched++; + var data = await _fetch(index * BlockSize, BlockSize, ct); + _blocks.AddFirst((index, data)); + if (_blocks.Count > MaxBlocks) _blocks.RemoveLast(); + return data; + } + } + + /// What a file says about itself: its duration and its chapters. + public sealed record FileChapters(long DurationMs, List Chapters); + + /// + /// Reads the chapters stored in audio files: MP4/M4B (Nero chpl and + /// QuickTime chapter tracks) and MP3 (ID3v2 CHAP frames), plus their + /// duration (MP4 mvhd; MP3 from the Xing header or the bitrate). + /// + public static class ChapterReader + { + public static bool CanRead(string? extension) => + (extension ?? string.Empty).TrimStart('.').ToLowerInvariant() is "m4b" or "m4a" or "mp4" or "aac" or "mp3"; + + public static async Task ReadAsync(RangeReader file, string extension, CancellationToken ct) + { + var ext = extension.TrimStart('.').ToLowerInvariant(); + if (ext == "mp3") return await ReadMp3Async(file, ct); + var head = await file.ReadAsync(0, 12, ct); + if (head.Length >= 8 && Encoding.ASCII.GetString(head, 4, 4) is "ftyp" or "moov" or "mdat" or "free" or "wide") + return await ReadMp4Async(file, ct); + if (head.Length >= 3 && head[0] == 'I' && head[1] == 'D' && head[2] == '3') + return await ReadMp3Async(file, ct); + return null; + } + + #region MP4 + + private sealed record Box(string Type, long Start, long Size, int Header) + { + public long Body => Start + Header; + public long End => Start + Size; + } + + private static async Task> ChildrenAsync(RangeReader file, long start, long end, CancellationToken ct) + { + var result = new List(); + var position = start; + while (position + 8 <= end) + { + var h = await file.ReadAsync(position, 16, ct); + if (h.Length < 8) break; + long size = BinaryPrimitives.ReadUInt32BigEndian(h); + var type = Encoding.ASCII.GetString(h, 4, 4); + var header = 8; + if (size == 1 && h.Length >= 16) + { + size = (long)BinaryPrimitives.ReadUInt64BigEndian(h.AsSpan(8)); + header = 16; + } + else if (size == 0) + { + size = end - position; + } + if (size < header) break; + result.Add(new Box(type, position, size, header)); + position += size; + } + return result; + } + + private static async Task ChildAsync(RangeReader file, Box parent, string type, CancellationToken ct, int skip = 0) => + (await ChildrenAsync(file, parent.Body + skip, parent.End, ct)).FirstOrDefault(b => b.Type == type); + + private static async Task ReadMp4Async(RangeReader file, CancellationToken ct) + { + var top = await ChildrenAsync(file, 0, file.Length, ct); + var moov = top.FirstOrDefault(b => b.Type == "moov"); + if (moov == null) return null; + var children = await ChildrenAsync(file, moov.Body, moov.End, ct); + + long durationMs = 0; + if (children.FirstOrDefault(b => b.Type == "mvhd") is { } mvhd) + { + var data = await file.ReadAsync(mvhd.Body, 32, ct); + if (data.Length >= 20) + { + long timescale, duration; + if (data[0] == 1 && data.Length >= 32) + { + timescale = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(20)); + duration = (long)BinaryPrimitives.ReadUInt64BigEndian(data.AsSpan(24)); + } + else + { + timescale = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(12)); + duration = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(16)); + } + if (timescale > 0) durationMs = duration * 1000 / timescale; + } + } + + var chapters = new List(); + // Nero chapters (moov/udta/chpl): everything in one small box + if (children.FirstOrDefault(b => b.Type == "udta") is { } udta && await ChildAsync(file, udta, "chpl", ct) is { } chpl && chpl.Size < 1_000_000) + chapters = ParseChpl(await file.ReadAsync(chpl.Body, (int)(chpl.Size - chpl.Header), ct)); + + // QuickTime chapters: a text track the audio track points to with tref/chap + if (chapters.Count == 0) + chapters = await ReadChapterTrackAsync(file, children.Where(b => b.Type == "trak").ToList(), ct); + + Close(chapters, durationMs); + return new FileChapters(durationMs, chapters); + } + + public static List ParseChpl(byte[] body) + { + var result = new List(); + if (body.Length < 5) return result; + var version = body[0]; + var p = 4; + if (version == 1) p += 4; + if (p >= body.Length) return result; + int count = body[p++]; + for (int i = 0; i < count && p + 9 <= body.Length; i++) + { + var start = (long)BinaryPrimitives.ReadUInt64BigEndian(body.AsSpan(p)); + p += 8; + int len = body[p++]; + if (p + len > body.Length) break; + var title = Encoding.UTF8.GetString(body, p, len).Trim('\0', ' '); + p += len; + result.Add(new AudiobookChapter { Title = title, StartMs = start / 10_000 }); + } + return result; + } + + private static async Task> ReadChapterTrackAsync(RangeReader file, List traks, CancellationToken ct) + { + var chapterIds = new HashSet(); + var byId = new Dictionary(); + foreach (var trak in traks) + { + var kids = await ChildrenAsync(file, trak.Body, trak.End, ct); + if (kids.FirstOrDefault(b => b.Type == "tkhd") is { } tkhd) + { + var h = await file.ReadAsync(tkhd.Body, 24, ct); + if (h.Length >= 24) + byId[BinaryPrimitives.ReadUInt32BigEndian(h.AsSpan(h[0] == 1 ? 20 : 12))] = trak; + } + if (kids.FirstOrDefault(b => b.Type == "tref") is { } tref && await ChildAsync(file, tref, "chap", ct) is { } chap) + { + var ids = await file.ReadAsync(chap.Body, (int)Math.Min(256, chap.Size - chap.Header), ct); + for (int i = 0; i + 4 <= ids.Length; i += 4) + chapterIds.Add(BinaryPrimitives.ReadUInt32BigEndian(ids.AsSpan(i))); + } + } + foreach (var id in chapterIds) + { + if (!byId.TryGetValue(id, out var trak)) continue; + var chapters = await ReadTextTrackAsync(file, trak, ct); + if (chapters.Count > 0) return chapters; + } + return new List(); + } + + private static async Task> ReadTextTrackAsync(RangeReader file, Box trak, CancellationToken ct) + { + var result = new List(); + var mdia = await ChildAsync(file, trak, "mdia", ct); + if (mdia == null) return result; + var mdiaKids = await ChildrenAsync(file, mdia.Body, mdia.End, ct); + long timescale = 1000; + if (mdiaKids.FirstOrDefault(b => b.Type == "mdhd") is { } mdhd) + { + var h = await file.ReadAsync(mdhd.Body, 24, ct); + if (h.Length >= 24) timescale = BinaryPrimitives.ReadUInt32BigEndian(h.AsSpan(h[0] == 1 ? 20 : 12)); + if (timescale <= 0) timescale = 1000; + } + var minf = mdiaKids.FirstOrDefault(b => b.Type == "minf"); + if (minf == null) return result; + var stbl = await ChildAsync(file, minf, "stbl", ct); + if (stbl == null) return result; + var tables = await ChildrenAsync(file, stbl.Body, stbl.End, ct); + async Task Table(string type) + { + var box = tables.FirstOrDefault(b => b.Type == type); + // A chapter track is small; a big table means this is not one + if (box == null || box.Size > 4_000_000) return null; + return await file.ReadAsync(box.Body, (int)(box.Size - box.Header), ct); + } + + var stts = await Table("stts"); + var stsz = await Table("stsz"); + var stsc = await Table("stsc"); + var stco = await Table("stco"); + var co64 = stco == null ? await Table("co64") : null; + if (stts == null || stsz == null || stsc == null || (stco == null && co64 == null)) return result; + + // Sample times + var starts = new List(); + long t = 0; + var entries = BinaryPrimitives.ReadUInt32BigEndian(stts.AsSpan(4)); + for (int i = 0; i < entries && 8 + i * 8 + 8 <= stts.Length; i++) + { + var count = BinaryPrimitives.ReadUInt32BigEndian(stts.AsSpan(8 + i * 8)); + var delta = BinaryPrimitives.ReadUInt32BigEndian(stts.AsSpan(12 + i * 8)); + for (uint k = 0; k < count && starts.Count < 2000; k++) + { + starts.Add(t * 1000 / timescale); + t += delta; + } + } + var samples = starts.Count; + if (samples == 0) return result; + + // Sample sizes + var uniform = BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(4)); + var sizes = new long[samples]; + for (int i = 0; i < samples; i++) + sizes[i] = uniform != 0 ? uniform : 12 + i * 4 + 4 <= stsz.Length ? BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(12 + i * 4)) : 0; + + // Chunk offsets and samples per chunk → offset of every sample + var chunkOffsets = new List(); + if (stco != null) + for (int i = 0; 8 + i * 4 + 4 <= stco.Length && i < BinaryPrimitives.ReadUInt32BigEndian(stco.AsSpan(4)); i++) + chunkOffsets.Add(BinaryPrimitives.ReadUInt32BigEndian(stco.AsSpan(8 + i * 4))); + else + for (int i = 0; 8 + i * 8 + 8 <= co64!.Length && i < BinaryPrimitives.ReadUInt32BigEndian(co64.AsSpan(4)); i++) + chunkOffsets.Add((long)BinaryPrimitives.ReadUInt64BigEndian(co64.AsSpan(8 + i * 8))); + var runs = new List<(int FirstChunk, int PerChunk)>(); + var stscEntries = BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(4)); + for (int i = 0; i < stscEntries && 8 + i * 12 + 12 <= stsc.Length; i++) + runs.Add(((int)BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(8 + i * 12)), (int)BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(12 + i * 12)))); + + var offsets = new long[samples]; + int sample = 0; + for (int chunk = 0; chunk < chunkOffsets.Count && sample < samples; chunk++) + { + var perChunk = runs.LastOrDefault(r => r.FirstChunk <= chunk + 1).PerChunk; + if (perChunk <= 0) perChunk = 1; + var offset = chunkOffsets[chunk]; + for (int k = 0; k < perChunk && sample < samples; k++) + { + offsets[sample] = offset; + offset += sizes[sample]; + sample++; + } + } + + for (int i = 0; i < samples; i++) + { + string title = $"Capítulo {i + 1}"; + if (sizes[i] >= 2 && sizes[i] < 4096) + { + var data = await file.ReadAsync(offsets[i], (int)sizes[i], ct); + if (data.Length >= 2) + { + int len = BinaryPrimitives.ReadUInt16BigEndian(data); + if (len > 0 && 2 + len <= data.Length) + title = DecodeText(data.AsSpan(2, len)) is { Length: > 0 } s ? s : title; + } + } + result.Add(new AudiobookChapter { Title = title, StartMs = starts[i] }); + } + return result; + } + + private static string DecodeText(ReadOnlySpan text) + { + if (text.Length >= 2 && text[0] == 0xFE && text[1] == 0xFF) return Encoding.BigEndianUnicode.GetString(text[2..]).Trim('\0', ' '); + if (text.Length >= 2 && text[0] == 0xFF && text[1] == 0xFE) return Encoding.Unicode.GetString(text[2..]).Trim('\0', ' '); + return Encoding.UTF8.GetString(text).Trim('\0', ' '); + } + + #endregion + + #region MP3 + + private static async Task ReadMp3Async(RangeReader file, CancellationToken ct) + { + var header = await file.ReadAsync(0, 10, ct); + var chapters = new List(); + long audioStart = 0; + if (header.Length == 10 && header[0] == 'I' && header[1] == 'D' && header[2] == '3') + { + var version = header[3]; + var tagSize = Syncsafe(header.AsSpan(6)); + audioStart = 10 + tagSize + ((header[5] & 0x10) != 0 ? 10 : 0); + if (tagSize > 0 && tagSize < 64 * 1024 * 1024) + { + var tag = await file.ReadAsync(10, (int)tagSize, ct); + chapters = ParseId3Chapters(tag, version); + } + } + var durationMs = await Mp3DurationAsync(file, audioStart, ct); + Close(chapters, durationMs); + return new FileChapters(durationMs, chapters); + } + + private static long Syncsafe(ReadOnlySpan b) => (b[0] & 0x7F) << 21 | (b[1] & 0x7F) << 14 | (b[2] & 0x7F) << 7 | (b[3] & 0x7F); + + public static List ParseId3Chapters(byte[] tag, byte version) + { + var result = new List(); + if (version < 3) return result; + var p = 0; + while (p + 10 <= tag.Length) + { + var id = Encoding.ASCII.GetString(tag, p, 4); + if (id[0] == '\0') break; + long size = version >= 4 ? Syncsafe(tag.AsSpan(p + 4)) : BinaryPrimitives.ReadUInt32BigEndian(tag.AsSpan(p + 4)); + if (size <= 0 || p + 10 + size > tag.Length) break; + if (id == "CHAP") + if (ParseChap(tag.AsSpan(p + 10, (int)size), version) is { } chapter) result.Add(chapter); + p += 10 + (int)size; + } + return result.OrderBy(c => c.StartMs).ToList(); + } + + private static AudiobookChapter? ParseChap(ReadOnlySpan frame, byte version) + { + var end = frame.IndexOf((byte)0); + if (end < 0 || end + 17 > frame.Length) return null; + var p = end + 1; + var start = BinaryPrimitives.ReadUInt32BigEndian(frame[p..]); + var stop = BinaryPrimitives.ReadUInt32BigEndian(frame[(p + 4)..]); + p += 16; + string? title = null; + while (p + 10 <= frame.Length) + { + var id = Encoding.ASCII.GetString(frame.Slice(p, 4)); + long size = version >= 4 ? Syncsafe(frame[(p + 4)..]) : BinaryPrimitives.ReadUInt32BigEndian(frame[(p + 4)..]); + if (size <= 0 || p + 10 + size > frame.Length) break; + if (id == "TIT2") title = DecodeId3Text(frame.Slice(p + 10, (int)size)); + p += 10 + (int)size; + } + return new AudiobookChapter { Title = title ?? string.Empty, StartMs = start, EndMs = stop == uint.MaxValue ? 0 : stop }; + } + + private static string DecodeId3Text(ReadOnlySpan data) + { + if (data.Length < 2) return string.Empty; + var body = data[1..]; + var s = data[0] switch + { + 1 => body.Length >= 2 && body[0] == 0xFE ? Encoding.BigEndianUnicode.GetString(body[2..]) : Encoding.Unicode.GetString(body.Length >= 2 && body[0] == 0xFF ? body[2..] : body), + 2 => Encoding.BigEndianUnicode.GetString(body), + 3 => Encoding.UTF8.GetString(body), + _ => Encoding.Latin1.GetString(body) + }; + return s.Trim('\0', ' '); + } + + private static readonly int[] Mpeg1L3 = { 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 }; + private static readonly int[] Mpeg2L3 = { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 }; + private static readonly int[][] Rates = { new[] { 11025, 12000, 8000 }, new[] { 0, 0, 0 }, new[] { 22050, 24000, 16000 }, new[] { 44100, 48000, 32000 } }; + + /// From the Xing/VBRI frame count when there is one, else from the first frame bitrate. + private static async Task Mp3DurationAsync(RangeReader file, long audioStart, CancellationToken ct) + { + var data = await file.ReadAsync(audioStart, 8192, ct); + for (int i = 0; i + 4 <= data.Length; i++) + { + if (data[i] != 0xFF || (data[i + 1] & 0xE0) != 0xE0) continue; + var versionBits = (data[i + 1] >> 3) & 3; + var layer = (data[i + 1] >> 1) & 3; + var bitrateIndex = data[i + 2] >> 4; + var rateIndex = (data[i + 2] >> 2) & 3; + if (versionBits == 1 || layer != 1 || bitrateIndex is 0 or 15 || rateIndex == 3) continue; + var sampleRate = Rates[versionBits][rateIndex]; + var mpeg1 = versionBits == 3; + var bitrate = (mpeg1 ? Mpeg1L3 : Mpeg2L3)[bitrateIndex] * 1000; + var mono = (data[i + 3] >> 6) == 3; + var samplesPerFrame = mpeg1 ? 1152 : 576; + var sideInfo = mpeg1 ? (mono ? 17 : 32) : (mono ? 9 : 17); + var xing = i + 4 + sideInfo; + if (xing + 12 <= data.Length) + { + var tag = Encoding.ASCII.GetString(data, xing, 4); + if ((tag == "Xing" || tag == "Info") && (data[xing + 7] & 1) != 0) + { + var frames = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(xing + 8)); + return frames * (long)samplesPerFrame * 1000 / sampleRate; + } + } + if (i + 36 + 18 <= data.Length && Encoding.ASCII.GetString(data, i + 36, 4) == "VBRI") + { + var frames = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(i + 36 + 14)); + return frames * (long)samplesPerFrame * 1000 / sampleRate; + } + var audioBytes = file.Length - audioStart - i; + return bitrate > 0 ? audioBytes * 8 * 1000 / bitrate : 0; + } + return 0; + } + + #endregion + + /// Sorted, without empty titles, each one ending where the next starts. + public static void Close(List chapters, long durationMs) + { + chapters.Sort((a, b) => a.StartMs.CompareTo(b.StartMs)); + for (int i = 0; i < chapters.Count; i++) + { + if (string.IsNullOrWhiteSpace(chapters[i].Title)) chapters[i].Title = $"Capítulo {i + 1}"; + var next = i + 1 < chapters.Count ? chapters[i + 1].StartMs : durationMs; + if (next > chapters[i].StartMs) chapters[i].EndMs = next; + else if (chapters[i].EndMs < chapters[i].StartMs) chapters[i].EndMs = chapters[i].StartMs; + } + } + } +} diff --git a/TelegramDownloader/Services/HelperService.cs b/TelegramDownloader/Services/HelperService.cs index 6e43b3f..e1c6bc1 100644 --- a/TelegramDownloader/Services/HelperService.cs +++ b/TelegramDownloader/Services/HelperService.cs @@ -141,6 +141,7 @@ public class FileExtensionTypeTest ".ogg", ".wma", ".m4a", + ".m4b", // audiobook ".aiff", ".alac", ".pcm", diff --git a/TelegramDownloader/Services/Library/HttpMetadataProviderBase.cs b/TelegramDownloader/Services/Library/HttpMetadataProviderBase.cs index 4dfeb84..a207d2a 100644 --- a/TelegramDownloader/Services/Library/HttpMetadataProviderBase.cs +++ b/TelegramDownloader/Services/Library/HttpMetadataProviderBase.cs @@ -5,10 +5,11 @@ namespace TelegramDownloader.Services.Library { /// - /// Shared HTTP plumbing for JSON metadata providers: a polite request rate, - /// retries on 429/5xx and provider errors surfaced as . + /// Shared HTTP plumbing for JSON sources (metadata providers of movies, + /// series and books): a polite request rate, retries on 429/5xx and errors + /// surfaced as . /// - public abstract class HttpMetadataProviderBase : IMetadataProvider + public abstract class HttpJsonSource { protected static readonly JsonSerializerOptions JsonOptions = new() { @@ -23,7 +24,7 @@ public abstract class HttpMetadataProviderBase : IMetadataProvider protected readonly ILogger Logger; protected readonly string ApiKey; - protected HttpMetadataProviderBase(HttpClient http, string apiKey, ILogger logger) + protected HttpJsonSource(HttpClient http, string apiKey, ILogger logger) { Http = http; ApiKey = apiKey; @@ -31,16 +32,11 @@ protected HttpMetadataProviderBase(HttpClient http, string apiKey, ILogger logge } public abstract string Id { get; } - public abstract ProviderDescriptor Descriptor { get; } + /// Name shown in errors. + protected abstract string SourceName { get; } /// Minimum gap between the start of two requests to this provider; several may be in flight. protected virtual TimeSpan MinInterval => TimeSpan.FromMilliseconds(250); - public abstract Task> SearchAsync(string kind, string query, int? year, CancellationToken ct); - public abstract Task GetItemAsync(string kind, string providerId, CancellationToken ct); - public abstract Task> GetSeasonAsync(string providerId, int season, CancellationToken ct); - public abstract Task FindByImdbAsync(string imdbId, string? kind, CancellationToken ct); - public abstract Task EnrichAsync(LibraryItem item, CancellationToken ct); - protected async Task GetJsonAsync(string url, CancellationToken ct, bool nullOn404 = true) { for (int attempt = 0; attempt < 4; attempt++) @@ -56,7 +52,7 @@ protected HttpMetadataProviderBase(HttpClient http, string apiKey, ILogger logge catch (Exception ex) when (ex is HttpRequestException || (ex is OperationCanceledException && !ct.IsCancellationRequested)) { // A timeout is a cancellation nobody asked for: it must not look like the user cancelled the scan - if (attempt == 3) throw new ProviderException($"{Descriptor.Name} is not reachable: {ex.Message}", null, ex); + if (attempt == 3) throw new ProviderException($"{SourceName} is not reachable: {ex.Message}", null, ex); await Task.Delay(TimeSpan.FromSeconds(2 * (attempt + 1)), ct); continue; } @@ -66,19 +62,19 @@ protected HttpMetadataProviderBase(HttpClient http, string apiKey, ILogger logge if (response.StatusCode == HttpStatusCode.NotFound && nullOn404) return null; if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden) - throw new ProviderException($"{Descriptor.Name} rejected the API key", (int)response.StatusCode); + throw new ProviderException($"{SourceName} rejected the API key", (int)response.StatusCode); if (response.StatusCode == HttpStatusCode.TooManyRequests || (int)response.StatusCode >= 500) { var wait = response.Headers.RetryAfter?.Delta ?? TimeSpan.FromSeconds(2 * (attempt + 1)); Logger.LogWarning("{Provider} answered {Status}; retrying in {Wait}s", Id, (int)response.StatusCode, wait.TotalSeconds); - if (attempt == 3) throw new ProviderException($"{Descriptor.Name} keeps answering {(int)response.StatusCode}", (int)response.StatusCode); + if (attempt == 3) throw new ProviderException($"{SourceName} keeps answering {(int)response.StatusCode}", (int)response.StatusCode); // Too many requests is about all of them, not only this one if (response.StatusCode == HttpStatusCode.TooManyRequests) await PauseAsync(wait, ct); else await Task.Delay(wait, ct); continue; } if (!response.IsSuccessStatusCode) - throw new ProviderException($"{Descriptor.Name} answered {(int)response.StatusCode}", (int)response.StatusCode); + throw new ProviderException($"{SourceName} answered {(int)response.StatusCode}", (int)response.StatusCode); await using var stream = await response.Content.ReadAsStreamAsync(ct); return await JsonDocument.ParseAsync(stream, cancellationToken: ct); @@ -150,4 +146,19 @@ private async Task PauseAsync(TimeSpan wait, CancellationToken ct) protected static string? Blank(string? s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim(); } + + /// A movie and series provider over . + public abstract class HttpMetadataProviderBase : HttpJsonSource, IMetadataProvider + { + protected HttpMetadataProviderBase(HttpClient http, string apiKey, ILogger logger) : base(http, apiKey, logger) { } + + public abstract ProviderDescriptor Descriptor { get; } + protected override string SourceName => Descriptor.Name; + + public abstract Task> SearchAsync(string kind, string query, int? year, CancellationToken ct); + public abstract Task GetItemAsync(string kind, string providerId, CancellationToken ct); + public abstract Task> GetSeasonAsync(string providerId, int season, CancellationToken ct); + public abstract Task FindByImdbAsync(string imdbId, string? kind, CancellationToken ct); + public abstract Task EnrichAsync(LibraryItem item, CancellationToken ct); + } } diff --git a/TelegramDownloader/Services/Library/LibraryFolderRules.cs b/TelegramDownloader/Services/Library/LibraryFolderRules.cs index 089be0c..f378769 100644 --- a/TelegramDownloader/Services/Library/LibraryFolderRules.cs +++ b/TelegramDownloader/Services/Library/LibraryFolderRules.cs @@ -8,8 +8,13 @@ public static class LibraryRuleKind public const string Movie = LibraryKind.Movie; public const string Series = LibraryKind.Series; public const string Ignore = "ignore"; + /// Audiobooks: the movie and series scan leaves the folder alone, the audiobook scan reads it. + public const string Audiobook = "audiobook"; - public static bool IsValid(string? kind) => kind == Movie || kind == Series || kind == Ignore; + public static bool IsValid(string? kind) => kind == Movie || kind == Series || kind == Ignore || kind == Audiobook; + + /// Kinds whose files the movie and series scan does not identify. + public static bool IsNotVideoLibrary(string? kind) => kind == Ignore || kind == Audiobook; } /// @@ -77,13 +82,14 @@ public static List Outermost(IEnumerable f return best; } - /// A kind suggested by the folder names themselves ("Series/", "Películas/"). Deepest wins. + /// A kind suggested by the folder names themselves ("Series/", "Películas/", "Audiolibros/"). Deepest wins. public static string? HintFromPath(string? folderPath) { var segments = Normalize(folderPath).Split('/', StringSplitOptions.RemoveEmptyEntries); for (int i = segments.Length - 1; i >= 0; i--) { var name = MediaNameParser.NormalizeForMatch(segments[i]); + if (Audiobooks.AudiobookNames.IsBookFolderName(segments[i])) return LibraryRuleKind.Audiobook; if (SeriesNames.Contains(name)) return LibraryRuleKind.Series; if (MovieNames.Contains(name)) return LibraryRuleKind.Movie; } diff --git a/TelegramDownloader/Services/Library/LibraryImageService.cs b/TelegramDownloader/Services/Library/LibraryImageService.cs index 86e3f81..3d2df13 100644 --- a/TelegramDownloader/Services/Library/LibraryImageService.cs +++ b/TelegramDownloader/Services/Library/LibraryImageService.cs @@ -40,7 +40,10 @@ public class LibraryImageService : IDisposable private static readonly HashSet AllowedHosts = new(StringComparer.OrdinalIgnoreCase) { - "image.tmdb.org", "m.media-amazon.com", "ia.media-imdb.com", "images-na.ssl-images-amazon.com", "artworks.thetvdb.com" + "image.tmdb.org", "m.media-amazon.com", "ia.media-imdb.com", "images-na.ssl-images-amazon.com", "artworks.thetvdb.com", + // Audiobook covers: iTunes, Google Books, Open Library (Audible uses m.media-amazon.com) + "is1-ssl.mzstatic.com", "is2-ssl.mzstatic.com", "is3-ssl.mzstatic.com", "is4-ssl.mzstatic.com", "is5-ssl.mzstatic.com", + "books.google.com", "books.googleusercontent.com", "covers.openlibrary.org" }; /// Extensions an image may be stored with, the usual one first. diff --git a/TelegramDownloader/Services/Library/LibraryScanService.cs b/TelegramDownloader/Services/Library/LibraryScanService.cs index b69d19f..b140101 100644 --- a/TelegramDownloader/Services/Library/LibraryScanService.cs +++ b/TelegramDownloader/Services/Library/LibraryScanService.cs @@ -443,9 +443,9 @@ private async Task> FindChangesAsync(string channelId, bool forc if (rule?.TitleKey is string title && !pins.TryGetValue(rule, out pin)) pins[rule] = pin = new PinnedTitle(rule, title, IsContinuous(config, rule, chId, docs)); - if (hint == LibraryRuleKind.Ignore) + if (LibraryRuleKind.IsNotVideoLibrary(hint)) { - // Folder rule: not library material (extras, trailers...) + // Folder rule: not library material (extras, trailers, audiobooks...) var file = NewFile(chId, doc, old, MediaNameParser.Parse(doc.Name, doc.FilterPath), null, hint, null); file.Status = LibraryFileStatus.Ignored; ignored.Add(file); diff --git a/Test/Audiobooks/AudiobooksTest.cs b/Test/Audiobooks/AudiobooksTest.cs new file mode 100644 index 0000000..d8d9213 --- /dev/null +++ b/Test/Audiobooks/AudiobooksTest.cs @@ -0,0 +1,500 @@ +using System.Collections.Concurrent; +using System.Reflection; +using System.Text; +using Microsoft.Extensions.Logging.Abstractions; +using TelegramDownloader.Data; +using TelegramDownloader.Data.db; +using TelegramDownloader.Models; +using TelegramDownloader.Models.Api; +using TelegramDownloader.Models.Audiobooks; +using TelegramDownloader.Models.Library; +using TelegramDownloader.Services.Audiobooks; +using TelegramDownloader.Services.Library; +using Test.Library; + +namespace Test.Audiobooks +{ + /// What audiobook folder and file names say. + public class AudiobookNamesTest + { + [Test] + public void Author_and_title() + { + var p = AudiobookNames.Parse("Brandon Sanderson - El imperio final"); + Assert.That((p.Author, p.Title), Is.EqualTo(("Brandon Sanderson", "El imperio final"))); + } + + [Test] + public void Author_series_number_and_title() + { + var p = AudiobookNames.Parse("Brandon Sanderson - Nacidos de la bruma 02 - El Pozo de la Ascensión"); + Assert.That((p.Author, p.Series, p.Sequence, p.Title), Is.EqualTo(("Brandon Sanderson", "Nacidos de la bruma", "2", "El Pozo de la Ascensión"))); + } + + [Test] + public void Narrator_year_and_noise_are_taken_out() + { + var p = AudiobookNames.Parse("Ken Follett - Los pilares de la Tierra (2015) (Narrado por Juan Magraner) [64kbps].m4b"); + Assert.That((p.Author, p.Title, p.Narrator, p.Year), Is.EqualTo(("Ken Follett", "Los pilares de la Tierra", "Juan Magraner", 2015))); + } + + [Test] + public void A_leading_number_is_the_order_in_the_series_of_the_folder_above() + { + var p = AudiobookNames.Parse("03. La Era de los Héroes", "Nacidos de la bruma"); + Assert.That((p.Title, p.Sequence, p.Series), Is.EqualTo(("La Era de los Héroes", "3", "Nacidos de la bruma"))); + } + + [Test] + public void The_parent_folder_is_context_unless_generic() + { + Assert.That(AudiobookNames.Parse("Dune", "Frank Herbert").Context, Is.EqualTo("Frank Herbert")); + Assert.That(AudiobookNames.Parse("Dune", "Audiolibros").Context, Is.Null); + } + + [Test] + public void Parts_of_one_book_share_a_key() + { + Assert.That(AudiobookNames.PartKey("Dune - Parte 1.m4b"), Is.EqualTo(AudiobookNames.PartKey("Dune - Parte 2.m4b"))); + Assert.That(AudiobookNames.PartKey("Dune (CD1).mp3"), Is.EqualTo(AudiobookNames.PartKey("Dune (CD2).mp3"))); + Assert.That(AudiobookNames.PartKey("Harry Potter 1.mp3"), Is.Not.EqualTo(AudiobookNames.PartKey("Harry Potter 2.mp3"))); + } + + [TestCase("CD1", true)] + [TestCase("Disco 02", true)] + [TestCase("Parte_3", true)] + [TestCase("El imperio final", false)] + public void Disc_folders(string name, bool disc) => Assert.That(AudiobookNames.IsDiscFolder(name), Is.EqualTo(disc)); + + [Test] + public void Natural_order_puts_2_before_10() + { + var names = new[] { "10.mp3", "2.mp3", "1.mp3" }.OrderBy(n => n, Comparer.Create(AudiobookNames.NaturalCompare)).ToList(); + Assert.That(names, Is.EqualTo(new[] { "1.mp3", "2.mp3", "10.mp3" })); + } + + [Test] + public void Chapter_titles_from_track_names() + { + Assert.That(AudiobookNames.ChapterTitleFromFile("03 - La huida.mp3", 2), Is.EqualTo("La huida")); + Assert.That(AudiobookNames.ChapterTitleFromFile("03.mp3", 2), Is.EqualTo("Capítulo 3")); + } + + [Test] + public void Audiobook_folders_are_a_hint_for_the_library() + { + Assert.That(LibraryFolderRules.HintFromPath("/Audiolibros/Autor/Libro/"), Is.EqualTo(LibraryRuleKind.Audiobook)); + Assert.That(LibraryRuleKind.IsNotVideoLibrary(LibraryRuleKind.Audiobook), Is.True); + } + } + + /// Which audio files are audiobooks and how they make books. + public class AudiobookGrouperTest + { + private static BsonFileManagerModel File(string name, string folder) => new() + { + Id = MongoDB.Bson.ObjectId.GenerateNewId().ToString(), + Name = name, + IsFile = true, + Type = Path.GetExtension(name), + FilterPath = folder, + Size = 100, + MessageId = 1 + }; + + [Test] + public void A_folder_is_a_book_and_its_disc_folders_too() + { + var groups = AudiobookGrouper.Group(new GeneralConfig(), 1, new[] + { + File("02.mp3", "/Audiolibros/Brandon Sanderson/El imperio final/CD1/"), + File("01.mp3", "/Audiolibros/Brandon Sanderson/El imperio final/CD1/"), + File("01.mp3", "/Audiolibros/Brandon Sanderson/El imperio final/CD2/") + }); + Assert.That(groups, Has.Count.EqualTo(1)); + var book = groups[0]; + Assert.That((book.Name, book.Context, book.FolderPath), Is.EqualTo(("El imperio final", "Brandon Sanderson", "/Audiolibros/Brandon Sanderson/El imperio final/"))); + Assert.That(book.Files.Select(f => f.FilterPath + f.Name), Is.EqualTo(new[] + { + "/Audiolibros/Brandon Sanderson/El imperio final/CD1/01.mp3", + "/Audiolibros/Brandon Sanderson/El imperio final/CD1/02.mp3", + "/Audiolibros/Brandon Sanderson/El imperio final/CD2/01.mp3" + })); + } + + [Test] + public void Files_in_the_root_are_books_and_their_parts_join() + { + var groups = AudiobookGrouper.Group(new GeneralConfig(), 1, new[] + { + File("Dune - Parte 1.mp3", "/Audiobooks/"), + File("Dune - Parte 2.mp3", "/Audiobooks/"), + File("Fundación.mp3", "/Audiobooks/") + }); + Assert.That(groups.Select(g => g.Files.Count).OrderBy(c => c), Is.EqualTo(new[] { 1, 2 })); + Assert.That(groups.All(g => g.Context == null), Is.True); + } + + [Test] + public void Music_is_not_an_audiobook_but_m4b_files_are_anywhere() + { + var groups = AudiobookGrouper.Group(new GeneralConfig(), 1, new[] + { + File("Canción.mp3", "/Música/Disco/"), + File("Libro suelto.m4b", "/Varios/"), + File("Otro.m4b", "/Varios/") + }); + Assert.That(groups.Select(g => g.Name).OrderBy(n => n), Is.EqualTo(new[] { "Libro suelto.m4b", "Otro.m4b" })); + } + + [Test] + public void Folder_rules_decide() + { + var config = new GeneralConfig + { + LibraryFolderRules = new List + { + new() { ChannelId = 1, Path = "/Lecturas/", Kind = LibraryRuleKind.Audiobook }, + new() { ChannelId = 1, Path = "/Audiolibros/Muestras/", Kind = LibraryRuleKind.Ignore } + } + }; + var groups = AudiobookGrouper.Group(config, 1, new[] + { + File("01.mp3", "/Lecturas/Rayuela/"), + File("muestra.mp3", "/Audiolibros/Muestras/"), + File("muestra.m4b", "/Audiolibros/Muestras/") + }); + Assert.That(groups.Select(g => g.Name), Is.EqualTo(new[] { "Rayuela" })); + } + } + + /// Picking the right book among the provider results. + public class AudiobookMatcherTest + { + private static BookCandidate Book(string title, params string[] authors) => new() { Provider = "p", ProviderId = title, Title = title, Authors = authors.ToList() }; + + [Test] + public void The_title_and_author_that_agree_win() + { + var parsed = AudiobookNames.Parse("Brandon Sanderson - El imperio final"); + var best = AudiobookMatcher.Best(parsed, new[] + { + Book("El imperio final", "Otro Autor"), + Book("El imperio final (Nacidos de la bruma 1)", "Brandon Sanderson"), + Book("El héroe de las eras", "Brandon Sanderson") + }); + Assert.That(best!.Candidate.Authors, Is.EqualTo(new[] { "Brandon Sanderson" })); + Assert.That(best.Status, Is.EqualTo(LibraryFileStatus.Matched)); + } + + [Test] + public void Title_then_author_also_works() + { + var parsed = AudiobookNames.Parse("Dune - Frank Herbert"); + var score = AudiobookMatcher.Score(parsed, Book("Dune", "Frank Herbert")); + Assert.That(score, Is.GreaterThanOrEqualTo(LibraryMatcher.MatchedThreshold)); + } + + [Test] + public void A_different_book_is_not_matched() + { + var parsed = AudiobookNames.Parse("Ken Follett - Los pilares de la Tierra"); + var best = AudiobookMatcher.Best(parsed, new[] { Book("Un mundo sin fin", "Ken Follett") }); + Assert.That(best!.Status, Is.EqualTo(LibraryFileStatus.Unmatched)); + } + + [Test] + public void Other_providers_only_fill_the_gaps() + { + var book = new Audiobook { ParsedTitle = "Dune" }; + AudiobookMatcher.Clear(book); + AudiobookMatcher.Apply(book, new BookCandidate { Provider = "itunes", ProviderId = "1", Title = "Dune", Authors = new() { "Frank Herbert" }, CoverUrl = "https://a/c.jpg" }, true); + AudiobookMatcher.Apply(book, new BookCandidate { Provider = "audible", ProviderId = "B0", Asin = "B0", Title = "Dune (edición)", Narrators = new() { "Narrador" }, CoverUrl = "https://b/c.jpg" }, false); + Assert.That((book.Title, book.CoverUrl, book.Narrators.Single(), book.Asin), Is.EqualTo(("Dune", "https://a/c.jpg", "Narrador", "B0"))); + } + } + + /// Chapters and durations read from the files themselves. + public class ChapterReaderTest + { + private static byte[] U32(long v) => new[] { (byte)(v >> 24), (byte)(v >> 16), (byte)(v >> 8), (byte)v }; + private static byte[] U16(int v) => new[] { (byte)(v >> 8), (byte)v }; + private static byte[] U64(long v) => U32(v >> 32).Concat(U32(v & 0xFFFFFFFF)).ToArray(); + private static byte[] Box(string type, params byte[][] body) + { + var content = body.SelectMany(b => b).ToArray(); + return U32(8 + content.Length).Concat(Encoding.ASCII.GetBytes(type)).Concat(content).ToArray(); + } + private static byte[] Mvhd(long timescale, long duration) => Box("mvhd", new byte[4], U32(0), U32(0), U32(timescale), U32(duration), new byte[80]); + + [Test] + public async Task Nero_chapters_of_an_m4b() + { + var chpl = Box("chpl", new byte[] { 1, 0, 0, 0 }, new byte[4], new byte[] { 2 }, + U64(0), new[] { (byte)5 }, Encoding.UTF8.GetBytes("Uno 1"), + U64(600_000_000), new[] { (byte)3 }, Encoding.UTF8.GetBytes("Dos")); + var file = Box("ftyp", Encoding.ASCII.GetBytes("M4B "), new byte[4]) + .Concat(Box("moov", Mvhd(1000, 120_000), Box("udta", chpl))).ToArray(); + + var found = await ChapterReader.ReadAsync(RangeReader.FromBytes(file), ".m4b", CancellationToken.None); + Assert.That(found!.DurationMs, Is.EqualTo(120_000)); + Assert.That(found.Chapters.Select(c => (c.Title, c.StartMs, c.EndMs)), Is.EqualTo(new[] { ("Uno 1", 0L, 60_000L), ("Dos", 60_000L, 120_000L) })); + } + + [Test] + public async Task QuickTime_chapter_track_with_moov_at_the_end() + { + var ftyp = Box("ftyp", Encoding.ASCII.GetBytes("M4A "), new byte[4]); + var samples = new[] { "Prólogo", "Capítulo uno" }.Select(t => U16(Encoding.UTF8.GetByteCount(t)).Concat(Encoding.UTF8.GetBytes(t)).ToArray()).ToArray(); + var mdat = Box("mdat", samples); + long firstSample = ftyp.Length + 8; + var textTrak = Box("trak", + Box("tkhd", new byte[4], U32(0), U32(0), U32(2), new byte[68]), + Box("mdia", + Box("mdhd", new byte[4], U32(0), U32(0), U32(1000), U32(90_000), new byte[4]), + Box("minf", Box("stbl", + Box("stts", new byte[4], U32(2), U32(1), U32(30_000), U32(1), U32(60_000)), + Box("stsz", new byte[4], U32(0), U32(2), U32(samples[0].Length), U32(samples[1].Length)), + Box("stsc", new byte[4], U32(1), U32(1), U32(2), U32(1)), + Box("stco", new byte[4], U32(1), U32(firstSample)))))); + var audioTrak = Box("trak", Box("tkhd", new byte[4], U32(0), U32(0), U32(1), new byte[68]), Box("tref", Box("chap", U32(2)))); + var file = ftyp.Concat(mdat).Concat(Box("moov", Mvhd(1000, 90_000), audioTrak, textTrak)).ToArray(); + + var found = await ChapterReader.ReadAsync(RangeReader.FromBytes(file), ".m4a", CancellationToken.None); + Assert.That(found!.Chapters.Select(c => (c.Title, c.StartMs, c.EndMs)), Is.EqualTo(new[] { ("Prólogo", 0L, 30_000L), ("Capítulo uno", 30_000L, 90_000L) })); + } + + [Test] + public async Task Id3_chapters_of_an_mp3() + { + static byte[] Frame(string id, byte[] body) => Encoding.ASCII.GetBytes(id).Concat(U32(body.Length)).Concat(new byte[2]).Concat(body).ToArray(); + static byte[] Chap(string id, long start, long end, string title) => Frame("CHAP", + Encoding.ASCII.GetBytes(id + "\0").Concat(U32(start)).Concat(U32(end)).Concat(U32(0xFFFFFFFF)).Concat(U32(0xFFFFFFFF)) + .Concat(Frame("TIT2", new byte[] { 3 }.Concat(Encoding.UTF8.GetBytes(title)).ToArray())).ToArray()); + var frames = Chap("c1", 5_000, 9_000, "Segundo").Concat(Chap("c0", 0, 5_000, "Primero")).ToArray(); + var size = frames.Length; + var header = new byte[] { (byte)'I', (byte)'D', (byte)'3', 3, 0, 0, (byte)((size >> 21) & 0x7F), (byte)((size >> 14) & 0x7F), (byte)((size >> 7) & 0x7F), (byte)(size & 0x7F) }; + var file = header.Concat(frames).Concat(new byte[1000]).ToArray(); + + var found = await ChapterReader.ReadAsync(RangeReader.FromBytes(file), ".mp3", CancellationToken.None); + Assert.That(found!.Chapters.Select(c => (c.Title, c.StartMs)), Is.EqualTo(new[] { ("Primero", 0L), ("Segundo", 5_000L) })); + } + + [Test] + public async Task Reading_stops_at_its_budget() + { + var calls = 0; + var reader = new RangeReader(100L * RangeReader.BlockSize, (o, c, _) => { calls++; return Task.FromResult(new byte[c]); }) { Budget = 3 }; + Assert.ThrowsAsync(async () => + { + for (long i = 0; i < 10; i++) await reader.ReadAsync(i * RangeReader.BlockSize, 4, CancellationToken.None); + }); + Assert.That(calls, Is.EqualTo(3)); + await Task.CompletedTask; + } + } + + /// In-memory audiobook storage. + public class FakeAudiobookDb : IAudiobookDbService + { + public ConcurrentDictionary Books { get; } = new(); + public ConcurrentDictionary Progress { get; } = new(); + public AudiobookScanState? State; + + public Task EnsureIndexes() => Task.CompletedTask; + public Task GetBook(string id) => Task.FromResult(Books.GetValueOrDefault(id)); + public Task> GetBooks(IEnumerable ids) => Task.FromResult(ids.Select(i => Books.GetValueOrDefault(i)).Where(b => b != null).ToList()!); + public Task> GetAllBooks() => Task.FromResult(Books.Values.ToList()); + public Task> GetBooksByChannel(long channelId) => Task.FromResult(Books.Values.Where(b => b.ChannelId == channelId).ToList()); + public Task UpsertBook(Audiobook book) { Books[book.Id] = book; return Task.CompletedTask; } + public Task DeleteBooks(IEnumerable ids) { foreach (var i in ids) Books.TryRemove(i, out _); return Task.CompletedTask; } + public Task GetProgress(string bookId) => Task.FromResult(Progress.GetValueOrDefault(bookId)); + public Task> GetAllProgress() => Task.FromResult(Progress.Values.ToList()); + public Task UpsertProgress(AudiobookProgress progress) { Progress[progress.Id] = progress; return Task.CompletedTask; } + public Task DeleteProgress(string bookId) { Progress.TryRemove(bookId, out _); return Task.CompletedTask; } + public Task GetScanState() => Task.FromResult(State); + public Task SaveScanState(AudiobookScanState state) { State = state.Clone(); return Task.CompletedTask; } + } + + public class FakeBookProvider : IBookProvider + { + public List Catalogue { get; } = new(); + public int Searches; + public string Id => "fake"; + public ProviderDescriptor Descriptor { get; } = new() { Id = "fake", Name = "Fake" }; + + public Task> SearchAsync(string title, string? author, CancellationToken ct) + { + Interlocked.Increment(ref Searches); + var q = MediaNameParser.NormalizeForMatch(title); + return Task.FromResult>(Catalogue.Where(c => MediaNameParser.NormalizeForMatch(c.Title).Contains(q) || q.Contains(MediaNameParser.NormalizeForMatch(c.Title))).ToList()); + } + + public Task GetAsync(string providerId, CancellationToken ct) => Task.FromResult(Catalogue.FirstOrDefault(c => c.ProviderId == providerId)); + } + + public class FakeBookSource : IBookProviderSource + { + public List Providers { get; } = new(); + public IReadOnlyList GetEnabled() => Providers; + public IBookProvider? Get(string id) => Providers.FirstOrDefault(p => p.Id == id); + } + + /// Telegram without a session: the scan cannot read the files. + public class OfflineTelegram : DispatchProxy + { + protected override object? Invoke(MethodInfo? method, object?[]? args) => method!.Name switch + { + nameof(ITelegramService.checkUserLogin) => false, + _ => throw new NotSupportedException(method.Name) + }; + } + + /// The whole scan, the catalogue and the progress, over in-memory storage. + public class AudiobookScanTest + { + private GeneralConfig _previous = null!; + private FakeLibraryDb _lib = null!; + private FakeAudiobookDb _db = null!; + private FakeBookProvider _provider = null!; + private AudiobookScanService _scan = null!; + private AudiobookService _service = null!; + + [SetUp] + public void SetUp() + { + _previous = GeneralConfigStatic.config; + GeneralConfigStatic.config = new GeneralConfig { AudiobooksEnabled = true }; + _lib = new FakeLibraryDb(); + _db = new FakeAudiobookDb(); + _provider = new FakeBookProvider(); + _provider.Catalogue.Add(new BookCandidate { Provider = "fake", ProviderId = "b1", Title = "El imperio final", Authors = new() { "Brandon Sanderson" }, Narrators = new() { "Alguien" }, CoverUrl = "https://is1-ssl.mzstatic.com/c.jpg" }); + _provider.Catalogue.Add(new BookCandidate { Provider = "fake", ProviderId = "b2", Title = "Dune", Authors = new() { "Frank Herbert" } }); + var source = new FakeBookSource(); + source.Providers.Add(_provider); + var telegram = DispatchProxy.Create(); + _scan = new AudiobookScanService(_lib, _db, source, new AudnexusClient(new HttpClient(), NullLogger.Instance), telegram, NullLogger.Instance); + _service = new AudiobookService(_db, source, _scan); + + _lib.AddChannelFile("100", "01 - Prólogo.mp3", "/Audiolibros/Brandon Sanderson/El imperio final/"); + _lib.AddChannelFile("100", "02 - Capítulo uno.mp3", "/Audiolibros/Brandon Sanderson/El imperio final/"); + _lib.AddChannelFile("100", "Frank Herbert - Dune.m4b", "/Varios/"); + _lib.AddChannelFile("100", "Canción.mp3", "/Música/"); + } + + [TearDown] + public void TearDown() => GeneralConfigStatic.config = _previous; + + private async Task ScanAsync(bool force = false) + { + var state = new AudiobookScanState { Running = true, Force = force }; + await _scan.ScanAsync(state, new List { "100" }, CancellationToken.None); + } + + [Test] + public async Task Books_are_found_and_identified() + { + await ScanAsync(); + var books = _db.Books.Values.OrderBy(b => b.Title).ToList(); + Assert.That(books.Select(b => (b.Title, b.Status)), Is.EqualTo(new[] { ("Dune", "matched"), ("El imperio final", "matched") })); + var empire = books[1]; + Assert.That(empire.Narrators, Is.EqualTo(new[] { "Alguien" })); + Assert.That(empire.Chapters.Select(c => c.Title), Is.EqualTo(new[] { "Prólogo", "Capítulo uno" })); + Assert.That(empire.ChapterSource, Is.EqualTo(ChapterSource.Files)); + Assert.That(empire.DetailsRead, Is.False, "without a Telegram session the details are read on a later scan"); + Assert.That(_db.State!.BooksFound, Is.EqualTo(2)); + } + + [Test] + public async Task A_second_scan_leaves_identified_books_alone_and_removes_gone_ones() + { + await ScanAsync(); + var searches = _provider.Searches; + _lib.Channels["100"].RemoveAll(d => d.Name.EndsWith(".m4b")); + await ScanAsync(); + Assert.That(_provider.Searches, Is.EqualTo(searches)); + Assert.That(_db.Books.Values.Select(b => b.Title), Is.EqualTo(new[] { "El imperio final" })); + } + + [Test] + public async Task A_book_identified_by_hand_stays() + { + await ScanAsync(); + var dune = _db.Books.Values.Single(b => b.Title == "Dune"); + await _service.IdentifyAsync(dune.Id, "fake", "b1", CancellationToken.None); + await ScanAsync(force: true); + Assert.That(_db.Books[dune.Id].Title, Is.EqualTo("El imperio final")); + Assert.That(_db.Books[dune.Id].MatchSource, Is.EqualTo(LibraryMatchSource.Manual)); + } + + [Test] + public async Task Progress_is_on_the_book_timeline_and_finishes_near_the_end() + { + await ScanAsync(); + var book = _db.Books.Values.First(); + book.DurationMs = 3_600_000; + await _db.UpsertBook(book); + + var p = await _service.SetProgressAsync(book.Id, new AudiobookProgressRequest { PositionMs = 1_800_000, Speed = 1.5 }); + Assert.That((p!.Progress, p.Finished, p.Speed), Is.EqualTo((0.5, false, 1.5))); + p = await _service.SetProgressAsync(book.Id, new AudiobookProgressRequest { PositionMs = 3_590_000 }); + Assert.That(p!.Finished, Is.True); + + var continuing = await _service.ContinueAsync(10, false, "http://x"); + Assert.That(continuing, Is.Empty, "a finished book is not being listened to"); + } + + [Test] + public async Task Bookmarks_are_kept_in_order() + { + await ScanAsync(); + var book = _db.Books.Values.First(); + await _service.AddBookmarkAsync(book.Id, new AudiobookBookmarkRequest { PositionMs = 50_000, Note = " frase " }); + var second = await _service.AddBookmarkAsync(book.Id, new AudiobookBookmarkRequest { PositionMs = 10_000 }); + var detail = await _service.GetAsync(book.Id, "http://x"); + Assert.That(detail!.Bookmarks.Select(b => (b.PositionMs, b.Note)), Is.EqualTo(new[] { (10_000L, (string?)null), (50_000L, "frase") })); + Assert.That(await _service.DeleteBookmarkAsync(book.Id, second!.Id), Is.True); + } + + [Test] + public async Task The_detail_has_track_urls_and_the_cover_through_the_server() + { + await ScanAsync(); + var book = _db.Books.Values.Single(b => b.Title == "El imperio final"); + var detail = await _service.GetAsync(book.Id, "http://srv"); + Assert.That(detail!.Tracks.Select(t => t.Index), Is.EqualTo(new[] { 0, 1 })); + Assert.That(detail.Tracks[0].PlaybackUrl, Does.StartWith("http://srv/api/v1/channels/100/files/")); + Assert.That(detail.CoverUrl, Does.StartWith("http://srv/api/v1/library/images/")); + } + + [Test] + public async Task Authors_and_series_lists() + { + await ScanAsync(); + var authors = await _service.AuthorsAsync(false, "http://x"); + Assert.That(authors.Select(a => (a.Name, a.Count)), Is.EqualTo(new[] { ("Brandon Sanderson", 1), ("Frank Herbert", 1) })); + } + } + + /// Chapters on the book timeline. + public class AudiobookChaptersTest + { + [Test] + public void Embedded_chapters_of_several_files_follow_each_other() + { + var book = new Audiobook + { + Tracks = new() + { + new AudiobookTrack { FileId = "a", FileName = "Parte 1.m4b", DurationMs = 100 }, + new AudiobookTrack { FileId = "b", FileName = "Parte 2.m4b", DurationMs = 50 } + } + }; + var chapters = AudiobookScanService.Combine(book, new Dictionary> + { + ["a"] = new() { new() { Title = "Uno", StartMs = 0, EndMs = 60 }, new() { Title = "Dos", StartMs = 60, EndMs = 100 } } + }); + Assert.That(chapters.Select(c => (c.Title, c.StartMs, c.EndMs)), Is.EqualTo(new[] { ("Uno", 0L, 60L), ("Dos", 60L, 100L), ("Parte 2", 100L, 150L) })); + } + } +} diff --git a/Test/MobileBulkAndSearchTest.cs b/Test/MobileBulkAndSearchTest.cs index d407e5e..9ef4dae 100644 --- a/Test/MobileBulkAndSearchTest.cs +++ b/Test/MobileBulkAndSearchTest.cs @@ -152,7 +152,8 @@ public void CapabilitiesAdvertiseExactFeatureSet() "playlist.bulkAdd", "search.global", "channels.refresh", "channels.refreshProgress", "stream.localTranscode", "events.hub", "search.v1", "files.thumbnails", "files.content", "files.preload", "local.copyMove", "shares.browse", "setup.write", "transfers.remove", "system.admin", "webAuth.passkeys", "files.deleteOperations", "messages.content", "transfers.pauseUploads", "library.seriesFolders", "library.scanFolders", "messages.browse", "channels.refreshSequential", - "player.sync", "audio.transcode", "library.fileFilters", "files.cue", "files.audioInfo", "local.archives", "transfers.autoExtract" + "player.sync", "audio.transcode", "library.fileFilters", "files.cue", "files.audioInfo", "local.archives", "transfers.autoExtract", + "audiobooks" })); } }