diff --git a/.dockerignore b/.dockerignore index 3e1c66f..2330f90 100644 --- a/.dockerignore +++ b/.dockerignore @@ -54,12 +54,11 @@ playwright.config.* *~ *.log -# Environment variables (only commit template files) -.env -.env*.local -.env.development -.env.test -.env.production.local +# Environment variables, in any workspace. Next.js inlines NEXT_PUBLIC_* values +# into the bundle and the Convex CLI reads .env.local on deploy. +**/.env +**/.env.* +!**/.env.example # Docker configuration files (not needed inside build context) Dockerfile* diff --git a/Dockerfile b/Dockerfile index 543c78d..ae29c75 100644 --- a/Dockerfile +++ b/Dockerfile @@ -195,7 +195,12 @@ RUN node --version \ && ldd /convex/generate_key \ && ! ldd /convex/convex-local-backend /convex/generate_key | grep -q 'not found' -RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes +# The backend gets its own user so the web server cannot read the database or +# instance secret. It joins the otunes group to clean up the web server's HLS +# cache in /tmp/otunes. +RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes \ + && useradd --system --user-group --groups otunes --create-home --home-dir /home/convex \ + --shell /usr/sbin/nologin convex COPY --from=convex-functions /app /opt/otunes/convex COPY docker/generate-auth-keys.mjs /opt/otunes/generate-auth-keys.mjs diff --git a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/queue.tsx b/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/queue.tsx deleted file mode 100644 index 4d4acb6..0000000 --- a/apps/mobile/app/(app)/(tabs)/(albums,artists,songs,playlists,favorites,recent)/queue.tsx +++ /dev/null @@ -1 +0,0 @@ -export { default } from "../library/queue" diff --git a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx index a32bf8c..66a7c26 100644 --- a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx @@ -35,7 +35,7 @@ import { MediaActionMenu, MediaContextMenu, type MediaAction, -} from "@/components/media-actions-sheet" +} from "@/components/media-context-menu" import { CollectionDetailSkeleton } from "@/components/skeletons" import { Button } from "@/components/ui/primitives" import { contentBottomInset } from "@/components/player" @@ -488,7 +488,7 @@ const AlbumTrackRow = memo(function AlbumTrackRow({ action: MediaAction ) => Promise }) { - const Row = Platform.OS === "ios" ? SongSwipeRow : Pressable + const Row = Platform.OS !== "web" ? SongSwipeRow : Pressable const { config } = useServerConfig() return ( void onAction(track, album, "play-next")} + onAddToQueue={() => void onAction(track, album, "play-last")} style={styles.trackRow} onPress={() => void onPlay(track.id as Id<"songs">, songIds)} > diff --git a/apps/mobile/app/(app)/(tabs)/home/artist/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/artist/[id].tsx index ef90e47..4b6b215 100644 --- a/apps/mobile/app/(app)/(tabs)/home/artist/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/artist/[id].tsx @@ -6,7 +6,7 @@ import { Ionicons } from "@expo/vector-icons" import { CoverImage } from "@/components/cover-image" import { MediaGridList } from "@/components/media-cards" -import { MediaActionMenu } from "@/components/media-actions-sheet" +import { MediaActionMenu } from "@/components/media-context-menu" import { CollectionDetailSkeleton } from "@/components/skeletons" import { Button } from "@/components/ui/primitives" import { contentBottomInset } from "@/components/player" diff --git a/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx index f11a0d1..e9f46f1 100644 --- a/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx @@ -46,7 +46,7 @@ import { import { MediaActionMenu, type MediaAction, -} from "@/components/media-actions-sheet" +} from "@/components/media-context-menu" import { CollectionDetailSkeleton } from "@/components/skeletons" import { Button } from "@/components/ui/primitives" import { contentBottomInset, SongListRow } from "@/components/player" @@ -314,7 +314,6 @@ function PlaylistContent({ deletePlaylist, handlePlaylistDetailAction, palette.foreground, - palette.background, palette.isDark, playlistId, playlist?.title, @@ -434,11 +433,18 @@ const PlaylistSongRow = memo(function PlaylistSongRow({ palette={palette} inset swipe={ - Platform.OS === "ios" + Platform.OS !== "web" ? { group: swipeGroup, backgroundColor: palette.background, onPlayNext: () => onAction(song, "play-next"), + onAddToQueue: () => onAction(song, "play-last"), + onRemove: + Platform.OS === "android" && removable + ? () => { + void onRemove(song.id) + } + : undefined, } : undefined } @@ -447,7 +453,7 @@ const PlaylistSongRow = memo(function PlaylistSongRow({ /> ) - if (Platform.OS === "ios" || !removable) { + if (Platform.OS !== "web" || !removable) { return row } diff --git a/apps/mobile/app/(app)/(tabs)/home/queue.tsx b/apps/mobile/app/(app)/(tabs)/home/queue.tsx deleted file mode 100644 index c378ed7..0000000 --- a/apps/mobile/app/(app)/(tabs)/home/queue.tsx +++ /dev/null @@ -1,186 +0,0 @@ -import { Stack, useRouter } from "expo-router" -import { memo, useCallback, useMemo } from "react" -import { FlatList, Pressable, StyleSheet, Text, View } from "react-native" - -import { Button } from "@/components/ui/primitives" -import { contentBottomInset, SongRow } from "@/components/player" -import { SongRowSkeleton } from "@/components/skeletons" -import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback" -import type { Id } from "@otunes/convex/_generated/dataModel" -import { longListProps } from "@/lib/list" -import { useSong, useSongs } from "@/lib/song-cache" -import { spacing, useThemeColors } from "@/lib/theme" - -/** `key` stays stable when earlier songs leave the queue, so rows are not remounted on skip. */ -type QueueItem = { songId: Id<"songs">; queueIndex: number; key: string } - -function queueItemKey(item: QueueItem) { - return item.key -} - -const QueueRow = memo(function QueueRow({ - songId, - queueIndex, - isLast, - isCurrent, - onSkipTo, - onMove, -}: Omit & { - isLast: boolean - isCurrent: boolean - onSkipTo: (index: number) => void - onMove: (index: number, direction: -1 | 1) => void -}) { - const colors = useThemeColors() - const song = useSong(songId) - - return ( - - {song ? ( - onSkipTo(queueIndex)} /> - ) : ( - - )} - - onMove(queueIndex, -1)} - > - Move up - - onMove(queueIndex, 1)}> - Move down - - {isCurrent ? ( - - Now playing - - ) : null} - - - ) -}) - -export default function QueueScreen() { - const router = useRouter() - const colors = useThemeColors() - const { queueSongIds, queueHistorySongIds } = usePlaybackQueue() - const { skipToQueueIndex, clearQueue, reorderQueue } = usePlaybackActions() - const historySongs = useSongs(queueHistorySongIds) - - const items = useMemo(() => { - const occurrences = new Map() - return queueSongIds.map((songId, queueIndex) => { - const occurrence = occurrences.get(songId) ?? 0 - occurrences.set(songId, occurrence + 1) - return { songId, queueIndex, key: `${songId}:${occurrence}` } - }) - }, [queueSongIds]) - - const moveSong = useCallback( - (fromIndex: number, direction: -1 | 1) => { - const toIndex = fromIndex + direction - if (toIndex < 0 || toIndex >= queueSongIds.length) return - const next = [...queueSongIds] - const [item] = next.splice(fromIndex, 1) - next.splice(toIndex, 0, item) - void reorderQueue(next) - }, - [queueSongIds, reorderQueue] - ) - - function handleClearQueue() { - if (router.canGoBack()) { - router.back() - setTimeout(() => { - void clearQueue() - }, 0) - return - } - - void clearQueue() - } - - return ( - <> - - queueSongIds.length > 0 ? ( - - - - - -
-
{track.title}
- {track.artists ? ( -

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

- ) : null} -
- - - {formatDuration(track.durationSeconds)} - - - - - - - ) -} - export function AlbumView({ album, highlightedSongId, @@ -269,17 +102,15 @@ export function AlbumView({ album: BrowseAlbumDetail highlightedSongId?: string }) { - const { openAddToPlaylist } = useAddToPlaylist() const { isSongFavorite, isAlbumFavorite, toggleSongFavorite, toggleAlbumFavorite, - favoriteSongs, } = useFavorites() const currentSongId = useCurrentSongId() const { playFromSong, playAlbum, playAlbumShuffled } = usePlaybackActions() - const { runQueueAction, createStation } = useQueueMediaActions() + const { runSongsAction } = useMediaActions() const albumSongIds = React.useMemo( () => album.tracks.map((track) => track.id as Id<"songs">), [album.tracks] @@ -317,7 +148,6 @@ export function AlbumView({ const { selectedIds, selectedCount, - isSelected, handleSelect, handlePointerDown, prepareContextMenu, @@ -345,55 +175,55 @@ export function AlbumView({ return indexById }, [album.tracks]) - function handleMediaAction( - action: MediaContextAction, - fallbackTrackId?: string - ) { - const targetIds = - selectedIds.size > 0 - ? Array.from(selectedIds) - : fallbackTrackId - ? [fallbackTrackId] - : activeTrackId - ? [activeTrackId] - : [] - switch (action) { - case "create-station": - void createStation(album.artist.id) - break - case "favorite": - void favoriteSongs(targetIds as Id<"songs">[]) - break - case "playlist": - openAddToPlaylist(targetIds as Id<"songs">[]) - break - case "play-next": - case "play-last": - case "shuffle": - void runQueueAction(action, targetIds as Id<"songs">[]) - break - } - } + const trackSongs = React.useMemo( + () => + new Map( + album.tracks.map((track) => [ + track.id, + { + id: track.id, + title: track.title, + durationSeconds: track.durationSeconds, + artist: album.artist, + album: { id: album.id, title: album.title, cover: album.cover }, + }, + ]) + ), + [album.tracks, album.artist, album.id, album.title, album.cover] + ) + + const handleMediaAction = useTrackListMediaAction({ + selectedIds, + artistId: album.artist.id, + }) + + const handleRowSelect = React.useCallback( + (index: number, event: React.MouseEvent) => { + const trackId = album.tracks[index].id + handleSelect(trackId, index, event) + setActiveTrackId(trackId) + }, + [album.tracks, handleSelect] + ) + + const handleRowPlay = React.useCallback( + (index: number) => { + void playFromSong(album.tracks[index].id, albumSongIds, `album:${album.id}`) + }, + [album.tracks, album.id, albumSongIds, playFromSong] + ) + + const handleToggleFavorite = React.useCallback( + (songId: string) => void toggleSongFavorite(songId as Id<"songs">), + [toggleSongFavorite] + ) function handleAlbumMediaAction(action: MediaContextAction) { - const targetIds = album.tracks.map((track) => track.id as Id<"songs">) - - switch (action) { - case "create-station": - void createStation(album.artist.id) - break - case "favorite": - void toggleAlbumFavorite(album.id as Id<"albums">) - break - case "playlist": - openAddToPlaylist(targetIds) - break - case "play-next": - case "play-last": - case "shuffle": - void runQueueAction(action, targetIds) - break + if (action === "favorite") { + void toggleAlbumFavorite(album.id as Id<"albums">) + return } + runSongsAction(action, albumSongIds, album.artist.id) } return ( @@ -527,39 +357,25 @@ export function AlbumView({ return ( 0 ? track.track : sectionTrackIndex + 1 + } + subtitle={track.artists?.join(", ")} isActive={track.id === activeTrackId} - isSelected={isSelected(track.id)} selectionPosition={selectionPositions[listIndex]} isFavorite={isSongFavorite(track.id)} - selectedCount={ - isSelected(track.id) && selectedCount > 0 - ? selectedCount - : 1 - } - onPointerDown={handlePointerDown} - onSelect={(event) => { - handleSelect(track.id, listIndex, event) - setActiveTrackId(track.id) - }} - onToggleFavorite={() => - void toggleSongFavorite(track.id as Id<"songs">) - } - onPrepareContextMenu={() => - prepareContextMenu(track.id) - } - onMediaAction={handleMediaAction} + selectedCount={selectedCount} + selectionStationArtistId={album.artist.id} isNowPlaying={currentSongId === track.id} - onPlay={() => - void playFromSong( - track.id as Id<"songs">, - albumSongIds, - `album:${album.id}` - ) - } + onPointerDown={handlePointerDown} + onSelect={handleRowSelect} + onPlay={handleRowPlay} + onToggleFavorite={handleToggleFavorite} + onPrepareContextMenu={prepareContextMenu} + onMediaAction={handleMediaAction} /> ) })} diff --git a/apps/web/components/artist-view.tsx b/apps/web/components/artist-view.tsx index c5b568b..5ab9e1e 100644 --- a/apps/web/components/artist-view.tsx +++ b/apps/web/components/artist-view.tsx @@ -4,27 +4,19 @@ import { PageHeader } from "@/components/library-skeletons" import * as React from "react" import Image from "next/image" import { Play, Shuffle } from "lucide-react" -import { useConvex } from "convex/react" -import { useCacheScope } from "@/components/persistent-cache-provider" -import { useAddToPlaylist } from "@/components/add-to-playlist-provider" import { useFavorites } from "@/components/favorites-provider" import { usePlaybackActions } from "@/components/playback-provider" -import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" +import { useMediaActions } from "@/hooks/use-media-actions" import { AlbumCard } from "@/components/album-card" import { FavoriteMediaButton } from "@/components/favorite-media-button" -import { - MediaContextMenu, - type MediaContextAction, -} from "@/components/media-context-menu" +import { MediaContextMenu } from "@/components/media-context-menu" import { Button } from "@/components/ui/button" import { ScrollArea } from "@/components/ui/scroll-area" -import { api } from "@otunes/convex/_generated/api" import type { Id } from "@otunes/convex/_generated/dataModel" import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types" import { albumGridClassName } from "@/lib/album-grid-classes" import { artistCoverUrl } from "@/lib/cover-urls" -import { fetchCachedQuery } from "@otunes/convex/client/cached-query" export function ArtistView({ artist, @@ -34,34 +26,8 @@ export function ArtistView({ albums: BrowseAlbum[] }) { const { isArtistFavorite, toggleArtistFavorite } = useFavorites() - const { openAddArtistToPlaylist } = useAddToPlaylist() const { playArtist, playArtistShuffled } = usePlaybackActions() - const { runQueueAction } = useQueueMediaActions() - const convex = useConvex() - const cacheScope = useCacheScope() - - async function handleMediaAction(action: MediaContextAction) { - switch (action) { - case "favorite": - void toggleArtistFavorite(artist.id as Id<"artists">) - break - case "playlist": - void openAddArtistToPlaylist(artist.id as Id<"artists">) - break - case "play-next": - case "play-last": - case "shuffle": { - const songIds = await fetchCachedQuery( - convex, - cacheScope, - api.playlists.getOrderedArtistSongIds, - { artistId: artist.id as Id<"artists"> } - ) - void runQueueAction(action, songIds) - break - } - } - } + const { runArtistAction } = useMediaActions() return (
@@ -118,7 +84,7 @@ export function ArtistView({ label={`More options for ${artist.name}`} selectedCount={albums.length} onOpenMenu={() => {}} - onAction={handleMediaAction} + onAction={(action) => void runArtistAction(action, artist.id)} favorited={isArtistFavorite(artist.id)} trackRowTrigger={false} triggerVariant="secondary" diff --git a/apps/web/components/artists-view.tsx b/apps/web/components/artists-view.tsx index a1a0938..f10b361 100644 --- a/apps/web/components/artists-view.tsx +++ b/apps/web/components/artists-view.tsx @@ -4,11 +4,8 @@ import * as React from "react" import Image from "next/image" import Link from "next/link" import { ChevronRightIcon, Play, Shuffle } from "lucide-react" -import { useConvex } from "convex/react" -import { useCacheScope } from "@/components/persistent-cache-provider" import { AlbumCard } from "@/components/album-card" -import { useAddToPlaylist } from "@/components/add-to-playlist-provider" import { FavoriteMediaButton } from "@/components/favorite-media-button" import { useFavorites } from "@/components/favorites-provider" import { @@ -18,15 +15,13 @@ import { type MediaContextMenuProps, } from "@/components/media-context-menu" import { usePlaybackActions } from "@/components/playback-provider" -import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" +import { useMediaActions } from "@/hooks/use-media-actions" import { Button } from "@/components/ui/button" import { ScrollArea } from "@/components/ui/scroll-area" -import { api } from "@otunes/convex/_generated/api" import { cn } from "@/lib/utils" import type { Id } from "@otunes/convex/_generated/dataModel" import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types" import { artistCoverUrl } from "@/lib/cover-urls" -import { fetchCachedQuery } from "@otunes/convex/client/cached-query" function ArtistAvatar({ artist }: { artist: BrowseArtist }) { return ( @@ -118,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 } = usePlaybackActions() - const { runQueueAction } = useQueueMediaActions() + const { runArtistAction } = useMediaActions() const selectedArtist = sortedArtists.find( (artist) => artist.id === selectedId @@ -138,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 (
@@ -177,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) } /> ))} @@ -233,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/playback-provider.tsx b/apps/web/components/playback-provider.tsx index 3754d09..79f9446 100644 --- a/apps/web/components/playback-provider.tsx +++ b/apps/web/components/playback-provider.tsx @@ -990,6 +990,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { if (!shouldContinuePlaying) { autoPlayNextRef.current = false isPlayingRef.current = false + audio.pause() audio.currentTime = 0 currentTimeRef.current = 0 setCurrentTime(0) diff --git a/apps/web/components/player-bar.tsx b/apps/web/components/player-bar.tsx index 6e28e99..720f459 100644 --- a/apps/web/components/player-bar.tsx +++ b/apps/web/components/player-bar.tsx @@ -31,13 +31,7 @@ import { Slider } from "@/components/ui/slider" import { useSidebar } from "@/components/ui/sidebar" import { albumCoverUrl } from "@/lib/cover-urls" import { cn } from "@/lib/utils" - -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")}` -} +import { formatDuration } from "@/lib/format-duration" function PlayerSeekBar({ hasActiveSong }: { hasActiveSong: boolean }) { const { currentTime, duration, seekTo } = usePlaybackProgress() diff --git a/apps/web/components/playlist-view.tsx b/apps/web/components/playlist-view.tsx index a5da623..6889fd3 100644 --- a/apps/web/components/playlist-view.tsx +++ b/apps/web/components/playlist-view.tsx @@ -9,279 +9,42 @@ 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 { 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, - MediaContextMenuArea, - MediaMenuItem, - MediaMenuSeparator, - type MediaContextMenuProps, } 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, DropdownMenuSeparator, } from "@/components/ui/dropdown-menu" import { ScrollArea } from "@/components/ui/scroll-area" -import { VirtualList } from "@/components/virtual-list" import { useCachedQuery } from "@/hooks/use-cached-query" -import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" -import { useStableCallback } from "@/hooks/use-stable-callback" +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 { getSelectionRangePositions } from "@/lib/selection-range-styles" const ADD_TO_ANOTHER_PLAYLIST = "Add to Another Playlist" const estimatePlaylistRowSize = () => 60 -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 ( -
- {song.album.title} -
- -
-
- ) -} - -const PlaylistSongRow = React.memo(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: (songId: string, index: number, event: React.MouseEvent) => void - onPointerDown: (event: React.MouseEvent) => void - onToggleFavorite: (songId: string) => void - onPrepareContextMenu: (songId: string) => void - onMediaAction: (action: MediaContextAction, songId: string) => void - onRemove: (songId: string) => void - onDragStart: (index: number, event: React.DragEvent) => void - onDragOver: (event: React.DragEvent) => void - onDrop: (index: number, event: React.DragEvent) => void - showFavoriteInMenu?: boolean - removeLabel?: string - isNowPlaying: boolean - onPlay: (songId: string) => void -}) { - const displayTrack = index + 1 - const play = () => onPlay(song.id) - const select = (event: React.MouseEvent) => onSelect(song.id, index, event) - const inRange = isInSelectionRange(selectionPosition) - - const menu: MediaContextMenuProps = { - label: `More options for ${song.title}`, - stationArtistId: stationArtist, - selectedCount, - inSelectionRange: inRange, - onOpenMenu: () => onPrepareContextMenu(song.id), - onAction: (action) => 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, - }, - children: canRemove ? ( - <> - - onRemove(song.id)} - > - {removeLabel} - - - - ) : null, - } - - return ( - -
onDragStart(index, event)} - onDragOver={onDragOver} - onDrop={(event) => onDrop(index, event)} - onMouseDown={onPointerDown} - onClick={select} - onDoubleClick={(event) => { - event.preventDefault() - play() - }} - onKeyDown={(event) => { - if (event.key === "Enter" || event.key === " ") { - event.preventDefault() - select(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} -
- onToggleFavorite(song.id)} - /> - - - - {song.title} - - - {formatDuration(song.durationSeconds)} - - - -
-
-
- ) -}) - export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { const router = useRouter() const isFavorites = playlist.isFavorites === true @@ -290,13 +53,8 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { currentUser === undefined ? playlist.isOwner : currentUser?._id === playlist.owner.id - const { openAddToPlaylist } = useAddToPlaylist() - const { - isSongFavorite, - toggleSongFavorite, - toggleSongsFavorite, - favoriteSongs: addFavoriteSongs, - } = useFavorites() + const { isSongFavorite, toggleSongFavorite, toggleSongsFavorite } = + useFavorites() const currentSongId = useCurrentSongId() const { playInOrder, @@ -305,7 +63,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { playPlaylistShuffled, playFromSong, } = usePlaybackActions() - const { runQueueAction, createStation } = useQueueMediaActions() + const { runSongsAction } = useMediaActions() const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist) const reorderSongs = useMutation(api.playlists.reorderPlaylistSongs) const deletePlaylist = useMutation(api.playlists.deletePlaylist) @@ -317,13 +75,9 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { const [hiddenFavoriteIds, setHiddenFavoriteIds] = React.useState( () => new Set() ) - const songs = React.useMemo( - () => - isFavorites - ? playlist.songs.filter((song) => !hiddenFavoriteIds.has(song.id)) - : playlistSongs, - [isFavorites, playlist.songs, hiddenFavoriteIds, playlistSongs] - ) + const songs = isFavorites + ? playlist.songs.filter((song) => !hiddenFavoriteIds.has(song.id)) + : playlistSongs const [searchQuery, setSearchQuery] = React.useState("") const normalizedQuery = searchQuery.trim().toLowerCase() const filteredSongs = React.useMemo( @@ -341,6 +95,10 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { () => songs.map((song) => song.id as Id<"songs">), [songs] ) + const playlistPositionById = React.useMemo( + () => new Map(songs.map((song, index) => [song.id, index + 1])), + [songs] + ) const [activeTrackId, setActiveTrackId] = React.useState("") const [dragIndex, setDragIndex] = React.useState(null) const [isSubscribed, setIsSubscribed] = React.useState(playlist.isSubscribed) @@ -355,7 +113,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { const { selectedIds, selectedCount, - isSelected, handleSelect, handlePointerDown, prepareContextMenu, @@ -393,56 +150,37 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { } } - function resolveTargetIds(fallbackSongId?: string) { - return selectedIds.size > 0 - ? Array.from(selectedIds) - : fallbackSongId - ? [fallbackSongId] - : activeTrackId - ? [activeTrackId] - : [] - } - - const handleMediaAction = useStableCallback( - (action: MediaContextAction, fallbackSongId?: string) => { - const targetIds = resolveTargetIds(fallbackSongId) - - switch (action) { - case "create-station": { - const artistId = stationArtistId(songs, new Set(targetIds)) - if (artistId) void createStation(artistId) - break - } - case "favorite": - void addFavoriteSongs(targetIds as Id<"songs">[]) - break - case "playlist": - openAddToPlaylist(targetIds as Id<"songs">[]) - break - case "play-next": - case "play-last": - case "shuffle": - void runQueueAction(action, targetIds as Id<"songs">[]) - break - } - } - ) + const handleMediaAction = useTrackListMediaAction({ selectedIds, songs }) function handlePlaylistMediaAction(action: MediaContextAction) { - const targetIds = songs.map((song) => song.id as Id<"songs">) + runSongsAction(action, playlistSongIds) + } - switch (action) { - case "favorite": - void addFavoriteSongs(targetIds) - break - case "playlist": - openAddToPlaylist(targetIds) - break - case "play-next": - case "play-last": - case "shuffle": - void runQueueAction(action, targetIds) - break + const canReorder = isOwner && !isFavorites && !normalizedQuery + + function handleRowSelect(index: number, event: React.MouseEvent) { + const songId = filteredSongs[index].id + handleSelect(songId, index, event) + setActiveTrackId(songId) + } + + function handleRowPlay(index: number) { + void playFromSong( + filteredSongs[index].id, + playlistSongIds, + `playlist:${playlist.id}` + ) + } + + function handleToggleFavorite(songId: string) { + const wasFavorite = isSongFavorite(songId) + void toggleSongFavorite(songId as Id<"songs">) + if (isFavorites && wasFavorite) { + setHiddenFavoriteIds((current) => { + const next = new Set(current) + next.add(songId) + return next + }) } } @@ -453,10 +191,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { : [songId] if (isFavorites) { - const succeeded = await toggleSongsFavorite( - ids as Id<"songs">[], - true - ) + const succeeded = await toggleSongsFavorite(ids as Id<"songs">[], true) if (!succeeded) return return } @@ -469,7 +204,9 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { setPlaylistSongs((current) => current.filter((song) => !ids.includes(song.id)) ) - toast.success(ids.length > 1 ? `Removed ${ids.length} songs` : "Removed song") + toast.success( + ids.length > 1 ? `Removed ${ids.length} songs` : "Removed song" + ) } catch (error) { toast.error( error instanceof Error ? error.message : "Failed to remove song" @@ -497,13 +234,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 } @@ -517,59 +248,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { void persistOrder(previous, next) } - const canReorder = isOwner && !isFavorites && !normalizedQuery - const getSongKey = React.useCallback( - (index: number) => filteredSongs[index].id, - [filteredSongs] - ) - - // Stable row callbacks so memoized rows skip re-rendering. - const handleRowSelect = useStableCallback( - (songId: string, index: number, event: React.MouseEvent) => { - handleSelect(songId, index, event) - setActiveTrackId(songId) - } - ) - - const handleToggleFavorite = useStableCallback((songId: string) => { - const wasFavorite = isSongFavorite(songId) - void toggleSongFavorite(songId as Id<"songs">) - if (isFavorites && wasFavorite) { - setHiddenFavoriteIds((current) => new Set(current).add(songId)) - } - }) - - const handleRemove = useStableCallback((songId: string) => { - void handleRemoveSong(songId) - }) - - const handleDragStart = useStableCallback( - (index: number, event: React.DragEvent) => { - if (!canReorder) return - setDragIndex(index) - event.dataTransfer.effectAllowed = "move" - } - ) - - const handleDragOver = useStableCallback((event: React.DragEvent) => { - if (canReorder) event.preventDefault() - }) - - const handleRowDrop = useStableCallback( - (index: number, event: React.DragEvent) => { - event.preventDefault() - handleDrop(index) - } - ) - - const handlePlay = useStableCallback((songId: string) => { - void playFromSong( - songId as Id<"songs">, - playlistSongIds, - `playlist:${playlist.id}` - ) - }) - async function handleDeletePlaylist() { try { await deletePlaylist({ @@ -617,7 +295,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
-
+
{isFavorites ? ( @@ -750,42 +428,42 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { filteredSongs[index].id} + // Keep the drag source mounted so its drop still lands. keepMounted={dragIndex} renderItem={(index) => { const song = filteredSongs[index] - const selected = isSelected(song.id) return ( - 0 ? selectedCount : 1 - } - stationArtist={ - selected ? selectedStationArtistId : song.artist.id - } - isDragging={dragIndex === index} onPointerDown={handlePointerDown} onSelect={handleRowSelect} + onPlay={handleRowPlay} onToggleFavorite={handleToggleFavorite} onPrepareContextMenu={prepareContextMenu} onMediaAction={handleMediaAction} - onRemove={handleRemove} - onDragStart={handleDragStart} - onDragOver={handleDragOver} - onDrop={handleRowDrop} - isNowPlaying={currentSongId === song.id} - onPlay={handlePlay} + onRemove={handleRemoveSong} + onDragStart={canReorder ? setDragIndex : undefined} + onDrop={canReorder ? handleDrop : undefined} /> ) }} diff --git a/apps/web/components/queue-panel.tsx b/apps/web/components/queue-panel.tsx index 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 ( -
- {title} -
- ) -} - function HistorySongRow({ song }: { song: HistorySong }) { return (
  • - {song.album.id ? ( - - ) : ( -
    - -
    - )} + void - onPointerDown: (event: React.MouseEvent) => void - onSkipTo: () => void - onDragStart: (event: React.DragEvent) => void - onDragOver: (event: React.DragEvent) => void - onDrop: (event: React.DragEvent) => void - } ->(function QueueSongRow( - { - song, - isNowPlaying, - selectionPosition, - isDragging, - onSelect, - onPointerDown, - onSkipTo, - onDragStart, - onDragOver, - onDrop, - }, - ref -) { - const inRange = isInSelectionRange(selectionPosition) - - return ( -
  • { - event.preventDefault() - onSkipTo() - }} - onKeyDown={(event) => { - if (event.key === "Enter" || event.key === " ") { - event.preventDefault() - onSelect(event as unknown as React.MouseEvent) - } - }} - className={cn( - "group relative w-full cursor-pointer select-none py-2 text-left text-sm transition-colors", - inRange && "text-primary-foreground", - isDragging && "opacity-50" - )} - > - - {!inRange && isNowPlaying ? : null} - {!inRange && !isNowPlaying ? : null} -
    - {song.album.id ? ( - - ) : ( -
    - -
    - )} - - - - - {formatDuration(song.durationSeconds)} - -
    -
  • - ) -}) - function QueueSongRowSkeleton() { return (
  • @@ -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/songs-view.tsx b/apps/web/components/songs-view.tsx index 0646849..b0404b7 100644 --- a/apps/web/components/songs-view.tsx +++ b/apps/web/components/songs-view.tsx @@ -2,20 +2,20 @@ import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger" import { stationArtistId } from "@/lib/station-artist" -import { memo, useCallback, useEffect, useMemo, useState, useRef, MouseEvent } from "react" -import Image from "next/image" -import Link from "next/link" -import { ArrowUpDown, Play, Star } from "lucide-react" +import { + useCallback, + useEffect, + useMemo, + useState, + useRef, + type MouseEvent, +} from "react" +import { ArrowUpDown } from "lucide-react" -import { useAddToPlaylist } from "@/components/add-to-playlist-provider" import { useFavorites } from "@/components/favorites-provider" import { usePlaybackActions } from "@/components/playback-provider" -import { - MediaContextMenu, - type MediaContextAction, - MediaContextMenuArea, - type MediaContextMenuProps, -} from "@/components/media-context-menu" +import { LibraryTrackListHeader, TrackRow } from "@/components/track-row" +import { VirtualList } from "@/components/virtual-list" import { Button } from "@/components/ui/button" import { DropdownMenu, @@ -27,26 +27,17 @@ 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 { VirtualList } from "@/components/virtual-list" -import { useStableCallback } from "@/hooks/use-stable-callback" import { api } from "@otunes/convex/_generated/api" 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" @@ -55,224 +46,9 @@ type SortDirection = "asc" | "desc" const SONGS_PAGE_SIZE = 50 const estimateSongRowSize = () => 56 -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 ( -
      - {song.album.title} -
      - -
      -
      - ) -} - -const SongRow = memo(function SongRow({ - song, - index, - isSelected, - selectionPosition, - isFavorite, - selectedCount, - stationArtist, - onSelect, - onPointerDown, - onToggleFavorite, - onPrepareContextMenu, - onMediaAction, - onPlay, -}: { - song: BrowseSong - index: number - isSelected: boolean - selectionPosition: SelectionRangePosition - isFavorite: boolean - selectedCount: number - stationArtist?: string - onSelect: (songId: string, index: number, event: MouseEvent) => void - onPointerDown: (event: MouseEvent) => void - onToggleFavorite: (songId: string) => void - onPrepareContextMenu: (songId: string) => void - onMediaAction: (action: MediaContextAction, songId: string) => void - onPlay: (songId: string) => void -}) { - const play = () => onPlay(song.id) - 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" - - const menu: MediaContextMenuProps = { - label: `More options for ${song.title}`, - stationArtistId: stationArtist, - selectedCount, - align: "end", - inSelectionRange: inRange, - onOpenMenu: () => onPrepareContextMenu(song.id), - onAction: (action) => 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, - }, - } - - return ( - -
      onSelect(song.id, index, event)} - onDoubleClick={(event) => { - event.preventDefault() - play() - }} - className="group cursor-pointer select-none whitespace-nowrap text-sm transition-colors has-aria-expanded:bg-muted/50" - > -
      - - {!inRange ? : null} -
      -
      -
      - -
      - - - {song.title} - {song.explicit ? ( - - E - - ) : null} - -
      -
      - event.stopPropagation()} - > - {song.artist.name} - -
      -
      - event.stopPropagation()} - > - {song.album.title} - -
      -
      - - {formatDuration(song.durationSeconds)} - - -
      -
      -
      - - ) -}) - export function SongsView() { - const { openAddToPlaylist } = useAddToPlaylist() - const { isSongFavorite, toggleSongFavorite, favoriteSongs } = useFavorites() + const { isSongFavorite, toggleSongFavorite } = useFavorites() const { playFromLibrarySong } = usePlaybackActions() - const { runQueueAction, createStation } = useQueueMediaActions() const [sortKey, setSortKey] = useState("title") const [sortDirection, setSortDirection] = useState("asc") @@ -313,7 +89,6 @@ export function SongsView() { const { selectedIds, selectedCount, - isSelected, handleSelect, handlePointerDown, prepareContextMenu, @@ -334,48 +109,26 @@ export function SongsView() { [songs, selectedIds] ) - const handleMediaAction = useStableCallback( - (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 handleRowSelect = useStableCallback(handleSelect) const handleToggleFavorite = useCallback( (songId: string) => void toggleSongFavorite(songId as Id<"songs">), [toggleSongFavorite] ) - const handlePlay = useCallback( - (songId: string) => - void playFromLibrarySong(songId as Id<"songs">, { - sortKey, - sortDirection, - }), - [playFromLibrarySong, sortKey, sortDirection] - ) const getSongKey = useCallback((index: number) => songs[index].id, [songs]) if (status === "LoadingFirstPage" && !isCached) { @@ -449,60 +202,35 @@ export function SongsView() {
      { if (event.target === event.currentTarget) { clearSelection() } }} > -
      -
      - - - Name -
      - - Artist - - - Album - -
      - - Time - - -
      + { - const song = songs[index] - const selected = isSelected(song.id) - return ( - 0 ? selectedCount : 1 - } - onPointerDown={handlePointerDown} - onSelect={handleRowSelect} - onToggleFavorite={handleToggleFavorite} - onPrepareContextMenu={prepareContextMenu} - onMediaAction={handleMediaAction} - onPlay={handlePlay} - /> - ) - }} + renderItem={(index) => ( + + )} />
      + onSelect: (index: number, event: React.MouseEvent) => void + onPointerDown: (event: React.MouseEvent) => void + onPlay: (index: number) => void + onToggleFavorite?: (songId: string) => void + onPrepareContextMenu?: (songId: string) => void + /** Renders the "more options" 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 ( +
      + {alt} + {children} +
      + ) +} + +function FavoriteStarButton({ + title, + isFavorite, + inRange, + className, + onToggle, +}: { + title: string + isFavorite: boolean + inRange: boolean + className?: string + onToggle: () => void +}) { + return ( + + ) +} + +function ExplicitBadge({ inRange }: { inRange: boolean }) { + return ( + + E + + ) +} + +function TrackTitle({ + song, + subtitle, + inRange, +}: { + song: BrowseSong + subtitle?: string + inRange: boolean +}) { + return ( +
      +
      + {song.title} + {song.explicit ? : null} +
      + {subtitle ? ( +

      + {subtitle} +

      + ) : null} +
      + ) +} + +export function LibraryTrackListHeader() { + const labelClass = "text-xs text-muted-foreground" + return ( +
      +
      + + + Name +
      + Artist + Album +
      + Time + +
      + ) +} + +function TrackRowComponent({ + variant, + song, + index, + trackNumber, + subtitle, + selectionPosition, + isActive = false, + isNowPlaying = false, + isFavorite = false, + isDragging = false, + selectedCount = 0, + selectionStationArtistId, + playlistLabel, + showFavoriteInMenu = true, + removeLabel, + ref, + onSelect, + onPointerDown, + onPlay, + onToggleFavorite, + onPrepareContextMenu, + onMediaAction, + onRemove, + onDragStart, + onDrop, +}: TrackRowProps) { + const inRange = isInSelectionRange(selectionPosition) + const flush = variant === "library" || variant === "queue" + const play = () => onPlay(index) + const toggleFavorite = () => onToggleFavorite?.(song.id) + + const favoriteStar = ( +
      + +
      + ) + + const trackNumberButton = ( + + ) + + const duration = ( + + {formatDuration(song.durationSeconds)} + + ) + + // 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.stopPropagation()} + > + {song.artist.name} + +
      +
      + event.stopPropagation()} + > + {song.album.title} + +
      +
      + {duration} + {menu} +
      + ) + break + } + case "album": + content = ( +
      + {favoriteStar} + {trackNumberButton} + + {duration} + {menu} +
      + ) + break + case "playlist": + content = ( +
      + +
      + +
      +
      + {trackNumberButton} + + {duration} + {menu} +
      + ) + break + case "queue": + content = ( +
      + + + {duration} +
      + ) + break + } + + const shellProps = { + role: "button", + tabIndex: 0, + draggable: onDragStart ? true : undefined, + onDragStart: onDragStart + ? (event: React.DragEvent) => { + event.dataTransfer.effectAllowed = "move" + onDragStart(index) + } + : undefined, + onDragOver: onDragStart + ? (event: React.DragEvent) => event.preventDefault() + : undefined, + onDrop: onDrop + ? (event: React.DragEvent) => { + event.preventDefault() + onDrop(index) + } + : undefined, + onMouseDown: onPointerDown, + onClick: (event: React.MouseEvent) => onSelect(index, event), + onDoubleClick: (event: React.MouseEvent) => { + event.preventDefault() + play() + }, + onKeyDown: (event: React.KeyboardEvent) => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault() + onSelect(index, event as unknown as React.MouseEvent) + } + }, + className: cn( + "group relative w-full cursor-pointer select-none text-left text-sm transition-colors", + flush ? "py-2" : "py-2.5", + inRange && "text-primary-foreground", + isDragging && "opacity-50" + ), + } + + const children = ( + <> + + {!inRange && isActive ? : null} + {!inRange && !isActive ? : null} + {content} + + ) + + 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/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-media-actions.ts b/apps/web/hooks/use-media-actions.ts new file mode 100644 index 0000000..d665acc --- /dev/null +++ b/apps/web/hooks/use-media-actions.ts @@ -0,0 +1,104 @@ +"use client" + +import * as React from "react" +import { useConvex } from "convex/react" + +import { useAddToPlaylist } from "@/components/add-to-playlist-provider" +import { useFavorites } from "@/components/favorites-provider" +import type { MediaContextAction } from "@/components/media-context-menu" +import { useCacheScope } from "@/components/persistent-cache-provider" +import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" +import { stationArtistId } from "@/lib/station-artist" +import { api } from "@otunes/convex/_generated/api" +import type { Id } from "@otunes/convex/_generated/dataModel" +import { fetchCachedQuery } from "@otunes/convex/client/cached-query" + +export function useMediaActions() { + const { openAddToPlaylist, openAddArtistToPlaylist } = useAddToPlaylist() + const { favoriteSongs, toggleArtistFavorite } = useFavorites() + const { runQueueAction, createStation } = useQueueMediaActions() + const convex = useConvex() + const cacheScope = useCacheScope() + + const runSongsAction = React.useCallback( + ( + action: MediaContextAction, + songIds: Id<"songs">[], + stationArtist?: string + ) => { + switch (action) { + case "create-station": + if (stationArtist) void createStation(stationArtist) + break + case "favorite": + void favoriteSongs(songIds) + break + case "playlist": + openAddToPlaylist(songIds) + break + case "play-next": + case "play-last": + case "shuffle": + void runQueueAction(action, songIds) + break + } + }, + [createStation, favoriteSongs, openAddToPlaylist, runQueueAction] + ) + + const runArtistAction = React.useCallback( + async (action: MediaContextAction, artistId: string) => { + switch (action) { + case "favorite": + void toggleArtistFavorite(artistId as Id<"artists">) + break + case "playlist": + void openAddArtistToPlaylist(artistId as Id<"artists">) + break + case "play-next": + case "play-last": + case "shuffle": { + const songIds = await fetchCachedQuery( + convex, + cacheScope, + api.playlists.getOrderedArtistSongIds, + { artistId: artistId as Id<"artists"> } + ) + void runQueueAction(action, songIds) + break + } + } + }, + [convex, cacheScope, toggleArtistFavorite, openAddArtistToPlaylist, runQueueAction] + ) + + return { runSongsAction, runArtistAction } +} + +/** + * Handles a track row menu action, targeting the current selection or else the + * row's song. The station artist is `artistId` when given, otherwise the artist + * every targeted song in `songs` shares. + */ +export function useTrackListMediaAction({ + selectedIds, + songs, + artistId, +}: { + selectedIds: ReadonlySet + songs?: { id: string; artist: { id: string } }[] + artistId?: string +}) { + const { runSongsAction } = useMediaActions() + + return React.useCallback( + (action: MediaContextAction, songId: string) => { + const targetIds = selectedIds.size > 0 ? Array.from(selectedIds) : [songId] + const stationArtist = + artistId ?? + (songs ? stationArtistId(songs, new Set(targetIds)) : undefined) + runSongsAction(action, targetIds as Id<"songs">[], stationArtist) + }, + [selectedIds, songs, artistId, runSongsAction] + ) +} diff --git a/apps/web/lib/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..009f065 100644 --- a/apps/web/lib/media-links.ts +++ b/apps/web/lib/media-links.ts @@ -13,15 +13,15 @@ function mediaOrigin() { return window.location.origin } -export function albumShareUrl(albumId: string) { +function albumShareUrl(albumId: string) { return `${mediaOrigin()}/album/${albumId}` } -export function songShareUrl(albumId: string, songId: string) { +function songShareUrl(albumId: string, songId: string) { return `${mediaOrigin()}/album/${albumId}?s=${songId}` } -export function playlistShareUrl( +function playlistShareUrl( playlistId: string, options?: { isFavorites?: boolean } ) { @@ -31,11 +31,11 @@ export function playlistShareUrl( return `${mediaOrigin()}/playlist/${playlistId}` } -export function artistShareUrl(artistId: string) { +function artistShareUrl(artistId: string) { return `${mediaOrigin()}/artist/${artistId}` } -export function mediaShareUrl(share: MediaShareContext) { +function mediaShareUrl(share: MediaShareContext) { switch (share.type) { case "album": return albumShareUrl(share.albumId) @@ -50,7 +50,7 @@ export function mediaShareUrl(share: MediaShareContext) { } } -export async function copyTextToClipboard(text: string) { +async function copyTextToClipboard(text: string) { await navigator.clipboard.writeText(text) toast.success("Link Copied") } @@ -63,10 +63,6 @@ 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 +73,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/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/docker/entrypoint.sh b/docker/entrypoint.sh index c179357..39352e8 100644 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -46,22 +46,34 @@ stop() { } trap 'stop; exit 0' TERM INT +as_convex=(setpriv --reuid=convex --regid=convex --init-groups env HOME=/home/convex) + convex_cli() { ( cd "$FUNCTIONS_DIR" unset CONVEX_DEPLOYMENT CONVEX_DEPLOY_KEY CONVEX_SELF_HOSTED_URL="$BACKEND_URL" \ CONVEX_SELF_HOSTED_ADMIN_KEY="$admin_key" \ - "$NODE" node_modules/convex/bin/main.js "$@" + "${as_convex[@]}" "$NODE" node_modules/convex/bin/main.js "$@" ) } -# Only root (the backend) may read the database and instance secret. +# Only the convex user may read the database and instance secret. Volumes from +# images that ran the backend as root are still owned by root, and +# read_credentials.sh generates a new instance secret if it cannot read the old one. mkdir -p "$CONVEX_DATA_DIR" +find "$CONVEX_DATA_DIR" \( ! -user convex -o ! -group convex \) \ + -exec chown -h convex:convex {} + chmod 700 "$CONVEX_DATA_DIR" +# The web server writes HLS streams here and a Convex cron deletes stale ones. +mkdir -p /tmp/otunes +chown otunes:otunes /tmp/otunes +chmod -R g+rwX /tmp/otunes +chmod g+s,o-rwx /tmp/otunes + log "Starting Convex backend" -(cd /convex && umask 077 && exec ./run_backend.sh) & +(cd /convex && umask 077 && exec "${as_convex[@]}" ./run_backend.sh) & backend_pid=$! for _ in $(seq 1 120); do @@ -80,17 +92,24 @@ if ! curl -fsS "$BACKEND_URL/version" >/dev/null 2>&1; then exit 1 fi -admin_key=$(cd /convex && ./generate_admin_key.sh) +admin_key=$(cd /convex && umask 077 && "${as_convex[@]}" ./generate_admin_key.sh) log "Deploying Convex functions" convex_cli deploy --typecheck disable --codegen disable -if [ -z "$(convex_cli env get JWKS 2>/dev/null || true)" ]; then +# `env get` exits 0 with no output when the variable is unset. Any other failure +# must not be read as "no keys": regenerating them signs every user out. +if ! jwks=$(convex_cli env get JWKS); then + log "Could not read Convex Auth signing keys" + stop + exit 1 +fi +if [ -z "$jwks" ]; then log "Generating Convex Auth signing keys" "$NODE" /opt/otunes/generate-auth-keys.mjs | convex_cli env set --force fi -unset admin_key +unset admin_key jwks log "Starting web server" ( @@ -100,6 +119,8 @@ log "Starting web server" # Server-side Convex helpers fall back to this at runtime. The browser bundle # is built without it, so browsers still derive their own URL. export NEXT_PUBLIC_CONVEX_URL="$BACKEND_URL" + # Lets the convex group member delete stale HLS streams. + umask 0002 exec setpriv --reuid=otunes --regid=otunes --init-groups \ "$NODE" apps/web/server.js ) & diff --git a/packages/convex/convex/actions.ts b/packages/convex/convex/actions.ts index 41feab7..a70ee20 100644 --- a/packages/convex/convex/actions.ts +++ b/packages/convex/convex/actions.ts @@ -578,13 +578,6 @@ export const updateLibrary = action({ }, }) -export const cleanupHlsStreams = internalAction({ - args: {}, - handler: async () => { - return await cleanHlsStreamsOlderThan(HLS_MAX_IDLE_MS) - }, -}) - export const adminCleanupHlsStreams = action({ args: {}, handler: async (ctx) => { 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/library.ts b/packages/convex/convex/library.ts index 80df22b..65a2a23 100644 --- a/packages/convex/convex/library.ts +++ b/packages/convex/convex/library.ts @@ -8,7 +8,6 @@ import type { PaginationOptions, PaginationResult } from "convex/server" import type { BrowseAlbum, BrowseAlbumDetail, - BrowseAlbumSummary, BrowseAlbumTrack, BrowseArtist, BrowseArtistDetail, @@ -26,7 +25,6 @@ import type { export type { BrowseAlbum, BrowseAlbumDetail, - BrowseAlbumSummary, BrowseAlbumTrack, BrowseArtist, BrowseArtistDetail, @@ -224,7 +222,7 @@ export const browseArtists = query({ }, }) -export function paginateSlice( +function paginateSlice( items: T[], paginationOpts: PaginationOptions ): PaginationResult { @@ -280,27 +278,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"), @@ -545,72 +522,6 @@ 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) - }, -}) - export const browseArtistDetail = query({ args: { id: v.id("artists") }, handler: async (ctx, args) => { @@ -908,16 +819,6 @@ export const getAlbums = internalQuery({ }, }) -export const getAlbumsInArtist = internalQuery({ - args: { artistID: v.id("artists") }, - handler: async (ctx, args) => { - return await ctx.db - .query("albums") - .withIndex("by_artist", (q) => q.eq("artist", args.artistID)) - .collect() - }, -}) - export const getSongs = internalQuery({ args: {}, handler: async (ctx) => { @@ -925,26 +826,6 @@ export const getSongs = internalQuery({ }, }) -export const getSongsInArtist = internalQuery({ - args: { artistID: v.id("artists") }, - handler: async (ctx, args) => { - return await ctx.db - .query("songs") - .withIndex("by_artist", (q) => q.eq("albumArtist", args.artistID)) - .collect() - }, -}) - -export const getSongsInAlbum = internalQuery({ - args: { albumID: v.id("albums") }, - handler: async (ctx, args) => { - return await ctx.db - .query("songs") - .withIndex("by_album", (q) => q.eq("album", args.albumID)) - .collect() - }, -}) - export const getArtist = query({ args: { id: v.id("artists") }, handler: async (ctx, args) => { @@ -952,16 +833,6 @@ export const getArtist = query({ }, }) -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({ args: { id: v.id("albums") }, handler: async (ctx, args) => { @@ -969,28 +840,6 @@ export const getAlbum = query({ }, }) -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({ args: { id: v.id("playlists") }, handler: async (ctx, args) => { @@ -1175,49 +1024,6 @@ export const intentCatalogPage = query({ }, }) -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( @@ -1242,29 +1048,6 @@ export const createArtists = internalMutation({ }, }) -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({ args: { albums: v.array( @@ -1294,50 +1077,6 @@ export const createAlbums = internalMutation({ }, }) -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 }) - }, -}) - -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) - }, -}) - export const createSongs = internalMutation({ args: { songs: v.array( @@ -1485,13 +1224,6 @@ export const purgeArtistsFromUsers = internalMutation({ }, }) -export const removeArtist = internalMutation({ - args: { id: v.id("artists") }, - handler: async (ctx, args) => { - return await ctx.db.delete("artists", args.id) - }, -}) - export const removeArtists = internalMutation({ args: { ids: v.array(v.id("artists")) }, handler: async (ctx, args) => { @@ -1501,13 +1233,6 @@ export const removeArtists = internalMutation({ }, }) -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) => { @@ -1517,20 +1242,6 @@ export const removeAlbums = internalMutation({ }, }) -export const removeSong = internalMutation({ - args: { id: v.id("songs") }, - handler: async (ctx, args) => { - return await ctx.db.delete("songs", args.id) - }, -}) - -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 }) - }, -}) - export const changeFilesForSongs = internalMutation({ args: { songs: v.array( diff --git a/packages/convex/convex/playback.ts b/packages/convex/convex/playback.ts index 6dbfe23..246176f 100644 --- a/packages/convex/convex/playback.ts +++ b/packages/convex/convex/playback.ts @@ -1,17 +1,9 @@ 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 { MutationCtx } from "./_generated/server" import { mutation, query } from "./_generated/server" -import type { QueueSong } from "./types" -import { - browseSongsFromIds, - compareAlbumSongs, - getSortedLibrarySongIds, - songsSortDirectionValidator, - songsSortKeyValidator, -} from "./library" +import { browseSongsFromIds } from "./library" export type { HistorySong, QueueSong } from "./types" @@ -59,35 +51,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,54 +59,6 @@ async function requireAuth(ctx: MutationCtx) { return userId } -function uniqueSongIds(songIds: Id<"songs">[]) { - return [...new Set(songIds)] -} - -function haveSameSongCounts(first: Id<"songs">[], second: Id<"songs">[]) { - if (first.length !== second.length) { - return false - } - 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">, @@ -168,26 +83,6 @@ async function patchPlayback( 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 } - : {}), - }) -} - export const getPlaybackState = query({ args: {}, handler: async (ctx) => { @@ -264,554 +159,6 @@ 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, - }) - }, -}) - -export const getSongProgress = query({ - args: {}, - handler: async (ctx) => { - const userId = await getAuthUserId(ctx) - if (userId === null) { - 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 - }, -}) - export const updateSongProgress = mutation({ args: { songId: v.id("songs"), diff --git a/packages/convex/convex/playlists.ts b/packages/convex/convex/playlists.ts index 6b4bd76..c763a67 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,7 @@ import type { PlaylistSummary, SidebarPlaylists, } from "./library" -import { browseSongsFromIds, compareAlbumSongs, paginateSlice } from "./library" +import { browseSongsFromIds, compareAlbumSongs } from "./library" function toPlaylistSummary( playlist: Doc<"playlists">, @@ -109,23 +108,15 @@ async function browsePlaylistSummaryHandler( } } -export const browsePlaylistSummary = query({ - args: { id: v.id("playlists") }, - handler: async (ctx, args) => browsePlaylistSummaryHandler(ctx, args.id), -}) - 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 +130,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) => { diff --git a/packages/convex/convex/types.ts b/packages/convex/convex/types.ts index 6aee22a..8b8a432 100644 --- a/packages/convex/convex/types.ts +++ b/packages/convex/convex/types.ts @@ -41,10 +41,6 @@ export type BrowseAlbumDetail = BrowseAlbum & { tracks: BrowseAlbumTrack[] } -export type BrowseAlbumSummary = Omit & { - trackCount: number -} - export type BrowseArtistDetail = { artist: BrowseArtist albums: BrowseAlbum[]