@@ -118,7 +84,7 @@ export function ArtistView({
label={`More options for ${artist.name}`}
selectedCount={albums.length}
onOpenMenu={() => {}}
- onAction={handleMediaAction}
+ onAction={(action) => void runArtistAction(action, artist.id)}
favorited={isArtistFavorite(artist.id)}
trackRowTrigger={false}
triggerVariant="secondary"
diff --git a/apps/web/components/artists-view.tsx b/apps/web/components/artists-view.tsx
index 554e35d..f10b361 100644
--- a/apps/web/components/artists-view.tsx
+++ b/apps/web/components/artists-view.tsx
@@ -4,27 +4,24 @@ import * as React from "react"
import Image from "next/image"
import Link from "next/link"
import { ChevronRightIcon, Play, Shuffle } from "lucide-react"
-import { useConvex } from "convex/react"
-import { useCacheScope } from "@/components/persistent-cache-provider"
import { AlbumCard } from "@/components/album-card"
-import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
import { FavoriteMediaButton } from "@/components/favorite-media-button"
import { useFavorites } from "@/components/favorites-provider"
import {
MediaContextMenu,
type MediaContextAction,
+ MediaContextMenuArea,
+ type MediaContextMenuProps,
} from "@/components/media-context-menu"
-import { usePlayback } from "@/components/playback-provider"
-import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
+import { usePlaybackActions } from "@/components/playback-provider"
+import { useMediaActions } from "@/hooks/use-media-actions"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
-import { api } from "@otunes/convex/_generated/api"
import { cn } from "@/lib/utils"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
import { artistCoverUrl } from "@/lib/cover-urls"
-import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
function ArtistAvatar({ artist }: { artist: BrowseArtist }) {
return (
@@ -55,36 +52,42 @@ function ArtistListItem({
onSelect: () => void
onMediaAction: (action: MediaContextAction) => void
}) {
+ const menu: MediaContextMenuProps = {
+ label: `More options for ${artist.name}`,
+ selectedCount: albumCount,
+ inSelectionRange: isSelected,
+ onOpenMenu: () => {},
+ onAction: onMediaAction,
+ favorited: isFavorite,
+ share: { type: "artist", artistId: artist.id },
+ }
+
return (
-
-
+
)
}
@@ -110,12 +113,9 @@ export function ArtistsView({
}
return sortedArtists[0]?.id ?? ""
}, [artistId, sortedArtists])
- const convex = useConvex()
- const cacheScope = useCacheScope()
- const { openAddArtistToPlaylist } = useAddToPlaylist()
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
- const { playArtist, playArtistShuffled } = usePlayback()
- const { runQueueAction } = useQueueMediaActions()
+ const { playArtist, playArtistShuffled } = usePlaybackActions()
+ const { runArtistAction } = useMediaActions()
const selectedArtist = sortedArtists.find(
(artist) => artist.id === selectedId
@@ -130,32 +130,6 @@ export function ArtistsView({
return counts
}, [albums])
- async function handleMediaAction(
- artistId: string,
- action: MediaContextAction
- ) {
- switch (action) {
- case "favorite":
- void toggleArtistFavorite(artistId as Id<"artists">)
- break
- case "playlist":
- void openAddArtistToPlaylist(artistId as Id<"artists">)
- break
- case "play-next":
- case "play-last":
- case "shuffle": {
- const songIds = await fetchCachedQuery(
- convex,
- cacheScope,
- api.playlists.getOrderedArtistSongIds,
- { artistId: artistId as Id<"artists"> }
- )
- void runQueueAction(action, songIds)
- break
- }
- }
- }
-
return (
@@ -169,7 +143,7 @@ export function ArtistsView({
isFavorite={isArtistFavorite(artist.id)}
onSelect={() => onSelectArtist(artist.id)}
onMediaAction={(action) =>
- void handleMediaAction(artist.id, action)
+ void runArtistAction(action, artist.id)
}
/>
))}
@@ -225,7 +199,7 @@ export function ArtistsView({
selectedCount={artistAlbums.length}
onOpenMenu={() => {}}
onAction={(action) =>
- void handleMediaAction(selectedArtist.id, action)
+ void runArtistAction(action, selectedArtist.id)
}
favorited={isArtistFavorite(selectedArtist.id)}
trackRowTrigger={false}
diff --git a/apps/web/components/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 (
-
diff --git a/apps/web/components/playlist-card.tsx b/apps/web/components/playlist-card.tsx
index 8f94976..2e796df 100644
--- a/apps/web/components/playlist-card.tsx
+++ b/apps/web/components/playlist-card.tsx
@@ -15,7 +15,7 @@ import {
MediaContextMenuItems,
type MediaContextAction,
} from "@/components/media-context-menu"
-import { usePlayback } from "@/components/playback-provider"
+import { usePlaybackActions } from "@/components/playback-provider"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
@@ -30,7 +30,7 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
const convex = useConvex()
const cacheScope = useCacheScope()
const { openAddPlaylistToPlaylist } = useAddToPlaylist()
- const { playPlaylist } = usePlayback()
+ const { playPlaylist } = usePlaybackActions()
const { runQueueAction } = useQueueMediaActions()
async function handleCardAction(action: MediaContextAction) {
diff --git a/apps/web/components/playlist-view.tsx b/apps/web/components/playlist-view.tsx
index 57ceaa8..e1a2eb1 100644
--- a/apps/web/components/playlist-view.tsx
+++ b/apps/web/components/playlist-view.tsx
@@ -9,15 +9,18 @@ import { useMutation } from "convex/react"
import { Play, SearchIcon, Share2, Shuffle, Star, Trash2 } from "lucide-react"
import { toast } from "sonner"
-import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
import { useFavorites } from "@/components/favorites-provider"
-import { usePlayback } from "@/components/playback-provider"
+import {
+ useCurrentSongId,
+ usePlaybackActions,
+} from "@/components/playback-provider"
import { MediaCollectionFooter } from "@/components/media-collection-footer"
-import { TrackNumberPlayButton } from "@/components/track-number-play-button"
import {
MediaContextMenu,
type MediaContextAction,
} from "@/components/media-context-menu"
+import { TrackRow } from "@/components/track-row"
+import { VirtualList } from "@/components/virtual-list"
import { Button } from "@/components/ui/button"
import {
DropdownMenuItem,
@@ -25,247 +28,23 @@ import {
} from "@/components/ui/dropdown-menu"
import { ScrollArea } from "@/components/ui/scroll-area"
import { useCachedQuery } from "@/hooks/use-cached-query"
-import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
+import {
+ useMediaActions,
+ useTrackListMediaAction,
+} from "@/hooks/use-media-actions"
import { useTrackSelection } from "@/hooks/use-track-selection"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowsePlaylistDetail, BrowseSong } from "@otunes/convex/types"
-import { albumCoverUrl, playlistCoverUrl } from "@/lib/cover-urls"
+import { playlistCoverUrl } from "@/lib/cover-urls"
import { copyPlaylistLink } from "@/lib/media-links"
import { sumDurationSeconds } from "@/lib/media-summary"
import { rememberSongs } from "@/lib/song-cache"
-import { cn } from "@/lib/utils"
-import {
- getSelectionRangePositions,
- isInSelectionRange,
- ALBUM_TRACK_ROW,
- ALBUM_TRACK_TITLE,
- SelectionRangeHighlight,
- TrackRowActiveHighlight,
- TrackRowHoverHighlight,
- TRACK_ROW_PADDING,
- type SelectionRangePosition,
-} from "@/lib/selection-range-styles"
+import { filterSongs } from "@otunes/convex/client/song-search"
+import { getSelectionRangePositions } from "@/lib/selection-range-styles"
const ADD_TO_ANOTHER_PLAYLIST = "Add to Another Playlist"
-
-function formatDuration(seconds: number): string {
- const minutes = Math.floor(seconds / 60)
- const remainingSeconds = seconds % 60
- return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
-}
-
-function PlaylistSongCover({
- song,
- inRange,
- isFavorite,
- onToggleFavorite,
-}: {
- song: BrowseSong
- inRange: boolean
- isFavorite: boolean
- onToggleFavorite: () => void
-}) {
- return (
-
-
-
- {
- event.stopPropagation()
- onToggleFavorite()
- }}
- >
-
-
-
-
- )
-}
-
-function PlaylistSongRow({
- song,
- index,
- isOwner,
- canRemove,
- isActive,
- selectionPosition,
- isFavorite,
- selectedCount,
- stationArtist,
- isDragging,
- onSelect,
- onPointerDown,
- onToggleFavorite,
- onPrepareContextMenu,
- onMediaAction,
- onRemove,
- onDragStart,
- onDragOver,
- onDrop,
- showFavoriteInMenu = true,
- removeLabel = "Remove from Playlist",
- isNowPlaying,
- onPlay,
-}: {
- song: BrowseSong
- index: number
- isOwner: boolean
- canRemove: boolean
- isActive: boolean
- selectionPosition: SelectionRangePosition
- isFavorite: boolean
- selectedCount: number
- stationArtist?: string
- isDragging: boolean
- onSelect: (event: React.MouseEvent) => void
- onPointerDown: (event: React.MouseEvent) => void
- onToggleFavorite: () => void
- onPrepareContextMenu: () => void
- onMediaAction: (action: MediaContextAction, songId: string) => void
- onRemove: () => void
- onDragStart: (event: React.DragEvent) => void
- onDragOver: (event: React.DragEvent) => void
- onDrop: (event: React.DragEvent) => void
- showFavoriteInMenu?: boolean
- removeLabel?: string
- isNowPlaying: boolean
- onPlay: () => void
-}) {
- const displayTrack = index + 1
- const inRange = isInSelectionRange(selectionPosition)
-
- return (
-
{
- event.preventDefault()
- onPlay()
- }}
- onKeyDown={(event) => {
- if (event.key === "Enter" || event.key === " ") {
- event.preventDefault()
- onSelect(event as unknown as React.MouseEvent)
- }
- }}
- className={cn(
- "group relative w-full cursor-pointer select-none py-2.5 text-left text-sm transition-colors",
- inRange && "text-primary-foreground",
- isDragging && "opacity-50"
- )}
- >
-
- {!inRange && isActive ?
: null}
- {!inRange && !isActive ?
: null}
-
-
-
-
-
-
{song.title}
-
-
- {formatDuration(song.durationSeconds)}
-
-
-
onMediaAction(action, song.id)}
- playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
- showFavorite={showFavoriteInMenu}
- favorited={isFavorite}
- navigation={{
- artist: { id: song.artist.id },
- album: { id: song.album.id },
- }}
- share={{
- type: "song",
- albumId: song.album.id,
- songId: song.id,
- }}
- >
- {canRemove ? (
- <>
-
-
- {removeLabel}
-
-
- >
- ) : null}
-
-
-
- )
-}
+const estimatePlaylistRowSize = () => 60
export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
const router = useRouter()
@@ -275,22 +54,17 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
currentUser === undefined
? playlist.isOwner
: currentUser?._id === playlist.owner.id
- const { openAddToPlaylist } = useAddToPlaylist()
+ const { isSongFavorite, toggleSongFavorite, toggleSongsFavorite } =
+ useFavorites()
+ const currentSongId = useCurrentSongId()
const {
- isSongFavorite,
- toggleSongFavorite,
- toggleSongsFavorite,
- favoriteSongs: addFavoriteSongs,
- } = useFavorites()
- const {
- currentSong,
playInOrder,
playShuffled,
playPlaylist,
playPlaylistShuffled,
playFromSong,
- } = usePlayback()
- const { runQueueAction, createStation } = useQueueMediaActions()
+ } = usePlaybackActions()
+ const { runSongsAction } = useMediaActions()
const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist)
const reorderSongs = useMutation(api.playlists.reorderPlaylistSongs)
const deletePlaylist = useMutation(api.playlists.deletePlaylist)
@@ -306,22 +80,19 @@ 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">),
[songs]
)
+ const playlistPositionById = React.useMemo(
+ () => new Map(songs.map((song, index) => [song.id, index + 1])),
+ [songs]
+ )
const [activeTrackId, setActiveTrackId] = React.useState("")
const [dragIndex, setDragIndex] = React.useState
(null)
const [isSubscribed, setIsSubscribed] = React.useState(playlist.isSubscribed)
@@ -336,7 +107,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
const {
selectedIds,
selectedCount,
- isSelected,
handleSelect,
handlePointerDown,
prepareContextMenu,
@@ -374,57 +144,37 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
}
}
- function resolveTargetIds(fallbackSongId?: string) {
- return selectedIds.size > 0
- ? Array.from(selectedIds)
- : fallbackSongId
- ? [fallbackSongId]
- : activeTrackId
- ? [activeTrackId]
- : []
- }
-
- function handleMediaAction(
- action: MediaContextAction,
- fallbackSongId?: string
- ) {
- const targetIds = resolveTargetIds(fallbackSongId)
-
- switch (action) {
- case "create-station": {
- const artistId = stationArtistId(songs, new Set(targetIds))
- if (artistId) void createStation(artistId)
- break
- }
- case "favorite":
- void addFavoriteSongs(targetIds as Id<"songs">[])
- break
- case "playlist":
- openAddToPlaylist(targetIds as Id<"songs">[])
- break
- case "play-next":
- case "play-last":
- case "shuffle":
- void runQueueAction(action, targetIds as Id<"songs">[])
- break
- }
- }
+ const handleMediaAction = useTrackListMediaAction({ selectedIds, songs })
function handlePlaylistMediaAction(action: MediaContextAction) {
- const targetIds = songs.map((song) => song.id as Id<"songs">)
+ runSongsAction(action, playlistSongIds)
+ }
- switch (action) {
- case "favorite":
- void addFavoriteSongs(targetIds)
- break
- case "playlist":
- openAddToPlaylist(targetIds)
- break
- case "play-next":
- case "play-last":
- case "shuffle":
- void runQueueAction(action, targetIds)
- break
+ const canReorder = isOwner && !isFavorites && !isSearching
+
+ function handleRowSelect(index: number, event: React.MouseEvent) {
+ const songId = filteredSongs[index].id
+ handleSelect(songId, index, event)
+ setActiveTrackId(songId)
+ }
+
+ function handleRowPlay(index: number) {
+ void playFromSong(
+ filteredSongs[index].id,
+ playlistSongIds,
+ `playlist:${playlist.id}`
+ )
+ }
+
+ function handleToggleFavorite(songId: string) {
+ const wasFavorite = isSongFavorite(songId)
+ void toggleSongFavorite(songId as Id<"songs">)
+ if (isFavorites && wasFavorite) {
+ setHiddenFavoriteIds((current) => {
+ const next = new Set(current)
+ next.add(songId)
+ return next
+ })
}
}
@@ -435,10 +185,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
: [songId]
if (isFavorites) {
- const succeeded = await toggleSongsFavorite(
- ids as Id<"songs">[],
- true
- )
+ const succeeded = await toggleSongsFavorite(ids as Id<"songs">[], true)
if (!succeeded) return
return
}
@@ -451,7 +198,9 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
setPlaylistSongs((current) =>
current.filter((song) => !ids.includes(song.id))
)
- toast.success(ids.length > 1 ? `Removed ${ids.length} songs` : "Removed song")
+ toast.success(
+ ids.length > 1 ? `Removed ${ids.length} songs` : "Removed song"
+ )
} catch (error) {
toast.error(
error instanceof Error ? error.message : "Failed to remove song"
@@ -479,13 +228,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
}
function handleDrop(targetIndex: number) {
- if (
- normalizedQuery ||
- isFavorites ||
- !isOwner ||
- dragIndex === null ||
- dragIndex === targetIndex
- ) {
+ if (!canReorder || dragIndex === null || dragIndex === targetIndex) {
setDragIndex(null)
return
}
@@ -546,7 +289,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
-
+
{isFavorites ? (
@@ -676,80 +419,52 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
{filteredSongs.length > 0 ? (
- filteredSongs.map((song, index) => (
-
0
- ? selectedCount
- : 1
- }
- stationArtist={
- isSelected(song.id)
- ? selectedStationArtistId
- : song.artist.id
- }
- isDragging={dragIndex === index}
- onPointerDown={handlePointerDown}
- onSelect={(event) => {
- handleSelect(song.id, index, event)
- setActiveTrackId(song.id)
- }}
- onToggleFavorite={() => {
- const wasFavorite = isSongFavorite(song.id)
- void toggleSongFavorite(song.id as Id<"songs">)
- if (isFavorites && wasFavorite) {
- setHiddenFavoriteIds((current) => {
- const next = new Set(current)
- next.add(song.id)
- return next
- })
- }
- }}
- onPrepareContextMenu={() => prepareContextMenu(song.id)}
- onMediaAction={handleMediaAction}
- onRemove={() => handleRemoveSong(song.id)}
- onDragStart={(event) => {
- if (normalizedQuery || isFavorites || !isOwner) {
- return
- }
- setDragIndex(index)
- event.dataTransfer.effectAllowed = "move"
- }}
- onDragOver={(event) => {
- if (normalizedQuery || isFavorites || !isOwner) {
- return
- }
- event.preventDefault()
- }}
- onDrop={(event) => {
- event.preventDefault()
- handleDrop(index)
- }}
- isNowPlaying={currentSong?.id === song.id}
- onPlay={() =>
- void playFromSong(
- song.id as Id<"songs">,
- playlistSongIds,
- `playlist:${playlist.id}`
- )
- }
- />
- ))
+ filteredSongs[index].id}
+ // Keep the drag source mounted so its drop still lands.
+ keepMounted={dragIndex}
+ renderItem={(index) => {
+ const song = filteredSongs[index]
+ return (
+
+ )
+ }}
+ />
) : (
- {normalizedQuery
+ {isSearching
? "No songs found."
: "This playlist has no songs yet."}
diff --git a/apps/web/components/queue-panel.tsx b/apps/web/components/queue-panel.tsx
index 10544ac..d2513bc 100644
--- a/apps/web/components/queue-panel.tsx
+++ b/apps/web/components/queue-panel.tsx
@@ -1,11 +1,10 @@
"use client"
import * as React from "react"
-import Image from "next/image"
-import { Music2 } from "lucide-react"
import { PlaybackSongMeta } from "@/components/playback-song-meta"
import { usePlayback } from "@/components/playback-provider"
+import { TrackCover, TrackRow } from "@/components/track-row"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Skeleton } from "@/components/ui/skeleton"
@@ -13,21 +12,14 @@ import { Spinner } from "@/components/ui/spinner"
import { useTrackSelection } from "@/hooks/use-track-selection"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong, HistorySong, QueueSong } from "@otunes/convex/types"
-import { albumCoverUrl } from "@/lib/cover-urls"
import {
getContiguousSelectedIndices,
moveQueueBlock,
} from "@/lib/move-queue-block"
-import {
- getSelectionRangePositions,
- isInSelectionRange,
- QueueSelectionRangeHighlight,
- QueueTrackRowActiveHighlight,
- QueueTrackRowHoverHighlight,
- type SelectionRangePosition,
-} from "@/lib/selection-range-styles"
+import { getSelectionRangePositions } from "@/lib/selection-range-styles"
import { useSongs } from "@/lib/song-cache"
import { cn } from "@/lib/utils"
+import { formatDuration } from "@/lib/format-duration"
const QUEUE_INITIAL_VISIBLE_COUNT = 100
const QUEUE_PAGE_SIZE = 50
@@ -40,12 +32,6 @@ type QueueItem = {
song: QueueSelectable | null
}
-function formatDuration(seconds: number): string {
- const minutes = Math.floor(seconds / 60)
- const remainingSeconds = seconds % 60
- return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
-}
-
function toSelectableQueue(
songIds: Id<"songs">[],
songs: (BrowseSong | undefined)[]
@@ -61,48 +47,16 @@ function toSelectableQueue(
})
}
-function QueueSongCover({
- albumId,
- title,
- inRange,
-}: {
- albumId: string
- title: string
- inRange: boolean
-}) {
- return (
-
-
-
- )
-}
-
function HistorySongRow({ song }: { song: HistorySong }) {
return (
- {song.album.id ? (
-
- ) : (
-
-
-
- )}
+
void
- onPointerDown: (event: React.MouseEvent) => void
- onSkipTo: () => void
- onDragStart: (event: React.DragEvent) => void
- onDragOver: (event: React.DragEvent) => void
- onDrop: (event: React.DragEvent) => void
- }
->(function QueueSongRow(
- {
- song,
- isNowPlaying,
- selectionPosition,
- isDragging,
- onSelect,
- onPointerDown,
- onSkipTo,
- onDragStart,
- onDragOver,
- onDrop,
- },
- ref
-) {
- const inRange = isInSelectionRange(selectionPosition)
-
- return (
- {
- event.preventDefault()
- onSkipTo()
- }}
- onKeyDown={(event) => {
- if (event.key === "Enter" || event.key === " ") {
- event.preventDefault()
- onSelect(event as unknown as React.MouseEvent)
- }
- }}
- className={cn(
- "group relative w-full cursor-pointer select-none py-2 text-left text-sm transition-colors",
- inRange && "text-primary-foreground",
- isDragging && "opacity-50"
- )}
- >
-
- {!inRange && isNowPlaying ? : null}
- {!inRange && !isNowPlaying ? : null}
-
- {song.album.id ? (
-
- ) : (
-
-
-
- )}
-
-
-
-
- {formatDuration(song.durationSeconds)}
-
-
-
- )
-})
-
function QueueSongRowSkeleton() {
return (
@@ -243,7 +97,7 @@ export function QueuePanel() {
skipToQueueIndex,
} = usePlayback()
const loadMoreRef = React.useRef(null)
- const nowPlayingRef = React.useRef(null)
+ const nowPlayingRef = React.useRef(null)
const [visibleCount, setVisibleCount] = React.useState(
QUEUE_INITIAL_VISIBLE_COUNT
)
@@ -311,12 +165,25 @@ export function QueuePanel() {
return () => observer.disconnect()
}, [hasMore])
- const {
- selectedIds,
- handleSelect,
- handlePointerDown,
- } = useTrackSelection(
- selectableQueue.map((item) => ({ id: item.selectionId }))
+ const selectionItems = React.useMemo(
+ () => selectableQueue.map((item) => ({ id: item.selectionId })),
+ [selectableQueue]
+ )
+ const { selectedIds, handleSelect, handlePointerDown } =
+ useTrackSelection(selectionItems)
+
+ const handleRowSelect = React.useCallback(
+ (index: number, event: React.MouseEvent) => {
+ handleSelect(selectableQueue[index].selectionId, index, event)
+ },
+ [selectableQueue, handleSelect]
+ )
+
+ const handleRowPlay = React.useCallback(
+ (index: number) => {
+ void skipToQueueIndex(selectableQueue[index].queueIndex)
+ },
+ [selectableQueue, skipToQueueIndex]
)
const selectionPositions = React.useMemo(
@@ -403,27 +270,21 @@ export function QueuePanel() {
{selectableQueue.map((item, index) =>
item.song ? (
- {
- handleSelect(item.selectionId, index, event)
- }}
- onSkipTo={() => void skipToQueueIndex(item.queueIndex)}
- onDragStart={(event) => {
- setDragIndex(index)
- event.dataTransfer.effectAllowed = "move"
- }}
- onDragOver={(event) => event.preventDefault()}
- onDrop={(event) => {
- event.preventDefault()
- handleDrop(index)
- }}
+ onSelect={handleRowSelect}
+ onPlay={handleRowPlay}
+ onDragStart={setDragIndex}
+ onDrop={handleDrop}
/>
) : (
diff --git a/apps/web/components/search-song-item.tsx b/apps/web/components/search-song-item.tsx
index 136d8ee..b4bfe05 100644
--- a/apps/web/components/search-song-item.tsx
+++ b/apps/web/components/search-song-item.tsx
@@ -8,6 +8,8 @@ import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import {
MediaContextMenu,
type MediaContextAction,
+ MediaContextMenuArea,
+ type MediaContextMenuProps,
} from "@/components/media-context-menu"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong } from "@otunes/convex/types"
@@ -38,52 +40,57 @@ export function SearchSongItem({ song }: { song: BrowseSong }) {
}
}
+ const menu: MediaContextMenuProps = {
+ label: `More options for ${song.title}`,
+ stationArtistId: song.artist.id,
+ selectedCount: 1,
+ onOpenMenu: () => {},
+ onAction: handleAction,
+ favorited: isSongFavorite(song.id),
+ navigation: {
+ artist: { id: song.artist.id },
+ album: { id: song.album.id },
+ },
+ share: {
+ type: "song",
+ albumId: song.album.id,
+ songId: song.id,
+ },
+ triggerClassName:
+ "size-8 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100",
+ triggerVariant: "ghost",
+ }
+
return (
-
-
-
-
-
-
-
-
{song.title}
-
+
+
- {}}
- onAction={handleAction}
- favorited={isSongFavorite(song.id)}
- navigation={{
- artist: { id: song.artist.id },
- album: { id: song.album.id },
- }}
- share={{
- type: "song",
- albumId: song.album.id,
- songId: song.id,
- }}
- triggerClassName="size-8 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100"
- triggerVariant="ghost"
- />
-
+
+
+
{song.title}
+
+
+
{song.artist.name}
+
+
+
+
+
+
)
}
diff --git a/apps/web/components/songs-view.tsx b/apps/web/components/songs-view.tsx
index 066fb5b..b0404b7 100644
--- a/apps/web/components/songs-view.tsx
+++ b/apps/web/components/songs-view.tsx
@@ -2,18 +2,20 @@
import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger"
import { stationArtistId } from "@/lib/station-artist"
-import { useEffect, useMemo, useState, useRef, MouseEvent } from "react"
-import Image from "next/image"
-import Link from "next/link"
-import { ArrowUpDown, Play, Star } from "lucide-react"
-
-import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
-import { useFavorites } from "@/components/favorites-provider"
-import { usePlayback } from "@/components/playback-provider"
import {
- MediaContextMenu,
- type MediaContextAction,
-} from "@/components/media-context-menu"
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+ useRef,
+ type MouseEvent,
+} from "react"
+import { ArrowUpDown } from "lucide-react"
+
+import { useFavorites } from "@/components/favorites-provider"
+import { usePlaybackActions } from "@/components/playback-provider"
+import { LibraryTrackListHeader, TrackRow } from "@/components/track-row"
+import { VirtualList } from "@/components/virtual-list"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
@@ -25,252 +27,28 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
-import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
+import { useTrackListMediaAction } from "@/hooks/use-media-actions"
import { useTrackSelection } from "@/hooks/use-track-selection"
import { SongListSkeleton } from "@/components/library-skeletons"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Spinner } from "@/components/ui/spinner"
import { api } from "@otunes/convex/_generated/api"
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@/components/ui/table"
import { cn } from "@/lib/utils"
import type { Id } from "@otunes/convex/_generated/dataModel"
-import type { BrowseSong } from "@otunes/convex/types"
-import { albumCoverUrl } from "@/lib/cover-urls"
import {
getSelectionRangePositions,
- isInSelectionRange,
- ALBUM_TRACK_TITLE,
- SongsSelectionRangeHighlight,
- SongsTrackRowHoverHighlight,
TRACK_ROW_PADDING,
- type SelectionRangePosition,
} from "@/lib/selection-range-styles"
type SortKey = "title" | "artist" | "album"
type SortDirection = "asc" | "desc"
const SONGS_PAGE_SIZE = 50
-
-const songRowLayout =
- "flex w-full items-center gap-x-4"
-const nameColumnLayout =
- "grid grid-cols-[2rem_2.5rem_minmax(0,10rem)] items-center gap-x-2"
-const songColumnClass = "w-36 shrink-0 truncate"
-
-function formatDuration(seconds: number): string {
- const minutes = Math.floor(seconds / 60)
- const remainingSeconds = seconds % 60
- return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
-}
-
-function SongCover({
- song,
- inRange,
- onPlay,
-}: {
- song: BrowseSong
- inRange: boolean
- onPlay: () => void
-}) {
- return (
-
-
-
-
{
- event.preventDefault()
- event.stopPropagation()
- onPlay()
- }}
- >
-
-
-
-
- )
-}
-
-function SongRow({
- song,
- isSelected,
- selectionPosition,
- isFavorite,
- selectedCount,
- stationArtist,
- onSelect,
- onPointerDown,
- onToggleFavorite,
- onPrepareContextMenu,
- onMediaAction,
- onPlay,
-}: {
- song: BrowseSong
- isSelected: boolean
- selectionPosition: SelectionRangePosition
- isFavorite: boolean
- selectedCount: number
- stationArtist?: string
- onSelect: (event: MouseEvent) => void
- onPointerDown: (event: MouseEvent) => void
- onToggleFavorite: () => void
- onPrepareContextMenu: () => void
- onMediaAction: (action: MediaContextAction, songId: string) => void
- onPlay: () => void
-}) {
- const inRange = isInSelectionRange(selectionPosition)
- const linkClass = inRange
- ? "text-primary-foreground hover:text-primary-foreground/80 hover:underline"
- : "text-muted-foreground hover:text-foreground hover:underline"
-
- return (
- {
- event.preventDefault()
- onPlay()
- }}
- className="group cursor-pointer select-none border-none hover:bg-transparent"
- >
-
-
-
- {!inRange ?
: null}
-
-
-
- {
- event.stopPropagation()
- onToggleFavorite()
- }}
- >
-
-
-
-
-
- {song.title}
- {song.explicit ? (
-
- E
-
- ) : null}
-
-
-
- event.stopPropagation()}
- >
- {song.artist.name}
-
-
-
- event.stopPropagation()}
- >
- {song.album.title}
-
-
-
-
- {formatDuration(song.durationSeconds)}
-
-
onMediaAction(action, song.id)}
- favorited={isFavorite}
- navigation={{
- artist: { id: song.artist.id },
- album: { id: song.album.id },
- }}
- share={{
- type: "song",
- albumId: song.album.id,
- songId: song.id,
- }}
- />
-
-
-
-
- )
-}
+const estimateSongRowSize = () => 56
export function SongsView() {
- const { openAddToPlaylist } = useAddToPlaylist()
- const { isSongFavorite, toggleSongFavorite, favoriteSongs } = useFavorites()
- const { playFromLibrarySong } = usePlayback()
- const { runQueueAction, createStation } = useQueueMediaActions()
+ const { isSongFavorite, toggleSongFavorite } = useFavorites()
+ const { playFromLibrarySong } = usePlaybackActions()
const [sortKey, setSortKey] = useState("title")
const [sortDirection, setSortDirection] =
useState("asc")
@@ -311,7 +89,6 @@ export function SongsView() {
const {
selectedIds,
selectedCount,
- isSelected,
handleSelect,
handlePointerDown,
prepareContextMenu,
@@ -332,32 +109,27 @@ export function SongsView() {
[songs, selectedIds]
)
- function handleMediaAction(action: MediaContextAction, fallbackSongId?: string) {
- const targetIds =
- selectedIds.size > 0
- ? Array.from(selectedIds)
- : fallbackSongId
- ? [fallbackSongId]
- : []
- switch (action) {
- case "create-station": {
- const artistId = stationArtistId(songs, new Set(targetIds))
- if (artistId) void createStation(artistId)
- break
- }
- case "favorite":
- void favoriteSongs(targetIds as Id<"songs">[])
- break
- case "playlist":
- openAddToPlaylist(targetIds as Id<"songs">[])
- break
- case "play-next":
- case "play-last":
- case "shuffle":
- void runQueueAction(action, targetIds as Id<"songs">[])
- break
- }
- }
+ const handleMediaAction = useTrackListMediaAction({ selectedIds, songs })
+
+ const handleRowSelect = useCallback(
+ (index: number, event: MouseEvent) => {
+ handleSelect(songs[index].id, index, event)
+ },
+ [songs, handleSelect]
+ )
+
+ const handleRowPlay = useCallback(
+ (index: number) => {
+ void playFromLibrarySong(songs[index].id, { sortKey, sortDirection })
+ },
+ [songs, sortKey, sortDirection, playFromLibrarySong]
+ )
+
+ const handleToggleFavorite = useCallback(
+ (songId: string) => void toggleSongFavorite(songId as Id<"songs">),
+ [toggleSongFavorite]
+ )
+ const getSongKey = useCallback((index: number) => songs[index].id, [songs])
if (status === "LoadingFirstPage" && !isCached) {
return (
@@ -428,7 +200,7 @@ export function SongsView() {
) : null}
-
+
{
@@ -437,68 +209,29 @@ export function SongsView() {
}
}}
>
-
-
-
-
-
-
-
-
- Name
-
-
- Artist
-
-
- Album
-
-
-
- Time
-
-
-
-
-
-
-
- {songs.map((song, index) => (
- 0
- ? selectedCount
- : 1
- }
- onPointerDown={handlePointerDown}
- onSelect={(event) => {
- handleSelect(song.id, index, event)
- }}
- onToggleFavorite={() =>
- void toggleSongFavorite(song.id as Id<"songs">)
- }
- onPrepareContextMenu={() => prepareContextMenu(song.id)}
- onMediaAction={handleMediaAction}
- onPlay={() =>
- void playFromLibrarySong(song.id as Id<"songs">, {
- sortKey,
- sortDirection,
- })
- }
- />
- ))}
-
-
+
+
(
+
+ )}
+ />
{
+ event.stopPropagation()
+ setIsPlaying(!isPlaying)
+ }}
+ >
+
+ {isPlaying ? (
+
+ ) : (
+
+ )}
+
+
+ {isPlaying ? (
+
+ ) : (
+
+ )}
+
+
+ )
+}
+
export function TrackNumberPlayButton({
displayTrack,
title,
@@ -22,26 +74,7 @@ export function TrackNumberPlayButton({
inRange: boolean
onPlay: () => void
}) {
- const { isPlaying, setIsPlaying } = usePlayback()
const showPlay = isActive || isNowPlaying
- const isCurrentlyPlaying = isNowPlaying && isPlaying
-
- const buttonClassName = cn(
- "absolute size-8 opacity-0 transition-opacity group-hover:opacity-100",
- showPlay && "opacity-100",
- inRange
- ? "text-primary-foreground hover:bg-white/15 hover:text-primary-foreground"
- : "text-primary hover:text-primary"
- )
-
- const handleClick = (event: MouseEvent) => {
- event.stopPropagation()
- if (isNowPlaying) {
- setIsPlaying(!isPlaying)
- return
- }
- onPlay()
- }
return (
{isNowPlaying ? (
-
-
- {isCurrentlyPlaying ? (
-
- ) : (
-
- )}
-
-
- {isCurrentlyPlaying ? (
-
- ) : (
-
- )}
-
-
+
) : (
{
+ event.stopPropagation()
+ onPlay()
+ }}
>
diff --git a/apps/web/components/track-row.tsx b/apps/web/components/track-row.tsx
new file mode 100644
index 0000000..9cbb54a
--- /dev/null
+++ b/apps/web/components/track-row.tsx
@@ -0,0 +1,518 @@
+"use client"
+
+import * as React from "react"
+import Image from "next/image"
+import Link from "next/link"
+import { Music2, Play, Star, Trash2 } from "lucide-react"
+
+import {
+ MediaContextMenu,
+ MediaContextMenuArea,
+ MediaMenuItem,
+ MediaMenuSeparator,
+ type MediaContextAction,
+ type MediaContextMenuProps,
+} from "@/components/media-context-menu"
+import { PlaybackSongMeta } from "@/components/playback-song-meta"
+import { TrackNumberPlayButton } from "@/components/track-number-play-button"
+import { Button } from "@/components/ui/button"
+import { albumCoverUrl } from "@/lib/cover-urls"
+import {
+ ALBUM_TRACK_ROW,
+ ALBUM_TRACK_TITLE,
+ isInSelectionRange,
+ SelectionRangeHighlight,
+ TrackRowActiveHighlight,
+ TrackRowHoverHighlight,
+ TRACK_ROW_PADDING,
+ type SelectionRangePosition,
+} from "@/lib/selection-range-styles"
+import { formatDuration } from "@/lib/format-duration"
+import { cn } from "@/lib/utils"
+import type { BrowseSong } from "@otunes/convex/types"
+
+/**
+ * - `library`: favorite star, cover with play overlay, title, artist and album
+ * columns (use with `LibraryTrackListHeader`).
+ * - `album`: favorite star, track number, title with optional credits.
+ * - `playlist`: cover with favorite overlay, track number, title.
+ * - `queue`: square cover, title and artist, no menu.
+ */
+export type TrackRowVariant = "library" | "album" | "playlist" | "queue"
+
+export type TrackRowProps = {
+ variant: TrackRowVariant
+ song: BrowseSong
+ /** Position in the list the selection hook was given. */
+ index: number
+ /** Number shown in the track number column (`album` and `playlist`). */
+ trackNumber?: number
+ /** Secondary line under the title, e.g. album track credits. */
+ subtitle?: string
+ selectionPosition: SelectionRangePosition
+ isActive?: boolean
+ isNowPlaying?: boolean
+ isFavorite?: boolean
+ isDragging?: boolean
+ /** Total selected songs; the menu acts on these when this row is selected. */
+ selectedCount?: number
+ /** Station artist for the selection when this row is selected. */
+ selectionStationArtistId?: string
+ playlistLabel?: string
+ showFavoriteInMenu?: boolean
+ /** Adds a destructive menu item calling `onRemove`. */
+ removeLabel?: string
+ ref?: React.Ref
+ onSelect: (index: number, event: React.MouseEvent) => void
+ onPointerDown: (event: React.MouseEvent) => void
+ onPlay: (index: number) => void
+ onToggleFavorite?: (songId: string) => void
+ onPrepareContextMenu?: (songId: string) => void
+ /** Renders the "more options" and right-click menus when provided. */
+ onMediaAction?: (action: MediaContextAction, songId: string) => void
+ onRemove?: (songId: string) => void
+ /** Makes the row draggable when provided. */
+ onDragStart?: (index: number) => void
+ onDrop?: (index: number) => void
+}
+
+const LIBRARY_ROW_LAYOUT = "flex w-full items-center gap-x-4"
+const LIBRARY_NAME_COLUMNS =
+ "grid grid-cols-[2rem_2.5rem_minmax(0,10rem)] items-center gap-x-2"
+const LIBRARY_COLUMN = "w-36 shrink-0 truncate"
+
+export function TrackCover({
+ albumId,
+ alt,
+ inRange,
+ square = false,
+ children,
+}: {
+ albumId: string | undefined
+ alt: string
+ inRange: boolean
+ square?: boolean
+ /** Overlay shown above the cover image. */
+ children?: React.ReactNode
+}) {
+ const ringClass = inRange ? "ring-white/25" : "ring-foreground/10"
+
+ if (!albumId) {
+ return (
+
+
+
+ )
+ }
+
+ return (
+
+
+ {children}
+
+ )
+}
+
+function FavoriteStarButton({
+ title,
+ isFavorite,
+ inRange,
+ className,
+ onToggle,
+}: {
+ title: string
+ isFavorite: boolean
+ inRange: boolean
+ className?: string
+ onToggle: () => void
+}) {
+ return (
+ {
+ event.stopPropagation()
+ onToggle()
+ }}
+ >
+
+
+ )
+}
+
+function ExplicitBadge({ inRange }: { inRange: boolean }) {
+ return (
+
+ E
+
+ )
+}
+
+function TrackTitle({
+ song,
+ subtitle,
+ inRange,
+}: {
+ song: BrowseSong
+ subtitle?: string
+ inRange: boolean
+}) {
+ return (
+
+
+ {song.title}
+ {song.explicit ? : null}
+
+ {subtitle ? (
+
+ {subtitle}
+
+ ) : null}
+
+ )
+}
+
+export function LibraryTrackListHeader() {
+ const labelClass = "text-xs text-muted-foreground"
+ return (
+
+
+
+
+ Name
+
+
Artist
+
Album
+
+
Time
+
+
+ )
+}
+
+function TrackRowComponent({
+ variant,
+ song,
+ index,
+ trackNumber,
+ subtitle,
+ selectionPosition,
+ isActive = false,
+ isNowPlaying = false,
+ isFavorite = false,
+ isDragging = false,
+ selectedCount = 0,
+ selectionStationArtistId,
+ playlistLabel,
+ showFavoriteInMenu = true,
+ removeLabel,
+ ref,
+ onSelect,
+ onPointerDown,
+ onPlay,
+ onToggleFavorite,
+ onPrepareContextMenu,
+ onMediaAction,
+ onRemove,
+ onDragStart,
+ onDrop,
+}: TrackRowProps) {
+ const inRange = isInSelectionRange(selectionPosition)
+ const flush = variant === "library" || variant === "queue"
+ const play = () => onPlay(index)
+ const toggleFavorite = () => onToggleFavorite?.(song.id)
+
+ const favoriteStar = (
+
+
+
+ )
+
+ const trackNumberButton = (
+
+ )
+
+ const duration = (
+
+ {formatDuration(song.durationSeconds)}
+
+ )
+
+ // Shared by the "more options" button and the right-click menu.
+ const menuProps: MediaContextMenuProps | null = onMediaAction
+ ? {
+ label: `More options for ${song.title}`,
+ stationArtistId: inRange ? selectionStationArtistId : song.artist.id,
+ selectedCount: inRange && selectedCount > 0 ? selectedCount : 1,
+ inSelectionRange: inRange,
+ onOpenMenu: () => onPrepareContextMenu?.(song.id),
+ onAction: (action) => onMediaAction(action, song.id),
+ playlistLabel,
+ showFavorite: showFavoriteInMenu,
+ favorited: isFavorite,
+ navigation: {
+ artist: { id: song.artist.id },
+ album: { id: song.album.id },
+ },
+ share: { type: "song", albumId: song.album.id, songId: song.id },
+ children:
+ removeLabel && onRemove ? (
+ <>
+
+ onRemove(song.id)}
+ >
+ {removeLabel}
+
+
+ >
+ ) : null,
+ }
+ : null
+ const menu = menuProps ? : null
+
+ let content: React.ReactNode
+ switch (variant) {
+ case "library": {
+ const linkClass = inRange
+ ? "text-primary-foreground hover:text-primary-foreground/80 hover:underline"
+ : "text-muted-foreground hover:text-foreground hover:underline"
+ content = (
+
+
+ {favoriteStar}
+
+
+
{
+ event.preventDefault()
+ event.stopPropagation()
+ play()
+ }}
+ >
+
+
+
+
+
+
+
+ event.stopPropagation()}
+ >
+ {song.artist.name}
+
+
+
+ event.stopPropagation()}
+ >
+ {song.album.title}
+
+
+
+ {duration}
+ {menu}
+
+ )
+ break
+ }
+ case "album":
+ content = (
+
+ {favoriteStar}
+ {trackNumberButton}
+
+ {duration}
+ {menu}
+
+ )
+ break
+ case "playlist":
+ content = (
+
+
+
+
+
+
+ {trackNumberButton}
+
+ {duration}
+ {menu}
+
+ )
+ break
+ case "queue":
+ content = (
+
+ )
+ break
+ }
+
+ const shellProps = {
+ role: "button",
+ tabIndex: 0,
+ draggable: onDragStart ? true : undefined,
+ onDragStart: onDragStart
+ ? (event: React.DragEvent) => {
+ event.dataTransfer.effectAllowed = "move"
+ onDragStart(index)
+ }
+ : undefined,
+ onDragOver: onDragStart
+ ? (event: React.DragEvent) => event.preventDefault()
+ : undefined,
+ onDrop: onDrop
+ ? (event: React.DragEvent) => {
+ event.preventDefault()
+ onDrop(index)
+ }
+ : undefined,
+ onMouseDown: onPointerDown,
+ onClick: (event: React.MouseEvent) => onSelect(index, event),
+ onDoubleClick: (event: React.MouseEvent) => {
+ event.preventDefault()
+ play()
+ },
+ onKeyDown: (event: React.KeyboardEvent) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault()
+ onSelect(index, event as unknown as React.MouseEvent)
+ }
+ },
+ className: cn(
+ "group relative w-full cursor-pointer select-none text-left text-sm transition-colors",
+ flush ? "py-2" : "py-2.5",
+ inRange && "text-primary-foreground",
+ isDragging && "opacity-50"
+ ),
+ }
+
+ const children = (
+ <>
+
+ {!inRange && isActive ? : null}
+ {!inRange && !isActive ? : null}
+ {content}
+ >
+ )
+
+ const shell =
+ variant === "queue" ? (
+ - } {...shellProps}>
+ {children}
+
+ ) : (
+ } {...shellProps}>
+ {children}
+
+ )
+
+ return menuProps ? (
+ {shell}
+ ) : (
+ shell
+ )
+}
+
+/**
+ * Pass stable callbacks: they receive the row's `index` or song id, so one
+ * handler can serve every row.
+ */
+export const TrackRow = React.memo(TrackRowComponent)
diff --git a/apps/web/components/virtual-list.tsx b/apps/web/components/virtual-list.tsx
new file mode 100644
index 0000000..66f0e63
--- /dev/null
+++ b/apps/web/components/virtual-list.tsx
@@ -0,0 +1,120 @@
+"use client"
+
+import * as React from "react"
+import {
+ defaultRangeExtractor,
+ useVirtualizer,
+ type Range,
+} from "@tanstack/react-virtual"
+
+import { cn } from "@/lib/utils"
+
+const scrollViewportSelector = '[data-slot="scroll-area-viewport"]'
+
+/**
+ * Renders only the visible items of a list placed inside a `ScrollArea`.
+ * The list may sit below other content in the same viewport.
+ */
+export function VirtualList({
+ count,
+ estimateSize,
+ getItemKey,
+ renderItem,
+ overscan = 10,
+ keepMounted = null,
+ className,
+}: {
+ count: number
+ estimateSize: (index: number) => number
+ getItemKey: (index: number) => string
+ renderItem: (index: number) => React.ReactNode
+ overscan?: number
+ /** Index rendered even when off screen, e.g. the source of a drag. */
+ keepMounted?: number | null
+ className?: string
+}) {
+ const listRef = React.useRef(null)
+ const [scrollMargin, setScrollMargin] = React.useState(0)
+
+ React.useLayoutEffect(() => {
+ const list = listRef.current
+ const viewport = list?.closest(scrollViewportSelector)
+ if (!list || !viewport) return
+
+ const measure = () => {
+ setScrollMargin(
+ Math.round(
+ list.getBoundingClientRect().top -
+ viewport.getBoundingClientRect().top +
+ viewport.scrollTop
+ )
+ )
+ }
+ const observer = new ResizeObserver(measure)
+ observer.observe(viewport)
+ if (viewport.firstElementChild) {
+ observer.observe(viewport.firstElementChild)
+ }
+ return () => observer.disconnect()
+ }, [])
+
+ const getScrollElement = () =>
+ listRef.current?.closest(scrollViewportSelector) ?? null
+
+ const virtualizer = useVirtualizer({
+ count,
+ getScrollElement,
+ // The virtualizer scrolls to this offset on attach. Keep the viewport's
+ // current position so `ScrollRestoration` is not reset to the top.
+ initialOffset: () => getScrollElement()?.scrollTop ?? 0,
+ estimateSize,
+ getItemKey,
+ overscan,
+ scrollMargin,
+ rangeExtractor: React.useCallback(
+ (range: Range) => {
+ const indexes = defaultRangeExtractor(range)
+ if (
+ keepMounted !== null &&
+ keepMounted < range.count &&
+ !indexes.includes(keepMounted)
+ ) {
+ indexes.push(keepMounted)
+ indexes.sort((a, b) => a - b)
+ }
+ return indexes
+ },
+ [keepMounted]
+ ),
+ })
+
+ // The virtualizer caches its offset across a detach. Clear it so a
+ // re-attach (e.g. StrictMode's effect replay) re-reads `initialOffset`
+ // instead of scrolling back to a stale position.
+ React.useLayoutEffect(
+ () => () => {
+ virtualizer.scrollOffset = null
+ },
+ [virtualizer]
+ )
+
+ return (
+
+ {virtualizer.getVirtualItems().map((item) => (
+
+ {renderItem(item.index)}
+
+ ))}
+
+ )
+}
diff --git a/apps/web/generateKeys.mjs b/apps/web/generateKeys.mjs
deleted file mode 100644
index 33d723b..0000000
--- a/apps/web/generateKeys.mjs
+++ /dev/null
@@ -1,15 +0,0 @@
-import { exportJWK, exportPKCS8, generateKeyPair } from "jose";
-
-const keys = await generateKeyPair("RS256", {
- extractable: true,
-});
-const privateKey = await exportPKCS8(keys.privateKey);
-const publicKey = await exportJWK(keys.publicKey);
-const jwks = JSON.stringify({ keys: [{ use: "sig", ...publicKey }] });
-
-process.stdout.write(
- `JWT_PRIVATE_KEY="${privateKey.trimEnd().replace(/\n/g, " ")}"`,
-);
-process.stdout.write("\n");
-process.stdout.write(`JWKS=${jwks}`);
-process.stdout.write("\n");
diff --git a/apps/web/hooks/use-cached-query.ts b/apps/web/hooks/use-cached-query.ts
index 87da8ff..98950ca 100644
--- a/apps/web/hooks/use-cached-query.ts
+++ b/apps/web/hooks/use-cached-query.ts
@@ -9,13 +9,18 @@ import {
type PaginatedQueryReference,
} from "convex/react"
import type { FunctionReference } from "convex/server"
-import { useCallback, useEffect, useSyncExternalStore } from "react"
+import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react"
import { useCacheScope } from "@/components/persistent-cache-provider"
import { queryCacheKey } from "@otunes/convex/client/cached-query"
import { readCache, subscribeCache, writeCache } from "@/lib/persistent-cache"
const MAX_CACHED_PAGINATED_ITEMS = 200
+const MAX_RESTORED_PAGINATED_ITEMS = 1000
+
+// Items loaded per paginated query this session, so a remount (e.g. back
+// navigation) loads as much as before and scroll restoration can reach it.
+const loadedItemCounts = new Map()
const noopUnsubscribe = () => {}
@@ -65,6 +70,7 @@ export function useCachedQuery>(
/**
* `usePaginatedQuery` that shows the first persisted pages while the first live
* page loads. `isCached` is true while those persisted results are shown.
+ * Remounts start with as many items as were last loaded this session.
*/
export function useCachedPaginatedQuery(
query: Query,
@@ -72,15 +78,28 @@ export function useCachedPaginatedQuery(
options: { initialNumItems: number }
) {
const scope = useCacheScope()
- const result = usePaginatedQuery(query, args, options)
const key =
args === "skip"
? null
: `${queryCacheKey(scope, query, args as Record)}:pages`
+ // Fixed per key: `usePaginatedQuery` restarts when this changes.
+ const initialNumItems = useMemo(
+ () =>
+ Math.max(
+ options.initialNumItems,
+ Math.min(
+ (key && loadedItemCounts.get(key)) || 0,
+ MAX_RESTORED_PAGINATED_ITEMS
+ )
+ ),
+ [key, options.initialNumItems]
+ )
+ const result = usePaginatedQuery(query, args, { initialNumItems })
const cached = useCachedValue[]>(key)
useEffect(() => {
if (key && result.status !== "LoadingFirstPage") {
+ loadedItemCounts.set(key, result.results.length)
writeCache(key, result.results.slice(0, MAX_CACHED_PAGINATED_ITEMS))
}
}, [key, result.status, result.results])
diff --git a/apps/web/hooks/use-media-actions.ts b/apps/web/hooks/use-media-actions.ts
new file mode 100644
index 0000000..d665acc
--- /dev/null
+++ b/apps/web/hooks/use-media-actions.ts
@@ -0,0 +1,104 @@
+"use client"
+
+import * as React from "react"
+import { useConvex } from "convex/react"
+
+import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
+import { useFavorites } from "@/components/favorites-provider"
+import type { MediaContextAction } from "@/components/media-context-menu"
+import { useCacheScope } from "@/components/persistent-cache-provider"
+import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
+import { stationArtistId } from "@/lib/station-artist"
+import { api } from "@otunes/convex/_generated/api"
+import type { Id } from "@otunes/convex/_generated/dataModel"
+import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
+
+export function useMediaActions() {
+ const { openAddToPlaylist, openAddArtistToPlaylist } = useAddToPlaylist()
+ const { favoriteSongs, toggleArtistFavorite } = useFavorites()
+ const { runQueueAction, createStation } = useQueueMediaActions()
+ const convex = useConvex()
+ const cacheScope = useCacheScope()
+
+ const runSongsAction = React.useCallback(
+ (
+ action: MediaContextAction,
+ songIds: Id<"songs">[],
+ stationArtist?: string
+ ) => {
+ switch (action) {
+ case "create-station":
+ if (stationArtist) void createStation(stationArtist)
+ break
+ case "favorite":
+ void favoriteSongs(songIds)
+ break
+ case "playlist":
+ openAddToPlaylist(songIds)
+ break
+ case "play-next":
+ case "play-last":
+ case "shuffle":
+ void runQueueAction(action, songIds)
+ break
+ }
+ },
+ [createStation, favoriteSongs, openAddToPlaylist, runQueueAction]
+ )
+
+ const runArtistAction = React.useCallback(
+ async (action: MediaContextAction, artistId: string) => {
+ switch (action) {
+ case "favorite":
+ void toggleArtistFavorite(artistId as Id<"artists">)
+ break
+ case "playlist":
+ void openAddArtistToPlaylist(artistId as Id<"artists">)
+ break
+ case "play-next":
+ case "play-last":
+ case "shuffle": {
+ const songIds = await fetchCachedQuery(
+ convex,
+ cacheScope,
+ api.playlists.getOrderedArtistSongIds,
+ { artistId: artistId as Id<"artists"> }
+ )
+ void runQueueAction(action, songIds)
+ break
+ }
+ }
+ },
+ [convex, cacheScope, toggleArtistFavorite, openAddArtistToPlaylist, runQueueAction]
+ )
+
+ return { runSongsAction, runArtistAction }
+}
+
+/**
+ * Handles a track row menu action, targeting the current selection or else the
+ * row's song. The station artist is `artistId` when given, otherwise the artist
+ * every targeted song in `songs` shares.
+ */
+export function useTrackListMediaAction({
+ selectedIds,
+ songs,
+ artistId,
+}: {
+ selectedIds: ReadonlySet
+ songs?: { id: string; artist: { id: string } }[]
+ artistId?: string
+}) {
+ const { runSongsAction } = useMediaActions()
+
+ return React.useCallback(
+ (action: MediaContextAction, songId: string) => {
+ const targetIds = selectedIds.size > 0 ? Array.from(selectedIds) : [songId]
+ const stationArtist =
+ artistId ??
+ (songs ? stationArtistId(songs, new Set(targetIds)) : undefined)
+ runSongsAction(action, targetIds as Id<"songs">[], stationArtist)
+ },
+ [selectedIds, songs, artistId, runSongsAction]
+ )
+}
diff --git a/apps/web/hooks/use-queue-media-actions.ts b/apps/web/hooks/use-queue-media-actions.ts
index 2837a81..b69d9f8 100644
--- a/apps/web/hooks/use-queue-media-actions.ts
+++ b/apps/web/hooks/use-queue-media-actions.ts
@@ -3,7 +3,7 @@
import * as React from "react"
import { toast } from "sonner"
-import { usePlayback } from "@/components/playback-provider"
+import { usePlaybackActions } from "@/components/playback-provider"
import type { MediaContextAction } from "@/components/media-context-menu"
import type { Id } from "@otunes/convex/_generated/dataModel"
@@ -29,7 +29,7 @@ function queueActionMessage(action: QueueMediaAction, count: number) {
export function useQueueMediaActions() {
const { addToQueueNext, addToQueueLast, playShuffled, playArtistShuffled } =
- usePlayback()
+ usePlaybackActions()
const runQueueAction = React.useCallback(
async (action: QueueMediaAction, songIds: Id<"songs">[]) => {
diff --git a/apps/web/hooks/use-stable-callback.ts b/apps/web/hooks/use-stable-callback.ts
new file mode 100644
index 0000000..e216f3d
--- /dev/null
+++ b/apps/web/hooks/use-stable-callback.ts
@@ -0,0 +1,19 @@
+"use client"
+
+import * as React from "react"
+
+/**
+ * Returns a function with a stable identity that always calls the latest
+ * `callback`. Only call it from event handlers, never during render.
+ */
+export function useStableCallback(
+ callback: (...args: Args) => Result
+): (...args: Args) => Result {
+ const callbackRef = React.useRef(callback)
+
+ React.useLayoutEffect(() => {
+ callbackRef.current = callback
+ })
+
+ return React.useCallback((...args: Args) => callbackRef.current(...args), [])
+}
diff --git a/apps/web/lib/album-grid-classes.ts b/apps/web/lib/album-grid-classes.ts
index a306661..12e7520 100644
--- a/apps/web/lib/album-grid-classes.ts
+++ b/apps/web/lib/album-grid-classes.ts
@@ -1,9 +1,3 @@
-/** Shared layout for album grids and carousel slides (gap-x-6 = 1.5rem). */
+/** Shared layout for album grids. */
export const albumGridClassName =
"grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6"
-
-/** Slide width matches one cell of `albumGridClassName` inside an `@container` ancestor. */
-export const albumGridCarouselSlideClassName =
- "w-[calc((100cqw-1.5rem)/2)] shrink-0 grow-0 basis-auto pl-6 sm:w-[calc((100cqw-3rem)/3)] md:w-[calc((100cqw-4.5rem)/4)] lg:w-[calc((100cqw-6rem)/5)] xl:w-[calc((100cqw-7.5rem)/6)]"
-
-export const albumGridCarouselContentClassName = "-ml-6"
diff --git a/apps/web/lib/data.ts b/apps/web/lib/data.ts
deleted file mode 100644
index 555d845..0000000
--- a/apps/web/lib/data.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import type {
- BrowseAlbum,
- BrowseAlbumDetail,
- BrowseAlbumTrack,
- BrowseArtist,
- BrowsePlaylistDetail,
- BrowsePlaylistOwner,
- BrowseSong,
- PlaylistSummary,
-} from "@otunes/convex/types"
-
-export type Artist = BrowseArtist
-export type Album = BrowseAlbum
-export type Song = BrowseSong
-export type Playlist = PlaylistSummary
-export type PlaylistOwner = BrowsePlaylistOwner
-export type PlaylistDetail = BrowsePlaylistDetail
-export type AlbumTrack = BrowseAlbumTrack
-export type AlbumDetail = BrowseAlbumDetail
diff --git a/apps/web/lib/format-duration.ts b/apps/web/lib/format-duration.ts
new file mode 100644
index 0000000..00f8b06
--- /dev/null
+++ b/apps/web/lib/format-duration.ts
@@ -0,0 +1,7 @@
+/** Formats seconds as `m:ss`, flooring fractional and negative input. */
+export function formatDuration(seconds: number): string {
+ const total = Math.max(0, Math.floor(seconds))
+ const minutes = Math.floor(total / 60)
+ const remainingSeconds = total % 60
+ return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
+}
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/selection-range-styles.tsx b/apps/web/lib/selection-range-styles.tsx
index d871df0..0c575fa 100644
--- a/apps/web/lib/selection-range-styles.tsx
+++ b/apps/web/lib/selection-range-styles.tsx
@@ -63,10 +63,19 @@ export function selectionHighlightRadiusClass(
export const TRACK_ROW_HIGHLIGHT_INSET = "absolute inset-y-0 left-2 right-2"
+/** Full-width, square-corner highlight used by the library and queue lists. */
+export const FLUSH_ROW_HIGHLIGHT_INSET = "absolute inset-0"
+
+/**
+ * Track row highlights are inset rounded pills by default; `flush` makes them
+ * full-width with square corners.
+ */
export function SelectionRangeHighlight({
position,
+ flush = false,
}: {
position: SelectionRangePosition
+ flush?: boolean
}) {
if (position === "none") {
return null
@@ -77,34 +86,34 @@ export function SelectionRangeHighlight({
aria-hidden
className={cn(
"pointer-events-none bg-primary",
- TRACK_ROW_HIGHLIGHT_INSET,
- selectionHighlightRadiusClass(position)
+ flush
+ ? FLUSH_ROW_HIGHLIGHT_INSET
+ : [TRACK_ROW_HIGHLIGHT_INSET, selectionHighlightRadiusClass(position)]
)}
/>
)
}
-/** Inset rounded hover background matching the selection pill shape. */
-export function TrackRowHoverHighlight() {
+export function TrackRowHoverHighlight({ flush = false }: { flush?: boolean }) {
return (
)
}
-/** Inset rounded background for the active (now playing) row. */
-export function TrackRowActiveHighlight() {
+/** Background for the active (focused or now playing) row. */
+export function TrackRowActiveHighlight({ flush = false }: { flush?: boolean }) {
return (
)
@@ -116,42 +125,6 @@ export const TRACK_ROW_PADDING = "pl-8 pr-10"
/** Centers the track list in the main content area. */
export const TRACK_LIST_CONTAINER = "mx-auto w-full max-w-9/10"
-/** Full-width highlight for library song rows (no horizontal inset). */
-export const SONGS_ROW_HIGHLIGHT_INSET = "absolute inset-0"
-
-export function SongsSelectionRangeHighlight({
- position,
-}: {
- position: SelectionRangePosition
-}) {
- if (position === "none") {
- return null
- }
-
- return (
-
- )
-}
-
-/** Full-width hover background for library song rows (not rounded). */
-export function SongsTrackRowHoverHighlight() {
- return (
-
- )
-}
-
/** Album track row: star, track #, title (flex), duration, menu. */
export const ALBUM_TRACK_ROW = "flex w-full min-w-0 items-center gap-x-3"
@@ -160,50 +133,3 @@ export const ALBUM_TRACK_TITLE = "min-w-0 flex-1 truncate font-normal"
export function isInSelectionRange(position: SelectionRangePosition) {
return position !== "none"
}
-
-/** Full-width, square-corner highlights for the queue sidebar. */
-export const QUEUE_ROW_HIGHLIGHT_INSET = "absolute inset-0"
-
-export function QueueSelectionRangeHighlight({
- position,
-}: {
- position: SelectionRangePosition
-}) {
- if (position === "none") {
- return null
- }
-
- return (
-
- )
-}
-
-export function QueueTrackRowHoverHighlight() {
- return (
-
- )
-}
-
-export function QueueTrackRowActiveHighlight() {
- return (
-
- )
-}
diff --git a/apps/web/lib/server-audio-info.ts b/apps/web/lib/server-audio-info.ts
new file mode 100644
index 0000000..79a71c8
--- /dev/null
+++ b/apps/web/lib/server-audio-info.ts
@@ -0,0 +1,41 @@
+import fs from "node:fs/promises"
+import * as music from "music-metadata"
+
+const MAX_ENTRIES = 1000
+
+export type AudioInfo = {
+ codec: string | undefined
+ duration: number | undefined
+}
+
+const cache = new Map>()
+
+/** Codec info for a file, parsed once per file version. */
+export async function audioInfo(file: string): Promise {
+ const stat = await fs.stat(file)
+ const key = `${file}\0${stat.size}\0${stat.mtimeMs}`
+
+ const cached = cache.get(key)
+ if (cached) {
+ cache.delete(key)
+ cache.set(key, cached)
+ return cached
+ }
+
+ const info = music.parseFile(file).then(({ format }) => ({
+ codec: format.codec,
+ duration: format.duration,
+ }))
+ cache.set(key, info)
+ info.catch(() => {
+ if (cache.get(key) === info) {
+ cache.delete(key)
+ }
+ })
+
+ if (cache.size > MAX_ENTRIES) {
+ cache.delete(cache.keys().next().value!)
+ }
+
+ return info
+}
diff --git a/apps/web/lib/server-audio-stream.ts b/apps/web/lib/server-audio-stream.ts
index f1c9d8b..d26b96c 100644
--- a/apps/web/lib/server-audio-stream.ts
+++ b/apps/web/lib/server-audio-stream.ts
@@ -1,96 +1,96 @@
-import { type ChildProcessWithoutNullStreams } from "node:child_process"
-import { createReadStream, ReadStream } from "node:fs"
+import { createReadStream } from "node:fs"
+import type { Readable } from "node:stream"
+import type { FfmpegProcess } from "@/lib/server-ffmpeg"
+
+const HIGH_WATER_MARK_BYTES = 256 * 1024
export type ByteRange = {
start: number
end: number
}
-async function* nodeStreamToIterator(stream: ReadStream) {
- for await (const chunk of stream) {
- yield new Uint8Array(chunk)
- }
-}
+/**
+ * Wraps a Node stream, pausing it while the consumer is behind. `cancel` runs
+ * when the consumer goes away (seek, track change, disconnect). `finish` runs
+ * when the source ends and may reject to error the stream.
+ */
+function toWebStream(
+ source: Readable,
+ {
+ cancel,
+ finish,
+ }: { cancel: () => void; finish?: () => Promise }
+): ReadableStream {
+ let done = false
-// @ts-expect-error trust me bro
-function iteratorToStream(iterator) {
- return new ReadableStream({
- async pull(controller) {
- const { value, done } = await iterator.next()
- if (done) {
- controller.close()
- } else {
- controller.enqueue(value)
- }
- },
- })
-}
-
-export function streamFile(path: string, range?: ByteRange): ReadableStream {
- const nodeStream = createReadStream(path, range)
- return iteratorToStream(nodeStreamToIterator(nodeStream))
-}
-
-export function ffmpegToReadableStream(
- ffmpegProcess: ChildProcessWithoutNullStreams
-) {
- let closed = false
-
- return new ReadableStream({
- start(controller) {
- const finalize = (err?: Error) => {
- if (closed) {
- return
- }
- closed = true
-
- try {
- if (err) {
- controller.error(err)
- } else {
- controller.close()
+ return new ReadableStream(
+ {
+ start(controller) {
+ const fail = (error: unknown) => {
+ if (done) {
+ return
}
- } catch {
- // Consumer may have already closed the stream (e.g. track change).
+ done = true
+ controller.error(error)
+ cancel()
}
- }
- ffmpegProcess.stdout.on("data", (chunk: Buffer) => {
- if (closed) {
+ source.on("data", (chunk: Buffer) => {
+ if (done) {
+ return
+ }
+ controller.enqueue(new Uint8Array(chunk))
+ if ((controller.desiredSize ?? 0) <= 0) {
+ source.pause()
+ }
+ })
+ source.once("error", fail)
+ source.once("end", () => {
+ if (done) {
+ return
+ }
+ void (finish?.() ?? Promise.resolve()).then(() => {
+ if (!done) {
+ done = true
+ controller.close()
+ }
+ }, fail)
+ })
+ },
+ pull() {
+ source.resume()
+ },
+ cancel() {
+ if (done) {
return
}
-
- try {
- controller.enqueue(new Uint8Array(chunk))
- } catch {
- closed = true
- ffmpegProcess.kill("SIGKILL")
- }
- })
-
- ffmpegProcess.stderr.on("data", (data) => {
- console.error(`FFmpeg log: ${data.toString()}`)
- })
-
- ffmpegProcess.stdout.on("end", () => finalize())
- ffmpegProcess.stdout.on("error", (err) => finalize(err))
-
- ffmpegProcess.on("close", (code) => {
- if (code !== 0 && !closed) {
- finalize(new Error(`ffmpeg exited with code ${code}`))
- } else {
- finalize()
- }
- })
-
- ffmpegProcess.on("error", (err) => finalize(err))
+ done = true
+ cancel()
+ },
},
- cancel() {
- if (closed) {
- return
+ new ByteLengthQueuingStrategy({ highWaterMark: HIGH_WATER_MARK_BYTES })
+ )
+}
+
+export function streamFile(path: string, range?: ByteRange) {
+ const file = createReadStream(path, range)
+ return toWebStream(file, { cancel: () => file.destroy() })
+}
+
+/** Streams ffmpeg stdout and kills ffmpeg when the consumer goes away. */
+export function ffmpegToReadableStream({
+ child,
+ exited,
+ stderrTail,
+}: FfmpegProcess) {
+ return toWebStream(child.stdout, {
+ cancel: () => child.kill("SIGKILL"),
+ finish: async () => {
+ const code = await exited
+ if (code !== 0) {
+ console.error(`ffmpeg transcode exited with code ${code}`, stderrTail())
+ throw new Error(`ffmpeg exited with code ${code}`)
}
- closed = true
- ffmpegProcess.kill("SIGKILL")
},
})
}
diff --git a/apps/web/lib/server-cache.ts b/apps/web/lib/server-cache.ts
new file mode 100644
index 0000000..bbc5702
--- /dev/null
+++ b/apps/web/lib/server-cache.ts
@@ -0,0 +1,132 @@
+import fs from "node:fs/promises"
+import os from "node:os"
+import path from "node:path"
+
+const DEFAULT_MAX_MB = 2048
+const ORPHAN_MAX_AGE_MS = 60 * 60 * 1000
+/** Prefix for in-progress entries. Pruning removes old unpinned ones as abandoned. */
+export const CACHE_ORPHAN_PREFIX = "convert-"
+
+type CacheState = {
+ pinned: Map
+ pruning: Promise | null
+}
+
+const globalState = globalThis as typeof globalThis & {
+ __otunesCache?: CacheState
+}
+const state = (globalState.__otunesCache ??= {
+ pinned: new Map(),
+ pruning: null,
+})
+
+/**
+ * Transcode cache root. Set OTUNES_CACHE_DIR to a persistent volume to keep
+ * transcodes across restarts.
+ */
+export function cacheRoot() {
+ return process.env.OTUNES_CACHE_DIR || path.join(os.tmpdir(), "otunes-cache")
+}
+
+export function cacheDir(kind: "hls" | "lossless") {
+ return path.join(cacheRoot(), kind)
+}
+
+function maxCacheBytes() {
+ const configured = Number(process.env.OTUNES_CACHE_MAX_MB)
+ const mb = Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_MAX_MB
+ return mb * 1024 * 1024
+}
+
+/** Pinned entries are never pruned. Pins are reference counted. */
+export function pinCacheEntry(entry: string) {
+ state.pinned.set(entry, (state.pinned.get(entry) ?? 0) + 1)
+}
+
+export function unpinCacheEntry(entry: string) {
+ const count = state.pinned.get(entry) ?? 0
+ if (count <= 1) {
+ state.pinned.delete(entry)
+ } else {
+ state.pinned.set(entry, count - 1)
+ }
+}
+
+/** Marks an entry as recently used so pruning removes it last. */
+export async function touchCacheEntry(entry: string) {
+ const now = new Date()
+ await fs.utimes(entry, now, now)
+}
+
+async function entrySize(entry: string): Promise {
+ const stat = await fs.stat(entry).catch(() => null)
+ if (!stat) {
+ return 0
+ }
+ if (!stat.isDirectory()) {
+ return stat.size
+ }
+ const names = await fs.readdir(entry).catch(() => [])
+ const sizes = await Promise.all(
+ names.map((name) => entrySize(path.join(entry, name)))
+ )
+ return sizes.reduce((total, size) => total + size, 0)
+}
+
+async function prune() {
+ const entries: {
+ path: string
+ size: number
+ mtimeMs: number
+ orphan: boolean
+ }[] = []
+
+ for (const kind of ["hls", "lossless"] as const) {
+ const dir = cacheDir(kind)
+ const names = await fs.readdir(dir).catch(() => [])
+ for (const name of names) {
+ const entry = path.join(dir, name)
+ const stat = await fs.stat(entry).catch(() => null)
+ if (!stat) {
+ continue
+ }
+ entries.push({
+ path: entry,
+ size: await entrySize(entry),
+ mtimeMs: stat.mtimeMs,
+ orphan: name.startsWith(CACHE_ORPHAN_PREFIX),
+ })
+ }
+ }
+
+ const maxBytes = maxCacheBytes()
+ const now = Date.now()
+ let total = entries.reduce((sum, entry) => sum + entry.size, 0)
+ entries.sort((a, b) => a.mtimeMs - b.mtimeMs)
+
+ for (const entry of entries) {
+ if (state.pinned.has(entry.path)) {
+ continue
+ }
+ const remove = entry.orphan
+ ? now - entry.mtimeMs > ORPHAN_MAX_AGE_MS
+ : total > maxBytes
+ if (remove) {
+ await fs.rm(entry.path, { recursive: true, force: true }).catch(() => {})
+ total -= entry.size
+ }
+ }
+}
+
+/**
+ * Removes least recently used entries until the cache fits under
+ * OTUNES_CACHE_MAX_MB, plus abandoned in-progress entries.
+ */
+export function pruneCache() {
+ state.pruning ??= prune()
+ .catch((error) => console.error("Transcode cache prune failed", error))
+ .finally(() => {
+ state.pruning = null
+ })
+ return state.pruning
+}
diff --git a/apps/web/lib/server-ffmpeg.ts b/apps/web/lib/server-ffmpeg.ts
new file mode 100644
index 0000000..ac732b7
--- /dev/null
+++ b/apps/web/lib/server-ffmpeg.ts
@@ -0,0 +1,113 @@
+import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"
+import os from "node:os"
+
+const STDERR_TAIL_BYTES = 4096
+
+export type FfmpegProcess = {
+ child: ChildProcessWithoutNullStreams
+ /** Resolves with the exit code, or null when killed by a signal. */
+ exited: Promise
+ stderrTail: () => string
+}
+
+type Limiter = {
+ running: number
+ waiting: (() => void)[]
+}
+
+// Kept on globalThis so dev reloads share one limit with processes they spawned.
+const globalState = globalThis as typeof globalThis & {
+ __otunesFfmpegLimiter?: Limiter
+}
+const limiter = (globalState.__otunesFfmpegLimiter ??= {
+ running: 0,
+ waiting: [],
+})
+
+function maxConcurrentFfmpeg() {
+ const configured = Number(process.env.OTUNES_MAX_FFMPEG)
+ if (Number.isInteger(configured) && configured > 0) {
+ return configured
+ }
+ return Math.max(2, os.availableParallelism())
+}
+
+async function acquireSlot(signal?: AbortSignal) {
+ signal?.throwIfAborted()
+ if (limiter.running < maxConcurrentFfmpeg()) {
+ limiter.running += 1
+ return
+ }
+
+ await new Promise((resolve, reject) => {
+ const grant = () => {
+ signal?.removeEventListener("abort", onAbort)
+ resolve()
+ }
+ const onAbort = () => {
+ const index = limiter.waiting.indexOf(grant)
+ if (index !== -1) {
+ limiter.waiting.splice(index, 1)
+ }
+ reject(signal?.reason)
+ }
+ limiter.waiting.push(grant)
+ signal?.addEventListener("abort", onAbort, { once: true })
+ })
+}
+
+function releaseSlot() {
+ const next = limiter.waiting.shift()
+ if (next) {
+ // The slot passes straight to the next waiter.
+ next()
+ } else {
+ limiter.running -= 1
+ }
+}
+
+/**
+ * Spawns ffmpeg once a slot under the concurrency cap is free. The slot is
+ * held until the process exits. Rejects if `signal` aborts while queued.
+ */
+export async function spawnFfmpeg(
+ args: string[],
+ signal?: AbortSignal
+): Promise {
+ await acquireSlot(signal)
+
+ let child: ChildProcessWithoutNullStreams
+ try {
+ child = spawn("ffmpeg", [
+ "-nostdin",
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ ...args,
+ ])
+ } catch (error) {
+ releaseSlot()
+ throw error
+ }
+
+ // stderr must be drained or ffmpeg blocks once the pipe buffer fills.
+ let stderr = ""
+ child.stderr.on("data", (data: Buffer) => {
+ stderr = (stderr + data.toString()).slice(-STDERR_TAIL_BYTES)
+ })
+
+ const exited = new Promise((resolve) => {
+ let released = false
+ const finish = (code: number | null) => {
+ if (!released) {
+ released = true
+ releaseSlot()
+ }
+ resolve(code)
+ }
+ child.once("error", () => finish(1))
+ child.once("close", (code) => finish(code))
+ })
+
+ return { child, exited, stderrTail: () => stderr.trim() }
+}
diff --git a/apps/web/lib/server-hls.ts b/apps/web/lib/server-hls.ts
index df3b876..e4f3182 100644
--- a/apps/web/lib/server-hls.ts
+++ b/apps/web/lib/server-hls.ts
@@ -1,13 +1,28 @@
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"
-import { spawn } from "node:child_process"
-import * as music from "music-metadata"
+import { audioInfo } from "@/lib/server-audio-info"
+import {
+ cacheDir,
+ pinCacheEntry,
+ pruneCache,
+ touchCacheEntry,
+ unpinCacheEntry,
+} from "@/lib/server-cache"
+import { spawnFfmpeg, type FfmpegProcess } from "@/lib/server-ffmpeg"
export const HLS_SEGMENT_SECONDS = 6
const HLS_MAX_IDLE_MS = 30 * 60 * 1000
+/** The server-only slice of a song needed to transcode it. */
+export type SongSource = Pick, "_id" | "files" | "length">
+
type HlsJob = {
key: string
lookupKey: string
@@ -17,42 +32,28 @@ type HlsJob = {
lastTouchedAt: number
processExited: boolean
processExitCode: number | null
+ process: FfmpegProcess | null
+ abort: AbortController
+ evicted: boolean
}
-const jobs = new Map()
-const jobsByLookup = new Map()
-let lastCleanupAt = 0
-
-export function qualityKbps(quality: string | null) {
- if (quality === "low") {
- return 64
- }
-
- if (quality === "high") {
- return 256
- }
-
- return 128
+type HlsState = {
+ /** In-flight and ready jobs by cache key, so overlapping requests share one ffmpeg. */
+ pending: Map>
+ jobs: Map
+ jobsByLookup: Map
+ lastCleanupAt: number
}
-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"
+const globalState = globalThis as typeof globalThis & {
+ __otunesHls?: HlsState
}
+const state = (globalState.__otunesHls ??= {
+ pending: new Map(),
+ jobs: new Map(),
+ jobsByLookup: new Map(),
+ lastCleanupAt: 0,
+})
function hlsLookupKey(
songId: string,
@@ -63,7 +64,7 @@ function hlsLookupKey(
}
async function hlsJobKey(
- song: Doc<"songs">,
+ song: SongSource,
sourcePath: string,
kbps: number
) {
@@ -88,31 +89,38 @@ export function hlsSegmentPath(job: HlsJob, segmentIndex: number) {
async function touchHlsJob(job: HlsJob) {
job.lastTouchedAt = Date.now()
- await fs.utimes(job.dir, new Date(job.lastTouchedAt), new Date(job.lastTouchedAt)).catch(
- () => {}
- )
-}
-
-function forgetJob(job: HlsJob) {
- jobs.delete(job.key)
- if (jobsByLookup.get(job.lookupKey) === job) {
- jobsByLookup.delete(job.lookupKey)
- }
+ await touchCacheEntry(job.dir).catch(() => {})
}
async function evictJob(job: HlsJob) {
- forgetJob(job)
- await fs.rm(job.dir, { recursive: true, force: true }).catch(() => {})
+ if (job.evicted) {
+ return
+ }
+ job.evicted = true
+ state.pending.delete(job.key)
+ state.jobs.delete(job.key)
+ if (state.jobsByLookup.get(job.lookupKey) === job) {
+ state.jobsByLookup.delete(job.lookupKey)
+ }
+
+ job.abort.abort()
+ job.process?.child.kill("SIGKILL")
+ const complete = job.processExited && job.processExitCode === 0
+ if (!complete) {
+ await job.process?.exited
+ await fs.rm(job.dir, { recursive: true, force: true }).catch(() => {})
+ }
+ unpinCacheEntry(job.dir)
}
async function cleanupIdleHlsJobs() {
const now = Date.now()
- if (now - lastCleanupAt < 60_000) {
+ if (now - state.lastCleanupAt < 60_000) {
return
}
- lastCleanupAt = now
+ state.lastCleanupAt = now
- for (const job of [...jobs.values()]) {
+ for (const job of [...state.jobs.values()]) {
if (now - job.lastTouchedAt > HLS_MAX_IDLE_MS) {
await evictJob(job)
}
@@ -124,7 +132,7 @@ export function getExistingHlsJob(
quality: string | null,
preferAtmos: boolean
) {
- return jobsByLookup.get(hlsLookupKey(songId, quality, preferAtmos)) ?? null
+ return state.jobsByLookup.get(hlsLookupKey(songId, quality, preferAtmos)) ?? null
}
export async function waitForHlsSegment(
@@ -137,18 +145,22 @@ export async function waitForHlsSegment(
const startedAt = Date.now()
while (Date.now() - startedAt < timeoutMs) {
+ // Read before checking the file so a segment renamed just before exit is found.
+ const exited = job.processExited
try {
- const firstStat = await fs.stat(segmentPath)
- if (firstStat.size > 0) {
- await new Promise((resolve) => setTimeout(resolve, 100))
- const secondStat = await fs.stat(segmentPath)
- if (firstStat.size === secondStat.size) {
- return segmentPath
- }
- }
+ // ffmpeg writes to a .tmp file and renames it when complete.
+ await fs.access(segmentPath)
+ return segmentPath
} catch {
- if (job.processExited && job.processExitCode !== 0) {
- throw new Error(`HLS transcode failed with code ${job.processExitCode}`)
+ if (job.evicted) {
+ throw new Error("HLS job was evicted")
+ }
+ if (exited) {
+ throw new Error(
+ job.processExitCode === 0
+ ? "HLS segment does not exist"
+ : `HLS transcode failed with code ${job.processExitCode}`
+ )
}
}
await new Promise((resolve) => setTimeout(resolve, 100))
@@ -157,52 +169,15 @@ export async function waitForHlsSegment(
throw new Error("Timed out waiting for HLS segment")
}
-export async function ensureHlsJob(
- song: Doc<"songs">,
- quality: string | null,
- preferAtmos: boolean
-) {
- await cleanupIdleHlsJobs()
-
- const kbps = qualityKbps(quality)
- const sourceCodec = selectHlsSourceCodec(song, quality, preferAtmos)
- const sourcePath = song.files[sourceCodec]
- const key = await hlsJobKey(song, sourcePath, kbps)
- const lookupKey = hlsLookupKey(song._id, quality, preferAtmos)
- const existingJob = jobs.get(key)
-
- if (existingJob) {
- try {
- await fs.access(existingJob.dir)
- await touchHlsJob(existingJob)
- return existingJob
- } catch {
- forgetJob(existingJob)
- }
- }
-
- const metadata = await music.parseFile(sourcePath)
- const duration = metadata.format.duration ?? song.length
- const segmentCount = Math.max(1, Math.ceil(duration / HLS_SEGMENT_SECONDS))
- const dir = path.join(hlsCacheRoot(), key)
- await fs.mkdir(dir, { recursive: true })
-
- const job: HlsJob = {
- key,
- lookupKey,
- dir,
- duration,
- segmentCount,
- lastTouchedAt: Date.now(),
- processExited: false,
- processExitCode: null,
- }
- jobs.set(key, job)
- jobsByLookup.set(lookupKey, job)
- await touchHlsJob(job)
+async function hasCompletePlaylist(dir: string) {
+ const playlist = await fs
+ .readFile(path.join(dir, "index.m3u8"), "utf8")
+ .catch(() => "")
+ return playlist.includes("#EXT-X-ENDLIST")
+}
+function startTranscode(job: HlsJob, sourcePath: string, kbps: number) {
const ffmpegArgs = [
- "-nostdin",
"-i",
sourcePath,
"-vn",
@@ -222,25 +197,126 @@ export async function ensureHlsJob(
"0",
"-hls_segment_type",
"mpegts",
+ "-hls_flags",
+ "temp_file",
"-hls_segment_filename",
- path.join(dir, "segment_%05d.ts"),
- path.join(dir, "index.m3u8"),
+ path.join(job.dir, "segment_%05d.ts"),
+ path.join(job.dir, "index.m3u8"),
]
- const ffmpegProcess = spawn("ffmpeg", ffmpegArgs)
- ffmpegProcess.stderr.on("data", (data) => {
- console.error(`FFmpeg HLS log: ${data.toString()}`)
- })
+ spawnFfmpeg(ffmpegArgs, job.abort.signal).then(
+ async (ffmpeg) => {
+ job.process = ffmpeg
+ if (job.evicted) {
+ ffmpeg.child.kill("SIGKILL")
+ }
+ const code = await ffmpeg.exited
+ job.process = null
+ job.processExited = true
+ job.processExitCode = code
+ if (job.evicted) {
+ return
+ }
+ if (code === 0) {
+ void pruneCache()
+ } else {
+ console.error(`ffmpeg HLS exited with code ${code}`, ffmpeg.stderrTail())
+ }
+ },
+ () => {
+ job.processExited = true
+ job.processExitCode = 1
+ }
+ )
+}
- ffmpegProcess.on("close", (code) => {
- job.processExited = true
- job.processExitCode = code
- })
+async function createHlsJob(
+ song: SongSource,
+ sourcePath: string,
+ kbps: number,
+ key: string,
+ lookupKey: string
+): Promise {
+ const info = await audioInfo(sourcePath)
+ const duration = info.duration ?? song.length
+ const segmentCount = Math.max(1, Math.ceil(duration / HLS_SEGMENT_SECONDS))
+ const dir = path.join(cacheDir("hls"), key)
+ pinCacheEntry(dir)
- ffmpegProcess.on("error", () => {
- job.processExited = true
- job.processExitCode = 1
- })
+ try {
+ const complete = await hasCompletePlaylist(dir)
+ if (!complete) {
+ await fs.rm(dir, { recursive: true, force: true })
+ await fs.mkdir(dir, { recursive: true })
+ }
+ const job: HlsJob = {
+ key,
+ lookupKey,
+ dir,
+ duration,
+ segmentCount,
+ lastTouchedAt: Date.now(),
+ processExited: complete,
+ processExitCode: complete ? 0 : null,
+ process: null,
+ abort: new AbortController(),
+ evicted: false,
+ }
+ state.jobs.set(key, job)
+ await touchHlsJob(job)
+
+ if (!complete) {
+ startTranscode(job, sourcePath, kbps)
+ }
+ return job
+ } catch (error) {
+ unpinCacheEntry(dir)
+ throw error
+ }
+}
+
+export async function ensureHlsJob(
+ song: SongSource,
+ quality: string | null,
+ preferAtmos: boolean
+): Promise {
+ await cleanupIdleHlsJobs()
+
+ 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)
+
+ let pending = state.pending.get(key)
+ if (!pending) {
+ pending = createHlsJob(song, sourcePath, kbps, key, lookupKey)
+ state.pending.set(key, pending)
+ const created = pending
+ created.catch(() => {
+ if (state.pending.get(key) === created) {
+ state.pending.delete(key)
+ }
+ })
+ }
+
+ const job = await pending
+ const exists = await fs.access(job.dir).then(
+ () => true,
+ () => false
+ )
+ if (job.evicted || !exists) {
+ await evictJob(job)
+ return ensureHlsJob(song, quality, preferAtmos)
+ }
+
+ state.jobsByLookup.set(lookupKey, job)
+ await touchHlsJob(job)
return job
}
diff --git a/apps/web/lib/server-lossless.ts b/apps/web/lib/server-lossless.ts
index 63efeac..93d8d0a 100644
--- a/apps/web/lib/server-lossless.ts
+++ b/apps/web/lib/server-lossless.ts
@@ -1,8 +1,15 @@
-import { spawn } from "node:child_process"
import { createHash } from "node:crypto"
import fs from "node:fs/promises"
-import os from "node:os"
import path from "node:path"
+import {
+ CACHE_ORPHAN_PREFIX,
+ cacheDir,
+ pinCacheEntry,
+ pruneCache,
+ touchCacheEntry,
+ unpinCacheEntry,
+} from "@/lib/server-cache"
+import { spawnFfmpeg } from "@/lib/server-ffmpeg"
const conversions = new Map>()
@@ -27,56 +34,38 @@ export async function seekableLosslessFile(source: string): Promise {
}
async function convert(source: string, key: string): Promise {
- const dir = path.join(os.tmpdir(), "otunes-lossless")
+ const dir = cacheDir("lossless")
await fs.mkdir(dir, { recursive: true })
- const cutoff = Date.now() - 30 * 60 * 1000
- await Promise.all(
- (await fs.readdir(dir))
- .filter((name) => name.endsWith(".flac"))
- .map(async (name) => {
- const file = path.join(dir, name)
- const stat = await fs.stat(file).catch(() => null)
- if (stat && stat.mtimeMs < cutoff) await fs.rm(file, { force: true })
- })
- )
const output = path.join(dir, `${key}.flac`)
try {
- await fs.access(output)
+ // Every range request touches the file so it stays cached while playing.
+ await touchCacheEntry(output)
return output
} catch {
// Publish only completed conversions so range requests always see a complete file.
}
- const temporary = path.join(
- await fs.mkdtemp(path.join(dir, "convert-")),
- "audio.flac"
- )
+ const temporaryDir = await fs.mkdtemp(path.join(dir, CACHE_ORPHAN_PREFIX))
+ const temporary = path.join(temporaryDir, "audio.flac")
+ pinCacheEntry(temporaryDir)
try {
- await new Promise((resolve, reject) => {
- const child = spawn(
- "ffmpeg",
- [
- "-nostdin",
- "-v",
- "error",
- "-i",
- source,
- "-map",
- "0:a:0",
- "-c:a",
- "flac",
- temporary,
- ],
- { stdio: "ignore" }
- )
- child.on("error", reject)
- child.on("close", (code) => {
- if (code === 0) resolve()
- else reject(new Error(`Lossless conversion failed: ${code}`))
- })
- })
+ const ffmpeg = await spawnFfmpeg([
+ "-i",
+ source,
+ "-map",
+ "0:a:0",
+ "-c:a",
+ "flac",
+ temporary,
+ ])
+ const code = await ffmpeg.exited
+ if (code !== 0) {
+ throw new Error(`Lossless conversion failed: ${code}: ${ffmpeg.stderrTail()}`)
+ }
await fs.rename(temporary, output)
- return output
} finally {
- await fs.rm(path.dirname(temporary), { recursive: true, force: true })
+ unpinCacheEntry(temporaryDir)
+ await fs.rm(temporaryDir, { recursive: true, force: true })
}
+ void pruneCache()
+ return output
}
diff --git a/apps/web/lib/server-song.ts b/apps/web/lib/server-song.ts
new file mode 100644
index 0000000..d0ff651
--- /dev/null
+++ b/apps/web/lib/server-song.ts
@@ -0,0 +1,23 @@
+import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server"
+import { api } from "@otunes/convex/_generated/api"
+import type { Id } from "@otunes/convex/_generated/dataModel"
+import { fetchQuery } from "convex/nextjs"
+import { convexServerOptions } from "@/lib/convex-server"
+import type { SongSource } from "@/lib/server-hls"
+
+/**
+ * Loads a song's file paths as the requesting listener, so Convex enforces auth
+ * even if the proxy is bypassed. Throws when signed out or the song is missing.
+ */
+export async function getSongSource(id: string): Promise {
+ const token = await convexAuthNextjsToken()
+ const song = await fetchQuery(
+ api.library.getSongSource,
+ { id: id as Id<"songs"> },
+ convexServerOptions(token)
+ )
+ if (!song) {
+ throw new Error("Song not found")
+ }
+ return song
+}
diff --git a/apps/web/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/apps/web/lib/station-artist.test.mjs b/apps/web/lib/station-artist.test.mjs
deleted file mode 100644
index da75532..0000000
--- a/apps/web/lib/station-artist.test.mjs
+++ /dev/null
@@ -1,30 +0,0 @@
-import assert from "node:assert/strict"
-import test from "node:test"
-
-import { stationArtistId } from "./station-artist.ts"
-
-const songs = [
- { id: "song-a", artist: { id: "artist-a" } },
- { id: "song-b", artist: { id: "artist-a" } },
- { id: "song-c", artist: { id: "artist-b" } },
-]
-
-test("a single song or a selection sharing one artist can create a station", () => {
- assert.equal(stationArtistId(songs, new Set(["song-c"])), "artist-b")
- assert.equal(
- stationArtistId(songs, new Set(["song-a", "song-b"])),
- "artist-a"
- )
-})
-
-test("mixed artists cannot create a station", () => {
- assert.equal(stationArtistId(songs, new Set(["song-a", "song-c"])), undefined)
-})
-
-test("empty or partially missing selections cannot create a station", () => {
- assert.equal(stationArtistId(songs, new Set()), undefined)
- assert.equal(
- stationArtistId(songs, new Set(["song-a", "missing"])),
- undefined
- )
-})
diff --git a/apps/web/package.json b/apps/web/package.json
index 1c7cd4a..f943371 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -14,6 +14,7 @@
"@base-ui/react": "^1.5.0",
"@convex-dev/auth": "^0.0.93",
"@otunes/convex": "workspace:*",
+ "@tanstack/react-virtual": "^3.14.26",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
diff --git a/apps/web/proxy.ts b/apps/web/proxy.ts
index 342af0d..f9ad380 100644
--- a/apps/web/proxy.ts
+++ b/apps/web/proxy.ts
@@ -12,7 +12,7 @@ const isPublic = createRouteMatcher([
"/api/playlist/:id/cover",
"/album/:id",
"/artist/:id",
- "/artists/:id",
+ "/library/artists/:id",
"/playlist/:id",
])
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index c179357..93a77b1 100644
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -46,22 +46,34 @@ stop() {
}
trap 'stop; exit 0' TERM INT
+as_convex=(setpriv --reuid=convex --regid=convex --init-groups env HOME=/home/convex)
+
convex_cli() {
(
cd "$FUNCTIONS_DIR"
unset CONVEX_DEPLOYMENT CONVEX_DEPLOY_KEY
CONVEX_SELF_HOSTED_URL="$BACKEND_URL" \
CONVEX_SELF_HOSTED_ADMIN_KEY="$admin_key" \
- "$NODE" node_modules/convex/bin/main.js "$@"
+ "${as_convex[@]}" "$NODE" node_modules/convex/bin/main.js "$@"
)
}
-# Only root (the backend) may read the database and instance secret.
+# Only the convex user may read the database and instance secret. Volumes from
+# images that ran the backend as root are still owned by root, and
+# read_credentials.sh generates a new instance secret if it cannot read the old one.
mkdir -p "$CONVEX_DATA_DIR"
+find "$CONVEX_DATA_DIR" \( ! -user convex -o ! -group convex \) \
+ -exec chown -h convex:convex {} +
chmod 700 "$CONVEX_DATA_DIR"
+# The web server writes HLS streams here and a Convex cron deletes stale ones.
+mkdir -p /tmp/otunes
+chown otunes:otunes /tmp/otunes
+chmod -R g+rwX /tmp/otunes
+chmod g+s,o-rwx /tmp/otunes
+
log "Starting Convex backend"
-(cd /convex && umask 077 && exec ./run_backend.sh) &
+(cd /convex && umask 077 && exec "${as_convex[@]}" ./run_backend.sh) &
backend_pid=$!
for _ in $(seq 1 120); do
@@ -80,17 +92,27 @@ if ! curl -fsS "$BACKEND_URL/version" >/dev/null 2>&1; then
exit 1
fi
-admin_key=$(cd /convex && ./generate_admin_key.sh)
+admin_key=$(cd /convex && umask 077 && "${as_convex[@]}" ./generate_admin_key.sh)
log "Deploying Convex functions"
convex_cli deploy --typecheck disable --codegen disable
-if [ -z "$(convex_cli env get JWKS 2>/dev/null || true)" ]; then
+log "Running data migrations"
+convex_cli run migrations:migrateUsers
+
+# `env get` exits 0 with no output when the variable is unset. Any other failure
+# must not be read as "no keys": regenerating them signs every user out.
+if ! jwks=$(convex_cli env get JWKS); then
+ log "Could not read Convex Auth signing keys"
+ stop
+ exit 1
+fi
+if [ -z "$jwks" ]; then
log "Generating Convex Auth signing keys"
"$NODE" /opt/otunes/generate-auth-keys.mjs | convex_cli env set --force
fi
-unset admin_key
+unset admin_key jwks
log "Starting web server"
(
@@ -100,6 +122,8 @@ log "Starting web server"
# Server-side Convex helpers fall back to this at runtime. The browser bundle
# is built without it, so browsers still derive their own URL.
export NEXT_PUBLIC_CONVEX_URL="$BACKEND_URL"
+ # Lets the convex group member delete stale HLS streams.
+ umask 0002
exec setpriv --reuid=otunes --regid=otunes --init-groups \
"$NODE" apps/web/server.js
) &
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/playback-store.ts b/packages/convex/client/playback-store.ts
index f91d524..f13c0b9 100644
--- a/packages/convex/client/playback-store.ts
+++ b/packages/convex/client/playback-store.ts
@@ -1,4 +1,5 @@
import type { Id } from "../convex/_generated/dataModel"
+import { MAX_QUEUE_LENGTH } from "../convex/limits"
import {
EMPTY_PLAYBACK_QUEUE,
type PlaybackQueueState,
@@ -7,6 +8,11 @@ import {
import { loadPersistentCache, readCache, writeCache } from "./persistent-cache"
const SYNC_DELAY_MS = 300
+/**
+ * Backoff for failed syncs. Convex queues mutations while offline, so a
+ * rejection means the server refused the state; after the last retry the
+ * change is dropped until the next local edit instead of retrying forever.
+ */
const RETRY_DELAYS_MS = [1_000, 3_000, 10_000, 30_000]
export type ServerPlaybackState = {
@@ -14,7 +20,6 @@ export type ServerPlaybackState = {
queueHistorySongIds: Id<"songs">[]
shuffleEnabled: boolean
repeatEnabled: RepeatMode
- currentSongProgress: number
revision: number
}
@@ -30,9 +35,12 @@ type PersistedPlayback = PlaybackQueueState & {
dirty: boolean
}
-export type PlaybackSyncTransport = (
- state: PlaybackQueueState
-) => Promise
+export type PlaybackSyncTransport = {
+ /** Saves the state and resolves with the new server revision. */
+ sync: (state: PlaybackQueueState) => Promise
+ /** One-shot read of the server's saved progress for its current song. */
+ loadProgress: () => Promise
+}
/**
* Client-owned playback queue. Changes apply locally (and persist on this
@@ -49,6 +57,7 @@ export class PlaybackStore {
private retryAttempt = 0
private syncTimer: ReturnType | null = null
private latestServerState: ServerPlaybackState | null = null
+ private adopting = false
private transport: PlaybackSyncTransport | null = null
private readonly listeners = new Set<() => void>()
@@ -79,7 +88,7 @@ export class PlaybackStore {
}
update(recipe: (state: PlaybackQueueState) => PlaybackQueueState) {
- const next = recipe(this.state)
+ const next = capQueue(recipe(this.state))
if (next === this.state) {
return
}
@@ -102,7 +111,7 @@ export class PlaybackStore {
receiveServerState(serverState: ServerPlaybackState) {
this.latestServerState = serverState
if (this.snapshot.hydrated) {
- this.adoptServerState()
+ void this.adoptServerState()
}
}
@@ -116,23 +125,52 @@ export class PlaybackStore {
const { revision, dirty, ...state } = persisted
this.revision = revision
this.dirty = dirty
- this.state = { ...EMPTY_PLAYBACK_QUEUE, ...state }
+ this.state = capQueue({ ...EMPTY_PLAYBACK_QUEUE, ...state })
}
this.snapshot = toSnapshot(this.state, true)
this.emit()
- this.adoptServerState()
+ void this.adoptServerState()
if (this.dirty) {
this.scheduleSync(0)
}
}
- private adoptServerState() {
+ private canAdopt(serverState: ServerPlaybackState | null) {
+ return (
+ serverState !== null &&
+ !this.dirty &&
+ !this.inFlight &&
+ (this.revision === null || serverState.revision > this.revision)
+ )
+ }
+
+ /**
+ * Adopts the latest server queue. Progress is not part of the queue query
+ * (it changes every few seconds), so it is fetched once here.
+ */
+ private async adoptServerState() {
const serverState = this.latestServerState
- if (!serverState || this.dirty || this.inFlight) {
+ if (this.adopting || !serverState || !this.canAdopt(serverState)) {
return
}
- if (this.revision !== null && serverState.revision <= this.revision) {
+
+ this.adopting = true
+ let progressSeconds = 0
+ try {
+ progressSeconds = (await this.transport?.loadProgress()) ?? 0
+ } catch {
+ // Starting from 0 beats not adopting the queue at all.
+ } finally {
+ this.adopting = false
+ }
+
+ // Newer server state or local edits may have arrived while loading.
+ if (this.latestServerState !== serverState) {
+ void this.adoptServerState()
+ return
+ }
+ if (!this.canAdopt(serverState)) {
return
}
@@ -142,7 +180,7 @@ export class PlaybackStore {
history: serverState.queueHistorySongIds,
shuffleEnabled: serverState.shuffleEnabled,
repeatEnabled: serverState.repeatEnabled,
- progressSeconds: serverState.currentSongProgress,
+ progressSeconds,
})
}
@@ -167,7 +205,7 @@ export class PlaybackStore {
let failed = false
try {
- const revision = await transport(this.state)
+ const revision = await transport.sync(this.state)
this.revision = Math.max(revision, this.revision ?? 0)
this.retryAttempt = 0
if (this.changeCount === changeCountAtStart) {
@@ -181,15 +219,17 @@ export class PlaybackStore {
this.persist()
- if (failed) {
- const delay =
- RETRY_DELAYS_MS[Math.min(this.retryAttempt, RETRY_DELAYS_MS.length - 1)]
+ if (failed && this.retryAttempt < RETRY_DELAYS_MS.length) {
+ this.scheduleSync(RETRY_DELAYS_MS[this.retryAttempt])
this.retryAttempt += 1
- this.scheduleSync(delay)
+ } else if (failed) {
+ this.retryAttempt = 0
+ this.dirty = false
+ this.persist()
} else if (this.dirty) {
this.scheduleSync(SYNC_DELAY_MS)
} else {
- this.adoptServerState()
+ void this.adoptServerState()
}
}
@@ -227,6 +267,14 @@ export class PlaybackStore {
}
}
+/** Mirrors the server's queue cap so local and synced state agree. */
+function capQueue(state: PlaybackQueueState): PlaybackQueueState {
+ if (state.queue.length <= MAX_QUEUE_LENGTH) {
+ return state
+ }
+ return { ...state, queue: state.queue.slice(0, MAX_QUEUE_LENGTH) }
+}
+
function toSnapshot(
state: PlaybackQueueState,
hydrated: boolean
diff --git a/packages/convex/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/_generated/api.d.ts b/packages/convex/convex/_generated/api.d.ts
index a4607bb..45b3d77 100644
--- a/packages/convex/convex/_generated/api.d.ts
+++ b/packages/convex/convex/_generated/api.d.ts
@@ -13,8 +13,13 @@ import type * as auth from "../auth.js";
import type * as crons from "../crons.js";
import type * as favorites from "../favorites.js";
import type * as http from "../http.js";
+import type * as intentCatalog from "../intentCatalog.js";
+import type * as intentCatalogChanges from "../intentCatalogChanges.js";
import type * as library from "../library.js";
+import type * as limits from "../limits.js";
+import type * as migrations from "../migrations.js";
import type * as playback from "../playback.js";
+import type * as playbackState from "../playbackState.js";
import type * as playlists from "../playlists.js";
import type * as types from "../types.js";
import type * as users from "../users.js";
@@ -31,8 +36,13 @@ declare const fullApi: ApiFromModules<{
crons: typeof crons;
favorites: typeof favorites;
http: typeof http;
+ intentCatalog: typeof intentCatalog;
+ intentCatalogChanges: typeof intentCatalogChanges;
library: typeof library;
+ limits: typeof limits;
+ migrations: typeof migrations;
playback: typeof playback;
+ playbackState: typeof playbackState;
playlists: typeof playlists;
types: typeof types;
users: typeof users;
diff --git a/packages/convex/convex/actions.ts b/packages/convex/convex/actions.ts
index 41feab7..eff747c 100644
--- a/packages/convex/convex/actions.ts
+++ b/packages/convex/convex/actions.ts
@@ -61,512 +61,494 @@ async function cleanHlsStreamsOlderThan(maxIdleMs: number) {
return { checked, removed, failed }
}
-async function coverPathIfExists(path: string): Promise {
- return fs
- .access(path)
- .then(() => path)
- .catch(() => null)
-}
+const SCAN_PAGE_SIZE = 2000
+/** Outlives the 10 minute action timeout so a crashed scan frees the lock. */
+const SCAN_LOCK_LEASE_MS = 15 * 60 * 1000
+/** New files left unparsed after this are picked up by the next scan. */
+const SCAN_PARSE_BUDGET_MS = 6 * 60 * 1000
+const SCAN_BATCH_SIZE = 200
+const FS_CONCURRENCY = 16
-async function syncArtistCover(
- ctx: ActionCtx,
- codec: string,
- dbCover: string | null,
- diskPath: string,
- id: Id<"artists">
-) {
- const onDisk = await coverPathIfExists(diskPath)
- if (onDisk !== null) {
- if (dbCover !== onDisk) {
- await ctx.runMutation(internal.library.updateArtistCover, {
- id,
- cover: onDisk,
- })
+type Page = { page: T[]; isDone: boolean; continueCursor: string }
+
+/** Reads every page of an internal paginated query. */
+async function collectPages(
+ load: (cursor: string | null) => Promise>
+): Promise {
+ const items: T[] = []
+ let cursor: string | null = null
+ for (;;) {
+ const result = await load(cursor)
+ items.push(...result.page)
+ if (result.isDone) {
+ return items
}
- } else if (dbCover !== null && dbCover.includes(codec)) {
- await ctx.runMutation(internal.library.updateArtistCover, {
- id,
- cover: null,
- })
+ cursor = result.continueCursor
}
}
-async function syncAlbumCover(
- ctx: ActionCtx,
- codec: string,
- dbCover: string | null,
- diskPath: string,
- id: Id<"albums">
-) {
- const onDisk = await coverPathIfExists(diskPath)
- if (onDisk !== null) {
- if (dbCover !== onDisk) {
- await ctx.runMutation(internal.library.updateAlbumCover, {
- id,
- cover: onDisk,
- })
+/** Like `Promise.all(items.map(fn))` with at most `limit` calls in flight. */
+async function mapLimit(
+ items: T[],
+ limit: number,
+ fn: (item: T) => Promise
+): Promise {
+ const results = new Array(items.length)
+ let next = 0
+ const worker = async () => {
+ while (next < items.length) {
+ const index = next++
+ results[index] = await fn(items[index])
}
- } else if (dbCover !== null && dbCover.includes(codec)) {
- await ctx.runMutation(internal.library.updateAlbumCover, {
- id,
- cover: null,
- })
+ }
+ await Promise.all(
+ Array.from({ length: Math.min(limit, items.length) }, worker)
+ )
+ return results
+}
+
+function chunk(items: T[], size: number): T[][] {
+ const chunks: T[][] = []
+ for (let i = 0; i < items.length; i += size) {
+ chunks.push(items.slice(i, i + size))
+ }
+ return chunks
+}
+
+async function readDirents(dir: string): Promise {
+ try {
+ return await fs.readdir(dir, { withFileTypes: true })
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
+ return []
+ }
+ throw error
}
}
-async function purgeRemovedSongs(ctx: ActionCtx, ids: Id<"songs">[]) {
- if (ids.length === 0) {
- return
- }
- await ctx.runMutation(internal.library.purgeSongsFromUsersAndPlaylists, {
- ids,
+type DiskAlbum = {
+ codec: string
+ artistFolder: string
+ albumFolder: string
+ files: string[]
+}
+
+type DiskLibrary = {
+ /** Every audio file path. */
+ files: Set
+ /** Every `folder.jpg` / `cover.jpg` path. */
+ covers: Set
+ albums: DiskAlbum[]
+}
+
+/** Lists `DATA_DIR////` with one readdir per directory. */
+async function walkLibrary(codecs: string[]): Promise {
+ const files = new Set()
+ const covers = new Set()
+
+ const artistDirs = (
+ await Promise.all(
+ codecs.map(async (codec) =>
+ (await readDirents(`${DATA_DIR}/${codec}`))
+ .filter((dirent) => dirent.isDirectory())
+ .map((dirent) => ({ codec, artistFolder: dirent.name }))
+ )
+ )
+ ).flat()
+
+ const albumDirs = (
+ await mapLimit(
+ artistDirs,
+ FS_CONCURRENCY,
+ async ({ codec, artistFolder }) => {
+ const artistPath = `${DATA_DIR}/${codec}/${artistFolder}`
+ const dirents = await readDirents(artistPath)
+ if (dirents.some((d) => !d.isDirectory() && d.name === "folder.jpg")) {
+ covers.add(`${artistPath}/folder.jpg`)
+ }
+ return dirents
+ .filter((dirent) => dirent.isDirectory())
+ .map((dirent) => ({ codec, artistFolder, albumFolder: dirent.name }))
+ }
+ )
+ ).flat()
+
+ const albums = await mapLimit(albumDirs, FS_CONCURRENCY, async (album) => {
+ const albumPath = `${DATA_DIR}/${album.codec}/${album.artistFolder}/${album.albumFolder}`
+ const albumFiles: string[] = []
+ for (const dirent of await readDirents(albumPath)) {
+ if (dirent.isDirectory()) {
+ continue
+ }
+ const filePath = `${albumPath}/${dirent.name}`
+ if (dirent.name === "cover.jpg") {
+ covers.add(filePath)
+ } else {
+ files.add(filePath)
+ albumFiles.push(filePath)
+ }
+ }
+ return { ...album, files: albumFiles }
})
+
+ return { files, covers, albums }
}
-async function purgeRemovedAlbums(ctx: ActionCtx, ids: Id<"albums">[]) {
- if (ids.length === 0) {
- return
+/**
+ * Keeps the current cover while its file exists, otherwise the first codec's
+ * cover on disk. Covers outside the data directory are left alone.
+ */
+function pickCover(
+ current: string | null,
+ candidates: string[],
+ covers: Set
+): string | null {
+ if (
+ current !== null &&
+ (covers.has(current) || !current.startsWith(`${DATA_DIR}/`))
+ ) {
+ return current
}
- await ctx.runMutation(internal.library.purgeAlbumsFromUsers, { ids })
+ return candidates.find((candidate) => covers.has(candidate)) ?? null
}
-async function purgeRemovedArtists(ctx: ActionCtx, ids: Id<"artists">[]) {
- if (ids.length === 0) {
- return
+/** Untagged years are stored as 0 / "", which both clients treat as unknown. */
+function releaseDate(common: music.ICommonTagsResult) {
+ if (common.date) {
+ return common.date
}
- await ctx.runMutation(internal.library.purgeArtistsFromUsers, { ids })
+ return common.year ? `01-01-${common.year}` : ""
}
-async function removeCodecFromDatabase(ctx: ActionCtx, codec: string) {
- const allSongs = await ctx.runQuery(internal.library.getSongs)
+type NewSong = {
+ name: string
+ files: Record
+ artist: string | string[]
+ length: number
+ diskNumber: number | null
+ track: number
+ year: number
+ date: string
+ genres: string[]
+}
- const songsToRemove: Id<"songs">[] = []
- const songsToUpdate: { id: Id<"songs">; files: Record }[] = []
- for (const song of allSongs) {
- if (!(codec in song.files)) {
+type ImportEntry = {
+ artist: { name: string; folder: string; cover: string | null }
+ album: {
+ name: string
+ folder: string
+ cover: string | null
+ year: number
+ date: string
+ }
+ songs: Map
+}
+
+/**
+ * Reconciles the database with the files on disk. Reads the library once in
+ * pages, walks the disk once, parses only untracked files and writes only
+ * what changed, so re-scanning an unchanged library makes no writes.
+ */
+async function scanLibrary(ctx: ActionCtx) {
+ const startedAt = Date.now()
+ const codecs = (await fs.readdir(DATA_DIR, { withFileTypes: true }))
+ .filter((dirent) => dirent.isDirectory())
+ .map((dirent) => dirent.name)
+
+ const [artists, albums, songs, disk] = await Promise.all([
+ collectPages((cursor) =>
+ ctx.runQuery(internal.library.scanArtistsPage, {
+ paginationOpts: { numItems: SCAN_PAGE_SIZE, cursor },
+ })
+ ),
+ collectPages((cursor) =>
+ ctx.runQuery(internal.library.scanAlbumsPage, {
+ paginationOpts: { numItems: SCAN_PAGE_SIZE, cursor },
+ })
+ ),
+ collectPages((cursor) =>
+ ctx.runQuery(internal.library.scanSongsPage, {
+ paginationOpts: { numItems: SCAN_PAGE_SIZE, cursor },
+ })
+ ),
+ walkLibrary(codecs),
+ ])
+
+ if (disk.files.size === 0 && songs.length > 0) {
+ throw new Error(
+ `No audio files found under ${DATA_DIR}; refusing to empty the library`
+ )
+ }
+
+ // Drop file paths that are gone from disk (including removed codecs). Songs
+ // left without files are deleted below unless a new file matches them.
+ const songFiles = new Map, Record>()
+ const changedSongs = new Set>()
+ const songsByAlbum = new Map, Map>>()
+ const tracked = new Set()
+ for (const song of songs) {
+ const entries = Object.entries(song.files)
+ const kept = entries.filter(([, filePath]) => disk.files.has(filePath))
+ if (kept.length !== entries.length) {
+ changedSongs.add(song._id)
+ }
+ songFiles.set(song._id, Object.fromEntries(kept))
+ for (const [, filePath] of kept) {
+ tracked.add(filePath)
+ }
+ const byName = songsByAlbum.get(song.album) ?? new Map()
+ if (!byName.has(song.name)) {
+ byName.set(song.name, song._id)
+ }
+ songsByAlbum.set(song.album, byName)
+ }
+
+ // Parse untracked files only.
+ const untracked = disk.albums.flatMap((album) =>
+ album.files
+ .filter((filePath) => !tracked.has(filePath))
+ .map((filePath) => ({ ...album, filePath }))
+ )
+ const deadline = startedAt + SCAN_PARSE_BUDGET_MS
+ const parsed = await mapLimit(untracked, FS_CONCURRENCY, async (file) => {
+ if (Date.now() > deadline) {
+ return null
+ }
+ try {
+ const metadata = await music.parseFile(file.filePath, {
+ skipCovers: true,
+ })
+ return { ...file, metadata }
+ } catch {
+ return null
+ }
+ })
+ const skipped = parsed.filter((file) => file === null).length
+
+ const artistByFolder = new Map(
+ artists.map((artist) => [artist.folder, artist])
+ )
+ const albumByKey = new Map(
+ albums.map((album) => [`${album.artist}/${album.folder}`, album])
+ )
+ const imports = new Map()
+ for (const file of parsed) {
+ if (file === null) {
+ continue
+ }
+ const { codec, artistFolder, albumFolder, filePath, metadata } = file
+ const common = metadata.common
+ const title = common.title || path.parse(filePath).name
+
+ const dbArtist = artistByFolder.get(artistFolder)
+ const dbAlbum = dbArtist
+ ? albumByKey.get(`${dbArtist._id}/${albumFolder}`)
+ : undefined
+ const existingId = dbAlbum && songsByAlbum.get(dbAlbum._id)?.get(title)
+ if (existingId) {
+ // A same-titled sibling must not steal a path that still exists.
+ const files = songFiles.get(existingId)!
+ if (!(codec in files)) {
+ songFiles.set(existingId, { ...files, [codec]: filePath })
+ changedSongs.add(existingId)
+ }
continue
}
- const { [codec]: _, ...update } = song.files
- if (Object.keys(update).length === 0) {
- songsToRemove.push(song._id)
- } else {
- songsToUpdate.push({
- id: song._id,
- files: update,
- })
+ const key = `${artistFolder}/${albumFolder}`
+ let entry = imports.get(key)
+ if (!entry) {
+ entry = {
+ artist: {
+ name: common.albumartist || artistFolder,
+ folder: artistFolder,
+ cover: pickCover(
+ null,
+ codecs.map((c) => `${DATA_DIR}/${c}/${artistFolder}/folder.jpg`),
+ disk.covers
+ ),
+ },
+ album: {
+ name: common.album || albumFolder,
+ folder: albumFolder,
+ cover: pickCover(
+ null,
+ codecs.map(
+ (c) => `${DATA_DIR}/${c}/${artistFolder}/${albumFolder}/cover.jpg`
+ ),
+ disk.covers
+ ),
+ year: common.year || 0,
+ date: releaseDate(common),
+ },
+ songs: new Map(),
+ }
+ imports.set(key, entry)
}
+
+ const pending = entry.songs.get(title)
+ if (pending) {
+ pending.files[codec] ??= filePath
+ continue
+ }
+ entry.songs.set(title, {
+ name: title,
+ files: { [codec]: filePath },
+ artist:
+ common.artist ?? common.artists ?? dbArtist?.name ?? entry.artist.name,
+ length: Math.round(metadata.format.duration || 0),
+ diskNumber: common.disk.of === 1 ? null : common.disk.no,
+ track: common.track.no || 0,
+ year: common.year || 0,
+ date: releaseDate(common),
+ genres: common.genre || [],
+ })
}
- await ctx.runMutation(internal.library.changeFilesForSongs, {
- songs: songsToUpdate,
- })
- await purgeRemovedSongs(ctx, songsToRemove)
- await ctx.runMutation(internal.library.removeSongs, { ids: songsToRemove })
-
- const allAlbums = await ctx.runQuery(internal.library.getAlbums)
- const removedSongIds = new Set(songsToRemove)
- const albumsWithSongs = new Set(
- allSongs.flatMap((song) =>
- removedSongIds.has(song._id) ? [] : [song.album]
- )
+ const deletedSongs = songs.flatMap((song) =>
+ Object.keys(songFiles.get(song._id)!).length === 0 ? [song._id] : []
)
- const albumsToRemove = allAlbums
+ const deletedSongSet = new Set(deletedSongs)
+ const updatedSongs = [...changedSongs].filter((id) => !deletedSongSet.has(id))
+
+ const albumsWithSongs = new Set(
+ songs.flatMap((song) => (deletedSongSet.has(song._id) ? [] : [song.album]))
+ )
+ const emptyAlbums = albums
.filter((album) => !albumsWithSongs.has(album._id))
.map((album) => album._id)
- await purgeRemovedAlbums(ctx, albumsToRemove)
- await ctx.runMutation(internal.library.removeAlbums, { ids: albumsToRemove })
-
- const allArtists = await ctx.runQuery(internal.library.getArtists)
- const removedAlbumIds = new Set(albumsToRemove)
+ const emptyAlbumSet = new Set(emptyAlbums)
const artistsWithAlbums = new Set(
- allAlbums.flatMap((album) =>
- removedAlbumIds.has(album._id) ? [] : [album.artist]
+ albums.flatMap((album) =>
+ emptyAlbumSet.has(album._id) ? [] : [album.artist]
)
)
- const artistsToRemove = allArtists
+ const emptyArtists = artists
.filter((artist) => !artistsWithAlbums.has(artist._id))
.map((artist) => artist._id)
- await purgeRemovedArtists(ctx, artistsToRemove)
- await ctx.runMutation(internal.library.removeArtists, {
- ids: artistsToRemove,
+ const emptyArtistSet = new Set(emptyArtists)
+
+ // Albums and artists about to be deleted keep their cover.
+ const artistById = new Map(artists.map((artist) => [artist._id, artist]))
+ const artistCovers = artists.flatMap((artist) => {
+ if (emptyArtistSet.has(artist._id)) {
+ return []
+ }
+ const cover = pickCover(
+ artist.cover,
+ codecs.map((c) => `${DATA_DIR}/${c}/${artist.folder}/folder.jpg`),
+ disk.covers
+ )
+ return cover === artist.cover ? [] : [{ id: artist._id, cover }]
})
+ const albumCovers = albums.flatMap((album) => {
+ const artist = artistById.get(album.artist)
+ if (!artist || emptyAlbumSet.has(album._id)) {
+ return []
+ }
+ const cover = pickCover(
+ album.cover,
+ codecs.map(
+ (c) => `${DATA_DIR}/${c}/${artist.folder}/${album.folder}/cover.jpg`
+ ),
+ disk.covers
+ )
+ return cover === album.cover ? [] : [{ id: album._id, cover }]
+ })
+
+ // Writes. Imports run before the empty-album/artist sweeps, and those
+ // mutations re-check emptiness, so nothing that gained songs is deleted.
+ for (const batch of chunk(updatedSongs, SCAN_BATCH_SIZE)) {
+ await ctx.runMutation(internal.library.changeFilesForSongs, {
+ songs: batch.map((id) => ({ id, files: songFiles.get(id)! })),
+ })
+ }
+ for (const batch of chunk(deletedSongs, SCAN_BATCH_SIZE)) {
+ await ctx.runMutation(internal.library.deleteSongs, { ids: batch })
+ }
+
+ let importBatch: ImportEntry[] = []
+ let importBatchSongs = 0
+ const flushImports = async () => {
+ if (importBatch.length === 0) {
+ return
+ }
+ await ctx.runMutation(internal.library.importAlbums, {
+ albums: importBatch.map((entry) => ({
+ ...entry,
+ songs: [...entry.songs.values()],
+ })),
+ })
+ importBatch = []
+ importBatchSongs = 0
+ }
+ for (const entry of imports.values()) {
+ importBatch.push(entry)
+ importBatchSongs += entry.songs.size
+ if (importBatchSongs >= SCAN_BATCH_SIZE) {
+ await flushImports()
+ }
+ }
+ await flushImports()
+
+ for (const batch of chunk(artistCovers, SCAN_BATCH_SIZE)) {
+ await ctx.runMutation(internal.library.updateArtistCovers, {
+ artists: batch,
+ })
+ }
+ for (const batch of chunk(albumCovers, SCAN_BATCH_SIZE)) {
+ await ctx.runMutation(internal.library.updateAlbumCovers, {
+ albums: batch,
+ })
+ }
+
+ let removedAlbums = 0
+ for (const batch of chunk(emptyAlbums, SCAN_BATCH_SIZE)) {
+ removedAlbums += await ctx.runMutation(internal.library.deleteEmptyAlbums, {
+ ids: batch,
+ })
+ }
+
+ let removedArtists = 0
+ for (const batch of chunk(emptyArtists, SCAN_BATCH_SIZE)) {
+ removedArtists += await ctx.runMutation(
+ internal.library.deleteEmptyArtists,
+ { ids: batch }
+ )
+ }
+
+ const importedSongs = [...imports.values()].reduce(
+ (total, entry) => total + entry.songs.size,
+ 0
+ )
+ const summary =
+ `songs: ${importedSongs} added, ${updatedSongs.length} updated, ` +
+ `${deletedSongs.length} removed; albums removed: ${removedAlbums}; ` +
+ `artists removed: ${removedArtists}; covers updated: ` +
+ `${artistCovers.length + albumCovers.length}; ` +
+ `files deferred: ${skipped}; ${Date.now() - startedAt}ms`
+ console.log(`library scan: ${summary}`)
+ return summary
}
+/** Runs one scan under the library scan lock; `null` if one is already running. */
export const scheduledUpdateLibrary = internalAction({
args: {},
- handler: async (ctx) => {
- const codecs = (await fs.readdir(DATA_DIR, { withFileTypes: true }))
- .filter((dirent) => dirent.isDirectory())
- .map((dirent) => dirent.name)
-
- const dbCodecs = Array.from(
- new Map(
- (await ctx.runQuery(internal.library.getSongs))
- .map((song) => {
- return Object.keys(song.files)
- })
- .flat()
- .map((codec) => [codec, codec])
- ).values()
+ handler: async (ctx): Promise => {
+ const token = crypto.randomUUID()
+ const acquired: boolean = await ctx.runMutation(
+ internal.library.acquireLibraryScanLock,
+ { token, leaseMs: SCAN_LOCK_LEASE_MS }
)
-
- for (const dbCodec of dbCodecs) {
- if (!codecs.includes(dbCodec)) {
- await removeCodecFromDatabase(ctx, dbCodec)
- }
+ if (!acquired) {
+ console.log("library scan: already running, skipped")
+ return null
}
-
- // Removals
- for (const codec of codecs) {
- const dbArtists = await ctx.runQuery(internal.library.getArtists)
- const dbAlbums = await ctx.runQuery(internal.library.getAlbums)
- const dbSongs = await ctx.runQuery(internal.library.getSongs)
-
- const dirtySongs = dbSongs
- .filter((song) => {
- return codec in song.files && !fsSync.existsSync(song.files[codec])
- })
- .map((song) => {
- const { [codec]: _, ...update } = song.files
- return { id: song._id, files: update }
- })
-
- const songsToDelete = dirtySongs.filter(
- (song) => Object.keys(song.files).length === 0
- )
- const songsToUpdate = dirtySongs.filter(
- (song) => Object.keys(song.files).length !== 0
- )
- const songsToDeleteIDs = songsToDelete.map((song) => song.id)
-
- await purgeRemovedSongs(ctx, songsToDeleteIDs)
- await ctx.runMutation(internal.library.removeSongs, {
- ids: songsToDeleteIDs,
- })
- await ctx.runMutation(internal.library.changeFilesForSongs, {
- songs: songsToUpdate,
- })
-
- const deletedSongIds = new Set(songsToDeleteIDs)
- const albumsWithSongs = new Set(
- dbSongs.flatMap((song) =>
- deletedSongIds.has(song._id) ? [] : [song.album]
- )
- )
- const albumsToDelete = dbAlbums
- .filter((album) => !albumsWithSongs.has(album._id))
- .map((album) => album._id)
- await purgeRemovedAlbums(ctx, albumsToDelete)
- await ctx.runMutation(internal.library.removeAlbums, {
- ids: albumsToDelete,
- })
-
- const deletedAlbumIds = new Set(albumsToDelete)
- const artistsWithAlbums = new Set(
- dbAlbums.flatMap((album) =>
- deletedAlbumIds.has(album._id) ? [] : [album.artist]
- )
- )
- const artistsToDelete = dbArtists
- .filter((artist) => !artistsWithAlbums.has(artist._id))
- .map((artist) => artist._id)
- await purgeRemovedArtists(ctx, artistsToDelete)
- await ctx.runMutation(internal.library.removeArtists, {
- ids: artistsToDelete,
- })
+ try {
+ return await scanLibrary(ctx)
+ } finally {
+ await ctx.runMutation(internal.library.releaseLibraryScanLock, { token })
}
-
- // Additions
- for (const codec of codecs) {
- // Artists
- console.log(`${codec}: artists`)
- let dbArtists = await ctx.runQuery(internal.library.getArtists)
- const dbArtistFolders = dbArtists.map((artist) => artist.folder)
- const artists = (
- await fs.readdir(`${DATA_DIR}/${codec}`, { withFileTypes: true })
- )
- .filter((dirent) => dirent.isDirectory())
- .map((dirent) => dirent.name)
- const potentialArtists = artists.filter(
- (artist) => !dbArtistFolders.includes(artist)
- )
-
- const newArtists = []
- for (const folder of potentialArtists) {
- const albums = (
- await fs.readdir(`${DATA_DIR}/${codec}/${folder}`, {
- withFileTypes: true,
- })
- )
- .filter((dirent) => dirent.isDirectory())
- .map((dirent) => dirent.name)
-
- if (albums.length === 0) {
- continue
- }
-
- for (let i = 0; i < albums.length; i++) {
- const songs = (
- await fs.readdir(`${DATA_DIR}/${codec}/${folder}/${albums[i]}`, {
- withFileTypes: true,
- })
- )
- .filter(
- (dirent) => !dirent.isDirectory() && dirent.name !== "cover.jpg"
- )
- .map((dirent) => dirent.name)
-
- if (songs.length === 0) {
- continue
- }
-
- try {
- const metadata = await music.parseFile(
- `${DATA_DIR}/${codec}/${folder}/${albums[i]}/${songs[0]}`,
- { skipCovers: true }
- )
-
- const artistCoverPath = `${DATA_DIR}/${codec}/${folder}/folder.jpg`
- const cover = await coverPathIfExists(artistCoverPath)
-
- newArtists.push({
- name: metadata.common.albumartist || folder,
- folder,
- cover,
- })
- break
- } catch {}
- }
- }
- await ctx.runMutation(internal.library.createArtists, {
- artists: newArtists,
- })
- dbArtists = await ctx.runQuery(internal.library.getArtists)
-
- // Albums
- console.log(`${codec}: albums`)
- let dbAlbums = await ctx.runQuery(internal.library.getAlbums)
- const newAlbums = []
- for (const dbArtist of dbArtists) {
- const dbAlbumsInArtist = dbAlbums.filter(
- (album) => album.artist === dbArtist._id
- )
- const dbAlbumFolders = dbAlbumsInArtist.map((album) => album.folder)
-
- if (!fsSync.existsSync(`${DATA_DIR}/${codec}/${dbArtist.folder}`)) {
- continue
- }
-
- const albums = (
- await fs.readdir(`${DATA_DIR}/${codec}/${dbArtist.folder}`, {
- withFileTypes: true,
- })
- )
- .filter((dirent) => dirent.isDirectory())
- .map((dirent) => dirent.name)
- const potentialAlbums = albums.filter(
- (album) => !dbAlbumFolders.includes(album)
- )
-
- for (const potentialAlbum of potentialAlbums) {
- const potentialAlbumPath = `${DATA_DIR}/${codec}/${dbArtist.folder}/${potentialAlbum}`
- if (!fsSync.existsSync(potentialAlbumPath)) {
- continue
- }
-
- const songs = (
- await fs.readdir(potentialAlbumPath, {
- withFileTypes: true,
- })
- )
- .filter(
- (dirent) => !dirent.isDirectory() && dirent.name !== "cover.jpg"
- )
- .map((dirent) => dirent.name)
-
- if (songs.length === 0) {
- continue
- }
-
- try {
- const metadata = await music.parseFile(
- `${potentialAlbumPath}/${songs[0]}`,
- { skipCovers: true }
- )
-
- const albumCoverPath = `${DATA_DIR}/${codec}/${dbArtist.folder}/${potentialAlbum}/cover.jpg`
- const cover = await coverPathIfExists(albumCoverPath)
-
- newAlbums.push({
- name: metadata.common.album || potentialAlbum,
- folder: potentialAlbum,
- cover,
- year: metadata.common.year || 2026,
- date:
- metadata.common.date || `01-01-${metadata.common.year || 2026}`,
- artist: dbArtist._id,
- })
- } catch {}
- }
- }
- await ctx.runMutation(internal.library.createAlbums, {
- albums: newAlbums,
- })
- dbAlbums = await ctx.runQuery(internal.library.getAlbums)
- const dbSongs = await ctx.runQuery(internal.library.getSongs)
-
- const dbAlbumsArtists = dbAlbums.map((album) => {
- return {
- ...album,
- artist: dbArtists.find((artist) => artist._id === album.artist)!,
- }
- })
-
- // Covers
- console.log(`${codec}: covers`)
- for (const dbArtist of dbArtists) {
- const artistPath = `${DATA_DIR}/${codec}/${dbArtist.folder}`
- if (!fsSync.existsSync(artistPath)) {
- continue
- }
- await syncArtistCover(
- ctx,
- codec,
- dbArtist.cover,
- `${artistPath}/folder.jpg`,
- dbArtist._id
- )
- }
-
- for (const dbAlbum of dbAlbumsArtists) {
- const artistPath = `${DATA_DIR}/${codec}/${dbAlbum.artist.folder}`
- const albumPath = `${artistPath}/${dbAlbum.folder}`
- if (!fsSync.existsSync(artistPath) || !fsSync.existsSync(albumPath)) {
- continue
- }
- await syncAlbumCover(
- ctx,
- codec,
- dbAlbum.cover,
- `${albumPath}/cover.jpg`,
- dbAlbum._id
- )
- }
-
- // Songs
- console.log(`${codec}: songs`)
-
- const newSongs = []
- const updateSongs = []
- for (const dbAlbum of dbAlbumsArtists) {
- const dbSongsInAlbum = dbSongs.filter(
- (song) => song.album === dbAlbum._id
- )
- const dbAlreadyTracked = dbSongsInAlbum
- .filter((song) => codec in song.files)
- .map((song) => song.files[codec])
-
- const artistPath = `${DATA_DIR}/${codec}/${dbAlbum.artist.folder}`
- const albumPath = `${artistPath}/${dbAlbum.folder}`
- if (!fsSync.existsSync(artistPath) || !fsSync.existsSync(albumPath)) {
- continue
- }
-
- const songs = (await fs.readdir(albumPath, { withFileTypes: true }))
- .filter(
- (dirent) => !dirent.isDirectory() && dirent.name !== "cover.jpg"
- )
- .map((dirent) => dirent.name)
- .filter((song) => !dbAlreadyTracked.includes(`${albumPath}/${song}`))
-
- for (const song of songs) {
- try {
- const path = `${DATA_DIR}/${codec}/${dbAlbum.artist.folder}/${dbAlbum.folder}/${song}`
- const metadata = await music.parseFile(path, { skipCovers: true })
-
- if (!metadata.common.title) {
- continue
- }
-
- const existingSong = dbSongsInAlbum.find(
- (dbSong) => dbSong.name === metadata.common.title
- )
-
- if (existingSong) {
- if (
- !(codec in existingSong.files) ||
- existingSong.files[codec] !== path
- ) {
- const update = { [codec]: path, ...existingSong.files }
- updateSongs.push({
- id: existingSong._id,
- files: update,
- })
- }
- } else {
- let files = { [codec]: path }
-
- if (codec !== "atmos") {
- const artistPath = `${DATA_DIR}/atmos/${dbAlbum.artist.folder}`
- const albumPath = `${artistPath}/${dbAlbum.folder}`
- const path = `${albumPath}/${song}`
-
- if (fsSync.existsSync(path)) {
- files = { atmos: path, ...files }
- }
- }
- if (codec !== "lossless") {
- const artistPath = `${DATA_DIR}/lossless/${dbAlbum.artist.folder}`
- const albumPath = `${artistPath}/${dbAlbum.folder}`
- const path = `${albumPath}/${song}`
-
- if (fsSync.existsSync(path)) {
- files = { lossless: path, ...files }
- }
- }
- if (codec !== "normal") {
- const artistPath = `${DATA_DIR}/normal/${dbAlbum.artist.folder}`
- const albumPath = `${artistPath}/${dbAlbum.folder}`
- const path = `${albumPath}/${song}`
-
- if (fsSync.existsSync(path)) {
- files = { normal: path, ...files }
- }
- }
-
- newSongs.push({
- name: metadata.common.title,
- files,
- album: dbAlbum._id,
- artist:
- metadata.common.artist ??
- metadata.common.artists ??
- dbAlbum.artist.name,
- albumArtist: dbAlbum.artist._id,
- length: Math.round(metadata.format.duration || 0),
- diskNumber:
- metadata.common.disk.of === 1
- ? null
- : metadata.common.disk.no,
- track: metadata.common.track.no || 0,
- year: metadata.common.year || 2026,
- date:
- metadata.common.date ||
- `01-01-${metadata.common.year || 2026}`,
- genres: metadata.common.genre || [],
- })
- }
- } catch {}
- }
- }
- await ctx.runMutation(internal.library.createSongs, { songs: newSongs })
- await ctx.runMutation(internal.library.changeFilesForSongs, {
- songs: updateSongs,
- })
- }
-
- return "success"
},
})
@@ -574,14 +556,13 @@ export const updateLibrary = action({
args: {},
handler: async (ctx): Promise => {
await requireAdmin(ctx)
- return ctx.runAction(internal.actions.scheduledUpdateLibrary)
- },
-})
-
-export const cleanupHlsStreams = internalAction({
- args: {},
- handler: async () => {
- return await cleanHlsStreamsOlderThan(HLS_MAX_IDLE_MS)
+ const result: string | null = await ctx.runAction(
+ internal.actions.scheduledUpdateLibrary
+ )
+ if (result === null) {
+ throw new ConvexError("A library scan is already running")
+ }
+ return result
},
})
diff --git a/packages/convex/convex/auth.ts b/packages/convex/convex/auth.ts
index e89895e..14314c8 100644
--- a/packages/convex/convex/auth.ts
+++ b/packages/convex/convex/auth.ts
@@ -3,6 +3,7 @@ import { ConvexError } from "convex/values"
import { Password } from "@convex-dev/auth/providers/Password"
import { query } from "./_generated/server"
import type { MutationCtx } from "./_generated/server"
+import { profileImagePath } from "./users"
export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({
providers: [
@@ -72,7 +73,7 @@ export const currentUser = query({
return {
_id: user._id,
name: user.name,
- image: user.image,
+ image: profileImagePath(user),
email: user.email,
isAdmin: user.isAdmin,
playbackQuality: user.playbackQuality,
diff --git a/packages/convex/convex/crons.ts b/packages/convex/convex/crons.ts
index d9e88f7..e69be87 100644
--- a/packages/convex/convex/crons.ts
+++ b/packages/convex/convex/crons.ts
@@ -9,4 +9,10 @@ crons.interval(
internal.actions.scheduledUpdateLibrary
)
+crons.daily(
+ "prune Siri catalog change log",
+ { hourUTC: 9, minuteUTC: 0 },
+ internal.intentCatalogChanges.pruneIntentCatalogChanges
+)
+
export default crons
diff --git a/packages/convex/convex/favorites.ts b/packages/convex/convex/favorites.ts
index ee5e79d..d4c0bc9 100644
--- a/packages/convex/convex/favorites.ts
+++ b/packages/convex/convex/favorites.ts
@@ -1,11 +1,10 @@
import { getAuthUserId } from "@convex-dev/auth/server"
import { ConvexError, v } from "convex/values"
-import { paginationOptsValidator } from "convex/server"
import type { Doc, Id } from "./_generated/dataModel"
import type { MutationCtx, QueryCtx } from "./_generated/server"
import { mutation, query } from "./_generated/server"
import type { BrowsePlaylistDetail, BrowsePlaylistSummary } from "./library"
-import { browseSongsFromIds, paginateSlice } from "./library"
+import { browseSongsFromIds } from "./library"
function uniqueIds(ids: T[]): T[] {
return [...new Set(ids)]
@@ -181,11 +180,6 @@ async function browseFavoritesSummaryHandler(
}
}
-export const browseFavoritesSummary = query({
- args: {},
- handler: async (ctx) => browseFavoritesSummaryHandler(ctx),
-})
-
export const browseFavoritesPlaylistDetail = query({
args: {},
handler: async (ctx): Promise => {
@@ -209,24 +203,6 @@ export const browseFavoritesPlaylistDetail = query({
},
})
-export const browseFavoritesSongsPaginated = query({
- args: { paginationOpts: paginationOptsValidator },
- handler: async (ctx, args) => {
- const summary = await browseFavoritesSummaryHandler(ctx)
- if (!summary) {
- return { page: [], isDone: true, continueCursor: "" }
- }
-
- const slice = paginateSlice(summary.songIds, args.paginationOpts)
- const page = await browseSongsFromIds(ctx, slice.page)
-
- return {
- ...slice,
- page,
- }
- },
-})
-
export const favoriteSong = mutation({
args: { songId: v.id("songs") },
handler: async (ctx, { songId }) => {
diff --git a/packages/convex/convex/intentCatalog.ts b/packages/convex/convex/intentCatalog.ts
new file mode 100644
index 0000000..cb649da
--- /dev/null
+++ b/packages/convex/convex/intentCatalog.ts
@@ -0,0 +1,337 @@
+import { getAuthUserId } from "@convex-dev/auth/server"
+import { paginationOptsValidator } from "convex/server"
+import { ConvexError, v } from "convex/values"
+import type { Doc, Id } from "./_generated/dataModel"
+import { query, type QueryCtx } from "./_generated/server"
+import {
+ INTENT_CATALOG_CHANGE_RETENTION_MS,
+ type LibraryCatalogKind,
+} from "./intentCatalogChanges"
+import { getSongArtistNames, songArtistsMatchAlbum } from "./library"
+
+/**
+ * Siri/App Intents entity catalog. Library records carry no per-user state, so
+ * clients sync them incrementally and overlay favorites locally.
+ */
+
+const FAVORITES_PLAYLIST_ID = "otunes:favorites"
+/** More changes than this since a client's cursor and it rebuilds instead. */
+const MAX_CHANGES_PER_SYNC = 2000
+
+const libraryKindValidator = v.union(
+ v.literal("song"),
+ v.literal("album"),
+ v.literal("artist")
+)
+
+type IntentEntity = {
+ id: string
+ title: string
+ subtitle?: string
+ synonyms?: string[]
+ metadata: Record
+}
+
+async function requireUser(ctx: QueryCtx) {
+ const userId = await getAuthUserId(ctx)
+ if (!userId) throw new ConvexError("Not authenticated")
+ return userId
+}
+
+function unique(values: T[]) {
+ return [...new Set(values)]
+}
+
+async function getMany(
+ ctx: QueryCtx,
+ table: Table,
+ ids: Id[]
+) {
+ const docs = await Promise.all(unique(ids).map((id) => ctx.db.get(table, id)))
+ return new Map(
+ docs.flatMap((doc) => (doc ? [[doc._id as Id, doc] as const] : []))
+ )
+}
+
+async function songEntities(ctx: QueryCtx, songs: Doc<"songs">[]) {
+ const [albums, artists] = await Promise.all([
+ getMany(
+ ctx,
+ "albums",
+ songs.map((song) => song.album)
+ ),
+ getMany(
+ ctx,
+ "artists",
+ songs.map((song) => song.albumArtist)
+ ),
+ ])
+ return songs.flatMap((song): IntentEntity[] => {
+ const album = albums.get(song.album)
+ const artist = artists.get(song.albumArtist)
+ if (!album || !artist || !song.name.trim()) return []
+ const credits = getSongArtistNames(song.artist)
+ const artistName = songArtistsMatchAlbum(credits, artist.name)
+ ? artist.name
+ : credits.join(", ") || artist.name
+ return [
+ {
+ id: song._id,
+ title: song.name,
+ subtitle: artistName,
+ metadata: {
+ artistName,
+ artistId: artist._id,
+ albumTitle: album.name,
+ albumId: album._id,
+ duration: String(Math.max(0, Math.round(song.length))),
+ genres: song.genres.join(", "),
+ year: song.year ? String(song.year) : "",
+ track: String(song.track),
+ disk: String(song.diskNumber ?? ""),
+ },
+ },
+ ]
+ })
+}
+
+async function albumEntities(ctx: QueryCtx, albums: Doc<"albums">[]) {
+ const artists = await getMany(
+ ctx,
+ "artists",
+ albums.map((album) => album.artist)
+ )
+ return albums.flatMap((album): IntentEntity[] => {
+ const artist = artists.get(album.artist)
+ if (!artist || !album.name.trim()) return []
+ return [
+ {
+ id: album._id,
+ title: album.name,
+ subtitle: artist.name,
+ metadata: {
+ artistName: artist.name,
+ artistId: artist._id,
+ year: album.year ? String(album.year) : "",
+ },
+ },
+ ]
+ })
+}
+
+function artistEntities(artists: Doc<"artists">[]) {
+ return artists.flatMap((artist): IntentEntity[] =>
+ artist.name.trim()
+ ? [{ id: artist._id, title: artist.name, metadata: {} }]
+ : []
+ )
+}
+
+/** Rows in `ids` not already in `rows`, so renamed records are re-sent. */
+async function withUpdatedRows(
+ rows: Row[],
+ ids: string[],
+ load: (id: string) => Promise
+) {
+ const seen = new Set(rows.map((row) => row._id))
+ const updated: (Row | null)[] = await Promise.all(
+ ids.filter((id) => !seen.has(id)).map(load)
+ )
+ return [...rows, ...updated.flatMap((row) => (row ? [row] : []))]
+}
+
+async function newestCreationTime(ctx: QueryCtx, kind: LibraryCatalogKind) {
+ const table =
+ kind === "song" ? "songs" : kind === "album" ? "albums" : "artists"
+ const [row, change] = await Promise.all([
+ ctx.db.query(table).order("desc").first(),
+ ctx.db
+ .query("intentCatalogChanges")
+ .withIndex("by_kind", (q) => q.eq("kind", kind))
+ .order("desc")
+ .first(),
+ ])
+ return Math.max(row?._creationTime ?? 0, change?._creationTime ?? 0)
+}
+
+/**
+ * Newest insert, rename or deletion per kind. Clients subscribe to this and
+ * fetch a kind only after it moves past their cursor.
+ */
+export const head = query({
+ args: {},
+ handler: async (ctx) => {
+ await requireUser(ctx)
+ const [song, album, artist] = await Promise.all([
+ newestCreationTime(ctx, "song"),
+ newestCreationTime(ctx, "album"),
+ newestCreationTime(ctx, "artist"),
+ ])
+ return { song, album, artist }
+ },
+})
+
+/**
+ * One page of catalog records. Without `since` it walks the whole library;
+ * with it, only records created, renamed or removed after `since`. The first
+ * page reports `head`, the cursor to resume from once every page is read, and
+ * `reset` when the change log no longer covers `since` (stale or too many
+ * changes); the client then rebuilds without `since`.
+ */
+export const page = query({
+ args: {
+ kind: libraryKindValidator,
+ since: v.optional(v.number()),
+ paginationOpts: paginationOptsValidator,
+ },
+ handler: async (ctx, { kind, since, paginationOpts }) => {
+ await requireUser(ctx)
+ const firstPage = paginationOpts.cursor === null
+ let removed: string[] = []
+ let updatedIds: string[] = []
+ if (firstPage && since !== undefined) {
+ const changes = await ctx.db
+ .query("intentCatalogChanges")
+ .withIndex("by_kind", (q) =>
+ q.eq("kind", kind).gt("_creationTime", since)
+ )
+ .take(MAX_CHANGES_PER_SYNC + 1)
+ // Pruning may have dropped deletions older than the retention window.
+ const expired = since < Date.now() - INTENT_CATALOG_CHANGE_RETENTION_MS
+ if (expired || changes.length > MAX_CHANGES_PER_SYNC) {
+ return {
+ page: [],
+ isDone: true,
+ continueCursor: "",
+ head: await newestCreationTime(ctx, kind),
+ removed,
+ reset: true,
+ }
+ }
+ removed = unique(
+ changes.filter((change) => change.removed).map((c) => c.entityId)
+ )
+ const removedIds = new Set(removed)
+ updatedIds = unique(
+ changes
+ .filter((change) => !removedIds.has(change.entityId))
+ .map((change) => change.entityId)
+ )
+ }
+ const head = firstPage ? await newestCreationTime(ctx, kind) : undefined
+
+ const respond = (
+ rows: { isDone: boolean; continueCursor: string },
+ page: IntentEntity[]
+ ) => ({
+ page,
+ isDone: rows.isDone,
+ continueCursor: rows.continueCursor,
+ head,
+ removed,
+ reset: false,
+ })
+ // Rows created after `since`, or every row when it is omitted.
+ if (kind === "song") {
+ const query = ctx.db.query("songs")
+ const rows = await (
+ since === undefined
+ ? query
+ : query.withIndex("by_creation_time", (q) =>
+ q.gt("_creationTime", since)
+ )
+ ).paginate(paginationOpts)
+ const docs = await withUpdatedRows(rows.page, updatedIds, (id) => {
+ const songId = ctx.db.normalizeId("songs", id)
+ return songId ? ctx.db.get("songs", songId) : Promise.resolve(null)
+ })
+ return respond(rows, await songEntities(ctx, docs))
+ }
+ if (kind === "album") {
+ const query = ctx.db.query("albums")
+ const rows = await (
+ since === undefined
+ ? query
+ : query.withIndex("by_creation_time", (q) =>
+ q.gt("_creationTime", since)
+ )
+ ).paginate(paginationOpts)
+ const docs = await withUpdatedRows(rows.page, updatedIds, (id) => {
+ const albumId = ctx.db.normalizeId("albums", id)
+ return albumId ? ctx.db.get("albums", albumId) : Promise.resolve(null)
+ })
+ return respond(rows, await albumEntities(ctx, docs))
+ }
+ const query = ctx.db.query("artists")
+ const rows = await (
+ since === undefined
+ ? query
+ : query.withIndex("by_creation_time", (q) =>
+ q.gt("_creationTime", since)
+ )
+ ).paginate(paginationOpts)
+ const docs = await withUpdatedRows(rows.page, updatedIds, (id) => {
+ const artistId = ctx.db.normalizeId("artists", id)
+ return artistId ? ctx.db.get("artists", artistId) : Promise.resolve(null)
+ })
+ return respond(rows, artistEntities(docs))
+ },
+})
+
+/** The signed-in user's own and subscribed playlists, plus Favorites. */
+export const playlists = query({
+ args: {},
+ handler: async (ctx) => {
+ const userId = await requireUser(ctx)
+ const user = await ctx.db.get("users", userId)
+ if (!user) throw new ConvexError("Not authenticated")
+ const [owned, subscribed] = await Promise.all([
+ ctx.db
+ .query("playlists")
+ .withIndex("by_owner", (q) => q.eq("owner", userId))
+ .collect(),
+ Promise.all(
+ unique(user.subscribedPlaylists ?? []).map((id) =>
+ ctx.db.get("playlists", id)
+ )
+ ),
+ ])
+ const others = subscribed.filter(
+ (playlist): playlist is Doc<"playlists"> =>
+ playlist !== null && playlist.owner !== userId
+ )
+ const owners = await getMany(
+ ctx,
+ "users",
+ others.map((playlist) => playlist.owner)
+ )
+ owners.set(userId, user)
+ const entities: IntentEntity[] = [
+ {
+ id: FAVORITES_PLAYLIST_ID,
+ title: "Favorites",
+ synonyms: [
+ "favorites",
+ "favourite songs",
+ "liked songs",
+ "loved songs",
+ ],
+ metadata: { ownerName: user.name, createdByMe: "1" },
+ },
+ ]
+ for (const playlist of [...owned, ...others]) {
+ if (!playlist.name.trim()) continue
+ const ownerName = owners.get(playlist.owner)?.name ?? ""
+ entities.push({
+ id: playlist._id,
+ title: playlist.name,
+ subtitle: ownerName,
+ metadata: {
+ ownerName,
+ createdByMe: playlist.owner === userId ? "1" : "0",
+ },
+ })
+ }
+ return entities
+ },
+})
diff --git a/packages/convex/convex/intentCatalogChanges.ts b/packages/convex/convex/intentCatalogChanges.ts
new file mode 100644
index 0000000..b77531d
--- /dev/null
+++ b/packages/convex/convex/intentCatalogChanges.ts
@@ -0,0 +1,40 @@
+import { internal } from "./_generated/api"
+import { internalMutation, type MutationCtx } from "./_generated/server"
+
+export type LibraryCatalogKind = "song" | "album" | "artist"
+
+/** Clients that last synced before this must rebuild their catalog from scratch. */
+export const INTENT_CATALOG_CHANGE_RETENTION_MS = 30 * 24 * 60 * 60_000
+const PRUNE_BATCH = 500
+
+export async function recordIntentCatalogChanges(
+ ctx: MutationCtx,
+ kind: LibraryCatalogKind,
+ entityIds: string[],
+ removed: boolean
+) {
+ for (const entityId of entityIds) {
+ await ctx.db.insert("intentCatalogChanges", { kind, entityId, removed })
+ }
+}
+
+export const pruneIntentCatalogChanges = internalMutation({
+ args: {},
+ handler: async (ctx) => {
+ const cutoff = Date.now() - INTENT_CATALOG_CHANGE_RETENTION_MS
+ const stale = await ctx.db
+ .query("intentCatalogChanges")
+ .withIndex("by_creation_time", (q) => q.lt("_creationTime", cutoff))
+ .take(PRUNE_BATCH)
+ for (const change of stale) {
+ await ctx.db.delete("intentCatalogChanges", change._id)
+ }
+ if (stale.length === PRUNE_BATCH) {
+ await ctx.scheduler.runAfter(
+ 0,
+ internal.intentCatalogChanges.pruneIntentCatalogChanges,
+ {}
+ )
+ }
+ },
+})
diff --git a/packages/convex/convex/library-scan.test.cjs b/packages/convex/convex/library-scan.test.cjs
new file mode 100644
index 0000000..3815ce8
--- /dev/null
+++ b/packages/convex/convex/library-scan.test.cjs
@@ -0,0 +1,138 @@
+const { test } = require("node:test")
+const assert = require("node:assert/strict")
+const fs = require("node:fs/promises")
+const path = require("node:path")
+const os = require("node:os")
+const vm = require("node:vm")
+const ts = require("typescript")
+
+// Exercise the action against real directory listings without a backend or
+// audio decoder. Metadata is fixed so renames and same-title copies match.
+async function scanner(root) {
+ const module = { exports: {} }
+ const source = ts.transpileModule(
+ await fs.readFile(`${__dirname}/actions.ts`, "utf8"),
+ {
+ compilerOptions: {
+ module: ts.ModuleKind.CommonJS,
+ target: ts.ScriptTarget.ES2022,
+ },
+ }
+ ).outputText
+ const library = new Proxy({}, { get: (_, name) => name })
+ vm.runInNewContext(source, {
+ module,
+ exports: module.exports,
+ process: { env: { DATA: root } },
+ crypto: require("node:crypto"),
+ console: { log() {} },
+ require(name) {
+ if (name.startsWith("node:")) return require(name)
+ if (name === "convex/values") return require(name)
+ if (name === "./_generated/api") return { api: {}, internal: { library } }
+ if (name === "./_generated/server")
+ return { action: (x) => x, internalAction: (x) => x }
+ if (name === "music-metadata")
+ return {
+ parseFile: async () => ({
+ common: { title: "Song", disk: {}, track: {} },
+ format: { duration: 60 },
+ }),
+ }
+ throw new Error(`Unexpected import ${name}`)
+ },
+ })
+ return module.exports.scheduledUpdateLibrary.handler
+}
+
+test("rescans keep tracked songs and covers stable, and a rename keeps the song ID", async (t) => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "otunes-scan-"))
+ t.after(() => fs.rm(root, { recursive: true, force: true }))
+ const folder = (codec) => path.join(root, codec, "The Abnormals", "Album")
+ for (const codec of ["normal", "lossless"]) {
+ await fs.mkdir(folder(codec), { recursive: true })
+ await fs.writeFile(path.join(folder(codec), "song.mp3"), "audio")
+ await fs.writeFile(path.join(folder(codec), "cover.jpg"), "cover")
+ await fs.writeFile(path.join(folder(codec), "..", "folder.jpg"), "cover")
+ }
+ const artists = [
+ {
+ _id: "artist",
+ name: "The Abnormals",
+ folder: "The Abnormals",
+ cover: path.join(root, "lossless", "The Abnormals", "folder.jpg"),
+ },
+ ]
+ const albums = [
+ {
+ _id: "album",
+ artist: "artist",
+ folder: "Album",
+ cover: path.join(folder("lossless"), "cover.jpg"),
+ },
+ ]
+ const songs = [
+ {
+ _id: "song",
+ name: "Song",
+ album: "album",
+ files: Object.fromEntries(
+ ["normal", "lossless"].map((c) => [c, path.join(folder(c), "song.mp3")])
+ ),
+ },
+ ]
+ const writes = []
+ let locked = false
+ const ctx = {
+ async runQuery(name) {
+ const page = {
+ scanArtistsPage: artists,
+ scanAlbumsPage: albums,
+ scanSongsPage: songs,
+ }[name]
+ assert.ok(page, name)
+ return { page, isDone: true, continueCursor: "" }
+ },
+ async runMutation(name, args) {
+ if (name === "acquireLibraryScanLock") return !locked
+ if (name === "releaseLibraryScanLock") return
+ writes.push({ name, args })
+ if (name === "changeFilesForSongs") {
+ for (const update of args.songs)
+ songs.find((s) => s._id === update.id).files = update.files
+ return
+ }
+ throw new Error(`Unexpected write ${name}`)
+ },
+ }
+ const scan = await scanner(root)
+ await scan(ctx)
+ assert.equal(writes.length, 0)
+ await fs.writeFile(path.join(folder("normal"), "copy.mp3"), "audio")
+ await scan(ctx)
+ await scan(ctx)
+ assert.equal(writes.length, 0)
+ await fs.rm(path.join(folder("normal"), "copy.mp3"))
+ await fs.rename(
+ path.join(folder("normal"), "song.mp3"),
+ path.join(folder("normal"), "renamed.mp3")
+ )
+ await scan(ctx)
+ assert.equal(writes.length, 1)
+ assert.equal(writes[0].args.songs[0].id, "song")
+ assert.equal(
+ songs[0].files.normal,
+ path.join(folder("normal"), "renamed.mp3")
+ )
+ await scan(ctx)
+ assert.equal(writes.length, 1)
+ locked = true
+ assert.equal(await scan(ctx), null)
+ assert.equal(writes.length, 1)
+ locked = false
+ for (const codec of ["normal", "lossless"]) {
+ await fs.rm(folder(codec), { recursive: true })
+ }
+ await assert.rejects(scan(ctx), /refusing to empty the library/)
+ assert.equal(writes.length, 1)
+})
diff --git a/packages/convex/convex/library.ts b/packages/convex/convex/library.ts
index 80df22b..6968ca7 100644
--- a/packages/convex/convex/library.ts
+++ b/packages/convex/convex/library.ts
@@ -3,12 +3,11 @@ import { getAuthUserId } from "@convex-dev/auth/server"
import { internalMutation, internalQuery, query } from "./_generated/server"
import { ConvexError, v } from "convex/values"
import type { Doc, Id } from "./_generated/dataModel"
-import type { QueryCtx } from "./_generated/server"
+import type { MutationCtx, QueryCtx } from "./_generated/server"
import type { PaginationOptions, PaginationResult } from "convex/server"
import type {
BrowseAlbum,
BrowseAlbumDetail,
- BrowseAlbumSummary,
BrowseAlbumTrack,
BrowseArtist,
BrowseArtistDetail,
@@ -22,11 +21,11 @@ import type {
SearchTopResultItem,
SidebarPlaylists,
} from "./types"
+import { recordIntentCatalogChanges } from "./intentCatalogChanges"
export type {
BrowseAlbum,
BrowseAlbumDetail,
- BrowseAlbumSummary,
BrowseAlbumTrack,
BrowseArtist,
BrowseArtistDetail,
@@ -41,7 +40,21 @@ export type {
SidebarPlaylists,
} from "./types"
-function getSongArtistNames(artist: string | string[]): string[] {
+const EMPTY_PAGE = { page: [], isDone: true, continueCursor: "" }
+
+/** Reactive queries return empty data when signed out so sign-out doesn't throw mid-render. */
+export async function isSignedIn(ctx: QueryCtx) {
+ return (await getAuthUserId(ctx)) !== null
+}
+
+/** Imperative lookups throw instead, so callers that cache results don't cache an empty one. */
+export async function requireSignedIn(ctx: QueryCtx) {
+ if (!(await isSignedIn(ctx))) {
+ throw new ConvexError("Not authenticated")
+ }
+}
+
+export function getSongArtistNames(artist: string | string[]): string[] {
if (Array.isArray(artist)) {
return artist.map((name) => name.trim()).filter((name) => name.length > 0)
}
@@ -49,7 +62,7 @@ function getSongArtistNames(artist: string | string[]): string[] {
return trimmed.length > 0 ? [trimmed] : []
}
-function songArtistsMatchAlbum(
+export function songArtistsMatchAlbum(
songArtists: string[],
albumArtistName: string
): boolean {
@@ -202,6 +215,9 @@ function toBrowseSong(
export const browseAlbums = query({
args: {},
handler: async (ctx) => {
+ if (!(await isSignedIn(ctx))) {
+ return []
+ }
const artistMap = await loadArtistMap(ctx)
const albums = await ctx.db.query("albums").collect()
@@ -217,6 +233,9 @@ export const browseAlbums = query({
export const browseArtists = query({
args: {},
handler: async (ctx) => {
+ if (!(await isSignedIn(ctx))) {
+ return []
+ }
const artists = await ctx.db.query("artists").collect()
return artists
.map(toBrowseArtist)
@@ -224,7 +243,7 @@ export const browseArtists = query({
},
})
-export function paginateSlice(
+function paginateSlice(
items: T[],
paginationOpts: PaginationOptions
): PaginationResult {
@@ -244,6 +263,9 @@ export function paginateSlice(
export const browseArtistsPaginated = query({
args: { paginationOpts: paginationOptsValidator },
handler: async (ctx, args) => {
+ if (!(await isSignedIn(ctx))) {
+ return EMPTY_PAGE
+ }
const result = await ctx.db
.query("artists")
.withIndex("by_name")
@@ -260,6 +282,9 @@ export const browseArtistsPaginated = query({
export const browseAlbumsPaginated = query({
args: { paginationOpts: paginationOptsValidator },
handler: async (ctx, args) => {
+ if (!(await isSignedIn(ctx))) {
+ return EMPTY_PAGE
+ }
const result = await ctx.db
.query("albums")
.withIndex("by_name")
@@ -280,27 +305,6 @@ export const browseAlbumsPaginated = query({
},
})
-export const browseSongs = query({
- args: {},
- handler: async (ctx) => {
- const artistMap = await loadArtistMap(ctx)
- const albums = await ctx.db.query("albums").collect()
- const albumMap = new Map(albums.map((album) => [album._id, album]))
- const songs = await ctx.db.query("songs").collect()
-
- return songs
- .flatMap((song) => {
- const album = albumMap.get(song.album)
- const albumArtist = artistMap.get(song.albumArtist)
- if (!album || !albumArtist) {
- return []
- }
- return [toBrowseSong(song, album, albumArtist)]
- })
- .sort((a, b) => a.title.localeCompare(b.title))
- },
-})
-
export const songsSortKeyValidator = v.union(
v.literal("title"),
v.literal("artist"),
@@ -481,6 +485,9 @@ export const browseSongsPaginated = query({
sortDirection: songsSortDirectionValidator,
},
handler: async (ctx, args) => {
+ if (!(await isSignedIn(ctx))) {
+ return EMPTY_PAGE
+ }
if (args.sortKey === "title") {
return paginateSongsByTitle(ctx, args.paginationOpts, args.sortDirection)
}
@@ -500,6 +507,7 @@ export const browseSortedSongIds = query({
sortDirection: songsSortDirectionValidator,
},
handler: async (ctx, args) => {
+ await requireSignedIn(ctx)
return getSortedLibrarySongIds(ctx, args.sortKey, args.sortDirection)
},
})
@@ -509,6 +517,7 @@ const MAX_SONGS_BY_IDS = 200
export const browseSongsByIds = query({
args: { ids: v.array(v.id("songs")) },
handler: async (ctx, args): Promise => {
+ await requireSignedIn(ctx)
if (args.ids.length > MAX_SONGS_BY_IDS) {
throw new ConvexError(`Request at most ${MAX_SONGS_BY_IDS} songs`)
}
@@ -516,6 +525,7 @@ export const browseSongsByIds = query({
},
})
+/** Public: shared /album links render this without a session. */
export const browseAlbumDetail = query({
args: { id: v.id("albums") },
handler: async (ctx, args): Promise => {
@@ -535,7 +545,7 @@ export const browseAlbumDetail = query({
return {
...toBrowseAlbum(album, artist),
- year: primarySong?.year ?? null,
+ year: primarySong?.year || null,
genre: primarySong?.genres[0] ?? null,
releaseDate: album.date,
hasLossless: songs.some((song) => "lossless" in song.files),
@@ -545,72 +555,7 @@ export const browseAlbumDetail = query({
},
})
-async function browseAlbumSummaryHandler(
- ctx: QueryCtx,
- albumId: Id<"albums">
-): Promise {
- const album = await ctx.db.get("albums", albumId)
- if (!album) {
- return null
- }
-
- const artist = await ctx.db.get("artists", album.artist)
- if (!artist) {
- return null
- }
-
- const songs = await ctx.db
- .query("songs")
- .withIndex("by_album", (q) => q.eq("album", albumId))
- .collect()
-
- songs.sort(compareAlbumSongs)
- const primarySong = songs[0]
-
- return {
- ...toBrowseAlbum(album, artist),
- year: primarySong?.year ?? null,
- genre: primarySong?.genres[0] ?? null,
- releaseDate: album.date,
- hasLossless: songs.some((song) => "lossless" in song.files),
- hasAtmos: songs.some((song) => "atmos" in song.files),
- trackCount: songs.length,
- }
-}
-
-export const browseAlbumSummary = query({
- args: { id: v.id("albums") },
- handler: async (ctx, args) => browseAlbumSummaryHandler(ctx, args.id),
-})
-
-export const browseAlbumTracksPaginated = query({
- args: {
- albumId: v.id("albums"),
- paginationOpts: paginationOptsValidator,
- },
- handler: async (ctx, args) => {
- const album = await ctx.db.get("albums", args.albumId)
- if (!album) {
- return { page: [], isDone: true, continueCursor: "" }
- }
-
- const artist = await ctx.db.get("artists", album.artist)
- if (!artist) {
- return { page: [], isDone: true, continueCursor: "" }
- }
-
- const songs = await ctx.db
- .query("songs")
- .withIndex("by_album", (q) => q.eq("album", args.albumId))
- .collect()
-
- songs.sort(compareAlbumSongs)
-
- const tracks = songs.map((song) => toBrowseAlbumTrack(song, artist.name))
- return paginateSlice(tracks, args.paginationOpts)
- },
-})
-
+/** Public: shared /artist links render this without a session. */
export const browseArtistDetail = query({
args: { id: v.id("artists") },
handler: async (ctx, args) => {
@@ -664,7 +609,7 @@ export const searchLibrary = query({
args: { query: v.string() },
handler: async (ctx, args) => {
const queryText = args.query.trim().toLowerCase()
- if (!queryText) {
+ if (!queryText || !(await isSignedIn(ctx))) {
return {
topResults: [],
artists: [],
@@ -766,6 +711,9 @@ export const searchLibrary = query({
export const browseRecentlyAdded = query({
args: { limit: v.optional(v.number()) },
handler: async (ctx, args) => {
+ if (!(await isSignedIn(ctx))) {
+ return []
+ }
const albumQuery = ctx.db.query("albums").order("desc")
const albums = args.limit
? await albumQuery.take(args.limit)
@@ -785,6 +733,9 @@ export const browseRecentlyAdded = query({
export const browseRecentlyAddedPaginated = query({
args: { paginationOpts: paginationOptsValidator },
handler: async (ctx, args) => {
+ if (!(await isSignedIn(ctx))) {
+ return EMPTY_PAGE
+ }
const result = await ctx.db
.query("albums")
.order("desc")
@@ -894,114 +845,102 @@ export const browseRecentlyPlayedPaginated = query({
},
})
-export const getArtists = internalQuery({
- args: {},
- handler: async (ctx) => {
- return await ctx.db.query("artists").collect()
- },
-})
-
-export const getAlbums = internalQuery({
- args: {},
- handler: async (ctx) => {
- return await ctx.db.query("albums").collect()
- },
-})
-
-export const getAlbumsInArtist = internalQuery({
- args: { artistID: v.id("artists") },
+export const scanArtistsPage = internalQuery({
+ args: { paginationOpts: paginationOptsValidator },
handler: async (ctx, args) => {
- return await ctx.db
- .query("albums")
- .withIndex("by_artist", (q) => q.eq("artist", args.artistID))
- .collect()
+ const result = await ctx.db.query("artists").paginate(args.paginationOpts)
+ return {
+ ...result,
+ page: result.page.map(({ _id, name, folder, cover }) => ({
+ _id,
+ name,
+ folder,
+ cover,
+ })),
+ }
},
})
-export const getSongs = internalQuery({
- args: {},
- handler: async (ctx) => {
- return await ctx.db.query("songs").collect()
- },
-})
-
-export const getSongsInArtist = internalQuery({
- args: { artistID: v.id("artists") },
+export const scanAlbumsPage = internalQuery({
+ args: { paginationOpts: paginationOptsValidator },
handler: async (ctx, args) => {
- return await ctx.db
- .query("songs")
- .withIndex("by_artist", (q) => q.eq("albumArtist", args.artistID))
- .collect()
+ const result = await ctx.db.query("albums").paginate(args.paginationOpts)
+ return {
+ ...result,
+ page: result.page.map(({ _id, folder, cover, artist }) => ({
+ _id,
+ folder,
+ cover,
+ artist,
+ })),
+ }
},
})
-export const getSongsInAlbum = internalQuery({
- args: { albumID: v.id("albums") },
+export const scanSongsPage = internalQuery({
+ args: { paginationOpts: paginationOptsValidator },
handler: async (ctx, args) => {
- return await ctx.db
- .query("songs")
- .withIndex("by_album", (q) => q.eq("album", args.albumID))
- .collect()
+ const result = await ctx.db.query("songs").paginate(args.paginationOpts)
+ return {
+ ...result,
+ page: result.page.map(({ _id, name, files, album }) => ({
+ _id,
+ name,
+ files,
+ album,
+ })),
+ }
},
})
-export const getArtist = query({
+
+/** Public: share-link previews load covers without a session. */
+export const getArtistCover = query({
args: { id: v.id("artists") },
handler: async (ctx, args) => {
- return await ctx.db.get("artists", args.id)
+ return (await ctx.db.get("artists", args.id))?.cover ?? null
},
})
-export const getArtistByName = internalQuery({
- args: { name: v.string() },
- handler: async (ctx, args) => {
- return await ctx.db
- .query("artists")
- .withIndex("by_name", (q) => q.eq("name", args.name))
- .first()
- },
-})
-
-export const getAlbum = query({
+/** Public: share-link previews load covers without a session. */
+export const getAlbumCover = query({
args: { id: v.id("albums") },
handler: async (ctx, args) => {
- return await ctx.db.get("albums", args.id)
+ return (await ctx.db.get("albums", args.id))?.cover ?? null
},
})
-export const getAlbumByName = internalQuery({
- args: { name: v.string() },
- handler: async (ctx, args) => {
- return await ctx.db
- .query("albums")
- .withIndex("by_name", (q) => q.eq("name", args.name))
- .first()
- },
-})
-
-export const getAlbumByAll = internalQuery({
- args: { folder: v.string(), artist: v.id("artists") },
- handler: async (ctx, args) => {
- return await ctx.db
- .query("albums")
- .withIndex("by_all", (q) =>
- q.eq("artist", args.artist).eq("folder", args.folder)
- )
- .first()
- },
-})
-
-export const getPlaylist = query({
+/** Public: share-link previews load covers without a session. */
+export const getPlaylistCover = query({
args: { id: v.id("playlists") },
handler: async (ctx, args) => {
- return await ctx.db.get("playlists", args.id)
+ return (await ctx.db.get("playlists", args.id))?.cover ?? null
},
})
+/** Public: share-link previews read song metadata without a session. Never returns file paths. */
export const getSong = query({
args: { id: v.id("songs") },
handler: async (ctx, args) => {
- return await ctx.db.get("songs", args.id)
+ const song = await ctx.db.get("songs", args.id)
+ if (!song) {
+ return null
+ }
+ const { files: _files, ...clientSong } = song
+ return clientSong
+ },
+})
+
+/** Returns absolute file paths. Only the web streaming routes call this, as the listener. */
+export const getSongSource = query({
+ args: { id: v.id("songs") },
+ handler: async (ctx, args) => {
+ await requireSignedIn(ctx)
+ const song = await ctx.db.get("songs", args.id)
+ if (!song) {
+ return null
+ }
+ return { _id: song._id, files: song.files, length: song.length }
},
})
@@ -1051,485 +990,260 @@ export const getSongsForPlayback = query({
},
})
-const FAVORITES_PLAYLIST_ID = "otunes:favorites"
-
-/** Bounded pages for the device's disk-backed Siri catalog. */
-export const intentCatalogPage = query({
- args: {
- kind: v.union(
- v.literal("song"),
- v.literal("album"),
- v.literal("artist"),
- v.literal("playlist")
- ),
- paginationOpts: paginationOptsValidator,
- },
- handler: async (ctx, { kind, paginationOpts }) => {
- const userId = await getAuthUserId(ctx)
- if (!userId) throw new ConvexError("Not authenticated")
- const user = await ctx.db.get("users", userId)
- if (!user) throw new ConvexError("Not authenticated")
- type Entity = {
- id: string
- title: string
- subtitle?: string
- synonyms?: string[]
- metadata: Record
- }
- const page: Entity[] = []
- if (kind === "song") {
- const result = await ctx.db.query("songs").paginate(paginationOpts)
- for (const song of result.page) {
- const album = await ctx.db.get("albums", song.album)
- const artist = await ctx.db.get("artists", song.albumArtist)
- if (!album || !artist || !song.name.trim()) continue
- const credits = getSongArtistNames(song.artist)
- const artistName = songArtistsMatchAlbum(credits, artist.name)
- ? artist.name
- : credits.join(", ") || artist.name
- page.push({
- id: song._id,
- title: song.name,
- subtitle: artistName,
- metadata: {
- artistName,
- artistId: artist._id,
- albumTitle: album.name,
- albumId: album._id,
- duration: String(Math.max(0, Math.round(song.length))),
- genres: song.genres.join(", "),
- year: String(song.year),
- track: String(song.track),
- disk: String(song.diskNumber ?? ""),
- favorite: user.favoriteSongs?.includes(song._id) ? "1" : "0",
- },
- })
- }
- return { ...result, page }
- }
- if (kind === "album") {
- const result = await ctx.db.query("albums").paginate(paginationOpts)
- for (const album of result.page) {
- const artist = await ctx.db.get("artists", album.artist)
- if (!artist || !album.name.trim()) continue
- page.push({
- id: album._id,
- title: album.name,
- subtitle: artist.name,
- metadata: {
- artistName: artist.name,
- artistId: artist._id,
- year: String(album.year),
- favorite: user.favoriteAlbums?.includes(album._id) ? "1" : "0",
- },
- })
- }
- return { ...result, page }
- }
- if (kind === "artist") {
- const result = await ctx.db.query("artists").paginate(paginationOpts)
- for (const artist of result.page) {
- if (artist.name.trim())
- page.push({
- id: artist._id,
- title: artist.name,
- metadata: {
- favorite: user.favoriteArtists?.includes(artist._id) ? "1" : "0",
- },
- })
- }
- return { ...result, page }
- }
- const result = await ctx.db.query("playlists").paginate(paginationOpts)
- for (const playlist of result.page) {
- if (
- playlist.owner !== userId &&
- !user.subscribedPlaylists?.includes(playlist._id)
- )
- continue
- if (!playlist.name.trim()) continue
- const owner = await ctx.db.get("users", playlist.owner)
- page.push({
- id: playlist._id,
- title: playlist.name,
- subtitle: owner?.name ?? "",
- metadata: {
- ownerName: owner?.name ?? "",
- createdByMe: playlist.owner === userId ? "1" : "0",
- },
- })
- }
- if (paginationOpts.cursor === null)
- page.unshift({
- id: FAVORITES_PLAYLIST_ID,
- title: "Favorites",
- synonyms: [
- "favorites",
- "favourite songs",
- "liked songs",
- "loved songs",
- ],
- metadata: { ownerName: user.name, createdByMe: "1" },
- })
- return { ...result, page }
- },
-})
-
-export const getSongByName = internalQuery({
- args: { name: v.string() },
- handler: async (ctx, args) => {
- return await ctx.db
- .query("songs")
- .withIndex("by_name", (q) => q.eq("name", args.name))
- .first()
- },
-})
-
-export const getSongByAll = internalQuery({
- args: {
- name: v.string(),
- albumArtist: v.id("artists"),
- album: v.id("albums"),
- },
- handler: async (ctx, args) => {
- return await ctx.db
- .query("songs")
- .withIndex("by_all", (q) =>
- q
- .eq("name", args.name)
- .eq("albumArtist", args.albumArtist)
- .eq("album", args.album)
- )
- .first()
- },
-})
-
-export const createArtist = internalMutation({
- args: { name: v.string(), folder: v.string(), cover: v.nullable(v.string()) },
- handler: async (ctx, args) => {
- const existing = await ctx.db
- .query("artists")
- .withIndex("by_folder", (q) => q.eq("folder", args.folder))
- .first()
- if (existing) {
- return existing._id
- }
- return await ctx.db.insert("artists", args)
- },
-})
-
-export const createArtists = internalMutation({
- args: {
- artists: v.array(
- v.object({
- name: v.string(),
- folder: v.string(),
- cover: v.nullable(v.string()),
- })
- ),
- },
- handler: async (ctx, args) => {
- for (const artist of args.artists) {
- const existing = await ctx.db
- .query("artists")
- .withIndex("by_folder", (q) => q.eq("folder", artist.folder))
- .first()
- if (existing) {
- continue
- }
- await ctx.db.insert("artists", artist)
- }
- },
-})
-
-export const createAlbum = internalMutation({
- args: {
- name: v.string(),
- folder: v.string(),
- cover: v.nullable(v.string()),
- year: v.number(),
- date: v.string(),
- artist: v.id("artists"),
- },
- handler: async (ctx, args) => {
- const existing = await ctx.db
- .query("albums")
- .withIndex("by_all", (q) =>
- q.eq("artist", args.artist).eq("folder", args.folder)
- )
- .first()
- if (existing) {
- return existing._id
- }
- return await ctx.db.insert("albums", args)
- },
-})
-
-export const createAlbums = internalMutation({
+/**
+ * Creates (or reuses, matched by folder) the artist and album for each entry
+ * together with its songs, so an album never exists without songs.
+ */
+export const importAlbums = internalMutation({
args: {
albums: v.array(
v.object({
- name: v.string(),
- folder: v.string(),
- cover: v.nullable(v.string()),
- year: v.number(),
- date: v.string(),
- artist: v.id("artists"),
+ artist: v.object({
+ name: v.string(),
+ folder: v.string(),
+ cover: v.nullable(v.string()),
+ }),
+ album: v.object({
+ name: v.string(),
+ folder: v.string(),
+ cover: v.nullable(v.string()),
+ year: v.number(),
+ date: v.string(),
+ }),
+ songs: v.array(
+ v.object({
+ name: v.string(),
+ files: v.record(v.string(), v.string()),
+ artist: v.union(v.string(), v.array(v.string())),
+ length: v.number(),
+ diskNumber: v.nullable(v.number()),
+ track: v.number(),
+ year: v.number(),
+ date: v.string(),
+ genres: v.array(v.string()),
+ })
+ ),
})
),
},
handler: async (ctx, args) => {
- for (const album of args.albums) {
- const existing = await ctx.db
- .query("albums")
- .withIndex("by_all", (q) =>
- q.eq("artist", album.artist).eq("folder", album.folder)
- )
- .first()
- if (existing) {
+ for (const entry of args.albums) {
+ if (entry.songs.length === 0) {
continue
}
- await ctx.db.insert("albums", album)
- }
- },
-})
-export const updateAlbumName = internalMutation({
- args: {
- id: v.id("albums"),
- newName: v.string(),
- },
- handler: async (ctx, args) => {
- return await ctx.db.patch("albums", args.id, { name: args.newName })
- },
-})
+ const artistId =
+ (
+ await ctx.db
+ .query("artists")
+ .withIndex("by_folder", (q) => q.eq("folder", entry.artist.folder))
+ .first()
+ )?._id ?? (await ctx.db.insert("artists", entry.artist))
-export const createSong = internalMutation({
- args: {
- name: v.string(),
- files: v.record(v.string(), v.string()),
- album: v.id("albums"),
- artist: v.union(v.string(), v.array(v.string())),
- albumArtist: v.id("artists"),
- length: v.number(),
- diskNumber: v.nullable(v.number()),
- track: v.number(),
- year: v.number(),
- date: v.string(),
- genres: v.array(v.string()),
- },
- handler: async (ctx, args) => {
- const existing = await ctx.db
- .query("songs")
- .withIndex("by_all", (q) =>
- q
- .eq("name", args.name)
- .eq("albumArtist", args.albumArtist)
- .eq("album", args.album)
- )
- .first()
- if (existing) {
- await ctx.db.patch(existing._id, {
- files: { ...existing.files, ...args.files },
- })
- return existing._id
- }
- return await ctx.db.insert("songs", args)
- },
-})
+ const albumId =
+ (
+ await ctx.db
+ .query("albums")
+ .withIndex("by_all", (q) =>
+ q.eq("artist", artistId).eq("folder", entry.album.folder)
+ )
+ .first()
+ )?._id ??
+ (await ctx.db.insert("albums", { ...entry.album, artist: artistId }))
-export const createSongs = internalMutation({
- args: {
- songs: v.array(
- v.object({
- name: v.string(),
- files: v.record(v.string(), v.string()),
- album: v.id("albums"),
- artist: v.union(v.string(), v.array(v.string())),
- albumArtist: v.id("artists"),
- length: v.number(),
- diskNumber: v.nullable(v.number()),
- track: v.number(),
- year: v.number(),
- date: v.string(),
- genres: v.array(v.string()),
- })
- ),
- },
- handler: async (ctx, args) => {
- for (const song of args.songs) {
- const existing = await ctx.db
- .query("songs")
- .withIndex("by_all", (q) =>
- q
- .eq("name", song.name)
- .eq("albumArtist", song.albumArtist)
- .eq("album", song.album)
- )
- .first()
- if (existing) {
- await ctx.db.patch(existing._id, {
- files: { ...existing.files, ...song.files },
+ for (const song of entry.songs) {
+ const existing = await ctx.db
+ .query("songs")
+ .withIndex("by_all", (q) =>
+ q
+ .eq("name", song.name)
+ .eq("albumArtist", artistId)
+ .eq("album", albumId)
+ )
+ .first()
+ if (existing) {
+ await ctx.db.patch(existing._id, {
+ files: { ...existing.files, ...song.files },
+ })
+ continue
+ }
+ await ctx.db.insert("songs", {
+ ...song,
+ album: albumId,
+ albumArtist: artistId,
})
- continue
}
- await ctx.db.insert("songs", song)
}
-
- return
},
})
-export const purgeSongsFromUsersAndPlaylists = internalMutation({
+/** Deletes songs and removes them from every playlist, favorite and queue. */
+export const deleteSongs = internalMutation({
args: { ids: v.array(v.id("songs")) },
handler: async (ctx, args) => {
- const remove = new Set(args.ids)
- if (remove.size === 0) {
- return
- }
-
- for (const playlist of await ctx.db.query("playlists").collect()) {
- if (playlist.songs.some((songId) => remove.has(songId))) {
- await ctx.db.patch(playlist._id, {
- songs: playlist.songs.filter((songId) => !remove.has(songId)),
- })
- }
- }
-
- for (const user of await ctx.db.query("users").collect()) {
- const favoriteSongs = user.favoriteSongs
- const songQueue = user.songQueue
- const queueHistory = user.queueHistory
- const patch: Partial<
- Pick<
- Doc<"users">,
- "favoriteSongs" | "songQueue" | "queueHistory" | "currentSongProgress"
- >
- > = {}
-
- if (favoriteSongs?.some((songId) => remove.has(songId))) {
- patch.favoriteSongs = favoriteSongs.filter(
- (songId) => !remove.has(songId)
- )
- }
- if (songQueue?.some((songId) => remove.has(songId))) {
- const currentRemoved = remove.has(songQueue[0])
- patch.songQueue = songQueue.filter((songId) => !remove.has(songId))
- if (currentRemoved) {
- patch.currentSongProgress = 0
- }
- }
- if (queueHistory?.some((songId) => remove.has(songId))) {
- patch.queueHistory = queueHistory.filter(
- (songId) => !remove.has(songId)
- )
- }
- if (Object.keys(patch).length > 0) {
- await ctx.db.patch(user._id, patch)
- }
+ for (const id of args.ids) {
+ await ctx.db.delete("songs", id)
}
+ await purgeSongsFromUsersAndPlaylists(ctx, new Set(args.ids))
+ await recordIntentCatalogChanges(ctx, "song", args.ids, true)
},
})
-export const purgeAlbumsFromUsers = internalMutation({
+/** Deletes the albums that still have no songs when this mutation runs. */
+export const deleteEmptyAlbums = internalMutation({
args: { ids: v.array(v.id("albums")) },
handler: async (ctx, args) => {
- const remove = new Set(args.ids)
- if (remove.size === 0) {
- return
- }
-
- for (const user of await ctx.db.query("users").collect()) {
- const favoriteAlbums = user.favoriteAlbums
- const recentlyPlayed = user.recentlyPlayed
- const patch: Partial<
- Pick, "favoriteAlbums" | "recentlyPlayed">
- > = {}
- if (favoriteAlbums?.some((albumId) => remove.has(albumId))) {
- patch.favoriteAlbums = favoriteAlbums.filter(
- (albumId) => !remove.has(albumId)
- )
- }
- if (
- recentlyPlayed?.some((itemId) => remove.has(itemId as Id<"albums">))
- ) {
- patch.recentlyPlayed = recentlyPlayed.filter(
- (itemId) => !remove.has(itemId as Id<"albums">)
- )
- }
- if (Object.keys(patch).length > 0) {
- await ctx.db.patch(user._id, patch)
+ const deleted = new Set>()
+ for (const id of args.ids) {
+ const song = await ctx.db
+ .query("songs")
+ .withIndex("by_album", (q) => q.eq("album", id))
+ .first()
+ if (song === null && (await ctx.db.get("albums", id)) !== null) {
+ await ctx.db.delete("albums", id)
+ deleted.add(id)
}
}
+ await purgeAlbumsFromUsers(ctx, deleted)
+ await recordIntentCatalogChanges(ctx, "album", [...deleted], true)
+ return deleted.size
},
})
-export const purgeArtistsFromUsers = internalMutation({
+/** Deletes the artists that still have no albums when this mutation runs. */
+export const deleteEmptyArtists = internalMutation({
args: { ids: v.array(v.id("artists")) },
handler: async (ctx, args) => {
- const remove = new Set(args.ids)
- if (remove.size === 0) {
- return
- }
-
- for (const user of await ctx.db.query("users").collect()) {
- const favoriteArtists = user.favoriteArtists
- if (favoriteArtists?.some((artistId) => remove.has(artistId))) {
- await ctx.db.patch(user._id, {
- favoriteArtists: favoriteArtists.filter(
- (artistId) => !remove.has(artistId)
- ),
- })
+ const deleted = new Set>()
+ for (const id of args.ids) {
+ const album = await ctx.db
+ .query("albums")
+ .withIndex("by_artist", (q) => q.eq("artist", id))
+ .first()
+ if (album === null && (await ctx.db.get("artists", id)) !== null) {
+ await ctx.db.delete("artists", id)
+ deleted.add(id)
}
}
+ await purgeArtistsFromUsers(ctx, deleted)
+ await recordIntentCatalogChanges(ctx, "artist", [...deleted], true)
+ return deleted.size
},
})
-export const removeArtist = internalMutation({
- args: { id: v.id("artists") },
- handler: async (ctx, args) => {
- return await ctx.db.delete("artists", args.id)
- },
-})
+async function purgeSongsFromUsersAndPlaylists(
+ ctx: MutationCtx,
+ remove: Set>
+) {
+ if (remove.size === 0) {
+ return
+ }
-export const removeArtists = internalMutation({
- args: { ids: v.array(v.id("artists")) },
- handler: async (ctx, args) => {
- for (const id of args.ids) {
- await ctx.db.delete("artists", id)
+ for (const playlist of await ctx.db.query("playlists").collect()) {
+ if (playlist.songs.some((songId) => remove.has(songId))) {
+ await ctx.db.patch(playlist._id, {
+ songs: playlist.songs.filter((songId) => !remove.has(songId)),
+ })
}
- },
-})
+ }
-export const removeAlbum = internalMutation({
- args: { id: v.id("albums") },
- handler: async (ctx, args) => {
- return await ctx.db.delete("albums", args.id)
- },
-})
-
-export const removeAlbums = internalMutation({
- args: { ids: v.array(v.id("albums")) },
- handler: async (ctx, args) => {
- for (const id of args.ids) {
- await ctx.db.delete("albums", id)
+ for (const state of await ctx.db.query("playbackStates").collect()) {
+ if (
+ state.songQueue.some((songId) => remove.has(songId)) ||
+ state.queueHistory.some((songId) => remove.has(songId))
+ ) {
+ await ctx.db.patch(state._id, {
+ songQueue: state.songQueue.filter((songId) => !remove.has(songId)),
+ queueHistory: state.queueHistory.filter(
+ (songId) => !remove.has(songId)
+ ),
+ revision: state.revision + 1,
+ })
}
- },
-})
+ }
-export const removeSong = internalMutation({
- args: { id: v.id("songs") },
- handler: async (ctx, args) => {
- return await ctx.db.delete("songs", args.id)
- },
-})
+ // Legacy queue fields stay until `migrations.migrateUsers` clears them.
+ for (const user of await ctx.db.query("users").collect()) {
+ const favoriteSongs = user.favoriteSongs
+ const songQueue = user.songQueue
+ const queueHistory = user.queueHistory
+ const patch: Partial<
+ Pick<
+ Doc<"users">,
+ "favoriteSongs" | "songQueue" | "queueHistory" | "currentSongProgress"
+ >
+ > = {}
-export const changeFilesForSong = internalMutation({
- args: { id: v.id("songs"), files: v.record(v.string(), v.string()) },
- handler: async (ctx, args) => {
- return await ctx.db.patch("songs", args.id, { files: args.files })
- },
-})
+ if (favoriteSongs?.some((songId) => remove.has(songId))) {
+ patch.favoriteSongs = favoriteSongs.filter(
+ (songId) => !remove.has(songId)
+ )
+ }
+ if (songQueue?.some((songId) => remove.has(songId))) {
+ const currentRemoved = remove.has(songQueue[0])
+ patch.songQueue = songQueue.filter((songId) => !remove.has(songId))
+ if (currentRemoved) {
+ patch.currentSongProgress = 0
+ }
+ }
+ if (queueHistory?.some((songId) => remove.has(songId))) {
+ patch.queueHistory = queueHistory.filter((songId) => !remove.has(songId))
+ }
+ if (Object.keys(patch).length > 0) {
+ await ctx.db.patch(user._id, patch)
+ }
+ }
+}
+
+async function purgeAlbumsFromUsers(
+ ctx: MutationCtx,
+ remove: Set>
+) {
+ if (remove.size === 0) {
+ return
+ }
+
+ for (const user of await ctx.db.query("users").collect()) {
+ const favoriteAlbums = user.favoriteAlbums
+ const recentlyPlayed = user.recentlyPlayed
+ const patch: Partial<
+ Pick, "favoriteAlbums" | "recentlyPlayed">
+ > = {}
+ if (favoriteAlbums?.some((albumId) => remove.has(albumId))) {
+ patch.favoriteAlbums = favoriteAlbums.filter(
+ (albumId) => !remove.has(albumId)
+ )
+ }
+ if (recentlyPlayed?.some((itemId) => remove.has(itemId as Id<"albums">))) {
+ patch.recentlyPlayed = recentlyPlayed.filter(
+ (itemId) => !remove.has(itemId as Id<"albums">)
+ )
+ }
+ if (Object.keys(patch).length > 0) {
+ await ctx.db.patch(user._id, patch)
+ }
+ }
+}
+
+async function purgeArtistsFromUsers(
+ ctx: MutationCtx,
+ remove: Set>
+) {
+ if (remove.size === 0) {
+ return
+ }
+
+ for (const user of await ctx.db.query("users").collect()) {
+ const favoriteArtists = user.favoriteArtists
+ if (favoriteArtists?.some((artistId) => remove.has(artistId))) {
+ await ctx.db.patch(user._id, {
+ favoriteArtists: favoriteArtists.filter(
+ (artistId) => !remove.has(artistId)
+ ),
+ })
+ }
+ }
+}
export const changeFilesForSongs = internalMutation({
args: {
@@ -1545,25 +1259,64 @@ export const changeFilesForSongs = internalMutation({
},
})
-export const updateArtistCover = internalMutation({
- args: { id: v.id("artists"), cover: v.nullable(v.string()) },
- handler: async (ctx, args) => {
- return await ctx.db.patch("artists", args.id, { cover: args.cover })
+export const updateArtistCovers = internalMutation({
+ args: {
+ artists: v.array(
+ v.object({ id: v.id("artists"), cover: v.nullable(v.string()) })
+ ),
},
-})
-
-export const updateAlbumCover = internalMutation({
- args: { id: v.id("albums"), cover: v.nullable(v.string()) },
handler: async (ctx, args) => {
- return await ctx.db.patch("albums", args.id, { cover: args.cover })
+ for (const { id, cover } of args.artists) {
+ if ((await ctx.db.get("artists", id)) !== null) {
+ await ctx.db.patch("artists", id, { cover })
+ }
+ }
},
})
-export const removeSongs = internalMutation({
- args: { ids: v.array(v.id("songs")) },
+export const updateAlbumCovers = internalMutation({
+ args: {
+ albums: v.array(
+ v.object({ id: v.id("albums"), cover: v.nullable(v.string()) })
+ ),
+ },
+ handler: async (ctx, args) => {
+ for (const { id, cover } of args.albums) {
+ if ((await ctx.db.get("albums", id)) !== null) {
+ await ctx.db.patch("albums", id, { cover })
+ }
+ }
+ },
+})
+
+/**
+ * Takes the single library scan lease if it is free or expired. The lease
+ * outlives the action timeout so a crashed scan cannot hold it forever.
+ */
+export const acquireLibraryScanLock = internalMutation({
+ args: { token: v.string(), leaseMs: v.number() },
+ handler: async (ctx, args) => {
+ const now = Date.now()
+ const lock = await ctx.db.query("libraryScanLock").first()
+ if (lock && lock.token !== args.token && lock.expiresAt > now) {
+ return false
+ }
+ const expiresAt = now + args.leaseMs
+ if (lock) {
+ await ctx.db.patch(lock._id, { token: args.token, expiresAt })
+ } else {
+ await ctx.db.insert("libraryScanLock", { token: args.token, expiresAt })
+ }
+ return true
+ },
+})
+
+export const releaseLibraryScanLock = internalMutation({
+ args: { token: v.string() },
handler: async (ctx, args) => {
- for (const id of args.ids) {
- await ctx.db.delete("songs", id)
+ const lock = await ctx.db.query("libraryScanLock").first()
+ if (lock?.token === args.token) {
+ await ctx.db.delete(lock._id)
}
},
})
diff --git a/packages/convex/convex/limits.ts b/packages/convex/convex/limits.ts
new file mode 100644
index 0000000..8adb174
--- /dev/null
+++ b/packages/convex/convex/limits.ts
@@ -0,0 +1,10 @@
+/**
+ * Limits shared by Convex functions and clients. Convex rejects arrays longer
+ * than 8,192 values in documents, arguments, and return values.
+ */
+
+/** Songs kept in the playback queue, including the current song. */
+export const MAX_QUEUE_LENGTH = 5_000
+
+/** Largest profile photo accepted, in bytes after base64 decoding. */
+export const MAX_PROFILE_IMAGE_BYTES = 2 * 1024 * 1024
diff --git a/packages/convex/convex/migrations.ts b/packages/convex/convex/migrations.ts
new file mode 100644
index 0000000..f8ce5bb
--- /dev/null
+++ b/packages/convex/convex/migrations.ts
@@ -0,0 +1,39 @@
+import { v } from "convex/values"
+import { internal } from "./_generated/api"
+import { internalMutation } from "./_generated/server"
+import { hasLegacyPlayback, migrateUserPlayback } from "./playbackState"
+
+const BATCH_SIZE = 25
+
+/**
+ * Moves playback state off `users` into `playbackStates`/`playbackProgress`
+ * and legacy data URL avatars into file storage. Idempotent; the Docker
+ * entrypoint runs it on every boot. Run manually with
+ * `npx convex run migrations:migrateUsers`.
+ */
+export const migrateUsers = internalMutation({
+ args: { cursor: v.optional(v.union(v.string(), v.null())) },
+ handler: async (ctx, { cursor }) => {
+ const page = await ctx.db
+ .query("users")
+ .paginate({ cursor: cursor ?? null, numItems: BATCH_SIZE })
+
+ for (const user of page.page) {
+ if (hasLegacyPlayback(user)) {
+ await migrateUserPlayback(ctx, user)
+ }
+ if (!user.imageStorageId && user.image?.startsWith("data:")) {
+ await ctx.scheduler.runAfter(0, internal.users.storeProfileImage, {
+ userId: user._id,
+ image: user.image,
+ })
+ }
+ }
+
+ if (!page.isDone) {
+ await ctx.scheduler.runAfter(0, internal.migrations.migrateUsers, {
+ cursor: page.continueCursor,
+ })
+ }
+ },
+})
diff --git a/packages/convex/convex/playback.ts b/packages/convex/convex/playback.ts
index 6dbfe23..8bf67ed 100644
--- a/packages/convex/convex/playback.ts
+++ b/packages/convex/convex/playback.ts
@@ -1,21 +1,19 @@
import { getAuthUserId } from "@convex-dev/auth/server"
-import { paginationOptsValidator } from "convex/server"
import { ConvexError, v } from "convex/values"
-import type { Doc, Id } from "./_generated/dataModel"
+import type { Id } from "./_generated/dataModel"
import type { MutationCtx } from "./_generated/server"
import { mutation, query } from "./_generated/server"
-import type { QueueSong } from "./types"
+import { browseSongsFromIds } from "./library"
import {
- browseSongsFromIds,
- compareAlbumSongs,
- getSortedLibrarySongIds,
- songsSortDirectionValidator,
- songsSortKeyValidator,
-} from "./library"
+ loadPlaybackForWrite,
+ readPlaybackProgress,
+ readPlaybackState,
+ writePlayback,
+ writeProgress,
+} from "./playbackState"
export type { HistorySong, QueueSong } from "./types"
-const MAX_QUEUE_HISTORY = 30
const MAX_RECENTLY_PLAYED = 30
type RecentlyPlayedItem = Id<"albums"> | Id<"playlists">
@@ -59,35 +57,6 @@ async function recordRecentlyPlayedFromSong(
await recordRecentlyPlayed(ctx, userId, song.album)
}
-async function recordPlaybackStart(
- ctx: MutationCtx,
- userId: Id<"users">,
- options: {
- songIds: Id<"songs">[]
- playlistId?: Id<"playlists">
- }
-) {
- if (options.songIds.length === 0) {
- return
- }
-
- if (options.playlistId) {
- await recordRecentlyPlayed(ctx, userId, options.playlistId)
- return
- }
-
- 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,98 +65,15 @@ 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
- }
- const counts = new Map, number>()
- for (const songId of first) {
- counts.set(songId, (counts.get(songId) ?? 0) + 1)
- }
- for (const songId of second) {
- const count = counts.get(songId)
- if (!count) {
- return false
- }
- if (count === 1) {
- counts.delete(songId)
- } else {
- counts.set(songId, count - 1)
- }
- }
- 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">,
- patch: Partial<
- Pick<
- Doc<"users">,
- | "songQueue"
- | "queueHistory"
- | "currentSongProgress"
- | "shuffleEnabled"
- | "repeatEnabled"
- >
- >
-) {
- const user = await ctx.db.get(userId)
- if (!user) {
+async function requirePlayback(ctx: MutationCtx, userId: Id<"users">) {
+ const playback = await loadPlaybackForWrite(ctx, userId)
+ if (!playback) {
throw new ConvexError("User not found")
}
-
- const playbackRevision = (user.playbackRevision ?? 0) + 1
- await ctx.db.patch(userId, { ...patch, playbackRevision })
- return playbackRevision
-}
-
-async function setQueueState(
- ctx: MutationCtx,
- userId: Id<"users">,
- patch: {
- songQueue: Id<"songs">[]
- shuffleEnabled?: boolean
- currentSongProgress?: number
- resetHistory?: boolean
- }
-) {
- await patchPlayback(ctx, userId, {
- songQueue: patch.songQueue,
- currentSongProgress: patch.currentSongProgress ?? 0,
- ...(patch.resetHistory ? { queueHistory: [] } : {}),
- ...(patch.shuffleEnabled !== undefined
- ? { shuffleEnabled: patch.shuffleEnabled }
- : {}),
- })
+ return playback
}
+/** Queue state without progress; progress comes from `getSongProgress`. */
export const getPlaybackState = query({
args: {},
handler: async (ctx) => {
@@ -196,12 +82,8 @@ export const getPlaybackState = query({
return null
}
- const user = await ctx.db.get(userId)
- if (!user) {
- return null
- }
-
- const songIds = user.songQueue ?? []
+ const playback = await readPlaybackState(ctx, userId)
+ const songIds = playback.songQueue
const currentSong =
songIds.length > 0
? ((await browseSongsFromIds(ctx, [songIds[0]]))[0] ?? null)
@@ -209,12 +91,16 @@ export const getPlaybackState = query({
return {
queueSongIds: songIds,
- queueHistorySongIds: user.queueHistory ?? [],
+ queueHistorySongIds: playback.queueHistory,
currentSong,
- shuffleEnabled: user.shuffleEnabled ?? false,
- repeatEnabled: user.repeatEnabled ?? ("none" as const),
- currentSongProgress: user.currentSongProgress ?? 0,
- revision: user.playbackRevision ?? 0,
+ shuffleEnabled: playback.shuffleEnabled,
+ repeatEnabled: playback.repeatEnabled,
+ /**
+ * @deprecated Always 0. Reading progress here would rerun this query on
+ * every progress save. Kept for app builds that predate `getSongProgress`.
+ */
+ currentSongProgress: 0,
+ revision: playback.revision,
}
},
})
@@ -239,12 +125,12 @@ export const syncPlaybackState = mutation({
},
handler: async (ctx, args) => {
const userId = await requireAuth(ctx)
- return await patchPlayback(ctx, userId, {
+ return await writePlayback(ctx, userId, {
songQueue: args.songQueue,
- queueHistory: args.queueHistory.slice(-MAX_QUEUE_HISTORY),
+ queueHistory: args.queueHistory,
shuffleEnabled: args.shuffleEnabled,
repeatEnabled: args.repeatEnabled,
- currentSongProgress: Math.max(0, Math.floor(args.currentSongProgress)),
+ progressSeconds: args.currentSongProgress,
})
},
})
@@ -264,537 +150,10 @@ export const recordPlay = mutation({
},
})
-export const getQueueHistory = query({
- args: {},
- handler: async (ctx) => {
- const userId = await getAuthUserId(ctx)
- if (userId === null) {
- return []
- }
-
- const user = await ctx.db.get(userId)
- if (!user) {
- return []
- }
-
- const songIds = user.queueHistory ?? []
- const songs = await browseSongsFromIds(ctx, songIds)
-
- return songs.map((song, index) => ({
- ...song,
- historyIndex: index,
- }))
- },
-})
-
-export const getQueuePaginated = query({
- args: {
- paginationOpts: paginationOptsValidator,
- queueVersion: v.string(),
- },
- handler: async (ctx, args) => {
- const userId = await getAuthUserId(ctx)
- if (userId === null) {
- return { page: [], isDone: true, continueCursor: "" }
- }
-
- const user = await ctx.db.get(userId)
- if (!user) {
- return { page: [], isDone: true, continueCursor: "" }
- }
-
- const songIds = user.songQueue ?? []
- const startIndex = args.paginationOpts.cursor
- ? Number.parseInt(args.paginationOpts.cursor, 10)
- : 0
- const endIndex = Math.min(
- startIndex + args.paginationOpts.numItems,
- songIds.length
- )
- const pageIds = songIds.slice(startIndex, endIndex)
- const songs = await browseSongsFromIds(ctx, pageIds)
-
- const page: QueueSong[] = songs.map((song, index) => ({
- ...song,
- queueIndex: startIndex + index,
- }))
-
- const isDone = endIndex >= songIds.length
-
- return {
- page,
- isDone,
- continueCursor: isDone ? "" : String(endIndex),
- }
- },
-})
-
-export const playInOrder = mutation({
- args: {
- songIds: v.array(v.id("songs")),
- playlistId: v.optional(v.id("playlists")),
- },
- handler: async (ctx, { songIds, playlistId }) => {
- const userId = await requireAuth(ctx)
- const queue = uniqueSongIds(songIds)
- await setQueueState(ctx, userId, {
- songQueue: queue,
- shuffleEnabled: false,
- resetHistory: true,
- })
- await recordPlaybackStart(ctx, userId, { songIds: queue, playlistId })
- },
-})
-
-export const playShuffled = mutation({
- args: {
- songIds: v.array(v.id("songs")),
- playlistId: v.optional(v.id("playlists")),
- },
- 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,
- })
- await recordPlaybackStart(ctx, userId, { songIds: queue, playlistId })
- },
-})
-
-function orderSongsForInsert(
- songIds: Id<"songs">[],
- shuffleEnabled: boolean
-): Id<"songs">[] {
- return shuffleEnabled ? shuffleArray(songIds) : songIds
-}
-
-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],
- })
- },
-})
-
-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],
- })
- },
-})
-
-export const playFromSong = mutation({
- args: {
- songId: v.id("songs"),
- songIds: v.array(v.id("songs")),
- },
- 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)
- },
-})
-
-async function albumSongIds(ctx: MutationCtx, albumId: Id<"albums">) {
- const songs = await ctx.db
- .query("songs")
- .withIndex("by_album", (q) => q.eq("album", albumId))
- .collect()
- songs.sort(compareAlbumSongs)
- return songs.map((song) => song._id)
-}
-
-async function orderedArtistSongIds(
- ctx: MutationCtx,
- artistId: Id<"artists">
-) {
- const songs = await ctx.db
- .query("songs")
- .withIndex("by_artist", (q) => q.eq("albumArtist", artistId))
- .collect()
-
- const albums = await ctx.db
- .query("albums")
- .withIndex("by_artist", (q) => q.eq("artist", artistId))
- .collect()
- const albumMap = new Map(albums.map((album) => [album._id, album]))
-
- songs.sort((a, b) => {
- const albumA = albumMap.get(a.album)?.name ?? ""
- const albumB = albumMap.get(b.album)?.name ?? ""
- if (albumA !== albumB) {
- return albumA.localeCompare(albumB)
- }
- if (a.track !== b.track) {
- return a.track - b.track
- }
- return a.name.localeCompare(b.name)
- })
-
- return songs.map((song) => song._id)
-}
-
-async function playCollection(
- ctx: MutationCtx,
- options: {
- songIds: Id<"songs">[]
- shuffled: boolean
- playlistId?: Id<"playlists">
- }
-) {
- const userId = await requireAuth(ctx)
- const unique = uniqueSongIds(options.songIds)
- if (unique.length === 0) {
- return
- }
-
- const queue = options.shuffled ? shuffleArray(unique) : unique
- await setQueueState(ctx, userId, {
- songQueue: queue,
- shuffleEnabled: options.shuffled,
- resetHistory: true,
- })
- await recordPlaybackStart(ctx, userId, {
- songIds: queue,
- playlistId: options.playlistId,
- })
-}
-
-export const playAlbum = mutation({
- args: { albumId: v.id("albums") },
- handler: async (ctx, { albumId }) => {
- await playCollection(ctx, {
- songIds: await albumSongIds(ctx, albumId),
- shuffled: false,
- })
- },
-})
-
-export const playAlbumShuffled = mutation({
- args: { albumId: v.id("albums") },
- handler: async (ctx, { albumId }) => {
- await playCollection(ctx, {
- songIds: await albumSongIds(ctx, albumId),
- shuffled: true,
- })
- },
-})
-
-export const playArtist = mutation({
- args: { artistId: v.id("artists") },
- handler: async (ctx, { artistId }) => {
- await playCollection(ctx, {
- songIds: await orderedArtistSongIds(ctx, artistId),
- shuffled: false,
- })
- },
-})
-
-export const playArtistShuffled = mutation({
- args: { artistId: v.id("artists") },
- handler: async (ctx, { artistId }) => {
- await playCollection(ctx, {
- songIds: await orderedArtistSongIds(ctx, artistId),
- shuffled: true,
- })
- },
-})
-
-export const playPlaylist = mutation({
- args: { playlistId: v.id("playlists") },
- handler: async (ctx, { playlistId }) => {
- const playlist = await ctx.db.get("playlists", playlistId)
- await playCollection(ctx, {
- songIds: playlist?.songs ?? [],
- shuffled: false,
- playlistId,
- })
- },
-})
-
-export const playPlaylistShuffled = mutation({
- args: { playlistId: v.id("playlists") },
- handler: async (ctx, { playlistId }) => {
- const playlist = await ctx.db.get("playlists", playlistId)
- await playCollection(ctx, {
- songIds: playlist?.songs ?? [],
- shuffled: true,
- playlistId,
- })
- },
-})
-
-export const playFromLibrarySong = mutation({
- args: {
- songId: v.id("songs"),
- sortKey: songsSortKeyValidator,
- sortDirection: songsSortDirectionValidator,
- },
- 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)
- },
-})
-
-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 })
- },
-})
-
-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 })
- },
-})
-
-export const clearQueue = mutation({
- args: {},
- handler: async (ctx) => {
- const userId = await requireAuth(ctx)
- await patchPlayback(ctx, userId, {
- songQueue: [],
- queueHistory: [],
- currentSongProgress: 0,
- })
- },
-})
-
-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 } : {}),
- })
- },
-})
-
-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,
- })
- },
-})
-
-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,
- })
- },
-})
-
-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,
- })
- },
-})
-
+/**
+ * Saved position of the current song. Subscribing reruns every few seconds
+ * during playback, so clients fetch it once when adopting a new queue.
+ */
export const getSongProgress = query({
args: {},
handler: async (ctx) => {
@@ -803,12 +162,11 @@ export const getSongProgress = query({
throw new ConvexError("User not logged in")
}
- const user = await ctx.db.get(userId)
- if (!user) {
- throw new ConvexError("User not found")
- }
-
- return user.currentSongProgress ?? 0
+ const [{ songQueue }, progress] = await Promise.all([
+ readPlaybackState(ctx, userId),
+ readPlaybackProgress(ctx, userId),
+ ])
+ return progress.songId === songQueue[0] ? progress.progressSeconds : 0
},
})
@@ -819,15 +177,15 @@ export const updateSongProgress = mutation({
},
handler: async (ctx, args) => {
const userId = await requireAuth(ctx)
- const user = await ctx.db.get(userId)
- if (!user) {
- throw new ConvexError("User not found")
- }
+ const playback = await requirePlayback(ctx, userId)
- if ((user.songQueue ?? [])[0] !== args.songId) {
+ if (playback.songQueue[0] !== args.songId) {
return
}
- await ctx.db.patch(userId, { currentSongProgress: args.progressSeconds })
+ await writeProgress(ctx, userId, {
+ songId: args.songId,
+ progressSeconds: args.progressSeconds,
+ })
},
})
diff --git a/packages/convex/convex/playbackState.ts b/packages/convex/convex/playbackState.ts
new file mode 100644
index 0000000..40c3c95
--- /dev/null
+++ b/packages/convex/convex/playbackState.ts
@@ -0,0 +1,235 @@
+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"
+
+export type RepeatMode = Doc<"playbackStates">["repeatEnabled"]
+
+export type PlaybackState = Pick<
+ Doc<"playbackStates">,
+ "songQueue" | "queueHistory" | "shuffleEnabled" | "repeatEnabled" | "revision"
+>
+
+export type PlaybackProgress = {
+ songId: Id<"songs"> | null
+ progressSeconds: number
+}
+
+export type PlaybackPatch = Partial<
+ Pick<
+ PlaybackState,
+ "songQueue" | "queueHistory" | "shuffleEnabled" | "repeatEnabled"
+ >
+> & {
+ /** Saved position of the new `songQueue[0]`. */
+ progressSeconds?: number
+}
+
+const LEGACY_PLAYBACK_FIELDS = [
+ "songQueue",
+ "queueHistory",
+ "currentSongProgress",
+ "playbackRevision",
+ "shuffleEnabled",
+ "repeatEnabled",
+] as const
+
+const EMPTY_STATE: PlaybackState = {
+ songQueue: [],
+ queueHistory: [],
+ shuffleEnabled: false,
+ repeatEnabled: "none",
+ revision: 0,
+}
+
+function legacyState(user: Doc<"users"> | null): PlaybackState {
+ if (!user) {
+ return EMPTY_STATE
+ }
+ return {
+ songQueue: (user.songQueue ?? []).slice(0, MAX_QUEUE_LENGTH),
+ queueHistory: (user.queueHistory ?? []).slice(-MAX_QUEUE_HISTORY),
+ shuffleEnabled: user.shuffleEnabled ?? false,
+ repeatEnabled: user.repeatEnabled ?? "none",
+ revision: user.playbackRevision ?? 0,
+ }
+}
+
+function legacyProgress(user: Doc<"users"> | null): PlaybackProgress {
+ return {
+ songId: user?.songQueue?.[0] ?? null,
+ progressSeconds: user?.currentSongProgress ?? 0,
+ }
+}
+
+export function hasLegacyPlayback(user: Doc<"users">) {
+ return LEGACY_PLAYBACK_FIELDS.some((field) => user[field] !== undefined)
+}
+
+function stateDoc(ctx: QueryCtx, userId: Id<"users">) {
+ return ctx.db
+ .query("playbackStates")
+ .withIndex("by_user", (q) => q.eq("userId", userId))
+ .unique()
+}
+
+function progressDoc(ctx: QueryCtx, userId: Id<"users">) {
+ return ctx.db
+ .query("playbackProgress")
+ .withIndex("by_user", (q) => q.eq("userId", userId))
+ .unique()
+}
+
+/**
+ * Reads the queue without touching progress, so progress saves do not rerun
+ * the caller. Users that have not been migrated yet fall back to `users`.
+ */
+export async function readPlaybackState(
+ ctx: QueryCtx,
+ userId: Id<"users">
+): Promise {
+ const doc = await stateDoc(ctx, userId)
+ if (doc) {
+ return doc
+ }
+ return legacyState(await ctx.db.get(userId))
+}
+
+export async function readPlaybackProgress(
+ ctx: QueryCtx,
+ userId: Id<"users">
+): Promise {
+ const doc = await progressDoc(ctx, userId)
+ if (doc) {
+ return { songId: doc.songId ?? null, progressSeconds: doc.progressSeconds }
+ }
+ return legacyProgress(await ctx.db.get(userId))
+}
+
+/**
+ * Moves a user's playback fields from `users` into `playbackStates` and
+ * `playbackProgress`. Safe to call repeatedly.
+ */
+export async function migrateUserPlayback(
+ ctx: MutationCtx,
+ user: Doc<"users">
+) {
+ const [existingState, existingProgress] = await Promise.all([
+ stateDoc(ctx, user._id),
+ progressDoc(ctx, user._id),
+ ])
+
+ let state = existingState
+ if (!state) {
+ const stateId = await ctx.db.insert("playbackStates", {
+ userId: user._id,
+ ...legacyState(user),
+ })
+ state = (await ctx.db.get(stateId))!
+ }
+ if (!existingProgress) {
+ const progress = legacyProgress(user)
+ await ctx.db.insert("playbackProgress", {
+ userId: user._id,
+ progressSeconds: progress.progressSeconds,
+ ...(progress.songId ? { songId: progress.songId } : {}),
+ })
+ }
+
+ if (hasLegacyPlayback(user)) {
+ await ctx.db.patch(user._id, {
+ songQueue: undefined,
+ queueHistory: undefined,
+ currentSongProgress: undefined,
+ playbackRevision: undefined,
+ shuffleEnabled: undefined,
+ repeatEnabled: undefined,
+ })
+ }
+
+ return state
+}
+
+/** Loads the queue in a mutation, migrating the user first if needed. */
+export async function loadPlaybackForWrite(
+ ctx: MutationCtx,
+ userId: Id<"users">
+) {
+ const doc = await stateDoc(ctx, userId)
+ if (doc) {
+ return doc
+ }
+ const user = await ctx.db.get(userId)
+ if (!user) {
+ return null
+ }
+ return await migrateUserPlayback(ctx, user)
+}
+
+/** Applies `patch`, bumps the revision, and returns the new revision. */
+export async function writePlayback(
+ ctx: MutationCtx,
+ userId: Id<"users">,
+ patch: PlaybackPatch
+): Promise {
+ const doc = await loadPlaybackForWrite(ctx, userId)
+ if (!doc) {
+ throw new ConvexError("User not found")
+ }
+
+ const { progressSeconds, ...fields } = patch
+ const revision = doc.revision + 1
+ const songQueue = fields.songQueue?.slice(0, MAX_QUEUE_LENGTH)
+ const queueHistory = fields.queueHistory?.slice(-MAX_QUEUE_HISTORY)
+ await ctx.db.patch(doc._id, {
+ ...fields,
+ ...(songQueue ? { songQueue } : {}),
+ ...(queueHistory ? { queueHistory } : {}),
+ revision,
+ })
+
+ if (progressSeconds !== undefined) {
+ await writeProgress(ctx, userId, {
+ songId: (songQueue ?? doc.songQueue)[0] ?? null,
+ progressSeconds,
+ })
+ }
+ return revision
+}
+
+export async function writeProgress(
+ ctx: MutationCtx,
+ userId: Id<"users">,
+ progress: PlaybackProgress
+) {
+ const value = {
+ songId: progress.songId ?? undefined,
+ progressSeconds: Math.max(0, Math.floor(progress.progressSeconds)),
+ }
+ const doc = await progressDoc(ctx, userId)
+ if (!doc) {
+ await ctx.db.insert("playbackProgress", { userId, ...value })
+ } else if (
+ doc.songId !== value.songId ||
+ doc.progressSeconds !== value.progressSeconds
+ ) {
+ await ctx.db.patch(doc._id, value)
+ }
+}
+
+export async function deleteUserPlayback(
+ ctx: MutationCtx,
+ userId: Id<"users">
+) {
+ const [state, progress] = await Promise.all([
+ stateDoc(ctx, userId),
+ progressDoc(ctx, userId),
+ ])
+ if (state) {
+ await ctx.db.delete(state._id)
+ }
+ if (progress) {
+ await ctx.db.delete(progress._id)
+ }
+}
diff --git a/packages/convex/convex/playlists.ts b/packages/convex/convex/playlists.ts
index 6b4bd76..dd34f42 100644
--- a/packages/convex/convex/playlists.ts
+++ b/packages/convex/convex/playlists.ts
@@ -1,4 +1,3 @@
-import { paginationOptsValidator } from "convex/server"
import { getAuthUserId } from "@convex-dev/auth/server"
import { ConvexError, v } from "convex/values"
import type { Doc, Id } from "./_generated/dataModel"
@@ -11,7 +10,11 @@ import type {
PlaylistSummary,
SidebarPlaylists,
} from "./library"
-import { browseSongsFromIds, compareAlbumSongs, paginateSlice } from "./library"
+import {
+ browseSongsFromIds,
+ compareAlbumSongs,
+ requireSignedIn,
+} from "./library"
function toPlaylistSummary(
playlist: Doc<"playlists">,
@@ -109,23 +112,16 @@ async function browsePlaylistSummaryHandler(
}
}
-export const browsePlaylistSummary = query({
- args: { id: v.id("playlists") },
- handler: async (ctx, args) => browsePlaylistSummaryHandler(ctx, args.id),
-})
-
+/** Public: shared /playlist links render this without a session. */
export const browsePlaylistDetail = query({
- args: { id: v.id("playlists"), includeSongs: v.optional(v.boolean()) },
+ args: { id: v.id("playlists") },
handler: async (ctx, args): Promise => {
const summary = await browsePlaylistSummaryHandler(ctx, args.id)
if (!summary) {
return null
}
- const songs =
- (args.includeSongs ?? true)
- ? await browseSongsFromIds(ctx, summary.songIds)
- : []
+ const songs = await browseSongsFromIds(ctx, summary.songIds)
return {
id: summary.id,
@@ -139,27 +135,6 @@ export const browsePlaylistDetail = query({
},
})
-export const browsePlaylistSongsPaginated = query({
- args: {
- id: v.id("playlists"),
- paginationOpts: paginationOptsValidator,
- },
- handler: async (ctx, args) => {
- const playlist = await ctx.db.get("playlists", args.id)
- if (!playlist) {
- return { page: [], isDone: true, continueCursor: "" }
- }
-
- const slice = paginateSlice(playlist.songs, args.paginationOpts)
- const page = await browseSongsFromIds(ctx, slice.page)
-
- return {
- ...slice,
- page,
- }
- },
-})
-
export const listOwnedPlaylists = query({
args: {},
handler: async (ctx) => {
@@ -297,6 +272,7 @@ export const listAllPlaylists = query({
export const getAlbumSongIds = query({
args: { albumId: v.id("albums") },
handler: async (ctx, args) => {
+ await requireSignedIn(ctx)
const songs = await ctx.db
.query("songs")
.withIndex("by_album", (q) => q.eq("album", args.albumId))
@@ -309,6 +285,7 @@ export const getAlbumSongIds = query({
export const getArtistSongIds = query({
args: { artistId: v.id("artists") },
handler: async (ctx, args) => {
+ await requireSignedIn(ctx)
const songs = await ctx.db
.query("songs")
.withIndex("by_artist", (q) => q.eq("albumArtist", args.artistId))
@@ -320,6 +297,7 @@ export const getArtistSongIds = query({
export const getOrderedArtistSongIds = query({
args: { artistId: v.id("artists") },
handler: async (ctx, args) => {
+ await requireSignedIn(ctx)
const songs = await ctx.db
.query("songs")
.withIndex("by_artist", (q) => q.eq("albumArtist", args.artistId))
@@ -350,6 +328,7 @@ export const getOrderedArtistSongIds = query({
export const getPlaylistSongIds = query({
args: { playlistId: v.id("playlists") },
handler: async (ctx, args) => {
+ await requireSignedIn(ctx)
const playlist = await ctx.db.get("playlists", args.playlistId)
return playlist?.songs ?? []
},
diff --git a/packages/convex/convex/schema.ts b/packages/convex/convex/schema.ts
index af46208..d090aba 100644
--- a/packages/convex/convex/schema.ts
+++ b/packages/convex/convex/schema.ts
@@ -2,11 +2,19 @@ import { defineSchema, defineTable } from "convex/server"
import { v } from "convex/values"
import { authTables } from "@convex-dev/auth/server"
+const repeatModeValidator = v.union(
+ v.literal("always"),
+ v.literal("once"),
+ v.literal("none")
+)
+
export default defineSchema({
...authTables,
users: defineTable({
name: v.string(),
+ /** Legacy base64 data URL; `migrations.migrateUsers` moves it to storage. */
image: v.optional(v.string()),
+ imageStorageId: v.optional(v.id("_storage")),
email: v.string(),
isAdmin: v.optional(v.boolean()),
playbackQuality: v.optional(
@@ -22,18 +30,34 @@ export default defineSchema({
favoriteArtists: v.optional(v.array(v.id("artists"))),
favoriteAlbums: v.optional(v.array(v.id("albums"))),
favoriteSongs: v.optional(v.array(v.id("songs"))),
- songQueue: v.optional(v.array(v.id("songs"))),
- queueHistory: v.optional(v.array(v.id("songs"))),
recentlyPlayed: v.optional(
v.array(v.union(v.id("playlists"), v.id("albums")))
),
+ // Legacy playback fields, now in `playbackStates` and `playbackProgress`.
+ // `migrations.migrateUsers` clears them; drop them once every deployment
+ // has run it.
+ songQueue: v.optional(v.array(v.id("songs"))),
+ queueHistory: v.optional(v.array(v.id("songs"))),
currentSongProgress: v.optional(v.number()),
playbackRevision: v.optional(v.number()),
shuffleEnabled: v.optional(v.boolean()),
- repeatEnabled: v.optional(
- v.union(v.literal("always"), v.literal("once"), v.literal("none"))
- ),
+ repeatEnabled: v.optional(repeatModeValidator),
}).index("email", ["email"]),
+ playbackStates: defineTable({
+ userId: v.id("users"),
+ songQueue: v.array(v.id("songs")),
+ queueHistory: v.array(v.id("songs")),
+ shuffleEnabled: v.boolean(),
+ repeatEnabled: repeatModeValidator,
+ revision: v.number(),
+ }).index("by_user", ["userId"]),
+ // Saved every few seconds during playback, so it lives apart from the queue
+ // to keep those writes from rerunning queue queries.
+ playbackProgress: defineTable({
+ userId: v.id("users"),
+ songId: v.optional(v.id("songs")),
+ progressSeconds: v.number(),
+ }).index("by_user", ["userId"]),
authVerifiers: defineTable({
sessionId: v.optional(v.id("authSessions")),
signature: v.optional(v.string()),
@@ -45,9 +69,19 @@ export default defineSchema({
invocationId: v.string(),
playlistId: v.id("playlists"),
}).index("by_user_invocation", ["userId", "invocationId"]),
+ /** Renames and deletions; Siri catalog clients find inserts by `_creationTime`. */
+ intentCatalogChanges: defineTable({
+ kind: v.union(v.literal("song"), v.literal("album"), v.literal("artist")),
+ entityId: v.string(),
+ removed: v.boolean(),
+ }).index("by_kind", ["kind"]),
appSettings: defineTable({
disableAccountCreation: v.boolean(),
}),
+ libraryScanLock: defineTable({
+ token: v.string(),
+ expiresAt: v.number(),
+ }),
artists: defineTable({
name: v.string(),
folder: v.string(),
diff --git a/packages/convex/convex/types.ts b/packages/convex/convex/types.ts
index 6aee22a..6cd39de 100644
--- a/packages/convex/convex/types.ts
+++ b/packages/convex/convex/types.ts
@@ -33,18 +33,16 @@ export type BrowseAlbumTrack = {
}
export type BrowseAlbumDetail = BrowseAlbum & {
+ /** `null` when the files have no year tag; clients hide it. */
year: number | null
genre: string | null
+ /** Empty when unknown; clients hide it. */
releaseDate: string
hasLossless: boolean
hasAtmos: boolean
tracks: BrowseAlbumTrack[]
}
-export type BrowseAlbumSummary = Omit & {
- trackCount: number
-}
-
export type BrowseArtistDetail = {
artist: BrowseArtist
albums: BrowseAlbum[]
diff --git a/packages/convex/convex/users.ts b/packages/convex/convex/users.ts
index 8836f81..35957b6 100644
--- a/packages/convex/convex/users.ts
+++ b/packages/convex/convex/users.ts
@@ -5,9 +5,18 @@ import {
} from "@convex-dev/auth/server"
import { ConvexError, v } from "convex/values"
import { api, internal } from "./_generated/api"
-import { action, internalQuery, mutation, query } from "./_generated/server"
-import type { Id } from "./_generated/dataModel"
+import {
+ action,
+ internalAction,
+ internalMutation,
+ internalQuery,
+ mutation,
+ query,
+} from "./_generated/server"
+import type { Doc, Id } from "./_generated/dataModel"
import type { ActionCtx, MutationCtx } from "./_generated/server"
+import { MAX_PROFILE_IMAGE_BYTES } from "./limits"
+import { deleteUserPlayback } from "./playbackState"
const playbackQualityValidator = v.union(
v.literal("low"),
@@ -178,18 +187,114 @@ export const listUsers = query({
},
})
+const DATA_URL_PATTERN = /^data:(image\/[\w.+-]+);base64,([A-Za-z0-9+/=]+)$/
+
+/** Splits an image data URL, rejecting anything over the size cap. */
+function parseImageDataUrl(image: string) {
+ const match = DATA_URL_PATTERN.exec(image)
+ if (!match) {
+ throw new ConvexError("Profile photo must be an image")
+ }
+ const [, contentType, base64] = match
+ if (Math.floor((base64.length * 3) / 4) > MAX_PROFILE_IMAGE_BYTES) {
+ throw new ConvexError(
+ `Profile photo must be ${MAX_PROFILE_IMAGE_BYTES / 1024 / 1024} MB or smaller`
+ )
+ }
+ return { contentType, base64 }
+}
+
+/**
+ * Path clients load the avatar from. The web server proxies it from Convex
+ * storage, since the backend's storage URLs are not reachable from browsers
+ * in every deployment. Legacy data URLs are returned as is until migrated.
+ */
+export function profileImagePath(user: Doc<"users">) {
+ if (user.imageStorageId) {
+ return `/api/user/${user._id}/avatar?v=${user.imageStorageId}`
+ }
+ return user.image
+}
+
+/**
+ * Takes a data URL so existing clients keep working. The image is moved into
+ * file storage in the background; `currentUser` updates once it lands.
+ */
export const updateProfileImage = mutation({
args: {
image: v.union(v.string(), v.null()),
},
handler: async (ctx, { image }) => {
const userId = await requireAuth(ctx)
- await ctx.db.patch(userId, {
- image: image === null ? undefined : image,
+ if (image === null) {
+ await setProfileImage(ctx, userId, null)
+ return
+ }
+ parseImageDataUrl(image)
+ await ctx.scheduler.runAfter(0, internal.users.storeProfileImage, {
+ userId,
+ image,
})
},
})
+/** Decodes a data URL into file storage and points the user at it. */
+export const storeProfileImage = internalAction({
+ args: { userId: v.id("users"), image: v.string() },
+ handler: async (ctx, { userId, image }) => {
+ const { contentType, base64 } = parseImageDataUrl(image)
+ const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0))
+ const storageId = await ctx.storage.store(
+ new Blob([bytes], { type: contentType })
+ )
+ await ctx.runMutation(internal.users.attachProfileImage, {
+ userId,
+ storageId,
+ })
+ },
+})
+
+export const attachProfileImage = internalMutation({
+ args: { userId: v.id("users"), storageId: v.id("_storage") },
+ handler: async (ctx, { userId, storageId }) => {
+ await setProfileImage(ctx, userId, storageId)
+ },
+})
+
+/** Replaces the avatar, deleting the previous file. Clears it for `null`. */
+async function setProfileImage(
+ ctx: MutationCtx,
+ userId: Id<"users">,
+ storageId: Id<"_storage"> | null
+) {
+ const user = await ctx.db.get(userId)
+ if (!user) {
+ if (storageId) {
+ await ctx.storage.delete(storageId)
+ }
+ return
+ }
+ if (user.imageStorageId && user.imageStorageId !== storageId) {
+ await ctx.storage.delete(user.imageStorageId)
+ }
+ await ctx.db.patch(userId, {
+ image: undefined,
+ imageStorageId: storageId ?? undefined,
+ })
+}
+
+/** Storage URL behind `profileImagePath`, for the web server's proxy route. */
+export const getProfileImageUrl = query({
+ args: { userId: v.id("users") },
+ handler: async (ctx, { userId }) => {
+ const user = await ctx.db.get(userId)
+ if (!user?.imageStorageId) {
+ return null
+ }
+ return await ctx.storage.getUrl(user.imageStorageId)
+ },
+})
+
export const updateProfileName = mutation({
args: { name: v.string() },
handler: async (ctx, { name }) => {
@@ -294,6 +399,8 @@ export const deleteUser = mutation({
throw new ConvexError("You cannot delete your own account")
}
await deleteOwnedPlaylists(ctx, userId)
+ await deleteUserPlayback(ctx, userId)
+ await setProfileImage(ctx, userId, null)
await deleteUserAuthData(ctx, userId)
},
})
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. */
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4631b7d..5866a70 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -179,6 +179,9 @@ importers:
'@otunes/convex':
specifier: workspace:*
version: link:../../packages/convex
+ '@tanstack/react-virtual':
+ specifier: ^3.14.26
+ version: 3.14.26(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
@@ -2657,6 +2660,15 @@ packages:
'@tailwindcss/postcss@4.3.2':
resolution: {integrity: sha512-rjVWYCa7Ngbi5AarT6k8TkxUG3Wl1QKzHdIZVsjZSzf36Jmo2IKZt/NHRAwly8oDkbBOH0YTu+CHuf9jPxMc+g==}
+ '@tanstack/react-virtual@3.14.26':
+ resolution: {integrity: sha512-HUDlfsrYH6ko5xH56L62Mcl/uzT+AGVNMHFuDNqDJMdZWc1AQa2oeVKNUvZ/RWBZQ4TYtyQerFrNvLnp39h65A==}
+ peerDependencies:
+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+
+ '@tanstack/virtual-core@3.19.11':
+ resolution: {integrity: sha512-/5iHb0RHBvj8Di59FDs4ESNm45jls33aZAi4zccVXZjc/6ZvwQP6nzEYeT6weXjTf9E6/vrp2JhYWRyO+ZP13A==}
+
'@tokenizer/inflate@0.4.1':
resolution: {integrity: sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==}
engines: {node: '>=18'}
@@ -9464,6 +9476,14 @@ snapshots:
postcss: 8.5.16
tailwindcss: 4.3.2
+ '@tanstack/react-virtual@3.14.26(react-dom@19.3.1(react@19.3.1))(react@19.3.1)':
+ dependencies:
+ '@tanstack/virtual-core': 3.19.11
+ react: 19.3.1
+ react-dom: 19.3.1(react@19.3.1)
+
+ '@tanstack/virtual-core@3.19.11': {}
+
'@tokenizer/inflate@0.4.1':
dependencies:
debug: 4.4.3