From ddc43a9286438030794d8a3b64c4c8eb8535d606 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 22:00:48 -0500 Subject: [PATCH] refactor: share logic duplicated across web, mobile, and Convex (#103) --- .../app/(app)/(tabs)/home/album/[id].tsx | 20 +-- .../mobile/app/(app)/(tabs)/home/settings.tsx | 6 +- apps/mobile/app/(app)/player.tsx | 4 +- apps/mobile/components/audio-format-badge.tsx | 44 +++--- .../mobile/components/playlist-search-bar.tsx | 14 +- apps/mobile/contexts/favorites.tsx | 104 ++----------- apps/mobile/contexts/persistent-cache.tsx | 16 +- apps/mobile/hooks/use-native-playlist-sync.ts | 12 +- apps/mobile/lib/media-links.ts | 45 +----- apps/mobile/lib/playback-capabilities.ts | 5 + apps/mobile/lib/song-cache.ts | 8 +- apps/mobile/lib/urls.ts | 44 ++---- apps/web/app/api/song/[id]/play/route.ts | 41 ++--- apps/web/components/album-view.tsx | 22 +-- apps/web/components/audio-format-badge.tsx | 45 +++--- apps/web/components/favorites-provider.tsx | 145 +++++++----------- apps/web/components/media-context-menu.tsx | 14 +- apps/web/components/options-modal.tsx | 3 +- .../components/persistent-cache-provider.tsx | 16 +- apps/web/components/playback-provider.tsx | 12 +- apps/web/components/playlist-view.tsx | 18 +-- apps/web/lib/media-links.ts | 64 ++------ apps/web/lib/server-hls.ts | 43 ++---- apps/web/lib/song-cache.ts | 26 +++- apps/web/lib/song-play-url.ts | 33 ---- packages/convex/client/audio-format-marks.ts | 30 ++++ packages/convex/client/auth-token.ts | 15 ++ packages/convex/client/favorites.ts | 96 ++++++++++++ packages/convex/client/media-links.ts | 34 ++++ packages/convex/client/playback-queue.ts | 7 +- packages/convex/client/song-cache.ts | 13 ++ packages/convex/client/song-search.ts | 21 +++ packages/convex/convex/playbackState.ts | 3 +- packages/convex/package.json | 20 +++ packages/convex/playback-stream.ts | 67 +++++++- 35 files changed, 529 insertions(+), 581 deletions(-) delete mode 100644 apps/web/lib/song-play-url.ts create mode 100644 packages/convex/client/audio-format-marks.ts create mode 100644 packages/convex/client/auth-token.ts create mode 100644 packages/convex/client/favorites.ts create mode 100644 packages/convex/client/media-links.ts create mode 100644 packages/convex/client/song-search.ts diff --git a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx index 66a7c26..39683c0 100644 --- a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx @@ -89,20 +89,6 @@ export default function AlbumScreen() { [album] ) - // Older servers do not include album format availability yet. - const formatTracks = useCachedQuery( - api.library.getSongsForPlayback, - album && (album.hasLossless === undefined || album.hasAtmos === undefined) - ? { ids: songIds } - : "skip" - ) - const hasLossless = - album?.hasLossless ?? - formatTracks?.some((track) => track && "lossless" in track.files) - const hasAtmos = - album?.hasAtmos ?? - formatTracks?.some((track) => track && "atmos" in track.files) - useEffect(() => { if (album) { rememberSongs(albumDetailSongs(album)) @@ -374,7 +360,7 @@ export default function AlbumScreen() { {metadata} ) : null} - {hasLossless ? ( + {album.hasLossless ? ( <> {metadata ? ( ) : null} - {hasAtmos ? ( + {album.hasAtmos ? ( <> - {metadata || hasLossless ? ( + {metadata || album.hasLossless ? ( void updateAtmos({ preferAtmos: checked }).catch((error: Error) => showError(error.message) diff --git a/apps/mobile/app/(app)/player.tsx b/apps/mobile/app/(app)/player.tsx index af25d25..57fda64 100644 --- a/apps/mobile/app/(app)/player.tsx +++ b/apps/mobile/app/(app)/player.tsx @@ -1,6 +1,6 @@ import { useTabletLayout } from "@/hooks/use-tablet-layout" import { TabletNowPlaying } from "@/components/tablet-now-playing" -import { dolbyAtmosSupported } from "@/lib/playback-capabilities" +import { atmosEnabled } from "@/lib/playback-capabilities" import { NavigationBar } from "expo-navigation-bar" import { MusicEntityView } from "@/components/music-entity-view" import { Stack, useRouter, useLocalSearchParams } from "expo-router" @@ -114,7 +114,7 @@ export default function PlayerScreen() { ? playbackFormat( playbackInfo.files, user.playbackQuality, - dolbyAtmosSupported && (user.preferAtmos ?? false) + atmosEnabled(user) ) : null diff --git a/apps/mobile/components/audio-format-badge.tsx b/apps/mobile/components/audio-format-badge.tsx index f2de453..c63decc 100644 --- a/apps/mobile/components/audio-format-badge.tsx +++ b/apps/mobile/components/audio-format-badge.tsx @@ -2,39 +2,33 @@ import { PaletteText } from "@/components/palette-text" import { StyleSheet, View } from "react-native" import Svg, { G, Path } from "react-native-svg" +import { + DOLBY_PATHS, + DOLBY_VIEW_BOX, + DOLBY_WIDTH, + LOSSLESS_FALL, + LOSSLESS_FALL_GAP, + LOSSLESS_PEAKS, + LOSSLESS_STROKES, + LOSSLESS_THIN_WIDTH, + LOSSLESS_VIEW_BOX, + LOSSLESS_WIDTH, + MARK_HEIGHT, +} from "@otunes/convex/client/audio-format-marks" import type { PlaybackFormat } from "@otunes/convex/playback-stream" const LABEL_SIZE = 13 -const MARK_HEIGHT = 11 function DolbyMark({ color }: { color: string }) { return ( - - - + + {DOLBY_PATHS.map((d) => ( + + ))} ) } -const LOSSLESS_PEAKS = [110, 215, 320] -const LOSSLESS_THIN_WIDTH = 24 -const LOSSLESS_STROKES: [peak: number, d: string][] = [ - [110, "M-70 320C-62 245 -38 166 0 166"], - [215, "M-70 320C-62 245 -38 166 0 166"], - [320, "M-30 185C-22 173 -11 166 0 166"], - [110, "M166 413C176 413 186 406 194 395"], - [215, "M166 413C200 413 226 340 240 275"], - [320, "M166 413C200 413 226 340 240 275"], -] -const LOSSLESS_FALL = - "M0 178L4 179L8 181L12 184L16 189L20 196L23 204L27 213L30 223L34 233L39 243L43 254L48 266L53 278L58 289L62 301L66 313L71 325L75 336L79 347L83 357L86 364L89 370L93 377L97 382L101 387L105 392L109 397L113 401L117 405L121 408L126 412L130 415L134 417L139 419L143 421L148 423L152 424L157 424L161 425L166 425L166 401L163 401L161 400L159 400L157 399L154 397L152 396L151 394L149 392L147 389L145 386L143 383L142 380L140 376L138 371L137 367L135 362L134 357L132 351L130 345L127 339L124 330L120 319L116 308L111 297L107 285L102 272L98 260L93 248L88 235L82 223L76 212L69 201L61 192L53 183L45 175L37 168L28 163L19 158L10 155L0 154Z" -const LOSSLESS_FALL_GAP = - "M0 178L4 180L6 184L8 190L9 197L11 203L14 210L17 219L21 228L24 238L29 248L33 259L38 270L43 282L47 293L52 305L56 317L60 328L64 340L68 351L73 361L76 368L79 375L83 381L87 387L91 393L95 398L100 403L104 408L109 412L113 416L118 419L124 422L130 424L135 425L141 426L147 426L152 426L157 425L161 425L166 425L166 401L163 401L161 399L159 398L158 395L157 393L156 390L155 387L155 384L154 381L153 379L152 376L150 373L149 369L148 366L146 361L145 357L143 352L142 347L140 341L137 335L134 326L130 315L126 304L122 293L117 281L113 268L108 256L103 243L98 231L92 219L86 207L79 196L71 186L62 177L53 168L44 161L32 157L21 155L10 154L0 154Z" - /** * Three overlapping waves. Each thick downstroke is outlined in the * background color so it reads as passing over the strokes behind it. @@ -48,9 +42,9 @@ function LosslessMark({ }) { return ( {LOSSLESS_STROKES.map(([peak, d], index) => ( { - const query = search.searchQuery.toLowerCase() - if (!query) return songs - return songs.filter((song) => - [song.title, song.artist.name, song.album.title].some((value) => - value.toLowerCase().includes(query) - ) - ) - }, [songs, search.searchQuery]) + const filteredSongs = useMemo( + () => filterSongs(songs, search.searchQuery), + [songs, search.searchQuery] + ) return { ...search, filteredSongs } } diff --git a/apps/mobile/contexts/favorites.tsx b/apps/mobile/contexts/favorites.tsx index 4b8223d..4befb5b 100644 --- a/apps/mobile/contexts/favorites.tsx +++ b/apps/mobile/contexts/favorites.tsx @@ -12,20 +12,23 @@ import { import { useCachedQuery } from "@/hooks/use-cached-query" import { api } from "@otunes/convex/_generated/api" +import { favoriteOptimisticUpdates } from "@otunes/convex/client/favorites" import type { Id } from "@otunes/convex/_generated/dataModel" import { showError } from "@/lib/toast" /** - * `useMutation(...).withOptimisticUpdate(...)` with a stable identity. The - * update is captured on first render, so it must not close over render state. + * `useMutation(...).withOptimisticUpdate(...)` with a stable identity. Pass a + * module-level update so it does not change between renders. */ function useOptimisticMutation>( mutation: Mutation, optimisticUpdate: OptimisticUpdate> ): ReactMutation { const base = useMutation(mutation) - const updateRef = useRef(optimisticUpdate) - return useMemo(() => base.withOptimisticUpdate(updateRef.current), [base]) + return useMemo( + () => base.withOptimisticUpdate(optimisticUpdate), + [base, optimisticUpdate] + ) } type FavoriteTables = { song: "songs"; album: "albums"; artist: "artists" } @@ -69,110 +72,31 @@ export function FavoritesProvider({ children }: { children: ReactNode }) { const favorites = useCachedQuery(api.favorites.getUserFavorites) const favoriteSong = useOptimisticMutation( api.favorites.favoriteSong, - (store, { songId }) => { - const current = store.getQuery(api.favorites.getUserFavorites, {}) - if (!current || current.favoriteSongs.includes(songId)) return - store.setQuery( - api.favorites.getUserFavorites, - {}, - { - ...current, - favoriteSongs: [...current.favoriteSongs, songId], - } - ) - } + favoriteOptimisticUpdates.favoriteSong ) const unfavoriteSong = useOptimisticMutation( api.favorites.unfavoriteSong, - (store, { songId }) => { - const current = store.getQuery(api.favorites.getUserFavorites, {}) - if (!current) return - store.setQuery( - api.favorites.getUserFavorites, - {}, - { - ...current, - favoriteSongs: current.favoriteSongs.filter((id) => id !== songId), - } - ) - } + favoriteOptimisticUpdates.unfavoriteSong ) const favoriteAlbum = useOptimisticMutation( api.favorites.favoriteAlbum, - (store, { albumId }) => { - const current = store.getQuery(api.favorites.getUserFavorites, {}) - if (!current || current.favoriteAlbums.includes(albumId)) return - store.setQuery( - api.favorites.getUserFavorites, - {}, - { - ...current, - favoriteAlbums: [...current.favoriteAlbums, albumId], - } - ) - } + favoriteOptimisticUpdates.favoriteAlbum ) const unfavoriteAlbum = useOptimisticMutation( api.favorites.unfavoriteAlbum, - (store, { albumId }) => { - const current = store.getQuery(api.favorites.getUserFavorites, {}) - if (!current) return - store.setQuery( - api.favorites.getUserFavorites, - {}, - { - ...current, - favoriteAlbums: current.favoriteAlbums.filter((id) => id !== albumId), - } - ) - } + favoriteOptimisticUpdates.unfavoriteAlbum ) const favoriteArtist = useOptimisticMutation( api.favorites.favoriteArtist, - (store, { artistId }) => { - const current = store.getQuery(api.favorites.getUserFavorites, {}) - if (!current || current.favoriteArtists.includes(artistId)) return - store.setQuery( - api.favorites.getUserFavorites, - {}, - { - ...current, - favoriteArtists: [...current.favoriteArtists, artistId], - } - ) - } + favoriteOptimisticUpdates.favoriteArtist ) const unfavoriteArtist = useOptimisticMutation( api.favorites.unfavoriteArtist, - (store, { artistId }) => { - const current = store.getQuery(api.favorites.getUserFavorites, {}) - if (!current) return - store.setQuery( - api.favorites.getUserFavorites, - {}, - { - ...current, - favoriteArtists: current.favoriteArtists.filter( - (id) => id !== artistId - ), - } - ) - } + favoriteOptimisticUpdates.unfavoriteArtist ) const favoriteSongsMutation = useOptimisticMutation( api.favorites.favoriteSongs, - (store, { songIds }) => { - const current = store.getQuery(api.favorites.getUserFavorites, {}) - if (!current) return - store.setQuery( - api.favorites.getUserFavorites, - {}, - { - ...current, - favoriteSongs: [...new Set([...current.favoriteSongs, ...songIds])], - } - ) - } + favoriteOptimisticUpdates.favoriteSongs ) const songIds = useMemo( diff --git a/apps/mobile/contexts/persistent-cache.tsx b/apps/mobile/contexts/persistent-cache.tsx index d3fec57..902f4aa 100644 --- a/apps/mobile/contexts/persistent-cache.tsx +++ b/apps/mobile/contexts/persistent-cache.tsx @@ -1,4 +1,5 @@ import { useAuthToken } from "@convex-dev/auth/react" +import { userIdFromToken } from "@otunes/convex/client/auth-token" import { createContext, useContext, useMemo, type ReactNode } from "react" import { loadPersistentCache } from "@/lib/persistent-cache" @@ -9,21 +10,6 @@ const CacheScopeContext = createContext(ANONYMOUS_CACHE_SCOPE) void loadPersistentCache() -function userIdFromToken(token: string | null) { - const payload = token?.split(".")[1] - if (!payload) { - return null - } - - try { - const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/")) - const subject = (JSON.parse(json) as { sub?: unknown }).sub - return typeof subject === "string" ? (subject.split("|")[0] ?? null) : null - } catch { - return null - } -} - /** Namespaces persisted client data by server and signed-in user. */ export function PersistentCacheProvider({ serverUrl, diff --git a/apps/mobile/hooks/use-native-playlist-sync.ts b/apps/mobile/hooks/use-native-playlist-sync.ts index dc07c9b..ff8e8d2 100644 --- a/apps/mobile/hooks/use-native-playlist-sync.ts +++ b/apps/mobile/hooks/use-native-playlist-sync.ts @@ -1,4 +1,4 @@ -import { dolbyAtmosSupported } from "@/lib/playback-capabilities" +import { atmosEnabled } from "@/lib/playback-capabilities" import { createAudioPlaylist, setAudioModeAsync, @@ -132,11 +132,7 @@ export function useNativePlaylistSync({ ]) : "" const userPlaybackKey = user - ? JSON.stringify([ - user._id, - user.playbackQuality, - dolbyAtmosSupported && (user.preferAtmos ?? false), - ]) + ? JSON.stringify([user._id, user.playbackQuality, atmosEnabled(user)]) : "" const settleWaiters = useCallback(() => { @@ -462,7 +458,7 @@ export function useNativePlaylistSync({ } if (!isCurrentLoad()) return - const loadKey = `${user.playbackQuality}:${dolbyAtmosSupported && (user.preferAtmos ?? false)}:${cookieHeader}` + const loadKey = `${user.playbackQuality}:${atmosEnabled(user)}:${cookieHeader}` const needsRebuild = loadedLoadKeyRef.current !== loadKey || nativePlaylistNeedsRebuild( @@ -503,7 +499,7 @@ export function useNativePlaylistSync({ const plan = playbackStreamPlan( song.files, user.playbackQuality, - dolbyAtmosSupported && (user.preferAtmos ?? false) + atmosEnabled(user) ) sources.set( song.id, diff --git a/apps/mobile/lib/media-links.ts b/apps/mobile/lib/media-links.ts index d04d8b3..ce479a1 100644 --- a/apps/mobile/lib/media-links.ts +++ b/apps/mobile/lib/media-links.ts @@ -1,40 +1,9 @@ -export type MediaShareContext = ( - | { type: "album"; albumId: string } - | { type: "song"; albumId: string; songId: string } - | { type: "playlist"; playlistId: string; isFavorites?: boolean } - | { type: "artist"; artistId: string } -) & { title: string } +import type { MediaShareTarget } from "@otunes/convex/client/media-links" -export function shouldShowShare( - share: MediaShareContext | undefined, - selectedCount: number -) { - if (!share) { - return false - } - if (share.type === "song") { - return selectedCount === 1 - } - return true -} +export { + mediaShareUrl, + shouldShowShare, +} from "@otunes/convex/client/media-links" -export function mediaShareUrl( - serverUrl: string, - share: MediaShareContext -): string { - const origin = serverUrl.replace(/\/+$/, "") - - switch (share.type) { - case "album": - return `${origin}/album/${share.albumId}` - case "song": - return `${origin}/album/${share.albumId}?s=${share.songId}` - case "playlist": - if (share.isFavorites) { - return `${origin}/playlist/favorites` - } - return `${origin}/playlist/${share.playlistId}` - case "artist": - return `${origin}/artist/${share.artistId}` - } -} +/** A share target plus the title shown in the native share sheet. */ +export type MediaShareContext = MediaShareTarget & { title: string } diff --git a/apps/mobile/lib/playback-capabilities.ts b/apps/mobile/lib/playback-capabilities.ts index fbab2a9..9f4bd14 100644 --- a/apps/mobile/lib/playback-capabilities.ts +++ b/apps/mobile/lib/playback-capabilities.ts @@ -2,3 +2,8 @@ import { Platform } from "react-native" // Android Dolby decoder reports do not reliably indicate working Atmos playback. export const dolbyAtmosSupported = Platform.OS === "ios" + +/** Whether to stream Atmos for this user: they opted in and the device can play it. */ +export function atmosEnabled(user: { preferAtmos?: boolean }) { + return dolbyAtmosSupported && (user.preferAtmos ?? false) +} diff --git a/apps/mobile/lib/song-cache.ts b/apps/mobile/lib/song-cache.ts index 36203e8..d12e713 100644 --- a/apps/mobile/lib/song-cache.ts +++ b/apps/mobile/lib/song-cache.ts @@ -5,8 +5,10 @@ import type { Id } from "@otunes/convex/_generated/dataModel" import type { BrowseSong } from "@otunes/convex/types" import { getCachedSong, + getSongSnapshot, getSongsVersion, requestSongs, + songFromSnapshot, subscribeSongs, } from "@otunes/convex/client/song-cache" import { isPersistentCacheLoaded } from "@/lib/persistent-cache" @@ -50,12 +52,10 @@ export function useSongs(songIds: readonly Id<"songs">[]) { */ export function useSong(songId: Id<"songs"> | null): BrowseSong | null { const convex = useConvex() - // While the song is missing the snapshot is the cache version, so every - // cache change re-renders and retries the fetch below. const snapshot = useSyncExternalStore(subscribeSongs, () => - songId ? (getCachedSong(songId) ?? getSongsVersion()) : null + getSongSnapshot(songId) ) - const song = typeof snapshot === "object" ? snapshot : null + const song = songFromSnapshot(snapshot) useEffect(() => { if (songId && !song && isPersistentCacheLoaded()) { diff --git a/apps/mobile/lib/urls.ts b/apps/mobile/lib/urls.ts index 3cedc74..fff6f82 100644 --- a/apps/mobile/lib/urls.ts +++ b/apps/mobile/lib/urls.ts @@ -1,9 +1,11 @@ -import { dolbyAtmosSupported } from "@/lib/playback-capabilities" +import { + type PlaybackQuality, + songHlsPlaylistPath, + songPlayPath, +} from "@otunes/convex/playback-stream" import { Platform } from "react-native" import type { AudioSource } from "expo-audio" -export type PlaybackQuality = "low" | "medium" | "high" | "lossless" - export const coverImageSizes = [64, 128, 192, 256, 384, 512, 768, 1024] as const export type CoverImageSize = (typeof coverImageSizes)[number] @@ -45,33 +47,6 @@ export function playlistCoverUrl( return sizedCoverUrl(`${serverUrl}/api/playlist/${playlistId}/cover`, size) } -export function songPlayUrl( - serverUrl: string, - songId: string, - quality: PlaybackQuality | undefined, - preferAtmos: boolean | undefined -) { - const params = new URLSearchParams() - if (Platform.OS === "ios") params.set("losslessFormat", "alac") - if (quality) params.set("quality", quality) - if (dolbyAtmosSupported && preferAtmos) params.set("preferAtmos", "true") - const query = params.toString() - return `${serverUrl}/api/song/${songId}/play${query ? `?${query}` : ""}` -} - -export function songHlsPlaylistUrl( - serverUrl: string, - songId: string, - quality: PlaybackQuality | undefined, - preferAtmos: boolean | undefined -) { - const params = new URLSearchParams() - if (quality) params.set("quality", quality) - if (dolbyAtmosSupported && preferAtmos) params.set("preferAtmos", "true") - const query = params.toString() - return `${serverUrl}/api/song/${songId}/play/hls${query ? `?${query}` : ""}` -} - export function songAudioSource( serverUrl: string, songId: string, @@ -80,9 +55,12 @@ export function songAudioSource( useHls: boolean, options?: { cookieHeader?: string | null; songTitle?: string } ): AudioSource { - const uri = useHls - ? songHlsPlaylistUrl(serverUrl, songId, quality, preferAtmos) - : songPlayUrl(serverUrl, songId, quality, preferAtmos) + const path = useHls + ? songHlsPlaylistPath(songId, quality, preferAtmos) + : songPlayPath(songId, quality, preferAtmos, { + losslessFormat: Platform.OS === "ios" ? "alac" : undefined, + }) + const uri = `${serverUrl}${path}` const headers = options?.cookieHeader ? { Cookie: options.cookieHeader } diff --git a/apps/web/app/api/song/[id]/play/route.ts b/apps/web/app/api/song/[id]/play/route.ts index b757658..d1f7bac 100644 --- a/apps/web/app/api/song/[id]/play/route.ts +++ b/apps/web/app/api/song/[id]/play/route.ts @@ -1,3 +1,7 @@ +import { + parsePlaybackQuality, + playbackStreamPlan, +} from "@otunes/convex/playback-stream" import { audioContentTypeForPath } from "@/lib/audio-content-type" import { seekableLosslessFile } from "@/lib/server-lossless" import { getSongSource } from "@/lib/server-song" @@ -118,34 +122,17 @@ export async function GET( try { const song = await getSongSource(id) - const quality = request.nextUrl.searchParams.get("quality") as - "low" | "medium" | "high" | "lossless" | null - - const preferAtmos = + const { + source: originalCodec, + kbps, + transcodeNeeded, + } = playbackStreamPlan( + song.files, + // Without a quality, serve the original file as this route always has. + parsePlaybackQuality(request.nextUrl.searchParams.get("quality")) ?? + "lossless", request.nextUrl.searchParams.get("preferAtmos") === "true" - - let kbps = 0 - if (quality === "low") { - kbps = 64 - } else if (quality === "medium") { - kbps = 128 - } else if (quality === "high") { - kbps = 256 - } - - let originalCodec = "lossless" in song.files ? "lossless" : "normal" - - let transcodeNeeded = true - if (preferAtmos && "atmos" in song.files) { - originalCodec = "atmos" - transcodeNeeded = false - } else if (kbps === 0 && "lossless" in song.files) { - originalCodec = "lossless" - transcodeNeeded = false - } else if (kbps === 0 || (kbps === 256 && "normal" in song.files)) { - originalCodec = "normal" - transcodeNeeded = false - } + ) if (!transcodeNeeded && originalCodec === "lossless") { // Native iOS playback does not identify itself as Safari. diff --git a/apps/web/components/album-view.tsx b/apps/web/components/album-view.tsx index e18b273..5fe12fd 100644 --- a/apps/web/components/album-view.tsx +++ b/apps/web/components/album-view.tsx @@ -24,8 +24,6 @@ import { import { TrackRow } from "@/components/track-row" import { Button } from "@/components/ui/button" import { ScrollArea } from "@/components/ui/scroll-area" -import { useCachedQuery } from "@/hooks/use-cached-query" -import { api } from "@otunes/convex/_generated/api" import { useMediaActions, useTrackListMediaAction, @@ -116,20 +114,6 @@ export function AlbumView({ [album.tracks] ) - // Older servers do not include album format availability yet. - const formatTracks = useCachedQuery( - api.library.getSongsForPlayback, - album.hasLossless === undefined || album.hasAtmos === undefined - ? { ids: albumSongIds } - : "skip" - ) - const hasLossless = - album.hasLossless ?? - formatTracks?.some((track) => track && "lossless" in track.files) - const hasAtmos = - album.hasAtmos ?? - formatTracks?.some((track) => track && "atmos" in track.files) - React.useEffect(() => { rememberSongs(albumDetailSongs(album)) }, [album]) @@ -260,15 +244,15 @@ export function AlbumView({
{metadata ? {metadata} : null} - {hasLossless ? ( + {album.hasLossless ? ( <> {metadata ? · : null} ) : null} - {hasAtmos ? ( + {album.hasAtmos ? ( <> - {metadata || hasLossless ? ( + {metadata || album.hasLossless ? ( · ) : null} diff --git a/apps/web/components/audio-format-badge.tsx b/apps/web/components/audio-format-badge.tsx index e5137dd..3425c3b 100644 --- a/apps/web/components/audio-format-badge.tsx +++ b/apps/web/components/audio-format-badge.tsx @@ -1,35 +1,28 @@ +import { + DOLBY_PATHS, + DOLBY_VIEW_BOX, + DOLBY_WIDTH, + LOSSLESS_FALL, + LOSSLESS_FALL_GAP, + LOSSLESS_PEAKS, + LOSSLESS_STROKES, + LOSSLESS_THIN_WIDTH, + LOSSLESS_VIEW_BOX, + LOSSLESS_WIDTH, + MARK_HEIGHT, +} from "@otunes/convex/client/audio-format-marks" import type { PlaybackFormat } from "@otunes/convex/playback-stream" -const MARK_HEIGHT = 11 - function DolbyMark({ color }: { color: string }) { return ( - - - + + {DOLBY_PATHS.map((d) => ( + + ))} ) } -const LOSSLESS_PEAKS = [110, 215, 320] -const LOSSLESS_THIN_WIDTH = 24 -const LOSSLESS_STROKES: [peak: number, d: string][] = [ - [110, "M-70 320C-62 245 -38 166 0 166"], - [215, "M-70 320C-62 245 -38 166 0 166"], - [320, "M-30 185C-22 173 -11 166 0 166"], - [110, "M166 413C176 413 186 406 194 395"], - [215, "M166 413C200 413 226 340 240 275"], - [320, "M166 413C200 413 226 340 240 275"], -] -const LOSSLESS_FALL = - "M0 178L4 179L8 181L12 184L16 189L20 196L23 204L27 213L30 223L34 233L39 243L43 254L48 266L53 278L58 289L62 301L66 313L71 325L75 336L79 347L83 357L86 364L89 370L93 377L97 382L101 387L105 392L109 397L113 401L117 405L121 408L126 412L130 415L134 417L139 419L143 421L148 423L152 424L157 424L161 425L166 425L166 401L163 401L161 400L159 400L157 399L154 397L152 396L151 394L149 392L147 389L145 386L143 383L142 380L140 376L138 371L137 367L135 362L134 357L132 351L130 345L127 339L124 330L120 319L116 308L111 297L107 285L102 272L98 260L93 248L88 235L82 223L76 212L69 201L61 192L53 183L45 175L37 168L28 163L19 158L10 155L0 154Z" -const LOSSLESS_FALL_GAP = - "M0 178L4 180L6 184L8 190L9 197L11 203L14 210L17 219L21 228L24 238L29 248L33 259L38 270L43 282L47 293L52 305L56 317L60 328L64 340L68 351L73 361L76 368L79 375L83 381L87 387L91 393L95 398L100 403L104 408L109 412L113 416L118 419L124 422L130 424L135 425L141 426L147 426L152 426L157 425L161 425L166 425L166 401L163 401L161 399L159 398L158 395L157 393L156 390L155 387L155 384L154 381L153 379L152 376L150 373L149 369L148 366L146 361L145 357L143 352L142 347L140 341L137 335L134 326L130 315L126 304L122 293L117 281L113 268L108 256L103 243L98 231L92 219L86 207L79 196L71 186L62 177L53 168L44 161L32 157L21 155L10 154L0 154Z" - /** * Three overlapping waves. Each thick downstroke is outlined in the * background color so it reads as passing over the strokes behind it. @@ -43,9 +36,9 @@ function LosslessMark({ }) { return ( {LOSSLESS_STROKES.map(([peak, d], index) => ( >( + mutation: Mutation, + optimisticUpdate: OptimisticUpdate> +): ReactMutation { + const base = useMutation(mutation) + return React.useMemo( + () => base.withOptimisticUpdate(optimisticUpdate), + [base, optimisticUpdate] + ) +} + type FavoritesContextValue = { isSongFavorite: (songId: string) => boolean isAlbumFavorite: (albumId: string) => boolean @@ -34,97 +52,38 @@ export function useFavorites() { export function FavoritesProvider({ children }: { children: React.ReactNode }) { const favorites = useCachedQuery(api.favorites.getUserFavorites) - const favoriteSong = useMutation(api.favorites.favoriteSong).withOptimisticUpdate( - (store, { songId }) => { - const current = store.getQuery(api.favorites.getUserFavorites, {}) - if (current && !current.favoriteSongs.includes(songId)) { - store.setQuery(api.favorites.getUserFavorites, {}, { - ...current, - favoriteSongs: [...current.favoriteSongs, songId], - }) - } - } + const favoriteSong = useOptimisticMutation( + api.favorites.favoriteSong, + favoriteOptimisticUpdates.favoriteSong + ) + const favoriteSongsMutation = useOptimisticMutation( + api.favorites.favoriteSongs, + favoriteOptimisticUpdates.favoriteSongs + ) + const unfavoriteSong = useOptimisticMutation( + api.favorites.unfavoriteSong, + favoriteOptimisticUpdates.unfavoriteSong + ) + const unfavoriteSongs = useOptimisticMutation( + api.favorites.unfavoriteSongs, + favoriteOptimisticUpdates.unfavoriteSongs + ) + const favoriteAlbum = useOptimisticMutation( + api.favorites.favoriteAlbum, + favoriteOptimisticUpdates.favoriteAlbum + ) + const unfavoriteAlbum = useOptimisticMutation( + api.favorites.unfavoriteAlbum, + favoriteOptimisticUpdates.unfavoriteAlbum + ) + const favoriteArtist = useOptimisticMutation( + api.favorites.favoriteArtist, + favoriteOptimisticUpdates.favoriteArtist + ) + const unfavoriteArtist = useOptimisticMutation( + api.favorites.unfavoriteArtist, + favoriteOptimisticUpdates.unfavoriteArtist ) - const favoriteSongsMutation = useMutation( - api.favorites.favoriteSongs - ).withOptimisticUpdate((store, { songIds }) => { - const current = store.getQuery(api.favorites.getUserFavorites, {}) - if (current) { - store.setQuery(api.favorites.getUserFavorites, {}, { - ...current, - favoriteSongs: [...new Set([...current.favoriteSongs, ...songIds])], - }) - } - }) - const unfavoriteSong = useMutation( - api.favorites.unfavoriteSong - ).withOptimisticUpdate((store, { songId }) => { - const current = store.getQuery(api.favorites.getUserFavorites, {}) - if (current) { - store.setQuery(api.favorites.getUserFavorites, {}, { - ...current, - favoriteSongs: current.favoriteSongs.filter((id) => id !== songId), - }) - } - }) - const unfavoriteSongs = useMutation( - api.favorites.unfavoriteSongs - ).withOptimisticUpdate((store, { songIds }) => { - const current = store.getQuery(api.favorites.getUserFavorites, {}) - if (current) { - const removed = new Set(songIds) - store.setQuery(api.favorites.getUserFavorites, {}, { - ...current, - favoriteSongs: current.favoriteSongs.filter((id) => !removed.has(id)), - }) - } - }) - const favoriteAlbum = useMutation( - api.favorites.favoriteAlbum - ).withOptimisticUpdate((store, { albumId }) => { - const current = store.getQuery(api.favorites.getUserFavorites, {}) - if (current && !current.favoriteAlbums.includes(albumId)) { - store.setQuery(api.favorites.getUserFavorites, {}, { - ...current, - favoriteAlbums: [...current.favoriteAlbums, albumId], - }) - } - }) - const unfavoriteAlbum = useMutation( - api.favorites.unfavoriteAlbum - ).withOptimisticUpdate((store, { albumId }) => { - const current = store.getQuery(api.favorites.getUserFavorites, {}) - if (current) { - store.setQuery(api.favorites.getUserFavorites, {}, { - ...current, - favoriteAlbums: current.favoriteAlbums.filter((id) => id !== albumId), - }) - } - }) - const favoriteArtist = useMutation( - api.favorites.favoriteArtist - ).withOptimisticUpdate((store, { artistId }) => { - const current = store.getQuery(api.favorites.getUserFavorites, {}) - if (current && !current.favoriteArtists.includes(artistId)) { - store.setQuery(api.favorites.getUserFavorites, {}, { - ...current, - favoriteArtists: [...current.favoriteArtists, artistId], - }) - } - }) - const unfavoriteArtist = useMutation( - api.favorites.unfavoriteArtist - ).withOptimisticUpdate((store, { artistId }) => { - const current = store.getQuery(api.favorites.getUserFavorites, {}) - if (current) { - store.setQuery(api.favorites.getUserFavorites, {}, { - ...current, - favoriteArtists: current.favoriteArtists.filter( - (id) => id !== artistId - ), - }) - } - }) const songIds = React.useMemo( () => new Set(favorites?.favoriteSongs.map(String) ?? []), @@ -288,6 +247,8 @@ export function FavoritesProvider({ children }: { children: React.ReactNode }) { ) return ( - {children} + + {children} + ) } diff --git a/apps/web/components/media-context-menu.tsx b/apps/web/components/media-context-menu.tsx index 032dac0..f7d5346 100644 --- a/apps/web/components/media-context-menu.tsx +++ b/apps/web/components/media-context-menu.tsx @@ -30,6 +30,7 @@ import { DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" import { copyMediaShareLink, type MediaShareContext } from "@/lib/media-links" +import { shouldShowShare } from "@otunes/convex/client/media-links" import { cn } from "@/lib/utils" export type MediaContextAction = @@ -47,19 +48,6 @@ export type MediaContextNavigation = { export type { MediaShareContext } from "@/lib/media-links" -function shouldShowShare( - share: MediaShareContext | undefined, - selectedCount: number -) { - if (!share) { - return false - } - if (share.type === "song") { - return selectedCount === 1 - } - return true -} - // Lets the same items render inside a dropdown or a right-click menu. const MenuKindContext = React.createContext<"dropdown" | "context">("dropdown") diff --git a/apps/web/components/options-modal.tsx b/apps/web/components/options-modal.tsx index efe7f85..b71fad4 100644 --- a/apps/web/components/options-modal.tsx +++ b/apps/web/components/options-modal.tsx @@ -47,13 +47,12 @@ import { import { usePlayback } from "@/components/playback-provider" import { api } from "@otunes/convex/_generated/api" import type { Id } from "@otunes/convex/_generated/dataModel" +import type { PlaybackQuality } from "@otunes/convex/playback-stream" import { resizeProfileImageToDataUrl } from "@/lib/resize-profile-image" import { cn } from "@/lib/utils" type Section = "profile" | "quality" | "users" | "library" -type PlaybackQuality = "low" | "medium" | "high" | "lossless" - type CurrentUser = { _id: Id<"users"> name: string diff --git a/apps/web/components/persistent-cache-provider.tsx b/apps/web/components/persistent-cache-provider.tsx index f9aaea0..9d3b02f 100644 --- a/apps/web/components/persistent-cache-provider.tsx +++ b/apps/web/components/persistent-cache-provider.tsx @@ -1,6 +1,7 @@ "use client" import { useAuthToken } from "@convex-dev/auth/react" +import { userIdFromToken } from "@otunes/convex/client/auth-token" import { createContext, ReactNode, useContext, useEffect, useMemo } from "react" import { loadPersistentCache } from "@/lib/persistent-cache" @@ -13,21 +14,6 @@ if (typeof window !== "undefined") { void loadPersistentCache() } -function userIdFromToken(token: string | null) { - const payload = token?.split(".")[1] - if (!payload) { - return null - } - - try { - const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/")) - const subject = (JSON.parse(json) as { sub?: unknown }).sub - return typeof subject === "string" ? (subject.split("|")[0] ?? null) : null - } catch { - return null - } -} - /** Namespaces persisted client data by the signed-in user. */ export function PersistentCacheProvider({ children }: { children: ReactNode }) { const token = useAuthToken() diff --git a/apps/web/components/playback-provider.tsx b/apps/web/components/playback-provider.tsx index 02c9e08..77f98a7 100644 --- a/apps/web/components/playback-provider.tsx +++ b/apps/web/components/playback-provider.tsx @@ -22,7 +22,10 @@ import type { BrowseSong } from "@otunes/convex/types" import { playbackFormat, type PlaybackFormat, + type PlaybackQuality, playbackStreamPlan, + songHlsPlaylistPath, + songPlayPath, } from "@otunes/convex/playback-stream" import { ANONYMOUS_CACHE_SCOPE, @@ -40,7 +43,6 @@ import { getServerPlaybackSnapshot, } from "@otunes/convex/client/playback-store" import { rememberSongs, useSong } from "@/lib/song-cache" -import { songHlsPlaylistUrl, songPlayUrl } from "@/lib/song-play-url" const PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS = 5 const PROGRESS_SAVE_INTERVAL_MS = 5000 @@ -183,14 +185,14 @@ function readStoredVolume(): number { type PlaybackLoadSettings = { preferAtmos: boolean - playbackQuality: "low" | "medium" | "high" | "lossless" + playbackQuality: PlaybackQuality useHls: boolean } function playbackLoadSettings( user: { preferAtmos?: boolean - playbackQuality?: "low" | "medium" | "high" | "lossless" + playbackQuality?: PlaybackQuality }, dolbyAtmosSupported: boolean | null, files: Record @@ -245,12 +247,12 @@ function loadAudioSource( ): AudioSourceCleanup { let disposed = false let hlsInstance: Hls | null = null - const directUrl = songPlayUrl( + const directUrl = songPlayPath( songId, settings.playbackQuality, settings.preferAtmos ) - const hlsUrl = songHlsPlaylistUrl( + const hlsUrl = songHlsPlaylistPath( songId, settings.playbackQuality, settings.preferAtmos diff --git a/apps/web/components/playlist-view.tsx b/apps/web/components/playlist-view.tsx index 6889fd3..e1a2eb1 100644 --- a/apps/web/components/playlist-view.tsx +++ b/apps/web/components/playlist-view.tsx @@ -40,6 +40,7 @@ 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 { filterSongs } from "@otunes/convex/client/song-search" import { getSelectionRangePositions } from "@/lib/selection-range-styles" const ADD_TO_ANOTHER_PLAYLIST = "Add to Another Playlist" @@ -79,17 +80,10 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { ? playlist.songs.filter((song) => !hiddenFavoriteIds.has(song.id)) : playlistSongs const [searchQuery, setSearchQuery] = React.useState("") - const normalizedQuery = searchQuery.trim().toLowerCase() + const isSearching = searchQuery.trim() !== "" const filteredSongs = React.useMemo( - () => - normalizedQuery - ? songs.filter((song) => - [song.title, song.artist.name, song.album.title].some((value) => - value.toLowerCase().includes(normalizedQuery) - ) - ) - : songs, - [songs, normalizedQuery] + () => filterSongs(songs, searchQuery), + [songs, searchQuery] ) const playlistSongIds = React.useMemo( () => songs.map((song) => song.id as Id<"songs">), @@ -156,7 +150,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { runSongsAction(action, playlistSongIds) } - const canReorder = isOwner && !isFavorites && !normalizedQuery + const canReorder = isOwner && !isFavorites && !isSearching function handleRowSelect(index: number, event: React.MouseEvent) { const songId = filteredSongs[index].id @@ -470,7 +464,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { /> ) : (

- {normalizedQuery + {isSearching ? "No songs found." : "This playlist has no songs yet."}

diff --git a/apps/web/lib/media-links.ts b/apps/web/lib/media-links.ts index 009f065..cb112c8 100644 --- a/apps/web/lib/media-links.ts +++ b/apps/web/lib/media-links.ts @@ -1,62 +1,16 @@ import { toast } from "sonner" +import { + mediaShareUrl, + type MediaShareTarget, +} from "@otunes/convex/client/media-links" -export type MediaShareContext = - | { type: "album"; albumId: string } - | { type: "song"; albumId: string; songId: string } - | { type: "playlist"; playlistId: string; isFavorites?: boolean } - | { type: "artist"; artistId: string } - -function mediaOrigin() { - if (typeof window === "undefined") { - return "" - } - return window.location.origin -} - -function albumShareUrl(albumId: string) { - return `${mediaOrigin()}/album/${albumId}` -} - -function songShareUrl(albumId: string, songId: string) { - return `${mediaOrigin()}/album/${albumId}?s=${songId}` -} - -function playlistShareUrl( - playlistId: string, - options?: { isFavorites?: boolean } -) { - if (options?.isFavorites) { - return `${mediaOrigin()}/playlist/favorites` - } - return `${mediaOrigin()}/playlist/${playlistId}` -} - -function artistShareUrl(artistId: string) { - return `${mediaOrigin()}/artist/${artistId}` -} - -function mediaShareUrl(share: MediaShareContext) { - switch (share.type) { - case "album": - return albumShareUrl(share.albumId) - case "song": - return songShareUrl(share.albumId, share.songId) - case "playlist": - return playlistShareUrl(share.playlistId, { - isFavorites: share.isFavorites, - }) - case "artist": - return artistShareUrl(share.artistId) - } -} - -async function copyTextToClipboard(text: string) { - await navigator.clipboard.writeText(text) - toast.success("Link Copied") -} +export type MediaShareContext = MediaShareTarget export async function copyMediaShareLink(share: MediaShareContext) { - await copyTextToClipboard(mediaShareUrl(share)) + await navigator.clipboard.writeText( + mediaShareUrl(window.location.origin, share) + ) + toast.success("Link Copied") } export async function copyAlbumLink(albumId: string) { diff --git a/apps/web/lib/server-hls.ts b/apps/web/lib/server-hls.ts index 50d84d1..e4f3182 100644 --- a/apps/web/lib/server-hls.ts +++ b/apps/web/lib/server-hls.ts @@ -1,4 +1,9 @@ import type { Doc } from "@otunes/convex/_generated/dataModel" +import { + parsePlaybackQuality, + playbackStreamPlan, + qualityKbps, +} from "@otunes/convex/playback-stream" import crypto from "node:crypto" import fs from "node:fs/promises" import path from "node:path" @@ -50,33 +55,6 @@ const state = (globalState.__otunesHls ??= { lastCleanupAt: 0, }) -export function qualityKbps(quality: string | null) { - if (quality === "low") { - return 64 - } - - if (quality === "high") { - return 256 - } - - return 128 -} - -export function selectHlsSourceCodec( - song: SongSource, - quality: string | null, - preferAtmos: boolean -) { - let sourceCodec = "lossless" in song.files ? "lossless" : "normal" - if (preferAtmos && "atmos" in song.files) { - sourceCodec = "atmos" - } else if (quality === "high" && "normal" in song.files) { - sourceCodec = "normal" - } - - return sourceCodec -} - function hlsLookupKey( songId: string, quality: string | null, @@ -305,9 +283,14 @@ export async function ensureHlsJob( ): Promise { await cleanupIdleHlsJobs() - const kbps = qualityKbps(quality) - const sourceCodec = selectHlsSourceCodec(song, quality, preferAtmos) - const sourcePath = song.files[sourceCodec] + const plan = playbackStreamPlan( + song.files, + parsePlaybackQuality(quality), + preferAtmos + ) + // HLS always transcodes, and lossless quality has no target bitrate. + const kbps = plan.kbps || qualityKbps("medium") + const sourcePath = song.files[plan.source] const key = await hlsJobKey(song, sourcePath, kbps) const lookupKey = hlsLookupKey(song._id, quality, preferAtmos) diff --git a/apps/web/lib/song-cache.ts b/apps/web/lib/song-cache.ts index 25c9ccc..2ab527a 100644 --- a/apps/web/lib/song-cache.ts +++ b/apps/web/lib/song-cache.ts @@ -2,10 +2,13 @@ import { useConvex } from "convex/react" import { useEffect, useMemo, useSyncExternalStore } from "react" import type { Id } from "@otunes/convex/_generated/dataModel" +import type { BrowseSong } from "@otunes/convex/types" import { getCachedSong, + getSongSnapshot, getSongsVersion, requestSongs, + songFromSnapshot, subscribeSongs, } from "@otunes/convex/client/song-cache" import { isPersistentCacheLoaded } from "@/lib/persistent-cache" @@ -48,7 +51,24 @@ export function useSongs(songIds: readonly Id<"songs">[]) { return songs } -export function useSong(songId: Id<"songs"> | null) { - const songIds = useMemo(() => (songId ? [songId] : []), [songId]) - return useSongs(songIds)[0] ?? null +/** + * Like `useSongs` for one song, but only re-renders when that song changes + * once it is cached. + */ +export function useSong(songId: Id<"songs"> | null): BrowseSong | null { + const convex = useConvex() + const snapshot = useSyncExternalStore( + subscribeSongs, + () => getSongSnapshot(songId), + () => null + ) + const song = songFromSnapshot(snapshot) + + useEffect(() => { + if (songId && !song && isPersistentCacheLoaded()) { + requestSongs(convex, [songId]) + } + }, [convex, songId, song, snapshot]) + + return song } diff --git a/apps/web/lib/song-play-url.ts b/apps/web/lib/song-play-url.ts deleted file mode 100644 index a61c00e..0000000 --- a/apps/web/lib/song-play-url.ts +++ /dev/null @@ -1,33 +0,0 @@ -export type PlaybackQuality = "low" | "medium" | "high" | "lossless" - -export function songPlayUrl( - songId: string, - quality: PlaybackQuality | undefined, - preferAtmos: boolean | undefined -) { - const params = new URLSearchParams() - if (quality) { - params.set("quality", quality) - } - if (preferAtmos) { - params.set("preferAtmos", "true") - } - const query = params.toString() - return `/api/song/${songId}/play${query ? `?${query}` : ""}` -} - -export function songHlsPlaylistUrl( - songId: string, - quality: PlaybackQuality | undefined, - preferAtmos: boolean | undefined -) { - const params = new URLSearchParams() - if (quality) { - params.set("quality", quality) - } - if (preferAtmos) { - params.set("preferAtmos", "true") - } - const query = params.toString() - return `/api/song/${songId}/play/hls${query ? `?${query}` : ""}` -} diff --git a/packages/convex/client/audio-format-marks.ts b/packages/convex/client/audio-format-marks.ts new file mode 100644 index 0000000..74ce326 --- /dev/null +++ b/packages/convex/client/audio-format-marks.ts @@ -0,0 +1,30 @@ +/** + * Path data for the Dolby Atmos and Lossless badge marks, drawn with each + * platform's own SVG primitives. + */ + +export const MARK_HEIGHT = 11 + +export const DOLBY_VIEW_BOX = "0 0 23 16" +export const DOLBY_WIDTH = (MARK_HEIGHT * 23) / 16 +export const DOLBY_PATHS = [ + "M0 0H2.5A8 8 0 0 1 2.5 16H0Z", + "M23 0H20.5A8 8 0 0 0 20.5 16H23Z", +] + +export const LOSSLESS_VIEW_BOX = "28 154 544 271" +export const LOSSLESS_WIDTH = (MARK_HEIGHT * 544) / 271 +export const LOSSLESS_PEAKS = [110, 215, 320] +export const LOSSLESS_THIN_WIDTH = 24 +export const LOSSLESS_STROKES: [peak: number, d: string][] = [ + [110, "M-70 320C-62 245 -38 166 0 166"], + [215, "M-70 320C-62 245 -38 166 0 166"], + [320, "M-30 185C-22 173 -11 166 0 166"], + [110, "M166 413C176 413 186 406 194 395"], + [215, "M166 413C200 413 226 340 240 275"], + [320, "M166 413C200 413 226 340 240 275"], +] +export const LOSSLESS_FALL = + "M0 178L4 179L8 181L12 184L16 189L20 196L23 204L27 213L30 223L34 233L39 243L43 254L48 266L53 278L58 289L62 301L66 313L71 325L75 336L79 347L83 357L86 364L89 370L93 377L97 382L101 387L105 392L109 397L113 401L117 405L121 408L126 412L130 415L134 417L139 419L143 421L148 423L152 424L157 424L161 425L166 425L166 401L163 401L161 400L159 400L157 399L154 397L152 396L151 394L149 392L147 389L145 386L143 383L142 380L140 376L138 371L137 367L135 362L134 357L132 351L130 345L127 339L124 330L120 319L116 308L111 297L107 285L102 272L98 260L93 248L88 235L82 223L76 212L69 201L61 192L53 183L45 175L37 168L28 163L19 158L10 155L0 154Z" +export const LOSSLESS_FALL_GAP = + "M0 178L4 180L6 184L8 190L9 197L11 203L14 210L17 219L21 228L24 238L29 248L33 259L38 270L43 282L47 293L52 305L56 317L60 328L64 340L68 351L73 361L76 368L79 375L83 381L87 387L91 393L95 398L100 403L104 408L109 412L113 416L118 419L124 422L130 424L135 425L141 426L147 426L152 426L157 425L161 425L166 425L166 401L163 401L161 399L159 398L158 395L157 393L156 390L155 387L155 384L154 381L153 379L152 376L150 373L149 369L148 366L146 361L145 357L143 352L142 347L140 341L137 335L134 326L130 315L126 304L122 293L117 281L113 268L108 256L103 243L98 231L92 219L86 207L79 196L71 186L62 177L53 168L44 161L32 157L21 155L10 154L0 154Z" diff --git a/packages/convex/client/auth-token.ts b/packages/convex/client/auth-token.ts new file mode 100644 index 0000000..b96dc61 --- /dev/null +++ b/packages/convex/client/auth-token.ts @@ -0,0 +1,15 @@ +/** Reads the user id from a Convex Auth JWT without verifying it, for scoping client caches. */ +export function userIdFromToken(token: string | null | undefined) { + const payload = token?.split(".")[1] + if (!payload) { + return null + } + + try { + const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/")) + const subject = (JSON.parse(json) as { sub?: unknown }).sub + return typeof subject === "string" ? (subject.split("|")[0] ?? null) : null + } catch { + return null + } +} diff --git a/packages/convex/client/favorites.ts b/packages/convex/client/favorites.ts new file mode 100644 index 0000000..69d20eb --- /dev/null +++ b/packages/convex/client/favorites.ts @@ -0,0 +1,96 @@ +import type { OptimisticLocalStore, OptimisticUpdate } from "convex/browser" +import type { FunctionArgs, FunctionReference } from "convex/server" + +import { api } from "../convex/_generated/api" +import type { Id } from "../convex/_generated/dataModel" + +type FavoriteIds = { + favoriteSongs: Id<"songs">[] + favoriteAlbums: Id<"albums">[] + favoriteArtists: Id<"artists">[] +} + +type FavoriteList = keyof FavoriteIds + +function patchFavorites( + store: OptimisticLocalStore, + list: List, + update: (ids: FavoriteIds[List]) => FavoriteIds[List] +) { + const current = store.getQuery(api.favorites.getUserFavorites, {}) + if (!current) return + const next = update(current[list]) + if (next !== current[list]) { + store.setQuery( + api.favorites.getUserFavorites, + {}, + { + ...current, + [list]: next, + } + ) + } +} + +function addFavorites( + store: OptimisticLocalStore, + list: List, + ids: FavoriteIds[List] +) { + patchFavorites(store, list, (current) => { + const added = ids.filter((id) => !(current as string[]).includes(id)) + return added.length === 0 + ? current + : ([...new Set([...current, ...added])] as FavoriteIds[List]) + }) +} + +function removeFavorites( + store: OptimisticLocalStore, + list: List, + ids: FavoriteIds[List] +) { + const removed = new Set(ids) + patchFavorites( + store, + list, + (current) => + (current as string[]).filter( + (id) => !removed.has(id) + ) as FavoriteIds[List] + ) +} + +type FavoritesApi = typeof api.favorites +type FavoriteMutation = { + [ + Name in keyof FavoritesApi + ]: FavoritesApi[Name] extends FunctionReference<"mutation"> ? Name : never +}[keyof FavoritesApi] + +/** + * Optimistic updates for the favorites mutations, so toggles show instantly. + * Pass them to `useMutation(...).withOptimisticUpdate(...)`. + */ +export const favoriteOptimisticUpdates = { + favoriteSong: (store, { songId }) => + addFavorites(store, "favoriteSongs", [songId]), + favoriteSongs: (store, { songIds }) => + addFavorites(store, "favoriteSongs", songIds), + unfavoriteSong: (store, { songId }) => + removeFavorites(store, "favoriteSongs", [songId]), + unfavoriteSongs: (store, { songIds }) => + removeFavorites(store, "favoriteSongs", songIds), + favoriteAlbum: (store, { albumId }) => + addFavorites(store, "favoriteAlbums", [albumId]), + unfavoriteAlbum: (store, { albumId }) => + removeFavorites(store, "favoriteAlbums", [albumId]), + favoriteArtist: (store, { artistId }) => + addFavorites(store, "favoriteArtists", [artistId]), + unfavoriteArtist: (store, { artistId }) => + removeFavorites(store, "favoriteArtists", [artistId]), +} satisfies { + [Name in FavoriteMutation]?: OptimisticUpdate< + FunctionArgs + > +} diff --git a/packages/convex/client/media-links.ts b/packages/convex/client/media-links.ts new file mode 100644 index 0000000..bce8666 --- /dev/null +++ b/packages/convex/client/media-links.ts @@ -0,0 +1,34 @@ +/** A piece of media that has a shareable page on the web app. */ +export type MediaShareTarget = + | { type: "album"; albumId: string } + | { type: "song"; albumId: string; songId: string } + | { type: "playlist"; playlistId: string; isFavorites?: boolean } + | { type: "artist"; artistId: string } + +/** Builds the web app URL for `share`, relative to `origin` (no trailing slash needed). */ +export function mediaShareUrl(origin: string, share: MediaShareTarget) { + const base = origin.replace(/\/+$/, "") + switch (share.type) { + case "album": + return `${base}/album/${share.albumId}` + case "song": + return `${base}/album/${share.albumId}?s=${share.songId}` + case "playlist": + return share.isFavorites + ? `${base}/playlist/favorites` + : `${base}/playlist/${share.playlistId}` + case "artist": + return `${base}/artist/${share.artistId}` + } +} + +/** Songs are shared one at a time; collections are shared whatever is selected. */ +export function shouldShowShare( + share: MediaShareTarget | undefined, + selectedCount: number +) { + if (!share) { + return false + } + return share.type !== "song" || selectedCount === 1 +} diff --git a/packages/convex/client/playback-queue.ts b/packages/convex/client/playback-queue.ts index 6063b5b..142d5d8 100644 --- a/packages/convex/client/playback-queue.ts +++ b/packages/convex/client/playback-queue.ts @@ -1,6 +1,9 @@ import type { Id } from "../convex/_generated/dataModel" -/** Mirrors the queue rules in `packages/convex/convex/playback.ts`. */ +/** + * Queue rules shared by the clients, which apply them locally, and the Convex + * playback mutations. + */ function shuffleArray(items: T[]): T[] { const next = [...items] @@ -30,7 +33,7 @@ export const EMPTY_PLAYBACK_QUEUE: PlaybackQueueState = { progressSeconds: 0, } -const MAX_QUEUE_HISTORY = 30 +export const MAX_QUEUE_HISTORY = 30 function uniqueSongIds(songIds: Id<"songs">[]) { return [...new Set(songIds)] diff --git a/packages/convex/client/song-cache.ts b/packages/convex/client/song-cache.ts index 6cf96a5..ad82c73 100644 --- a/packages/convex/client/song-cache.ts +++ b/packages/convex/client/song-cache.ts @@ -59,6 +59,19 @@ export function getCachedSong(songId: string) { return readCache(songKey(songId)) } +/** + * `useSyncExternalStore` snapshot for one song: the song once cached, else the + * cache version, so a missing song re-renders on every cache change (to retry + * the fetch) and a cached one only when it changes. + */ +export function getSongSnapshot(songId: string | null) { + return songId ? (getCachedSong(songId) ?? version) : null +} + +export function songFromSnapshot(snapshot: ReturnType) { + return typeof snapshot === "object" ? snapshot : null +} + /** Stores song metadata so the player and queue can render it offline. */ export function rememberSongs(songs: readonly BrowseSong[]) { let changed = false diff --git a/packages/convex/client/song-search.ts b/packages/convex/client/song-search.ts new file mode 100644 index 0000000..954d2e2 --- /dev/null +++ b/packages/convex/client/song-search.ts @@ -0,0 +1,21 @@ +type SearchableSong = { + title: string + artist: { name: string } + album: { title: string } +} + +/** Case-insensitive match on title, artist, or album. A blank query keeps every song. */ +export function filterSongs( + songs: T[], + query: string +) { + const normalized = query.trim().toLowerCase() + if (!normalized) { + return songs + } + return songs.filter((song) => + [song.title, song.artist.name, song.album.title].some((value) => + value.toLowerCase().includes(normalized) + ) + ) +} diff --git a/packages/convex/convex/playbackState.ts b/packages/convex/convex/playbackState.ts index c57855d..40c3c95 100644 --- a/packages/convex/convex/playbackState.ts +++ b/packages/convex/convex/playbackState.ts @@ -1,10 +1,9 @@ import { ConvexError } from "convex/values" import type { Doc, Id } from "./_generated/dataModel" import type { MutationCtx, QueryCtx } from "./_generated/server" +import { MAX_QUEUE_HISTORY } from "../client/playback-queue" import { MAX_QUEUE_LENGTH } from "./limits" -const MAX_QUEUE_HISTORY = 30 - export type RepeatMode = Doc<"playbackStates">["repeatEnabled"] export type PlaybackState = Pick< diff --git a/packages/convex/package.json b/packages/convex/package.json index 031b310..3a53357 100644 --- a/packages/convex/package.json +++ b/packages/convex/package.json @@ -23,10 +23,26 @@ "types": "./server-url.ts", "default": "./server-url.ts" }, + "./client/audio-format-marks": { + "types": "./client/audio-format-marks.ts", + "default": "./client/audio-format-marks.ts" + }, + "./client/auth-token": { + "types": "./client/auth-token.ts", + "default": "./client/auth-token.ts" + }, "./client/cached-query": { "types": "./client/cached-query.ts", "default": "./client/cached-query.ts" }, + "./client/favorites": { + "types": "./client/favorites.ts", + "default": "./client/favorites.ts" + }, + "./client/media-links": { + "types": "./client/media-links.ts", + "default": "./client/media-links.ts" + }, "./client/persistent-cache": { "types": "./client/persistent-cache.ts", "default": "./client/persistent-cache.ts" @@ -42,6 +58,10 @@ "./client/song-cache": { "types": "./client/song-cache.ts", "default": "./client/song-cache.ts" + }, + "./client/song-search": { + "types": "./client/song-search.ts", + "default": "./client/song-search.ts" } }, "scripts": { diff --git a/packages/convex/playback-stream.ts b/packages/convex/playback-stream.ts index a55a145..27d3eba 100644 --- a/packages/convex/playback-stream.ts +++ b/packages/convex/playback-stream.ts @@ -1,5 +1,21 @@ export type PlaybackQuality = "low" | "medium" | "high" | "lossless" +const PLAYBACK_QUALITIES: readonly string[] = [ + "low", + "medium", + "high", + "lossless", +] satisfies PlaybackQuality[] + +/** Reads a `quality` request parameter; anything unknown means the default. */ +export function parsePlaybackQuality( + value: string | null | undefined +): PlaybackQuality | undefined { + return value && PLAYBACK_QUALITIES.includes(value) + ? (value as PlaybackQuality) + : undefined +} + export function qualityKbps(quality: PlaybackQuality | null | undefined) { if (quality === "low") { return 64 @@ -16,9 +32,15 @@ export function qualityKbps(quality: PlaybackQuality | null | undefined) { return 0 } +export type PlaybackSource = "atmos" | "lossless" | "normal" + export type PlaybackStreamPlan = { playbackQuality: PlaybackQuality preferAtmos: boolean + /** The file that is streamed as-is, or transcoded when `transcodeNeeded`. */ + source: PlaybackSource + /** AAC bitrate to transcode to; 0 for lossless quality. */ + kbps: number transcodeNeeded: boolean useHls: boolean } @@ -29,27 +51,70 @@ export function playbackStreamPlan( preferAtmos: boolean ): PlaybackStreamPlan { const playbackQuality = quality ?? "medium" - const kbps = playbackQuality === "lossless" ? 0 : qualityKbps(playbackQuality) + const kbps = qualityKbps(playbackQuality) const effectivePreferAtmos = preferAtmos && "atmos" in files + let source: PlaybackSource = "lossless" in files ? "lossless" : "normal" let transcodeNeeded = true if (effectivePreferAtmos) { + source = "atmos" transcodeNeeded = false } else if (kbps === 0 && "lossless" in files) { + source = "lossless" transcodeNeeded = false } else if (kbps === 0 || (kbps === 256 && "normal" in files)) { + source = "normal" transcodeNeeded = false } return { playbackQuality, preferAtmos: effectivePreferAtmos, + source, + kbps, transcodeNeeded, useHls: transcodeNeeded, } } +function songStreamQuery( + params: URLSearchParams, + quality: PlaybackQuality | undefined, + preferAtmos: boolean | undefined +) { + if (quality) { + params.set("quality", quality) + } + if (preferAtmos) { + params.set("preferAtmos", "true") + } + const query = params.toString() + return query ? `?${query}` : "" +} + +export function songPlayPath( + songId: string, + quality: PlaybackQuality | undefined, + preferAtmos: boolean | undefined, + options?: { losslessFormat?: "alac" } +) { + const params = new URLSearchParams() + if (options?.losslessFormat) { + params.set("losslessFormat", options.losslessFormat) + } + return `/api/song/${songId}/play${songStreamQuery(params, quality, preferAtmos)}` +} + +export function songHlsPlaylistPath( + songId: string, + quality: PlaybackQuality | undefined, + preferAtmos: boolean | undefined +) { + const query = songStreamQuery(new URLSearchParams(), quality, preferAtmos) + return `/api/song/${songId}/play/hls${query}` +} + export type PlaybackFormat = "atmos" | "lossless" /** The labeled format a song streams in under the plan, if any. */