feat(web): support downloads in the static export
Main's download routes are server-only like the other API routes. They take the session from a `token` parameter, the options POST is allowed cross-origin, and the client fetches songs and covers from the picked server. The service worker matches downloaded covers from any origin, and skips offline page caching in exports since they are served locally. pnpm 12 fails on ignored build scripts, so electron-winstaller's is denied explicitly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f8e5dc7325
commit
37d1195955
10 files changed
+67
-42
No files matched your search
+1
-1
@@ -37,7 +37,7 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
let songs: Awaited<ReturnType<typeof getSongSources>>
|
||||
try {
|
||||
songs = await getSongSources(songIds)
|
||||
songs = await getSongSources(songIds, request)
|
||||
} catch {
|
||||
return new Response("Not found", { status: 404 })
|
||||
}
|
||||
+5
-9
@@ -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<ReturnType<typeof getSongSource>>
|
||||
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") {
|
||||
@@ -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 }),
|
||||
|
||||
@@ -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)
|
||||
},
|
||||
|
||||
@@ -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<SongSource> {
|
||||
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<string | null> {
|
||||
const token = await convexAuthNextjsToken()
|
||||
export async function getSongLyrics(
|
||||
id: string,
|
||||
request: NextRequest
|
||||
): Promise<string | null> {
|
||||
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<Doc<"songs">, "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))
|
||||
|
||||
@@ -53,10 +53,10 @@ export function setMediaToken(token: string | null) {
|
||||
}
|
||||
|
||||
/**
|
||||
* URL for a song route, which needs a session. `<audio>` and native HLS cannot
|
||||
* send headers, and exports have no cookie on the server's origin, so they
|
||||
* pass the session token in the query. HLS segment URLs inherit it from the
|
||||
* playlist URL.
|
||||
* URL for a route that needs a session (songs, downloads). `<audio>` and
|
||||
* native HLS cannot send headers, and exports have no cookie on the server's
|
||||
* origin, so they pass the session token in the query. HLS segment URLs
|
||||
* inherit it from the playlist URL.
|
||||
*/
|
||||
export function authedUrl(path: string) {
|
||||
const url = serverUrl(path)
|
||||
|
||||
@@ -21,7 +21,11 @@ const nextConfig: NextConfig = {
|
||||
: async () => [
|
||||
{
|
||||
source: "/api/:path*",
|
||||
headers: [{ key: "Access-Control-Allow-Origin", value: "*" }],
|
||||
headers: [
|
||||
{ key: "Access-Control-Allow-Origin", value: "*" },
|
||||
// For the JSON body of POST /api/download/options.
|
||||
{ key: "Access-Control-Allow-Headers", value: "Content-Type" },
|
||||
],
|
||||
},
|
||||
],
|
||||
experimental: {
|
||||
|
||||
@@ -10,6 +10,7 @@ const isPublic = createRouteMatcher([
|
||||
// Song routes check the session themselves, from the cookie or a `token`
|
||||
// query parameter (static exports on another origin).
|
||||
"/api/song/(.*)",
|
||||
"/api/download/options",
|
||||
"/api/album/:id/cover",
|
||||
"/api/artist/:id/cover",
|
||||
"/api/playlist/:id/cover",
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
// unused for a month is deleted, so old deploys don't pile up.
|
||||
// - Covers of downloaded music, saved by lib/downloads.ts, served only when
|
||||
// the network fails. Any other cover falls back to the placeholder the
|
||||
// server would send for a missing cover.
|
||||
// server would send for a missing cover. Static exports load covers from
|
||||
// the picked server's origin, so covers match on the path alone.
|
||||
// Pages and app code are only handled in production builds (`?offline-app`),
|
||||
// where app code is content-hashed.
|
||||
const COVER_CACHE = "otunes-download-covers"
|
||||
@@ -71,8 +72,7 @@ async function pruneStatic() {
|
||||
|
||||
/** The saved cover's key for a cover request, also through `/_next/image`. */
|
||||
function coverKey(url) {
|
||||
if (url.origin !== self.location.origin) return null
|
||||
if (url.pathname === "/_next/image") {
|
||||
if (url.origin === self.location.origin && url.pathname === "/_next/image") {
|
||||
const inner = url.searchParams.get("url")
|
||||
return inner ? coverKey(new URL(inner, self.location.origin)) : null
|
||||
}
|
||||
@@ -170,7 +170,10 @@ async function savedCover(key) {
|
||||
async function handleCover(request, key) {
|
||||
try {
|
||||
const response = await fetch(request)
|
||||
return response.ok ? response : ((await savedCover(key)) ?? response)
|
||||
// Covers from another origin load as opaque responses, with no status.
|
||||
return response.ok || response.type === "opaque"
|
||||
? response
|
||||
: ((await savedCover(key)) ?? response)
|
||||
} catch (error) {
|
||||
const cover = await savedCover(key)
|
||||
if (cover) return cover
|
||||
@@ -195,6 +198,11 @@ self.addEventListener("fetch", (event) => {
|
||||
const { request } = event
|
||||
if (request.method !== "GET") return
|
||||
const url = new URL(request.url)
|
||||
const cover = coverKey(url)
|
||||
if (cover) {
|
||||
event.respondWith(handleCover(request, cover))
|
||||
return
|
||||
}
|
||||
if (url.origin !== self.location.origin) return
|
||||
|
||||
if (OFFLINE_APP && request.mode === "navigate") {
|
||||
@@ -205,11 +213,6 @@ self.addEventListener("fetch", (event) => {
|
||||
event.respondWith(handleStatic(request, url))
|
||||
return
|
||||
}
|
||||
const cover = coverKey(url)
|
||||
if (cover) {
|
||||
event.respondWith(handleCover(request, cover))
|
||||
return
|
||||
}
|
||||
if (OFFLINE_APP && PUBLIC_FILE.test(url.pathname)) {
|
||||
event.respondWith(handlePublicFile(request, url.pathname))
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ patchedDependencies:
|
||||
'expo-router@58.0.25': patches/expo-router@58.0.25.patch
|
||||
allowBuilds:
|
||||
electron: true
|
||||
# Squirrel installer support; the Windows build uses NSIS.
|
||||
electron-winstaller: false
|
||||
esbuild: true
|
||||
unrs-resolver: true
|
||||
overrides:
|
||||
|
||||
Reference in new issue
Block a user