feat(desktop): ship the web UI as a static export
The static export now works away from the oTunes server. It picks a server at /server (saved in localStorage), connects Convex to it, and loads covers, avatars and streams from it. Streams and avatars pass the session token as a `token` query parameter, which the song and avatar routes accept alongside the cookie. The server allows any origin on /api. Electron serves that export from 127.0.0.1:47836 and drops the bundled Next.js server, the media gateway, symlink materializing and Sharp pruning. The same export can ship in a Tauri app. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
120cb1abde
commit
7c37174e4b
31 files changed
+346
-649
No files matched your search
@@ -56,9 +56,6 @@ jobs:
|
||||
- name: Check desktop scripts
|
||||
run: pnpm --filter @otunes/desktop typecheck
|
||||
|
||||
- name: Test UI bundling
|
||||
run: pnpm --filter @otunes/desktop test
|
||||
|
||||
- name: Build x64 and ARM64 installers
|
||||
run: pnpm --filter @otunes/desktop build:${{ matrix.target }}
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# oTunes desktop
|
||||
|
||||
The Windows and Linux desktop app. It runs stock Electron, bundles the web UI and runs its standalone Next.js server on loopback using Electron's Node utility process. It never loads the UI hosted on your music server. On first launch, enter the oTunes server domain, then sign in. The address is saved in the app's user data directory, not compiled into the package.
|
||||
The Windows and Linux desktop app. It runs stock Electron and serves the web app's static export (`pnpm --filter @otunes/web build:export`) from `http://127.0.0.1:47836`. There is no bundled Node.js server: the UI talks to the selected oTunes server and its Convex backend directly. On first launch, enter the oTunes server domain, then sign in. The address and session are saved in the app's local storage, not compiled into the package.
|
||||
|
||||
For `music.example.com`, Convex connects to `https://convex.music.example.com`. Local hosts follow the mobile convention and use port 3210. The selected oTunes server provides streaming audio, cover art and avatars through the desktop's local gateway. Authentication routes stay local and connect to the selected Convex backend. The desktop app does not bundle Convex, FFmpeg or a music library.
|
||||
For `music.example.com`, Convex connects to `https://convex.music.example.com`. Local hosts follow the mobile convention and use port 3210. The selected server streams audio and serves cover art and avatars. Streams and avatars pass the session token as a `token` query parameter, since the app is on another origin and has no cookie there. The desktop app does not bundle Convex, FFmpeg or a music library.
|
||||
|
||||
The server-entry view uses the web app's controls, colors and logos, with the system theme by default. Use **Server > Change server** to select another server. Switching servers clears the local login session and cached data.
|
||||
Use **Server > Change server** or **Change Server** in the account menu to select another server. Sessions are kept per server; switching clears the cached library data.
|
||||
|
||||
Stock Chromium cannot decode EAC-3, so the player's codec check reports no Dolby Atmos support and the server streams the regular track instead.
|
||||
|
||||
@@ -20,11 +20,7 @@ pnpm --filter @otunes/desktop build:windows
|
||||
pnpm --filter @otunes/desktop build:linux
|
||||
```
|
||||
|
||||
All of these first build and bundle the local web UI. `pnpm --filter @otunes/desktop build:web` builds that bundle alone. Desktop builds use `apps/web/.next-desktop` and copy the standalone output, static assets and public assets into `apps/desktop/web`. Installers cannot carry symlinks, so pnpm's links are replaced with real copies, with each package's dependencies nested under it. The web app's normal `.next` output is separate. On Windows, enable Developer Mode or symlink permissions before building. The build rejects absolute junctions or links outside the standalone directory because they cannot be relocated into an installer.
|
||||
|
||||
Desktop images bypass Next's optimizer, so the bundle drops Sharp's native libraries. Any other native library fails the build, because it would match the build host rather than the target.
|
||||
|
||||
The desktop gateway binds only to `127.0.0.1:47836`. A single instance owns that port. The bundled Next.js process uses a separate OS-assigned loopback port and restarts when the server selection changes. No external Node.js installation is required by the installed app.
|
||||
All of these first build the static export and copy it to `apps/desktop/web`. `pnpm --filter @otunes/desktop build:web` does that step alone. A single instance owns port 47836, so the app's local storage keeps the same origin between launches.
|
||||
|
||||
Packaging writes to `apps/desktop/dist`: an NSIS installer per architecture for Windows, a Flatpak per architecture for Linux. To pick one architecture, pass it after the target: `node scripts/package.mjs linux x64`. Building Windows installers on Linux needs Wine. Flatpaks need flatpak-builder with Flathub added, and ARM64 Flatpaks on an x64 host need `qemu-user-static` registered with binfmt. Installers are unsigned unless you configure electron-builder's signing environment.
|
||||
|
||||
|
||||
+61
-220
@@ -1,219 +1,66 @@
|
||||
const {
|
||||
app,
|
||||
BrowserWindow,
|
||||
Menu,
|
||||
nativeTheme,
|
||||
session,
|
||||
utilityProcess,
|
||||
} = require("electron")
|
||||
const { createServer, request: httpRequest } = require("node:http")
|
||||
const { request: httpsRequest } = require("node:https")
|
||||
const { readFile, mkdir, writeFile, rename } = require("node:fs/promises")
|
||||
const { app, BrowserWindow, Menu, nativeTheme, session } = require("electron")
|
||||
const { createServer } = require("node:http")
|
||||
const { readFile } = require("node:fs/promises")
|
||||
const path = require("node:path")
|
||||
const { parseServer } = require("./server-config.cjs")
|
||||
|
||||
const origin = "http://127.0.0.1:47836"
|
||||
let window,
|
||||
gateway,
|
||||
nextProcess,
|
||||
config,
|
||||
changingServer = false
|
||||
let nextPort
|
||||
const configPath = () => path.join(app.getPath("userData"), "server.json")
|
||||
// The UI is the web app's static export, served on a fixed loopback origin so
|
||||
// its localStorage (picked server, session) persists between launches. An
|
||||
// http://127.0.0.1 page is a secure context that can still reach http servers
|
||||
// on the local network.
|
||||
const host = "127.0.0.1:47836"
|
||||
const origin = `http://${host}`
|
||||
const webRoot = path.join(
|
||||
app.isPackaged ? process.resourcesPath : __dirname,
|
||||
"web",
|
||||
"apps",
|
||||
"web"
|
||||
)
|
||||
|
||||
async function startWeb() {
|
||||
if (nextProcess) {
|
||||
const previous = nextProcess
|
||||
nextProcess = undefined
|
||||
await new Promise((resolve) => {
|
||||
previous.once("exit", resolve)
|
||||
previous.kill()
|
||||
})
|
||||
}
|
||||
// Let the OS allocate a private port for the bundled Next.js server.
|
||||
const reservation = createServer()
|
||||
await new Promise((resolve, reject) => {
|
||||
reservation.once("error", reject)
|
||||
reservation.listen(0, "127.0.0.1", resolve)
|
||||
})
|
||||
nextPort = reservation.address().port
|
||||
await new Promise((resolve) => reservation.close(resolve))
|
||||
nextProcess = utilityProcess.fork(path.join(webRoot, "server.js"), [], {
|
||||
cwd: webRoot,
|
||||
env: {
|
||||
...process.env,
|
||||
NODE_ENV: "production",
|
||||
HOSTNAME: "127.0.0.1",
|
||||
PORT: String(nextPort),
|
||||
OTUNES_DESKTOP: "1",
|
||||
OTUNES_DESKTOP_HOSTNAME: config?.hostname ?? "",
|
||||
PUBLIC_CONVEX_URL: config?.convexUrl ?? "",
|
||||
CONVEX_INTERNAL_URL: config?.convexUrl ?? "http://127.0.0.1:3210",
|
||||
NEXT_PUBLIC_CONVEX_URL: config?.convexUrl ?? "",
|
||||
},
|
||||
stdio: "pipe",
|
||||
})
|
||||
nextProcess.stdout.on("data", (data) => console.log(data.toString()))
|
||||
nextProcess.stderr.on("data", (data) => console.error(data.toString()))
|
||||
let exited = false
|
||||
const child = nextProcess
|
||||
child.once("exit", () => {
|
||||
exited = true
|
||||
if (nextProcess === child) nextProcess = undefined
|
||||
})
|
||||
for (let attempt = 0; attempt < 150; attempt++) {
|
||||
if (exited) throw new Error("The packaged web server exited during startup")
|
||||
try {
|
||||
const response = await fetch(`http://127.0.0.1:${nextPort}/desktop`, {
|
||||
signal: AbortSignal.timeout(1000),
|
||||
})
|
||||
if (!response.ok) throw new Error("Server entry page did not load")
|
||||
await response.body?.cancel()
|
||||
return
|
||||
} catch {
|
||||
await new Promise((resolve) => setTimeout(resolve, 200))
|
||||
}
|
||||
}
|
||||
throw new Error("The packaged web server did not start")
|
||||
const contentTypes = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".txt": "text/plain; charset=utf-8",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".json": "application/json",
|
||||
".webmanifest": "application/manifest+json",
|
||||
".png": "image/png",
|
||||
".svg": "image/svg+xml",
|
||||
".ico": "image/x-icon",
|
||||
".woff2": "font/woff2",
|
||||
}
|
||||
let window, server
|
||||
|
||||
async function saveServer(request, response) {
|
||||
if (
|
||||
request.headers.origin !== origin ||
|
||||
request.headers["content-type"] !== "application/json"
|
||||
) {
|
||||
response.writeHead(403).end()
|
||||
return
|
||||
}
|
||||
if (changingServer) {
|
||||
response.writeHead(409).end()
|
||||
return
|
||||
}
|
||||
changingServer = true
|
||||
// Resolves paths the way static hosts serve a Next.js export: /album is
|
||||
// album.html, / is index.html, and anything missing is 404.html.
|
||||
async function serveStatic(request, response) {
|
||||
if (request.headers.host !== host) return response.writeHead(403).end()
|
||||
if (request.method !== "GET" && request.method !== "HEAD")
|
||||
return response.writeHead(405).end()
|
||||
let pathname
|
||||
try {
|
||||
let body = ""
|
||||
for await (const chunk of request) {
|
||||
body += chunk
|
||||
if (body.length > 2048) throw new Error("Server address is too long.")
|
||||
}
|
||||
const selected = parseServer(JSON.parse(body).hostname)
|
||||
// Validate against Convex before replacing the current server and session.
|
||||
const check = await fetch(`${selected.convexUrl}/version`, {
|
||||
signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
if (!check.ok)
|
||||
throw new Error(
|
||||
"Could not reach the Convex server. Check the address and try again."
|
||||
)
|
||||
const previous = config
|
||||
config = selected
|
||||
pathname = decodeURIComponent(new URL(request.url, origin).pathname)
|
||||
} catch {
|
||||
return response.writeHead(400).end()
|
||||
}
|
||||
const relative = pathname.replace(/^\/+|\/+$/g, "")
|
||||
const candidates = relative
|
||||
? [relative, `${relative}.html`, `${relative}/index.html`]
|
||||
: ["index.html"]
|
||||
for (const candidate of [...candidates, "404.html"]) {
|
||||
const file = path.resolve(webRoot, candidate)
|
||||
if (!file.startsWith(webRoot + path.sep)) continue
|
||||
try {
|
||||
await startWeb()
|
||||
} catch (error) {
|
||||
config = previous
|
||||
await startWeb()
|
||||
throw error
|
||||
}
|
||||
await mkdir(app.getPath("userData"), { recursive: true })
|
||||
await writeFile(`${configPath()}.tmp`, JSON.stringify(selected), {
|
||||
mode: 0o600,
|
||||
})
|
||||
await rename(`${configPath()}.tmp`, configPath())
|
||||
if (previous?.hostname !== selected.hostname) {
|
||||
await session.defaultSession.clearStorageData()
|
||||
await session.defaultSession.clearCache()
|
||||
}
|
||||
response
|
||||
.writeHead(200, {
|
||||
"Content-Type": "application/json",
|
||||
"Cache-Control": "no-store",
|
||||
const body = await readFile(file)
|
||||
response.writeHead(candidate === "404.html" ? 404 : 200, {
|
||||
"Content-Type":
|
||||
contentTypes[path.extname(file)] ?? "application/octet-stream",
|
||||
"Cache-Control": file.includes(`${path.sep}_next${path.sep}static`)
|
||||
? "public, max-age=31536000, immutable"
|
||||
: "no-cache",
|
||||
})
|
||||
.end("{}")
|
||||
} catch (error) {
|
||||
response.writeHead(400, { "Content-Type": "application/json" }).end(
|
||||
JSON.stringify({
|
||||
error:
|
||||
error instanceof TypeError
|
||||
? "Could not reach the server. Check the address and try again."
|
||||
: error.message,
|
||||
})
|
||||
)
|
||||
} finally {
|
||||
changingServer = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleRequest(request, response) {
|
||||
if (request.headers.host !== new URL(origin).host) {
|
||||
response.writeHead(403).end()
|
||||
return
|
||||
}
|
||||
const url = new URL(request.url, origin)
|
||||
if (url.pathname === "/__desktop/server" && request.method === "POST") {
|
||||
void saveServer(request, response)
|
||||
return
|
||||
}
|
||||
if (changingServer) {
|
||||
response.writeHead(503).end("Switching server")
|
||||
return
|
||||
}
|
||||
// Only data routes go to the remote server. All UI and auth routes stay local.
|
||||
const remote =
|
||||
config && /^\/api\/(song|album|artist|playlist|user)\//.test(url.pathname)
|
||||
const target = new URL(
|
||||
`${url.pathname}${url.search}`,
|
||||
remote ? config.serverUrl : `http://127.0.0.1:${nextPort}`
|
||||
)
|
||||
const headers = {
|
||||
...request.headers,
|
||||
host: remote ? target.host : request.headers.host,
|
||||
}
|
||||
if (remote) {
|
||||
delete headers.origin
|
||||
// Convex Auth uses __Host- cookie names on public HTTPS servers.
|
||||
// Forward only the access token, never the local refresh token.
|
||||
const token = request.headers.cookie
|
||||
?.split(";")
|
||||
.map((part) => part.trim())
|
||||
.find((part) => part.startsWith("__convexAuthJWT="))
|
||||
?.slice("__convexAuthJWT=".length)
|
||||
delete headers.cookie
|
||||
if (token) {
|
||||
const prefix = /(localhost|127\.0\.0\.1):\d+/.test(target.host)
|
||||
? ""
|
||||
: "__Host-"
|
||||
headers.cookie = `${prefix}__convexAuthJWT=${token}`
|
||||
return response.end(request.method === "HEAD" ? undefined : body)
|
||||
} catch {
|
||||
// Try the next candidate.
|
||||
}
|
||||
}
|
||||
delete headers.connection
|
||||
const upstream = (target.protocol === "https:" ? httpsRequest : httpRequest)(
|
||||
target,
|
||||
{
|
||||
method: request.method,
|
||||
headers,
|
||||
},
|
||||
(incoming) => {
|
||||
// Never redirect the window to remote HTML or accept remote session cookies.
|
||||
const resultHeaders = { ...incoming.headers }
|
||||
if (remote) delete resultHeaders["set-cookie"]
|
||||
response.writeHead(incoming.statusCode ?? 502, resultHeaders)
|
||||
incoming.on("error", () => response.destroy())
|
||||
incoming.pipe(response)
|
||||
}
|
||||
)
|
||||
upstream.on("error", () => {
|
||||
if (!response.headersSent) response.writeHead(502)
|
||||
response.end("Server unavailable")
|
||||
})
|
||||
request.on("aborted", () => upstream.destroy())
|
||||
response.on("close", () => upstream.destroy())
|
||||
request.pipe(upstream)
|
||||
response.writeHead(404).end()
|
||||
}
|
||||
|
||||
function openWindow() {
|
||||
@@ -239,7 +86,7 @@ function openWindow() {
|
||||
(_contents, _permission, callback) => callback(false)
|
||||
)
|
||||
session.defaultSession.setPermissionCheckHandler(() => false)
|
||||
window.loadURL(`${origin}${config ? "/" : "/desktop"}`).catch(console.error)
|
||||
window.loadURL(`${origin}/`).catch(console.error)
|
||||
window.on("closed", () => {
|
||||
window = undefined
|
||||
})
|
||||
@@ -254,18 +101,15 @@ else {
|
||||
app
|
||||
.whenReady()
|
||||
.then(async () => {
|
||||
try {
|
||||
config = parseServer(
|
||||
JSON.parse(await readFile(configPath(), "utf8")).hostname
|
||||
)
|
||||
} catch {
|
||||
config = undefined
|
||||
}
|
||||
await startWeb()
|
||||
gateway = createServer(handleRequest)
|
||||
server = createServer((request, response) => {
|
||||
serveStatic(request, response).catch(() => {
|
||||
if (!response.headersSent) response.writeHead(500)
|
||||
response.end()
|
||||
})
|
||||
})
|
||||
await new Promise((resolve, reject) => {
|
||||
gateway.once("error", reject)
|
||||
gateway.listen(47836, "127.0.0.1", resolve)
|
||||
server.once("error", reject)
|
||||
server.listen(47836, "127.0.0.1", resolve)
|
||||
})
|
||||
Menu.setApplicationMenu(
|
||||
Menu.buildFromTemplate([
|
||||
@@ -275,7 +119,7 @@ else {
|
||||
submenu: [
|
||||
{
|
||||
label: "Change server…",
|
||||
click: () => window?.loadURL(`${origin}/desktop`),
|
||||
click: () => window?.loadURL(`${origin}/server`),
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -294,10 +138,7 @@ else {
|
||||
app.quit()
|
||||
})
|
||||
}
|
||||
app.on("before-quit", () => {
|
||||
nextProcess?.kill()
|
||||
gateway?.close()
|
||||
})
|
||||
app.on("before-quit", () => server?.close())
|
||||
app.on("window-all-closed", () => {
|
||||
if (process.platform !== "darwin") app.quit()
|
||||
})
|
||||
@@ -11,8 +11,7 @@
|
||||
"build:windows": "pnpm build:web && node scripts/package.mjs windows",
|
||||
"build:linux": "pnpm build:web && node scripts/package.mjs linux",
|
||||
"build:web": "node scripts/build-web.mjs",
|
||||
"typecheck": "node --check main.cjs && node --check server-config.cjs && node --check scripts/build-web.mjs && node --check scripts/package.mjs && node --check scripts/prune-native-images.mjs && node --check scripts/materialize-links.mjs",
|
||||
"test": "node --test scripts/build.test.mjs"
|
||||
"typecheck": "node --check main.cjs && node --check scripts/build-web.mjs && node --check scripts/package.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"electron": "45.3.4",
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { execFileSync } from "node:child_process"
|
||||
import { createRequire } from "node:module"
|
||||
import { cp, mkdir, rm, readdir, readlink, realpath } from "node:fs/promises"
|
||||
import { cp, rm } from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import { materializeLinks } from "./materialize-links.mjs"
|
||||
import { pruneNativeImages } from "./prune-native-images.mjs"
|
||||
import { fileURLToPath } from "node:url"
|
||||
|
||||
// Builds the web app's static export and copies it to apps/desktop/web,
|
||||
// which main.cjs serves and package.mjs ships.
|
||||
const desktopRoot = fileURLToPath(new URL("../", import.meta.url))
|
||||
const web = path.resolve(desktopRoot, "../web")
|
||||
const webRequire = createRequire(path.join(web, "package.json"))
|
||||
@@ -15,57 +15,10 @@ execFileSync(
|
||||
{
|
||||
cwd: web,
|
||||
stdio: "inherit",
|
||||
env: {
|
||||
...process.env,
|
||||
OTUNES_DESKTOP_BUILD: "1",
|
||||
NEXT_PUBLIC_CONVEX_URL: "",
|
||||
},
|
||||
env: { ...process.env, OTUNES_STATIC_EXPORT: "1" },
|
||||
}
|
||||
)
|
||||
|
||||
// Junction fallbacks on Windows can point back into the developer's checkout.
|
||||
// Reject them rather than shipping an installer that only works on that machine.
|
||||
const standalone = path.join(web, ".next-desktop/standalone")
|
||||
async function checkLinks(directory) {
|
||||
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
||||
const file = path.join(directory, entry.name)
|
||||
if (entry.isSymbolicLink()) {
|
||||
const target = await readlink(file)
|
||||
const resolved = await realpath(file)
|
||||
const relative = path.relative(standalone, resolved)
|
||||
if (
|
||||
path.isAbsolute(target) ||
|
||||
relative === ".." ||
|
||||
relative.startsWith(`..${path.sep}`) ||
|
||||
path.isAbsolute(relative)
|
||||
) {
|
||||
throw new Error(
|
||||
"The standalone bundle contains a non-relocatable link. Enable symlink permissions or Windows Developer Mode and rebuild."
|
||||
)
|
||||
}
|
||||
} else if (entry.isDirectory()) {
|
||||
await checkLinks(file)
|
||||
}
|
||||
}
|
||||
}
|
||||
await checkLinks(standalone)
|
||||
const destination = path.join(desktopRoot, "web")
|
||||
await rm(destination, { recursive: true, force: true })
|
||||
await cp(standalone, destination, {
|
||||
recursive: true,
|
||||
verbatimSymlinks: true,
|
||||
filter: (file) => !path.basename(file).startsWith(".env"),
|
||||
})
|
||||
const app = path.join(destination, "apps/web")
|
||||
await mkdir(path.join(app, ".next-desktop"), { recursive: true })
|
||||
await cp(
|
||||
path.join(web, ".next-desktop/static"),
|
||||
path.join(app, ".next-desktop/static"),
|
||||
{ recursive: true }
|
||||
)
|
||||
await cp(path.join(web, "public"), path.join(app, "public"), {
|
||||
recursive: true,
|
||||
})
|
||||
|
||||
await materializeLinks(destination)
|
||||
await pruneNativeImages(destination)
|
||||
await cp(path.join(web, "out"), destination, { recursive: true })
|
||||
@@ -1,104 +0,0 @@
|
||||
import { test } from "node:test"
|
||||
import assert from "node:assert/strict"
|
||||
import {
|
||||
mkdtemp,
|
||||
mkdir,
|
||||
writeFile,
|
||||
readFile,
|
||||
rm,
|
||||
access,
|
||||
symlink,
|
||||
lstat,
|
||||
} from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { pruneNativeImages } from "./prune-native-images.mjs"
|
||||
import { materializeLinks } from "./materialize-links.mjs"
|
||||
|
||||
async function fixture(run) {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "otunes-build-"))
|
||||
try {
|
||||
await run(directory)
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
test("the UI bundle drops unused Sharp binaries but keeps JavaScript and package metadata", async () => {
|
||||
await fixture(async (directory) => {
|
||||
const lib = path.join(
|
||||
directory,
|
||||
"node_modules",
|
||||
"@img",
|
||||
"sharp-linux-x64",
|
||||
"lib"
|
||||
)
|
||||
await mkdir(lib, { recursive: true })
|
||||
for (const file of [
|
||||
"sharp.node",
|
||||
"libvips-cpp.so.8.17.3",
|
||||
"index.js",
|
||||
"debug.node.js",
|
||||
"package.json",
|
||||
])
|
||||
await writeFile(path.join(lib, file), file)
|
||||
await pruneNativeImages(directory)
|
||||
for (const file of ["sharp.node", "libvips-cpp.so.8.17.3"])
|
||||
await assert.rejects(access(path.join(lib, file)))
|
||||
assert.equal(await readFile(path.join(lib, "index.js"), "utf8"), "index.js")
|
||||
await access(path.join(lib, "debug.node.js"))
|
||||
await access(path.join(lib, "package.json"))
|
||||
})
|
||||
})
|
||||
|
||||
test("new native dependencies fail the UI build instead of shipping a build-host binary", async () => {
|
||||
await fixture(async (directory) => {
|
||||
await writeFile(path.join(directory, "new-dependency.node"), "fixture")
|
||||
await assert.rejects(
|
||||
pruneNativeImages(directory),
|
||||
/Unexpected native dependency/
|
||||
)
|
||||
await access(path.join(directory, "new-dependency.node"))
|
||||
})
|
||||
})
|
||||
|
||||
test("pnpm links become real copies that keep each package's dependency versions", async () => {
|
||||
await fixture(async (directory) => {
|
||||
const store = path.join(directory, "node_modules", ".pnpm")
|
||||
async function storePackage(id, name, version, dependencies = {}) {
|
||||
const root = path.join(store, id, "node_modules")
|
||||
await mkdir(path.join(root, name), { recursive: true })
|
||||
await writeFile(path.join(root, name, "package.json"), version)
|
||||
for (const [dependency, target] of Object.entries(dependencies))
|
||||
await symlink(
|
||||
path.relative(
|
||||
root,
|
||||
path.join(store, target, "node_modules", dependency)
|
||||
),
|
||||
path.join(root, dependency)
|
||||
)
|
||||
}
|
||||
await storePackage("react@1", "react", "1")
|
||||
await storePackage("react@2", "react", "2")
|
||||
await storePackage("next@1", "next", "next", { react: "react@1" })
|
||||
await storePackage("convex@1", "convex", "convex", { react: "react@2" })
|
||||
const app = path.join(directory, "apps", "web", "node_modules")
|
||||
await mkdir(app, { recursive: true })
|
||||
await symlink(
|
||||
"../../../node_modules/.pnpm/next@1/node_modules/next",
|
||||
path.join(app, "next")
|
||||
)
|
||||
await symlink(
|
||||
"../../../node_modules/.pnpm/convex@1/node_modules/convex",
|
||||
path.join(app, "convex")
|
||||
)
|
||||
|
||||
await materializeLinks(directory)
|
||||
|
||||
const read = (file) => readFile(path.join(app, file), "utf8")
|
||||
assert.equal(await read("next/node_modules/react/package.json"), "1")
|
||||
assert.equal(await read("convex/node_modules/react/package.json"), "2")
|
||||
assert.equal((await lstat(path.join(app, "next"))).isSymbolicLink(), false)
|
||||
await assert.rejects(access(store))
|
||||
})
|
||||
})
|
||||
@@ -1,64 +0,0 @@
|
||||
import { cp, readdir, realpath, rm } from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
|
||||
// Installers cannot carry pnpm's symlinks: NSIS extracts them as broken files
|
||||
// and electron-builder drops the `.pnpm` store. Replace every link outside the
|
||||
// store with a real copy, nesting each package's dependencies under it (npm v2
|
||||
// layout) so Node resolves the same versions pnpm chose. Then drop the store.
|
||||
export async function materializeLinks(directory) {
|
||||
const store = path.join(directory, "node_modules", ".pnpm")
|
||||
for (const link of await findLinks(directory, store)) {
|
||||
const real = await realpath(link)
|
||||
await rm(link)
|
||||
await copyPackage(real, link, new Set())
|
||||
}
|
||||
await rm(store, { recursive: true, force: true })
|
||||
}
|
||||
|
||||
async function findLinks(directory, store) {
|
||||
const links = []
|
||||
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
||||
const file = path.join(directory, entry.name)
|
||||
if (file === store) continue
|
||||
if (entry.isSymbolicLink()) links.push(file)
|
||||
else if (entry.isDirectory()) links.push(...(await findLinks(file, store)))
|
||||
}
|
||||
return links
|
||||
}
|
||||
|
||||
// `real` is <store>/<id>/node_modules/<name>; its siblings are its dependencies.
|
||||
async function copyPackage(real, destination, ancestors) {
|
||||
const match = /^(.*[\\/]\.pnpm[\\/][^\\/]+[\\/]node_modules)[\\/](.+)$/.exec(
|
||||
real
|
||||
)
|
||||
if (!match) throw new Error(`Link outside the pnpm store: ${real}`)
|
||||
const [, root, name] = match
|
||||
await cp(real, destination, { recursive: true })
|
||||
const chain = new Set(ancestors).add(real)
|
||||
for (const dependency of await packageNames(root)) {
|
||||
if (dependency === name.split(path.sep).join("/")) continue
|
||||
const source = await realpath(path.join(root, dependency))
|
||||
// A package that depends on an ancestor resolves it by walking up.
|
||||
if (chain.has(source)) continue
|
||||
await copyPackage(
|
||||
source,
|
||||
path.join(destination, "node_modules", dependency),
|
||||
chain
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Package names in a node_modules directory, including @scope/name.
|
||||
async function packageNames(directory) {
|
||||
const names = []
|
||||
for (const entry of await readdir(directory)) {
|
||||
if (entry.startsWith(".")) continue
|
||||
if (!entry.startsWith("@")) {
|
||||
names.push(entry)
|
||||
continue
|
||||
}
|
||||
for (const scoped of await readdir(path.join(directory, entry)))
|
||||
names.push(`${entry}/${scoped}`)
|
||||
}
|
||||
return names
|
||||
}
|
||||
@@ -20,8 +20,10 @@ if (!architectures.every((arch) => arch === "x64" || arch === "arm64"))
|
||||
const staging = path.join(desktopRoot, ".package")
|
||||
await rm(staging, { recursive: true, force: true })
|
||||
await mkdir(staging, { recursive: true })
|
||||
for (const file of ["main.cjs", "server-config.cjs"])
|
||||
await copyFile(path.join(desktopRoot, file), path.join(staging, file))
|
||||
await copyFile(
|
||||
path.join(desktopRoot, "main.cjs"),
|
||||
path.join(staging, "main.cjs")
|
||||
)
|
||||
const pkg = JSON.parse(
|
||||
await readFile(path.join(desktopRoot, "package.json"), "utf8")
|
||||
)
|
||||
@@ -49,7 +51,7 @@ for (const arch of architectures) {
|
||||
artifactName: "oTunes-${version}-${os}-${arch}.${ext}",
|
||||
icon: path.resolve(desktopRoot, "../web/public/logo.png"),
|
||||
directories: { app: staging, output: path.join(desktopRoot, "dist") },
|
||||
files: ["main.cjs", "server-config.cjs", "package.json"],
|
||||
files: ["main.cjs", "package.json"],
|
||||
extraResources: [
|
||||
{ from: path.join(desktopRoot, "web"), to: "web", filter: ["**/*"] },
|
||||
],
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { readdir, rm } from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
|
||||
// Desktop images bypass Next's optimizer. Its traced Sharp binaries are unused
|
||||
// and match the build host, not the target (Windows installers build on Linux).
|
||||
export async function pruneNativeImages(directory) {
|
||||
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
||||
const file = path.join(directory, entry.name)
|
||||
if (entry.isDirectory()) await pruneNativeImages(file)
|
||||
else if (
|
||||
entry.isFile() &&
|
||||
/\.(node|dylib|dll)$|\.so(?:\.\d+)*$/.test(entry.name)
|
||||
) {
|
||||
if (!file.includes(`${path.sep}@img${path.sep}sharp-`)) {
|
||||
throw new Error(
|
||||
`Unexpected native dependency in the desktop web bundle: ${file}`
|
||||
)
|
||||
}
|
||||
await rm(file)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
// Match mobile's public-domain and local-network Convex conventions.
|
||||
function parseServer(input) {
|
||||
if (typeof input !== "string" || !input.trim())
|
||||
throw new Error("Enter your server address.")
|
||||
const raw = input
|
||||
.trim()
|
||||
.replace(/^https?:\/\//i, "")
|
||||
.replace(/\/+$/, "")
|
||||
if (/[\s/@?#\\]/.test(raw))
|
||||
throw new Error("Enter a hostname, without a path or credentials.")
|
||||
const parsed = new URL(`https://${raw}`)
|
||||
const local =
|
||||
parsed.hostname === "localhost" ||
|
||||
parsed.hostname.endsWith(".local") ||
|
||||
/^\d{1,3}(\.\d{1,3}){3}$/.test(parsed.hostname)
|
||||
const protocol = local ? "http:" : "https:"
|
||||
const hostname = parsed.host
|
||||
return {
|
||||
hostname,
|
||||
serverUrl: `${protocol}//${hostname}`,
|
||||
convexUrl: local
|
||||
? `${protocol}//${parsed.hostname}:3210`
|
||||
: `${protocol}//convex.${hostname}`,
|
||||
}
|
||||
}
|
||||
module.exports = { parseServer }
|
||||
@@ -1,44 +1,13 @@
|
||||
import { buildConvexUrl, isLocalHost } from "@otunes/convex/server-url"
|
||||
import type { ServerConfig } from "@otunes/convex/server-url"
|
||||
|
||||
export type ServerConfig = {
|
||||
/** Raw hostname the user entered, e.g. `music.example.com` or `192.168.86.25:3000` */
|
||||
hostname: string
|
||||
/** Base URL for the Next.js server, e.g. `https://music.example.com` */
|
||||
serverUrl: string
|
||||
/** Convex deployment URL, e.g. `https://convex.music.example.com` */
|
||||
convexUrl: string
|
||||
}
|
||||
export {
|
||||
parseServerHostname,
|
||||
type ServerConfig,
|
||||
} from "@otunes/convex/server-url"
|
||||
|
||||
const SERVER_CONFIG_KEY = "otunes.server-config"
|
||||
const LEGACY_SERVER_CONFIG_KEY = "otunes:server-config"
|
||||
|
||||
function normalizeHostnameInput(input: string): string {
|
||||
return input
|
||||
.trim()
|
||||
.replace(/^https?:\/\//i, "")
|
||||
.replace(/\/+$/, "")
|
||||
}
|
||||
|
||||
function buildServerUrl(hostname: string): string {
|
||||
const protocol = isLocalHost(hostname) ? "http" : "https"
|
||||
return `${protocol}://${hostname}`
|
||||
}
|
||||
|
||||
export function parseServerHostname(input: string): ServerConfig | null {
|
||||
const hostname = normalizeHostnameInput(input)
|
||||
if (!hostname) return null
|
||||
|
||||
try {
|
||||
const serverUrl = buildServerUrl(hostname)
|
||||
const convexUrl = buildConvexUrl(hostname)
|
||||
new URL(serverUrl)
|
||||
new URL(convexUrl)
|
||||
return { hostname, serverUrl, convexUrl }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadServerConfig(
|
||||
getItem: (key: string) => Promise<string | null>
|
||||
): Promise<ServerConfig | null> {
|
||||
|
||||
@@ -15,7 +15,7 @@ export async function GET(
|
||||
const { id } = await params
|
||||
|
||||
try {
|
||||
const song = await getSongSource(id)
|
||||
const song = await getSongSource(id, request)
|
||||
|
||||
const quality = request.nextUrl.searchParams.get("quality")
|
||||
const preferAtmos =
|
||||
|
||||
@@ -35,7 +35,7 @@ export async function GET(
|
||||
const preferAtmos =
|
||||
request.nextUrl.searchParams.get("preferAtmos") === "true"
|
||||
// Resolve the source even when a job is cached so every segment is authorized.
|
||||
const song = await getSongSource(id)
|
||||
const song = await getSongSource(id, request)
|
||||
const job =
|
||||
getExistingHlsJob(id, quality, preferAtmos) ??
|
||||
(await ensureHlsJob(song, quality, preferAtmos))
|
||||
|
||||
@@ -120,7 +120,7 @@ export async function GET(
|
||||
const { browser } = userAgent(request)
|
||||
|
||||
try {
|
||||
const song = await getSongSource(id)
|
||||
const song = await getSongSource(id, request)
|
||||
|
||||
const {
|
||||
source: originalCodec,
|
||||
|
||||
@@ -1,21 +1,37 @@
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import sharp from "sharp"
|
||||
import { getConvexClient, getConvexServerUrl } from "@/lib/convex-server"
|
||||
import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server"
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import type { NextRequest } from "next/server"
|
||||
import {
|
||||
convexServerOptions,
|
||||
getConvexClient,
|
||||
getConvexServerUrl,
|
||||
} from "@/lib/convex-server"
|
||||
|
||||
const AVATAR_SIZE = 256
|
||||
|
||||
/**
|
||||
* Serves a profile photo from Convex storage, downscaled. URLs carry the
|
||||
* storage id (`?v=`), so a new photo gets a new URL and responses can be
|
||||
* cached for good.
|
||||
* cached for good. Requires a session, from the cookie or a `token` query
|
||||
* parameter (desktop apps on another origin).
|
||||
*/
|
||||
export async function GET(
|
||||
_request: Request,
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const { id } = await params
|
||||
try {
|
||||
const token =
|
||||
request.nextUrl.searchParams.get("token") ??
|
||||
(await convexAuthNextjsToken())
|
||||
if (
|
||||
!(await fetchQuery(api.auth.currentUser, {}, convexServerOptions(token)))
|
||||
)
|
||||
return new Response("Not found", { status: 404 })
|
||||
|
||||
const storageUrl = await getConvexClient().query(
|
||||
api.users.getProfileImageUrl,
|
||||
{ userId: id as Id<"users"> }
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import { notFound } from "next/navigation"
|
||||
import { connection } from "next/server"
|
||||
import { DesktopServerForm } from "@/components/desktop-server-form"
|
||||
|
||||
export default async function DesktopServerPage() {
|
||||
await connection()
|
||||
if (process.env.OTUNES_DESKTOP !== "1") notFound()
|
||||
return (
|
||||
<DesktopServerForm hostname={process.env.OTUNES_DESKTOP_HOSTNAME ?? ""} />
|
||||
)
|
||||
}
|
||||
@@ -73,8 +73,6 @@ export default function RootLayout({
|
||||
}: Readonly<{
|
||||
children: React.ReactNode
|
||||
}>) {
|
||||
const desktop = process.env.OTUNES_DESKTOP === "1"
|
||||
const needsServer = desktop && !process.env.PUBLIC_CONVEX_URL
|
||||
const content = (
|
||||
<ThemeProvider defaultTheme="system">
|
||||
{children}
|
||||
@@ -94,15 +92,11 @@ export default function RootLayout({
|
||||
)}
|
||||
>
|
||||
<body className={"overflow-x-hidden"}>
|
||||
{needsServer ? (
|
||||
content
|
||||
) : staticExport ? (
|
||||
{staticExport ? (
|
||||
<ConvexClientProvider>{content}</ConvexClientProvider>
|
||||
) : (
|
||||
<ConvexAuthNextjsServerProvider storageNamespace="otunes">
|
||||
<ConvexClientProvider convexUrl={process.env.PUBLIC_CONVEX_URL}>
|
||||
{content}
|
||||
</ConvexClientProvider>
|
||||
<ConvexClientProvider>{content}</ConvexClientProvider>
|
||||
</ConvexAuthNextjsServerProvider>
|
||||
)}
|
||||
</body>
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { notFound } from "next/navigation"
|
||||
|
||||
import { ServerForm } from "@/components/server-form"
|
||||
|
||||
export default function ServerPage() {
|
||||
// The server build is the server; only desktop apps pick one.
|
||||
if (process.env.OTUNES_STATIC_EXPORT !== "1") notFound()
|
||||
return <ServerForm />
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { playlistPath } from "@/lib/routes"
|
||||
import { authedUrl, staticExport } from "@/lib/server"
|
||||
|
||||
import {
|
||||
Disc3,
|
||||
@@ -11,6 +12,7 @@ import {
|
||||
Mic,
|
||||
Music2,
|
||||
Search,
|
||||
Server,
|
||||
Settings,
|
||||
Star,
|
||||
} from "lucide-react"
|
||||
@@ -189,7 +191,10 @@ export function AppSidebar() {
|
||||
<SidebarMenuButton size="lg" className="min-w-0 flex-1">
|
||||
<Avatar size="sm" key={user?.image ?? "fallback"}>
|
||||
{user?.image ? (
|
||||
<AvatarImage src={user.image} alt={user.name} />
|
||||
<AvatarImage
|
||||
src={authedUrl(user.image)}
|
||||
alt={user.name}
|
||||
/>
|
||||
) : null}
|
||||
<AvatarFallback>{fallbackLetters}</AvatarFallback>
|
||||
</Avatar>
|
||||
@@ -212,6 +217,15 @@ export function AppSidebar() {
|
||||
Options
|
||||
<Settings />
|
||||
</DropdownMenuItem>
|
||||
{staticExport ? (
|
||||
<DropdownMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => router.push("/server")}
|
||||
>
|
||||
Change Server
|
||||
<Server />
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
{optionsOpen ? (
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
"use client"
|
||||
|
||||
import { ConvexAuthNextjsProvider } from "@convex-dev/auth/nextjs"
|
||||
import { ConvexAuthProvider } from "@convex-dev/auth/react"
|
||||
import { ConvexAuthProvider, useAuthToken } from "@convex-dev/auth/react"
|
||||
import { buildConvexUrl } from "@otunes/convex/server-url"
|
||||
import { ConvexReactClient } from "convex/react"
|
||||
import { ReactNode } from "react"
|
||||
import { usePathname, useRouter } from "next/navigation"
|
||||
import { ReactNode, useEffect } from "react"
|
||||
|
||||
import { PersistentCacheProvider } from "@/components/persistent-cache-provider"
|
||||
import {
|
||||
selectedServer,
|
||||
setMediaToken,
|
||||
staticExport,
|
||||
useSelectedServer,
|
||||
} from "@/lib/server"
|
||||
|
||||
// Server rendering never runs Convex queries, so this URL is never contacted.
|
||||
const SSR_CONVEX_URL = "http://127.0.0.1:3210"
|
||||
@@ -18,37 +25,50 @@ function browserConvexUrl() {
|
||||
return buildConvexUrl(host, protocol === "https:" ? "https" : "http")
|
||||
}
|
||||
|
||||
function getConvexClient(convexUrl: string | undefined) {
|
||||
if (!client) {
|
||||
client = new ConvexReactClient(
|
||||
typeof window === "undefined"
|
||||
? SSR_CONVEX_URL
|
||||
: (convexUrl ??
|
||||
process.env.NEXT_PUBLIC_CONVEX_URL ??
|
||||
browserConvexUrl())
|
||||
)
|
||||
}
|
||||
function getConvexClient(convexUrl: string) {
|
||||
client ??= new ConvexReactClient(convexUrl)
|
||||
return client
|
||||
}
|
||||
|
||||
export function ConvexClientProvider({
|
||||
convexUrl,
|
||||
children,
|
||||
}: {
|
||||
convexUrl?: string
|
||||
children: ReactNode
|
||||
}) {
|
||||
const client = getConvexClient(convexUrl)
|
||||
const content = <PersistentCacheProvider>{children}</PersistentCacheProvider>
|
||||
// Static exports have no Next.js server to hold the session in cookies, so
|
||||
// tokens live in localStorage, as in the mobile app.
|
||||
return process.env.OTUNES_STATIC_EXPORT === "1" ? (
|
||||
<ConvexAuthProvider client={client} storageNamespace="otunes">
|
||||
{content}
|
||||
</ConvexAuthProvider>
|
||||
) : (
|
||||
<ConvexAuthNextjsProvider client={client}>
|
||||
{content}
|
||||
export function ConvexClientProvider({ children }: { children: ReactNode }) {
|
||||
if (staticExport) return <ExportProviders>{children}</ExportProviders>
|
||||
const url =
|
||||
typeof window === "undefined"
|
||||
? SSR_CONVEX_URL
|
||||
: (process.env.NEXT_PUBLIC_CONVEX_URL ?? browserConvexUrl())
|
||||
return (
|
||||
<ConvexAuthNextjsProvider client={getConvexClient(url)}>
|
||||
<PersistentCacheProvider>{children}</PersistentCacheProvider>
|
||||
</ConvexAuthNextjsProvider>
|
||||
)
|
||||
}
|
||||
|
||||
// Static exports pick a server at /server first. With no Next.js server to
|
||||
// hold the session in cookies, tokens live in localStorage, keyed by the
|
||||
// Convex URL, as in the mobile app. Changing servers reloads the page.
|
||||
function ExportProviders({ children }: { children: ReactNode }) {
|
||||
const server = useSelectedServer()
|
||||
const pathname = usePathname()
|
||||
const router = useRouter()
|
||||
const onServerPage = pathname === "/server"
|
||||
|
||||
useEffect(() => {
|
||||
if (!onServerPage && !selectedServer()) router.replace("/server")
|
||||
}, [onServerPage, router])
|
||||
|
||||
if (onServerPage) return children
|
||||
if (!server) return null
|
||||
return (
|
||||
<ConvexAuthProvider client={getConvexClient(server.convexUrl)}>
|
||||
<MediaTokenSync />
|
||||
<PersistentCacheProvider>{children}</PersistentCacheProvider>
|
||||
</ConvexAuthProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function MediaTokenSync() {
|
||||
const token = useAuthToken()
|
||||
// Set during render so players created in this commit see the new token.
|
||||
setMediaToken(token)
|
||||
return null
|
||||
}
|
||||
@@ -2,11 +2,14 @@
|
||||
|
||||
import { ArrowUpRight } from "lucide-react"
|
||||
|
||||
import { serverOrigin } from "@/lib/server"
|
||||
|
||||
export function OpenAppButton() {
|
||||
function openApp() {
|
||||
const link = new URL("otunes://open")
|
||||
// The app understands share links (/album/<id>), not in-app /album?id=<id>.
|
||||
const page = new URL(window.location.href)
|
||||
const { pathname, search } = window.location
|
||||
const page = new URL(`${pathname}${search}`, serverOrigin())
|
||||
const id = page.searchParams.get("id")
|
||||
if (id && /^\/(album|artist|playlist)$/.test(page.pathname)) {
|
||||
page.pathname += `/${encodeURIComponent(id)}`
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { authedUrl } from "@/lib/server"
|
||||
|
||||
import { useAction, useMutation, useQuery } from "convex/react"
|
||||
import { MoreHorizontal, Trash2, Upload, UserPlus } from "lucide-react"
|
||||
import { useCallback, useEffect, useRef, useState } from "react"
|
||||
@@ -148,7 +150,9 @@ function UserAvatar({
|
||||
key={user.image ?? "fallback"}
|
||||
size={size === "sm" ? "sm" : "default"}
|
||||
>
|
||||
{user.image ? <AvatarImage src={user.image} alt={user.name} /> : null}
|
||||
{user.image ? (
|
||||
<AvatarImage src={authedUrl(user.image)} alt={user.name} />
|
||||
) : null}
|
||||
<AvatarFallback>{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { authedUrl } from "@/lib/server"
|
||||
|
||||
import {
|
||||
useState,
|
||||
useEffect,
|
||||
@@ -247,15 +249,11 @@ function loadAudioSource(
|
||||
): AudioSourceCleanup {
|
||||
let disposed = false
|
||||
let hlsInstance: Hls | null = null
|
||||
const directUrl = songPlayPath(
|
||||
songId,
|
||||
settings.playbackQuality,
|
||||
settings.preferAtmos
|
||||
const directUrl = authedUrl(
|
||||
songPlayPath(songId, settings.playbackQuality, settings.preferAtmos)
|
||||
)
|
||||
const hlsUrl = songHlsPlaylistPath(
|
||||
songId,
|
||||
settings.playbackQuality,
|
||||
settings.preferAtmos
|
||||
const hlsUrl = authedUrl(
|
||||
songHlsPlaylistPath(songId, settings.playbackQuality, settings.preferAtmos)
|
||||
)
|
||||
|
||||
const onReadyToPlay = () => {
|
||||
|
||||
@@ -10,33 +10,41 @@ import {
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
} from "@/components/ui/field"
|
||||
import { clearPersistentCache } from "@/lib/persistent-cache"
|
||||
import { saveServer, selectedServer } from "@/lib/server"
|
||||
import { parseServerHostname } from "@otunes/convex/server-url"
|
||||
|
||||
export function DesktopServerForm({ hostname }: { hostname: string }) {
|
||||
const [address, setAddress] = useState(hostname)
|
||||
// Picks the oTunes server for static exports (desktop apps). Saving reloads
|
||||
// the app so Convex connects to the new server.
|
||||
export function ServerForm() {
|
||||
const [address, setAddress] = useState(() => selectedServer()?.hostname ?? "")
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
async function connect(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault()
|
||||
const server = parseServerHostname(address)
|
||||
if (!server) {
|
||||
setError("Enter a hostname, like music.example.com.")
|
||||
return
|
||||
}
|
||||
setError(null)
|
||||
setSubmitting(true)
|
||||
try {
|
||||
const response = await fetch("/__desktop/server", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ hostname: address }),
|
||||
// Opaque, but it fails when the Convex server cannot be reached.
|
||||
await fetch(`${server.convexUrl}/version`, {
|
||||
mode: "no-cors",
|
||||
signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
if (!response.ok) {
|
||||
const result: { error?: string } = await response.json()
|
||||
throw new Error(result.error ?? "Could not connect to the server.")
|
||||
}
|
||||
window.location.replace("/signin")
|
||||
} catch (error) {
|
||||
setError(
|
||||
error instanceof Error ? error.message : "Could not save the server."
|
||||
)
|
||||
} catch {
|
||||
setError("Could not reach the server. Check the address and try again.")
|
||||
setSubmitting(false)
|
||||
return
|
||||
}
|
||||
if (server.convexUrl !== selectedServer()?.convexUrl)
|
||||
await clearPersistentCache()
|
||||
saveServer(server)
|
||||
window.location.replace("/signin")
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -1,7 +1,9 @@
|
||||
import { serverUrl } from "@/lib/server"
|
||||
|
||||
export type CoverImageSize = 64 | 128 | 192 | 256 | 384 | 512 | 768 | 1024
|
||||
|
||||
function withCoverImageSize(uri: string, size?: CoverImageSize) {
|
||||
return size ? `${uri}?size=${size}` : uri
|
||||
return serverUrl(size ? `${uri}?size=${size}` : uri)
|
||||
}
|
||||
|
||||
export function artistCoverUrl(artistId: string, size?: CoverImageSize) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { toast } from "sonner"
|
||||
import { serverOrigin } from "@/lib/server"
|
||||
import {
|
||||
mediaShareUrl,
|
||||
type MediaShareTarget,
|
||||
@@ -7,9 +8,7 @@ import {
|
||||
export type MediaShareContext = MediaShareTarget
|
||||
|
||||
export async function copyMediaShareLink(share: MediaShareContext) {
|
||||
await navigator.clipboard.writeText(
|
||||
mediaShareUrl(window.location.origin, share)
|
||||
)
|
||||
await navigator.clipboard.writeText(mediaShareUrl(serverOrigin(), share))
|
||||
toast.success("Link Copied")
|
||||
}
|
||||
|
||||
|
||||
@@ -2,15 +2,21 @@ import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import type { NextRequest } from "next/server"
|
||||
import { convexServerOptions } from "@/lib/convex-server"
|
||||
import type { SongSource } from "@/lib/server-hls"
|
||||
|
||||
/**
|
||||
* Loads a song's file paths as the requesting listener, so Convex enforces auth
|
||||
* even if the proxy is bypassed. Throws when signed out or the song is missing.
|
||||
* 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.
|
||||
*/
|
||||
export async function getSongSource(id: string): Promise<SongSource> {
|
||||
const token = await convexAuthNextjsToken()
|
||||
export async function getSongSource(
|
||||
id: string,
|
||||
request: NextRequest
|
||||
): Promise<SongSource> {
|
||||
const token =
|
||||
request.nextUrl.searchParams.get("token") ?? (await convexAuthNextjsToken())
|
||||
const song = await fetchQuery(
|
||||
api.library.getSongSource,
|
||||
{ id: id as Id<"songs"> },
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { ServerConfig } from "@otunes/convex/server-url"
|
||||
import { useSyncExternalStore } from "react"
|
||||
|
||||
// The server build is served by the oTunes server, so media paths stay
|
||||
// relative and the session cookie authenticates them. Static exports (desktop
|
||||
// apps) are served locally and talk to a server the user picks at runtime.
|
||||
export const staticExport = process.env.OTUNES_STATIC_EXPORT === "1"
|
||||
|
||||
const SERVER_KEY = "otunes.server"
|
||||
|
||||
function readServer(): ServerConfig | null {
|
||||
if (!staticExport || typeof window === "undefined") return null
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(SERVER_KEY) ?? "null")
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
let server = readServer()
|
||||
|
||||
export function selectedServer() {
|
||||
return server
|
||||
}
|
||||
|
||||
export function saveServer(config: ServerConfig) {
|
||||
localStorage.setItem(SERVER_KEY, JSON.stringify(config))
|
||||
server = config
|
||||
}
|
||||
|
||||
const noop = () => () => {}
|
||||
|
||||
/** The picked server in static exports. `null` while prerendering. */
|
||||
export function useSelectedServer() {
|
||||
return useSyncExternalStore(noop, selectedServer, () => null)
|
||||
}
|
||||
|
||||
/** Origin of the oTunes server, for share links. */
|
||||
export function serverOrigin() {
|
||||
return server?.serverUrl ?? window.location.origin
|
||||
}
|
||||
|
||||
/** Resolves an `/api/...` path against the oTunes server. */
|
||||
export function serverUrl(path: string) {
|
||||
return server ? `${server.serverUrl}${path}` : path
|
||||
}
|
||||
|
||||
let mediaToken: string | null = null
|
||||
|
||||
/** Kept current by the auth provider in static exports. */
|
||||
export function setMediaToken(token: string | null) {
|
||||
mediaToken = token
|
||||
}
|
||||
|
||||
/**
|
||||
* URL for a route that needs a session (songs, avatars). `<audio>`, `<img>`
|
||||
* 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)
|
||||
if (!server || !mediaToken) return url
|
||||
return `${url}${url.includes("?") ? "&" : "?"}token=${encodeURIComponent(mediaToken)}`
|
||||
}
|
||||
+15
-6
@@ -1,20 +1,29 @@
|
||||
import path from "node:path"
|
||||
import type { NextConfig } from "next"
|
||||
|
||||
const desktop = process.env.OTUNES_DESKTOP_BUILD === "1"
|
||||
// `pnpm build:export` writes the UI as static files to `out`. It leaves out
|
||||
// server-only files (`*.server.ts[x]`): route handlers, the proxy, share-link
|
||||
// metadata pages and the desktop server picker.
|
||||
// `pnpm build:export` writes the UI as static files to `out`, for the desktop
|
||||
// apps. It leaves out server-only files (`*.server.ts[x]`): route handlers, the
|
||||
// proxy and share-link metadata pages.
|
||||
const staticExport = process.env.OTUNES_STATIC_EXPORT === "1"
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
output: staticExport ? "export" : "standalone",
|
||||
distDir: staticExport ? "out" : desktop ? ".next-desktop" : ".next",
|
||||
distDir: staticExport ? "out" : ".next",
|
||||
pageExtensions: staticExport
|
||||
? ["tsx", "ts"]
|
||||
: ["server.tsx", "server.ts", "tsx", "ts"],
|
||||
env: { OTUNES_STATIC_EXPORT: staticExport ? "1" : "" },
|
||||
outputFileTracingRoot: path.join(__dirname, "../../"),
|
||||
// Desktop apps load media from their own origin. Session routes take a
|
||||
// `token` parameter rather than cookies, so allowing any origin is safe.
|
||||
headers: staticExport
|
||||
? undefined
|
||||
: async () => [
|
||||
{
|
||||
source: "/api/:path*",
|
||||
headers: [{ key: "Access-Control-Allow-Origin", value: "*" }],
|
||||
},
|
||||
],
|
||||
experimental: {
|
||||
// App pages render their data from the client cache, so reusing a visited
|
||||
// page's server payload is safe and skips a round trip on revisits.
|
||||
@@ -23,7 +32,7 @@ const nextConfig: NextConfig = {
|
||||
},
|
||||
},
|
||||
images: {
|
||||
unoptimized: desktop || staticExport,
|
||||
unoptimized: staticExport,
|
||||
minimumCacheTTL: 60,
|
||||
dangerouslyAllowSVG: true,
|
||||
contentDispositionType: "attachment",
|
||||
|
||||
@@ -3,15 +3,14 @@ import {
|
||||
createRouteMatcher,
|
||||
nextjsMiddlewareRedirect,
|
||||
} from "@convex-dev/auth/nextjs/server"
|
||||
import {
|
||||
NextResponse,
|
||||
type NextRequest,
|
||||
type NextFetchEvent,
|
||||
} from "next/server"
|
||||
import { getConvexServerUrl } from "@/lib/convex-server"
|
||||
|
||||
const isAuthPage = createRouteMatcher(["/signin", "/signup"])
|
||||
// Song and avatar routes check the session themselves, from the cookie or a
|
||||
// `token` query parameter (static exports on another origin).
|
||||
const isPublic = createRouteMatcher([
|
||||
"/api/song/(.*)",
|
||||
"/api/user/:id/avatar",
|
||||
"/api/album/:id/cover",
|
||||
"/api/artist/:id/cover",
|
||||
"/api/playlist/:id/cover",
|
||||
@@ -42,15 +41,7 @@ const authMiddleware = convexAuthNextjsMiddleware(
|
||||
{ convexUrl: getConvexServerUrl() }
|
||||
)
|
||||
|
||||
export default function proxy(request: NextRequest, event: NextFetchEvent) {
|
||||
if (process.env.OTUNES_DESKTOP === "1") {
|
||||
if (request.nextUrl.pathname === "/desktop") return NextResponse.next()
|
||||
if (!process.env.PUBLIC_CONVEX_URL) {
|
||||
return NextResponse.redirect(new URL("/desktop", request.url))
|
||||
}
|
||||
}
|
||||
return authMiddleware(request, event)
|
||||
}
|
||||
export default authMiddleware
|
||||
|
||||
export const config = {
|
||||
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
|
||||
|
||||
@@ -45,3 +45,32 @@ export function buildConvexUrl(
|
||||
? `${protocol}://${convexHost}:${port}`
|
||||
: `${protocol}://${convexHost}`
|
||||
}
|
||||
|
||||
export type ServerConfig = {
|
||||
/** Raw hostname the user entered, e.g. `music.example.com` or `192.168.86.25:3000` */
|
||||
hostname: string
|
||||
/** Base URL for the Next.js server, e.g. `https://music.example.com` */
|
||||
serverUrl: string
|
||||
/** Convex deployment URL, e.g. `https://convex.music.example.com` */
|
||||
convexUrl: string
|
||||
}
|
||||
|
||||
/** Parses a user-entered server address. Local hosts use http, others https. */
|
||||
export function parseServerHostname(input: string): ServerConfig | null {
|
||||
const hostname = input
|
||||
.trim()
|
||||
.replace(/^https?:\/\//i, "")
|
||||
.replace(/\/+$/, "")
|
||||
if (!hostname) return null
|
||||
|
||||
try {
|
||||
const protocol = isLocalHost(hostname) ? "http" : "https"
|
||||
const serverUrl = `${protocol}://${hostname}`
|
||||
const convexUrl = buildConvexUrl(hostname)
|
||||
new URL(serverUrl)
|
||||
new URL(convexUrl)
|
||||
return { hostname, serverUrl, convexUrl }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user