From 22cb6b6ccc855442d50bcb1a0c6abd8da9886c0c Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 14:22:19 -0500 Subject: [PATCH] refactor: share logic duplicated across web, mobile, and Convex Move queue rules, stream planning, stream URLs, share links, song search, favorites optimistic updates, token parsing, and format badge marks into @otunes/convex so each rule has one implementation. Co-Authored-By: Claude Opus 5.5 --- .../app/(app)/(tabs)/home/album/[id].tsx | 3 +- .../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/contexts/playback.tsx | 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 | 24 +- apps/web/lib/media-links.ts | 72 +--- 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/playback.ts | 369 ++++-------------- packages/convex/package.json | 20 + packages/convex/playback-stream.ts | 67 +++- 35 files changed, 612 insertions(+), 861 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 a32bf8c..3b7f808 100644 --- a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx @@ -89,7 +89,8 @@ export default function AlbumScreen() { [album] ) - // Older servers do not include album format availability yet. + // Servers from before the album format fields (#61, 2026-11-03) omit them, + // so derive them from the tracks there. Current servers skip this query. const formatTracks = useCachedQuery( api.library.getSongsForPlayback, album && (album.hasLossless === undefined || album.hasAtmos === undefined) diff --git a/apps/mobile/app/(app)/(tabs)/home/settings.tsx b/apps/mobile/app/(app)/(tabs)/home/settings.tsx index 30a0cfb..d36b708 100644 --- a/apps/mobile/app/(app)/(tabs)/home/settings.tsx +++ b/apps/mobile/app/(app)/(tabs)/home/settings.tsx @@ -1,4 +1,4 @@ -import { dolbyAtmosSupported } from "@/lib/playback-capabilities" +import { atmosEnabled, dolbyAtmosSupported } from "@/lib/playback-capabilities" import { Ionicons } from "@expo/vector-icons" import { useAction, useMutation, useQuery } from "convex/react" import { Image } from "expo-image" @@ -30,7 +30,7 @@ import { useCachedQuery } from "@/hooks/use-cached-query" import { changeServer, signOut } from "@/lib/session" import { radius, spacing, useThemeColors } from "@/lib/theme" import { showError } from "@/lib/toast" -import type { PlaybackQuality } from "@/lib/urls" +import type { PlaybackQuality } from "@otunes/convex/playback-stream" import { api } from "@otunes/convex/_generated/api" import type { Id } from "@otunes/convex/_generated/dataModel" @@ -419,7 +419,7 @@ function QualitySection({ user }: { user: CurrentUser }) { : "This device does not support Dolby Atmos playback." } disabled={!dolbyAtmosSupported} - value={dolbyAtmosSupported && (user.preferAtmos ?? false)} + value={atmosEnabled(user)} onValueChange={(checked) => 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 74da7bc..752bd59 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 f07a2b6..dcb676b 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 FavoritesContextValue = { @@ -52,110 +55,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/contexts/playback.tsx b/apps/mobile/contexts/playback.tsx index 96241e8..e70df52 100644 --- a/apps/mobile/contexts/playback.tsx +++ b/apps/mobile/contexts/playback.tsx @@ -1,4 +1,4 @@ -import { dolbyAtmosSupported } from "@/lib/playback-capabilities" +import { atmosEnabled } from "@/lib/playback-capabilities" import { createAudioPlaylist, setAudioModeAsync, @@ -323,11 +323,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { ]) : "" const userPlaybackKey = user - ? JSON.stringify([ - user._id, - user.playbackQuality, - dolbyAtmosSupported && (user.preferAtmos ?? false), - ]) + ? JSON.stringify([user._id, user.playbackQuality, atmosEnabled(user)]) : "" const scheduleTrackChangeHandling = useCallback(() => { @@ -654,7 +650,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { } 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( @@ -696,7 +692,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { 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 45801dc..38a26e1 100644 --- a/apps/web/app/api/song/[id]/play/route.ts +++ b/apps/web/app/api/song/[id]/play/route.ts @@ -1,5 +1,9 @@ import { api } from "@otunes/convex/_generated/api" import type { Id } from "@otunes/convex/_generated/dataModel" +import { + parsePlaybackQuality, + playbackStreamPlan, +} from "@otunes/convex/playback-stream" import { audioContentTypeForPath } from "@/lib/audio-content-type" import { seekableLosslessFile } from "@/lib/server-lossless" import { getConvexClient } from "@/lib/convex-server" @@ -122,34 +126,17 @@ export async function GET( id: id as Id<"songs">, }))! - 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 - } + ) const metadata = await music.parseFile(song.files[originalCodec]) diff --git a/apps/web/components/album-view.tsx b/apps/web/components/album-view.tsx index ec3ce45..06f6569 100644 --- a/apps/web/components/album-view.tsx +++ b/apps/web/components/album-view.tsx @@ -22,8 +22,6 @@ import { } from "@/components/media-context-menu" 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 { useQueueMediaActions } from "@/hooks/use-queue-media-actions" import { useTrackSelection } from "@/hooks/use-track-selection" import { cn } from "@/lib/utils" @@ -276,20 +274,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]) @@ -421,15 +405,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 d216401..2ff44cf 100644 --- a/apps/web/components/media-context-menu.tsx +++ b/apps/web/components/media-context-menu.tsx @@ -23,6 +23,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 = @@ -40,19 +41,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 -} - function actionLabel(base: string, selectedCount: number) { return selectedCount > 1 ? `${base} (${selectedCount})` : base } 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 524a611..8d3d0f3 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 @@ -164,14 +166,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 @@ -226,12 +228,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 57ceaa8..0ef2f20 100644 --- a/apps/web/components/playlist-view.tsx +++ b/apps/web/components/playlist-view.tsx @@ -35,6 +35,7 @@ import { copyPlaylistLink } from "@/lib/media-links" import { sumDurationSeconds } from "@/lib/media-summary" import { rememberSongs } from "@/lib/song-cache" import { cn } from "@/lib/utils" +import { filterSongs } from "@otunes/convex/client/song-search" import { getSelectionRangePositions, isInSelectionRange, @@ -306,17 +307,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">), @@ -480,7 +474,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { function handleDrop(targetIndex: number) { if ( - normalizedQuery || + isSearching || isFavorites || !isOwner || dragIndex === null || @@ -681,7 +675,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { key={song.id} song={song} index={index} - isOwner={isOwner && !isFavorites && !normalizedQuery} + isOwner={isOwner && !isFavorites && !isSearching} canRemove={isFavorites || isOwner} showFavoriteInMenu={!isFavorites} removeLabel={ @@ -721,14 +715,14 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { onMediaAction={handleMediaAction} onRemove={() => handleRemoveSong(song.id)} onDragStart={(event) => { - if (normalizedQuery || isFavorites || !isOwner) { + if (isSearching || isFavorites || !isOwner) { return } setDragIndex(index) event.dataTransfer.effectAllowed = "move" }} onDragOver={(event) => { - if (normalizedQuery || isFavorites || !isOwner) { + if (isSearching || isFavorites || !isOwner) { return } event.preventDefault() @@ -749,7 +743,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 31d8c17..cb112c8 100644 --- a/apps/web/lib/media-links.ts +++ b/apps/web/lib/media-links.ts @@ -1,72 +1,22 @@ 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 -} - -export function albumShareUrl(albumId: string) { - return `${mediaOrigin()}/album/${albumId}` -} - -export function songShareUrl(albumId: string, songId: string) { - return `${mediaOrigin()}/album/${albumId}?s=${songId}` -} - -export function playlistShareUrl( - playlistId: string, - options?: { isFavorites?: boolean } -) { - if (options?.isFavorites) { - return `${mediaOrigin()}/playlist/favorites` - } - return `${mediaOrigin()}/playlist/${playlistId}` -} - -export function artistShareUrl(artistId: string) { - return `${mediaOrigin()}/artist/${artistId}` -} - -export 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) - } -} - -export 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) { await copyMediaShareLink({ type: "album", albumId }) } -export async function copySongLink(albumId: string, songId: string) { - await copyMediaShareLink({ type: "song", albumId, songId }) -} - export async function copyPlaylistLink( playlistId: string, options?: { isFavorites?: boolean } @@ -77,7 +27,3 @@ export async function copyPlaylistLink( isFavorites: options?.isFavorites, }) } - -export async function copyArtistLink(artistId: string) { - await copyMediaShareLink({ type: "artist", artistId }) -} diff --git a/apps/web/lib/server-hls.ts b/apps/web/lib/server-hls.ts index df3b876..4221aee 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" @@ -23,33 +28,6 @@ const jobs = new Map() const jobsByLookup = new Map() let lastCleanupAt = 0 -export function qualityKbps(quality: string | null) { - if (quality === "low") { - return 64 - } - - if (quality === "high") { - return 256 - } - - return 128 -} - -export function selectHlsSourceCodec( - song: Doc<"songs">, - 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 hlsCacheRoot() { return "/tmp/otunes" } @@ -164,9 +142,14 @@ export async function ensureHlsJob( ) { 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) const existingJob = jobs.get(key) 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/playback.ts b/packages/convex/convex/playback.ts index 6dbfe23..75389ec 100644 --- a/packages/convex/convex/playback.ts +++ b/packages/convex/convex/playback.ts @@ -12,10 +12,11 @@ import { songsSortDirectionValidator, songsSortKeyValidator, } from "./library" +import * as playbackQueue from "../client/playback-queue" +import type { PlaybackQueueState } from "../client/playback-queue" export type { HistorySong, QueueSong } from "./types" -const MAX_QUEUE_HISTORY = 30 const MAX_RECENTLY_PLAYED = 30 type RecentlyPlayedItem = Id<"albums"> | Id<"playlists"> @@ -79,15 +80,6 @@ async function recordPlaybackStart( await recordRecentlyPlayedFromSong(ctx, userId, options.songIds[0]) } -function shuffleArray(items: T[]): T[] { - const next = [...items] - for (let i = next.length - 1; i > 0; i--) { - const j = Math.floor(Math.random() * (i + 1)) - ;[next[i], next[j]] = [next[j], next[i]] - } - return next -} - async function requireAuth(ctx: MutationCtx) { const userId = await getAuthUserId(ctx) if (userId === null) { @@ -96,10 +88,6 @@ async function requireAuth(ctx: MutationCtx) { return userId } -function uniqueSongIds(songIds: Id<"songs">[]) { - return [...new Set(songIds)] -} - function haveSameSongCounts(first: Id<"songs">[], second: Id<"songs">[]) { if (first.length !== second.length) { return false @@ -122,28 +110,6 @@ function haveSameSongCounts(first: Id<"songs">[], second: Id<"songs">[]) { return counts.size === 0 } -function appendToQueueHistory( - history: Id<"songs">[], - songId: Id<"songs"> -): Id<"songs">[] { - const next = [...history, songId] - if (next.length <= MAX_QUEUE_HISTORY) { - return next - } - return next.slice(next.length - MAX_QUEUE_HISTORY) -} - -function appendManyToQueueHistory( - history: Id<"songs">[], - songIds: Id<"songs">[] -): Id<"songs">[] { - let next = history - for (const songId of songIds) { - next = appendToQueueHistory(next, songId) - } - return next -} - async function patchPlayback( ctx: MutationCtx, userId: Id<"users">, @@ -168,24 +134,38 @@ async function patchPlayback( return playbackRevision } -async function setQueueState( +/** Applies a queue rule to the user's stored playback state. */ +async function updateQueue( ctx: MutationCtx, userId: Id<"users">, - patch: { - songQueue: Id<"songs">[] - shuffleEnabled?: boolean - currentSongProgress?: number - resetHistory?: boolean - } + update: (state: PlaybackQueueState) => PlaybackQueueState ) { - await patchPlayback(ctx, userId, { - songQueue: patch.songQueue, - currentSongProgress: patch.currentSongProgress ?? 0, - ...(patch.resetHistory ? { queueHistory: [] } : {}), - ...(patch.shuffleEnabled !== undefined - ? { shuffleEnabled: patch.shuffleEnabled } - : {}), + const user = await ctx.db.get(userId) + if (!user) { + throw new ConvexError("User not found") + } + + const state: PlaybackQueueState = { + queue: user.songQueue ?? [], + history: user.queueHistory ?? [], + shuffleEnabled: user.shuffleEnabled ?? false, + repeatEnabled: user.repeatEnabled ?? "none", + progressSeconds: user.currentSongProgress ?? 0, + } + const next = update(state) + if (next === state) { + return next + } + + await ctx.db.patch(userId, { + songQueue: next.queue, + queueHistory: next.history, + shuffleEnabled: next.shuffleEnabled, + repeatEnabled: next.repeatEnabled, + currentSongProgress: next.progressSeconds, + playbackRevision: (user.playbackRevision ?? 0) + 1, }) + return next } export const getPlaybackState = query({ @@ -241,7 +221,7 @@ export const syncPlaybackState = mutation({ const userId = await requireAuth(ctx) return await patchPlayback(ctx, userId, { songQueue: args.songQueue, - queueHistory: args.queueHistory.slice(-MAX_QUEUE_HISTORY), + queueHistory: args.queueHistory.slice(-playbackQueue.MAX_QUEUE_HISTORY), shuffleEnabled: args.shuffleEnabled, repeatEnabled: args.repeatEnabled, currentSongProgress: Math.max(0, Math.floor(args.currentSongProgress)), @@ -336,12 +316,9 @@ export const playInOrder = mutation({ }, handler: async (ctx, { songIds, playlistId }) => { const userId = await requireAuth(ctx) - const queue = uniqueSongIds(songIds) - await setQueueState(ctx, userId, { - songQueue: queue, - shuffleEnabled: false, - resetHistory: true, - }) + const { queue } = await updateQueue(ctx, userId, (state) => + playbackQueue.startQueue(state, songIds, false) + ) await recordPlaybackStart(ctx, userId, { songIds: queue, playlistId }) }, }) @@ -353,73 +330,54 @@ export const playShuffled = mutation({ }, handler: async (ctx, { songIds, playlistId }) => { const userId = await requireAuth(ctx) - const queue = shuffleArray(uniqueSongIds(songIds)) - await setQueueState(ctx, userId, { - songQueue: queue, - shuffleEnabled: true, - resetHistory: true, - }) + const { queue } = await updateQueue(ctx, userId, (state) => + playbackQueue.startQueue(state, songIds, true) + ) await recordPlaybackStart(ctx, userId, { songIds: queue, playlistId }) }, }) -function orderSongsForInsert( +async function addToQueue( + ctx: MutationCtx, songIds: Id<"songs">[], - shuffleEnabled: boolean -): Id<"songs">[] { - return shuffleEnabled ? shuffleArray(songIds) : songIds + position: "next" | "last" +) { + if (songIds.length === 0) { + return + } + + const userId = await requireAuth(ctx) + await updateQueue(ctx, userId, (state) => + playbackQueue.addToQueue(state, songIds, position) + ) } export const addToQueueNext = mutation({ args: { songIds: v.array(v.id("songs")) }, handler: async (ctx, { songIds }) => { - if (songIds.length === 0) { - return - } - - const userId = await requireAuth(ctx) - const user = await ctx.db.get(userId) - if (!user) { - throw new ConvexError("User not found") - } - - const toAdd = orderSongsForInsert(songIds, user.shuffleEnabled ?? false) - const queue = user.songQueue ?? [] - - if (queue.length === 0) { - await setQueueState(ctx, userId, { songQueue: toAdd }) - return - } - - const [current, ...rest] = queue - await setQueueState(ctx, userId, { - songQueue: [current, ...toAdd, ...rest], - }) + await addToQueue(ctx, songIds, "next") }, }) export const addToQueueLast = mutation({ args: { songIds: v.array(v.id("songs")) }, handler: async (ctx, { songIds }) => { - if (songIds.length === 0) { - return - } - - const userId = await requireAuth(ctx) - const user = await ctx.db.get(userId) - if (!user) { - throw new ConvexError("User not found") - } - - const toAdd = orderSongsForInsert(songIds, user.shuffleEnabled ?? false) - const queue = user.songQueue ?? [] - - await setQueueState(ctx, userId, { - songQueue: queue.length === 0 ? toAdd : [...queue, ...toAdd], - }) + await addToQueue(ctx, songIds, "last") }, }) +async function playFromSongIn( + ctx: MutationCtx, + userId: Id<"users">, + songId: Id<"songs">, + songIds: Id<"songs">[] +) { + await updateQueue(ctx, userId, (state) => + playbackQueue.startQueueFromSong(state, songId, songIds) + ) + await recordRecentlyPlayedFromSong(ctx, userId, songId) +} + export const playFromSong = mutation({ args: { songId: v.id("songs"), @@ -427,24 +385,7 @@ export const playFromSong = mutation({ }, handler: async (ctx, { songId, songIds }) => { const userId = await requireAuth(ctx) - const user = await ctx.db.get(userId) - if (!user) { - throw new ConvexError("User not found") - } - - const index = songIds.indexOf(songId) - const rest = user.shuffleEnabled - ? uniqueSongIds(songIds).filter((id) => id !== songId) - : index === -1 - ? [] - : songIds.slice(index + 1) - const queueRest = user.shuffleEnabled ? shuffleArray(rest) : rest - - await setQueueState(ctx, userId, { - songQueue: [songId, ...queueRest], - resetHistory: true, - }) - await recordRecentlyPlayedFromSong(ctx, userId, songId) + await playFromSongIn(ctx, userId, songId, songIds) }, }) @@ -496,17 +437,13 @@ async function playCollection( } ) { const userId = await requireAuth(ctx) - const unique = uniqueSongIds(options.songIds) - if (unique.length === 0) { + if (options.songIds.length === 0) { return } - const queue = options.shuffled ? shuffleArray(unique) : unique - await setQueueState(ctx, userId, { - songQueue: queue, - shuffleEnabled: options.shuffled, - resetHistory: true, - }) + const { queue } = await updateQueue(ctx, userId, (state) => + playbackQueue.startQueue(state, options.songIds, options.shuffled) + ) await recordPlaybackStart(ctx, userId, { songIds: queue, playlistId: options.playlistId, @@ -585,25 +522,8 @@ export const playFromLibrarySong = mutation({ }, handler: async (ctx, { songId, sortKey, sortDirection }) => { const userId = await requireAuth(ctx) - const user = await ctx.db.get(userId) - if (!user) { - throw new ConvexError("User not found") - } - const songIds = await getSortedLibrarySongIds(ctx, sortKey, sortDirection) - const index = songIds.indexOf(songId) - const rest = user.shuffleEnabled - ? uniqueSongIds(songIds).filter((id) => id !== songId) - : index === -1 - ? [] - : songIds.slice(index + 1) - const queueRest = user.shuffleEnabled ? shuffleArray(rest) : rest - - await setQueueState(ctx, userId, { - songQueue: [songId, ...queueRest], - resetHistory: true, - }) - await recordRecentlyPlayedFromSong(ctx, userId, songId) + await playFromSongIn(ctx, userId, songId, songIds) }, }) @@ -611,24 +531,7 @@ export const toggleShuffle = mutation({ args: {}, handler: async (ctx) => { const userId = await requireAuth(ctx) - const user = await ctx.db.get(userId) - if (!user) { - throw new ConvexError("User not found") - } - - const shuffleEnabled = !(user.shuffleEnabled ?? false) - const queue = user.songQueue ?? [] - - if (shuffleEnabled && queue.length > 1) { - const [current, ...upNext] = queue - await patchPlayback(ctx, userId, { - shuffleEnabled: true, - songQueue: [current, ...shuffleArray(upNext)], - }) - return - } - - await patchPlayback(ctx, userId, { shuffleEnabled }) + await updateQueue(ctx, userId, playbackQueue.toggleShuffle) }, }) @@ -636,16 +539,7 @@ export const cycleRepeat = mutation({ args: {}, handler: async (ctx) => { const userId = await requireAuth(ctx) - const user = await ctx.db.get(userId) - if (!user) { - throw new ConvexError("User not found") - } - - const current = user.repeatEnabled ?? "none" - const next = - current === "none" ? "once" : current === "once" ? "always" : "none" - - await patchPlayback(ctx, userId, { repeatEnabled: next }) + await updateQueue(ctx, userId, playbackQueue.cycleRepeat) }, }) @@ -653,11 +547,7 @@ export const clearQueue = mutation({ args: {}, handler: async (ctx) => { const userId = await requireAuth(ctx) - await patchPlayback(ctx, userId, { - songQueue: [], - queueHistory: [], - currentSongProgress: 0, - }) + await updateQueue(ctx, userId, playbackQueue.clearQueue) }, }) @@ -665,25 +555,11 @@ export const reorderQueue = mutation({ args: { songIds: v.array(v.id("songs")) }, handler: async (ctx, { songIds }) => { const userId = await requireAuth(ctx) - const user = await ctx.db.get(userId) - if (!user) { - throw new ConvexError("User not found") - } - - const queue = user.songQueue ?? [] - if (!haveSameSongCounts(queue, songIds)) { - throw new ConvexError("Invalid queue order") - } - const currentSongChanged = songIds.length > 0 && songIds[0] !== queue[0] - const history = - currentSongChanged && queue.length > 0 - ? appendToQueueHistory(user.queueHistory ?? [], queue[0]) - : (user.queueHistory ?? []) - - await patchPlayback(ctx, userId, { - songQueue: songIds, - queueHistory: history, - ...(currentSongChanged ? { currentSongProgress: 0 } : {}), + await updateQueue(ctx, userId, (state) => { + if (!haveSameSongCounts(state.queue, songIds)) { + throw new ConvexError("Invalid queue order") + } + return playbackQueue.reorderQueue(state, songIds) }) }, }) @@ -692,24 +568,9 @@ export const skipToQueueIndex = mutation({ args: { index: v.number() }, handler: async (ctx, { index }) => { const userId = await requireAuth(ctx) - const user = await ctx.db.get(userId) - if (!user) { - throw new ConvexError("User not found") - } - - const queue = user.songQueue ?? [] - if (index < 0 || index >= queue.length || index === 0) { - return - } - - const skipped = queue.slice(0, index) - const history = appendManyToQueueHistory(user.queueHistory ?? [], skipped) - - await patchPlayback(ctx, userId, { - songQueue: queue.slice(index), - queueHistory: history, - currentSongProgress: 0, - }) + await updateQueue(ctx, userId, (state) => + playbackQueue.skipToQueueIndex(state, index) + ) }, }) @@ -717,48 +578,7 @@ export const skipNext = mutation({ args: {}, handler: async (ctx) => { const userId = await requireAuth(ctx) - const user = await ctx.db.get(userId) - if (!user) { - throw new ConvexError("User not found") - } - - const queue = user.songQueue ?? [] - if (queue.length === 0) { - return - } - - const repeat = user.repeatEnabled ?? "none" - - if (repeat === "once") { - await patchPlayback(ctx, userId, { currentSongProgress: 0 }) - return - } - - const [current, ...rest] = queue - - if (repeat === "always") { - await patchPlayback(ctx, userId, { - songQueue: [...rest, current], - currentSongProgress: 0, - }) - return - } - - if (rest.length === 0) { - await patchPlayback(ctx, userId, { - songQueue: [current], - currentSongProgress: 0, - }) - return - } - - const history = appendToQueueHistory(user.queueHistory ?? [], current) - - await patchPlayback(ctx, userId, { - songQueue: rest, - queueHistory: history, - currentSongProgress: 0, - }) + await updateQueue(ctx, userId, playbackQueue.skipNext) }, }) @@ -766,32 +586,7 @@ export const skipPrevious = mutation({ args: {}, handler: async (ctx) => { const userId = await requireAuth(ctx) - const user = await ctx.db.get(userId) - if (!user) { - throw new ConvexError("User not found") - } - - const queue = user.songQueue ?? [] - const history = user.queueHistory ?? [] - - if (queue.length === 0) { - return - } - - if (history.length === 0) { - await patchPlayback(ctx, userId, { currentSongProgress: 0 }) - return - } - - const [current, ...rest] = queue - const previous = history[history.length - 1] - const newHistory = history.slice(0, -1) - - await patchPlayback(ctx, userId, { - songQueue: [previous, current, ...rest], - queueHistory: newHistory, - currentSongProgress: 0, - }) + await updateQueue(ctx, userId, playbackQueue.skipPrevious) }, }) 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. */