162 lines
4.6 KiB
TypeScript
162 lines
4.6 KiB
TypeScript
import {
|
|
downloadPlan,
|
|
parseDownloadQuality,
|
|
} from "@otunes/convex/download-quality"
|
|
import { audioContentTypeForPath } from "@/lib/audio-content-type"
|
|
import { audioInfo } from "@/lib/server-audio-info"
|
|
import { streamFile } from "@/lib/server-audio-stream"
|
|
import { spawnFfmpeg } from "@/lib/server-ffmpeg"
|
|
import { seekableLosslessFile } from "@/lib/server-lossless"
|
|
import { getSongLyrics, getSongSource } from "@/lib/server-song"
|
|
import { NextRequest, NextResponse, userAgent } from "next/server"
|
|
import fs from "node:fs/promises"
|
|
import os from "node:os"
|
|
import path from "node:path"
|
|
|
|
/** The filename tells native clients which extension to save the file with. */
|
|
function downloadHeaders(
|
|
songId: string,
|
|
extension: string,
|
|
contentType: string,
|
|
size: number
|
|
) {
|
|
return {
|
|
"Cache-Control": "no-store",
|
|
"Content-Disposition": `attachment; filename="${songId}${extension}"`,
|
|
"Content-Length": String(size),
|
|
"Content-Type": contentType,
|
|
}
|
|
}
|
|
|
|
async function fileResponse(songId: string, file: string, contentType: string) {
|
|
const { size } = await fs.stat(file)
|
|
return new NextResponse(streamFile(file), {
|
|
headers: downloadHeaders(
|
|
songId,
|
|
path.extname(file).toLowerCase(),
|
|
contentType,
|
|
size
|
|
),
|
|
})
|
|
}
|
|
|
|
/** Longest lyrics passed to ffmpeg; Linux caps one argument at 128 KiB. */
|
|
const MAX_LYRICS_ARGUMENT_BYTES = 100 * 1024
|
|
|
|
/**
|
|
* Transcodes to an AAC .m4a with its index up front, so the saved file has a
|
|
* duration and seeks offline. Tags carry over, and the stored lyrics are
|
|
* written too, since ffmpeg drops some formats' lyrics tags (like MP3 USLT)
|
|
* when writing MP4. The temporary file is removed once sent.
|
|
*/
|
|
async function transcodeResponse(
|
|
songId: string,
|
|
source: string,
|
|
kbps: number,
|
|
signal: AbortSignal
|
|
) {
|
|
const lyrics = await getSongLyrics(songId)
|
|
const lyricsArgs =
|
|
lyrics && Buffer.byteLength(lyrics) <= MAX_LYRICS_ARGUMENT_BYTES
|
|
? ["-metadata", `lyrics=${lyrics}`]
|
|
: []
|
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "otunes-download-"))
|
|
const output = path.join(dir, "audio.m4a")
|
|
const cleanup = () => fs.rm(dir, { recursive: true, force: true })
|
|
try {
|
|
const ffmpeg = await spawnFfmpeg(
|
|
[
|
|
"-i",
|
|
source,
|
|
"-map",
|
|
"0:a:0",
|
|
"-c:a",
|
|
"aac",
|
|
"-b:a",
|
|
`${kbps}k`,
|
|
...lyricsArgs,
|
|
"-movflags",
|
|
"+faststart",
|
|
output,
|
|
],
|
|
signal
|
|
)
|
|
const onAbort = () => ffmpeg.child.kill("SIGKILL")
|
|
signal.addEventListener("abort", onAbort, { once: true })
|
|
const code = await ffmpeg.exited
|
|
signal.removeEventListener("abort", onAbort)
|
|
if (code !== 0) {
|
|
throw new Error(
|
|
`Download transcode failed: ${code}: ${ffmpeg.stderrTail()}`
|
|
)
|
|
}
|
|
const { size } = await fs.stat(output)
|
|
return new NextResponse(streamFile(output, undefined, cleanup), {
|
|
headers: downloadHeaders(songId, ".m4a", "audio/mp4", size),
|
|
})
|
|
} catch (error) {
|
|
await cleanup()
|
|
throw error
|
|
}
|
|
}
|
|
|
|
/** Sends one song as a whole file for offline playback. */
|
|
export async function GET(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
const { id } = await params
|
|
const quality = parseDownloadQuality(
|
|
request.nextUrl.searchParams.get("quality")
|
|
)
|
|
if (!quality) {
|
|
return new Response("Unknown quality", { status: 400 })
|
|
}
|
|
|
|
let song: Awaited<ReturnType<typeof getSongSource>>
|
|
try {
|
|
song = await getSongSource(id)
|
|
} catch {
|
|
return new Response("Not found", { status: 404 })
|
|
}
|
|
|
|
const plan = downloadPlan(song.files, quality)
|
|
const sourceFile = song.files[plan.source]
|
|
if (!sourceFile) {
|
|
return new Response("Not found", { status: 404 })
|
|
}
|
|
|
|
try {
|
|
if (plan.kbps > 0) {
|
|
return await transcodeResponse(
|
|
song._id,
|
|
sourceFile,
|
|
plan.kbps,
|
|
request.signal
|
|
)
|
|
}
|
|
|
|
if (plan.source === "lossless") {
|
|
// Only Safari and iOS play ALAC, so everyone else gets FLAC.
|
|
const acceptsAlac =
|
|
userAgent(request).browser.name === "Safari" ||
|
|
request.nextUrl.searchParams.get("losslessFormat") === "alac"
|
|
if (!acceptsAlac && (await audioInfo(sourceFile)).codec === "ALAC") {
|
|
const flac = await seekableLosslessFile(sourceFile)
|
|
return await fileResponse(song._id, flac, "audio/flac")
|
|
}
|
|
}
|
|
|
|
return await fileResponse(
|
|
song._id,
|
|
sourceFile,
|
|
audioContentTypeForPath(sourceFile)
|
|
)
|
|
} catch (error) {
|
|
if (!request.signal.aborted) {
|
|
console.error("Song download failed", error)
|
|
}
|
|
return new Response("Server Error", { status: 500 })
|
|
}
|
|
}
|