diff --git a/docs/backend/podcast-transcript-request.md b/docs/backend/podcast-transcript-request.md index d6f857e..87e13a8 100644 --- a/docs/backend/podcast-transcript-request.md +++ b/docs/backend/podcast-transcript-request.md @@ -44,3 +44,15 @@ If the backend prefers a separate door (for example the studio inspector load it lazily), or different field names, the frontend changes in one place: the type above and the `transcript` prop passed to `PodcastPlayer`. + +## Related: the audio door cannot be seeked + +`GET /podcast/jobs/{id}/audio` answers `200` with `Transfer-Encoding: chunked`, +no `Content-Length`, no `Accept-Ranges`, and ignores a `Range` header +(checked 2026-09-23). Browsers then report `seekable` as `[0, 0]` and every +seek snaps back to 0:00. The frontend works around it by loading the whole +file once (`getPodcastJobAudioBlob`) and seeking in a local copy, which costs +a full download before the first seek. Answering `Range` with `206 Partial +Content` (plus `Accept-Ranges: bytes` and `Content-Length` on the full +response) would make seeking instant; the player already prefers the stream +whenever the browser says it can seek there. diff --git a/src/api/__tests__/podcast/podcast.test.ts b/src/api/__tests__/podcast/podcast.test.ts index 286cd49..461d7e2 100644 --- a/src/api/__tests__/podcast/podcast.test.ts +++ b/src/api/__tests__/podcast/podcast.test.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { + getPodcastJobAudioBlob, getPodcastJobById, getPodcastJobResultById, listPodcastJobs, @@ -7,7 +8,7 @@ import { postPodcastJob, postPodcastJobCancel, } from "../../podcast"; -import { lastFetchCall, mockFetchSuccess } from "../helpers/mock-fetch"; +import { lastFetchCall, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch"; describe("podcast API", () => { afterEach(() => { @@ -86,6 +87,18 @@ describe("podcast API", () => { expect(podcastAudioUrl("j 1")).toBe("/api/podcast/jobs/j%201/audio"); }); + it("getPodcastJobAudioBlob loads the whole episode from the same door", async () => { + const blob = new Blob(["mp3"], { type: "audio/mpeg" }); + mockFetchBlob(blob); + + const result = await getPodcastJobAudioBlob("j 1"); + expect(result.type).toBe("audio/mpeg"); + + const [url, init] = lastFetchCall(); + expect(url).toBe("/api/podcast/jobs/j%201/audio"); + expect(init?.method ?? "GET").toBe("GET"); + }); + it("listPodcastJobs asks for the whole history when no note is given", async () => { mockFetchSuccess({ items: [], total: 0, limit: 10, offset: 0 }); diff --git a/src/api/podcast/getPodcastJobAudioBlob.ts b/src/api/podcast/getPodcastJobAudioBlob.ts new file mode 100644 index 0000000..f15c52d --- /dev/null +++ b/src/api/podcast/getPodcastJobAudioBlob.ts @@ -0,0 +1,10 @@ +import { blobClient } from "../client"; + +/** + * The whole produced episode as one Blob. The audio door streams chunked with + * no length and ignores `Range`, so a browser cannot seek on the stream; the + * player loads this once and seeks inside a local object URL instead. + */ +export function getPodcastJobAudioBlob(jobId: string, signal?: AbortSignal): Promise { + return blobClient(`/podcast/jobs/${encodeURIComponent(jobId)}/audio`, signal); +} diff --git a/src/api/podcast/index.ts b/src/api/podcast/index.ts index f1571f4..20c1ee9 100644 --- a/src/api/podcast/index.ts +++ b/src/api/podcast/index.ts @@ -4,3 +4,4 @@ export * from "./getPodcastJobById"; export * from "./getPodcastJobResultById"; export * from "./postPodcastJobCancel"; export * from "./podcastAudioUrl"; +export * from "./getPodcastJobAudioBlob"; diff --git a/src/components/layout/app-shell.tsx b/src/components/layout/app-shell.tsx index d0c76c0..0886ae8 100644 --- a/src/components/layout/app-shell.tsx +++ b/src/components/layout/app-shell.tsx @@ -19,6 +19,7 @@ import { IconPanelLeft, IconSparkles } from "@/components/ui/icons"; import { Toaster } from "@/components/ui/toast"; import { useAuth } from "@/stores/auth-context"; import { useModules } from "@/stores/modules-context"; +import { useSchool } from "@/stores/school-context"; import { celebiPanelOpen, openCelebiPanel, setCelebiPanelOpen } from "@/stores/celebi-panel"; import { commandPaletteOpen, openCommandPalette, setCommandPaletteOpen } from "@/stores/command-palette"; import { quickActionsSuppressed } from "@/stores/quick-actions"; @@ -35,6 +36,7 @@ export function AppShell(props: ParentProps) { const auth = useAuth(); const prefs = usePreferences(); const t = useT(); + const school = useSchool(); const modules = useModules(); const navigate = useNavigate(); const [mobileOpen, setMobileOpen] = createSignal(false); @@ -112,13 +114,18 @@ export function AppShell(props: ParentProps) { - {t("app.name")} + + {t("app.name")} + + {(name) => {name()}} + + diff --git a/src/components/layout/nav-bar.tsx b/src/components/layout/nav-bar.tsx index e497195..c840c1e 100644 --- a/src/components/layout/nav-bar.tsx +++ b/src/components/layout/nav-bar.tsx @@ -8,10 +8,12 @@ import { ThemeModeControl } from "@/components/layout/theme-mode-control"; import { LocaleSwitcher } from "@/components/layout/locale-switcher"; import { IconMenu, IconX } from "@/components/ui/icons"; import { useAuth } from "@/stores/auth-context"; +import { useSchool } from "@/stores/school-context"; import { useT } from "@/stores/preferences-context"; export function NavBar() { const auth = useAuth(); + const school = useSchool(); const t = useT(); const [mobileOpen, setMobileOpen] = createSignal(false); @@ -36,8 +38,11 @@ export function NavBar() { - - {t("app.name")} + + {t("app.name")} + + {school.name()} + diff --git a/src/components/notes/podcast-history.test.tsx b/src/components/notes/podcast-history.test.tsx index 9bb587c..74cd497 100644 --- a/src/components/notes/podcast-history.test.tsx +++ b/src/components/notes/podcast-history.test.tsx @@ -8,6 +8,7 @@ import { PreferencesProvider } from "@/stores/preferences-context"; const podcastApi = vi.hoisted(() => ({ listPodcastJobs: vi.fn(), podcastAudioUrl: vi.fn((jobId: string) => `/api/podcast/jobs/${encodeURIComponent(jobId)}/audio`), + getPodcastJobAudioBlob: vi.fn(), })); vi.mock("@/api/podcast", () => podcastApi); @@ -51,18 +52,27 @@ describe("PodcastHistory", () => { )); - it("renders a finished row's title, state and duration, and plays it by job id", async () => { - podcastApi.listPodcastJobs.mockResolvedValue(page([job({})])); + it("names rows by narration, selects the newest finished one and plays a picked row", async () => { + podcastApi.listPodcastJobs.mockResolvedValue( + page([job({ job_id: "job-2", format: "ogrenci_hoca" }), job({ job_id: "job-1" })]), + ); renderHistory("note-1"); - await waitFor(() => expect(screen.getByText("Hücre")).toBeTruthy()); - expect(screen.getByText("Hazır")).toBeTruthy(); - expect(screen.getByText("12:34")).toBeTruthy(); + // Scoped to one note, the note's title is not repeated on every row. + await waitFor(() => expect(screen.getAllByText("Öğrenci ve öğretmen").length).toBeGreaterThan(0)); + expect(screen.queryByText("Hücre")).toBeNull(); + expect(screen.getAllByText("12:34").length).toBeGreaterThan(0); + // One player, on the newest finished episode, not playing on its own. + expect(document.querySelectorAll("audio")).toHaveLength(1); + expect(document.querySelector("audio")?.getAttribute("src")).toBe("/api/podcast/jobs/job-2/audio"); - fireEvent.click(screen.getByRole("button", { name: "Bölümü oynat" })); - expect(podcastApi.podcastAudioUrl).toHaveBeenCalledWith("job-1"); - expect(document.querySelector("audio")?.getAttribute("src")).toBe("/api/podcast/jobs/job-1/audio"); + fireEvent.click(screen.getByRole("button", { name: /^Bölümü oynat: Düz okuma/ })); + + await waitFor(() => + expect(document.querySelector("audio")?.getAttribute("src")).toBe("/api/podcast/jobs/job-1/audio"), + ); + expect(document.querySelectorAll("audio")).toHaveLength(1); }); it("gives a non-done row no play control", async () => { @@ -82,10 +92,11 @@ describe("PodcastHistory", () => { renderHistory("note-1"); - await waitFor(() => expect(screen.getByText("Hücre")).toBeTruthy()); - const link = screen.getByRole("link", { name: "Bölümü indir" }) as HTMLAnchorElement; - expect(link.getAttribute("href")).toBe("/api/podcast/jobs/job-1/audio"); - expect(link.getAttribute("download")).toBe("Hücre.mp3"); + await waitFor(() => expect(screen.getAllByRole("link", { name: "Bölümü indir" }).length).toBeGreaterThan(0)); + for (const link of screen.getAllByRole("link", { name: "Bölümü indir" }) as HTMLAnchorElement[]) { + expect(link.getAttribute("href")).toBe("/api/podcast/jobs/job-1/audio"); + expect(link.getAttribute("download")).toBe("Hücre.mp3"); + } }); it("gives a non-done row no download control", async () => { @@ -140,12 +151,13 @@ describe("PodcastHistory", () => { expect(podcastApi.listPodcastJobs).not.toHaveBeenCalled(); }); - it("falls back to the note id when the note is gone", async () => { + it("falls back to the note id for a download when the note is gone", async () => { podcastApi.listPodcastJobs.mockResolvedValue(page([job({ source_id: "note-gone", source_title: null })])); renderHistory("note-1"); - await waitFor(() => expect(screen.getByText("note-gone")).toBeTruthy()); + await waitFor(() => expect(screen.getAllByRole("link", { name: "Bölümü indir" }).length).toBeGreaterThan(0)); + expect(screen.getAllByRole("link", { name: "Bölümü indir" })[0].getAttribute("download")).toBe("note-gone.mp3"); }); it("refetches when the panel signals a finished generation", async () => { @@ -164,46 +176,43 @@ describe("PodcastHistory", () => { }); it("paginates the selected note's podcast history", async () => { - const first = job({ job_id: "job-1", source_title: "İlk bölüm" }); - const second = job({ job_id: "job-2", source_title: "İkinci bölüm" }); + const first = job({ job_id: "job-1", format: "duz_okuma" }); + const second = job({ job_id: "job-2", format: "tek_ogretici" }); podcastApi.listPodcastJobs .mockResolvedValueOnce(page([first], 11, 0)) .mockResolvedValueOnce(page([second], 11, 10)); renderHistory("note-1"); - await waitFor(() => expect(screen.getByText("İlk bölüm")).toBeTruthy()); + await waitFor(() => expect(screen.getAllByText("Düz okuma").length).toBeGreaterThan(0)); expect(screen.getByText("1 / 2")).toBeTruthy(); fireEvent.click(screen.getByRole("button", { name: "Sonraki" })); - await waitFor(() => expect(screen.getByText("İkinci bölüm")).toBeTruthy()); + await waitFor(() => expect(screen.getAllByText("Tek öğretici").length).toBeGreaterThan(0)); expect(podcastApi.listPodcastJobs).toHaveBeenLastCalledWith({ limit: 10, offset: 10, sourceId: "note-1" }); expect(screen.getByText("2 / 2")).toBeTruthy(); }); it("marks each episode with the narration the service settled on", async () => { podcastApi.listPodcastJobs.mockResolvedValue( - page([ - job({ job_id: "job-1", source_title: "Düz", format: "duz_okuma" }), - job({ job_id: "job-2", source_title: "İkili", format: "ogrenci_hoca" }), - ]), + page([job({ job_id: "job-1", format: "duz_okuma" }), job({ job_id: "job-2", format: "ogrenci_hoca" })]), ); renderHistory("note-1"); - await waitFor(() => expect(screen.getByText("Düz okuma")).toBeTruthy()); - expect(screen.getByText("Öğrenci ve öğretmen")).toBeTruthy(); + await waitFor(() => expect(screen.getAllByText("Düz okuma").length).toBeGreaterThan(0)); + expect(screen.getAllByText("Öğrenci ve öğretmen").length).toBeGreaterThan(0); }); - it("leaves a job the service has not settled a format for unmarked", async () => { + it("names an episode the service has not settled a format for plainly", async () => { podcastApi.listPodcastJobs.mockResolvedValue( page([job({ state: "queued", format: null, duration_secs: null, finished_at: null })]), ); renderHistory("note-1"); - await waitFor(() => expect(screen.getByText("Hücre")).toBeTruthy()); + await waitFor(() => expect(screen.getByText("Bölüm")).toBeTruthy()); expect(screen.queryByText("Düz okuma")).toBeNull(); }); }); diff --git a/src/components/notes/podcast-history.tsx b/src/components/notes/podcast-history.tsx index d50b12c..4880e08 100644 --- a/src/components/notes/podcast-history.tsx +++ b/src/components/notes/podcast-history.tsx @@ -1,20 +1,19 @@ import { For, Show, Suspense, createEffect, createMemo, createSignal } from "solid-js"; import { createResponsivePageSize } from "@/lib/create-page-size"; import { createResource } from "@/lib/create-resource"; -import { formatApiError } from "@/api/client"; +import { formatApiError, type PodcastJobSummary, type PodcastTranscriptSegment } from "@/api/client"; import type { MessageKey } from "@/i18n/messages"; import { listPodcastJobs, podcastAudioUrl } from "@/api/podcast"; import { Alert } from "@/components/ui/alert"; import { Badge } from "@/components/ui/badge"; -import { Button, buttonVariants } from "@/components/ui/button"; import { EmptyInline } from "@/components/ui/empty-inline"; import { PageSpinner } from "@/components/ui/page-spinner"; import { TablePagination } from "@/components/ui/table-pagination"; -import { IconDownload, IconPlay } from "@/components/ui/icons"; +import { IconDownload, IconPlay, IconWaveform } from "@/components/ui/icons"; import { PodcastPlayer } from "@/components/notes/podcast-player"; import { cn } from "@/lib/cn"; import { podcastDownloadFilename, usePodcastDownloadT } from "@/components/notes/podcast-download"; -import { formatDate, formatDurationClock } from "@/lib/format"; +import { formatDateTime, formatDurationClock } from "@/lib/format"; import { usePreferences, useT } from "@/stores/preferences-context"; const HISTORY_PAGE_SIZE = 10; @@ -29,18 +28,26 @@ const FORMAT_KEYS: Record = { }; /** - * The caller's own episodes, under the Ses Atölyesi panel. One-directional: - * the studio produces, this only reads. A finished episode plays through the - * same job-id audio door the panel's own player uses. + * The note's episodes: one player on top for the selected episode, and a + * plain list under it — narration, when, how long. A row is picked, not + * expanded, so there is only ever one player and one set of controls. * - * The list always follows the note selected in the studio. There is no second - * global-history scope here: the podcast tab is about the current note. + * The newest finished episode is selected on load (not played); a generation + * the panel just finished is selected as it lands. Unfinished rows stay in + * the list, muted, with their state instead of a player. */ -export function PodcastHistory(props: { noteId?: string; active?: boolean; refetchKey?: string | number }) { +export function PodcastHistory(props: { + noteId?: string; + active?: boolean; + refetchKey?: string | number; + /** The transcript of the episode the panel just produced, if the service sent one. */ + transcript?: { jobId: string; segments: PodcastTranscriptSegment[] } | null; +}) { const t = useT(); const downloadT = usePodcastDownloadT(); const { locale } = usePreferences(); - const [playing, setPlaying] = createSignal(""); + const [selected, setSelected] = createSignal(""); + const [autoplay, setAutoplay] = createSignal(false); const [page, setPage] = createSignal(0); const pageSize = createResponsivePageSize(HISTORY_PAGE_SIZE); const active = () => props.active !== false; @@ -49,6 +56,8 @@ export function PodcastHistory(props: { noteId?: string; active?: boolean; refet props.noteId; pageSize(); setPage(0); + setSelected(""); + setAutoplay(false); }); // The source is the scope string, not a fresh object: an identity-stable @@ -60,10 +69,15 @@ export function PodcastHistory(props: { noteId?: string; active?: boolean; refet ); // The panel bumps the key ("", then the job id) when a generation finishes; - // pull a fresh page so the episode it just produced appears. The history - // never starts work itself. + // pull a fresh page so the episode it just produced appears, and select it. createEffect(() => { - if (props.refetchKey) void refetch(); + const key = props.refetchKey; + if (!key) return; + void refetch(); + if (typeof key === "string") { + setSelected(key); + setAutoplay(false); + } }); const jobs = () => list()?.items ?? []; @@ -74,12 +88,18 @@ export function PodcastHistory(props: { noteId?: string; active?: boolean; refet if (page() > totalPages() - 1) setPage(totalPages() - 1); }); - const stateVariant = (state: string) => { - if (state === "done") return "success" as const; - if (state === "failed") return "destructive" as const; - if (state === "cancelled") return "secondary" as const; - return "warning" as const; - }; + // Nothing picked yet (or the pick left the page): fall back to the newest + // finished episode on screen. + createEffect(() => { + const rows = jobs(); + if (rows.some((row) => row.job_id === selected() && row.state === "done")) return; + const first = rows.find((row) => row.state === "done"); + // A just-finished job may not be on the refetched page yet; keep it picked. + const waitingForFresh = !!props.refetchKey && props.refetchKey === selected(); + if (first && !waitingForFresh) setSelected(first.job_id); + }); + const current = createMemo(() => jobs().find((row) => row.job_id === selected() && row.state === "done") ?? null); + const formatLabel = (format: string | null) => { if (!format) return ""; const key = FORMAT_KEYS[format]; @@ -91,12 +111,24 @@ export function PodcastHistory(props: { noteId?: string; active?: boolean; refet if (state === "cancelled") return t("podcast.history.state.cancelled"); return t("podcast.history.state.pending"); }; + const stateVariant = (state: string) => { + if (state === "failed") return "destructive" as const; + if (state === "cancelled") return "secondary" as const; + return "warning" as const; + }; + // Scoped to one note, every row narrates the same note — its title would + // only repeat; the narration names the episode instead. + const rowTitle = (row: PodcastJobSummary) => + props.noteId ? formatLabel(row.format) || t("podcast.history.episode") : row.source_title ?? row.source_id; + const noteName = (row: PodcastJobSummary) => row.source_title ?? row.source_id; + const pick = (row: PodcastJobSummary) => { + setSelected(row.job_id); + setAutoplay(true); + }; return (
-
-

{t("podcast.history.title")}

-
+

{t("podcast.history.title")}

{formatApiError(list.error)} @@ -108,78 +140,87 @@ export function PodcastHistory(props: { noteId?: string; active?: boolean; refet when={jobs().length > 0} fallback={ } > -
    + + {(row) => ( + + )} + + +
      - {(row) => ( -
    • -
      -
      -

      {row.source_title ?? row.source_id}

      -
      - {stateLabel(row.state)} - - {(label) => {label()}} - - - {row.error_code} - - {formatDate(row.created_at, locale())} - - {formatDurationClock((row.duration_secs ?? 0) * 1000)} - -
      -
      - -
      -
      + } + > + + + + {rowTitle(row)} + {formatDateTime(row.created_at, locale())} + + + + {formatDurationClock((row.duration_secs ?? 0) * 1000)} + + + - {downloadT("podcast.download.label")} -
      - -
- {/* The player opens in the row the reader clicked. A single - one under the whole list put it a screen away from the - episode it belonged to. */} - - - - - )} + + + ); + }} @@ -188,7 +229,6 @@ export function PodcastHistory(props: { noteId?: string; active?: boolean; refet - ); } diff --git a/src/components/notes/podcast-panel.test.tsx b/src/components/notes/podcast-panel.test.tsx index 6f90a15..16ea21a 100644 --- a/src/components/notes/podcast-panel.test.tsx +++ b/src/components/notes/podcast-panel.test.tsx @@ -10,6 +10,7 @@ const podcastApi = vi.hoisted(() => ({ postPodcastJobCancel: vi.fn(), listPodcastJobs: vi.fn(async () => ({ items: [], total: 0, limit: 10, offset: 0 })), podcastAudioUrl: vi.fn((jobId: string) => `/api/podcast/jobs/${encodeURIComponent(jobId)}/audio`), + getPodcastJobAudioBlob: vi.fn(), })); vi.mock("@/api/podcast", () => podcastApi); @@ -58,6 +59,24 @@ describe("PodcastPanel", () => { // stream by `job_id`. Handing it `audio_id` (the output-root path) composes // a URL the backend has no route for, and the player dies silently. sessionStorage.setItem("hezarfen.podcast.note-7", "pj1"); + podcastApi.listPodcastJobs.mockResolvedValue({ + items: [ + { + job_id: "pj1", + state: "done", + format: "duz_okuma", + source_id: "note-7", + source_title: "Hücre ve Canlıların Ortak Özellikleri", + created_at: 1, + finished_at: 2, + duration_secs: 42, + error_code: null, + }, + ], + total: 1, + limit: 10, + offset: 0, + }); podcastApi.getPodcastJobById.mockResolvedValue({ job_id: "pj1", state: "done", stage: "done", progress: 1 }); podcastApi.getPodcastJobResultById.mockResolvedValue({ job_id: "pj1", @@ -72,15 +91,33 @@ describe("PodcastPanel", () => { )); + // The finished job hands off to the episode list, which selects it. await waitFor(() => { - expect(screen.getByText("Your episode is ready.")).toBeTruthy(); + expect(document.querySelector("audio")?.getAttribute("src")).toBe("/api/podcast/jobs/pj1/audio"); }); expect(podcastApi.podcastAudioUrl).toHaveBeenCalledWith("pj1"); - expect(document.querySelector("audio")?.getAttribute("src")).toBe("/api/podcast/jobs/pj1/audio"); }); it("downloads the finished episode under the note's own title", async () => { sessionStorage.setItem("hezarfen.podcast.note-7", "pj1"); + podcastApi.listPodcastJobs.mockResolvedValue({ + items: [ + { + job_id: "pj1", + state: "done", + format: "duz_okuma", + source_id: "note-7", + source_title: "Hücre ve Canlıların Ortak Özellikleri", + created_at: 1, + finished_at: 2, + duration_secs: 42, + error_code: null, + }, + ], + total: 1, + limit: 10, + offset: 0, + }); podcastApi.getPodcastJobById.mockResolvedValue({ job_id: "pj1", state: "done", stage: "done", progress: 1 }); podcastApi.getPodcastJobResultById.mockResolvedValue({ job_id: "pj1", @@ -96,15 +133,16 @@ describe("PodcastPanel", () => { )); await waitFor(() => { - expect(screen.getByText("Your episode is ready.")).toBeTruthy(); + expect(screen.getAllByRole("link", { name: "Download episode" }).length).toBeGreaterThan(0); }); - const link = screen.getByRole("link", { name: "Download episode" }) as HTMLAnchorElement; + const link = screen.getAllByRole("link", { name: "Download episode" })[0] as HTMLAnchorElement; expect(link.getAttribute("href")).toBe("/api/podcast/jobs/pj1/audio"); expect(link.getAttribute("download")).toBe("Hücre ve Canlıların Ortak Özellikleri.mp3"); }); it("shows no download control while the episode is still being made", async () => { sessionStorage.setItem("hezarfen.podcast.note-7", "pj2"); + podcastApi.listPodcastJobs.mockResolvedValue({ items: [], total: 0, limit: 10, offset: 0 }); podcastApi.getPodcastJobById.mockResolvedValue({ job_id: "pj2", state: "running", stage: "script", progress: 0.4 }); render(() => ( diff --git a/src/components/notes/podcast-panel.tsx b/src/components/notes/podcast-panel.tsx index a33c2e1..c013eb3 100644 --- a/src/components/notes/podcast-panel.tsx +++ b/src/components/notes/podcast-panel.tsx @@ -10,7 +10,6 @@ import { Label } from "@/components/ui/label"; import { Select } from "@/components/ui/select"; import { PodcastHistory } from "@/components/notes/podcast-history"; import { PodcastStageTrail, type PodcastStageEntry } from "@/components/notes/podcast-stage-trail"; -import { PodcastPlayer } from "@/components/notes/podcast-player"; import { createLivePoll } from "@/lib/create-live-poll"; import { useT } from "@/stores/preferences-context"; @@ -205,7 +204,8 @@ export function PodcastPanel(props: { noteId: string; active?: boolean; noteTitl - + {/* A finished job hands off to the episode list, which selects it. */} + {(current) => (
{/* Compact textual metadata over a progress bar: the state, how far @@ -238,25 +238,13 @@ export function PodcastPanel(props: { noteId: string; active?: boolean; noteTitl )} - - {(result) => ( -
-

{t("podcast.ready")}

- option.value === result().format)?.label : undefined} - durationSecs={result().duration_secs} - transcript={result().transcript} - /> -
- )} -
- diff --git a/src/components/notes/podcast-player.test.tsx b/src/components/notes/podcast-player.test.tsx index f88f2f2..974f69b 100644 --- a/src/components/notes/podcast-player.test.tsx +++ b/src/components/notes/podcast-player.test.tsx @@ -33,6 +33,12 @@ describe("PodcastPlayer", () => { vi.spyOn(HTMLMediaElement.prototype, "pause").mockImplementation(() => {}); // Nor element scrolling, which the transcript's follow uses. Element.prototype.scrollTo ??= () => {}; + // A stream the server lets the browser seek in, so no local copy is loaded. + vi.spyOn(HTMLMediaElement.prototype, "seekable", "get").mockReturnValue({ + length: 1, + start: () => 0, + end: () => 754, + } as unknown as TimeRanges); }); afterEach(() => { diff --git a/src/components/notes/podcast-player.tsx b/src/components/notes/podcast-player.tsx index 6ca6983..ce24df9 100644 --- a/src/components/notes/podcast-player.tsx +++ b/src/components/notes/podcast-player.tsx @@ -1,5 +1,5 @@ import { Show, createSignal } from "solid-js"; -import { podcastAudioUrl } from "@/api/podcast"; +import { getPodcastJobAudioBlob, podcastAudioUrl } from "@/api/podcast"; import type { PodcastTranscriptSegment } from "@/api/client"; import { AudioPlayer, type AudioPlayerController } from "@/components/ui/audio-player"; import { IconDownload, IconTranscript } from "@/components/ui/icons"; @@ -22,6 +22,8 @@ export function PodcastPlayer(props: { autoplay?: boolean; /** Off where the surrounding row already offers the download. */ download?: boolean; + /** The download's filename stem; defaults to the title. */ + downloadName?: string; class?: string; }) { const t = useT(); @@ -38,6 +40,7 @@ export function PodcastPlayer(props: { title={props.title} subtitle={props.subtitle} durationHint={props.durationSecs} + loadBlob={(signal) => getPodcastJobAudioBlob(props.jobId, signal)} autoplay={props.autoplay} onTimeUpdate={setCurrentSecs} controller={(value) => (controller = value)} @@ -45,7 +48,7 @@ export function PodcastPlayer(props: { Promise; onTimeUpdate?: (secs: number) => void; controller?: (controller: AudioPlayerController) => void; class?: string; @@ -77,6 +83,54 @@ export function AudioPlayer(props: AudioPlayerProps) { const [volume, setVolume] = createSignal(readStored(VOLUME_KEY, 1, (v) => v >= 0 && v <= 1)); const [muted, setMuted] = createSignal(false); const [failed, setFailed] = createSignal(false); + // Seeking waits on the local copy; the seek bar already shows the target. + const [seeking, setSeeking] = createSignal(false); + const [source, setSource] = createSignal(props.src); + + // The local copy of the file, loaded once per `src` on first play or on the + // first seek the stream cannot serve. + let objectUrl: string | null = null; + let localLoad: Promise | null = null; + let abort: AbortController | null = null; + let pendingSeek: number | null = null; + let resumeAfterSeek = false; + let seekToken = 0; + let afterLoad: (() => void) | null = null; + + const dropLocal = () => { + abort?.abort(); + abort = null; + localLoad = null; + if (objectUrl) URL.revokeObjectURL(objectUrl); + objectUrl = null; + }; + const loadLocal = (): Promise => { + const load = props.loadBlob; + if (!load) return Promise.resolve(null); + if (!localLoad) { + const controller = new AbortController(); + abort = controller; + localLoad = load(controller.signal).then( + (blob) => { + if (controller.signal.aborted) return null; + objectUrl = URL.createObjectURL(blob); + return objectUrl; + }, + () => { + if (abort === controller) localLoad = null; + return null; + }, + ); + } + return localLoad; + }; + const canSeekTo = (secs: number) => { + const ranges = audio.seekable; + for (let i = 0; i < ranges.length; i += 1) { + if (ranges.end(i) > 0 && secs >= ranges.start(i) && secs <= ranges.end(i)) return true; + } + return false; + }; const duration = () => mediaDuration() ?? (props.durationHint && props.durationHint > 0 ? props.durationHint : null); const fraction = (value: number) => { @@ -87,10 +141,50 @@ export function AudioPlayer(props: AudioPlayerProps) { const seek = (secs: number) => { const total = duration(); const next = Math.max(0, total ? Math.min(total, secs) : secs); - audio.currentTime = next; setCurrent(next); + if (!props.loadBlob || canSeekTo(next)) { + audio.currentTime = next; + return; + } + // The stream cannot go there: hold the target, pause the stream at its + // wrong position, and resume from the target on the local copy. + const token = ++seekToken; + pendingSeek = next; + resumeAfterSeek ||= !audio.paused; + audio.pause(); + setSeeking(true); + void loadLocal().then((url) => { + if (token !== seekToken) return; + const at = pendingSeek ?? next; + const resume = resumeAfterSeek; + pendingSeek = null; + resumeAfterSeek = false; + if (!url) { + setSeeking(false); + setCurrent(audio.currentTime); + setFailed(true); + return; + } + afterLoad = () => { + audio.currentTime = at; + setCurrent(at); + setSeeking(false); + if (resume) play(); + }; + if (source() === url) { + const run = afterLoad; + afterLoad = null; + run(); + } else { + setSource(url); + } + }); }; const play = () => { + if (pendingSeek != null) { + resumeAfterSeek = true; + return; + } setFailed(false); void audio.play().catch(() => { // A refused autoplay or an aborted load is not a broken file; the @@ -98,7 +192,11 @@ export function AudioPlayer(props: AudioPlayerProps) { setPlaying(false); }); }; - const toggle = () => (audio.paused ? play() : audio.pause()); + const toggle = () => { + if (pendingSeek != null) resumeAfterSeek = !resumeAfterSeek; + else if (audio.paused) play(); + else audio.pause(); + }; const skip = (delta: number) => seek(audio.currentTime + delta); const cycleRate = () => { const index = RATES.indexOf(rate() as (typeof RATES)[number]); @@ -120,6 +218,7 @@ export function AudioPlayer(props: AudioPlayerProps) { onCleanup(() => { players.delete(audio); audio?.pause(); + dropLocal(); }); createEffect(() => { @@ -133,7 +232,14 @@ export function AudioPlayer(props: AudioPlayerProps) { }); // A new episode in the same player starts from its own beginning. createEffect(() => { - void props.src; + const src = props.src; + dropLocal(); + seekToken += 1; + pendingSeek = null; + resumeAfterSeek = false; + afterLoad = null; + setSeeking(false); + setSource(src); setCurrent(0); setMediaDuration(null); setBuffered(0); @@ -184,22 +290,30 @@ export function AudioPlayer(props: AudioPlayerProps) { >