Files
otunes/apps/web/app/api/song/[id]/play/hls/route.ts
T
joshuafhiggins 73c7283d4d Add Expo mobile app and extract shared Convex package
- Replace mobile placeholder with Expo Router app (tabs, playback, auth, library)
- Move Convex backend to @otunes/convex for web and mobile reuse
- Update web app imports and API routes to use shared package
2026-08-02 04:14:01 +00:00

59 lines
1.8 KiB
TypeScript

import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { getConvexClient } from "@/lib/convex-server"
import { ensureHlsJob, HLS_SEGMENT_SECONDS } from "@/lib/server-hls"
import { NextRequest } from "next/server"
function hlsSegmentUrl(request: NextRequest, index: number) {
const url = new URL(request.url)
url.pathname = `${url.pathname.replace(/\/$/, "")}/segment/${index}.ts`
return `${url.pathname}${url.search}`
}
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
try {
const song = (await getConvexClient().query(api.library.getSong, {
id: id as Id<"songs">,
}))!
const quality = request.nextUrl.searchParams.get("quality")
const preferAtmos =
request.nextUrl.searchParams.get("preferAtmos") === "true"
const job = await ensureHlsJob(song, quality, preferAtmos)
const { duration, segmentCount } = job
const targetDuration = Math.ceil(HLS_SEGMENT_SECONDS)
const lines = [
"#EXTM3U",
"#EXT-X-VERSION:3",
`#EXT-X-TARGETDURATION:${targetDuration}`,
"#EXT-X-MEDIA-SEQUENCE:0",
"#EXT-X-PLAYLIST-TYPE:VOD",
]
for (let index = 0; index < segmentCount; index += 1) {
const start = index * HLS_SEGMENT_SECONDS
const segmentDuration = Math.min(HLS_SEGMENT_SECONDS, duration - start)
lines.push(`#EXTINF:${segmentDuration.toFixed(3)},`)
lines.push(hlsSegmentUrl(request, index))
}
lines.push("#EXT-X-ENDLIST")
return new Response(`${lines.join("\n")}\n`, {
status: 200,
headers: {
"Cache-Control": "no-cache",
"Content-Type": "application/vnd.apple.mpegurl",
},
})
} catch {
return new Response("Not found", { status: 404 })
}
}