diff --git a/apps/web/app/api/download/options/route.ts b/apps/web/app/api/download/options/route.server.ts similarity index 98% rename from apps/web/app/api/download/options/route.ts rename to apps/web/app/api/download/options/route.server.ts index 78a27bc..bd2e273 100644 --- a/apps/web/app/api/download/options/route.ts +++ b/apps/web/app/api/download/options/route.server.ts @@ -37,7 +37,7 @@ export async function POST(request: NextRequest) { let songs: Awaited> try { - songs = await getSongSources(songIds) + songs = await getSongSources(songIds, request) } catch { return new Response("Not found", { status: 404 }) } diff --git a/apps/web/app/api/song/[id]/download/route.ts b/apps/web/app/api/song/[id]/download/route.server.ts similarity index 95% rename from apps/web/app/api/song/[id]/download/route.ts rename to apps/web/app/api/song/[id]/download/route.server.ts index d57d0d0..8c73536 100644 --- a/apps/web/app/api/song/[id]/download/route.ts +++ b/apps/web/app/api/song/[id]/download/route.server.ts @@ -53,9 +53,10 @@ async function transcodeResponse( songId: string, source: string, kbps: number, - signal: AbortSignal + request: NextRequest ) { - const lyrics = await getSongLyrics(songId) + const { signal } = request + const lyrics = await getSongLyrics(songId, request) const lyricsArgs = lyrics && Buffer.byteLength(lyrics) <= MAX_LYRICS_ARGUMENT_BYTES ? ["-metadata", `lyrics=${lyrics}`] @@ -115,7 +116,7 @@ export async function GET( let song: Awaited> try { - song = await getSongSource(id) + song = await getSongSource(id, request) } catch { return new Response("Not found", { status: 404 }) } @@ -128,12 +129,7 @@ export async function GET( try { if (plan.kbps > 0) { - return await transcodeResponse( - song._id, - sourceFile, - plan.kbps, - request.signal - ) + return await transcodeResponse(song._id, sourceFile, plan.kbps, request) } if (plan.source === "lossless") { diff --git a/apps/web/components/downloads-provider.tsx b/apps/web/components/downloads-provider.tsx index 802c119..0e177ff 100644 --- a/apps/web/components/downloads-provider.tsx +++ b/apps/web/components/downloads-provider.tsx @@ -18,6 +18,7 @@ import { Label } from "@/components/ui/label" import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group" import { useCachedQuery } from "@/hooks/use-cached-query" import { useDownloadsVersion } from "@/hooks/use-downloads" +import { authedUrl } from "@/lib/server" import { downloadQueue, readRememberedDownloadQuality, @@ -78,7 +79,7 @@ export function useDownloads() { } async function fetchDownloadOptions(songIds: string[]) { - const response = await fetch(DOWNLOAD_OPTIONS_PATH, { + const response = await fetch(authedUrl(DOWNLOAD_OPTIONS_PATH), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ songIds }), diff --git a/apps/web/lib/downloads.ts b/apps/web/lib/downloads.ts index 06c6c99..925388b 100644 --- a/apps/web/lib/downloads.ts +++ b/apps/web/lib/downloads.ts @@ -12,6 +12,8 @@ import { songDownloadPath, type DownloadQuality, } from "@otunes/convex/download-quality" +import { albumPath, playlistPath } from "@/lib/routes" +import { authedUrl, serverUrl, staticExport } from "@/lib/server" // Like YouTube Music on the web, downloads live in this browser's IndexedDB // and only play inside the app. Clearing site data removes them. @@ -38,21 +40,22 @@ export const OTHER_DOWNLOADS_PATH = "/library/downloads/other" export const FROM_DOWNLOADS_PARAM = "from=downloads" export function downloadedCollectionPath({ kind, id }: DownloadedCollection) { - if (kind === "album") return `/album/${id}?${FROM_DOWNLOADS_PARAM}` if (id === FAVORITES_ID) return `/playlist/favorites?${FROM_DOWNLOADS_PARAM}` - return `/playlist/${id}?${FROM_DOWNLOADS_PARAM}` + const path = kind === "album" ? albumPath(id) : playlistPath(id) + return `${path}&${FROM_DOWNLOADS_PARAM}` } // Saved pages are specific to the signed-in user (public/downloads-sw.js). const OFFLINE_PAGE_CACHE = "otunes-offline-pages" /** - * Lets downloaded covers show offline. In production builds the worker also - * keeps pages and app code so the app opens offline. + * Lets downloaded covers show offline. In production server builds the worker + * also keeps pages and app code so the app opens offline. Static exports are + * served locally, so they always open. */ export function registerDownloadsServiceWorker() { const url = - process.env.NODE_ENV === "production" + process.env.NODE_ENV === "production" && !staticExport ? "/downloads-sw.js?offline-app" : "/downloads-sw.js" void navigator.serviceWorker?.register(url, { scope: "/" }).catch(() => {}) @@ -123,9 +126,12 @@ const storage: DownloadStorage = { ) }, async save({ songId, requested, quality, albumId }, signal) { - const response = await fetch(songDownloadPath(songId, requested), { - signal, - }) + const response = await fetch( + authedUrl(songDownloadPath(songId, requested)), + { + signal, + } + ) if (!response.ok) { throw new Error(`Download failed with ${response.status}`) } @@ -142,7 +148,7 @@ const storage: DownloadStorage = { const cache = await caches.open(COVER_CACHE) const key = coverPath(cover) if (await cache.match(key)) return - const response = await fetch(`${key}?size=${COVER_SIZE}`) + const response = await fetch(serverUrl(`${key}?size=${COVER_SIZE}`)) if (!response.ok) throw new Error(`Cover failed with ${response.status}`) await cache.put(key, response) }, diff --git a/apps/web/lib/server-song.ts b/apps/web/lib/server-song.ts index 3624ef2..9294201 100644 --- a/apps/web/lib/server-song.ts +++ b/apps/web/lib/server-song.ts @@ -6,17 +6,25 @@ import type { NextRequest } from "next/server" import { convexServerOptions } from "@/lib/convex-server" import type { SongSource } from "@/lib/server-hls" +/** + * The listener's session, from the cookie or from a `token` query parameter + * (static exports on another origin). + */ +async function sessionToken(request: NextRequest) { + return ( + request.nextUrl.searchParams.get("token") ?? (await convexAuthNextjsToken()) + ) +} + /** * Loads a song's file paths as the requesting listener, so Convex enforces - * auth. The session comes from the cookie, or from a `token` query parameter - * for desktop apps on another origin. Throws when signed out or missing. + * auth. Throws when signed out or missing. */ export async function getSongSource( id: string, request: NextRequest ): Promise { - const token = - request.nextUrl.searchParams.get("token") ?? (await convexAuthNextjsToken()) + const token = await sessionToken(request) const song = await fetchQuery( api.library.getSongSource, { id: id as Id<"songs"> }, @@ -29,8 +37,11 @@ export async function getSongSource( } /** The song's stored lyrics tag, or null without lyrics. */ -export async function getSongLyrics(id: string): Promise { - const token = await convexAuthNextjsToken() +export async function getSongLyrics( + id: string, + request: NextRequest +): Promise { + const token = await sessionToken(request) return await fetchQuery( api.lyrics.forSong, { id: id as Id<"songs"> }, @@ -42,9 +53,10 @@ const SOURCE_BATCH_SIZE = 200 /** `getSongSource` for many songs, in batches. Missing songs are left out. */ export async function getSongSources( - ids: string[] + ids: string[], + request: NextRequest ): Promise<(SongSource & Pick, "album">)[]> { - const token = await convexAuthNextjsToken() + const token = await sessionToken(request) const batches: string[][] = [] for (let start = 0; start < ids.length; start += SOURCE_BATCH_SIZE) { batches.push(ids.slice(start, start + SOURCE_BATCH_SIZE)) diff --git a/apps/web/lib/server.ts b/apps/web/lib/server.ts index be38e48..8717088 100644 --- a/apps/web/lib/server.ts +++ b/apps/web/lib/server.ts @@ -53,10 +53,10 @@ export function setMediaToken(token: string | null) { } /** - * URL for a song route, which needs a session. `