Compare commits
No files matched your search
+47
-20
@@ -7,12 +7,11 @@
|
|||||||
# To ensure security and compatibility, regularly update the NODE_VERSION ARG to the latest LTS version.
|
# To ensure security and compatibility, regularly update the NODE_VERSION ARG to the latest LTS version.
|
||||||
ARG NODE_VERSION=24.13.0-slim
|
ARG NODE_VERSION=24.13.0-slim
|
||||||
|
|
||||||
FROM node:${NODE_VERSION} AS runner-base
|
# The Convex backend runs inside the oTunes image. Pin to a commit tag from
|
||||||
|
# https://github.com/get-convex/convex-backend/pkgs/container/convex-backend
|
||||||
RUN apt-get update && \
|
ARG CONVEX_BACKEND_IMAGE=ghcr.io/get-convex/convex-backend:5c7cb5bc7db457290f1769f95f1d1340912f7fd7
|
||||||
apt-get install -y ffmpeg && \
|
|
||||||
rm -rf /var/lib/apt/lists/*
|
|
||||||
|
|
||||||
|
FROM node:${NODE_VERSION} AS node
|
||||||
|
|
||||||
FROM node:${NODE_VERSION} AS dependencies
|
FROM node:${NODE_VERSION} AS dependencies
|
||||||
|
|
||||||
@@ -57,35 +56,63 @@ COPY --from=dependencies /app/packages/convex/node_modules ./packages/convex/nod
|
|||||||
|
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
ARG NEXT_PUBLIC_CONVEX_URL
|
|
||||||
|
|
||||||
WORKDIR /app/apps/web
|
WORKDIR /app/apps/web
|
||||||
|
|
||||||
RUN --mount=type=cache,target=/app/apps/web/.next/cache \
|
RUN --mount=type=cache,target=/app/apps/web/.next/cache \
|
||||||
corepack enable pnpm && pnpm build
|
corepack enable pnpm && pnpm build
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# Stage 3: Run Next.js application
|
# Stage 3: Convex functions, deployed to the bundled backend on boot
|
||||||
# ============================================
|
# ============================================
|
||||||
|
|
||||||
FROM runner-base AS runner
|
FROM node:${NODE_VERSION} AS convex-functions
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
ENV NODE_ENV=production
|
COPY package.json pnpm-lock.yaml .npmrc ./
|
||||||
ENV PORT=3000
|
COPY packages/convex/package.json ./packages/convex/
|
||||||
ENV HOSTNAME="0.0.0.0"
|
|
||||||
|
|
||||||
RUN mkdir /data
|
RUN printf '%s\n' \
|
||||||
|
'packages:' \
|
||||||
|
' - "packages/convex"' \
|
||||||
|
> pnpm-workspace.yaml
|
||||||
|
|
||||||
COPY --from=builder --chown=node:node /app/apps/web/public ./apps/web/public
|
RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
|
||||||
COPY --from=builder --chown=node:node /app/apps/web/.next/standalone ./
|
corepack enable pnpm && \
|
||||||
COPY --from=builder --chown=node:node /app/apps/web/.next/static ./apps/web/.next/static
|
pnpm install --frozen-lockfile --prod --filter @otunes/convex...
|
||||||
|
|
||||||
RUN mkdir -p apps/web/.next && chown -R node:node apps/web/.next
|
COPY packages/convex ./packages/convex
|
||||||
|
|
||||||
USER node
|
# ============================================
|
||||||
|
# Stage 4: Run Convex and Next.js together
|
||||||
|
# ============================================
|
||||||
|
|
||||||
EXPOSE 3000
|
FROM ${CONVEX_BACKEND_IMAGE} AS runner
|
||||||
|
|
||||||
CMD ["node", "apps/web/server.js"]
|
RUN apt-get update && \
|
||||||
|
apt-get install -y --no-install-recommends ffmpeg tini && \
|
||||||
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes
|
||||||
|
|
||||||
|
COPY --from=node /usr/local/bin/node /opt/node/bin/node
|
||||||
|
|
||||||
|
COPY --from=convex-functions /app /opt/otunes/convex
|
||||||
|
COPY docker/generate-auth-keys.mjs /opt/otunes/generate-auth-keys.mjs
|
||||||
|
COPY --chmod=755 docker/entrypoint.sh /usr/local/bin/otunes-entrypoint
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY --from=builder --chown=otunes:otunes /app/apps/web/public ./apps/web/public
|
||||||
|
COPY --from=builder --chown=otunes:otunes /app/apps/web/.next/standalone ./
|
||||||
|
COPY --from=builder --chown=otunes:otunes /app/apps/web/.next/static ./apps/web/.next/static
|
||||||
|
|
||||||
|
RUN mkdir -p apps/web/.next /data && chown -R otunes:otunes apps/web/.next
|
||||||
|
|
||||||
|
EXPOSE 3000 3210
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=10s --timeout=5s --start-period=60s \
|
||||||
|
CMD curl -fsS http://127.0.0.1:3210/version && curl -fsS -o /dev/null http://127.0.0.1:3000/signin
|
||||||
|
|
||||||
|
ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/otunes-entrypoint"]
|
||||||
|
CMD []
|
||||||
@@ -40,6 +40,12 @@ Run the Convex backend (from the shared package):
|
|||||||
pnpm dev:convex
|
pnpm dev:convex
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Point the dev deployment at your music folder (it defaults to `/data`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd packages/convex && npx convex env set DATA "/path/to/Music"
|
||||||
|
```
|
||||||
|
|
||||||
Other commands:
|
Other commands:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -51,61 +57,39 @@ pnpm format # format with Prettier
|
|||||||
|
|
||||||
## Hosting with Docker
|
## Hosting with Docker
|
||||||
|
|
||||||
Here's an example `docker-compose.yml` file to get you started:
|
The image runs both the web app and its Convex backend, so there is nothing to configure. Here's an example `docker-compose.yml`:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
name: music
|
name: music
|
||||||
services:
|
services:
|
||||||
otunes:
|
otunes:
|
||||||
|
image: git.abunchofknowitalls.com/joshuafhiggins/otunes:latest
|
||||||
ports:
|
ports:
|
||||||
- "3000:3000"
|
- "3000:3000" # web app
|
||||||
|
- "3210:3210" # Convex
|
||||||
volumes:
|
volumes:
|
||||||
|
- ./otunes-data:/convex/data
|
||||||
- /SomeAttachedStorage/Music:/data
|
- /SomeAttachedStorage/Music:/data
|
||||||
environment:
|
|
||||||
- NEXT_PUBLIC_CONVEX_URL=http://127.0.0.1:3210
|
|
||||||
- CONVEX_SELF_HOSTED_URL=http://127.0.0.1:3210
|
|
||||||
- CONVEX_SELF_HOSTED_ADMIN_KEY=REPLACE_ME
|
|
||||||
restart: unless-stopped
|
|
||||||
image: otunes
|
|
||||||
build:
|
|
||||||
context: .
|
|
||||||
dockerfile: Dockerfile
|
|
||||||
args:
|
|
||||||
- NEXT_PUBLIC_CONVEX_URL=http://127.0.0.1:3210
|
|
||||||
backend:
|
|
||||||
stop_grace_period: 10s
|
stop_grace_period: 10s
|
||||||
stop_signal: SIGINT
|
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
ports:
|
|
||||||
- "3210:3210"
|
|
||||||
- "3211:3211"
|
|
||||||
volumes:
|
|
||||||
- ./database:/convex/data
|
|
||||||
environment:
|
|
||||||
- CONVEX_CLOUD_ORIGIN=http://127.0.0.1:3210
|
|
||||||
- CONVEX_SITE_ORIGIN=http://127.0.0.1:3211
|
|
||||||
- APPLICATION_MAX_CONCURRENT_MUTATIONS=16
|
|
||||||
- APPLICATION_MAX_CONCURRENT_NODE_ACTIONS=16
|
|
||||||
- APPLICATION_MAX_CONCURRENT_QUERIES=16
|
|
||||||
- APPLICATION_MAX_CONCURRENT_V8_ACTIONS=16
|
|
||||||
- DISABLE_BEACON=true
|
|
||||||
- DISABLE_METRICS_ENDPOINT=true
|
|
||||||
- DOCUMENT_RETENTION_DELAY=172800
|
|
||||||
- DO_NOT_REQUIRE_SSL=true
|
|
||||||
- REDACT_LOGS_TO_CLIENT=true
|
|
||||||
- RUST_LOG=info
|
|
||||||
image: ghcr.io/get-convex/convex-backend:latest
|
|
||||||
healthcheck:
|
|
||||||
test: curl -f http://localhost:3210/version
|
|
||||||
interval: 5s
|
|
||||||
start_period: 10s
|
|
||||||
```
|
```
|
||||||
|
|
||||||
First run `docker compose up -d backend` and `docker compose exec backend ./generate_admin_key.sh` to generate the admin key needed for the frontend. Take this key and put it in the `CONVEX_SELF_HOSTED_ADMIN_KEY` environment variable for the `otunes` service.
|
Change `/SomeAttachedStorage/Music` to the folder containing your `lossless`, `normal`, and `atmos` libraries, then run `docker compose up -d`. The first account you create becomes the admin.
|
||||||
|
|
||||||
`CONVEX_SELF_HOSTED_URL`, `CONVEX_CLOUD_ORIGIN`, and `NEXT_PUBLIC_CONVEX_URL` should be changed to the same reversed proxied, SSL protected, domain and `CONVEX_SITE_ORIGIN` on a different domain.
|
On first boot the container generates its own Convex instance secret and sign-in keys and stores them in `./otunes-data`, so no two installs share secrets. Back up that folder: it holds your database and keys.
|
||||||
|
|
||||||
Then change `/SomeAttachedStorage/Music` to the path where your music is stored and run `docker compose down && docker compose up -d` to start the whole app together.
|
### Reverse proxy
|
||||||
|
|
||||||
|
The web app finds Convex from the address you open it at:
|
||||||
|
|
||||||
|
| You open | Convex is expected at |
|
||||||
|
| --- | --- |
|
||||||
|
| `https://music.example.com` | `https://convex.music.example.com` |
|
||||||
|
| `http://192.168.1.5:3000` or `http://localhost:3000` | port `3210` on the same host |
|
||||||
|
|
||||||
|
So for a domain, point `music.example.com` at port `3000` and `convex.music.example.com` at port `3210` (WebSockets must be allowed). The mobile app uses the same convention.
|
||||||
|
|
||||||
|
If Convex has to live somewhere else, set `PUBLIC_CONVEX_URL` on the container to its public URL.
|
||||||
|
|
||||||
## Downloads
|
## Downloads
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { buildConvexUrl, isLocalHost } from "@otunes/convex/server-url"
|
||||||
|
|
||||||
export type ServerConfig = {
|
export type ServerConfig = {
|
||||||
/** Raw hostname the user entered, e.g. `music.example.com` or `192.168.86.25:3000` */
|
/** Raw hostname the user entered, e.g. `music.example.com` or `192.168.86.25:3000` */
|
||||||
hostname: string
|
hostname: string
|
||||||
@@ -9,30 +11,6 @@ export type ServerConfig = {
|
|||||||
|
|
||||||
const SERVER_CONFIG_KEY = "otunes.server-config"
|
const SERVER_CONFIG_KEY = "otunes.server-config"
|
||||||
const LEGACY_SERVER_CONFIG_KEY = "otunes:server-config"
|
const LEGACY_SERVER_CONFIG_KEY = "otunes:server-config"
|
||||||
const LOCAL_CONVEX_PORT = "3210"
|
|
||||||
|
|
||||||
function parseHostPort(hostname: string): { host: string; port?: string } {
|
|
||||||
const colonIndex = hostname.lastIndexOf(":")
|
|
||||||
if (colonIndex === -1) {
|
|
||||||
return { host: hostname }
|
|
||||||
}
|
|
||||||
const host = hostname.slice(0, colonIndex)
|
|
||||||
const port = hostname.slice(colonIndex + 1)
|
|
||||||
if (!/^\d+$/.test(port)) {
|
|
||||||
return { host: hostname }
|
|
||||||
}
|
|
||||||
return { host, port }
|
|
||||||
}
|
|
||||||
|
|
||||||
function isLocalHost(hostname: string): boolean {
|
|
||||||
const host = parseHostPort(hostname).host.toLowerCase()
|
|
||||||
return (
|
|
||||||
host === "localhost" ||
|
|
||||||
host === "127.0.0.1" ||
|
|
||||||
host.endsWith(".local") ||
|
|
||||||
/^\d{1,3}(\.\d{1,3}){3}$/.test(host)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeHostnameInput(input: string): string {
|
function normalizeHostnameInput(input: string): string {
|
||||||
return input.trim().replace(/^https?:\/\//i, "").replace(/\/+$/, "")
|
return input.trim().replace(/^https?:\/\//i, "").replace(/\/+$/, "")
|
||||||
@@ -43,16 +21,6 @@ function buildServerUrl(hostname: string): string {
|
|||||||
return `${protocol}://${hostname}`
|
return `${protocol}://${hostname}`
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildConvexUrl(hostname: string): string {
|
|
||||||
const { host, port } = parseHostPort(hostname)
|
|
||||||
const protocol = isLocalHost(hostname) ? "http" : "https"
|
|
||||||
if (isLocalHost(hostname)) {
|
|
||||||
return `${protocol}://${host}:${LOCAL_CONVEX_PORT}`
|
|
||||||
}
|
|
||||||
const convexHost = `convex.${host}`
|
|
||||||
return port ? `${protocol}://${convexHost}:${port}` : `${protocol}://${convexHost}`
|
|
||||||
}
|
|
||||||
|
|
||||||
export function parseServerHostname(input: string): ServerConfig | null {
|
export function parseServerHostname(input: string): ServerConfig | null {
|
||||||
const hostname = normalizeHostnameInput(input)
|
const hostname = normalizeHostnameInput(input)
|
||||||
if (!hostname) return null
|
if (!hostname) return null
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { HomeSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||||
|
|
||||||
|
export default function Loading() {
|
||||||
|
return (
|
||||||
|
<div className="flex h-svh flex-col">
|
||||||
|
<PageHeader title="Home" />
|
||||||
|
<HomeSkeleton />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { ContentCarousel } from "@/components/content-carousel"
|
||||||
|
import { HomeSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||||
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||||
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
|
|
||||||
|
export default function Page() {
|
||||||
|
const recentlyAdded = useCachedQuery(api.library.browseRecentlyAdded, {
|
||||||
|
limit: 9,
|
||||||
|
})
|
||||||
|
const recentlyPlayed = useCachedQuery(api.library.browseRecentlyPlayed, {
|
||||||
|
limit: 9,
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex h-svh flex-col">
|
||||||
|
<PageHeader title="Home" />
|
||||||
|
|
||||||
|
{recentlyAdded === undefined || recentlyPlayed === undefined ? (
|
||||||
|
<HomeSkeleton />
|
||||||
|
) : (
|
||||||
|
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
||||||
|
<div className="flex flex-col gap-10">
|
||||||
|
{recentlyPlayed.length > 0 ? (
|
||||||
|
<ContentCarousel
|
||||||
|
title="Recently Played"
|
||||||
|
href="/recently-played"
|
||||||
|
content={recentlyPlayed}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
<ContentCarousel
|
||||||
|
title="Recently Added"
|
||||||
|
href="/recently-added"
|
||||||
|
content={recentlyAdded}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,9 +1,5 @@
|
|||||||
import { LibraryLoading } from "@/components/library-loading"
|
import { CollectionDetailSkeleton } from "@/components/library-skeletons"
|
||||||
|
|
||||||
export default function Loading() {
|
export default function Loading() {
|
||||||
return (
|
return <CollectionDetailSkeleton />
|
||||||
<div className="flex h-svh flex-col">
|
|
||||||
<LibraryLoading />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { AlbumView } from "@/components/album-view"
|
import { AlbumPage } from "@/components/album-page"
|
||||||
import { LibraryLoading } from "@/components/library-loading"
|
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
import { fetchQuery } from "convex/nextjs"
|
import { fetchQuery } from "convex/nextjs"
|
||||||
|
import { convexServerOptions } from "@/lib/convex-server"
|
||||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
import { Metadata } from "next"
|
import { Metadata } from "next"
|
||||||
import { cache } from "react"
|
import { cache } from "react"
|
||||||
@@ -12,7 +12,7 @@ interface PageProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const fetchAlbumDetail = cache((id: Id<"albums">) =>
|
const fetchAlbumDetail = cache((id: Id<"albums">) =>
|
||||||
fetchQuery(api.library.browseAlbumDetail, { id })
|
fetchQuery(api.library.browseAlbumDetail, { id }, convexServerOptions())
|
||||||
)
|
)
|
||||||
|
|
||||||
export async function generateMetadata({
|
export async function generateMetadata({
|
||||||
@@ -48,29 +48,15 @@ export async function generateMetadata({
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default async function Page({ params, searchParams }: PageProps) {
|
export default async function Page({ params, searchParams }: PageProps) {
|
||||||
const { id } = await params
|
const [{ id }, { s: highlightedSongId }] = await Promise.all([
|
||||||
const [{ s: highlightedSongId }, album] = await Promise.all([
|
params,
|
||||||
searchParams,
|
searchParams,
|
||||||
fetchAlbumDetail(id as Id<"albums">),
|
|
||||||
])
|
])
|
||||||
|
|
||||||
if (album === undefined) {
|
return (
|
||||||
return (
|
<AlbumPage
|
||||||
<div className="flex h-svh flex-col">
|
albumId={id as Id<"albums">}
|
||||||
<LibraryLoading />
|
highlightedSongId={highlightedSongId}
|
||||||
</div>
|
/>
|
||||||
)
|
)
|
||||||
}
|
|
||||||
|
|
||||||
if (album === null) {
|
|
||||||
return (
|
|
||||||
<div className="flex h-svh flex-col">
|
|
||||||
<div className="flex flex-1 items-center justify-center pb-28">
|
|
||||||
<p className="text-sm text-muted-foreground">Album not found.</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return <AlbumView album={album} highlightedSongId={highlightedSongId} />
|
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,5 @@
|
|||||||
import { LibraryLoading } from "@/components/library-loading"
|
import { ArtistDetailSkeleton } from "@/components/library-skeletons"
|
||||||
|
|
||||||
export default function Loading() {
|
export default function Loading() {
|
||||||
return (
|
return <ArtistDetailSkeleton />
|
||||||
<div className="flex h-svh flex-col">
|
|
||||||
<LibraryLoading />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { fetchQuery } from "convex/nextjs"
|
import { fetchQuery } from "convex/nextjs"
|
||||||
import { ArtistView } from "@/components/artist-view"
|
import { convexServerOptions } from "@/lib/convex-server"
|
||||||
import { LibraryLoading } from "@/components/library-loading"
|
import { ArtistPage } from "@/components/artist-page"
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
import { Metadata } from "next"
|
import { Metadata } from "next"
|
||||||
@@ -11,7 +11,7 @@ interface PageProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const fetchArtistDetail = cache((id: Id<"artists">) =>
|
const fetchArtistDetail = cache((id: Id<"artists">) =>
|
||||||
fetchQuery(api.library.browseArtistDetail, { id })
|
fetchQuery(api.library.browseArtistDetail, { id }, convexServerOptions())
|
||||||
)
|
)
|
||||||
|
|
||||||
export async function generateMetadata({
|
export async function generateMetadata({
|
||||||
@@ -38,25 +38,5 @@ export async function generateMetadata({
|
|||||||
|
|
||||||
export default async function Page({ params }: PageProps) {
|
export default async function Page({ params }: PageProps) {
|
||||||
const { id } = await params
|
const { id } = await params
|
||||||
const data = await fetchArtistDetail(id as Id<"artists">)
|
return <ArtistPage artistId={id as Id<"artists">} />
|
||||||
|
|
||||||
if (data === undefined) {
|
|
||||||
return (
|
|
||||||
<div className="flex h-svh flex-col">
|
|
||||||
<LibraryLoading />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data === null) {
|
|
||||||
return (
|
|
||||||
<div className="flex h-svh flex-col">
|
|
||||||
<div className="flex flex-1 items-center justify-center pb-28">
|
|
||||||
<p className="text-sm text-muted-foreground">Artist not found.</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return <ArtistView artist={data.artist} albums={data.albums} />
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { CardGridSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||||
|
|
||||||
|
export default function Loading() {
|
||||||
|
return (
|
||||||
|
<div className="flex h-svh flex-col">
|
||||||
|
<PageHeader title="Albums" />
|
||||||
|
<CardGridSkeleton />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,25 +1,23 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useQuery } from "convex/react"
|
|
||||||
|
|
||||||
import { AlbumCard } from "@/components/album-card"
|
import { AlbumCard } from "@/components/album-card"
|
||||||
import { LibraryLoading } from "@/components/library-loading"
|
import { CardGridSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||||
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||||
|
import { albumGridClassName } from "@/lib/album-grid-classes"
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
|
|
||||||
export default function Page() {
|
export default function Page() {
|
||||||
const albums = useQuery(api.library.browseAlbums)
|
const albums = useCachedQuery(api.library.browseAlbums)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-svh flex-col">
|
<div className="flex h-svh flex-col">
|
||||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
<PageHeader title="Albums" />
|
||||||
<h1 className="text-lg font-semibold">Albums</h1>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
{albums === undefined ? (
|
{albums === undefined ? (
|
||||||
<LibraryLoading />
|
<CardGridSkeleton />
|
||||||
) : (
|
) : (
|
||||||
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
||||||
<div className="grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
<div className={albumGridClassName}>
|
||||||
{albums.map((album) => (
|
{albums.map((album) => (
|
||||||
<AlbumCard key={album.id} album={album} />
|
<AlbumCard key={album.id} album={album} />
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -1,20 +1,21 @@
|
|||||||
import { fetchQuery } from "convex/nextjs"
|
import { fetchQuery } from "convex/nextjs"
|
||||||
import { ArtistsView } from "@/components/artists-view"
|
import { convexServerOptions } from "@/lib/convex-server"
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
import { Metadata } from "next"
|
import { Metadata } from "next"
|
||||||
import { cache } from "react"
|
|
||||||
|
|
||||||
interface PageProps {
|
interface PageProps {
|
||||||
params: Promise<{ id: string }>
|
params: Promise<{ id: string }>
|
||||||
}
|
}
|
||||||
|
|
||||||
const fetchArtists = cache(() => fetchQuery(api.library.browseArtists))
|
|
||||||
|
|
||||||
export async function generateMetadata({
|
export async function generateMetadata({
|
||||||
params,
|
params,
|
||||||
}: PageProps): Promise<Metadata> {
|
}: PageProps): Promise<Metadata> {
|
||||||
const { id } = await params
|
const { id } = await params
|
||||||
const artists = await fetchArtists()
|
const artists = await fetchQuery(
|
||||||
|
api.library.browseArtists,
|
||||||
|
{},
|
||||||
|
convexServerOptions()
|
||||||
|
)
|
||||||
const selectedArtist = artists.find((artist) => artist.id === id)
|
const selectedArtist = artists.find((artist) => artist.id === id)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -33,19 +34,6 @@ export async function generateMetadata({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async function Page({ params }: PageProps) {
|
export default function Page() {
|
||||||
const { id } = await params
|
return null
|
||||||
const [artists, albums] = await Promise.all([
|
|
||||||
fetchArtists(),
|
|
||||||
fetchQuery(api.library.browseAlbums),
|
|
||||||
])
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex h-svh flex-col">
|
|
||||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
|
||||||
<h1 className="text-lg font-semibold">Artists</h1>
|
|
||||||
</header>
|
|
||||||
<ArtistsView artists={artists} albums={albums} artistId={id} />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { ArtistsPage } from "@/components/artists-page"
|
||||||
|
|
||||||
|
export default function ArtistsLayout({
|
||||||
|
children,
|
||||||
|
}: Readonly<{
|
||||||
|
children: React.ReactNode
|
||||||
|
}>) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<ArtistsPage />
|
||||||
|
{children}
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
/**
|
||||||
|
* The artists UI lives in the layout and renders from the client cache, so
|
||||||
|
* navigations only need this (empty) boundary to commit.
|
||||||
|
*/
|
||||||
|
export default function Loading() {
|
||||||
|
return null
|
||||||
|
}
|
||||||
@@ -1,25 +1,3 @@
|
|||||||
import { fetchQuery } from "convex/nextjs"
|
export default function Page() {
|
||||||
import { ArtistsView } from "@/components/artists-view"
|
return null
|
||||||
import { LibraryLoading } from "@/components/library-loading"
|
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
|
||||||
|
|
||||||
export default async function Page() {
|
|
||||||
const [artists, albums] = await Promise.all([
|
|
||||||
fetchQuery(api.library.browseArtists),
|
|
||||||
fetchQuery(api.library.browseAlbums),
|
|
||||||
])
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex h-svh flex-col">
|
|
||||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
|
||||||
<h1 className="text-lg font-semibold">Artists</h1>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
{artists === undefined || albums === undefined ? (
|
|
||||||
<LibraryLoading />
|
|
||||||
) : (
|
|
||||||
<ArtistsView artists={artists} albums={albums} />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { PageHeader, SongListSkeleton } from "@/components/library-skeletons"
|
||||||
|
|
||||||
|
export default function Loading() {
|
||||||
|
return (
|
||||||
|
<div className="flex h-svh flex-col">
|
||||||
|
<PageHeader title="Songs" />
|
||||||
|
<SongListSkeleton />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { useQuery } from "convex/react"
|
|
||||||
|
|
||||||
import { ContentCarousel } from "@/components/content-carousel"
|
|
||||||
import { LibraryLoading } from "@/components/library-loading"
|
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
|
||||||
|
|
||||||
export default function Page() {
|
|
||||||
const recentlyAdded = useQuery(api.library.browseRecentlyAdded, { limit: 9 })
|
|
||||||
const recentlyPlayed = useQuery(api.library.browseRecentlyPlayed, {
|
|
||||||
limit: 9,
|
|
||||||
})
|
|
||||||
|
|
||||||
if (recentlyAdded === undefined || recentlyPlayed === undefined) {
|
|
||||||
return (
|
|
||||||
<div className="flex h-svh flex-col">
|
|
||||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
|
||||||
<h1 className="text-lg font-semibold">Home</h1>
|
|
||||||
</header>
|
|
||||||
<LibraryLoading />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex h-svh flex-col">
|
|
||||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
|
||||||
<h1 className="text-lg font-semibold">Home</h1>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
|
||||||
<div className="flex flex-col gap-10">
|
|
||||||
{recentlyPlayed.length > 0 ? (
|
|
||||||
<ContentCarousel
|
|
||||||
title="Recently Played"
|
|
||||||
href="/recently-played"
|
|
||||||
content={recentlyPlayed}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
<ContentCarousel
|
|
||||||
title="Recently Added"
|
|
||||||
href="/recently-added"
|
|
||||||
content={recentlyAdded}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { CollectionDetailSkeleton } from "@/components/library-skeletons"
|
||||||
|
|
||||||
|
export default function Loading() {
|
||||||
|
return <CollectionDetailSkeleton />
|
||||||
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import { LibraryLoading } from "@/components/library-loading"
|
import { PlaylistPage } from "@/components/playlist-page"
|
||||||
import { PlaylistView } from "@/components/playlist-view"
|
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server"
|
import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server"
|
||||||
import { fetchQuery } from "convex/nextjs"
|
import { fetchQuery } from "convex/nextjs"
|
||||||
|
import { convexServerOptions } from "@/lib/convex-server"
|
||||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
import { Metadata } from "next"
|
import { Metadata } from "next"
|
||||||
import { cache } from "react"
|
import { cache } from "react"
|
||||||
@@ -16,7 +16,7 @@ const fetchPlaylistDetail = cache(async (id: Id<"playlists">) => {
|
|||||||
return fetchQuery(
|
return fetchQuery(
|
||||||
api.playlists.browsePlaylistDetail,
|
api.playlists.browsePlaylistDetail,
|
||||||
{ id },
|
{ id },
|
||||||
{ token }
|
convexServerOptions(token)
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -40,25 +40,5 @@ export async function generateMetadata({
|
|||||||
|
|
||||||
export default async function Page({ params }: PageProps) {
|
export default async function Page({ params }: PageProps) {
|
||||||
const { id } = await params
|
const { id } = await params
|
||||||
const playlist = await fetchPlaylistDetail(id as Id<"playlists">)
|
return <PlaylistPage playlistId={id as Id<"playlists">} />
|
||||||
|
|
||||||
if (playlist === undefined) {
|
|
||||||
return (
|
|
||||||
<div className="flex h-svh flex-col">
|
|
||||||
<LibraryLoading />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (playlist === null) {
|
|
||||||
return (
|
|
||||||
<div className="flex h-svh flex-col">
|
|
||||||
<div className="flex flex-1 items-center justify-center pb-28">
|
|
||||||
<p className="text-sm text-muted-foreground">Playlist not found.</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return <PlaylistView key={playlist.id} playlist={playlist} />
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { CollectionDetailSkeleton } from "@/components/library-skeletons"
|
||||||
|
|
||||||
|
export default function Loading() {
|
||||||
|
return <CollectionDetailSkeleton />
|
||||||
|
}
|
||||||
@@ -1,33 +1,7 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useQuery } from "convex/react"
|
import { FavoritesPlaylistPage } from "@/components/playlist-page"
|
||||||
|
|
||||||
import { LibraryLoading } from "@/components/library-loading"
|
|
||||||
import { PlaylistView } from "@/components/playlist-view"
|
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
|
||||||
|
|
||||||
export default function Page() {
|
export default function Page() {
|
||||||
const favorites = useQuery(api.favorites.browseFavoritesPlaylistDetail)
|
return <FavoritesPlaylistPage />
|
||||||
|
|
||||||
if (favorites === undefined) {
|
|
||||||
return (
|
|
||||||
<div className="flex h-svh flex-col">
|
|
||||||
<LibraryLoading />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (favorites === null) {
|
|
||||||
return (
|
|
||||||
<div className="flex h-svh flex-col">
|
|
||||||
<div className="flex flex-1 items-center justify-center pb-28">
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
Sign in to view your favorites.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return <PlaylistView playlist={favorites} />
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { CardGridSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||||
|
|
||||||
|
export default function Loading() {
|
||||||
|
return (
|
||||||
|
<div className="flex h-svh flex-col">
|
||||||
|
<PageHeader title="Playlists" />
|
||||||
|
<CardGridSkeleton />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,16 +1,17 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useQuery } from "convex/react"
|
|
||||||
import { Plus } from "lucide-react"
|
import { Plus } from "lucide-react"
|
||||||
|
|
||||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||||
import { LibraryLoading } from "@/components/library-loading"
|
import { CardGridSkeleton } from "@/components/library-skeletons"
|
||||||
import { PlaylistCard } from "@/components/playlist-card"
|
import { PlaylistCard } from "@/components/playlist-card"
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||||
|
import { albumGridClassName } from "@/lib/album-grid-classes"
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
|
|
||||||
export default function Page() {
|
export default function Page() {
|
||||||
const playlists = useQuery(api.playlists.listAllPlaylists)
|
const playlists = useCachedQuery(api.playlists.listAllPlaylists)
|
||||||
const { openCreatePlaylist } = useAddToPlaylist()
|
const { openCreatePlaylist } = useAddToPlaylist()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -29,10 +30,10 @@ export default function Page() {
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
{playlists === undefined ? (
|
{playlists === undefined ? (
|
||||||
<LibraryLoading />
|
<CardGridSkeleton />
|
||||||
) : (
|
) : (
|
||||||
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
||||||
<div className="grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
<div className={albumGridClassName}>
|
||||||
{playlists.map((playlist) => (
|
{playlists.map((playlist) => (
|
||||||
<PlaylistCard key={playlist.id} playlist={playlist} />
|
<PlaylistCard key={playlist.id} playlist={playlist} />
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { CardGridSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||||
|
|
||||||
|
export default function Loading() {
|
||||||
|
return (
|
||||||
|
<div className="flex h-svh flex-col">
|
||||||
|
<PageHeader title="Recently Added" />
|
||||||
|
<CardGridSkeleton />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,25 +1,23 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useQuery } from "convex/react"
|
|
||||||
|
|
||||||
import { AlbumCard } from "@/components/album-card"
|
import { AlbumCard } from "@/components/album-card"
|
||||||
import { LibraryLoading } from "@/components/library-loading"
|
import { CardGridSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||||
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||||
|
import { albumGridClassName } from "@/lib/album-grid-classes"
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
|
|
||||||
export default function Page() {
|
export default function Page() {
|
||||||
const albums = useQuery(api.library.browseRecentlyAdded, {})
|
const albums = useCachedQuery(api.library.browseRecentlyAdded, {})
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-svh flex-col">
|
<div className="flex h-svh flex-col">
|
||||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
<PageHeader title="Recently Added" />
|
||||||
<h1 className="text-lg font-semibold">Recently Added</h1>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
{albums === undefined ? (
|
{albums === undefined ? (
|
||||||
<LibraryLoading />
|
<CardGridSkeleton />
|
||||||
) : (
|
) : (
|
||||||
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
||||||
<div className="grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
<div className={albumGridClassName}>
|
||||||
{albums.map((album) => (
|
{albums.map((album) => (
|
||||||
<AlbumCard key={album.id} album={album} />
|
<AlbumCard key={album.id} album={album} />
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { CardGridSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||||
|
|
||||||
|
export default function Loading() {
|
||||||
|
return (
|
||||||
|
<div className="flex h-svh flex-col">
|
||||||
|
<PageHeader title="Recently Played" />
|
||||||
|
<CardGridSkeleton />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useQuery } from "convex/react"
|
|
||||||
|
|
||||||
import { AlbumCard } from "@/components/album-card"
|
import { AlbumCard } from "@/components/album-card"
|
||||||
import { LibraryLoading } from "@/components/library-loading"
|
import { CardGridSkeleton, PageHeader } from "@/components/library-skeletons"
|
||||||
import { PlaylistCard } from "@/components/playlist-card"
|
import { PlaylistCard } from "@/components/playlist-card"
|
||||||
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||||
|
import { albumGridClassName } from "@/lib/album-grid-classes"
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
import type { BrowseAlbum, PlaylistSummary } from "@otunes/convex/types"
|
import type { BrowseAlbum, PlaylistSummary } from "@otunes/convex/types"
|
||||||
|
|
||||||
@@ -20,16 +20,14 @@ function RecentlyPlayedCard({
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function Page() {
|
export default function Page() {
|
||||||
const recentlyPlayed = useQuery(api.library.browseRecentlyPlayed, {})
|
const recentlyPlayed = useCachedQuery(api.library.browseRecentlyPlayed, {})
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-svh flex-col">
|
<div className="flex h-svh flex-col">
|
||||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
<PageHeader title="Recently Played" />
|
||||||
<h1 className="text-lg font-semibold">Recently Played</h1>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
{recentlyPlayed === undefined ? (
|
{recentlyPlayed === undefined ? (
|
||||||
<LibraryLoading />
|
<CardGridSkeleton />
|
||||||
) : recentlyPlayed.length === 0 ? (
|
) : recentlyPlayed.length === 0 ? (
|
||||||
<div className="flex flex-1 items-center justify-center p-6 pb-28">
|
<div className="flex flex-1 items-center justify-center p-6 pb-28">
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
@@ -38,7 +36,7 @@ export default function Page() {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
||||||
<div className="grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
<div className={albumGridClassName}>
|
||||||
{recentlyPlayed.map((item) => (
|
{recentlyPlayed.map((item) => (
|
||||||
<RecentlyPlayedCard key={item.id} item={item} />
|
<RecentlyPlayedCard key={item.id} item={item} />
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useSearchParams } from "next/navigation"
|
||||||
|
|
||||||
|
import { SearchResultsSkeleton } from "@/components/library-skeletons"
|
||||||
|
import { SearchPrompt } from "@/components/search-prompt"
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton"
|
||||||
|
|
||||||
|
export default function Loading() {
|
||||||
|
const hasQuery = Boolean(useSearchParams().get("q")?.trim())
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex h-svh flex-col">
|
||||||
|
<header className="flex items-center justify-center border-b px-4 py-3">
|
||||||
|
<Skeleton className="h-10 w-full max-w-xl rounded-full" />
|
||||||
|
</header>
|
||||||
|
{hasQuery ? <SearchResultsSkeleton /> : <SearchPrompt />}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,14 +1,15 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { Suspense, useCallback, useEffect, useRef, useState } from "react"
|
import { Suspense, useCallback, useEffect, useRef, useState } from "react"
|
||||||
import { useQuery } from "convex/react"
|
|
||||||
import { SearchIcon } from "lucide-react"
|
import { SearchIcon } from "lucide-react"
|
||||||
import { usePathname, useSearchParams } from "next/navigation"
|
import { usePathname, useSearchParams } from "next/navigation"
|
||||||
|
|
||||||
import { ContentCarousel } from "@/components/content-carousel"
|
import { ContentCarousel } from "@/components/content-carousel"
|
||||||
import { LibraryLoading } from "@/components/library-loading"
|
import { SearchResultsSkeleton } from "@/components/library-skeletons"
|
||||||
|
import { SearchPrompt } from "@/components/search-prompt"
|
||||||
import { SearchSongItem } from "@/components/search-song-item"
|
import { SearchSongItem } from "@/components/search-song-item"
|
||||||
import { SearchTopResultCard, type TopResult } from "@/components/search-top-result-card"
|
import { SearchTopResultCard, type TopResult } from "@/components/search-top-result-card"
|
||||||
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
|
|
||||||
const SEARCH_DEBOUNCE_MS = 300
|
const SEARCH_DEBOUNCE_MS = 300
|
||||||
@@ -30,11 +31,11 @@ function readUrlQuery() {
|
|||||||
function SearchResults({ query }: { query: string }) {
|
function SearchResults({ query }: { query: string }) {
|
||||||
const hasQuery = query.length > 0
|
const hasQuery = query.length > 0
|
||||||
|
|
||||||
const results = useQuery(
|
const results = useCachedQuery(
|
||||||
api.library.searchLibrary,
|
api.library.searchLibrary,
|
||||||
hasQuery ? { query } : "skip"
|
hasQuery ? { query } : "skip"
|
||||||
)
|
)
|
||||||
const playlistResults = useQuery(
|
const playlistResults = useCachedQuery(
|
||||||
api.playlists.searchPlaylists,
|
api.playlists.searchPlaylists,
|
||||||
hasQuery ? { query } : "skip"
|
hasQuery ? { query } : "skip"
|
||||||
)
|
)
|
||||||
@@ -51,17 +52,11 @@ function SearchResults({ query }: { query: string }) {
|
|||||||
const showResults = hasQuery && results !== undefined
|
const showResults = hasQuery && results !== undefined
|
||||||
|
|
||||||
if (isSearching) {
|
if (isSearching) {
|
||||||
return <LibraryLoading />
|
return <SearchResultsSkeleton />
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!hasQuery) {
|
if (!hasQuery) {
|
||||||
return (
|
return <SearchPrompt />
|
||||||
<div className="flex flex-1 items-center justify-center px-6 pb-28">
|
|
||||||
<p className="text-center text-muted-foreground">
|
|
||||||
Search for songs, albums, artists, and playlists in your library.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!showResults) {
|
if (!showResults) {
|
||||||
@@ -239,7 +234,7 @@ function SearchPageContent() {
|
|||||||
|
|
||||||
export default function Page() {
|
export default function Page() {
|
||||||
return (
|
return (
|
||||||
<Suspense fallback={<LibraryLoading />}>
|
<Suspense fallback={<SearchResultsSkeleton />}>
|
||||||
<SearchPageContent />
|
<SearchPageContent />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,11 +1,16 @@
|
|||||||
import { fetchQuery } from "convex/nextjs"
|
import { fetchQuery } from "convex/nextjs"
|
||||||
import { connection } from "next/server"
|
import { connection } from "next/server"
|
||||||
import { AuthForm } from "@/components/auth-form"
|
import { AuthForm } from "@/components/auth-form"
|
||||||
|
import { convexServerOptions } from "@/lib/convex-server"
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
|
|
||||||
export default async function SignInPage() {
|
export default async function SignInPage() {
|
||||||
await connection()
|
await connection()
|
||||||
const { disableAccountCreation } = await fetchQuery(api.users.getAppSettings)
|
const { disableAccountCreation } = await fetchQuery(
|
||||||
|
api.users.getAppSettings,
|
||||||
|
{},
|
||||||
|
convexServerOptions()
|
||||||
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthForm flow="signIn" accountCreationDisabled={disableAccountCreation} />
|
<AuthForm flow="signIn" accountCreationDisabled={disableAccountCreation} />
|
||||||
|
|||||||
@@ -1,11 +1,16 @@
|
|||||||
import { fetchQuery } from "convex/nextjs"
|
import { fetchQuery } from "convex/nextjs"
|
||||||
import { connection } from "next/server"
|
import { connection } from "next/server"
|
||||||
import { AuthForm } from "@/components/auth-form"
|
import { AuthForm } from "@/components/auth-form"
|
||||||
|
import { convexServerOptions } from "@/lib/convex-server"
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
|
|
||||||
export default async function SignUpPage() {
|
export default async function SignUpPage() {
|
||||||
await connection()
|
await connection()
|
||||||
const { disableAccountCreation } = await fetchQuery(api.users.getAppSettings)
|
const { disableAccountCreation } = await fetchQuery(
|
||||||
|
api.users.getAppSettings,
|
||||||
|
{},
|
||||||
|
convexServerOptions()
|
||||||
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthForm flow="signUp" accountCreationDisabled={disableAccountCreation} />
|
<AuthForm flow="signUp" accountCreationDisabled={disableAccountCreation} />
|
||||||
|
|||||||
+48
-22
@@ -7,6 +7,7 @@ import { ThemeProvider } from "@/components/theme-provider"
|
|||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils"
|
||||||
import { Toaster } from "@/components/ui/sonner"
|
import { Toaster } from "@/components/ui/sonner"
|
||||||
import type { Metadata } from "next"
|
import type { Metadata } from "next"
|
||||||
|
import { headers } from "next/headers"
|
||||||
|
|
||||||
const inter = Inter({ subsets: ["latin"], variable: "--font-sans" })
|
const inter = Inter({ subsets: ["latin"], variable: "--font-sans" })
|
||||||
|
|
||||||
@@ -15,28 +16,53 @@ const fontMono = Geist_Mono({
|
|||||||
variable: "--font-mono",
|
variable: "--font-mono",
|
||||||
})
|
})
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
async function hostedUrl() {
|
||||||
title: "oTunes",
|
if (process.env.HOSTED_URL) {
|
||||||
description: "Our Music",
|
return new URL(process.env.HOSTED_URL)
|
||||||
appleWebApp: {
|
}
|
||||||
capable: true,
|
|
||||||
title: "oTunes",
|
const requestHeaders = await headers()
|
||||||
startupImage: "/logo-dark.png",
|
const host = (
|
||||||
statusBarStyle: "default",
|
requestHeaders.get("x-forwarded-host") ?? requestHeaders.get("host")
|
||||||
},
|
)
|
||||||
openGraph: {
|
?.split(",")[0]
|
||||||
type: "website",
|
.trim()
|
||||||
url: process.env.HOSTED_URL || "http://localhost:3000",
|
const protocol =
|
||||||
|
requestHeaders.get("x-forwarded-proto")?.split(",")[0].trim() ?? "http"
|
||||||
|
|
||||||
|
try {
|
||||||
|
return new URL(`${protocol}://${host}`)
|
||||||
|
} catch {
|
||||||
|
return new URL("http://localhost:3000")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function generateMetadata(): Promise<Metadata> {
|
||||||
|
const url = await hostedUrl()
|
||||||
|
|
||||||
|
return {
|
||||||
title: "oTunes",
|
title: "oTunes",
|
||||||
description: "Our Music",
|
description: "Our Music",
|
||||||
siteName: "oTunes",
|
appleWebApp: {
|
||||||
images: [
|
capable: true,
|
||||||
{
|
title: "oTunes",
|
||||||
url: "/logo-dark.png",
|
startupImage: "/logo-dark.png",
|
||||||
},
|
statusBarStyle: "default",
|
||||||
],
|
},
|
||||||
},
|
openGraph: {
|
||||||
metadataBase: new URL(process.env.HOSTED_URL || "http://localhost:3000"),
|
type: "website",
|
||||||
|
url,
|
||||||
|
title: "oTunes",
|
||||||
|
description: "Our Music",
|
||||||
|
siteName: "oTunes",
|
||||||
|
images: [
|
||||||
|
{
|
||||||
|
url: "/logo-dark.png",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
metadataBase: url,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function RootLayout({
|
export default function RootLayout({
|
||||||
@@ -56,8 +82,8 @@ export default function RootLayout({
|
|||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<body className={"overflow-x-hidden"}>
|
<body className={"overflow-x-hidden"}>
|
||||||
<ConvexAuthNextjsServerProvider>
|
<ConvexAuthNextjsServerProvider storageNamespace="otunes">
|
||||||
<ConvexClientProvider>
|
<ConvexClientProvider convexUrl={process.env.PUBLIC_CONVEX_URL}>
|
||||||
<ThemeProvider>
|
<ThemeProvider>
|
||||||
{children}
|
{children}
|
||||||
<Toaster />
|
<Toaster />
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { useRouter } from "next/navigation"
|
|||||||
import { ListMusic, Plus } from "lucide-react"
|
import { ListMusic, Plus } from "lucide-react"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
|
|
||||||
|
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
@@ -19,6 +20,7 @@ import { Input } from "@/components/ui/input"
|
|||||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
|
import { fetchCachedQuery } from "@/lib/cached-query"
|
||||||
|
|
||||||
function countSongsToAdd(
|
function countSongsToAdd(
|
||||||
playlistSongIds: Id<"songs">[],
|
playlistSongIds: Id<"songs">[],
|
||||||
@@ -80,6 +82,7 @@ export function AddToPlaylistProvider({
|
|||||||
children: React.ReactNode
|
children: React.ReactNode
|
||||||
}) {
|
}) {
|
||||||
const convex = useConvex()
|
const convex = useConvex()
|
||||||
|
const cacheScope = useCacheScope()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const addSongs = useMutation(api.playlists.addSongsToPlaylist)
|
const addSongs = useMutation(api.playlists.addSongsToPlaylist)
|
||||||
const createPlaylist = useMutation(api.playlists.createPlaylist)
|
const createPlaylist = useMutation(api.playlists.createPlaylist)
|
||||||
@@ -117,9 +120,14 @@ export function AddToPlaylistProvider({
|
|||||||
async (albumId: Id<"albums">) => {
|
async (albumId: Id<"albums">) => {
|
||||||
const requestId = ++selectionRequestRef.current
|
const requestId = ++selectionRequestRef.current
|
||||||
try {
|
try {
|
||||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
const songIds = await fetchCachedQuery(
|
||||||
albumId,
|
convex,
|
||||||
})
|
cacheScope,
|
||||||
|
api.playlists.getAlbumSongIds,
|
||||||
|
{
|
||||||
|
albumId,
|
||||||
|
}
|
||||||
|
)
|
||||||
if (requestId === selectionRequestRef.current) {
|
if (requestId === selectionRequestRef.current) {
|
||||||
showAddToPlaylist(songIds)
|
showAddToPlaylist(songIds)
|
||||||
}
|
}
|
||||||
@@ -131,16 +139,21 @@ export function AddToPlaylistProvider({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[convex, showAddToPlaylist]
|
[convex, cacheScope, showAddToPlaylist]
|
||||||
)
|
)
|
||||||
|
|
||||||
const openAddPlaylistToPlaylist = React.useCallback(
|
const openAddPlaylistToPlaylist = React.useCallback(
|
||||||
async (playlistId: Id<"playlists">) => {
|
async (playlistId: Id<"playlists">) => {
|
||||||
const requestId = ++selectionRequestRef.current
|
const requestId = ++selectionRequestRef.current
|
||||||
try {
|
try {
|
||||||
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
const songIds = await fetchCachedQuery(
|
||||||
playlistId,
|
convex,
|
||||||
})
|
cacheScope,
|
||||||
|
api.playlists.getPlaylistSongIds,
|
||||||
|
{
|
||||||
|
playlistId,
|
||||||
|
}
|
||||||
|
)
|
||||||
if (requestId === selectionRequestRef.current) {
|
if (requestId === selectionRequestRef.current) {
|
||||||
showAddToPlaylist(songIds)
|
showAddToPlaylist(songIds)
|
||||||
}
|
}
|
||||||
@@ -152,16 +165,21 @@ export function AddToPlaylistProvider({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[convex, showAddToPlaylist]
|
[convex, cacheScope, showAddToPlaylist]
|
||||||
)
|
)
|
||||||
|
|
||||||
const openAddArtistToPlaylist = React.useCallback(
|
const openAddArtistToPlaylist = React.useCallback(
|
||||||
async (artistId: Id<"artists">) => {
|
async (artistId: Id<"artists">) => {
|
||||||
const requestId = ++selectionRequestRef.current
|
const requestId = ++selectionRequestRef.current
|
||||||
try {
|
try {
|
||||||
const songIds = await convex.query(api.playlists.getArtistSongIds, {
|
const songIds = await fetchCachedQuery(
|
||||||
artistId,
|
convex,
|
||||||
})
|
cacheScope,
|
||||||
|
api.playlists.getArtistSongIds,
|
||||||
|
{
|
||||||
|
artistId,
|
||||||
|
}
|
||||||
|
)
|
||||||
if (requestId === selectionRequestRef.current) {
|
if (requestId === selectionRequestRef.current) {
|
||||||
showAddToPlaylist(songIds)
|
showAddToPlaylist(songIds)
|
||||||
}
|
}
|
||||||
@@ -173,7 +191,7 @@ export function AddToPlaylistProvider({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[convex, showAddToPlaylist]
|
[convex, cacheScope, showAddToPlaylist]
|
||||||
)
|
)
|
||||||
|
|
||||||
const openCreatePlaylist = React.useCallback(() => {
|
const openCreatePlaylist = React.useCallback(() => {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import Link from "next/link"
|
|||||||
import { MoreHorizontal, Play } from "lucide-react"
|
import { MoreHorizontal, Play } from "lucide-react"
|
||||||
import { useConvex } from "convex/react"
|
import { useConvex } from "convex/react"
|
||||||
|
|
||||||
|
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||||
import { useFavorites } from "@/components/favorites-provider"
|
import { useFavorites } from "@/components/favorites-provider"
|
||||||
import {
|
import {
|
||||||
@@ -25,6 +26,7 @@ import type { BrowseAlbum } from "@otunes/convex/types"
|
|||||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
import { albumCoverUrl } from "@/lib/cover-urls"
|
import { albumCoverUrl } from "@/lib/cover-urls"
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils"
|
||||||
|
import { fetchCachedQuery } from "@/lib/cached-query"
|
||||||
|
|
||||||
let activeAlbumCardMenuClose: (() => void) | null = null
|
let activeAlbumCardMenuClose: (() => void) | null = null
|
||||||
|
|
||||||
@@ -43,6 +45,7 @@ function closeExclusiveAlbumCardMenu(closeMenu: () => void) {
|
|||||||
|
|
||||||
export function AlbumCard({ album }: { album: BrowseAlbum }) {
|
export function AlbumCard({ album }: { album: BrowseAlbum }) {
|
||||||
const convex = useConvex()
|
const convex = useConvex()
|
||||||
|
const cacheScope = useCacheScope()
|
||||||
const { openAddAlbumToPlaylist } = useAddToPlaylist()
|
const { openAddAlbumToPlaylist } = useAddToPlaylist()
|
||||||
const { isAlbumFavorite, toggleAlbumFavorite } = useFavorites()
|
const { isAlbumFavorite, toggleAlbumFavorite } = useFavorites()
|
||||||
const { playAlbum } = usePlayback()
|
const { playAlbum } = usePlayback()
|
||||||
@@ -77,9 +80,14 @@ export function AlbumCard({ album }: { album: BrowseAlbum }) {
|
|||||||
case "play-next":
|
case "play-next":
|
||||||
case "play-last":
|
case "play-last":
|
||||||
case "shuffle": {
|
case "shuffle": {
|
||||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
const songIds = await fetchCachedQuery(
|
||||||
albumId: album.id as Id<"albums">,
|
convex,
|
||||||
})
|
cacheScope,
|
||||||
|
api.playlists.getAlbumSongIds,
|
||||||
|
{
|
||||||
|
albumId: album.id as Id<"albums">,
|
||||||
|
}
|
||||||
|
)
|
||||||
void runQueueAction(action, songIds)
|
void runQueueAction(action, songIds)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { AlbumView } from "@/components/album-view"
|
||||||
|
import { CollectionDetailSkeleton } from "@/components/library-skeletons"
|
||||||
|
import { PageMessage } from "@/components/page-message"
|
||||||
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||||
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
|
|
||||||
|
export function AlbumPage({
|
||||||
|
albumId,
|
||||||
|
highlightedSongId,
|
||||||
|
}: {
|
||||||
|
albumId: Id<"albums">
|
||||||
|
highlightedSongId?: string
|
||||||
|
}) {
|
||||||
|
const album = useCachedQuery(api.library.browseAlbumDetail, { id: albumId })
|
||||||
|
|
||||||
|
if (album === undefined) {
|
||||||
|
return <CollectionDetailSkeleton />
|
||||||
|
}
|
||||||
|
|
||||||
|
if (album === null) {
|
||||||
|
return <PageMessage>Album not found.</PageMessage>
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AlbumView
|
||||||
|
key={album.id}
|
||||||
|
album={album}
|
||||||
|
highlightedSongId={highlightedSongId}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -39,6 +39,7 @@ import {
|
|||||||
} from "@/lib/selection-range-styles"
|
} from "@/lib/selection-range-styles"
|
||||||
import { albumCoverUrl } from "@/lib/cover-urls"
|
import { albumCoverUrl } from "@/lib/cover-urls"
|
||||||
import { sumDurationSeconds } from "@/lib/media-summary"
|
import { sumDurationSeconds } from "@/lib/media-summary"
|
||||||
|
import { albumDetailSongs, rememberSongs } from "@/lib/song-cache"
|
||||||
|
|
||||||
function formatDuration(seconds: number): string {
|
function formatDuration(seconds: number): string {
|
||||||
const minutes = Math.floor(seconds / 60)
|
const minutes = Math.floor(seconds / 60)
|
||||||
@@ -269,6 +270,11 @@ export function AlbumView({
|
|||||||
() => album.tracks.map((track) => track.id as Id<"songs">),
|
() => album.tracks.map((track) => track.id as Id<"songs">),
|
||||||
[album.tracks]
|
[album.tracks]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
rememberSongs(albumDetailSongs(album))
|
||||||
|
}, [album])
|
||||||
|
|
||||||
const metadata = formatMetadata(album.genre, album.year)
|
const metadata = formatMetadata(album.genre, album.year)
|
||||||
const [activeTrackId, setActiveTrackId] = React.useState("")
|
const [activeTrackId, setActiveTrackId] = React.useState("")
|
||||||
const validHighlightedSongId = React.useMemo(() => {
|
const validHighlightedSongId = React.useMemo(() => {
|
||||||
@@ -398,14 +404,21 @@ export function AlbumView({
|
|||||||
size="icon"
|
size="icon"
|
||||||
className="rounded-full"
|
className="rounded-full"
|
||||||
aria-label="Shuffle album"
|
aria-label="Shuffle album"
|
||||||
onClick={() => void playAlbumShuffled(album.id as Id<"albums">)}
|
onClick={() =>
|
||||||
|
void playAlbumShuffled(
|
||||||
|
album.id as Id<"albums">,
|
||||||
|
albumSongIds
|
||||||
|
)
|
||||||
|
}
|
||||||
>
|
>
|
||||||
<Shuffle />
|
<Shuffle />
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
className="h-10 gap-2 rounded-full bg-foreground px-6 text-background hover:bg-foreground/90"
|
className="h-10 gap-2 rounded-full bg-foreground px-6 text-background hover:bg-foreground/90"
|
||||||
aria-label={`Play ${album.title}`}
|
aria-label={`Play ${album.title}`}
|
||||||
onClick={() => void playAlbum(album.id as Id<"albums">)}
|
onClick={() =>
|
||||||
|
void playAlbum(album.id as Id<"albums">, albumSongIds)
|
||||||
|
}
|
||||||
>
|
>
|
||||||
<Play className="fill-current" />
|
<Play className="fill-current" />
|
||||||
Play
|
Play
|
||||||
|
|||||||
@@ -41,9 +41,11 @@ import Image from "next/image"
|
|||||||
import Link from "next/link"
|
import Link from "next/link"
|
||||||
import { useTheme } from "next-themes"
|
import { useTheme } from "next-themes"
|
||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
import { useQuery } from "convex/react"
|
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||||
import { useMounted } from "@/hooks/use-mounted"
|
import { useMounted } from "@/hooks/use-mounted"
|
||||||
|
import { clearPersistentCache } from "@/lib/persistent-cache"
|
||||||
|
import { resetPlaybackStores } from "@/lib/playback-store"
|
||||||
|
|
||||||
const OptionsModal = dynamic(() =>
|
const OptionsModal = dynamic(() =>
|
||||||
import("@/components/options-modal").then((module) => module.OptionsModal)
|
import("@/components/options-modal").then((module) => module.OptionsModal)
|
||||||
@@ -64,8 +66,8 @@ export function AppSidebar() {
|
|||||||
const pathname = usePathname()
|
const pathname = usePathname()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const { signOut } = useAuthActions()
|
const { signOut } = useAuthActions()
|
||||||
const user = useQuery(api.auth.currentUser)
|
const user = useCachedQuery(api.auth.currentUser)
|
||||||
const sidebarPlaylists = useQuery(api.playlists.listSidebarPlaylists)
|
const sidebarPlaylists = useCachedQuery(api.playlists.listSidebarPlaylists)
|
||||||
const fallbackLetters = user?.name?.match(/\b(\w)/g)?.join("") || "NA"
|
const fallbackLetters = user?.name?.match(/\b(\w)/g)?.join("") || "NA"
|
||||||
|
|
||||||
const { resolvedTheme } = useTheme()
|
const { resolvedTheme } = useTheme()
|
||||||
@@ -74,6 +76,8 @@ export function AppSidebar() {
|
|||||||
|
|
||||||
async function handleSignOut() {
|
async function handleSignOut() {
|
||||||
await signOut()
|
await signOut()
|
||||||
|
resetPlaybackStores()
|
||||||
|
await clearPersistentCache()
|
||||||
router.push("/signin")
|
router.push("/signin")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { ArtistView } from "@/components/artist-view"
|
||||||
|
import { ArtistDetailSkeleton } from "@/components/library-skeletons"
|
||||||
|
import { PageMessage } from "@/components/page-message"
|
||||||
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||||
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
|
|
||||||
|
export function ArtistPage({ artistId }: { artistId: Id<"artists"> }) {
|
||||||
|
const data = useCachedQuery(api.library.browseArtistDetail, { id: artistId })
|
||||||
|
|
||||||
|
if (data === undefined) {
|
||||||
|
return <ArtistDetailSkeleton />
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data === null) {
|
||||||
|
return <PageMessage>Artist not found.</PageMessage>
|
||||||
|
}
|
||||||
|
|
||||||
|
return <ArtistView artist={data.artist} albums={data.albums} />
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import Image from "next/image"
|
|||||||
import { Play, Shuffle } from "lucide-react"
|
import { Play, Shuffle } from "lucide-react"
|
||||||
import { useConvex } from "convex/react"
|
import { useConvex } from "convex/react"
|
||||||
|
|
||||||
|
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||||
import { useFavorites } from "@/components/favorites-provider"
|
import { useFavorites } from "@/components/favorites-provider"
|
||||||
import { usePlayback } from "@/components/playback-provider"
|
import { usePlayback } from "@/components/playback-provider"
|
||||||
@@ -22,6 +23,7 @@ import type { Id } from "@otunes/convex/_generated/dataModel"
|
|||||||
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
|
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
|
||||||
import { albumGridClassName } from "@/lib/album-grid-classes"
|
import { albumGridClassName } from "@/lib/album-grid-classes"
|
||||||
import { artistCoverUrl } from "@/lib/cover-urls"
|
import { artistCoverUrl } from "@/lib/cover-urls"
|
||||||
|
import { fetchCachedQuery } from "@/lib/cached-query"
|
||||||
|
|
||||||
export function ArtistView({
|
export function ArtistView({
|
||||||
artist,
|
artist,
|
||||||
@@ -35,6 +37,7 @@ export function ArtistView({
|
|||||||
const { playArtist, playArtistShuffled } = usePlayback()
|
const { playArtist, playArtistShuffled } = usePlayback()
|
||||||
const { runQueueAction } = useQueueMediaActions()
|
const { runQueueAction } = useQueueMediaActions()
|
||||||
const convex = useConvex()
|
const convex = useConvex()
|
||||||
|
const cacheScope = useCacheScope()
|
||||||
|
|
||||||
async function handleMediaAction(action: MediaContextAction) {
|
async function handleMediaAction(action: MediaContextAction) {
|
||||||
switch (action) {
|
switch (action) {
|
||||||
@@ -47,7 +50,9 @@ export function ArtistView({
|
|||||||
case "play-next":
|
case "play-next":
|
||||||
case "play-last":
|
case "play-last":
|
||||||
case "shuffle": {
|
case "shuffle": {
|
||||||
const songIds = await convex.query(
|
const songIds = await fetchCachedQuery(
|
||||||
|
convex,
|
||||||
|
cacheScope,
|
||||||
api.playlists.getOrderedArtistSongIds,
|
api.playlists.getOrderedArtistSongIds,
|
||||||
{ artistId: artist.id as Id<"artists"> }
|
{ artistId: artist.id as Id<"artists"> }
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { usePathname } from "next/navigation"
|
||||||
|
import { useCallback } from "react"
|
||||||
|
|
||||||
|
import { ArtistsView } from "@/components/artists-view"
|
||||||
|
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 pathname = usePathname()
|
||||||
|
const artists = useCachedQuery(api.library.browseArtists)
|
||||||
|
const albums = useCachedQuery(api.library.browseAlbums)
|
||||||
|
|
||||||
|
const selectArtist = useCallback((artistId: string) => {
|
||||||
|
window.history.pushState(null, "", `${ARTISTS_PATH}/${artistId}`)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex h-svh flex-col">
|
||||||
|
<PageHeader title="Artists" />
|
||||||
|
|
||||||
|
{artists === undefined || albums === undefined ? (
|
||||||
|
<ArtistsSkeleton />
|
||||||
|
) : (
|
||||||
|
<ArtistsView
|
||||||
|
artists={artists}
|
||||||
|
albums={albums}
|
||||||
|
artistId={artistIdFromPathname(pathname)}
|
||||||
|
onSelectArtist={selectArtist}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -3,10 +3,10 @@
|
|||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
import Image from "next/image"
|
import Image from "next/image"
|
||||||
import Link from "next/link"
|
import Link from "next/link"
|
||||||
import { useRouter } from "next/navigation"
|
|
||||||
import { ChevronRightIcon, Play, Shuffle } from "lucide-react"
|
import { ChevronRightIcon, Play, Shuffle } from "lucide-react"
|
||||||
import { useConvex } from "convex/react"
|
import { useConvex } from "convex/react"
|
||||||
|
|
||||||
|
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||||
import { AlbumCard } from "@/components/album-card"
|
import { AlbumCard } from "@/components/album-card"
|
||||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||||
import { FavoriteMediaButton } from "@/components/favorite-media-button"
|
import { FavoriteMediaButton } from "@/components/favorite-media-button"
|
||||||
@@ -24,6 +24,7 @@ import { cn } from "@/lib/utils"
|
|||||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
|
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
|
||||||
import { artistCoverUrl } from "@/lib/cover-urls"
|
import { artistCoverUrl } from "@/lib/cover-urls"
|
||||||
|
import { fetchCachedQuery } from "@/lib/cached-query"
|
||||||
|
|
||||||
function ArtistAvatar({ artist }: { artist: BrowseArtist }) {
|
function ArtistAvatar({ artist }: { artist: BrowseArtist }) {
|
||||||
return (
|
return (
|
||||||
@@ -91,12 +92,13 @@ export function ArtistsView({
|
|||||||
artists,
|
artists,
|
||||||
albums,
|
albums,
|
||||||
artistId,
|
artistId,
|
||||||
|
onSelectArtist,
|
||||||
}: {
|
}: {
|
||||||
artists: BrowseArtist[]
|
artists: BrowseArtist[]
|
||||||
albums: BrowseAlbum[]
|
albums: BrowseAlbum[]
|
||||||
artistId?: string
|
artistId?: string
|
||||||
|
onSelectArtist: (artistId: string) => void
|
||||||
}) {
|
}) {
|
||||||
const router = useRouter()
|
|
||||||
const sortedArtists = React.useMemo(
|
const sortedArtists = React.useMemo(
|
||||||
() => [...artists].sort((a, b) => a.name.localeCompare(b.name)),
|
() => [...artists].sort((a, b) => a.name.localeCompare(b.name)),
|
||||||
[artists]
|
[artists]
|
||||||
@@ -109,6 +111,7 @@ export function ArtistsView({
|
|||||||
return sortedArtists[0]?.id ?? ""
|
return sortedArtists[0]?.id ?? ""
|
||||||
}, [artistId, sortedArtists])
|
}, [artistId, sortedArtists])
|
||||||
const convex = useConvex()
|
const convex = useConvex()
|
||||||
|
const cacheScope = useCacheScope()
|
||||||
const { openAddArtistToPlaylist } = useAddToPlaylist()
|
const { openAddArtistToPlaylist } = useAddToPlaylist()
|
||||||
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
|
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
|
||||||
const { playArtist, playArtistShuffled } = usePlayback()
|
const { playArtist, playArtistShuffled } = usePlayback()
|
||||||
@@ -141,7 +144,9 @@ export function ArtistsView({
|
|||||||
case "play-next":
|
case "play-next":
|
||||||
case "play-last":
|
case "play-last":
|
||||||
case "shuffle": {
|
case "shuffle": {
|
||||||
const songIds = await convex.query(
|
const songIds = await fetchCachedQuery(
|
||||||
|
convex,
|
||||||
|
cacheScope,
|
||||||
api.playlists.getOrderedArtistSongIds,
|
api.playlists.getOrderedArtistSongIds,
|
||||||
{ artistId: artistId as Id<"artists"> }
|
{ artistId: artistId as Id<"artists"> }
|
||||||
)
|
)
|
||||||
@@ -162,7 +167,7 @@ export function ArtistsView({
|
|||||||
albumCount={albumCountByArtistId.get(artist.id) ?? 0}
|
albumCount={albumCountByArtistId.get(artist.id) ?? 0}
|
||||||
isSelected={artist.id === selectedId}
|
isSelected={artist.id === selectedId}
|
||||||
isFavorite={isArtistFavorite(artist.id)}
|
isFavorite={isArtistFavorite(artist.id)}
|
||||||
onSelect={() => router.push(`/library/artists/${artist.id}`)}
|
onSelect={() => onSelectArtist(artist.id)}
|
||||||
onMediaAction={(action) =>
|
onMediaAction={(action) =>
|
||||||
void handleMediaAction(artist.id, action)
|
void handleMediaAction(artist.id, action)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,44 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { ConvexAuthNextjsProvider } from "@convex-dev/auth/nextjs"
|
import { ConvexAuthNextjsProvider } from "@convex-dev/auth/nextjs"
|
||||||
|
import { buildConvexUrl } from "@otunes/convex/server-url"
|
||||||
import { ConvexReactClient } from "convex/react"
|
import { ConvexReactClient } from "convex/react"
|
||||||
import { ReactNode } from "react"
|
import { ReactNode } from "react"
|
||||||
|
|
||||||
const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!)
|
import { PersistentCacheProvider } from "@/components/persistent-cache-provider"
|
||||||
|
|
||||||
export function ConvexClientProvider({ children }: { children: ReactNode }) {
|
// Server rendering never runs Convex queries, so this URL is never contacted.
|
||||||
|
const SSR_CONVEX_URL = "http://127.0.0.1:3210"
|
||||||
|
|
||||||
|
let client: ConvexReactClient | undefined
|
||||||
|
|
||||||
|
function browserConvexUrl() {
|
||||||
|
const { host, protocol } = window.location
|
||||||
|
return buildConvexUrl(host, protocol === "https:" ? "https" : "http")
|
||||||
|
}
|
||||||
|
|
||||||
|
function getConvexClient(convexUrl: string | undefined) {
|
||||||
|
if (!client) {
|
||||||
|
client = new ConvexReactClient(
|
||||||
|
typeof window === "undefined"
|
||||||
|
? SSR_CONVEX_URL
|
||||||
|
: (convexUrl ??
|
||||||
|
process.env.NEXT_PUBLIC_CONVEX_URL ??
|
||||||
|
browserConvexUrl())
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return client
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ConvexClientProvider({
|
||||||
|
convexUrl,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
convexUrl?: string
|
||||||
|
children: ReactNode
|
||||||
|
}) {
|
||||||
return (
|
return (
|
||||||
<ConvexAuthNextjsProvider client={convex}>
|
<ConvexAuthNextjsProvider client={getConvexClient(convexUrl)}>
|
||||||
{children}
|
<PersistentCacheProvider>{children}</PersistentCacheProvider> </ConvexAuthNextjsProvider>
|
||||||
</ConvexAuthNextjsProvider>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
import { useMutation, useQuery } from "convex/react"
|
import { useMutation } from "convex/react"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
|
|
||||||
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
|
|
||||||
@@ -32,7 +33,7 @@ export function useFavorites() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function FavoritesProvider({ children }: { children: React.ReactNode }) {
|
export function FavoritesProvider({ children }: { children: React.ReactNode }) {
|
||||||
const favorites = useQuery(api.favorites.getUserFavorites)
|
const favorites = useCachedQuery(api.favorites.getUserFavorites)
|
||||||
const favoriteSong = useMutation(api.favorites.favoriteSong).withOptimisticUpdate(
|
const favoriteSong = useMutation(api.favorites.favoriteSong).withOptimisticUpdate(
|
||||||
(store, { songId }) => {
|
(store, { songId }) => {
|
||||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
import { Spinner } from "@/components/ui/spinner"
|
|
||||||
|
|
||||||
export function LibraryLoading() {
|
|
||||||
return (
|
|
||||||
<div className="flex flex-1 items-center justify-center p-6 pb-28">
|
|
||||||
<Spinner className="size-6 text-muted-foreground" />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
import { Skeleton } from "@/components/ui/skeleton"
|
||||||
|
import { albumGridClassName } from "@/lib/album-grid-classes"
|
||||||
|
import { TRACK_LIST_CONTAINER } from "@/lib/selection-range-styles"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function LoadingRegion({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
className?: string
|
||||||
|
children: React.ReactNode
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div role="status" aria-busy className={className}>
|
||||||
|
<span className="sr-only">Loading</span>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PageHeader({ title }: { title: string }) {
|
||||||
|
return (
|
||||||
|
<header className="flex items-center gap-2 border-b px-4 py-3">
|
||||||
|
<h1 className="text-lg font-semibold">{title}</h1>
|
||||||
|
</header>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardSkeleton({ round = false }: { round?: boolean }) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Skeleton
|
||||||
|
className={cn(
|
||||||
|
"aspect-square w-full",
|
||||||
|
round ? "rounded-full" : "rounded-lg"
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<div className={cn("flex flex-col gap-1.5", round && "items-center")}>
|
||||||
|
<Skeleton className="h-3.5 w-3/4" />
|
||||||
|
{round ? null : <Skeleton className="h-3 w-1/2" />}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardGrid({ count }: { count: number }) {
|
||||||
|
return (
|
||||||
|
<div className={albumGridClassName}>
|
||||||
|
{Array.from({ length: count }, (_, index) => (
|
||||||
|
<CardSkeleton key={index} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CardGridSkeleton({ count = 18 }: { count?: number }) {
|
||||||
|
return (
|
||||||
|
<LoadingRegion className="flex-1 overflow-hidden p-6 pb-28">
|
||||||
|
<CardGrid count={count} />
|
||||||
|
</LoadingRegion>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CarouselRowSkeleton() {
|
||||||
|
return (
|
||||||
|
<section className="flex min-w-0 flex-col gap-4">
|
||||||
|
<Skeleton className="h-7 w-44" />
|
||||||
|
<div className="-ml-4 flex overflow-hidden">
|
||||||
|
{Array.from({ length: 6 }, (_, index) => (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className="min-w-0 shrink-0 grow-0 basis-1/2 pl-4 sm:basis-1/3 md:basis-1/4 lg:basis-1/5 xl:basis-1/6"
|
||||||
|
>
|
||||||
|
<CardSkeleton />
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function HomeSkeleton() {
|
||||||
|
return (
|
||||||
|
<LoadingRegion className="flex flex-1 flex-col gap-10 overflow-hidden p-6 pb-28">
|
||||||
|
<CarouselRowSkeleton />
|
||||||
|
<CarouselRowSkeleton />
|
||||||
|
</LoadingRegion>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function TrackRowSkeleton({ showCover = false }: { showCover?: boolean }) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-4 py-2.5 pr-10 pl-8">
|
||||||
|
{showCover ? (
|
||||||
|
<Skeleton className="size-9 shrink-0 rounded" />
|
||||||
|
) : (
|
||||||
|
<Skeleton className="h-3.5 w-5 shrink-0" />
|
||||||
|
)}
|
||||||
|
<div className="flex min-w-0 flex-1 flex-col gap-1.5">
|
||||||
|
<Skeleton className="h-3.5 w-2/5 max-w-72" />
|
||||||
|
<Skeleton className="h-3 w-1/4 max-w-40" />
|
||||||
|
</div>
|
||||||
|
<Skeleton className="h-3 w-9 shrink-0" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TrackListSkeleton({
|
||||||
|
count = 12,
|
||||||
|
showCover = false,
|
||||||
|
}: {
|
||||||
|
count?: number
|
||||||
|
showCover?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col">
|
||||||
|
{Array.from({ length: count }, (_, index) => (
|
||||||
|
<TrackRowSkeleton key={index} showCover={showCover} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SongListSkeleton() {
|
||||||
|
return (
|
||||||
|
<LoadingRegion className="flex-1 overflow-hidden pt-9 pb-28">
|
||||||
|
<TrackListSkeleton count={16} showCover />
|
||||||
|
</LoadingRegion>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Matches the header + track list layout of album and playlist pages. */
|
||||||
|
export function CollectionDetailSkeleton() {
|
||||||
|
return (
|
||||||
|
<LoadingRegion className="flex h-svh flex-col overflow-hidden pb-28">
|
||||||
|
<div className="mx-auto w-full max-w-9/10 min-w-0">
|
||||||
|
<div className="flex flex-col gap-8 px-6 pt-6 pb-8 sm:flex-row sm:items-end">
|
||||||
|
<Skeleton className="mx-auto aspect-square w-full max-w-60 shrink-0 rounded-lg sm:mx-0" />
|
||||||
|
<div className="flex min-w-0 flex-1 flex-col items-center gap-4 sm:items-start">
|
||||||
|
<div className="flex w-full flex-col items-center gap-2 sm:items-start">
|
||||||
|
<Skeleton className="h-3 w-14" />
|
||||||
|
<Skeleton className="h-9 w-2/3 max-w-96" />
|
||||||
|
<Skeleton className="h-5 w-40" />
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Skeleton className="size-9 rounded-full" />
|
||||||
|
<Skeleton className="h-10 w-28 rounded-full" />
|
||||||
|
<Skeleton className="size-9 rounded-full" />
|
||||||
|
<Skeleton className="size-9 rounded-full" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className={TRACK_LIST_CONTAINER}>
|
||||||
|
<TrackListSkeleton />
|
||||||
|
</div>
|
||||||
|
</LoadingRegion>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ArtistDetailSkeleton() {
|
||||||
|
return (
|
||||||
|
<LoadingRegion className="flex h-svh flex-col overflow-hidden pb-28">
|
||||||
|
<div className="flex min-w-0 items-center gap-4 px-6 pt-6 pb-8 sm:gap-6">
|
||||||
|
<Skeleton className="size-32 shrink-0 rounded-full sm:size-40" />
|
||||||
|
<div className="flex min-w-0 flex-1 flex-col gap-4">
|
||||||
|
<Skeleton className="h-10 w-1/2 max-w-80" />
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Skeleton className="size-11 rounded-full" />
|
||||||
|
<Skeleton className="size-11 rounded-full" />
|
||||||
|
<Skeleton className="size-11 rounded-full" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-4 px-6">
|
||||||
|
<Skeleton className="h-7 w-24" />
|
||||||
|
<CardGrid count={6} />
|
||||||
|
</div>
|
||||||
|
</LoadingRegion>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ArtistListSkeleton() {
|
||||||
|
return (
|
||||||
|
<div className="w-72 shrink-0 overflow-hidden border-r pb-28">
|
||||||
|
{Array.from({ length: 14 }, (_, index) => (
|
||||||
|
<div key={index} className="flex items-center gap-3 px-4 py-2.5">
|
||||||
|
<Skeleton className="size-8 shrink-0 rounded-full" />
|
||||||
|
<Skeleton className="h-3.5 flex-1" />
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ArtistsSkeleton() {
|
||||||
|
return (
|
||||||
|
<LoadingRegion className="flex min-h-0 flex-1">
|
||||||
|
<ArtistListSkeleton />
|
||||||
|
<div className="min-w-0 flex-1 overflow-hidden">
|
||||||
|
<div className="flex items-center justify-between gap-4 border-b px-6 py-4">
|
||||||
|
<Skeleton className="h-7 w-48" />
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Skeleton className="size-9 rounded-full" />
|
||||||
|
<Skeleton className="size-9 rounded-full" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="p-6">
|
||||||
|
<div className="grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 lg:grid-cols-4">
|
||||||
|
{Array.from({ length: 8 }, (_, index) => (
|
||||||
|
<CardSkeleton key={index} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</LoadingRegion>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SearchResultsSkeleton() {
|
||||||
|
return (
|
||||||
|
<LoadingRegion className="flex-1 overflow-hidden p-6 pb-28">
|
||||||
|
<div className="mx-auto flex max-w-6xl flex-col gap-10">
|
||||||
|
<section className="flex flex-col gap-4">
|
||||||
|
<Skeleton className="h-7 w-36" />
|
||||||
|
<div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-3">
|
||||||
|
{Array.from({ length: 3 }, (_, index) => (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className="flex items-center gap-4 rounded-lg p-3"
|
||||||
|
>
|
||||||
|
<Skeleton className="size-16 shrink-0 rounded-md" />
|
||||||
|
<div className="flex flex-1 flex-col gap-2">
|
||||||
|
<Skeleton className="h-4 w-2/3" />
|
||||||
|
<Skeleton className="h-3 w-1/3" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<CarouselRowSkeleton />
|
||||||
|
</div>
|
||||||
|
</LoadingRegion>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
export function PageMessage({ children }: { children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-svh flex-col">
|
||||||
|
<div className="flex flex-1 items-center justify-center pb-28">
|
||||||
|
<p className="text-sm text-muted-foreground">{children}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useAuthToken } from "@convex-dev/auth/react"
|
||||||
|
import { createContext, ReactNode, useContext, useEffect, useMemo } from "react"
|
||||||
|
|
||||||
|
import { loadPersistentCache } from "@/lib/persistent-cache"
|
||||||
|
|
||||||
|
export const ANONYMOUS_CACHE_SCOPE = "anon"
|
||||||
|
|
||||||
|
const CacheScopeContext = createContext(ANONYMOUS_CACHE_SCOPE)
|
||||||
|
|
||||||
|
if (typeof window !== "undefined") {
|
||||||
|
void loadPersistentCache()
|
||||||
|
}
|
||||||
|
|
||||||
|
function userIdFromToken(token: string | null) {
|
||||||
|
const payload = token?.split(".")[1]
|
||||||
|
if (!payload) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"))
|
||||||
|
const subject = (JSON.parse(json) as { sub?: unknown }).sub
|
||||||
|
return typeof subject === "string" ? (subject.split("|")[0] ?? null) : null
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Namespaces persisted client data by the signed-in user. */
|
||||||
|
export function PersistentCacheProvider({ children }: { children: ReactNode }) {
|
||||||
|
const token = useAuthToken()
|
||||||
|
const scope = useMemo(
|
||||||
|
() => userIdFromToken(token) ?? ANONYMOUS_CACHE_SCOPE,
|
||||||
|
[token]
|
||||||
|
)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadPersistentCache()
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<CacheScopeContext.Provider value={scope}>
|
||||||
|
{children}
|
||||||
|
</CacheScopeContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCacheScope() {
|
||||||
|
return useContext(CacheScopeContext)
|
||||||
|
}
|
||||||
@@ -12,7 +12,7 @@ import {
|
|||||||
useSyncExternalStore,
|
useSyncExternalStore,
|
||||||
useMemo,
|
useMemo,
|
||||||
} from "react"
|
} from "react"
|
||||||
import { useMutation, useQuery } from "convex/react"
|
import { useConvex, useMutation, useQuery } from "convex/react"
|
||||||
import type Hls from "hls.js"
|
import type Hls from "hls.js"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
|
|
||||||
@@ -20,13 +20,26 @@ import { api } from "@otunes/convex/_generated/api"
|
|||||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
import type { BrowseSong } from "@otunes/convex/types"
|
import type { BrowseSong } from "@otunes/convex/types"
|
||||||
import { playbackStreamPlan } from "@otunes/convex/playback-stream"
|
import { playbackStreamPlan } from "@otunes/convex/playback-stream"
|
||||||
|
import {
|
||||||
|
ANONYMOUS_CACHE_SCOPE,
|
||||||
|
useCacheScope,
|
||||||
|
} from "@/components/persistent-cache-provider"
|
||||||
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||||
import { useMediaSession } from "@/hooks/use-media-session"
|
import { useMediaSession } from "@/hooks/use-media-session"
|
||||||
|
import { fetchCachedQuery } from "@/lib/cached-query"
|
||||||
import { supportsDolbyAtmosPlayback } from "@/lib/dolby-atmos-support"
|
import { supportsDolbyAtmosPlayback } from "@/lib/dolby-atmos-support"
|
||||||
|
import { flushPersistentCache } from "@/lib/persistent-cache"
|
||||||
|
import * as playbackQueue from "@/lib/playback-queue"
|
||||||
|
import type { RepeatMode } from "@/lib/playback-queue"
|
||||||
|
import {
|
||||||
|
getPlaybackStore,
|
||||||
|
getServerPlaybackSnapshot,
|
||||||
|
} from "@/lib/playback-store"
|
||||||
|
import { rememberSongs, useSong } from "@/lib/song-cache"
|
||||||
import { songHlsPlaylistUrl, songPlayUrl } from "@/lib/song-play-url"
|
import { songHlsPlaylistUrl, songPlayUrl } from "@/lib/song-play-url"
|
||||||
|
|
||||||
type RepeatMode = "none" | "once" | "always"
|
|
||||||
|
|
||||||
const PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS = 5
|
const PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS = 5
|
||||||
|
const PROGRESS_SAVE_INTERVAL_MS = 5000
|
||||||
|
|
||||||
type PlaybackContextValue = {
|
type PlaybackContextValue = {
|
||||||
queueSongIds: Id<"songs">[]
|
queueSongIds: Id<"songs">[]
|
||||||
@@ -53,12 +66,23 @@ type PlaybackContextValue = {
|
|||||||
sortDirection: "asc" | "desc"
|
sortDirection: "asc" | "desc"
|
||||||
}
|
}
|
||||||
) => Promise<void>
|
) => Promise<void>
|
||||||
playAlbum: (albumId: Id<"albums">) => Promise<void>
|
/** Pass `songIds` when the caller already has the album's tracks. */
|
||||||
playAlbumShuffled: (albumId: Id<"albums">) => Promise<void>
|
playAlbum: (albumId: Id<"albums">, songIds?: Id<"songs">[]) => Promise<void>
|
||||||
|
playAlbumShuffled: (
|
||||||
|
albumId: Id<"albums">,
|
||||||
|
songIds?: Id<"songs">[]
|
||||||
|
) => Promise<void>
|
||||||
playArtist: (artistId: Id<"artists">) => Promise<void>
|
playArtist: (artistId: Id<"artists">) => Promise<void>
|
||||||
playArtistShuffled: (artistId: Id<"artists">) => Promise<void>
|
playArtistShuffled: (artistId: Id<"artists">) => Promise<void>
|
||||||
playPlaylist: (playlistId: Id<"playlists">) => Promise<void>
|
/** Pass `songIds` when the caller already has the playlist's songs. */
|
||||||
playPlaylistShuffled: (playlistId: Id<"playlists">) => Promise<void>
|
playPlaylist: (
|
||||||
|
playlistId: Id<"playlists">,
|
||||||
|
songIds?: Id<"songs">[]
|
||||||
|
) => Promise<void>
|
||||||
|
playPlaylistShuffled: (
|
||||||
|
playlistId: Id<"playlists">,
|
||||||
|
songIds?: Id<"songs">[]
|
||||||
|
) => Promise<void>
|
||||||
toggleShuffle: () => Promise<void>
|
toggleShuffle: () => Promise<void>
|
||||||
cycleRepeat: () => Promise<void>
|
cycleRepeat: () => Promise<void>
|
||||||
clearQueue: () => Promise<void>
|
clearQueue: () => Promise<void>
|
||||||
@@ -279,8 +303,62 @@ export function usePlaybackProgress() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function PlaybackProvider({ children }: { children: ReactNode }) {
|
export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||||
const user = useQuery(api.auth.currentUser)
|
const convex = useConvex()
|
||||||
const playback = useQuery(api.playback.getPlaybackState)
|
const cacheScope = useCacheScope()
|
||||||
|
const isSignedIn = cacheScope !== ANONYMOUS_CACHE_SCOPE
|
||||||
|
const store = useMemo(
|
||||||
|
() => getPlaybackStore(isSignedIn ? cacheScope : null),
|
||||||
|
[cacheScope, isSignedIn]
|
||||||
|
)
|
||||||
|
const playback = useSyncExternalStore(
|
||||||
|
store.subscribe,
|
||||||
|
store.getSnapshot,
|
||||||
|
getServerPlaybackSnapshot
|
||||||
|
)
|
||||||
|
const user = useCachedQuery(api.auth.currentUser)
|
||||||
|
const serverPlayback = useQuery(
|
||||||
|
api.playback.getPlaybackState,
|
||||||
|
isSignedIn ? {} : "skip"
|
||||||
|
)
|
||||||
|
const syncPlaybackStateMutation = useMutation(
|
||||||
|
api.playback.syncPlaybackState
|
||||||
|
)
|
||||||
|
const recordPlayMutation = useMutation(api.playback.recordPlay)
|
||||||
|
const updateSongProgressMutation = useMutation(api.playback.updateSongProgress)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isSignedIn) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
store.setTransport((state) =>
|
||||||
|
syncPlaybackStateMutation({
|
||||||
|
songQueue: state.queue,
|
||||||
|
queueHistory: state.history,
|
||||||
|
shuffleEnabled: state.shuffleEnabled,
|
||||||
|
repeatEnabled: state.repeatEnabled,
|
||||||
|
currentSongProgress: state.progressSeconds,
|
||||||
|
})
|
||||||
|
)
|
||||||
|
return () => store.setTransport(null)
|
||||||
|
}, [store, isSignedIn, syncPlaybackStateMutation])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!serverPlayback) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (serverPlayback.currentSong) {
|
||||||
|
rememberSongs([serverPlayback.currentSong])
|
||||||
|
}
|
||||||
|
store.receiveServerState(serverPlayback)
|
||||||
|
}, [store, serverPlayback])
|
||||||
|
|
||||||
|
const recordPlay = useCallback(
|
||||||
|
(args: { songId?: Id<"songs">; playlistId?: Id<"playlists"> }) => {
|
||||||
|
void recordPlayMutation(args).catch(() => {})
|
||||||
|
},
|
||||||
|
[recordPlayMutation]
|
||||||
|
)
|
||||||
|
|
||||||
const audioRef = useRef<HTMLAudioElement | null>(null)
|
const audioRef = useRef<HTMLAudioElement | null>(null)
|
||||||
const hlsRef = useRef<Hls | null>(null)
|
const hlsRef = useRef<Hls | null>(null)
|
||||||
const preloadAudioRef = useRef<HTMLAudioElement | null>(null)
|
const preloadAudioRef = useRef<HTMLAudioElement | null>(null)
|
||||||
@@ -292,56 +370,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
const autoPlayNextRef = useRef(false)
|
const autoPlayNextRef = useRef(false)
|
||||||
const intentionalLoadRef = useRef(false)
|
const intentionalLoadRef = useRef(false)
|
||||||
const ignoreAudioSyncRef = useRef(false)
|
const ignoreAudioSyncRef = useRef(false)
|
||||||
const playInOrderMutation = useMutation(api.playback.playInOrder)
|
|
||||||
const playShuffledMutation = useMutation(api.playback.playShuffled)
|
|
||||||
const addToQueueNextMutation = useMutation(api.playback.addToQueueNext)
|
|
||||||
const addToQueueLastMutation = useMutation(api.playback.addToQueueLast)
|
|
||||||
const playFromSongMutation = useMutation(api.playback.playFromSong)
|
|
||||||
const playFromLibrarySongMutation = useMutation(
|
|
||||||
api.playback.playFromLibrarySong
|
|
||||||
)
|
|
||||||
const playAlbumMutation = useMutation(api.playback.playAlbum)
|
|
||||||
const playAlbumShuffledMutation = useMutation(api.playback.playAlbumShuffled)
|
|
||||||
const playArtistMutation = useMutation(api.playback.playArtist)
|
|
||||||
const playArtistShuffledMutation = useMutation(
|
|
||||||
api.playback.playArtistShuffled
|
|
||||||
)
|
|
||||||
const playPlaylistMutation = useMutation(api.playback.playPlaylist)
|
|
||||||
const playPlaylistShuffledMutation = useMutation(
|
|
||||||
api.playback.playPlaylistShuffled
|
|
||||||
)
|
|
||||||
const toggleShuffleMutation = useMutation(
|
|
||||||
api.playback.toggleShuffle
|
|
||||||
).withOptimisticUpdate((store) => {
|
|
||||||
const current = store.getQuery(api.playback.getPlaybackState, {})
|
|
||||||
if (!current) return
|
|
||||||
store.setQuery(api.playback.getPlaybackState, {}, {
|
|
||||||
...current,
|
|
||||||
shuffleEnabled: !current.shuffleEnabled,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
const cycleRepeatMutation = useMutation(
|
|
||||||
api.playback.cycleRepeat
|
|
||||||
).withOptimisticUpdate((store) => {
|
|
||||||
const current = store.getQuery(api.playback.getPlaybackState, {})
|
|
||||||
if (!current) return
|
|
||||||
const next =
|
|
||||||
current.repeatEnabled === "none"
|
|
||||||
? "once"
|
|
||||||
: current.repeatEnabled === "once"
|
|
||||||
? "always"
|
|
||||||
: "none"
|
|
||||||
store.setQuery(api.playback.getPlaybackState, {}, {
|
|
||||||
...current,
|
|
||||||
repeatEnabled: next,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
const clearQueueMutation = useMutation(api.playback.clearQueue)
|
|
||||||
const reorderQueueMutation = useMutation(api.playback.reorderQueue)
|
|
||||||
const skipToQueueIndexMutation = useMutation(api.playback.skipToQueueIndex)
|
|
||||||
const skipNextMutation = useMutation(api.playback.skipNext)
|
|
||||||
const skipPreviousMutation = useMutation(api.playback.skipPrevious)
|
|
||||||
const updateSongProgressMutation = useMutation(api.playback.updateSongProgress)
|
|
||||||
|
|
||||||
const progressRestoredForSongRef = useRef<Id<"songs"> | null>(null)
|
const progressRestoredForSongRef = useRef<Id<"songs"> | null>(null)
|
||||||
const lastSavedProgressRef = useRef(-1)
|
const lastSavedProgressRef = useRef(-1)
|
||||||
@@ -381,29 +409,29 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const currentSong = playback?.currentSong ?? null
|
const queueSongIds = playback.queue
|
||||||
const currentSongId = currentSong?.id ?? null
|
const currentSongId = queueSongIds[0] ?? null
|
||||||
|
const currentSong = useSong(currentSongId)
|
||||||
const playbackQuality = user?.playbackQuality
|
const playbackQuality = user?.playbackQuality
|
||||||
const preferAtmos = user?.preferAtmos
|
const preferAtmos = user?.preferAtmos
|
||||||
const duration =
|
const duration =
|
||||||
currentSong && measuredDuration?.songId === currentSong.id
|
currentSongId && measuredDuration?.songId === currentSongId
|
||||||
? measuredDuration.seconds
|
? measuredDuration.seconds
|
||||||
: (currentSong?.durationSeconds ?? 0)
|
: (currentSong?.durationSeconds ?? 0)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
durationRef.current = duration
|
durationRef.current = duration
|
||||||
}, [duration])
|
}, [duration])
|
||||||
const currentSongDoc = useQuery(
|
const currentSongDoc = useCachedQuery(
|
||||||
api.library.getSongPlaybackInfo,
|
api.library.getSongPlaybackInfo,
|
||||||
currentSong ? { id: currentSong.id } : "skip"
|
currentSongId ? { id: currentSongId } : "skip"
|
||||||
)
|
)
|
||||||
const isPlaybackActive = Boolean(currentSong && isPlaying)
|
const isPlaybackActive = Boolean(currentSongId && isPlaying)
|
||||||
const repeatEnabled = playback?.repeatEnabled ?? "none"
|
const repeatEnabled = playback.repeatEnabled
|
||||||
const queueLength = playback?.queueSongIds.length ?? 0
|
const queueLength = queueSongIds.length
|
||||||
const queueSongIds = playback?.queueSongIds ?? []
|
|
||||||
const nextQueueSongId =
|
const nextQueueSongId =
|
||||||
queueSongIds.length > 1 ? queueSongIds[1] : null
|
queueSongIds.length > 1 ? queueSongIds[1] : null
|
||||||
const nextQueueSongDoc = useQuery(
|
const nextQueueSongDoc = useCachedQuery(
|
||||||
api.library.getSongPlaybackInfo,
|
api.library.getSongPlaybackInfo,
|
||||||
nextQueueSongId ? { id: nextQueueSongId } : "skip"
|
nextQueueSongId ? { id: nextQueueSongId } : "skip"
|
||||||
)
|
)
|
||||||
@@ -439,16 +467,19 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
lastSavedProgressRef.current = progressSeconds
|
lastSavedProgressRef.current = progressSeconds
|
||||||
void updateSongProgressMutation({
|
store.setProgress(currentSongId, progressSeconds)
|
||||||
songId: currentSongId,
|
if (isSignedIn) {
|
||||||
progressSeconds,
|
void updateSongProgressMutation({
|
||||||
})
|
songId: currentSongId,
|
||||||
|
progressSeconds,
|
||||||
|
}).catch(() => {})
|
||||||
|
}
|
||||||
},
|
},
|
||||||
[currentSongId, updateSongProgressMutation]
|
[currentSongId, store, isSignedIn, updateSongProgressMutation]
|
||||||
)
|
)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!currentSongId || !playback) {
|
if (!currentSongId) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -458,8 +489,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
|
|
||||||
progressRestoredForSongRef.current = currentSongId
|
progressRestoredForSongRef.current = currentSongId
|
||||||
lastSavedProgressRef.current = -1
|
lastSavedProgressRef.current = -1
|
||||||
setProgressToRestore(playback.currentSongProgress ?? 0)
|
setProgressToRestore(store.getState().progressSeconds)
|
||||||
}, [currentSongId, playback])
|
}, [currentSongId, store])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (progressToRestore === null || progressToRestore <= 0) {
|
if (progressToRestore === null || progressToRestore <= 0) {
|
||||||
@@ -520,13 +551,36 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
saveProgress(audio.currentTime)
|
saveProgress(audio.currentTime)
|
||||||
}, 5000)
|
}, PROGRESS_SAVE_INTERVAL_MS)
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
window.clearInterval(interval)
|
window.clearInterval(interval)
|
||||||
}
|
}
|
||||||
}, [isPlaying, currentSongId, saveProgress])
|
}, [isPlaying, currentSongId, saveProgress])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const persistNow = () => {
|
||||||
|
const audio = audioRef.current
|
||||||
|
const restorePending = progressToRestore !== null && progressToRestore > 0
|
||||||
|
if (audio && currentSongId && !restorePending) {
|
||||||
|
saveProgress(audio.currentTime)
|
||||||
|
}
|
||||||
|
flushPersistentCache()
|
||||||
|
}
|
||||||
|
const onVisibilityChange = () => {
|
||||||
|
if (document.visibilityState === "hidden") {
|
||||||
|
persistNow()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener("pagehide", persistNow)
|
||||||
|
document.addEventListener("visibilitychange", onVisibilityChange)
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("pagehide", persistNow)
|
||||||
|
document.removeEventListener("visibilitychange", onVisibilityChange)
|
||||||
|
}
|
||||||
|
}, [currentSongId, progressToRestore, saveProgress])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
isPlayingRef.current = isPlaying
|
isPlayingRef.current = isPlaying
|
||||||
}, [isPlaying])
|
}, [isPlaying])
|
||||||
@@ -797,7 +851,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const audio = audioRef.current
|
const audio = audioRef.current
|
||||||
if (!audio || !currentSong) {
|
if (!audio || !currentSongId) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -827,7 +881,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
return () => {
|
return () => {
|
||||||
audio.removeEventListener("canplay", onCanPlay)
|
audio.removeEventListener("canplay", onCanPlay)
|
||||||
}
|
}
|
||||||
}, [isPlaying, currentSong, attemptPlayback])
|
}, [isPlaying, currentSongId, attemptPlayback])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const audio = audioRef.current
|
const audio = audioRef.current
|
||||||
@@ -836,7 +890,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleEnded = () => {
|
const handleEnded = () => {
|
||||||
if (repeatEnabled === "once") {
|
const loopsSingleSong = repeatEnabled === "always" && queueLength === 1
|
||||||
|
if (repeatEnabled === "once" || loopsSingleSong) {
|
||||||
audio.currentTime = 0
|
audio.currentTime = 0
|
||||||
void audio.play()
|
void audio.play()
|
||||||
return
|
return
|
||||||
@@ -885,34 +940,23 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void skipNextMutation()
|
store.update(playbackQueue.skipNext)
|
||||||
.then(() => {
|
|
||||||
if (shouldContinuePlaying) {
|
|
||||||
autoPlayNextRef.current = true
|
|
||||||
isPlayingRef.current = true
|
|
||||||
setIsPlaying(true)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
autoPlayNextRef.current = false
|
if (!shouldContinuePlaying) {
|
||||||
isPlayingRef.current = false
|
autoPlayNextRef.current = false
|
||||||
audio.currentTime = 0
|
isPlayingRef.current = false
|
||||||
currentTimeRef.current = 0
|
audio.currentTime = 0
|
||||||
setCurrentTime(0)
|
currentTimeRef.current = 0
|
||||||
setIsPlaying(false)
|
setCurrentTime(0)
|
||||||
})
|
setIsPlaying(false)
|
||||||
.catch(() => {
|
}
|
||||||
autoPlayNextRef.current = false
|
|
||||||
isPlayingRef.current = false
|
|
||||||
setIsPlaying(false)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleError = () => {
|
const handleError = () => {
|
||||||
if (intentionalLoadRef.current) {
|
if (intentionalLoadRef.current) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (!currentSong || playbackErrorHandledRef.current) {
|
if (!currentSongId || playbackErrorHandledRef.current) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
playbackErrorHandledRef.current = true
|
playbackErrorHandledRef.current = true
|
||||||
@@ -936,7 +980,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
toast.error("Playback error", {
|
toast.error("Playback error", {
|
||||||
description: "Could not play this track. The queue has been cleared.",
|
description: "Could not play this track. The queue has been cleared.",
|
||||||
})
|
})
|
||||||
void clearQueueMutation()
|
store.update(playbackQueue.clearQueue)
|
||||||
}
|
}
|
||||||
|
|
||||||
audio.addEventListener("ended", handleEnded)
|
audio.addEventListener("ended", handleEnded)
|
||||||
@@ -948,14 +992,13 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
}
|
}
|
||||||
}, [
|
}, [
|
||||||
repeatEnabled,
|
repeatEnabled,
|
||||||
currentSong,
|
currentSongId,
|
||||||
queueLength,
|
queueLength,
|
||||||
nextQueueSongId,
|
nextQueueSongId,
|
||||||
nextQueueSongDoc,
|
nextQueueSongDoc,
|
||||||
user,
|
user,
|
||||||
dolbyAtmosSupported,
|
dolbyAtmosSupported,
|
||||||
skipNextMutation,
|
store,
|
||||||
clearQueueMutation,
|
|
||||||
destroyHls,
|
destroyHls,
|
||||||
runWithoutAudioSync,
|
runWithoutAudioSync,
|
||||||
attemptPlayback,
|
attemptPlayback,
|
||||||
@@ -968,16 +1011,17 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const syncDuration = () => {
|
const syncDuration = () => {
|
||||||
|
if (!currentSongId) {
|
||||||
|
return
|
||||||
|
}
|
||||||
if (Number.isFinite(audio.duration) && audio.duration > 0) {
|
if (Number.isFinite(audio.duration) && audio.duration > 0) {
|
||||||
if (currentSong) {
|
setMeasuredDuration({
|
||||||
setMeasuredDuration({
|
songId: currentSongId,
|
||||||
songId: currentSong.id,
|
seconds: audio.duration,
|
||||||
seconds: audio.duration,
|
})
|
||||||
})
|
|
||||||
}
|
|
||||||
} else if (currentSong) {
|
} else if (currentSong) {
|
||||||
setMeasuredDuration({
|
setMeasuredDuration({
|
||||||
songId: currentSong.id,
|
songId: currentSongId,
|
||||||
seconds: currentSong.durationSeconds,
|
seconds: currentSong.durationSeconds,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -999,17 +1043,72 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
audio.removeEventListener("loadedmetadata", syncDuration)
|
audio.removeEventListener("loadedmetadata", syncDuration)
|
||||||
audio.removeEventListener("seeked", syncTime)
|
audio.removeEventListener("seeked", syncTime)
|
||||||
}
|
}
|
||||||
}, [currentSong])
|
}, [currentSongId, currentSong])
|
||||||
|
|
||||||
|
const playRequestRef = useRef(0)
|
||||||
|
|
||||||
|
const startPlayback = useCallback(
|
||||||
|
(
|
||||||
|
recipe: (
|
||||||
|
state: playbackQueue.PlaybackQueueState
|
||||||
|
) => playbackQueue.PlaybackQueueState,
|
||||||
|
recorded: { playlistId?: Id<"playlists"> } = {}
|
||||||
|
) => {
|
||||||
|
playRequestRef.current += 1
|
||||||
|
const previousSongId = store.getState().queue[0]
|
||||||
|
store.update(recipe)
|
||||||
|
const firstSongId = store.getState().queue[0]
|
||||||
|
if (!firstSongId) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (firstSongId === previousSongId) {
|
||||||
|
seekTo(0)
|
||||||
|
}
|
||||||
|
setIsPlaying(true)
|
||||||
|
recordPlay(
|
||||||
|
recorded.playlistId
|
||||||
|
? { playlistId: recorded.playlistId }
|
||||||
|
: { songId: firstSongId }
|
||||||
|
)
|
||||||
|
},
|
||||||
|
[store, seekTo, recordPlay]
|
||||||
|
)
|
||||||
|
|
||||||
|
const playCollection = useCallback(
|
||||||
|
async (
|
||||||
|
songIds: Id<"songs">[] | Promise<Id<"songs">[]>,
|
||||||
|
shuffled: boolean,
|
||||||
|
recorded: { playlistId?: Id<"playlists"> } = {}
|
||||||
|
) => {
|
||||||
|
const request = ++playRequestRef.current
|
||||||
|
let resolvedSongIds: Id<"songs">[]
|
||||||
|
try {
|
||||||
|
resolvedSongIds = await songIds
|
||||||
|
} catch {
|
||||||
|
toast.error("Could not load songs to play")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request !== playRequestRef.current || resolvedSongIds.length === 0) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
startPlayback(
|
||||||
|
(state) => playbackQueue.startQueue(state, resolvedSongIds, shuffled),
|
||||||
|
recorded
|
||||||
|
)
|
||||||
|
},
|
||||||
|
[startPlayback]
|
||||||
|
)
|
||||||
|
|
||||||
const playInOrder = useCallback(
|
const playInOrder = useCallback(
|
||||||
async (songIds: Id<"songs">[]) => {
|
async (songIds: Id<"songs">[]) => {
|
||||||
if (songIds.length === 0) {
|
if (songIds.length === 0) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
await playInOrderMutation({ songIds })
|
startPlayback((state) => playbackQueue.startQueue(state, songIds, false))
|
||||||
setIsPlaying(true)
|
|
||||||
},
|
},
|
||||||
[playInOrderMutation]
|
[startPlayback]
|
||||||
)
|
)
|
||||||
|
|
||||||
const playShuffled = useCallback(
|
const playShuffled = useCallback(
|
||||||
@@ -1017,10 +1116,9 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
if (songIds.length === 0) {
|
if (songIds.length === 0) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
await playShuffledMutation({ songIds })
|
startPlayback((state) => playbackQueue.startQueue(state, songIds, true))
|
||||||
setIsPlaying(true)
|
|
||||||
},
|
},
|
||||||
[playShuffledMutation]
|
[startPlayback]
|
||||||
)
|
)
|
||||||
|
|
||||||
const addToQueueNext = useCallback(
|
const addToQueueNext = useCallback(
|
||||||
@@ -1028,10 +1126,10 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
if (songIds.length === 0) {
|
if (songIds.length === 0) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
await addToQueueNextMutation({ songIds })
|
store.update((state) => playbackQueue.addToQueue(state, songIds, "next"))
|
||||||
setIsPlaying(true)
|
setIsPlaying(true)
|
||||||
},
|
},
|
||||||
[addToQueueNextMutation]
|
[store]
|
||||||
)
|
)
|
||||||
|
|
||||||
const addToQueueLast = useCallback(
|
const addToQueueLast = useCallback(
|
||||||
@@ -1039,18 +1137,19 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
if (songIds.length === 0) {
|
if (songIds.length === 0) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
await addToQueueLastMutation({ songIds })
|
store.update((state) => playbackQueue.addToQueue(state, songIds, "last"))
|
||||||
setIsPlaying(true)
|
setIsPlaying(true)
|
||||||
},
|
},
|
||||||
[addToQueueLastMutation]
|
[store]
|
||||||
)
|
)
|
||||||
|
|
||||||
const playFromSong = useCallback(
|
const playFromSong = useCallback(
|
||||||
async (songId: Id<"songs">, songIds: Id<"songs">[]) => {
|
async (songId: Id<"songs">, songIds: Id<"songs">[]) => {
|
||||||
await playFromSongMutation({ songId, songIds })
|
startPlayback((state) =>
|
||||||
setIsPlaying(true)
|
playbackQueue.startQueueFromSong(state, songId, songIds)
|
||||||
|
)
|
||||||
},
|
},
|
||||||
[playFromSongMutation]
|
[startPlayback]
|
||||||
)
|
)
|
||||||
|
|
||||||
const playFromLibrarySong = useCallback(
|
const playFromLibrarySong = useCallback(
|
||||||
@@ -1061,84 +1160,155 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
sortDirection: "asc" | "desc"
|
sortDirection: "asc" | "desc"
|
||||||
}
|
}
|
||||||
) => {
|
) => {
|
||||||
await playFromLibrarySongMutation({ songId, ...sort })
|
startPlayback((state) =>
|
||||||
setIsPlaying(true)
|
playbackQueue.startQueueFromSong(state, songId, [songId])
|
||||||
|
)
|
||||||
|
const request = playRequestRef.current
|
||||||
|
|
||||||
|
let songIds: Id<"songs">[]
|
||||||
|
try {
|
||||||
|
songIds = await fetchCachedQuery(
|
||||||
|
convex,
|
||||||
|
cacheScope,
|
||||||
|
api.library.browseSortedSongIds,
|
||||||
|
sort
|
||||||
|
)
|
||||||
|
} catch {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request === playRequestRef.current) {
|
||||||
|
store.update((state) =>
|
||||||
|
playbackQueue.extendQueueFromSong(state, songId, songIds)
|
||||||
|
)
|
||||||
|
}
|
||||||
},
|
},
|
||||||
[playFromLibrarySongMutation]
|
[convex, cacheScope, store, startPlayback]
|
||||||
|
)
|
||||||
|
|
||||||
|
const loadAlbumSongIds = useCallback(
|
||||||
|
(albumId: Id<"albums">, songIds?: Id<"songs">[]) =>
|
||||||
|
songIds ??
|
||||||
|
fetchCachedQuery(convex, cacheScope, api.playlists.getAlbumSongIds, {
|
||||||
|
albumId,
|
||||||
|
}),
|
||||||
|
[convex, cacheScope]
|
||||||
|
)
|
||||||
|
|
||||||
|
const loadArtistSongIds = useCallback(
|
||||||
|
(artistId: Id<"artists">) =>
|
||||||
|
fetchCachedQuery(
|
||||||
|
convex,
|
||||||
|
cacheScope,
|
||||||
|
api.playlists.getOrderedArtistSongIds,
|
||||||
|
{ artistId }
|
||||||
|
),
|
||||||
|
[convex, cacheScope]
|
||||||
|
)
|
||||||
|
|
||||||
|
const loadPlaylistSongIds = useCallback(
|
||||||
|
(playlistId: Id<"playlists">, songIds?: Id<"songs">[]) =>
|
||||||
|
songIds ??
|
||||||
|
fetchCachedQuery(convex, cacheScope, api.playlists.getPlaylistSongIds, {
|
||||||
|
playlistId,
|
||||||
|
}),
|
||||||
|
[convex, cacheScope]
|
||||||
)
|
)
|
||||||
|
|
||||||
const playAlbum = useCallback(
|
const playAlbum = useCallback(
|
||||||
async (albumId: Id<"albums">) => {
|
(albumId: Id<"albums">, songIds?: Id<"songs">[]) =>
|
||||||
await playAlbumMutation({ albumId })
|
playCollection(loadAlbumSongIds(albumId, songIds), false),
|
||||||
setIsPlaying(true)
|
[playCollection, loadAlbumSongIds]
|
||||||
},
|
|
||||||
[playAlbumMutation]
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const playAlbumShuffled = useCallback(
|
const playAlbumShuffled = useCallback(
|
||||||
async (albumId: Id<"albums">) => {
|
(albumId: Id<"albums">, songIds?: Id<"songs">[]) =>
|
||||||
await playAlbumShuffledMutation({ albumId })
|
playCollection(loadAlbumSongIds(albumId, songIds), true),
|
||||||
setIsPlaying(true)
|
[playCollection, loadAlbumSongIds]
|
||||||
},
|
|
||||||
[playAlbumShuffledMutation]
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const playArtist = useCallback(
|
const playArtist = useCallback(
|
||||||
async (artistId: Id<"artists">) => {
|
(artistId: Id<"artists">) =>
|
||||||
await playArtistMutation({ artistId })
|
playCollection(loadArtistSongIds(artistId), false),
|
||||||
setIsPlaying(true)
|
[playCollection, loadArtistSongIds]
|
||||||
},
|
|
||||||
[playArtistMutation]
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const playArtistShuffled = useCallback(
|
const playArtistShuffled = useCallback(
|
||||||
async (artistId: Id<"artists">) => {
|
(artistId: Id<"artists">) =>
|
||||||
await playArtistShuffledMutation({ artistId })
|
playCollection(loadArtistSongIds(artistId), true),
|
||||||
setIsPlaying(true)
|
[playCollection, loadArtistSongIds]
|
||||||
},
|
|
||||||
[playArtistShuffledMutation]
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const playPlaylist = useCallback(
|
const playPlaylist = useCallback(
|
||||||
async (playlistId: Id<"playlists">) => {
|
(playlistId: Id<"playlists">, songIds?: Id<"songs">[]) =>
|
||||||
await playPlaylistMutation({ playlistId })
|
playCollection(loadPlaylistSongIds(playlistId, songIds), false, {
|
||||||
setIsPlaying(true)
|
playlistId,
|
||||||
},
|
}),
|
||||||
[playPlaylistMutation]
|
[playCollection, loadPlaylistSongIds]
|
||||||
)
|
)
|
||||||
|
|
||||||
const playPlaylistShuffled = useCallback(
|
const playPlaylistShuffled = useCallback(
|
||||||
async (playlistId: Id<"playlists">) => {
|
(playlistId: Id<"playlists">, songIds?: Id<"songs">[]) =>
|
||||||
await playPlaylistShuffledMutation({ playlistId })
|
playCollection(loadPlaylistSongIds(playlistId, songIds), true, {
|
||||||
setIsPlaying(true)
|
playlistId,
|
||||||
},
|
}),
|
||||||
[playPlaylistShuffledMutation]
|
[playCollection, loadPlaylistSongIds]
|
||||||
)
|
)
|
||||||
|
|
||||||
const toggleQueueOpen = useCallback(() => {
|
const toggleQueueOpen = useCallback(() => {
|
||||||
setQueueOpen((open) => !open)
|
setQueueOpen((open) => !open)
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
|
const toggleShuffle = useCallback(async () => {
|
||||||
|
store.update(playbackQueue.toggleShuffle)
|
||||||
|
}, [store])
|
||||||
|
|
||||||
|
const cycleRepeat = useCallback(async () => {
|
||||||
|
store.update(playbackQueue.cycleRepeat)
|
||||||
|
}, [store])
|
||||||
|
|
||||||
|
const clearQueue = useCallback(async () => {
|
||||||
|
playRequestRef.current += 1
|
||||||
|
store.update(playbackQueue.clearQueue)
|
||||||
|
setIsPlaying(false)
|
||||||
|
}, [store])
|
||||||
|
|
||||||
|
const reorderQueue = useCallback(
|
||||||
|
async (songIds: Id<"songs">[]) => {
|
||||||
|
store.update((state) => playbackQueue.reorderQueue(state, songIds))
|
||||||
|
},
|
||||||
|
[store]
|
||||||
|
)
|
||||||
|
|
||||||
|
const skipToQueueIndex = useCallback(
|
||||||
|
async (index: number) => {
|
||||||
|
store.update((state) => playbackQueue.skipToQueueIndex(state, index))
|
||||||
|
},
|
||||||
|
[store]
|
||||||
|
)
|
||||||
|
|
||||||
const skipNext = useCallback(async () => {
|
const skipNext = useCallback(async () => {
|
||||||
const isFinishingQueue =
|
const before = store.getState()
|
||||||
repeatEnabled === "none" && queueSongIds.length <= 1
|
if (before.repeatEnabled === "none" && before.queue.length <= 1) {
|
||||||
if (isFinishingQueue) {
|
|
||||||
setIsPlaying(false)
|
setIsPlaying(false)
|
||||||
|
}
|
||||||
|
store.update(playbackQueue.skipNext)
|
||||||
|
if (store.getState().queue[0] === before.queue[0]) {
|
||||||
seekTo(0)
|
seekTo(0)
|
||||||
}
|
}
|
||||||
await skipNextMutation()
|
}, [store, seekTo])
|
||||||
if (isFinishingQueue) {
|
|
||||||
seekTo(0)
|
|
||||||
}
|
|
||||||
}, [repeatEnabled, queueSongIds.length, seekTo, skipNextMutation])
|
|
||||||
|
|
||||||
const skipPrevious = useCallback(async () => {
|
const skipPrevious = useCallback(async () => {
|
||||||
if (currentTimeRef.current > PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS) {
|
if (currentTimeRef.current > PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS) {
|
||||||
seekTo(0)
|
seekTo(0)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
await skipPreviousMutation()
|
const previousSongId = store.getState().queue[0]
|
||||||
}, [seekTo, skipPreviousMutation])
|
store.update(playbackQueue.skipPrevious)
|
||||||
|
if (store.getState().queue[0] === previousSongId) {
|
||||||
|
seekTo(0)
|
||||||
|
}
|
||||||
|
}, [store, seekTo])
|
||||||
|
|
||||||
useMediaSession({
|
useMediaSession({
|
||||||
song: currentSong,
|
song: currentSong,
|
||||||
@@ -1153,11 +1323,11 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
|
|
||||||
const value = useMemo<PlaybackContextValue>(
|
const value = useMemo<PlaybackContextValue>(
|
||||||
() => ({
|
() => ({
|
||||||
queueSongIds: playback?.queueSongIds ?? [],
|
queueSongIds: playback.queue,
|
||||||
queueHistorySongIds: playback?.queueHistorySongIds ?? [],
|
queueHistorySongIds: playback.history,
|
||||||
currentSong: playback?.currentSong ?? null,
|
currentSong,
|
||||||
shuffleEnabled: playback?.shuffleEnabled ?? false,
|
shuffleEnabled: playback.shuffleEnabled,
|
||||||
repeatEnabled: playback?.repeatEnabled ?? "none",
|
repeatEnabled: playback.repeatEnabled,
|
||||||
queueOpen,
|
queueOpen,
|
||||||
isPlaying: isPlaybackActive,
|
isPlaying: isPlaybackActive,
|
||||||
volume,
|
volume,
|
||||||
@@ -1177,28 +1347,18 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
playArtistShuffled,
|
playArtistShuffled,
|
||||||
playPlaylist,
|
playPlaylist,
|
||||||
playPlaylistShuffled,
|
playPlaylistShuffled,
|
||||||
toggleShuffle: async () => {
|
toggleShuffle,
|
||||||
await toggleShuffleMutation()
|
cycleRepeat,
|
||||||
},
|
clearQueue,
|
||||||
cycleRepeat: async () => {
|
reorderQueue,
|
||||||
await cycleRepeatMutation()
|
skipToQueueIndex,
|
||||||
},
|
|
||||||
clearQueue: async () => {
|
|
||||||
await clearQueueMutation()
|
|
||||||
setIsPlaying(false)
|
|
||||||
},
|
|
||||||
reorderQueue: async (songIds) => {
|
|
||||||
await reorderQueueMutation({ songIds })
|
|
||||||
},
|
|
||||||
skipToQueueIndex: async (index) => {
|
|
||||||
await skipToQueueIndexMutation({ index })
|
|
||||||
},
|
|
||||||
skipNext,
|
skipNext,
|
||||||
skipPrevious,
|
skipPrevious,
|
||||||
dolbyAtmosSupported,
|
dolbyAtmosSupported,
|
||||||
}),
|
}),
|
||||||
[
|
[
|
||||||
playback,
|
playback,
|
||||||
|
currentSong,
|
||||||
queueOpen,
|
queueOpen,
|
||||||
isPlaybackActive,
|
isPlaybackActive,
|
||||||
volume,
|
volume,
|
||||||
@@ -1216,11 +1376,11 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|||||||
playArtistShuffled,
|
playArtistShuffled,
|
||||||
playPlaylist,
|
playPlaylist,
|
||||||
playPlaylistShuffled,
|
playPlaylistShuffled,
|
||||||
toggleShuffleMutation,
|
toggleShuffle,
|
||||||
cycleRepeatMutation,
|
cycleRepeat,
|
||||||
clearQueueMutation,
|
clearQueue,
|
||||||
reorderQueueMutation,
|
reorderQueue,
|
||||||
skipToQueueIndexMutation,
|
skipToQueueIndex,
|
||||||
skipNext,
|
skipNext,
|
||||||
skipPrevious,
|
skipPrevious,
|
||||||
dolbyAtmosSupported,
|
dolbyAtmosSupported,
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { playlistCoverUrl } from "@/lib/cover-urls"
|
|||||||
import { useConvex } from "convex/react"
|
import { useConvex } from "convex/react"
|
||||||
import { MoreHorizontal, Play } from "lucide-react"
|
import { MoreHorizontal, Play } from "lucide-react"
|
||||||
|
|
||||||
|
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||||
import {
|
import {
|
||||||
MediaContextMenuItems,
|
MediaContextMenuItems,
|
||||||
@@ -23,9 +24,11 @@ import {
|
|||||||
} from "@/components/ui/dropdown-menu"
|
} from "@/components/ui/dropdown-menu"
|
||||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
|
import { fetchCachedQuery } from "@/lib/cached-query"
|
||||||
|
|
||||||
export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
|
export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
|
||||||
const convex = useConvex()
|
const convex = useConvex()
|
||||||
|
const cacheScope = useCacheScope()
|
||||||
const { openAddPlaylistToPlaylist } = useAddToPlaylist()
|
const { openAddPlaylistToPlaylist } = useAddToPlaylist()
|
||||||
const { playPlaylist } = usePlayback()
|
const { playPlaylist } = usePlayback()
|
||||||
const { runQueueAction } = useQueueMediaActions()
|
const { runQueueAction } = useQueueMediaActions()
|
||||||
@@ -38,9 +41,14 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
|
|||||||
case "play-next":
|
case "play-next":
|
||||||
case "play-last":
|
case "play-last":
|
||||||
case "shuffle": {
|
case "shuffle": {
|
||||||
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
const songIds = await fetchCachedQuery(
|
||||||
playlistId: playlist.id as Id<"playlists">,
|
convex,
|
||||||
})
|
cacheScope,
|
||||||
|
api.playlists.getPlaylistSongIds,
|
||||||
|
{
|
||||||
|
playlistId: playlist.id as Id<"playlists">,
|
||||||
|
}
|
||||||
|
)
|
||||||
void runQueueAction(action, songIds)
|
void runQueueAction(action, songIds)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { CollectionDetailSkeleton } from "@/components/library-skeletons"
|
||||||
|
import { PageMessage } from "@/components/page-message"
|
||||||
|
import { PlaylistView } from "@/components/playlist-view"
|
||||||
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||||
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
|
|
||||||
|
export function PlaylistPage({ playlistId }: { playlistId: Id<"playlists"> }) {
|
||||||
|
const playlist = useCachedQuery(api.playlists.browsePlaylistDetail, {
|
||||||
|
id: playlistId,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (playlist === undefined) {
|
||||||
|
return <CollectionDetailSkeleton />
|
||||||
|
}
|
||||||
|
|
||||||
|
if (playlist === null) {
|
||||||
|
return <PageMessage>Playlist not found.</PageMessage>
|
||||||
|
}
|
||||||
|
|
||||||
|
return <PlaylistView key={playlist.id} playlist={playlist} />
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FavoritesPlaylistPage() {
|
||||||
|
const favorites = useCachedQuery(api.favorites.browseFavoritesPlaylistDetail)
|
||||||
|
|
||||||
|
if (favorites === undefined) {
|
||||||
|
return <CollectionDetailSkeleton />
|
||||||
|
}
|
||||||
|
|
||||||
|
if (favorites === null) {
|
||||||
|
return <PageMessage>Sign in to view your favorites.</PageMessage>
|
||||||
|
}
|
||||||
|
|
||||||
|
return <PlaylistView playlist={favorites} />
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
import Image from "next/image"
|
import Image from "next/image"
|
||||||
import { useRouter } from "next/navigation"
|
import { useRouter } from "next/navigation"
|
||||||
import { useMutation, useQuery } from "convex/react"
|
import { useMutation } from "convex/react"
|
||||||
import { Play, Share2, Shuffle, Star, Trash2 } from "lucide-react"
|
import { Play, Share2, Shuffle, Star, Trash2 } from "lucide-react"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
|
|
||||||
@@ -22,6 +22,7 @@ import {
|
|||||||
DropdownMenuSeparator,
|
DropdownMenuSeparator,
|
||||||
} from "@/components/ui/dropdown-menu"
|
} from "@/components/ui/dropdown-menu"
|
||||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||||
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||||
import { useTrackSelection } from "@/hooks/use-track-selection"
|
import { useTrackSelection } from "@/hooks/use-track-selection"
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
@@ -30,6 +31,7 @@ import type { BrowsePlaylistDetail, BrowseSong } from "@otunes/convex/types"
|
|||||||
import { albumCoverUrl, playlistCoverUrl } from "@/lib/cover-urls"
|
import { albumCoverUrl, playlistCoverUrl } from "@/lib/cover-urls"
|
||||||
import { copyPlaylistLink } from "@/lib/media-links"
|
import { copyPlaylistLink } from "@/lib/media-links"
|
||||||
import { sumDurationSeconds } from "@/lib/media-summary"
|
import { sumDurationSeconds } from "@/lib/media-summary"
|
||||||
|
import { rememberSongs } from "@/lib/song-cache"
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils"
|
||||||
import {
|
import {
|
||||||
getSelectionRangePositions,
|
getSelectionRangePositions,
|
||||||
@@ -263,7 +265,7 @@ function PlaylistSongRow({
|
|||||||
export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const isFavorites = playlist.isFavorites === true
|
const isFavorites = playlist.isFavorites === true
|
||||||
const currentUser = useQuery(api.auth.currentUser)
|
const currentUser = useCachedQuery(api.auth.currentUser)
|
||||||
const isOwner =
|
const isOwner =
|
||||||
currentUser === undefined
|
currentUser === undefined
|
||||||
? playlist.isOwner
|
? playlist.isOwner
|
||||||
@@ -277,6 +279,8 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
|||||||
} = useFavorites()
|
} = useFavorites()
|
||||||
const {
|
const {
|
||||||
currentSong,
|
currentSong,
|
||||||
|
playInOrder,
|
||||||
|
playShuffled,
|
||||||
playPlaylist,
|
playPlaylist,
|
||||||
playPlaylistShuffled,
|
playPlaylistShuffled,
|
||||||
playFromSong,
|
playFromSong,
|
||||||
@@ -289,6 +293,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
|||||||
const unsubscribe = useMutation(api.playlists.unsubscribeFromPlaylist)
|
const unsubscribe = useMutation(api.playlists.unsubscribeFromPlaylist)
|
||||||
|
|
||||||
const [playlistSongs, setPlaylistSongs] = React.useState(playlist.songs)
|
const [playlistSongs, setPlaylistSongs] = React.useState(playlist.songs)
|
||||||
|
const [syncedPlaylist, setSyncedPlaylist] = React.useState(playlist)
|
||||||
const [hiddenFavoriteIds, setHiddenFavoriteIds] = React.useState(
|
const [hiddenFavoriteIds, setHiddenFavoriteIds] = React.useState(
|
||||||
() => new Set<string>()
|
() => new Set<string>()
|
||||||
)
|
)
|
||||||
@@ -304,6 +309,12 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
|||||||
const [isSubscribed, setIsSubscribed] = React.useState(playlist.isSubscribed)
|
const [isSubscribed, setIsSubscribed] = React.useState(playlist.isSubscribed)
|
||||||
const [subscriptionPending, setSubscriptionPending] = React.useState(false)
|
const [subscriptionPending, setSubscriptionPending] = React.useState(false)
|
||||||
|
|
||||||
|
if (syncedPlaylist !== playlist) {
|
||||||
|
setSyncedPlaylist(playlist)
|
||||||
|
setPlaylistSongs(playlist.songs)
|
||||||
|
setIsSubscribed(playlist.isSubscribed)
|
||||||
|
}
|
||||||
|
|
||||||
const {
|
const {
|
||||||
selectedIds,
|
selectedIds,
|
||||||
selectedCount,
|
selectedCount,
|
||||||
@@ -322,6 +333,19 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
|||||||
[songs]
|
[songs]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
rememberSongs(playlist.songs)
|
||||||
|
}, [playlist.songs])
|
||||||
|
|
||||||
|
function playAll(shuffled: boolean) {
|
||||||
|
if (playlist.id) {
|
||||||
|
const play = shuffled ? playPlaylistShuffled : playPlaylist
|
||||||
|
void play(playlist.id, playlistSongIds)
|
||||||
|
} else {
|
||||||
|
void (shuffled ? playShuffled : playInOrder)(playlistSongIds)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function resolveTargetIds(fallbackSongId?: string) {
|
function resolveTargetIds(fallbackSongId?: string) {
|
||||||
return selectedIds.size > 0
|
return selectedIds.size > 0
|
||||||
? Array.from(selectedIds)
|
? Array.from(selectedIds)
|
||||||
@@ -520,9 +544,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
|||||||
size="icon"
|
size="icon"
|
||||||
className="rounded-full"
|
className="rounded-full"
|
||||||
aria-label="Shuffle playlist"
|
aria-label="Shuffle playlist"
|
||||||
onClick={() =>
|
onClick={() => playAll(true)}
|
||||||
void playPlaylistShuffled(playlist.id as Id<"playlists">)
|
|
||||||
}
|
|
||||||
disabled={playlistSongIds.length === 0}
|
disabled={playlistSongIds.length === 0}
|
||||||
>
|
>
|
||||||
<Shuffle />
|
<Shuffle />
|
||||||
@@ -530,9 +552,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
|||||||
<Button
|
<Button
|
||||||
className="h-10 gap-2 rounded-full bg-foreground px-6 text-background hover:bg-foreground/90"
|
className="h-10 gap-2 rounded-full bg-foreground px-6 text-background hover:bg-foreground/90"
|
||||||
aria-label={`Play ${playlist.title}`}
|
aria-label={`Play ${playlist.title}`}
|
||||||
onClick={() =>
|
onClick={() => playAll(false)}
|
||||||
void playPlaylist(playlist.id as Id<"playlists">)
|
|
||||||
}
|
|
||||||
disabled={playlistSongIds.length === 0}
|
disabled={playlistSongIds.length === 0}
|
||||||
>
|
>
|
||||||
<Play className="fill-current" />
|
<Play className="fill-current" />
|
||||||
|
|||||||
@@ -2,19 +2,17 @@
|
|||||||
|
|
||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
import Image from "next/image"
|
import Image from "next/image"
|
||||||
import { useMutation, usePaginatedQuery, useQuery } from "convex/react"
|
|
||||||
import { Music2 } from "lucide-react"
|
import { Music2 } from "lucide-react"
|
||||||
import { toast } from "sonner"
|
|
||||||
|
|
||||||
import { PlaybackSongMeta } from "@/components/playback-song-meta"
|
import { PlaybackSongMeta } from "@/components/playback-song-meta"
|
||||||
import { usePlayback } from "@/components/playback-provider"
|
import { usePlayback } from "@/components/playback-provider"
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton"
|
||||||
import { Spinner } from "@/components/ui/spinner"
|
import { Spinner } from "@/components/ui/spinner"
|
||||||
import { useTrackSelection } from "@/hooks/use-track-selection"
|
import { useTrackSelection } from "@/hooks/use-track-selection"
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
|
||||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
import type { HistorySong, QueueSong } from "@otunes/convex/types"
|
import type { BrowseSong, HistorySong, QueueSong } from "@otunes/convex/types"
|
||||||
import { albumCoverUrl } from "@/lib/cover-urls"
|
import { albumCoverUrl } from "@/lib/cover-urls"
|
||||||
import {
|
import {
|
||||||
getContiguousSelectedIndices,
|
getContiguousSelectedIndices,
|
||||||
@@ -28,18 +26,18 @@ import {
|
|||||||
QueueTrackRowHoverHighlight,
|
QueueTrackRowHoverHighlight,
|
||||||
type SelectionRangePosition,
|
type SelectionRangePosition,
|
||||||
} from "@/lib/selection-range-styles"
|
} from "@/lib/selection-range-styles"
|
||||||
|
import { useSongs } from "@/lib/song-cache"
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
const QUEUE_PAGINATION_THRESHOLD = 100
|
const QUEUE_INITIAL_VISIBLE_COUNT = 100
|
||||||
const QUEUE_PAGE_SIZE = 50
|
const QUEUE_PAGE_SIZE = 50
|
||||||
|
|
||||||
type QueueSelectable = QueueSong & { selectionId: string }
|
type QueueSelectable = QueueSong & { selectionId: string }
|
||||||
|
|
||||||
function getQueueVersion(queueSongIds: Id<"songs">[]) {
|
type QueueItem = {
|
||||||
if (queueSongIds.length === 0) {
|
selectionId: string
|
||||||
return "empty"
|
queueIndex: number
|
||||||
}
|
song: QueueSelectable | null
|
||||||
return `${queueSongIds.length}:${queueSongIds[0]}:${queueSongIds[queueSongIds.length - 1]}`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatDuration(seconds: number): string {
|
function formatDuration(seconds: number): string {
|
||||||
@@ -48,11 +46,19 @@ function formatDuration(seconds: number): string {
|
|||||||
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
|
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
|
||||||
}
|
}
|
||||||
|
|
||||||
function toSelectableQueue(songs: QueueSong[]): QueueSelectable[] {
|
function toSelectableQueue(
|
||||||
return songs.map((song) => ({
|
songIds: Id<"songs">[],
|
||||||
...song,
|
songs: (BrowseSong | undefined)[]
|
||||||
selectionId: `${song.id}-${song.queueIndex}`,
|
): QueueItem[] {
|
||||||
}))
|
return songIds.map((songId, queueIndex) => {
|
||||||
|
const selectionId = `${songId}-${queueIndex}`
|
||||||
|
const song = songs[queueIndex]
|
||||||
|
return {
|
||||||
|
selectionId,
|
||||||
|
queueIndex,
|
||||||
|
song: song ? { ...song, queueIndex, selectionId } : null,
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
function QueueSongCover({
|
function QueueSongCover({
|
||||||
@@ -214,39 +220,52 @@ const QueueSongRow = React.forwardRef<
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
function QueueSongRowSkeleton() {
|
||||||
|
return (
|
||||||
|
<li className="flex items-center gap-3 px-2 py-2" aria-hidden>
|
||||||
|
<Skeleton className="size-10 shrink-0 rounded-none" />
|
||||||
|
<div className="flex min-w-0 flex-1 flex-col gap-1.5">
|
||||||
|
<Skeleton className="h-3.5 w-3/4" />
|
||||||
|
<Skeleton className="h-3 w-1/2" />
|
||||||
|
</div>
|
||||||
|
<Skeleton className="h-3 w-8 shrink-0" />
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
export function QueuePanel() {
|
export function QueuePanel() {
|
||||||
const { queueSongIds, queueOpen, clearQueue, skipToQueueIndex } =
|
const {
|
||||||
usePlayback()
|
queueSongIds,
|
||||||
const reorderQueue = useMutation(api.playback.reorderQueue)
|
queueHistorySongIds,
|
||||||
|
queueOpen,
|
||||||
|
clearQueue,
|
||||||
|
reorderQueue,
|
||||||
|
skipToQueueIndex,
|
||||||
|
} = usePlayback()
|
||||||
const loadMoreRef = React.useRef<HTMLDivElement>(null)
|
const loadMoreRef = React.useRef<HTMLDivElement>(null)
|
||||||
const nowPlayingRef = React.useRef<HTMLLIElement>(null)
|
const nowPlayingRef = React.useRef<HTMLLIElement>(null)
|
||||||
|
const [visibleCount, setVisibleCount] = React.useState(
|
||||||
const historySongs = useQuery(
|
QUEUE_INITIAL_VISIBLE_COUNT
|
||||||
api.playback.getQueueHistory,
|
|
||||||
queueOpen ? {} : "skip"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const queueVersion = React.useMemo(
|
const visibleQueueIds = React.useMemo(
|
||||||
() => getQueueVersion(queueSongIds),
|
() => queueSongIds.slice(0, visibleCount),
|
||||||
[queueSongIds]
|
[queueSongIds, visibleCount]
|
||||||
)
|
)
|
||||||
const shouldPaginate = queueSongIds.length > QUEUE_PAGINATION_THRESHOLD
|
const visibleQueueSongs = useSongs(visibleQueueIds)
|
||||||
const initialPageSize = shouldPaginate
|
const historySongMetadata = useSongs(queueHistorySongIds)
|
||||||
? QUEUE_PAGE_SIZE
|
const historySongs = React.useMemo(
|
||||||
: queueSongIds.length
|
() =>
|
||||||
|
historySongMetadata.flatMap((song, historyIndex) =>
|
||||||
const { results, status, loadMore } = usePaginatedQuery(
|
song ? [{ ...song, historyIndex }] : []
|
||||||
api.playback.getQueuePaginated,
|
),
|
||||||
queueOpen && queueSongIds.length > 0
|
[historySongMetadata]
|
||||||
? { queueVersion }
|
|
||||||
: "skip",
|
|
||||||
{ initialNumItems: initialPageSize }
|
|
||||||
)
|
)
|
||||||
|
const hasMore = queueSongIds.length > visibleCount
|
||||||
|
|
||||||
const queueSongs = React.useMemo(() => results ?? [], [results])
|
|
||||||
const selectableQueue = React.useMemo(
|
const selectableQueue = React.useMemo(
|
||||||
() => toSelectableQueue(queueSongs),
|
() => toSelectableQueue(visibleQueueIds, visibleQueueSongs),
|
||||||
[queueSongs]
|
[visibleQueueIds, visibleQueueSongs]
|
||||||
)
|
)
|
||||||
|
|
||||||
const [dragIndex, setDragIndex] = React.useState<number | null>(null)
|
const [dragIndex, setDragIndex] = React.useState<number | null>(null)
|
||||||
@@ -265,7 +284,7 @@ export function QueuePanel() {
|
|||||||
}, [queueOpen, queueSongIds.length, currentQueueSongId])
|
}, [queueOpen, queueSongIds.length, currentQueueSongId])
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
if (!shouldPaginate) {
|
if (!hasMore) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -281,8 +300,8 @@ export function QueuePanel() {
|
|||||||
|
|
||||||
const observer = new IntersectionObserver(
|
const observer = new IntersectionObserver(
|
||||||
(entries) => {
|
(entries) => {
|
||||||
if (entries[0]?.isIntersecting && status === "CanLoadMore") {
|
if (entries[0]?.isIntersecting) {
|
||||||
loadMore(QUEUE_PAGE_SIZE)
|
setVisibleCount((count) => count + QUEUE_PAGE_SIZE)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{ root: viewport, rootMargin: "240px" }
|
{ root: viewport, rootMargin: "240px" }
|
||||||
@@ -290,7 +309,7 @@ export function QueuePanel() {
|
|||||||
|
|
||||||
observer.observe(sentinel)
|
observer.observe(sentinel)
|
||||||
return () => observer.disconnect()
|
return () => observer.disconnect()
|
||||||
}, [shouldPaginate, status, loadMore])
|
}, [hasMore])
|
||||||
|
|
||||||
const {
|
const {
|
||||||
selectedIds,
|
selectedIds,
|
||||||
@@ -318,16 +337,6 @@ export function QueuePanel() {
|
|||||||
)
|
)
|
||||||
}, [dragIndex, selectableQueue, selectedIds])
|
}, [dragIndex, selectableQueue, selectedIds])
|
||||||
|
|
||||||
async function persistOrder(nextQueue: Id<"songs">[]) {
|
|
||||||
try {
|
|
||||||
await reorderQueue({ songIds: nextQueue })
|
|
||||||
} catch (error) {
|
|
||||||
toast.error(
|
|
||||||
error instanceof Error ? error.message : "Failed to reorder queue"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleDrop(targetLocalIndex: number) {
|
function handleDrop(targetLocalIndex: number) {
|
||||||
if (dragIndex === null) {
|
if (dragIndex === null) {
|
||||||
return
|
return
|
||||||
@@ -350,7 +359,7 @@ export function QueuePanel() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
void persistOrder(next)
|
void reorderQueue(next)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!queueOpen) {
|
if (!queueOpen) {
|
||||||
@@ -382,13 +391,9 @@ export function QueuePanel() {
|
|||||||
<p className="px-4 py-8 text-sm text-muted-foreground">
|
<p className="px-4 py-8 text-sm text-muted-foreground">
|
||||||
Nothing in the queue.
|
Nothing in the queue.
|
||||||
</p>
|
</p>
|
||||||
) : status === "LoadingFirstPage" ? (
|
|
||||||
<div className="flex items-center justify-center py-8">
|
|
||||||
<Spinner className="size-5 text-muted-foreground" />
|
|
||||||
</div>
|
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
{historySongs && historySongs.length > 0 ? (
|
{historySongs.length > 0 ? (
|
||||||
<ul className="flex flex-col border-b py-1">
|
<ul className="flex flex-col border-b py-1">
|
||||||
{historySongs.map((song) => (
|
{historySongs.map((song) => (
|
||||||
<HistorySongRow key={`history-${song.id}-${song.historyIndex}`} song={song} />
|
<HistorySongRow key={`history-${song.id}-${song.historyIndex}`} song={song} />
|
||||||
@@ -396,40 +401,42 @@ export function QueuePanel() {
|
|||||||
</ul>
|
</ul>
|
||||||
) : null}
|
) : null}
|
||||||
<ul className="flex flex-col py-1">
|
<ul className="flex flex-col py-1">
|
||||||
{selectableQueue.map((song, index) => (
|
{selectableQueue.map((item, index) =>
|
||||||
<QueueSongRow
|
item.song ? (
|
||||||
key={song.selectionId}
|
<QueueSongRow
|
||||||
ref={song.queueIndex === 0 ? nowPlayingRef : undefined}
|
key={item.selectionId}
|
||||||
song={song}
|
ref={item.queueIndex === 0 ? nowPlayingRef : undefined}
|
||||||
isNowPlaying={song.queueIndex === 0}
|
song={item.song}
|
||||||
selectionPosition={selectionPositions[index]}
|
isNowPlaying={item.queueIndex === 0}
|
||||||
isDragging={draggingIndices.has(index)}
|
selectionPosition={selectionPositions[index]}
|
||||||
onPointerDown={handlePointerDown}
|
isDragging={draggingIndices.has(index)}
|
||||||
onSelect={(event) => {
|
onPointerDown={handlePointerDown}
|
||||||
handleSelect(song.selectionId, index, event)
|
onSelect={(event) => {
|
||||||
}}
|
handleSelect(item.selectionId, index, event)
|
||||||
onSkipTo={() => void skipToQueueIndex(song.queueIndex)}
|
}}
|
||||||
onDragStart={(event) => {
|
onSkipTo={() => void skipToQueueIndex(item.queueIndex)}
|
||||||
setDragIndex(index)
|
onDragStart={(event) => {
|
||||||
event.dataTransfer.effectAllowed = "move"
|
setDragIndex(index)
|
||||||
}}
|
event.dataTransfer.effectAllowed = "move"
|
||||||
onDragOver={(event) => event.preventDefault()}
|
}}
|
||||||
onDrop={(event) => {
|
onDragOver={(event) => event.preventDefault()}
|
||||||
event.preventDefault()
|
onDrop={(event) => {
|
||||||
handleDrop(index)
|
event.preventDefault()
|
||||||
}}
|
handleDrop(index)
|
||||||
/>
|
}}
|
||||||
))}
|
/>
|
||||||
|
) : (
|
||||||
|
<QueueSongRowSkeleton key={item.selectionId} />
|
||||||
|
)
|
||||||
|
)}
|
||||||
</ul>
|
</ul>
|
||||||
{shouldPaginate ? (
|
{hasMore ? (
|
||||||
<div
|
<div
|
||||||
ref={loadMoreRef}
|
ref={loadMoreRef}
|
||||||
className="flex items-center justify-center py-4"
|
className="flex items-center justify-center py-4"
|
||||||
aria-hidden={status !== "LoadingMore"}
|
aria-hidden
|
||||||
>
|
>
|
||||||
{status === "LoadingMore" ? (
|
<Spinner className="size-5 text-muted-foreground" />
|
||||||
<Spinner className="size-5 text-muted-foreground" />
|
|
||||||
) : null}
|
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
export function SearchPrompt() {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-1 items-center justify-center px-6 pb-28">
|
||||||
|
<p className="text-center text-muted-foreground">
|
||||||
|
Search for songs, albums, artists, and playlists in your library.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -3,7 +3,6 @@
|
|||||||
import { useEffect, useMemo, useState, useRef, MouseEvent } from "react"
|
import { useEffect, useMemo, useState, useRef, MouseEvent } from "react"
|
||||||
import Image from "next/image"
|
import Image from "next/image"
|
||||||
import Link from "next/link"
|
import Link from "next/link"
|
||||||
import { usePaginatedQuery } from "convex/react"
|
|
||||||
import { ArrowUpDown, Play, Star } from "lucide-react"
|
import { ArrowUpDown, Play, Star } from "lucide-react"
|
||||||
|
|
||||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||||
@@ -23,9 +22,10 @@ import {
|
|||||||
DropdownMenuSeparator,
|
DropdownMenuSeparator,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "@/components/ui/dropdown-menu"
|
} from "@/components/ui/dropdown-menu"
|
||||||
|
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
|
||||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||||
import { useTrackSelection } from "@/hooks/use-track-selection"
|
import { useTrackSelection } from "@/hooks/use-track-selection"
|
||||||
import { LibraryLoading } from "@/components/library-loading"
|
import { SongListSkeleton } from "@/components/library-skeletons"
|
||||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||||
import { Spinner } from "@/components/ui/spinner"
|
import { Spinner } from "@/components/ui/spinner"
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
@@ -271,7 +271,7 @@ export function SongsView() {
|
|||||||
useState<SortDirection>("asc")
|
useState<SortDirection>("asc")
|
||||||
const loadMoreRef = useRef<HTMLDivElement>(null)
|
const loadMoreRef = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
const { results, status, loadMore } = usePaginatedQuery(
|
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
|
||||||
api.library.browseSongsPaginated,
|
api.library.browseSongsPaginated,
|
||||||
{ sortKey, sortDirection },
|
{ sortKey, sortDirection },
|
||||||
{ initialNumItems: SONGS_PAGE_SIZE }
|
{ initialNumItems: SONGS_PAGE_SIZE }
|
||||||
@@ -344,13 +344,13 @@ export function SongsView() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (status === "LoadingFirstPage") {
|
if (status === "LoadingFirstPage" && !isCached) {
|
||||||
return (
|
return (
|
||||||
<div className="flex h-svh flex-col">
|
<div className="flex h-svh flex-col">
|
||||||
<header className="flex items-center justify-between gap-2 border-b px-4 py-3">
|
<header className="flex items-center justify-between gap-2 border-b px-4 py-3">
|
||||||
<h1 className="text-lg font-semibold">Songs</h1>
|
<h1 className="text-lg font-semibold">Songs</h1>
|
||||||
</header>
|
</header>
|
||||||
<LibraryLoading />
|
<SongListSkeleton />
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import {
|
||||||
|
usePaginatedQuery,
|
||||||
|
useQuery,
|
||||||
|
type OptionalRestArgsOrSkip,
|
||||||
|
type PaginatedQueryArgs,
|
||||||
|
type PaginatedQueryItem,
|
||||||
|
type PaginatedQueryReference,
|
||||||
|
} from "convex/react"
|
||||||
|
import type { FunctionReference } from "convex/server"
|
||||||
|
import { useCallback, useEffect, useSyncExternalStore } from "react"
|
||||||
|
|
||||||
|
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||||
|
import { queryCacheKey } from "@/lib/cached-query"
|
||||||
|
import { readCache, subscribeCache, writeCache } from "@/lib/persistent-cache"
|
||||||
|
|
||||||
|
const MAX_CACHED_PAGINATED_ITEMS = 200
|
||||||
|
|
||||||
|
const noopUnsubscribe = () => {}
|
||||||
|
|
||||||
|
function useCachedValue<T>(key: string | null) {
|
||||||
|
const subscribe = useCallback(
|
||||||
|
(listener: () => void) =>
|
||||||
|
key ? subscribeCache(key, listener) : noopUnsubscribe,
|
||||||
|
[key]
|
||||||
|
)
|
||||||
|
return useSyncExternalStore(
|
||||||
|
subscribe,
|
||||||
|
() => (key ? readCache<T>(key) : undefined),
|
||||||
|
() => undefined
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `useQuery` that falls back to the last result persisted on this device while
|
||||||
|
* the live subscription is loading, so revisits render immediately.
|
||||||
|
*/
|
||||||
|
export function useCachedQuery<Query extends FunctionReference<"query">>(
|
||||||
|
query: Query,
|
||||||
|
...args: OptionalRestArgsOrSkip<Query>
|
||||||
|
): Query["_returnType"] | undefined {
|
||||||
|
const scope = useCacheScope()
|
||||||
|
const live = useQuery(query, ...args)
|
||||||
|
const queryArgs = args[0]
|
||||||
|
const key =
|
||||||
|
queryArgs === "skip"
|
||||||
|
? null
|
||||||
|
: queryCacheKey(
|
||||||
|
scope,
|
||||||
|
query,
|
||||||
|
(queryArgs ?? {}) as Record<string, unknown>
|
||||||
|
)
|
||||||
|
const cached = useCachedValue<Query["_returnType"]>(key)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (key && live !== undefined) {
|
||||||
|
writeCache(key, live)
|
||||||
|
}
|
||||||
|
}, [key, live])
|
||||||
|
|
||||||
|
return live !== undefined ? live : cached
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `usePaginatedQuery` that shows the first persisted pages while the first live
|
||||||
|
* page loads. `isCached` is true while those persisted results are shown.
|
||||||
|
*/
|
||||||
|
export function useCachedPaginatedQuery<Query extends PaginatedQueryReference>(
|
||||||
|
query: Query,
|
||||||
|
args: PaginatedQueryArgs<Query> | "skip",
|
||||||
|
options: { initialNumItems: number }
|
||||||
|
) {
|
||||||
|
const scope = useCacheScope()
|
||||||
|
const result = usePaginatedQuery(query, args, options)
|
||||||
|
const key =
|
||||||
|
args === "skip"
|
||||||
|
? null
|
||||||
|
: `${queryCacheKey(scope, query, args as Record<string, unknown>)}:pages`
|
||||||
|
const cached = useCachedValue<PaginatedQueryItem<Query>[]>(key)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (key && result.status !== "LoadingFirstPage") {
|
||||||
|
writeCache(key, result.results.slice(0, MAX_CACHED_PAGINATED_ITEMS))
|
||||||
|
}
|
||||||
|
}, [key, result.status, result.results])
|
||||||
|
|
||||||
|
if (result.status === "LoadingFirstPage" && cached !== undefined) {
|
||||||
|
return { ...result, results: cached, isCached: true }
|
||||||
|
}
|
||||||
|
return { ...result, isCached: false }
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import type { ConvexReactClient } from "convex/react"
|
||||||
|
import {
|
||||||
|
getFunctionName,
|
||||||
|
type FunctionArgs,
|
||||||
|
type FunctionReference,
|
||||||
|
type FunctionReturnType,
|
||||||
|
} from "convex/server"
|
||||||
|
import { convexToJson, type Value } from "convex/values"
|
||||||
|
|
||||||
|
import {
|
||||||
|
loadPersistentCache,
|
||||||
|
readCache,
|
||||||
|
writeCache,
|
||||||
|
} from "@/lib/persistent-cache"
|
||||||
|
|
||||||
|
export function queryCacheKey(
|
||||||
|
scope: string,
|
||||||
|
query: FunctionReference<"query">,
|
||||||
|
args: Record<string, unknown>
|
||||||
|
) {
|
||||||
|
return `q:${scope}:${getFunctionName(query)}:${JSON.stringify(
|
||||||
|
convexToJson(args as Value)
|
||||||
|
)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves from the persistent cache when possible and refreshes it in the
|
||||||
|
* background; only waits on the network for a cold cache.
|
||||||
|
*/
|
||||||
|
export async function fetchCachedQuery<
|
||||||
|
Query extends FunctionReference<"query">,
|
||||||
|
>(
|
||||||
|
convex: ConvexReactClient,
|
||||||
|
scope: string,
|
||||||
|
query: Query,
|
||||||
|
args: FunctionArgs<Query>
|
||||||
|
): Promise<FunctionReturnType<Query>> {
|
||||||
|
await loadPersistentCache()
|
||||||
|
const key = queryCacheKey(scope, query, args)
|
||||||
|
const cached = readCache<FunctionReturnType<Query>>(key)
|
||||||
|
const request = convex.query(query, args).then((result) => {
|
||||||
|
writeCache(key, result, { notify: true })
|
||||||
|
return result
|
||||||
|
})
|
||||||
|
|
||||||
|
if (cached !== undefined) {
|
||||||
|
request.catch(() => {})
|
||||||
|
return cached
|
||||||
|
}
|
||||||
|
return request
|
||||||
|
}
|
||||||
@@ -2,9 +2,25 @@ import { ConvexHttpClient } from "convex/browser"
|
|||||||
|
|
||||||
let client: ConvexHttpClient | null = null
|
let client: ConvexHttpClient | null = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* URL the Next.js server uses to reach Convex. Never derive this from request
|
||||||
|
* headers: auth tokens are sent to it, so a forged Host would leak them.
|
||||||
|
*/
|
||||||
|
export function getConvexServerUrl() {
|
||||||
|
return (
|
||||||
|
process.env.CONVEX_INTERNAL_URL ??
|
||||||
|
process.env.NEXT_PUBLIC_CONVEX_URL ??
|
||||||
|
"http://127.0.0.1:3210"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function convexServerOptions(token?: string) {
|
||||||
|
return { url: getConvexServerUrl(), token }
|
||||||
|
}
|
||||||
|
|
||||||
export function getConvexClient() {
|
export function getConvexClient() {
|
||||||
if (!client) {
|
if (!client) {
|
||||||
client = new ConvexHttpClient(process.env.NEXT_PUBLIC_CONVEX_URL!)
|
client = new ConvexHttpClient(getConvexServerUrl())
|
||||||
}
|
}
|
||||||
return client
|
return client
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,268 @@
|
|||||||
|
const DB_NAME = "otunes-cache"
|
||||||
|
const DB_VERSION = 1
|
||||||
|
const STORE_NAME = "entries"
|
||||||
|
const WRITE_DELAY_MS = 250
|
||||||
|
/** Keys are `<prefix>:<rest>`; prefixes without a limit are never evicted. */
|
||||||
|
const MAX_ENTRIES_BY_PREFIX: Record<string, number> = {
|
||||||
|
q: 400,
|
||||||
|
song: 5000,
|
||||||
|
}
|
||||||
|
|
||||||
|
type Entry = { value: unknown; touchedAt: number }
|
||||||
|
|
||||||
|
const memory = new Map<string, Entry>()
|
||||||
|
const prefixCounts = new Map<string, number>()
|
||||||
|
const listeners = new Map<string, Set<() => void>>()
|
||||||
|
const loadListeners = new Set<() => void>()
|
||||||
|
const pendingWrites = new Map<string, Entry | null>()
|
||||||
|
let flushTimer: ReturnType<typeof setTimeout> | null = null
|
||||||
|
let dbPromise: Promise<IDBDatabase | null> | null = null
|
||||||
|
let loadPromise: Promise<void> | null = null
|
||||||
|
let loaded = false
|
||||||
|
|
||||||
|
function requestToPromise<T>(request: IDBRequest<T>) {
|
||||||
|
return new Promise<T>((resolve, reject) => {
|
||||||
|
request.onsuccess = () => resolve(request.result)
|
||||||
|
request.onerror = () => reject(request.error)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function transactionDone(transaction: IDBTransaction) {
|
||||||
|
return new Promise<void>((resolve, reject) => {
|
||||||
|
transaction.oncomplete = () => resolve()
|
||||||
|
transaction.onabort = () => reject(transaction.error)
|
||||||
|
transaction.onerror = () => reject(transaction.error)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function openDb() {
|
||||||
|
if (dbPromise) {
|
||||||
|
return dbPromise
|
||||||
|
}
|
||||||
|
|
||||||
|
dbPromise = new Promise<IDBDatabase | null>((resolve) => {
|
||||||
|
if (typeof indexedDB === "undefined") {
|
||||||
|
resolve(null)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const request = indexedDB.open(DB_NAME, DB_VERSION)
|
||||||
|
request.onupgradeneeded = () => {
|
||||||
|
if (!request.result.objectStoreNames.contains(STORE_NAME)) {
|
||||||
|
request.result.createObjectStore(STORE_NAME)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
request.onsuccess = () => resolve(request.result)
|
||||||
|
request.onerror = () => resolve(null)
|
||||||
|
request.onblocked = () => resolve(null)
|
||||||
|
} catch {
|
||||||
|
resolve(null)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return dbPromise
|
||||||
|
}
|
||||||
|
|
||||||
|
function notify(key: string) {
|
||||||
|
for (const listener of listeners.get(key) ?? []) {
|
||||||
|
listener()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function notifyAll() {
|
||||||
|
for (const key of listeners.keys()) {
|
||||||
|
notify(key)
|
||||||
|
}
|
||||||
|
for (const listener of loadListeners) {
|
||||||
|
listener()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function flushWrites() {
|
||||||
|
flushTimer = null
|
||||||
|
if (pendingWrites.size === 0) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const writes = [...pendingWrites]
|
||||||
|
pendingWrites.clear()
|
||||||
|
|
||||||
|
const db = await openDb()
|
||||||
|
if (!db) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const transaction = db.transaction(STORE_NAME, "readwrite")
|
||||||
|
const store = transaction.objectStore(STORE_NAME)
|
||||||
|
for (const [key, entry] of writes) {
|
||||||
|
if (entry === null) {
|
||||||
|
store.delete(key)
|
||||||
|
} else {
|
||||||
|
store.put(entry, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await transactionDone(transaction)
|
||||||
|
} catch {
|
||||||
|
// Persisting is best-effort; the in-memory copy stays authoritative.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function scheduleWrite(key: string, entry: Entry | null) {
|
||||||
|
pendingWrites.set(key, entry)
|
||||||
|
if (flushTimer === null) {
|
||||||
|
flushTimer = setTimeout(() => void flushWrites(), WRITE_DELAY_MS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function entryPrefix(key: string) {
|
||||||
|
const index = key.indexOf(":")
|
||||||
|
return index === -1 ? key : key.slice(0, index)
|
||||||
|
}
|
||||||
|
|
||||||
|
function evictOldEntries(prefix: string, force = false) {
|
||||||
|
const limit = MAX_ENTRIES_BY_PREFIX[prefix]
|
||||||
|
const count = prefixCounts.get(prefix) ?? 0
|
||||||
|
if (limit === undefined || count <= (force ? limit : limit * 1.25)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldest = [...memory.entries()]
|
||||||
|
.filter(([key]) => entryPrefix(key) === prefix)
|
||||||
|
.sort(([, a], [, b]) => a.touchedAt - b.touchedAt)
|
||||||
|
.slice(0, count - limit)
|
||||||
|
|
||||||
|
for (const [key] of oldest) {
|
||||||
|
removeFromMemory(key)
|
||||||
|
scheduleWrite(key, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setInMemory(key: string, entry: Entry) {
|
||||||
|
if (!memory.has(key)) {
|
||||||
|
const prefix = entryPrefix(key)
|
||||||
|
prefixCounts.set(prefix, (prefixCounts.get(prefix) ?? 0) + 1)
|
||||||
|
}
|
||||||
|
memory.set(key, entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeFromMemory(key: string) {
|
||||||
|
if (memory.delete(key)) {
|
||||||
|
const prefix = entryPrefix(key)
|
||||||
|
prefixCounts.set(prefix, (prefixCounts.get(prefix) ?? 1) - 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Writes pending entries now instead of after the batching delay. */
|
||||||
|
export function flushPersistentCache() {
|
||||||
|
if (flushTimer !== null) {
|
||||||
|
clearTimeout(flushTimer)
|
||||||
|
}
|
||||||
|
void flushWrites()
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadPersistentCache() {
|
||||||
|
if (loadPromise) {
|
||||||
|
return loadPromise
|
||||||
|
}
|
||||||
|
|
||||||
|
loadPromise = (async () => {
|
||||||
|
const db = await openDb()
|
||||||
|
if (db) {
|
||||||
|
try {
|
||||||
|
const transaction = db.transaction(STORE_NAME, "readonly")
|
||||||
|
const store = transaction.objectStore(STORE_NAME)
|
||||||
|
const [keys, values] = await Promise.all([
|
||||||
|
requestToPromise(store.getAllKeys()),
|
||||||
|
requestToPromise(store.getAll() as IDBRequest<Entry[]>),
|
||||||
|
])
|
||||||
|
keys.forEach((key, index) => {
|
||||||
|
const entry = values[index]
|
||||||
|
if (typeof key === "string" && entry && !memory.has(key)) {
|
||||||
|
setInMemory(key, entry)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
for (const prefix of Object.keys(MAX_ENTRIES_BY_PREFIX)) {
|
||||||
|
evictOldEntries(prefix, true)
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Treat an unreadable cache as empty.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
loaded = true
|
||||||
|
notifyAll()
|
||||||
|
})()
|
||||||
|
|
||||||
|
return loadPromise
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isPersistentCacheLoaded() {
|
||||||
|
return loaded
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readCache<T>(key: string): T | undefined {
|
||||||
|
return memory.get(key)?.value as T | undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
export function writeCache(
|
||||||
|
key: string,
|
||||||
|
value: unknown,
|
||||||
|
options: { notify?: boolean } = {}
|
||||||
|
) {
|
||||||
|
const entry = { value, touchedAt: Date.now() }
|
||||||
|
setInMemory(key, entry)
|
||||||
|
scheduleWrite(key, entry)
|
||||||
|
evictOldEntries(entryPrefix(key))
|
||||||
|
if (options.notify) {
|
||||||
|
notify(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function clearPersistentCache() {
|
||||||
|
memory.clear()
|
||||||
|
prefixCounts.clear()
|
||||||
|
pendingWrites.clear()
|
||||||
|
if (flushTimer !== null) {
|
||||||
|
clearTimeout(flushTimer)
|
||||||
|
flushTimer = null
|
||||||
|
}
|
||||||
|
notifyAll()
|
||||||
|
|
||||||
|
const db = await openDb()
|
||||||
|
if (!db) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const transaction = db.transaction(STORE_NAME, "readwrite")
|
||||||
|
transaction.objectStore(STORE_NAME).clear()
|
||||||
|
await transactionDone(transaction)
|
||||||
|
} catch {
|
||||||
|
// Ignore; stale entries are scoped per user and evicted over time.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subscribeCache(key: string, listener: () => void) {
|
||||||
|
let keyListeners = listeners.get(key)
|
||||||
|
if (!keyListeners) {
|
||||||
|
keyListeners = new Set()
|
||||||
|
listeners.set(key, keyListeners)
|
||||||
|
}
|
||||||
|
keyListeners.add(listener)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
keyListeners.delete(listener)
|
||||||
|
if (keyListeners.size === 0) {
|
||||||
|
listeners.delete(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subscribeCacheLoaded(listener: () => void) {
|
||||||
|
loadListeners.add(listener)
|
||||||
|
return () => {
|
||||||
|
loadListeners.delete(listener)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
|
import { shuffleArray } from "@/lib/shuffle-array"
|
||||||
|
|
||||||
|
/** Mirrors the queue rules in `packages/convex/convex/playback.ts`. */
|
||||||
|
|
||||||
|
export type RepeatMode = "none" | "once" | "always"
|
||||||
|
|
||||||
|
export type PlaybackQueueState = {
|
||||||
|
queue: Id<"songs">[]
|
||||||
|
history: Id<"songs">[]
|
||||||
|
shuffleEnabled: boolean
|
||||||
|
repeatEnabled: RepeatMode
|
||||||
|
/** Saved position of `queue[0]`, in seconds. */
|
||||||
|
progressSeconds: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export const EMPTY_PLAYBACK_QUEUE: PlaybackQueueState = {
|
||||||
|
queue: [],
|
||||||
|
history: [],
|
||||||
|
shuffleEnabled: false,
|
||||||
|
repeatEnabled: "none",
|
||||||
|
progressSeconds: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_QUEUE_HISTORY = 30
|
||||||
|
|
||||||
|
function uniqueSongIds(songIds: Id<"songs">[]) {
|
||||||
|
return [...new Set(songIds)]
|
||||||
|
}
|
||||||
|
|
||||||
|
function appendToHistory(history: Id<"songs">[], songIds: Id<"songs">[]) {
|
||||||
|
const next = [...history, ...songIds]
|
||||||
|
return next.length <= MAX_QUEUE_HISTORY
|
||||||
|
? next
|
||||||
|
: next.slice(next.length - MAX_QUEUE_HISTORY)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function startQueue(
|
||||||
|
state: PlaybackQueueState,
|
||||||
|
songIds: Id<"songs">[],
|
||||||
|
shuffled: boolean
|
||||||
|
): PlaybackQueueState {
|
||||||
|
const unique = uniqueSongIds(songIds)
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
queue: shuffled ? shuffleArray(unique) : unique,
|
||||||
|
history: [],
|
||||||
|
shuffleEnabled: shuffled,
|
||||||
|
progressSeconds: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function startQueueFromSong(
|
||||||
|
state: PlaybackQueueState,
|
||||||
|
songId: Id<"songs">,
|
||||||
|
songIds: Id<"songs">[]
|
||||||
|
): PlaybackQueueState {
|
||||||
|
const index = songIds.indexOf(songId)
|
||||||
|
const rest = index === -1 ? [] : songIds.slice(index + 1)
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
queue: [songId, ...(state.shuffleEnabled ? shuffleArray(rest) : rest)],
|
||||||
|
history: [],
|
||||||
|
progressSeconds: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fills in the rest of a queue started with only `songId`, unless the queue
|
||||||
|
* changed in the meantime.
|
||||||
|
*/
|
||||||
|
export function extendQueueFromSong(
|
||||||
|
state: PlaybackQueueState,
|
||||||
|
songId: Id<"songs">,
|
||||||
|
songIds: Id<"songs">[]
|
||||||
|
): PlaybackQueueState {
|
||||||
|
if (state.queue.length !== 1 || state.queue[0] !== songId) {
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
const { queue } = startQueueFromSong(state, songId, songIds)
|
||||||
|
return queue.length > 1 ? { ...state, queue } : state
|
||||||
|
}
|
||||||
|
|
||||||
|
export function addToQueue(
|
||||||
|
state: PlaybackQueueState,
|
||||||
|
songIds: Id<"songs">[],
|
||||||
|
position: "next" | "last"
|
||||||
|
): PlaybackQueueState {
|
||||||
|
const toAdd = state.shuffleEnabled ? shuffleArray(songIds) : songIds
|
||||||
|
if (state.queue.length === 0) {
|
||||||
|
return { ...state, queue: toAdd, progressSeconds: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
const [current, ...rest] = state.queue
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
queue:
|
||||||
|
position === "next"
|
||||||
|
? [current, ...toAdd, ...rest]
|
||||||
|
: [...state.queue, ...toAdd],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toggleShuffle(state: PlaybackQueueState): PlaybackQueueState {
|
||||||
|
const shuffleEnabled = !state.shuffleEnabled
|
||||||
|
if (shuffleEnabled && state.queue.length > 1) {
|
||||||
|
const [current, ...upNext] = state.queue
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
shuffleEnabled,
|
||||||
|
queue: [current, ...shuffleArray(upNext)],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { ...state, shuffleEnabled }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cycleRepeat(state: PlaybackQueueState): PlaybackQueueState {
|
||||||
|
const repeatEnabled: RepeatMode =
|
||||||
|
state.repeatEnabled === "none"
|
||||||
|
? "once"
|
||||||
|
: state.repeatEnabled === "once"
|
||||||
|
? "always"
|
||||||
|
: "none"
|
||||||
|
return { ...state, repeatEnabled }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearQueue(state: PlaybackQueueState): PlaybackQueueState {
|
||||||
|
return { ...state, queue: [], history: [], progressSeconds: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function reorderQueue(
|
||||||
|
state: PlaybackQueueState,
|
||||||
|
songIds: Id<"songs">[]
|
||||||
|
): PlaybackQueueState {
|
||||||
|
const currentSongChanged =
|
||||||
|
songIds.length > 0 &&
|
||||||
|
state.queue.length > 0 &&
|
||||||
|
songIds[0] !== state.queue[0]
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
queue: songIds,
|
||||||
|
history: currentSongChanged
|
||||||
|
? appendToHistory(state.history, [state.queue[0]])
|
||||||
|
: state.history,
|
||||||
|
progressSeconds: currentSongChanged ? 0 : state.progressSeconds,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function skipToQueueIndex(
|
||||||
|
state: PlaybackQueueState,
|
||||||
|
index: number
|
||||||
|
): PlaybackQueueState {
|
||||||
|
if (index <= 0 || index >= state.queue.length) {
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
queue: state.queue.slice(index),
|
||||||
|
history: appendToHistory(state.history, state.queue.slice(0, index)),
|
||||||
|
progressSeconds: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function skipNext(state: PlaybackQueueState): PlaybackQueueState {
|
||||||
|
if (state.queue.length === 0) {
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
if (state.repeatEnabled === "once") {
|
||||||
|
return { ...state, progressSeconds: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
const [current, ...rest] = state.queue
|
||||||
|
if (state.repeatEnabled === "always") {
|
||||||
|
return { ...state, queue: [...rest, current], progressSeconds: 0 }
|
||||||
|
}
|
||||||
|
if (rest.length === 0) {
|
||||||
|
return { ...state, progressSeconds: 0 }
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
queue: rest,
|
||||||
|
history: appendToHistory(state.history, [current]),
|
||||||
|
progressSeconds: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function skipPrevious(state: PlaybackQueueState): PlaybackQueueState {
|
||||||
|
if (state.queue.length === 0) {
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
if (state.history.length === 0) {
|
||||||
|
return { ...state, progressSeconds: 0 }
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
queue: [state.history[state.history.length - 1], ...state.queue],
|
||||||
|
history: state.history.slice(0, -1),
|
||||||
|
progressSeconds: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,274 @@
|
|||||||
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
|
import {
|
||||||
|
EMPTY_PLAYBACK_QUEUE,
|
||||||
|
type PlaybackQueueState,
|
||||||
|
type RepeatMode,
|
||||||
|
} from "@/lib/playback-queue"
|
||||||
|
import {
|
||||||
|
loadPersistentCache,
|
||||||
|
readCache,
|
||||||
|
writeCache,
|
||||||
|
} from "@/lib/persistent-cache"
|
||||||
|
|
||||||
|
const SYNC_DELAY_MS = 300
|
||||||
|
const RETRY_DELAYS_MS = [1_000, 3_000, 10_000, 30_000]
|
||||||
|
|
||||||
|
export type ServerPlaybackState = {
|
||||||
|
queueSongIds: Id<"songs">[]
|
||||||
|
queueHistorySongIds: Id<"songs">[]
|
||||||
|
shuffleEnabled: boolean
|
||||||
|
repeatEnabled: RepeatMode
|
||||||
|
currentSongProgress: number
|
||||||
|
revision: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Everything except progress, which changes too often to re-render on. */
|
||||||
|
export type PlaybackSnapshot = Omit<PlaybackQueueState, "progressSeconds"> & {
|
||||||
|
hydrated: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
type PersistedPlayback = PlaybackQueueState & {
|
||||||
|
/** Server revision the local state was last reconciled with. */
|
||||||
|
revision: number | null
|
||||||
|
/** Local changes that the server has not acknowledged yet. */
|
||||||
|
dirty: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PlaybackSyncTransport = (
|
||||||
|
state: PlaybackQueueState
|
||||||
|
) => Promise<number>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Client-owned playback queue. Changes apply locally (and persist on this
|
||||||
|
* device) immediately, then sync to Convex in the background. Remote changes
|
||||||
|
* are adopted only when there are no unsynced local changes.
|
||||||
|
*/
|
||||||
|
export class PlaybackStore {
|
||||||
|
private state: PlaybackQueueState = EMPTY_PLAYBACK_QUEUE
|
||||||
|
private snapshot: PlaybackSnapshot = toSnapshot(EMPTY_PLAYBACK_QUEUE, false)
|
||||||
|
private revision: number | null = null
|
||||||
|
private dirty = false
|
||||||
|
private changeCount = 0
|
||||||
|
private inFlight = false
|
||||||
|
private retryAttempt = 0
|
||||||
|
private syncTimer: ReturnType<typeof setTimeout> | null = null
|
||||||
|
private latestServerState: ServerPlaybackState | null = null
|
||||||
|
private transport: PlaybackSyncTransport | null = null
|
||||||
|
private readonly listeners = new Set<() => void>()
|
||||||
|
|
||||||
|
constructor(private readonly storageKey: string | null) {
|
||||||
|
if (typeof window !== "undefined") {
|
||||||
|
void this.hydrate()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
subscribe = (listener: () => void) => {
|
||||||
|
this.listeners.add(listener)
|
||||||
|
return () => {
|
||||||
|
this.listeners.delete(listener)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getSnapshot = () => this.snapshot
|
||||||
|
|
||||||
|
getState() {
|
||||||
|
return this.state
|
||||||
|
}
|
||||||
|
|
||||||
|
setTransport(transport: PlaybackSyncTransport | null) {
|
||||||
|
this.transport = transport
|
||||||
|
if (transport && this.dirty) {
|
||||||
|
this.scheduleSync(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
update(recipe: (state: PlaybackQueueState) => PlaybackQueueState) {
|
||||||
|
const next = recipe(this.state)
|
||||||
|
if (next === this.state) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
this.changeCount += 1
|
||||||
|
this.dirty = true
|
||||||
|
this.setState(next)
|
||||||
|
this.scheduleSync(SYNC_DELAY_MS)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Records progress locally; the server copy is synced separately. */
|
||||||
|
setProgress(songId: Id<"songs">, progressSeconds: number) {
|
||||||
|
if (this.state.queue[0] !== songId) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.state = { ...this.state, progressSeconds }
|
||||||
|
this.persist()
|
||||||
|
}
|
||||||
|
|
||||||
|
receiveServerState(serverState: ServerPlaybackState) {
|
||||||
|
this.latestServerState = serverState
|
||||||
|
if (this.snapshot.hydrated) {
|
||||||
|
this.adoptServerState()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async hydrate() {
|
||||||
|
await loadPersistentCache()
|
||||||
|
const persisted = this.storageKey
|
||||||
|
? readCache<PersistedPlayback>(this.storageKey)
|
||||||
|
: undefined
|
||||||
|
|
||||||
|
if (persisted && this.changeCount === 0) {
|
||||||
|
const { revision, dirty, ...state } = persisted
|
||||||
|
this.revision = revision
|
||||||
|
this.dirty = dirty
|
||||||
|
this.state = { ...EMPTY_PLAYBACK_QUEUE, ...state }
|
||||||
|
}
|
||||||
|
|
||||||
|
this.snapshot = toSnapshot(this.state, true)
|
||||||
|
this.emit()
|
||||||
|
this.adoptServerState()
|
||||||
|
if (this.dirty) {
|
||||||
|
this.scheduleSync(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private adoptServerState() {
|
||||||
|
const serverState = this.latestServerState
|
||||||
|
if (!serverState || this.dirty || this.inFlight) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (this.revision !== null && serverState.revision <= this.revision) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
this.revision = serverState.revision
|
||||||
|
this.setState({
|
||||||
|
queue: serverState.queueSongIds,
|
||||||
|
history: serverState.queueHistorySongIds,
|
||||||
|
shuffleEnabled: serverState.shuffleEnabled,
|
||||||
|
repeatEnabled: serverState.repeatEnabled,
|
||||||
|
progressSeconds: serverState.currentSongProgress,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private scheduleSync(delayMs: number) {
|
||||||
|
if (this.syncTimer !== null) {
|
||||||
|
clearTimeout(this.syncTimer)
|
||||||
|
}
|
||||||
|
this.syncTimer = setTimeout(() => {
|
||||||
|
this.syncTimer = null
|
||||||
|
void this.flush()
|
||||||
|
}, delayMs)
|
||||||
|
}
|
||||||
|
|
||||||
|
private async flush() {
|
||||||
|
const transport = this.transport
|
||||||
|
if (!transport || this.inFlight || !this.dirty) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
this.inFlight = true
|
||||||
|
const changeCountAtStart = this.changeCount
|
||||||
|
let failed = false
|
||||||
|
|
||||||
|
try {
|
||||||
|
const revision = await transport(this.state)
|
||||||
|
this.revision = Math.max(revision, this.revision ?? 0)
|
||||||
|
this.retryAttempt = 0
|
||||||
|
if (this.changeCount === changeCountAtStart) {
|
||||||
|
this.dirty = false
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
failed = true
|
||||||
|
} finally {
|
||||||
|
this.inFlight = false
|
||||||
|
}
|
||||||
|
|
||||||
|
this.persist()
|
||||||
|
|
||||||
|
if (failed) {
|
||||||
|
const delay =
|
||||||
|
RETRY_DELAYS_MS[Math.min(this.retryAttempt, RETRY_DELAYS_MS.length - 1)]
|
||||||
|
this.retryAttempt += 1
|
||||||
|
this.scheduleSync(delay)
|
||||||
|
} else if (this.dirty) {
|
||||||
|
this.scheduleSync(SYNC_DELAY_MS)
|
||||||
|
} else {
|
||||||
|
this.adoptServerState()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private setState(state: PlaybackQueueState) {
|
||||||
|
const previous = this.state
|
||||||
|
this.state = state
|
||||||
|
this.persist()
|
||||||
|
|
||||||
|
if (
|
||||||
|
previous.queue !== state.queue ||
|
||||||
|
previous.history !== state.history ||
|
||||||
|
previous.shuffleEnabled !== state.shuffleEnabled ||
|
||||||
|
previous.repeatEnabled !== state.repeatEnabled
|
||||||
|
) {
|
||||||
|
this.snapshot = toSnapshot(state, this.snapshot.hydrated)
|
||||||
|
this.emit()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private persist() {
|
||||||
|
if (!this.storageKey) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeCache(this.storageKey, {
|
||||||
|
...this.state,
|
||||||
|
revision: this.revision,
|
||||||
|
dirty: this.dirty,
|
||||||
|
} satisfies PersistedPlayback)
|
||||||
|
}
|
||||||
|
|
||||||
|
private emit() {
|
||||||
|
for (const listener of this.listeners) {
|
||||||
|
listener()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toSnapshot(
|
||||||
|
state: PlaybackQueueState,
|
||||||
|
hydrated: boolean
|
||||||
|
): PlaybackSnapshot {
|
||||||
|
return {
|
||||||
|
queue: state.queue,
|
||||||
|
history: state.history,
|
||||||
|
shuffleEnabled: state.shuffleEnabled,
|
||||||
|
repeatEnabled: state.repeatEnabled,
|
||||||
|
hydrated,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const SERVER_SNAPSHOT = toSnapshot(EMPTY_PLAYBACK_QUEUE, false)
|
||||||
|
|
||||||
|
export function getServerPlaybackSnapshot() {
|
||||||
|
return SERVER_SNAPSHOT
|
||||||
|
}
|
||||||
|
|
||||||
|
const stores = new Map<string, PlaybackStore>()
|
||||||
|
|
||||||
|
export function getPlaybackStore(scope: string | null) {
|
||||||
|
if (typeof window === "undefined") {
|
||||||
|
return new PlaybackStore(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
const key = scope ?? ""
|
||||||
|
let store = stores.get(key)
|
||||||
|
if (!store) {
|
||||||
|
store = new PlaybackStore(scope ? `playback:${scope}` : null)
|
||||||
|
stores.set(key, store)
|
||||||
|
}
|
||||||
|
return store
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resetPlaybackStores() {
|
||||||
|
for (const store of stores.values()) {
|
||||||
|
store.setTransport(null)
|
||||||
|
}
|
||||||
|
stores.clear()
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
import { useConvex, type ConvexReactClient } from "convex/react"
|
||||||
|
import { useEffect, useMemo, useSyncExternalStore } from "react"
|
||||||
|
|
||||||
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
|
import type { BrowseAlbumDetail, BrowseSong } from "@otunes/convex/types"
|
||||||
|
import {
|
||||||
|
isPersistentCacheLoaded,
|
||||||
|
readCache,
|
||||||
|
subscribeCacheLoaded,
|
||||||
|
writeCache,
|
||||||
|
} from "@/lib/persistent-cache"
|
||||||
|
|
||||||
|
const FETCH_BATCH_SIZE = 100
|
||||||
|
const FETCH_DELAY_MS = 16
|
||||||
|
|
||||||
|
const listeners = new Set<() => void>()
|
||||||
|
const missingSongIds = new Set<string>()
|
||||||
|
const inFlightSongIds = new Set<string>()
|
||||||
|
const queuedSongIds = new Set<Id<"songs">>()
|
||||||
|
let version = 0
|
||||||
|
let fetchTimer: ReturnType<typeof setTimeout> | null = null
|
||||||
|
|
||||||
|
function songKey(songId: string) {
|
||||||
|
return `song:${songId}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function notify() {
|
||||||
|
version += 1
|
||||||
|
for (const listener of listeners) {
|
||||||
|
listener()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof window !== "undefined") {
|
||||||
|
subscribeCacheLoaded(notify)
|
||||||
|
}
|
||||||
|
|
||||||
|
function subscribe(listener: () => void) {
|
||||||
|
listeners.add(listener)
|
||||||
|
return () => {
|
||||||
|
listeners.delete(listener)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function sameSong(a: BrowseSong, b: BrowseSong) {
|
||||||
|
return (
|
||||||
|
a.title === b.title &&
|
||||||
|
a.durationSeconds === b.durationSeconds &&
|
||||||
|
a.explicit === b.explicit &&
|
||||||
|
a.artist.id === b.artist.id &&
|
||||||
|
a.artist.name === b.artist.name &&
|
||||||
|
a.artist.photo === b.artist.photo &&
|
||||||
|
a.album.id === b.album.id &&
|
||||||
|
a.album.title === b.album.title &&
|
||||||
|
a.album.cover === b.album.cover
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCachedSong(songId: string) {
|
||||||
|
return readCache<BrowseSong>(songKey(songId))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stores song metadata so the player and queue can render it offline. */
|
||||||
|
export function rememberSongs(songs: readonly BrowseSong[]) {
|
||||||
|
let changed = false
|
||||||
|
for (const song of songs) {
|
||||||
|
const existing = getCachedSong(song.id)
|
||||||
|
if (existing && sameSong(existing, song)) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
writeCache(songKey(song.id), song)
|
||||||
|
missingSongIds.delete(song.id)
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
if (changed) {
|
||||||
|
notify()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function albumDetailSongs(album: BrowseAlbumDetail): BrowseSong[] {
|
||||||
|
return album.tracks.map((track) => ({
|
||||||
|
id: track.id,
|
||||||
|
title: track.title,
|
||||||
|
artist: album.artist,
|
||||||
|
album: { id: album.id, title: album.title, cover: album.cover },
|
||||||
|
durationSeconds: track.durationSeconds,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchQueuedSongs(convex: ConvexReactClient) {
|
||||||
|
fetchTimer = null
|
||||||
|
const ids = [...queuedSongIds]
|
||||||
|
queuedSongIds.clear()
|
||||||
|
|
||||||
|
for (let start = 0; start < ids.length; start += FETCH_BATCH_SIZE) {
|
||||||
|
const batch = ids.slice(start, start + FETCH_BATCH_SIZE)
|
||||||
|
try {
|
||||||
|
const songs = await convex.query(api.library.browseSongsByIds, {
|
||||||
|
ids: batch,
|
||||||
|
})
|
||||||
|
const found = new Set(songs.map((song) => song.id as string))
|
||||||
|
for (const id of batch) {
|
||||||
|
if (!found.has(id)) {
|
||||||
|
missingSongIds.add(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rememberSongs(songs)
|
||||||
|
} catch {
|
||||||
|
// Leave them uncached so a later render retries.
|
||||||
|
} finally {
|
||||||
|
for (const id of batch) {
|
||||||
|
inFlightSongIds.delete(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
notify()
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestSongs(convex: ConvexReactClient, songIds: Id<"songs">[]) {
|
||||||
|
for (const songId of songIds) {
|
||||||
|
if (
|
||||||
|
getCachedSong(songId) ||
|
||||||
|
missingSongIds.has(songId) ||
|
||||||
|
inFlightSongIds.has(songId)
|
||||||
|
) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
inFlightSongIds.add(songId)
|
||||||
|
queuedSongIds.add(songId)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (queuedSongIds.size > 0 && fetchTimer === null) {
|
||||||
|
fetchTimer = setTimeout(() => void fetchQueuedSongs(convex), FETCH_DELAY_MS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves song metadata from the persistent song cache, fetching anything
|
||||||
|
* missing in batches. Entries are `undefined` until loaded.
|
||||||
|
*/
|
||||||
|
export function useSongs(songIds: readonly Id<"songs">[]) {
|
||||||
|
const convex = useConvex()
|
||||||
|
const songsVersion = useSyncExternalStore(
|
||||||
|
subscribe,
|
||||||
|
() => version,
|
||||||
|
() => 0
|
||||||
|
)
|
||||||
|
|
||||||
|
const songs = useMemo(
|
||||||
|
() => songIds.map((songId) => getCachedSong(songId)),
|
||||||
|
// songsVersion invalidates the lookup when the cache changes.
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
[songIds, songsVersion]
|
||||||
|
)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isPersistentCacheLoaded()) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const missing = songIds.filter((songId, index) => !songs[index])
|
||||||
|
if (missing.length > 0) {
|
||||||
|
requestSongs(convex, missing)
|
||||||
|
}
|
||||||
|
}, [convex, songIds, songs])
|
||||||
|
|
||||||
|
return songs
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useSong(songId: Id<"songs"> | null) {
|
||||||
|
const songIds = useMemo(() => (songId ? [songId] : []), [songId])
|
||||||
|
return useSongs(songIds)[0] ?? null
|
||||||
|
}
|
||||||
@@ -4,6 +4,13 @@ import type { NextConfig } from "next"
|
|||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
output: "standalone",
|
output: "standalone",
|
||||||
outputFileTracingRoot: path.join(__dirname, "../../"),
|
outputFileTracingRoot: path.join(__dirname, "../../"),
|
||||||
|
experimental: {
|
||||||
|
// App pages render their data from the client cache, so reusing a visited
|
||||||
|
// page's server payload is safe and skips a round trip on revisits.
|
||||||
|
staleTimes: {
|
||||||
|
dynamic: 300,
|
||||||
|
},
|
||||||
|
},
|
||||||
images: {
|
images: {
|
||||||
minimumCacheTTL: 60,
|
minimumCacheTTL: 60,
|
||||||
dangerouslyAllowSVG: true,
|
dangerouslyAllowSVG: true,
|
||||||
|
|||||||
+16
-12
@@ -3,6 +3,7 @@ import {
|
|||||||
createRouteMatcher,
|
createRouteMatcher,
|
||||||
nextjsMiddlewareRedirect,
|
nextjsMiddlewareRedirect,
|
||||||
} from "@convex-dev/auth/nextjs/server"
|
} from "@convex-dev/auth/nextjs/server"
|
||||||
|
import { getConvexServerUrl } from "@/lib/convex-server"
|
||||||
|
|
||||||
const isAuthPage = createRouteMatcher(["/signin", "/signup"])
|
const isAuthPage = createRouteMatcher(["/signin", "/signup"])
|
||||||
const isPublic = createRouteMatcher([
|
const isPublic = createRouteMatcher([
|
||||||
@@ -15,21 +16,24 @@ const isPublic = createRouteMatcher([
|
|||||||
"/playlist/:id",
|
"/playlist/:id",
|
||||||
])
|
])
|
||||||
|
|
||||||
export default convexAuthNextjsMiddleware(async (request, { convexAuth }) => {
|
export default convexAuthNextjsMiddleware(
|
||||||
if (isPublic(request)) {
|
async (request, { convexAuth }) => {
|
||||||
return
|
if (isPublic(request)) {
|
||||||
}
|
return
|
||||||
|
}
|
||||||
|
|
||||||
const authenticated = await convexAuth.isAuthenticated()
|
const authenticated = await convexAuth.isAuthenticated()
|
||||||
|
|
||||||
if (isAuthPage(request) && authenticated) {
|
if (isAuthPage(request) && authenticated) {
|
||||||
return nextjsMiddlewareRedirect(request, "/")
|
return nextjsMiddlewareRedirect(request, "/")
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!isAuthPage(request) && !authenticated) {
|
if (!isAuthPage(request) && !authenticated) {
|
||||||
return nextjsMiddlewareRedirect(request, "/signin")
|
return nextjsMiddlewareRedirect(request, "/signin")
|
||||||
}
|
}
|
||||||
})
|
},
|
||||||
|
{ convexUrl: getConvexServerUrl() }
|
||||||
|
)
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
|
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
|
||||||
|
|||||||
@@ -0,0 +1,115 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Runs the Convex backend and the oTunes web server in one container.
|
||||||
|
#
|
||||||
|
# Every secret is generated on first boot and kept in /convex/data:
|
||||||
|
# - the Convex instance secret (by the upstream read_credentials.sh)
|
||||||
|
# - the Convex Auth signing keys (stored as Convex environment variables)
|
||||||
|
# The admin key is derived from the instance secret on each boot, used to deploy
|
||||||
|
# the bundled functions, and never exported to the web server.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
NODE=/opt/node/bin/node
|
||||||
|
CONVEX_DATA_DIR=/convex/data
|
||||||
|
FUNCTIONS_DIR=/opt/otunes/convex/packages/convex
|
||||||
|
BACKEND_URL=http://127.0.0.1:3210
|
||||||
|
|
||||||
|
: "${CONVEX_CLOUD_ORIGIN:=http://127.0.0.1:3210}"
|
||||||
|
: "${CONVEX_SITE_ORIGIN:=http://127.0.0.1:3211}"
|
||||||
|
: "${APPLICATION_MAX_CONCURRENT_MUTATIONS:=16}"
|
||||||
|
: "${APPLICATION_MAX_CONCURRENT_NODE_ACTIONS:=16}"
|
||||||
|
: "${APPLICATION_MAX_CONCURRENT_QUERIES:=16}"
|
||||||
|
: "${APPLICATION_MAX_CONCURRENT_V8_ACTIONS:=16}"
|
||||||
|
: "${DISABLE_BEACON:=true}"
|
||||||
|
: "${DISABLE_METRICS_ENDPOINT:=true}"
|
||||||
|
: "${DOCUMENT_RETENTION_DELAY:=172800}"
|
||||||
|
: "${DO_NOT_REQUIRE_SSL:=true}"
|
||||||
|
: "${REDACT_LOGS_TO_CLIENT:=true}"
|
||||||
|
: "${RUST_LOG:=info}"
|
||||||
|
export CONVEX_CLOUD_ORIGIN CONVEX_SITE_ORIGIN \
|
||||||
|
APPLICATION_MAX_CONCURRENT_MUTATIONS APPLICATION_MAX_CONCURRENT_NODE_ACTIONS \
|
||||||
|
APPLICATION_MAX_CONCURRENT_QUERIES APPLICATION_MAX_CONCURRENT_V8_ACTIONS \
|
||||||
|
DISABLE_BEACON DISABLE_METRICS_ENDPOINT DOCUMENT_RETENTION_DELAY \
|
||||||
|
DO_NOT_REQUIRE_SSL REDACT_LOGS_TO_CLIENT RUST_LOG
|
||||||
|
|
||||||
|
backend_pid=""
|
||||||
|
web_pid=""
|
||||||
|
|
||||||
|
log() {
|
||||||
|
echo "[otunes] $*"
|
||||||
|
}
|
||||||
|
|
||||||
|
stop() {
|
||||||
|
trap - TERM INT
|
||||||
|
if [ -n "$web_pid" ]; then kill -TERM "$web_pid" 2>/dev/null || true; fi
|
||||||
|
if [ -n "$backend_pid" ]; then kill -INT "$backend_pid" 2>/dev/null || true; fi
|
||||||
|
wait || true
|
||||||
|
}
|
||||||
|
trap 'stop; exit 0' TERM INT
|
||||||
|
|
||||||
|
convex_cli() {
|
||||||
|
(
|
||||||
|
cd "$FUNCTIONS_DIR"
|
||||||
|
unset CONVEX_DEPLOYMENT CONVEX_DEPLOY_KEY
|
||||||
|
CONVEX_SELF_HOSTED_URL="$BACKEND_URL" \
|
||||||
|
CONVEX_SELF_HOSTED_ADMIN_KEY="$admin_key" \
|
||||||
|
"$NODE" node_modules/convex/bin/main.js "$@"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
# Only root (the backend) may read the database and instance secret.
|
||||||
|
mkdir -p "$CONVEX_DATA_DIR"
|
||||||
|
chmod 700 "$CONVEX_DATA_DIR"
|
||||||
|
|
||||||
|
log "Starting Convex backend"
|
||||||
|
(cd /convex && umask 077 && exec ./run_backend.sh) &
|
||||||
|
backend_pid=$!
|
||||||
|
|
||||||
|
for _ in $(seq 1 120); do
|
||||||
|
if curl -fsS "$BACKEND_URL/version" >/dev/null 2>&1; then
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
if ! kill -0 "$backend_pid" 2>/dev/null; then
|
||||||
|
log "Convex backend exited during startup"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
sleep 0.5
|
||||||
|
done
|
||||||
|
if ! curl -fsS "$BACKEND_URL/version" >/dev/null 2>&1; then
|
||||||
|
log "Convex backend did not become ready"
|
||||||
|
stop
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
admin_key=$(cd /convex && ./generate_admin_key.sh)
|
||||||
|
|
||||||
|
log "Deploying Convex functions"
|
||||||
|
convex_cli deploy --typecheck disable --codegen disable
|
||||||
|
|
||||||
|
if [ -z "$(convex_cli env get JWKS 2>/dev/null || true)" ]; then
|
||||||
|
log "Generating Convex Auth signing keys"
|
||||||
|
"$NODE" /opt/otunes/generate-auth-keys.mjs | convex_cli env set --force
|
||||||
|
fi
|
||||||
|
|
||||||
|
unset admin_key
|
||||||
|
|
||||||
|
log "Starting web server"
|
||||||
|
(
|
||||||
|
cd /app
|
||||||
|
export HOME=/app NODE_ENV=production PORT=3000 HOSTNAME=0.0.0.0
|
||||||
|
export CONVEX_INTERNAL_URL="$BACKEND_URL"
|
||||||
|
# Server-side Convex helpers fall back to this at runtime. The browser bundle
|
||||||
|
# is built without it, so browsers still derive their own URL.
|
||||||
|
export NEXT_PUBLIC_CONVEX_URL="$BACKEND_URL"
|
||||||
|
exec setpriv --reuid=otunes --regid=otunes --init-groups \
|
||||||
|
"$NODE" apps/web/server.js
|
||||||
|
) &
|
||||||
|
web_pid=$!
|
||||||
|
|
||||||
|
set +e
|
||||||
|
wait -n "$backend_pid" "$web_pid"
|
||||||
|
status=$?
|
||||||
|
set -e
|
||||||
|
|
||||||
|
log "A process exited with status $status, shutting down"
|
||||||
|
stop
|
||||||
|
exit "$status"
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
// Prints a fresh Convex Auth signing key pair in .env format for `convex env set`.
|
||||||
|
import { generateKeyPairSync } from "node:crypto"
|
||||||
|
|
||||||
|
const { privateKey, publicKey } = generateKeyPairSync("rsa", {
|
||||||
|
modulusLength: 2048,
|
||||||
|
})
|
||||||
|
const pkcs8 = privateKey.export({ type: "pkcs8", format: "pem" })
|
||||||
|
const jwk = publicKey.export({ format: "jwk" })
|
||||||
|
const jwks = JSON.stringify({ keys: [{ use: "sig", ...jwk }] })
|
||||||
|
|
||||||
|
process.stdout.write(
|
||||||
|
`JWT_PRIVATE_KEY="${pkcs8.trimEnd().replace(/\n/g, " ")}"\n`
|
||||||
|
)
|
||||||
|
process.stdout.write(`JWKS=${jwks}\n`)
|
||||||
@@ -11,9 +11,7 @@ import { ConvexError } from "convex/values"
|
|||||||
import type { Id } from "./_generated/dataModel"
|
import type { Id } from "./_generated/dataModel"
|
||||||
import { action, internalAction, type ActionCtx } from "./_generated/server"
|
import { action, internalAction, type ActionCtx } from "./_generated/server"
|
||||||
|
|
||||||
const DATA_DIR = process.env.CONVEX_SITE_URL?.includes("127.0.0.1")
|
const DATA_DIR = process.env.DATA || "/data"
|
||||||
? "/Volumes/FastStorage/Apple Music"
|
|
||||||
: process.env.DATA || "/data"
|
|
||||||
const HLS_CACHE_DIR = "/tmp/otunes"
|
const HLS_CACHE_DIR = "/tmp/otunes"
|
||||||
const HLS_MAX_IDLE_MS = 30 * 60 * 1000
|
const HLS_MAX_IDLE_MS = 30 * 60 * 1000
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { paginationOptsValidator } from "convex/server"
|
import { paginationOptsValidator } from "convex/server"
|
||||||
import { getAuthUserId } from "@convex-dev/auth/server"
|
import { getAuthUserId } from "@convex-dev/auth/server"
|
||||||
import { internalMutation, internalQuery, query } from "./_generated/server"
|
import { internalMutation, internalQuery, query } from "./_generated/server"
|
||||||
import { v } from "convex/values"
|
import { ConvexError, v } from "convex/values"
|
||||||
import type { Doc, Id } from "./_generated/dataModel"
|
import type { Doc, Id } from "./_generated/dataModel"
|
||||||
import type { QueryCtx } from "./_generated/server"
|
import type { QueryCtx } from "./_generated/server"
|
||||||
import type { PaginationOptions, PaginationResult } from "convex/server"
|
import type { PaginationOptions, PaginationResult } from "convex/server"
|
||||||
@@ -494,6 +494,28 @@ export const browseSongsPaginated = query({
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
export const browseSortedSongIds = query({
|
||||||
|
args: {
|
||||||
|
sortKey: songsSortKeyValidator,
|
||||||
|
sortDirection: songsSortDirectionValidator,
|
||||||
|
},
|
||||||
|
handler: async (ctx, args) => {
|
||||||
|
return getSortedLibrarySongIds(ctx, args.sortKey, args.sortDirection)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const MAX_SONGS_BY_IDS = 200
|
||||||
|
|
||||||
|
export const browseSongsByIds = query({
|
||||||
|
args: { ids: v.array(v.id("songs")) },
|
||||||
|
handler: async (ctx, args): Promise<BrowseSong[]> => {
|
||||||
|
if (args.ids.length > MAX_SONGS_BY_IDS) {
|
||||||
|
throw new ConvexError(`Request at most ${MAX_SONGS_BY_IDS} songs`)
|
||||||
|
}
|
||||||
|
return browseSongsFromIds(ctx, args.ids)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
export const browseAlbumDetail = query({
|
export const browseAlbumDetail = query({
|
||||||
args: { id: v.id("albums") },
|
args: { id: v.id("albums") },
|
||||||
handler: async (ctx, args): Promise<BrowseAlbumDetail | null> => {
|
handler: async (ctx, args): Promise<BrowseAlbumDetail | null> => {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { getAuthUserId } from "@convex-dev/auth/server"
|
import { getAuthUserId } from "@convex-dev/auth/server"
|
||||||
import { paginationOptsValidator } from "convex/server"
|
import { paginationOptsValidator } from "convex/server"
|
||||||
import { ConvexError, v } from "convex/values"
|
import { ConvexError, v } from "convex/values"
|
||||||
import type { Id } from "./_generated/dataModel"
|
import type { Doc, Id } from "./_generated/dataModel"
|
||||||
import type { MutationCtx } from "./_generated/server"
|
import type { MutationCtx } from "./_generated/server"
|
||||||
import { mutation, query } from "./_generated/server"
|
import { mutation, query } from "./_generated/server"
|
||||||
import type { QueueSong } from "./types"
|
import type { QueueSong } from "./types"
|
||||||
@@ -144,6 +144,30 @@ function appendManyToQueueHistory(
|
|||||||
return next
|
return next
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function patchPlayback(
|
||||||
|
ctx: MutationCtx,
|
||||||
|
userId: Id<"users">,
|
||||||
|
patch: Partial<
|
||||||
|
Pick<
|
||||||
|
Doc<"users">,
|
||||||
|
| "songQueue"
|
||||||
|
| "queueHistory"
|
||||||
|
| "currentSongProgress"
|
||||||
|
| "shuffleEnabled"
|
||||||
|
| "repeatEnabled"
|
||||||
|
>
|
||||||
|
>
|
||||||
|
) {
|
||||||
|
const user = await ctx.db.get(userId)
|
||||||
|
if (!user) {
|
||||||
|
throw new ConvexError("User not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
const playbackRevision = (user.playbackRevision ?? 0) + 1
|
||||||
|
await ctx.db.patch(userId, { ...patch, playbackRevision })
|
||||||
|
return playbackRevision
|
||||||
|
}
|
||||||
|
|
||||||
async function setQueueState(
|
async function setQueueState(
|
||||||
ctx: MutationCtx,
|
ctx: MutationCtx,
|
||||||
userId: Id<"users">,
|
userId: Id<"users">,
|
||||||
@@ -154,7 +178,7 @@ async function setQueueState(
|
|||||||
resetHistory?: boolean
|
resetHistory?: boolean
|
||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
await ctx.db.patch(userId, {
|
await patchPlayback(ctx, userId, {
|
||||||
songQueue: patch.songQueue,
|
songQueue: patch.songQueue,
|
||||||
currentSongProgress: patch.currentSongProgress ?? 0,
|
currentSongProgress: patch.currentSongProgress ?? 0,
|
||||||
...(patch.resetHistory ? { queueHistory: [] } : {}),
|
...(patch.resetHistory ? { queueHistory: [] } : {}),
|
||||||
@@ -190,6 +214,52 @@ export const getPlaybackState = query({
|
|||||||
shuffleEnabled: user.shuffleEnabled ?? false,
|
shuffleEnabled: user.shuffleEnabled ?? false,
|
||||||
repeatEnabled: user.repeatEnabled ?? ("none" as const),
|
repeatEnabled: user.repeatEnabled ?? ("none" as const),
|
||||||
currentSongProgress: user.currentSongProgress ?? 0,
|
currentSongProgress: user.currentSongProgress ?? 0,
|
||||||
|
revision: user.playbackRevision ?? 0,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const repeatModeValidator = v.union(
|
||||||
|
v.literal("none"),
|
||||||
|
v.literal("once"),
|
||||||
|
v.literal("always")
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replaces the whole playback state with the client's local copy. Clients
|
||||||
|
* apply queue changes locally first and push snapshots here in the background.
|
||||||
|
*/
|
||||||
|
export const syncPlaybackState = mutation({
|
||||||
|
args: {
|
||||||
|
songQueue: v.array(v.id("songs")),
|
||||||
|
queueHistory: v.array(v.id("songs")),
|
||||||
|
shuffleEnabled: v.boolean(),
|
||||||
|
repeatEnabled: repeatModeValidator,
|
||||||
|
currentSongProgress: v.number(),
|
||||||
|
},
|
||||||
|
handler: async (ctx, args) => {
|
||||||
|
const userId = await requireAuth(ctx)
|
||||||
|
return await patchPlayback(ctx, userId, {
|
||||||
|
songQueue: args.songQueue,
|
||||||
|
queueHistory: args.queueHistory.slice(-MAX_QUEUE_HISTORY),
|
||||||
|
shuffleEnabled: args.shuffleEnabled,
|
||||||
|
repeatEnabled: args.repeatEnabled,
|
||||||
|
currentSongProgress: Math.max(0, Math.floor(args.currentSongProgress)),
|
||||||
|
})
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
export const recordPlay = mutation({
|
||||||
|
args: {
|
||||||
|
songId: v.optional(v.id("songs")),
|
||||||
|
playlistId: v.optional(v.id("playlists")),
|
||||||
|
},
|
||||||
|
handler: async (ctx, { songId, playlistId }) => {
|
||||||
|
const userId = await requireAuth(ctx)
|
||||||
|
if (playlistId) {
|
||||||
|
await recordRecentlyPlayed(ctx, userId, playlistId)
|
||||||
|
} else if (songId) {
|
||||||
|
await recordRecentlyPlayedFromSong(ctx, userId, songId)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -543,14 +613,14 @@ export const toggleShuffle = mutation({
|
|||||||
|
|
||||||
if (shuffleEnabled && queue.length > 1) {
|
if (shuffleEnabled && queue.length > 1) {
|
||||||
const [current, ...upNext] = queue
|
const [current, ...upNext] = queue
|
||||||
await ctx.db.patch(userId, {
|
await patchPlayback(ctx, userId, {
|
||||||
shuffleEnabled: true,
|
shuffleEnabled: true,
|
||||||
songQueue: [current, ...shuffleArray(upNext)],
|
songQueue: [current, ...shuffleArray(upNext)],
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
await ctx.db.patch(userId, { shuffleEnabled })
|
await patchPlayback(ctx, userId, { shuffleEnabled })
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -567,7 +637,7 @@ export const cycleRepeat = mutation({
|
|||||||
const next =
|
const next =
|
||||||
current === "none" ? "once" : current === "once" ? "always" : "none"
|
current === "none" ? "once" : current === "once" ? "always" : "none"
|
||||||
|
|
||||||
await ctx.db.patch(userId, { repeatEnabled: next })
|
await patchPlayback(ctx, userId, { repeatEnabled: next })
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -575,7 +645,7 @@ export const clearQueue = mutation({
|
|||||||
args: {},
|
args: {},
|
||||||
handler: async (ctx) => {
|
handler: async (ctx) => {
|
||||||
const userId = await requireAuth(ctx)
|
const userId = await requireAuth(ctx)
|
||||||
await ctx.db.patch(userId, {
|
await patchPlayback(ctx, userId, {
|
||||||
songQueue: [],
|
songQueue: [],
|
||||||
queueHistory: [],
|
queueHistory: [],
|
||||||
currentSongProgress: 0,
|
currentSongProgress: 0,
|
||||||
@@ -602,7 +672,7 @@ export const reorderQueue = mutation({
|
|||||||
? appendToQueueHistory(user.queueHistory ?? [], queue[0])
|
? appendToQueueHistory(user.queueHistory ?? [], queue[0])
|
||||||
: (user.queueHistory ?? [])
|
: (user.queueHistory ?? [])
|
||||||
|
|
||||||
await ctx.db.patch(userId, {
|
await patchPlayback(ctx, userId, {
|
||||||
songQueue: songIds,
|
songQueue: songIds,
|
||||||
queueHistory: history,
|
queueHistory: history,
|
||||||
...(currentSongChanged ? { currentSongProgress: 0 } : {}),
|
...(currentSongChanged ? { currentSongProgress: 0 } : {}),
|
||||||
@@ -627,7 +697,7 @@ export const skipToQueueIndex = mutation({
|
|||||||
const skipped = queue.slice(0, index)
|
const skipped = queue.slice(0, index)
|
||||||
const history = appendManyToQueueHistory(user.queueHistory ?? [], skipped)
|
const history = appendManyToQueueHistory(user.queueHistory ?? [], skipped)
|
||||||
|
|
||||||
await ctx.db.patch(userId, {
|
await patchPlayback(ctx, userId, {
|
||||||
songQueue: queue.slice(index),
|
songQueue: queue.slice(index),
|
||||||
queueHistory: history,
|
queueHistory: history,
|
||||||
currentSongProgress: 0,
|
currentSongProgress: 0,
|
||||||
@@ -652,14 +722,14 @@ export const skipNext = mutation({
|
|||||||
const repeat = user.repeatEnabled ?? "none"
|
const repeat = user.repeatEnabled ?? "none"
|
||||||
|
|
||||||
if (repeat === "once") {
|
if (repeat === "once") {
|
||||||
await ctx.db.patch(userId, { currentSongProgress: 0 })
|
await patchPlayback(ctx, userId, { currentSongProgress: 0 })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const [current, ...rest] = queue
|
const [current, ...rest] = queue
|
||||||
|
|
||||||
if (repeat === "always") {
|
if (repeat === "always") {
|
||||||
await ctx.db.patch(userId, {
|
await patchPlayback(ctx, userId, {
|
||||||
songQueue: [...rest, current],
|
songQueue: [...rest, current],
|
||||||
currentSongProgress: 0,
|
currentSongProgress: 0,
|
||||||
})
|
})
|
||||||
@@ -667,7 +737,7 @@ export const skipNext = mutation({
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (rest.length === 0) {
|
if (rest.length === 0) {
|
||||||
await ctx.db.patch(userId, {
|
await patchPlayback(ctx, userId, {
|
||||||
songQueue: [current],
|
songQueue: [current],
|
||||||
currentSongProgress: 0,
|
currentSongProgress: 0,
|
||||||
})
|
})
|
||||||
@@ -676,7 +746,7 @@ export const skipNext = mutation({
|
|||||||
|
|
||||||
const history = appendToQueueHistory(user.queueHistory ?? [], current)
|
const history = appendToQueueHistory(user.queueHistory ?? [], current)
|
||||||
|
|
||||||
await ctx.db.patch(userId, {
|
await patchPlayback(ctx, userId, {
|
||||||
songQueue: rest,
|
songQueue: rest,
|
||||||
queueHistory: history,
|
queueHistory: history,
|
||||||
currentSongProgress: 0,
|
currentSongProgress: 0,
|
||||||
@@ -701,7 +771,7 @@ export const skipPrevious = mutation({
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (history.length === 0) {
|
if (history.length === 0) {
|
||||||
await ctx.db.patch(userId, { currentSongProgress: 0 })
|
await patchPlayback(ctx, userId, { currentSongProgress: 0 })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -709,7 +779,7 @@ export const skipPrevious = mutation({
|
|||||||
const previous = history[history.length - 1]
|
const previous = history[history.length - 1]
|
||||||
const newHistory = history.slice(0, -1)
|
const newHistory = history.slice(0, -1)
|
||||||
|
|
||||||
await ctx.db.patch(userId, {
|
await patchPlayback(ctx, userId, {
|
||||||
songQueue: [previous, current, ...rest],
|
songQueue: [previous, current, ...rest],
|
||||||
queueHistory: newHistory,
|
queueHistory: newHistory,
|
||||||
currentSongProgress: 0,
|
currentSongProgress: 0,
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ export default defineSchema({
|
|||||||
v.array(v.union(v.id("playlists"), v.id("albums")))
|
v.array(v.union(v.id("playlists"), v.id("albums")))
|
||||||
),
|
),
|
||||||
currentSongProgress: v.optional(v.number()),
|
currentSongProgress: v.optional(v.number()),
|
||||||
|
playbackRevision: v.optional(v.number()),
|
||||||
shuffleEnabled: v.optional(v.boolean()),
|
shuffleEnabled: v.optional(v.boolean()),
|
||||||
repeatEnabled: v.optional(
|
repeatEnabled: v.optional(
|
||||||
v.union(v.literal("always"), v.literal("once"), v.literal("none"))
|
v.union(v.literal("always"), v.literal("once"), v.literal("none"))
|
||||||
|
|||||||
@@ -18,6 +18,10 @@
|
|||||||
"./playback-stream": {
|
"./playback-stream": {
|
||||||
"types": "./playback-stream.ts",
|
"types": "./playback-stream.ts",
|
||||||
"default": "./playback-stream.ts"
|
"default": "./playback-stream.ts"
|
||||||
|
},
|
||||||
|
"./server-url": {
|
||||||
|
"types": "./server-url.ts",
|
||||||
|
"default": "./server-url.ts"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
/** Port the self-hosted Convex backend listens on when there is no `convex.` subdomain. */
|
||||||
|
export const LOCAL_CONVEX_PORT = "3210"
|
||||||
|
|
||||||
|
export function parseHostPort(hostname: string): {
|
||||||
|
host: string
|
||||||
|
port?: string
|
||||||
|
} {
|
||||||
|
const colonIndex = hostname.lastIndexOf(":")
|
||||||
|
if (colonIndex === -1) {
|
||||||
|
return { host: hostname }
|
||||||
|
}
|
||||||
|
const host = hostname.slice(0, colonIndex)
|
||||||
|
const port = hostname.slice(colonIndex + 1)
|
||||||
|
if (!/^\d+$/.test(port)) {
|
||||||
|
return { host: hostname }
|
||||||
|
}
|
||||||
|
return { host, port }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isLocalHost(hostname: string): boolean {
|
||||||
|
const host = parseHostPort(hostname).host.toLowerCase()
|
||||||
|
return (
|
||||||
|
host === "localhost" ||
|
||||||
|
host === "127.0.0.1" ||
|
||||||
|
host.endsWith(".local") ||
|
||||||
|
/^\d{1,3}(\.\d{1,3}){3}$/.test(host)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convex URL for an oTunes server reached at `hostname` (host with optional port).
|
||||||
|
* Local hosts use the Convex port directly, everything else uses the
|
||||||
|
* `convex.` subdomain, e.g. `music.example.com` -> `https://convex.music.example.com`.
|
||||||
|
*/
|
||||||
|
export function buildConvexUrl(
|
||||||
|
hostname: string,
|
||||||
|
protocol: "http" | "https" = isLocalHost(hostname) ? "http" : "https"
|
||||||
|
): string {
|
||||||
|
const { host, port } = parseHostPort(hostname)
|
||||||
|
if (isLocalHost(hostname)) {
|
||||||
|
return `${protocol}://${host}:${LOCAL_CONVEX_PORT}`
|
||||||
|
}
|
||||||
|
const convexHost = `convex.${host}`
|
||||||
|
return port
|
||||||
|
? `${protocol}://${convexHost}:${port}`
|
||||||
|
: `${protocol}://${convexHost}`
|
||||||
|
}
|
||||||
Reference in new issue
Block a user