Compare commits
12
Commits
No files matched your search
+116
-17
@@ -1,3 +1,5 @@
|
|||||||
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# Stage 1: Dependencies Installation Stage
|
# Stage 1: Dependencies Installation Stage
|
||||||
# ============================================
|
# ============================================
|
||||||
@@ -11,6 +13,11 @@ ARG NODE_VERSION=24.13.0-slim
|
|||||||
# https://github.com/get-convex/convex-backend/pkgs/container/convex-backend
|
# https://github.com/get-convex/convex-backend/pkgs/container/convex-backend
|
||||||
ARG CONVEX_BACKEND_IMAGE=ghcr.io/get-convex/convex-backend:5c7cb5bc7db457290f1769f95f1d1340912f7fd7
|
ARG CONVEX_BACKEND_IMAGE=ghcr.io/get-convex/convex-backend:5c7cb5bc7db457290f1769f95f1d1340912f7fd7
|
||||||
|
|
||||||
|
# Audio-only static ffmpeg. The distro package links video filters that pull
|
||||||
|
# in LLVM and Mesa (~420MB) for codecs this app never uses.
|
||||||
|
ARG FFMPEG_VERSION=7.1.5
|
||||||
|
ARG FFMPEG_SHA256=de668509caf9e35e3cd162473441fdb29538c6d96ed080292b3cf9e6fc5d558f
|
||||||
|
|
||||||
FROM node:${NODE_VERSION} AS node
|
FROM node:${NODE_VERSION} AS node
|
||||||
|
|
||||||
FROM node:${NODE_VERSION} AS dependencies
|
FROM node:${NODE_VERSION} AS dependencies
|
||||||
@@ -28,7 +35,12 @@ 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 && \
|
||||||
@@ -38,21 +50,20 @@ 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 — no need to re-copy node_modules from a blank image.
|
# Reuse the installed workspace. Copying node_modules into a new layer retars
|
||||||
|
# hundreds of thousands of files on every source change.
|
||||||
FROM dependencies AS builder
|
FROM dependencies AS builder
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Overlay sources; nested node_modules must be dockerignored so they do not
|
COPY apps/web /tmp/src/apps/web
|
||||||
# replace the install from the dependencies stage with host pnpm symlinks.
|
COPY packages/convex /tmp/src/packages/convex
|
||||||
COPY apps/web ./apps/web
|
|
||||||
COPY packages/convex ./packages/convex
|
|
||||||
|
|
||||||
# Re-apply the install tree after source COPY so module resolution cannot be
|
# Merge sources onto the install. cp does not remove the existing
|
||||||
# clobbered even if a nested node_modules slips into the build context.
|
# node_modules tree, and the build context already dockerignores it.
|
||||||
COPY --from=dependencies /app/node_modules ./node_modules
|
RUN cp -a /tmp/src/apps/web/. ./apps/web/ \
|
||||||
COPY --from=dependencies /app/apps/web/node_modules ./apps/web/node_modules
|
&& cp -a /tmp/src/packages/convex/. ./packages/convex/ \
|
||||||
COPY --from=dependencies /app/packages/convex/node_modules ./packages/convex/node_modules
|
&& rm -rf /tmp/src
|
||||||
|
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
@@ -75,7 +86,12 @@ COPY packages/convex/package.json ./packages/convex/
|
|||||||
RUN printf '%s\n' \
|
RUN printf '%s\n' \
|
||||||
'packages:' \
|
'packages:' \
|
||||||
' - "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 && \
|
||||||
@@ -83,19 +99,100 @@ RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
|
|||||||
|
|
||||||
COPY packages/convex ./packages/convex
|
COPY packages/convex ./packages/convex
|
||||||
|
|
||||||
|
# Source maps and the Convex package's TypeScript sources are not used at runtime.
|
||||||
|
RUN find /app -type f -name '*.map' -delete \
|
||||||
|
&& rm -rf /app/node_modules/.pnpm/convex@*/node_modules/convex/src
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# Stage 4: Run Convex and Next.js together
|
# Stage 4: Audio-only ffmpeg
|
||||||
# ============================================
|
# ============================================
|
||||||
|
|
||||||
FROM ${CONVEX_BACKEND_IMAGE} AS runner
|
FROM ubuntu:24.04 AS ffmpeg
|
||||||
|
|
||||||
|
ARG FFMPEG_VERSION
|
||||||
|
ARG FFMPEG_SHA256
|
||||||
|
|
||||||
RUN apt-get update && \
|
RUN apt-get update && \
|
||||||
apt-get install -y --no-install-recommends ffmpeg tini && \
|
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/*
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes
|
WORKDIR /src
|
||||||
|
|
||||||
COPY --from=node /usr/local/bin/node /opt/node/bin/node
|
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 --from=convex-functions /app /opt/otunes/convex
|
||||||
COPY docker/generate-auth-keys.mjs /opt/otunes/generate-auth-keys.mjs
|
COPY docker/generate-auth-keys.mjs /opt/otunes/generate-auth-keys.mjs
|
||||||
@@ -109,6 +206,8 @@ COPY --from=builder --chown=otunes:otunes /app/apps/web/.next/static ./apps/web/
|
|||||||
|
|
||||||
RUN mkdir -p apps/web/.next /data && chown -R otunes:otunes apps/web/.next
|
RUN mkdir -p apps/web/.next /data && chown -R otunes:otunes apps/web/.next
|
||||||
|
|
||||||
|
ENV PATH="/usr/local/bin:${PATH}"
|
||||||
|
|
||||||
EXPOSE 3000 3210
|
EXPOSE 3000 3210
|
||||||
|
|
||||||
HEALTHCHECK --interval=10s --timeout=5s --start-period=60s \
|
HEALTHCHECK --interval=10s --timeout=5s --start-period=60s \
|
||||||
|
|||||||
@@ -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,11 +9,13 @@ import {
|
|||||||
MediaActionMenu,
|
MediaActionMenu,
|
||||||
MediaContextMenu,
|
MediaContextMenu,
|
||||||
} from "@/components/media-actions-sheet"
|
} from "@/components/media-actions-sheet"
|
||||||
import { Button, LoadingView } from "@/components/ui/primitives"
|
import { CollectionDetailSkeleton } from "@/components/skeletons"
|
||||||
|
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"
|
||||||
@@ -21,6 +23,7 @@ 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"
|
||||||
|
|
||||||
@@ -29,7 +32,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 = useQuery(
|
const album = useCachedQuery(
|
||||||
api.library.browseAlbumDetail,
|
api.library.browseAlbumDetail,
|
||||||
typeof id === "string" ? { id: id as Id<"albums"> } : "skip"
|
typeof id === "string" ? { id: id as Id<"albums"> } : "skip"
|
||||||
)
|
)
|
||||||
@@ -49,6 +52,12 @@ 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 (
|
||||||
<>
|
<>
|
||||||
@@ -58,7 +67,7 @@ export default function AlbumScreen() {
|
|||||||
headerLargeTitle: false,
|
headerLargeTitle: false,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<LoadingView />
|
<CollectionDetailSkeleton />
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -159,14 +168,14 @@ export default function AlbumScreen() {
|
|||||||
<Button
|
<Button
|
||||||
title="Play"
|
title="Play"
|
||||||
icon="play"
|
icon="play"
|
||||||
onPress={() => void playAlbum(album.id)}
|
onPress={() => void playAlbum(album.id, songIds)}
|
||||||
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)}
|
onPress={() => void playAlbumShuffled(album.id, songIds)}
|
||||||
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,4 +1,3 @@
|
|||||||
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"
|
||||||
@@ -7,11 +6,13 @@ 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 { Button, LoadingView } from "@/components/ui/primitives"
|
import { CollectionDetailSkeleton } from "@/components/skeletons"
|
||||||
|
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"
|
||||||
@@ -22,7 +23,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 = useQuery(
|
const data = useCachedQuery(
|
||||||
api.library.browseArtistDetail,
|
api.library.browseArtistDetail,
|
||||||
typeof id === "string" ? { id: id as Id<"artists"> } : "skip"
|
typeof id === "string" ? { id: id as Id<"artists"> } : "skip"
|
||||||
)
|
)
|
||||||
@@ -40,7 +41,7 @@ export default function ArtistScreen() {
|
|||||||
headerLargeTitle: false,
|
headerLargeTitle: false,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<LoadingView />
|
<CollectionDetailSkeleton round />
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
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 { LoadingView } from "@/components/ui/primitives"
|
import { MediaGridSkeleton } from "@/components/skeletons"
|
||||||
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"
|
||||||
|
|
||||||
@@ -12,16 +15,20 @@ 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 } = usePaginatedQuery(
|
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
|
||||||
api.library.browseAlbumsPaginated,
|
api.library.browseAlbumsPaginated,
|
||||||
{},
|
{},
|
||||||
{ initialNumItems: PAGE_SIZE }
|
{ initialNumItems: PAGE_SIZE }
|
||||||
)
|
)
|
||||||
const searchResults = useQuery(
|
const searchResults = useCachedQuery(
|
||||||
api.library.searchLibrary,
|
api.library.searchLibrary,
|
||||||
searchQuery ? { query: searchQuery } : "skip"
|
searchQuery ? { query: searchQuery } : "skip"
|
||||||
)
|
)
|
||||||
const albums = searchQuery ? searchResults?.albums : results
|
const albums = searchQuery
|
||||||
|
? searchResults?.albums
|
||||||
|
: status === "LoadingFirstPage" && !isCached
|
||||||
|
? undefined
|
||||||
|
: results
|
||||||
|
|
||||||
const handleChangeText = useCallback(
|
const handleChangeText = useCallback(
|
||||||
(event: { nativeEvent: { text: string } }) => {
|
(event: { nativeEvent: { text: string } }) => {
|
||||||
@@ -46,7 +53,7 @@ export default function AlbumsScreen() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{searchBar}
|
{searchBar}
|
||||||
<LoadingView />
|
<MediaGridSkeleton />
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,17 @@
|
|||||||
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 { LoadingView } from "@/components/ui/primitives"
|
import { ArtistListSkeleton } from "@/components/skeletons"
|
||||||
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"
|
||||||
@@ -24,17 +27,21 @@ 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 } = usePaginatedQuery(
|
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
|
||||||
api.library.browseArtistsPaginated,
|
api.library.browseArtistsPaginated,
|
||||||
{},
|
{},
|
||||||
{ initialNumItems: PAGE_SIZE }
|
{ initialNumItems: PAGE_SIZE }
|
||||||
)
|
)
|
||||||
const searchResults = useQuery(
|
const searchResults = useCachedQuery(
|
||||||
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 ? searchResults?.artists : results
|
const artists = searchQuery
|
||||||
|
? searchResults?.artists
|
||||||
|
: status === "LoadingFirstPage" && !isCached
|
||||||
|
? undefined
|
||||||
|
: results
|
||||||
|
|
||||||
const handleChangeText = useCallback(
|
const handleChangeText = useCallback(
|
||||||
(event: { nativeEvent: { text: string } }) => {
|
(event: { nativeEvent: { text: string } }) => {
|
||||||
@@ -59,7 +66,7 @@ export default function ArtistsScreen() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{searchBar}
|
{searchBar}
|
||||||
<LoadingView />
|
<ArtistListSkeleton />
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 { LoadingView } from "@/components/ui/primitives"
|
import { MediaGridSkeleton } from "@/components/skeletons"
|
||||||
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 = useQuery(api.playlists.listAllPlaylists)
|
const playlists = useCachedQuery(api.playlists.listAllPlaylists)
|
||||||
const { openCreatePlaylist } = useAddToPlaylist()
|
const { openCreatePlaylist } = useAddToPlaylist()
|
||||||
|
|
||||||
if (playlists === undefined) {
|
if (playlists === undefined) {
|
||||||
@@ -38,7 +38,7 @@ export default function PlaylistsTabScreen() {
|
|||||||
),
|
),
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<LoadingView />
|
<MediaGridSkeleton />
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
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 { LoadingView } from "@/components/ui/primitives"
|
import { SongListSkeleton } from "@/components/skeletons"
|
||||||
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"
|
||||||
@@ -23,16 +26,20 @@ 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 } = usePaginatedQuery(
|
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
|
||||||
api.library.browseSongsPaginated,
|
api.library.browseSongsPaginated,
|
||||||
{ sortKey, sortDirection },
|
{ sortKey, sortDirection },
|
||||||
{ initialNumItems: PAGE_SIZE }
|
{ initialNumItems: PAGE_SIZE }
|
||||||
)
|
)
|
||||||
const searchResults = useQuery(
|
const searchResults = useCachedQuery(
|
||||||
api.library.searchLibrary,
|
api.library.searchLibrary,
|
||||||
searchQuery ? { query: searchQuery } : "skip"
|
searchQuery ? { query: searchQuery } : "skip"
|
||||||
)
|
)
|
||||||
const songs = searchQuery ? searchResults?.songs : results
|
const songs = searchQuery
|
||||||
|
? searchResults?.songs
|
||||||
|
: status === "LoadingFirstPage" && !isCached
|
||||||
|
? undefined
|
||||||
|
: results
|
||||||
|
|
||||||
const handleChangeText = useCallback(
|
const handleChangeText = useCallback(
|
||||||
(event: { nativeEvent: { text: string } }) => {
|
(event: { nativeEvent: { text: string } }) => {
|
||||||
@@ -57,7 +64,7 @@ export default function SongsScreen() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{searchBar}
|
{searchBar}
|
||||||
<LoadingView />
|
<SongListSkeleton />
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { usePaginatedQuery } from "convex/react"
|
import { memo } from "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 { LoadingView } from "@/components/ui/primitives"
|
import { HomeSkeleton } from "@/components/skeletons"
|
||||||
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,34 +38,26 @@ const HomeCarousels = memo(function HomeCarousels({
|
|||||||
|
|
||||||
export default function HomeScreen() {
|
export default function HomeScreen() {
|
||||||
const colors = useThemeColors()
|
const colors = useThemeColors()
|
||||||
const { results: recentlyAdded } = usePaginatedQuery(
|
const recentlyAdded = useCachedPaginatedQuery(
|
||||||
api.library.browseRecentlyAddedPaginated,
|
api.library.browseRecentlyAddedPaginated,
|
||||||
{},
|
{},
|
||||||
{ initialNumItems: CAROUSEL_ITEM_LIMIT }
|
{ initialNumItems: CAROUSEL_ITEM_LIMIT }
|
||||||
)
|
)
|
||||||
const { results: recentlyPlayed } = usePaginatedQuery(
|
const recentlyPlayed = useCachedPaginatedQuery(
|
||||||
api.library.browseRecentlyPlayedPaginated,
|
api.library.browseRecentlyPlayedPaginated,
|
||||||
{},
|
{},
|
||||||
{ initialNumItems: CAROUSEL_ITEM_LIMIT }
|
{ initialNumItems: CAROUSEL_ITEM_LIMIT }
|
||||||
)
|
)
|
||||||
const cachedData = useRef<{
|
|
||||||
recentlyAdded?: BrowseAlbum[]
|
|
||||||
recentlyPlayed?: (BrowseAlbum | PlaylistSummary)[]
|
|
||||||
}>({})
|
|
||||||
|
|
||||||
if (recentlyAdded !== undefined) {
|
const isLoading = [recentlyAdded, recentlyPlayed].some(
|
||||||
cachedData.current.recentlyAdded = recentlyAdded
|
(result) => result.status === "LoadingFirstPage" && !result.isCached
|
||||||
}
|
)
|
||||||
if (recentlyPlayed !== undefined) {
|
if (isLoading) {
|
||||||
cachedData.current.recentlyPlayed = recentlyPlayed
|
return <HomeSkeleton />
|
||||||
}
|
}
|
||||||
|
|
||||||
const added = recentlyAdded ?? cachedData.current.recentlyAdded
|
const added = recentlyAdded.results.slice(0, CAROUSEL_ITEM_LIMIT)
|
||||||
const played = recentlyPlayed ?? cachedData.current.recentlyPlayed
|
const played = recentlyPlayed.results.slice(0, CAROUSEL_ITEM_LIMIT)
|
||||||
|
|
||||||
if (added === undefined || played === undefined) {
|
|
||||||
return <LoadingView />
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ScrollView
|
<ScrollView
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useMutation, usePaginatedQuery, useQuery } from "convex/react"
|
import { useMutation } from "convex/react"
|
||||||
|
import { useEffect } from "react"
|
||||||
import {
|
import {
|
||||||
Button as SwiftUIButton,
|
Button as SwiftUIButton,
|
||||||
ContextMenu,
|
ContextMenu,
|
||||||
@@ -36,17 +37,23 @@ import {
|
|||||||
MediaActionMenu,
|
MediaActionMenu,
|
||||||
type MediaAction,
|
type MediaAction,
|
||||||
} from "@/components/media-actions-sheet"
|
} from "@/components/media-actions-sheet"
|
||||||
import { Button, LoadingView } from "@/components/ui/primitives"
|
import { CollectionDetailSkeleton } from "@/components/skeletons"
|
||||||
|
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"
|
||||||
@@ -60,7 +67,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 = useQuery(
|
const playlist = useCachedQuery(
|
||||||
api.playlists.browsePlaylistDetail,
|
api.playlists.browsePlaylistDetail,
|
||||||
playlistId
|
playlistId
|
||||||
? {
|
? {
|
||||||
@@ -73,12 +80,13 @@ export default function PlaylistScreen() {
|
|||||||
results: songs,
|
results: songs,
|
||||||
status,
|
status,
|
||||||
loadMore,
|
loadMore,
|
||||||
} = usePaginatedQuery(
|
isCached,
|
||||||
|
} = useCachedPaginatedQuery(
|
||||||
api.playlists.browsePlaylistSongsPaginated,
|
api.playlists.browsePlaylistSongsPaginated,
|
||||||
playlistId ? { id: playlistId } : "skip",
|
playlistId ? { id: playlistId } : "skip",
|
||||||
{ initialNumItems: PAGE_SIZE }
|
{ initialNumItems: PAGE_SIZE }
|
||||||
)
|
)
|
||||||
const allSongIds = useQuery(
|
const allSongIds = useCachedQuery(
|
||||||
api.playlists.getPlaylistSongIds,
|
api.playlists.getPlaylistSongIds,
|
||||||
playlistId ? { playlistId } : "skip"
|
playlistId ? { playlistId } : "skip"
|
||||||
)
|
)
|
||||||
@@ -100,10 +108,13 @@ export default function PlaylistScreen() {
|
|||||||
colors.background
|
colors.background
|
||||||
)
|
)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
rememberSongs(songs)
|
||||||
|
}, [songs])
|
||||||
|
|
||||||
if (
|
if (
|
||||||
playlist === undefined ||
|
playlist === undefined ||
|
||||||
songs === undefined ||
|
(status === "LoadingFirstPage" && !isCached) ||
|
||||||
allSongIds === undefined ||
|
|
||||||
!config
|
!config
|
||||||
) {
|
) {
|
||||||
return (
|
return (
|
||||||
@@ -114,7 +125,7 @@ export default function PlaylistScreen() {
|
|||||||
headerLargeTitle: false,
|
headerLargeTitle: false,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<LoadingView />
|
<CollectionDetailSkeleton />
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -137,7 +148,7 @@ export default function PlaylistScreen() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const songIds = allSongIds
|
const songIds = allSongIds ?? songs.map((song) => song.id)
|
||||||
const serverUrl = config.serverUrl
|
const serverUrl = config.serverUrl
|
||||||
|
|
||||||
function maybeLoadMore() {
|
function maybeLoadMore() {
|
||||||
@@ -346,9 +357,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)}
|
onPlay={() => playlist.id && void playPlaylist(playlist.id, allSongIds)}
|
||||||
onShuffle={() =>
|
onShuffle={() =>
|
||||||
playlist.id && void playPlaylistShuffled(playlist.id)
|
playlist.id && void playPlaylistShuffled(playlist.id, allSongIds)
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</RNHostView>
|
</RNHostView>
|
||||||
@@ -405,9 +416,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)}
|
onPlay={() => playlist.id && void playPlaylist(playlist.id, allSongIds)}
|
||||||
onShuffle={() =>
|
onShuffle={() =>
|
||||||
playlist.id && void playPlaylistShuffled(playlist.id)
|
playlist.id && void playPlaylistShuffled(playlist.id, allSongIds)
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,17 @@
|
|||||||
import { useQuery } from "convex/react"
|
import { useEffect } from "react"
|
||||||
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
|
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
|
||||||
|
|
||||||
import { Button, LoadingView } from "@/components/ui/primitives"
|
import { CollectionDetailSkeleton } from "@/components/skeletons"
|
||||||
|
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"
|
||||||
@@ -16,11 +19,17 @@ 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 = useQuery(api.favorites.browseFavoritesPlaylistDetail)
|
const favorites = useCachedQuery(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 (
|
||||||
<>
|
<>
|
||||||
@@ -30,7 +39,7 @@ export default function FavoritesScreen() {
|
|||||||
headerLargeTitle: false,
|
headerLargeTitle: false,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<LoadingView />
|
<CollectionDetailSkeleton />
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,59 +1,83 @@
|
|||||||
import { usePaginatedQuery, useQuery } from "convex/react"
|
|
||||||
import { Stack, useRouter } from "expo-router"
|
import { Stack, useRouter } from "expo-router"
|
||||||
import { useState } from "react"
|
import { memo, useCallback, useMemo } from "react"
|
||||||
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
|
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
|
||||||
|
|
||||||
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 { SongRowSkeleton } from "@/components/skeletons"
|
||||||
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
|
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
import type { BrowseSong } from "@otunes/convex/types"
|
import { useSong, useSongs } from "@/lib/song-cache"
|
||||||
import { spacing, useThemeColors } from "@/lib/theme"
|
import { spacing, useThemeColors } from "@/lib/theme"
|
||||||
import { showError } from "@/lib/toast"
|
|
||||||
|
|
||||||
const PAGE_SIZE = 50
|
type QueueItem = { songId: Id<"songs">; queueIndex: number }
|
||||||
|
|
||||||
|
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, currentSong } = usePlaybackQueue()
|
const { queueSongIds, queueHistorySongIds } = usePlaybackQueue()
|
||||||
const { skipToQueueIndex, clearQueue, reorderQueue } = usePlaybackActions()
|
const { skipToQueueIndex, clearQueue, reorderQueue } = usePlaybackActions()
|
||||||
const [reordering, setReordering] = useState(false)
|
const historySongs = useSongs(queueHistorySongIds)
|
||||||
|
|
||||||
const queueVersion = queueSongIds.length
|
const items = useMemo<QueueItem[]>(
|
||||||
? `${queueSongIds.length}:${queueSongIds[0]}:${queueSongIds[queueSongIds.length - 1]}`
|
() => queueSongIds.map((songId, queueIndex) => ({ songId, queueIndex })),
|
||||||
: "empty"
|
[queueSongIds]
|
||||||
|
|
||||||
const {
|
|
||||||
results: queueSongs,
|
|
||||||
status,
|
|
||||||
loadMore,
|
|
||||||
} = usePaginatedQuery(
|
|
||||||
api.playback.getQueuePaginated,
|
|
||||||
queueSongIds.length > 0 ? { queueVersion } : "skip",
|
|
||||||
{ initialNumItems: PAGE_SIZE }
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const historySongs = useQuery(api.playback.getQueueHistory)
|
const moveSong = useCallback(
|
||||||
|
(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)
|
||||||
setReordering(true)
|
void reorderQueue(next)
|
||||||
try {
|
},
|
||||||
await reorderQueue(next)
|
[queueSongIds, reorderQueue]
|
||||||
} 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()) {
|
||||||
@@ -67,10 +91,6 @@ export default function QueueScreen() {
|
|||||||
void clearQueue()
|
void clearQueue()
|
||||||
}
|
}
|
||||||
|
|
||||||
if (queueSongIds.length > 0 && queueSongs === undefined) {
|
|
||||||
return <LoadingView />
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Stack.Screen
|
<Stack.Screen
|
||||||
@@ -99,51 +119,35 @@ export default function QueueScreen() {
|
|||||||
) : null}
|
) : null}
|
||||||
</View>
|
</View>
|
||||||
}
|
}
|
||||||
data={queueSongs ?? []}
|
data={items}
|
||||||
keyExtractor={(item) => `${item.id}-${item.queueIndex}`}
|
keyExtractor={(item) => `${item.songId}-${item.queueIndex}`}
|
||||||
contentContainerStyle={{ paddingBottom: contentBottomInset }}
|
contentContainerStyle={{ paddingBottom: contentBottomInset }}
|
||||||
contentInsetAdjustmentBehavior="automatic"
|
contentInsetAdjustmentBehavior="automatic"
|
||||||
onEndReached={() => {
|
initialNumToRender={15}
|
||||||
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
|
|
||||||
}}
|
|
||||||
renderItem={({ item }) => (
|
renderItem={({ item }) => (
|
||||||
<View>
|
<QueueRow
|
||||||
<SongRow
|
{...item}
|
||||||
song={item}
|
isLast={item.queueIndex === queueSongIds.length - 1}
|
||||||
onPress={() => void skipToQueueIndex(item.queueIndex)}
|
isCurrent={item.queueIndex === 0}
|
||||||
|
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={
|
||||||
historySongs && historySongs.length > 0 ? (
|
queueHistorySongIds.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: BrowseSong) => (
|
{historySongs.map((song, index) =>
|
||||||
<SongRow key={song.id} song={song} />
|
song ? (
|
||||||
))}
|
<SongRow key={`${song.id}-${index}`} song={song} />
|
||||||
|
) : (
|
||||||
|
<SongRowSkeleton
|
||||||
|
key={`${queueHistorySongIds[index]}-${index}`}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
)}
|
||||||
</View>
|
</View>
|
||||||
) : null
|
) : null
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,20 @@
|
|||||||
import { usePaginatedQuery } from "convex/react"
|
|
||||||
|
|
||||||
import { MediaGridList } from "@/components/media-cards"
|
import { MediaGridList } from "@/components/media-cards"
|
||||||
import { LoadingView } from "@/components/ui/primitives"
|
import { MediaGridSkeleton } from "@/components/skeletons"
|
||||||
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 } = usePaginatedQuery(
|
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
|
||||||
api.library.browseRecentlyAddedPaginated,
|
api.library.browseRecentlyAddedPaginated,
|
||||||
{},
|
{},
|
||||||
{ initialNumItems: PAGE_SIZE }
|
{ initialNumItems: PAGE_SIZE }
|
||||||
)
|
)
|
||||||
|
|
||||||
if (results === undefined) {
|
if (status === "LoadingFirstPage" && !isCached) {
|
||||||
return <LoadingView />
|
return <MediaGridSkeleton />
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -1,21 +1,20 @@
|
|||||||
import { usePaginatedQuery } from "convex/react"
|
|
||||||
|
|
||||||
import { MediaGridList } from "@/components/media-cards"
|
import { MediaGridList } from "@/components/media-cards"
|
||||||
import { LoadingView } from "@/components/ui/primitives"
|
import { MediaGridSkeleton } from "@/components/skeletons"
|
||||||
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 } = usePaginatedQuery(
|
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
|
||||||
api.library.browseRecentlyPlayedPaginated,
|
api.library.browseRecentlyPlayedPaginated,
|
||||||
{},
|
{},
|
||||||
{ initialNumItems: PAGE_SIZE }
|
{ initialNumItems: PAGE_SIZE }
|
||||||
)
|
)
|
||||||
|
|
||||||
if (results === undefined) {
|
if (status === "LoadingFirstPage" && !isCached) {
|
||||||
return <LoadingView />
|
return <MediaGridSkeleton />
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -19,7 +19,8 @@ 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 { signOutToSignIn } from "@/lib/session"
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||||
|
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"
|
||||||
@@ -73,7 +74,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 = useQuery(api.auth.currentUser)
|
const user = useCachedQuery(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")
|
||||||
@@ -95,6 +96,7 @@ 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")
|
||||||
}
|
}
|
||||||
@@ -460,7 +462,7 @@ function UsersSection({
|
|||||||
<SettingsCard title="Sign Up">
|
<SettingsCard title="Sign Up">
|
||||||
<SwitchRow
|
<SwitchRow
|
||||||
title="Disable account creation"
|
title="Disable account creation"
|
||||||
subtitle="Prevent new users from creating accounts."
|
subtitle="Stop people from registering themselves. Admins can still create accounts from the web app."
|
||||||
value={appSettings?.disableAccountCreation ?? false}
|
value={appSettings?.disableAccountCreation ?? false}
|
||||||
onValueChange={(checked) =>
|
onValueChange={(checked) =>
|
||||||
void setDisableCreation({ disabled: checked }).catch(
|
void setDisableCreation({ disabled: checked }).catch(
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
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"
|
||||||
@@ -7,7 +6,8 @@ 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 { LoadingView } from "@/components/ui/primitives"
|
import { MediaGridSkeleton } from "@/components/skeletons"
|
||||||
|
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 } = usePaginatedQuery(
|
const { results, status, loadMore, isCached } = useCachedPaginatedQuery(
|
||||||
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 (results === undefined) {
|
if (status === "LoadingFirstPage" && !isCached) {
|
||||||
return (
|
return (
|
||||||
<View style={{ flex: 1, backgroundColor: colors.background }}>
|
<View style={{ flex: 1, backgroundColor: colors.background }}>
|
||||||
{listHeader}
|
{listHeader}
|
||||||
<LoadingView />
|
<MediaGridSkeleton contentInset={false} />
|
||||||
</View>
|
</View>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
import { useConvexAuth as useLocalConvexAuth } from "@convex-dev/auth/react"
|
import { useConvexAuth as useLocalConvexAuth } from "@convex-dev/auth/react"
|
||||||
import { useConvexAuth as useServerConvexAuth } from "convex/react"
|
import {
|
||||||
|
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"
|
||||||
@@ -20,14 +23,21 @@ 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 (!localAuth?.isAuthenticated || serverAuth?.isAuthenticated) {
|
if (
|
||||||
|
!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)
|
||||||
@@ -35,6 +45,7 @@ export default function AppLayout() {
|
|||||||
return () => clearTimeout(timer)
|
return () => clearTimeout(timer)
|
||||||
}, [
|
}, [
|
||||||
invalidateSession,
|
invalidateSession,
|
||||||
|
isWebSocketConnected,
|
||||||
localAuth?.isAuthenticated,
|
localAuth?.isAuthenticated,
|
||||||
serverAuth?.isAuthenticated,
|
serverAuth?.isAuthenticated,
|
||||||
])
|
])
|
||||||
@@ -51,13 +62,8 @@ export default function AppLayout() {
|
|||||||
return <Redirect href="/signin" />
|
return <Redirect href="/signin" />
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!serverAuth || serverAuth.isLoading || serverAuth.isRefreshing) {
|
// Convex holds queries until the stored token is confirmed, so the app can
|
||||||
return <LoadingView />
|
// render cached data while the server handshake is still in progress.
|
||||||
}
|
|
||||||
|
|
||||||
if (!serverAuth.isAuthenticated) {
|
|
||||||
return <LoadingView />
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ConvexAuthRecovery onInvalidate={invalidateSession}>
|
<ConvexAuthRecovery onInvalidate={invalidateSession}>
|
||||||
|
|||||||
@@ -52,8 +52,10 @@ export default function PlayerScreen() {
|
|||||||
skipPrevious,
|
skipPrevious,
|
||||||
} = usePlayback()
|
} = usePlayback()
|
||||||
|
|
||||||
|
const hasQueue = queueSongIds.length > 0
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (currentSong) {
|
if (hasQueue) {
|
||||||
hadSongRef.current = true
|
hadSongRef.current = true
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -61,7 +63,7 @@ export default function PlayerScreen() {
|
|||||||
if (hadSongRef.current) {
|
if (hadSongRef.current) {
|
||||||
router.back()
|
router.back()
|
||||||
}
|
}
|
||||||
}, [currentSong, router])
|
}, [hasQueue, router])
|
||||||
|
|
||||||
if (!currentSong || !config) {
|
if (!currentSong || !config) {
|
||||||
return null
|
return null
|
||||||
|
|||||||
@@ -10,7 +10,10 @@ import {
|
|||||||
} from "react"
|
} from "react"
|
||||||
|
|
||||||
import { LoadingView } from "@/components/ui/primitives"
|
import { LoadingView } from "@/components/ui/primitives"
|
||||||
import { shouldInvalidateAuthSession } from "@/lib/auth-errors"
|
import {
|
||||||
|
isConvexAuthError,
|
||||||
|
shouldInvalidateAuthSession,
|
||||||
|
} from "@/lib/auth-errors"
|
||||||
|
|
||||||
type ConvexAuthRecoveryProps = {
|
type ConvexAuthRecoveryProps = {
|
||||||
children: ReactNode
|
children: ReactNode
|
||||||
@@ -43,10 +46,22 @@ 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 (shouldInvalidateAuthSession(error, this.props.sessionEstablished)) {
|
if (isConvexAuthError(error)) {
|
||||||
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 = useQuery(api.auth.currentUser)
|
const user = useCachedQuery(api.auth.currentUser)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Pressable
|
<Pressable
|
||||||
|
|||||||
@@ -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 { LoadingView } from "@/components/ui/primitives"
|
import { SongListSkeleton } from "@/components/skeletons"
|
||||||
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 = useQuery(
|
const results = useCachedQuery(
|
||||||
api.library.searchLibrary,
|
api.library.searchLibrary,
|
||||||
hasQuery ? { query: searchQuery } : "skip"
|
hasQuery ? { query: searchQuery } : "skip"
|
||||||
)
|
)
|
||||||
const playlistResults = useQuery(
|
const playlistResults = useCachedQuery(
|
||||||
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 <LoadingView />
|
return <SongListSkeleton />
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!hasQuery) {
|
if (!hasQuery) {
|
||||||
|
|||||||
@@ -0,0 +1,257 @@
|
|||||||
|
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 },
|
||||||
|
})
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useConvex, useMutation, useQuery } from "convex/react"
|
import { useConvex, useMutation } from "convex/react"
|
||||||
import {
|
import {
|
||||||
createContext,
|
createContext,
|
||||||
useCallback,
|
useCallback,
|
||||||
@@ -19,6 +19,9 @@ 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"
|
||||||
@@ -50,6 +53,7 @@ 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)
|
||||||
@@ -63,7 +67,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 = useQuery(
|
const ownedPlaylists = useCachedQuery(
|
||||||
api.playlists.listOwnedPlaylists,
|
api.playlists.listOwnedPlaylists,
|
||||||
open ? {} : "skip"
|
open ? {} : "skip"
|
||||||
)
|
)
|
||||||
@@ -92,9 +96,12 @@ 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 convex.query(api.playlists.getAlbumSongIds, {
|
const songIds = await fetchCachedQuery(
|
||||||
albumId,
|
convex,
|
||||||
})
|
cacheScope,
|
||||||
|
api.playlists.getAlbumSongIds,
|
||||||
|
{ albumId }
|
||||||
|
)
|
||||||
if (selectionRequestIdRef.current !== requestId) return
|
if (selectionRequestIdRef.current !== requestId) return
|
||||||
setPendingSongIds(songIds)
|
setPendingSongIds(songIds)
|
||||||
setOpen(true)
|
setOpen(true)
|
||||||
@@ -105,16 +112,19 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[convex]
|
[convex, cacheScope]
|
||||||
)
|
)
|
||||||
|
|
||||||
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 convex.query(api.playlists.getPlaylistSongIds, {
|
const songIds = await fetchCachedQuery(
|
||||||
playlistId,
|
convex,
|
||||||
})
|
cacheScope,
|
||||||
|
api.playlists.getPlaylistSongIds,
|
||||||
|
{ playlistId }
|
||||||
|
)
|
||||||
if (selectionRequestIdRef.current !== requestId) return
|
if (selectionRequestIdRef.current !== requestId) return
|
||||||
setPendingSongIds(songIds)
|
setPendingSongIds(songIds)
|
||||||
setOpen(true)
|
setOpen(true)
|
||||||
@@ -125,14 +135,16 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[convex]
|
[convex, cacheScope]
|
||||||
)
|
)
|
||||||
|
|
||||||
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 convex.query(
|
const songIds = await fetchCachedQuery(
|
||||||
|
convex,
|
||||||
|
cacheScope,
|
||||||
api.playlists.getOrderedArtistSongIds,
|
api.playlists.getOrderedArtistSongIds,
|
||||||
{ artistId }
|
{ artistId }
|
||||||
)
|
)
|
||||||
@@ -146,7 +158,7 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[convex]
|
[convex, cacheScope]
|
||||||
)
|
)
|
||||||
|
|
||||||
const openCreatePlaylist = useCallback(() => {
|
const openCreatePlaylist = useCallback(() => {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ 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"
|
||||||
|
|
||||||
@@ -35,7 +36,9 @@ 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>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useMutation, useQuery } from "convex/react"
|
import { useMutation } from "convex/react"
|
||||||
import {
|
import {
|
||||||
createContext,
|
createContext,
|
||||||
useCallback,
|
useCallback,
|
||||||
@@ -7,6 +7,7 @@ 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"
|
||||||
@@ -32,7 +33,7 @@ export function useFavorites() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function FavoritesProvider({ children }: { children: ReactNode }) {
|
export function FavoritesProvider({ children }: { children: ReactNode }) {
|
||||||
const favorites = useQuery(api.favorites.getUserFavorites)
|
const favorites = useCachedQuery(api.favorites.getUserFavorites)
|
||||||
const favoriteSong = useMutation(
|
const favoriteSong = useMutation(
|
||||||
api.favorites.favoriteSong
|
api.favorites.favoriteSong
|
||||||
).withOptimisticUpdate((store, { songId }) => {
|
).withOptimisticUpdate((store, { songId }) => {
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
+347
-349
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,88 @@
|
|||||||
|
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 }
|
||||||
|
}
|
||||||
@@ -3,11 +3,13 @@ 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,
|
||||||
@@ -28,6 +30,7 @@ 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,
|
||||||
@@ -110,9 +113,12 @@ export function useMediaMenuActions() {
|
|||||||
case "play-next":
|
case "play-next":
|
||||||
case "play-last":
|
case "play-last":
|
||||||
case "shuffle": {
|
case "shuffle": {
|
||||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
const songIds = await fetchCachedQuery(
|
||||||
albumId: album.id as Id<"albums">,
|
convex,
|
||||||
})
|
cacheScope,
|
||||||
|
api.playlists.getAlbumSongIds,
|
||||||
|
{ albumId: album.id as Id<"albums"> }
|
||||||
|
)
|
||||||
await runQueueAction(action, songIds)
|
await runQueueAction(action, songIds)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -124,7 +130,14 @@ export function useMediaMenuActions() {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
[convex, openAddAlbumToPlaylist, push, runQueueAction, toggleAlbumFavorite]
|
[
|
||||||
|
convex,
|
||||||
|
cacheScope,
|
||||||
|
openAddAlbumToPlaylist,
|
||||||
|
push,
|
||||||
|
runQueueAction,
|
||||||
|
toggleAlbumFavorite,
|
||||||
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
const handleArtistAction = useCallback(
|
const handleArtistAction = useCallback(
|
||||||
@@ -140,7 +153,9 @@ export function useMediaMenuActions() {
|
|||||||
case "play-next":
|
case "play-next":
|
||||||
case "play-last":
|
case "play-last":
|
||||||
case "shuffle": {
|
case "shuffle": {
|
||||||
const songIds = await convex.query(
|
const songIds = await fetchCachedQuery(
|
||||||
|
convex,
|
||||||
|
cacheScope,
|
||||||
api.playlists.getOrderedArtistSongIds,
|
api.playlists.getOrderedArtistSongIds,
|
||||||
{ artistId: artist.id as Id<"artists"> }
|
{ artistId: artist.id as Id<"artists"> }
|
||||||
)
|
)
|
||||||
@@ -152,7 +167,13 @@ export function useMediaMenuActions() {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
[convex, openAddArtistToPlaylist, runQueueAction, toggleArtistFavorite]
|
[
|
||||||
|
convex,
|
||||||
|
cacheScope,
|
||||||
|
openAddArtistToPlaylist,
|
||||||
|
runQueueAction,
|
||||||
|
toggleArtistFavorite,
|
||||||
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
const handlePlaylistAction = useCallback(
|
const handlePlaylistAction = useCallback(
|
||||||
@@ -165,7 +186,9 @@ export function useMediaMenuActions() {
|
|||||||
case "play-next":
|
case "play-next":
|
||||||
case "play-last":
|
case "play-last":
|
||||||
case "shuffle": {
|
case "shuffle": {
|
||||||
const songIds = await convex.query(
|
const songIds = await fetchCachedQuery(
|
||||||
|
convex,
|
||||||
|
cacheScope,
|
||||||
api.playlists.getPlaylistSongIds,
|
api.playlists.getPlaylistSongIds,
|
||||||
{
|
{
|
||||||
playlistId: playlist.id as Id<"playlists">,
|
playlistId: playlist.id as Id<"playlists">,
|
||||||
@@ -179,7 +202,7 @@ export function useMediaMenuActions() {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
[convex, openAddPlaylistToPlaylist, runQueueAction]
|
[convex, cacheScope, openAddPlaylistToPlaylist, runQueueAction]
|
||||||
)
|
)
|
||||||
|
|
||||||
const handleAlbumDetailAction = useCallback(
|
const handleAlbumDetailAction = useCallback(
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
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 },
|
||||||
|
})
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
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
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,11 +1,21 @@
|
|||||||
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")
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
@@ -20,7 +20,7 @@ import { Input } from "@/components/ui/input"
|
|||||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
import { fetchCachedQuery } from "@/lib/cached-query"
|
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
|
||||||
|
|
||||||
function countSongsToAdd(
|
function countSongsToAdd(
|
||||||
playlistSongIds: Id<"songs">[],
|
playlistSongIds: Id<"songs">[],
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ import type { BrowseAlbum } from "@otunes/convex/types"
|
|||||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
import { albumCoverUrl } from "@/lib/cover-urls"
|
import { albumCoverUrl } from "@/lib/cover-urls"
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils"
|
||||||
import { fetchCachedQuery } from "@/lib/cached-query"
|
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
|
||||||
|
|
||||||
let activeAlbumCardMenuClose: (() => void) | null = null
|
let activeAlbumCardMenuClose: (() => void) | null = null
|
||||||
|
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ import { api } from "@otunes/convex/_generated/api"
|
|||||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
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 { clearPersistentCache } from "@/lib/persistent-cache"
|
||||||
import { resetPlaybackStores } from "@/lib/playback-store"
|
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)
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ import type { Id } from "@otunes/convex/_generated/dataModel"
|
|||||||
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
|
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
|
||||||
import { albumGridClassName } from "@/lib/album-grid-classes"
|
import { albumGridClassName } from "@/lib/album-grid-classes"
|
||||||
import { artistCoverUrl } from "@/lib/cover-urls"
|
import { artistCoverUrl } from "@/lib/cover-urls"
|
||||||
import { fetchCachedQuery } from "@/lib/cached-query"
|
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
|
||||||
|
|
||||||
export function ArtistView({
|
export function ArtistView({
|
||||||
artist,
|
artist,
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ import { cn } from "@/lib/utils"
|
|||||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||||
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
|
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
|
||||||
import { artistCoverUrl } from "@/lib/cover-urls"
|
import { artistCoverUrl } from "@/lib/cover-urls"
|
||||||
import { fetchCachedQuery } from "@/lib/cached-query"
|
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
|
||||||
|
|
||||||
function ArtistAvatar({ artist }: { artist: BrowseArtist }) {
|
function ArtistAvatar({ artist }: { artist: BrowseArtist }) {
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
CarouselItem,
|
CarouselItem,
|
||||||
CarouselNext,
|
CarouselNext,
|
||||||
CarouselPrevious,
|
CarouselPrevious,
|
||||||
|
useCarousel,
|
||||||
} from "@/components/ui/carousel"
|
} from "@/components/ui/carousel"
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils"
|
||||||
import { ArtistCard } from "./artist-card"
|
import { ArtistCard } from "./artist-card"
|
||||||
@@ -34,6 +35,34 @@ function CarouselCard({
|
|||||||
return <ArtistCard artist={item} />
|
return <ArtistCard artist={item} />
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const carouselNavButtonClassName =
|
||||||
|
"pointer-events-none z-10 h-16! w-6! border-0 bg-primary text-primary-foreground opacity-0 shadow-md transition-opacity hover:bg-primary/80 hover:text-primary-foreground focus-visible:pointer-events-auto! focus-visible:opacity-100! group-hover/carousel:pointer-events-auto! group-hover/carousel:opacity-100! group-focus-within/carousel:pointer-events-auto! group-focus-within/carousel:opacity-100! active:not-aria-[haspopup]:-translate-y-1/2 dark:bg-primary dark:text-primary-foreground dark:hover:bg-primary/80 [@media(hover:none)]:pointer-events-auto! [@media(hover:none)]:opacity-100!"
|
||||||
|
|
||||||
|
function CarouselControls() {
|
||||||
|
const { canScrollPrev, canScrollNext } = useCarousel()
|
||||||
|
|
||||||
|
if (!canScrollPrev && !canScrollNext) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="pointer-events-none absolute inset-x-8 top-0 z-10 aspect-[2/1] sm:aspect-[3/1] md:aspect-[4/1] lg:aspect-[5/1] xl:aspect-[6/1]">
|
||||||
|
{canScrollPrev ? (
|
||||||
|
<CarouselPrevious
|
||||||
|
variant="default"
|
||||||
|
className={cn(carouselNavButtonClassName, "-left-8")}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
{canScrollNext ? (
|
||||||
|
<CarouselNext
|
||||||
|
variant="default"
|
||||||
|
className={cn(carouselNavButtonClassName, "-right-8")}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
export function ContentCarousel({
|
export function ContentCarousel({
|
||||||
title,
|
title,
|
||||||
href,
|
href,
|
||||||
@@ -51,6 +80,7 @@ export function ContentCarousel({
|
|||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<section className={cn("flex min-w-0 flex-col gap-4", className)}>
|
<section className={cn("flex min-w-0 flex-col gap-4", className)}>
|
||||||
|
<div className="px-8">
|
||||||
{href ? (
|
{href ? (
|
||||||
<Link
|
<Link
|
||||||
href={href}
|
href={href}
|
||||||
@@ -62,29 +92,24 @@ export function ContentCarousel({
|
|||||||
) : (
|
) : (
|
||||||
<h2 className="text-xl font-bold tracking-tight">{title}</h2>
|
<h2 className="text-xl font-bold tracking-tight">{title}</h2>
|
||||||
)}
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
<Carousel
|
<Carousel
|
||||||
opts={{
|
opts={{
|
||||||
align: "start",
|
align: "start",
|
||||||
dragFree: true,
|
dragFree: true,
|
||||||
containScroll: false,
|
slidesToScroll: "auto",
|
||||||
slidesToScroll: 5,
|
|
||||||
}}
|
}}
|
||||||
className="relative min-w-0"
|
className="group/carousel relative min-w-0 px-8"
|
||||||
>
|
|
||||||
<CarouselContent
|
|
||||||
className={cn("w-full", carouselContentClassName)}
|
|
||||||
>
|
>
|
||||||
|
<CarouselContent className={cn("w-full", carouselContentClassName)}>
|
||||||
{content.map((item) => (
|
{content.map((item) => (
|
||||||
<CarouselItem key={item.id} className={slideClassName}>
|
<CarouselItem key={item.id} className={slideClassName}>
|
||||||
<CarouselCard item={item} />
|
<CarouselCard item={item} />
|
||||||
</CarouselItem>
|
</CarouselItem>
|
||||||
))}
|
))}
|
||||||
</CarouselContent>
|
</CarouselContent>
|
||||||
<div className="pointer-events-none absolute top-1/2 flex w-1/2 -translate-y-1/2 justify-between sm:w-2/3 md:w-3/4 lg:w-4/5 xl:w-5/6">
|
<CarouselControls />
|
||||||
<CarouselPrevious className="relative -left-4 h-16 w-6 bg-primary/90 opacity-0 pointer-events-none hover:pointer-events-auto hover:opacity-100 disabled:pointer-events-none disabled:opacity-0" />
|
|
||||||
<CarouselNext className="relative -right-2 h-16 w-6 bg-primary/90 opacity-0 pointer-events-none hover:pointer-events-auto hover:opacity-100 disabled:pointer-events-none disabled:opacity-0" />
|
|
||||||
</div>
|
|
||||||
</Carousel>
|
</Carousel>
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -848,9 +848,15 @@ 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 />
|
||||||
|
|||||||
@@ -26,15 +26,15 @@ import {
|
|||||||
} from "@/components/persistent-cache-provider"
|
} from "@/components/persistent-cache-provider"
|
||||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||||
import { useMediaSession } from "@/hooks/use-media-session"
|
import { useMediaSession } from "@/hooks/use-media-session"
|
||||||
import { fetchCachedQuery } from "@/lib/cached-query"
|
import { 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 { flushPersistentCache } from "@/lib/persistent-cache"
|
||||||
import * as playbackQueue from "@/lib/playback-queue"
|
import * as playbackQueue from "@otunes/convex/client/playback-queue"
|
||||||
import type { RepeatMode } from "@/lib/playback-queue"
|
import type { RepeatMode } from "@otunes/convex/client/playback-queue"
|
||||||
import {
|
import {
|
||||||
getPlaybackStore,
|
getPlaybackStore,
|
||||||
getServerPlaybackSnapshot,
|
getServerPlaybackSnapshot,
|
||||||
} from "@/lib/playback-store"
|
} from "@otunes/convex/client/playback-store"
|
||||||
import { rememberSongs, useSong } from "@/lib/song-cache"
|
import { rememberSongs, useSong } from "@/lib/song-cache"
|
||||||
import { songHlsPlaylistUrl, songPlayUrl } from "@/lib/song-play-url"
|
import { songHlsPlaylistUrl, songPlayUrl } from "@/lib/song-play-url"
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ import {
|
|||||||
} from "@/components/ui/dropdown-menu"
|
} from "@/components/ui/dropdown-menu"
|
||||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||||
import { api } from "@otunes/convex/_generated/api"
|
import { api } from "@otunes/convex/_generated/api"
|
||||||
import { fetchCachedQuery } from "@/lib/cached-query"
|
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()
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import type { FunctionReference } from "convex/server"
|
|||||||
import { useCallback, useEffect, useSyncExternalStore } from "react"
|
import { useCallback, useEffect, useSyncExternalStore } from "react"
|
||||||
|
|
||||||
import { useCacheScope } from "@/components/persistent-cache-provider"
|
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||||
import { queryCacheKey } from "@/lib/cached-query"
|
import { queryCacheKey } from "@otunes/convex/client/cached-query"
|
||||||
import { readCache, subscribeCache, writeCache } from "@/lib/persistent-cache"
|
import { readCache, subscribeCache, writeCache } from "@/lib/persistent-cache"
|
||||||
|
|
||||||
const MAX_CACHED_PAGINATED_ITEMS = 200
|
const MAX_CACHED_PAGINATED_ITEMS = 200
|
||||||
|
|||||||
@@ -1,24 +1,16 @@
|
|||||||
|
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_NAME = "otunes-cache"
|
||||||
const DB_VERSION = 1
|
const DB_VERSION = 1
|
||||||
const STORE_NAME = "entries"
|
const STORE_NAME = "entries"
|
||||||
const WRITE_DELAY_MS = 250
|
|
||||||
/** Keys are `<prefix>:<rest>`; prefixes without a limit are never evicted. */
|
|
||||||
const MAX_ENTRIES_BY_PREFIX: Record<string, number> = {
|
|
||||||
q: 400,
|
|
||||||
song: 5000,
|
|
||||||
}
|
|
||||||
|
|
||||||
type Entry = { value: unknown; touchedAt: number }
|
|
||||||
|
|
||||||
const memory = new Map<string, Entry>()
|
|
||||||
const prefixCounts = new Map<string, number>()
|
|
||||||
const listeners = new Map<string, Set<() => void>>()
|
|
||||||
const loadListeners = new Set<() => void>()
|
|
||||||
const pendingWrites = new Map<string, Entry | null>()
|
|
||||||
let flushTimer: ReturnType<typeof setTimeout> | null = null
|
|
||||||
let dbPromise: Promise<IDBDatabase | null> | null = null
|
let dbPromise: Promise<IDBDatabase | null> | null = null
|
||||||
let loadPromise: Promise<void> | null = null
|
|
||||||
let loaded = false
|
|
||||||
|
|
||||||
function requestToPromise<T>(request: IDBRequest<T>) {
|
function requestToPromise<T>(request: IDBRequest<T>) {
|
||||||
return new Promise<T>((resolve, reject) => {
|
return new Promise<T>((resolve, reject) => {
|
||||||
@@ -64,36 +56,35 @@ function openDb() {
|
|||||||
return dbPromise
|
return dbPromise
|
||||||
}
|
}
|
||||||
|
|
||||||
function notify(key: string) {
|
const indexedDbBackend: PersistentCacheBackend = {
|
||||||
for (const listener of listeners.get(key) ?? []) {
|
async loadAll() {
|
||||||
listener()
|
const db = await openDb()
|
||||||
}
|
if (!db) {
|
||||||
}
|
return []
|
||||||
|
|
||||||
function notifyAll() {
|
|
||||||
for (const key of listeners.keys()) {
|
|
||||||
notify(key)
|
|
||||||
}
|
|
||||||
for (const listener of loadListeners) {
|
|
||||||
listener()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function flushWrites() {
|
|
||||||
flushTimer = null
|
|
||||||
if (pendingWrites.size === 0) {
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const writes = [...pendingWrites]
|
const transaction = db.transaction(STORE_NAME, "readonly")
|
||||||
pendingWrites.clear()
|
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()
|
const db = await openDb()
|
||||||
if (!db) {
|
if (!db) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
|
||||||
const transaction = db.transaction(STORE_NAME, "readwrite")
|
const transaction = db.transaction(STORE_NAME, "readwrite")
|
||||||
const store = transaction.objectStore(STORE_NAME)
|
const store = transaction.objectStore(STORE_NAME)
|
||||||
for (const [key, entry] of writes) {
|
for (const [key, entry] of writes) {
|
||||||
@@ -104,165 +95,22 @@ async function flushWrites() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
await transactionDone(transaction)
|
await transactionDone(transaction)
|
||||||
} catch {
|
},
|
||||||
// Persisting is best-effort; the in-memory copy stays authoritative.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function scheduleWrite(key: string, entry: Entry | null) {
|
|
||||||
pendingWrites.set(key, entry)
|
|
||||||
if (flushTimer === null) {
|
|
||||||
flushTimer = setTimeout(() => void flushWrites(), WRITE_DELAY_MS)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function entryPrefix(key: string) {
|
|
||||||
const index = key.indexOf(":")
|
|
||||||
return index === -1 ? key : key.slice(0, index)
|
|
||||||
}
|
|
||||||
|
|
||||||
function evictOldEntries(prefix: string, force = false) {
|
|
||||||
const limit = MAX_ENTRIES_BY_PREFIX[prefix]
|
|
||||||
const count = prefixCounts.get(prefix) ?? 0
|
|
||||||
if (limit === undefined || count <= (force ? limit : limit * 1.25)) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const oldest = [...memory.entries()]
|
|
||||||
.filter(([key]) => entryPrefix(key) === prefix)
|
|
||||||
.sort(([, a], [, b]) => a.touchedAt - b.touchedAt)
|
|
||||||
.slice(0, count - limit)
|
|
||||||
|
|
||||||
for (const [key] of oldest) {
|
|
||||||
removeFromMemory(key)
|
|
||||||
scheduleWrite(key, null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function setInMemory(key: string, entry: Entry) {
|
|
||||||
if (!memory.has(key)) {
|
|
||||||
const prefix = entryPrefix(key)
|
|
||||||
prefixCounts.set(prefix, (prefixCounts.get(prefix) ?? 0) + 1)
|
|
||||||
}
|
|
||||||
memory.set(key, entry)
|
|
||||||
}
|
|
||||||
|
|
||||||
function removeFromMemory(key: string) {
|
|
||||||
if (memory.delete(key)) {
|
|
||||||
const prefix = entryPrefix(key)
|
|
||||||
prefixCounts.set(prefix, (prefixCounts.get(prefix) ?? 1) - 1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Writes pending entries now instead of after the batching delay. */
|
|
||||||
export function flushPersistentCache() {
|
|
||||||
if (flushTimer !== null) {
|
|
||||||
clearTimeout(flushTimer)
|
|
||||||
}
|
|
||||||
void flushWrites()
|
|
||||||
}
|
|
||||||
|
|
||||||
export function loadPersistentCache() {
|
|
||||||
if (loadPromise) {
|
|
||||||
return loadPromise
|
|
||||||
}
|
|
||||||
|
|
||||||
loadPromise = (async () => {
|
|
||||||
const db = await openDb()
|
|
||||||
if (db) {
|
|
||||||
try {
|
|
||||||
const transaction = db.transaction(STORE_NAME, "readonly")
|
|
||||||
const store = transaction.objectStore(STORE_NAME)
|
|
||||||
const [keys, values] = await Promise.all([
|
|
||||||
requestToPromise(store.getAllKeys()),
|
|
||||||
requestToPromise(store.getAll() as IDBRequest<Entry[]>),
|
|
||||||
])
|
|
||||||
keys.forEach((key, index) => {
|
|
||||||
const entry = values[index]
|
|
||||||
if (typeof key === "string" && entry && !memory.has(key)) {
|
|
||||||
setInMemory(key, entry)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
for (const prefix of Object.keys(MAX_ENTRIES_BY_PREFIX)) {
|
|
||||||
evictOldEntries(prefix, true)
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Treat an unreadable cache as empty.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
loaded = true
|
|
||||||
notifyAll()
|
|
||||||
})()
|
|
||||||
|
|
||||||
return loadPromise
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isPersistentCacheLoaded() {
|
|
||||||
return loaded
|
|
||||||
}
|
|
||||||
|
|
||||||
export function readCache<T>(key: string): T | undefined {
|
|
||||||
return memory.get(key)?.value as T | undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
export function writeCache(
|
|
||||||
key: string,
|
|
||||||
value: unknown,
|
|
||||||
options: { notify?: boolean } = {}
|
|
||||||
) {
|
|
||||||
const entry = { value, touchedAt: Date.now() }
|
|
||||||
setInMemory(key, entry)
|
|
||||||
scheduleWrite(key, entry)
|
|
||||||
evictOldEntries(entryPrefix(key))
|
|
||||||
if (options.notify) {
|
|
||||||
notify(key)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function clearPersistentCache() {
|
|
||||||
memory.clear()
|
|
||||||
prefixCounts.clear()
|
|
||||||
pendingWrites.clear()
|
|
||||||
if (flushTimer !== null) {
|
|
||||||
clearTimeout(flushTimer)
|
|
||||||
flushTimer = null
|
|
||||||
}
|
|
||||||
notifyAll()
|
|
||||||
|
|
||||||
|
async clear() {
|
||||||
const db = await openDb()
|
const db = await openDb()
|
||||||
if (!db) {
|
if (!db) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
|
||||||
const transaction = db.transaction(STORE_NAME, "readwrite")
|
const transaction = db.transaction(STORE_NAME, "readwrite")
|
||||||
transaction.objectStore(STORE_NAME).clear()
|
transaction.objectStore(STORE_NAME).clear()
|
||||||
await transactionDone(transaction)
|
await transactionDone(transaction)
|
||||||
} catch {
|
},
|
||||||
// Ignore; stale entries are scoped per user and evicted over time.
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function subscribeCache(key: string, listener: () => void) {
|
if (typeof window !== "undefined") {
|
||||||
let keyListeners = listeners.get(key)
|
configurePersistentCache(indexedDbBackend, {
|
||||||
if (!keyListeners) {
|
maxEntriesByPrefix: { q: 400, song: 5000 },
|
||||||
keyListeners = new Set()
|
})
|
||||||
listeners.set(key, keyListeners)
|
|
||||||
}
|
|
||||||
keyListeners.add(listener)
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
keyListeners.delete(listener)
|
|
||||||
if (keyListeners.size === 0) {
|
|
||||||
listeners.delete(key)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function subscribeCacheLoaded(listener: () => void) {
|
|
||||||
loadListeners.add(listener)
|
|
||||||
return () => {
|
|
||||||
loadListeners.delete(listener)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
+14
-133
@@ -1,139 +1,20 @@
|
|||||||
import { useConvex, type ConvexReactClient } from "convex/react"
|
import { useConvex } from "convex/react"
|
||||||
import { useEffect, useMemo, useSyncExternalStore } from "react"
|
import { useEffect, useMemo, useSyncExternalStore } from "react"
|
||||||
|
|
||||||
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 { BrowseAlbumDetail, BrowseSong } from "@otunes/convex/types"
|
|
||||||
import {
|
import {
|
||||||
isPersistentCacheLoaded,
|
getCachedSong,
|
||||||
readCache,
|
getSongsVersion,
|
||||||
subscribeCacheLoaded,
|
requestSongs,
|
||||||
writeCache,
|
subscribeSongs,
|
||||||
} from "@/lib/persistent-cache"
|
} from "@otunes/convex/client/song-cache"
|
||||||
|
import { isPersistentCacheLoaded } from "@/lib/persistent-cache"
|
||||||
|
|
||||||
const FETCH_BATCH_SIZE = 100
|
export {
|
||||||
const FETCH_DELAY_MS = 16
|
albumDetailSongs,
|
||||||
|
getCachedSong,
|
||||||
const listeners = new Set<() => void>()
|
rememberSongs,
|
||||||
const missingSongIds = new Set<string>()
|
} from "@otunes/convex/client/song-cache"
|
||||||
const inFlightSongIds = new Set<string>()
|
|
||||||
const queuedSongIds = new Set<Id<"songs">>()
|
|
||||||
let version = 0
|
|
||||||
let fetchTimer: ReturnType<typeof setTimeout> | null = null
|
|
||||||
|
|
||||||
function songKey(songId: string) {
|
|
||||||
return `song:${songId}`
|
|
||||||
}
|
|
||||||
|
|
||||||
function notify() {
|
|
||||||
version += 1
|
|
||||||
for (const listener of listeners) {
|
|
||||||
listener()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof window !== "undefined") {
|
|
||||||
subscribeCacheLoaded(notify)
|
|
||||||
}
|
|
||||||
|
|
||||||
function subscribe(listener: () => void) {
|
|
||||||
listeners.add(listener)
|
|
||||||
return () => {
|
|
||||||
listeners.delete(listener)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function sameSong(a: BrowseSong, b: BrowseSong) {
|
|
||||||
return (
|
|
||||||
a.title === b.title &&
|
|
||||||
a.durationSeconds === b.durationSeconds &&
|
|
||||||
a.explicit === b.explicit &&
|
|
||||||
a.artist.id === b.artist.id &&
|
|
||||||
a.artist.name === b.artist.name &&
|
|
||||||
a.artist.photo === b.artist.photo &&
|
|
||||||
a.album.id === b.album.id &&
|
|
||||||
a.album.title === b.album.title &&
|
|
||||||
a.album.cover === b.album.cover
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getCachedSong(songId: string) {
|
|
||||||
return readCache<BrowseSong>(songKey(songId))
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Stores song metadata so the player and queue can render it offline. */
|
|
||||||
export function rememberSongs(songs: readonly BrowseSong[]) {
|
|
||||||
let changed = false
|
|
||||||
for (const song of songs) {
|
|
||||||
const existing = getCachedSong(song.id)
|
|
||||||
if (existing && sameSong(existing, song)) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
writeCache(songKey(song.id), song)
|
|
||||||
missingSongIds.delete(song.id)
|
|
||||||
changed = true
|
|
||||||
}
|
|
||||||
if (changed) {
|
|
||||||
notify()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function albumDetailSongs(album: BrowseAlbumDetail): BrowseSong[] {
|
|
||||||
return album.tracks.map((track) => ({
|
|
||||||
id: track.id,
|
|
||||||
title: track.title,
|
|
||||||
artist: album.artist,
|
|
||||||
album: { id: album.id, title: album.title, cover: album.cover },
|
|
||||||
durationSeconds: track.durationSeconds,
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchQueuedSongs(convex: ConvexReactClient) {
|
|
||||||
fetchTimer = null
|
|
||||||
const ids = [...queuedSongIds]
|
|
||||||
queuedSongIds.clear()
|
|
||||||
|
|
||||||
for (let start = 0; start < ids.length; start += FETCH_BATCH_SIZE) {
|
|
||||||
const batch = ids.slice(start, start + FETCH_BATCH_SIZE)
|
|
||||||
try {
|
|
||||||
const songs = await convex.query(api.library.browseSongsByIds, {
|
|
||||||
ids: batch,
|
|
||||||
})
|
|
||||||
const found = new Set(songs.map((song) => song.id as string))
|
|
||||||
for (const id of batch) {
|
|
||||||
if (!found.has(id)) {
|
|
||||||
missingSongIds.add(id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
rememberSongs(songs)
|
|
||||||
} catch {
|
|
||||||
// Leave them uncached so a later render retries.
|
|
||||||
} finally {
|
|
||||||
for (const id of batch) {
|
|
||||||
inFlightSongIds.delete(id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
notify()
|
|
||||||
}
|
|
||||||
|
|
||||||
function requestSongs(convex: ConvexReactClient, songIds: Id<"songs">[]) {
|
|
||||||
for (const songId of songIds) {
|
|
||||||
if (
|
|
||||||
getCachedSong(songId) ||
|
|
||||||
missingSongIds.has(songId) ||
|
|
||||||
inFlightSongIds.has(songId)
|
|
||||||
) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
inFlightSongIds.add(songId)
|
|
||||||
queuedSongIds.add(songId)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (queuedSongIds.size > 0 && fetchTimer === null) {
|
|
||||||
fetchTimer = setTimeout(() => void fetchQueuedSongs(convex), FETCH_DELAY_MS)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolves song metadata from the persistent song cache, fetching anything
|
* Resolves song metadata from the persistent song cache, fetching anything
|
||||||
@@ -142,8 +23,8 @@ function requestSongs(convex: ConvexReactClient, songIds: Id<"songs">[]) {
|
|||||||
export function useSongs(songIds: readonly Id<"songs">[]) {
|
export function useSongs(songIds: readonly Id<"songs">[]) {
|
||||||
const convex = useConvex()
|
const convex = useConvex()
|
||||||
const songsVersion = useSyncExternalStore(
|
const songsVersion = useSyncExternalStore(
|
||||||
subscribe,
|
subscribeSongs,
|
||||||
() => version,
|
getSongsVersion,
|
||||||
() => 0
|
() => 0
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
# the bundled functions, and never exported to the web server.
|
# the bundled functions, and never exported to the web server.
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
NODE=/opt/node/bin/node
|
NODE=/usr/local/bin/node
|
||||||
CONVEX_DATA_DIR=/convex/data
|
CONVEX_DATA_DIR=/convex/data
|
||||||
FUNCTIONS_DIR=/opt/otunes/convex/packages/convex
|
FUNCTIONS_DIR=/opt/otunes/convex/packages/convex
|
||||||
BACKEND_URL=http://127.0.0.1:3210
|
BACKEND_URL=http://127.0.0.1:3210
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import type { ConvexReactClient } from "convex/react"
|
|
||||||
import {
|
import {
|
||||||
getFunctionName,
|
getFunctionName,
|
||||||
type FunctionArgs,
|
type FunctionArgs,
|
||||||
@@ -7,11 +6,15 @@ import {
|
|||||||
} from "convex/server"
|
} from "convex/server"
|
||||||
import { convexToJson, type Value } from "convex/values"
|
import { convexToJson, type Value } from "convex/values"
|
||||||
|
|
||||||
import {
|
import { loadPersistentCache, readCache, writeCache } from "./persistent-cache"
|
||||||
loadPersistentCache,
|
|
||||||
readCache,
|
/** The part of `ConvexReactClient` the cache needs. */
|
||||||
writeCache,
|
export type QueryClient = {
|
||||||
} from "@/lib/persistent-cache"
|
query<Query extends FunctionReference<"query">>(
|
||||||
|
query: Query,
|
||||||
|
args: FunctionArgs<Query>
|
||||||
|
): Promise<FunctionReturnType<Query>>
|
||||||
|
}
|
||||||
|
|
||||||
export function queryCacheKey(
|
export function queryCacheKey(
|
||||||
scope: string,
|
scope: string,
|
||||||
@@ -30,7 +33,7 @@ export function queryCacheKey(
|
|||||||
export async function fetchCachedQuery<
|
export async function fetchCachedQuery<
|
||||||
Query extends FunctionReference<"query">,
|
Query extends FunctionReference<"query">,
|
||||||
>(
|
>(
|
||||||
convex: ConvexReactClient,
|
convex: QueryClient,
|
||||||
scope: string,
|
scope: string,
|
||||||
query: Query,
|
query: Query,
|
||||||
args: FunctionArgs<Query>
|
args: FunctionArgs<Query>
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
export type PersistentCacheEntry = { value: unknown; touchedAt: number }
|
||||||
|
|
||||||
|
/** Storage for persisted entries; `null` in `write` deletes the key. */
|
||||||
|
export type PersistentCacheBackend = {
|
||||||
|
loadAll(): Promise<Array<[string, PersistentCacheEntry]>>
|
||||||
|
write(writes: Array<[string, PersistentCacheEntry | null]>): Promise<void>
|
||||||
|
clear(): Promise<void>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PersistentCacheOptions = {
|
||||||
|
/** Keys are `<prefix>:<rest>`; prefixes without a limit are never evicted. */
|
||||||
|
maxEntriesByPrefix: Record<string, number>
|
||||||
|
writeDelayMs?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_WRITE_DELAY_MS = 250
|
||||||
|
|
||||||
|
const memory = new Map<string, PersistentCacheEntry>()
|
||||||
|
const prefixCounts = new Map<string, number>()
|
||||||
|
const listeners = new Map<string, Set<() => void>>()
|
||||||
|
const loadListeners = new Set<() => void>()
|
||||||
|
const pendingWrites = new Map<string, PersistentCacheEntry | null>()
|
||||||
|
let flushTimer: ReturnType<typeof setTimeout> | null = null
|
||||||
|
let loadPromise: Promise<void> | null = null
|
||||||
|
let loaded = false
|
||||||
|
|
||||||
|
let backend: PersistentCacheBackend | null = null
|
||||||
|
let options: PersistentCacheOptions = { maxEntriesByPrefix: {} }
|
||||||
|
let resolveConfigured: () => void
|
||||||
|
const configured = new Promise<void>((resolve) => {
|
||||||
|
resolveConfigured = resolve
|
||||||
|
})
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Must be called once per app before the cache is used. Loading waits until
|
||||||
|
* then, so modules can read the cache before the app picks a backend.
|
||||||
|
*/
|
||||||
|
export function configurePersistentCache(
|
||||||
|
nextBackend: PersistentCacheBackend,
|
||||||
|
nextOptions: PersistentCacheOptions
|
||||||
|
) {
|
||||||
|
backend = nextBackend
|
||||||
|
options = nextOptions
|
||||||
|
resolveConfigured()
|
||||||
|
}
|
||||||
|
|
||||||
|
function notify(key: string) {
|
||||||
|
for (const listener of listeners.get(key) ?? []) {
|
||||||
|
listener()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function notifyAll() {
|
||||||
|
for (const key of listeners.keys()) {
|
||||||
|
notify(key)
|
||||||
|
}
|
||||||
|
for (const listener of loadListeners) {
|
||||||
|
listener()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function flushWrites() {
|
||||||
|
flushTimer = null
|
||||||
|
if (pendingWrites.size === 0 || !backend) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const writes = [...pendingWrites]
|
||||||
|
pendingWrites.clear()
|
||||||
|
|
||||||
|
try {
|
||||||
|
await backend.write(writes)
|
||||||
|
} catch {
|
||||||
|
// Persisting is best-effort; the in-memory copy stays authoritative.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function scheduleWrite(key: string, entry: PersistentCacheEntry | null) {
|
||||||
|
pendingWrites.set(key, entry)
|
||||||
|
if (flushTimer === null) {
|
||||||
|
flushTimer = setTimeout(
|
||||||
|
() => void flushWrites(),
|
||||||
|
options.writeDelayMs ?? DEFAULT_WRITE_DELAY_MS
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function entryPrefix(key: string) {
|
||||||
|
const index = key.indexOf(":")
|
||||||
|
return index === -1 ? key : key.slice(0, index)
|
||||||
|
}
|
||||||
|
|
||||||
|
function evictOldEntries(prefix: string, force = false) {
|
||||||
|
const limit = options.maxEntriesByPrefix[prefix]
|
||||||
|
const count = prefixCounts.get(prefix) ?? 0
|
||||||
|
if (limit === undefined || count <= (force ? limit : limit * 1.25)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldest = [...memory.entries()]
|
||||||
|
.filter(([key]) => entryPrefix(key) === prefix)
|
||||||
|
.sort(([, a], [, b]) => a.touchedAt - b.touchedAt)
|
||||||
|
.slice(0, count - limit)
|
||||||
|
|
||||||
|
for (const [key] of oldest) {
|
||||||
|
removeFromMemory(key)
|
||||||
|
scheduleWrite(key, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setInMemory(key: string, entry: PersistentCacheEntry) {
|
||||||
|
if (!memory.has(key)) {
|
||||||
|
const prefix = entryPrefix(key)
|
||||||
|
prefixCounts.set(prefix, (prefixCounts.get(prefix) ?? 0) + 1)
|
||||||
|
}
|
||||||
|
memory.set(key, entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeFromMemory(key: string) {
|
||||||
|
if (memory.delete(key)) {
|
||||||
|
const prefix = entryPrefix(key)
|
||||||
|
prefixCounts.set(prefix, (prefixCounts.get(prefix) ?? 1) - 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Writes pending entries now instead of after the batching delay. */
|
||||||
|
export function flushPersistentCache() {
|
||||||
|
if (flushTimer !== null) {
|
||||||
|
clearTimeout(flushTimer)
|
||||||
|
}
|
||||||
|
void flushWrites()
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadPersistentCache() {
|
||||||
|
if (loadPromise) {
|
||||||
|
return loadPromise
|
||||||
|
}
|
||||||
|
|
||||||
|
loadPromise = (async () => {
|
||||||
|
await configured
|
||||||
|
try {
|
||||||
|
const entries = (await backend?.loadAll()) ?? []
|
||||||
|
for (const [key, entry] of entries) {
|
||||||
|
if (!memory.has(key)) {
|
||||||
|
setInMemory(key, entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const prefix of Object.keys(options.maxEntriesByPrefix)) {
|
||||||
|
evictOldEntries(prefix, true)
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Treat an unreadable cache as empty.
|
||||||
|
}
|
||||||
|
|
||||||
|
loaded = true
|
||||||
|
notifyAll()
|
||||||
|
})()
|
||||||
|
|
||||||
|
return loadPromise
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isPersistentCacheLoaded() {
|
||||||
|
return loaded
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readCache<T>(key: string): T | undefined {
|
||||||
|
return memory.get(key)?.value as T | undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
export function writeCache(
|
||||||
|
key: string,
|
||||||
|
value: unknown,
|
||||||
|
writeOptions: { notify?: boolean } = {}
|
||||||
|
) {
|
||||||
|
const entry = { value, touchedAt: Date.now() }
|
||||||
|
setInMemory(key, entry)
|
||||||
|
scheduleWrite(key, entry)
|
||||||
|
evictOldEntries(entryPrefix(key))
|
||||||
|
if (writeOptions.notify) {
|
||||||
|
notify(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function clearPersistentCache() {
|
||||||
|
memory.clear()
|
||||||
|
prefixCounts.clear()
|
||||||
|
pendingWrites.clear()
|
||||||
|
if (flushTimer !== null) {
|
||||||
|
clearTimeout(flushTimer)
|
||||||
|
flushTimer = null
|
||||||
|
}
|
||||||
|
notifyAll()
|
||||||
|
|
||||||
|
try {
|
||||||
|
await backend?.clear()
|
||||||
|
} catch {
|
||||||
|
// Ignore; stale entries are scoped per user and evicted over time.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subscribeCache(key: string, listener: () => void) {
|
||||||
|
let keyListeners = listeners.get(key)
|
||||||
|
if (!keyListeners) {
|
||||||
|
keyListeners = new Set()
|
||||||
|
listeners.set(key, keyListeners)
|
||||||
|
}
|
||||||
|
keyListeners.add(listener)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
keyListeners.delete(listener)
|
||||||
|
if (keyListeners.size === 0) {
|
||||||
|
listeners.delete(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subscribeCacheLoaded(listener: () => void) {
|
||||||
|
loadListeners.add(listener)
|
||||||
|
return () => {
|
||||||
|
loadListeners.delete(listener)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,16 @@
|
|||||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
import type { Id } from "../convex/_generated/dataModel"
|
||||||
import { shuffleArray } from "@/lib/shuffle-array"
|
|
||||||
|
|
||||||
/** Mirrors the queue rules in `packages/convex/convex/playback.ts`. */
|
/** Mirrors the queue rules in `packages/convex/convex/playback.ts`. */
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
export type RepeatMode = "none" | "once" | "always"
|
export type RepeatMode = "none" | "once" | "always"
|
||||||
|
|
||||||
export type PlaybackQueueState = {
|
export type PlaybackQueueState = {
|
||||||
@@ -1,14 +1,10 @@
|
|||||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
import type { Id } from "../convex/_generated/dataModel"
|
||||||
import {
|
import {
|
||||||
EMPTY_PLAYBACK_QUEUE,
|
EMPTY_PLAYBACK_QUEUE,
|
||||||
type PlaybackQueueState,
|
type PlaybackQueueState,
|
||||||
type RepeatMode,
|
type RepeatMode,
|
||||||
} from "@/lib/playback-queue"
|
} from "./playback-queue"
|
||||||
import {
|
import { loadPersistentCache, readCache, writeCache } from "./persistent-cache"
|
||||||
loadPersistentCache,
|
|
||||||
readCache,
|
|
||||||
writeCache,
|
|
||||||
} from "@/lib/persistent-cache"
|
|
||||||
|
|
||||||
const SYNC_DELAY_MS = 300
|
const SYNC_DELAY_MS = 300
|
||||||
const RETRY_DELAYS_MS = [1_000, 3_000, 10_000, 30_000]
|
const RETRY_DELAYS_MS = [1_000, 3_000, 10_000, 30_000]
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import { api } from "../convex/_generated/api"
|
||||||
|
import type { Id } from "../convex/_generated/dataModel"
|
||||||
|
import type { BrowseAlbumDetail, BrowseSong } from "../convex/types"
|
||||||
|
import type { QueryClient } from "./cached-query"
|
||||||
|
import { readCache, subscribeCacheLoaded, writeCache } from "./persistent-cache"
|
||||||
|
|
||||||
|
const FETCH_BATCH_SIZE = 100
|
||||||
|
const FETCH_DELAY_MS = 16
|
||||||
|
|
||||||
|
const listeners = new Set<() => void>()
|
||||||
|
const missingSongIds = new Set<string>()
|
||||||
|
const inFlightSongIds = new Set<string>()
|
||||||
|
const queuedSongIds = new Set<Id<"songs">>()
|
||||||
|
let version = 0
|
||||||
|
let fetchTimer: ReturnType<typeof setTimeout> | null = null
|
||||||
|
|
||||||
|
function songKey(songId: string) {
|
||||||
|
return `song:${songId}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function notify() {
|
||||||
|
version += 1
|
||||||
|
for (const listener of listeners) {
|
||||||
|
listener()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof window !== "undefined") {
|
||||||
|
subscribeCacheLoaded(notify)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subscribeSongs(listener: () => void) {
|
||||||
|
listeners.add(listener)
|
||||||
|
return () => {
|
||||||
|
listeners.delete(listener)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Changes whenever any cached song changes. */
|
||||||
|
export function getSongsVersion() {
|
||||||
|
return version
|
||||||
|
}
|
||||||
|
|
||||||
|
function sameSong(a: BrowseSong, b: BrowseSong) {
|
||||||
|
return (
|
||||||
|
a.title === b.title &&
|
||||||
|
a.durationSeconds === b.durationSeconds &&
|
||||||
|
a.explicit === b.explicit &&
|
||||||
|
a.artist.id === b.artist.id &&
|
||||||
|
a.artist.name === b.artist.name &&
|
||||||
|
a.artist.photo === b.artist.photo &&
|
||||||
|
a.album.id === b.album.id &&
|
||||||
|
a.album.title === b.album.title &&
|
||||||
|
a.album.cover === b.album.cover
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCachedSong(songId: string) {
|
||||||
|
return readCache<BrowseSong>(songKey(songId))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stores song metadata so the player and queue can render it offline. */
|
||||||
|
export function rememberSongs(songs: readonly BrowseSong[]) {
|
||||||
|
let changed = false
|
||||||
|
for (const song of songs) {
|
||||||
|
const existing = getCachedSong(song.id)
|
||||||
|
if (existing && sameSong(existing, song)) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
writeCache(songKey(song.id), song)
|
||||||
|
missingSongIds.delete(song.id)
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
if (changed) {
|
||||||
|
notify()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function albumDetailSongs(album: BrowseAlbumDetail): BrowseSong[] {
|
||||||
|
return album.tracks.map((track) => ({
|
||||||
|
id: track.id,
|
||||||
|
title: track.title,
|
||||||
|
artist: album.artist,
|
||||||
|
album: { id: album.id, title: album.title, cover: album.cover },
|
||||||
|
durationSeconds: track.durationSeconds,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchQueuedSongs(convex: QueryClient) {
|
||||||
|
fetchTimer = null
|
||||||
|
const ids = [...queuedSongIds]
|
||||||
|
queuedSongIds.clear()
|
||||||
|
|
||||||
|
for (let start = 0; start < ids.length; start += FETCH_BATCH_SIZE) {
|
||||||
|
const batch = ids.slice(start, start + FETCH_BATCH_SIZE)
|
||||||
|
try {
|
||||||
|
const songs = await convex.query(api.library.browseSongsByIds, {
|
||||||
|
ids: batch,
|
||||||
|
})
|
||||||
|
const found = new Set(songs.map((song) => song.id as string))
|
||||||
|
for (const id of batch) {
|
||||||
|
if (!found.has(id)) {
|
||||||
|
missingSongIds.add(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rememberSongs(songs)
|
||||||
|
} catch {
|
||||||
|
// Leave them uncached so a later render retries.
|
||||||
|
} finally {
|
||||||
|
for (const id of batch) {
|
||||||
|
inFlightSongIds.delete(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
notify()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fetches metadata for songs that are not cached yet, in batches. */
|
||||||
|
export function requestSongs(convex: QueryClient, songIds: Id<"songs">[]) {
|
||||||
|
for (const songId of songIds) {
|
||||||
|
if (
|
||||||
|
getCachedSong(songId) ||
|
||||||
|
missingSongIds.has(songId) ||
|
||||||
|
inFlightSongIds.has(songId)
|
||||||
|
) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
inFlightSongIds.add(songId)
|
||||||
|
queuedSongIds.add(songId)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (queuedSongIds.size > 0 && fetchTimer === null) {
|
||||||
|
fetchTimer = setTimeout(() => void fetchQueuedSongs(convex), FETCH_DELAY_MS)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,11 @@ export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({
|
|||||||
if (existingUserId === null) {
|
if (existingUserId === null) {
|
||||||
const settings = await db.query("appSettings").first()
|
const settings = await db.query("appSettings").first()
|
||||||
if (settings?.disableAccountCreation) {
|
if (settings?.disableAccountCreation) {
|
||||||
|
// Self-service sign-up has no admin session. Accounts created from
|
||||||
|
// the admin tools run as that admin, so they stay allowed.
|
||||||
|
const actorId = await getAuthUserId(ctx)
|
||||||
|
const actor = actorId === null ? null : await db.get(actorId)
|
||||||
|
if (!actor?.isAdmin) {
|
||||||
const sessions = await db
|
const sessions = await db
|
||||||
.query("authSessions")
|
.query("authSessions")
|
||||||
.withIndex("userId", (q) => q.eq("userId", userId))
|
.withIndex("userId", (q) => q.eq("userId", userId))
|
||||||
@@ -38,6 +43,7 @@ export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({
|
|||||||
await db.delete(userId)
|
await db.delete(userId)
|
||||||
throw new ConvexError("Account creation is currently disabled")
|
throw new ConvexError("Account creation is currently disabled")
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const users = await db.query("users").take(2)
|
const users = await db.query("users").take(2)
|
||||||
await db.patch(userId, {
|
await db.patch(userId, {
|
||||||
|
|||||||
@@ -22,6 +22,26 @@
|
|||||||
"./server-url": {
|
"./server-url": {
|
||||||
"types": "./server-url.ts",
|
"types": "./server-url.ts",
|
||||||
"default": "./server-url.ts"
|
"default": "./server-url.ts"
|
||||||
|
},
|
||||||
|
"./client/cached-query": {
|
||||||
|
"types": "./client/cached-query.ts",
|
||||||
|
"default": "./client/cached-query.ts"
|
||||||
|
},
|
||||||
|
"./client/persistent-cache": {
|
||||||
|
"types": "./client/persistent-cache.ts",
|
||||||
|
"default": "./client/persistent-cache.ts"
|
||||||
|
},
|
||||||
|
"./client/playback-queue": {
|
||||||
|
"types": "./client/playback-queue.ts",
|
||||||
|
"default": "./client/playback-queue.ts"
|
||||||
|
},
|
||||||
|
"./client/playback-store": {
|
||||||
|
"types": "./client/playback-store.ts",
|
||||||
|
"default": "./client/playback-store.ts"
|
||||||
|
},
|
||||||
|
"./client/song-cache": {
|
||||||
|
"types": "./client/song-cache.ts",
|
||||||
|
"default": "./client/song-cache.ts"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
Reference in new issue
Block a user