Compare commits

..
111 changed files with 1281 additions and 4248 deletions

No files matched your search

+30 -156
View File
@@ -1,5 +1,3 @@
# syntax=docker/dockerfile:1
# ============================================ # ============================================
# Stage 1: Dependencies Installation Stage # Stage 1: Dependencies Installation Stage
# ============================================ # ============================================
@@ -9,16 +7,12 @@
# 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
# The Convex backend runs inside the oTunes image. Pin to a commit tag from FROM node:${NODE_VERSION} AS runner-base
# https://github.com/get-convex/convex-backend/pkgs/container/convex-backend
ARG CONVEX_BACKEND_IMAGE=ghcr.io/get-convex/convex-backend:5c7cb5bc7db457290f1769f95f1d1340912f7fd7
# Audio-only static ffmpeg. The distro package links video filters that pull RUN apt-get update && \
# in LLVM and Mesa (~420MB) for codecs this app never uses. apt-get install -y ffmpeg && \
ARG FFMPEG_VERSION=7.1.5 rm -rf /var/lib/apt/lists/*
ARG FFMPEG_SHA256=de668509caf9e35e3cd162473441fdb29538c6d96ed080292b3cf9e6fc5d558f
FROM node:${NODE_VERSION} AS node
FROM node:${NODE_VERSION} AS dependencies FROM node:${NODE_VERSION} AS dependencies
@@ -35,12 +29,7 @@ RUN printf '%s\n' \
'packages:' \ 'packages:' \
' - "apps/web"' \ ' - "apps/web"' \
' - "packages/convex"' \ ' - "packages/convex"' \
>> pnpm-workspace.yaml \ > pnpm-workspace.yaml
&& printf '\n%s\n' \
'supportedArchitectures.os=current' \
'supportedArchitectures.cpu=current' \
'supportedArchitectures.libc=current' \
>> .npmrc
RUN --mount=type=cache,target=/root/.local/share/pnpm/store \ RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
corepack enable pnpm && \ corepack enable pnpm && \
@@ -50,168 +39,53 @@ RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
# Stage 2: Build Next.js application in standalone mode # Stage 2: Build Next.js application in standalone mode
# ============================================ # ============================================
# Reuse the installed workspace. Copying node_modules into a new layer retars # Reuse the installed workspace — no need to re-copy node_modules from a blank image.
# hundreds of thousands of files on every source change.
FROM dependencies AS builder FROM dependencies AS builder
WORKDIR /app WORKDIR /app
COPY apps/web /tmp/src/apps/web # Overlay sources; nested node_modules must be dockerignored so they do not
COPY packages/convex /tmp/src/packages/convex # replace the install from the dependencies stage with host pnpm symlinks.
COPY apps/web ./apps/web
COPY packages/convex ./packages/convex
# Merge sources onto the install. cp does not remove the existing # Re-apply the install tree after source COPY so module resolution cannot be
# node_modules tree, and the build context already dockerignores it. # clobbered even if a nested node_modules slips into the build context.
RUN cp -a /tmp/src/apps/web/. ./apps/web/ \ COPY --from=dependencies /app/node_modules ./node_modules
&& cp -a /tmp/src/packages/convex/. ./packages/convex/ \ COPY --from=dependencies /app/apps/web/node_modules ./apps/web/node_modules
&& rm -rf /tmp/src COPY --from=dependencies /app/packages/convex/node_modules ./packages/convex/node_modules
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: Convex functions, deployed to the bundled backend on boot # Stage 3: Run Next.js application
# ============================================ # ============================================
FROM node:${NODE_VERSION} AS convex-functions FROM runner-base AS runner
WORKDIR /app WORKDIR /app
COPY package.json pnpm-lock.yaml .npmrc ./ ENV NODE_ENV=production
COPY packages/convex/package.json ./packages/convex/ ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
RUN printf '%s\n' \ RUN mkdir /data
'packages:' \
' - "packages/convex"' \
> pnpm-workspace.yaml \
&& printf '\n%s\n' \
'supportedArchitectures.os=current' \
'supportedArchitectures.cpu=current' \
'supportedArchitectures.libc=current' \
>> .npmrc
RUN --mount=type=cache,target=/root/.local/share/pnpm/store \ COPY --from=builder --chown=node:node /app/apps/web/public ./apps/web/public
corepack enable pnpm && \ COPY --from=builder --chown=node:node /app/apps/web/.next/standalone ./
pnpm install --frozen-lockfile --prod --filter @otunes/convex... COPY --from=builder --chown=node:node /app/apps/web/.next/static ./apps/web/.next/static
COPY packages/convex ./packages/convex RUN mkdir -p apps/web/.next && chown -R node:node apps/web/.next
# Source maps and the Convex package's TypeScript sources are not used at runtime. USER node
RUN find /app -type f -name '*.map' -delete \
&& rm -rf /app/node_modules/.pnpm/convex@*/node_modules/convex/src
# ============================================ EXPOSE 3000
# Stage 4: Audio-only ffmpeg
# ============================================
FROM ubuntu:24.04 AS ffmpeg CMD ["node", "apps/web/server.js"]
ARG FFMPEG_VERSION
ARG FFMPEG_SHA256
RUN apt-get update && \
apt-get install -y --no-install-recommends \
build-essential ca-certificates curl nasm pkg-config xz-utils zlib1g-dev && \
rm -rf /var/lib/apt/lists/*
WORKDIR /src
RUN curl -fsSL -o ffmpeg.tar.xz "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz" \
&& echo "${FFMPEG_SHA256} ffmpeg.tar.xz" | sha256sum -c - \
&& tar -xJf ffmpeg.tar.xz --strip-components=1 \
&& rm ffmpeg.tar.xz
# Decoders cover the library formats (FLAC, ALAC/AAC in m4a, MP3, Opus,
# Vorbis, WavPack, WMA, E-AC-3/TrueHD for Atmos). Encoders are only the two
# the app writes: AAC (HLS and ADTS) and FLAC.
RUN ./configure \
--prefix=/opt/ffmpeg \
--disable-shared \
--enable-static \
--disable-debug \
--disable-doc \
--disable-ffplay \
--disable-ffprobe \
--disable-network \
--disable-autodetect \
--disable-everything \
--enable-ffmpeg \
--enable-protocol=file,pipe \
--enable-demuxer=aac,ac3,aiff,ape,asf,au,caf,dsf,flac,matroska,mov,mp3,ogg,wav,wv \
--enable-decoder=aac,aac_latm,ac3,alac,ape,dsd_lsbf,dsd_msbf,eac3,flac,mlp,mp3,opus,pcm_f32le,pcm_s16be,pcm_s16le,pcm_s24be,pcm_s24le,pcm_s32be,pcm_s32le,pcm_u8,truehd,vorbis,wavpack,wmav1,wmav2 \
--enable-encoder=aac,flac \
--enable-muxer=adts,flac,hls,mpegts \
--enable-parser=aac,aac_latm,ac3,flac,mpegaudio,opus,vorbis \
--enable-bsf=aac_adtstoasc \
--enable-filter=aresample,aformat \
--enable-zlib \
--extra-cflags="-Os" \
--extra-ldflags="-static" \
--pkg-config-flags="--static" \
&& make -j"$(nproc)" \
&& make install \
&& strip /opt/ffmpeg/bin/ffmpeg
# ============================================
# Stage 5: Run Convex and Next.js together
# ============================================
FROM ${CONVEX_BACKEND_IMAGE} AS convex-backend
# Fresh Ubuntu instead of the Convex image. That image installs libclang,
# which pulls LLVM (~200MB) even though the backend only links libstdc++.
FROM ubuntu:24.04 AS runner
RUN apt-get update && \
apt-get install -y --no-install-recommends ca-certificates curl openssl tini && \
rm -rf /var/lib/apt/lists/*
WORKDIR /convex
COPY --from=convex-backend --chmod=755 \
/convex/convex-local-backend \
/convex/generate_key \
/convex/run_backend.sh \
/convex/generate_admin_key.sh \
/convex/read_credentials.sh \
./
COPY --from=node --chmod=755 /usr/local/bin/node /usr/local/bin/node
COPY --from=ffmpeg --chmod=755 /opt/ffmpeg/bin/ffmpeg /usr/local/bin/ffmpeg
# Fail the build if a binary is missing a shared library.
RUN node --version \
&& ffmpeg -hide_banner -version \
&& openssl version \
&& command -v tini \
&& command -v curl \
&& ldd /convex/convex-local-backend \
&& ldd /convex/generate_key \
&& ! ldd /convex/convex-local-backend /convex/generate_key | grep -q 'not found'
RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes
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
ENV PATH="/usr/local/bin:${PATH}"
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 []
+42 -26
View File
@@ -40,12 +40,6 @@ 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
@@ -57,39 +51,61 @@ pnpm format # format with Prettier
## Hosting with Docker ## Hosting with Docker
The image runs both the web app and its Convex backend, so there is nothing to configure. Here's an example `docker-compose.yml`: Here's an example `docker-compose.yml` file to get you started:
```yaml ```yaml
name: music name: music
services: services:
otunes: otunes:
image: git.abunchofknowitalls.com/joshuafhiggins/otunes:latest
ports: ports:
- "3000:3000" # web app - "3000:3000"
- "3210:3210" # Convex
volumes: volumes:
- ./otunes-data:/convex/data
- /SomeAttachedStorage/Music:/data - /SomeAttachedStorage/Music:/data
stop_grace_period: 10s 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 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_signal: SIGINT
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
``` ```
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. 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.
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. `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.
### Reverse proxy 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.
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
@@ -16,17 +16,18 @@ export default function HomeLayout() {
screenOptions={({ route }) => ({ screenOptions={({ route }) => ({
...baseOptions, ...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Home", title: tabStackScreenTitles[route.name] ?? "Home",
headerRight: route.name === "settings" ? undefined : () => <ProfileHeaderButton />, headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems: unstable_headerRightItems:
route.name === "settings" route.name === "index"
? undefined ? () => [
: () => [
{ {
type: "custom", type: "custom",
element: <ProfileHeaderButton />, element: <ProfileHeaderButton />,
hidesSharedBackground: true, hidesSharedBackground: true,
}, },
], ]
: undefined,
})} })}
/> />
) )
@@ -1,5 +1,5 @@
import { useQuery } from "convex/react"
import { Stack, useLocalSearchParams } from "expo-router" import { Stack, useLocalSearchParams } from "expo-router"
import { useEffect } from "react"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native" import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
import { Ionicons } from "@expo/vector-icons" import { Ionicons } from "@expo/vector-icons"
@@ -9,13 +9,11 @@ import {
MediaActionMenu, MediaActionMenu,
MediaContextMenu, MediaContextMenu,
} from "@/components/media-actions-sheet" } from "@/components/media-actions-sheet"
import { CollectionDetailSkeleton } from "@/components/skeletons" import { Button, LoadingView } from "@/components/ui/primitives"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player" import { contentBottomInset } from "@/components/player"
import { useFavorites } from "@/contexts/favorites" import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback" import { usePlaybackActions } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color" import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
@@ -23,7 +21,6 @@ import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseAlbumTrack } from "@otunes/convex/types" import type { BrowseAlbumTrack } from "@otunes/convex/types"
import { formatDuration, formatMetadata } from "@/lib/format" import { formatDuration, formatMetadata } from "@/lib/format"
import { useAppNavigation } from "@/lib/app-navigation" import { useAppNavigation } from "@/lib/app-navigation"
import { albumDetailSongs, rememberSongs } from "@/lib/song-cache"
import { albumCoverUrl } from "@/lib/urls" import { albumCoverUrl } from "@/lib/urls"
import { radius, spacing, useThemeColors } from "@/lib/theme" import { radius, spacing, useThemeColors } from "@/lib/theme"
@@ -32,7 +29,7 @@ export default function AlbumScreen() {
const { push } = useAppNavigation() const { push } = useAppNavigation()
const colors = useThemeColors() const colors = useThemeColors()
const { config } = useServerConfig() const { config } = useServerConfig()
const album = useCachedQuery( const album = useQuery(
api.library.browseAlbumDetail, api.library.browseAlbumDetail,
typeof id === "string" ? { id: id as Id<"albums"> } : "skip" typeof id === "string" ? { id: id as Id<"albums"> } : "skip"
) )
@@ -52,12 +49,6 @@ export default function AlbumScreen() {
colors.background colors.background
) )
useEffect(() => {
if (album) {
rememberSongs(albumDetailSongs(album))
}
}, [album])
if (album === undefined || !config) { if (album === undefined || !config) {
return ( return (
<> <>
@@ -67,7 +58,7 @@ export default function AlbumScreen() {
headerLargeTitle: false, headerLargeTitle: false,
}} }}
/> />
<CollectionDetailSkeleton /> <LoadingView />
</> </>
) )
} }
@@ -168,14 +159,14 @@ export default function AlbumScreen() {
<Button <Button
title="Play" title="Play"
icon="play" icon="play"
onPress={() => void playAlbum(album.id, songIds)} onPress={() => void playAlbum(album.id)}
style={styles.playButton} style={styles.playButton}
/> />
<Pressable <Pressable
accessibilityRole="button" accessibilityRole="button"
accessibilityLabel="Shuffle" accessibilityLabel="Shuffle"
hitSlop={8} hitSlop={8}
onPress={() => void playAlbumShuffled(album.id, songIds)} onPress={() => void playAlbumShuffled(album.id)}
style={[styles.iconAction, { backgroundColor: colors.muted }]} style={[styles.iconAction, { backgroundColor: colors.muted }]}
> >
<Ionicons name="shuffle" size={24} color={colors.foreground} /> <Ionicons name="shuffle" size={24} color={colors.foreground} />
@@ -1,3 +1,4 @@
import { useQuery } from "convex/react"
import { Stack, useLocalSearchParams } from "expo-router" import { Stack, useLocalSearchParams } from "expo-router"
import { Pressable, StyleSheet, Text, View } from "react-native" import { Pressable, StyleSheet, Text, View } from "react-native"
import { Ionicons } from "@expo/vector-icons" import { Ionicons } from "@expo/vector-icons"
@@ -6,13 +7,11 @@ import { CoverImage } from "@/components/cover-image"
import { MediaGridList } from "@/components/media-cards" import { MediaGridList } from "@/components/media-cards"
import { MediaActionMenu } from "@/components/media-actions-sheet" import { MediaActionMenu } from "@/components/media-actions-sheet"
import { CollectionDetailSkeleton } from "@/components/skeletons" import { Button, LoadingView } from "@/components/ui/primitives"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player" import { contentBottomInset } from "@/components/player"
import { useFavorites } from "@/contexts/favorites" import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback" import { usePlaybackActions } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
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"
@@ -23,7 +22,7 @@ export default function ArtistScreen() {
const { id } = useLocalSearchParams<{ id: string }>() const { id } = useLocalSearchParams<{ id: string }>()
const colors = useThemeColors() const colors = useThemeColors()
const { config } = useServerConfig() const { config } = useServerConfig()
const data = useCachedQuery( const data = useQuery(
api.library.browseArtistDetail, api.library.browseArtistDetail,
typeof id === "string" ? { id: id as Id<"artists"> } : "skip" typeof id === "string" ? { id: id as Id<"artists"> } : "skip"
) )
@@ -41,7 +40,7 @@ export default function ArtistScreen() {
headerLargeTitle: false, headerLargeTitle: false,
}} }}
/> />
<CollectionDetailSkeleton round /> <LoadingView />
</> </>
) )
} }
@@ -1,13 +1,10 @@
import { usePaginatedQuery, useQuery } from "convex/react"
import { Stack } from "expo-router" import { Stack } from "expo-router"
import { useCallback } from "react" import { useCallback } from "react"
import { MediaGridList } from "@/components/media-cards" import { MediaGridList } from "@/components/media-cards"
import { MediaGridSkeleton } from "@/components/skeletons" import { LoadingView } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player" import { contentBottomInset } from "@/components/player"
import {
useCachedPaginatedQuery,
useCachedQuery,
} from "@/hooks/use-cached-query"
import { useDebouncedSearch } from "@/hooks/use-debounced-search" import { useDebouncedSearch } from "@/hooks/use-debounced-search"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
@@ -15,20 +12,16 @@ const PAGE_SIZE = 50
export default function AlbumsScreen() { export default function AlbumsScreen() {
const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch() const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch()
const { results, status, loadMore, isCached } = useCachedPaginatedQuery( const { results, status, loadMore } = usePaginatedQuery(
api.library.browseAlbumsPaginated, api.library.browseAlbumsPaginated,
{}, {},
{ initialNumItems: PAGE_SIZE } { initialNumItems: PAGE_SIZE }
) )
const searchResults = useCachedQuery( const searchResults = useQuery(
api.library.searchLibrary, api.library.searchLibrary,
searchQuery ? { query: searchQuery } : "skip" searchQuery ? { query: searchQuery } : "skip"
) )
const albums = searchQuery const albums = searchQuery ? searchResults?.albums : results
? searchResults?.albums
: status === "LoadingFirstPage" && !isCached
? undefined
: results
const handleChangeText = useCallback( const handleChangeText = useCallback(
(event: { nativeEvent: { text: string } }) => { (event: { nativeEvent: { text: string } }) => {
@@ -53,7 +46,7 @@ export default function AlbumsScreen() {
return ( return (
<> <>
{searchBar} {searchBar}
<MediaGridSkeleton /> <LoadingView />
</> </>
) )
} }
@@ -1,17 +1,14 @@
import { Ionicons } from "@expo/vector-icons" import { Ionicons } from "@expo/vector-icons"
import { usePaginatedQuery, useQuery } from "convex/react"
import { Stack } from "expo-router" import { Stack } from "expo-router"
import { useCallback } from "react" import { useCallback } from "react"
import { FlatList, Pressable, StyleSheet, Text } from "react-native" import { FlatList, Pressable, StyleSheet, Text } from "react-native"
import { MediaContextMenu } from "@/components/media-context-menu" import { MediaContextMenu } from "@/components/media-context-menu"
import { CoverImage } from "@/components/cover-image" import { CoverImage } from "@/components/cover-image"
import { ArtistListSkeleton } from "@/components/skeletons" import { LoadingView } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player" import { contentBottomInset } from "@/components/player"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import {
useCachedPaginatedQuery,
useCachedQuery,
} from "@/hooks/use-cached-query"
import { useDebouncedSearch } from "@/hooks/use-debounced-search" import { useDebouncedSearch } from "@/hooks/use-debounced-search"
import { useAppNavigation } from "@/lib/app-navigation" import { useAppNavigation } from "@/lib/app-navigation"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
@@ -27,21 +24,17 @@ export default function ArtistsScreen() {
const colors = useThemeColors() const colors = useThemeColors()
const { config } = useServerConfig() const { config } = useServerConfig()
const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch() const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch()
const { results, status, loadMore, isCached } = useCachedPaginatedQuery( const { results, status, loadMore } = usePaginatedQuery(
api.library.browseArtistsPaginated, api.library.browseArtistsPaginated,
{}, {},
{ initialNumItems: PAGE_SIZE } { initialNumItems: PAGE_SIZE }
) )
const searchResults = useCachedQuery( const searchResults = useQuery(
api.library.searchLibrary, api.library.searchLibrary,
searchQuery ? { query: searchQuery } : "skip" searchQuery ? { query: searchQuery } : "skip"
) )
const { handleArtistAction, isArtistFavorite } = useMediaMenuActions() const { handleArtistAction, isArtistFavorite } = useMediaMenuActions()
const artists = searchQuery const artists = searchQuery ? searchResults?.artists : results
? searchResults?.artists
: status === "LoadingFirstPage" && !isCached
? undefined
: results
const handleChangeText = useCallback( const handleChangeText = useCallback(
(event: { nativeEvent: { text: string } }) => { (event: { nativeEvent: { text: string } }) => {
@@ -66,7 +59,7 @@ export default function ArtistsScreen() {
return ( return (
<> <>
{searchBar} {searchBar}
<ArtistListSkeleton /> <LoadingView />
</> </>
) )
} }
@@ -1,9 +1,9 @@
import { useQuery } from "convex/react"
import { Pressable } from "react-native" import { Pressable } from "react-native"
import { MediaGridList } from "@/components/media-cards" import { MediaGridList } from "@/components/media-cards"
import { MediaGridSkeleton } from "@/components/skeletons" import { LoadingView } from "@/components/ui/primitives"
import { tabContentBottomInset } from "@/components/player" import { tabContentBottomInset } from "@/components/player"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import { useThemeColors } from "@/lib/theme" import { useThemeColors } from "@/lib/theme"
import { Ionicons } from "@expo/vector-icons" import { Ionicons } from "@expo/vector-icons"
@@ -13,7 +13,7 @@ import { useAddToPlaylist } from "@/contexts/add-to-playlist"
export default function PlaylistsTabScreen() { export default function PlaylistsTabScreen() {
const colors = useThemeColors() const colors = useThemeColors()
const playlists = useCachedQuery(api.playlists.listAllPlaylists) const playlists = useQuery(api.playlists.listAllPlaylists)
const { openCreatePlaylist } = useAddToPlaylist() const { openCreatePlaylist } = useAddToPlaylist()
if (playlists === undefined) { if (playlists === undefined) {
@@ -38,7 +38,7 @@ export default function PlaylistsTabScreen() {
), ),
}} }}
/> />
<MediaGridSkeleton /> <LoadingView />
</> </>
) )
} }
@@ -1,15 +1,12 @@
import { usePaginatedQuery, useQuery } from "convex/react"
import { Stack } from "expo-router" import { Stack } from "expo-router"
import { useCallback, useState } from "react" import { useCallback, useState } from "react"
import { FlatList, StyleSheet } from "react-native" import { FlatList, StyleSheet } from "react-native"
import { contentBottomInset, SongRow } from "@/components/player" import { contentBottomInset, SongRow } from "@/components/player"
import { SongListSkeleton } from "@/components/skeletons" import { LoadingView } from "@/components/ui/primitives"
import { useFavorites } from "@/contexts/favorites" import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback" import { usePlaybackActions } from "@/contexts/playback"
import {
useCachedPaginatedQuery,
useCachedQuery,
} from "@/hooks/use-cached-query"
import { useDebouncedSearch } from "@/hooks/use-debounced-search" import { useDebouncedSearch } from "@/hooks/use-debounced-search"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
@@ -26,20 +23,16 @@ export default function SongsScreen() {
const [sortKey, setSortKey] = useState<"title" | "artist" | "album">("title") const [sortKey, setSortKey] = useState<"title" | "artist" | "album">("title")
const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc") const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc")
const { results, status, loadMore, isCached } = useCachedPaginatedQuery( const { results, status, loadMore } = usePaginatedQuery(
api.library.browseSongsPaginated, api.library.browseSongsPaginated,
{ sortKey, sortDirection }, { sortKey, sortDirection },
{ initialNumItems: PAGE_SIZE } { initialNumItems: PAGE_SIZE }
) )
const searchResults = useCachedQuery( const searchResults = useQuery(
api.library.searchLibrary, api.library.searchLibrary,
searchQuery ? { query: searchQuery } : "skip" searchQuery ? { query: searchQuery } : "skip"
) )
const songs = searchQuery const songs = searchQuery ? searchResults?.songs : results
? searchResults?.songs
: status === "LoadingFirstPage" && !isCached
? undefined
: results
const handleChangeText = useCallback( const handleChangeText = useCallback(
(event: { nativeEvent: { text: string } }) => { (event: { nativeEvent: { text: string } }) => {
@@ -64,7 +57,7 @@ export default function SongsScreen() {
return ( return (
<> <>
{searchBar} {searchBar}
<SongListSkeleton /> <LoadingView />
</> </>
) )
} }
+20 -12
View File
@@ -1,10 +1,10 @@
import { memo } from "react" import { usePaginatedQuery } from "convex/react"
import { memo, useRef } from "react"
import { ScrollView, StyleSheet } from "react-native" import { ScrollView, StyleSheet } from "react-native"
import { ContentCarousel } from "@/components/media-cards" import { ContentCarousel } from "@/components/media-cards"
import { HomeSkeleton } from "@/components/skeletons" import { LoadingView } from "@/components/ui/primitives"
import { tabContentBottomInset } from "@/components/player" import { tabContentBottomInset } from "@/components/player"
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
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"
import { spacing, useThemeColors } from "@/lib/theme" import { spacing, useThemeColors } from "@/lib/theme"
@@ -38,26 +38,34 @@ const HomeCarousels = memo(function HomeCarousels({
export default function HomeScreen() { export default function HomeScreen() {
const colors = useThemeColors() const colors = useThemeColors()
const recentlyAdded = useCachedPaginatedQuery( const { results: recentlyAdded } = usePaginatedQuery(
api.library.browseRecentlyAddedPaginated, api.library.browseRecentlyAddedPaginated,
{}, {},
{ initialNumItems: CAROUSEL_ITEM_LIMIT } { initialNumItems: CAROUSEL_ITEM_LIMIT }
) )
const recentlyPlayed = useCachedPaginatedQuery( const { results: recentlyPlayed } = usePaginatedQuery(
api.library.browseRecentlyPlayedPaginated, api.library.browseRecentlyPlayedPaginated,
{}, {},
{ initialNumItems: CAROUSEL_ITEM_LIMIT } { initialNumItems: CAROUSEL_ITEM_LIMIT }
) )
const cachedData = useRef<{
recentlyAdded?: BrowseAlbum[]
recentlyPlayed?: (BrowseAlbum | PlaylistSummary)[]
}>({})
const isLoading = [recentlyAdded, recentlyPlayed].some( if (recentlyAdded !== undefined) {
(result) => result.status === "LoadingFirstPage" && !result.isCached cachedData.current.recentlyAdded = recentlyAdded
) }
if (isLoading) { if (recentlyPlayed !== undefined) {
return <HomeSkeleton /> cachedData.current.recentlyPlayed = recentlyPlayed
} }
const added = recentlyAdded.results.slice(0, CAROUSEL_ITEM_LIMIT) const added = recentlyAdded ?? cachedData.current.recentlyAdded
const played = recentlyPlayed.results.slice(0, CAROUSEL_ITEM_LIMIT) const played = recentlyPlayed ?? cachedData.current.recentlyPlayed
if (added === undefined || played === undefined) {
return <LoadingView />
}
return ( return (
<ScrollView <ScrollView
@@ -1,5 +1,4 @@
import { useMutation } from "convex/react" import { useMutation, usePaginatedQuery, useQuery } from "convex/react"
import { useEffect } from "react"
import { import {
Button as SwiftUIButton, Button as SwiftUIButton,
ContextMenu, ContextMenu,
@@ -37,23 +36,17 @@ import {
MediaActionMenu, MediaActionMenu,
type MediaAction, type MediaAction,
} from "@/components/media-actions-sheet" } from "@/components/media-actions-sheet"
import { CollectionDetailSkeleton } from "@/components/skeletons" import { Button, LoadingView } from "@/components/ui/primitives"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset, SongRow } from "@/components/player" import { contentBottomInset, SongRow } from "@/components/player"
import { useFavorites } from "@/contexts/favorites" import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback" import { usePlaybackActions } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import {
useCachedPaginatedQuery,
useCachedQuery,
} from "@/hooks/use-cached-query"
import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color" import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
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 type { BrowseSong } from "@otunes/convex/types" import type { BrowseSong } from "@otunes/convex/types"
import { shareMediaLink } from "@/lib/share-media-link" import { shareMediaLink } from "@/lib/share-media-link"
import { rememberSongs } from "@/lib/song-cache"
import { showError, showSuccess } from "@/lib/toast" import { showError, showSuccess } from "@/lib/toast"
import { playlistCoverUrl } from "@/lib/urls" import { playlistCoverUrl } from "@/lib/urls"
import { radius, spacing, useThemeColors } from "@/lib/theme" import { radius, spacing, useThemeColors } from "@/lib/theme"
@@ -67,7 +60,7 @@ export default function PlaylistScreen() {
const colors = useThemeColors() const colors = useThemeColors()
const { config } = useServerConfig() const { config } = useServerConfig()
const playlistId = typeof id === "string" ? (id as Id<"playlists">) : null const playlistId = typeof id === "string" ? (id as Id<"playlists">) : null
const playlist = useCachedQuery( const playlist = useQuery(
api.playlists.browsePlaylistDetail, api.playlists.browsePlaylistDetail,
playlistId playlistId
? { ? {
@@ -80,13 +73,12 @@ export default function PlaylistScreen() {
results: songs, results: songs,
status, status,
loadMore, loadMore,
isCached, } = usePaginatedQuery(
} = useCachedPaginatedQuery(
api.playlists.browsePlaylistSongsPaginated, api.playlists.browsePlaylistSongsPaginated,
playlistId ? { id: playlistId } : "skip", playlistId ? { id: playlistId } : "skip",
{ initialNumItems: PAGE_SIZE } { initialNumItems: PAGE_SIZE }
) )
const allSongIds = useCachedQuery( const allSongIds = useQuery(
api.playlists.getPlaylistSongIds, api.playlists.getPlaylistSongIds,
playlistId ? { playlistId } : "skip" playlistId ? { playlistId } : "skip"
) )
@@ -108,13 +100,10 @@ export default function PlaylistScreen() {
colors.background colors.background
) )
useEffect(() => {
rememberSongs(songs)
}, [songs])
if ( if (
playlist === undefined || playlist === undefined ||
(status === "LoadingFirstPage" && !isCached) || songs === undefined ||
allSongIds === undefined ||
!config !config
) { ) {
return ( return (
@@ -125,7 +114,7 @@ export default function PlaylistScreen() {
headerLargeTitle: false, headerLargeTitle: false,
}} }}
/> />
<CollectionDetailSkeleton /> <LoadingView />
</> </>
) )
} }
@@ -148,7 +137,7 @@ export default function PlaylistScreen() {
) )
} }
const songIds = allSongIds ?? songs.map((song) => song.id) const songIds = allSongIds
const serverUrl = config.serverUrl const serverUrl = config.serverUrl
function maybeLoadMore() { function maybeLoadMore() {
@@ -357,9 +346,9 @@ export default function PlaylistScreen() {
title={playlist.title} title={playlist.title}
ownerName={playlist.owner.name} ownerName={playlist.owner.name}
colors={colors} colors={colors}
onPlay={() => playlist.id && void playPlaylist(playlist.id, allSongIds)} onPlay={() => playlist.id && void playPlaylist(playlist.id)}
onShuffle={() => onShuffle={() =>
playlist.id && void playPlaylistShuffled(playlist.id, allSongIds) playlist.id && void playPlaylistShuffled(playlist.id)
} }
/> />
</RNHostView> </RNHostView>
@@ -416,9 +405,9 @@ export default function PlaylistScreen() {
isSubscribed={playlist.isSubscribed} isSubscribed={playlist.isSubscribed}
showSubscribe={!playlist.isOwner && !!playlist.id} showSubscribe={!playlist.isOwner && !!playlist.id}
onSubscribeToggle={() => void handleSubscribeToggle()} onSubscribeToggle={() => void handleSubscribeToggle()}
onPlay={() => playlist.id && void playPlaylist(playlist.id, allSongIds)} onPlay={() => playlist.id && void playPlaylist(playlist.id)}
onShuffle={() => onShuffle={() =>
playlist.id && void playPlaylistShuffled(playlist.id, allSongIds) playlist.id && void playPlaylistShuffled(playlist.id)
} }
/> />
} }
@@ -1,17 +1,14 @@
import { useEffect } from "react" import { useQuery } from "convex/react"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native" import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
import { CollectionDetailSkeleton } from "@/components/skeletons" import { Button, LoadingView } from "@/components/ui/primitives"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset, SongRow } from "@/components/player" import { contentBottomInset, SongRow } from "@/components/player"
import { useFavorites } from "@/contexts/favorites" import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback" import { usePlaybackActions } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import type { BrowseSong } from "@otunes/convex/types" import type { BrowseSong } from "@otunes/convex/types"
import { rememberSongs } from "@/lib/song-cache"
import { radius, spacing, useThemeColors } from "@/lib/theme" import { radius, spacing, useThemeColors } from "@/lib/theme"
import { Ionicons } from "@expo/vector-icons" import { Ionicons } from "@expo/vector-icons"
import { Stack } from "expo-router" import { Stack } from "expo-router"
@@ -19,17 +16,11 @@ import { Stack } from "expo-router"
export default function FavoritesScreen() { export default function FavoritesScreen() {
const colors = useThemeColors() const colors = useThemeColors()
const { config } = useServerConfig() const { config } = useServerConfig()
const favorites = useCachedQuery(api.favorites.browseFavoritesPlaylistDetail) const favorites = useQuery(api.favorites.browseFavoritesPlaylistDetail)
const { playInOrder, playShuffled, playFromSong } = usePlaybackActions() const { playInOrder, playShuffled, playFromSong } = usePlaybackActions()
const { isSongFavorite } = useFavorites() const { isSongFavorite } = useFavorites()
const { handleSongAction } = useMediaMenuActions() const { handleSongAction } = useMediaMenuActions()
useEffect(() => {
if (favorites) {
rememberSongs(favorites.songs)
}
}, [favorites])
if (favorites === undefined || !config) { if (favorites === undefined || !config) {
return ( return (
<> <>
@@ -39,7 +30,7 @@ export default function FavoritesScreen() {
headerLargeTitle: false, headerLargeTitle: false,
}} }}
/> />
<CollectionDetailSkeleton /> <LoadingView />
</> </>
) )
} }
+74 -78
View File
@@ -1,83 +1,59 @@
import { usePaginatedQuery, useQuery } from "convex/react"
import { Stack, useRouter } from "expo-router" import { Stack, useRouter } from "expo-router"
import { memo, useCallback, useMemo } from "react" import { useState } from "react"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native" import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
import { Button } from "@/components/ui/primitives" import { Button, LoadingView } from "@/components/ui/primitives"
import { contentBottomInset, SongRow } from "@/components/player" import { contentBottomInset, SongRow } from "@/components/player"
import { SongRowSkeleton } from "@/components/skeletons"
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback" import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
import type { Id } from "@otunes/convex/_generated/dataModel" import { api } from "@otunes/convex/_generated/api"
import { useSong, useSongs } from "@/lib/song-cache" import type { BrowseSong } from "@otunes/convex/types"
import { spacing, useThemeColors } from "@/lib/theme" import { spacing, useThemeColors } from "@/lib/theme"
import { showError } from "@/lib/toast"
type QueueItem = { songId: Id<"songs">; queueIndex: number } const PAGE_SIZE = 50
const QueueRow = memo(function QueueRow({
songId,
queueIndex,
isLast,
isCurrent,
onSkipTo,
onMove,
}: QueueItem & {
isLast: boolean
isCurrent: boolean
onSkipTo: (index: number) => void
onMove: (index: number, direction: -1 | 1) => void
}) {
const colors = useThemeColors()
const song = useSong(songId)
return (
<View>
{song ? (
<SongRow song={song} onPress={() => onSkipTo(queueIndex)} />
) : (
<SongRowSkeleton />
)}
<View style={styles.queueActions}>
<Pressable
disabled={queueIndex === 0}
onPress={() => onMove(queueIndex, -1)}
>
<Text style={{ color: colors.foreground }}>Move up</Text>
</Pressable>
<Pressable disabled={isLast} onPress={() => onMove(queueIndex, 1)}>
<Text style={{ color: colors.foreground }}>Move down</Text>
</Pressable>
{isCurrent ? (
<Text style={{ color: colors.primary, fontWeight: "700" }}>
Now playing
</Text>
) : null}
</View>
</View>
)
})
export default function QueueScreen() { export default function QueueScreen() {
const router = useRouter() const router = useRouter()
const colors = useThemeColors() const colors = useThemeColors()
const { queueSongIds, queueHistorySongIds } = usePlaybackQueue() const { queueSongIds, currentSong } = usePlaybackQueue()
const { skipToQueueIndex, clearQueue, reorderQueue } = usePlaybackActions() const { skipToQueueIndex, clearQueue, reorderQueue } = usePlaybackActions()
const historySongs = useSongs(queueHistorySongIds) const [reordering, setReordering] = useState(false)
const items = useMemo<QueueItem[]>( const queueVersion = queueSongIds.length
() => queueSongIds.map((songId, queueIndex) => ({ songId, queueIndex })), ? `${queueSongIds.length}:${queueSongIds[0]}:${queueSongIds[queueSongIds.length - 1]}`
[queueSongIds] : "empty"
const {
results: queueSongs,
status,
loadMore,
} = usePaginatedQuery(
api.playback.getQueuePaginated,
queueSongIds.length > 0 ? { queueVersion } : "skip",
{ initialNumItems: PAGE_SIZE }
) )
const moveSong = useCallback( const historySongs = useQuery(api.playback.getQueueHistory)
(fromIndex: number, direction: -1 | 1) => {
async function moveSong(fromIndex: number, direction: -1 | 1) {
if (reordering) return
const toIndex = fromIndex + direction const toIndex = fromIndex + direction
if (toIndex < 0 || toIndex >= queueSongIds.length) return if (toIndex < 0 || toIndex >= queueSongIds.length) return
const next = [...queueSongIds] const next = [...queueSongIds]
const [item] = next.splice(fromIndex, 1) const [item] = next.splice(fromIndex, 1)
next.splice(toIndex, 0, item) next.splice(toIndex, 0, item)
void reorderQueue(next) setReordering(true)
}, try {
[queueSongIds, reorderQueue] await reorderQueue(next)
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to reorder queue"
) )
} finally {
setReordering(false)
}
}
function handleClearQueue() { function handleClearQueue() {
if (router.canGoBack()) { if (router.canGoBack()) {
@@ -91,6 +67,10 @@ export default function QueueScreen() {
void clearQueue() void clearQueue()
} }
if (queueSongIds.length > 0 && queueSongs === undefined) {
return <LoadingView />
}
return ( return (
<> <>
<Stack.Screen <Stack.Screen
@@ -119,35 +99,51 @@ export default function QueueScreen() {
) : null} ) : null}
</View> </View>
} }
data={items} data={queueSongs ?? []}
keyExtractor={(item) => `${item.songId}-${item.queueIndex}`} keyExtractor={(item) => `${item.id}-${item.queueIndex}`}
contentContainerStyle={{ paddingBottom: contentBottomInset }} contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic" contentInsetAdjustmentBehavior="automatic"
initialNumToRender={15} onEndReached={() => {
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
}}
renderItem={({ item }) => ( renderItem={({ item }) => (
<QueueRow <View>
{...item} <SongRow
isLast={item.queueIndex === queueSongIds.length - 1} song={item}
isCurrent={item.queueIndex === 0} onPress={() => void skipToQueueIndex(item.queueIndex)}
onSkipTo={skipToQueueIndex}
onMove={moveSong}
/> />
<View style={styles.queueActions}>
<Pressable
disabled={reordering || item.queueIndex === 0}
onPress={() => void moveSong(item.queueIndex, -1)}
>
<Text style={{ color: colors.foreground }}>Move up</Text>
</Pressable>
<Pressable
disabled={
reordering || item.queueIndex === queueSongIds.length - 1
}
onPress={() => void moveSong(item.queueIndex, 1)}
>
<Text style={{ color: colors.foreground }}>Move down</Text>
</Pressable>
{currentSong?.id === item.id ? (
<Text style={{ color: colors.primary, fontWeight: "700" }}>
Now playing
</Text>
) : null}
</View>
</View>
)} )}
ListFooterComponent={ ListFooterComponent={
queueHistorySongIds.length > 0 ? ( historySongs && historySongs.length > 0 ? (
<View style={styles.history}> <View style={styles.history}>
<Text style={[styles.section, { color: colors.mutedForeground }]}> <Text style={[styles.section, { color: colors.mutedForeground }]}>
History History
</Text> </Text>
{historySongs.map((song, index) => {historySongs.map((song: BrowseSong) => (
song ? ( <SongRow key={song.id} song={song} />
<SongRow key={`${song.id}-${index}`} song={song} /> ))}
) : (
<SongRowSkeleton
key={`${queueHistorySongIds[index]}-${index}`}
/>
)
)}
</View> </View>
) : null ) : null
} }
@@ -1,20 +1,21 @@
import { usePaginatedQuery } from "convex/react"
import { MediaGridList } from "@/components/media-cards" import { MediaGridList } from "@/components/media-cards"
import { MediaGridSkeleton } from "@/components/skeletons" import { LoadingView } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player" import { contentBottomInset } from "@/components/player"
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
const PAGE_SIZE = 16 const PAGE_SIZE = 16
export default function RecentlyAddedScreen() { export default function RecentlyAddedScreen() {
const { results, status, loadMore, isCached } = useCachedPaginatedQuery( const { results, status, loadMore } = usePaginatedQuery(
api.library.browseRecentlyAddedPaginated, api.library.browseRecentlyAddedPaginated,
{}, {},
{ initialNumItems: PAGE_SIZE } { initialNumItems: PAGE_SIZE }
) )
if (status === "LoadingFirstPage" && !isCached) { if (results === undefined) {
return <MediaGridSkeleton /> return <LoadingView />
} }
return ( return (
@@ -1,20 +1,21 @@
import { usePaginatedQuery } from "convex/react"
import { MediaGridList } from "@/components/media-cards" import { MediaGridList } from "@/components/media-cards"
import { MediaGridSkeleton } from "@/components/skeletons" import { LoadingView } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player" import { contentBottomInset } from "@/components/player"
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
const PAGE_SIZE = 50 const PAGE_SIZE = 50
export default function RecentlyPlayedScreen() { export default function RecentlyPlayedScreen() {
const { results, status, loadMore, isCached } = useCachedPaginatedQuery( const { results, status, loadMore } = usePaginatedQuery(
api.library.browseRecentlyPlayedPaginated, api.library.browseRecentlyPlayedPaginated,
{}, {},
{ initialNumItems: PAGE_SIZE } { initialNumItems: PAGE_SIZE }
) )
if (status === "LoadingFirstPage" && !isCached) { if (results === undefined) {
return <MediaGridSkeleton /> return <LoadingView />
} }
return ( return (
@@ -19,8 +19,7 @@ import { Button, Input, LoadingView } from "@/components/ui/primitives"
import { useInvalidateAuthSession } from "@/contexts/convex-auth-session" import { useInvalidateAuthSession } from "@/contexts/convex-auth-session"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import { initialsFromName } from "@/lib/format" import { initialsFromName } from "@/lib/format"
import { useCachedQuery } from "@/hooks/use-cached-query" import { signOutToSignIn } from "@/lib/session"
import { clearLocalData, signOutToSignIn } from "@/lib/session"
import { radius, spacing, useThemeColors } from "@/lib/theme" import { radius, spacing, useThemeColors } from "@/lib/theme"
import { showError, showSuccess } from "@/lib/toast" import { showError, showSuccess } from "@/lib/toast"
import type { PlaybackQuality } from "@/lib/urls" import type { PlaybackQuality } from "@/lib/urls"
@@ -74,7 +73,7 @@ const SECTIONS: SectionConfig[] = [
export default function SettingsScreen() { export default function SettingsScreen() {
const colors = useThemeColors() const colors = useThemeColors()
const router = useRouter() const router = useRouter()
const user = useCachedQuery(api.auth.currentUser) const user = useQuery(api.auth.currentUser)
const { invalidateSession } = useInvalidateAuthSession() const { invalidateSession } = useInvalidateAuthSession()
const { clearServer } = useServerConfig() const { clearServer } = useServerConfig()
const [section, setSection] = useState<Section>("profile") const [section, setSection] = useState<Section>("profile")
@@ -96,7 +95,6 @@ export default function SettingsScreen() {
async function handleChangeServer() { async function handleChangeServer() {
await invalidateSession() await invalidateSession()
await clearLocalData()
await clearServer() await clearServer()
router.replace("/server") router.replace("/server")
} }
@@ -462,7 +460,7 @@ function UsersSection({
<SettingsCard title="Sign Up"> <SettingsCard title="Sign Up">
<SwitchRow <SwitchRow
title="Disable account creation" title="Disable account creation"
subtitle="Stop people from registering themselves. Admins can still create accounts from the web app." subtitle="Prevent new users from creating accounts."
value={appSettings?.disableAccountCreation ?? false} value={appSettings?.disableAccountCreation ?? false}
onValueChange={(checked) => onValueChange={(checked) =>
void setDisableCreation({ disabled: checked }).catch( void setDisableCreation({ disabled: checked }).catch(
@@ -16,17 +16,18 @@ export default function LibraryLayout() {
screenOptions={({ route }) => ({ screenOptions={({ route }) => ({
...baseOptions, ...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Library", title: tabStackScreenTitles[route.name] ?? "Library",
headerRight: route.name === "settings" ? undefined : () => <ProfileHeaderButton />, headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems: unstable_headerRightItems:
route.name === "settings" route.name === "index"
? undefined ? () => [
: () => [
{ {
type: "custom", type: "custom",
element: <ProfileHeaderButton />, element: <ProfileHeaderButton />,
hidesSharedBackground: true, hidesSharedBackground: true,
}, },
], ]
: undefined,
})} })}
/> />
) )
@@ -1,3 +1,4 @@
import { usePaginatedQuery } from "convex/react"
import { useMemo } from "react" import { useMemo } from "react"
import { Pressable, StyleSheet, Text, View } from "react-native" import { Pressable, StyleSheet, Text, View } from "react-native"
import { SymbolView } from "expo-symbols" import { SymbolView } from "expo-symbols"
@@ -6,8 +7,7 @@ import { Ionicons } from "@expo/vector-icons"
import { MediaGridList } from "@/components/media-cards" import { MediaGridList } from "@/components/media-cards"
import { tabContentBottomInset } from "@/components/player" import { tabContentBottomInset } from "@/components/player"
import { MediaGridSkeleton } from "@/components/skeletons" import { LoadingView } from "@/components/ui/primitives"
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
import { useAppNavigation } from "@/lib/app-navigation" import { useAppNavigation } from "@/lib/app-navigation"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import { appleMusic, spacing, useThemeColors } from "@/lib/theme" import { appleMusic, spacing, useThemeColors } from "@/lib/theme"
@@ -49,7 +49,7 @@ function LibraryIcon({ name }: { name: (typeof links)[number]["icon"] }) {
export default function LibraryScreen() { export default function LibraryScreen() {
const { push } = useAppNavigation() const { push } = useAppNavigation()
const colors = useThemeColors() const colors = useThemeColors()
const { results, status, loadMore, isCached } = useCachedPaginatedQuery( const { results, status, loadMore } = usePaginatedQuery(
api.library.browseRecentlyAddedPaginated, api.library.browseRecentlyAddedPaginated,
{}, {},
{ initialNumItems: PAGE_SIZE } { initialNumItems: PAGE_SIZE }
@@ -83,11 +83,11 @@ export default function LibraryScreen() {
[colors.border, colors.foreground, colors.mutedForeground, push] [colors.border, colors.foreground, colors.mutedForeground, push]
) )
if (status === "LoadingFirstPage" && !isCached) { if (results === undefined) {
return ( return (
<View style={{ flex: 1, backgroundColor: colors.background }}> <View style={{ flex: 1, backgroundColor: colors.background }}>
{listHeader} {listHeader}
<MediaGridSkeleton contentInset={false} /> <LoadingView />
</View> </View>
) )
} }
@@ -16,17 +16,18 @@ export default function SearchLayout() {
screenOptions={({ route }) => ({ screenOptions={({ route }) => ({
...baseOptions, ...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Search", title: tabStackScreenTitles[route.name] ?? "Search",
headerRight: route.name === "settings" ? undefined : () => <ProfileHeaderButton />, headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems: unstable_headerRightItems:
route.name === "settings" route.name === "index"
? undefined ? () => [
: () => [
{ {
type: "custom", type: "custom",
element: <ProfileHeaderButton />, element: <ProfileHeaderButton />,
hidesSharedBackground: true, hidesSharedBackground: true,
}, },
], ]
: undefined,
})} })}
/> />
) )
+9 -15
View File
@@ -1,8 +1,5 @@
import { useConvexAuth as useLocalConvexAuth } from "@convex-dev/auth/react" import { useConvexAuth as useLocalConvexAuth } from "@convex-dev/auth/react"
import { import { useConvexAuth as useServerConvexAuth } from "convex/react"
useConvexAuth as useServerConvexAuth,
useConvexConnectionState,
} from "convex/react"
import { Redirect, Stack } from "expo-router" import { Redirect, Stack } from "expo-router"
import { Platform } from "react-native" import { Platform } from "react-native"
import { useEffect } from "react" import { useEffect } from "react"
@@ -23,21 +20,14 @@ export default function AppLayout() {
const { config } = useServerConfig() const { config } = useServerConfig()
const localAuth = useLocalConvexAuth() const localAuth = useLocalConvexAuth()
const serverAuth = useServerConvexAuth() const serverAuth = useServerConvexAuth()
const { isWebSocketConnected } = useConvexConnectionState()
const { invalidateSession } = useInvalidateAuthSession() const { invalidateSession } = useInvalidateAuthSession()
const stackOptions = useStackScreenOptions() const stackOptions = useStackScreenOptions()
useEffect(() => { useEffect(() => {
if ( if (!localAuth?.isAuthenticated || serverAuth?.isAuthenticated) {
!localAuth?.isAuthenticated ||
serverAuth?.isAuthenticated ||
!isWebSocketConnected
) {
return return
} }
// Only a reachable server that never accepts the session counts as a
// failed handshake; offline launches keep the session and cached data.
const timer = setTimeout(() => { const timer = setTimeout(() => {
void invalidateSession() void invalidateSession()
}, AUTH_HANDSHAKE_TIMEOUT_MS) }, AUTH_HANDSHAKE_TIMEOUT_MS)
@@ -45,7 +35,6 @@ export default function AppLayout() {
return () => clearTimeout(timer) return () => clearTimeout(timer)
}, [ }, [
invalidateSession, invalidateSession,
isWebSocketConnected,
localAuth?.isAuthenticated, localAuth?.isAuthenticated,
serverAuth?.isAuthenticated, serverAuth?.isAuthenticated,
]) ])
@@ -62,8 +51,13 @@ export default function AppLayout() {
return <Redirect href="/signin" /> return <Redirect href="/signin" />
} }
// Convex holds queries until the stored token is confirmed, so the app can if (!serverAuth || serverAuth.isLoading || serverAuth.isRefreshing) {
// render cached data while the server handshake is still in progress. return <LoadingView />
}
if (!serverAuth.isAuthenticated) {
return <LoadingView />
}
return ( return (
<ConvexAuthRecovery onInvalidate={invalidateSession}> <ConvexAuthRecovery onInvalidate={invalidateSession}>
+2 -4
View File
@@ -52,10 +52,8 @@ export default function PlayerScreen() {
skipPrevious, skipPrevious,
} = usePlayback() } = usePlayback()
const hasQueue = queueSongIds.length > 0
useEffect(() => { useEffect(() => {
if (hasQueue) { if (currentSong) {
hadSongRef.current = true hadSongRef.current = true
return return
} }
@@ -63,7 +61,7 @@ export default function PlayerScreen() {
if (hadSongRef.current) { if (hadSongRef.current) {
router.back() router.back()
} }
}, [hasQueue, router]) }, [currentSong, router])
if (!currentSong || !config) { if (!currentSong || !config) {
return null return null
@@ -10,10 +10,7 @@ import {
} from "react" } from "react"
import { LoadingView } from "@/components/ui/primitives" import { LoadingView } from "@/components/ui/primitives"
import { import { shouldInvalidateAuthSession } from "@/lib/auth-errors"
isConvexAuthError,
shouldInvalidateAuthSession,
} from "@/lib/auth-errors"
type ConvexAuthRecoveryProps = { type ConvexAuthRecoveryProps = {
children: ReactNode children: ReactNode
@@ -46,22 +43,10 @@ class ConvexAuthErrorBoundary extends Component<
} }
} }
componentDidUpdate(previous: ConvexAuthErrorBoundaryProps) {
// Screens render before the handshake finishes, so an auth error from that
// window clears once the server accepts the session.
if (
this.state.error &&
!previous.sessionEstablished &&
this.props.sessionEstablished
) {
this.setState({ error: null })
}
}
render() { render() {
const { error } = this.state const { error } = this.state
if (error) { if (error) {
if (isConvexAuthError(error)) { if (shouldInvalidateAuthSession(error, this.props.sessionEstablished)) {
return <LoadingView /> return <LoadingView />
} }
throw error throw error
@@ -1,8 +1,8 @@
import { useQuery } from "convex/react"
import { Image } from "expo-image" import { Image } from "expo-image"
import { useRouter } from "expo-router" import { useRouter } from "expo-router"
import { Pressable, StyleSheet, Text, View } from "react-native" import { Pressable, StyleSheet, Text, View } from "react-native"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { initialsFromName } from "@/lib/format" import { initialsFromName } from "@/lib/format"
import { radius, useThemeColors } from "@/lib/theme" import { radius, useThemeColors } from "@/lib/theme"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
@@ -10,7 +10,7 @@ import { api } from "@otunes/convex/_generated/api"
export function ProfileHeaderButton() { export function ProfileHeaderButton() {
const router = useRouter() const router = useRouter()
const colors = useThemeColors() const colors = useThemeColors()
const user = useCachedQuery(api.auth.currentUser) const user = useQuery(api.auth.currentUser)
return ( return (
<Pressable <Pressable
+5 -5
View File
@@ -1,12 +1,12 @@
import { useQuery } from "convex/react"
import { memo, useMemo } from "react" import { memo, useMemo } from "react"
import { FlatList, StyleSheet, Text, View } from "react-native" import { FlatList, StyleSheet, Text, View } from "react-native"
import { ContentCarousel } from "@/components/media-cards" import { ContentCarousel } from "@/components/media-cards"
import { tabContentBottomInset, SongRow } from "@/components/player" import { tabContentBottomInset, SongRow } from "@/components/player"
import { SongListSkeleton } from "@/components/skeletons" import { LoadingView } from "@/components/ui/primitives"
import { useFavorites } from "@/contexts/favorites" import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback" import { usePlaybackActions } from "@/contexts/playback"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import type { BrowseSong } from "@otunes/convex/types" import type { BrowseSong } from "@otunes/convex/types"
@@ -19,11 +19,11 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
const { handleSongAction } = useMediaMenuActions() const { handleSongAction } = useMediaMenuActions()
const hasQuery = searchQuery.length > 0 const hasQuery = searchQuery.length > 0
const results = useCachedQuery( const results = useQuery(
api.library.searchLibrary, api.library.searchLibrary,
hasQuery ? { query: searchQuery } : "skip" hasQuery ? { query: searchQuery } : "skip"
) )
const playlistResults = useCachedQuery( const playlistResults = useQuery(
api.playlists.searchPlaylists, api.playlists.searchPlaylists,
hasQuery ? { query: searchQuery } : "skip" hasQuery ? { query: searchQuery } : "skip"
) )
@@ -49,7 +49,7 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
) )
if (isSearching) { if (isSearching) {
return <SongListSkeleton /> return <LoadingView />
} }
if (!hasQuery) { if (!hasQuery) {
-257
View File
@@ -1,257 +0,0 @@
import { useEffect, useRef } from "react"
import {
Animated,
ScrollView,
StyleSheet,
View,
type DimensionValue,
type StyleProp,
type ViewStyle,
} from "react-native"
import { contentBottomInset } from "@/components/player"
import {
carouselCardWidth,
radius,
spacing,
useThemeColors,
useTwoColumnCardWidth,
} from "@/lib/theme"
export function Skeleton({ style }: { style?: StyleProp<ViewStyle> }) {
const colors = useThemeColors()
const opacity = useRef(new Animated.Value(1)).current
useEffect(() => {
const pulse = Animated.loop(
Animated.sequence([
Animated.timing(opacity, {
toValue: 0.5,
duration: 800,
useNativeDriver: true,
}),
Animated.timing(opacity, {
toValue: 1,
duration: 800,
useNativeDriver: true,
}),
])
)
pulse.start()
return () => pulse.stop()
}, [opacity])
return (
<Animated.View
style={[
{ backgroundColor: colors.muted, borderRadius: radius.sm, opacity },
style,
]}
/>
)
}
function TextLine({
width,
height = 14,
}: {
width: DimensionValue
height?: number
}) {
return <Skeleton style={{ width, height, borderRadius: 4 }} />
}
export function SongRowSkeleton() {
const colors = useThemeColors()
return (
<View style={[styles.songRow, { borderBottomColor: colors.border }]}>
<Skeleton style={styles.songArtwork} />
<View style={styles.songMeta}>
<TextLine width="60%" height={16} />
<TextLine width="40%" />
</View>
</View>
)
}
export function SongListSkeleton({ rows = 10 }: { rows?: number }) {
return (
<View accessibilityLabel="Loading" accessibilityRole="progressbar">
{Array.from({ length: rows }, (_, index) => (
<SongRowSkeleton key={index} />
))}
</View>
)
}
function CardSkeleton({
width,
round = false,
}: {
width: number
round?: boolean
}) {
return (
<View style={[styles.card, { width }]}>
<Skeleton
style={{
width,
height: width,
borderRadius: round ? width / 2 : radius.md,
}}
/>
<TextLine width="80%" />
{round ? null : <TextLine width="50%" height={12} />}
</View>
)
}
export function MediaGridSkeleton({
items = 6,
contentInset = true,
}: {
items?: number
contentInset?: boolean
}) {
const cardWidth = useTwoColumnCardWidth()
return (
<View
accessibilityLabel="Loading"
accessibilityRole="progressbar"
style={[
styles.grid,
contentInset ? styles.gridInset : styles.gridRowInset,
]}
>
{Array.from({ length: items }, (_, index) => (
<CardSkeleton key={index} width={cardWidth} />
))}
</View>
)
}
export function CarouselSkeleton() {
return (
<View style={styles.carousel}>
<TextLine width={160} height={22} />
<View style={styles.carouselRow}>
{Array.from({ length: 3 }, (_, index) => (
<CardSkeleton key={index} width={carouselCardWidth} />
))}
</View>
</View>
)
}
export function HomeSkeleton() {
const colors = useThemeColors()
return (
<ScrollView
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={styles.home}
contentInsetAdjustmentBehavior="automatic"
scrollEnabled={false}
accessibilityLabel="Loading"
>
<CarouselSkeleton />
<CarouselSkeleton />
</ScrollView>
)
}
/** Album and playlist pages: cover, title, play buttons, then tracks. */
export function CollectionDetailSkeleton({
round = false,
}: {
round?: boolean
}) {
const colors = useThemeColors()
const coverSize = round ? 180 : 210
return (
<ScrollView
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
scrollEnabled={false}
accessibilityLabel="Loading"
>
<View style={styles.hero}>
<Skeleton
style={{
width: coverSize,
height: coverSize,
borderRadius: round ? coverSize / 2 : radius.lg,
}}
/>
<TextLine width={200} height={24} />
<TextLine width={120} height={16} />
<View style={styles.actions}>
<Skeleton style={styles.iconAction} />
<Skeleton style={styles.playButton} />
<Skeleton style={styles.iconAction} />
</View>
</View>
{round ? (
<MediaGridSkeleton items={4} contentInset={false} />
) : (
<SongListSkeleton rows={8} />
)}
</ScrollView>
)
}
export function ArtistListSkeleton({ rows = 12 }: { rows?: number }) {
const colors = useThemeColors()
return (
<View accessibilityLabel="Loading" accessibilityRole="progressbar">
{Array.from({ length: rows }, (_, index) => (
<View
key={index}
style={[styles.artistRow, { borderBottomColor: colors.border }]}
>
<Skeleton style={styles.artistAvatar} />
<TextLine width="50%" height={16} />
</View>
))}
</View>
)
}
const styles = StyleSheet.create({
songRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
minHeight: 64,
paddingVertical: 10,
paddingHorizontal: spacing.lg,
borderBottomWidth: StyleSheet.hairlineWidth,
},
songArtwork: { width: 44, height: 44, borderRadius: 6 },
songMeta: { flex: 1, gap: 6 },
card: { gap: spacing.xs },
grid: { flexDirection: "row", flexWrap: "wrap", gap: spacing.md },
gridInset: { padding: spacing.lg },
gridRowInset: { paddingHorizontal: spacing.lg },
carousel: { gap: spacing.md },
carouselRow: { flexDirection: "row", gap: spacing.md },
home: { padding: spacing.lg, gap: spacing.xl },
hero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm },
actions: {
flexDirection: "row",
alignItems: "center",
gap: spacing.sm,
marginTop: spacing.sm,
},
iconAction: { width: 44, height: 44, borderRadius: 22 },
playButton: { width: 160, height: 44, borderRadius: 999 },
artistRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
paddingHorizontal: spacing.lg,
paddingVertical: spacing.md,
borderBottomWidth: StyleSheet.hairlineWidth,
},
artistAvatar: { width: 44, height: 44, borderRadius: 22 },
})
+12 -24
View File
@@ -1,4 +1,4 @@
import { useConvex, useMutation } from "convex/react" import { useConvex, useMutation, useQuery } from "convex/react"
import { import {
createContext, createContext,
useCallback, useCallback,
@@ -19,9 +19,6 @@ import {
} from "react-native" } from "react-native"
import { Button, Input } from "@/components/ui/primitives" import { Button, Input } from "@/components/ui/primitives"
import { useCacheScope } from "@/contexts/persistent-cache"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import type { OwnedPlaylistForAdd } from "@otunes/convex/types" import type { OwnedPlaylistForAdd } from "@otunes/convex/types"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
@@ -53,7 +50,6 @@ export function useAddToPlaylist() {
export function AddToPlaylistProvider({ children }: { children: ReactNode }) { export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
const convex = useConvex() const convex = useConvex()
const cacheScope = useCacheScope()
const { push } = useAppNavigation() const { push } = useAppNavigation()
const colors = useThemeColors() const colors = useThemeColors()
const addSongs = useMutation(api.playlists.addSongsToPlaylist) const addSongs = useMutation(api.playlists.addSongsToPlaylist)
@@ -67,7 +63,7 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
const [addingToPlaylistId, setAddingToPlaylistId] = const [addingToPlaylistId, setAddingToPlaylistId] =
useState<Id<"playlists"> | null>(null) useState<Id<"playlists"> | null>(null)
const selectionRequestIdRef = useRef(0) const selectionRequestIdRef = useRef(0)
const ownedPlaylists = useCachedQuery( const ownedPlaylists = useQuery(
api.playlists.listOwnedPlaylists, api.playlists.listOwnedPlaylists,
open ? {} : "skip" open ? {} : "skip"
) )
@@ -96,12 +92,9 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
async (albumId: Id<"albums">) => { async (albumId: Id<"albums">) => {
const requestId = ++selectionRequestIdRef.current const requestId = ++selectionRequestIdRef.current
try { try {
const songIds = await fetchCachedQuery( const songIds = await convex.query(api.playlists.getAlbumSongIds, {
convex, albumId,
cacheScope, })
api.playlists.getAlbumSongIds,
{ albumId }
)
if (selectionRequestIdRef.current !== requestId) return if (selectionRequestIdRef.current !== requestId) return
setPendingSongIds(songIds) setPendingSongIds(songIds)
setOpen(true) setOpen(true)
@@ -112,19 +105,16 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
) )
} }
}, },
[convex, cacheScope] [convex]
) )
const openAddPlaylistToPlaylist = useCallback( const openAddPlaylistToPlaylist = useCallback(
async (playlistId: Id<"playlists">) => { async (playlistId: Id<"playlists">) => {
const requestId = ++selectionRequestIdRef.current const requestId = ++selectionRequestIdRef.current
try { try {
const songIds = await fetchCachedQuery( const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
convex, playlistId,
cacheScope, })
api.playlists.getPlaylistSongIds,
{ playlistId }
)
if (selectionRequestIdRef.current !== requestId) return if (selectionRequestIdRef.current !== requestId) return
setPendingSongIds(songIds) setPendingSongIds(songIds)
setOpen(true) setOpen(true)
@@ -135,16 +125,14 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
) )
} }
}, },
[convex, cacheScope] [convex]
) )
const openAddArtistToPlaylist = useCallback( const openAddArtistToPlaylist = useCallback(
async (artistId: Id<"artists">) => { async (artistId: Id<"artists">) => {
const requestId = ++selectionRequestIdRef.current const requestId = ++selectionRequestIdRef.current
try { try {
const songIds = await fetchCachedQuery( const songIds = await convex.query(
convex,
cacheScope,
api.playlists.getOrderedArtistSongIds, api.playlists.getOrderedArtistSongIds,
{ artistId } { artistId }
) )
@@ -158,7 +146,7 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
) )
} }
}, },
[convex, cacheScope] [convex]
) )
const openCreatePlaylist = useCallback(() => { const openCreatePlaylist = useCallback(() => {
-3
View File
@@ -3,7 +3,6 @@ import { ConvexReactClient } from "convex/react"
import { useCallback, useMemo, useState, type ReactNode } from "react" import { useCallback, useMemo, useState, type ReactNode } from "react"
import { ConvexAuthSessionProvider } from "@/contexts/convex-auth-session" import { ConvexAuthSessionProvider } from "@/contexts/convex-auth-session"
import { PersistentCacheProvider } from "@/contexts/persistent-cache"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import { clearStoredAuthTokens, secureStorage } from "@/lib/auth-storage" import { clearStoredAuthTokens, secureStorage } from "@/lib/auth-storage"
@@ -36,9 +35,7 @@ export function ConvexAppProvider({ children }: { children: ReactNode }) {
storage={secureStorage} storage={secureStorage}
storageNamespace={config.convexUrl} storageNamespace={config.convexUrl}
> >
<PersistentCacheProvider serverUrl={config.serverUrl}>
{children} {children}
</PersistentCacheProvider>
</ConvexAuthProvider> </ConvexAuthProvider>
</ConvexAuthSessionProvider> </ConvexAuthSessionProvider>
) )
+2 -3
View File
@@ -1,4 +1,4 @@
import { useMutation } from "convex/react" import { useMutation, useQuery } from "convex/react"
import { import {
createContext, createContext,
useCallback, useCallback,
@@ -7,7 +7,6 @@ import {
type ReactNode, type ReactNode,
} from "react" } from "react"
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"
import { showError, showSuccess } from "@/lib/toast" import { showError, showSuccess } from "@/lib/toast"
@@ -33,7 +32,7 @@ export function useFavorites() {
} }
export function FavoritesProvider({ children }: { children: ReactNode }) { export function FavoritesProvider({ children }: { children: ReactNode }) {
const favorites = useCachedQuery(api.favorites.getUserFavorites) const favorites = useQuery(api.favorites.getUserFavorites)
const favoriteSong = useMutation( const favoriteSong = useMutation(
api.favorites.favoriteSong api.favorites.favoriteSong
).withOptimisticUpdate((store, { songId }) => { ).withOptimisticUpdate((store, { songId }) => {
-51
View File
@@ -1,51 +0,0 @@
import { useAuthToken } from "@convex-dev/auth/react"
import { createContext, useContext, useMemo, type ReactNode } from "react"
import { loadPersistentCache } from "@/lib/persistent-cache"
export const ANONYMOUS_CACHE_SCOPE = "anon"
const CacheScopeContext = createContext(ANONYMOUS_CACHE_SCOPE)
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 server and signed-in user. */
export function PersistentCacheProvider({
serverUrl,
children,
}: {
serverUrl: string
children: ReactNode
}) {
const token = useAuthToken()
const userId = userIdFromToken(token)
const scope = useMemo(
() => (userId ? `${serverUrl}|${userId}` : ANONYMOUS_CACHE_SCOPE),
[serverUrl, userId]
)
return (
<CacheScopeContext.Provider value={scope}>
{children}
</CacheScopeContext.Provider>
)
}
export function useCacheScope() {
return useContext(CacheScopeContext)
}
File diff suppressed because it is too large. Load diff
-88
View File
@@ -1,88 +0,0 @@
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 "@/contexts/persistent-cache"
import { queryCacheKey } from "@otunes/convex/client/cached-query"
import { readCache, subscribeCache, writeCache } from "@/lib/persistent-cache"
const MAX_CACHED_PAGINATED_ITEMS = 100
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
)
}
/**
* `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 }
}
+8 -31
View File
@@ -3,13 +3,11 @@ import { useCallback } from "react"
import type { MediaAction } from "@/components/media-context-menu" import type { MediaAction } from "@/components/media-context-menu"
import { useAddToPlaylist } from "@/contexts/add-to-playlist" import { useAddToPlaylist } from "@/contexts/add-to-playlist"
import { useCacheScope } from "@/contexts/persistent-cache"
import { useFavorites } from "@/contexts/favorites" import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback" import { usePlaybackActions } from "@/contexts/playback"
import { useAppNavigation } from "@/lib/app-navigation" import { useAppNavigation } from "@/lib/app-navigation"
import { showError, showSuccess } from "@/lib/toast" import { showError, showSuccess } from "@/lib/toast"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
import type { import type {
BrowseAlbum, BrowseAlbum,
@@ -30,7 +28,6 @@ async function runMediaAction(action: () => Promise<void>) {
export function useMediaMenuActions() { export function useMediaMenuActions() {
const convex = useConvex() const convex = useConvex()
const cacheScope = useCacheScope()
const { push } = useAppNavigation() const { push } = useAppNavigation()
const { const {
openAddToPlaylist, openAddToPlaylist,
@@ -113,12 +110,9 @@ export function useMediaMenuActions() {
case "play-next": case "play-next":
case "play-last": case "play-last":
case "shuffle": { case "shuffle": {
const songIds = await fetchCachedQuery( const songIds = await convex.query(api.playlists.getAlbumSongIds, {
convex, albumId: album.id as Id<"albums">,
cacheScope, })
api.playlists.getAlbumSongIds,
{ albumId: album.id as Id<"albums"> }
)
await runQueueAction(action, songIds) await runQueueAction(action, songIds)
break break
} }
@@ -130,14 +124,7 @@ export function useMediaMenuActions() {
} }
}) })
}, },
[ [convex, openAddAlbumToPlaylist, push, runQueueAction, toggleAlbumFavorite]
convex,
cacheScope,
openAddAlbumToPlaylist,
push,
runQueueAction,
toggleAlbumFavorite,
]
) )
const handleArtistAction = useCallback( const handleArtistAction = useCallback(
@@ -153,9 +140,7 @@ export function useMediaMenuActions() {
case "play-next": case "play-next":
case "play-last": case "play-last":
case "shuffle": { case "shuffle": {
const songIds = await fetchCachedQuery( const songIds = await convex.query(
convex,
cacheScope,
api.playlists.getOrderedArtistSongIds, api.playlists.getOrderedArtistSongIds,
{ artistId: artist.id as Id<"artists"> } { artistId: artist.id as Id<"artists"> }
) )
@@ -167,13 +152,7 @@ export function useMediaMenuActions() {
} }
}) })
}, },
[ [convex, openAddArtistToPlaylist, runQueueAction, toggleArtistFavorite]
convex,
cacheScope,
openAddArtistToPlaylist,
runQueueAction,
toggleArtistFavorite,
]
) )
const handlePlaylistAction = useCallback( const handlePlaylistAction = useCallback(
@@ -186,9 +165,7 @@ export function useMediaMenuActions() {
case "play-next": case "play-next":
case "play-last": case "play-last":
case "shuffle": { case "shuffle": {
const songIds = await fetchCachedQuery( const songIds = await convex.query(
convex,
cacheScope,
api.playlists.getPlaylistSongIds, api.playlists.getPlaylistSongIds,
{ {
playlistId: playlist.id as Id<"playlists">, playlistId: playlist.id as Id<"playlists">,
@@ -202,7 +179,7 @@ export function useMediaMenuActions() {
} }
}) })
}, },
[convex, cacheScope, openAddPlaylistToPlaylist, runQueueAction] [convex, openAddPlaylistToPlaylist, runQueueAction]
) )
const handleAlbumDetailAction = useCallback( const handleAlbumDetailAction = useCallback(
-67
View File
@@ -1,67 +0,0 @@
import AsyncStorage from "@react-native-async-storage/async-storage"
import {
configurePersistentCache,
type PersistentCacheBackend,
type PersistentCacheEntry,
} from "@otunes/convex/client/persistent-cache"
export * from "@otunes/convex/client/persistent-cache"
const KEY_PREFIX = "otunes-cache:"
const READ_BATCH_SIZE = 200
async function cacheStorageKeys() {
const keys = await AsyncStorage.getAllKeys()
return keys.filter((key) => key.startsWith(KEY_PREFIX))
}
const asyncStorageBackend: PersistentCacheBackend = {
async loadAll() {
const keys = await cacheStorageKeys()
const entries: Array<[string, PersistentCacheEntry]> = []
for (let start = 0; start < keys.length; start += READ_BATCH_SIZE) {
const pairs = await AsyncStorage.multiGet(
keys.slice(start, start + READ_BATCH_SIZE)
)
for (const [storageKey, raw] of pairs) {
if (!raw) continue
try {
entries.push([
storageKey.slice(KEY_PREFIX.length),
JSON.parse(raw) as PersistentCacheEntry,
])
} catch {
// Skip entries that were cut off mid-write.
}
}
}
return entries
},
async write(writes) {
const sets: [string, string][] = []
const removes: string[] = []
for (const [key, entry] of writes) {
if (entry === null) {
removes.push(KEY_PREFIX + key)
} else {
sets.push([KEY_PREFIX + key, JSON.stringify(entry)])
}
}
await Promise.all([
sets.length > 0 ? AsyncStorage.multiSet(sets) : null,
removes.length > 0 ? AsyncStorage.multiRemove(removes) : null,
])
},
async clear() {
await AsyncStorage.multiRemove(await cacheStorageKeys())
},
}
// Android's AsyncStorage database is capped at 6 MB by default, so keep fewer
// entries than the web cache.
configurePersistentCache(asyncStorageBackend, {
maxEntriesByPrefix: { q: 200, song: 3000, files: 500 },
})
-48
View File
@@ -1,48 +0,0 @@
import type { ConvexReactClient } from "convex/react"
import type { FunctionReturnType } from "convex/server"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import {
loadPersistentCache,
readCache,
writeCache,
} from "@/lib/persistent-cache"
export type PlaybackSong = NonNullable<
FunctionReturnType<typeof api.library.getSongsForPlayback>[number]
>
function filesKey(scope: string, songId: Id<"songs">) {
return `files:${scope}|${songId}`
}
/**
* Stream info for each song, served from this device when possible so a
* cached queue can start playing without waiting on Convex.
*/
export async function loadPlaybackSongs(
convex: ConvexReactClient,
scope: string,
songIds: Id<"songs">[]
): Promise<(PlaybackSong | null)[]> {
await loadPersistentCache()
const missing = songIds.filter(
(songId) => readCache<PlaybackSong>(filesKey(scope, songId)) === undefined
)
if (missing.length > 0) {
const fetched = await convex.query(api.library.getSongsForPlayback, {
ids: missing,
})
fetched.forEach((song, index) => {
if (song) {
writeCache(filesKey(scope, missing[index]), song)
}
})
}
return songIds.map(
(songId) => readCache<PlaybackSong>(filesKey(scope, songId)) ?? null
)
}
+34 -2
View File
@@ -1,5 +1,3 @@
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
@@ -11,6 +9,30 @@ 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(/\/+$/, "")
@@ -21,6 +43,16 @@ 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
-10
View File
@@ -1,21 +1,11 @@
import type { useRouter } from "expo-router" import type { useRouter } from "expo-router"
import { resetPlaybackStores } from "@otunes/convex/client/playback-store"
import { clearPersistentCache } from "@/lib/persistent-cache"
type AppRouter = ReturnType<typeof useRouter> type AppRouter = ReturnType<typeof useRouter>
/** Forgets this device's cached library and playback state. */
export async function clearLocalData() {
resetPlaybackStores()
await clearPersistentCache()
}
export async function signOutToSignIn( export async function signOutToSignIn(
router: Pick<AppRouter, "replace">, router: Pick<AppRouter, "replace">,
invalidateSession: () => Promise<void> invalidateSession: () => Promise<void>
) { ) {
await invalidateSession() await invalidateSession()
await clearLocalData()
router.replace("/signin") router.replace("/signin")
} }
-49
View File
@@ -1,49 +0,0 @@
import { useConvex } from "convex/react"
import { useEffect, useMemo, useSyncExternalStore } from "react"
import type { Id } from "@otunes/convex/_generated/dataModel"
import {
getCachedSong,
getSongsVersion,
requestSongs,
subscribeSongs,
} from "@otunes/convex/client/song-cache"
import { isPersistentCacheLoaded } from "@/lib/persistent-cache"
export {
albumDetailSongs,
getCachedSong,
rememberSongs,
} from "@otunes/convex/client/song-cache"
/**
* 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(subscribeSongs, getSongsVersion)
const songs = useMemo(
() => songIds.map((songId) => getCachedSong(songId)),
// songsVersion invalidates the lookup when the cache changes.
[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
}
-10
View File
@@ -1,10 +0,0 @@
import { HomeSkeleton, PageHeader } from "@/components/library-skeletons"
export default function Loading() {
return (
<div className="flex h-svh flex-col">
<PageHeader title="Home" />
<HomeSkeleton />
</div>
)
}
-42
View File
@@ -1,42 +0,0 @@
"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>
)
}
+6 -2
View File
@@ -1,5 +1,9 @@
import { CollectionDetailSkeleton } from "@/components/library-skeletons" import { LibraryLoading } from "@/components/library-loading"
export default function Loading() { export default function Loading() {
return <CollectionDetailSkeleton /> return (
<div className="flex h-svh flex-col">
<LibraryLoading />
</div>
)
} }
+23 -9
View File
@@ -1,7 +1,7 @@
import { AlbumPage } from "@/components/album-page" import { AlbumView } from "@/components/album-view"
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 }, convexServerOptions()) fetchQuery(api.library.browseAlbumDetail, { id })
) )
export async function generateMetadata({ export async function generateMetadata({
@@ -48,15 +48,29 @@ export async function generateMetadata({
} }
export default async function Page({ params, searchParams }: PageProps) { export default async function Page({ params, searchParams }: PageProps) {
const [{ id }, { s: highlightedSongId }] = await Promise.all([ const { id } = await params
params, const [{ s: highlightedSongId }, album] = await Promise.all([
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} />
}
+6 -2
View File
@@ -1,5 +1,9 @@
import { ArtistDetailSkeleton } from "@/components/library-skeletons" import { LibraryLoading } from "@/components/library-loading"
export default function Loading() { export default function Loading() {
return <ArtistDetailSkeleton /> return (
<div className="flex h-svh flex-col">
<LibraryLoading />
</div>
)
} }
+24 -4
View File
@@ -1,6 +1,6 @@
import { fetchQuery } from "convex/nextjs" import { fetchQuery } from "convex/nextjs"
import { convexServerOptions } from "@/lib/convex-server" import { ArtistView } from "@/components/artist-view"
import { ArtistPage } from "@/components/artist-page" import { LibraryLoading } from "@/components/library-loading"
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 }, convexServerOptions()) fetchQuery(api.library.browseArtistDetail, { id })
) )
export async function generateMetadata({ export async function generateMetadata({
@@ -38,5 +38,25 @@ 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
return <ArtistPage artistId={id as Id<"artists">} /> const data = await fetchArtistDetail(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} />
} }
@@ -1,10 +0,0 @@
import { CardGridSkeleton, PageHeader } from "@/components/library-skeletons"
export default function Loading() {
return (
<div className="flex h-svh flex-col">
<PageHeader title="Albums" />
<CardGridSkeleton />
</div>
)
}
+9 -7
View File
@@ -1,23 +1,25 @@
"use client" "use client"
import { useQuery } from "convex/react"
import { AlbumCard } from "@/components/album-card" import { AlbumCard } from "@/components/album-card"
import { CardGridSkeleton, PageHeader } from "@/components/library-skeletons" import { LibraryLoading } from "@/components/library-loading"
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 = useCachedQuery(api.library.browseAlbums) const albums = useQuery(api.library.browseAlbums)
return ( return (
<div className="flex h-svh flex-col"> <div className="flex h-svh flex-col">
<PageHeader title="Albums" /> <header className="flex items-center gap-2 border-b px-4 py-3">
<h1 className="text-lg font-semibold">Albums</h1>
</header>
{albums === undefined ? ( {albums === undefined ? (
<CardGridSkeleton /> <LibraryLoading />
) : ( ) : (
<div className="flex-1 overflow-y-auto p-6 pb-28"> <div className="flex-1 overflow-y-auto p-6 pb-28">
<div className={albumGridClassName}> <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">
{albums.map((album) => ( {albums.map((album) => (
<AlbumCard key={album.id} album={album} /> <AlbumCard key={album.id} album={album} />
))} ))}
@@ -1,21 +1,20 @@
import { fetchQuery } from "convex/nextjs" import { fetchQuery } from "convex/nextjs"
import { convexServerOptions } from "@/lib/convex-server" import { ArtistsView } from "@/components/artists-view"
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 fetchQuery( const artists = await fetchArtists()
api.library.browseArtists,
{},
convexServerOptions()
)
const selectedArtist = artists.find((artist) => artist.id === id) const selectedArtist = artists.find((artist) => artist.id === id)
return { return {
@@ -34,6 +33,19 @@ export async function generateMetadata({
} }
} }
export default function Page() { export default async function Page({ params }: PageProps) {
return null const { id } = await params
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>
)
} }
@@ -1,14 +0,0 @@
import { ArtistsPage } from "@/components/artists-page"
export default function ArtistsLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<>
<ArtistsPage />
{children}
</>
)
}
@@ -1,7 +0,0 @@
/**
* 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
}
+24 -2
View File
@@ -1,3 +1,25 @@
export default function Page() { import { fetchQuery } from "convex/nextjs"
return null import { ArtistsView } from "@/components/artists-view"
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>
)
} }
@@ -1,10 +0,0 @@
import { PageHeader, SongListSkeleton } from "@/components/library-skeletons"
export default function Loading() {
return (
<div className="flex h-svh flex-col">
<PageHeader title="Songs" />
<SongListSkeleton />
</div>
)
}
+50
View File
@@ -0,0 +1,50 @@
"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>
)
}
@@ -1,5 +0,0 @@
import { CollectionDetailSkeleton } from "@/components/library-skeletons"
export default function Loading() {
return <CollectionDetailSkeleton />
}
+24 -4
View File
@@ -1,8 +1,8 @@
import { PlaylistPage } from "@/components/playlist-page" import { LibraryLoading } from "@/components/library-loading"
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 },
convexServerOptions(token) { token }
) )
}) })
@@ -40,5 +40,25 @@ 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
return <PlaylistPage playlistId={id as Id<"playlists">} /> const playlist = await fetchPlaylistDetail(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} />
} }
@@ -1,5 +0,0 @@
import { CollectionDetailSkeleton } from "@/components/library-skeletons"
export default function Loading() {
return <CollectionDetailSkeleton />
}
+28 -2
View File
@@ -1,7 +1,33 @@
"use client" "use client"
import { FavoritesPlaylistPage } from "@/components/playlist-page" import { useQuery } from "convex/react"
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() {
return <FavoritesPlaylistPage /> const favorites = useQuery(api.favorites.browseFavoritesPlaylistDetail)
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} />
} }
-10
View File
@@ -1,10 +0,0 @@
import { CardGridSkeleton, PageHeader } from "@/components/library-skeletons"
export default function Loading() {
return (
<div className="flex h-svh flex-col">
<PageHeader title="Playlists" />
<CardGridSkeleton />
</div>
)
}
+5 -6
View File
@@ -1,17 +1,16 @@
"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 { CardGridSkeleton } from "@/components/library-skeletons" import { LibraryLoading } from "@/components/library-loading"
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 = useCachedQuery(api.playlists.listAllPlaylists) const playlists = useQuery(api.playlists.listAllPlaylists)
const { openCreatePlaylist } = useAddToPlaylist() const { openCreatePlaylist } = useAddToPlaylist()
return ( return (
@@ -30,10 +29,10 @@ export default function Page() {
</header> </header>
{playlists === undefined ? ( {playlists === undefined ? (
<CardGridSkeleton /> <LibraryLoading />
) : ( ) : (
<div className="flex-1 overflow-y-auto p-6 pb-28"> <div className="flex-1 overflow-y-auto p-6 pb-28">
<div className={albumGridClassName}> <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">
{playlists.map((playlist) => ( {playlists.map((playlist) => (
<PlaylistCard key={playlist.id} playlist={playlist} /> <PlaylistCard key={playlist.id} playlist={playlist} />
))} ))}
@@ -1,10 +0,0 @@
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>
)
}
+9 -7
View File
@@ -1,23 +1,25 @@
"use client" "use client"
import { useQuery } from "convex/react"
import { AlbumCard } from "@/components/album-card" import { AlbumCard } from "@/components/album-card"
import { CardGridSkeleton, PageHeader } from "@/components/library-skeletons" import { LibraryLoading } from "@/components/library-loading"
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 = useCachedQuery(api.library.browseRecentlyAdded, {}) const albums = useQuery(api.library.browseRecentlyAdded, {})
return ( return (
<div className="flex h-svh flex-col"> <div className="flex h-svh flex-col">
<PageHeader title="Recently Added" /> <header className="flex items-center gap-2 border-b px-4 py-3">
<h1 className="text-lg font-semibold">Recently Added</h1>
</header>
{albums === undefined ? ( {albums === undefined ? (
<CardGridSkeleton /> <LibraryLoading />
) : ( ) : (
<div className="flex-1 overflow-y-auto p-6 pb-28"> <div className="flex-1 overflow-y-auto p-6 pb-28">
<div className={albumGridClassName}> <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">
{albums.map((album) => ( {albums.map((album) => (
<AlbumCard key={album.id} album={album} /> <AlbumCard key={album.id} album={album} />
))} ))}
@@ -1,10 +0,0 @@
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>
)
}
+9 -7
View File
@@ -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 { CardGridSkeleton, PageHeader } from "@/components/library-skeletons" import { LibraryLoading } from "@/components/library-loading"
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,14 +20,16 @@ function RecentlyPlayedCard({
} }
export default function Page() { export default function Page() {
const recentlyPlayed = useCachedQuery(api.library.browseRecentlyPlayed, {}) const recentlyPlayed = useQuery(api.library.browseRecentlyPlayed, {})
return ( return (
<div className="flex h-svh flex-col"> <div className="flex h-svh flex-col">
<PageHeader title="Recently Played" /> <header className="flex items-center gap-2 border-b px-4 py-3">
<h1 className="text-lg font-semibold">Recently Played</h1>
</header>
{recentlyPlayed === undefined ? ( {recentlyPlayed === undefined ? (
<CardGridSkeleton /> <LibraryLoading />
) : 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">
@@ -36,7 +38,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={albumGridClassName}> <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">
{recentlyPlayed.map((item) => ( {recentlyPlayed.map((item) => (
<RecentlyPlayedCard key={item.id} item={item} /> <RecentlyPlayedCard key={item.id} item={item} />
))} ))}
-20
View File
@@ -1,20 +0,0 @@
"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>
)
}
+13 -8
View File
@@ -1,15 +1,14 @@
"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 { SearchResultsSkeleton } from "@/components/library-skeletons" import { LibraryLoading } from "@/components/library-loading"
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
@@ -31,11 +30,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 = useCachedQuery( const results = useQuery(
api.library.searchLibrary, api.library.searchLibrary,
hasQuery ? { query } : "skip" hasQuery ? { query } : "skip"
) )
const playlistResults = useCachedQuery( const playlistResults = useQuery(
api.playlists.searchPlaylists, api.playlists.searchPlaylists,
hasQuery ? { query } : "skip" hasQuery ? { query } : "skip"
) )
@@ -52,11 +51,17 @@ function SearchResults({ query }: { query: string }) {
const showResults = hasQuery && results !== undefined const showResults = hasQuery && results !== undefined
if (isSearching) { if (isSearching) {
return <SearchResultsSkeleton /> return <LibraryLoading />
} }
if (!hasQuery) { if (!hasQuery) {
return <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>
)
} }
if (!showResults) { if (!showResults) {
@@ -234,7 +239,7 @@ function SearchPageContent() {
export default function Page() { export default function Page() {
return ( return (
<Suspense fallback={<SearchResultsSkeleton />}> <Suspense fallback={<LibraryLoading />}>
<SearchPageContent /> <SearchPageContent />
</Suspense> </Suspense>
) )
+4 -15
View File
@@ -1,18 +1,7 @@
import { fetchQuery } from "convex/nextjs" "use client"
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"
export default async function SignInPage() { export default function SignInPage() {
await connection() return <AuthForm flow="signIn" />
const { disableAccountCreation } = await fetchQuery(
api.users.getAppSettings,
{},
convexServerOptions()
)
return (
<AuthForm flow="signIn" accountCreationDisabled={disableAccountCreation} />
)
} }
+4 -15
View File
@@ -1,18 +1,7 @@
import { fetchQuery } from "convex/nextjs" "use client"
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"
export default async function SignUpPage() { export default function SignUpPage() {
await connection() return <AuthForm flow="signUp" />
const { disableAccountCreation } = await fetchQuery(
api.users.getAppSettings,
{},
convexServerOptions()
)
return (
<AuthForm flow="signUp" accountCreationDisabled={disableAccountCreation} />
)
} }
+5 -31
View File
@@ -7,7 +7,6 @@ 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" })
@@ -16,31 +15,7 @@ const fontMono = Geist_Mono({
variable: "--font-mono", variable: "--font-mono",
}) })
async function hostedUrl() { export const metadata: Metadata = {
if (process.env.HOSTED_URL) {
return new URL(process.env.HOSTED_URL)
}
const requestHeaders = await headers()
const host = (
requestHeaders.get("x-forwarded-host") ?? requestHeaders.get("host")
)
?.split(",")[0]
.trim()
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",
appleWebApp: { appleWebApp: {
@@ -51,7 +26,7 @@ export async function generateMetadata(): Promise<Metadata> {
}, },
openGraph: { openGraph: {
type: "website", type: "website",
url, url: process.env.HOSTED_URL || "http://localhost:3000",
title: "oTunes", title: "oTunes",
description: "Our Music", description: "Our Music",
siteName: "oTunes", siteName: "oTunes",
@@ -61,8 +36,7 @@ export async function generateMetadata(): Promise<Metadata> {
}, },
], ],
}, },
metadataBase: url, metadataBase: new URL(process.env.HOSTED_URL || "http://localhost:3000"),
}
} }
export default function RootLayout({ export default function RootLayout({
@@ -82,8 +56,8 @@ export default function RootLayout({
)} )}
> >
<body className={"overflow-x-hidden"}> <body className={"overflow-x-hidden"}>
<ConvexAuthNextjsServerProvider storageNamespace="otunes"> <ConvexAuthNextjsServerProvider>
<ConvexClientProvider convexUrl={process.env.PUBLIC_CONVEX_URL}> <ConvexClientProvider>
<ThemeProvider> <ThemeProvider>
{children} {children}
<Toaster /> <Toaster />
@@ -6,7 +6,6 @@ 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,
@@ -20,7 +19,6 @@ 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 "@otunes/convex/client/cached-query"
function countSongsToAdd( function countSongsToAdd(
playlistSongIds: Id<"songs">[], playlistSongIds: Id<"songs">[],
@@ -82,7 +80,6 @@ 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)
@@ -120,14 +117,9 @@ export function AddToPlaylistProvider({
async (albumId: Id<"albums">) => { async (albumId: Id<"albums">) => {
const requestId = ++selectionRequestRef.current const requestId = ++selectionRequestRef.current
try { try {
const songIds = await fetchCachedQuery( const songIds = await convex.query(api.playlists.getAlbumSongIds, {
convex,
cacheScope,
api.playlists.getAlbumSongIds,
{
albumId, albumId,
} })
)
if (requestId === selectionRequestRef.current) { if (requestId === selectionRequestRef.current) {
showAddToPlaylist(songIds) showAddToPlaylist(songIds)
} }
@@ -139,21 +131,16 @@ export function AddToPlaylistProvider({
} }
} }
}, },
[convex, cacheScope, showAddToPlaylist] [convex, 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 fetchCachedQuery( const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
convex,
cacheScope,
api.playlists.getPlaylistSongIds,
{
playlistId, playlistId,
} })
)
if (requestId === selectionRequestRef.current) { if (requestId === selectionRequestRef.current) {
showAddToPlaylist(songIds) showAddToPlaylist(songIds)
} }
@@ -165,21 +152,16 @@ export function AddToPlaylistProvider({
} }
} }
}, },
[convex, cacheScope, showAddToPlaylist] [convex, 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 fetchCachedQuery( const songIds = await convex.query(api.playlists.getArtistSongIds, {
convex,
cacheScope,
api.playlists.getArtistSongIds,
{
artistId, artistId,
} })
)
if (requestId === selectionRequestRef.current) { if (requestId === selectionRequestRef.current) {
showAddToPlaylist(songIds) showAddToPlaylist(songIds)
} }
@@ -191,7 +173,7 @@ export function AddToPlaylistProvider({
} }
} }
}, },
[convex, cacheScope, showAddToPlaylist] [convex, showAddToPlaylist]
) )
const openCreatePlaylist = React.useCallback(() => { const openCreatePlaylist = React.useCallback(() => {
+2 -10
View File
@@ -6,7 +6,6 @@ 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 {
@@ -26,7 +25,6 @@ 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 "@otunes/convex/client/cached-query"
let activeAlbumCardMenuClose: (() => void) | null = null let activeAlbumCardMenuClose: (() => void) | null = null
@@ -45,7 +43,6 @@ 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()
@@ -80,14 +77,9 @@ 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 fetchCachedQuery( const songIds = await convex.query(api.playlists.getAlbumSongIds, {
convex,
cacheScope,
api.playlists.getAlbumSongIds,
{
albumId: album.id as Id<"albums">, albumId: album.id as Id<"albums">,
} })
)
void runQueueAction(action, songIds) void runQueueAction(action, songIds)
break break
} }
-34
View File
@@ -1,34 +0,0 @@
"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}
/>
)
}
+2 -15
View File
@@ -39,7 +39,6 @@ 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)
@@ -270,11 +269,6 @@ 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(() => {
@@ -404,21 +398,14 @@ export function AlbumView({
size="icon" size="icon"
className="rounded-full" className="rounded-full"
aria-label="Shuffle album" aria-label="Shuffle album"
onClick={() => onClick={() => void playAlbumShuffled(album.id as Id<"albums">)}
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={() => onClick={() => void playAlbum(album.id as Id<"albums">)}
void playAlbum(album.id as Id<"albums">, albumSongIds)
}
> >
<Play className="fill-current" /> <Play className="fill-current" />
Play Play
+3 -7
View File
@@ -41,11 +41,9 @@ 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 "@otunes/convex/client/playback-store"
const OptionsModal = dynamic(() => const OptionsModal = dynamic(() =>
import("@/components/options-modal").then((module) => module.OptionsModal) import("@/components/options-modal").then((module) => module.OptionsModal)
@@ -66,8 +64,8 @@ export function AppSidebar() {
const pathname = usePathname() const pathname = usePathname()
const router = useRouter() const router = useRouter()
const { signOut } = useAuthActions() const { signOut } = useAuthActions()
const user = useCachedQuery(api.auth.currentUser) const user = useQuery(api.auth.currentUser)
const sidebarPlaylists = useCachedQuery(api.playlists.listSidebarPlaylists) const sidebarPlaylists = useQuery(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()
@@ -76,8 +74,6 @@ export function AppSidebar() {
async function handleSignOut() { async function handleSignOut() {
await signOut() await signOut()
resetPlaybackStores()
await clearPersistentCache()
router.push("/signin") router.push("/signin")
} }
-22
View File
@@ -1,22 +0,0 @@
"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} />
}
+1 -6
View File
@@ -5,7 +5,6 @@ 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"
@@ -23,7 +22,6 @@ 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 "@otunes/convex/client/cached-query"
export function ArtistView({ export function ArtistView({
artist, artist,
@@ -37,7 +35,6 @@ 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) {
@@ -50,9 +47,7 @@ export function ArtistView({
case "play-next": case "play-next":
case "play-last": case "play-last":
case "shuffle": { case "shuffle": {
const songIds = await fetchCachedQuery( const songIds = await convex.query(
convex,
cacheScope,
api.playlists.getOrderedArtistSongIds, api.playlists.getOrderedArtistSongIds,
{ artistId: artist.id as Id<"artists"> } { artistId: artist.id as Id<"artists"> }
) )
-43
View File
@@ -1,43 +0,0 @@
"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>
)
}
+4 -9
View File
@@ -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,7 +24,6 @@ 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 "@otunes/convex/client/cached-query"
function ArtistAvatar({ artist }: { artist: BrowseArtist }) { function ArtistAvatar({ artist }: { artist: BrowseArtist }) {
return ( return (
@@ -92,13 +91,12 @@ 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]
@@ -111,7 +109,6 @@ 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()
@@ -144,9 +141,7 @@ export function ArtistsView({
case "play-next": case "play-next":
case "play-last": case "play-last":
case "shuffle": { case "shuffle": {
const songIds = await fetchCachedQuery( const songIds = await convex.query(
convex,
cacheScope,
api.playlists.getOrderedArtistSongIds, api.playlists.getOrderedArtistSongIds,
{ artistId: artistId as Id<"artists"> } { artistId: artistId as Id<"artists"> }
) )
@@ -167,7 +162,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={() => onSelectArtist(artist.id)} onSelect={() => router.push(`/library/artists/${artist.id}`)}
onMediaAction={(action) => onMediaAction={(action) =>
void handleMediaAction(artist.id, action) void handleMediaAction(artist.id, action)
} }
+5 -7
View File
@@ -4,8 +4,10 @@ import { useState } from "react"
import { useRouter } from "next/navigation" import { useRouter } from "next/navigation"
import Link from "next/link" import Link from "next/link"
import { useAuthActions } from "@convex-dev/auth/react" import { useAuthActions } from "@convex-dev/auth/react"
import { useQuery } from "convex/react"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { api } from "@otunes/convex/_generated/api"
import { import {
Card, Card,
CardContent, CardContent,
@@ -48,19 +50,15 @@ const copy: Record<
}, },
} }
export function AuthForm({ export function AuthForm({ flow }: { flow: AuthFlow }) {
flow,
accountCreationDisabled,
}: {
flow: AuthFlow
accountCreationDisabled: boolean
}) {
const { signIn } = useAuthActions() const { signIn } = useAuthActions()
const router = useRouter() const router = useRouter()
const appSettings = useQuery(api.users.getAppSettings)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false) const [submitting, setSubmitting] = useState(false)
const text = copy[flow] const text = copy[flow]
const accountCreationDisabled = appSettings?.disableAccountCreation ?? false
const signupsDisabled = flow === "signUp" && accountCreationDisabled const signupsDisabled = flow === "signUp" && accountCreationDisabled
const hideSignUpLink = flow === "signIn" && accountCreationDisabled const hideSignUpLink = flow === "signIn" && accountCreationDisabled
+5 -34
View File
@@ -1,44 +1,15 @@
"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"
import { PersistentCacheProvider } from "@/components/persistent-cache-provider" const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!)
// Server rendering never runs Convex queries, so this URL is never contacted. export function ConvexClientProvider({ children }: { children: ReactNode }) {
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={getConvexClient(convexUrl)}> <ConvexAuthNextjsProvider client={convex}>
<PersistentCacheProvider>{children}</PersistentCacheProvider> </ConvexAuthNextjsProvider> {children}
</ConvexAuthNextjsProvider>
) )
} }
+2 -3
View File
@@ -1,10 +1,9 @@
"use client" "use client"
import * as React from "react" import * as React from "react"
import { useMutation } from "convex/react" import { useMutation, useQuery } 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"
@@ -33,7 +32,7 @@ export function useFavorites() {
} }
export function FavoritesProvider({ children }: { children: React.ReactNode }) { export function FavoritesProvider({ children }: { children: React.ReactNode }) {
const favorites = useCachedQuery(api.favorites.getUserFavorites) const favorites = useQuery(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, {})
+9
View File
@@ -0,0 +1,9 @@
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>
)
}
-245
View File
@@ -1,245 +0,0 @@
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>
)
}
-6
View File
@@ -848,15 +848,9 @@ function UsersSection({
.catch((error: Error) => toast.error(error.message)) .catch((error: Error) => toast.error(error.message))
}} }}
/> />
<div className="space-y-1">
<Label htmlFor="disable-signups" className="font-normal"> <Label htmlFor="disable-signups" className="font-normal">
Disable account creation Disable account creation
</Label> </Label>
<p className="text-sm text-muted-foreground">
Stops people from registering themselves. You can still create
accounts.
</p>
</div>
</div> </div>
<Button type="button" size="sm" onClick={() => setCreateOpen(true)}> <Button type="button" size="sm" onClick={() => setCreateOpen(true)}>
<UserPlus /> <UserPlus />
-9
View File
@@ -1,9 +0,0 @@
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>
)
}
@@ -1,52 +0,0 @@
"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)
}
+184 -344
View File
@@ -12,7 +12,7 @@ import {
useSyncExternalStore, useSyncExternalStore,
useMemo, useMemo,
} from "react" } from "react"
import { useConvex, useMutation, useQuery } from "convex/react" import { 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,26 +20,13 @@ 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 "@otunes/convex/client/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 "@otunes/convex/client/playback-queue"
import type { RepeatMode } from "@otunes/convex/client/playback-queue"
import {
getPlaybackStore,
getServerPlaybackSnapshot,
} from "@otunes/convex/client/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">[]
@@ -66,23 +53,12 @@ type PlaybackContextValue = {
sortDirection: "asc" | "desc" sortDirection: "asc" | "desc"
} }
) => Promise<void> ) => Promise<void>
/** Pass `songIds` when the caller already has the album's tracks. */ playAlbum: (albumId: Id<"albums">) => Promise<void>
playAlbum: (albumId: Id<"albums">, songIds?: Id<"songs">[]) => Promise<void> playAlbumShuffled: (albumId: Id<"albums">) => 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>
/** Pass `songIds` when the caller already has the playlist's songs. */ playPlaylist: (playlistId: Id<"playlists">) => Promise<void>
playPlaylist: ( playPlaylistShuffled: (playlistId: Id<"playlists">) => Promise<void>
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>
@@ -303,62 +279,8 @@ export function usePlaybackProgress() {
} }
export function PlaybackProvider({ children }: { children: ReactNode }) { export function PlaybackProvider({ children }: { children: ReactNode }) {
const convex = useConvex() const user = useQuery(api.auth.currentUser)
const cacheScope = useCacheScope() const playback = useQuery(api.playback.getPlaybackState)
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)
@@ -370,6 +292,56 @@ 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)
@@ -409,29 +381,29 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
} }
}, []) }, [])
const queueSongIds = playback.queue const currentSong = playback?.currentSong ?? null
const currentSongId = queueSongIds[0] ?? null const currentSongId = currentSong?.id ?? 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 =
currentSongId && measuredDuration?.songId === currentSongId currentSong && measuredDuration?.songId === currentSong.id
? measuredDuration.seconds ? measuredDuration.seconds
: (currentSong?.durationSeconds ?? 0) : (currentSong?.durationSeconds ?? 0)
useEffect(() => { useEffect(() => {
durationRef.current = duration durationRef.current = duration
}, [duration]) }, [duration])
const currentSongDoc = useCachedQuery( const currentSongDoc = useQuery(
api.library.getSongPlaybackInfo, api.library.getSongPlaybackInfo,
currentSongId ? { id: currentSongId } : "skip" currentSong ? { id: currentSong.id } : "skip"
) )
const isPlaybackActive = Boolean(currentSongId && isPlaying) const isPlaybackActive = Boolean(currentSong && isPlaying)
const repeatEnabled = playback.repeatEnabled const repeatEnabled = playback?.repeatEnabled ?? "none"
const queueLength = queueSongIds.length const queueLength = playback?.queueSongIds.length ?? 0
const queueSongIds = playback?.queueSongIds ?? []
const nextQueueSongId = const nextQueueSongId =
queueSongIds.length > 1 ? queueSongIds[1] : null queueSongIds.length > 1 ? queueSongIds[1] : null
const nextQueueSongDoc = useCachedQuery( const nextQueueSongDoc = useQuery(
api.library.getSongPlaybackInfo, api.library.getSongPlaybackInfo,
nextQueueSongId ? { id: nextQueueSongId } : "skip" nextQueueSongId ? { id: nextQueueSongId } : "skip"
) )
@@ -467,19 +439,16 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
} }
lastSavedProgressRef.current = progressSeconds lastSavedProgressRef.current = progressSeconds
store.setProgress(currentSongId, progressSeconds)
if (isSignedIn) {
void updateSongProgressMutation({ void updateSongProgressMutation({
songId: currentSongId, songId: currentSongId,
progressSeconds, progressSeconds,
}).catch(() => {}) })
}
}, },
[currentSongId, store, isSignedIn, updateSongProgressMutation] [currentSongId, updateSongProgressMutation]
) )
useEffect(() => { useEffect(() => {
if (!currentSongId) { if (!currentSongId || !playback) {
return return
} }
@@ -489,8 +458,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
progressRestoredForSongRef.current = currentSongId progressRestoredForSongRef.current = currentSongId
lastSavedProgressRef.current = -1 lastSavedProgressRef.current = -1
setProgressToRestore(store.getState().progressSeconds) setProgressToRestore(playback.currentSongProgress ?? 0)
}, [currentSongId, store]) }, [currentSongId, playback])
useEffect(() => { useEffect(() => {
if (progressToRestore === null || progressToRestore <= 0) { if (progressToRestore === null || progressToRestore <= 0) {
@@ -551,36 +520,13 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
} }
saveProgress(audio.currentTime) saveProgress(audio.currentTime)
}, PROGRESS_SAVE_INTERVAL_MS) }, 5000)
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])
@@ -851,7 +797,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
useEffect(() => { useEffect(() => {
const audio = audioRef.current const audio = audioRef.current
if (!audio || !currentSongId) { if (!audio || !currentSong) {
return return
} }
@@ -881,7 +827,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
return () => { return () => {
audio.removeEventListener("canplay", onCanPlay) audio.removeEventListener("canplay", onCanPlay)
} }
}, [isPlaying, currentSongId, attemptPlayback]) }, [isPlaying, currentSong, attemptPlayback])
useEffect(() => { useEffect(() => {
const audio = audioRef.current const audio = audioRef.current
@@ -890,8 +836,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
} }
const handleEnded = () => { const handleEnded = () => {
const loopsSingleSong = repeatEnabled === "always" && queueLength === 1 if (repeatEnabled === "once") {
if (repeatEnabled === "once" || loopsSingleSong) {
audio.currentTime = 0 audio.currentTime = 0
void audio.play() void audio.play()
return return
@@ -940,23 +885,34 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
} }
} }
store.update(playbackQueue.skipNext) void skipNextMutation()
.then(() => {
if (shouldContinuePlaying) {
autoPlayNextRef.current = true
isPlayingRef.current = true
setIsPlaying(true)
return
}
if (!shouldContinuePlaying) {
autoPlayNextRef.current = false autoPlayNextRef.current = false
isPlayingRef.current = false isPlayingRef.current = false
audio.currentTime = 0 audio.currentTime = 0
currentTimeRef.current = 0 currentTimeRef.current = 0
setCurrentTime(0) setCurrentTime(0)
setIsPlaying(false) setIsPlaying(false)
} })
.catch(() => {
autoPlayNextRef.current = false
isPlayingRef.current = false
setIsPlaying(false)
})
} }
const handleError = () => { const handleError = () => {
if (intentionalLoadRef.current) { if (intentionalLoadRef.current) {
return return
} }
if (!currentSongId || playbackErrorHandledRef.current) { if (!currentSong || playbackErrorHandledRef.current) {
return return
} }
playbackErrorHandledRef.current = true playbackErrorHandledRef.current = true
@@ -980,7 +936,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.",
}) })
store.update(playbackQueue.clearQueue) void clearQueueMutation()
} }
audio.addEventListener("ended", handleEnded) audio.addEventListener("ended", handleEnded)
@@ -992,13 +948,14 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
} }
}, [ }, [
repeatEnabled, repeatEnabled,
currentSongId, currentSong,
queueLength, queueLength,
nextQueueSongId, nextQueueSongId,
nextQueueSongDoc, nextQueueSongDoc,
user, user,
dolbyAtmosSupported, dolbyAtmosSupported,
store, skipNextMutation,
clearQueueMutation,
destroyHls, destroyHls,
runWithoutAudioSync, runWithoutAudioSync,
attemptPlayback, attemptPlayback,
@@ -1011,17 +968,16 @@ 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: currentSongId, songId: currentSong.id,
seconds: currentSong.durationSeconds, seconds: currentSong.durationSeconds,
}) })
} }
@@ -1043,72 +999,17 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
audio.removeEventListener("loadedmetadata", syncDuration) audio.removeEventListener("loadedmetadata", syncDuration)
audio.removeEventListener("seeked", syncTime) audio.removeEventListener("seeked", syncTime)
} }
}, [currentSongId, currentSong]) }, [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
} }
startPlayback((state) => playbackQueue.startQueue(state, songIds, false)) await playInOrderMutation({ songIds })
setIsPlaying(true)
}, },
[startPlayback] [playInOrderMutation]
) )
const playShuffled = useCallback( const playShuffled = useCallback(
@@ -1116,9 +1017,10 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
if (songIds.length === 0) { if (songIds.length === 0) {
return return
} }
startPlayback((state) => playbackQueue.startQueue(state, songIds, true)) await playShuffledMutation({ songIds })
setIsPlaying(true)
}, },
[startPlayback] [playShuffledMutation]
) )
const addToQueueNext = useCallback( const addToQueueNext = useCallback(
@@ -1126,10 +1028,10 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
if (songIds.length === 0) { if (songIds.length === 0) {
return return
} }
store.update((state) => playbackQueue.addToQueue(state, songIds, "next")) await addToQueueNextMutation({ songIds })
setIsPlaying(true) setIsPlaying(true)
}, },
[store] [addToQueueNextMutation]
) )
const addToQueueLast = useCallback( const addToQueueLast = useCallback(
@@ -1137,19 +1039,18 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
if (songIds.length === 0) { if (songIds.length === 0) {
return return
} }
store.update((state) => playbackQueue.addToQueue(state, songIds, "last")) await addToQueueLastMutation({ songIds })
setIsPlaying(true) setIsPlaying(true)
}, },
[store] [addToQueueLastMutation]
) )
const playFromSong = useCallback( const playFromSong = useCallback(
async (songId: Id<"songs">, songIds: Id<"songs">[]) => { async (songId: Id<"songs">, songIds: Id<"songs">[]) => {
startPlayback((state) => await playFromSongMutation({ songId, songIds })
playbackQueue.startQueueFromSong(state, songId, songIds) setIsPlaying(true)
)
}, },
[startPlayback] [playFromSongMutation]
) )
const playFromLibrarySong = useCallback( const playFromLibrarySong = useCallback(
@@ -1160,155 +1061,84 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
sortDirection: "asc" | "desc" sortDirection: "asc" | "desc"
} }
) => { ) => {
startPlayback((state) => await playFromLibrarySongMutation({ songId, ...sort })
playbackQueue.startQueueFromSong(state, songId, [songId]) setIsPlaying(true)
)
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)
)
}
}, },
[convex, cacheScope, store, startPlayback] [playFromLibrarySongMutation]
)
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(
(albumId: Id<"albums">, songIds?: Id<"songs">[]) => async (albumId: Id<"albums">) => {
playCollection(loadAlbumSongIds(albumId, songIds), false), await playAlbumMutation({ albumId })
[playCollection, loadAlbumSongIds] setIsPlaying(true)
},
[playAlbumMutation]
) )
const playAlbumShuffled = useCallback( const playAlbumShuffled = useCallback(
(albumId: Id<"albums">, songIds?: Id<"songs">[]) => async (albumId: Id<"albums">) => {
playCollection(loadAlbumSongIds(albumId, songIds), true), await playAlbumShuffledMutation({ albumId })
[playCollection, loadAlbumSongIds] setIsPlaying(true)
},
[playAlbumShuffledMutation]
) )
const playArtist = useCallback( const playArtist = useCallback(
(artistId: Id<"artists">) => async (artistId: Id<"artists">) => {
playCollection(loadArtistSongIds(artistId), false), await playArtistMutation({ artistId })
[playCollection, loadArtistSongIds] setIsPlaying(true)
},
[playArtistMutation]
) )
const playArtistShuffled = useCallback( const playArtistShuffled = useCallback(
(artistId: Id<"artists">) => async (artistId: Id<"artists">) => {
playCollection(loadArtistSongIds(artistId), true), await playArtistShuffledMutation({ artistId })
[playCollection, loadArtistSongIds] setIsPlaying(true)
},
[playArtistShuffledMutation]
) )
const playPlaylist = useCallback( const playPlaylist = useCallback(
(playlistId: Id<"playlists">, songIds?: Id<"songs">[]) => async (playlistId: Id<"playlists">) => {
playCollection(loadPlaylistSongIds(playlistId, songIds), false, { await playPlaylistMutation({ playlistId })
playlistId, setIsPlaying(true)
}), },
[playCollection, loadPlaylistSongIds] [playPlaylistMutation]
) )
const playPlaylistShuffled = useCallback( const playPlaylistShuffled = useCallback(
(playlistId: Id<"playlists">, songIds?: Id<"songs">[]) => async (playlistId: Id<"playlists">) => {
playCollection(loadPlaylistSongIds(playlistId, songIds), true, { await playPlaylistShuffledMutation({ playlistId })
playlistId, setIsPlaying(true)
}), },
[playCollection, loadPlaylistSongIds] [playPlaylistShuffledMutation]
) )
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 before = store.getState() const isFinishingQueue =
if (before.repeatEnabled === "none" && before.queue.length <= 1) { repeatEnabled === "none" && queueSongIds.length <= 1
if (isFinishingQueue) {
setIsPlaying(false) setIsPlaying(false)
}
store.update(playbackQueue.skipNext)
if (store.getState().queue[0] === before.queue[0]) {
seekTo(0) seekTo(0)
} }
}, [store, seekTo]) await skipNextMutation()
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
} }
const previousSongId = store.getState().queue[0] await skipPreviousMutation()
store.update(playbackQueue.skipPrevious) }, [seekTo, skipPreviousMutation])
if (store.getState().queue[0] === previousSongId) {
seekTo(0)
}
}, [store, seekTo])
useMediaSession({ useMediaSession({
song: currentSong, song: currentSong,
@@ -1323,11 +1153,11 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
const value = useMemo<PlaybackContextValue>( const value = useMemo<PlaybackContextValue>(
() => ({ () => ({
queueSongIds: playback.queue, queueSongIds: playback?.queueSongIds ?? [],
queueHistorySongIds: playback.history, queueHistorySongIds: playback?.queueHistorySongIds ?? [],
currentSong, currentSong: playback?.currentSong ?? null,
shuffleEnabled: playback.shuffleEnabled, shuffleEnabled: playback?.shuffleEnabled ?? false,
repeatEnabled: playback.repeatEnabled, repeatEnabled: playback?.repeatEnabled ?? "none",
queueOpen, queueOpen,
isPlaying: isPlaybackActive, isPlaying: isPlaybackActive,
volume, volume,
@@ -1347,18 +1177,28 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
playArtistShuffled, playArtistShuffled,
playPlaylist, playPlaylist,
playPlaylistShuffled, playPlaylistShuffled,
toggleShuffle, toggleShuffle: async () => {
cycleRepeat, await toggleShuffleMutation()
clearQueue, },
reorderQueue, cycleRepeat: async () => {
skipToQueueIndex, await cycleRepeatMutation()
},
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,
@@ -1376,11 +1216,11 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
playArtistShuffled, playArtistShuffled,
playPlaylist, playPlaylist,
playPlaylistShuffled, playPlaylistShuffled,
toggleShuffle, toggleShuffleMutation,
cycleRepeat, cycleRepeatMutation,
clearQueue, clearQueueMutation,
reorderQueue, reorderQueueMutation,
skipToQueueIndex, skipToQueueIndexMutation,
skipNext, skipNext,
skipPrevious, skipPrevious,
dolbyAtmosSupported, dolbyAtmosSupported,
+2 -10
View File
@@ -9,7 +9,6 @@ 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,
@@ -24,11 +23,9 @@ 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 "@otunes/convex/client/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()
@@ -41,14 +38,9 @@ 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 fetchCachedQuery( const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
convex,
cacheScope,
api.playlists.getPlaylistSongIds,
{
playlistId: playlist.id as Id<"playlists">, playlistId: playlist.id as Id<"playlists">,
} })
)
void runQueueAction(action, songIds) void runQueueAction(action, songIds)
break break
} }
-38
View File
@@ -1,38 +0,0 @@
"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} />
}
+8 -28
View File
@@ -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 } from "convex/react" import { useMutation, useQuery } 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,7 +22,6 @@ 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"
@@ -31,7 +30,6 @@ 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,
@@ -265,7 +263,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 = useCachedQuery(api.auth.currentUser) const currentUser = useQuery(api.auth.currentUser)
const isOwner = const isOwner =
currentUser === undefined currentUser === undefined
? playlist.isOwner ? playlist.isOwner
@@ -279,8 +277,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
} = useFavorites() } = useFavorites()
const { const {
currentSong, currentSong,
playInOrder,
playShuffled,
playPlaylist, playPlaylist,
playPlaylistShuffled, playPlaylistShuffled,
playFromSong, playFromSong,
@@ -293,7 +289,6 @@ 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>()
) )
@@ -309,12 +304,6 @@ 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,
@@ -333,19 +322,6 @@ 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)
@@ -544,7 +520,9 @@ 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={() => playAll(true)} onClick={() =>
void playPlaylistShuffled(playlist.id as Id<"playlists">)
}
disabled={playlistSongIds.length === 0} disabled={playlistSongIds.length === 0}
> >
<Shuffle /> <Shuffle />
@@ -552,7 +530,9 @@ 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={() => playAll(false)} onClick={() =>
void playPlaylist(playlist.id as Id<"playlists">)
}
disabled={playlistSongIds.length === 0} disabled={playlistSongIds.length === 0}
> >
<Play className="fill-current" /> <Play className="fill-current" />
+72 -79
View File
@@ -2,17 +2,19 @@
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 { BrowseSong, HistorySong, QueueSong } from "@otunes/convex/types" import type { HistorySong, QueueSong } from "@otunes/convex/types"
import { albumCoverUrl } from "@/lib/cover-urls" import { albumCoverUrl } from "@/lib/cover-urls"
import { import {
getContiguousSelectedIndices, getContiguousSelectedIndices,
@@ -26,18 +28,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_INITIAL_VISIBLE_COUNT = 100 const QUEUE_PAGINATION_THRESHOLD = 100
const QUEUE_PAGE_SIZE = 50 const QUEUE_PAGE_SIZE = 50
type QueueSelectable = QueueSong & { selectionId: string } type QueueSelectable = QueueSong & { selectionId: string }
type QueueItem = { function getQueueVersion(queueSongIds: Id<"songs">[]) {
selectionId: string if (queueSongIds.length === 0) {
queueIndex: number return "empty"
song: QueueSelectable | null }
return `${queueSongIds.length}:${queueSongIds[0]}:${queueSongIds[queueSongIds.length - 1]}`
} }
function formatDuration(seconds: number): string { function formatDuration(seconds: number): string {
@@ -46,19 +48,11 @@ function formatDuration(seconds: number): string {
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}` return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
} }
function toSelectableQueue( function toSelectableQueue(songs: QueueSong[]): QueueSelectable[] {
songIds: Id<"songs">[], return songs.map((song) => ({
songs: (BrowseSong | undefined)[] ...song,
): QueueItem[] { selectionId: `${song.id}-${song.queueIndex}`,
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({
@@ -220,52 +214,39 @@ 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 { const { queueSongIds, queueOpen, clearQueue, skipToQueueIndex } =
queueSongIds, usePlayback()
queueHistorySongIds, const reorderQueue = useMutation(api.playback.reorderQueue)
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(
QUEUE_INITIAL_VISIBLE_COUNT const historySongs = useQuery(
api.playback.getQueueHistory,
queueOpen ? {} : "skip"
) )
const visibleQueueIds = React.useMemo( const queueVersion = React.useMemo(
() => queueSongIds.slice(0, visibleCount), () => getQueueVersion(queueSongIds),
[queueSongIds, visibleCount] [queueSongIds]
) )
const visibleQueueSongs = useSongs(visibleQueueIds) const shouldPaginate = queueSongIds.length > QUEUE_PAGINATION_THRESHOLD
const historySongMetadata = useSongs(queueHistorySongIds) const initialPageSize = shouldPaginate
const historySongs = React.useMemo( ? QUEUE_PAGE_SIZE
() => : queueSongIds.length
historySongMetadata.flatMap((song, historyIndex) =>
song ? [{ ...song, historyIndex }] : []
),
[historySongMetadata]
)
const hasMore = queueSongIds.length > visibleCount
const { results, status, loadMore } = usePaginatedQuery(
api.playback.getQueuePaginated,
queueOpen && queueSongIds.length > 0
? { queueVersion }
: "skip",
{ initialNumItems: initialPageSize }
)
const queueSongs = React.useMemo(() => results ?? [], [results])
const selectableQueue = React.useMemo( const selectableQueue = React.useMemo(
() => toSelectableQueue(visibleQueueIds, visibleQueueSongs), () => toSelectableQueue(queueSongs),
[visibleQueueIds, visibleQueueSongs] [queueSongs]
) )
const [dragIndex, setDragIndex] = React.useState<number | null>(null) const [dragIndex, setDragIndex] = React.useState<number | null>(null)
@@ -284,7 +265,7 @@ export function QueuePanel() {
}, [queueOpen, queueSongIds.length, currentQueueSongId]) }, [queueOpen, queueSongIds.length, currentQueueSongId])
React.useEffect(() => { React.useEffect(() => {
if (!hasMore) { if (!shouldPaginate) {
return return
} }
@@ -300,8 +281,8 @@ export function QueuePanel() {
const observer = new IntersectionObserver( const observer = new IntersectionObserver(
(entries) => { (entries) => {
if (entries[0]?.isIntersecting) { if (entries[0]?.isIntersecting && status === "CanLoadMore") {
setVisibleCount((count) => count + QUEUE_PAGE_SIZE) loadMore(QUEUE_PAGE_SIZE)
} }
}, },
{ root: viewport, rootMargin: "240px" } { root: viewport, rootMargin: "240px" }
@@ -309,7 +290,7 @@ export function QueuePanel() {
observer.observe(sentinel) observer.observe(sentinel)
return () => observer.disconnect() return () => observer.disconnect()
}, [hasMore]) }, [shouldPaginate, status, loadMore])
const { const {
selectedIds, selectedIds,
@@ -337,6 +318,16 @@ 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
@@ -359,7 +350,7 @@ export function QueuePanel() {
return return
} }
void reorderQueue(next) void persistOrder(next)
} }
if (!queueOpen) { if (!queueOpen) {
@@ -391,9 +382,13 @@ 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.length > 0 ? ( {historySongs && 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} />
@@ -401,20 +396,19 @@ export function QueuePanel() {
</ul> </ul>
) : null} ) : null}
<ul className="flex flex-col py-1"> <ul className="flex flex-col py-1">
{selectableQueue.map((item, index) => {selectableQueue.map((song, index) => (
item.song ? (
<QueueSongRow <QueueSongRow
key={item.selectionId} key={song.selectionId}
ref={item.queueIndex === 0 ? nowPlayingRef : undefined} ref={song.queueIndex === 0 ? nowPlayingRef : undefined}
song={item.song} song={song}
isNowPlaying={item.queueIndex === 0} isNowPlaying={song.queueIndex === 0}
selectionPosition={selectionPositions[index]} selectionPosition={selectionPositions[index]}
isDragging={draggingIndices.has(index)} isDragging={draggingIndices.has(index)}
onPointerDown={handlePointerDown} onPointerDown={handlePointerDown}
onSelect={(event) => { onSelect={(event) => {
handleSelect(item.selectionId, index, event) handleSelect(song.selectionId, index, event)
}} }}
onSkipTo={() => void skipToQueueIndex(item.queueIndex)} onSkipTo={() => void skipToQueueIndex(song.queueIndex)}
onDragStart={(event) => { onDragStart={(event) => {
setDragIndex(index) setDragIndex(index)
event.dataTransfer.effectAllowed = "move" event.dataTransfer.effectAllowed = "move"
@@ -425,18 +419,17 @@ export function QueuePanel() {
handleDrop(index) handleDrop(index)
}} }}
/> />
) : ( ))}
<QueueSongRowSkeleton key={item.selectionId} />
)
)}
</ul> </ul>
{hasMore ? ( {shouldPaginate ? (
<div <div
ref={loadMoreRef} ref={loadMoreRef}
className="flex items-center justify-center py-4" className="flex items-center justify-center py-4"
aria-hidden aria-hidden={status !== "LoadingMore"}
> >
{status === "LoadingMore" ? (
<Spinner className="size-5 text-muted-foreground" /> <Spinner className="size-5 text-muted-foreground" />
) : null}
</div> </div>
) : null} ) : null}
</> </>
-9
View File
@@ -1,9 +0,0 @@
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>
)
}
+5 -5
View File
@@ -3,6 +3,7 @@
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"
@@ -22,10 +23,9 @@ 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 { SongListSkeleton } from "@/components/library-skeletons" import { LibraryLoading } from "@/components/library-loading"
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, isCached } = useCachedPaginatedQuery( const { results, status, loadMore } = usePaginatedQuery(
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" && !isCached) { if (status === "LoadingFirstPage") {
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>
<SongListSkeleton /> <LibraryLoading />
</div> </div>
) )
} }
-92
View File
@@ -1,92 +0,0 @@
"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 "@otunes/convex/client/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 }
}
+1 -17
View File
@@ -2,25 +2,9 @@ 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(getConvexServerUrl()) client = new ConvexHttpClient(process.env.NEXT_PUBLIC_CONVEX_URL!)
} }
return client return client
} }
-116
View File
@@ -1,116 +0,0 @@
import {
configurePersistentCache,
type PersistentCacheBackend,
type PersistentCacheEntry,
} from "@otunes/convex/client/persistent-cache"
export * from "@otunes/convex/client/persistent-cache"
const DB_NAME = "otunes-cache"
const DB_VERSION = 1
const STORE_NAME = "entries"
let dbPromise: Promise<IDBDatabase | null> | null = null
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
}
const indexedDbBackend: PersistentCacheBackend = {
async loadAll() {
const db = await openDb()
if (!db) {
return []
}
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<PersistentCacheEntry[]>),
])
const entries: Array<[string, PersistentCacheEntry]> = []
keys.forEach((key, index) => {
const entry = values[index]
if (typeof key === "string" && entry) {
entries.push([key, entry])
}
})
return entries
},
async write(writes) {
const db = await openDb()
if (!db) {
return
}
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)
},
async clear() {
const db = await openDb()
if (!db) {
return
}
const transaction = db.transaction(STORE_NAME, "readwrite")
transaction.objectStore(STORE_NAME).clear()
await transactionDone(transaction)
},
}
if (typeof window !== "undefined") {
configurePersistentCache(indexedDbBackend, {
maxEntriesByPrefix: { q: 400, song: 5000 },
})
}
+8
View File
@@ -0,0 +1,8 @@
export function shuffleArray<T>(items: T[]): T[] {
const next = [...items]
for (let i = next.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[next[i], next[j]] = [next[j], next[i]]
}
return next
}
-54
View File
@@ -1,54 +0,0 @@
import { useConvex } from "convex/react"
import { useEffect, useMemo, useSyncExternalStore } from "react"
import type { Id } from "@otunes/convex/_generated/dataModel"
import {
getCachedSong,
getSongsVersion,
requestSongs,
subscribeSongs,
} from "@otunes/convex/client/song-cache"
import { isPersistentCacheLoaded } from "@/lib/persistent-cache"
export {
albumDetailSongs,
getCachedSong,
rememberSongs,
} from "@otunes/convex/client/song-cache"
/**
* 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(
subscribeSongs,
getSongsVersion,
() => 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
}
-7
View File
@@ -4,13 +4,6 @@ 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,
+2 -6
View File
@@ -3,7 +3,6 @@ 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([
@@ -16,8 +15,7 @@ const isPublic = createRouteMatcher([
"/playlist/:id", "/playlist/:id",
]) ])
export default convexAuthNextjsMiddleware( export default convexAuthNextjsMiddleware(async (request, { convexAuth }) => {
async (request, { convexAuth }) => {
if (isPublic(request)) { if (isPublic(request)) {
return return
} }
@@ -31,9 +29,7 @@ export default convexAuthNextjsMiddleware(
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)(.*)"],
-115
View File
@@ -1,115 +0,0 @@
#!/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=/usr/local/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"
-14
View File
@@ -1,14 +0,0 @@
// 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`)
-54
View File
@@ -1,54 +0,0 @@
import {
getFunctionName,
type FunctionArgs,
type FunctionReference,
type FunctionReturnType,
} from "convex/server"
import { convexToJson, type Value } from "convex/values"
import { loadPersistentCache, readCache, writeCache } from "./persistent-cache"
/** The part of `ConvexReactClient` the cache needs. */
export type QueryClient = {
query<Query extends FunctionReference<"query">>(
query: Query,
args: FunctionArgs<Query>
): Promise<FunctionReturnType<Query>>
}
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: QueryClient,
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
}
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff. Show more