From 7ee1580a7290e24ece2e88a006e193db40f03b7a Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 21:43:32 -0500 Subject: [PATCH 01/11] feat(mobile): add songs to queue with a full swipe (#89) --- .../app/(app)/(tabs)/home/album/[id].tsx | 3 +- .../app/(app)/(tabs)/home/playlist/[id].tsx | 11 +- apps/mobile/components/player.tsx | 8 +- apps/mobile/components/song-swipe-row.tsx | 191 +++++++++++++++--- 4 files changed, 178 insertions(+), 35 deletions(-) diff --git a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx index a32bf8c..512fccd 100644 --- a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx @@ -488,7 +488,7 @@ const AlbumTrackRow = memo(function AlbumTrackRow({ action: MediaAction ) => Promise }) { - const Row = Platform.OS === "ios" ? SongSwipeRow : Pressable + const Row = Platform.OS !== "web" ? SongSwipeRow : Pressable const { config } = useServerConfig() return ( void onAction(track, album, "play-next")} + onAddToQueue={() => void onAction(track, album, "play-last")} style={styles.trackRow} onPress={() => void onPlay(track.id as Id<"songs">, songIds)} > diff --git a/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx index f11a0d1..34037bd 100644 --- a/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx @@ -434,11 +434,18 @@ const PlaylistSongRow = memo(function PlaylistSongRow({ palette={palette} inset swipe={ - Platform.OS === "ios" + Platform.OS !== "web" ? { group: swipeGroup, backgroundColor: palette.background, onPlayNext: () => onAction(song, "play-next"), + onAddToQueue: () => onAction(song, "play-last"), + onRemove: + Platform.OS === "android" && removable + ? () => { + void onRemove(song.id) + } + : undefined, } : undefined } @@ -447,7 +454,7 @@ const PlaylistSongRow = memo(function PlaylistSongRow({ /> ) - if (Platform.OS === "ios" || !removable) { + if (Platform.OS !== "web" || !removable) { return row } diff --git a/apps/mobile/components/player.tsx b/apps/mobile/components/player.tsx index 0aaf866..3c77866 100644 --- a/apps/mobile/components/player.tsx +++ b/apps/mobile/components/player.tsx @@ -45,6 +45,8 @@ export const SongRow = memo(function SongRow({ swipe?: { group: SwipeRowGroup onPlayNext: () => void + onAddToQueue: () => void + onRemove?: () => void backgroundColor: string } /** Album/playlist layout: the divider starts at the title, not the artwork. */ @@ -107,10 +109,12 @@ export const SongRow = memo(function SongRow({ ? styles.insetRow : [styles.row, { borderBottomColor: divider }] const row = - swipe && Platform.OS === "ios" ? ( + swipe && Platform.OS !== "web" ? ( void + onAddToQueue: () => void + onRemove?: () => void backgroundColor: string } onPlay: (song: BrowseSong) => void diff --git a/apps/mobile/components/song-swipe-row.tsx b/apps/mobile/components/song-swipe-row.tsx index 3e2f044..e19973e 100644 --- a/apps/mobile/components/song-swipe-row.tsx +++ b/apps/mobile/components/song-swipe-row.tsx @@ -1,3 +1,4 @@ +import { Ionicons } from "@expo/vector-icons" import * as Haptics from "expo-haptics" import { SymbolView } from "expo-symbols" import { @@ -8,6 +9,7 @@ import { type ReactNode, } from "react" import { + Platform, Pressable, StyleSheet, type StyleProp, @@ -26,7 +28,10 @@ import Animated, { import { scheduleOnRN } from "react-native-worklets" import type { SwipeRowGroup } from "@/components/ios-swipe-to-remove-row" +const IS_ANDROID = Platform.OS === "android" + const ACTION_WIDTH = 82 +const LEADING_ACTION_WIDTH = 72 const SPRING = { duration: 450, dampingRatio: 1 } function impact() { @@ -41,6 +46,8 @@ export function SongSwipeRow({ group, onPress, onPlayNext, + onAddToQueue, + onRemove, }: { children: ReactNode style?: StyleProp @@ -48,7 +55,10 @@ export function SongSwipeRow({ group: SwipeRowGroup onPress?: () => void onPlayNext: () => void + onAddToQueue: () => void + onRemove?: () => void }) { + const hasRemove = IS_ANDROID && !!onRemove const x = useSharedValue(0) const startX = useSharedValue(0) const width = useSharedValue(0) @@ -78,10 +88,10 @@ export function SongSwipeRow({ const activate = useCallback( (side: number) => { close() - if (side > 0) onPlayNext() + if (side > 0) onAddToQueue() // Download is intentionally a placeholder. }, - [close, onPlayNext] + [close, onAddToQueue] ) const tapRow = useCallback(() => { if (open) close() @@ -105,7 +115,13 @@ export function SongSwipeRow({ Math.min(width.value, startX.value + event.translationX) ) const commit = - Math.abs(x.value) > Math.max(ACTION_WIDTH, width.value * 0.55) + Math.abs(x.value) > + Math.max( + x.value > 0 + ? LEADING_ACTION_WIDTH * 2 + : ACTION_WIDTH * (hasRemove ? 2 : 1), + width.value * 0.55 + ) if (commit !== committed.value) { committed.value = commit commitProgress.value = withSpring(commit ? 1 : 0, SPRING) @@ -124,10 +140,16 @@ export function SongSwipeRow({ Math.abs(x.value) > 10 && projected * side > ACTION_WIDTH / 2 ? side : 0 - x.value = withSpring(target * ACTION_WIDTH, { - ...SPRING, - velocity: event.velocityX, - }) + x.value = withSpring( + target * + (target > 0 + ? LEADING_ACTION_WIDTH * 2 + : ACTION_WIDTH * (hasRemove ? 2 : 1)), + { + ...SPRING, + velocity: event.velocityX, + } + ) scheduleOnRN(settle, target) }) .onFinalize((_event, success) => { @@ -145,6 +167,7 @@ export function SongSwipeRow({ return Gesture.Exclusive(pan, tap) }, [ activate, + hasRemove, begin, close, commitProgress, @@ -158,12 +181,14 @@ export function SongSwipeRow({ const rowStyle = useAnimatedStyle(() => ({ transform: [{ translateX: x.value }], - borderRadius: interpolate( - Math.abs(x.value), - [0, 40], - [0, height.value / 2], - Extrapolation.CLAMP - ), + borderRadius: IS_ANDROID + ? 0 + : interpolate( + Math.abs(x.value), + [0, 40], + [0, height.value / 2], + Extrapolation.CLAMP + ), })) const fillStyle = useAnimatedStyle(() => ({ opacity: interpolate( @@ -190,8 +215,37 @@ export function SongSwipeRow({ open={open === 1} onPress={() => activate(1)} /> + { + close() + onPlayNext() + }} + /> + {hasRemove && ( + { + close() + onRemove?.() + }} + /> + )} { - if (event.nativeEvent.actionName === "playNext") activate(1) + if (event.nativeEvent.actionName === "remove" && hasRemove) { + close() + onRemove?.() + } + if (event.nativeEvent.actionName === "addToQueue") activate(1) + if (event.nativeEvent.actionName === "playNext") { + close() + onPlayNext() + } }} style={[styles.row, { backgroundColor }, rowStyle]} > @@ -225,6 +291,9 @@ export function SongSwipeRow({ function SwipeAction({ side, + secondary = false, + paired = side > 0, + remove = false, x, height, progress, @@ -232,22 +301,48 @@ function SwipeAction({ onPress, }: { side: 1 | -1 + secondary?: boolean + paired?: boolean + remove?: boolean x: SharedValue height: SharedValue progress: SharedValue open: boolean onPress: () => void }) { - const actionStyle = useAnimatedStyle(() => ({ - width: Math.max(0, x.value * side), - })) - const pillStyle = useAnimatedStyle(() => { + const actionStyle = useAnimatedStyle(() => { const revealed = Math.max(0, x.value * side) + const primaryWidth = (revealed * (1 + progress.value)) / 2 + return { + width: !paired + ? revealed + : secondary + ? revealed - primaryWidth + : primaryWidth, + ...(secondary + ? side > 0 + ? { left: primaryWidth } + : { right: primaryWidth } + : {}), + } + }) + const pillStyle = useAnimatedStyle(() => { + const total = Math.max(0, x.value * side) + const revealed = !paired + ? total + : (total * (secondary ? 1 - progress.value : 1 + progress.value)) / 2 + if (IS_ANDROID) { + return { width: revealed, height: height.value, borderRadius: 0 } + } const resting = Math.max( 0, Math.min( - revealed - 20, - interpolate(revealed, [24, ACTION_WIDTH, 220], [0, 62, 200]) + revealed - (side > 0 ? 10 : 20), + interpolate( + revealed, + [24, side > 0 ? LEADING_ACTION_WIDTH : ACTION_WIDTH, 220], + [0, 62, 200] + ) ) ) const pillWidth = @@ -292,27 +387,61 @@ function SwipeAction({ > 0 ? "Play Next" : "Download"} + accessibilityLabel={ + remove + ? "Remove from Playlist" + : side > 0 + ? secondary + ? "Play Next" + : "Add to Queue" + : "Download" + } onPress={onPress} style={styles.actionButton} > 0 ? "#6b5bff" : "#008dff" }, + { + backgroundColor: remove + ? "#d32f2f" + : side > 0 + ? secondary + ? "#6b5bff" + : "#f29943" + : "#008dff", + }, pillStyle, ]} > - 0 - ? "text.line.first.and.arrowtriangle.forward" - : "arrow.down" - } - size={22} - tintColor="white" - /> + {IS_ANDROID ? ( + + ) : ( + 0 + ? secondary + ? "text.line.first.and.arrowtriangle.forward" + : "text.line.last.and.arrowtriangle.forward" + : "arrow.down" + } + size={22} + tintColor="white" + /> + )} From db29de28c00c1942a3fb5a894adacf82c2cb7830 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 21:43:38 -0500 Subject: [PATCH 02/11] fix(playback): pause and replay the final queue track (#90) --- apps/mobile/contexts/playback.tsx | 14 +++++++++++--- apps/web/components/playback-provider.tsx | 1 + 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/apps/mobile/contexts/playback.tsx b/apps/mobile/contexts/playback.tsx index 96241e8..8980e63 100644 --- a/apps/mobile/contexts/playback.tsx +++ b/apps/mobile/contexts/playback.tsx @@ -376,7 +376,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { const handlePlaylistStatusUpdate = useCallback( (status: AudioPlaylistStatus) => { - if (!status.isLoaded) return + // iOS may remove the finished item before delivering its final status. + if (!status.isLoaded && !status.didJustFinish) return const state = storeRef.current.getState() if (loadedSongIdsRef.current[status.currentIndex] !== state.queue[0]) { return @@ -427,7 +428,14 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { isPlayingRef.current = false setIsPlayingState(false) storeRef.current.update(playbackQueue.skipNext) - void playlistRef.current?.seekTo(0) + const playlist = playlistRef.current + if (playlist) { + playlist.pause() + // Reload the final item, which iOS removes when playback ends. + ignoreTrackChangeRef.current = true + playlist.skipTo(status.currentIndex) + scheduleTrackChangeHandling() + } currentTimeRef.current = 0 setCurrentTime(0) return @@ -443,7 +451,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { playlist?.play() } }, - [] + [scheduleTrackChangeHandling] ) const handleTrackChanged = useCallback( diff --git a/apps/web/components/playback-provider.tsx b/apps/web/components/playback-provider.tsx index 524a611..99471b7 100644 --- a/apps/web/components/playback-provider.tsx +++ b/apps/web/components/playback-provider.tsx @@ -955,6 +955,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { if (!shouldContinuePlaying) { autoPlayNextRef.current = false isPlayingRef.current = false + audio.pause() audio.currentTime = 0 currentTimeRef.current = 0 setCurrentTime(0) From cf61b0ac2548eeddadc745f3603e58d8552979a8 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 21:43:53 -0500 Subject: [PATCH 03/11] fix(mobile): run only the selected artwork color pipeline (#92) --- .../mobile/app/(app)/(tabs)/home/settings.tsx | 6 +- apps/mobile/hooks/cover-palette-source.ts | 142 ++++++++++++++++ apps/mobile/hooks/use-cover-palette.ts | 160 ++++-------------- apps/mobile/hooks/use-legacy-cover-palette.ts | 153 +++-------------- apps/mobile/lib/artwork-color-preference.ts | 39 +++-- 5 files changed, 216 insertions(+), 284 deletions(-) create mode 100644 apps/mobile/hooks/cover-palette-source.ts diff --git a/apps/mobile/app/(app)/(tabs)/home/settings.tsx b/apps/mobile/app/(app)/(tabs)/home/settings.tsx index 30a0cfb..d3e8d72 100644 --- a/apps/mobile/app/(app)/(tabs)/home/settings.tsx +++ b/apps/mobile/app/(app)/(tabs)/home/settings.tsx @@ -23,7 +23,6 @@ import { useServerConfig } from "@/contexts/server-config" import { setArtworkColorsEnabled, useArtworkColorsEnabled, - useArtworkColorPreferenceLoaded, } from "@/lib/artwork-color-preference" import { initialsFromName } from "@/lib/format" import { useCachedQuery } from "@/hooks/use-cached-query" @@ -172,7 +171,6 @@ export default function SettingsScreen() { function AppearanceSection() { const enabled = useArtworkColorsEnabled() - const loaded = useArtworkColorPreferenceLoaded() const [saving, setSaving] = useState(false) return ( @@ -180,8 +178,8 @@ function AppearanceSection() { { setSaving(true) try { diff --git a/apps/mobile/hooks/cover-palette-source.ts b/apps/mobile/hooks/cover-palette-source.ts new file mode 100644 index 0000000..31e1d35 --- /dev/null +++ b/apps/mobile/hooks/cover-palette-source.ts @@ -0,0 +1,142 @@ +import { useEffect, useMemo, useState } from "react" + +import { themeCoverPalette, type CoverPalette } from "@/lib/cover-palette" +import { readCache, writeCache } from "@/lib/persistent-cache" +import { useIsDark, useThemeColors } from "@/lib/theme" +import { withCoverImageSize } from "@/lib/urls" + +// How long a screen holds its skeleton for the first extraction of a cover, +// so rows render once with final colors instead of flashing from the theme. +export const COVER_PALETTE_WAIT_MS = 400 + +export type CoverPaletteResult = { palette: CoverPalette; settled: boolean } + +type CoverPaletteSourceOptions = { + /** Persistent cache key for a 64px cover URI. */ + cacheKey: (colorSourceUri: string) => string + extract: (colorSourceUri: string) => Promise + derive: (swatches: Swatches, isDark: boolean) => CoverPalette | null + /** Reject persisted entries written in an older shape. */ + isValidCache?: (swatches: Swatches) => boolean +} + +/** + * One artwork color pipeline: an extractor and palette derivation with their + * own memory cache, persistent cache and in-flight requests. + */ +export function createCoverPaletteSource({ + cacheKey, + extract, + derive, + isValidCache, +}: CoverPaletteSourceOptions) { + const swatchesByKey = new Map() + const pending = new Map>() + + function cachedSwatches(key: string): Swatches | null | undefined { + if (swatchesByKey.has(key)) return swatchesByKey.get(key) + const cached = readCache(cacheKey(key)) + return cached && isValidCache && !isValidCache(cached) ? undefined : cached + } + + function extractSwatches(key: string) { + const inFlight = pending.get(key) + if (inFlight) return inFlight + + const request = extract(key) + .catch(() => null) + .then((swatches) => { + swatchesByKey.set(key, swatches) + if (swatches) writeCache(cacheKey(key), swatches) + pending.delete(key) + return swatches + }) + pending.set(key, request) + return request + } + + function prefetch(uri: string) { + const key = withCoverImageSize(uri, 64) + if (cachedSwatches(key) !== undefined) return + void extractSwatches(key) + } + + /** + * Colors for a screen tinted by `uri`'s cover art. Pass `uri` as "" to skip + * extraction. Pass `hasCover` as `undefined` while it isn't known yet so + * extraction can start early. + * + * `settled` turns true once the palette is final or after + * `COVER_PALETTE_WAIT_MS`, whichever comes first. + */ + function usePalette( + uri: string, + hasCover: boolean | undefined + ): CoverPaletteResult { + const theme = useThemeColors() + const isDark = useIsDark() + const key = uri ? withCoverImageSize(uri, 64) : "" + const [resolved, setResolved] = useState(() => ({ + key, + swatches: key ? cachedSwatches(key) : null, + })) + const [waitedKey, setWaitedKey] = useState(null) + + const swatches = + resolved.key === key ? resolved.swatches : key ? cachedSwatches(key) : null + + useEffect(() => { + if (!key || hasCover === false) return + let cancelled = false + const known = cachedSwatches(key) + const show = (next: Swatches | null) => + setResolved((prev) => + prev.key === key && sameSwatches(prev.swatches, next) + ? prev + : { key, swatches: next } + ) + if (known !== undefined && swatchesByKey.has(key)) { + show(known) + return + } + + // Persisted swatches render immediately; refresh them in the background + // in case the cover changed. + const timer = + known === undefined + ? setTimeout( + () => !cancelled && setWaitedKey(key), + COVER_PALETTE_WAIT_MS + ) + : null + void extractSwatches(key).then((next) => { + if (!cancelled) show(next ?? known ?? null) + }) + return () => { + cancelled = true + if (timer) clearTimeout(timer) + } + }, [hasCover, key]) + + const palette = useMemo(() => { + const fromArt = + hasCover !== false && swatches ? derive(swatches, isDark) : null + return fromArt ?? themeCoverPalette(theme, isDark) + }, [hasCover, isDark, swatches, theme]) + + return { + palette, + settled: + !key || + hasCover === false || + swatches !== undefined || + waitedKey === key, + } + } + + return { prefetch, usePalette } +} + +function sameSwatches(a: unknown, b: unknown) { + return a === b || JSON.stringify(a) === JSON.stringify(b) +} diff --git a/apps/mobile/hooks/use-cover-palette.ts b/apps/mobile/hooks/use-cover-palette.ts index 7280c45..6cea962 100644 --- a/apps/mobile/hooks/use-cover-palette.ts +++ b/apps/mobile/hooks/use-cover-palette.ts @@ -1,147 +1,47 @@ -import { useEffect, useMemo, useState } from "react" import { - artworkColorsEnabled, + createCoverPaletteSource, + type CoverPaletteResult, +} from "@/hooks/cover-palette-source" +import { + prefetchLegacyCoverPalette, + useLegacyCoverPalette, +} from "@/hooks/use-legacy-cover-palette" +import { + loadArtworkColorsEnabled, useArtworkColorsEnabled, } from "@/lib/artwork-color-preference" -import { prefetchLegacyCoverPalette, useLegacyCoverPalette } from "@/hooks/use-legacy-cover-palette" import { extractCoverSwatches } from "@/lib/artwork-colors" +import { deriveCoverPalette, type CoverSwatches } from "@/lib/cover-palette" -import { - deriveCoverPalette, - themeCoverPalette, - type CoverPalette, - type CoverSwatches, -} from "@/lib/cover-palette" -import { readCache, writeCache } from "@/lib/persistent-cache" -import { useIsDark, useThemeColors } from "@/lib/theme" -import { withCoverImageSize } from "@/lib/urls" +export { COVER_PALETTE_WAIT_MS } from "@/hooks/cover-palette-source" -// How long a screen holds its skeleton for the first extraction of a cover, -// so rows render once with final colors instead of flashing from the theme. -export const COVER_PALETTE_WAIT_MS = 400 - -const swatchesByKey = new Map() -const pending = new Map>() - -function cacheKey(colorSourceUri: string) { - return `palette:v2:${colorSourceUri}` -} - -function sameSwatches( - a: CoverSwatches | null | undefined, - b: CoverSwatches | null | undefined -) { - return a === b || JSON.stringify(a) === JSON.stringify(b) -} - -function cachedSwatches(key: string): CoverSwatches | null | undefined { - if (swatchesByKey.has(key)) return swatchesByKey.get(key) - return readCache(cacheKey(key)) -} - -function extractSwatches(key: string) { - const inFlight = pending.get(key) - if (inFlight) return inFlight - - const request = extractCoverSwatches(key) - .catch(() => null) - .then((swatches) => { - swatchesByKey.set(key, swatches) - if (swatches) writeCache(cacheKey(key), swatches) - pending.delete(key) - return swatches - }) - pending.set(key, request) - return request -} +const region = createCoverPaletteSource({ + cacheKey: (colorSourceUri) => `palette:v2:${colorSourceUri}`, + extract: extractCoverSwatches, + derive: (swatches) => deriveCoverPalette(swatches), +}) /** Warm visible artwork colors before a detail page is pushed. */ export function prefetchCoverPalette(uri: string) { - if (!artworkColorsEnabled()) { - prefetchLegacyCoverPalette(uri) - return - } - const key = withCoverImageSize(uri, 64) - if (cachedSwatches(key) !== undefined) return - void extractSwatches(key) + void loadArtworkColorsEnabled().then((enabled) => + enabled ? region.prefetch(uri) : prefetchLegacyCoverPalette(uri) + ) } /** - * Colors for a screen tinted by `uri`'s cover art. Extraction runs once per - * cover and is cached on device. Pass `hasCover` as `undefined` while it isn't - * known yet so extraction can start early. - * - * `settled` turns true once the palette is final or after - * `COVER_PALETTE_WAIT_MS`, whichever comes first. + * Colors for a screen tinted by `uri`'s cover art, from whichever pipeline the + * device preference selects. Nothing is extracted until the preference loads, + * and the screen stays unsettled meanwhile so it doesn't flash theme colors. */ -function useRegionCoverPalette( +export function useCoverPalette( uri: string, hasCover: boolean | undefined -): { palette: CoverPalette; settled: boolean } { - const theme = useThemeColors() - const isDark = useIsDark() - const key = uri ? withCoverImageSize(uri, 64) : "" - const [resolved, setResolved] = useState(() => ({ - key, - swatches: key ? cachedSwatches(key) : null, - })) - const [waitedKey, setWaitedKey] = useState(null) - - const swatches = - resolved.key === key ? resolved.swatches : key ? cachedSwatches(key) : null - - useEffect(() => { - if (!key || hasCover === false) return - let cancelled = false - const known = cachedSwatches(key) - const show = (next: CoverSwatches | null) => - setResolved((prev) => - prev.key === key && sameSwatches(prev.swatches, next) - ? prev - : { key, swatches: next } - ) - if (known !== undefined && swatchesByKey.has(key)) { - show(known) - return - } - - // Persisted swatches render immediately; refresh them in the background in - // case the cover changed. - const timer = - known === undefined - ? setTimeout( - () => !cancelled && setWaitedKey(key), - COVER_PALETTE_WAIT_MS - ) - : null - void extractSwatches(key).then((next) => { - if (!cancelled) show(next ?? known ?? null) - }) - return () => { - cancelled = true - if (timer) clearTimeout(timer) - } - }, [hasCover, key]) - - const palette = useMemo(() => { - const fromArt = - hasCover !== false && swatches - ? deriveCoverPalette(swatches) - : null - return fromArt ?? themeCoverPalette(theme, isDark) - }, [hasCover, isDark, swatches, theme]) - - return { - palette, - settled: - !key || hasCover === false || swatches !== undefined || waitedKey === key, - } -} - -/** Switch both extraction and palette derivation without mixing their caches. */ -export function useCoverPalette(uri: string, hasCover: boolean | undefined) { +): CoverPaletteResult { const enabled = useArtworkColorsEnabled() - const region = useRegionCoverPalette(enabled ? uri : "", hasCover) - const legacy = useLegacyCoverPalette(enabled ? "" : uri, hasCover) - return enabled ? region : legacy + const current = region.usePalette(enabled === true ? uri : "", hasCover) + const legacy = useLegacyCoverPalette(enabled === false ? uri : "", hasCover) + if (enabled === undefined) { + return { palette: current.palette, settled: !uri || hasCover === false } + } + return enabled ? current : legacy } diff --git a/apps/mobile/hooks/use-legacy-cover-palette.ts b/apps/mobile/hooks/use-legacy-cover-palette.ts index 49a7350..9ea720b 100644 --- a/apps/mobile/hooks/use-legacy-cover-palette.ts +++ b/apps/mobile/hooks/use-legacy-cover-palette.ts @@ -1,29 +1,14 @@ -import { useEffect, useMemo, useState } from "react" import { getColors, type ImageColorsResult } from "react-native-image-colors" +import { createCoverPaletteSource } from "@/hooks/cover-palette-source" import { - themeCoverPalette, - type CoverPalette, -} from "@/lib/cover-palette" -import { deriveCoverPalette, type LegacyCoverSwatches as CoverSwatches } from "@/lib/legacy-cover-palette" -import { readCache, writeCache } from "@/lib/persistent-cache" -import { useIsDark, useThemeColors } from "@/lib/theme" -import { withCoverImageSize } from "@/lib/urls" - -// How long a screen holds its skeleton for the first extraction of a cover, -// so rows render once with final colors instead of flashing from the theme. -const COVER_PALETTE_WAIT_MS = 400 + deriveCoverPalette, + type LegacyCoverSwatches as CoverSwatches, +} from "@/lib/legacy-cover-palette" // image-colors substitutes this for swatches it couldn't find. const MISSING = "#010203" -const swatchesByKey = new Map() -const pending = new Map>() - -function cacheKey(colorSourceUri: string) { - return `palette:${colorSourceUri}` -} - function present(colors: (string | undefined)[]) { return colors.filter( (color): color is string => !!color && color.toLowerCase() !== MISSING @@ -59,120 +44,24 @@ function toSwatches(result: ImageColorsResult): CoverSwatches | null { } } -function sameSwatches( - a: CoverSwatches | null | undefined, - b: CoverSwatches | null | undefined -) { - return a === b || JSON.stringify(a) === JSON.stringify(b) -} - -function cachedSwatches(key: string): CoverSwatches | null | undefined { - if (swatchesByKey.has(key)) return swatchesByKey.get(key) - const cached = readCache(cacheKey(key)) +const legacy = createCoverPaletteSource({ + cacheKey: (colorSourceUri) => `palette:${colorSourceUri}`, + extract: (key) => + getColors(key, { + fallback: MISSING, + cache: true, + key, + quality: "low", + pixelSpacing: 4, + }).then(toSwatches), + derive: deriveCoverPalette, // Discard the background-only entries written by the tablet palette experiment. - return cached && (!Array.isArray(cached.text) || !Array.isArray(cached.accent)) - ? undefined - : cached -} - -function extractSwatches(key: string) { - const inFlight = pending.get(key) - if (inFlight) return inFlight - - const request = getColors(key, { - fallback: MISSING, - cache: true, - key, - quality: "low", - pixelSpacing: 4, - }) - .then(toSwatches) - .catch(() => null) - .then((swatches) => { - swatchesByKey.set(key, swatches) - if (swatches) writeCache(cacheKey(key), swatches) - pending.delete(key) - return swatches - }) - pending.set(key, request) - return request -} + isValidCache: (cached) => + Array.isArray(cached.text) && Array.isArray(cached.accent), +}) /** Warm visible artwork colors before a detail page is pushed. */ -export function prefetchLegacyCoverPalette(uri: string) { - const key = withCoverImageSize(uri, 64) - if (cachedSwatches(key) !== undefined) return - void extractSwatches(key) -} +export const prefetchLegacyCoverPalette = legacy.prefetch -/** - * Colors for a screen tinted by `uri`'s cover art. Extraction runs once per - * cover and is cached on device. Pass `hasCover` as `undefined` while it isn't - * known yet so extraction can start early. - * - * `settled` turns true once the palette is final or after - * `COVER_PALETTE_WAIT_MS`, whichever comes first. - */ -export function useLegacyCoverPalette( - uri: string, - hasCover: boolean | undefined -): { palette: CoverPalette; settled: boolean } { - const theme = useThemeColors() - const isDark = useIsDark() - const key = uri ? withCoverImageSize(uri, 64) : "" - const [resolved, setResolved] = useState(() => ({ - key, - swatches: key ? cachedSwatches(key) : null, - })) - const [waitedKey, setWaitedKey] = useState(null) - - const swatches = - resolved.key === key ? resolved.swatches : key ? cachedSwatches(key) : null - - useEffect(() => { - if (!key || hasCover === false) return - let cancelled = false - const known = cachedSwatches(key) - const show = (next: CoverSwatches | null) => - setResolved((prev) => - prev.key === key && sameSwatches(prev.swatches, next) - ? prev - : { key, swatches: next } - ) - if (known !== undefined && swatchesByKey.has(key)) { - show(known) - return - } - - // Persisted swatches render immediately; refresh them in the background in - // case the cover changed. - const timer = - known === undefined - ? setTimeout( - () => !cancelled && setWaitedKey(key), - COVER_PALETTE_WAIT_MS - ) - : null - void extractSwatches(key).then((next) => { - if (!cancelled) show(next ?? known ?? null) - }) - return () => { - cancelled = true - if (timer) clearTimeout(timer) - } - }, [hasCover, key]) - - const palette = useMemo(() => { - const fromArt = - hasCover !== false && swatches - ? deriveCoverPalette(swatches, isDark) - : null - return fromArt ?? themeCoverPalette(theme, isDark) - }, [hasCover, isDark, swatches, theme]) - - return { - palette, - settled: - !key || hasCover === false || swatches !== undefined || waitedKey === key, - } -} +/** `react-native-image-colors` pipeline used when new artwork colors are off. */ +export const useLegacyCoverPalette = legacy.usePalette diff --git a/apps/mobile/lib/artwork-color-preference.ts b/apps/mobile/lib/artwork-color-preference.ts index 2651ddd..c59d684 100644 --- a/apps/mobile/lib/artwork-color-preference.ts +++ b/apps/mobile/lib/artwork-color-preference.ts @@ -3,8 +3,8 @@ import { useSyncExternalStore } from "react" const STORAGE_KEY = "otunes:artwork-colors" const listeners = new Set<() => void>() -let enabled = true -let loaded = false +// Undefined until storage has been read, so callers never act on a guess. +let enabled: boolean | undefined let loading: Promise | undefined function notify() { @@ -13,37 +13,40 @@ function notify() { function load() { return (loading ??= AsyncStorage.getItem(STORAGE_KEY) + .then((value) => value !== "false") + // Keep the default when local storage is unavailable. + .catch(() => true) .then((value) => { - enabled = value !== "false" - }) - .catch(() => { - // Keep the default when local storage is unavailable. - }) - .finally(() => { - loaded = true + enabled = value notify() })) } +void load() + function subscribe(listener: () => void) { listeners.add(listener) - void load() return () => { listeners.delete(listener) } } -/** Device preference, kept outside account data and the disposable query cache. */ +/** + * Device preference, kept outside account data and the disposable query cache. + * `undefined` until it has loaded. + */ export function useArtworkColorsEnabled() { - return useSyncExternalStore(subscribe, () => loaded && enabled, () => false) + return useSyncExternalStore( + subscribe, + () => enabled, + () => undefined + ) } -export function useArtworkColorPreferenceLoaded() { - return useSyncExternalStore(subscribe, () => loaded, () => false) -} - -export function artworkColorsEnabled() { - return loaded && enabled +/** Resolves with the preference once it has loaded. */ +export async function loadArtworkColorsEnabled() { + await load() + return enabled ?? true } export async function setArtworkColorsEnabled(value: boolean) { From 2427ca1cda42aad81ead4a9fbb810dce113c60d7 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 21:43:57 -0500 Subject: [PATCH 04/11] fix(docker): run backend as non-root, keep env files out, never silently rotate auth keys (#93) --- .dockerignore | 11 +++++------ Dockerfile | 7 ++++++- docker/entrypoint.sh | 33 +++++++++++++++++++++++++++------ 3 files changed, 38 insertions(+), 13 deletions(-) diff --git a/.dockerignore b/.dockerignore index 3e1c66f..2330f90 100644 --- a/.dockerignore +++ b/.dockerignore @@ -54,12 +54,11 @@ playwright.config.* *~ *.log -# Environment variables (only commit template files) -.env -.env*.local -.env.development -.env.test -.env.production.local +# Environment variables, in any workspace. Next.js inlines NEXT_PUBLIC_* values +# into the bundle and the Convex CLI reads .env.local on deploy. +**/.env +**/.env.* +!**/.env.example # Docker configuration files (not needed inside build context) Dockerfile* diff --git a/Dockerfile b/Dockerfile index 543c78d..ae29c75 100644 --- a/Dockerfile +++ b/Dockerfile @@ -195,7 +195,12 @@ RUN node --version \ && 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 +# The backend gets its own user so the web server cannot read the database or +# instance secret. It joins the otunes group to clean up the web server's HLS +# cache in /tmp/otunes. +RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes \ + && useradd --system --user-group --groups otunes --create-home --home-dir /home/convex \ + --shell /usr/sbin/nologin convex COPY --from=convex-functions /app /opt/otunes/convex COPY docker/generate-auth-keys.mjs /opt/otunes/generate-auth-keys.mjs diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index c179357..39352e8 100644 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -46,22 +46,34 @@ stop() { } trap 'stop; exit 0' TERM INT +as_convex=(setpriv --reuid=convex --regid=convex --init-groups env HOME=/home/convex) + convex_cli() { ( cd "$FUNCTIONS_DIR" unset CONVEX_DEPLOYMENT CONVEX_DEPLOY_KEY CONVEX_SELF_HOSTED_URL="$BACKEND_URL" \ CONVEX_SELF_HOSTED_ADMIN_KEY="$admin_key" \ - "$NODE" node_modules/convex/bin/main.js "$@" + "${as_convex[@]}" "$NODE" node_modules/convex/bin/main.js "$@" ) } -# Only root (the backend) may read the database and instance secret. +# Only the convex user may read the database and instance secret. Volumes from +# images that ran the backend as root are still owned by root, and +# read_credentials.sh generates a new instance secret if it cannot read the old one. mkdir -p "$CONVEX_DATA_DIR" +find "$CONVEX_DATA_DIR" \( ! -user convex -o ! -group convex \) \ + -exec chown -h convex:convex {} + chmod 700 "$CONVEX_DATA_DIR" +# The web server writes HLS streams here and a Convex cron deletes stale ones. +mkdir -p /tmp/otunes +chown otunes:otunes /tmp/otunes +chmod -R g+rwX /tmp/otunes +chmod g+s,o-rwx /tmp/otunes + log "Starting Convex backend" -(cd /convex && umask 077 && exec ./run_backend.sh) & +(cd /convex && umask 077 && exec "${as_convex[@]}" ./run_backend.sh) & backend_pid=$! for _ in $(seq 1 120); do @@ -80,17 +92,24 @@ if ! curl -fsS "$BACKEND_URL/version" >/dev/null 2>&1; then exit 1 fi -admin_key=$(cd /convex && ./generate_admin_key.sh) +admin_key=$(cd /convex && umask 077 && "${as_convex[@]}" ./generate_admin_key.sh) log "Deploying Convex functions" convex_cli deploy --typecheck disable --codegen disable -if [ -z "$(convex_cli env get JWKS 2>/dev/null || true)" ]; then +# `env get` exits 0 with no output when the variable is unset. Any other failure +# must not be read as "no keys": regenerating them signs every user out. +if ! jwks=$(convex_cli env get JWKS); then + log "Could not read Convex Auth signing keys" + stop + exit 1 +fi +if [ -z "$jwks" ]; then log "Generating Convex Auth signing keys" "$NODE" /opt/otunes/generate-auth-keys.mjs | convex_cli env set --force fi -unset admin_key +unset admin_key jwks log "Starting web server" ( @@ -100,6 +119,8 @@ log "Starting web server" # Server-side Convex helpers fall back to this at runtime. The browser bundle # is built without it, so browsers still derive their own URL. export NEXT_PUBLIC_CONVEX_URL="$BACKEND_URL" + # Lets the convex group member delete stale HLS streams. + umask 0002 exec setpriv --reuid=otunes --regid=otunes --init-groups \ "$NODE" apps/web/server.js ) & From 22e659cd662093edccdfec4106853ccc4cdc2c6b Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 21:45:25 -0500 Subject: [PATCH 05/11] chore: remove dead code and dedupe web formatDuration (#94) --- .../queue.tsx | 1 - .../app/(app)/(tabs)/home/album/[id].tsx | 2 +- .../app/(app)/(tabs)/home/artist/[id].tsx | 2 +- .../app/(app)/(tabs)/home/playlist/[id].tsx | 3 +- apps/mobile/app/(app)/(tabs)/home/queue.tsx | 186 ----- .../mobile/app/(app)/(tabs)/library/queue.tsx | 1 - apps/mobile/app/(app)/(tabs)/search/queue.tsx | 1 - apps/mobile/app/(app)/player.tsx | 2 +- .../mobile/components/media-actions-sheet.tsx | 7 - apps/mobile/components/tablet-mini-player.tsx | 2 +- apps/mobile/contexts/convex-auth-session.tsx | 14 +- apps/web/components/album-view.tsx | 7 +- apps/web/components/player-bar.tsx | 8 +- apps/web/components/playlist-view.tsx | 7 +- apps/web/components/queue-panel.tsx | 7 +- apps/web/components/songs-view.tsx | 7 +- apps/web/generateKeys.mjs | 15 - apps/web/lib/album-grid-classes.ts | 8 +- apps/web/lib/data.ts | 19 - apps/web/lib/format-duration.ts | 7 + apps/web/lib/media-links.ts | 20 +- apps/web/lib/selection-range-styles.tsx | 8 +- apps/web/lib/station-artist.test.mjs | 30 - packages/convex/convex/actions.ts | 7 - packages/convex/convex/favorites.ts | 26 +- packages/convex/convex/library.ts | 291 +------- packages/convex/convex/playback.ts | 655 +----------------- packages/convex/convex/playlists.ts | 36 +- packages/convex/convex/types.ts | 4 - 29 files changed, 42 insertions(+), 1341 deletions(-) delete mode 100644 apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/queue.tsx delete mode 100644 apps/mobile/app/(app)/(tabs)/home/queue.tsx delete mode 100644 apps/mobile/app/(app)/(tabs)/library/queue.tsx delete mode 100644 apps/mobile/app/(app)/(tabs)/search/queue.tsx delete mode 100644 apps/mobile/components/media-actions-sheet.tsx delete mode 100644 apps/web/generateKeys.mjs delete mode 100644 apps/web/lib/data.ts create mode 100644 apps/web/lib/format-duration.ts delete mode 100644 apps/web/lib/station-artist.test.mjs diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/queue.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/queue.tsx deleted file mode 100644 index 4d4acb6..0000000 --- a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/queue.tsx +++ /dev/null @@ -1 +0,0 @@ -export { default } from "../library/queue" diff --git a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx index 512fccd..66a7c26 100644 --- a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx @@ -35,7 +35,7 @@ import { MediaActionMenu, MediaContextMenu, type MediaAction, -} from "@/components/media-actions-sheet" +} from "@/components/media-context-menu" import { CollectionDetailSkeleton } from "@/components/skeletons" import { Button } from "@/components/ui/primitives" import { contentBottomInset } from "@/components/player" diff --git a/apps/mobile/app/(app)/(tabs)/home/artist/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/artist/[id].tsx index ef90e47..4b6b215 100644 --- a/apps/mobile/app/(app)/(tabs)/home/artist/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/artist/[id].tsx @@ -6,7 +6,7 @@ import { Ionicons } from "@expo/vector-icons" import { CoverImage } from "@/components/cover-image" import { MediaGridList } from "@/components/media-cards" -import { MediaActionMenu } from "@/components/media-actions-sheet" +import { MediaActionMenu } from "@/components/media-context-menu" import { CollectionDetailSkeleton } from "@/components/skeletons" import { Button } from "@/components/ui/primitives" import { contentBottomInset } from "@/components/player" diff --git a/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx index 34037bd..e9f46f1 100644 --- a/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx @@ -46,7 +46,7 @@ import { import { MediaActionMenu, type MediaAction, -} from "@/components/media-actions-sheet" +} from "@/components/media-context-menu" import { CollectionDetailSkeleton } from "@/components/skeletons" import { Button } from "@/components/ui/primitives" import { contentBottomInset, SongListRow } from "@/components/player" @@ -314,7 +314,6 @@ function PlaylistContent({ deletePlaylist, handlePlaylistDetailAction, palette.foreground, - palette.background, palette.isDark, playlistId, playlist?.title, diff --git a/apps/mobile/app/(app)/(tabs)/home/queue.tsx b/apps/mobile/app/(app)/(tabs)/home/queue.tsx deleted file mode 100644 index c378ed7..0000000 --- a/apps/mobile/app/(app)/(tabs)/home/queue.tsx +++ /dev/null @@ -1,186 +0,0 @@ -import { Stack, useRouter } from "expo-router" -import { memo, useCallback, useMemo } from "react" -import { FlatList, Pressable, StyleSheet, Text, View } from "react-native" - -import { Button } from "@/components/ui/primitives" -import { contentBottomInset, SongRow } from "@/components/player" -import { SongRowSkeleton } from "@/components/skeletons" -import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback" -import type { Id } from "@otunes/convex/_generated/dataModel" -import { longListProps } from "@/lib/list" -import { useSong, useSongs } from "@/lib/song-cache" -import { spacing, useThemeColors } from "@/lib/theme" - -/** `key` stays stable when earlier songs leave the queue, so rows are not remounted on skip. */ -type QueueItem = { songId: Id<"songs">; queueIndex: number; key: string } - -function queueItemKey(item: QueueItem) { - return item.key -} - -const QueueRow = memo(function QueueRow({ - songId, - queueIndex, - isLast, - isCurrent, - onSkipTo, - onMove, -}: Omit & { - isLast: boolean - isCurrent: boolean - onSkipTo: (index: number) => void - onMove: (index: number, direction: -1 | 1) => void -}) { - const colors = useThemeColors() - const song = useSong(songId) - - return ( - - {song ? ( - onSkipTo(queueIndex)} /> - ) : ( - - )} - - onMove(queueIndex, -1)} - > - Move up - - onMove(queueIndex, 1)}> - Move down - - {isCurrent ? ( - - Now playing - - ) : null} - - - ) -}) - -export default function QueueScreen() { - const router = useRouter() - const colors = useThemeColors() - const { queueSongIds, queueHistorySongIds } = usePlaybackQueue() - const { skipToQueueIndex, clearQueue, reorderQueue } = usePlaybackActions() - const historySongs = useSongs(queueHistorySongIds) - - const items = useMemo(() => { - const occurrences = new Map() - return queueSongIds.map((songId, queueIndex) => { - const occurrence = occurrences.get(songId) ?? 0 - occurrences.set(songId, occurrence + 1) - return { songId, queueIndex, key: `${songId}:${occurrence}` } - }) - }, [queueSongIds]) - - const moveSong = useCallback( - (fromIndex: number, direction: -1 | 1) => { - const toIndex = fromIndex + direction - if (toIndex < 0 || toIndex >= queueSongIds.length) return - const next = [...queueSongIds] - const [item] = next.splice(fromIndex, 1) - next.splice(toIndex, 0, item) - void reorderQueue(next) - }, - [queueSongIds, reorderQueue] - ) - - function handleClearQueue() { - if (router.canGoBack()) { - router.back() - setTimeout(() => { - void clearQueue() - }, 0) - return - } - - void clearQueue() - } - - return ( - <> - - queueSongIds.length > 0 ? ( - - - - - -
-
{track.title}
- {track.artists ? ( -

- {track.artists.join(", ")} -

- ) : null} -
- - - {formatDuration(track.durationSeconds)} - - - onMediaAction(action, track.id)} - favorited={isFavorite} - navigation={{ - artist: { id: artist.id }, - album: { id: albumId }, - }} - share={{ - type: "song", - albumId, - songId: track.id, - }} - /> - - - ) -} - export function AlbumView({ album, highlightedSongId, @@ -255,17 +99,15 @@ export function AlbumView({ album: BrowseAlbumDetail highlightedSongId?: string }) { - const { openAddToPlaylist } = useAddToPlaylist() const { isSongFavorite, isAlbumFavorite, toggleSongFavorite, toggleAlbumFavorite, - favoriteSongs, } = useFavorites() const { currentSong, playFromSong, playAlbum, playAlbumShuffled } = usePlayback() - const { runQueueAction, createStation } = useQueueMediaActions() + const { runSongsAction } = useMediaActions() const albumSongIds = React.useMemo( () => album.tracks.map((track) => track.id as Id<"songs">), [album.tracks] @@ -303,7 +145,6 @@ export function AlbumView({ const { selectedIds, selectedCount, - isSelected, handleSelect, handlePointerDown, prepareContextMenu, @@ -331,55 +172,55 @@ export function AlbumView({ return indexById }, [album.tracks]) - function handleMediaAction( - action: MediaContextAction, - fallbackTrackId?: string - ) { - const targetIds = - selectedIds.size > 0 - ? Array.from(selectedIds) - : fallbackTrackId - ? [fallbackTrackId] - : activeTrackId - ? [activeTrackId] - : [] - switch (action) { - case "create-station": - void createStation(album.artist.id) - break - case "favorite": - void favoriteSongs(targetIds as Id<"songs">[]) - break - case "playlist": - openAddToPlaylist(targetIds as Id<"songs">[]) - break - case "play-next": - case "play-last": - case "shuffle": - void runQueueAction(action, targetIds as Id<"songs">[]) - break - } - } + const trackSongs = React.useMemo( + () => + new Map( + album.tracks.map((track) => [ + track.id, + { + id: track.id, + title: track.title, + durationSeconds: track.durationSeconds, + artist: album.artist, + album: { id: album.id, title: album.title, cover: album.cover }, + }, + ]) + ), + [album.tracks, album.artist, album.id, album.title, album.cover] + ) + + const handleMediaAction = useTrackListMediaAction({ + selectedIds, + artistId: album.artist.id, + }) + + const handleRowSelect = React.useCallback( + (index: number, event: React.MouseEvent) => { + const trackId = album.tracks[index].id + handleSelect(trackId, index, event) + setActiveTrackId(trackId) + }, + [album.tracks, handleSelect] + ) + + const handleRowPlay = React.useCallback( + (index: number) => { + void playFromSong(album.tracks[index].id, albumSongIds, `album:${album.id}`) + }, + [album.tracks, album.id, albumSongIds, playFromSong] + ) + + const handleToggleFavorite = React.useCallback( + (songId: string) => void toggleSongFavorite(songId as Id<"songs">), + [toggleSongFavorite] + ) function handleAlbumMediaAction(action: MediaContextAction) { - const targetIds = album.tracks.map((track) => track.id as Id<"songs">) - - switch (action) { - case "create-station": - void createStation(album.artist.id) - break - case "favorite": - void toggleAlbumFavorite(album.id as Id<"albums">) - break - case "playlist": - openAddToPlaylist(targetIds) - break - case "play-next": - case "play-last": - case "shuffle": - void runQueueAction(action, targetIds) - break + if (action === "favorite") { + void toggleAlbumFavorite(album.id as Id<"albums">) + return } + runSongsAction(action, albumSongIds, album.artist.id) } return ( @@ -513,39 +354,25 @@ export function AlbumView({ return ( 0 ? track.track : sectionTrackIndex + 1 + } + subtitle={track.artists?.join(", ")} isActive={track.id === activeTrackId} - isSelected={isSelected(track.id)} selectionPosition={selectionPositions[listIndex]} isFavorite={isSongFavorite(track.id)} - selectedCount={ - isSelected(track.id) && selectedCount > 0 - ? selectedCount - : 1 - } - onPointerDown={handlePointerDown} - onSelect={(event) => { - handleSelect(track.id, listIndex, event) - setActiveTrackId(track.id) - }} - onToggleFavorite={() => - void toggleSongFavorite(track.id as Id<"songs">) - } - onPrepareContextMenu={() => - prepareContextMenu(track.id) - } - onMediaAction={handleMediaAction} + selectedCount={selectedCount} + selectionStationArtistId={album.artist.id} isNowPlaying={currentSong?.id === track.id} - onPlay={() => - void playFromSong( - track.id as Id<"songs">, - albumSongIds, - `album:${album.id}` - ) - } + onPointerDown={handlePointerDown} + onSelect={handleRowSelect} + onPlay={handleRowPlay} + onToggleFavorite={handleToggleFavorite} + onPrepareContextMenu={prepareContextMenu} + onMediaAction={handleMediaAction} /> ) })} diff --git a/apps/web/components/artist-view.tsx b/apps/web/components/artist-view.tsx index 4b2fbf9..5bab21e 100644 --- a/apps/web/components/artist-view.tsx +++ b/apps/web/components/artist-view.tsx @@ -4,27 +4,19 @@ import { PageHeader } from "@/components/library-skeletons" import * as React from "react" import Image from "next/image" import { Play, Shuffle } from "lucide-react" -import { useConvex } from "convex/react" -import { useCacheScope } from "@/components/persistent-cache-provider" -import { useAddToPlaylist } from "@/components/add-to-playlist-provider" import { useFavorites } from "@/components/favorites-provider" import { usePlayback } from "@/components/playback-provider" -import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" +import { useMediaActions } from "@/hooks/use-media-actions" import { AlbumCard } from "@/components/album-card" import { FavoriteMediaButton } from "@/components/favorite-media-button" -import { - MediaContextMenu, - type MediaContextAction, -} from "@/components/media-context-menu" +import { MediaContextMenu } from "@/components/media-context-menu" import { Button } from "@/components/ui/button" import { ScrollArea } from "@/components/ui/scroll-area" -import { api } from "@otunes/convex/_generated/api" import type { Id } from "@otunes/convex/_generated/dataModel" import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types" import { albumGridClassName } from "@/lib/album-grid-classes" import { artistCoverUrl } from "@/lib/cover-urls" -import { fetchCachedQuery } from "@otunes/convex/client/cached-query" export function ArtistView({ artist, @@ -34,34 +26,8 @@ export function ArtistView({ albums: BrowseAlbum[] }) { const { isArtistFavorite, toggleArtistFavorite } = useFavorites() - const { openAddArtistToPlaylist } = useAddToPlaylist() const { playArtist, playArtistShuffled } = usePlayback() - const { runQueueAction } = useQueueMediaActions() - const convex = useConvex() - const cacheScope = useCacheScope() - - async function handleMediaAction(action: MediaContextAction) { - switch (action) { - case "favorite": - void toggleArtistFavorite(artist.id as Id<"artists">) - break - case "playlist": - void openAddArtistToPlaylist(artist.id as Id<"artists">) - break - case "play-next": - case "play-last": - case "shuffle": { - const songIds = await fetchCachedQuery( - convex, - cacheScope, - api.playlists.getOrderedArtistSongIds, - { artistId: artist.id as Id<"artists"> } - ) - void runQueueAction(action, songIds) - break - } - } - } + const { runArtistAction } = useMediaActions() return (
@@ -118,7 +84,7 @@ export function ArtistView({ label={`More options for ${artist.name}`} selectedCount={albums.length} onOpenMenu={() => {}} - onAction={handleMediaAction} + onAction={(action) => void runArtistAction(action, artist.id)} favorited={isArtistFavorite(artist.id)} trackRowTrigger={false} triggerVariant="secondary" diff --git a/apps/web/components/artists-view.tsx b/apps/web/components/artists-view.tsx index 554e35d..48b3d8a 100644 --- a/apps/web/components/artists-view.tsx +++ b/apps/web/components/artists-view.tsx @@ -4,11 +4,8 @@ import * as React from "react" import Image from "next/image" import Link from "next/link" import { ChevronRightIcon, Play, Shuffle } from "lucide-react" -import { useConvex } from "convex/react" -import { useCacheScope } from "@/components/persistent-cache-provider" import { AlbumCard } from "@/components/album-card" -import { useAddToPlaylist } from "@/components/add-to-playlist-provider" import { FavoriteMediaButton } from "@/components/favorite-media-button" import { useFavorites } from "@/components/favorites-provider" import { @@ -16,15 +13,13 @@ import { type MediaContextAction, } from "@/components/media-context-menu" import { usePlayback } from "@/components/playback-provider" -import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" +import { useMediaActions } from "@/hooks/use-media-actions" import { Button } from "@/components/ui/button" import { ScrollArea } from "@/components/ui/scroll-area" -import { api } from "@otunes/convex/_generated/api" import { cn } from "@/lib/utils" import type { Id } from "@otunes/convex/_generated/dataModel" import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types" import { artistCoverUrl } from "@/lib/cover-urls" -import { fetchCachedQuery } from "@otunes/convex/client/cached-query" function ArtistAvatar({ artist }: { artist: BrowseArtist }) { return ( @@ -110,12 +105,9 @@ export function ArtistsView({ } return sortedArtists[0]?.id ?? "" }, [artistId, sortedArtists]) - const convex = useConvex() - const cacheScope = useCacheScope() - const { openAddArtistToPlaylist } = useAddToPlaylist() const { isArtistFavorite, toggleArtistFavorite } = useFavorites() const { playArtist, playArtistShuffled } = usePlayback() - const { runQueueAction } = useQueueMediaActions() + const { runArtistAction } = useMediaActions() const selectedArtist = sortedArtists.find( (artist) => artist.id === selectedId @@ -130,32 +122,6 @@ export function ArtistsView({ return counts }, [albums]) - async function handleMediaAction( - artistId: string, - action: MediaContextAction - ) { - switch (action) { - case "favorite": - void toggleArtistFavorite(artistId as Id<"artists">) - break - case "playlist": - void openAddArtistToPlaylist(artistId as Id<"artists">) - break - case "play-next": - case "play-last": - case "shuffle": { - const songIds = await fetchCachedQuery( - convex, - cacheScope, - api.playlists.getOrderedArtistSongIds, - { artistId: artistId as Id<"artists"> } - ) - void runQueueAction(action, songIds) - break - } - } - } - return (
@@ -169,7 +135,7 @@ export function ArtistsView({ isFavorite={isArtistFavorite(artist.id)} onSelect={() => onSelectArtist(artist.id)} onMediaAction={(action) => - void handleMediaAction(artist.id, action) + void runArtistAction(action, artist.id) } /> ))} @@ -225,7 +191,7 @@ export function ArtistsView({ selectedCount={artistAlbums.length} onOpenMenu={() => {}} onAction={(action) => - void handleMediaAction(selectedArtist.id, action) + void runArtistAction(action, selectedArtist.id) } favorited={isArtistFavorite(selectedArtist.id)} trackRowTrigger={false} diff --git a/apps/web/components/playlist-view.tsx b/apps/web/components/playlist-view.tsx index a12dbff..6dd6eaa 100644 --- a/apps/web/components/playlist-view.tsx +++ b/apps/web/components/playlist-view.tsx @@ -9,15 +9,14 @@ import { useMutation } from "convex/react" import { Play, SearchIcon, Share2, Shuffle, Star, Trash2 } from "lucide-react" import { toast } from "sonner" -import { useAddToPlaylist } from "@/components/add-to-playlist-provider" import { useFavorites } from "@/components/favorites-provider" import { usePlayback } from "@/components/playback-provider" import { MediaCollectionFooter } from "@/components/media-collection-footer" -import { TrackNumberPlayButton } from "@/components/track-number-play-button" import { MediaContextMenu, type MediaContextAction, } from "@/components/media-context-menu" +import { TrackRow } from "@/components/track-row" import { Button } from "@/components/ui/button" import { DropdownMenuItem, @@ -25,243 +24,22 @@ import { } from "@/components/ui/dropdown-menu" import { ScrollArea } from "@/components/ui/scroll-area" import { useCachedQuery } from "@/hooks/use-cached-query" -import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" +import { + useMediaActions, + useTrackListMediaAction, +} from "@/hooks/use-media-actions" import { useTrackSelection } from "@/hooks/use-track-selection" import { api } from "@otunes/convex/_generated/api" import type { Id } from "@otunes/convex/_generated/dataModel" import type { BrowsePlaylistDetail, BrowseSong } from "@otunes/convex/types" -import { albumCoverUrl, playlistCoverUrl } from "@/lib/cover-urls" +import { playlistCoverUrl } from "@/lib/cover-urls" import { copyPlaylistLink } from "@/lib/media-links" import { sumDurationSeconds } from "@/lib/media-summary" import { rememberSongs } from "@/lib/song-cache" -import { cn } from "@/lib/utils" -import { - getSelectionRangePositions, - isInSelectionRange, - ALBUM_TRACK_ROW, - ALBUM_TRACK_TITLE, - SelectionRangeHighlight, - TrackRowActiveHighlight, - TrackRowHoverHighlight, - TRACK_ROW_PADDING, - type SelectionRangePosition, -} from "@/lib/selection-range-styles" -import { formatDuration } from "@/lib/format-duration" +import { getSelectionRangePositions } from "@/lib/selection-range-styles" const ADD_TO_ANOTHER_PLAYLIST = "Add to Another Playlist" -function PlaylistSongCover({ - song, - inRange, - isFavorite, - onToggleFavorite, -}: { - song: BrowseSong - inRange: boolean - isFavorite: boolean - onToggleFavorite: () => void -}) { - return ( -
- {song.album.title} -
- -
-
- ) -} - -function PlaylistSongRow({ - song, - index, - isOwner, - canRemove, - isActive, - selectionPosition, - isFavorite, - selectedCount, - stationArtist, - isDragging, - onSelect, - onPointerDown, - onToggleFavorite, - onPrepareContextMenu, - onMediaAction, - onRemove, - onDragStart, - onDragOver, - onDrop, - showFavoriteInMenu = true, - removeLabel = "Remove from Playlist", - isNowPlaying, - onPlay, -}: { - song: BrowseSong - index: number - isOwner: boolean - canRemove: boolean - isActive: boolean - selectionPosition: SelectionRangePosition - isFavorite: boolean - selectedCount: number - stationArtist?: string - isDragging: boolean - onSelect: (event: React.MouseEvent) => void - onPointerDown: (event: React.MouseEvent) => void - onToggleFavorite: () => void - onPrepareContextMenu: () => void - onMediaAction: (action: MediaContextAction, songId: string) => void - onRemove: () => void - onDragStart: (event: React.DragEvent) => void - onDragOver: (event: React.DragEvent) => void - onDrop: (event: React.DragEvent) => void - showFavoriteInMenu?: boolean - removeLabel?: string - isNowPlaying: boolean - onPlay: () => void -}) { - const displayTrack = index + 1 - const inRange = isInSelectionRange(selectionPosition) - - return ( -
{ - event.preventDefault() - onPlay() - }} - onKeyDown={(event) => { - if (event.key === "Enter" || event.key === " ") { - event.preventDefault() - onSelect(event as unknown as React.MouseEvent) - } - }} - className={cn( - "group relative w-full cursor-pointer select-none py-2.5 text-left text-sm transition-colors", - inRange && "text-primary-foreground", - isDragging && "opacity-50" - )} - > - - {!inRange && isActive ? : null} - {!inRange && !isActive ? : null} -
- - - - - {song.title} - - - {formatDuration(song.durationSeconds)} - - - onMediaAction(action, song.id)} - playlistLabel={ADD_TO_ANOTHER_PLAYLIST} - showFavorite={showFavoriteInMenu} - favorited={isFavorite} - navigation={{ - artist: { id: song.artist.id }, - album: { id: song.album.id }, - }} - share={{ - type: "song", - albumId: song.album.id, - songId: song.id, - }} - > - {canRemove ? ( - <> - - - {removeLabel} - - - - ) : null} - -
-
- ) -} - export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { const router = useRouter() const isFavorites = playlist.isFavorites === true @@ -270,13 +48,8 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { currentUser === undefined ? playlist.isOwner : currentUser?._id === playlist.owner.id - const { openAddToPlaylist } = useAddToPlaylist() - const { - isSongFavorite, - toggleSongFavorite, - toggleSongsFavorite, - favoriteSongs: addFavoriteSongs, - } = useFavorites() + const { isSongFavorite, toggleSongFavorite, toggleSongsFavorite } = + useFavorites() const { currentSong, playInOrder, @@ -285,7 +58,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { playPlaylistShuffled, playFromSong, } = usePlayback() - const { runQueueAction, createStation } = useQueueMediaActions() + const { runSongsAction } = useMediaActions() const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist) const reorderSongs = useMutation(api.playlists.reorderPlaylistSongs) const deletePlaylist = useMutation(api.playlists.deletePlaylist) @@ -317,6 +90,10 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { () => songs.map((song) => song.id as Id<"songs">), [songs] ) + const playlistPositionById = React.useMemo( + () => new Map(songs.map((song, index) => [song.id, index + 1])), + [songs] + ) const [activeTrackId, setActiveTrackId] = React.useState("") const [dragIndex, setDragIndex] = React.useState(null) const [isSubscribed, setIsSubscribed] = React.useState(playlist.isSubscribed) @@ -331,7 +108,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { const { selectedIds, selectedCount, - isSelected, handleSelect, handlePointerDown, prepareContextMenu, @@ -369,57 +145,37 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { } } - function resolveTargetIds(fallbackSongId?: string) { - return selectedIds.size > 0 - ? Array.from(selectedIds) - : fallbackSongId - ? [fallbackSongId] - : activeTrackId - ? [activeTrackId] - : [] - } - - function handleMediaAction( - action: MediaContextAction, - fallbackSongId?: string - ) { - const targetIds = resolveTargetIds(fallbackSongId) - - switch (action) { - case "create-station": { - const artistId = stationArtistId(songs, new Set(targetIds)) - if (artistId) void createStation(artistId) - break - } - case "favorite": - void addFavoriteSongs(targetIds as Id<"songs">[]) - break - case "playlist": - openAddToPlaylist(targetIds as Id<"songs">[]) - break - case "play-next": - case "play-last": - case "shuffle": - void runQueueAction(action, targetIds as Id<"songs">[]) - break - } - } + const handleMediaAction = useTrackListMediaAction({ selectedIds, songs }) function handlePlaylistMediaAction(action: MediaContextAction) { - const targetIds = songs.map((song) => song.id as Id<"songs">) + runSongsAction(action, playlistSongIds) + } - switch (action) { - case "favorite": - void addFavoriteSongs(targetIds) - break - case "playlist": - openAddToPlaylist(targetIds) - break - case "play-next": - case "play-last": - case "shuffle": - void runQueueAction(action, targetIds) - break + const canReorder = isOwner && !isFavorites && !normalizedQuery + + function handleRowSelect(index: number, event: React.MouseEvent) { + const songId = filteredSongs[index].id + handleSelect(songId, index, event) + setActiveTrackId(songId) + } + + function handleRowPlay(index: number) { + void playFromSong( + filteredSongs[index].id, + playlistSongIds, + `playlist:${playlist.id}` + ) + } + + function handleToggleFavorite(songId: string) { + const wasFavorite = isSongFavorite(songId) + void toggleSongFavorite(songId as Id<"songs">) + if (isFavorites && wasFavorite) { + setHiddenFavoriteIds((current) => { + const next = new Set(current) + next.add(songId) + return next + }) } } @@ -474,13 +230,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { } function handleDrop(targetIndex: number) { - if ( - normalizedQuery || - isFavorites || - !isOwner || - dragIndex === null || - dragIndex === targetIndex - ) { + if (!canReorder || dragIndex === null || dragIndex === targetIndex) { setDragIndex(null) return } @@ -672,74 +422,37 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
{filteredSongs.length > 0 ? ( filteredSongs.map((song, index) => ( - 0 - ? selectedCount - : 1 - } - stationArtist={ - isSelected(song.id) - ? selectedStationArtistId - : song.artist.id - } - isDragging={dragIndex === index} onPointerDown={handlePointerDown} - onSelect={(event) => { - handleSelect(song.id, index, event) - setActiveTrackId(song.id) - }} - onToggleFavorite={() => { - const wasFavorite = isSongFavorite(song.id) - void toggleSongFavorite(song.id as Id<"songs">) - if (isFavorites && wasFavorite) { - setHiddenFavoriteIds((current) => { - const next = new Set(current) - next.add(song.id) - return next - }) - } - }} - onPrepareContextMenu={() => prepareContextMenu(song.id)} + onSelect={handleRowSelect} + onPlay={handleRowPlay} + onToggleFavorite={handleToggleFavorite} + onPrepareContextMenu={prepareContextMenu} onMediaAction={handleMediaAction} - onRemove={() => handleRemoveSong(song.id)} - onDragStart={(event) => { - if (normalizedQuery || isFavorites || !isOwner) { - return - } - setDragIndex(index) - event.dataTransfer.effectAllowed = "move" - }} - onDragOver={(event) => { - if (normalizedQuery || isFavorites || !isOwner) { - return - } - event.preventDefault() - }} - onDrop={(event) => { - event.preventDefault() - handleDrop(index) - }} - isNowPlaying={currentSong?.id === song.id} - onPlay={() => - void playFromSong( - song.id as Id<"songs">, - playlistSongIds, - `playlist:${playlist.id}` - ) - } + onRemove={handleRemoveSong} + onDragStart={canReorder ? setDragIndex : undefined} + onDrop={canReorder ? handleDrop : undefined} /> )) ) : ( diff --git a/apps/web/components/queue-panel.tsx b/apps/web/components/queue-panel.tsx index c642996..d2513bc 100644 --- a/apps/web/components/queue-panel.tsx +++ b/apps/web/components/queue-panel.tsx @@ -1,11 +1,10 @@ "use client" import * as React from "react" -import Image from "next/image" -import { Music2 } from "lucide-react" import { PlaybackSongMeta } from "@/components/playback-song-meta" import { usePlayback } from "@/components/playback-provider" +import { TrackCover, TrackRow } from "@/components/track-row" import { Button } from "@/components/ui/button" import { ScrollArea } from "@/components/ui/scroll-area" import { Skeleton } from "@/components/ui/skeleton" @@ -13,19 +12,11 @@ import { Spinner } from "@/components/ui/spinner" import { useTrackSelection } from "@/hooks/use-track-selection" import type { Id } from "@otunes/convex/_generated/dataModel" import type { BrowseSong, HistorySong, QueueSong } from "@otunes/convex/types" -import { albumCoverUrl } from "@/lib/cover-urls" import { getContiguousSelectedIndices, moveQueueBlock, } from "@/lib/move-queue-block" -import { - getSelectionRangePositions, - isInSelectionRange, - QueueSelectionRangeHighlight, - QueueTrackRowActiveHighlight, - QueueTrackRowHoverHighlight, - type SelectionRangePosition, -} from "@/lib/selection-range-styles" +import { getSelectionRangePositions } from "@/lib/selection-range-styles" import { useSongs } from "@/lib/song-cache" import { cn } from "@/lib/utils" import { formatDuration } from "@/lib/format-duration" @@ -56,48 +47,16 @@ function toSelectableQueue( }) } -function QueueSongCover({ - albumId, - title, - inRange, -}: { - albumId: string - title: string - inRange: boolean -}) { - return ( -
- {title} -
- ) -} - function HistorySongRow({ song }: { song: HistorySong }) { return (
  • - {song.album.id ? ( - - ) : ( -
    - -
    - )} + void - onPointerDown: (event: React.MouseEvent) => void - onSkipTo: () => void - onDragStart: (event: React.DragEvent) => void - onDragOver: (event: React.DragEvent) => void - onDrop: (event: React.DragEvent) => void - } ->(function QueueSongRow( - { - song, - isNowPlaying, - selectionPosition, - isDragging, - onSelect, - onPointerDown, - onSkipTo, - onDragStart, - onDragOver, - onDrop, - }, - ref -) { - const inRange = isInSelectionRange(selectionPosition) - - return ( -
  • { - event.preventDefault() - onSkipTo() - }} - onKeyDown={(event) => { - if (event.key === "Enter" || event.key === " ") { - event.preventDefault() - onSelect(event as unknown as React.MouseEvent) - } - }} - className={cn( - "group relative w-full cursor-pointer select-none py-2 text-left text-sm transition-colors", - inRange && "text-primary-foreground", - isDragging && "opacity-50" - )} - > - - {!inRange && isNowPlaying ? : null} - {!inRange && !isNowPlaying ? : null} -
    - {song.album.id ? ( - - ) : ( -
    - -
    - )} - - - - - {formatDuration(song.durationSeconds)} - -
    -
  • - ) -}) - function QueueSongRowSkeleton() { return (
  • @@ -238,7 +97,7 @@ export function QueuePanel() { skipToQueueIndex, } = usePlayback() const loadMoreRef = React.useRef(null) - const nowPlayingRef = React.useRef(null) + const nowPlayingRef = React.useRef(null) const [visibleCount, setVisibleCount] = React.useState( QUEUE_INITIAL_VISIBLE_COUNT ) @@ -306,12 +165,25 @@ export function QueuePanel() { return () => observer.disconnect() }, [hasMore]) - const { - selectedIds, - handleSelect, - handlePointerDown, - } = useTrackSelection( - selectableQueue.map((item) => ({ id: item.selectionId })) + const selectionItems = React.useMemo( + () => selectableQueue.map((item) => ({ id: item.selectionId })), + [selectableQueue] + ) + const { selectedIds, handleSelect, handlePointerDown } = + useTrackSelection(selectionItems) + + const handleRowSelect = React.useCallback( + (index: number, event: React.MouseEvent) => { + handleSelect(selectableQueue[index].selectionId, index, event) + }, + [selectableQueue, handleSelect] + ) + + const handleRowPlay = React.useCallback( + (index: number) => { + void skipToQueueIndex(selectableQueue[index].queueIndex) + }, + [selectableQueue, skipToQueueIndex] ) const selectionPositions = React.useMemo( @@ -398,27 +270,21 @@ export function QueuePanel() {
      {selectableQueue.map((item, index) => item.song ? ( - { - handleSelect(item.selectionId, index, event) - }} - onSkipTo={() => void skipToQueueIndex(item.queueIndex)} - onDragStart={(event) => { - setDragIndex(index) - event.dataTransfer.effectAllowed = "move" - }} - onDragOver={(event) => event.preventDefault()} - onDrop={(event) => { - event.preventDefault() - handleDrop(index) - }} + onSelect={handleRowSelect} + onPlay={handleRowPlay} + onDragStart={setDragIndex} + onDrop={handleDrop} /> ) : ( diff --git a/apps/web/components/songs-view.tsx b/apps/web/components/songs-view.tsx index 3ac20a9..2bdf0ae 100644 --- a/apps/web/components/songs-view.tsx +++ b/apps/web/components/songs-view.tsx @@ -2,18 +2,19 @@ import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger" import { stationArtistId } from "@/lib/station-artist" -import { useEffect, useMemo, useState, useRef, MouseEvent } from "react" -import Image from "next/image" -import Link from "next/link" -import { ArrowUpDown, Play, Star } from "lucide-react" +import { + useCallback, + useEffect, + useMemo, + useState, + useRef, + type MouseEvent, +} from "react" +import { ArrowUpDown } from "lucide-react" -import { useAddToPlaylist } from "@/components/add-to-playlist-provider" import { useFavorites } from "@/components/favorites-provider" import { usePlayback } from "@/components/playback-provider" -import { - MediaContextMenu, - type MediaContextAction, -} from "@/components/media-context-menu" +import { LibraryTrackListHeader, TrackRow } from "@/components/track-row" import { Button } from "@/components/ui/button" import { DropdownMenu, @@ -25,247 +26,27 @@ import { DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" import { useCachedPaginatedQuery } from "@/hooks/use-cached-query" -import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" +import { useTrackListMediaAction } from "@/hooks/use-media-actions" import { useTrackSelection } from "@/hooks/use-track-selection" import { SongListSkeleton } from "@/components/library-skeletons" import { ScrollArea } from "@/components/ui/scroll-area" import { Spinner } from "@/components/ui/spinner" import { api } from "@otunes/convex/_generated/api" -import { - Table, - TableBody, - TableCell, - TableHead, - TableHeader, - TableRow, -} from "@/components/ui/table" import { cn } from "@/lib/utils" import type { Id } from "@otunes/convex/_generated/dataModel" -import type { BrowseSong } from "@otunes/convex/types" -import { albumCoverUrl } from "@/lib/cover-urls" import { getSelectionRangePositions, - isInSelectionRange, - ALBUM_TRACK_TITLE, - SongsSelectionRangeHighlight, - SongsTrackRowHoverHighlight, TRACK_ROW_PADDING, - type SelectionRangePosition, } from "@/lib/selection-range-styles" -import { formatDuration } from "@/lib/format-duration" type SortKey = "title" | "artist" | "album" type SortDirection = "asc" | "desc" const SONGS_PAGE_SIZE = 50 -const songRowLayout = - "flex w-full items-center gap-x-4" -const nameColumnLayout = - "grid grid-cols-[2rem_2.5rem_minmax(0,10rem)] items-center gap-x-2" -const songColumnClass = "w-36 shrink-0 truncate" - -function SongCover({ - song, - inRange, - onPlay, -}: { - song: BrowseSong - inRange: boolean - onPlay: () => void -}) { - return ( -
      - {song.album.title} -
      - -
      -
      - ) -} - -function SongRow({ - song, - isSelected, - selectionPosition, - isFavorite, - selectedCount, - stationArtist, - onSelect, - onPointerDown, - onToggleFavorite, - onPrepareContextMenu, - onMediaAction, - onPlay, -}: { - song: BrowseSong - isSelected: boolean - selectionPosition: SelectionRangePosition - isFavorite: boolean - selectedCount: number - stationArtist?: string - onSelect: (event: MouseEvent) => void - onPointerDown: (event: MouseEvent) => void - onToggleFavorite: () => void - onPrepareContextMenu: () => void - onMediaAction: (action: MediaContextAction, songId: string) => void - onPlay: () => void -}) { - const inRange = isInSelectionRange(selectionPosition) - const linkClass = inRange - ? "text-primary-foreground hover:text-primary-foreground/80 hover:underline" - : "text-muted-foreground hover:text-foreground hover:underline" - - return ( - { - event.preventDefault() - onPlay() - }} - className="group cursor-pointer select-none border-none hover:bg-transparent" - > - -
      - - {!inRange ? : null} -
      -
      -
      - -
      - - - {song.title} - {song.explicit ? ( - - E - - ) : null} - -
      -
      - event.stopPropagation()} - > - {song.artist.name} - -
      -
      - event.stopPropagation()} - > - {song.album.title} - -
      -
      - - {formatDuration(song.durationSeconds)} - - onMediaAction(action, song.id)} - favorited={isFavorite} - navigation={{ - artist: { id: song.artist.id }, - album: { id: song.album.id }, - }} - share={{ - type: "song", - albumId: song.album.id, - songId: song.id, - }} - /> -
      -
      - - - ) -} - export function SongsView() { - const { openAddToPlaylist } = useAddToPlaylist() - const { isSongFavorite, toggleSongFavorite, favoriteSongs } = useFavorites() + const { isSongFavorite, toggleSongFavorite } = useFavorites() const { playFromLibrarySong } = usePlayback() - const { runQueueAction, createStation } = useQueueMediaActions() const [sortKey, setSortKey] = useState("title") const [sortDirection, setSortDirection] = useState("asc") @@ -306,7 +87,6 @@ export function SongsView() { const { selectedIds, selectedCount, - isSelected, handleSelect, handlePointerDown, prepareContextMenu, @@ -327,32 +107,26 @@ export function SongsView() { [songs, selectedIds] ) - function handleMediaAction(action: MediaContextAction, fallbackSongId?: string) { - const targetIds = - selectedIds.size > 0 - ? Array.from(selectedIds) - : fallbackSongId - ? [fallbackSongId] - : [] - switch (action) { - case "create-station": { - const artistId = stationArtistId(songs, new Set(targetIds)) - if (artistId) void createStation(artistId) - break - } - case "favorite": - void favoriteSongs(targetIds as Id<"songs">[]) - break - case "playlist": - openAddToPlaylist(targetIds as Id<"songs">[]) - break - case "play-next": - case "play-last": - case "shuffle": - void runQueueAction(action, targetIds as Id<"songs">[]) - break - } - } + const handleMediaAction = useTrackListMediaAction({ selectedIds, songs }) + + const handleRowSelect = useCallback( + (index: number, event: MouseEvent) => { + handleSelect(songs[index].id, index, event) + }, + [songs, handleSelect] + ) + + const handleRowPlay = useCallback( + (index: number) => { + void playFromLibrarySong(songs[index].id, { sortKey, sortDirection }) + }, + [songs, sortKey, sortDirection, playFromLibrarySong] + ) + + const handleToggleFavorite = useCallback( + (songId: string) => void toggleSongFavorite(songId as Id<"songs">), + [toggleSongFavorite] + ) if (status === "LoadingFirstPage" && !isCached) { return ( @@ -432,68 +206,25 @@ export function SongsView() { } }} > - - - - -
      -
      - - - Name -
      - - Artist - - - Album - -
      - - Time - - -
      - - - - - {songs.map((song, index) => ( - 0 - ? selectedCount - : 1 - } - onPointerDown={handlePointerDown} - onSelect={(event) => { - handleSelect(song.id, index, event) - }} - onToggleFavorite={() => - void toggleSongFavorite(song.id as Id<"songs">) - } - onPrepareContextMenu={() => prepareContextMenu(song.id)} - onMediaAction={handleMediaAction} - onPlay={() => - void playFromLibrarySong(song.id as Id<"songs">, { - sortKey, - sortDirection, - }) - } - /> - ))} - -
      + + {songs.map((song, index) => ( + + ))}
      + onSelect: (index: number, event: React.MouseEvent) => void + onPointerDown: (event: React.MouseEvent) => void + onPlay: (index: number) => void + onToggleFavorite?: (songId: string) => void + onPrepareContextMenu?: (songId: string) => void + /** Renders the "more options" menu when provided. */ + onMediaAction?: (action: MediaContextAction, songId: string) => void + onRemove?: (songId: string) => void + /** Makes the row draggable when provided. */ + onDragStart?: (index: number) => void + onDrop?: (index: number) => void +} + +const LIBRARY_ROW_LAYOUT = "flex w-full items-center gap-x-4" +const LIBRARY_NAME_COLUMNS = + "grid grid-cols-[2rem_2.5rem_minmax(0,10rem)] items-center gap-x-2" +const LIBRARY_COLUMN = "w-36 shrink-0 truncate" + +export function TrackCover({ + albumId, + alt, + inRange, + square = false, + children, +}: { + albumId: string | undefined + alt: string + inRange: boolean + square?: boolean + /** Overlay shown above the cover image. */ + children?: React.ReactNode +}) { + const ringClass = inRange ? "ring-white/25" : "ring-foreground/10" + + if (!albumId) { + return ( +
      + +
      + ) + } + + return ( +
      + {alt} + {children} +
      + ) +} + +function FavoriteStarButton({ + title, + isFavorite, + inRange, + className, + onToggle, +}: { + title: string + isFavorite: boolean + inRange: boolean + className?: string + onToggle: () => void +}) { + return ( + + ) +} + +function ExplicitBadge({ inRange }: { inRange: boolean }) { + return ( + + E + + ) +} + +function TrackTitle({ + song, + subtitle, + inRange, +}: { + song: BrowseSong + subtitle?: string + inRange: boolean +}) { + return ( +
      +
      + {song.title} + {song.explicit ? : null} +
      + {subtitle ? ( +

      + {subtitle} +

      + ) : null} +
      + ) +} + +export function LibraryTrackListHeader() { + const labelClass = "text-xs text-muted-foreground" + return ( +
      +
      + + + Name +
      + Artist + Album +
      + Time + +
      + ) +} + +function TrackRowComponent({ + variant, + song, + index, + trackNumber, + subtitle, + selectionPosition, + isActive = false, + isNowPlaying = false, + isFavorite = false, + isDragging = false, + selectedCount = 0, + selectionStationArtistId, + playlistLabel, + showFavoriteInMenu = true, + removeLabel, + ref, + onSelect, + onPointerDown, + onPlay, + onToggleFavorite, + onPrepareContextMenu, + onMediaAction, + onRemove, + onDragStart, + onDrop, +}: TrackRowProps) { + const inRange = isInSelectionRange(selectionPosition) + const flush = variant === "library" || variant === "queue" + const play = () => onPlay(index) + const toggleFavorite = () => onToggleFavorite?.(song.id) + + const favoriteStar = ( +
      + +
      + ) + + const trackNumberButton = ( + + ) + + const duration = ( + + {formatDuration(song.durationSeconds)} + + ) + + const menu = onMediaAction ? ( + 0 ? selectedCount : 1} + inSelectionRange={inRange} + onOpenMenu={() => onPrepareContextMenu?.(song.id)} + onAction={(action) => onMediaAction(action, song.id)} + playlistLabel={playlistLabel} + showFavorite={showFavoriteInMenu} + favorited={isFavorite} + navigation={{ + artist: { id: song.artist.id }, + album: { id: song.album.id }, + }} + share={{ type: "song", albumId: song.album.id, songId: song.id }} + > + {removeLabel && onRemove ? ( + <> + + onRemove(song.id)} + > + {removeLabel} + + + + ) : null} + + ) : null + + let content: React.ReactNode + switch (variant) { + case "library": { + const linkClass = inRange + ? "text-primary-foreground hover:text-primary-foreground/80 hover:underline" + : "text-muted-foreground hover:text-foreground hover:underline" + content = ( +
      +
      + {favoriteStar} + +
      + +
      +
      + +
      +
      + event.stopPropagation()} + > + {song.artist.name} + +
      +
      + event.stopPropagation()} + > + {song.album.title} + +
      +
      + {duration} + {menu} +
      + ) + break + } + case "album": + content = ( +
      + {favoriteStar} + {trackNumberButton} + + {duration} + {menu} +
      + ) + break + case "playlist": + content = ( +
      + +
      + +
      +
      + {trackNumberButton} + + {duration} + {menu} +
      + ) + break + case "queue": + content = ( +
      + + + {duration} +
      + ) + break + } + + const shellProps = { + role: "button", + tabIndex: 0, + draggable: onDragStart ? true : undefined, + onDragStart: onDragStart + ? (event: React.DragEvent) => { + event.dataTransfer.effectAllowed = "move" + onDragStart(index) + } + : undefined, + onDragOver: onDragStart + ? (event: React.DragEvent) => event.preventDefault() + : undefined, + onDrop: onDrop + ? (event: React.DragEvent) => { + event.preventDefault() + onDrop(index) + } + : undefined, + onMouseDown: onPointerDown, + onClick: (event: React.MouseEvent) => onSelect(index, event), + onDoubleClick: (event: React.MouseEvent) => { + event.preventDefault() + play() + }, + onKeyDown: (event: React.KeyboardEvent) => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault() + onSelect(index, event as unknown as React.MouseEvent) + } + }, + className: cn( + "group relative w-full cursor-pointer select-none text-left text-sm transition-colors", + flush ? "py-2" : "py-2.5", + inRange && "text-primary-foreground", + isDragging && "opacity-50" + ), + } + + const children = ( + <> + + {!inRange && isActive ? : null} + {!inRange && !isActive ? : null} + {content} + + ) + + return variant === "queue" ? ( +
    • } {...shellProps}> + {children} +
    • + ) : ( +
      } {...shellProps}> + {children} +
      + ) +} + +/** + * Pass stable callbacks: they receive the row's `index` or song id, so one + * handler can serve every row. + */ +export const TrackRow = React.memo(TrackRowComponent) diff --git a/apps/web/hooks/use-media-actions.ts b/apps/web/hooks/use-media-actions.ts new file mode 100644 index 0000000..d665acc --- /dev/null +++ b/apps/web/hooks/use-media-actions.ts @@ -0,0 +1,104 @@ +"use client" + +import * as React from "react" +import { useConvex } from "convex/react" + +import { useAddToPlaylist } from "@/components/add-to-playlist-provider" +import { useFavorites } from "@/components/favorites-provider" +import type { MediaContextAction } from "@/components/media-context-menu" +import { useCacheScope } from "@/components/persistent-cache-provider" +import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" +import { stationArtistId } from "@/lib/station-artist" +import { api } from "@otunes/convex/_generated/api" +import type { Id } from "@otunes/convex/_generated/dataModel" +import { fetchCachedQuery } from "@otunes/convex/client/cached-query" + +export function useMediaActions() { + const { openAddToPlaylist, openAddArtistToPlaylist } = useAddToPlaylist() + const { favoriteSongs, toggleArtistFavorite } = useFavorites() + const { runQueueAction, createStation } = useQueueMediaActions() + const convex = useConvex() + const cacheScope = useCacheScope() + + const runSongsAction = React.useCallback( + ( + action: MediaContextAction, + songIds: Id<"songs">[], + stationArtist?: string + ) => { + switch (action) { + case "create-station": + if (stationArtist) void createStation(stationArtist) + break + case "favorite": + void favoriteSongs(songIds) + break + case "playlist": + openAddToPlaylist(songIds) + break + case "play-next": + case "play-last": + case "shuffle": + void runQueueAction(action, songIds) + break + } + }, + [createStation, favoriteSongs, openAddToPlaylist, runQueueAction] + ) + + const runArtistAction = React.useCallback( + async (action: MediaContextAction, artistId: string) => { + switch (action) { + case "favorite": + void toggleArtistFavorite(artistId as Id<"artists">) + break + case "playlist": + void openAddArtistToPlaylist(artistId as Id<"artists">) + break + case "play-next": + case "play-last": + case "shuffle": { + const songIds = await fetchCachedQuery( + convex, + cacheScope, + api.playlists.getOrderedArtistSongIds, + { artistId: artistId as Id<"artists"> } + ) + void runQueueAction(action, songIds) + break + } + } + }, + [convex, cacheScope, toggleArtistFavorite, openAddArtistToPlaylist, runQueueAction] + ) + + return { runSongsAction, runArtistAction } +} + +/** + * Handles a track row menu action, targeting the current selection or else the + * row's song. The station artist is `artistId` when given, otherwise the artist + * every targeted song in `songs` shares. + */ +export function useTrackListMediaAction({ + selectedIds, + songs, + artistId, +}: { + selectedIds: ReadonlySet + songs?: { id: string; artist: { id: string } }[] + artistId?: string +}) { + const { runSongsAction } = useMediaActions() + + return React.useCallback( + (action: MediaContextAction, songId: string) => { + const targetIds = selectedIds.size > 0 ? Array.from(selectedIds) : [songId] + const stationArtist = + artistId ?? + (songs ? stationArtistId(songs, new Set(targetIds)) : undefined) + runSongsAction(action, targetIds as Id<"songs">[], stationArtist) + }, + [selectedIds, songs, artistId, runSongsAction] + ) +} diff --git a/apps/web/lib/selection-range-styles.tsx b/apps/web/lib/selection-range-styles.tsx index 5f534a4..0c575fa 100644 --- a/apps/web/lib/selection-range-styles.tsx +++ b/apps/web/lib/selection-range-styles.tsx @@ -46,7 +46,7 @@ export function getSelectionRangePositions( return positions } -function selectionHighlightRadiusClass( +export function selectionHighlightRadiusClass( position: SelectionRangePosition ) { switch (position) { @@ -61,12 +61,21 @@ function selectionHighlightRadiusClass( } } -const TRACK_ROW_HIGHLIGHT_INSET = "absolute inset-y-0 left-2 right-2" +export const TRACK_ROW_HIGHLIGHT_INSET = "absolute inset-y-0 left-2 right-2" +/** Full-width, square-corner highlight used by the library and queue lists. */ +export const FLUSH_ROW_HIGHLIGHT_INSET = "absolute inset-0" + +/** + * Track row highlights are inset rounded pills by default; `flush` makes them + * full-width with square corners. + */ export function SelectionRangeHighlight({ position, + flush = false, }: { position: SelectionRangePosition + flush?: boolean }) { if (position === "none") { return null @@ -77,34 +86,34 @@ export function SelectionRangeHighlight({ aria-hidden className={cn( "pointer-events-none bg-primary", - TRACK_ROW_HIGHLIGHT_INSET, - selectionHighlightRadiusClass(position) + flush + ? FLUSH_ROW_HIGHLIGHT_INSET + : [TRACK_ROW_HIGHLIGHT_INSET, selectionHighlightRadiusClass(position)] )} /> ) } -/** Inset rounded hover background matching the selection pill shape. */ -export function TrackRowHoverHighlight() { +export function TrackRowHoverHighlight({ flush = false }: { flush?: boolean }) { return (
      ) } -/** Inset rounded background for the active (now playing) row. */ -export function TrackRowActiveHighlight() { +/** Background for the active (focused or now playing) row. */ +export function TrackRowActiveHighlight({ flush = false }: { flush?: boolean }) { return (
      ) @@ -116,42 +125,6 @@ export const TRACK_ROW_PADDING = "pl-8 pr-10" /** Centers the track list in the main content area. */ export const TRACK_LIST_CONTAINER = "mx-auto w-full max-w-9/10" -/** Full-width highlight for library song rows (no horizontal inset). */ -const SONGS_ROW_HIGHLIGHT_INSET = "absolute inset-0" - -export function SongsSelectionRangeHighlight({ - position, -}: { - position: SelectionRangePosition -}) { - if (position === "none") { - return null - } - - return ( -
      - ) -} - -/** Full-width hover background for library song rows (not rounded). */ -export function SongsTrackRowHoverHighlight() { - return ( -
      - ) -} - /** Album track row: star, track #, title (flex), duration, menu. */ export const ALBUM_TRACK_ROW = "flex w-full min-w-0 items-center gap-x-3" @@ -160,50 +133,3 @@ export const ALBUM_TRACK_TITLE = "min-w-0 flex-1 truncate font-normal" export function isInSelectionRange(position: SelectionRangePosition) { return position !== "none" } - -/** Full-width, square-corner highlights for the queue sidebar. */ -const QUEUE_ROW_HIGHLIGHT_INSET = "absolute inset-0" - -export function QueueSelectionRangeHighlight({ - position, -}: { - position: SelectionRangePosition -}) { - if (position === "none") { - return null - } - - return ( -
      - ) -} - -export function QueueTrackRowHoverHighlight() { - return ( -
      - ) -} - -export function QueueTrackRowActiveHighlight() { - return ( -
      - ) -} From 36a01531d0ae159aae13fd382e5769431178fdc2 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 21:51:39 -0500 Subject: [PATCH 08/11] perf(web): virtualize song lists and add row right-click menus (#97) --- apps/web/components/album-card.tsx | 4 +- apps/web/components/album-view.tsx | 11 +- apps/web/components/artist-view.tsx | 4 +- apps/web/components/artists-view.tsx | 64 ++++---- apps/web/components/media-context-menu.tsx | 155 +++++++++++++----- apps/web/components/playback-provider.tsx | 94 ++++++++--- apps/web/components/player-bar.tsx | 61 ++++--- apps/web/components/playlist-card.tsx | 4 +- apps/web/components/playlist-view.tsx | 99 ++++++----- apps/web/components/search-song-item.tsx | 91 +++++----- apps/web/components/songs-view.tsx | 49 +++--- .../components/track-number-play-button.tsx | 103 +++++++----- apps/web/components/track-row.tsx | 97 ++++++----- apps/web/components/virtual-list.tsx | 120 ++++++++++++++ apps/web/hooks/use-cached-query.ts | 23 ++- apps/web/hooks/use-queue-media-actions.ts | 4 +- apps/web/hooks/use-stable-callback.ts | 19 +++ apps/web/package.json | 1 + pnpm-lock.yaml | 20 +++ 19 files changed, 696 insertions(+), 327 deletions(-) create mode 100644 apps/web/components/virtual-list.tsx create mode 100644 apps/web/hooks/use-stable-callback.ts diff --git a/apps/web/components/album-card.tsx b/apps/web/components/album-card.tsx index b17a7a6..076ac12 100644 --- a/apps/web/components/album-card.tsx +++ b/apps/web/components/album-card.tsx @@ -13,7 +13,7 @@ import { MediaContextMenuItems, type MediaContextAction, } from "@/components/media-context-menu" -import { usePlayback } from "@/components/playback-provider" +import { usePlaybackActions } from "@/components/playback-provider" import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" import { api } from "@otunes/convex/_generated/api" import { Button } from "@/components/ui/button" @@ -48,7 +48,7 @@ export function AlbumCard({ album }: { album: BrowseAlbum }) { const cacheScope = useCacheScope() const { openAddAlbumToPlaylist } = useAddToPlaylist() const { isAlbumFavorite, toggleAlbumFavorite } = useFavorites() - const { playAlbum } = usePlayback() + const { playAlbum } = usePlaybackActions() const { runQueueAction, createStation } = useQueueMediaActions() const [menuOpen, setMenuOpen] = React.useState(false) const [hovered, setHovered] = React.useState(false) diff --git a/apps/web/components/album-view.tsx b/apps/web/components/album-view.tsx index 5fc401c..e18b273 100644 --- a/apps/web/components/album-view.tsx +++ b/apps/web/components/album-view.tsx @@ -11,7 +11,10 @@ import { MediaCollectionFooter } from "@/components/media-collection-footer" import { FavoriteMediaButton } from "@/components/favorite-media-button" import { useFavorites } from "@/components/favorites-provider" -import { usePlayback } from "@/components/playback-provider" +import { + useCurrentSongId, + usePlaybackActions, +} from "@/components/playback-provider" import { copyAlbumLink } from "@/lib/media-links" import { @@ -105,8 +108,8 @@ export function AlbumView({ toggleSongFavorite, toggleAlbumFavorite, } = useFavorites() - const { currentSong, playFromSong, playAlbum, playAlbumShuffled } = - usePlayback() + const currentSongId = useCurrentSongId() + const { playFromSong, playAlbum, playAlbumShuffled } = usePlaybackActions() const { runSongsAction } = useMediaActions() const albumSongIds = React.useMemo( () => album.tracks.map((track) => track.id as Id<"songs">), @@ -366,7 +369,7 @@ export function AlbumView({ isFavorite={isSongFavorite(track.id)} selectedCount={selectedCount} selectionStationArtistId={album.artist.id} - isNowPlaying={currentSong?.id === track.id} + isNowPlaying={currentSongId === track.id} onPointerDown={handlePointerDown} onSelect={handleRowSelect} onPlay={handleRowPlay} diff --git a/apps/web/components/artist-view.tsx b/apps/web/components/artist-view.tsx index 5bab21e..5ab9e1e 100644 --- a/apps/web/components/artist-view.tsx +++ b/apps/web/components/artist-view.tsx @@ -6,7 +6,7 @@ import Image from "next/image" import { Play, Shuffle } from "lucide-react" import { useFavorites } from "@/components/favorites-provider" -import { usePlayback } from "@/components/playback-provider" +import { usePlaybackActions } from "@/components/playback-provider" import { useMediaActions } from "@/hooks/use-media-actions" import { AlbumCard } from "@/components/album-card" import { FavoriteMediaButton } from "@/components/favorite-media-button" @@ -26,7 +26,7 @@ export function ArtistView({ albums: BrowseAlbum[] }) { const { isArtistFavorite, toggleArtistFavorite } = useFavorites() - const { playArtist, playArtistShuffled } = usePlayback() + const { playArtist, playArtistShuffled } = usePlaybackActions() const { runArtistAction } = useMediaActions() return ( diff --git a/apps/web/components/artists-view.tsx b/apps/web/components/artists-view.tsx index 48b3d8a..f10b361 100644 --- a/apps/web/components/artists-view.tsx +++ b/apps/web/components/artists-view.tsx @@ -11,8 +11,10 @@ import { useFavorites } from "@/components/favorites-provider" import { MediaContextMenu, type MediaContextAction, + MediaContextMenuArea, + type MediaContextMenuProps, } from "@/components/media-context-menu" -import { usePlayback } from "@/components/playback-provider" +import { usePlaybackActions } from "@/components/playback-provider" import { useMediaActions } from "@/hooks/use-media-actions" import { Button } from "@/components/ui/button" import { ScrollArea } from "@/components/ui/scroll-area" @@ -50,36 +52,42 @@ function ArtistListItem({ onSelect: () => void onMediaAction: (action: MediaContextAction) => void }) { + const menu: MediaContextMenuProps = { + label: `More options for ${artist.name}`, + selectedCount: albumCount, + inSelectionRange: isSelected, + onOpenMenu: () => {}, + onAction: onMediaAction, + favorited: isFavorite, + share: { type: "artist", artistId: artist.id }, + } + return ( -
      - - {}} - onAction={onMediaAction} - favorited={isFavorite} - share={{ type: "artist", artistId: artist.id }} - /> -
      + + +
      + ) } @@ -106,7 +114,7 @@ export function ArtistsView({ return sortedArtists[0]?.id ?? "" }, [artistId, sortedArtists]) const { isArtistFavorite, toggleArtistFavorite } = useFavorites() - const { playArtist, playArtistShuffled } = usePlayback() + const { playArtist, playArtistShuffled } = usePlaybackActions() const { runArtistAction } = useMediaActions() const selectedArtist = sortedArtists.find( diff --git a/apps/web/components/media-context-menu.tsx b/apps/web/components/media-context-menu.tsx index d216401..032dac0 100644 --- a/apps/web/components/media-context-menu.tsx +++ b/apps/web/components/media-context-menu.tsx @@ -15,6 +15,13 @@ import { } from "lucide-react" import { Button } from "@/components/ui/button" +import { + ContextMenu, + ContextMenuContent, + ContextMenuItem, + ContextMenuSeparator, + ContextMenuTrigger, +} from "@/components/ui/context-menu" import { DropdownMenu, DropdownMenuContent, @@ -53,6 +60,28 @@ function shouldShowShare( return true } +// Lets the same items render inside a dropdown or a right-click menu. +const MenuKindContext = React.createContext<"dropdown" | "context">("dropdown") + +/** Menu item that works in both `MediaContextMenu` and `MediaContextMenuArea`. */ +export function MediaMenuItem( + props: React.ComponentProps +) { + return React.use(MenuKindContext) === "context" ? ( + + ) : ( + + ) +} + +export function MediaMenuSeparator() { + return React.use(MenuKindContext) === "context" ? ( + + ) : ( + + ) +} + function actionLabel(base: string, selectedCount: number) { return selectedCount > 1 ? `${base} (${selectedCount})` : base } @@ -83,86 +112,86 @@ export function MediaContextMenuItems({ <> {showShare ? ( <> - void copyMediaShareLink(share!)} > Share - - + + ) : null} - onAction("playlist")} > {actionLabel(playlistLabel, selectedCount)} - - - + + onAction("play-next")} > {actionLabel("Play Next", selectedCount)} - - + onAction("play-last")} > {actionLabel("Play Last", selectedCount)} - - + onAction("shuffle")} > {actionLabel("Shuffle", selectedCount)} - + {stationArtistId ? ( - onAction("create-station")} > Create Station - + ) : null} {artist || album ? ( <> - + {artist ? ( - + Go to Artist - + ) : null} {album ? ( - + Go to Album - + ) : null} ) : null} {showFavorite ? ( <> - - + onAction("favorite")} > {actionLabel(favorited ? "Unfavorite" : "Favorite", selectedCount)} - + ) : null} @@ -194,6 +223,67 @@ export function mediaContextMenuTriggerClassName({ ) } +export type MediaContextMenuProps = { + label: string + selectedCount: number + onOpenMenu: () => void + onAction: (action: MediaContextAction) => void + playlistLabel?: string + showFavorite?: boolean + favorited?: boolean + stationArtistId?: string + navigation?: MediaContextNavigation + share?: MediaShareContext + inSelectionRange?: boolean + /** When false, the trigger uses default button/dropdown styling (page headers). */ + trackRowTrigger?: boolean + triggerClassName?: string + triggerVariant?: "ghost" | "secondary" + triggerIconClassName?: string + align?: "start" | "end" + /** Extra items; use `MediaMenuItem` so they also work in the right-click menu. */ + children?: React.ReactNode +} + +/** + * Opens `menu` (the props given to the row's `MediaContextMenu`) when + * `children`, a single element such as a track row, is right-clicked. + */ +export function MediaContextMenuArea({ + menu, + children, +}: { + menu: MediaContextMenuProps + children: React.ReactElement +}) { + return ( + { + if (open) { + menu.onOpenMenu() + } + }} + > + {children} + + + + {menu.children} + + + + ) +} + export function MediaContextMenu({ label, selectedCount, @@ -212,26 +302,7 @@ export function MediaContextMenu({ triggerIconClassName = "size-4", align = "end", children, -}: { - label: string - selectedCount: number - onOpenMenu: () => void - onAction: (action: MediaContextAction) => void - playlistLabel?: string - showFavorite?: boolean - favorited?: boolean - stationArtistId?: string - navigation?: MediaContextNavigation - share?: MediaShareContext - inSelectionRange?: boolean - /** When false, the trigger uses default button/dropdown styling (page headers). */ - trackRowTrigger?: boolean - triggerClassName?: string - triggerVariant?: "ghost" | "secondary" - triggerIconClassName?: string - align?: "start" | "end" - children?: React.ReactNode -}) { +}: MediaContextMenuProps) { return ( { diff --git a/apps/web/components/playback-provider.tsx b/apps/web/components/playback-provider.tsx index 99471b7..79f9446 100644 --- a/apps/web/components/playback-provider.tsx +++ b/apps/web/components/playback-provider.tsx @@ -102,7 +102,26 @@ type PlaybackContextValue = { dolbyAtmosSupported: boolean | null } +type PlaybackActions = Omit< + PlaybackContextValue, + | "queueSongIds" + | "queueHistorySongIds" + | "currentFormat" + | "currentSong" + | "shuffleEnabled" + | "repeatEnabled" + | "queueOpen" + | "isPlaying" + | "volume" + | "dolbyAtmosSupported" +> + const PlaybackContext = createContext(null) +// Long lists read these narrow contexts so playback state changes do not +// re-render every row. +const PlaybackActionsContext = createContext(null) +const CurrentSongIdContext = createContext | null>(null) +const IsPlayingContext = createContext(false) const PlaybackProgressContext = createContext<{ currentTime: number duration: number @@ -301,6 +320,22 @@ export function usePlayback() { return context } +export function usePlaybackActions() { + const context = useContext(PlaybackActionsContext) + if (!context) { + throw new Error("usePlaybackActions must be used within PlaybackProvider") + } + return context +} + +export function useCurrentSongId() { + return useContext(CurrentSongIdContext) +} + +export function useIsPlaying() { + return useContext(IsPlayingContext) +} + export function usePlaybackProgress() { const context = useContext(PlaybackProgressContext) if (!context) { @@ -1361,17 +1396,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { ) : null - const value = useMemo( + const actions = useMemo( () => ({ - queueSongIds: playback.queue, - queueHistorySongIds: playback.history, - currentSong, - currentFormat, - shuffleEnabled: playback.shuffleEnabled, - repeatEnabled: playback.repeatEnabled, - queueOpen, - isPlaying: isPlaybackActive, - volume, setQueueOpen, toggleQueueOpen, setIsPlaying, @@ -1395,15 +1421,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { skipToQueueIndex, skipNext, skipPrevious, - dolbyAtmosSupported, }), [ - playback, - currentSong, - currentFormat, - queueOpen, - isPlaybackActive, - volume, toggleQueueOpen, setVolume, playInOrder, @@ -1425,6 +1444,31 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { skipToQueueIndex, skipNext, skipPrevious, + ] + ) + + const value = useMemo( + () => ({ + ...actions, + queueSongIds: playback.queue, + queueHistorySongIds: playback.history, + currentSong, + currentFormat, + shuffleEnabled: playback.shuffleEnabled, + repeatEnabled: playback.repeatEnabled, + queueOpen, + isPlaying: isPlaybackActive, + volume, + dolbyAtmosSupported, + }), + [ + actions, + playback, + currentSong, + currentFormat, + queueOpen, + isPlaybackActive, + volume, dolbyAtmosSupported, ] ) @@ -1435,10 +1479,16 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { ) return ( - - - {children} - - + + + + + + {children} + + + + + ) } diff --git a/apps/web/components/player-bar.tsx b/apps/web/components/player-bar.tsx index 82b7def..720f459 100644 --- a/apps/web/components/player-bar.tsx +++ b/apps/web/components/player-bar.tsx @@ -33,6 +33,39 @@ import { albumCoverUrl } from "@/lib/cover-urls" import { cn } from "@/lib/utils" import { formatDuration } from "@/lib/format-duration" +function PlayerSeekBar({ hasActiveSong }: { hasActiveSong: boolean }) { + const { currentTime, duration, seekTo } = usePlaybackProgress() + const [isSeeking, setIsSeeking] = React.useState(false) + const [seekValue, setSeekValue] = React.useState(0) + + const displayTime = hasActiveSong ? (isSeeking ? seekValue : currentTime) : 0 + const maxDuration = Math.max(duration, 1) + + return ( + { + setIsSeeking(true) + setSeekValue(value) + }} + onValueCommit={([value]) => { + seekTo(value) + setIsSeeking(false) + }} + aria-label="Seek" + aria-valuetext={`${formatDuration(displayTime)} of ${formatDuration(duration)}`} + /> + ) +} + export function PlayerBar() { const { currentSong, @@ -51,16 +84,10 @@ export function PlayerBar() { skipNext, skipPrevious, } = usePlayback() - const { currentTime, duration, seekTo } = usePlaybackProgress() const { state, isMobile } = useSidebar() - const [isSeeking, setIsSeeking] = React.useState(false) - const [seekValue, setSeekValue] = React.useState(0) const hasQueue = queueSongIds.length > 0 - const hasActiveSong = Boolean(currentSong) const sidebarExpanded = !isMobile && state === "expanded" - const displayTime = hasActiveSong ? (isSeeking ? seekValue : currentTime) : 0 - const maxDuration = Math.max(duration, 1) return (
      )}
      - { - setIsSeeking(true) - setSeekValue(value) - }} - onValueCommit={([value]) => { - seekTo(value) - setIsSeeking(false) - }} - aria-label="Seek" - aria-valuetext={`${formatDuration(displayTime)} of ${formatDuration(duration)}`} - /> +
      diff --git a/apps/web/components/playlist-card.tsx b/apps/web/components/playlist-card.tsx index 8f94976..2e796df 100644 --- a/apps/web/components/playlist-card.tsx +++ b/apps/web/components/playlist-card.tsx @@ -15,7 +15,7 @@ import { MediaContextMenuItems, type MediaContextAction, } from "@/components/media-context-menu" -import { usePlayback } from "@/components/playback-provider" +import { usePlaybackActions } from "@/components/playback-provider" import { Button } from "@/components/ui/button" import { DropdownMenu, @@ -30,7 +30,7 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) { const convex = useConvex() const cacheScope = useCacheScope() const { openAddPlaylistToPlaylist } = useAddToPlaylist() - const { playPlaylist } = usePlayback() + const { playPlaylist } = usePlaybackActions() const { runQueueAction } = useQueueMediaActions() async function handleCardAction(action: MediaContextAction) { diff --git a/apps/web/components/playlist-view.tsx b/apps/web/components/playlist-view.tsx index 6dd6eaa..6889fd3 100644 --- a/apps/web/components/playlist-view.tsx +++ b/apps/web/components/playlist-view.tsx @@ -10,13 +10,17 @@ import { Play, SearchIcon, Share2, Shuffle, Star, Trash2 } from "lucide-react" import { toast } from "sonner" import { useFavorites } from "@/components/favorites-provider" -import { usePlayback } from "@/components/playback-provider" +import { + useCurrentSongId, + usePlaybackActions, +} from "@/components/playback-provider" import { MediaCollectionFooter } from "@/components/media-collection-footer" import { MediaContextMenu, type MediaContextAction, } from "@/components/media-context-menu" import { TrackRow } from "@/components/track-row" +import { VirtualList } from "@/components/virtual-list" import { Button } from "@/components/ui/button" import { DropdownMenuItem, @@ -39,6 +43,7 @@ import { rememberSongs } from "@/lib/song-cache" import { getSelectionRangePositions } from "@/lib/selection-range-styles" const ADD_TO_ANOTHER_PLAYLIST = "Add to Another Playlist" +const estimatePlaylistRowSize = () => 60 export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { const router = useRouter() @@ -50,14 +55,14 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { : currentUser?._id === playlist.owner.id const { isSongFavorite, toggleSongFavorite, toggleSongsFavorite } = useFavorites() + const currentSongId = useCurrentSongId() const { - currentSong, playInOrder, playShuffled, playPlaylist, playPlaylistShuffled, playFromSong, - } = usePlayback() + } = usePlaybackActions() const { runSongsAction } = useMediaActions() const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist) const reorderSongs = useMutation(api.playlists.reorderPlaylistSongs) @@ -186,10 +191,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { : [songId] if (isFavorites) { - const succeeded = await toggleSongsFavorite( - ids as Id<"songs">[], - true - ) + const succeeded = await toggleSongsFavorite(ids as Id<"songs">[], true) if (!succeeded) return return } @@ -202,7 +204,9 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { setPlaylistSongs((current) => current.filter((song) => !ids.includes(song.id)) ) - toast.success(ids.length > 1 ? `Removed ${ids.length} songs` : "Removed song") + toast.success( + ids.length > 1 ? `Removed ${ids.length} songs` : "Removed song" + ) } catch (error) { toast.error( error instanceof Error ? error.message : "Failed to remove song" @@ -291,7 +295,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
      -
      +
      {isFavorites ? ( @@ -421,40 +425,49 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
      {filteredSongs.length > 0 ? ( - filteredSongs.map((song, index) => ( - - )) + filteredSongs[index].id} + // Keep the drag source mounted so its drop still lands. + keepMounted={dragIndex} + renderItem={(index) => { + const song = filteredSongs[index] + return ( + + ) + }} + /> ) : (

      {normalizedQuery diff --git a/apps/web/components/search-song-item.tsx b/apps/web/components/search-song-item.tsx index 136d8ee..b4bfe05 100644 --- a/apps/web/components/search-song-item.tsx +++ b/apps/web/components/search-song-item.tsx @@ -8,6 +8,8 @@ import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" import { MediaContextMenu, type MediaContextAction, + MediaContextMenuArea, + type MediaContextMenuProps, } from "@/components/media-context-menu" import type { Id } from "@otunes/convex/_generated/dataModel" import type { BrowseSong } from "@otunes/convex/types" @@ -38,52 +40,57 @@ export function SearchSongItem({ song }: { song: BrowseSong }) { } } + const menu: MediaContextMenuProps = { + label: `More options for ${song.title}`, + stationArtistId: song.artist.id, + selectedCount: 1, + onOpenMenu: () => {}, + onAction: handleAction, + favorited: isSongFavorite(song.id), + navigation: { + artist: { id: song.artist.id }, + album: { id: song.album.id }, + }, + share: { + type: "song", + albumId: song.album.id, + songId: song.id, + }, + triggerClassName: + "size-8 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100", + triggerVariant: "ghost", + } + return ( -

      - - {song.album.title} - - -
      - -

      {song.title}

      - + +
      -

      {song.artist.name}

      + {song.album.title} -
      - {}} - onAction={handleAction} - favorited={isSongFavorite(song.id)} - navigation={{ - artist: { id: song.artist.id }, - album: { id: song.album.id }, - }} - share={{ - type: "song", - albumId: song.album.id, - songId: song.id, - }} - triggerClassName="size-8 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100" - triggerVariant="ghost" - /> -
      +
      + +

      {song.title}

      + + +

      {song.artist.name}

      + +
      + + +
      + ) } diff --git a/apps/web/components/songs-view.tsx b/apps/web/components/songs-view.tsx index 2bdf0ae..b0404b7 100644 --- a/apps/web/components/songs-view.tsx +++ b/apps/web/components/songs-view.tsx @@ -13,8 +13,9 @@ import { import { ArrowUpDown } from "lucide-react" import { useFavorites } from "@/components/favorites-provider" -import { usePlayback } from "@/components/playback-provider" +import { usePlaybackActions } from "@/components/playback-provider" import { LibraryTrackListHeader, TrackRow } from "@/components/track-row" +import { VirtualList } from "@/components/virtual-list" import { Button } from "@/components/ui/button" import { DropdownMenu, @@ -43,10 +44,11 @@ type SortKey = "title" | "artist" | "album" type SortDirection = "asc" | "desc" const SONGS_PAGE_SIZE = 50 +const estimateSongRowSize = () => 56 export function SongsView() { const { isSongFavorite, toggleSongFavorite } = useFavorites() - const { playFromLibrarySong } = usePlayback() + const { playFromLibrarySong } = usePlaybackActions() const [sortKey, setSortKey] = useState("title") const [sortDirection, setSortDirection] = useState("asc") @@ -127,6 +129,7 @@ export function SongsView() { (songId: string) => void toggleSongFavorite(songId as Id<"songs">), [toggleSongFavorite] ) + const getSongKey = useCallback((index: number) => songs[index].id, [songs]) if (status === "LoadingFirstPage" && !isCached) { return ( @@ -197,7 +200,7 @@ export function SongsView() {

      ) : null} - +
      { @@ -207,24 +210,28 @@ export function SongsView() { }} > - {songs.map((song, index) => ( - - ))} + ( + + )} + />
      { + event.stopPropagation() + setIsPlaying(!isPlaying) + }} + > + + {isPlaying ? ( + + ) : ( + + )} + + + {isPlaying ? ( + + ) : ( + + )} + + + ) +} + export function TrackNumberPlayButton({ displayTrack, title, @@ -22,26 +74,7 @@ export function TrackNumberPlayButton({ inRange: boolean onPlay: () => void }) { - const { isPlaying, setIsPlaying } = usePlayback() const showPlay = isActive || isNowPlaying - const isCurrentlyPlaying = isNowPlaying && isPlaying - - const buttonClassName = cn( - "absolute size-8 opacity-0 transition-opacity group-hover:opacity-100", - showPlay && "opacity-100", - inRange - ? "text-primary-foreground hover:bg-white/15 hover:text-primary-foreground" - : "text-primary hover:text-primary" - ) - - const handleClick = (event: MouseEvent) => { - event.stopPropagation() - if (isNowPlaying) { - setIsPlaying(!isPlaying) - return - } - onPlay() - } return (
      {isNowPlaying ? ( - + ) : ( diff --git a/apps/web/components/track-row.tsx b/apps/web/components/track-row.tsx index 6fb653c..9cbb54a 100644 --- a/apps/web/components/track-row.tsx +++ b/apps/web/components/track-row.tsx @@ -7,15 +7,15 @@ import { Music2, Play, Star, Trash2 } from "lucide-react" import { MediaContextMenu, + MediaContextMenuArea, + MediaMenuItem, + MediaMenuSeparator, type MediaContextAction, + type MediaContextMenuProps, } from "@/components/media-context-menu" import { PlaybackSongMeta } from "@/components/playback-song-meta" import { TrackNumberPlayButton } from "@/components/track-number-play-button" import { Button } from "@/components/ui/button" -import { - DropdownMenuItem, - DropdownMenuSeparator, -} from "@/components/ui/dropdown-menu" import { albumCoverUrl } from "@/lib/cover-urls" import { ALBUM_TRACK_ROW, @@ -68,7 +68,7 @@ export type TrackRowProps = { onPlay: (index: number) => void onToggleFavorite?: (songId: string) => void onPrepareContextMenu?: (songId: string) => void - /** Renders the "more options" menu when provided. */ + /** Renders the "more options" and right-click menus when provided. */ onMediaAction?: (action: MediaContextAction, songId: string) => void onRemove?: (songId: string) => void /** Makes the row draggable when provided. */ @@ -304,38 +304,40 @@ function TrackRowComponent({ ) - const menu = onMediaAction ? ( - 0 ? selectedCount : 1} - inSelectionRange={inRange} - onOpenMenu={() => onPrepareContextMenu?.(song.id)} - onAction={(action) => onMediaAction(action, song.id)} - playlistLabel={playlistLabel} - showFavorite={showFavoriteInMenu} - favorited={isFavorite} - navigation={{ - artist: { id: song.artist.id }, - album: { id: song.album.id }, - }} - share={{ type: "song", albumId: song.album.id, songId: song.id }} - > - {removeLabel && onRemove ? ( - <> - - onRemove(song.id)} - > - {removeLabel} - - - - ) : null} - - ) : null + // Shared by the "more options" button and the right-click menu. + const menuProps: MediaContextMenuProps | null = onMediaAction + ? { + label: `More options for ${song.title}`, + stationArtistId: inRange ? selectionStationArtistId : song.artist.id, + selectedCount: inRange && selectedCount > 0 ? selectedCount : 1, + inSelectionRange: inRange, + onOpenMenu: () => onPrepareContextMenu?.(song.id), + onAction: (action) => onMediaAction(action, song.id), + playlistLabel, + showFavorite: showFavoriteInMenu, + favorited: isFavorite, + navigation: { + artist: { id: song.artist.id }, + album: { id: song.album.id }, + }, + share: { type: "song", albumId: song.album.id, songId: song.id }, + children: + removeLabel && onRemove ? ( + <> + + onRemove(song.id)} + > + {removeLabel} + + + + ) : null, + } + : null + const menu = menuProps ? : null let content: React.ReactNode switch (variant) { @@ -491,14 +493,21 @@ function TrackRowComponent({ ) - return variant === "queue" ? ( -
    • } {...shellProps}> - {children} -
    • + const shell = + variant === "queue" ? ( +
    • } {...shellProps}> + {children} +
    • + ) : ( +
      } {...shellProps}> + {children} +
      + ) + + return menuProps ? ( + {shell} ) : ( -
      } {...shellProps}> - {children} -
      + shell ) } diff --git a/apps/web/components/virtual-list.tsx b/apps/web/components/virtual-list.tsx new file mode 100644 index 0000000..66f0e63 --- /dev/null +++ b/apps/web/components/virtual-list.tsx @@ -0,0 +1,120 @@ +"use client" + +import * as React from "react" +import { + defaultRangeExtractor, + useVirtualizer, + type Range, +} from "@tanstack/react-virtual" + +import { cn } from "@/lib/utils" + +const scrollViewportSelector = '[data-slot="scroll-area-viewport"]' + +/** + * Renders only the visible items of a list placed inside a `ScrollArea`. + * The list may sit below other content in the same viewport. + */ +export function VirtualList({ + count, + estimateSize, + getItemKey, + renderItem, + overscan = 10, + keepMounted = null, + className, +}: { + count: number + estimateSize: (index: number) => number + getItemKey: (index: number) => string + renderItem: (index: number) => React.ReactNode + overscan?: number + /** Index rendered even when off screen, e.g. the source of a drag. */ + keepMounted?: number | null + className?: string +}) { + const listRef = React.useRef(null) + const [scrollMargin, setScrollMargin] = React.useState(0) + + React.useLayoutEffect(() => { + const list = listRef.current + const viewport = list?.closest(scrollViewportSelector) + if (!list || !viewport) return + + const measure = () => { + setScrollMargin( + Math.round( + list.getBoundingClientRect().top - + viewport.getBoundingClientRect().top + + viewport.scrollTop + ) + ) + } + const observer = new ResizeObserver(measure) + observer.observe(viewport) + if (viewport.firstElementChild) { + observer.observe(viewport.firstElementChild) + } + return () => observer.disconnect() + }, []) + + const getScrollElement = () => + listRef.current?.closest(scrollViewportSelector) ?? null + + const virtualizer = useVirtualizer({ + count, + getScrollElement, + // The virtualizer scrolls to this offset on attach. Keep the viewport's + // current position so `ScrollRestoration` is not reset to the top. + initialOffset: () => getScrollElement()?.scrollTop ?? 0, + estimateSize, + getItemKey, + overscan, + scrollMargin, + rangeExtractor: React.useCallback( + (range: Range) => { + const indexes = defaultRangeExtractor(range) + if ( + keepMounted !== null && + keepMounted < range.count && + !indexes.includes(keepMounted) + ) { + indexes.push(keepMounted) + indexes.sort((a, b) => a - b) + } + return indexes + }, + [keepMounted] + ), + }) + + // The virtualizer caches its offset across a detach. Clear it so a + // re-attach (e.g. StrictMode's effect replay) re-reads `initialOffset` + // instead of scrolling back to a stale position. + React.useLayoutEffect( + () => () => { + virtualizer.scrollOffset = null + }, + [virtualizer] + ) + + return ( +
      + {virtualizer.getVirtualItems().map((item) => ( +
      + {renderItem(item.index)} +
      + ))} +
      + ) +} diff --git a/apps/web/hooks/use-cached-query.ts b/apps/web/hooks/use-cached-query.ts index 87da8ff..98950ca 100644 --- a/apps/web/hooks/use-cached-query.ts +++ b/apps/web/hooks/use-cached-query.ts @@ -9,13 +9,18 @@ import { type PaginatedQueryReference, } from "convex/react" import type { FunctionReference } from "convex/server" -import { useCallback, useEffect, useSyncExternalStore } from "react" +import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react" import { useCacheScope } from "@/components/persistent-cache-provider" import { queryCacheKey } from "@otunes/convex/client/cached-query" import { readCache, subscribeCache, writeCache } from "@/lib/persistent-cache" const MAX_CACHED_PAGINATED_ITEMS = 200 +const MAX_RESTORED_PAGINATED_ITEMS = 1000 + +// Items loaded per paginated query this session, so a remount (e.g. back +// navigation) loads as much as before and scroll restoration can reach it. +const loadedItemCounts = new Map() const noopUnsubscribe = () => {} @@ -65,6 +70,7 @@ export function useCachedQuery>( /** * `usePaginatedQuery` that shows the first persisted pages while the first live * page loads. `isCached` is true while those persisted results are shown. + * Remounts start with as many items as were last loaded this session. */ export function useCachedPaginatedQuery( query: Query, @@ -72,15 +78,28 @@ export function useCachedPaginatedQuery( options: { initialNumItems: number } ) { const scope = useCacheScope() - const result = usePaginatedQuery(query, args, options) const key = args === "skip" ? null : `${queryCacheKey(scope, query, args as Record)}:pages` + // Fixed per key: `usePaginatedQuery` restarts when this changes. + const initialNumItems = useMemo( + () => + Math.max( + options.initialNumItems, + Math.min( + (key && loadedItemCounts.get(key)) || 0, + MAX_RESTORED_PAGINATED_ITEMS + ) + ), + [key, options.initialNumItems] + ) + const result = usePaginatedQuery(query, args, { initialNumItems }) const cached = useCachedValue[]>(key) useEffect(() => { if (key && result.status !== "LoadingFirstPage") { + loadedItemCounts.set(key, result.results.length) writeCache(key, result.results.slice(0, MAX_CACHED_PAGINATED_ITEMS)) } }, [key, result.status, result.results]) diff --git a/apps/web/hooks/use-queue-media-actions.ts b/apps/web/hooks/use-queue-media-actions.ts index 2837a81..b69d9f8 100644 --- a/apps/web/hooks/use-queue-media-actions.ts +++ b/apps/web/hooks/use-queue-media-actions.ts @@ -3,7 +3,7 @@ import * as React from "react" import { toast } from "sonner" -import { usePlayback } from "@/components/playback-provider" +import { usePlaybackActions } from "@/components/playback-provider" import type { MediaContextAction } from "@/components/media-context-menu" import type { Id } from "@otunes/convex/_generated/dataModel" @@ -29,7 +29,7 @@ function queueActionMessage(action: QueueMediaAction, count: number) { export function useQueueMediaActions() { const { addToQueueNext, addToQueueLast, playShuffled, playArtistShuffled } = - usePlayback() + usePlaybackActions() const runQueueAction = React.useCallback( async (action: QueueMediaAction, songIds: Id<"songs">[]) => { diff --git a/apps/web/hooks/use-stable-callback.ts b/apps/web/hooks/use-stable-callback.ts new file mode 100644 index 0000000..e216f3d --- /dev/null +++ b/apps/web/hooks/use-stable-callback.ts @@ -0,0 +1,19 @@ +"use client" + +import * as React from "react" + +/** + * Returns a function with a stable identity that always calls the latest + * `callback`. Only call it from event handlers, never during render. + */ +export function useStableCallback( + callback: (...args: Args) => Result +): (...args: Args) => Result { + const callbackRef = React.useRef(callback) + + React.useLayoutEffect(() => { + callbackRef.current = callback + }) + + return React.useCallback((...args: Args) => callbackRef.current(...args), []) +} diff --git a/apps/web/package.json b/apps/web/package.json index 1c7cd4a..f943371 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -14,6 +14,7 @@ "@base-ui/react": "^1.5.0", "@convex-dev/auth": "^0.0.93", "@otunes/convex": "workspace:*", + "@tanstack/react-virtual": "^3.14.26", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "cmdk": "^1.1.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4631b7d..5866a70 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -179,6 +179,9 @@ importers: '@otunes/convex': specifier: workspace:* version: link:../../packages/convex + '@tanstack/react-virtual': + specifier: ^3.14.26 + version: 3.14.26(react-dom@19.3.1(react@19.3.1))(react@19.3.1) class-variance-authority: specifier: ^0.7.1 version: 0.7.1 @@ -2657,6 +2660,15 @@ packages: '@tailwindcss/postcss@4.3.2': resolution: {integrity: sha512-rjVWYCa7Ngbi5AarT6k8TkxUG3Wl1QKzHdIZVsjZSzf36Jmo2IKZt/NHRAwly8oDkbBOH0YTu+CHuf9jPxMc+g==} + '@tanstack/react-virtual@3.14.26': + resolution: {integrity: sha512-HUDlfsrYH6ko5xH56L62Mcl/uzT+AGVNMHFuDNqDJMdZWc1AQa2oeVKNUvZ/RWBZQ4TYtyQerFrNvLnp39h65A==} + peerDependencies: + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + + '@tanstack/virtual-core@3.19.11': + resolution: {integrity: sha512-/5iHb0RHBvj8Di59FDs4ESNm45jls33aZAi4zccVXZjc/6ZvwQP6nzEYeT6weXjTf9E6/vrp2JhYWRyO+ZP13A==} + '@tokenizer/inflate@0.4.1': resolution: {integrity: sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==} engines: {node: '>=18'} @@ -9464,6 +9476,14 @@ snapshots: postcss: 8.5.16 tailwindcss: 4.3.2 + '@tanstack/react-virtual@3.14.26(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@tanstack/virtual-core': 3.19.11 + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + + '@tanstack/virtual-core@3.19.11': {} + '@tokenizer/inflate@0.4.1': dependencies: debug: 4.4.3 From 777713baf70132a35ada15ce4dc9870aef3e576d Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 21:51:43 -0500 Subject: [PATCH 09/11] fix(web): close leaked audio streams and ffmpeg jobs (#98) --- apps/web/app/api/song/[id]/play/route.ts | 21 +- apps/web/lib/server-audio-info.ts | 41 ++++ apps/web/lib/server-audio-stream.ts | 158 ++++++------- apps/web/lib/server-cache.ts | 132 +++++++++++ apps/web/lib/server-ffmpeg.ts | 113 ++++++++++ apps/web/lib/server-hls.ts | 276 +++++++++++++++-------- apps/web/lib/server-lossless.ts | 75 +++--- 7 files changed, 588 insertions(+), 228 deletions(-) create mode 100644 apps/web/lib/server-audio-info.ts create mode 100644 apps/web/lib/server-cache.ts create mode 100644 apps/web/lib/server-ffmpeg.ts diff --git a/apps/web/app/api/song/[id]/play/route.ts b/apps/web/app/api/song/[id]/play/route.ts index 45801dc..0c5e73e 100644 --- a/apps/web/app/api/song/[id]/play/route.ts +++ b/apps/web/app/api/song/[id]/play/route.ts @@ -3,11 +3,11 @@ import type { Id } from "@otunes/convex/_generated/dataModel" import { audioContentTypeForPath } from "@/lib/audio-content-type" import { seekableLosslessFile } from "@/lib/server-lossless" import { getConvexClient } from "@/lib/convex-server" +import { audioInfo } from "@/lib/server-audio-info" import { ffmpegToReadableStream, streamFile } from "@/lib/server-audio-stream" +import { spawnFfmpeg } from "@/lib/server-ffmpeg" import { NextRequest, NextResponse, userAgent } from "next/server" -import { spawn } from "node:child_process" import fs from "node:fs/promises" -import * as music from "music-metadata" function parseByteRange(rangeHeader: string | null, fileSize: number) { if (!rangeHeader) { @@ -151,14 +151,15 @@ export async function GET( transcodeNeeded = false } - const metadata = await music.parseFile(song.files[originalCodec]) - if (!transcodeNeeded && originalCodec === "lossless") { // Native iOS playback does not identify itself as Safari. const acceptsAlac = browser.name === "Safari" || request.nextUrl.searchParams.get("losslessFormat") === "alac" - if (acceptsAlac && metadata.format.codec === "ALAC") { + if ( + acceptsAlac && + (await audioInfo(song.files[originalCodec])).codec === "ALAC" + ) { try { return await streamFileResponse( request, @@ -183,11 +184,6 @@ export async function GET( (originalCodec === "atmos" || originalCodec === "normal") ) { // TODO: Dolby Atmos doesn't work on Google Chrome - console.log( - metadata.format.codec, - metadata.format.container, - metadata.format.codecProfile - ) try { return await streamFileResponse( request, @@ -200,7 +196,6 @@ export async function GET( } const ffmpegArgs = [ - "-nostdin", "-i", song.files[originalCodec], "-c:a", @@ -214,8 +209,8 @@ export async function GET( try { // TODO: Fix seeking for this - const ffmpegProcess = spawn("ffmpeg", ffmpegArgs) - const stream = ffmpegToReadableStream(ffmpegProcess) + const ffmpeg = await spawnFfmpeg(ffmpegArgs, request.signal) + const stream = ffmpegToReadableStream(ffmpeg) return new NextResponse(stream, { status: 200, diff --git a/apps/web/lib/server-audio-info.ts b/apps/web/lib/server-audio-info.ts new file mode 100644 index 0000000..79a71c8 --- /dev/null +++ b/apps/web/lib/server-audio-info.ts @@ -0,0 +1,41 @@ +import fs from "node:fs/promises" +import * as music from "music-metadata" + +const MAX_ENTRIES = 1000 + +export type AudioInfo = { + codec: string | undefined + duration: number | undefined +} + +const cache = new Map>() + +/** Codec info for a file, parsed once per file version. */ +export async function audioInfo(file: string): Promise { + const stat = await fs.stat(file) + const key = `${file}\0${stat.size}\0${stat.mtimeMs}` + + const cached = cache.get(key) + if (cached) { + cache.delete(key) + cache.set(key, cached) + return cached + } + + const info = music.parseFile(file).then(({ format }) => ({ + codec: format.codec, + duration: format.duration, + })) + cache.set(key, info) + info.catch(() => { + if (cache.get(key) === info) { + cache.delete(key) + } + }) + + if (cache.size > MAX_ENTRIES) { + cache.delete(cache.keys().next().value!) + } + + return info +} diff --git a/apps/web/lib/server-audio-stream.ts b/apps/web/lib/server-audio-stream.ts index f1c9d8b..d26b96c 100644 --- a/apps/web/lib/server-audio-stream.ts +++ b/apps/web/lib/server-audio-stream.ts @@ -1,96 +1,96 @@ -import { type ChildProcessWithoutNullStreams } from "node:child_process" -import { createReadStream, ReadStream } from "node:fs" +import { createReadStream } from "node:fs" +import type { Readable } from "node:stream" +import type { FfmpegProcess } from "@/lib/server-ffmpeg" + +const HIGH_WATER_MARK_BYTES = 256 * 1024 export type ByteRange = { start: number end: number } -async function* nodeStreamToIterator(stream: ReadStream) { - for await (const chunk of stream) { - yield new Uint8Array(chunk) - } -} +/** + * Wraps a Node stream, pausing it while the consumer is behind. `cancel` runs + * when the consumer goes away (seek, track change, disconnect). `finish` runs + * when the source ends and may reject to error the stream. + */ +function toWebStream( + source: Readable, + { + cancel, + finish, + }: { cancel: () => void; finish?: () => Promise } +): ReadableStream { + let done = false -// @ts-expect-error trust me bro -function iteratorToStream(iterator) { - return new ReadableStream({ - async pull(controller) { - const { value, done } = await iterator.next() - if (done) { - controller.close() - } else { - controller.enqueue(value) - } - }, - }) -} - -export function streamFile(path: string, range?: ByteRange): ReadableStream { - const nodeStream = createReadStream(path, range) - return iteratorToStream(nodeStreamToIterator(nodeStream)) -} - -export function ffmpegToReadableStream( - ffmpegProcess: ChildProcessWithoutNullStreams -) { - let closed = false - - return new ReadableStream({ - start(controller) { - const finalize = (err?: Error) => { - if (closed) { - return - } - closed = true - - try { - if (err) { - controller.error(err) - } else { - controller.close() + return new ReadableStream( + { + start(controller) { + const fail = (error: unknown) => { + if (done) { + return } - } catch { - // Consumer may have already closed the stream (e.g. track change). + done = true + controller.error(error) + cancel() } - } - ffmpegProcess.stdout.on("data", (chunk: Buffer) => { - if (closed) { + source.on("data", (chunk: Buffer) => { + if (done) { + return + } + controller.enqueue(new Uint8Array(chunk)) + if ((controller.desiredSize ?? 0) <= 0) { + source.pause() + } + }) + source.once("error", fail) + source.once("end", () => { + if (done) { + return + } + void (finish?.() ?? Promise.resolve()).then(() => { + if (!done) { + done = true + controller.close() + } + }, fail) + }) + }, + pull() { + source.resume() + }, + cancel() { + if (done) { return } - - try { - controller.enqueue(new Uint8Array(chunk)) - } catch { - closed = true - ffmpegProcess.kill("SIGKILL") - } - }) - - ffmpegProcess.stderr.on("data", (data) => { - console.error(`FFmpeg log: ${data.toString()}`) - }) - - ffmpegProcess.stdout.on("end", () => finalize()) - ffmpegProcess.stdout.on("error", (err) => finalize(err)) - - ffmpegProcess.on("close", (code) => { - if (code !== 0 && !closed) { - finalize(new Error(`ffmpeg exited with code ${code}`)) - } else { - finalize() - } - }) - - ffmpegProcess.on("error", (err) => finalize(err)) + done = true + cancel() + }, }, - cancel() { - if (closed) { - return + new ByteLengthQueuingStrategy({ highWaterMark: HIGH_WATER_MARK_BYTES }) + ) +} + +export function streamFile(path: string, range?: ByteRange) { + const file = createReadStream(path, range) + return toWebStream(file, { cancel: () => file.destroy() }) +} + +/** Streams ffmpeg stdout and kills ffmpeg when the consumer goes away. */ +export function ffmpegToReadableStream({ + child, + exited, + stderrTail, +}: FfmpegProcess) { + return toWebStream(child.stdout, { + cancel: () => child.kill("SIGKILL"), + finish: async () => { + const code = await exited + if (code !== 0) { + console.error(`ffmpeg transcode exited with code ${code}`, stderrTail()) + throw new Error(`ffmpeg exited with code ${code}`) } - closed = true - ffmpegProcess.kill("SIGKILL") }, }) } diff --git a/apps/web/lib/server-cache.ts b/apps/web/lib/server-cache.ts new file mode 100644 index 0000000..bbc5702 --- /dev/null +++ b/apps/web/lib/server-cache.ts @@ -0,0 +1,132 @@ +import fs from "node:fs/promises" +import os from "node:os" +import path from "node:path" + +const DEFAULT_MAX_MB = 2048 +const ORPHAN_MAX_AGE_MS = 60 * 60 * 1000 +/** Prefix for in-progress entries. Pruning removes old unpinned ones as abandoned. */ +export const CACHE_ORPHAN_PREFIX = "convert-" + +type CacheState = { + pinned: Map + pruning: Promise | null +} + +const globalState = globalThis as typeof globalThis & { + __otunesCache?: CacheState +} +const state = (globalState.__otunesCache ??= { + pinned: new Map(), + pruning: null, +}) + +/** + * Transcode cache root. Set OTUNES_CACHE_DIR to a persistent volume to keep + * transcodes across restarts. + */ +export function cacheRoot() { + return process.env.OTUNES_CACHE_DIR || path.join(os.tmpdir(), "otunes-cache") +} + +export function cacheDir(kind: "hls" | "lossless") { + return path.join(cacheRoot(), kind) +} + +function maxCacheBytes() { + const configured = Number(process.env.OTUNES_CACHE_MAX_MB) + const mb = Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_MAX_MB + return mb * 1024 * 1024 +} + +/** Pinned entries are never pruned. Pins are reference counted. */ +export function pinCacheEntry(entry: string) { + state.pinned.set(entry, (state.pinned.get(entry) ?? 0) + 1) +} + +export function unpinCacheEntry(entry: string) { + const count = state.pinned.get(entry) ?? 0 + if (count <= 1) { + state.pinned.delete(entry) + } else { + state.pinned.set(entry, count - 1) + } +} + +/** Marks an entry as recently used so pruning removes it last. */ +export async function touchCacheEntry(entry: string) { + const now = new Date() + await fs.utimes(entry, now, now) +} + +async function entrySize(entry: string): Promise { + const stat = await fs.stat(entry).catch(() => null) + if (!stat) { + return 0 + } + if (!stat.isDirectory()) { + return stat.size + } + const names = await fs.readdir(entry).catch(() => []) + const sizes = await Promise.all( + names.map((name) => entrySize(path.join(entry, name))) + ) + return sizes.reduce((total, size) => total + size, 0) +} + +async function prune() { + const entries: { + path: string + size: number + mtimeMs: number + orphan: boolean + }[] = [] + + for (const kind of ["hls", "lossless"] as const) { + const dir = cacheDir(kind) + const names = await fs.readdir(dir).catch(() => []) + for (const name of names) { + const entry = path.join(dir, name) + const stat = await fs.stat(entry).catch(() => null) + if (!stat) { + continue + } + entries.push({ + path: entry, + size: await entrySize(entry), + mtimeMs: stat.mtimeMs, + orphan: name.startsWith(CACHE_ORPHAN_PREFIX), + }) + } + } + + const maxBytes = maxCacheBytes() + const now = Date.now() + let total = entries.reduce((sum, entry) => sum + entry.size, 0) + entries.sort((a, b) => a.mtimeMs - b.mtimeMs) + + for (const entry of entries) { + if (state.pinned.has(entry.path)) { + continue + } + const remove = entry.orphan + ? now - entry.mtimeMs > ORPHAN_MAX_AGE_MS + : total > maxBytes + if (remove) { + await fs.rm(entry.path, { recursive: true, force: true }).catch(() => {}) + total -= entry.size + } + } +} + +/** + * Removes least recently used entries until the cache fits under + * OTUNES_CACHE_MAX_MB, plus abandoned in-progress entries. + */ +export function pruneCache() { + state.pruning ??= prune() + .catch((error) => console.error("Transcode cache prune failed", error)) + .finally(() => { + state.pruning = null + }) + return state.pruning +} diff --git a/apps/web/lib/server-ffmpeg.ts b/apps/web/lib/server-ffmpeg.ts new file mode 100644 index 0000000..ac732b7 --- /dev/null +++ b/apps/web/lib/server-ffmpeg.ts @@ -0,0 +1,113 @@ +import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process" +import os from "node:os" + +const STDERR_TAIL_BYTES = 4096 + +export type FfmpegProcess = { + child: ChildProcessWithoutNullStreams + /** Resolves with the exit code, or null when killed by a signal. */ + exited: Promise + stderrTail: () => string +} + +type Limiter = { + running: number + waiting: (() => void)[] +} + +// Kept on globalThis so dev reloads share one limit with processes they spawned. +const globalState = globalThis as typeof globalThis & { + __otunesFfmpegLimiter?: Limiter +} +const limiter = (globalState.__otunesFfmpegLimiter ??= { + running: 0, + waiting: [], +}) + +function maxConcurrentFfmpeg() { + const configured = Number(process.env.OTUNES_MAX_FFMPEG) + if (Number.isInteger(configured) && configured > 0) { + return configured + } + return Math.max(2, os.availableParallelism()) +} + +async function acquireSlot(signal?: AbortSignal) { + signal?.throwIfAborted() + if (limiter.running < maxConcurrentFfmpeg()) { + limiter.running += 1 + return + } + + await new Promise((resolve, reject) => { + const grant = () => { + signal?.removeEventListener("abort", onAbort) + resolve() + } + const onAbort = () => { + const index = limiter.waiting.indexOf(grant) + if (index !== -1) { + limiter.waiting.splice(index, 1) + } + reject(signal?.reason) + } + limiter.waiting.push(grant) + signal?.addEventListener("abort", onAbort, { once: true }) + }) +} + +function releaseSlot() { + const next = limiter.waiting.shift() + if (next) { + // The slot passes straight to the next waiter. + next() + } else { + limiter.running -= 1 + } +} + +/** + * Spawns ffmpeg once a slot under the concurrency cap is free. The slot is + * held until the process exits. Rejects if `signal` aborts while queued. + */ +export async function spawnFfmpeg( + args: string[], + signal?: AbortSignal +): Promise { + await acquireSlot(signal) + + let child: ChildProcessWithoutNullStreams + try { + child = spawn("ffmpeg", [ + "-nostdin", + "-hide_banner", + "-loglevel", + "error", + ...args, + ]) + } catch (error) { + releaseSlot() + throw error + } + + // stderr must be drained or ffmpeg blocks once the pipe buffer fills. + let stderr = "" + child.stderr.on("data", (data: Buffer) => { + stderr = (stderr + data.toString()).slice(-STDERR_TAIL_BYTES) + }) + + const exited = new Promise((resolve) => { + let released = false + const finish = (code: number | null) => { + if (!released) { + released = true + releaseSlot() + } + resolve(code) + } + child.once("error", () => finish(1)) + child.once("close", (code) => finish(code)) + }) + + return { child, exited, stderrTail: () => stderr.trim() } +} diff --git a/apps/web/lib/server-hls.ts b/apps/web/lib/server-hls.ts index df3b876..4e9682d 100644 --- a/apps/web/lib/server-hls.ts +++ b/apps/web/lib/server-hls.ts @@ -2,8 +2,15 @@ import type { Doc } from "@otunes/convex/_generated/dataModel" import crypto from "node:crypto" import fs from "node:fs/promises" import path from "node:path" -import { spawn } from "node:child_process" -import * as music from "music-metadata" +import { audioInfo } from "@/lib/server-audio-info" +import { + cacheDir, + pinCacheEntry, + pruneCache, + touchCacheEntry, + unpinCacheEntry, +} from "@/lib/server-cache" +import { spawnFfmpeg, type FfmpegProcess } from "@/lib/server-ffmpeg" export const HLS_SEGMENT_SECONDS = 6 const HLS_MAX_IDLE_MS = 30 * 60 * 1000 @@ -17,11 +24,28 @@ type HlsJob = { lastTouchedAt: number processExited: boolean processExitCode: number | null + process: FfmpegProcess | null + abort: AbortController + evicted: boolean } -const jobs = new Map() -const jobsByLookup = new Map() -let lastCleanupAt = 0 +type HlsState = { + /** In-flight and ready jobs by cache key, so overlapping requests share one ffmpeg. */ + pending: Map> + jobs: Map + jobsByLookup: Map + lastCleanupAt: number +} + +const globalState = globalThis as typeof globalThis & { + __otunesHls?: HlsState +} +const state = (globalState.__otunesHls ??= { + pending: new Map(), + jobs: new Map(), + jobsByLookup: new Map(), + lastCleanupAt: 0, +}) export function qualityKbps(quality: string | null) { if (quality === "low") { @@ -50,10 +74,6 @@ export function selectHlsSourceCodec( return sourceCodec } -function hlsCacheRoot() { - return "/tmp/otunes" -} - function hlsLookupKey( songId: string, quality: string | null, @@ -88,31 +108,38 @@ export function hlsSegmentPath(job: HlsJob, segmentIndex: number) { async function touchHlsJob(job: HlsJob) { job.lastTouchedAt = Date.now() - await fs.utimes(job.dir, new Date(job.lastTouchedAt), new Date(job.lastTouchedAt)).catch( - () => {} - ) -} - -function forgetJob(job: HlsJob) { - jobs.delete(job.key) - if (jobsByLookup.get(job.lookupKey) === job) { - jobsByLookup.delete(job.lookupKey) - } + await touchCacheEntry(job.dir).catch(() => {}) } async function evictJob(job: HlsJob) { - forgetJob(job) - await fs.rm(job.dir, { recursive: true, force: true }).catch(() => {}) + if (job.evicted) { + return + } + job.evicted = true + state.pending.delete(job.key) + state.jobs.delete(job.key) + if (state.jobsByLookup.get(job.lookupKey) === job) { + state.jobsByLookup.delete(job.lookupKey) + } + + job.abort.abort() + job.process?.child.kill("SIGKILL") + const complete = job.processExited && job.processExitCode === 0 + if (!complete) { + await job.process?.exited + await fs.rm(job.dir, { recursive: true, force: true }).catch(() => {}) + } + unpinCacheEntry(job.dir) } async function cleanupIdleHlsJobs() { const now = Date.now() - if (now - lastCleanupAt < 60_000) { + if (now - state.lastCleanupAt < 60_000) { return } - lastCleanupAt = now + state.lastCleanupAt = now - for (const job of [...jobs.values()]) { + for (const job of [...state.jobs.values()]) { if (now - job.lastTouchedAt > HLS_MAX_IDLE_MS) { await evictJob(job) } @@ -124,7 +151,7 @@ export function getExistingHlsJob( quality: string | null, preferAtmos: boolean ) { - return jobsByLookup.get(hlsLookupKey(songId, quality, preferAtmos)) ?? null + return state.jobsByLookup.get(hlsLookupKey(songId, quality, preferAtmos)) ?? null } export async function waitForHlsSegment( @@ -137,18 +164,22 @@ export async function waitForHlsSegment( const startedAt = Date.now() while (Date.now() - startedAt < timeoutMs) { + // Read before checking the file so a segment renamed just before exit is found. + const exited = job.processExited try { - const firstStat = await fs.stat(segmentPath) - if (firstStat.size > 0) { - await new Promise((resolve) => setTimeout(resolve, 100)) - const secondStat = await fs.stat(segmentPath) - if (firstStat.size === secondStat.size) { - return segmentPath - } - } + // ffmpeg writes to a .tmp file and renames it when complete. + await fs.access(segmentPath) + return segmentPath } catch { - if (job.processExited && job.processExitCode !== 0) { - throw new Error(`HLS transcode failed with code ${job.processExitCode}`) + if (job.evicted) { + throw new Error("HLS job was evicted") + } + if (exited) { + throw new Error( + job.processExitCode === 0 + ? "HLS segment does not exist" + : `HLS transcode failed with code ${job.processExitCode}` + ) } } await new Promise((resolve) => setTimeout(resolve, 100)) @@ -157,52 +188,15 @@ export async function waitForHlsSegment( throw new Error("Timed out waiting for HLS segment") } -export async function ensureHlsJob( - song: Doc<"songs">, - quality: string | null, - preferAtmos: boolean -) { - await cleanupIdleHlsJobs() - - const kbps = qualityKbps(quality) - const sourceCodec = selectHlsSourceCodec(song, quality, preferAtmos) - const sourcePath = song.files[sourceCodec] - const key = await hlsJobKey(song, sourcePath, kbps) - const lookupKey = hlsLookupKey(song._id, quality, preferAtmos) - const existingJob = jobs.get(key) - - if (existingJob) { - try { - await fs.access(existingJob.dir) - await touchHlsJob(existingJob) - return existingJob - } catch { - forgetJob(existingJob) - } - } - - const metadata = await music.parseFile(sourcePath) - const duration = metadata.format.duration ?? song.length - const segmentCount = Math.max(1, Math.ceil(duration / HLS_SEGMENT_SECONDS)) - const dir = path.join(hlsCacheRoot(), key) - await fs.mkdir(dir, { recursive: true }) - - const job: HlsJob = { - key, - lookupKey, - dir, - duration, - segmentCount, - lastTouchedAt: Date.now(), - processExited: false, - processExitCode: null, - } - jobs.set(key, job) - jobsByLookup.set(lookupKey, job) - await touchHlsJob(job) +async function hasCompletePlaylist(dir: string) { + const playlist = await fs + .readFile(path.join(dir, "index.m3u8"), "utf8") + .catch(() => "") + return playlist.includes("#EXT-X-ENDLIST") +} +function startTranscode(job: HlsJob, sourcePath: string, kbps: number) { const ffmpegArgs = [ - "-nostdin", "-i", sourcePath, "-vn", @@ -222,25 +216,121 @@ export async function ensureHlsJob( "0", "-hls_segment_type", "mpegts", + "-hls_flags", + "temp_file", "-hls_segment_filename", - path.join(dir, "segment_%05d.ts"), - path.join(dir, "index.m3u8"), + path.join(job.dir, "segment_%05d.ts"), + path.join(job.dir, "index.m3u8"), ] - const ffmpegProcess = spawn("ffmpeg", ffmpegArgs) - ffmpegProcess.stderr.on("data", (data) => { - console.error(`FFmpeg HLS log: ${data.toString()}`) - }) + spawnFfmpeg(ffmpegArgs, job.abort.signal).then( + async (ffmpeg) => { + job.process = ffmpeg + if (job.evicted) { + ffmpeg.child.kill("SIGKILL") + } + const code = await ffmpeg.exited + job.process = null + job.processExited = true + job.processExitCode = code + if (job.evicted) { + return + } + if (code === 0) { + void pruneCache() + } else { + console.error(`ffmpeg HLS exited with code ${code}`, ffmpeg.stderrTail()) + } + }, + () => { + job.processExited = true + job.processExitCode = 1 + } + ) +} - ffmpegProcess.on("close", (code) => { - job.processExited = true - job.processExitCode = code - }) +async function createHlsJob( + song: Doc<"songs">, + sourcePath: string, + kbps: number, + key: string, + lookupKey: string +): Promise { + const info = await audioInfo(sourcePath) + const duration = info.duration ?? song.length + const segmentCount = Math.max(1, Math.ceil(duration / HLS_SEGMENT_SECONDS)) + const dir = path.join(cacheDir("hls"), key) + pinCacheEntry(dir) - ffmpegProcess.on("error", () => { - job.processExited = true - job.processExitCode = 1 - }) + try { + const complete = await hasCompletePlaylist(dir) + if (!complete) { + await fs.rm(dir, { recursive: true, force: true }) + await fs.mkdir(dir, { recursive: true }) + } + const job: HlsJob = { + key, + lookupKey, + dir, + duration, + segmentCount, + lastTouchedAt: Date.now(), + processExited: complete, + processExitCode: complete ? 0 : null, + process: null, + abort: new AbortController(), + evicted: false, + } + state.jobs.set(key, job) + await touchHlsJob(job) + + if (!complete) { + startTranscode(job, sourcePath, kbps) + } + return job + } catch (error) { + unpinCacheEntry(dir) + throw error + } +} + +export async function ensureHlsJob( + song: Doc<"songs">, + quality: string | null, + preferAtmos: boolean +): Promise { + await cleanupIdleHlsJobs() + + const kbps = qualityKbps(quality) + const sourceCodec = selectHlsSourceCodec(song, quality, preferAtmos) + const sourcePath = song.files[sourceCodec] + const key = await hlsJobKey(song, sourcePath, kbps) + const lookupKey = hlsLookupKey(song._id, quality, preferAtmos) + + let pending = state.pending.get(key) + if (!pending) { + pending = createHlsJob(song, sourcePath, kbps, key, lookupKey) + state.pending.set(key, pending) + const created = pending + created.catch(() => { + if (state.pending.get(key) === created) { + state.pending.delete(key) + } + }) + } + + const job = await pending + const exists = await fs.access(job.dir).then( + () => true, + () => false + ) + if (job.evicted || !exists) { + await evictJob(job) + return ensureHlsJob(song, quality, preferAtmos) + } + + state.jobsByLookup.set(lookupKey, job) + await touchHlsJob(job) return job } diff --git a/apps/web/lib/server-lossless.ts b/apps/web/lib/server-lossless.ts index 63efeac..93d8d0a 100644 --- a/apps/web/lib/server-lossless.ts +++ b/apps/web/lib/server-lossless.ts @@ -1,8 +1,15 @@ -import { spawn } from "node:child_process" import { createHash } from "node:crypto" import fs from "node:fs/promises" -import os from "node:os" import path from "node:path" +import { + CACHE_ORPHAN_PREFIX, + cacheDir, + pinCacheEntry, + pruneCache, + touchCacheEntry, + unpinCacheEntry, +} from "@/lib/server-cache" +import { spawnFfmpeg } from "@/lib/server-ffmpeg" const conversions = new Map>() @@ -27,56 +34,38 @@ export async function seekableLosslessFile(source: string): Promise { } async function convert(source: string, key: string): Promise { - const dir = path.join(os.tmpdir(), "otunes-lossless") + const dir = cacheDir("lossless") await fs.mkdir(dir, { recursive: true }) - const cutoff = Date.now() - 30 * 60 * 1000 - await Promise.all( - (await fs.readdir(dir)) - .filter((name) => name.endsWith(".flac")) - .map(async (name) => { - const file = path.join(dir, name) - const stat = await fs.stat(file).catch(() => null) - if (stat && stat.mtimeMs < cutoff) await fs.rm(file, { force: true }) - }) - ) const output = path.join(dir, `${key}.flac`) try { - await fs.access(output) + // Every range request touches the file so it stays cached while playing. + await touchCacheEntry(output) return output } catch { // Publish only completed conversions so range requests always see a complete file. } - const temporary = path.join( - await fs.mkdtemp(path.join(dir, "convert-")), - "audio.flac" - ) + const temporaryDir = await fs.mkdtemp(path.join(dir, CACHE_ORPHAN_PREFIX)) + const temporary = path.join(temporaryDir, "audio.flac") + pinCacheEntry(temporaryDir) try { - await new Promise((resolve, reject) => { - const child = spawn( - "ffmpeg", - [ - "-nostdin", - "-v", - "error", - "-i", - source, - "-map", - "0:a:0", - "-c:a", - "flac", - temporary, - ], - { stdio: "ignore" } - ) - child.on("error", reject) - child.on("close", (code) => { - if (code === 0) resolve() - else reject(new Error(`Lossless conversion failed: ${code}`)) - }) - }) + const ffmpeg = await spawnFfmpeg([ + "-i", + source, + "-map", + "0:a:0", + "-c:a", + "flac", + temporary, + ]) + const code = await ffmpeg.exited + if (code !== 0) { + throw new Error(`Lossless conversion failed: ${code}: ${ffmpeg.stderrTail()}`) + } await fs.rename(temporary, output) - return output } finally { - await fs.rm(path.dirname(temporary), { recursive: true, force: true }) + unpinCacheEntry(temporaryDir) + await fs.rm(temporaryDir, { recursive: true, force: true }) } + void pruneCache() + return output } From 5c94c45b69be666d96987f39852d1c44b27223e6 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 21:53:43 -0500 Subject: [PATCH 10/11] fix(convex): stop leaking song file paths and gate library queries (#99) --- .../app/(app)/library/artists/[id]/page.tsx | 11 +-- apps/web/app/api/album/[id]/cover/route.ts | 4 +- apps/web/app/api/artist/[id]/cover/route.ts | 4 +- apps/web/app/api/playlist/[id]/cover/route.ts | 4 +- apps/web/app/api/song/[id]/play/hls/route.ts | 8 +- .../[id]/play/hls/segment/[segment]/route.ts | 17 ++-- apps/web/app/api/song/[id]/play/route.ts | 8 +- apps/web/lib/server-hls.ts | 11 ++- apps/web/lib/server-song.ts | 23 ++++++ apps/web/proxy.ts | 2 +- packages/convex/convex/library.ts | 77 +++++++++++++++++-- packages/convex/convex/playlists.ts | 11 ++- 12 files changed, 131 insertions(+), 49 deletions(-) create mode 100644 apps/web/lib/server-song.ts diff --git a/apps/web/app/(app)/library/artists/[id]/page.tsx b/apps/web/app/(app)/library/artists/[id]/page.tsx index 289e0e2..862ad7b 100644 --- a/apps/web/app/(app)/library/artists/[id]/page.tsx +++ b/apps/web/app/(app)/library/artists/[id]/page.tsx @@ -1,6 +1,7 @@ import { fetchQuery } from "convex/nextjs" import { convexServerOptions } from "@/lib/convex-server" import { api } from "@otunes/convex/_generated/api" +import type { Id } from "@otunes/convex/_generated/dataModel" import { Metadata } from "next" interface PageProps { @@ -11,12 +12,12 @@ export async function generateMetadata({ params, }: PageProps): Promise { const { id } = await params - const artists = await fetchQuery( - api.library.browseArtists, - {}, + const detail = await fetchQuery( + api.library.browseArtistDetail, + { id: id as Id<"artists"> }, convexServerOptions() - ) - const selectedArtist = artists.find((artist) => artist.id === id) + ).catch(() => null) + const selectedArtist = detail?.artist return { title: `${selectedArtist ? `${selectedArtist.name}` : "oTunes"}`, diff --git a/apps/web/app/api/album/[id]/cover/route.ts b/apps/web/app/api/album/[id]/cover/route.ts index 358cbf5..0bcacd3 100644 --- a/apps/web/app/api/album/[id]/cover/route.ts +++ b/apps/web/app/api/album/[id]/cover/route.ts @@ -10,10 +10,10 @@ export async function GET( const { id } = await params try { - const album = await getConvexClient().query(api.library.getAlbum, { + const cover = await getConvexClient().query(api.library.getAlbumCover, { id: id as Id<"albums">, }) - return serveCoverFile(album?.cover, request) + return serveCoverFile(cover, request) } catch { return new Response("Not found", { status: 404 }) } diff --git a/apps/web/app/api/artist/[id]/cover/route.ts b/apps/web/app/api/artist/[id]/cover/route.ts index 5cc988f..f038486 100644 --- a/apps/web/app/api/artist/[id]/cover/route.ts +++ b/apps/web/app/api/artist/[id]/cover/route.ts @@ -10,10 +10,10 @@ export async function GET( const { id } = await params try { - const artist = await getConvexClient().query(api.library.getArtist, { + const cover = await getConvexClient().query(api.library.getArtistCover, { id: id as Id<"artists">, }) - return serveCoverFile(artist?.cover, request) + return serveCoverFile(cover, request) } catch { return new Response("Not found", { status: 404 }) } diff --git a/apps/web/app/api/playlist/[id]/cover/route.ts b/apps/web/app/api/playlist/[id]/cover/route.ts index 1fab4b8..5cb6d26 100644 --- a/apps/web/app/api/playlist/[id]/cover/route.ts +++ b/apps/web/app/api/playlist/[id]/cover/route.ts @@ -9,10 +9,10 @@ export async function GET( ) { const { id } = await params try { - const playlist = await getConvexClient().query(api.library.getPlaylist, { + const cover = await getConvexClient().query(api.library.getPlaylistCover, { id: id as Id<"playlists">, }) - return serveCoverFile(playlist?.cover, request) + return serveCoverFile(cover, request) } catch { return new Response("Not found", { status: 404 }) } diff --git a/apps/web/app/api/song/[id]/play/hls/route.ts b/apps/web/app/api/song/[id]/play/hls/route.ts index 103b9f0..b256834 100644 --- a/apps/web/app/api/song/[id]/play/hls/route.ts +++ b/apps/web/app/api/song/[id]/play/hls/route.ts @@ -1,6 +1,4 @@ -import { api } from "@otunes/convex/_generated/api" -import type { Id } from "@otunes/convex/_generated/dataModel" -import { getConvexClient } from "@/lib/convex-server" +import { getSongSource } from "@/lib/server-song" import { ensureHlsJob, HLS_SEGMENT_SECONDS } from "@/lib/server-hls" import { NextRequest } from "next/server" @@ -17,9 +15,7 @@ export async function GET( const { id } = await params try { - const song = (await getConvexClient().query(api.library.getSong, { - id: id as Id<"songs">, - }))! + const song = await getSongSource(id) const quality = request.nextUrl.searchParams.get("quality") const preferAtmos = diff --git a/apps/web/app/api/song/[id]/play/hls/segment/[segment]/route.ts b/apps/web/app/api/song/[id]/play/hls/segment/[segment]/route.ts index 0346b57..597f68d 100644 --- a/apps/web/app/api/song/[id]/play/hls/segment/[segment]/route.ts +++ b/apps/web/app/api/song/[id]/play/hls/segment/[segment]/route.ts @@ -1,6 +1,4 @@ -import { api } from "@otunes/convex/_generated/api" -import type { Id } from "@otunes/convex/_generated/dataModel" -import { getConvexClient } from "@/lib/convex-server" +import { getSongSource } from "@/lib/server-song" import { ensureHlsJob, getExistingHlsJob, @@ -36,16 +34,11 @@ export async function GET( const quality = request.nextUrl.searchParams.get("quality") const preferAtmos = request.nextUrl.searchParams.get("preferAtmos") === "true" - const existingJob = getExistingHlsJob(id, quality, preferAtmos) + // Resolve the source even when a job is cached so every segment is authorized. + const song = await getSongSource(id) const job = - existingJob ?? - (await ensureHlsJob( - (await getConvexClient().query(api.library.getSong, { - id: id as Id<"songs">, - }))!, - quality, - preferAtmos - )) + getExistingHlsJob(id, quality, preferAtmos) ?? + (await ensureHlsJob(song, quality, preferAtmos)) if (segmentIndex >= job.segmentCount) { return new Response("Segment not found", { status: 404 }) } diff --git a/apps/web/app/api/song/[id]/play/route.ts b/apps/web/app/api/song/[id]/play/route.ts index 0c5e73e..b757658 100644 --- a/apps/web/app/api/song/[id]/play/route.ts +++ b/apps/web/app/api/song/[id]/play/route.ts @@ -1,8 +1,6 @@ -import { api } from "@otunes/convex/_generated/api" -import type { Id } from "@otunes/convex/_generated/dataModel" import { audioContentTypeForPath } from "@/lib/audio-content-type" import { seekableLosslessFile } from "@/lib/server-lossless" -import { getConvexClient } from "@/lib/convex-server" +import { getSongSource } from "@/lib/server-song" import { audioInfo } from "@/lib/server-audio-info" import { ffmpegToReadableStream, streamFile } from "@/lib/server-audio-stream" import { spawnFfmpeg } from "@/lib/server-ffmpeg" @@ -118,9 +116,7 @@ export async function GET( const { browser } = userAgent(request) try { - const song = (await getConvexClient().query(api.library.getSong, { - id: id as Id<"songs">, - }))! + const song = await getSongSource(id) const quality = request.nextUrl.searchParams.get("quality") as "low" | "medium" | "high" | "lossless" | null diff --git a/apps/web/lib/server-hls.ts b/apps/web/lib/server-hls.ts index 4e9682d..50d84d1 100644 --- a/apps/web/lib/server-hls.ts +++ b/apps/web/lib/server-hls.ts @@ -15,6 +15,9 @@ import { spawnFfmpeg, type FfmpegProcess } from "@/lib/server-ffmpeg" export const HLS_SEGMENT_SECONDS = 6 const HLS_MAX_IDLE_MS = 30 * 60 * 1000 +/** The server-only slice of a song needed to transcode it. */ +export type SongSource = Pick, "_id" | "files" | "length"> + type HlsJob = { key: string lookupKey: string @@ -60,7 +63,7 @@ export function qualityKbps(quality: string | null) { } export function selectHlsSourceCodec( - song: Doc<"songs">, + song: SongSource, quality: string | null, preferAtmos: boolean ) { @@ -83,7 +86,7 @@ function hlsLookupKey( } async function hlsJobKey( - song: Doc<"songs">, + song: SongSource, sourcePath: string, kbps: number ) { @@ -250,7 +253,7 @@ function startTranscode(job: HlsJob, sourcePath: string, kbps: number) { } async function createHlsJob( - song: Doc<"songs">, + song: SongSource, sourcePath: string, kbps: number, key: string, @@ -296,7 +299,7 @@ async function createHlsJob( } export async function ensureHlsJob( - song: Doc<"songs">, + song: SongSource, quality: string | null, preferAtmos: boolean ): Promise { diff --git a/apps/web/lib/server-song.ts b/apps/web/lib/server-song.ts new file mode 100644 index 0000000..d0ff651 --- /dev/null +++ b/apps/web/lib/server-song.ts @@ -0,0 +1,23 @@ +import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server" +import { api } from "@otunes/convex/_generated/api" +import type { Id } from "@otunes/convex/_generated/dataModel" +import { fetchQuery } from "convex/nextjs" +import { convexServerOptions } from "@/lib/convex-server" +import type { SongSource } from "@/lib/server-hls" + +/** + * Loads a song's file paths as the requesting listener, so Convex enforces auth + * even if the proxy is bypassed. Throws when signed out or the song is missing. + */ +export async function getSongSource(id: string): Promise { + const token = await convexAuthNextjsToken() + const song = await fetchQuery( + api.library.getSongSource, + { id: id as Id<"songs"> }, + convexServerOptions(token) + ) + if (!song) { + throw new Error("Song not found") + } + return song +} diff --git a/apps/web/proxy.ts b/apps/web/proxy.ts index 342af0d..f9ad380 100644 --- a/apps/web/proxy.ts +++ b/apps/web/proxy.ts @@ -12,7 +12,7 @@ const isPublic = createRouteMatcher([ "/api/playlist/:id/cover", "/album/:id", "/artist/:id", - "/artists/:id", + "/library/artists/:id", "/playlist/:id", ]) diff --git a/packages/convex/convex/library.ts b/packages/convex/convex/library.ts index 65a2a23..acb9970 100644 --- a/packages/convex/convex/library.ts +++ b/packages/convex/convex/library.ts @@ -39,6 +39,20 @@ export type { SidebarPlaylists, } from "./types" +const EMPTY_PAGE = { page: [], isDone: true, continueCursor: "" } + +/** Reactive queries return empty data when signed out so sign-out doesn't throw mid-render. */ +export async function isSignedIn(ctx: QueryCtx) { + return (await getAuthUserId(ctx)) !== null +} + +/** Imperative lookups throw instead, so callers that cache results don't cache an empty one. */ +export async function requireSignedIn(ctx: QueryCtx) { + if (!(await isSignedIn(ctx))) { + throw new ConvexError("Not authenticated") + } +} + function getSongArtistNames(artist: string | string[]): string[] { if (Array.isArray(artist)) { return artist.map((name) => name.trim()).filter((name) => name.length > 0) @@ -200,6 +214,9 @@ function toBrowseSong( export const browseAlbums = query({ args: {}, handler: async (ctx) => { + if (!(await isSignedIn(ctx))) { + return [] + } const artistMap = await loadArtistMap(ctx) const albums = await ctx.db.query("albums").collect() @@ -215,6 +232,9 @@ export const browseAlbums = query({ export const browseArtists = query({ args: {}, handler: async (ctx) => { + if (!(await isSignedIn(ctx))) { + return [] + } const artists = await ctx.db.query("artists").collect() return artists .map(toBrowseArtist) @@ -242,6 +262,9 @@ function paginateSlice( export const browseArtistsPaginated = query({ args: { paginationOpts: paginationOptsValidator }, handler: async (ctx, args) => { + if (!(await isSignedIn(ctx))) { + return EMPTY_PAGE + } const result = await ctx.db .query("artists") .withIndex("by_name") @@ -258,6 +281,9 @@ export const browseArtistsPaginated = query({ export const browseAlbumsPaginated = query({ args: { paginationOpts: paginationOptsValidator }, handler: async (ctx, args) => { + if (!(await isSignedIn(ctx))) { + return EMPTY_PAGE + } const result = await ctx.db .query("albums") .withIndex("by_name") @@ -458,6 +484,9 @@ export const browseSongsPaginated = query({ sortDirection: songsSortDirectionValidator, }, handler: async (ctx, args) => { + if (!(await isSignedIn(ctx))) { + return EMPTY_PAGE + } if (args.sortKey === "title") { return paginateSongsByTitle(ctx, args.paginationOpts, args.sortDirection) } @@ -477,6 +506,7 @@ export const browseSortedSongIds = query({ sortDirection: songsSortDirectionValidator, }, handler: async (ctx, args) => { + await requireSignedIn(ctx) return getSortedLibrarySongIds(ctx, args.sortKey, args.sortDirection) }, }) @@ -486,6 +516,7 @@ const MAX_SONGS_BY_IDS = 200 export const browseSongsByIds = query({ args: { ids: v.array(v.id("songs")) }, handler: async (ctx, args): Promise => { + await requireSignedIn(ctx) if (args.ids.length > MAX_SONGS_BY_IDS) { throw new ConvexError(`Request at most ${MAX_SONGS_BY_IDS} songs`) } @@ -493,6 +524,7 @@ export const browseSongsByIds = query({ }, }) +/** Public: shared /album links render this without a session. */ export const browseAlbumDetail = query({ args: { id: v.id("albums") }, handler: async (ctx, args): Promise => { @@ -522,6 +554,7 @@ export const browseAlbumDetail = query({ }, }) +/** Public: shared /artist links render this without a session. */ export const browseArtistDetail = query({ args: { id: v.id("artists") }, handler: async (ctx, args) => { @@ -575,7 +608,7 @@ export const searchLibrary = query({ args: { query: v.string() }, handler: async (ctx, args) => { const queryText = args.query.trim().toLowerCase() - if (!queryText) { + if (!queryText || !(await isSignedIn(ctx))) { return { topResults: [], artists: [], @@ -677,6 +710,9 @@ export const searchLibrary = query({ export const browseRecentlyAdded = query({ args: { limit: v.optional(v.number()) }, handler: async (ctx, args) => { + if (!(await isSignedIn(ctx))) { + return [] + } const albumQuery = ctx.db.query("albums").order("desc") const albums = args.limit ? await albumQuery.take(args.limit) @@ -696,6 +732,9 @@ export const browseRecentlyAdded = query({ export const browseRecentlyAddedPaginated = query({ args: { paginationOpts: paginationOptsValidator }, handler: async (ctx, args) => { + if (!(await isSignedIn(ctx))) { + return EMPTY_PAGE + } const result = await ctx.db .query("albums") .order("desc") @@ -826,31 +865,53 @@ export const getSongs = internalQuery({ }, }) -export const getArtist = query({ +/** Public: share-link previews load covers without a session. */ +export const getArtistCover = query({ args: { id: v.id("artists") }, handler: async (ctx, args) => { - return await ctx.db.get("artists", args.id) + return (await ctx.db.get("artists", args.id))?.cover ?? null }, }) -export const getAlbum = query({ +/** Public: share-link previews load covers without a session. */ +export const getAlbumCover = query({ args: { id: v.id("albums") }, handler: async (ctx, args) => { - return await ctx.db.get("albums", args.id) + return (await ctx.db.get("albums", args.id))?.cover ?? null }, }) -export const getPlaylist = query({ +/** Public: share-link previews load covers without a session. */ +export const getPlaylistCover = query({ args: { id: v.id("playlists") }, handler: async (ctx, args) => { - return await ctx.db.get("playlists", args.id) + return (await ctx.db.get("playlists", args.id))?.cover ?? null }, }) +/** Public: share-link previews read song metadata without a session. Never returns file paths. */ export const getSong = query({ args: { id: v.id("songs") }, handler: async (ctx, args) => { - return await ctx.db.get("songs", args.id) + const song = await ctx.db.get("songs", args.id) + if (!song) { + return null + } + const { files: _files, ...clientSong } = song + return clientSong + }, +}) + +/** Returns absolute file paths. Only the web streaming routes call this, as the listener. */ +export const getSongSource = query({ + args: { id: v.id("songs") }, + handler: async (ctx, args) => { + await requireSignedIn(ctx) + const song = await ctx.db.get("songs", args.id) + if (!song) { + return null + } + return { _id: song._id, files: song.files, length: song.length } }, }) diff --git a/packages/convex/convex/playlists.ts b/packages/convex/convex/playlists.ts index c763a67..dd34f42 100644 --- a/packages/convex/convex/playlists.ts +++ b/packages/convex/convex/playlists.ts @@ -10,7 +10,11 @@ import type { PlaylistSummary, SidebarPlaylists, } from "./library" -import { browseSongsFromIds, compareAlbumSongs } from "./library" +import { + browseSongsFromIds, + compareAlbumSongs, + requireSignedIn, +} from "./library" function toPlaylistSummary( playlist: Doc<"playlists">, @@ -108,6 +112,7 @@ async function browsePlaylistSummaryHandler( } } +/** Public: shared /playlist links render this without a session. */ export const browsePlaylistDetail = query({ args: { id: v.id("playlists") }, handler: async (ctx, args): Promise => { @@ -267,6 +272,7 @@ export const listAllPlaylists = query({ export const getAlbumSongIds = query({ args: { albumId: v.id("albums") }, handler: async (ctx, args) => { + await requireSignedIn(ctx) const songs = await ctx.db .query("songs") .withIndex("by_album", (q) => q.eq("album", args.albumId)) @@ -279,6 +285,7 @@ export const getAlbumSongIds = query({ export const getArtistSongIds = query({ args: { artistId: v.id("artists") }, handler: async (ctx, args) => { + await requireSignedIn(ctx) const songs = await ctx.db .query("songs") .withIndex("by_artist", (q) => q.eq("albumArtist", args.artistId)) @@ -290,6 +297,7 @@ export const getArtistSongIds = query({ export const getOrderedArtistSongIds = query({ args: { artistId: v.id("artists") }, handler: async (ctx, args) => { + await requireSignedIn(ctx) const songs = await ctx.db .query("songs") .withIndex("by_artist", (q) => q.eq("albumArtist", args.artistId)) @@ -320,6 +328,7 @@ export const getOrderedArtistSongIds = query({ export const getPlaylistSongIds = query({ args: { playlistId: v.id("playlists") }, handler: async (ctx, args) => { + await requireSignedIn(ctx) const playlist = await ctx.db.get("playlists", args.playlistId) return playlist?.songs ?? [] }, From 51ceab738b5a96945b8e55968a5aab9b4bdd8c59 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 21:56:01 -0500 Subject: [PATCH 11/11] fix(convex): move playback state and avatars off the users document (#100) --- .../mobile/app/(app)/(tabs)/home/settings.tsx | 6 +- .../components/profile-header-button.tsx | 6 +- apps/mobile/components/tablet-sidebar.tsx | 4 +- apps/mobile/contexts/playback.tsx | 22 +- apps/mobile/hooks/use-profile-image-url.ts | 13 + apps/web/app/api/user/[id]/avatar/route.ts | 55 ++++ apps/web/components/playback-provider.tsx | 22 +- docker/entrypoint.sh | 3 + packages/convex/client/playback-store.ts | 84 +++++-- packages/convex/convex/_generated/api.d.ts | 6 + packages/convex/convex/auth.ts | 3 +- packages/convex/convex/limits.ts | 10 + packages/convex/convex/migrations.ts | 39 +++ packages/convex/convex/playback.ts | 95 +++---- packages/convex/convex/playbackState.ts | 236 ++++++++++++++++++ packages/convex/convex/schema.ts | 34 ++- packages/convex/convex/users.ts | 115 ++++++++- 17 files changed, 658 insertions(+), 95 deletions(-) create mode 100644 apps/mobile/hooks/use-profile-image-url.ts create mode 100644 apps/web/app/api/user/[id]/avatar/route.ts create mode 100644 packages/convex/convex/limits.ts create mode 100644 packages/convex/convex/migrations.ts create mode 100644 packages/convex/convex/playbackState.ts diff --git a/apps/mobile/app/(app)/(tabs)/home/settings.tsx b/apps/mobile/app/(app)/(tabs)/home/settings.tsx index d3e8d72..e0e5d55 100644 --- a/apps/mobile/app/(app)/(tabs)/home/settings.tsx +++ b/apps/mobile/app/(app)/(tabs)/home/settings.tsx @@ -26,6 +26,7 @@ import { } from "@/lib/artwork-color-preference" import { initialsFromName } from "@/lib/format" import { useCachedQuery } from "@/hooks/use-cached-query" +import { useProfileImageUrl } from "@/hooks/use-profile-image-url" import { changeServer, signOut } from "@/lib/session" import { radius, spacing, useThemeColors } from "@/lib/theme" import { showError } from "@/lib/toast" @@ -768,6 +769,7 @@ function ProfileAvatar({ style?: StyleProp }) { const colors = useThemeColors() + const imageUrl = useProfileImageUrl(user.image) const avatarStyle = [ styles.avatar, { @@ -779,11 +781,11 @@ function ProfileAvatar({ style, ] - if (user.image) { + if (imageUrl) { return ( diff --git a/apps/mobile/components/profile-header-button.tsx b/apps/mobile/components/profile-header-button.tsx index 429b38f..fc77855 100644 --- a/apps/mobile/components/profile-header-button.tsx +++ b/apps/mobile/components/profile-header-button.tsx @@ -4,6 +4,7 @@ import { Image } from "expo-image" import { Pressable, StyleSheet, Text, View } from "react-native" import { useCachedQuery } from "@/hooks/use-cached-query" +import { useProfileImageUrl } from "@/hooks/use-profile-image-url" import { initialsFromName } from "@/lib/format" import { radius, useThemeColors } from "@/lib/theme" import { api } from "@otunes/convex/_generated/api" @@ -13,6 +14,7 @@ export function ProfileHeaderButton() { const openSettings = useOpenSettings() const colors = useThemeColors() const user = useCachedQuery(api.auth.currentUser) + const imageUrl = useProfileImageUrl(user?.image) if (tabletLayout) return null @@ -33,9 +35,9 @@ export function ProfileHeaderButton() { }, ]} > - {user?.image ? ( + {imageUrl ? ( diff --git a/apps/mobile/components/tablet-sidebar.tsx b/apps/mobile/components/tablet-sidebar.tsx index f2811cb..707b2aa 100644 --- a/apps/mobile/components/tablet-sidebar.tsx +++ b/apps/mobile/components/tablet-sidebar.tsx @@ -4,6 +4,7 @@ import { useIsFocused } from "expo-router" import { Platform, type ViewProps } from "react-native" import { useCachedQuery } from "@/hooks/use-cached-query" +import { useProfileImageUrl } from "@/hooks/use-profile-image-url" import { initialsFromName } from "@/lib/format" import { api } from "@otunes/convex/_generated/api" @@ -22,6 +23,7 @@ const NativeSidebar = export function TabletSidebar() { const user = useCachedQuery(api.auth.currentUser) + const imageUrl = useProfileImageUrl(user?.image) const openSettings = useOpenSettings() const active = useIsFocused() @@ -31,7 +33,7 @@ export function TabletSidebar() { style={{ position: "absolute", width: 0, height: 0 }} accountName={user?.name ?? "Account"} initials={initialsFromName(user?.name ?? "Me")} - imageURL={user?.image} + imageURL={imageUrl} active={active} onProfilePress={openSettings} /> diff --git a/apps/mobile/contexts/playback.tsx b/apps/mobile/contexts/playback.tsx index a95720a..a69dbab 100644 --- a/apps/mobile/contexts/playback.tsx +++ b/apps/mobile/contexts/playback.tsx @@ -203,17 +203,19 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { useEffect(() => { if (!isSignedIn) return - store.setTransport((state) => - syncPlaybackStateMutation({ - songQueue: state.queue, - queueHistory: state.history, - shuffleEnabled: state.shuffleEnabled, - repeatEnabled: state.repeatEnabled, - currentSongProgress: state.progressSeconds, - }) - ) + store.setTransport({ + sync: (state) => + syncPlaybackStateMutation({ + songQueue: state.queue, + queueHistory: state.history, + shuffleEnabled: state.shuffleEnabled, + repeatEnabled: state.repeatEnabled, + currentSongProgress: state.progressSeconds, + }), + loadProgress: () => convex.query(api.playback.getSongProgress, {}), + }) return () => store.setTransport(null) - }, [store, isSignedIn, syncPlaybackStateMutation]) + }, [store, isSignedIn, syncPlaybackStateMutation, convex]) useEffect(() => { if (!serverPlayback) return diff --git a/apps/mobile/hooks/use-profile-image-url.ts b/apps/mobile/hooks/use-profile-image-url.ts new file mode 100644 index 0000000..f2a8f9d --- /dev/null +++ b/apps/mobile/hooks/use-profile-image-url.ts @@ -0,0 +1,13 @@ +import { useServerConfig } from "@/contexts/server-config" + +/** + * Resolves `currentUser.image` to a loadable URI. Stored avatars come back as + * paths on the oTunes web server; legacy ones are data URLs. + */ +export function useProfileImageUrl(image: string | undefined) { + const { config } = useServerConfig() + if (!image?.startsWith("/")) { + return image + } + return config ? `${config.serverUrl.replace(/\/+$/, "")}${image}` : undefined +} diff --git a/apps/web/app/api/user/[id]/avatar/route.ts b/apps/web/app/api/user/[id]/avatar/route.ts new file mode 100644 index 0000000..95e30a4 --- /dev/null +++ b/apps/web/app/api/user/[id]/avatar/route.ts @@ -0,0 +1,55 @@ +import { api } from "@otunes/convex/_generated/api" +import type { Id } from "@otunes/convex/_generated/dataModel" +import sharp from "sharp" +import { getConvexClient, getConvexServerUrl } from "@/lib/convex-server" + +const AVATAR_SIZE = 256 + +/** + * Serves a profile photo from Convex storage, downscaled. URLs carry the + * storage id (`?v=`), so a new photo gets a new URL and responses can be + * cached for good. + */ +export async function GET( + _request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params + try { + const storageUrl = await getConvexClient().query( + api.users.getProfileImageUrl, + { userId: id as Id<"users"> } + ) + if (!storageUrl) { + return new Response("Not found", { status: 404 }) + } + + // The backend builds storage URLs from its public origin, which may not + // be reachable from here. Fetch the same path from the internal URL. + const { pathname, search } = new URL(storageUrl) + const upstream = await fetch( + new URL(pathname + search, getConvexServerUrl()) + ) + if (!upstream.ok) { + return new Response("Not found", { status: 404 }) + } + + const data = await sharp(Buffer.from(await upstream.arrayBuffer())) + .rotate() + .resize(AVATAR_SIZE, AVATAR_SIZE, { + fit: "cover", + withoutEnlargement: true, + }) + .webp({ quality: 85 }) + .toBuffer() + + return new Response(new Uint8Array(data), { + headers: { + "Content-Type": "image/webp", + "Cache-Control": "public, max-age=31536000, immutable", + }, + }) + } catch { + return new Response("Not found", { status: 404 }) + } +} diff --git a/apps/web/components/playback-provider.tsx b/apps/web/components/playback-provider.tsx index 79f9446..02c9e08 100644 --- a/apps/web/components/playback-provider.tsx +++ b/apps/web/components/playback-provider.tsx @@ -374,17 +374,19 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { if (!isSignedIn) { return } - store.setTransport((state) => - syncPlaybackStateMutation({ - songQueue: state.queue, - queueHistory: state.history, - shuffleEnabled: state.shuffleEnabled, - repeatEnabled: state.repeatEnabled, - currentSongProgress: state.progressSeconds, - }) - ) + store.setTransport({ + sync: (state) => + syncPlaybackStateMutation({ + songQueue: state.queue, + queueHistory: state.history, + shuffleEnabled: state.shuffleEnabled, + repeatEnabled: state.repeatEnabled, + currentSongProgress: state.progressSeconds, + }), + loadProgress: () => convex.query(api.playback.getSongProgress, {}), + }) return () => store.setTransport(null) - }, [store, isSignedIn, syncPlaybackStateMutation]) + }, [store, isSignedIn, syncPlaybackStateMutation, convex]) useEffect(() => { if (!serverPlayback) { diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index 39352e8..93a77b1 100644 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -97,6 +97,9 @@ admin_key=$(cd /convex && umask 077 && "${as_convex[@]}" ./generate_admin_key.sh log "Deploying Convex functions" convex_cli deploy --typecheck disable --codegen disable +log "Running data migrations" +convex_cli run migrations:migrateUsers + # `env get` exits 0 with no output when the variable is unset. Any other failure # must not be read as "no keys": regenerating them signs every user out. if ! jwks=$(convex_cli env get JWKS); then diff --git a/packages/convex/client/playback-store.ts b/packages/convex/client/playback-store.ts index f91d524..f13c0b9 100644 --- a/packages/convex/client/playback-store.ts +++ b/packages/convex/client/playback-store.ts @@ -1,4 +1,5 @@ import type { Id } from "../convex/_generated/dataModel" +import { MAX_QUEUE_LENGTH } from "../convex/limits" import { EMPTY_PLAYBACK_QUEUE, type PlaybackQueueState, @@ -7,6 +8,11 @@ import { import { loadPersistentCache, readCache, writeCache } from "./persistent-cache" const SYNC_DELAY_MS = 300 +/** + * Backoff for failed syncs. Convex queues mutations while offline, so a + * rejection means the server refused the state; after the last retry the + * change is dropped until the next local edit instead of retrying forever. + */ const RETRY_DELAYS_MS = [1_000, 3_000, 10_000, 30_000] export type ServerPlaybackState = { @@ -14,7 +20,6 @@ export type ServerPlaybackState = { queueHistorySongIds: Id<"songs">[] shuffleEnabled: boolean repeatEnabled: RepeatMode - currentSongProgress: number revision: number } @@ -30,9 +35,12 @@ type PersistedPlayback = PlaybackQueueState & { dirty: boolean } -export type PlaybackSyncTransport = ( - state: PlaybackQueueState -) => Promise +export type PlaybackSyncTransport = { + /** Saves the state and resolves with the new server revision. */ + sync: (state: PlaybackQueueState) => Promise + /** One-shot read of the server's saved progress for its current song. */ + loadProgress: () => Promise +} /** * Client-owned playback queue. Changes apply locally (and persist on this @@ -49,6 +57,7 @@ export class PlaybackStore { private retryAttempt = 0 private syncTimer: ReturnType | null = null private latestServerState: ServerPlaybackState | null = null + private adopting = false private transport: PlaybackSyncTransport | null = null private readonly listeners = new Set<() => void>() @@ -79,7 +88,7 @@ export class PlaybackStore { } update(recipe: (state: PlaybackQueueState) => PlaybackQueueState) { - const next = recipe(this.state) + const next = capQueue(recipe(this.state)) if (next === this.state) { return } @@ -102,7 +111,7 @@ export class PlaybackStore { receiveServerState(serverState: ServerPlaybackState) { this.latestServerState = serverState if (this.snapshot.hydrated) { - this.adoptServerState() + void this.adoptServerState() } } @@ -116,23 +125,52 @@ export class PlaybackStore { const { revision, dirty, ...state } = persisted this.revision = revision this.dirty = dirty - this.state = { ...EMPTY_PLAYBACK_QUEUE, ...state } + this.state = capQueue({ ...EMPTY_PLAYBACK_QUEUE, ...state }) } this.snapshot = toSnapshot(this.state, true) this.emit() - this.adoptServerState() + void this.adoptServerState() if (this.dirty) { this.scheduleSync(0) } } - private adoptServerState() { + private canAdopt(serverState: ServerPlaybackState | null) { + return ( + serverState !== null && + !this.dirty && + !this.inFlight && + (this.revision === null || serverState.revision > this.revision) + ) + } + + /** + * Adopts the latest server queue. Progress is not part of the queue query + * (it changes every few seconds), so it is fetched once here. + */ + private async adoptServerState() { const serverState = this.latestServerState - if (!serverState || this.dirty || this.inFlight) { + if (this.adopting || !serverState || !this.canAdopt(serverState)) { return } - if (this.revision !== null && serverState.revision <= this.revision) { + + this.adopting = true + let progressSeconds = 0 + try { + progressSeconds = (await this.transport?.loadProgress()) ?? 0 + } catch { + // Starting from 0 beats not adopting the queue at all. + } finally { + this.adopting = false + } + + // Newer server state or local edits may have arrived while loading. + if (this.latestServerState !== serverState) { + void this.adoptServerState() + return + } + if (!this.canAdopt(serverState)) { return } @@ -142,7 +180,7 @@ export class PlaybackStore { history: serverState.queueHistorySongIds, shuffleEnabled: serverState.shuffleEnabled, repeatEnabled: serverState.repeatEnabled, - progressSeconds: serverState.currentSongProgress, + progressSeconds, }) } @@ -167,7 +205,7 @@ export class PlaybackStore { let failed = false try { - const revision = await transport(this.state) + const revision = await transport.sync(this.state) this.revision = Math.max(revision, this.revision ?? 0) this.retryAttempt = 0 if (this.changeCount === changeCountAtStart) { @@ -181,15 +219,17 @@ export class PlaybackStore { this.persist() - if (failed) { - const delay = - RETRY_DELAYS_MS[Math.min(this.retryAttempt, RETRY_DELAYS_MS.length - 1)] + if (failed && this.retryAttempt < RETRY_DELAYS_MS.length) { + this.scheduleSync(RETRY_DELAYS_MS[this.retryAttempt]) this.retryAttempt += 1 - this.scheduleSync(delay) + } else if (failed) { + this.retryAttempt = 0 + this.dirty = false + this.persist() } else if (this.dirty) { this.scheduleSync(SYNC_DELAY_MS) } else { - this.adoptServerState() + void this.adoptServerState() } } @@ -227,6 +267,14 @@ export class PlaybackStore { } } +/** Mirrors the server's queue cap so local and synced state agree. */ +function capQueue(state: PlaybackQueueState): PlaybackQueueState { + if (state.queue.length <= MAX_QUEUE_LENGTH) { + return state + } + return { ...state, queue: state.queue.slice(0, MAX_QUEUE_LENGTH) } +} + function toSnapshot( state: PlaybackQueueState, hydrated: boolean diff --git a/packages/convex/convex/_generated/api.d.ts b/packages/convex/convex/_generated/api.d.ts index a4607bb..ce68e7d 100644 --- a/packages/convex/convex/_generated/api.d.ts +++ b/packages/convex/convex/_generated/api.d.ts @@ -14,7 +14,10 @@ import type * as crons from "../crons.js"; import type * as favorites from "../favorites.js"; import type * as http from "../http.js"; import type * as library from "../library.js"; +import type * as limits from "../limits.js"; +import type * as migrations from "../migrations.js"; import type * as playback from "../playback.js"; +import type * as playbackState from "../playbackState.js"; import type * as playlists from "../playlists.js"; import type * as types from "../types.js"; import type * as users from "../users.js"; @@ -32,7 +35,10 @@ declare const fullApi: ApiFromModules<{ favorites: typeof favorites; http: typeof http; library: typeof library; + limits: typeof limits; + migrations: typeof migrations; playback: typeof playback; + playbackState: typeof playbackState; playlists: typeof playlists; types: typeof types; users: typeof users; diff --git a/packages/convex/convex/auth.ts b/packages/convex/convex/auth.ts index e89895e..14314c8 100644 --- a/packages/convex/convex/auth.ts +++ b/packages/convex/convex/auth.ts @@ -3,6 +3,7 @@ import { ConvexError } from "convex/values" import { Password } from "@convex-dev/auth/providers/Password" import { query } from "./_generated/server" import type { MutationCtx } from "./_generated/server" +import { profileImagePath } from "./users" export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({ providers: [ @@ -72,7 +73,7 @@ export const currentUser = query({ return { _id: user._id, name: user.name, - image: user.image, + image: profileImagePath(user), email: user.email, isAdmin: user.isAdmin, playbackQuality: user.playbackQuality, diff --git a/packages/convex/convex/limits.ts b/packages/convex/convex/limits.ts new file mode 100644 index 0000000..8adb174 --- /dev/null +++ b/packages/convex/convex/limits.ts @@ -0,0 +1,10 @@ +/** + * Limits shared by Convex functions and clients. Convex rejects arrays longer + * than 8,192 values in documents, arguments, and return values. + */ + +/** Songs kept in the playback queue, including the current song. */ +export const MAX_QUEUE_LENGTH = 5_000 + +/** Largest profile photo accepted, in bytes after base64 decoding. */ +export const MAX_PROFILE_IMAGE_BYTES = 2 * 1024 * 1024 diff --git a/packages/convex/convex/migrations.ts b/packages/convex/convex/migrations.ts new file mode 100644 index 0000000..f8ce5bb --- /dev/null +++ b/packages/convex/convex/migrations.ts @@ -0,0 +1,39 @@ +import { v } from "convex/values" +import { internal } from "./_generated/api" +import { internalMutation } from "./_generated/server" +import { hasLegacyPlayback, migrateUserPlayback } from "./playbackState" + +const BATCH_SIZE = 25 + +/** + * Moves playback state off `users` into `playbackStates`/`playbackProgress` + * and legacy data URL avatars into file storage. Idempotent; the Docker + * entrypoint runs it on every boot. Run manually with + * `npx convex run migrations:migrateUsers`. + */ +export const migrateUsers = internalMutation({ + args: { cursor: v.optional(v.union(v.string(), v.null())) }, + handler: async (ctx, { cursor }) => { + const page = await ctx.db + .query("users") + .paginate({ cursor: cursor ?? null, numItems: BATCH_SIZE }) + + for (const user of page.page) { + if (hasLegacyPlayback(user)) { + await migrateUserPlayback(ctx, user) + } + if (!user.imageStorageId && user.image?.startsWith("data:")) { + await ctx.scheduler.runAfter(0, internal.users.storeProfileImage, { + userId: user._id, + image: user.image, + }) + } + } + + if (!page.isDone) { + await ctx.scheduler.runAfter(0, internal.migrations.migrateUsers, { + cursor: page.continueCursor, + }) + } + }, +}) diff --git a/packages/convex/convex/playback.ts b/packages/convex/convex/playback.ts index 246176f..8bf67ed 100644 --- a/packages/convex/convex/playback.ts +++ b/packages/convex/convex/playback.ts @@ -1,13 +1,19 @@ import { getAuthUserId } from "@convex-dev/auth/server" import { ConvexError, v } from "convex/values" -import type { Doc, Id } from "./_generated/dataModel" +import type { Id } from "./_generated/dataModel" import type { MutationCtx } from "./_generated/server" import { mutation, query } from "./_generated/server" import { browseSongsFromIds } from "./library" +import { + loadPlaybackForWrite, + readPlaybackProgress, + readPlaybackState, + writePlayback, + writeProgress, +} from "./playbackState" export type { HistorySong, QueueSong } from "./types" -const MAX_QUEUE_HISTORY = 30 const MAX_RECENTLY_PLAYED = 30 type RecentlyPlayedItem = Id<"albums"> | Id<"playlists"> @@ -59,30 +65,15 @@ async function requireAuth(ctx: MutationCtx) { return userId } -async function patchPlayback( - ctx: MutationCtx, - userId: Id<"users">, - patch: Partial< - Pick< - Doc<"users">, - | "songQueue" - | "queueHistory" - | "currentSongProgress" - | "shuffleEnabled" - | "repeatEnabled" - > - > -) { - const user = await ctx.db.get(userId) - if (!user) { +async function requirePlayback(ctx: MutationCtx, userId: Id<"users">) { + const playback = await loadPlaybackForWrite(ctx, userId) + if (!playback) { throw new ConvexError("User not found") } - - const playbackRevision = (user.playbackRevision ?? 0) + 1 - await ctx.db.patch(userId, { ...patch, playbackRevision }) - return playbackRevision + return playback } +/** Queue state without progress; progress comes from `getSongProgress`. */ export const getPlaybackState = query({ args: {}, handler: async (ctx) => { @@ -91,12 +82,8 @@ export const getPlaybackState = query({ return null } - const user = await ctx.db.get(userId) - if (!user) { - return null - } - - const songIds = user.songQueue ?? [] + const playback = await readPlaybackState(ctx, userId) + const songIds = playback.songQueue const currentSong = songIds.length > 0 ? ((await browseSongsFromIds(ctx, [songIds[0]]))[0] ?? null) @@ -104,12 +91,16 @@ export const getPlaybackState = query({ return { queueSongIds: songIds, - queueHistorySongIds: user.queueHistory ?? [], + queueHistorySongIds: playback.queueHistory, currentSong, - shuffleEnabled: user.shuffleEnabled ?? false, - repeatEnabled: user.repeatEnabled ?? ("none" as const), - currentSongProgress: user.currentSongProgress ?? 0, - revision: user.playbackRevision ?? 0, + shuffleEnabled: playback.shuffleEnabled, + repeatEnabled: playback.repeatEnabled, + /** + * @deprecated Always 0. Reading progress here would rerun this query on + * every progress save. Kept for app builds that predate `getSongProgress`. + */ + currentSongProgress: 0, + revision: playback.revision, } }, }) @@ -134,12 +125,12 @@ export const syncPlaybackState = mutation({ }, handler: async (ctx, args) => { const userId = await requireAuth(ctx) - return await patchPlayback(ctx, userId, { + return await writePlayback(ctx, userId, { songQueue: args.songQueue, - queueHistory: args.queueHistory.slice(-MAX_QUEUE_HISTORY), + queueHistory: args.queueHistory, shuffleEnabled: args.shuffleEnabled, repeatEnabled: args.repeatEnabled, - currentSongProgress: Math.max(0, Math.floor(args.currentSongProgress)), + progressSeconds: args.currentSongProgress, }) }, }) @@ -159,6 +150,26 @@ export const recordPlay = mutation({ }, }) +/** + * Saved position of the current song. Subscribing reruns every few seconds + * during playback, so clients fetch it once when adopting a new queue. + */ +export const getSongProgress = query({ + args: {}, + handler: async (ctx) => { + const userId = await getAuthUserId(ctx) + if (userId === null) { + throw new ConvexError("User not logged in") + } + + const [{ songQueue }, progress] = await Promise.all([ + readPlaybackState(ctx, userId), + readPlaybackProgress(ctx, userId), + ]) + return progress.songId === songQueue[0] ? progress.progressSeconds : 0 + }, +}) + export const updateSongProgress = mutation({ args: { songId: v.id("songs"), @@ -166,15 +177,15 @@ export const updateSongProgress = mutation({ }, handler: async (ctx, args) => { const userId = await requireAuth(ctx) - const user = await ctx.db.get(userId) - if (!user) { - throw new ConvexError("User not found") - } + const playback = await requirePlayback(ctx, userId) - if ((user.songQueue ?? [])[0] !== args.songId) { + if (playback.songQueue[0] !== args.songId) { return } - await ctx.db.patch(userId, { currentSongProgress: args.progressSeconds }) + await writeProgress(ctx, userId, { + songId: args.songId, + progressSeconds: args.progressSeconds, + }) }, }) diff --git a/packages/convex/convex/playbackState.ts b/packages/convex/convex/playbackState.ts new file mode 100644 index 0000000..c57855d --- /dev/null +++ b/packages/convex/convex/playbackState.ts @@ -0,0 +1,236 @@ +import { ConvexError } from "convex/values" +import type { Doc, Id } from "./_generated/dataModel" +import type { MutationCtx, QueryCtx } from "./_generated/server" +import { MAX_QUEUE_LENGTH } from "./limits" + +const MAX_QUEUE_HISTORY = 30 + +export type RepeatMode = Doc<"playbackStates">["repeatEnabled"] + +export type PlaybackState = Pick< + Doc<"playbackStates">, + "songQueue" | "queueHistory" | "shuffleEnabled" | "repeatEnabled" | "revision" +> + +export type PlaybackProgress = { + songId: Id<"songs"> | null + progressSeconds: number +} + +export type PlaybackPatch = Partial< + Pick< + PlaybackState, + "songQueue" | "queueHistory" | "shuffleEnabled" | "repeatEnabled" + > +> & { + /** Saved position of the new `songQueue[0]`. */ + progressSeconds?: number +} + +const LEGACY_PLAYBACK_FIELDS = [ + "songQueue", + "queueHistory", + "currentSongProgress", + "playbackRevision", + "shuffleEnabled", + "repeatEnabled", +] as const + +const EMPTY_STATE: PlaybackState = { + songQueue: [], + queueHistory: [], + shuffleEnabled: false, + repeatEnabled: "none", + revision: 0, +} + +function legacyState(user: Doc<"users"> | null): PlaybackState { + if (!user) { + return EMPTY_STATE + } + return { + songQueue: (user.songQueue ?? []).slice(0, MAX_QUEUE_LENGTH), + queueHistory: (user.queueHistory ?? []).slice(-MAX_QUEUE_HISTORY), + shuffleEnabled: user.shuffleEnabled ?? false, + repeatEnabled: user.repeatEnabled ?? "none", + revision: user.playbackRevision ?? 0, + } +} + +function legacyProgress(user: Doc<"users"> | null): PlaybackProgress { + return { + songId: user?.songQueue?.[0] ?? null, + progressSeconds: user?.currentSongProgress ?? 0, + } +} + +export function hasLegacyPlayback(user: Doc<"users">) { + return LEGACY_PLAYBACK_FIELDS.some((field) => user[field] !== undefined) +} + +function stateDoc(ctx: QueryCtx, userId: Id<"users">) { + return ctx.db + .query("playbackStates") + .withIndex("by_user", (q) => q.eq("userId", userId)) + .unique() +} + +function progressDoc(ctx: QueryCtx, userId: Id<"users">) { + return ctx.db + .query("playbackProgress") + .withIndex("by_user", (q) => q.eq("userId", userId)) + .unique() +} + +/** + * Reads the queue without touching progress, so progress saves do not rerun + * the caller. Users that have not been migrated yet fall back to `users`. + */ +export async function readPlaybackState( + ctx: QueryCtx, + userId: Id<"users"> +): Promise { + const doc = await stateDoc(ctx, userId) + if (doc) { + return doc + } + return legacyState(await ctx.db.get(userId)) +} + +export async function readPlaybackProgress( + ctx: QueryCtx, + userId: Id<"users"> +): Promise { + const doc = await progressDoc(ctx, userId) + if (doc) { + return { songId: doc.songId ?? null, progressSeconds: doc.progressSeconds } + } + return legacyProgress(await ctx.db.get(userId)) +} + +/** + * Moves a user's playback fields from `users` into `playbackStates` and + * `playbackProgress`. Safe to call repeatedly. + */ +export async function migrateUserPlayback( + ctx: MutationCtx, + user: Doc<"users"> +) { + const [existingState, existingProgress] = await Promise.all([ + stateDoc(ctx, user._id), + progressDoc(ctx, user._id), + ]) + + let state = existingState + if (!state) { + const stateId = await ctx.db.insert("playbackStates", { + userId: user._id, + ...legacyState(user), + }) + state = (await ctx.db.get(stateId))! + } + if (!existingProgress) { + const progress = legacyProgress(user) + await ctx.db.insert("playbackProgress", { + userId: user._id, + progressSeconds: progress.progressSeconds, + ...(progress.songId ? { songId: progress.songId } : {}), + }) + } + + if (hasLegacyPlayback(user)) { + await ctx.db.patch(user._id, { + songQueue: undefined, + queueHistory: undefined, + currentSongProgress: undefined, + playbackRevision: undefined, + shuffleEnabled: undefined, + repeatEnabled: undefined, + }) + } + + return state +} + +/** Loads the queue in a mutation, migrating the user first if needed. */ +export async function loadPlaybackForWrite( + ctx: MutationCtx, + userId: Id<"users"> +) { + const doc = await stateDoc(ctx, userId) + if (doc) { + return doc + } + const user = await ctx.db.get(userId) + if (!user) { + return null + } + return await migrateUserPlayback(ctx, user) +} + +/** Applies `patch`, bumps the revision, and returns the new revision. */ +export async function writePlayback( + ctx: MutationCtx, + userId: Id<"users">, + patch: PlaybackPatch +): Promise { + const doc = await loadPlaybackForWrite(ctx, userId) + if (!doc) { + throw new ConvexError("User not found") + } + + const { progressSeconds, ...fields } = patch + const revision = doc.revision + 1 + const songQueue = fields.songQueue?.slice(0, MAX_QUEUE_LENGTH) + const queueHistory = fields.queueHistory?.slice(-MAX_QUEUE_HISTORY) + await ctx.db.patch(doc._id, { + ...fields, + ...(songQueue ? { songQueue } : {}), + ...(queueHistory ? { queueHistory } : {}), + revision, + }) + + if (progressSeconds !== undefined) { + await writeProgress(ctx, userId, { + songId: (songQueue ?? doc.songQueue)[0] ?? null, + progressSeconds, + }) + } + return revision +} + +export async function writeProgress( + ctx: MutationCtx, + userId: Id<"users">, + progress: PlaybackProgress +) { + const value = { + songId: progress.songId ?? undefined, + progressSeconds: Math.max(0, Math.floor(progress.progressSeconds)), + } + const doc = await progressDoc(ctx, userId) + if (!doc) { + await ctx.db.insert("playbackProgress", { userId, ...value }) + } else if ( + doc.songId !== value.songId || + doc.progressSeconds !== value.progressSeconds + ) { + await ctx.db.patch(doc._id, value) + } +} + +export async function deleteUserPlayback( + ctx: MutationCtx, + userId: Id<"users"> +) { + const [state, progress] = await Promise.all([ + stateDoc(ctx, userId), + progressDoc(ctx, userId), + ]) + if (state) { + await ctx.db.delete(state._id) + } + if (progress) { + await ctx.db.delete(progress._id) + } +} diff --git a/packages/convex/convex/schema.ts b/packages/convex/convex/schema.ts index af46208..d48d4c7 100644 --- a/packages/convex/convex/schema.ts +++ b/packages/convex/convex/schema.ts @@ -2,11 +2,19 @@ import { defineSchema, defineTable } from "convex/server" import { v } from "convex/values" import { authTables } from "@convex-dev/auth/server" +const repeatModeValidator = v.union( + v.literal("always"), + v.literal("once"), + v.literal("none") +) + export default defineSchema({ ...authTables, users: defineTable({ name: v.string(), + /** Legacy base64 data URL; `migrations.migrateUsers` moves it to storage. */ image: v.optional(v.string()), + imageStorageId: v.optional(v.id("_storage")), email: v.string(), isAdmin: v.optional(v.boolean()), playbackQuality: v.optional( @@ -22,18 +30,34 @@ export default defineSchema({ favoriteArtists: v.optional(v.array(v.id("artists"))), favoriteAlbums: v.optional(v.array(v.id("albums"))), favoriteSongs: v.optional(v.array(v.id("songs"))), - songQueue: v.optional(v.array(v.id("songs"))), - queueHistory: v.optional(v.array(v.id("songs"))), recentlyPlayed: v.optional( v.array(v.union(v.id("playlists"), v.id("albums"))) ), + // Legacy playback fields, now in `playbackStates` and `playbackProgress`. + // `migrations.migrateUsers` clears them; drop them once every deployment + // has run it. + songQueue: v.optional(v.array(v.id("songs"))), + queueHistory: v.optional(v.array(v.id("songs"))), currentSongProgress: v.optional(v.number()), playbackRevision: v.optional(v.number()), shuffleEnabled: v.optional(v.boolean()), - repeatEnabled: v.optional( - v.union(v.literal("always"), v.literal("once"), v.literal("none")) - ), + repeatEnabled: v.optional(repeatModeValidator), }).index("email", ["email"]), + playbackStates: defineTable({ + userId: v.id("users"), + songQueue: v.array(v.id("songs")), + queueHistory: v.array(v.id("songs")), + shuffleEnabled: v.boolean(), + repeatEnabled: repeatModeValidator, + revision: v.number(), + }).index("by_user", ["userId"]), + // Saved every few seconds during playback, so it lives apart from the queue + // to keep those writes from rerunning queue queries. + playbackProgress: defineTable({ + userId: v.id("users"), + songId: v.optional(v.id("songs")), + progressSeconds: v.number(), + }).index("by_user", ["userId"]), authVerifiers: defineTable({ sessionId: v.optional(v.id("authSessions")), signature: v.optional(v.string()), diff --git a/packages/convex/convex/users.ts b/packages/convex/convex/users.ts index 8836f81..35957b6 100644 --- a/packages/convex/convex/users.ts +++ b/packages/convex/convex/users.ts @@ -5,9 +5,18 @@ import { } from "@convex-dev/auth/server" import { ConvexError, v } from "convex/values" import { api, internal } from "./_generated/api" -import { action, internalQuery, mutation, query } from "./_generated/server" -import type { Id } from "./_generated/dataModel" +import { + action, + internalAction, + internalMutation, + internalQuery, + mutation, + query, +} from "./_generated/server" +import type { Doc, Id } from "./_generated/dataModel" import type { ActionCtx, MutationCtx } from "./_generated/server" +import { MAX_PROFILE_IMAGE_BYTES } from "./limits" +import { deleteUserPlayback } from "./playbackState" const playbackQualityValidator = v.union( v.literal("low"), @@ -178,18 +187,114 @@ export const listUsers = query({ }, }) +const DATA_URL_PATTERN = /^data:(image\/[\w.+-]+);base64,([A-Za-z0-9+/=]+)$/ + +/** Splits an image data URL, rejecting anything over the size cap. */ +function parseImageDataUrl(image: string) { + const match = DATA_URL_PATTERN.exec(image) + if (!match) { + throw new ConvexError("Profile photo must be an image") + } + const [, contentType, base64] = match + if (Math.floor((base64.length * 3) / 4) > MAX_PROFILE_IMAGE_BYTES) { + throw new ConvexError( + `Profile photo must be ${MAX_PROFILE_IMAGE_BYTES / 1024 / 1024} MB or smaller` + ) + } + return { contentType, base64 } +} + +/** + * Path clients load the avatar from. The web server proxies it from Convex + * storage, since the backend's storage URLs are not reachable from browsers + * in every deployment. Legacy data URLs are returned as is until migrated. + */ +export function profileImagePath(user: Doc<"users">) { + if (user.imageStorageId) { + return `/api/user/${user._id}/avatar?v=${user.imageStorageId}` + } + return user.image +} + +/** + * Takes a data URL so existing clients keep working. The image is moved into + * file storage in the background; `currentUser` updates once it lands. + */ export const updateProfileImage = mutation({ args: { image: v.union(v.string(), v.null()), }, handler: async (ctx, { image }) => { const userId = await requireAuth(ctx) - await ctx.db.patch(userId, { - image: image === null ? undefined : image, + if (image === null) { + await setProfileImage(ctx, userId, null) + return + } + parseImageDataUrl(image) + await ctx.scheduler.runAfter(0, internal.users.storeProfileImage, { + userId, + image, }) }, }) +/** Decodes a data URL into file storage and points the user at it. */ +export const storeProfileImage = internalAction({ + args: { userId: v.id("users"), image: v.string() }, + handler: async (ctx, { userId, image }) => { + const { contentType, base64 } = parseImageDataUrl(image) + const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0)) + const storageId = await ctx.storage.store( + new Blob([bytes], { type: contentType }) + ) + await ctx.runMutation(internal.users.attachProfileImage, { + userId, + storageId, + }) + }, +}) + +export const attachProfileImage = internalMutation({ + args: { userId: v.id("users"), storageId: v.id("_storage") }, + handler: async (ctx, { userId, storageId }) => { + await setProfileImage(ctx, userId, storageId) + }, +}) + +/** Replaces the avatar, deleting the previous file. Clears it for `null`. */ +async function setProfileImage( + ctx: MutationCtx, + userId: Id<"users">, + storageId: Id<"_storage"> | null +) { + const user = await ctx.db.get(userId) + if (!user) { + if (storageId) { + await ctx.storage.delete(storageId) + } + return + } + if (user.imageStorageId && user.imageStorageId !== storageId) { + await ctx.storage.delete(user.imageStorageId) + } + await ctx.db.patch(userId, { + image: undefined, + imageStorageId: storageId ?? undefined, + }) +} + +/** Storage URL behind `profileImagePath`, for the web server's proxy route. */ +export const getProfileImageUrl = query({ + args: { userId: v.id("users") }, + handler: async (ctx, { userId }) => { + const user = await ctx.db.get(userId) + if (!user?.imageStorageId) { + return null + } + return await ctx.storage.getUrl(user.imageStorageId) + }, +}) + export const updateProfileName = mutation({ args: { name: v.string() }, handler: async (ctx, { name }) => { @@ -294,6 +399,8 @@ export const deleteUser = mutation({ throw new ConvexError("You cannot delete your own account") } await deleteOwnedPlaylists(ctx, userId) + await deleteUserPlayback(ctx, userId) + await setProfileImage(ctx, userId, null) await deleteUserAuthData(ctx, userId) }, })