Compare commits

..
87 changed files with 506 additions and 2924 deletions

No files matched your search

-70
View File
@@ -1,70 +0,0 @@
name: Desktop builds
on:
workflow_dispatch:
push:
tags:
- "v*"
jobs:
build:
# Both targets build in electronuserland/builder:wine. Wine lets
# electron-builder stamp the Windows executable; the Flatpak job adds
# flatpak-builder and needs a privileged container for its sandbox.
# See apps/desktop/README.md for the runner setup.
name: Desktop ${{ matrix.target }}
runs-on: ubuntu-latest
timeout-minutes: 90
strategy:
fail-fast: false
matrix:
include:
- target: windows
options: ""
- target: linux
options: --privileged
container:
image: electronuserland/builder:wine
options: ${{ matrix.options }}
env:
OTUNES_DESKTOP_REF: ${{ gitea.ref }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up pnpm
uses: pnpm/action-setup@v4
with:
version: 10.1.0
run_install: false
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: "24"
- name: Install Flatpak tools
if: matrix.target == 'linux'
run: |
apt-get update
apt-get install -y flatpak flatpak-builder
flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo
- name: Install desktop and web dependencies
run: pnpm --filter @otunes/desktop --filter @otunes/web... install --frozen-lockfile
- name: Check desktop scripts
run: pnpm --filter @otunes/desktop typecheck
- name: Build x64 and ARM64 installers
run: pnpm --filter @otunes/desktop build:${{ matrix.target }}
# Gitea's artifact service uses the v3 protocol, not GitHub's v4 service.
- name: Upload installers
uses: actions/upload-artifact@v3
with:
name: otunes-desktop-${{ matrix.target }}
path: |
apps/desktop/dist/*.exe
apps/desktop/dist/*.flatpak
if-no-files-found: error
-6
View File
@@ -47,9 +47,3 @@ docker-compose.yml
**/credentials/
**/*.ipa
**/*.apk
# Electron desktop build artifacts
apps/desktop/.package/
apps/desktop/dist/
apps/web/.next-desktop/
apps/desktop/web/
-5
View File
@@ -9,7 +9,6 @@ This project uses [pnpm workspaces](https://pnpm.io/workspaces):
| Package | Path | Description |
| --- | --- | --- |
| `@otunes/web` | `apps/web` | Next.js web app |
| `@otunes/desktop` | `apps/desktop` | Electron client for Windows and Linux |
| `@otunes/mobile` | `apps/mobile` | Expo React Native mobile app |
| `@otunes/convex` | `packages/convex` | Shared Convex backend and client types |
@@ -95,7 +94,3 @@ If Convex has to live somewhere else, set `PUBLIC_CONVEX_URL` on the container t
## Downloads
Check the releases tab for the latest downloads for apps: [Releases](https://git.abunchofknowitalls.com/joshuafhiggins/otunes/releases)
## Desktop builds
See [the desktop build guide](apps/desktop/README.md) to package the web player for Windows or Linux. The UI is bundled locally, and users choose their oTunes server before signing in.
-38
View File
@@ -1,38 +0,0 @@
# oTunes desktop
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 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.
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.
## Run and package
```sh
pnpm install
pnpm dev:desktop
# Or create installers for this OS, x64 and ARM64:
pnpm build:desktop
# Or a specific target from a Linux host:
pnpm --filter @otunes/desktop build:windows
pnpm --filter @otunes/desktop build:linux
```
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.
Flatpaks pin `org.freedesktop.Platform`, its SDK and `org.electronjs.Electron2.BaseApp` to `25.08`. Network, audio, graphics and display access are enabled. Home-directory access is not needed.
## Gitea builds
`.gitea/workflows/desktop-build.yml` runs manually and on `v*` tags, matching the Docker workflow. Both jobs run on the `ubuntu-latest` Docker runner and upload installers with `actions/upload-artifact@v3`. Tags set the installer version, so use semantic version tags such as `v1.2.3`. Manual runs use the desktop package version. Nothing is published.
Both jobs use the `electronuserland/builder:wine` container: `windows` builds x64 and ARM64 NSIS installers, and `linux` installs flatpak-builder from apt and builds x64 and ARM64 Flatpaks.
The Linux job needs two things from the runner host:
- Privileged job containers, since flatpak-builder sandboxes its build. Set `container.privileged: true` in the runner's config.
- An ARM64 binfmt handler. Register it once with `apt install qemu-user-static` on Debian/Ubuntu, which persists across reboots.
-144
View File
@@ -1,144 +0,0 @@
const { app, BrowserWindow, Menu, nativeTheme, session } = require("electron")
const { createServer } = require("node:http")
const { readFile } = require("node:fs/promises")
const path = require("node:path")
// 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"
)
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
// 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 {
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 {
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",
})
return response.end(request.method === "HEAD" ? undefined : body)
} catch {
// Try the next candidate.
}
}
response.writeHead(404).end()
}
function openWindow() {
window = new BrowserWindow({
title: "oTunes",
width: 1280,
height: 850,
backgroundColor: nativeTheme.shouldUseDarkColors ? "#000000" : "#ffffff",
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
webSecurity: true,
},
})
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }))
const restrictNavigation = (event, target) => {
if (new URL(target).origin !== origin) event.preventDefault()
}
window.webContents.on("will-navigate", restrictNavigation)
window.webContents.on("will-redirect", restrictNavigation)
session.defaultSession.setPermissionRequestHandler(
(_contents, _permission, callback) => callback(false)
)
session.defaultSession.setPermissionCheckHandler(() => false)
window.loadURL(`${origin}/`).catch(console.error)
window.on("closed", () => {
window = undefined
})
}
if (!app.requestSingleInstanceLock()) app.quit()
else {
app.on("second-instance", () => {
window?.show()
window?.focus()
})
app
.whenReady()
.then(async () => {
server = createServer((request, response) => {
serveStatic(request, response).catch(() => {
if (!response.headersSent) response.writeHead(500)
response.end()
})
})
await new Promise((resolve, reject) => {
server.once("error", reject)
server.listen(47836, "127.0.0.1", resolve)
})
Menu.setApplicationMenu(
Menu.buildFromTemplate([
...(process.platform === "darwin" ? [{ role: "appMenu" }] : []),
{
label: "Server",
submenu: [
{
label: "Change server…",
click: () => window?.loadURL(`${origin}/server`),
},
],
},
{ role: "editMenu" },
{ role: "viewMenu" },
{ role: "windowMenu" },
])
)
openWindow()
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) openWindow()
})
})
.catch((error) => {
console.error(error)
app.quit()
})
}
app.on("before-quit", () => server?.close())
app.on("window-all-closed", () => {
if (process.platform !== "darwin") app.quit()
})
-20
View File
@@ -1,20 +0,0 @@
{
"name": "@otunes/desktop",
"version": "0.0.1",
"private": true,
"description": "oTunes desktop client for Windows and Linux",
"author": "oTunes contributors",
"main": "main.cjs",
"scripts": {
"start": "pnpm build:web && electron .",
"build": "pnpm build:web && node scripts/package.mjs",
"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 scripts/build-web.mjs && node --check scripts/package.mjs"
},
"devDependencies": {
"electron": "45.3.4",
"electron-builder": "26.18.0"
}
}
-24
View File
@@ -1,24 +0,0 @@
import { execFileSync } from "node:child_process"
import { createRequire } from "node:module"
import { cp, rm } from "node:fs/promises"
import path from "node:path"
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"))
execFileSync(
process.execPath,
[webRequire.resolve("next/dist/bin/next"), "build"],
{
cwd: web,
stdio: "inherit",
env: { ...process.env, OTUNES_STATIC_EXPORT: "1" },
}
)
const destination = path.join(desktopRoot, "web")
await rm(destination, { recursive: true, force: true })
await cp(path.join(web, "out"), destination, { recursive: true })
-77
View File
@@ -1,77 +0,0 @@
import { build, Platform, Arch } from "electron-builder"
import { mkdir, copyFile, writeFile, rm, readFile } from "node:fs/promises"
import { createRequire } from "node:module"
import path from "node:path"
import { fileURLToPath } from "node:url"
// Packages stock Electron with the bundled UI from build-web.mjs.
// Usage: node scripts/package.mjs [windows|linux] [x64|arm64]
// Defaults to the host OS and both architectures. Linux hosts can build both
// targets: Windows needs Wine, ARM64 Flatpaks need qemu-user binfmt.
const desktopRoot = fileURLToPath(new URL("../", import.meta.url))
const hostTarget = { win32: "windows", linux: "linux" }[process.platform]
const [target = hostTarget, onlyArch] = process.argv.slice(2)
const platform = { windows: Platform.WINDOWS, linux: Platform.LINUX }[target]
if (!platform) throw new Error("Targets are windows or linux")
const architectures = onlyArch ? [onlyArch] : ["x64", "arm64"]
if (!architectures.every((arch) => arch === "x64" || arch === "arm64"))
throw new Error("Architectures are x64 or arm64")
const staging = path.join(desktopRoot, ".package")
await rm(staging, { recursive: true, force: true })
await mkdir(staging, { recursive: true })
await copyFile(
path.join(desktopRoot, "main.cjs"),
path.join(staging, "main.cjs")
)
const pkg = JSON.parse(
await readFile(path.join(desktopRoot, "package.json"), "utf8")
)
const ref = process.env.OTUNES_DESKTOP_REF ?? ""
if (ref.startsWith("refs/tags/"))
pkg.version = ref.slice("refs/tags/".length).replace(/^v/, "")
delete pkg.devDependencies
delete pkg.scripts
await writeFile(
path.join(staging, "package.json"),
JSON.stringify(pkg, null, 2)
)
const { version: electronVersion } = createRequire(import.meta.url)(
"electron/package.json"
)
// One build per architecture: a multi-arch NSIS build merges both into one installer.
for (const arch of architectures) {
await build({
targets: platform.createTarget(undefined, Arch[arch]),
config: {
appId: "com.otunes.desktop",
productName: "oTunes",
electronVersion,
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", "package.json"],
extraResources: [
{ from: path.join(desktopRoot, "web"), to: "web", filter: ["**/*"] },
],
npmRebuild: false,
win: { target: ["nsis"] },
linux: { category: "AudioVideo", target: ["flatpak"] },
flatpak: {
runtimeVersion: "25.08",
baseVersion: "25.08",
finishArgs: [
"--socket=wayland",
"--socket=fallback-x11",
"--share=ipc",
"--device=dri",
"--socket=pulseaudio",
"--share=network",
],
},
publish: null,
},
publish: "never",
})
}
+5 -12
View File
@@ -4,6 +4,7 @@ import { Stack } from "expo-router"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import {
inlineTitleOptions,
showHeaderProfile,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
@@ -22,18 +23,10 @@ export default function HomeLayout() {
...baseOptions,
...inlineTitleOptions,
title: tabStackScreenTitles[route.name] ?? "Home",
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
// iOS shows the profile button inline with the screen title instead.
headerRight: showHeaderProfile(route.name)
? () => <ProfileHeaderButton />
: undefined,
})}
/>
)
+10 -2
View File
@@ -5,6 +5,7 @@ import Animated from "react-native-reanimated"
import { ContentCarousel } from "@/components/media-cards"
import { HomeSkeleton } from "@/components/skeletons"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import { tabContentBottomInset } from "@/components/player"
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api"
@@ -56,7 +57,9 @@ export default function HomeScreen() {
(result) => result.status === "LoadingFirstPage" && !result.isCached
)
if (isLoading) {
return <HomeSkeleton title="Home" />
return (
<HomeSkeleton title="Home" titleAccessory={<ProfileHeaderButton />} />
)
}
const added = recentlyAdded.results.slice(0, CAROUSEL_ITEM_LIMIT)
@@ -73,7 +76,12 @@ export default function HomeScreen() {
]}
contentInsetAdjustmentBehavior="automatic"
>
<ScreenTitle title="Home" scrollY={scrollY} style={styles.title} />
<ScreenTitle
title="Home"
scrollY={scrollY}
accessory={<ProfileHeaderButton />}
style={styles.title}
/>
<HomeCarousels recentlyAdded={added} recentlyPlayed={played} />
</Animated.ScrollView>
)
@@ -5,6 +5,7 @@ import { Stack } from "expo-router"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import {
inlineTitleOptions,
showHeaderProfile,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
@@ -26,18 +27,10 @@ export default function LibraryLayout() {
title:
tabStackScreenTitles[route.name] ??
(tabletLayout ? "Recently Added" : "Library"),
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
// iOS shows the profile button inline with the screen title instead.
headerRight: showHeaderProfile(route.name)
? () => <ProfileHeaderButton />
: undefined,
})}
/>
)
@@ -8,6 +8,7 @@ import { Ionicons } from "@expo/vector-icons"
import { MediaGridList } from "@/components/media-cards"
import { tabContentBottomInset } from "@/components/player"
import { MediaGridSkeleton } from "@/components/skeletons"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
import { useAppNavigation } from "@/lib/app-navigation"
import { api } from "@otunes/convex/_generated/api"
@@ -128,6 +129,7 @@ export default function LibraryScreen() {
return (
<MediaGridSkeleton
title={title}
titleAccessory={<ProfileHeaderButton />}
contentInset={false}
header={listHeader}
/>
@@ -137,6 +139,7 @@ export default function LibraryScreen() {
return (
<MediaGridList
title={title}
titleAccessory={<ProfileHeaderButton />}
content={results}
paddingBottom={tabContentBottomInset}
contentInset={false}
@@ -4,6 +4,7 @@ import { Stack } from "expo-router"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import {
inlineTitleOptions,
showHeaderProfile,
tabStackScreenTitles,
useStackScreenOptions,
} from "@/lib/navigation"
@@ -22,18 +23,10 @@ export default function SearchLayout() {
...baseOptions,
...inlineTitleOptions,
title: tabStackScreenTitles[route.name] ?? "Search",
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
// iOS shows the profile button inline with the screen title instead.
headerRight: showHeaderProfile(route.name)
? () => <ProfileHeaderButton />
: undefined,
})}
/>
)
+44 -171
View File
@@ -7,14 +7,6 @@ import {
View,
type ScrollViewInstance,
} from "react-native"
import Animated, {
cancelAnimation,
Easing,
useAnimatedStyle,
useSharedValue,
withTiming,
type SharedValue,
} from "react-native-reanimated"
import {
usePlaybackActions,
@@ -26,7 +18,6 @@ import type { NowPlayingColors } from "@/lib/now-playing-colors"
import {
activeLineIndex,
type LyricLine,
type LyricWord,
type Lyrics,
} from "@otunes/convex/client/lyrics"
@@ -34,8 +25,6 @@ import {
const MANUAL_SCROLL_HOLD_MS = 3000
/** Where the playing line sits, as a share of the view's height from the top. */
const ACTIVE_LINE_POSITION = 0.12
/** Blur radius by distance from the playing line; farther lines share the last. */
const LINE_BLUR = [0, 1, 2, 3]
/**
* Lyrics in the player's own colors. Synced lines follow playback and seek
@@ -81,22 +70,19 @@ function LyricsLines({
const scrollRef = useRef<ScrollViewInstance>(null)
const lineOffsets = useRef<number[]>([])
const [height, setHeight] = useState(0)
// While the listener scrolls, lines stay sharp and the view stays put.
const [browsing, setBrowsing] = useState(false)
const browseTimer = useRef<ReturnType<typeof setTimeout>>(undefined)
useEffect(() => () => clearTimeout(browseTimer.current), [])
const manualScrollAt = useRef(0)
const scrollToLine = useCallback(
(index: number) => {
const y = lineOffsets.current[Math.max(index, 0)]
if (y === undefined || !synced || height === 0 || browsing) return
if (y === undefined || !synced || height === 0) return
if (Date.now() - manualScrollAt.current < MANUAL_SCROLL_HOLD_MS) return
scrollRef.current?.scrollTo({
y: Math.max(0, y - height * ACTIVE_LINE_POSITION),
animated: true,
})
},
[height, synced, browsing]
[height, synced]
)
useEffect(() => {
@@ -120,20 +106,11 @@ function LyricsLines({
(seconds: number) => {
seekTo(seconds)
setIsPlaying(true)
clearTimeout(browseTimer.current)
setBrowsing(false)
manualScrollAt.current = 0
},
[seekTo, setIsPlaying]
)
const releaseScroll = () => {
clearTimeout(browseTimer.current)
browseTimer.current = setTimeout(
() => setBrowsing(false),
MANUAL_SCROLL_HOLD_MS
)
}
const lineStyle = useMemo(
() => ({ fontSize, lineHeight: Math.round(fontSize * 1.18) }),
[fontSize]
@@ -150,12 +127,12 @@ function LyricsLines({
showsVerticalScrollIndicator={false}
onLayout={(event) => setHeight(event.nativeEvent.layout.height)}
onScrollBeginDrag={() => {
clearTimeout(browseTimer.current)
setBrowsing(true)
manualScrollAt.current = Date.now()
}}
onMomentumScrollEnd={() => {
// Hold from when the scroll settles, not when the finger lifted.
if (manualScrollAt.current > 0) manualScrollAt.current = Date.now()
}}
// Hold from when the scroll settles, not when the finger lifted.
onScrollEndDrag={releaseScroll}
onMomentumScrollEnd={releaseScroll}
>
{lyrics.lines.map((line, index) =>
synced ? (
@@ -163,14 +140,10 @@ function LyricsLines({
key={index}
index={index}
line={line}
distance={
browsing
? 0
: Math.min(Math.abs(index - active), LINE_BLUR.length - 1)
state={
index === active ? "active" : index < active ? "past" : "next"
}
active={index === active}
time={index === active ? time : null}
isPlaying={isPlaying}
colors={colors}
textStyle={lineStyle}
onSelect={playFrom}
@@ -198,17 +171,14 @@ function LyricsLines({
}
/**
* One timed line, blurred by its `distance` from the playing line. Only the
* playing line gets the time, so the others skip re-rendering as the song
* plays.
* One timed line. Only the playing line gets the time, so the others skip
* re-rendering as the song plays.
*/
const SyncedLine = memo(function SyncedLine({
index,
line,
distance,
active,
state,
time,
isPlaying,
colors,
textStyle,
onSelect,
@@ -216,155 +186,58 @@ const SyncedLine = memo(function SyncedLine({
}: {
index: number
line: LyricLine
distance: number
active: boolean
state: "past" | "active" | "next"
time: number | null
isPlaying: boolean
colors: NowPlayingColors
textStyle: { fontSize: number; lineHeight: number }
onSelect: (seconds: number) => void
onLayoutY: (index: number, y: number) => void
}) {
const blur = LINE_BLUR[distance]
const active = state === "active"
return (
<Pressable
onPress={() => onSelect(line.start ?? 0)}
onLayout={(event) => onLayoutY(index, event.nativeEvent.layout.y)}
accessibilityRole="button"
accessibilityHint="Plays from this line"
style={[styles.line, blur > 0 && { filter: [{ blur }] }]}
style={styles.line}
>
{active && line.words && time !== null ? (
<FilledWords
words={line.words}
time={time}
isPlaying={isPlaying}
colors={colors}
textStyle={textStyle}
/>
) : (
<Text
style={[
styles.lineText,
textStyle,
{
color:
active && !line.words
? colors.foreground
: colors.lyricsInactive,
},
]}
>
{line.text}
</Text>
)}
<Text
style={[
styles.lineText,
textStyle,
{
color:
active && !line.words ? colors.foreground : colors.lyricsInactive,
},
]}
>
{active && line.words
? line.words.map((word, wordIndex) => (
<Text
key={wordIndex}
style={{
color:
time !== null && time >= word.start
? colors.foreground
: colors.lyricsUnsung,
}}
>
{word.text}
</Text>
))
: line.text}
</Text>
</Pressable>
)
})
/**
* The playing line's words, each wiping from dim to bright as it is sung.
* Reanimated runs the wipe; playback updates only re-anchor it.
*/
function FilledWords({
words,
time,
isPlaying,
colors,
textStyle,
}: {
words: LyricWord[]
time: number
isPlaying: boolean
colors: NowPlayingColors
textStyle: { fontSize: number; lineHeight: number }
}) {
const sung = useSharedValue(time)
const end = words.at(-1)?.end ?? time
useEffect(() => {
cancelAnimation(sung)
sung.value = time
if (isPlaying && end > time) {
sung.value = withTiming(end, {
duration: (end - time) * 1000,
easing: Easing.linear,
})
}
}, [sung, time, isPlaying, end])
return (
<View style={[styles.words, { columnGap: textStyle.fontSize * 0.25 }]}>
{words.map((word, index) => (
<FilledWord
key={index}
word={word}
sung={sung}
colors={colors}
textStyle={textStyle}
/>
))}
</View>
)
}
function FilledWord({
word,
sung,
colors,
textStyle,
}: {
word: LyricWord
sung: SharedValue<number>
colors: NowPlayingColors
textStyle: { fontSize: number; lineHeight: number }
}) {
const [width, setWidth] = useState(0)
const text = word.text.trim()
const wipe = useAnimatedStyle(() => {
const progress =
(sung.value - word.start) / Math.max(word.end - word.start, 0.05)
return { width: width * Math.min(Math.max(progress, 0), 1) }
})
return (
<View>
<Text
style={[styles.lineText, textStyle, { color: colors.lyricsUnsung }]}
onLayout={(event) => setWidth(event.nativeEvent.layout.width)}
>
{text}
</Text>
<Animated.View style={[styles.wipe, wipe]}>
<Text
numberOfLines={1}
style={[
styles.lineText,
textStyle,
{ color: colors.foreground, width },
]}
>
{text}
</Text>
</Animated.View>
</View>
)
}
const styles = StyleSheet.create({
fill: { flex: 1 },
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
emptyText: { fontSize: 17, fontWeight: "600" },
line: { paddingVertical: 9 },
lineText: { fontWeight: "800" },
words: { flexDirection: "row", flexWrap: "wrap" },
wipe: {
position: "absolute",
top: 0,
bottom: 0,
left: 0,
overflow: "hidden",
},
plainLine: { fontWeight: "700", paddingVertical: 2 },
stanzaGap: { height: 18 },
})
+5 -1
View File
@@ -7,7 +7,7 @@ import { MusicEntityView } from "@/components/music-entity-view"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import { Link } from "expo-router"
import { Ionicons } from "@expo/vector-icons"
import { memo, useCallback, type ReactElement } from "react"
import { memo, useCallback, type ReactElement, type ReactNode } from "react"
import {
FlatList,
Platform,
@@ -302,6 +302,7 @@ export function MediaGridList({
ListHeaderComponent,
contentInset = true,
title,
titleAccessory,
}: {
content: MediaItem[]
paddingBottom: number
@@ -310,6 +311,7 @@ export function MediaGridList({
contentInset?: boolean
/** iOS `ScreenTitle` shown above the grid; it replaces the top inset. */
title?: string
titleAccessory?: ReactNode
}) {
const tabletLayout = useTabletLayout()
const { columns, cardWidth, onLayout, horizontalPadding, gap } =
@@ -334,6 +336,7 @@ export function MediaGridList({
ListHeaderComponent={ListHeaderComponent}
contentInset={contentInset}
title={title}
titleAccessory={titleAccessory}
renderCard={renderTabletCard}
/>
)
@@ -344,6 +347,7 @@ export function MediaGridList({
<ScreenTitle
title={title}
scrollY={scrollY}
accessory={titleAccessory}
// Inset grids already pad the whole list horizontally.
style={{ paddingHorizontal: contentInset ? 0 : horizontalPadding }}
/>
+29 -16
View File
@@ -1,11 +1,12 @@
import { useHeaderHeight } from "expo-router/react-navigation"
import type { Component } from "react"
import type { Component, ReactNode } from "react"
import {
Platform,
StyleSheet,
Text,
type ScrollViewInstance,
type StyleProp,
type TextStyle,
type ViewStyle,
} from "react-native"
import Animated, {
useAnimatedRef,
@@ -33,17 +34,20 @@ export function useScreenTitleScroll<
* iOS screen title rendered as the first item of a screen's scroll content,
* in place of the native large title (Apple Music style): it scrolls away
* with the content, never collapses into the bar, and stays put on
* pull-down. Android keeps its native header title, so this renders nothing.
* pull-down. `accessory` (e.g. the profile button) sits on the same row and
* scrolls with it. Android keeps its native header, so this renders nothing.
*/
export function ScreenTitle({
title,
scrollY,
accessory,
style,
}: {
title: string
/** From `useScreenTitleScroll`; omit for screens that never scroll. */
scrollY?: SharedValue<number>
style?: StyleProp<TextStyle>
accessory?: ReactNode
style?: StyleProp<ViewStyle>
}) {
const colors = useThemeColors()
// At rest the scroll offset is minus the automatic header inset, so any
@@ -60,25 +64,34 @@ export function ScreenTitle({
if (Platform.OS !== "ios") return null
return (
<Animated.Text
accessibilityRole="header"
numberOfLines={2}
style={[styles.title, { color: colors.foreground }, style, pinStyle]}
>
{title}
</Animated.Text>
<Animated.View style={[styles.row, style, pinStyle]}>
<Text
accessibilityRole="header"
numberOfLines={2}
style={[styles.title, { color: colors.foreground }]}
>
{title}
</Text>
{accessory}
</Animated.View>
)
}
// Matches UIKit's large title metrics: 34pt bold in a 52pt tall area.
const styles = StyleSheet.create({
title: {
fontSize: 34,
lineHeight: 41,
fontWeight: "700",
letterSpacing: 0.37,
row: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
paddingHorizontal: spacing.lg,
paddingTop: 3,
paddingBottom: 8,
},
title: {
flex: 1,
fontSize: 34,
lineHeight: 41,
fontWeight: "700",
letterSpacing: 0.37,
},
})
+12 -2
View File
@@ -9,6 +9,7 @@ import {
import Animated from "react-native-reanimated"
import { ContentCarousel } from "@/components/media-cards"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import { ScreenTitle, useScreenTitleScroll } from "@/components/screen-title"
import type { MediaAction } from "@/components/media-context-menu"
import { tabContentBottomInset, SongListRow } from "@/components/player"
@@ -86,7 +87,12 @@ function SearchResultsBody({
)
if (isSearching) {
return <SongListSkeleton title={title} />
return (
<SongListSkeleton
title={title}
titleAccessory={<ProfileHeaderButton />}
/>
)
}
return (
@@ -101,7 +107,11 @@ function SearchResultsBody({
keyboardShouldPersistTaps="handled"
ListHeaderComponent={
<>
<ScreenTitle title={title} scrollY={scrollY} />
<ScreenTitle
title={title}
scrollY={scrollY}
accessory={<ProfileHeaderButton />}
/>
{hasQuery && !hasResults ? (
<View style={styles.empty}>
<Text
+26 -5
View File
@@ -155,13 +155,15 @@ function SongRows({ rows, inset }: { rows: number; inset?: boolean }) {
export function SongListSkeleton({
rows = 10,
title,
titleAccessory,
}: {
rows?: number
title?: string
titleAccessory?: ReactNode
}) {
return (
<SkeletonScreen>
{title ? <ScreenTitle title={title} /> : null}
{title ? <ScreenTitle title={title} accessory={titleAccessory} /> : null}
<SongRows rows={rows} />
</SkeletonScreen>
)
@@ -243,6 +245,7 @@ export function MediaGridSkeleton({
contentInset = true,
header,
title,
titleAccessory,
}: {
items?: number
contentInset?: boolean
@@ -250,6 +253,7 @@ export function MediaGridSkeleton({
header?: ReactNode
/** The loaded list's `ScreenTitle`, which replaces its top inset. */
title?: string
titleAccessory?: ReactNode
}) {
return (
<SkeletonScreen>
@@ -259,7 +263,7 @@ export function MediaGridSkeleton({
header={
title ? (
<>
<MediaGridTitle title={title} />
<MediaGridTitle title={title} accessory={titleAccessory} />
{header}
</>
) : (
@@ -271,11 +275,18 @@ export function MediaGridSkeleton({
)
}
function MediaGridTitle({ title }: { title: string }) {
function MediaGridTitle({
title,
accessory,
}: {
title: string
accessory?: ReactNode
}) {
const { horizontalPadding } = useMediaGridLayout()
return (
<ScreenTitle
title={title}
accessory={accessory}
style={{ paddingHorizontal: horizontalPadding }}
/>
)
@@ -294,11 +305,21 @@ export function CarouselSkeleton() {
)
}
export function HomeSkeleton({ title }: { title: string }) {
export function HomeSkeleton({
title,
titleAccessory,
}: {
title: string
titleAccessory?: ReactNode
}) {
return (
<SkeletonScreen>
<View style={styles.home}>
<ScreenTitle title={title} style={styles.homeTitle} />
<ScreenTitle
title={title}
accessory={titleAccessory}
style={styles.homeTitle}
/>
<CarouselSkeleton />
<CarouselSkeleton />
</View>
@@ -4,6 +4,7 @@ import {
useRef,
useState,
type ReactElement,
type ReactNode,
} from "react"
import {
type ScrollViewInstance,
@@ -31,6 +32,7 @@ type GridProps = {
contentInset?: boolean
/** iOS `ScreenTitle` shown above the grid; it replaces the top inset. */
title?: string
titleAccessory?: ReactNode
renderCard: (item: MediaItem, width: number) => ReactElement
}
@@ -45,6 +47,7 @@ export function TabletMediaGrid({
ListHeaderComponent,
contentInset = true,
title,
titleAccessory,
renderCard,
}: GridProps) {
const colors = useThemeColors()
@@ -126,6 +129,7 @@ export function TabletMediaGrid({
<ScreenTitle
title={title}
scrollY={titleScrollY}
accessory={titleAccessory}
style={{ paddingHorizontal: horizontalPadding }}
/>
) : null}
+5
View File
@@ -24,6 +24,11 @@ export const tabStackScreenTitles: Record<string, string> = {
export const inlineTitleOptions: StackScreenOptions =
Platform.OS === "ios" ? { headerTitleStyle: { color: "transparent" } } : {}
/** Tab roots show the profile button in the header, except on iOS where `ScreenTitle` holds it. */
export function showHeaderProfile(routeName: string) {
return routeName === "index" && Platform.OS !== "ios"
}
export function useStackScreenOptions(
overrides?: StackScreenOptions
): StackScreenOptions {
+36 -5
View File
@@ -1,13 +1,44 @@
import type { ServerConfig } from "@otunes/convex/server-url"
import { buildConvexUrl, isLocalHost } from "@otunes/convex/server-url"
export {
parseServerHostname,
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
}
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> {
@@ -23,7 +23,7 @@ export default function Page() {
</p>
<div className="mt-6 flex flex-wrap justify-center gap-2">
<Button asChild>
<Link href="/">
<Link href="/public">
<Home />
Home
</Link>
@@ -1,5 +1,3 @@
// Share links (/album/<id>) land here on the server build, which adds
// link-preview metadata. The app itself links to /album?id=<id>.
import { AlbumPage } from "@/components/album-page"
import { api } from "@otunes/convex/_generated/api"
import { fetchQuery } from "convex/nextjs"
-19
View File
@@ -1,19 +0,0 @@
"use client"
import { useSearchParams } from "next/navigation"
import { AlbumPage } from "@/components/album-page"
import { PageMessage } from "@/components/page-message"
import type { Id } from "@otunes/convex/_generated/dataModel"
export default function Page() {
const searchParams = useSearchParams()
const id = searchParams.get("id")
if (!id) return <PageMessage>Album not found.</PageMessage>
return (
<AlbumPage
albumId={id as Id<"albums">}
highlightedSongId={searchParams.get("s") ?? undefined}
/>
)
}
@@ -1,5 +1,3 @@
// Share links (/artist/<id>) land here on the server build, which adds
// link-preview metadata. The app itself links to /artist?id=<id>.
import { fetchQuery } from "convex/nextjs"
import { convexServerOptions } from "@/lib/convex-server"
import { ArtistPage } from "@/components/artist-page"
-13
View File
@@ -1,13 +0,0 @@
"use client"
import { useSearchParams } from "next/navigation"
import { ArtistPage } from "@/components/artist-page"
import { PageMessage } from "@/components/page-message"
import type { Id } from "@otunes/convex/_generated/dataModel"
export default function Page() {
const id = useSearchParams().get("id")
if (!id) return <PageMessage>Artist not found.</PageMessage>
return <ArtistPage artistId={id as Id<"artists">} />
}
-4
View File
@@ -1,4 +1,3 @@
import { AuthRedirect } from "@/components/auth-redirect"
import { AddToPlaylistProvider } from "@/components/add-to-playlist-provider"
import { DownloadsProvider } from "@/components/downloads-provider"
import { FavoritesProvider } from "@/components/favorites-provider"
@@ -22,9 +21,6 @@ export default function AppLayout({
<AddToPlaylistProvider>
<DownloadsProvider>
<FavoritesProvider>
{process.env.OTUNES_STATIC_EXPORT === "1" && (
<AuthRedirect area="app" />
)}
<AppSidebar />
<div className="flex min-h-svh min-w-0 flex-1">
<SidebarInset className="min-w-0 flex-1">
@@ -0,0 +1,40 @@
import { fetchQuery } from "convex/nextjs"
import { convexServerOptions } from "@/lib/convex-server"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { Metadata } from "next"
interface PageProps {
params: Promise<{ id: string }>
}
export async function generateMetadata({
params,
}: PageProps): Promise<Metadata> {
const { id } = await params
const detail = await fetchQuery(
api.library.browseArtistDetail,
{ id: id as Id<"artists"> },
convexServerOptions()
).catch(() => null)
const selectedArtist = detail?.artist
return {
title: `${selectedArtist ? `${selectedArtist.name}` : "oTunes"}`,
openGraph: {
title: `${selectedArtist ? `${selectedArtist.name}` : "oTunes"}`,
description: "oTunes",
images: selectedArtist
? {
url: `/api/artist/${selectedArtist.id}/cover`,
width: 512,
height: 512,
}
: [],
},
}
}
export default function Page() {
return null
}
@@ -1,5 +1,3 @@
// Share links (/playlist/<id>) land here on the server build, which adds
// link-preview metadata. The app itself links to /playlist?id=<id>.
import { PlaylistPage } from "@/components/playlist-page"
import { api } from "@otunes/convex/_generated/api"
import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server"
-13
View File
@@ -1,13 +0,0 @@
"use client"
import { useSearchParams } from "next/navigation"
import { PageMessage } from "@/components/page-message"
import { PlaylistPage } from "@/components/playlist-page"
import type { Id } from "@otunes/convex/_generated/dataModel"
export default function Page() {
const id = useSearchParams().get("id")
if (!id) return <PageMessage>Playlist not found.</PageMessage>
return <PlaylistPage playlistId={id as Id<"playlists">} />
}
-2
View File
@@ -1,4 +1,3 @@
import { AuthRedirect } from "@/components/auth-redirect"
export default function AuthLayout({
children,
}: Readonly<{
@@ -6,7 +5,6 @@ export default function AuthLayout({
}>) {
return (
<div className="flex min-h-svh flex-col items-center justify-center bg-muted/30 p-6">
{process.env.OTUNES_STATIC_EXPORT === "1" && <AuthRedirect area="auth" />}
{children}
</div>
)
+15 -2
View File
@@ -1,5 +1,18 @@
import { fetchQuery } from "convex/nextjs"
import { connection } from "next/server"
import { AuthForm } from "@/components/auth-form"
import { convexServerOptions } from "@/lib/convex-server"
import { api } from "@otunes/convex/_generated/api"
export default function SignInPage() {
return <AuthForm flow="signIn" />
export default async function SignInPage() {
await connection()
const { disableAccountCreation } = await fetchQuery(
api.users.getAppSettings,
{},
convexServerOptions()
)
return (
<AuthForm flow="signIn" accountCreationDisabled={disableAccountCreation} />
)
}
+12 -24
View File
@@ -1,30 +1,18 @@
"use client"
import { useQuery } from "convex/react"
import Link from "next/link"
import { fetchQuery } from "convex/nextjs"
import { connection } from "next/server"
import { AuthForm } from "@/components/auth-form"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { convexServerOptions } from "@/lib/convex-server"
import { api } from "@otunes/convex/_generated/api"
export default function SignUpPage() {
const settings = useQuery(api.users.getAppSettings)
// Render nothing until the setting loads so the form never flashes.
if (settings === undefined) return null
if (!settings.disableAccountCreation) return <AuthForm flow="signUp" />
export default async function SignUpPage() {
await connection()
const { disableAccountCreation } = await fetchQuery(
api.users.getAppSettings,
{},
convexServerOptions()
)
return (
<Card className="w-full max-w-sm">
<CardHeader>
<CardTitle className="text-lg">
This server has disabled new signups :(
</CardTitle>
</CardHeader>
<CardContent>
<Button asChild className="w-full">
<Link href="/signin">Back</Link>
</Button>
</CardContent>
</Card>
<AuthForm flow="signUp" accountCreationDisabled={disableAccountCreation} />
)
}
@@ -37,7 +37,7 @@ export async function POST(request: NextRequest) {
let songs: Awaited<ReturnType<typeof getSongSources>>
try {
songs = await getSongSources(songIds, request)
songs = await getSongSources(songIds)
} catch {
return new Response("Not found", { status: 404 })
}
@@ -53,10 +53,9 @@ async function transcodeResponse(
songId: string,
source: string,
kbps: number,
request: NextRequest
signal: AbortSignal
) {
const { signal } = request
const lyrics = await getSongLyrics(songId, request)
const lyrics = await getSongLyrics(songId)
const lyricsArgs =
lyrics && Buffer.byteLength(lyrics) <= MAX_LYRICS_ARGUMENT_BYTES
? ["-metadata", `lyrics=${lyrics}`]
@@ -116,7 +115,7 @@ export async function GET(
let song: Awaited<ReturnType<typeof getSongSource>>
try {
song = await getSongSource(id, request)
song = await getSongSource(id)
} catch {
return new Response("Not found", { status: 404 })
}
@@ -129,7 +128,12 @@ export async function GET(
try {
if (plan.kbps > 0) {
return await transcodeResponse(song._id, sourceFile, plan.kbps, request)
return await transcodeResponse(
song._id,
sourceFile,
plan.kbps,
request.signal
)
}
if (plan.source === "lossless") {
@@ -15,7 +15,7 @@ export async function GET(
const { id } = await params
try {
const song = await getSongSource(id, request)
const song = await getSongSource(id)
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, request)
const song = await getSongSource(id)
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, request)
const song = await getSongSource(id)
const {
source: originalCodec,
+9 -18
View File
@@ -37,11 +37,8 @@ async function hostedUrl() {
}
}
const staticExport = process.env.OTUNES_STATIC_EXPORT === "1"
export async function generateMetadata(): Promise<Metadata> {
// Static exports have no request to read the host from.
const url = staticExport ? undefined : await hostedUrl()
const url = await hostedUrl()
return {
title: "oTunes",
@@ -73,13 +70,6 @@ export default function RootLayout({
}: Readonly<{
children: React.ReactNode
}>) {
const content = (
<ThemeProvider defaultTheme="system">
{children}
<Toaster />
</ThemeProvider>
)
return (
<html
lang="en"
@@ -92,13 +82,14 @@ export default function RootLayout({
)}
>
<body className={"overflow-x-hidden"}>
{staticExport ? (
<ConvexClientProvider>{content}</ConvexClientProvider>
) : (
<ConvexAuthNextjsServerProvider storageNamespace="otunes">
<ConvexClientProvider>{content}</ConvexClientProvider>
</ConvexAuthNextjsServerProvider>
)}
<ConvexAuthNextjsServerProvider storageNamespace="otunes">
<ConvexClientProvider convexUrl={process.env.PUBLIC_CONVEX_URL}>
<ThemeProvider>
{children}
<Toaster />
</ThemeProvider>
</ConvexClientProvider>
</ConvexAuthNextjsServerProvider>
</body>
</html>
)
-2
View File
@@ -1,7 +1,5 @@
import type { MetadataRoute } from "next"
export const dynamic = "force-static"
export default function manifest(): MetadataRoute.Manifest {
return {
name: "oTunes",
-9
View File
@@ -1,9 +0,0 @@
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,7 +1,5 @@
"use client"
import { playlistPath } from "@/lib/routes"
import * as React from "react"
import { useConvex, useMutation, useQuery } from "convex/react"
import { useRouter } from "next/navigation"
@@ -258,7 +256,7 @@ export function AddToPlaylistProvider({
setNewPlaylistName("")
setPendingSongIds([])
if (count === 0) {
router.push(playlistPath(playlistId))
router.push(`/playlist/${playlistId}`)
}
} catch (error) {
toast.error(
+3 -5
View File
@@ -1,7 +1,5 @@
"use client"
import { albumPath, artistPath } from "@/lib/routes"
import * as React from "react"
import Image from "next/image"
import Link from "next/link"
@@ -125,7 +123,7 @@ export function AlbumCard({ album }: { album: BrowseAlbum }) {
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
>
<Link className="absolute inset-0" href={albumPath(album.id)}>
<Link className="absolute inset-0" href={"/album/" + album.id}>
<Image
src={albumCoverUrl(album.id)}
alt={album.title}
@@ -188,11 +186,11 @@ export function AlbumCard({ album }: { album: BrowseAlbum }) {
</div>
<div className="min-w-0">
<Link href={albumPath(album.id)} className="hover:underline">
<Link href={"/album/" + album.id} className="hover:underline">
<p className="truncate text-sm font-medium">{album.title}</p>
</Link>
<Link
href={artistPath(album.artist.id)}
href={"/artist/" + album.artist.id}
className="text-muted-foreground decoration-muted-foreground hover:underline"
>
<p className="truncate text-xs">{album.artist.name}</p>
+1 -3
View File
@@ -1,7 +1,5 @@
"use client"
import { artistPath } from "@/lib/routes"
import { PageHeader } from "@/components/library-skeletons"
import * as React from "react"
import Image from "next/image"
@@ -289,7 +287,7 @@ export function AlbumView({
{album.title}
</h1>
<Link
href={artistPath(album.artist.id)}
href={"/artist/" + album.artist.id}
className="inline-block text-lg font-semibold text-primary hover:underline"
>
{album.artist.name}
+15 -77
View File
@@ -1,8 +1,5 @@
"use client"
import { playlistPath } from "@/lib/routes"
import { serverUrl, staticExport } from "@/lib/server"
import {
ArrowDownToLine,
Disc3,
@@ -13,12 +10,11 @@ import {
Mic,
Music2,
Search,
Server,
Settings,
Star,
} from "lucide-react"
import { usePathname, useRouter, useSearchParams } from "next/navigation"
import { usePathname, useRouter } from "next/navigation"
import dynamic from "next/dynamic"
import { useAuthActions } from "@convex-dev/auth/react"
@@ -47,7 +43,6 @@ import Image from "next/image"
import Link from "next/link"
import { useTheme } from "next-themes"
import * as React from "react"
import { Suspense } from "react"
import { api } from "@otunes/convex/_generated/api"
import { playlistCoverUrl } from "@/lib/cover-urls"
import { useCachedQuery } from "@/hooks/use-cached-query"
@@ -114,7 +109,7 @@ export function AppSidebar() {
...(sidebarPlaylists?.subscribed ?? []),
].map((playlist) => ({
title: playlist.title,
path: playlistPath(playlist.id),
path: `/playlist/${playlist.id}`,
icon: playlist.cover ? (
// eslint-disable-next-line @next/next/no-img-element -- versioned cover, already sized by the route
<img
@@ -201,20 +196,18 @@ export function AppSidebar() {
<SidebarGroup>
<SidebarGroupLabel>Playlists</SidebarGroupLabel>
<SidebarGroupContent>
<Suspense
fallback={
<PlaylistMenu
items={playlistNav}
route={pathname}
onNavigate={() => setOpenMobile(false)}
/>
}
>
<CurrentPlaylistMenu
items={playlistNav}
onNavigate={() => setOpenMobile(false)}
/>
</Suspense>
<SidebarMenu>
{playlistNav.map((item) => (
<SidebarMenuItem key={item.path}>
<SidebarMenuButton isActive={pathname === item.path} asChild>
<Link href={item.path} onClick={() => setOpenMobile(false)}>
{item.icon}
<span>{item.title}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
</SidebarContent>
@@ -227,10 +220,7 @@ export function AppSidebar() {
<SidebarMenuButton size="lg" className="min-w-0 flex-1">
<Avatar size="sm" key={user?.image ?? "fallback"}>
{user?.image ? (
<AvatarImage
src={serverUrl(user.image)}
alt={user.name}
/>
<AvatarImage src={user.image} alt={user.name} />
) : null}
<AvatarFallback>{fallbackLetters}</AvatarFallback>
</Avatar>
@@ -253,15 +243,6 @@ export function AppSidebar() {
Options
<Settings />
</DropdownMenuItem>
{staticExport ? (
<DropdownMenuItem
className="justify-between"
onClick={() => router.push("/server")}
>
Change Server
<Server />
</DropdownMenuItem>
) : null}
</DropdownMenuContent>
</DropdownMenu>
{optionsOpen ? (
@@ -274,46 +255,3 @@ export function AppSidebar() {
</Sidebar>
)
}
type NavItem = { title: string; path: string; icon: React.ReactNode }
// Playlist routes differ only by `?id=`. Reading the query needs a Suspense
// boundary in static exports, so the fallback matches on the path alone.
function CurrentPlaylistMenu(props: {
items: NavItem[]
onNavigate: () => void
}) {
const pathname = usePathname()
const query = useSearchParams().toString()
return (
<PlaylistMenu
{...props}
route={query ? `${pathname}?${query}` : pathname}
/>
)
}
function PlaylistMenu({
items,
route,
onNavigate,
}: {
items: NavItem[]
route: string
onNavigate: () => void
}) {
return (
<SidebarMenu>
{items.map((item) => (
<SidebarMenuItem key={item.path}>
<SidebarMenuButton isActive={route === item.path} asChild>
<Link href={item.path} onClick={onNavigate}>
{item.icon}
<span>{item.title}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
)
}
+2 -4
View File
@@ -1,7 +1,5 @@
"use client"
import { artistPath } from "@/lib/routes"
import Image from "next/image"
import Link from "next/link"
@@ -13,7 +11,7 @@ export function ArtistCard({ artist }: { artist: BrowseArtist }) {
<div className="group flex flex-col items-center gap-2">
<Link
className="relative flex aspect-square w-full items-center justify-center overflow-hidden rounded-full ring-1 ring-foreground/10"
href={artistPath(artist.id)}
href={"/artist/" + artist.id}
>
<Image
src={artistCoverUrl(artist.id)}
@@ -24,7 +22,7 @@ export function ArtistCard({ artist }: { artist: BrowseArtist }) {
/>
</Link>
<div className="min-w-0">
<Link href={artistPath(artist.id)} className="hover:underline">
<Link href={"/artist/" + artist.id} className="hover:underline">
<p className="truncate text-center text-sm font-medium">
{artist.name}
</p>
+11 -8
View File
@@ -1,6 +1,6 @@
"use client"
import { useSearchParams } from "next/navigation"
import { usePathname } from "next/navigation"
import { useCallback } from "react"
import { ArtistsView } from "@/components/artists-view"
@@ -8,17 +8,20 @@ import { ArtistsSkeleton, PageHeader } from "@/components/library-skeletons"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api"
const ARTISTS_PATH = "/library/artists"
function artistIdFromPathname(pathname: string) {
const [, id] = pathname.slice(ARTISTS_PATH.length).split("/")
return id ? decodeURIComponent(id) : undefined
}
export function ArtistsPage() {
const artistId = useSearchParams().get("id") ?? undefined
const pathname = usePathname()
const artists = useCachedQuery(api.library.browseArtists)
const albums = useCachedQuery(api.library.browseAlbums)
const selectArtist = useCallback((artistId: string) => {
window.history.pushState(
null,
"",
`/library/artists?${new URLSearchParams({ id: artistId })}`
)
window.history.pushState(null, "", `${ARTISTS_PATH}/${artistId}`)
}, [])
return (
@@ -31,7 +34,7 @@ export function ArtistsPage() {
<ArtistsView
artists={artists.flat()}
albums={albums.flat()}
artistId={artistId}
artistId={artistIdFromPathname(pathname)}
onSelectArtist={selectArtist}
/>
)}
+1 -3
View File
@@ -1,7 +1,5 @@
"use client"
import { artistPath } from "@/lib/routes"
import * as React from "react"
import Image from "next/image"
import Link from "next/link"
@@ -157,7 +155,7 @@ export function ArtistsView({
<div className="pb-28">
<div className="flex min-w-0 items-center justify-between gap-4 border-b px-6 py-4">
<Link
href={artistPath(selectedArtist.id)}
href={`/artist/${selectedArtist.id}`}
className="group inline-flex min-w-0 flex-1 items-center gap-1 text-xl font-bold tracking-tight hover:underline"
>
<span className="min-w-0 truncate">{selectedArtist.name}</span>
+72 -52
View File
@@ -53,16 +53,27 @@ const copy: Record<
},
}
export function AuthForm({ flow }: { flow: AuthFlow }) {
export function AuthForm({
flow,
accountCreationDisabled,
}: {
flow: AuthFlow
accountCreationDisabled: boolean
}) {
const { signIn } = useAuthActions()
const router = useRouter()
const [error, setError] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false)
const text = copy[flow]
const signupsDisabled = flow === "signUp" && accountCreationDisabled
const hideSignUpLink = flow === "signIn" && accountCreationDisabled
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault()
if (signupsDisabled) {
return
}
setError(null)
setSubmitting(true)
@@ -89,62 +100,71 @@ export function AuthForm({ flow }: { flow: AuthFlow }) {
<CardDescription>{text.description}</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit}>
<FieldGroup>
{flow === "signUp" && (
{signupsDisabled ? (
<p className="text-sm text-muted-foreground">
New account registration is currently disabled. Contact an
administrator if you need access.
</p>
) : (
<form onSubmit={handleSubmit}>
<FieldGroup>
{flow === "signUp" && (
<Field>
<FieldLabel htmlFor="name">Name</FieldLabel>
<Input
id="name"
name="name"
type="text"
autoComplete="name"
placeholder="Ada Lovelace"
required
/>
</Field>
)}
<Field>
<FieldLabel htmlFor="name">Name</FieldLabel>
<FieldLabel htmlFor="email">Email</FieldLabel>
<Input
id="name"
name="name"
type="text"
autoComplete="name"
placeholder="Ada Lovelace"
id="email"
name="email"
type="email"
autoComplete="email"
placeholder="you@example.com"
required
/>
</Field>
)}
<Field>
<FieldLabel htmlFor="email">Email</FieldLabel>
<Input
id="email"
name="email"
type="email"
autoComplete="email"
placeholder="you@example.com"
required
/>
</Field>
<Field>
<FieldLabel htmlFor="password">Password</FieldLabel>
<Input
id="password"
name="password"
type="password"
autoComplete={
flow === "signIn" ? "current-password" : "new-password"
}
required
/>
</Field>
{error && <FieldError>{error}</FieldError>}
<Field>
<Button type="submit" disabled={submitting}>
{submitting && <Spinner />}
{text.submit}
</Button>
</Field>
<p className="text-center text-sm text-muted-foreground">
{text.switchPrompt}{" "}
<Link
href={text.switchHref}
className="text-primary underline-offset-4 hover:underline"
>
{text.switchLabel}
</Link>
</p>
</FieldGroup>
</form>
<Field>
<FieldLabel htmlFor="password">Password</FieldLabel>
<Input
id="password"
name="password"
type="password"
autoComplete={
flow === "signIn" ? "current-password" : "new-password"
}
required
/>
</Field>
{error && <FieldError>{error}</FieldError>}
<Field>
<Button type="submit" disabled={submitting}>
{submitting && <Spinner />}
{text.submit}
</Button>
</Field>
{!hideSignUpLink ? (
<p className="text-center text-sm text-muted-foreground">
{text.switchPrompt}{" "}
<Link
href={text.switchHref}
className="text-primary underline-offset-4 hover:underline"
>
{text.switchLabel}
</Link>
</p>
) : null}
</FieldGroup>
</form>
)}
</CardContent>
</Card>
)
-27
View File
@@ -1,27 +0,0 @@
"use client"
import { useConvexAuth } from "convex/react"
import { usePathname, useRouter } from "next/navigation"
import { useEffect } from "react"
// Media pages that signed-out visitors can open from share links.
const PUBLIC_PATHS = new Set(["/album", "/artist", "/playlist"])
/**
* Static exports have no proxy, so this keeps signed-out users on the auth
* pages and signed-in users off them. Server builds redirect in proxy.server.ts.
*/
export function AuthRedirect({ area }: { area: "app" | "auth" }) {
const { isAuthenticated, isLoading } = useConvexAuth()
const pathname = usePathname()
const router = useRouter()
useEffect(() => {
if (isLoading) return
if (area === "auth" && isAuthenticated) router.replace("/")
if (area === "app" && !isAuthenticated && !PUBLIC_PATHS.has(pathname))
router.replace("/signin")
}, [area, isAuthenticated, isLoading, pathname, router])
return null
}
+20 -49
View File
@@ -1,19 +1,11 @@
"use client"
import { ConvexAuthNextjsProvider } from "@convex-dev/auth/nextjs"
import { ConvexAuthProvider, useAuthToken } from "@convex-dev/auth/react"
import { buildConvexUrl } from "@otunes/convex/server-url"
import { ConvexReactClient } from "convex/react"
import { usePathname, useRouter } from "next/navigation"
import { ReactNode, useEffect } from "react"
import { ReactNode } 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"
@@ -25,50 +17,29 @@ function browserConvexUrl() {
return buildConvexUrl(host, protocol === "https:" ? "https" : "http")
}
function getConvexClient(convexUrl: string) {
client ??= new ConvexReactClient(convexUrl)
function getConvexClient(convexUrl: string | undefined) {
if (!client) {
client = new ConvexReactClient(
typeof window === "undefined"
? SSR_CONVEX_URL
: (convexUrl ??
process.env.NEXT_PUBLIC_CONVEX_URL ??
browserConvexUrl())
)
}
return client
}
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())
export function ConvexClientProvider({
convexUrl,
children,
}: {
convexUrl?: string
children: ReactNode
}) {
return (
<ConvexAuthNextjsProvider client={getConvexClient(url)}>
<PersistentCacheProvider>{children}</PersistentCacheProvider>
<ConvexAuthNextjsProvider client={getConvexClient(convexUrl)}>
<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
}
+1 -2
View File
@@ -18,7 +18,6 @@ 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,
@@ -79,7 +78,7 @@ export function useDownloads() {
}
async function fetchDownloadOptions(songIds: string[]) {
const response = await fetch(authedUrl(DOWNLOAD_OPTIONS_PATH), {
const response = await fetch(DOWNLOAD_OPTIONS_PATH, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ songIds }),
+35 -113
View File
@@ -12,26 +12,11 @@ import { cn } from "@/lib/utils"
import {
activeLineIndex,
type LyricLine,
type LyricWord,
type Lyrics,
} from "@otunes/convex/client/lyrics"
/** How long a manual scroll keeps the panel from following the song. */
const MANUAL_SCROLL_HOLD_MS = 3000
/** Blur by distance from the playing line; farther lines share the last. */
const LINE_BLUR = ["blur-none", "blur-[1px]", "blur-[2px]", "blur-[3px]"]
/** Unsung words wipe from dim to bright, soft edge first, as they are sung. */
const WORD_FILL = {
backgroundImage:
"linear-gradient(90deg, var(--foreground) 40%, color-mix(in oklab, var(--foreground) 45%, transparent) 60%)",
backgroundSize: "250% 100%",
}
const WORD_FILL_FRAMES = [
{ backgroundPosition: "100% 0" },
{ backgroundPosition: "0% 0" },
]
/** How far a word's fill may drift from playback before it is reset. */
const FILL_DRIFT_MS = 80
/** Lyrics beside the page, in the queue's place. Synced lines follow playback. */
export function LyricsPanel() {
@@ -62,42 +47,38 @@ function LyricsLines({ lyrics }: { lyrics: Lyrics }) {
const time = useLyricsTime(lyrics, currentTime, isPlaying)
const active = activeLineIndex(lyrics, time)
const scrollRef = React.useRef<HTMLDivElement>(null)
const manualScrollAt = React.useRef(0)
const synced = lyrics.synced !== "none"
// While the listener scrolls, lines stay sharp and the panel stays put.
const [browsing, setBrowsing] = React.useState(false)
const browseTimer = React.useRef<ReturnType<typeof setTimeout>>(undefined)
React.useEffect(() => () => clearTimeout(browseTimer.current), [])
React.useEffect(() => {
const container = scrollRef.current
const line = container?.querySelector<HTMLElement>(
`[data-line="${Math.max(active, 0)}"]`
)
if (!container || !line || !synced || browsing) return
if (
!container ||
!line ||
!synced ||
Date.now() - manualScrollAt.current < MANUAL_SCROLL_HOLD_MS
) {
return
}
container.scrollTo({
top: line.offsetTop - container.clientHeight * 0.25,
behavior: "smooth",
})
}, [active, synced, browsing])
}, [active, synced])
const playFrom = React.useCallback(
(seconds: number) => {
seekTo(seconds)
setIsPlaying(true)
clearTimeout(browseTimer.current)
setBrowsing(false)
},
[seekTo, setIsPlaying]
)
const holdScroll = () => {
setBrowsing(true)
clearTimeout(browseTimer.current)
browseTimer.current = setTimeout(
() => setBrowsing(false),
MANUAL_SCROLL_HOLD_MS
)
manualScrollAt.current = Date.now()
}
return (
@@ -105,7 +86,7 @@ function LyricsLines({ lyrics }: { lyrics: Lyrics }) {
ref={scrollRef}
onWheel={holdScroll}
onTouchMove={holdScroll}
className="group relative min-h-0 flex-1 overflow-y-auto px-6 pt-[25svh] pb-[60svh]"
className="relative min-h-0 flex-1 overflow-y-auto px-6 pt-[25svh] pb-[60svh]"
>
{lyrics.lines.map((line, index) =>
synced ? (
@@ -113,14 +94,10 @@ function LyricsLines({ lyrics }: { lyrics: Lyrics }) {
key={index}
index={index}
line={line}
distance={
browsing
? 0
: Math.min(Math.abs(index - active), LINE_BLUR.length - 1)
state={
index === active ? "active" : index < active ? "past" : "next"
}
active={index === active}
time={index === active ? time : null}
isPlaying={isPlaying}
onSelect={playFrom}
/>
) : (
@@ -140,103 +117,48 @@ function LyricsLines({ lyrics }: { lyrics: Lyrics }) {
}
/**
* One timed line, blurred by its `distance` from the playing line. Only the
* active line gets the playback time, so memoized lines elsewhere skip
* re-rendering as the song plays.
* One timed line. Only the active line gets the playback time, so memoized
* lines elsewhere skip re-rendering as the song plays.
*/
const SyncedLine = React.memo(function SyncedLine({
index,
line,
distance,
active,
state,
time,
isPlaying,
onSelect,
}: {
index: number
line: LyricLine
distance: number
active: boolean
state: "past" | "active" | "next"
time: number | null
isPlaying: boolean
onSelect: (seconds: number) => void
}) {
const active = state === "active"
return (
<button
type="button"
data-line={index}
onClick={() => onSelect(line.start ?? 0)}
className={cn(
"-mx-2 my-1 block w-[calc(100%+1rem)] rounded-md px-2 py-1.5 text-left text-[22px] leading-tight font-bold transition-[color,filter] duration-300 group-hover:blur-none hover:bg-foreground/5",
LINE_BLUR[distance],
"-mx-2 my-1 block w-[calc(100%+1rem)] rounded-md px-2 py-1.5 text-left text-[22px] leading-tight font-bold transition-colors duration-300 hover:bg-foreground/5",
active && !line.words ? "text-foreground" : "text-foreground/30"
)}
>
{active && line.words && time !== null ? (
<FilledWords words={line.words} time={time} isPlaying={isPlaying} />
) : (
line.text
)}
{active && line.words
? line.words.map((word, wordIndex) => (
<span
key={wordIndex}
className={cn(
"transition-colors duration-200",
time !== null && time >= word.start
? "text-foreground"
: "text-foreground/45"
)}
>
{word.text}
</span>
))
: line.text}
</button>
)
})
/**
* The playing line's words, each filled as far as it has been sung. The
* browser runs the fills; playback updates only correct their drift.
*/
function FilledWords({
words,
time,
isPlaying,
}: {
words: LyricWord[]
time: number
isPlaying: boolean
}) {
const spans = React.useRef<(HTMLSpanElement | null)[]>([])
const fills = React.useRef<(Animation | undefined)[]>([])
React.useEffect(() => {
fills.current = words.map((word, index) =>
spans.current[index]?.animate(WORD_FILL_FRAMES, {
duration: Math.max(word.end - word.start, 0.05) * 1000,
easing: "linear",
fill: "both",
})
)
return () => fills.current.forEach((fill) => fill?.cancel())
}, [words])
React.useEffect(() => {
fills.current.forEach((fill, index) => {
if (!fill) return
const at = (time - words[index].start) * 1000
if (Math.abs(Number(fill.currentTime ?? 0) - at) > FILL_DRIFT_MS) {
fill.currentTime = at
}
// `play` on a finished fill would rewind it.
const duration = Number(fill.effect?.getTiming().duration ?? 0)
if (isPlaying && at < duration) fill.play()
else fill.pause()
})
}, [words, time, isPlaying])
return words.map((word, index) => {
const text = word.text.trimEnd()
return (
<React.Fragment key={index}>
<span
ref={(span) => {
spans.current[index] = span
}}
className="bg-clip-text text-transparent"
style={WORD_FILL}
>
{text}
</span>
{word.text.slice(text.length)}
</React.Fragment>
)
})
}
+2 -4
View File
@@ -1,7 +1,5 @@
"use client"
import { albumPath, artistPath } from "@/lib/routes"
import * as React from "react"
import Link from "next/link"
import {
@@ -167,7 +165,7 @@ export function MediaContextMenuItems({
<MediaMenuSeparator />
{artist ? (
<MediaMenuItem asChild className="justify-between">
<Link href={artistPath(artist.id)}>
<Link href={`/artist/${artist.id}`}>
Go to Artist
<MicVocal />
</Link>
@@ -175,7 +173,7 @@ export function MediaContextMenuItems({
) : null}
{album ? (
<MediaMenuItem asChild className="justify-between">
<Link href={albumPath(album.id)}>
<Link href={`/album/${album.id}`}>
Go to Album
<GalleryVerticalEnd />
</Link>
+1 -11
View File
@@ -2,20 +2,10 @@
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 { 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)}`
page.searchParams.delete("id")
}
link.searchParams.set("url", page.href)
link.searchParams.set("url", window.location.href)
window.location.assign(link.href)
}
+1 -5
View File
@@ -1,7 +1,5 @@
"use client"
import { serverUrl } 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"
@@ -151,9 +149,7 @@ function UserAvatar({
key={user.image ?? "fallback"}
size={size === "sm" ? "sm" : "default"}
>
{user.image ? (
<AvatarImage src={serverUrl(user.image)} alt={user.name} />
) : null}
{user.image ? <AvatarImage src={user.image} alt={user.name} /> : null}
<AvatarFallback>{initials}</AvatarFallback>
</Avatar>
)
+8 -6
View File
@@ -1,7 +1,5 @@
"use client"
import { authedUrl } from "@/lib/server"
import {
useState,
useEffect,
@@ -356,11 +354,15 @@ function loadAudioSource(
}
const { settings } = source
const directUrl = authedUrl(
songPlayPath(songId, settings.playbackQuality, settings.preferAtmos)
const directUrl = songPlayPath(
songId,
settings.playbackQuality,
settings.preferAtmos
)
const hlsUrl = authedUrl(
songHlsPlaylistPath(songId, settings.playbackQuality, settings.preferAtmos)
const hlsUrl = songHlsPlaylistPath(
songId,
settings.playbackQuality,
settings.preferAtmos
)
const loadDirectSource = () => {
+3 -4
View File
@@ -1,4 +1,3 @@
import { albumPath, artistPath } from "@/lib/routes"
import Link from "next/link"
import type { BrowseSong } from "@otunes/convex/types"
@@ -25,7 +24,7 @@ export function PlaybackSongMeta({
)}
>
<Link
href={albumPath(song.album.id)}
href={`/album/${song.album.id}`}
className={cn(
"block truncate text-sm font-medium hover:underline",
inRange && "text-primary-foreground hover:text-primary-foreground/80",
@@ -41,7 +40,7 @@ export function PlaybackSongMeta({
)}
>
<Link
href={artistPath(song.artist.id)}
href={`/artist/${song.artist.id}`}
className={cn(
"hover:underline",
inRange
@@ -55,7 +54,7 @@ export function PlaybackSongMeta({
<>
<span aria-hidden="true"> — </span>
<Link
href={albumPath(song.album.id)}
href={`/album/${song.album.id}`}
className="hover:text-foreground hover:underline"
>
{song.album.title}
+3 -5
View File
@@ -1,7 +1,5 @@
"use client"
import { albumPath, artistPath } from "@/lib/routes"
import * as React from "react"
import Image from "next/image"
import Link from "next/link"
@@ -186,21 +184,21 @@ export function PlayerBar() {
</div>
<div className="min-w-0 flex-1">
<Link
href={albumPath(currentSong.album.id)}
href={`/album/${currentSong.album.id}`}
className="block truncate text-sm font-semibold hover:underline md:text-[13px] md:leading-4"
>
{currentSong.title}
</Link>
<p className="truncate text-xs">
<Link
href={artistPath(currentSong.artist.id)}
href={`/artist/${currentSong.artist.id}`}
className="hover:underline"
>
{currentSong.artist.name}
</Link>
<span aria-hidden> · </span>
<Link
href={albumPath(currentSong.album.id)}
href={`/album/${currentSong.album.id}`}
className="hover:underline"
>
{currentSong.album.title}
+2 -4
View File
@@ -1,7 +1,5 @@
"use client"
import { playlistPath } from "@/lib/routes"
import Image from "next/image"
import Link from "next/link"
@@ -81,7 +79,7 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
return (
<div className="flex flex-col gap-2">
<div className="group relative aspect-square overflow-hidden rounded-lg ring-1 ring-foreground/10">
<Link className="absolute inset-0" href={playlistPath(playlist.id)}>
<Link className="absolute inset-0" href={"/playlist/" + playlist.id}>
<Image
src={playlistCoverUrl(playlist.id, playlist.cover, 384)}
alt={playlist.title}
@@ -132,7 +130,7 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
</div>
<div className="min-w-0">
<Link href={playlistPath(playlist.id)} className="hover:underline">
<Link href={"/playlist/" + playlist.id} className="hover:underline">
<p className="truncate text-sm font-medium">{playlist.title}</p>
</Link>
<p className="truncate text-xs text-muted-foreground decoration-muted-foreground">
+3 -5
View File
@@ -2,8 +2,6 @@
import { useDownloads } from "@/components/downloads-provider"
import { useSongDownloadState } from "@/hooks/use-downloads"
import { albumPath, artistPath } from "@/lib/routes"
import Image from "next/image"
import Link from "next/link"
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
@@ -83,7 +81,7 @@ export function SearchSongItem({ song }: { song: SearchSong }) {
<MediaContextMenuArea menu={menu}>
<div className="group flex items-center gap-3 rounded-lg px-1 py-1.5 transition-colors hover:bg-muted/50">
<Link
href={albumPath(song.album.id)}
href={`/album/${song.album.id}`}
className="relative size-11 shrink-0 overflow-hidden rounded ring-1 ring-foreground/10"
>
<Image
@@ -96,11 +94,11 @@ export function SearchSongItem({ song }: { song: SearchSong }) {
</Link>
<div className="min-w-0 flex-1">
<Link href={albumPath(song.album.id)} className="hover:underline">
<Link href={`/album/${song.album.id}`} className="hover:underline">
<p className="truncate text-sm font-medium">{song.title}</p>
</Link>
<Link
href={artistPath(song.artist.id)}
href={`/artist/${song.artist.id}`}
className="text-muted-foreground hover:text-foreground hover:underline"
>
<p className="truncate text-sm">{song.artist.name}</p>
@@ -1,7 +1,5 @@
"use client"
import { albumPath, artistPath } from "@/lib/routes"
import Image from "next/image"
import Link from "next/link"
@@ -14,11 +12,11 @@ export type TopResult = SearchTopResultItem
function resultHref(result: TopResult) {
switch (result.kind) {
case "song":
return albumPath(result.item.album.id)
return `/album/${result.item.album.id}`
case "album":
return albumPath(result.item.id)
return `/album/${result.item.id}`
case "artist":
return artistPath(result.item.id)
return `/artist/${result.item.id}`
}
}
-115
View File
@@ -1,115 +0,0 @@
"use client"
import { useState, type FormEvent } from "react"
import Image from "next/image"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
Field,
FieldError,
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"
// 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 {
// Opaque, but it fails when the Convex server cannot be reached.
await fetch(`${server.convexUrl}/version`, {
mode: "no-cors",
signal: AbortSignal.timeout(10000),
})
} 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 (
<main className="grid min-h-svh bg-background text-foreground md:grid-cols-2">
<aside className="flex flex-col justify-between gap-12 border-b border-border bg-muted/30 p-8 md:border-r md:border-b-0 md:p-12">
<div className="flex items-center gap-3">
<Image
src="/logo.png"
alt=""
width={48}
height={48}
unoptimized
className="dark:hidden"
/>
<Image
src="/logo-dark.png"
alt=""
width={48}
height={48}
unoptimized
className="hidden dark:block"
/>
<span className="text-xl font-semibold">oTunes</span>
</div>
<h1 className="text-4xl font-semibold tracking-tight lg:text-5xl">
Your server.
<br />
Your music.
</h1>
</aside>
<section className="flex items-center justify-center p-8 md:p-12">
<form onSubmit={connect} className="w-full max-w-sm">
<h2 className="mb-8 text-2xl font-semibold tracking-tight">
Connect to a server
</h2>
<FieldGroup>
<Field>
<FieldLabel htmlFor="server-address">Server address</FieldLabel>
<Input
id="server-address"
name="hostname"
value={address}
onChange={(event) => setAddress(event.target.value)}
placeholder="music.example.com"
autoCapitalize="none"
autoCorrect="off"
spellCheck={false}
autoComplete="url"
required
disabled={submitting}
aria-invalid={!!error}
aria-describedby={error ? "server-error" : undefined}
/>
{error && (
<FieldError id="server-error" role="alert">
{error}
</FieldError>
)}
</Field>
<Button type="submit" disabled={submitting}>
{submitting ? "Connecting…" : "Continue"}
</Button>
</FieldGroup>
</form>
</section>
</main>
)
}
+2 -4
View File
@@ -1,7 +1,5 @@
"use client"
import { albumPath, artistPath } from "@/lib/routes"
import * as React from "react"
import Image from "next/image"
import Link from "next/link"
@@ -400,7 +398,7 @@ function TrackRowComponent({
</div>
<div className={LIBRARY_COLUMN}>
<Link
href={artistPath(song.artist.id)}
href={"/artist/" + song.artist.id}
className={linkClass}
onClick={(event) => event.stopPropagation()}
>
@@ -409,7 +407,7 @@ function TrackRowComponent({
</div>
<div className={LIBRARY_COLUMN}>
<Link
href={albumPath(song.album.id)}
href={"/album/" + song.album.id}
className={linkClass}
onClick={(event) => event.stopPropagation()}
>
+1 -3
View File
@@ -1,9 +1,7 @@
import { serverUrl } from "@/lib/server"
export type CoverImageSize = 64 | 128 | 192 | 256 | 384 | 512 | 768 | 1024
function withCoverImageSize(uri: string, size?: CoverImageSize) {
return serverUrl(size ? `${uri}?size=${size}` : uri)
return size ? `${uri}?size=${size}` : uri
}
export function artistCoverUrl(artistId: string, size?: CoverImageSize) {
+2 -5
View File
@@ -1,4 +1,4 @@
const EC3_MIMES = ['audio/mp4; codecs="ec-3"', 'audio/x-m4a; codecs="ec-3"']
const EC3_MIME = 'audio/x-m4a; codecs="ec-3"'
const AC4_MIME = 'audio/x-m4a; codecs="ac-4"'
function canPlayMime(audio: HTMLAudioElement, mime: string): boolean {
@@ -6,8 +6,5 @@ function canPlayMime(audio: HTMLAudioElement, mime: string): boolean {
}
export function supportsDolbyAtmosPlayback(audio: HTMLAudioElement): boolean {
return (
EC3_MIMES.some((mime) => canPlayMime(audio, mime)) ||
canPlayMime(audio, AC4_MIME)
)
return canPlayMime(audio, EC3_MIME) || canPlayMime(audio, AC4_MIME)
}
+9 -15
View File
@@ -12,8 +12,6 @@ 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.
@@ -40,22 +38,21 @@ 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}`
const path = kind === "album" ? albumPath(id) : playlistPath(id)
return `${path}&${FROM_DOWNLOADS_PARAM}`
return `/playlist/${id}?${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 server builds the worker
* also keeps pages and app code so the app opens offline. Static exports are
* served locally, so they always open.
* Lets downloaded covers show offline. In production builds the worker also
* keeps pages and app code so the app opens offline.
*/
export function registerDownloadsServiceWorker() {
const url =
process.env.NODE_ENV === "production" && !staticExport
process.env.NODE_ENV === "production"
? "/downloads-sw.js?offline-app"
: "/downloads-sw.js"
void navigator.serviceWorker?.register(url, { scope: "/" }).catch(() => {})
@@ -126,12 +123,9 @@ const storage: DownloadStorage = {
)
},
async save({ songId, requested, quality, albumId }, signal) {
const response = await fetch(
authedUrl(songDownloadPath(songId, requested)),
{
signal,
}
)
const response = await fetch(songDownloadPath(songId, requested), {
signal,
})
if (!response.ok) {
throw new Error(`Download failed with ${response.status}`)
}
@@ -148,7 +142,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(serverUrl(`${key}?size=${COVER_SIZE}`))
const response = await fetch(`${key}?size=${COVER_SIZE}`)
if (!response.ok) throw new Error(`Cover failed with ${response.status}`)
await cache.put(key, response)
},
+3 -2
View File
@@ -1,5 +1,4 @@
import { toast } from "sonner"
import { serverOrigin } from "@/lib/server"
import {
mediaShareUrl,
type MediaShareTarget,
@@ -8,7 +7,9 @@ import {
export type MediaShareContext = MediaShareTarget
export async function copyMediaShareLink(share: MediaShareContext) {
await navigator.clipboard.writeText(mediaShareUrl(serverOrigin(), share))
await navigator.clipboard.writeText(
mediaShareUrl(window.location.origin, share)
)
toast.success("Link Copied")
}
-17
View File
@@ -1,17 +0,0 @@
// In-app routes pass ids as query parameters so the UI can be a static export.
// Share links keep the `/album/<id>` form (see mediaShareUrl), which only the
// server build serves, with link-preview metadata.
export function albumPath(albumId: string, songId?: string) {
const query = new URLSearchParams({ id: albumId })
if (songId) query.set("s", songId)
return `/album?${query}`
}
export function artistPath(artistId: string) {
return `/artist?${new URLSearchParams({ id: artistId })}`
}
export function playlistPath(playlistId: string) {
return `/playlist?${new URLSearchParams({ id: playlistId })}`
}
+8 -26
View File
@@ -2,29 +2,15 @@ import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server"
import { api } from "@otunes/convex/_generated/api"
import type { Doc, 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"
/**
* The listener's session, from the cookie or from a `token` query parameter
* (static exports on another origin).
* 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.
*/
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. Throws when signed out or missing.
*/
export async function getSongSource(
id: string,
request: NextRequest
): Promise<SongSource> {
const token = await sessionToken(request)
export async function getSongSource(id: string): Promise<SongSource> {
const token = await convexAuthNextjsToken()
const song = await fetchQuery(
api.library.getSongSource,
{ id: id as Id<"songs"> },
@@ -37,11 +23,8 @@ export async function getSongSource(
}
/** The song's stored lyrics tag, or null without lyrics. */
export async function getSongLyrics(
id: string,
request: NextRequest
): Promise<string | null> {
const token = await sessionToken(request)
export async function getSongLyrics(id: string): Promise<string | null> {
const token = await convexAuthNextjsToken()
return await fetchQuery(
api.lyrics.forSong,
{ id: id as Id<"songs"> },
@@ -53,10 +36,9 @@ const SOURCE_BATCH_SIZE = 200
/** `getSongSource` for many songs, in batches. Missing songs are left out. */
export async function getSongSources(
ids: string[],
request: NextRequest
ids: string[]
): Promise<(SongSource & Pick<Doc<"songs">, "album">)[]> {
const token = await sessionToken(request)
const token = await convexAuthNextjsToken()
const batches: string[][] = []
for (let start = 0; start < ids.length; start += SOURCE_BATCH_SIZE) {
batches.push(ids.slice(start, start + SOURCE_BATCH_SIZE))
-65
View File
@@ -1,65 +0,0 @@
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, 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)
if (!server || !mediaToken) return url
return `${url}${url.includes("?") ? "&" : "?"}token=${encodeURIComponent(mediaToken)}`
}
+1 -26
View File
@@ -1,33 +1,9 @@
import path from "node:path"
import type { NextConfig } from "next"
// `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" : ".next",
pageExtensions: staticExport
? ["tsx", "ts"]
: ["server.tsx", "server.ts", "tsx", "ts"],
env: { OTUNES_STATIC_EXPORT: staticExport ? "1" : "" },
output: "standalone",
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: "*" },
// For the JSON body of POST /api/download/options.
{ key: "Access-Control-Allow-Headers", value: "Content-Type" },
],
},
],
experimental: {
// Failed navigations wait for the connection instead of reloading the
// page, which would show the browser's offline page and stop playback.
@@ -39,7 +15,6 @@ const nextConfig: NextConfig = {
},
},
images: {
unoptimized: staticExport,
minimumCacheTTL: 60,
dangerouslyAllowSVG: true,
contentDispositionType: "attachment",
-1
View File
@@ -5,7 +5,6 @@
"scripts": {
"dev": "next dev",
"build": "next build",
"build:export": "OTUNES_STATIC_EXPORT=1 next build",
"start": "next start",
"lint": "eslint .",
"typecheck": "tsc --noEmit"
+2 -10
View File
@@ -7,24 +7,18 @@ import { getConvexServerUrl } from "@/lib/convex-server"
const isAuthPage = createRouteMatcher(["/signin", "/signup"])
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",
// Mobile clients load avatars without the web auth cookie.
"/api/user/:id/avatar",
"/album",
"/album/:id",
"/artist",
"/artist/:id",
"/playlist",
"/library/artists/:id",
"/playlist/:id",
])
const authMiddleware = convexAuthNextjsMiddleware(
export default convexAuthNextjsMiddleware(
async (request, { convexAuth }) => {
if (isPublic(request)) {
return
@@ -43,8 +37,6 @@ const authMiddleware = convexAuthNextjsMiddleware(
{ convexUrl: getConvexServerUrl() }
)
export default authMiddleware
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
}
+9 -12
View File
@@ -7,8 +7,7 @@
// 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. Static exports load covers from
// the picked server's origin, so covers match on the path alone.
// server would send for a missing cover.
// Pages and app code are only handled in production builds (`?offline-app`),
// where app code is content-hashed.
const COVER_CACHE = "otunes-download-covers"
@@ -72,7 +71,8 @@ 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 && url.pathname === "/_next/image") {
if (url.origin !== self.location.origin) return null
if (url.pathname === "/_next/image") {
const inner = url.searchParams.get("url")
return inner ? coverKey(new URL(inner, self.location.origin)) : null
}
@@ -170,10 +170,7 @@ async function savedCover(key) {
async function handleCover(request, key) {
try {
const response = await fetch(request)
// Covers from another origin load as opaque responses, with no status.
return response.ok || response.type === "opaque"
? response
: ((await savedCover(key)) ?? response)
return response.ok ? response : ((await savedCover(key)) ?? response)
} catch (error) {
const cover = await savedCover(key)
if (cover) return cover
@@ -198,11 +195,6 @@ 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") {
@@ -213,6 +205,11 @@ 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))
}
+1 -3
View File
@@ -29,9 +29,7 @@
"**/*.tsx",
"**/*.mts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
".next-desktop/types/**/*.ts",
".next-desktop/dev/types/**/*.ts"
".next/dev/types/**/*.ts"
],
"exclude": ["node_modules"]
}
+1 -3
View File
@@ -12,9 +12,7 @@
"start": "pnpm --filter @otunes/web start",
"lint": "pnpm -r lint",
"format": "prettier --write \"**/*.{ts,tsx}\"",
"typecheck": "pnpm -r typecheck",
"dev:desktop": "pnpm --filter @otunes/desktop start",
"build:desktop": "pnpm --filter @otunes/desktop build"
"typecheck": "pnpm -r typecheck"
},
"devDependencies": {
"prettier": "^3.8.3",
-29
View File
@@ -45,32 +45,3 @@ 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
}
}
-1446
View File
File diff suppressed because it is too large. Load diff
-3
View File
@@ -10,9 +10,6 @@ patchedDependencies:
'@react-native-community/slider@5.2.1': patches/@react-native-community__slider@5.2.1.patch
'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: