Compare commits

..
90 changed files with 4316 additions and 4944 deletions

No files matched your search

+6 -5
View File
@@ -54,11 +54,12 @@ playwright.config.*
*~ *~
*.log *.log
# Environment variables, in any workspace. Next.js inlines NEXT_PUBLIC_* values # Environment variables (only commit template files)
# into the bundle and the Convex CLI reads .env.local on deploy. .env
**/.env .env*.local
**/.env.* .env.development
!**/.env.example .env.test
.env.production.local
# Docker configuration files (not needed inside build context) # Docker configuration files (not needed inside build context)
Dockerfile* Dockerfile*
+1 -6
View File
@@ -195,12 +195,7 @@ RUN node --version \
&& ldd /convex/generate_key \ && ldd /convex/generate_key \
&& ! ldd /convex/convex-local-backend /convex/generate_key | grep -q 'not found' && ! ldd /convex/convex-local-backend /convex/generate_key | grep -q 'not found'
# The backend gets its own user so the web server cannot read the database or RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes
# 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 --from=convex-functions /app /opt/otunes/convex
COPY docker/generate-auth-keys.mjs /opt/otunes/generate-auth-keys.mjs COPY docker/generate-auth-keys.mjs /opt/otunes/generate-auth-keys.mjs
@@ -0,0 +1 @@
export { default } from "../library/queue"
@@ -1,8 +1,3 @@
import { SongSwipeRow } from "@/components/song-swipe-row"
import {
useSwipeRowGroup,
type SwipeRowGroup,
} from "@/components/ios-swipe-to-remove-row"
import { import {
CollectionHero, CollectionHero,
useCollectionHeroLayout, useCollectionHeroLayout,
@@ -35,7 +30,7 @@ import {
MediaActionMenu, MediaActionMenu,
MediaContextMenu, MediaContextMenu,
type MediaAction, type MediaAction,
} from "@/components/media-context-menu" } from "@/components/media-actions-sheet"
import { CollectionDetailSkeleton } from "@/components/skeletons" import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives" import { Button } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player" import { contentBottomInset } from "@/components/player"
@@ -73,7 +68,6 @@ export default function AlbumScreen() {
handleAlbumTrackAction, handleAlbumTrackAction,
isAlbumFavorite: isAlbumFav, isAlbumFavorite: isAlbumFav,
} = useMediaMenuActions() } = useMediaMenuActions()
const swipeGroup = useSwipeRowGroup()
const isFocused = useIsFocused() const isFocused = useIsFocused()
const coverUri = const coverUri =
config && typeof id === "string" ? albumCoverUrl(config.serverUrl, id) : "" config && typeof id === "string" ? albumCoverUrl(config.serverUrl, id) : ""
@@ -118,7 +112,6 @@ export default function AlbumScreen() {
} }
return album ? ( return album ? (
<AlbumTrackRow <AlbumTrackRow
swipeGroup={swipeGroup}
track={item.track} track={item.track}
number={item.number} number={item.number}
album={album} album={album}
@@ -139,7 +132,6 @@ export default function AlbumScreen() {
palette, palette,
playFromSong, playFromSong,
songIds, songIds,
swipeGroup,
] ]
) )
@@ -243,7 +235,6 @@ export default function AlbumScreen() {
}} }}
/> />
<Animated.FlatList <Animated.FlatList
onScrollBeginDrag={swipeGroup.closeOpenRow}
onLayout={onLayout} onLayout={onLayout}
{...longListProps} {...longListProps}
data={listItems} data={listItems}
@@ -465,7 +456,6 @@ function albumListItemKey(item: AlbumListItem) {
const AlbumTrackRow = memo(function AlbumTrackRow({ const AlbumTrackRow = memo(function AlbumTrackRow({
track, track,
swipeGroup,
number, number,
album, album,
songIds, songIds,
@@ -475,7 +465,6 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
onAction, onAction,
}: { }: {
track: BrowseAlbumTrack track: BrowseAlbumTrack
swipeGroup: SwipeRowGroup
number: number number: number
album: BrowseAlbumDetail album: BrowseAlbumDetail
songIds: Id<"songs">[] songIds: Id<"songs">[]
@@ -488,22 +477,8 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
action: MediaAction action: MediaAction
) => Promise<void> ) => Promise<void>
}) { }) {
const Row = Platform.OS !== "web" ? SongSwipeRow : Pressable
const { config } = useServerConfig()
return ( return (
<MediaContextMenu <MediaContextMenu
preview={
config
? {
kind: "song",
title: track.title,
artist: album.artist.name,
album: album.title,
artworkUrl: albumCoverUrl(config.serverUrl, album.id),
hasArtwork: album.cover != null,
}
: undefined
}
stationArtistId={album.artist.id} stationArtistId={album.artist.id}
favorited={favorited} favorited={favorited}
navigation={{ navigation={{
@@ -519,11 +494,7 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
onAction={(action) => void onAction(track, album, action)} onAction={(action) => void onAction(track, album, action)}
> >
<MusicEntityView kind="song" id={track.id}> <MusicEntityView kind="song" id={track.id}>
<Row <Pressable
group={swipeGroup}
backgroundColor={palette.background}
onPlayNext={() => void onAction(track, album, "play-next")}
onAddToQueue={() => void onAction(track, album, "play-last")}
style={styles.trackRow} style={styles.trackRow}
onPress={() => void onPlay(track.id as Id<"songs">, songIds)} onPress={() => void onPlay(track.id as Id<"songs">, songIds)}
> >
@@ -564,7 +535,7 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
{formatDuration(track.durationSeconds)} {formatDuration(track.durationSeconds)}
</PaletteText> </PaletteText>
</View> </View>
</Row> </Pressable>
</MusicEntityView> </MusicEntityView>
</MediaContextMenu> </MediaContextMenu>
) )
@@ -6,7 +6,7 @@ import { Ionicons } from "@expo/vector-icons"
import { CoverImage } from "@/components/cover-image" import { CoverImage } from "@/components/cover-image"
import { MediaGridList } from "@/components/media-cards" import { MediaGridList } from "@/components/media-cards"
import { MediaActionMenu } from "@/components/media-context-menu" import { MediaActionMenu } from "@/components/media-actions-sheet"
import { CollectionDetailSkeleton } from "@/components/skeletons" import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives" import { Button } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player" import { contentBottomInset } from "@/components/player"
@@ -141,12 +141,6 @@ const ArtistRow = memo(function ArtistRow({
return ( return (
<MediaContextMenu <MediaContextMenu
preview={{
kind: "artist",
title: artist.name,
artworkUrl: artistCoverUrl(serverUrl, artist.id),
hasArtwork: artist.photo != null,
}}
favorited={favorited} favorited={favorited}
share={{ type: "artist", artistId: artist.id, title: artist.name }} share={{ type: "artist", artistId: artist.id, title: artist.name }}
onAction={(action) => void onAction(artist, action)} onAction={(action) => void onAction(artist, action)}
@@ -166,11 +160,7 @@ const ArtistRow = memo(function ArtistRow({
> >
{artist.name} {artist.name}
</Text> </Text>
<Ionicons <Ionicons name="chevron-forward" size={16} color={colors.mutedForeground} />
name="chevron-forward"
size={16}
color={colors.mutedForeground}
/>
</Pressable> </Pressable>
</MediaContextMenu> </MediaContextMenu>
) )
@@ -39,6 +39,7 @@ import ReanimatedSwipeable from "react-native-gesture-handler/ReanimatedSwipeabl
import { CollectionDivider } from "@/components/collection-list" import { CollectionDivider } from "@/components/collection-list"
import { CoverImage } from "@/components/cover-image" import { CoverImage } from "@/components/cover-image"
import { import {
SwipeToRemoveRow,
useSwipeRowGroup, useSwipeRowGroup,
type SwipeRowGroup, type SwipeRowGroup,
} from "@/components/ios-swipe-to-remove-row" } from "@/components/ios-swipe-to-remove-row"
@@ -46,7 +47,7 @@ import {
import { import {
MediaActionMenu, MediaActionMenu,
type MediaAction, type MediaAction,
} from "@/components/media-context-menu" } from "@/components/media-actions-sheet"
import { CollectionDetailSkeleton } from "@/components/skeletons" import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives" import { Button } from "@/components/ui/primitives"
import { contentBottomInset, SongListRow } from "@/components/player" import { contentBottomInset, SongListRow } from "@/components/player"
@@ -314,6 +315,7 @@ function PlaylistContent({
deletePlaylist, deletePlaylist,
handlePlaylistDetailAction, handlePlaylistDetailAction,
palette.foreground, palette.foreground,
palette.background,
palette.isDark, palette.isDark,
playlistId, playlistId,
playlist?.title, playlist?.title,
@@ -432,31 +434,28 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
playlistLabel={PLAYLIST_LABEL} playlistLabel={PLAYLIST_LABEL}
palette={palette} palette={palette}
inset inset
swipe={
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
}
onPlay={onPlay} onPlay={onPlay}
onAction={onAction} onAction={onAction}
/> />
) )
if (Platform.OS !== "web" || !removable) { if (!removable) {
return row return row
} }
if (Platform.OS === "ios") {
return (
<SwipeToRemoveRow
group={swipeGroup}
backgroundColor={palette.background}
actionAccessibilityLabel={`Remove ${song.title} from playlist`}
onRemove={handleRemove}
>
{row}
</SwipeToRemoveRow>
)
}
return ( return (
<ReanimatedSwipeable <ReanimatedSwipeable
friction={2} friction={2}
+186
View File
@@ -0,0 +1,186 @@
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<QueueItem, "key"> & {
isLast: boolean
isCurrent: boolean
onSkipTo: (index: number) => void
onMove: (index: number, direction: -1 | 1) => void
}) {
const colors = useThemeColors()
const song = useSong(songId)
return (
<View>
{song ? (
<SongRow song={song} onPress={() => onSkipTo(queueIndex)} />
) : (
<SongRowSkeleton />
)}
<View style={styles.queueActions}>
<Pressable
disabled={queueIndex === 0}
onPress={() => onMove(queueIndex, -1)}
>
<Text style={{ color: colors.foreground }}>Move up</Text>
</Pressable>
<Pressable disabled={isLast} onPress={() => onMove(queueIndex, 1)}>
<Text style={{ color: colors.foreground }}>Move down</Text>
</Pressable>
{isCurrent ? (
<Text style={{ color: colors.primary, fontWeight: "700" }}>
Now playing
</Text>
) : null}
</View>
</View>
)
})
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<QueueItem[]>(() => {
const occurrences = new Map<string, number>()
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 (
<>
<Stack.Screen
options={{
headerRight: () =>
queueSongIds.length > 0 ? (
<Button
title="Clear"
variant="ghost"
onPress={handleClearQueue}
/>
) : null,
}}
/>
<FlatList
style={{ flex: 1, backgroundColor: colors.background }}
ListHeaderComponent={
<View>
<Text style={[styles.section, { color: colors.mutedForeground }]}>
Up Next
</Text>
{queueSongIds.length === 0 ? (
<Text style={[styles.empty, { color: colors.mutedForeground }]}>
Queue is empty
</Text>
) : null}
</View>
}
{...longListProps}
data={items}
keyExtractor={queueItemKey}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
renderItem={({ item }) => (
<QueueRow
songId={item.songId}
queueIndex={item.queueIndex}
isLast={item.queueIndex === queueSongIds.length - 1}
isCurrent={item.queueIndex === 0}
onSkipTo={skipToQueueIndex}
onMove={moveSong}
/>
)}
ListFooterComponent={
queueHistorySongIds.length > 0 ? (
<View style={styles.history}>
<Text style={[styles.section, { color: colors.mutedForeground }]}>
History
</Text>
{historySongs.map((song, index) =>
song ? (
<SongRow key={`${song.id}-${index}`} song={song} />
) : (
<SongRowSkeleton
key={`${queueHistorySongIds[index]}-${index}`}
/>
)
)}
</View>
) : undefined
}
/>
</>
)
}
const styles = StyleSheet.create({
section: {
paddingHorizontal: spacing.lg,
paddingTop: spacing.md,
fontSize: 12,
fontWeight: "700",
textTransform: "uppercase",
},
empty: { padding: spacing.lg },
queueActions: {
flexDirection: "row",
gap: spacing.lg,
paddingHorizontal: spacing.lg,
paddingBottom: spacing.sm,
},
history: { marginTop: spacing.lg },
})
@@ -23,10 +23,10 @@ import { useServerConfig } from "@/contexts/server-config"
import { import {
setArtworkColorsEnabled, setArtworkColorsEnabled,
useArtworkColorsEnabled, useArtworkColorsEnabled,
useArtworkColorPreferenceLoaded,
} from "@/lib/artwork-color-preference" } from "@/lib/artwork-color-preference"
import { initialsFromName } from "@/lib/format" import { initialsFromName } from "@/lib/format"
import { useCachedQuery } from "@/hooks/use-cached-query" import { useCachedQuery } from "@/hooks/use-cached-query"
import { useProfileImageUrl } from "@/hooks/use-profile-image-url"
import { changeServer, signOut } from "@/lib/session" import { changeServer, signOut } from "@/lib/session"
import { radius, spacing, useThemeColors } from "@/lib/theme" import { radius, spacing, useThemeColors } from "@/lib/theme"
import { showError } from "@/lib/toast" import { showError } from "@/lib/toast"
@@ -172,6 +172,7 @@ export default function SettingsScreen() {
function AppearanceSection() { function AppearanceSection() {
const enabled = useArtworkColorsEnabled() const enabled = useArtworkColorsEnabled()
const loaded = useArtworkColorPreferenceLoaded()
const [saving, setSaving] = useState(false) const [saving, setSaving] = useState(false)
return ( return (
@@ -179,8 +180,8 @@ function AppearanceSection() {
<SwitchRow <SwitchRow
title="New artwork colors" title="New artwork colors"
subtitle="Use the new color algorithm on this device." subtitle="Use the new color algorithm on this device."
value={enabled ?? false} value={enabled}
disabled={enabled === undefined || saving} disabled={!loaded || saving}
onValueChange={async (checked) => { onValueChange={async (checked) => {
setSaving(true) setSaving(true)
try { try {
@@ -769,7 +770,6 @@ function ProfileAvatar({
style?: StyleProp<ViewStyle> style?: StyleProp<ViewStyle>
}) { }) {
const colors = useThemeColors() const colors = useThemeColors()
const imageUrl = useProfileImageUrl(user.image)
const avatarStyle = [ const avatarStyle = [
styles.avatar, styles.avatar,
{ {
@@ -781,11 +781,11 @@ function ProfileAvatar({
style, style,
] ]
if (imageUrl) { if (user.image) {
return ( return (
<View style={avatarStyle}> <View style={avatarStyle}>
<Image <Image
source={{ uri: imageUrl }} source={{ uri: user.image }}
style={styles.avatarImage} style={styles.avatarImage}
contentFit="cover" contentFit="cover"
/> />
@@ -0,0 +1 @@
export { default } from "../home/queue"
@@ -0,0 +1 @@
export { default } from "../home/queue"
+8 -18
View File
@@ -39,12 +39,11 @@ import { MarqueeText } from "@/components/marquee-text"
import { import {
MediaActionMenu, MediaActionMenu,
type MediaAction, type MediaAction,
} from "@/components/media-context-menu" } from "@/components/media-actions-sheet"
import { import {
NowPlayingQueue, NowPlayingQueue,
QUEUE_HORIZONTAL_INSET, QUEUE_HORIZONTAL_INSET,
} from "@/components/now-playing-queue" } from "@/components/now-playing-queue"
import { PlayerArtistMenu } from "@/components/player-artist-menu"
import { PlayerSlider } from "@/components/player-slider" import { PlayerSlider } from "@/components/player-slider"
import { PlayerSymbol } from "@/components/player-symbol" import { PlayerSymbol } from "@/components/player-symbol"
import { useFavorites } from "@/contexts/favorites" import { useFavorites } from "@/contexts/favorites"
@@ -545,15 +544,13 @@ function SongMeta({
{ color: colors.foreground }, { color: colors.foreground },
]} ]}
/> />
<PlayerArtistMenu song={song} onAction={handleAction}> <MarqueeText
<MarqueeText text={song.artist.name}
text={song.artist.name} style={[
style={[ compact ? styles.compactArtist : styles.artist,
compact ? styles.compactArtist : styles.artist, { color: colors.secondaryForeground },
{ color: colors.secondaryForeground }, ]}
]} />
/>
</PlayerArtistMenu>
</View> </View>
<Pressable <Pressable
onPress={() => void toggleSongFavorite(song.id)} onPress={() => void toggleSongFavorite(song.id)}
@@ -570,12 +567,6 @@ function SongMeta({
/> />
</Pressable> </Pressable>
<MediaActionMenu <MediaActionMenu
share={{
type: "song",
songId: song.id,
albumId: song.album.id,
title: song.title,
}}
stationArtistId={song.artist.id} stationArtistId={song.artist.id}
favorited={favorited} favorited={favorited}
navigation={{ navigation={{
@@ -583,7 +574,6 @@ function SongMeta({
album: { id: song.album.id }, album: { id: song.album.id },
}} }}
includeActions={[ includeActions={[
"share",
"play-next", "play-next",
"play-last", "play-last",
"shuffle", "shuffle",
@@ -0,0 +1,7 @@
export type { MediaAction, MediaMenuConfig, MediaNavigation } from "@/components/media-context-menu"
export type { MediaShareContext } from "@/lib/media-links"
export {
buildMediaMenuActions,
MediaActionMenu,
MediaContextMenu,
} from "@/components/media-context-menu"
-13
View File
@@ -94,13 +94,6 @@ export const AlbumCard = memo(function AlbumCard({
return ( return (
<MediaContextMenu <MediaContextMenu
preview={{
kind: "album",
title: album.title,
artist: album.artist.name,
artworkUrl: albumCoverUrl(config.serverUrl, album.id),
hasArtwork: album.cover != null,
}}
favorited={isAlbumFavorite(album.id)} favorited={isAlbumFavorite(album.id)}
stationArtistId={album.artist.id} stationArtistId={album.artist.id}
navigation={{ artist: { id: album.artist.id } }} navigation={{ artist: { id: album.artist.id } }}
@@ -156,12 +149,6 @@ export const ArtistCard = memo(function ArtistCard({
return ( return (
<MediaContextMenu <MediaContextMenu
preview={{
kind: "artist",
title: artist.name,
artworkUrl: artistCoverUrl(config.serverUrl, artist.id),
hasArtwork: artist.photo != null,
}}
favorited={isArtistFavorite(artist.id)} favorited={isArtistFavorite(artist.id)}
share={{ type: "artist", artistId: artist.id, title: artist.name }} share={{ type: "artist", artistId: artist.id, title: artist.name }}
onAction={(action) => void handleArtistAction(artist, action)} onAction={(action) => void handleArtistAction(artist, action)}
+4 -119
View File
@@ -4,19 +4,12 @@ import { requireNativeView } from "expo"
import type { ComponentType, ReactNode } from "react" import type { ComponentType, ReactNode } from "react"
import { import {
Platform, Platform,
Text,
useWindowDimensions,
View, View,
type StyleProp, type StyleProp,
type ViewProps, type ViewProps,
type ViewStyle, type ViewStyle,
} from "react-native" } from "react-native"
import { Ionicons } from "@expo/vector-icons"
import { CoverImage } from "@/components/cover-image"
import { useThemeColors } from "@/lib/theme"
import { useAppNavigation } from "@/lib/app-navigation"
import { useServerConfig } from "@/contexts/server-config" import { useServerConfig } from "@/contexts/server-config"
import type { MediaShareContext } from "@/lib/media-links" import type { MediaShareContext } from "@/lib/media-links"
import { shouldShowShare } from "@/lib/media-links" import { shouldShowShare } from "@/lib/media-links"
@@ -39,17 +32,7 @@ export type MediaNavigation = {
album?: { id: string } album?: { id: string }
} }
export type MediaMenuPreview = {
title: string
artist?: string
album?: string
artworkUrl: string
hasArtwork: boolean
kind: "album" | "artist" | "song"
}
export type MediaMenuConfig = { export type MediaMenuConfig = {
preview?: MediaMenuPreview
selectedCount?: number selectedCount?: number
playlistLabel?: string playlistLabel?: string
favorited?: boolean favorited?: boolean
@@ -106,12 +89,12 @@ const MEDIA_ACTION_ITEMS: {
{ {
action: "go-artist", action: "go-artist",
label: () => "Go to Artist", label: () => "Go to Artist",
image: "music.mic", image: "person",
}, },
{ {
action: "go-album", action: "go-album",
label: () => "Go to Album", label: () => "Go to Album",
image: "square.stack", image: "opticaldisc",
}, },
{ {
action: "favorite", action: "favorite",
@@ -231,95 +214,10 @@ function MediaMenuBase({
const NativeContextMenuView = const NativeContextMenuView =
Platform.OS === "ios" Platform.OS === "ios"
? requireNativeView< ? requireNativeView<
ViewProps & { ViewProps & { disableForceFlatten?: boolean; children: ReactNode }
disableForceFlatten?: boolean
children: ReactNode
onPreviewTappedAnimationCompleted?: () => void
}
>("ExpoRouterNativeLinkPreview", "NativeLinkPreviewView") >("ExpoRouterNativeLinkPreview", "NativeLinkPreviewView")
: null : null
const NativeContextMenuPreview =
Platform.OS === "ios"
? requireNativeView<
ViewProps & {
preferredContentSize: { width: number; height: number }
children: ReactNode
}
>("ExpoRouterNativeLinkPreview", "NativeLinkPreviewContentView")
: null
function MediaPreview({ preview }: { preview: MediaMenuPreview }) {
const colors = useThemeColors()
const { width: windowWidth, fontScale } = useWindowDimensions()
if (!NativeContextMenuPreview) return null
const width = Math.min(360, windowWidth - 32)
const height = Math.max(124, 32 + 76 * fontScale)
const isArtist = preview.kind === "artist"
return (
// Match Expo Router's preview wrapper: UIKit mounts this separately, but
// Yoga must also keep it out of the trigger's normal layout.
<NativeContextMenuPreview
preferredContentSize={{ width, height }}
style={{ position: "absolute", top: 0, left: 0 }}
>
<View
style={{
width,
height,
padding: 16,
flexDirection: "row",
alignItems: "center",
gap: 16,
backgroundColor: colors.card,
}}
>
<CoverImage
uri={preview.artworkUrl}
hasCover={preview.hasArtwork}
style={{ width: 88, height: 88, borderRadius: isArtist ? 44 : 12 }}
/>
<View style={{ flex: 1, gap: 2 }}>
<Text
numberOfLines={2}
style={{
color: colors.foreground,
fontSize: 17,
fontWeight: "600",
}}
>
{preview.title}
</Text>
{preview.artist ? (
<Text
numberOfLines={1}
style={{ color: colors.mutedForeground, fontSize: 15 }}
>
{preview.artist}
</Text>
) : null}
{preview.album ? (
<Text
numberOfLines={1}
style={{ color: colors.mutedForeground, fontSize: 14 }}
>
{preview.album}
</Text>
) : null}
</View>
{preview.kind !== "song" ? (
<Ionicons
name="chevron-forward"
size={20}
color={colors.mutedForeground}
/>
) : null}
</View>
</NativeContextMenuPreview>
)
}
const NativeContextMenuAction: ComponentType<{ const NativeContextMenuAction: ComponentType<{
identifier: string identifier: string
title: string title: string
@@ -335,13 +233,11 @@ const NativeContextMenuAction: ComponentType<{
function NativeMediaContextMenu({ function NativeMediaContextMenu({
children, children,
preview,
onAction, onAction,
share, share,
...actionConfig ...actionConfig
}: MediaMenuWrapperProps) { }: MediaMenuWrapperProps) {
const { config } = useServerConfig() const { config } = useServerConfig()
const { push } = useAppNavigation()
if (!NativeContextMenuView || !NativeContextMenuAction) { if (!NativeContextMenuView || !NativeContextMenuAction) {
return children return children
@@ -356,21 +252,10 @@ function NativeMediaContextMenu({
} }
return ( return (
<NativeContextMenuView <NativeContextMenuView style={{ display: "contents" }} disableForceFlatten>
style={{ display: "contents" }}
disableForceFlatten
onPreviewTappedAnimationCompleted={() => {
if (share?.type === "artist") push(`/artist/${share.artistId}`)
else if (share?.type === "album" || share?.type === "song")
push(`/album/${share.albumId}`)
}}
>
{/* The native menu retains its first trigger. Keep that view mounted when {/* The native menu retains its first trigger. Keep that view mounted when
focus changes replace the Siri entity wrapper inside it. */} focus changes replace the Siri entity wrapper inside it. */}
<View collapsable={false}>{children}</View> <View collapsable={false}>{children}</View>
{preview && (actionConfig.selectedCount ?? 1) === 1 ? (
<MediaPreview preview={preview} />
) : null}
{buildMediaMenuActions({ ...actionConfig, share }).map((action) => ( {buildMediaMenuActions({ ...actionConfig, share }).map((action) => (
<NativeContextMenuAction <NativeContextMenuAction
key={action.id} key={action.id}
-45
View File
@@ -1,45 +0,0 @@
import type { MenuComponentProps } from "@expo/ui/community/menu"
import { Button, Host, Menu, RNHostView } from "@expo/ui/swift-ui"
import { disabled, menuOrder } from "@expo/ui/swift-ui/modifiers"
// SwiftUI's automatic order reverses menus that open upward in the player.
// Keep the same top-to-bottom order as the UIKit long-press menus.
export function MenuView({
actions,
children,
style,
testID,
onPressAction,
}: MenuComponentProps) {
return (
<Host matchContents style={style} testID={testID} ignoreSafeArea="all">
<Menu
modifiers={[menuOrder("fixed")]}
label={
<RNHostView matchContents>
<>{children}</>
</RNHostView>
}
>
{actions
.filter((action) => !action.attributes?.hidden)
.map((action) => (
<Button
key={action.id ?? action.title}
label={action.title}
systemImage={
typeof action.image === "string" ? action.image : undefined
}
role={action.attributes?.destructive ? "destructive" : undefined}
modifiers={[disabled(action.attributes?.disabled ?? false)]}
onPress={() =>
onPressAction?.({
nativeEvent: { event: action.id ?? action.title },
})
}
/>
))}
</Menu>
</Host>
)
}
@@ -1,56 +0,0 @@
import { useState, type ReactNode } from "react"
import { StyleSheet, View } from "react-native"
import {
MediaActionMenu,
type MediaAction,
} from "@/components/media-context-menu"
import type { BrowseSong } from "@otunes/convex/types"
export function PlayerArtistMenu({
song,
onAction,
children,
}: {
song: BrowseSong
onAction: (action: MediaAction) => void
children: ReactNode
}) {
const [size, setSize] = useState({ width: 0, height: 0 })
return (
<View
style={styles.container}
onLayout={({ nativeEvent: { layout } }) =>
setSize({ width: layout.width, height: layout.height })
}
>
<View
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
>
{children}
</View>
{size.width > 0 ? (
<MediaActionMenu
style={StyleSheet.absoluteFill}
includeActions={["go-album", "go-artist"]}
onAction={onAction}
>
<View
style={size}
accessible
accessibilityRole="button"
accessibilityLabel={song.artist.name}
accessibilityHint="Opens album and artist options"
/>
</MediaActionMenu>
) : null}
</View>
)
}
const styles = StyleSheet.create({
container: { overflow: "hidden" },
})
+8 -60
View File
@@ -1,5 +1,3 @@
import { SongSwipeRow } from "@/components/song-swipe-row"
import type { SwipeRowGroup } from "@/components/ios-swipe-to-remove-row"
import { PaletteText } from "@/components/palette-text" import { PaletteText } from "@/components/palette-text"
import { MusicEntityView } from "@/components/music-entity-view" import { MusicEntityView } from "@/components/music-entity-view"
import { collectionInset } from "@/components/collection-list" import { collectionInset } from "@/components/collection-list"
@@ -24,8 +22,6 @@ import {
type MediaMenuConfig, type MediaMenuConfig,
} from "@/components/media-context-menu" } from "@/components/media-context-menu"
function consumeLongPress() {}
export const SongRow = memo(function SongRow({ export const SongRow = memo(function SongRow({
song, song,
onPress, onPress,
@@ -33,7 +29,6 @@ export const SongRow = memo(function SongRow({
trailing, trailing,
palette, palette,
inset = false, inset = false,
swipe,
}: { }: {
song: BrowseSong song: BrowseSong
onPress?: () => void onPress?: () => void
@@ -42,13 +37,6 @@ export const SongRow = memo(function SongRow({
} }
trailing?: React.ReactNode trailing?: React.ReactNode
palette?: Pick<CoverPalette, "foreground" | "secondaryForeground" | "divider"> palette?: Pick<CoverPalette, "foreground" | "secondaryForeground" | "divider">
swipe?: {
group: SwipeRowGroup
onPlayNext: () => void
onAddToQueue: () => void
onRemove?: () => void
backgroundColor: string
}
/** Album/playlist layout: the divider starts at the title, not the artwork. */ /** Album/playlist layout: the divider starts at the title, not the artwork. */
inset?: boolean inset?: boolean
}) { }) {
@@ -89,8 +77,13 @@ export const SongRow = memo(function SongRow({
</> </>
) )
const rowContent = ( const row = (
<> <Pressable
style={
inset ? styles.insetRow : [styles.row, { borderBottomColor: divider }]
}
onPress={onPress}
>
<CoverImage <CoverImage
uri={albumCoverUrl(config.serverUrl, song.album.id)} uri={albumCoverUrl(config.serverUrl, song.album.id)}
hasCover={song.album.cover != null} hasCover={song.album.cover != null}
@@ -103,33 +96,8 @@ export const SongRow = memo(function SongRow({
) : ( ) : (
content content
)} )}
</> </Pressable>
) )
const rowStyle = inset
? styles.insetRow
: [styles.row, { borderBottomColor: divider }]
const row =
swipe && Platform.OS !== "web" ? (
<SongSwipeRow
group={swipe.group}
onPlayNext={swipe.onPlayNext}
onAddToQueue={swipe.onAddToQueue}
onRemove={swipe.onRemove}
backgroundColor={swipe.backgroundColor}
onPress={onPress}
style={rowStyle}
>
{rowContent}
</SongSwipeRow>
) : (
<Pressable
style={rowStyle}
onPress={onPress}
onLongPress={contextMenu ? consumeLongPress : undefined}
>
{rowContent}
</Pressable>
)
if (!contextMenu) { if (!contextMenu) {
return ( return (
@@ -159,7 +127,6 @@ export const SongListRow = memo(function SongListRow({
playlistLabel, playlistLabel,
palette, palette,
inset, inset,
swipe,
onPlay, onPlay,
onAction, onAction,
}: { }: {
@@ -168,17 +135,9 @@ export const SongListRow = memo(function SongListRow({
playlistLabel?: string playlistLabel?: string
palette?: Pick<CoverPalette, "foreground" | "secondaryForeground" | "divider"> palette?: Pick<CoverPalette, "foreground" | "secondaryForeground" | "divider">
inset?: boolean inset?: boolean
swipe?: {
group: SwipeRowGroup
onPlayNext: () => void
onAddToQueue: () => void
onRemove?: () => void
backgroundColor: string
}
onPlay: (song: BrowseSong) => void onPlay: (song: BrowseSong) => void
onAction: (song: BrowseSong, action: MediaAction) => void onAction: (song: BrowseSong, action: MediaAction) => void
}) { }) {
const { config } = useServerConfig()
const handlePress = useCallback(() => onPlay(song), [onPlay, song]) const handlePress = useCallback(() => onPlay(song), [onPlay, song])
return ( return (
@@ -186,19 +145,8 @@ export const SongListRow = memo(function SongListRow({
song={song} song={song}
palette={palette} palette={palette}
inset={inset} inset={inset}
swipe={swipe}
onPress={handlePress} onPress={handlePress}
contextMenu={{ contextMenu={{
preview: config
? {
kind: "song",
title: song.title,
artist: song.artist.name,
album: song.album.title,
artworkUrl: albumCoverUrl(config.serverUrl, song.album.id),
hasArtwork: song.album.cover != null,
}
: undefined,
stationArtistId: song.artist.id, stationArtistId: song.artist.id,
favorited, favorited,
playlistLabel, playlistLabel,
@@ -4,7 +4,6 @@ import { Image } from "expo-image"
import { Pressable, StyleSheet, Text, View } from "react-native" import { Pressable, StyleSheet, Text, View } from "react-native"
import { useCachedQuery } from "@/hooks/use-cached-query" import { useCachedQuery } from "@/hooks/use-cached-query"
import { useProfileImageUrl } from "@/hooks/use-profile-image-url"
import { initialsFromName } from "@/lib/format" import { initialsFromName } from "@/lib/format"
import { radius, useThemeColors } from "@/lib/theme" import { radius, useThemeColors } from "@/lib/theme"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
@@ -14,7 +13,6 @@ export function ProfileHeaderButton() {
const openSettings = useOpenSettings() const openSettings = useOpenSettings()
const colors = useThemeColors() const colors = useThemeColors()
const user = useCachedQuery(api.auth.currentUser) const user = useCachedQuery(api.auth.currentUser)
const imageUrl = useProfileImageUrl(user?.image)
if (tabletLayout) return null if (tabletLayout) return null
@@ -35,9 +33,9 @@ export function ProfileHeaderButton() {
}, },
]} ]}
> >
{imageUrl ? ( {user?.image ? (
<Image <Image
source={{ uri: imageUrl }} source={{ uri: user.image }}
style={styles.image} style={styles.image}
contentFit="cover" contentFit="cover"
/> />
-461
View File
@@ -1,461 +0,0 @@
import { Ionicons } from "@expo/vector-icons"
import * as Haptics from "expo-haptics"
import { SymbolView } from "expo-symbols"
import {
useCallback,
useEffect,
useMemo,
useState,
type ReactNode,
} from "react"
import {
Platform,
Pressable,
StyleSheet,
type StyleProp,
type ViewStyle,
} from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import Animated, {
type SharedValue,
cancelAnimation,
Extrapolation,
interpolate,
useAnimatedStyle,
useSharedValue,
withSpring,
} from "react-native-reanimated"
import { scheduleOnRN } from "react-native-worklets"
import type { SwipeRowGroup } from "@/components/ios-swipe-to-remove-row"
const IS_ANDROID = Platform.OS === "android"
const ACTION_WIDTH = 82
const LEADING_ACTION_WIDTH = 72
const SPRING = { duration: 450, dampingRatio: 1 }
function impact() {
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium)
}
/** A tap competes with the swipe so dragging a moving row never starts playback. */
export function SongSwipeRow({
children,
style,
backgroundColor,
group,
onPress,
onPlayNext,
onAddToQueue,
onRemove,
}: {
children: ReactNode
style?: StyleProp<ViewStyle>
backgroundColor: string
group: SwipeRowGroup
onPress?: () => void
onPlayNext: () => void
onAddToQueue: () => void
onRemove?: () => void
}) {
const hasRemove = IS_ANDROID && !!onRemove
const x = useSharedValue(0)
const startX = useSharedValue(0)
const width = useSharedValue(0)
const height = useSharedValue(0)
const committed = useSharedValue(false)
const commitProgress = useSharedValue(0)
const [open, setOpen] = useState<-1 | 0 | 1>(0)
const close = useCallback(() => {
x.value = withSpring(0, SPRING)
committed.value = false
commitProgress.value = withSpring(0, SPRING)
setOpen(0)
group.clear(close)
}, [commitProgress, committed, group, x])
useEffect(() => () => group.clear(close), [close, group])
const begin = useCallback(() => group.setOpen(close), [close, group])
const settle = useCallback(
(side: -1 | 0 | 1) => {
setOpen(side)
if (!side) group.clear(close)
},
[close, group]
)
const activate = useCallback(
(side: number) => {
close()
if (side > 0) onAddToQueue()
// Download is intentionally a placeholder.
},
[close, onAddToQueue]
)
const tapRow = useCallback(() => {
if (open) close()
else onPress?.()
}, [close, onPress, open])
const gesture = useMemo(() => {
const pan = Gesture.Pan()
// Leave the screen's leading edge available for native back navigation.
.hitSlop({ left: -24 })
.activeOffsetX([-10, 10])
.failOffsetY([-10, 10])
.onStart(() => {
cancelAnimation(x)
startX.value = x.value
scheduleOnRN(begin)
})
.onUpdate((event) => {
x.value = Math.max(
-width.value,
Math.min(width.value, startX.value + event.translationX)
)
const commit =
Math.abs(x.value) >
Math.max(
x.value > 0
? LEADING_ACTION_WIDTH * 2
: ACTION_WIDTH * (hasRemove ? 2 : 1),
width.value * 0.55
)
if (commit !== committed.value) {
committed.value = commit
commitProgress.value = withSpring(commit ? 1 : 0, SPRING)
scheduleOnRN(impact)
}
})
.onEnd((event) => {
const side = x.value > 0 ? 1 : -1
if (committed.value) {
x.value = withSpring(0, SPRING)
scheduleOnRN(activate, side)
return
}
const projected = x.value + event.velocityX * 0.12
const target =
Math.abs(x.value) > 10 && projected * side > ACTION_WIDTH / 2
? side
: 0
x.value = withSpring(
target *
(target > 0
? LEADING_ACTION_WIDTH * 2
: ACTION_WIDTH * (hasRemove ? 2 : 1)),
{
...SPRING,
velocity: event.velocityX,
}
)
scheduleOnRN(settle, target)
})
.onFinalize((_event, success) => {
if (!success) {
x.value = withSpring(0, SPRING)
scheduleOnRN(close)
}
})
const tap = Gesture.Tap()
.maxDistance(10)
.maxDuration(500)
.onEnd((_event, success) => {
if (success) scheduleOnRN(tapRow)
})
return Gesture.Exclusive(pan, tap)
}, [
activate,
hasRemove,
begin,
close,
commitProgress,
committed,
settle,
startX,
tapRow,
width,
x,
])
const rowStyle = useAnimatedStyle(() => ({
transform: [{ translateX: x.value }],
borderRadius: IS_ANDROID
? 0
: interpolate(
Math.abs(x.value),
[0, 40],
[0, height.value / 2],
Extrapolation.CLAMP
),
}))
const fillStyle = useAnimatedStyle(() => ({
opacity: interpolate(
Math.abs(x.value),
[0, 40],
[0, 1],
Extrapolation.CLAMP
),
}))
return (
<Animated.View
style={styles.container}
onLayout={(event) => {
width.value = event.nativeEvent.layout.width
height.value = event.nativeEvent.layout.height
}}
>
<SwipeAction
side={1}
x={x}
height={height}
progress={commitProgress}
open={open === 1}
onPress={() => activate(1)}
/>
<SwipeAction
side={1}
secondary
x={x}
height={height}
progress={commitProgress}
open={open === 1}
onPress={() => {
close()
onPlayNext()
}}
/>
{hasRemove && (
<SwipeAction
side={-1}
secondary
paired
remove
x={x}
height={height}
progress={commitProgress}
open={open === -1}
onPress={() => {
close()
onRemove?.()
}}
/>
)}
<SwipeAction
side={-1}
paired={hasRemove}
x={x}
height={height}
progress={commitProgress}
open={open === -1}
onPress={() => activate(-1)}
/>
<GestureDetector gesture={gesture}>
<Animated.View
accessible
accessibilityRole="button"
onAccessibilityTap={tapRow}
accessibilityActions={[
{ name: "addToQueue", label: "Add to Queue" },
{ name: "playNext", label: "Play Next" },
{ name: "download", label: "Download" },
...(hasRemove
? [{ name: "remove", label: "Remove from Playlist" }]
: []),
]}
onAccessibilityAction={(event) => {
if (event.nativeEvent.actionName === "remove" && hasRemove) {
close()
onRemove?.()
}
if (event.nativeEvent.actionName === "addToQueue") activate(1)
if (event.nativeEvent.actionName === "playNext") {
close()
onPlayNext()
}
}}
style={[styles.row, { backgroundColor }, rowStyle]}
>
<Animated.View
pointerEvents="none"
style={[StyleSheet.absoluteFill, styles.fill, fillStyle]}
/>
<Animated.View style={style}>{children}</Animated.View>
</Animated.View>
</GestureDetector>
</Animated.View>
)
}
function SwipeAction({
side,
secondary = false,
paired = side > 0,
remove = false,
x,
height,
progress,
open,
onPress,
}: {
side: 1 | -1
secondary?: boolean
paired?: boolean
remove?: boolean
x: SharedValue<number>
height: SharedValue<number>
progress: SharedValue<number>
open: boolean
onPress: () => void
}) {
const actionStyle = useAnimatedStyle(() => {
const revealed = Math.max(0, x.value * side)
const primaryWidth = (revealed * (1 + progress.value)) / 2
return {
width: !paired
? revealed
: secondary
? revealed - primaryWidth
: primaryWidth,
...(secondary
? side > 0
? { left: primaryWidth }
: { right: primaryWidth }
: {}),
}
})
const pillStyle = useAnimatedStyle(() => {
const total = Math.max(0, x.value * side)
const revealed = !paired
? total
: (total * (secondary ? 1 - progress.value : 1 + progress.value)) / 2
if (IS_ANDROID) {
return { width: revealed, height: height.value, borderRadius: 0 }
}
const resting = Math.max(
0,
Math.min(
revealed - (side > 0 ? 10 : 20),
interpolate(
revealed,
[24, side > 0 ? LEADING_ACTION_WIDTH : ACTION_WIDTH, 220],
[0, 62, 200]
)
)
)
const pillWidth =
resting + (Math.max(0, revealed - 12) - resting) * progress.value
const restingHeight = interpolate(
pillWidth,
[0, 24, 62, 140, 200],
[0, 0.3, 0.77, 0.82, 0.86].map((ratio) => ratio * height.value),
Extrapolation.CLAMP
)
const pillHeight =
restingHeight +
(Math.max(0, height.value - 12) - restingHeight) * progress.value
return {
width: pillWidth,
height: pillHeight,
borderRadius: pillHeight / 2,
}
})
const iconStyle = useAnimatedStyle(() => ({
transform: [
{
scale: interpolate(
x.value * side,
[24, 64],
[0, 1],
Extrapolation.CLAMP
),
},
],
}))
return (
<Animated.View
pointerEvents={open ? "auto" : "none"}
accessibilityElementsHidden={!open}
importantForAccessibility={open ? "auto" : "no-hide-descendants"}
style={[
styles.action,
side > 0 ? styles.leading : styles.trailing,
actionStyle,
]}
>
<Pressable
accessibilityRole="button"
accessibilityLabel={
remove
? "Remove from Playlist"
: side > 0
? secondary
? "Play Next"
: "Add to Queue"
: "Download"
}
onPress={onPress}
style={styles.actionButton}
>
<Animated.View
style={[
styles.pill,
{
backgroundColor: remove
? "#d32f2f"
: side > 0
? secondary
? "#6b5bff"
: "#f29943"
: "#008dff",
},
pillStyle,
]}
>
<Animated.View style={iconStyle}>
{IS_ANDROID ? (
<Ionicons
name={
remove
? "trash-outline"
: side < 0
? "arrow-down"
: secondary
? "play-forward"
: "list"
}
size={22}
color="white"
/>
) : (
<SymbolView
name={
side > 0
? secondary
? "text.line.first.and.arrowtriangle.forward"
: "text.line.last.and.arrowtriangle.forward"
: "arrow.down"
}
size={22}
tintColor="white"
/>
)}
</Animated.View>
</Animated.View>
</Pressable>
</Animated.View>
)
}
const styles = StyleSheet.create({
container: { overflow: "hidden" },
row: { overflow: "hidden" },
fill: { backgroundColor: "rgba(128,128,128,0.16)" },
action: { position: "absolute", top: 0, bottom: 0 },
leading: { left: 0 },
trailing: { right: 0 },
actionButton: { flex: 1, alignItems: "center", justifyContent: "center" },
pill: { alignItems: "center", justifyContent: "center", overflow: "hidden" },
})
@@ -18,7 +18,7 @@ import {
import { useTabletPlayerInsets } from "@/contexts/tablet-player-layout" import { useTabletPlayerInsets } from "@/contexts/tablet-player-layout"
import { CoverImage } from "@/components/cover-image" import { CoverImage } from "@/components/cover-image"
import { MediaActionMenu } from "@/components/media-context-menu" import { MediaActionMenu } from "@/components/media-actions-sheet"
import { PlayerSymbol } from "@/components/player-symbol" import { PlayerSymbol } from "@/components/player-symbol"
import { useFavorites } from "@/contexts/favorites" import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback" import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
+1 -3
View File
@@ -4,7 +4,6 @@ import { useIsFocused } from "expo-router"
import { Platform, type ViewProps } from "react-native" import { Platform, type ViewProps } from "react-native"
import { useCachedQuery } from "@/hooks/use-cached-query" import { useCachedQuery } from "@/hooks/use-cached-query"
import { useProfileImageUrl } from "@/hooks/use-profile-image-url"
import { initialsFromName } from "@/lib/format" import { initialsFromName } from "@/lib/format"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
@@ -23,7 +22,6 @@ const NativeSidebar =
export function TabletSidebar() { export function TabletSidebar() {
const user = useCachedQuery(api.auth.currentUser) const user = useCachedQuery(api.auth.currentUser)
const imageUrl = useProfileImageUrl(user?.image)
const openSettings = useOpenSettings() const openSettings = useOpenSettings()
const active = useIsFocused() const active = useIsFocused()
@@ -33,7 +31,7 @@ export function TabletSidebar() {
style={{ position: "absolute", width: 0, height: 0 }} style={{ position: "absolute", width: 0, height: 0 }}
accountName={user?.name ?? "Account"} accountName={user?.name ?? "Account"}
initials={initialsFromName(user?.name ?? "Me")} initials={initialsFromName(user?.name ?? "Me")}
imageURL={imageUrl} imageURL={user?.image}
active={active} active={active}
onProfilePress={openSettings} onProfilePress={openSettings}
/> />
+6 -8
View File
@@ -1,11 +1,12 @@
import { createContext, useContext, useMemo, type ReactNode } from "react" import { createContext, useContext, type ReactNode } from "react"
type ConvexAuthSessionContextValue = { type ConvexAuthSessionContextValue = {
invalidateSession: () => Promise<void> invalidateSession: () => Promise<void>
} }
const ConvexAuthSessionContext = const ConvexAuthSessionContext = createContext<ConvexAuthSessionContextValue | null>(
createContext<ConvexAuthSessionContextValue | null>(null) null
)
export function ConvexAuthSessionProvider({ export function ConvexAuthSessionProvider({
children, children,
@@ -14,9 +15,8 @@ export function ConvexAuthSessionProvider({
children: ReactNode children: ReactNode
invalidateSession: () => Promise<void> invalidateSession: () => Promise<void>
}) { }) {
const value = useMemo(() => ({ invalidateSession }), [invalidateSession])
return ( return (
<ConvexAuthSessionContext.Provider value={value}> <ConvexAuthSessionContext.Provider value={{ invalidateSession }}>
{children} {children}
</ConvexAuthSessionContext.Provider> </ConvexAuthSessionContext.Provider>
) )
@@ -25,9 +25,7 @@ export function ConvexAuthSessionProvider({
export function useInvalidateAuthSession() { export function useInvalidateAuthSession() {
const context = useContext(ConvexAuthSessionContext) const context = useContext(ConvexAuthSessionContext)
if (!context) { if (!context) {
throw new Error( throw new Error("useInvalidateAuthSession must be used within ConvexAppProvider")
"useInvalidateAuthSession must be used within ConvexAuthSessionProvider"
)
} }
return context return context
} }
File diff suppressed because it is too large. Load diff
-142
View File
@@ -1,142 +0,0 @@
import { useEffect, useMemo, useState } from "react"
import { themeCoverPalette, type CoverPalette } from "@/lib/cover-palette"
import { readCache, writeCache } from "@/lib/persistent-cache"
import { useIsDark, useThemeColors } from "@/lib/theme"
import { withCoverImageSize } from "@/lib/urls"
// How long a screen holds its skeleton for the first extraction of a cover,
// so rows render once with final colors instead of flashing from the theme.
export const COVER_PALETTE_WAIT_MS = 400
export type CoverPaletteResult = { palette: CoverPalette; settled: boolean }
type CoverPaletteSourceOptions<Swatches> = {
/** Persistent cache key for a 64px cover URI. */
cacheKey: (colorSourceUri: string) => string
extract: (colorSourceUri: string) => Promise<Swatches | null>
derive: (swatches: Swatches, isDark: boolean) => CoverPalette | null
/** Reject persisted entries written in an older shape. */
isValidCache?: (swatches: Swatches) => boolean
}
/**
* One artwork color pipeline: an extractor and palette derivation with their
* own memory cache, persistent cache and in-flight requests.
*/
export function createCoverPaletteSource<Swatches>({
cacheKey,
extract,
derive,
isValidCache,
}: CoverPaletteSourceOptions<Swatches>) {
const swatchesByKey = new Map<string, Swatches | null>()
const pending = new Map<string, Promise<Swatches | null>>()
function cachedSwatches(key: string): Swatches | null | undefined {
if (swatchesByKey.has(key)) return swatchesByKey.get(key)
const cached = readCache<Swatches>(cacheKey(key))
return cached && isValidCache && !isValidCache(cached) ? undefined : cached
}
function extractSwatches(key: string) {
const inFlight = pending.get(key)
if (inFlight) return inFlight
const request = extract(key)
.catch(() => null)
.then((swatches) => {
swatchesByKey.set(key, swatches)
if (swatches) writeCache(cacheKey(key), swatches)
pending.delete(key)
return swatches
})
pending.set(key, request)
return request
}
function prefetch(uri: string) {
const key = withCoverImageSize(uri, 64)
if (cachedSwatches(key) !== undefined) return
void extractSwatches(key)
}
/**
* Colors for a screen tinted by `uri`'s cover art. Pass `uri` as "" to skip
* extraction. Pass `hasCover` as `undefined` while it isn't known yet so
* extraction can start early.
*
* `settled` turns true once the palette is final or after
* `COVER_PALETTE_WAIT_MS`, whichever comes first.
*/
function usePalette(
uri: string,
hasCover: boolean | undefined
): CoverPaletteResult {
const theme = useThemeColors()
const isDark = useIsDark()
const key = uri ? withCoverImageSize(uri, 64) : ""
const [resolved, setResolved] = useState(() => ({
key,
swatches: key ? cachedSwatches(key) : null,
}))
const [waitedKey, setWaitedKey] = useState<string | null>(null)
const swatches =
resolved.key === key ? resolved.swatches : key ? cachedSwatches(key) : null
useEffect(() => {
if (!key || hasCover === false) return
let cancelled = false
const known = cachedSwatches(key)
const show = (next: Swatches | null) =>
setResolved((prev) =>
prev.key === key && sameSwatches(prev.swatches, next)
? prev
: { key, swatches: next }
)
if (known !== undefined && swatchesByKey.has(key)) {
show(known)
return
}
// Persisted swatches render immediately; refresh them in the background
// in case the cover changed.
const timer =
known === undefined
? setTimeout(
() => !cancelled && setWaitedKey(key),
COVER_PALETTE_WAIT_MS
)
: null
void extractSwatches(key).then((next) => {
if (!cancelled) show(next ?? known ?? null)
})
return () => {
cancelled = true
if (timer) clearTimeout(timer)
}
}, [hasCover, key])
const palette = useMemo(() => {
const fromArt =
hasCover !== false && swatches ? derive(swatches, isDark) : null
return fromArt ?? themeCoverPalette(theme, isDark)
}, [hasCover, isDark, swatches, theme])
return {
palette,
settled:
!key ||
hasCover === false ||
swatches !== undefined ||
waitedKey === key,
}
}
return { prefetch, usePalette }
}
function sameSwatches(a: unknown, b: unknown) {
return a === b || JSON.stringify(a) === JSON.stringify(b)
}
+130 -30
View File
@@ -1,47 +1,147 @@
import { useEffect, useMemo, useState } from "react"
import { import {
createCoverPaletteSource, artworkColorsEnabled,
type CoverPaletteResult,
} from "@/hooks/cover-palette-source"
import {
prefetchLegacyCoverPalette,
useLegacyCoverPalette,
} from "@/hooks/use-legacy-cover-palette"
import {
loadArtworkColorsEnabled,
useArtworkColorsEnabled, useArtworkColorsEnabled,
} from "@/lib/artwork-color-preference" } from "@/lib/artwork-color-preference"
import { prefetchLegacyCoverPalette, useLegacyCoverPalette } from "@/hooks/use-legacy-cover-palette"
import { extractCoverSwatches } from "@/lib/artwork-colors" import { extractCoverSwatches } from "@/lib/artwork-colors"
import { deriveCoverPalette, type CoverSwatches } from "@/lib/cover-palette"
export { COVER_PALETTE_WAIT_MS } from "@/hooks/cover-palette-source" import {
deriveCoverPalette,
themeCoverPalette,
type CoverPalette,
type CoverSwatches,
} from "@/lib/cover-palette"
import { readCache, writeCache } from "@/lib/persistent-cache"
import { useIsDark, useThemeColors } from "@/lib/theme"
import { withCoverImageSize } from "@/lib/urls"
const region = createCoverPaletteSource<CoverSwatches>({ // How long a screen holds its skeleton for the first extraction of a cover,
cacheKey: (colorSourceUri) => `palette:v2:${colorSourceUri}`, // so rows render once with final colors instead of flashing from the theme.
extract: extractCoverSwatches, export const COVER_PALETTE_WAIT_MS = 400
derive: (swatches) => deriveCoverPalette(swatches),
}) const swatchesByKey = new Map<string, CoverSwatches | null>()
const pending = new Map<string, Promise<CoverSwatches | null>>()
function cacheKey(colorSourceUri: string) {
return `palette:v2:${colorSourceUri}`
}
function sameSwatches(
a: CoverSwatches | null | undefined,
b: CoverSwatches | null | undefined
) {
return a === b || JSON.stringify(a) === JSON.stringify(b)
}
function cachedSwatches(key: string): CoverSwatches | null | undefined {
if (swatchesByKey.has(key)) return swatchesByKey.get(key)
return readCache<CoverSwatches>(cacheKey(key))
}
function extractSwatches(key: string) {
const inFlight = pending.get(key)
if (inFlight) return inFlight
const request = extractCoverSwatches(key)
.catch(() => null)
.then((swatches) => {
swatchesByKey.set(key, swatches)
if (swatches) writeCache(cacheKey(key), swatches)
pending.delete(key)
return swatches
})
pending.set(key, request)
return request
}
/** Warm visible artwork colors before a detail page is pushed. */ /** Warm visible artwork colors before a detail page is pushed. */
export function prefetchCoverPalette(uri: string) { export function prefetchCoverPalette(uri: string) {
void loadArtworkColorsEnabled().then((enabled) => if (!artworkColorsEnabled()) {
enabled ? region.prefetch(uri) : prefetchLegacyCoverPalette(uri) prefetchLegacyCoverPalette(uri)
) return
}
const key = withCoverImageSize(uri, 64)
if (cachedSwatches(key) !== undefined) return
void extractSwatches(key)
} }
/** /**
* Colors for a screen tinted by `uri`'s cover art, from whichever pipeline the * Colors for a screen tinted by `uri`'s cover art. Extraction runs once per
* device preference selects. Nothing is extracted until the preference loads, * cover and is cached on device. Pass `hasCover` as `undefined` while it isn't
* and the screen stays unsettled meanwhile so it doesn't flash theme colors. * known yet so extraction can start early.
*
* `settled` turns true once the palette is final or after
* `COVER_PALETTE_WAIT_MS`, whichever comes first.
*/ */
export function useCoverPalette( function useRegionCoverPalette(
uri: string, uri: string,
hasCover: boolean | undefined hasCover: boolean | undefined
): CoverPaletteResult { ): { palette: CoverPalette; settled: boolean } {
const enabled = useArtworkColorsEnabled() const theme = useThemeColors()
const current = region.usePalette(enabled === true ? uri : "", hasCover) const isDark = useIsDark()
const legacy = useLegacyCoverPalette(enabled === false ? uri : "", hasCover) const key = uri ? withCoverImageSize(uri, 64) : ""
if (enabled === undefined) { const [resolved, setResolved] = useState(() => ({
return { palette: current.palette, settled: !uri || hasCover === false } key,
swatches: key ? cachedSwatches(key) : null,
}))
const [waitedKey, setWaitedKey] = useState<string | null>(null)
const swatches =
resolved.key === key ? resolved.swatches : key ? cachedSwatches(key) : null
useEffect(() => {
if (!key || hasCover === false) return
let cancelled = false
const known = cachedSwatches(key)
const show = (next: CoverSwatches | null) =>
setResolved((prev) =>
prev.key === key && sameSwatches(prev.swatches, next)
? prev
: { key, swatches: next }
)
if (known !== undefined && swatchesByKey.has(key)) {
show(known)
return
}
// Persisted swatches render immediately; refresh them in the background in
// case the cover changed.
const timer =
known === undefined
? setTimeout(
() => !cancelled && setWaitedKey(key),
COVER_PALETTE_WAIT_MS
)
: null
void extractSwatches(key).then((next) => {
if (!cancelled) show(next ?? known ?? null)
})
return () => {
cancelled = true
if (timer) clearTimeout(timer)
}
}, [hasCover, key])
const palette = useMemo(() => {
const fromArt =
hasCover !== false && swatches
? deriveCoverPalette(swatches)
: null
return fromArt ?? themeCoverPalette(theme, isDark)
}, [hasCover, isDark, swatches, theme])
return {
palette,
settled:
!key || hasCover === false || swatches !== undefined || waitedKey === key,
} }
return enabled ? current : legacy }
/** Switch both extraction and palette derivation without mixing their caches. */
export function useCoverPalette(uri: string, hasCover: boolean | undefined) {
const enabled = useArtworkColorsEnabled()
const region = useRegionCoverPalette(enabled ? uri : "", hasCover)
const legacy = useLegacyCoverPalette(enabled ? "" : uri, hasCover)
return enabled ? region : legacy
} }
+132 -21
View File
@@ -1,14 +1,29 @@
import { useEffect, useMemo, useState } from "react"
import { getColors, type ImageColorsResult } from "react-native-image-colors" import { getColors, type ImageColorsResult } from "react-native-image-colors"
import { createCoverPaletteSource } from "@/hooks/cover-palette-source"
import { import {
deriveCoverPalette, themeCoverPalette,
type LegacyCoverSwatches as CoverSwatches, type CoverPalette,
} from "@/lib/legacy-cover-palette" } from "@/lib/cover-palette"
import { deriveCoverPalette, type LegacyCoverSwatches as CoverSwatches } from "@/lib/legacy-cover-palette"
import { readCache, writeCache } from "@/lib/persistent-cache"
import { useIsDark, useThemeColors } from "@/lib/theme"
import { withCoverImageSize } from "@/lib/urls"
// How long a screen holds its skeleton for the first extraction of a cover,
// so rows render once with final colors instead of flashing from the theme.
const COVER_PALETTE_WAIT_MS = 400
// image-colors substitutes this for swatches it couldn't find. // image-colors substitutes this for swatches it couldn't find.
const MISSING = "#010203" const MISSING = "#010203"
const swatchesByKey = new Map<string, CoverSwatches | null>()
const pending = new Map<string, Promise<CoverSwatches | null>>()
function cacheKey(colorSourceUri: string) {
return `palette:${colorSourceUri}`
}
function present(colors: (string | undefined)[]) { function present(colors: (string | undefined)[]) {
return colors.filter( return colors.filter(
(color): color is string => !!color && color.toLowerCase() !== MISSING (color): color is string => !!color && color.toLowerCase() !== MISSING
@@ -44,24 +59,120 @@ function toSwatches(result: ImageColorsResult): CoverSwatches | null {
} }
} }
const legacy = createCoverPaletteSource<CoverSwatches>({ function sameSwatches(
cacheKey: (colorSourceUri) => `palette:${colorSourceUri}`, a: CoverSwatches | null | undefined,
extract: (key) => b: CoverSwatches | null | undefined
getColors(key, { ) {
fallback: MISSING, return a === b || JSON.stringify(a) === JSON.stringify(b)
cache: true, }
key,
quality: "low", function cachedSwatches(key: string): CoverSwatches | null | undefined {
pixelSpacing: 4, if (swatchesByKey.has(key)) return swatchesByKey.get(key)
}).then(toSwatches), const cached = readCache<CoverSwatches>(cacheKey(key))
derive: deriveCoverPalette,
// Discard the background-only entries written by the tablet palette experiment. // Discard the background-only entries written by the tablet palette experiment.
isValidCache: (cached) => return cached && (!Array.isArray(cached.text) || !Array.isArray(cached.accent))
Array.isArray(cached.text) && Array.isArray(cached.accent), ? undefined
}) : cached
}
function extractSwatches(key: string) {
const inFlight = pending.get(key)
if (inFlight) return inFlight
const request = getColors(key, {
fallback: MISSING,
cache: true,
key,
quality: "low",
pixelSpacing: 4,
})
.then(toSwatches)
.catch(() => null)
.then((swatches) => {
swatchesByKey.set(key, swatches)
if (swatches) writeCache(cacheKey(key), swatches)
pending.delete(key)
return swatches
})
pending.set(key, request)
return request
}
/** Warm visible artwork colors before a detail page is pushed. */ /** Warm visible artwork colors before a detail page is pushed. */
export const prefetchLegacyCoverPalette = legacy.prefetch export function prefetchLegacyCoverPalette(uri: string) {
const key = withCoverImageSize(uri, 64)
if (cachedSwatches(key) !== undefined) return
void extractSwatches(key)
}
/** `react-native-image-colors` pipeline used when new artwork colors are off. */ /**
export const useLegacyCoverPalette = legacy.usePalette * Colors for a screen tinted by `uri`'s cover art. Extraction runs once per
* cover and is cached on device. Pass `hasCover` as `undefined` while it isn't
* known yet so extraction can start early.
*
* `settled` turns true once the palette is final or after
* `COVER_PALETTE_WAIT_MS`, whichever comes first.
*/
export function useLegacyCoverPalette(
uri: string,
hasCover: boolean | undefined
): { palette: CoverPalette; settled: boolean } {
const theme = useThemeColors()
const isDark = useIsDark()
const key = uri ? withCoverImageSize(uri, 64) : ""
const [resolved, setResolved] = useState(() => ({
key,
swatches: key ? cachedSwatches(key) : null,
}))
const [waitedKey, setWaitedKey] = useState<string | null>(null)
const swatches =
resolved.key === key ? resolved.swatches : key ? cachedSwatches(key) : null
useEffect(() => {
if (!key || hasCover === false) return
let cancelled = false
const known = cachedSwatches(key)
const show = (next: CoverSwatches | null) =>
setResolved((prev) =>
prev.key === key && sameSwatches(prev.swatches, next)
? prev
: { key, swatches: next }
)
if (known !== undefined && swatchesByKey.has(key)) {
show(known)
return
}
// Persisted swatches render immediately; refresh them in the background in
// case the cover changed.
const timer =
known === undefined
? setTimeout(
() => !cancelled && setWaitedKey(key),
COVER_PALETTE_WAIT_MS
)
: null
void extractSwatches(key).then((next) => {
if (!cancelled) show(next ?? known ?? null)
})
return () => {
cancelled = true
if (timer) clearTimeout(timer)
}
}, [hasCover, key])
const palette = useMemo(() => {
const fromArt =
hasCover !== false && swatches
? deriveCoverPalette(swatches, isDark)
: null
return fromArt ?? themeCoverPalette(theme, isDark)
}, [hasCover, isDark, swatches, theme])
return {
palette,
settled:
!key || hasCover === false || swatches !== undefined || waitedKey === key,
}
}
@@ -1,728 +0,0 @@
import { dolbyAtmosSupported } from "@/lib/playback-capabilities"
import {
createAudioPlaylist,
setAudioModeAsync,
setIsAudioActiveAsync,
type AudioMetadata,
type AudioPlaylist,
type AudioPlaylistStatus,
type AudioSource,
} from "expo-audio"
import { useConvex } from "convex/react"
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useCacheScope } from "@/contexts/persistent-cache"
import { useServerConfig } from "@/contexts/server-config"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong } from "@otunes/convex/types"
import { playbackStreamPlan } from "@otunes/convex/playback-stream"
import * as playbackQueue from "@otunes/convex/client/playback-queue"
import type { RepeatMode } from "@otunes/convex/client/playback-queue"
import type { PlaybackStore } from "@otunes/convex/client/playback-store"
import { getAuthCookieHeader } from "@/lib/auth-cookies"
import { loadPlaybackSongs } from "@/lib/playback-files"
import { showError } from "@/lib/toast"
import { albumCoverUrl, songAudioSource } from "@/lib/urls"
import {
activatePlaylistLockScreen,
releaseAudioPlaylist,
updatePlaylistLockScreenMetadata,
} from "@/lib/audio-playlist-lock-screen"
import {
nativePlaylistEdits,
nativePlaylistNeedsRebuild,
nativePlaylistSongIds,
repeatToPlaylistLoop,
} from "@/lib/native-playlist-window"
const PLAYBACK_READY_TIMEOUT_MS = 20_000
function lockScreenMetadata(
song: BrowseSong,
serverUrl: string
): AudioMetadata {
return {
title: song.title,
artist: song.artist.name,
albumTitle: song.album.title,
artworkUrl: albumCoverUrl(serverUrl, song.album.id, 512),
}
}
type PlaybackWaiter = { playing?: boolean; resolve: () => void }
/** Where the last sync left the native player, and the queue it reflects. */
type SyncedPosition = {
index: number
songId: Id<"songs"> | undefined
historyLength: number
}
/**
* Keeps the native `AudioPlaylist` in step with the playback queue, and
* feeds its status (position, playing, track changes) back into the queue.
*/
export function useNativePlaylistSync({
store,
queueSongIds,
queueHistorySongIds,
repeatEnabled,
currentSong,
queueStartVersion,
}: {
store: PlaybackStore
queueSongIds: Id<"songs">[]
queueHistorySongIds: Id<"songs">[]
repeatEnabled: RepeatMode
currentSong: BrowseSong | null
queueStartVersion: number
}) {
const convex = useConvex()
const { config } = useServerConfig()
const cacheScope = useCacheScope()
const user = useCachedQuery(api.auth.currentUser)
const storeRef = useRef(store)
storeRef.current = store
const playlistRef = useRef<AudioPlaylist | null>(null)
const statusSubscriptionRef = useRef<{ remove: () => void } | null>(null)
const trackChangedSubscriptionRef = useRef<{ remove: () => void } | null>(
null
)
const loadedSongIdsRef = useRef<Id<"songs">[]>([])
const loadedLoadKeyRef = useRef<string | null>(null)
const syncedPositionRef = useRef<SyncedPosition | null>(null)
const waitersRef = useRef(new Map<Id<"songs">, Set<PlaybackWaiter>>())
const autoPlayNextRef = useRef(false)
const isPlayingRef = useRef(false)
const currentTimeRef = useRef(0)
const pendingSeekRef = useRef<number | null>(null)
const seekInFlightRef = useRef(false)
// Set while `play()` waits for a pending seek to land.
const deferredPlayRef = useRef(false)
const loadRequestIdRef = useRef(0)
const [isPlaying, setIsPlayingState] = useState(false)
const [currentTime, setCurrentTime] = useState(0)
const [measuredDuration, setDuration] = useState(0)
const currentSongId = queueSongIds[0] ?? null
const duration =
measuredDuration > 0
? measuredDuration
: (currentSong?.durationSeconds ?? 0)
const queueSyncKey = useMemo(
() => JSON.stringify(queueSongIds),
[queueSongIds]
)
const historySyncKey = useMemo(
() => JSON.stringify(queueHistorySongIds),
[queueHistorySongIds]
)
const currentSongSyncKey = currentSong
? JSON.stringify([
currentSong.id,
currentSong.title,
currentSong.artist.name,
currentSong.album.id,
currentSong.album.title,
currentSong.album.cover ?? "",
])
: ""
const userPlaybackKey = user
? JSON.stringify([
user._id,
user.playbackQuality,
dolbyAtmosSupported && (user.preferAtmos ?? false),
])
: ""
const settleWaiters = useCallback(() => {
const player = playlistRef.current
if (waitersRef.current.size === 0 || !player) return
const songId = loadedSongIdsRef.current[player.currentIndex]
const waiters = songId && waitersRef.current.get(songId)
if (!waiters || !player.isLoaded) return
for (const waiter of waiters) {
if (waiter.playing === undefined || player.playing === waiter.playing) {
waiter.resolve()
}
}
}, [])
const markSynced = useCallback(
(playlist: AudioPlaylist, songId: Id<"songs">, historyLength: number) => {
syncedPositionRef.current = {
index: playlist.currentIndex,
songId,
historyLength,
}
settleWaiters()
},
[settleWaiters]
)
const destroyPlaylist = useCallback(() => {
statusSubscriptionRef.current?.remove()
statusSubscriptionRef.current = null
trackChangedSubscriptionRef.current?.remove()
trackChangedSubscriptionRef.current = null
const playlist = playlistRef.current
if (playlist) {
playlist.pause()
releaseAudioPlaylist(playlist)
}
playlistRef.current = null
loadedSongIdsRef.current = []
loadedLoadKeyRef.current = null
syncedPositionRef.current = null
}, [])
const resetPosition = useCallback(() => {
pendingSeekRef.current = null
deferredPlayRef.current = false
currentTimeRef.current = 0
setCurrentTime(0)
setDuration(0)
}, [])
// A new queue must not inherit the native player's position or a pending seek.
const resetForNewQueue = useCallback(() => {
loadRequestIdRef.current += 1
destroyPlaylist()
seekInFlightRef.current = false
resetPosition()
}, [destroyPlaylist, resetPosition])
/**
* Starts the player, unless a seek (a restored position) is still pending.
* Then the status handler starts it once the seek lands, so playback never
* starts at 0:00 and jumps.
*/
const startPlayer = useCallback((playlist: AudioPlaylist) => {
if (pendingSeekRef.current !== null && pendingSeekRef.current > 0) {
deferredPlayRef.current = true
return
}
playlist.play()
}, [])
const handlePlaylistStatusUpdate = useCallback(
(status: AudioPlaylistStatus) => {
settleWaiters()
// iOS may remove the finished item before delivering its final status.
if (!status.isLoaded && !status.didJustFinish) return
const state = storeRef.current.getState()
if (loadedSongIdsRef.current[status.currentIndex] !== state.queue[0]) {
return
}
if (status.duration > 0) {
setDuration(status.duration)
}
if (pendingSeekRef.current !== null && pendingSeekRef.current > 0) {
const seekSeconds =
status.duration > 0
? Math.min(pendingSeekRef.current, status.duration)
: pendingSeekRef.current
pendingSeekRef.current = null
const playlist = playlistRef.current
if (playlist) {
// Statuses report the old position until the seek lands.
seekInFlightRef.current = true
void playlist.seekTo(seekSeconds).finally(() => {
seekInFlightRef.current = false
if (deferredPlayRef.current && playlistRef.current === playlist) {
deferredPlayRef.current = false
playlist.play()
}
})
}
currentTimeRef.current = seekSeconds
setCurrentTime(seekSeconds)
} else if (!seekInFlightRef.current) {
currentTimeRef.current = status.currentTime
setCurrentTime(status.currentTime)
}
if (status.playing) {
autoPlayNextRef.current = false
if (!isPlayingRef.current) {
isPlayingRef.current = true
setIsPlayingState(true)
}
} else if (
isPlayingRef.current &&
!status.didJustFinish &&
!deferredPlayRef.current
) {
autoPlayNextRef.current = false
isPlayingRef.current = false
setIsPlayingState(false)
}
if (!status.didJustFinish) return
if (state.repeatEnabled === "once") return
if (status.currentIndex < status.trackCount - 1) return
const shouldContinue =
state.repeatEnabled !== "none" || state.queue.length > 1
if (!shouldContinue) {
autoPlayNextRef.current = false
isPlayingRef.current = false
setIsPlayingState(false)
storeRef.current.update(playbackQueue.skipNext)
const playlist = playlistRef.current
if (playlist) {
playlist.pause()
// Reload the final item, which iOS removes when playback ends. The
// index doesn't move, so handleTrackChanged treats it as ours.
playlist.skipTo(status.currentIndex)
}
currentTimeRef.current = 0
setCurrentTime(0)
return
}
autoPlayNextRef.current = true
isPlayingRef.current = true
setIsPlayingState(true)
storeRef.current.update(playbackQueue.skipNext)
if (storeRef.current.getState().queue[0] === state.queue[0]) {
const playlist = playlistRef.current
void playlist?.seekTo(0)
playlist?.play()
}
},
[settleWaiters]
)
const handleTrackChanged = useCallback(() => {
const playlist = playlistRef.current
const synced = syncedPositionRef.current
if (!playlist || !synced) return
// Queue edits run synchronously, so an event can describe an index from
// before them (Android's `previousIndex` also goes stale). The player's
// live index is the one that matters; if it is where the last sync left
// it, this change was ours.
const index = playlist.currentIndex
if (index === synced.index) return
const state = storeRef.current.getState()
// A queue change is still being applied and will move the player itself.
if (
state.queue[0] !== synced.songId ||
state.history.length !== synced.historyLength
) {
return
}
// The window is history then queue, so the current track sits at
// `history.length`.
const steps = index - state.history.length
if (steps === 0) return
autoPlayNextRef.current = true
isPlayingRef.current = true
setIsPlayingState(true)
storeRef.current.update((state) => {
if (steps === 1) return playbackQueue.skipNext(state)
if (steps > 1) return playbackQueue.skipToQueueIndex(state, steps)
let next = state
for (let i = 0; i < -steps; i++) {
next = playbackQueue.skipPrevious(next)
}
return next
})
const next = storeRef.current.getState()
syncedPositionRef.current = {
index,
songId: next.queue[0],
historyLength: next.history.length,
}
settleWaiters()
}, [settleWaiters])
const ensurePlaylist = useCallback(
(sources: AudioSource[]) => {
if (playlistRef.current) {
return playlistRef.current
}
const playlist = createAudioPlaylist({
sources,
updateInterval: 500,
loop: repeatToPlaylistLoop(storeRef.current.getState().repeatEnabled),
})
// System volume controls loudness; keep the player gain at full scale.
playlist.volume = 1
statusSubscriptionRef.current = playlist.addListener(
"playlistStatusUpdate",
handlePlaylistStatusUpdate
)
trackChangedSubscriptionRef.current = playlist.addListener(
"trackChanged",
handleTrackChanged
)
playlistRef.current = playlist
return playlist
},
[handlePlaylistStatusUpdate, handleTrackChanged]
)
useEffect(() => {
let cancelled = false
void setAudioModeAsync({
playsInSilentMode: true,
shouldPlayInBackground: true,
interruptionMode: "doNotMix",
}).catch(() => {
if (!cancelled) {
showError("Audio playback could not be initialized.")
}
})
return () => {
cancelled = true
destroyPlaylist()
}
}, [destroyPlaylist])
useEffect(() => {
const playlist = playlistRef.current
if (playlist) {
playlist.loop = repeatToPlaylistLoop(repeatEnabled)
}
}, [repeatEnabled])
const setIsPlaying = useCallback(
(playing: boolean) => {
isPlayingRef.current = playing
setIsPlayingState(playing)
const playlist = playlistRef.current
if (!playlist) return
if (playing) {
startPlayer(playlist)
} else {
deferredPlayRef.current = false
playlist.pause()
}
},
[startPlayer]
)
const seekTo = useCallback(
async (seconds: number) => {
const playlist = playlistRef.current
if (!playlist) return
const maxDuration = playlist.duration || duration || 0
const clamped = Math.max(0, Math.min(seconds, maxDuration))
await playlist.seekTo(clamped)
currentTimeRef.current = clamped
setCurrentTime(clamped)
},
[duration]
)
const handlePlaybackLoadFailure = useCallback(() => {
autoPlayNextRef.current = false
isPlayingRef.current = false
destroyPlaylist()
setIsPlayingState(false)
showError("Could not play this track. The queue has been cleared.")
storeRef.current.update(playbackQueue.clearQueue)
}, [destroyPlaylist])
useEffect(() => {
const loadRequestId = ++loadRequestIdRef.current
const isCurrentLoad = () => loadRequestIdRef.current === loadRequestId
async function syncPlaylist() {
if (!config || !currentSongId || !user) {
if (!currentSongId) {
destroyPlaylist()
}
return
}
const windowSongIds = nativePlaylistSongIds(
queueHistorySongIds,
queueSongIds
)
const currentIndex = queueHistorySongIds.length
const cookieHeader = await getAuthCookieHeader(
config.serverUrl,
config.convexUrl
)
if (!cookieHeader) {
showError("Your session has expired. Please sign in again.")
return
}
if (!isCurrentLoad()) return
const loadKey = `${user.playbackQuality}:${dolbyAtmosSupported && (user.preferAtmos ?? false)}:${cookieHeader}`
const needsRebuild =
loadedLoadKeyRef.current !== loadKey ||
nativePlaylistNeedsRebuild(
loadedSongIdsRef.current,
queueHistorySongIds,
queueSongIds
)
const metadata = currentSong
? lockScreenMetadata(currentSong, config.serverUrl)
: null
const shouldPlay = isPlayingRef.current || autoPlayNextRef.current
if (!needsRebuild) {
const playlist = playlistRef.current
if (!playlist) return
if (playlist.currentIndex !== currentIndex) {
playlist.skipTo(currentIndex)
}
playlist.loop = repeatToPlaylistLoop(repeatEnabled)
if (metadata) {
updatePlaylistLockScreenMetadata(playlist, metadata)
}
markSynced(playlist, currentSongId, currentIndex)
if (shouldPlay) {
isPlayingRef.current = true
setIsPlayingState(true)
startPlayer(playlist)
}
return
}
const buildSources = async (songIds: Id<"songs">[]) => {
const songs = await loadPlaybackSongs(convex, cacheScope, songIds)
const sources = new Map<Id<"songs">, AudioSource>()
for (const song of songs) {
if (!song) return null
const plan = playbackStreamPlan(
song.files,
user.playbackQuality,
dolbyAtmosSupported && (user.preferAtmos ?? false)
)
sources.set(
song.id,
songAudioSource(
config.serverUrl,
song.id,
plan.playbackQuality,
plan.preferAtmos,
plan.useHls,
{ cookieHeader, songTitle: song.title }
)
)
}
return sources
}
// Queue and history edits around the playing track are applied in place
// so playback isn't interrupted.
const loadedPlaylist = playlistRef.current
const edits =
loadedPlaylist && loadedLoadKeyRef.current === loadKey
? nativePlaylistEdits(
loadedSongIdsRef.current,
loadedPlaylist.currentIndex,
windowSongIds,
currentIndex
)
: null
if (loadedPlaylist && edits) {
const addedSongIds = edits.flatMap((edit) =>
edit.type === "remove" ? [] : [edit.songId]
)
const sources = await buildSources([...new Set(addedSongIds)])
if (!isCurrentLoad()) return
if (!sources) {
handlePlaybackLoadFailure()
return
}
for (const edit of edits) {
if (edit.type === "remove") {
loadedPlaylist.remove(edit.index)
} else if (edit.type === "insert") {
loadedPlaylist.insert(sources.get(edit.songId)!, edit.index)
} else {
loadedPlaylist.add(sources.get(edit.songId)!)
}
}
loadedSongIdsRef.current = windowSongIds
loadedPlaylist.loop = repeatToPlaylistLoop(repeatEnabled)
markSynced(loadedPlaylist, currentSongId, currentIndex)
if (shouldPlay && !loadedPlaylist.playing) {
isPlayingRef.current = true
setIsPlayingState(true)
startPlayer(loadedPlaylist)
}
return
}
const sourcesById = await buildSources(windowSongIds)
if (!isCurrentLoad()) return
if (!sourcesById) {
handlePlaybackLoadFailure()
return
}
const sources = windowSongIds.map((songId) => sourcesById.get(songId)!)
// Keep the position when only the stream settings changed.
const resumeSeconds =
loadedPlaylist &&
loadedSongIdsRef.current[loadedPlaylist.currentIndex] === currentSongId
? currentTimeRef.current
: null
destroyPlaylist()
if (resumeSeconds !== null && resumeSeconds > 0) {
pendingSeekRef.current = resumeSeconds
}
// Start at the current track and put history in front of it, so an
// earlier song is never loaded first.
const playlist = ensurePlaylist(sources.slice(currentIndex))
for (let index = 0; index < currentIndex; index++) {
playlist.insert(sources[index], index)
}
loadedSongIdsRef.current = windowSongIds
loadedLoadKeyRef.current = loadKey
playlist.loop = repeatToPlaylistLoop(repeatEnabled)
activatePlaylistLockScreen(
playlist,
metadata ?? { title: currentSong?.title }
)
markSynced(playlist, currentSongId, currentIndex)
if (shouldPlay) {
isPlayingRef.current = true
setIsPlayingState(true)
startPlayer(playlist)
} else {
playlist.pause()
// Enable audio for the restored queue without starting playback.
try {
await setIsAudioActiveAsync(true)
} catch {
if (isCurrentLoad()) {
showError("Audio playback could not be initialized.")
}
}
}
}
void syncPlaylist().catch(() => {
if (!isCurrentLoad()) return
handlePlaybackLoadFailure()
})
return () => {
if (loadRequestIdRef.current === loadRequestId) {
loadRequestIdRef.current += 1
}
}
}, [
cacheScope,
config,
convex,
currentSongId,
currentSongSyncKey,
destroyPlaylist,
ensurePlaylist,
handlePlaybackLoadFailure,
historySyncKey,
markSynced,
queueSyncKey,
queueStartVersion,
repeatEnabled,
startPlayer,
userPlaybackKey,
])
/**
* Resolves once the native player has `songId` loaded (and playing or
* paused, if given). Rejects if the queue moves to another song first.
*/
const waitForSong = useCallback(
(songId: Id<"songs">, playing?: boolean) =>
new Promise<void>((resolve, reject) => {
const store = storeRef.current
const waiters = waitersRef.current
let songWaiters = waiters.get(songId)
if (!songWaiters) {
songWaiters = new Set()
waiters.set(songId, songWaiters)
}
const finish = (error?: Error) => {
clearTimeout(timeout)
unsubscribe()
songWaiters.delete(waiter)
if (songWaiters.size === 0 && waiters.get(songId) === songWaiters) {
waiters.delete(songId)
}
if (error) reject(error)
else resolve()
}
const waiter: PlaybackWaiter = { playing, resolve: () => finish() }
const timeout = setTimeout(
() =>
finish(
new Error(
"The audio did not become ready. Check your connection and try again."
)
),
PLAYBACK_READY_TIMEOUT_MS
)
// Starting a queue clears it and fills it in one go; only the
// settled queue counts.
const unsubscribe = store.subscribe(() => {
queueMicrotask(() => {
if (store.getState().queue[0] !== songId) {
finish(
new Error(
"The playback queue changed before the request finished."
)
)
}
})
})
songWaiters.add(waiter)
settleWaiters()
}),
[settleWaiters]
)
/**
* Starts the current song at `seconds` once it loads, and shows that
* position right away. Playback waits for the seek (see `startPlayer`).
*/
const queueSeek = useCallback((seconds: number) => {
pendingSeekRef.current = seconds
currentTimeRef.current = seconds
setCurrentTime(seconds)
}, [])
const hasPlayer = useCallback(() => playlistRef.current !== null, [])
const requestAutoPlay = useCallback(() => {
autoPlayNextRef.current = true
}, [])
return {
isPlaying,
setIsPlaying,
currentTime,
currentTimeRef,
duration,
seekTo,
queueSeek,
hasPlayer,
requestAutoPlay,
resetPosition,
resetForNewQueue,
waitForSong,
}
}
@@ -1,13 +0,0 @@
import { useServerConfig } from "@/contexts/server-config"
/**
* Resolves `currentUser.image` to a loadable URI. Stored avatars come back as
* paths on the oTunes web server; legacy ones are data URLs.
*/
export function useProfileImageUrl(image: string | undefined) {
const { config } = useServerConfig()
if (!image?.startsWith("/")) {
return image
}
return config ? `${config.serverUrl.replace(/\/+$/, "")}${image}` : undefined
}
@@ -1,110 +0,0 @@
import { useMutation } from "convex/react"
import { useCallback, useEffect, useRef, type RefObject } from "react"
import { AppState } from "react-native"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { PlaybackStore } from "@otunes/convex/client/playback-store"
import { flushPersistentCache } from "@/lib/persistent-cache"
const PROGRESS_SAVE_INTERVAL_MS = 5000
/**
* Restores the saved position when a song becomes current, and saves the
* position while it plays, on pause, and when the app leaves the foreground.
*/
export function useProgressPersistence({
store,
currentSongId,
isPlaying,
queueStartVersion,
currentTimeRef,
hasPlayer,
queueSeek,
resetPosition,
}: {
store: PlaybackStore
currentSongId: Id<"songs"> | null
isPlaying: boolean
queueStartVersion: number
currentTimeRef: RefObject<number>
hasPlayer: () => boolean
queueSeek: (seconds: number) => void
resetPosition: () => void
}) {
const updateSongProgressMutation = useMutation(
api.playback.updateSongProgress
)
const storeRef = useRef(store)
storeRef.current = store
const progressRestoredForSongRef = useRef<Id<"songs"> | null>(null)
const lastSavedProgressRef = useRef(-1)
const prevIsPlayingRef = useRef(false)
const saveProgress = useCallback(
(seconds: number) => {
const songId = storeRef.current.getState().queue[0]
if (!songId) return
const progressSeconds = Math.max(0, Math.floor(seconds))
if (progressSeconds === lastSavedProgressRef.current) return
lastSavedProgressRef.current = progressSeconds
storeRef.current.setProgress(songId, progressSeconds)
void updateSongProgressMutation({
songId,
progressSeconds,
}).catch(() => {})
},
[updateSongProgressMutation]
)
const resetProgress = useCallback(() => {
progressRestoredForSongRef.current = null
lastSavedProgressRef.current = -1
}, [])
useEffect(() => {
if (!currentSongId) {
progressRestoredForSongRef.current = null
return
}
if (progressRestoredForSongRef.current === currentSongId) return
progressRestoredForSongRef.current = currentSongId
lastSavedProgressRef.current = -1
resetPosition()
// Queue the seek before the song loads, so playback starts there.
const progressSeconds = store.getState().progressSeconds
if (progressSeconds > 0) {
queueSeek(progressSeconds)
}
}, [currentSongId, queueStartVersion, queueSeek, resetPosition, store])
useEffect(() => {
if (!currentSongId) return
if (prevIsPlayingRef.current === isPlaying) return
prevIsPlayingRef.current = isPlaying
saveProgress(currentTimeRef.current)
}, [isPlaying, currentSongId, currentTimeRef, saveProgress])
useEffect(() => {
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active") return
if (currentSongId && hasPlayer()) {
saveProgress(currentTimeRef.current)
}
flushPersistentCache()
})
return () => subscription.remove()
}, [currentSongId, currentTimeRef, hasPlayer, saveProgress])
useEffect(() => {
if (!isPlaying || !currentSongId) return
const interval = setInterval(() => {
saveProgress(currentTimeRef.current)
}, PROGRESS_SAVE_INTERVAL_MS)
return () => clearInterval(interval)
}, [isPlaying, currentSongId, currentTimeRef, saveProgress])
return { resetProgress }
}
+18 -21
View File
@@ -3,8 +3,8 @@ import { useSyncExternalStore } from "react"
const STORAGE_KEY = "otunes:artwork-colors" const STORAGE_KEY = "otunes:artwork-colors"
const listeners = new Set<() => void>() const listeners = new Set<() => void>()
// Undefined until storage has been read, so callers never act on a guess. let enabled = true
let enabled: boolean | undefined let loaded = false
let loading: Promise<void> | undefined let loading: Promise<void> | undefined
function notify() { function notify() {
@@ -13,40 +13,37 @@ function notify() {
function load() { function load() {
return (loading ??= AsyncStorage.getItem(STORAGE_KEY) return (loading ??= AsyncStorage.getItem(STORAGE_KEY)
.then((value) => value !== "false")
// Keep the default when local storage is unavailable.
.catch(() => true)
.then((value) => { .then((value) => {
enabled = value enabled = value !== "false"
})
.catch(() => {
// Keep the default when local storage is unavailable.
})
.finally(() => {
loaded = true
notify() notify()
})) }))
} }
void load()
function subscribe(listener: () => void) { function subscribe(listener: () => void) {
listeners.add(listener) listeners.add(listener)
void load()
return () => { return () => {
listeners.delete(listener) listeners.delete(listener)
} }
} }
/** /** Device preference, kept outside account data and the disposable query cache. */
* Device preference, kept outside account data and the disposable query cache.
* `undefined` until it has loaded.
*/
export function useArtworkColorsEnabled() { export function useArtworkColorsEnabled() {
return useSyncExternalStore( return useSyncExternalStore(subscribe, () => loaded && enabled, () => false)
subscribe,
() => enabled,
() => undefined
)
} }
/** Resolves with the preference once it has loaded. */ export function useArtworkColorPreferenceLoaded() {
export async function loadArtworkColorsEnabled() { return useSyncExternalStore(subscribe, () => loaded, () => false)
await load() }
return enabled ?? true
export function artworkColorsEnabled() {
return loaded && enabled
} }
export async function setArtworkColorsEnabled(value: boolean) { export async function setArtworkColorsEnabled(value: boolean) {
@@ -1,7 +1,6 @@
import { fetchQuery } from "convex/nextjs" import { fetchQuery } from "convex/nextjs"
import { convexServerOptions } from "@/lib/convex-server" import { convexServerOptions } from "@/lib/convex-server"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { Metadata } from "next" import { Metadata } from "next"
interface PageProps { interface PageProps {
@@ -12,12 +11,12 @@ export async function generateMetadata({
params, params,
}: PageProps): Promise<Metadata> { }: PageProps): Promise<Metadata> {
const { id } = await params const { id } = await params
const detail = await fetchQuery( const artists = await fetchQuery(
api.library.browseArtistDetail, api.library.browseArtists,
{ id: id as Id<"artists"> }, {},
convexServerOptions() convexServerOptions()
).catch(() => null) )
const selectedArtist = detail?.artist const selectedArtist = artists.find((artist) => artist.id === id)
return { return {
title: `${selectedArtist ? `${selectedArtist.name}` : "oTunes"}`, title: `${selectedArtist ? `${selectedArtist.name}` : "oTunes"}`,
+2 -2
View File
@@ -10,10 +10,10 @@ export async function GET(
const { id } = await params const { id } = await params
try { try {
const cover = await getConvexClient().query(api.library.getAlbumCover, { const album = await getConvexClient().query(api.library.getAlbum, {
id: id as Id<"albums">, id: id as Id<"albums">,
}) })
return serveCoverFile(cover, request) return serveCoverFile(album?.cover, request)
} catch { } catch {
return new Response("Not found", { status: 404 }) return new Response("Not found", { status: 404 })
} }
+2 -2
View File
@@ -10,10 +10,10 @@ export async function GET(
const { id } = await params const { id } = await params
try { try {
const cover = await getConvexClient().query(api.library.getArtistCover, { const artist = await getConvexClient().query(api.library.getArtist, {
id: id as Id<"artists">, id: id as Id<"artists">,
}) })
return serveCoverFile(cover, request) return serveCoverFile(artist?.cover, request)
} catch { } catch {
return new Response("Not found", { status: 404 }) return new Response("Not found", { status: 404 })
} }
@@ -9,10 +9,10 @@ export async function GET(
) { ) {
const { id } = await params const { id } = await params
try { try {
const cover = await getConvexClient().query(api.library.getPlaylistCover, { const playlist = await getConvexClient().query(api.library.getPlaylist, {
id: id as Id<"playlists">, id: id as Id<"playlists">,
}) })
return serveCoverFile(cover, request) return serveCoverFile(playlist?.cover, request)
} catch { } catch {
return new Response("Not found", { status: 404 }) return new Response("Not found", { status: 404 })
} }
+6 -2
View File
@@ -1,4 +1,6 @@
import { getSongSource } from "@/lib/server-song" import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { getConvexClient } from "@/lib/convex-server"
import { ensureHlsJob, HLS_SEGMENT_SECONDS } from "@/lib/server-hls" import { ensureHlsJob, HLS_SEGMENT_SECONDS } from "@/lib/server-hls"
import { NextRequest } from "next/server" import { NextRequest } from "next/server"
@@ -15,7 +17,9 @@ export async function GET(
const { id } = await params const { id } = await params
try { try {
const song = await getSongSource(id) const song = (await getConvexClient().query(api.library.getSong, {
id: id as Id<"songs">,
}))!
const quality = request.nextUrl.searchParams.get("quality") const quality = request.nextUrl.searchParams.get("quality")
const preferAtmos = const preferAtmos =
@@ -1,4 +1,6 @@
import { getSongSource } from "@/lib/server-song" import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { getConvexClient } from "@/lib/convex-server"
import { import {
ensureHlsJob, ensureHlsJob,
getExistingHlsJob, getExistingHlsJob,
@@ -34,11 +36,16 @@ export async function GET(
const quality = request.nextUrl.searchParams.get("quality") const quality = request.nextUrl.searchParams.get("quality")
const preferAtmos = const preferAtmos =
request.nextUrl.searchParams.get("preferAtmos") === "true" request.nextUrl.searchParams.get("preferAtmos") === "true"
// Resolve the source even when a job is cached so every segment is authorized. const existingJob = getExistingHlsJob(id, quality, preferAtmos)
const song = await getSongSource(id)
const job = const job =
getExistingHlsJob(id, quality, preferAtmos) ?? existingJob ??
(await ensureHlsJob(song, quality, preferAtmos)) (await ensureHlsJob(
(await getConvexClient().query(api.library.getSong, {
id: id as Id<"songs">,
}))!,
quality,
preferAtmos
))
if (segmentIndex >= job.segmentCount) { if (segmentIndex >= job.segmentCount) {
return new Response("Segment not found", { status: 404 }) return new Response("Segment not found", { status: 404 })
} }
+19 -10
View File
@@ -1,11 +1,13 @@
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { audioContentTypeForPath } from "@/lib/audio-content-type" import { audioContentTypeForPath } from "@/lib/audio-content-type"
import { seekableLosslessFile } from "@/lib/server-lossless" import { seekableLosslessFile } from "@/lib/server-lossless"
import { getSongSource } from "@/lib/server-song" import { getConvexClient } from "@/lib/convex-server"
import { audioInfo } from "@/lib/server-audio-info"
import { ffmpegToReadableStream, streamFile } from "@/lib/server-audio-stream" import { ffmpegToReadableStream, streamFile } from "@/lib/server-audio-stream"
import { spawnFfmpeg } from "@/lib/server-ffmpeg"
import { NextRequest, NextResponse, userAgent } from "next/server" import { NextRequest, NextResponse, userAgent } from "next/server"
import { spawn } from "node:child_process"
import fs from "node:fs/promises" import fs from "node:fs/promises"
import * as music from "music-metadata"
function parseByteRange(rangeHeader: string | null, fileSize: number) { function parseByteRange(rangeHeader: string | null, fileSize: number) {
if (!rangeHeader) { if (!rangeHeader) {
@@ -116,7 +118,9 @@ export async function GET(
const { browser } = userAgent(request) const { browser } = userAgent(request)
try { try {
const song = await getSongSource(id) const song = (await getConvexClient().query(api.library.getSong, {
id: id as Id<"songs">,
}))!
const quality = request.nextUrl.searchParams.get("quality") as const quality = request.nextUrl.searchParams.get("quality") as
"low" | "medium" | "high" | "lossless" | null "low" | "medium" | "high" | "lossless" | null
@@ -147,15 +151,14 @@ export async function GET(
transcodeNeeded = false transcodeNeeded = false
} }
const metadata = await music.parseFile(song.files[originalCodec])
if (!transcodeNeeded && originalCodec === "lossless") { if (!transcodeNeeded && originalCodec === "lossless") {
// Native iOS playback does not identify itself as Safari. // Native iOS playback does not identify itself as Safari.
const acceptsAlac = const acceptsAlac =
browser.name === "Safari" || browser.name === "Safari" ||
request.nextUrl.searchParams.get("losslessFormat") === "alac" request.nextUrl.searchParams.get("losslessFormat") === "alac"
if ( if (acceptsAlac && metadata.format.codec === "ALAC") {
acceptsAlac &&
(await audioInfo(song.files[originalCodec])).codec === "ALAC"
) {
try { try {
return await streamFileResponse( return await streamFileResponse(
request, request,
@@ -180,6 +183,11 @@ export async function GET(
(originalCodec === "atmos" || originalCodec === "normal") (originalCodec === "atmos" || originalCodec === "normal")
) { ) {
// TODO: Dolby Atmos doesn't work on Google Chrome // TODO: Dolby Atmos doesn't work on Google Chrome
console.log(
metadata.format.codec,
metadata.format.container,
metadata.format.codecProfile
)
try { try {
return await streamFileResponse( return await streamFileResponse(
request, request,
@@ -192,6 +200,7 @@ export async function GET(
} }
const ffmpegArgs = [ const ffmpegArgs = [
"-nostdin",
"-i", "-i",
song.files[originalCodec], song.files[originalCodec],
"-c:a", "-c:a",
@@ -205,8 +214,8 @@ export async function GET(
try { try {
// TODO: Fix seeking for this // TODO: Fix seeking for this
const ffmpeg = await spawnFfmpeg(ffmpegArgs, request.signal) const ffmpegProcess = spawn("ffmpeg", ffmpegArgs)
const stream = ffmpegToReadableStream(ffmpeg) const stream = ffmpegToReadableStream(ffmpegProcess)
return new NextResponse(stream, { return new NextResponse(stream, {
status: 200, status: 200,
@@ -1,55 +0,0 @@
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import sharp from "sharp"
import { getConvexClient, getConvexServerUrl } from "@/lib/convex-server"
const AVATAR_SIZE = 256
/**
* Serves a profile photo from Convex storage, downscaled. URLs carry the
* storage id (`?v=`), so a new photo gets a new URL and responses can be
* cached for good.
*/
export async function GET(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
try {
const storageUrl = await getConvexClient().query(
api.users.getProfileImageUrl,
{ userId: id as Id<"users"> }
)
if (!storageUrl) {
return new Response("Not found", { status: 404 })
}
// The backend builds storage URLs from its public origin, which may not
// be reachable from here. Fetch the same path from the internal URL.
const { pathname, search } = new URL(storageUrl)
const upstream = await fetch(
new URL(pathname + search, getConvexServerUrl())
)
if (!upstream.ok) {
return new Response("Not found", { status: 404 })
}
const data = await sharp(Buffer.from(await upstream.arrayBuffer()))
.rotate()
.resize(AVATAR_SIZE, AVATAR_SIZE, {
fit: "cover",
withoutEnlargement: true,
})
.webp({ quality: 85 })
.toBuffer()
return new Response(new Uint8Array(data), {
headers: {
"Content-Type": "image/webp",
"Cache-Control": "public, max-age=31536000, immutable",
},
})
} catch {
return new Response("Not found", { status: 404 })
}
}
+2 -2
View File
@@ -13,7 +13,7 @@ import {
MediaContextMenuItems, MediaContextMenuItems,
type MediaContextAction, type MediaContextAction,
} from "@/components/media-context-menu" } from "@/components/media-context-menu"
import { usePlaybackActions } from "@/components/playback-provider" import { usePlayback } from "@/components/playback-provider"
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
@@ -48,7 +48,7 @@ export function AlbumCard({ album }: { album: BrowseAlbum }) {
const cacheScope = useCacheScope() const cacheScope = useCacheScope()
const { openAddAlbumToPlaylist } = useAddToPlaylist() const { openAddAlbumToPlaylist } = useAddToPlaylist()
const { isAlbumFavorite, toggleAlbumFavorite } = useFavorites() const { isAlbumFavorite, toggleAlbumFavorite } = useFavorites()
const { playAlbum } = usePlaybackActions() const { playAlbum } = usePlayback()
const { runQueueAction, createStation } = useQueueMediaActions() const { runQueueAction, createStation } = useQueueMediaActions()
const [menuOpen, setMenuOpen] = React.useState(false) const [menuOpen, setMenuOpen] = React.useState(false)
const [hovered, setHovered] = React.useState(false) const [hovered, setHovered] = React.useState(false)
+253 -78
View File
@@ -4,48 +4,53 @@ import { PageHeader } from "@/components/library-skeletons"
import * as React from "react" import * as React from "react"
import Image from "next/image" import Image from "next/image"
import Link from "next/link" import Link from "next/link"
import { Play, Share2, Shuffle } from "lucide-react" import { Play, Share2, Shuffle, Star } from "lucide-react"
import { AudioFormatBadge } from "@/components/audio-format-badge" import { AudioFormatBadge } from "@/components/audio-format-badge"
import { MediaCollectionFooter } from "@/components/media-collection-footer" import { MediaCollectionFooter } from "@/components/media-collection-footer"
import { TrackNumberPlayButton } from "@/components/track-number-play-button"
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
import { FavoriteMediaButton } from "@/components/favorite-media-button" import { FavoriteMediaButton } from "@/components/favorite-media-button"
import { useFavorites } from "@/components/favorites-provider" import { useFavorites } from "@/components/favorites-provider"
import { import { usePlayback } from "@/components/playback-provider"
useCurrentSongId,
usePlaybackActions,
} from "@/components/playback-provider"
import { copyAlbumLink } from "@/lib/media-links" import { copyAlbumLink } from "@/lib/media-links"
import { import {
MediaContextMenu, MediaContextMenu,
type MediaContextAction, type MediaContextAction,
} from "@/components/media-context-menu" } from "@/components/media-context-menu"
import { TrackRow } from "@/components/track-row"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area" import { ScrollArea } from "@/components/ui/scroll-area"
import { useCachedQuery } from "@/hooks/use-cached-query" import { useCachedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import { import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
useMediaActions,
useTrackListMediaAction,
} from "@/hooks/use-media-actions"
import { useTrackSelection } from "@/hooks/use-track-selection" import { useTrackSelection } from "@/hooks/use-track-selection"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
import type { import type { BrowseAlbumDetail, BrowseAlbumTrack } from "@otunes/convex/types"
BrowseAlbumDetail,
BrowseAlbumTrack,
BrowseSong,
} from "@otunes/convex/types"
import { import {
getSelectionRangePositions, getSelectionRangePositions,
isInSelectionRange,
ALBUM_TRACK_ROW,
ALBUM_TRACK_TITLE,
SelectionRangeHighlight,
TRACK_LIST_CONTAINER, TRACK_LIST_CONTAINER,
TrackRowActiveHighlight,
TrackRowHoverHighlight,
TRACK_ROW_PADDING,
type SelectionRangePosition,
} from "@/lib/selection-range-styles" } from "@/lib/selection-range-styles"
import { albumCoverUrl } from "@/lib/cover-urls" import { albumCoverUrl } from "@/lib/cover-urls"
import { sumDurationSeconds } from "@/lib/media-summary" import { sumDurationSeconds } from "@/lib/media-summary"
import { albumDetailSongs, rememberSongs } from "@/lib/song-cache" import { albumDetailSongs, rememberSongs } from "@/lib/song-cache"
function formatDuration(seconds: number): string {
const minutes = Math.floor(seconds / 60)
const remainingSeconds = seconds % 60
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
}
function formatMetadata(genre: string | null, year: number | null): string | null { function formatMetadata(genre: string | null, year: number | null): string | null {
const parts: string[] = [] const parts: string[] = []
if (genre) { if (genre) {
@@ -95,6 +100,159 @@ function groupAlbumTracksByDisk(tracks: BrowseAlbumTrack[]): AlbumTrackSection[]
return sections return sections
} }
function TrackRow({
track,
sectionIndex,
artist,
isActive,
isSelected,
selectionPosition,
isFavorite,
selectedCount,
onSelect,
onPointerDown,
onToggleFavorite,
onPrepareContextMenu,
onMediaAction,
isNowPlaying,
onPlay,
albumId,
}: {
track: BrowseAlbumTrack
sectionIndex: number
artist: BrowseAlbumDetail["artist"]
albumId: string
isActive: boolean
isSelected: boolean
selectionPosition: SelectionRangePosition
isFavorite: boolean
selectedCount: number
onSelect: (event: React.MouseEvent) => void
onPointerDown: (event: React.MouseEvent) => void
onToggleFavorite: () => void
onPrepareContextMenu: () => void
onMediaAction: (action: MediaContextAction, trackId: string) => void
isNowPlaying: boolean
onPlay: () => void
}) {
const displayTrack =
track.track > 0 ? track.track : sectionIndex + 1
const inRange = isInSelectionRange(selectionPosition)
return (
<div
role="button"
tabIndex={0}
onMouseDown={onPointerDown}
onClick={onSelect}
onDoubleClick={(event) => {
event.preventDefault()
onPlay()
}}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault()
onSelect(event as unknown as React.MouseEvent)
}
}}
className={cn(
"group relative w-full cursor-pointer select-none py-2.5 text-left text-sm transition-colors",
inRange && "text-primary-foreground"
)}
>
<SelectionRangeHighlight position={selectionPosition} />
{!inRange && isActive ? <TrackRowActiveHighlight /> : null}
{!inRange && !isActive ? <TrackRowHoverHighlight /> : null}
<div
className={cn("relative z-10", ALBUM_TRACK_ROW, TRACK_ROW_PADDING)}
>
<div className="flex shrink-0 items-center justify-center">
<Button
variant="ghost"
size="icon-sm"
className={cn(
"size-8 opacity-0 transition-opacity group-hover:opacity-100",
inRange
? "text-primary-foreground hover:bg-white/15 hover:text-primary-foreground"
: "text-primary hover:text-primary",
(isFavorite || isActive || isSelected) && "opacity-100"
)}
aria-label={
isFavorite
? `Remove ${track.title} from favorites`
: `Favorite ${track.title}`
}
onClick={(event) => {
event.stopPropagation()
onToggleFavorite()
}}
>
<Star
className={cn(
"size-4",
isFavorite && (inRange ? "fill-current" : "fill-primary")
)}
/>
</Button>
</div>
<TrackNumberPlayButton
displayTrack={displayTrack}
title={track.title}
isActive={isActive}
isNowPlaying={isNowPlaying}
inRange={inRange}
onPlay={onPlay}
/>
<div className="min-w-0 flex-1">
<div className={ALBUM_TRACK_TITLE}>{track.title}</div>
{track.artists ? (
<p
className={cn(
"truncate text-xs",
inRange
? "text-primary-foreground/80"
: "text-muted-foreground"
)}
>
{track.artists.join(", ")}
</p>
) : null}
</div>
<span
className={cn(
"shrink-0 text-right tabular-nums",
inRange ? "text-primary-foreground" : "text-muted-foreground"
)}
>
{formatDuration(track.durationSeconds)}
</span>
<MediaContextMenu
label={`More options for ${track.title}`}
stationArtistId={artist.id}
selectedCount={selectedCount}
inSelectionRange={inRange}
onOpenMenu={onPrepareContextMenu}
onAction={(action) => onMediaAction(action, track.id)}
favorited={isFavorite}
navigation={{
artist: { id: artist.id },
album: { id: albumId },
}}
share={{
type: "song",
albumId,
songId: track.id,
}}
/>
</div>
</div>
)
}
export function AlbumView({ export function AlbumView({
album, album,
highlightedSongId, highlightedSongId,
@@ -102,15 +260,17 @@ export function AlbumView({
album: BrowseAlbumDetail album: BrowseAlbumDetail
highlightedSongId?: string highlightedSongId?: string
}) { }) {
const { openAddToPlaylist } = useAddToPlaylist()
const { const {
isSongFavorite, isSongFavorite,
isAlbumFavorite, isAlbumFavorite,
toggleSongFavorite, toggleSongFavorite,
toggleAlbumFavorite, toggleAlbumFavorite,
favoriteSongs,
} = useFavorites() } = useFavorites()
const currentSongId = useCurrentSongId() const { currentSong, playFromSong, playAlbum, playAlbumShuffled } =
const { playFromSong, playAlbum, playAlbumShuffled } = usePlaybackActions() usePlayback()
const { runSongsAction } = useMediaActions() const { runQueueAction, createStation } = useQueueMediaActions()
const albumSongIds = React.useMemo( const albumSongIds = React.useMemo(
() => album.tracks.map((track) => track.id as Id<"songs">), () => album.tracks.map((track) => track.id as Id<"songs">),
[album.tracks] [album.tracks]
@@ -148,6 +308,7 @@ export function AlbumView({
const { const {
selectedIds, selectedIds,
selectedCount, selectedCount,
isSelected,
handleSelect, handleSelect,
handlePointerDown, handlePointerDown,
prepareContextMenu, prepareContextMenu,
@@ -175,55 +336,55 @@ export function AlbumView({
return indexById return indexById
}, [album.tracks]) }, [album.tracks])
const trackSongs = React.useMemo( function handleMediaAction(
() => action: MediaContextAction,
new Map<string, BrowseSong>( fallbackTrackId?: string
album.tracks.map((track) => [ ) {
track.id, const targetIds =
{ selectedIds.size > 0
id: track.id, ? Array.from(selectedIds)
title: track.title, : fallbackTrackId
durationSeconds: track.durationSeconds, ? [fallbackTrackId]
artist: album.artist, : activeTrackId
album: { id: album.id, title: album.title, cover: album.cover }, ? [activeTrackId]
}, : []
]) switch (action) {
), case "create-station":
[album.tracks, album.artist, album.id, album.title, album.cover] void createStation(album.artist.id)
) break
case "favorite":
const handleMediaAction = useTrackListMediaAction({ void favoriteSongs(targetIds as Id<"songs">[])
selectedIds, break
artistId: album.artist.id, case "playlist":
}) openAddToPlaylist(targetIds as Id<"songs">[])
break
const handleRowSelect = React.useCallback( case "play-next":
(index: number, event: React.MouseEvent) => { case "play-last":
const trackId = album.tracks[index].id case "shuffle":
handleSelect(trackId, index, event) void runQueueAction(action, targetIds as Id<"songs">[])
setActiveTrackId(trackId) break
}, }
[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) { function handleAlbumMediaAction(action: MediaContextAction) {
if (action === "favorite") { const targetIds = album.tracks.map((track) => track.id as Id<"songs">)
void toggleAlbumFavorite(album.id as Id<"albums">)
return 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
} }
runSongsAction(action, albumSongIds, album.artist.id)
} }
return ( return (
@@ -357,25 +518,39 @@ export function AlbumView({
return ( return (
<TrackRow <TrackRow
key={track.id} key={track.id}
variant="album" track={track}
song={trackSongs.get(track.id)!} sectionIndex={sectionTrackIndex}
index={listIndex} artist={album.artist}
trackNumber={ albumId={album.id}
track.track > 0 ? track.track : sectionTrackIndex + 1
}
subtitle={track.artists?.join(", ")}
isActive={track.id === activeTrackId} isActive={track.id === activeTrackId}
isSelected={isSelected(track.id)}
selectionPosition={selectionPositions[listIndex]} selectionPosition={selectionPositions[listIndex]}
isFavorite={isSongFavorite(track.id)} isFavorite={isSongFavorite(track.id)}
selectedCount={selectedCount} selectedCount={
selectionStationArtistId={album.artist.id} isSelected(track.id) && selectedCount > 0
isNowPlaying={currentSongId === track.id} ? selectedCount
: 1
}
onPointerDown={handlePointerDown} onPointerDown={handlePointerDown}
onSelect={handleRowSelect} onSelect={(event) => {
onPlay={handleRowPlay} handleSelect(track.id, listIndex, event)
onToggleFavorite={handleToggleFavorite} setActiveTrackId(track.id)
onPrepareContextMenu={prepareContextMenu} }}
onToggleFavorite={() =>
void toggleSongFavorite(track.id as Id<"songs">)
}
onPrepareContextMenu={() =>
prepareContextMenu(track.id)
}
onMediaAction={handleMediaAction} onMediaAction={handleMediaAction}
isNowPlaying={currentSong?.id === track.id}
onPlay={() =>
void playFromSong(
track.id as Id<"songs">,
albumSongIds,
`album:${album.id}`
)
}
/> />
) )
})} })}
+40 -6
View File
@@ -4,19 +4,27 @@ import { PageHeader } from "@/components/library-skeletons"
import * as React from "react" import * as React from "react"
import Image from "next/image" import Image from "next/image"
import { Play, Shuffle } from "lucide-react" 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 { useFavorites } from "@/components/favorites-provider"
import { usePlaybackActions } from "@/components/playback-provider" import { usePlayback } from "@/components/playback-provider"
import { useMediaActions } from "@/hooks/use-media-actions" import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import { AlbumCard } from "@/components/album-card" import { AlbumCard } from "@/components/album-card"
import { FavoriteMediaButton } from "@/components/favorite-media-button" import { FavoriteMediaButton } from "@/components/favorite-media-button"
import { MediaContextMenu } from "@/components/media-context-menu" import {
MediaContextMenu,
type MediaContextAction,
} from "@/components/media-context-menu"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area" import { ScrollArea } from "@/components/ui/scroll-area"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types" import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
import { albumGridClassName } from "@/lib/album-grid-classes" import { albumGridClassName } from "@/lib/album-grid-classes"
import { artistCoverUrl } from "@/lib/cover-urls" import { artistCoverUrl } from "@/lib/cover-urls"
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
export function ArtistView({ export function ArtistView({
artist, artist,
@@ -26,8 +34,34 @@ export function ArtistView({
albums: BrowseAlbum[] albums: BrowseAlbum[]
}) { }) {
const { isArtistFavorite, toggleArtistFavorite } = useFavorites() const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
const { playArtist, playArtistShuffled } = usePlaybackActions() const { openAddArtistToPlaylist } = useAddToPlaylist()
const { runArtistAction } = useMediaActions() const { playArtist, playArtistShuffled } = usePlayback()
const { runQueueAction } = useQueueMediaActions()
const convex = useConvex()
const cacheScope = useCacheScope()
async function handleMediaAction(action: MediaContextAction) {
switch (action) {
case "favorite":
void toggleArtistFavorite(artist.id as Id<"artists">)
break
case "playlist":
void openAddArtistToPlaylist(artist.id as Id<"artists">)
break
case "play-next":
case "play-last":
case "shuffle": {
const songIds = await fetchCachedQuery(
convex,
cacheScope,
api.playlists.getOrderedArtistSongIds,
{ artistId: artist.id as Id<"artists"> }
)
void runQueueAction(action, songIds)
break
}
}
}
return ( return (
<div className="flex h-svh flex-col"> <div className="flex h-svh flex-col">
@@ -84,7 +118,7 @@ export function ArtistView({
label={`More options for ${artist.name}`} label={`More options for ${artist.name}`}
selectedCount={albums.length} selectedCount={albums.length}
onOpenMenu={() => {}} onOpenMenu={() => {}}
onAction={(action) => void runArtistAction(action, artist.id)} onAction={handleMediaAction}
favorited={isArtistFavorite(artist.id)} favorited={isArtistFavorite(artist.id)}
trackRowTrigger={false} trackRowTrigger={false}
triggerVariant="secondary" triggerVariant="secondary"
+66 -40
View File
@@ -4,24 +4,27 @@ import * as React from "react"
import Image from "next/image" import Image from "next/image"
import Link from "next/link" import Link from "next/link"
import { ChevronRightIcon, Play, Shuffle } from "lucide-react" 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 { AlbumCard } from "@/components/album-card"
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
import { FavoriteMediaButton } from "@/components/favorite-media-button" import { FavoriteMediaButton } from "@/components/favorite-media-button"
import { useFavorites } from "@/components/favorites-provider" import { useFavorites } from "@/components/favorites-provider"
import { import {
MediaContextMenu, MediaContextMenu,
type MediaContextAction, type MediaContextAction,
MediaContextMenuArea,
type MediaContextMenuProps,
} from "@/components/media-context-menu" } from "@/components/media-context-menu"
import { usePlaybackActions } from "@/components/playback-provider" import { usePlayback } from "@/components/playback-provider"
import { useMediaActions } from "@/hooks/use-media-actions" import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area" import { ScrollArea } from "@/components/ui/scroll-area"
import { api } from "@otunes/convex/_generated/api"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types" import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
import { artistCoverUrl } from "@/lib/cover-urls" import { artistCoverUrl } from "@/lib/cover-urls"
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
function ArtistAvatar({ artist }: { artist: BrowseArtist }) { function ArtistAvatar({ artist }: { artist: BrowseArtist }) {
return ( return (
@@ -52,42 +55,36 @@ function ArtistListItem({
onSelect: () => void onSelect: () => void
onMediaAction: (action: MediaContextAction) => void onMediaAction: (action: MediaContextAction) => void
}) { }) {
const menu: MediaContextMenuProps = {
label: `More options for ${artist.name}`,
selectedCount: albumCount,
inSelectionRange: isSelected,
onOpenMenu: () => {},
onAction: onMediaAction,
favorited: isFavorite,
share: { type: "artist", artistId: artist.id },
}
return ( return (
<MediaContextMenuArea menu={menu}> <div
<div className={cn(
"group flex w-full min-w-0 items-center gap-1 overflow-hidden pr-1",
isSelected ? "bg-primary text-primary-foreground" : "hover:bg-muted/50"
)}
>
<button
type="button"
onClick={onSelect}
className={cn( className={cn(
"group flex w-full min-w-0 items-center gap-1 overflow-hidden pr-1", "flex min-w-0 flex-1 items-center gap-3 overflow-hidden px-4 py-2.5 text-left text-sm transition-colors",
isSelected isSelected ? "text-primary-foreground" : ""
? "bg-primary text-primary-foreground"
: "hover:bg-muted/50"
)} )}
> >
<button <ArtistAvatar artist={artist} />
type="button" <span className="min-w-0 flex-1 truncate font-medium">
onClick={onSelect} {artist.name}
className={cn( </span>
"flex min-w-0 flex-1 items-center gap-3 overflow-hidden px-4 py-2.5 text-left text-sm transition-colors", </button>
isSelected ? "text-primary-foreground" : "" <MediaContextMenu
)} label={`More options for ${artist.name}`}
> selectedCount={albumCount}
<ArtistAvatar artist={artist} /> inSelectionRange={isSelected}
<span className="min-w-0 flex-1 truncate font-medium"> onOpenMenu={() => {}}
{artist.name} onAction={onMediaAction}
</span> favorited={isFavorite}
</button> share={{ type: "artist", artistId: artist.id }}
<MediaContextMenu {...menu} /> />
</div> </div>
</MediaContextMenuArea>
) )
} }
@@ -113,9 +110,12 @@ export function ArtistsView({
} }
return sortedArtists[0]?.id ?? "" return sortedArtists[0]?.id ?? ""
}, [artistId, sortedArtists]) }, [artistId, sortedArtists])
const convex = useConvex()
const cacheScope = useCacheScope()
const { openAddArtistToPlaylist } = useAddToPlaylist()
const { isArtistFavorite, toggleArtistFavorite } = useFavorites() const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
const { playArtist, playArtistShuffled } = usePlaybackActions() const { playArtist, playArtistShuffled } = usePlayback()
const { runArtistAction } = useMediaActions() const { runQueueAction } = useQueueMediaActions()
const selectedArtist = sortedArtists.find( const selectedArtist = sortedArtists.find(
(artist) => artist.id === selectedId (artist) => artist.id === selectedId
@@ -130,6 +130,32 @@ export function ArtistsView({
return counts return counts
}, [albums]) }, [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 ( return (
<div className="flex min-h-0 flex-1"> <div className="flex min-h-0 flex-1">
<ScrollArea className="w-72 shrink-0 border-r"> <ScrollArea className="w-72 shrink-0 border-r">
@@ -143,7 +169,7 @@ export function ArtistsView({
isFavorite={isArtistFavorite(artist.id)} isFavorite={isArtistFavorite(artist.id)}
onSelect={() => onSelectArtist(artist.id)} onSelect={() => onSelectArtist(artist.id)}
onMediaAction={(action) => onMediaAction={(action) =>
void runArtistAction(action, artist.id) void handleMediaAction(artist.id, action)
} }
/> />
))} ))}
@@ -199,7 +225,7 @@ export function ArtistsView({
selectedCount={artistAlbums.length} selectedCount={artistAlbums.length}
onOpenMenu={() => {}} onOpenMenu={() => {}}
onAction={(action) => onAction={(action) =>
void runArtistAction(action, selectedArtist.id) void handleMediaAction(selectedArtist.id, action)
} }
favorited={isArtistFavorite(selectedArtist.id)} favorited={isArtistFavorite(selectedArtist.id)}
trackRowTrigger={false} trackRowTrigger={false}
+50 -118
View File
@@ -3,25 +3,18 @@
import * as React from "react" import * as React from "react"
import Link from "next/link" import Link from "next/link"
import { import {
GalleryVerticalEnd, Disc3,
ListEnd, ListEnd,
ListPlus, ListPlus,
ListStart, ListStart,
MicVocal,
MoreHorizontal, MoreHorizontal,
Share2, Share2,
Shuffle, Shuffle,
Star, Star,
User,
} from "lucide-react" } from "lucide-react"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import {
ContextMenu,
ContextMenuContent,
ContextMenuItem,
ContextMenuSeparator,
ContextMenuTrigger,
} from "@/components/ui/context-menu"
import { import {
DropdownMenu, DropdownMenu,
DropdownMenuContent, DropdownMenuContent,
@@ -29,7 +22,10 @@ import {
DropdownMenuSeparator, DropdownMenuSeparator,
DropdownMenuTrigger, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu" } from "@/components/ui/dropdown-menu"
import { copyMediaShareLink, type MediaShareContext } from "@/lib/media-links" import {
copyMediaShareLink,
type MediaShareContext,
} from "@/lib/media-links"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
export type MediaContextAction = export type MediaContextAction =
@@ -60,28 +56,6 @@ function shouldShowShare(
return true return true
} }
// Lets the same items render inside a dropdown or a right-click menu.
const MenuKindContext = React.createContext<"dropdown" | "context">("dropdown")
/** Menu item that works in both `MediaContextMenu` and `MediaContextMenuArea`. */
export function MediaMenuItem(
props: React.ComponentProps<typeof DropdownMenuItem>
) {
return React.use(MenuKindContext) === "context" ? (
<ContextMenuItem {...props} />
) : (
<DropdownMenuItem {...props} />
)
}
export function MediaMenuSeparator() {
return React.use(MenuKindContext) === "context" ? (
<ContextMenuSeparator />
) : (
<DropdownMenuSeparator />
)
}
function actionLabel(base: string, selectedCount: number) { function actionLabel(base: string, selectedCount: number) {
return selectedCount > 1 ? `${base} (${selectedCount})` : base return selectedCount > 1 ? `${base} (${selectedCount})` : base
} }
@@ -112,86 +86,86 @@ export function MediaContextMenuItems({
<> <>
{showShare ? ( {showShare ? (
<> <>
<MediaMenuItem <DropdownMenuItem
className="justify-between" className="justify-between"
onClick={() => void copyMediaShareLink(share!)} onClick={() => void copyMediaShareLink(share!)}
> >
Share Share
<Share2 /> <Share2 />
</MediaMenuItem> </DropdownMenuItem>
<MediaMenuSeparator /> <DropdownMenuSeparator />
</> </>
) : null} ) : null}
<MediaMenuItem <DropdownMenuItem
className="justify-between" className="justify-between"
onClick={() => onAction("playlist")} onClick={() => onAction("playlist")}
> >
{actionLabel(playlistLabel, selectedCount)} {actionLabel(playlistLabel, selectedCount)}
<ListPlus /> <ListPlus />
</MediaMenuItem> </DropdownMenuItem>
<MediaMenuSeparator /> <DropdownMenuSeparator />
<MediaMenuItem <DropdownMenuItem
className="justify-between" className="justify-between"
onClick={() => onAction("play-next")} onClick={() => onAction("play-next")}
> >
{actionLabel("Play Next", selectedCount)} {actionLabel("Play Next", selectedCount)}
<ListStart /> <ListStart />
</MediaMenuItem> </DropdownMenuItem>
<MediaMenuItem <DropdownMenuItem
className="justify-between" className="justify-between"
onClick={() => onAction("play-last")} onClick={() => onAction("play-last")}
> >
{actionLabel("Play Last", selectedCount)} {actionLabel("Play Last", selectedCount)}
<ListEnd /> <ListEnd />
</MediaMenuItem> </DropdownMenuItem>
<MediaMenuItem <DropdownMenuItem
className="justify-between" className="justify-between"
onClick={() => onAction("shuffle")} onClick={() => onAction("shuffle")}
> >
{actionLabel("Shuffle", selectedCount)} {actionLabel("Shuffle", selectedCount)}
<Shuffle /> <Shuffle />
</MediaMenuItem> </DropdownMenuItem>
{stationArtistId ? ( {stationArtistId ? (
<MediaMenuItem <DropdownMenuItem
className="justify-between" className="justify-between"
onClick={() => onAction("create-station")} onClick={() => onAction("create-station")}
> >
Create Station Create Station
<Shuffle /> <Shuffle />
</MediaMenuItem> </DropdownMenuItem>
) : null} ) : null}
{artist || album ? ( {artist || album ? (
<> <>
<MediaMenuSeparator /> <DropdownMenuSeparator />
{artist ? ( {artist ? (
<MediaMenuItem asChild className="justify-between"> <DropdownMenuItem asChild className="justify-between">
<Link href={`/artist/${artist.id}`}> <Link href={`/artist/${artist.id}`}>
Go to Artist Go to Artist
<MicVocal /> <User />
</Link> </Link>
</MediaMenuItem> </DropdownMenuItem>
) : null} ) : null}
{album ? ( {album ? (
<MediaMenuItem asChild className="justify-between"> <DropdownMenuItem asChild className="justify-between">
<Link href={`/album/${album.id}`}> <Link href={`/album/${album.id}`}>
Go to Album Go to Album
<GalleryVerticalEnd /> <Disc3 />
</Link> </Link>
</MediaMenuItem> </DropdownMenuItem>
) : null} ) : null}
</> </>
) : null} ) : null}
{showFavorite ? ( {showFavorite ? (
<> <>
<MediaMenuSeparator /> <DropdownMenuSeparator />
<MediaMenuItem <DropdownMenuItem
variant={favorited ? "destructive" : "default"} variant={favorited ? "destructive" : "default"}
className="justify-between" className="justify-between"
onClick={() => onAction("favorite")} onClick={() => onAction("favorite")}
> >
{actionLabel(favorited ? "Unfavorite" : "Favorite", selectedCount)} {actionLabel(favorited ? "Unfavorite" : "Favorite", selectedCount)}
<Star /> <Star />
</MediaMenuItem> </DropdownMenuItem>
</> </>
) : null} ) : null}
</> </>
@@ -223,67 +197,6 @@ export function mediaContextMenuTriggerClassName({
) )
} }
export type MediaContextMenuProps = {
label: string
selectedCount: number
onOpenMenu: () => void
onAction: (action: MediaContextAction) => void
playlistLabel?: string
showFavorite?: boolean
favorited?: boolean
stationArtistId?: string
navigation?: MediaContextNavigation
share?: MediaShareContext
inSelectionRange?: boolean
/** When false, the trigger uses default button/dropdown styling (page headers). */
trackRowTrigger?: boolean
triggerClassName?: string
triggerVariant?: "ghost" | "secondary"
triggerIconClassName?: string
align?: "start" | "end"
/** Extra items; use `MediaMenuItem` so they also work in the right-click menu. */
children?: React.ReactNode
}
/**
* Opens `menu` (the props given to the row's `MediaContextMenu`) when
* `children`, a single element such as a track row, is right-clicked.
*/
export function MediaContextMenuArea({
menu,
children,
}: {
menu: MediaContextMenuProps
children: React.ReactElement
}) {
return (
<ContextMenu
onOpenChange={(open) => {
if (open) {
menu.onOpenMenu()
}
}}
>
<ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
<ContextMenuContent className="w-48">
<MenuKindContext value="context">
<MediaContextMenuItems
selectedCount={menu.selectedCount}
onAction={menu.onAction}
playlistLabel={menu.playlistLabel}
showFavorite={menu.showFavorite}
favorited={menu.favorited}
stationArtistId={menu.stationArtistId}
navigation={menu.navigation}
share={menu.share}
/>
{menu.children}
</MenuKindContext>
</ContextMenuContent>
</ContextMenu>
)
}
export function MediaContextMenu({ export function MediaContextMenu({
label, label,
selectedCount, selectedCount,
@@ -302,7 +215,26 @@ export function MediaContextMenu({
triggerIconClassName = "size-4", triggerIconClassName = "size-4",
align = "end", align = "end",
children, children,
}: MediaContextMenuProps) { }: {
label: string
selectedCount: number
onOpenMenu: () => void
onAction: (action: MediaContextAction) => void
playlistLabel?: string
showFavorite?: boolean
favorited?: boolean
stationArtistId?: string
navigation?: MediaContextNavigation
share?: MediaShareContext
inSelectionRange?: boolean
/** When false, the trigger uses default button/dropdown styling (page headers). */
trackRowTrigger?: boolean
triggerClassName?: string
triggerVariant?: "ghost" | "secondary"
triggerIconClassName?: string
align?: "start" | "end"
children?: React.ReactNode
}) {
return ( return (
<DropdownMenu <DropdownMenu
onOpenChange={(open) => { onOpenChange={(open) => {
+32 -85
View File
@@ -102,26 +102,7 @@ type PlaybackContextValue = {
dolbyAtmosSupported: boolean | null dolbyAtmosSupported: boolean | null
} }
type PlaybackActions = Omit<
PlaybackContextValue,
| "queueSongIds"
| "queueHistorySongIds"
| "currentFormat"
| "currentSong"
| "shuffleEnabled"
| "repeatEnabled"
| "queueOpen"
| "isPlaying"
| "volume"
| "dolbyAtmosSupported"
>
const PlaybackContext = createContext<PlaybackContextValue | null>(null) const PlaybackContext = createContext<PlaybackContextValue | null>(null)
// Long lists read these narrow contexts so playback state changes do not
// re-render every row.
const PlaybackActionsContext = createContext<PlaybackActions | null>(null)
const CurrentSongIdContext = createContext<Id<"songs"> | null>(null)
const IsPlayingContext = createContext(false)
const PlaybackProgressContext = createContext<{ const PlaybackProgressContext = createContext<{
currentTime: number currentTime: number
duration: number duration: number
@@ -320,22 +301,6 @@ export function usePlayback() {
return context return context
} }
export function usePlaybackActions() {
const context = useContext(PlaybackActionsContext)
if (!context) {
throw new Error("usePlaybackActions must be used within PlaybackProvider")
}
return context
}
export function useCurrentSongId() {
return useContext(CurrentSongIdContext)
}
export function useIsPlaying() {
return useContext(IsPlayingContext)
}
export function usePlaybackProgress() { export function usePlaybackProgress() {
const context = useContext(PlaybackProgressContext) const context = useContext(PlaybackProgressContext)
if (!context) { if (!context) {
@@ -374,19 +339,17 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
if (!isSignedIn) { if (!isSignedIn) {
return return
} }
store.setTransport({ store.setTransport((state) =>
sync: (state) => syncPlaybackStateMutation({
syncPlaybackStateMutation({ songQueue: state.queue,
songQueue: state.queue, queueHistory: state.history,
queueHistory: state.history, shuffleEnabled: state.shuffleEnabled,
shuffleEnabled: state.shuffleEnabled, repeatEnabled: state.repeatEnabled,
repeatEnabled: state.repeatEnabled, currentSongProgress: state.progressSeconds,
currentSongProgress: state.progressSeconds, })
}), )
loadProgress: () => convex.query(api.playback.getSongProgress, {}),
})
return () => store.setTransport(null) return () => store.setTransport(null)
}, [store, isSignedIn, syncPlaybackStateMutation, convex]) }, [store, isSignedIn, syncPlaybackStateMutation])
useEffect(() => { useEffect(() => {
if (!serverPlayback) { if (!serverPlayback) {
@@ -992,7 +955,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
if (!shouldContinuePlaying) { if (!shouldContinuePlaying) {
autoPlayNextRef.current = false autoPlayNextRef.current = false
isPlayingRef.current = false isPlayingRef.current = false
audio.pause()
audio.currentTime = 0 audio.currentTime = 0
currentTimeRef.current = 0 currentTimeRef.current = 0
setCurrentTime(0) setCurrentTime(0)
@@ -1398,8 +1360,17 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
) )
: null : null
const actions = useMemo<PlaybackActions>( const value = useMemo<PlaybackContextValue>(
() => ({ () => ({
queueSongIds: playback.queue,
queueHistorySongIds: playback.history,
currentSong,
currentFormat,
shuffleEnabled: playback.shuffleEnabled,
repeatEnabled: playback.repeatEnabled,
queueOpen,
isPlaying: isPlaybackActive,
volume,
setQueueOpen, setQueueOpen,
toggleQueueOpen, toggleQueueOpen,
setIsPlaying, setIsPlaying,
@@ -1423,8 +1394,15 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
skipToQueueIndex, skipToQueueIndex,
skipNext, skipNext,
skipPrevious, skipPrevious,
dolbyAtmosSupported,
}), }),
[ [
playback,
currentSong,
currentFormat,
queueOpen,
isPlaybackActive,
volume,
toggleQueueOpen, toggleQueueOpen,
setVolume, setVolume,
playInOrder, playInOrder,
@@ -1446,31 +1424,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
skipToQueueIndex, skipToQueueIndex,
skipNext, skipNext,
skipPrevious, skipPrevious,
]
)
const value = useMemo<PlaybackContextValue>(
() => ({
...actions,
queueSongIds: playback.queue,
queueHistorySongIds: playback.history,
currentSong,
currentFormat,
shuffleEnabled: playback.shuffleEnabled,
repeatEnabled: playback.repeatEnabled,
queueOpen,
isPlaying: isPlaybackActive,
volume,
dolbyAtmosSupported,
}),
[
actions,
playback,
currentSong,
currentFormat,
queueOpen,
isPlaybackActive,
volume,
dolbyAtmosSupported, dolbyAtmosSupported,
] ]
) )
@@ -1481,16 +1434,10 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
) )
return ( return (
<PlaybackActionsContext.Provider value={actions}> <PlaybackContext.Provider value={value}>
<CurrentSongIdContext.Provider value={currentSongId}> <PlaybackProgressContext.Provider value={progressValue}>
<IsPlayingContext.Provider value={isPlaybackActive}> {children}
<PlaybackContext.Provider value={value}> </PlaybackProgressContext.Provider>
<PlaybackProgressContext.Provider value={progressValue}> </PlaybackContext.Provider>
{children}
</PlaybackProgressContext.Provider>
</PlaybackContext.Provider>
</IsPlayingContext.Provider>
</CurrentSongIdContext.Provider>
</PlaybackActionsContext.Provider>
) )
} }
+32 -33
View File
@@ -31,39 +31,12 @@ import { Slider } from "@/components/ui/slider"
import { useSidebar } from "@/components/ui/sidebar" import { useSidebar } from "@/components/ui/sidebar"
import { albumCoverUrl } from "@/lib/cover-urls" import { albumCoverUrl } from "@/lib/cover-urls"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import { formatDuration } from "@/lib/format-duration"
function PlayerSeekBar({ hasActiveSong }: { hasActiveSong: boolean }) { function formatDuration(seconds: number): string {
const { currentTime, duration, seekTo } = usePlaybackProgress() const total = Math.max(0, Math.floor(seconds))
const [isSeeking, setIsSeeking] = React.useState(false) const minutes = Math.floor(total / 60)
const [seekValue, setSeekValue] = React.useState(0) const remainingSeconds = total % 60
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
const displayTime = hasActiveSong ? (isSeeking ? seekValue : currentTime) : 0
const maxDuration = Math.max(duration, 1)
return (
<Slider
className={cn(
"h-3 flex-1 [&_[data-slot=slider-range]]:bg-current/80 [&_[data-slot=slider-thumb]]:size-2 [&_[data-slot=slider-thumb]]:border-current [&_[data-slot=slider-thumb]]:bg-current [&_[data-slot=slider-thumb]]:opacity-0 focus-within:[&_[data-slot=slider-thumb]]:opacity-100 hover:[&_[data-slot=slider-thumb]]:opacity-100 [&_[data-slot=slider-track]]:h-[3px] [&_[data-slot=slider-track]]:bg-current/30 md:[&_[data-slot=slider-track]]:h-0.5",
!hasActiveSong && "[&_[data-slot=slider-thumb]]:hidden"
)}
min={0}
max={maxDuration}
step={0.1}
value={[displayTime]}
disabled={!hasActiveSong}
onValueChange={([value]) => {
setIsSeeking(true)
setSeekValue(value)
}}
onValueCommit={([value]) => {
seekTo(value)
setIsSeeking(false)
}}
aria-label="Seek"
aria-valuetext={`${formatDuration(displayTime)} of ${formatDuration(duration)}`}
/>
)
} }
export function PlayerBar() { export function PlayerBar() {
@@ -84,10 +57,16 @@ export function PlayerBar() {
skipNext, skipNext,
skipPrevious, skipPrevious,
} = usePlayback() } = usePlayback()
const { currentTime, duration, seekTo } = usePlaybackProgress()
const { state, isMobile } = useSidebar() const { state, isMobile } = useSidebar()
const [isSeeking, setIsSeeking] = React.useState(false)
const [seekValue, setSeekValue] = React.useState(0)
const hasQueue = queueSongIds.length > 0 const hasQueue = queueSongIds.length > 0
const hasActiveSong = Boolean(currentSong)
const sidebarExpanded = !isMobile && state === "expanded" const sidebarExpanded = !isMobile && state === "expanded"
const displayTime = hasActiveSong ? (isSeeking ? seekValue : currentTime) : 0
const maxDuration = Math.max(duration, 1)
return ( return (
<div <div
@@ -219,7 +198,27 @@ export function PlayerBar() {
/> />
)} )}
<div className="absolute inset-x-0 -bottom-1"> <div className="absolute inset-x-0 -bottom-1">
<PlayerSeekBar hasActiveSong={Boolean(currentSong)} /> <Slider
className={cn(
"h-3 flex-1 [&_[data-slot=slider-range]]:bg-current/80 [&_[data-slot=slider-thumb]]:size-2 [&_[data-slot=slider-thumb]]:border-current [&_[data-slot=slider-thumb]]:bg-current [&_[data-slot=slider-thumb]]:opacity-0 focus-within:[&_[data-slot=slider-thumb]]:opacity-100 hover:[&_[data-slot=slider-thumb]]:opacity-100 [&_[data-slot=slider-track]]:h-[3px] [&_[data-slot=slider-track]]:bg-current/30 md:[&_[data-slot=slider-track]]:h-0.5",
!hasActiveSong && "[&_[data-slot=slider-thumb]]:hidden"
)}
min={0}
max={maxDuration}
step={0.1}
value={[displayTime]}
disabled={!hasActiveSong}
onValueChange={([value]) => {
setIsSeeking(true)
setSeekValue(value)
}}
onValueCommit={([value]) => {
seekTo(value)
setIsSeeking(false)
}}
aria-label="Seek"
aria-valuetext={`${formatDuration(displayTime)} of ${formatDuration(duration)}`}
/>
</div> </div>
</div> </div>
+2 -2
View File
@@ -15,7 +15,7 @@ import {
MediaContextMenuItems, MediaContextMenuItems,
type MediaContextAction, type MediaContextAction,
} from "@/components/media-context-menu" } from "@/components/media-context-menu"
import { usePlaybackActions } from "@/components/playback-provider" import { usePlayback } from "@/components/playback-provider"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { import {
DropdownMenu, DropdownMenu,
@@ -30,7 +30,7 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
const convex = useConvex() const convex = useConvex()
const cacheScope = useCacheScope() const cacheScope = useCacheScope()
const { openAddPlaylistToPlaylist } = useAddToPlaylist() const { openAddPlaylistToPlaylist } = useAddToPlaylist()
const { playPlaylist } = usePlaybackActions() const { playPlaylist } = usePlayback()
const { runQueueAction } = useQueueMediaActions() const { runQueueAction } = useQueueMediaActions()
async function handleCardAction(action: MediaContextAction) { async function handleCardAction(action: MediaContextAction) {
+378 -99
View File
@@ -9,18 +9,15 @@ import { useMutation } from "convex/react"
import { Play, SearchIcon, Share2, Shuffle, Star, Trash2 } from "lucide-react" import { Play, SearchIcon, Share2, Shuffle, Star, Trash2 } from "lucide-react"
import { toast } from "sonner" import { toast } from "sonner"
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
import { useFavorites } from "@/components/favorites-provider" import { useFavorites } from "@/components/favorites-provider"
import { import { usePlayback } from "@/components/playback-provider"
useCurrentSongId,
usePlaybackActions,
} from "@/components/playback-provider"
import { MediaCollectionFooter } from "@/components/media-collection-footer" import { MediaCollectionFooter } from "@/components/media-collection-footer"
import { TrackNumberPlayButton } from "@/components/track-number-play-button"
import { import {
MediaContextMenu, MediaContextMenu,
type MediaContextAction, type MediaContextAction,
} from "@/components/media-context-menu" } from "@/components/media-context-menu"
import { TrackRow } from "@/components/track-row"
import { VirtualList } from "@/components/virtual-list"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { import {
DropdownMenuItem, DropdownMenuItem,
@@ -28,22 +25,247 @@ import {
} from "@/components/ui/dropdown-menu" } from "@/components/ui/dropdown-menu"
import { ScrollArea } from "@/components/ui/scroll-area" import { ScrollArea } from "@/components/ui/scroll-area"
import { useCachedQuery } from "@/hooks/use-cached-query" import { useCachedQuery } from "@/hooks/use-cached-query"
import { import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
useMediaActions,
useTrackListMediaAction,
} from "@/hooks/use-media-actions"
import { useTrackSelection } from "@/hooks/use-track-selection" import { useTrackSelection } from "@/hooks/use-track-selection"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowsePlaylistDetail, BrowseSong } from "@otunes/convex/types" import type { BrowsePlaylistDetail, BrowseSong } from "@otunes/convex/types"
import { playlistCoverUrl } from "@/lib/cover-urls" import { albumCoverUrl, playlistCoverUrl } from "@/lib/cover-urls"
import { copyPlaylistLink } from "@/lib/media-links" import { copyPlaylistLink } from "@/lib/media-links"
import { sumDurationSeconds } from "@/lib/media-summary" import { sumDurationSeconds } from "@/lib/media-summary"
import { rememberSongs } from "@/lib/song-cache" import { rememberSongs } from "@/lib/song-cache"
import { getSelectionRangePositions } from "@/lib/selection-range-styles" 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"
const ADD_TO_ANOTHER_PLAYLIST = "Add to Another Playlist" 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 (
<div
className={cn(
"group/cover relative size-10 shrink-0 overflow-hidden rounded ring-1",
inRange ? "ring-white/25" : "ring-foreground/10"
)}
>
<Image
src={albumCoverUrl(song.album.id)}
alt={song.album.title}
fill
sizes="40px"
className="object-cover"
/>
<div
className={cn(
"absolute inset-0 flex items-center justify-center bg-black/0 opacity-0 transition-opacity group-hover/cover:opacity-100",
"group-hover/cover:bg-black/40"
)}
>
<Button
variant="ghost"
size="icon-sm"
className={cn(
"size-8",
inRange
? "text-primary-foreground hover:bg-white/15 hover:text-primary-foreground"
: "text-primary hover:text-primary"
)}
aria-label={
isFavorite
? `Remove ${song.title} from favorites`
: `Favorite ${song.title}`
}
onClick={(event) => {
event.stopPropagation()
onToggleFavorite()
}}
>
<Star
className={cn(
"size-4",
isFavorite && (inRange ? "fill-current" : "fill-primary")
)}
/>
</Button>
</div>
</div>
)
}
function PlaylistSongRow({
song,
index,
isOwner,
canRemove,
isActive,
selectionPosition,
isFavorite,
selectedCount,
stationArtist,
isDragging,
onSelect,
onPointerDown,
onToggleFavorite,
onPrepareContextMenu,
onMediaAction,
onRemove,
onDragStart,
onDragOver,
onDrop,
showFavoriteInMenu = true,
removeLabel = "Remove from Playlist",
isNowPlaying,
onPlay,
}: {
song: BrowseSong
index: number
isOwner: boolean
canRemove: boolean
isActive: boolean
selectionPosition: SelectionRangePosition
isFavorite: boolean
selectedCount: number
stationArtist?: string
isDragging: boolean
onSelect: (event: React.MouseEvent) => void
onPointerDown: (event: React.MouseEvent) => void
onToggleFavorite: () => void
onPrepareContextMenu: () => void
onMediaAction: (action: MediaContextAction, songId: string) => void
onRemove: () => void
onDragStart: (event: React.DragEvent) => void
onDragOver: (event: React.DragEvent) => void
onDrop: (event: React.DragEvent) => void
showFavoriteInMenu?: boolean
removeLabel?: string
isNowPlaying: boolean
onPlay: () => void
}) {
const displayTrack = index + 1
const inRange = isInSelectionRange(selectionPosition)
return (
<div
role="button"
tabIndex={0}
draggable={isOwner}
onDragStart={onDragStart}
onDragOver={onDragOver}
onDrop={onDrop}
onMouseDown={onPointerDown}
onClick={onSelect}
onDoubleClick={(event) => {
event.preventDefault()
onPlay()
}}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault()
onSelect(event as unknown as React.MouseEvent)
}
}}
className={cn(
"group relative w-full cursor-pointer select-none py-2.5 text-left text-sm transition-colors",
inRange && "text-primary-foreground",
isDragging && "opacity-50"
)}
>
<SelectionRangeHighlight position={selectionPosition} />
{!inRange && isActive ? <TrackRowActiveHighlight /> : null}
{!inRange && !isActive ? <TrackRowHoverHighlight /> : null}
<div
className={cn("relative z-10", ALBUM_TRACK_ROW, TRACK_ROW_PADDING)}
>
<PlaylistSongCover
song={song}
inRange={inRange}
isFavorite={isFavorite}
onToggleFavorite={onToggleFavorite}
/>
<TrackNumberPlayButton
displayTrack={displayTrack}
title={song.title}
isActive={isActive}
isNowPlaying={isNowPlaying}
inRange={inRange}
onPlay={onPlay}
/>
<span className={ALBUM_TRACK_TITLE}>{song.title}</span>
<span
className={cn(
"shrink-0 text-right tabular-nums",
inRange ? "text-primary-foreground" : "text-muted-foreground"
)}
>
{formatDuration(song.durationSeconds)}
</span>
<MediaContextMenu
label={`More options for ${song.title}`}
stationArtistId={stationArtist}
selectedCount={selectedCount}
inSelectionRange={inRange}
onOpenMenu={onPrepareContextMenu}
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,
}}
>
{canRemove ? (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
variant="destructive"
className="justify-between"
onClick={onRemove}
>
{removeLabel}
<Trash2 />
</DropdownMenuItem>
</>
) : null}
</MediaContextMenu>
</div>
</div>
)
}
export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
const router = useRouter() const router = useRouter()
@@ -53,17 +275,22 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
currentUser === undefined currentUser === undefined
? playlist.isOwner ? playlist.isOwner
: currentUser?._id === playlist.owner.id : currentUser?._id === playlist.owner.id
const { isSongFavorite, toggleSongFavorite, toggleSongsFavorite } = const { openAddToPlaylist } = useAddToPlaylist()
useFavorites()
const currentSongId = useCurrentSongId()
const { const {
isSongFavorite,
toggleSongFavorite,
toggleSongsFavorite,
favoriteSongs: addFavoriteSongs,
} = useFavorites()
const {
currentSong,
playInOrder, playInOrder,
playShuffled, playShuffled,
playPlaylist, playPlaylist,
playPlaylistShuffled, playPlaylistShuffled,
playFromSong, playFromSong,
} = usePlaybackActions() } = usePlayback()
const { runSongsAction } = useMediaActions() const { runQueueAction, createStation } = useQueueMediaActions()
const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist) const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist)
const reorderSongs = useMutation(api.playlists.reorderPlaylistSongs) const reorderSongs = useMutation(api.playlists.reorderPlaylistSongs)
const deletePlaylist = useMutation(api.playlists.deletePlaylist) const deletePlaylist = useMutation(api.playlists.deletePlaylist)
@@ -95,10 +322,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
() => songs.map((song) => song.id as Id<"songs">), () => songs.map((song) => song.id as Id<"songs">),
[songs] [songs]
) )
const playlistPositionById = React.useMemo(
() => new Map(songs.map((song, index) => [song.id, index + 1])),
[songs]
)
const [activeTrackId, setActiveTrackId] = React.useState("") const [activeTrackId, setActiveTrackId] = React.useState("")
const [dragIndex, setDragIndex] = React.useState<number | null>(null) const [dragIndex, setDragIndex] = React.useState<number | null>(null)
const [isSubscribed, setIsSubscribed] = React.useState(playlist.isSubscribed) const [isSubscribed, setIsSubscribed] = React.useState(playlist.isSubscribed)
@@ -113,6 +336,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
const { const {
selectedIds, selectedIds,
selectedCount, selectedCount,
isSelected,
handleSelect, handleSelect,
handlePointerDown, handlePointerDown,
prepareContextMenu, prepareContextMenu,
@@ -150,37 +374,57 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
} }
} }
const handleMediaAction = useTrackListMediaAction({ selectedIds, songs }) function resolveTargetIds(fallbackSongId?: string) {
return selectedIds.size > 0
? Array.from(selectedIds)
: fallbackSongId
? [fallbackSongId]
: activeTrackId
? [activeTrackId]
: []
}
function handleMediaAction(
action: MediaContextAction,
fallbackSongId?: string
) {
const targetIds = resolveTargetIds(fallbackSongId)
switch (action) {
case "create-station": {
const artistId = stationArtistId(songs, new Set(targetIds))
if (artistId) void createStation(artistId)
break
}
case "favorite":
void addFavoriteSongs(targetIds as Id<"songs">[])
break
case "playlist":
openAddToPlaylist(targetIds as Id<"songs">[])
break
case "play-next":
case "play-last":
case "shuffle":
void runQueueAction(action, targetIds as Id<"songs">[])
break
}
}
function handlePlaylistMediaAction(action: MediaContextAction) { function handlePlaylistMediaAction(action: MediaContextAction) {
runSongsAction(action, playlistSongIds) const targetIds = songs.map((song) => song.id as Id<"songs">)
}
const canReorder = isOwner && !isFavorites && !normalizedQuery switch (action) {
case "favorite":
function handleRowSelect(index: number, event: React.MouseEvent) { void addFavoriteSongs(targetIds)
const songId = filteredSongs[index].id break
handleSelect(songId, index, event) case "playlist":
setActiveTrackId(songId) openAddToPlaylist(targetIds)
} break
case "play-next":
function handleRowPlay(index: number) { case "play-last":
void playFromSong( case "shuffle":
filteredSongs[index].id, void runQueueAction(action, targetIds)
playlistSongIds, break
`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
})
} }
} }
@@ -191,7 +435,10 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
: [songId] : [songId]
if (isFavorites) { if (isFavorites) {
const succeeded = await toggleSongsFavorite(ids as Id<"songs">[], true) const succeeded = await toggleSongsFavorite(
ids as Id<"songs">[],
true
)
if (!succeeded) return if (!succeeded) return
return return
} }
@@ -204,9 +451,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
setPlaylistSongs((current) => setPlaylistSongs((current) =>
current.filter((song) => !ids.includes(song.id)) current.filter((song) => !ids.includes(song.id))
) )
toast.success( toast.success(ids.length > 1 ? `Removed ${ids.length} songs` : "Removed song")
ids.length > 1 ? `Removed ${ids.length} songs` : "Removed song"
)
} catch (error) { } catch (error) {
toast.error( toast.error(
error instanceof Error ? error.message : "Failed to remove song" error instanceof Error ? error.message : "Failed to remove song"
@@ -234,7 +479,13 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
} }
function handleDrop(targetIndex: number) { function handleDrop(targetIndex: number) {
if (!canReorder || dragIndex === null || dragIndex === targetIndex) { if (
normalizedQuery ||
isFavorites ||
!isOwner ||
dragIndex === null ||
dragIndex === targetIndex
) {
setDragIndex(null) setDragIndex(null)
return return
} }
@@ -295,7 +546,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
<PageHeader openApp /> <PageHeader openApp />
<ScrollArea className="min-h-0 flex-1"> <ScrollArea className="min-h-0 flex-1">
<div className="pb-28"> <div className="pb-28">
<div className="mx-auto w-full max-w-9/10 min-w-0"> <div className="mx-auto w-full min-w-0 max-w-9/10">
<div className="flex flex-col gap-8 px-6 pt-6 pb-8 sm:flex-row sm:items-end"> <div className="flex flex-col gap-8 px-6 pt-6 pb-8 sm:flex-row sm:items-end">
<div className="relative mx-auto aspect-square w-full max-w-60 shrink-0 overflow-hidden rounded-lg ring-1 ring-foreground/10 sm:mx-0"> <div className="relative mx-auto aspect-square w-full max-w-60 shrink-0 overflow-hidden rounded-lg ring-1 ring-foreground/10 sm:mx-0">
{isFavorites ? ( {isFavorites ? (
@@ -425,49 +676,77 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
</div> </div>
</div> </div>
{filteredSongs.length > 0 ? ( {filteredSongs.length > 0 ? (
<VirtualList filteredSongs.map((song, index) => (
count={filteredSongs.length} <PlaylistSongRow
estimateSize={estimatePlaylistRowSize} key={song.id}
getItemKey={(index) => filteredSongs[index].id} song={song}
// Keep the drag source mounted so its drop still lands. index={index}
keepMounted={dragIndex} isOwner={isOwner && !isFavorites && !normalizedQuery}
renderItem={(index) => { canRemove={isFavorites || isOwner}
const song = filteredSongs[index] showFavoriteInMenu={!isFavorites}
return ( removeLabel={
<TrackRow isFavorites ? "Unfavorite" : "Remove from Playlist"
variant="playlist" }
song={song} isActive={song.id === activeTrackId}
index={index} selectionPosition={selectionPositions[index]}
trackNumber={playlistPositionById.get(song.id)} isFavorite={isSongFavorite(song.id)}
isActive={song.id === activeTrackId} selectedCount={
isNowPlaying={currentSongId === song.id} isSelected(song.id) && selectedCount > 0
isFavorite={isSongFavorite(song.id)} ? selectedCount
isDragging={dragIndex === index} : 1
selectionPosition={selectionPositions[index]} }
selectedCount={selectedCount} stationArtist={
selectionStationArtistId={selectedStationArtistId} isSelected(song.id)
playlistLabel={ADD_TO_ANOTHER_PLAYLIST} ? selectedStationArtistId
showFavoriteInMenu={!isFavorites} : song.artist.id
removeLabel={ }
isFavorites isDragging={dragIndex === index}
? "Unfavorite" onPointerDown={handlePointerDown}
: isOwner onSelect={(event) => {
? "Remove from Playlist" handleSelect(song.id, index, event)
: undefined setActiveTrackId(song.id)
} }}
onPointerDown={handlePointerDown} onToggleFavorite={() => {
onSelect={handleRowSelect} const wasFavorite = isSongFavorite(song.id)
onPlay={handleRowPlay} void toggleSongFavorite(song.id as Id<"songs">)
onToggleFavorite={handleToggleFavorite} if (isFavorites && wasFavorite) {
onPrepareContextMenu={prepareContextMenu} setHiddenFavoriteIds((current) => {
onMediaAction={handleMediaAction} const next = new Set(current)
onRemove={handleRemoveSong} next.add(song.id)
onDragStart={canReorder ? setDragIndex : undefined} return next
onDrop={canReorder ? handleDrop : undefined} })
/> }
) }}
}} onPrepareContextMenu={() => prepareContextMenu(song.id)}
/> onMediaAction={handleMediaAction}
onRemove={() => handleRemoveSong(song.id)}
onDragStart={(event) => {
if (normalizedQuery || isFavorites || !isOwner) {
return
}
setDragIndex(index)
event.dataTransfer.effectAllowed = "move"
}}
onDragOver={(event) => {
if (normalizedQuery || isFavorites || !isOwner) {
return
}
event.preventDefault()
}}
onDrop={(event) => {
event.preventDefault()
handleDrop(index)
}}
isNowPlaying={currentSong?.id === song.id}
onPlay={() =>
void playFromSong(
song.id as Id<"songs">,
playlistSongIds,
`playlist:${playlist.id}`
)
}
/>
))
) : ( ) : (
<p className="px-6 py-8 text-sm text-muted-foreground"> <p className="px-6 py-8 text-sm text-muted-foreground">
{normalizedQuery {normalizedQuery
+176 -37
View File
@@ -1,10 +1,11 @@
"use client" "use client"
import * as React from "react" import * as React from "react"
import Image from "next/image"
import { Music2 } from "lucide-react"
import { PlaybackSongMeta } from "@/components/playback-song-meta" import { PlaybackSongMeta } from "@/components/playback-song-meta"
import { usePlayback } from "@/components/playback-provider" import { usePlayback } from "@/components/playback-provider"
import { TrackCover, TrackRow } from "@/components/track-row"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area" import { ScrollArea } from "@/components/ui/scroll-area"
import { Skeleton } from "@/components/ui/skeleton" import { Skeleton } from "@/components/ui/skeleton"
@@ -12,14 +13,21 @@ import { Spinner } from "@/components/ui/spinner"
import { useTrackSelection } from "@/hooks/use-track-selection" import { useTrackSelection } from "@/hooks/use-track-selection"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong, HistorySong, QueueSong } from "@otunes/convex/types" import type { BrowseSong, HistorySong, QueueSong } from "@otunes/convex/types"
import { albumCoverUrl } from "@/lib/cover-urls"
import { import {
getContiguousSelectedIndices, getContiguousSelectedIndices,
moveQueueBlock, moveQueueBlock,
} from "@/lib/move-queue-block" } from "@/lib/move-queue-block"
import { getSelectionRangePositions } from "@/lib/selection-range-styles" import {
getSelectionRangePositions,
isInSelectionRange,
QueueSelectionRangeHighlight,
QueueTrackRowActiveHighlight,
QueueTrackRowHoverHighlight,
type SelectionRangePosition,
} from "@/lib/selection-range-styles"
import { useSongs } from "@/lib/song-cache" import { useSongs } from "@/lib/song-cache"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import { formatDuration } from "@/lib/format-duration"
const QUEUE_INITIAL_VISIBLE_COUNT = 100 const QUEUE_INITIAL_VISIBLE_COUNT = 100
const QUEUE_PAGE_SIZE = 50 const QUEUE_PAGE_SIZE = 50
@@ -32,6 +40,12 @@ type QueueItem = {
song: QueueSelectable | null 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( function toSelectableQueue(
songIds: Id<"songs">[], songIds: Id<"songs">[],
songs: (BrowseSong | undefined)[] songs: (BrowseSong | undefined)[]
@@ -47,16 +61,48 @@ function toSelectableQueue(
}) })
} }
function QueueSongCover({
albumId,
title,
inRange,
}: {
albumId: string
title: string
inRange: boolean
}) {
return (
<div
className={cn(
"relative size-10 shrink-0 overflow-hidden ring-1",
inRange ? "ring-white/25" : "ring-foreground/10"
)}
>
<Image
src={albumCoverUrl(albumId)}
alt={title}
fill
sizes="40px"
className="object-cover"
/>
</div>
)
}
function HistorySongRow({ song }: { song: HistorySong }) { function HistorySongRow({ song }: { song: HistorySong }) {
return ( return (
<li className="relative w-full py-2 text-left text-sm opacity-60"> <li className="relative w-full py-2 text-left text-sm opacity-60">
<div className="relative z-10 flex items-center gap-3 px-2"> <div className="relative z-10 flex items-center gap-3 px-2">
<TrackCover {song.album.id ? (
albumId={song.album.id} <QueueSongCover
alt={song.album.title} albumId={song.album.id}
inRange={false} title={song.album.title}
square inRange={false}
/> />
) : (
<div className="flex size-10 shrink-0 items-center justify-center bg-muted ring-1 ring-foreground/10">
<Music2 className="size-4 text-muted-foreground" />
</div>
)}
<PlaybackSongMeta <PlaybackSongMeta
song={song} song={song}
@@ -74,6 +120,106 @@ function HistorySongRow({ song }: { song: HistorySong }) {
) )
} }
const QueueSongRow = React.forwardRef<
HTMLLIElement,
{
song: QueueSelectable
isNowPlaying: boolean
selectionPosition: SelectionRangePosition
isDragging: boolean
onSelect: (event: React.MouseEvent) => 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 (
<li
ref={ref}
role="button"
tabIndex={0}
draggable
onDragStart={onDragStart}
onDragOver={onDragOver}
onDrop={onDrop}
onMouseDown={onPointerDown}
onClick={onSelect}
onDoubleClick={(event) => {
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"
)}
>
<QueueSelectionRangeHighlight position={selectionPosition} />
{!inRange && isNowPlaying ? <QueueTrackRowActiveHighlight /> : null}
{!inRange && !isNowPlaying ? <QueueTrackRowHoverHighlight /> : null}
<div className="relative z-10 flex items-center gap-3 px-2">
{song.album.id ? (
<QueueSongCover
albumId={song.album.id}
title={song.album.title}
inRange={inRange}
/>
) : (
<div
className={cn(
"flex size-10 shrink-0 items-center justify-center bg-muted ring-1",
inRange ? "ring-white/25" : "ring-foreground/10"
)}
>
<Music2 className="size-4 text-muted-foreground" />
</div>
)}
<PlaybackSongMeta
song={song}
isCurrent={isNowPlaying}
inRange={inRange}
align="start"
showAlbum={false}
/>
<span
className={cn(
"shrink-0 text-xs tabular-nums",
inRange ? "text-primary-foreground" : "text-muted-foreground"
)}
>
{formatDuration(song.durationSeconds)}
</span>
</div>
</li>
)
})
function QueueSongRowSkeleton() { function QueueSongRowSkeleton() {
return ( return (
<li className="flex items-center gap-3 px-2 py-2" aria-hidden> <li className="flex items-center gap-3 px-2 py-2" aria-hidden>
@@ -97,7 +243,7 @@ export function QueuePanel() {
skipToQueueIndex, skipToQueueIndex,
} = usePlayback() } = usePlayback()
const loadMoreRef = React.useRef<HTMLDivElement>(null) const loadMoreRef = React.useRef<HTMLDivElement>(null)
const nowPlayingRef = React.useRef<HTMLElement>(null) const nowPlayingRef = React.useRef<HTMLLIElement>(null)
const [visibleCount, setVisibleCount] = React.useState( const [visibleCount, setVisibleCount] = React.useState(
QUEUE_INITIAL_VISIBLE_COUNT QUEUE_INITIAL_VISIBLE_COUNT
) )
@@ -165,25 +311,12 @@ export function QueuePanel() {
return () => observer.disconnect() return () => observer.disconnect()
}, [hasMore]) }, [hasMore])
const selectionItems = React.useMemo( const {
() => selectableQueue.map((item) => ({ id: item.selectionId })), selectedIds,
[selectableQueue] handleSelect,
) handlePointerDown,
const { selectedIds, handleSelect, handlePointerDown } = } = useTrackSelection(
useTrackSelection(selectionItems) selectableQueue.map((item) => ({ id: item.selectionId }))
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( const selectionPositions = React.useMemo(
@@ -270,21 +403,27 @@ export function QueuePanel() {
<ul className="flex flex-col py-1"> <ul className="flex flex-col py-1">
{selectableQueue.map((item, index) => {selectableQueue.map((item, index) =>
item.song ? ( item.song ? (
<TrackRow <QueueSongRow
key={item.selectionId} key={item.selectionId}
ref={item.queueIndex === 0 ? nowPlayingRef : undefined} ref={item.queueIndex === 0 ? nowPlayingRef : undefined}
variant="queue"
song={item.song} song={item.song}
index={index}
isActive={item.queueIndex === 0}
isNowPlaying={item.queueIndex === 0} isNowPlaying={item.queueIndex === 0}
selectionPosition={selectionPositions[index]} selectionPosition={selectionPositions[index]}
isDragging={draggingIndices.has(index)} isDragging={draggingIndices.has(index)}
onPointerDown={handlePointerDown} onPointerDown={handlePointerDown}
onSelect={handleRowSelect} onSelect={(event) => {
onPlay={handleRowPlay} handleSelect(item.selectionId, index, event)
onDragStart={setDragIndex} }}
onDrop={handleDrop} onSkipTo={() => void skipToQueueIndex(item.queueIndex)}
onDragStart={(event) => {
setDragIndex(index)
event.dataTransfer.effectAllowed = "move"
}}
onDragOver={(event) => event.preventDefault()}
onDrop={(event) => {
event.preventDefault()
handleDrop(index)
}}
/> />
) : ( ) : (
<QueueSongRowSkeleton key={item.selectionId} /> <QueueSongRowSkeleton key={item.selectionId} />
+42 -49
View File
@@ -8,8 +8,6 @@ import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import { import {
MediaContextMenu, MediaContextMenu,
type MediaContextAction, type MediaContextAction,
MediaContextMenuArea,
type MediaContextMenuProps,
} from "@/components/media-context-menu" } from "@/components/media-context-menu"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong } from "@otunes/convex/types" import type { BrowseSong } from "@otunes/convex/types"
@@ -40,57 +38,52 @@ export function SearchSongItem({ song }: { song: BrowseSong }) {
} }
} }
const menu: MediaContextMenuProps = {
label: `More options for ${song.title}`,
stationArtistId: song.artist.id,
selectedCount: 1,
onOpenMenu: () => {},
onAction: handleAction,
favorited: isSongFavorite(song.id),
navigation: {
artist: { id: song.artist.id },
album: { id: song.album.id },
},
share: {
type: "song",
albumId: song.album.id,
songId: song.id,
},
triggerClassName:
"size-8 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100",
triggerVariant: "ghost",
}
return ( return (
<MediaContextMenuArea menu={menu}> <div className="group flex items-center gap-3 rounded-lg px-1 py-1.5 transition-colors hover:bg-muted/50">
<div className="group flex items-center gap-3 rounded-lg px-1 py-1.5 transition-colors hover:bg-muted/50"> <Link
href={`/album/${song.album.id}`}
className="relative size-11 shrink-0 overflow-hidden rounded ring-1 ring-foreground/10"
>
<Image
src={albumCoverUrl(song.album.id)}
alt={song.album.title}
fill
sizes="44px"
className="object-cover"
/>
</Link>
<div className="min-w-0 flex-1">
<Link href={`/album/${song.album.id}`} className="hover:underline">
<p className="truncate text-sm font-medium">{song.title}</p>
</Link>
<Link <Link
href={`/album/${song.album.id}`} href={`/artist/${song.artist.id}`}
className="relative size-11 shrink-0 overflow-hidden rounded ring-1 ring-foreground/10" className="text-muted-foreground hover:text-foreground hover:underline"
> >
<Image <p className="truncate text-sm">{song.artist.name}</p>
src={albumCoverUrl(song.album.id)}
alt={song.album.title}
fill
sizes="44px"
className="object-cover"
/>
</Link> </Link>
<div className="min-w-0 flex-1">
<Link href={`/album/${song.album.id}`} className="hover:underline">
<p className="truncate text-sm font-medium">{song.title}</p>
</Link>
<Link
href={`/artist/${song.artist.id}`}
className="text-muted-foreground hover:text-foreground hover:underline"
>
<p className="truncate text-sm">{song.artist.name}</p>
</Link>
</div>
<MediaContextMenu {...menu} />
</div> </div>
</MediaContextMenuArea>
<MediaContextMenu
label={`More options for ${song.title}`}
stationArtistId={song.artist.id}
selectedCount={1}
onOpenMenu={() => {}}
onAction={handleAction}
favorited={isSongFavorite(song.id)}
navigation={{
artist: { id: song.artist.id },
album: { id: song.album.id },
}}
share={{
type: "song",
albumId: song.album.id,
songId: song.id,
}}
triggerClassName="size-8 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100"
triggerVariant="ghost"
/>
</div>
) )
} }
+328 -61
View File
@@ -2,20 +2,18 @@
import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger" import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger"
import { stationArtistId } from "@/lib/station-artist" import { stationArtistId } from "@/lib/station-artist"
import { import { useEffect, useMemo, useState, useRef, MouseEvent } from "react"
useCallback, import Image from "next/image"
useEffect, import Link from "next/link"
useMemo, import { ArrowUpDown, Play, Star } from "lucide-react"
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 { useFavorites } from "@/components/favorites-provider"
import { usePlaybackActions } from "@/components/playback-provider" import { usePlayback } from "@/components/playback-provider"
import { LibraryTrackListHeader, TrackRow } from "@/components/track-row" import {
import { VirtualList } from "@/components/virtual-list" MediaContextMenu,
type MediaContextAction,
} from "@/components/media-context-menu"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { import {
DropdownMenu, DropdownMenu,
@@ -27,28 +25,252 @@ import {
DropdownMenuTrigger, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu" } from "@/components/ui/dropdown-menu"
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query" import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
import { useTrackListMediaAction } from "@/hooks/use-media-actions" import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import { useTrackSelection } from "@/hooks/use-track-selection" import { useTrackSelection } from "@/hooks/use-track-selection"
import { SongListSkeleton } from "@/components/library-skeletons" import { SongListSkeleton } from "@/components/library-skeletons"
import { ScrollArea } from "@/components/ui/scroll-area" import { ScrollArea } from "@/components/ui/scroll-area"
import { Spinner } from "@/components/ui/spinner" import { Spinner } from "@/components/ui/spinner"
import { api } from "@otunes/convex/_generated/api" import { api } from "@otunes/convex/_generated/api"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong } from "@otunes/convex/types"
import { albumCoverUrl } from "@/lib/cover-urls"
import { import {
getSelectionRangePositions, getSelectionRangePositions,
isInSelectionRange,
ALBUM_TRACK_TITLE,
SongsSelectionRangeHighlight,
SongsTrackRowHoverHighlight,
TRACK_ROW_PADDING, TRACK_ROW_PADDING,
type SelectionRangePosition,
} from "@/lib/selection-range-styles" } from "@/lib/selection-range-styles"
type SortKey = "title" | "artist" | "album" type SortKey = "title" | "artist" | "album"
type SortDirection = "asc" | "desc" type SortDirection = "asc" | "desc"
const SONGS_PAGE_SIZE = 50 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 (
<div
className={cn(
"relative size-10 shrink-0 overflow-hidden rounded ring-1",
inRange ? "ring-white/25" : "ring-foreground/10"
)}
>
<Image
src={albumCoverUrl(song.album.id)}
alt={song.album.title}
fill
sizes="40px"
className="object-cover"
/>
<div className="absolute inset-0 flex items-center justify-center bg-black/0 transition-colors group-hover:bg-black/40">
<Button
size="icon-sm"
className="size-7 rounded-full opacity-0 transition-opacity group-hover:opacity-100"
aria-label={`Play ${song.title}`}
onClick={(event) => {
event.preventDefault()
event.stopPropagation()
onPlay()
}}
>
<Play className="size-3 fill-current" />
</Button>
</div>
</div>
)
}
function SongRow({
song,
isSelected,
selectionPosition,
isFavorite,
selectedCount,
stationArtist,
onSelect,
onPointerDown,
onToggleFavorite,
onPrepareContextMenu,
onMediaAction,
onPlay,
}: {
song: BrowseSong
isSelected: boolean
selectionPosition: SelectionRangePosition
isFavorite: boolean
selectedCount: number
stationArtist?: string
onSelect: (event: MouseEvent) => void
onPointerDown: (event: MouseEvent) => void
onToggleFavorite: () => void
onPrepareContextMenu: () => void
onMediaAction: (action: MediaContextAction, songId: string) => void
onPlay: () => void
}) {
const inRange = isInSelectionRange(selectionPosition)
const linkClass = inRange
? "text-primary-foreground hover:text-primary-foreground/80 hover:underline"
: "text-muted-foreground hover:text-foreground hover:underline"
return (
<TableRow
onMouseDown={onPointerDown}
onClick={onSelect}
onDoubleClick={(event) => {
event.preventDefault()
onPlay()
}}
className="group cursor-pointer select-none border-none hover:bg-transparent"
>
<TableCell colSpan={4} className="p-0">
<div
className={cn(
"relative py-2",
inRange && "text-primary-foreground"
)}
>
<SongsSelectionRangeHighlight position={selectionPosition} />
{!inRange ? <SongsTrackRowHoverHighlight /> : null}
<div
className={cn("relative z-10", songRowLayout, TRACK_ROW_PADDING)}
>
<div className={nameColumnLayout}>
<div className="flex items-center justify-center">
<Button
variant="ghost"
size="icon-sm"
className={cn(
"size-8 opacity-0 transition-opacity group-hover:opacity-100",
inRange
? "text-primary-foreground hover:bg-white/15 hover:text-primary-foreground"
: "text-primary hover:text-primary",
(isFavorite || isSelected) && "opacity-100"
)}
aria-label={
isFavorite
? `Remove ${song.title} from favorites`
: `Favorite ${song.title}`
}
onClick={(event) => {
event.stopPropagation()
onToggleFavorite()
}}
>
<Star
className={cn(
"size-4",
isFavorite && (inRange ? "fill-current" : "fill-primary")
)}
/>
</Button>
</div>
<SongCover song={song} inRange={inRange} onPlay={onPlay} />
<span className={ALBUM_TRACK_TITLE}>
{song.title}
{song.explicit ? (
<span
className={cn(
"ml-1.5 inline-flex size-3.5 shrink-0 items-center justify-center rounded-sm text-[9px] font-semibold leading-none",
inRange
? "bg-white/20 text-primary-foreground"
: "bg-muted-foreground/20 text-muted-foreground"
)}
aria-label="Explicit"
>
E
</span>
) : null}
</span>
</div>
<div className={songColumnClass}>
<Link
href={"/artist/" + song.artist.id}
className={linkClass}
onClick={(event) => event.stopPropagation()}
>
{song.artist.name}
</Link>
</div>
<div className={songColumnClass}>
<Link
href={"/album/" + song.album.id}
className={linkClass}
onClick={(event) => event.stopPropagation()}
>
{song.album.title}
</Link>
</div>
<div className="min-w-4 flex-1" />
<span
className={cn(
"shrink-0 text-right tabular-nums",
inRange ? "text-primary-foreground" : "text-muted-foreground"
)}
>
{formatDuration(song.durationSeconds)}
</span>
<MediaContextMenu
label={`More options for ${song.title}`}
stationArtistId={stationArtist}
selectedCount={selectedCount}
align="end"
inSelectionRange={inRange}
onOpenMenu={onPrepareContextMenu}
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,
}}
/>
</div>
</div>
</TableCell>
</TableRow>
)
}
export function SongsView() { export function SongsView() {
const { isSongFavorite, toggleSongFavorite } = useFavorites() const { openAddToPlaylist } = useAddToPlaylist()
const { playFromLibrarySong } = usePlaybackActions() const { isSongFavorite, toggleSongFavorite, favoriteSongs } = useFavorites()
const { playFromLibrarySong } = usePlayback()
const { runQueueAction, createStation } = useQueueMediaActions()
const [sortKey, setSortKey] = useState<SortKey>("title") const [sortKey, setSortKey] = useState<SortKey>("title")
const [sortDirection, setSortDirection] = const [sortDirection, setSortDirection] =
useState<SortDirection>("asc") useState<SortDirection>("asc")
@@ -89,6 +311,7 @@ export function SongsView() {
const { const {
selectedIds, selectedIds,
selectedCount, selectedCount,
isSelected,
handleSelect, handleSelect,
handlePointerDown, handlePointerDown,
prepareContextMenu, prepareContextMenu,
@@ -109,27 +332,32 @@ export function SongsView() {
[songs, selectedIds] [songs, selectedIds]
) )
const handleMediaAction = useTrackListMediaAction({ selectedIds, songs }) function handleMediaAction(action: MediaContextAction, fallbackSongId?: string) {
const targetIds =
const handleRowSelect = useCallback( selectedIds.size > 0
(index: number, event: MouseEvent) => { ? Array.from(selectedIds)
handleSelect(songs[index].id, index, event) : fallbackSongId
}, ? [fallbackSongId]
[songs, handleSelect] : []
) switch (action) {
case "create-station": {
const handleRowPlay = useCallback( const artistId = stationArtistId(songs, new Set(targetIds))
(index: number) => { if (artistId) void createStation(artistId)
void playFromLibrarySong(songs[index].id, { sortKey, sortDirection }) break
}, }
[songs, sortKey, sortDirection, playFromLibrarySong] case "favorite":
) void favoriteSongs(targetIds as Id<"songs">[])
break
const handleToggleFavorite = useCallback( case "playlist":
(songId: string) => void toggleSongFavorite(songId as Id<"songs">), openAddToPlaylist(targetIds as Id<"songs">[])
[toggleSongFavorite] break
) case "play-next":
const getSongKey = useCallback((index: number) => songs[index].id, [songs]) case "play-last":
case "shuffle":
void runQueueAction(action, targetIds as Id<"songs">[])
break
}
}
if (status === "LoadingFirstPage" && !isCached) { if (status === "LoadingFirstPage" && !isCached) {
return ( return (
@@ -200,7 +428,7 @@ export function SongsView() {
</p> </p>
) : null} ) : null}
<ScrollArea className="min-h-0 flex-1 [&_[data-slot=scroll-area-viewport]>div]:block!"> <ScrollArea className="min-h-0 flex-1">
<div <div
className="w-full pb-28" className="w-full pb-28"
onClick={(event) => { onClick={(event) => {
@@ -209,29 +437,68 @@ export function SongsView() {
} }
}} }}
> >
<LibraryTrackListHeader /> <Table>
<VirtualList <TableHeader>
count={songs.length} <TableRow className="border-none hover:bg-transparent">
estimateSize={estimateSongRowSize} <TableHead colSpan={4} className="h-9 p-0 font-normal">
getItemKey={getSongKey} <div className={cn(songRowLayout, TRACK_ROW_PADDING)}>
renderItem={(index) => ( <div className={nameColumnLayout}>
<TrackRow <span aria-hidden />
variant="library" <span aria-hidden />
song={songs[index]} <span className="text-xs text-muted-foreground">Name</span>
index={index} </div>
selectionPosition={selectionPositions[index]} <span className={cn(songColumnClass, "text-xs text-muted-foreground")}>
isFavorite={isSongFavorite(songs[index].id)} Artist
selectedCount={selectedCount} </span>
selectionStationArtistId={selectedStationArtistId} <span className={cn(songColumnClass, "text-xs text-muted-foreground")}>
onPointerDown={handlePointerDown} Album
onSelect={handleRowSelect} </span>
onPlay={handleRowPlay} <div className="min-w-4 flex-1" />
onToggleFavorite={handleToggleFavorite} <span className="shrink-0 text-right text-xs text-muted-foreground">
onPrepareContextMenu={prepareContextMenu} Time
onMediaAction={handleMediaAction} </span>
/> <span className="size-8 shrink-0" aria-hidden />
)} </div>
/> </TableHead>
</TableRow>
</TableHeader>
<TableBody>
{songs.map((song, index) => (
<SongRow
key={song.id}
song={song}
isSelected={isSelected(song.id)}
selectionPosition={selectionPositions[index]}
isFavorite={isSongFavorite(song.id)}
stationArtist={
isSelected(song.id)
? selectedStationArtistId
: song.artist.id
}
selectedCount={
isSelected(song.id) && selectedCount > 0
? selectedCount
: 1
}
onPointerDown={handlePointerDown}
onSelect={(event) => {
handleSelect(song.id, index, event)
}}
onToggleFavorite={() =>
void toggleSongFavorite(song.id as Id<"songs">)
}
onPrepareContextMenu={() => prepareContextMenu(song.id)}
onMediaAction={handleMediaAction}
onPlay={() =>
void playFromLibrarySong(song.id as Id<"songs">, {
sortKey,
sortDirection,
})
}
/>
))}
</TableBody>
</Table>
<div <div
ref={loadMoreRef} ref={loadMoreRef}
className="flex items-center justify-center py-4" className="flex items-center justify-center py-4"
@@ -3,62 +3,10 @@
import type { MouseEvent } from "react" import type { MouseEvent } from "react"
import { AudioLines, Pause, Play } from "lucide-react" import { AudioLines, Pause, Play } from "lucide-react"
import { import { usePlayback } from "@/components/playback-provider"
useIsPlaying,
usePlaybackActions,
} from "@/components/playback-provider"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
function trackButtonClassName(showPlay: boolean, inRange: boolean) {
return cn(
"absolute size-8 opacity-0 transition-opacity group-hover:opacity-100",
showPlay && "opacity-100",
inRange
? "text-primary-foreground hover:bg-white/15 hover:text-primary-foreground"
: "text-primary hover:text-primary"
)
}
function NowPlayingButton({
title,
inRange,
}: {
title: string
inRange: boolean
}) {
const isPlaying = useIsPlaying()
const { setIsPlaying } = usePlaybackActions()
return (
<Button
variant="ghost"
size="icon-sm"
className={trackButtonClassName(true, inRange)}
aria-label={isPlaying ? `Pause ${title}` : `Play ${title}`}
onClick={(event: MouseEvent) => {
event.stopPropagation()
setIsPlaying(!isPlaying)
}}
>
<span className="absolute inset-0 flex items-center justify-center transition-opacity group-hover:opacity-0">
{isPlaying ? (
<AudioLines className="size-4" />
) : (
<Play className="size-4 fill-current" />
)}
</span>
<span className="absolute inset-0 flex items-center justify-center opacity-0 transition-opacity group-hover:opacity-100">
{isPlaying ? (
<Pause className="size-4" />
) : (
<Play className="size-4 fill-current" />
)}
</span>
</Button>
)
}
export function TrackNumberPlayButton({ export function TrackNumberPlayButton({
displayTrack, displayTrack,
title, title,
@@ -74,7 +22,26 @@ export function TrackNumberPlayButton({
inRange: boolean inRange: boolean
onPlay: () => void onPlay: () => void
}) { }) {
const { isPlaying, setIsPlaying } = usePlayback()
const showPlay = isActive || isNowPlaying const showPlay = isActive || isNowPlaying
const isCurrentlyPlaying = isNowPlaying && isPlaying
const buttonClassName = cn(
"absolute size-8 opacity-0 transition-opacity group-hover:opacity-100",
showPlay && "opacity-100",
inRange
? "text-primary-foreground hover:bg-white/15 hover:text-primary-foreground"
: "text-primary hover:text-primary"
)
const handleClick = (event: MouseEvent) => {
event.stopPropagation()
if (isNowPlaying) {
setIsPlaying(!isPlaying)
return
}
onPlay()
}
return ( return (
<div <div
@@ -92,17 +59,35 @@ export function TrackNumberPlayButton({
{displayTrack} {displayTrack}
</span> </span>
{isNowPlaying ? ( {isNowPlaying ? (
<NowPlayingButton title={title} inRange={inRange} /> <Button
variant="ghost"
size="icon-sm"
className={buttonClassName}
aria-label={isCurrentlyPlaying ? `Pause ${title}` : `Play ${title}`}
onClick={handleClick}
>
<span className="absolute inset-0 flex items-center justify-center transition-opacity group-hover:opacity-0">
{isCurrentlyPlaying ? (
<AudioLines className="size-4" />
) : (
<Play className="size-4 fill-current" />
)}
</span>
<span className="absolute inset-0 flex items-center justify-center opacity-0 transition-opacity group-hover:opacity-100">
{isCurrentlyPlaying ? (
<Pause className="size-4" />
) : (
<Play className="size-4 fill-current" />
)}
</span>
</Button>
) : ( ) : (
<Button <Button
variant="ghost" variant="ghost"
size="icon-sm" size="icon-sm"
className={trackButtonClassName(showPlay, inRange)} className={buttonClassName}
aria-label={`Play ${title}`} aria-label={`Play ${title}`}
onClick={(event) => { onClick={handleClick}
event.stopPropagation()
onPlay()
}}
> >
<Play className="size-4 fill-current" /> <Play className="size-4 fill-current" />
</Button> </Button>
-518
View File
@@ -1,518 +0,0 @@
"use client"
import * as React from "react"
import Image from "next/image"
import Link from "next/link"
import { Music2, Play, Star, Trash2 } from "lucide-react"
import {
MediaContextMenu,
MediaContextMenuArea,
MediaMenuItem,
MediaMenuSeparator,
type MediaContextAction,
type MediaContextMenuProps,
} from "@/components/media-context-menu"
import { PlaybackSongMeta } from "@/components/playback-song-meta"
import { TrackNumberPlayButton } from "@/components/track-number-play-button"
import { Button } from "@/components/ui/button"
import { albumCoverUrl } from "@/lib/cover-urls"
import {
ALBUM_TRACK_ROW,
ALBUM_TRACK_TITLE,
isInSelectionRange,
SelectionRangeHighlight,
TrackRowActiveHighlight,
TrackRowHoverHighlight,
TRACK_ROW_PADDING,
type SelectionRangePosition,
} from "@/lib/selection-range-styles"
import { formatDuration } from "@/lib/format-duration"
import { cn } from "@/lib/utils"
import type { BrowseSong } from "@otunes/convex/types"
/**
* - `library`: favorite star, cover with play overlay, title, artist and album
* columns (use with `LibraryTrackListHeader`).
* - `album`: favorite star, track number, title with optional credits.
* - `playlist`: cover with favorite overlay, track number, title.
* - `queue`: square cover, title and artist, no menu.
*/
export type TrackRowVariant = "library" | "album" | "playlist" | "queue"
export type TrackRowProps = {
variant: TrackRowVariant
song: BrowseSong
/** Position in the list the selection hook was given. */
index: number
/** Number shown in the track number column (`album` and `playlist`). */
trackNumber?: number
/** Secondary line under the title, e.g. album track credits. */
subtitle?: string
selectionPosition: SelectionRangePosition
isActive?: boolean
isNowPlaying?: boolean
isFavorite?: boolean
isDragging?: boolean
/** Total selected songs; the menu acts on these when this row is selected. */
selectedCount?: number
/** Station artist for the selection when this row is selected. */
selectionStationArtistId?: string
playlistLabel?: string
showFavoriteInMenu?: boolean
/** Adds a destructive menu item calling `onRemove`. */
removeLabel?: string
ref?: React.Ref<HTMLElement>
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 (
<div
className={cn(
"flex size-10 shrink-0 items-center justify-center bg-muted ring-1",
!square && "rounded",
ringClass
)}
>
<Music2 className="size-4 text-muted-foreground" />
</div>
)
}
return (
<div
className={cn(
"group/cover relative size-10 shrink-0 overflow-hidden ring-1",
!square && "rounded",
ringClass
)}
>
<Image
src={albumCoverUrl(albumId)}
alt={alt}
fill
sizes="40px"
className="object-cover"
/>
{children}
</div>
)
}
function FavoriteStarButton({
title,
isFavorite,
inRange,
className,
onToggle,
}: {
title: string
isFavorite: boolean
inRange: boolean
className?: string
onToggle: () => void
}) {
return (
<Button
variant="ghost"
size="icon-sm"
className={cn(
"size-8",
inRange
? "text-primary-foreground hover:bg-white/15 hover:text-primary-foreground"
: "text-primary hover:text-primary",
className
)}
aria-label={isFavorite ? `Remove ${title} from favorites` : `Favorite ${title}`}
onClick={(event) => {
event.stopPropagation()
onToggle()
}}
>
<Star
className={cn(
"size-4",
isFavorite && (inRange ? "fill-current" : "fill-primary")
)}
/>
</Button>
)
}
function ExplicitBadge({ inRange }: { inRange: boolean }) {
return (
<span
className={cn(
"ml-1.5 inline-flex size-3.5 shrink-0 items-center justify-center rounded-sm text-[9px] font-semibold leading-none",
inRange
? "bg-white/20 text-primary-foreground"
: "bg-muted-foreground/20 text-muted-foreground"
)}
aria-label="Explicit"
>
E
</span>
)
}
function TrackTitle({
song,
subtitle,
inRange,
}: {
song: BrowseSong
subtitle?: string
inRange: boolean
}) {
return (
<div className="min-w-0 flex-1">
<div className={ALBUM_TRACK_TITLE}>
{song.title}
{song.explicit ? <ExplicitBadge inRange={inRange} /> : null}
</div>
{subtitle ? (
<p
className={cn(
"truncate text-xs",
inRange ? "text-primary-foreground/80" : "text-muted-foreground"
)}
>
{subtitle}
</p>
) : null}
</div>
)
}
export function LibraryTrackListHeader() {
const labelClass = "text-xs text-muted-foreground"
return (
<div className={cn("flex h-9 items-center", LIBRARY_ROW_LAYOUT, TRACK_ROW_PADDING)}>
<div className={LIBRARY_NAME_COLUMNS}>
<span aria-hidden />
<span aria-hidden />
<span className={labelClass}>Name</span>
</div>
<span className={cn(LIBRARY_COLUMN, labelClass)}>Artist</span>
<span className={cn(LIBRARY_COLUMN, labelClass)}>Album</span>
<div className="min-w-4 flex-1" />
<span className={cn("shrink-0 text-right", labelClass)}>Time</span>
<span className="size-8 shrink-0" aria-hidden />
</div>
)
}
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 = (
<div className="flex shrink-0 items-center justify-center">
<FavoriteStarButton
title={song.title}
isFavorite={isFavorite}
inRange={inRange}
className={cn(
"opacity-0 transition-opacity group-hover:opacity-100",
(isFavorite || isActive || inRange) && "opacity-100"
)}
onToggle={toggleFavorite}
/>
</div>
)
const trackNumberButton = (
<TrackNumberPlayButton
displayTrack={trackNumber ?? index + 1}
title={song.title}
isActive={isActive}
isNowPlaying={isNowPlaying}
inRange={inRange}
onPlay={play}
/>
)
const duration = (
<span
className={cn(
"shrink-0 text-right tabular-nums",
variant === "queue" && "text-xs",
inRange ? "text-primary-foreground" : "text-muted-foreground"
)}
>
{formatDuration(song.durationSeconds)}
</span>
)
// 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 ? (
<>
<MediaMenuSeparator />
<MediaMenuItem
variant="destructive"
className="justify-between"
onClick={() => onRemove(song.id)}
>
{removeLabel}
<Trash2 />
</MediaMenuItem>
</>
) : null,
}
: null
const menu = menuProps ? <MediaContextMenu {...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 = (
<div className={cn("relative z-10", LIBRARY_ROW_LAYOUT, TRACK_ROW_PADDING)}>
<div className={LIBRARY_NAME_COLUMNS}>
{favoriteStar}
<TrackCover albumId={song.album.id} alt={song.album.title} inRange={inRange}>
<div className="absolute inset-0 flex items-center justify-center bg-black/0 transition-colors group-hover:bg-black/40">
<Button
size="icon-sm"
className="size-7 rounded-full opacity-0 transition-opacity group-hover:opacity-100"
aria-label={`Play ${song.title}`}
onClick={(event) => {
event.preventDefault()
event.stopPropagation()
play()
}}
>
<Play className="size-3 fill-current" />
</Button>
</div>
</TrackCover>
<TrackTitle song={song} inRange={inRange} />
</div>
<div className={LIBRARY_COLUMN}>
<Link
href={"/artist/" + song.artist.id}
className={linkClass}
onClick={(event) => event.stopPropagation()}
>
{song.artist.name}
</Link>
</div>
<div className={LIBRARY_COLUMN}>
<Link
href={"/album/" + song.album.id}
className={linkClass}
onClick={(event) => event.stopPropagation()}
>
{song.album.title}
</Link>
</div>
<div className="min-w-4 flex-1" />
{duration}
{menu}
</div>
)
break
}
case "album":
content = (
<div className={cn("relative z-10", ALBUM_TRACK_ROW, TRACK_ROW_PADDING)}>
{favoriteStar}
{trackNumberButton}
<TrackTitle song={song} subtitle={subtitle} inRange={inRange} />
{duration}
{menu}
</div>
)
break
case "playlist":
content = (
<div className={cn("relative z-10", ALBUM_TRACK_ROW, TRACK_ROW_PADDING)}>
<TrackCover albumId={song.album.id} alt={song.album.title} inRange={inRange}>
<div className="absolute inset-0 flex items-center justify-center bg-black/0 opacity-0 transition-opacity group-hover/cover:bg-black/40 group-hover/cover:opacity-100">
<FavoriteStarButton
title={song.title}
isFavorite={isFavorite}
inRange={inRange}
onToggle={toggleFavorite}
/>
</div>
</TrackCover>
{trackNumberButton}
<TrackTitle song={song} subtitle={subtitle} inRange={inRange} />
{duration}
{menu}
</div>
)
break
case "queue":
content = (
<div className="relative z-10 flex items-center gap-3 px-2">
<TrackCover
albumId={song.album.id}
alt={song.album.title}
inRange={inRange}
square
/>
<PlaybackSongMeta
song={song}
isCurrent={isNowPlaying}
inRange={inRange}
align="start"
showAlbum={false}
/>
{duration}
</div>
)
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 = (
<>
<SelectionRangeHighlight position={selectionPosition} flush={flush} />
{!inRange && isActive ? <TrackRowActiveHighlight flush={flush} /> : null}
{!inRange && !isActive ? <TrackRowHoverHighlight flush={flush} /> : null}
{content}
</>
)
const shell =
variant === "queue" ? (
<li ref={ref as React.Ref<HTMLLIElement>} {...shellProps}>
{children}
</li>
) : (
<div ref={ref as React.Ref<HTMLDivElement>} {...shellProps}>
{children}
</div>
)
return menuProps ? (
<MediaContextMenuArea menu={menuProps}>{shell}</MediaContextMenuArea>
) : (
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)
-120
View File
@@ -1,120 +0,0 @@
"use client"
import * as React from "react"
import {
defaultRangeExtractor,
useVirtualizer,
type Range,
} from "@tanstack/react-virtual"
import { cn } from "@/lib/utils"
const scrollViewportSelector = '[data-slot="scroll-area-viewport"]'
/**
* Renders only the visible items of a list placed inside a `ScrollArea`.
* The list may sit below other content in the same viewport.
*/
export function VirtualList({
count,
estimateSize,
getItemKey,
renderItem,
overscan = 10,
keepMounted = null,
className,
}: {
count: number
estimateSize: (index: number) => number
getItemKey: (index: number) => string
renderItem: (index: number) => React.ReactNode
overscan?: number
/** Index rendered even when off screen, e.g. the source of a drag. */
keepMounted?: number | null
className?: string
}) {
const listRef = React.useRef<HTMLDivElement>(null)
const [scrollMargin, setScrollMargin] = React.useState(0)
React.useLayoutEffect(() => {
const list = listRef.current
const viewport = list?.closest<HTMLElement>(scrollViewportSelector)
if (!list || !viewport) return
const measure = () => {
setScrollMargin(
Math.round(
list.getBoundingClientRect().top -
viewport.getBoundingClientRect().top +
viewport.scrollTop
)
)
}
const observer = new ResizeObserver(measure)
observer.observe(viewport)
if (viewport.firstElementChild) {
observer.observe(viewport.firstElementChild)
}
return () => observer.disconnect()
}, [])
const getScrollElement = () =>
listRef.current?.closest<HTMLElement>(scrollViewportSelector) ?? null
const virtualizer = useVirtualizer({
count,
getScrollElement,
// The virtualizer scrolls to this offset on attach. Keep the viewport's
// current position so `ScrollRestoration` is not reset to the top.
initialOffset: () => getScrollElement()?.scrollTop ?? 0,
estimateSize,
getItemKey,
overscan,
scrollMargin,
rangeExtractor: React.useCallback(
(range: Range) => {
const indexes = defaultRangeExtractor(range)
if (
keepMounted !== null &&
keepMounted < range.count &&
!indexes.includes(keepMounted)
) {
indexes.push(keepMounted)
indexes.sort((a, b) => a - b)
}
return indexes
},
[keepMounted]
),
})
// The virtualizer caches its offset across a detach. Clear it so a
// re-attach (e.g. StrictMode's effect replay) re-reads `initialOffset`
// instead of scrolling back to a stale position.
React.useLayoutEffect(
() => () => {
virtualizer.scrollOffset = null
},
[virtualizer]
)
return (
<div
ref={listRef}
className={cn("relative w-full", className)}
style={{ height: virtualizer.getTotalSize() }}
>
{virtualizer.getVirtualItems().map((item) => (
<div
key={item.key}
data-index={item.index}
ref={virtualizer.measureElement}
className="absolute top-0 left-0 w-full"
style={{ transform: `translateY(${item.start - scrollMargin}px)` }}
>
{renderItem(item.index)}
</div>
))}
</div>
)
}
+15
View File
@@ -0,0 +1,15 @@
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");
+2 -21
View File
@@ -9,18 +9,13 @@ import {
type PaginatedQueryReference, type PaginatedQueryReference,
} from "convex/react" } from "convex/react"
import type { FunctionReference } from "convex/server" import type { FunctionReference } from "convex/server"
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react" import { useCallback, useEffect, useSyncExternalStore } from "react"
import { useCacheScope } from "@/components/persistent-cache-provider" import { useCacheScope } from "@/components/persistent-cache-provider"
import { queryCacheKey } from "@otunes/convex/client/cached-query" import { queryCacheKey } from "@otunes/convex/client/cached-query"
import { readCache, subscribeCache, writeCache } from "@/lib/persistent-cache" import { readCache, subscribeCache, writeCache } from "@/lib/persistent-cache"
const MAX_CACHED_PAGINATED_ITEMS = 200 const MAX_CACHED_PAGINATED_ITEMS = 200
const MAX_RESTORED_PAGINATED_ITEMS = 1000
// Items loaded per paginated query this session, so a remount (e.g. back
// navigation) loads as much as before and scroll restoration can reach it.
const loadedItemCounts = new Map<string, number>()
const noopUnsubscribe = () => {} const noopUnsubscribe = () => {}
@@ -70,7 +65,6 @@ export function useCachedQuery<Query extends FunctionReference<"query">>(
/** /**
* `usePaginatedQuery` that shows the first persisted pages while the first live * `usePaginatedQuery` that shows the first persisted pages while the first live
* page loads. `isCached` is true while those persisted results are shown. * page loads. `isCached` is true while those persisted results are shown.
* Remounts start with as many items as were last loaded this session.
*/ */
export function useCachedPaginatedQuery<Query extends PaginatedQueryReference>( export function useCachedPaginatedQuery<Query extends PaginatedQueryReference>(
query: Query, query: Query,
@@ -78,28 +72,15 @@ export function useCachedPaginatedQuery<Query extends PaginatedQueryReference>(
options: { initialNumItems: number } options: { initialNumItems: number }
) { ) {
const scope = useCacheScope() const scope = useCacheScope()
const result = usePaginatedQuery(query, args, options)
const key = const key =
args === "skip" args === "skip"
? null ? null
: `${queryCacheKey(scope, query, args as Record<string, unknown>)}:pages` : `${queryCacheKey(scope, query, args as Record<string, unknown>)}:pages`
// Fixed per key: `usePaginatedQuery` restarts when this changes.
const initialNumItems = useMemo(
() =>
Math.max(
options.initialNumItems,
Math.min(
(key && loadedItemCounts.get(key)) || 0,
MAX_RESTORED_PAGINATED_ITEMS
)
),
[key, options.initialNumItems]
)
const result = usePaginatedQuery(query, args, { initialNumItems })
const cached = useCachedValue<PaginatedQueryItem<Query>[]>(key) const cached = useCachedValue<PaginatedQueryItem<Query>[]>(key)
useEffect(() => { useEffect(() => {
if (key && result.status !== "LoadingFirstPage") { if (key && result.status !== "LoadingFirstPage") {
loadedItemCounts.set(key, result.results.length)
writeCache(key, result.results.slice(0, MAX_CACHED_PAGINATED_ITEMS)) writeCache(key, result.results.slice(0, MAX_CACHED_PAGINATED_ITEMS))
} }
}, [key, result.status, result.results]) }, [key, result.status, result.results])
-104
View File
@@ -1,104 +0,0 @@
"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<string>
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]
)
}
+2 -2
View File
@@ -3,7 +3,7 @@
import * as React from "react" import * as React from "react"
import { toast } from "sonner" import { toast } from "sonner"
import { usePlaybackActions } from "@/components/playback-provider" import { usePlayback } from "@/components/playback-provider"
import type { MediaContextAction } from "@/components/media-context-menu" import type { MediaContextAction } from "@/components/media-context-menu"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
@@ -29,7 +29,7 @@ function queueActionMessage(action: QueueMediaAction, count: number) {
export function useQueueMediaActions() { export function useQueueMediaActions() {
const { addToQueueNext, addToQueueLast, playShuffled, playArtistShuffled } = const { addToQueueNext, addToQueueLast, playShuffled, playArtistShuffled } =
usePlaybackActions() usePlayback()
const runQueueAction = React.useCallback( const runQueueAction = React.useCallback(
async (action: QueueMediaAction, songIds: Id<"songs">[]) => { async (action: QueueMediaAction, songIds: Id<"songs">[]) => {
-19
View File
@@ -1,19 +0,0 @@
"use client"
import * as React from "react"
/**
* Returns a function with a stable identity that always calls the latest
* `callback`. Only call it from event handlers, never during render.
*/
export function useStableCallback<Args extends unknown[], Result>(
callback: (...args: Args) => Result
): (...args: Args) => Result {
const callbackRef = React.useRef(callback)
React.useLayoutEffect(() => {
callbackRef.current = callback
})
return React.useCallback((...args: Args) => callbackRef.current(...args), [])
}
+7 -1
View File
@@ -1,3 +1,9 @@
/** Shared layout for album grids. */ /** Shared layout for album grids and carousel slides (gap-x-6 = 1.5rem). */
export const albumGridClassName = 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" "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"
+19
View File
@@ -0,0 +1,19 @@
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
-7
View File
@@ -1,7 +0,0 @@
/** 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")}`
}
+14 -6
View File
@@ -13,15 +13,15 @@ function mediaOrigin() {
return window.location.origin return window.location.origin
} }
function albumShareUrl(albumId: string) { export function albumShareUrl(albumId: string) {
return `${mediaOrigin()}/album/${albumId}` return `${mediaOrigin()}/album/${albumId}`
} }
function songShareUrl(albumId: string, songId: string) { export function songShareUrl(albumId: string, songId: string) {
return `${mediaOrigin()}/album/${albumId}?s=${songId}` return `${mediaOrigin()}/album/${albumId}?s=${songId}`
} }
function playlistShareUrl( export function playlistShareUrl(
playlistId: string, playlistId: string,
options?: { isFavorites?: boolean } options?: { isFavorites?: boolean }
) { ) {
@@ -31,11 +31,11 @@ function playlistShareUrl(
return `${mediaOrigin()}/playlist/${playlistId}` return `${mediaOrigin()}/playlist/${playlistId}`
} }
function artistShareUrl(artistId: string) { export function artistShareUrl(artistId: string) {
return `${mediaOrigin()}/artist/${artistId}` return `${mediaOrigin()}/artist/${artistId}`
} }
function mediaShareUrl(share: MediaShareContext) { export function mediaShareUrl(share: MediaShareContext) {
switch (share.type) { switch (share.type) {
case "album": case "album":
return albumShareUrl(share.albumId) return albumShareUrl(share.albumId)
@@ -50,7 +50,7 @@ function mediaShareUrl(share: MediaShareContext) {
} }
} }
async function copyTextToClipboard(text: string) { export async function copyTextToClipboard(text: string) {
await navigator.clipboard.writeText(text) await navigator.clipboard.writeText(text)
toast.success("Link Copied") toast.success("Link Copied")
} }
@@ -63,6 +63,10 @@ export async function copyAlbumLink(albumId: string) {
await copyMediaShareLink({ type: "album", albumId }) await copyMediaShareLink({ type: "album", albumId })
} }
export async function copySongLink(albumId: string, songId: string) {
await copyMediaShareLink({ type: "song", albumId, songId })
}
export async function copyPlaylistLink( export async function copyPlaylistLink(
playlistId: string, playlistId: string,
options?: { isFavorites?: boolean } options?: { isFavorites?: boolean }
@@ -73,3 +77,7 @@ export async function copyPlaylistLink(
isFavorites: options?.isFavorites, isFavorites: options?.isFavorites,
}) })
} }
export async function copyArtistLink(artistId: string) {
await copyMediaShareLink({ type: "artist", artistId })
}
+93 -19
View File
@@ -63,19 +63,10 @@ export function selectionHighlightRadiusClass(
export const TRACK_ROW_HIGHLIGHT_INSET = "absolute inset-y-0 left-2 right-2" export const TRACK_ROW_HIGHLIGHT_INSET = "absolute inset-y-0 left-2 right-2"
/** Full-width, square-corner highlight used by the library and queue lists. */
export const FLUSH_ROW_HIGHLIGHT_INSET = "absolute inset-0"
/**
* Track row highlights are inset rounded pills by default; `flush` makes them
* full-width with square corners.
*/
export function SelectionRangeHighlight({ export function SelectionRangeHighlight({
position, position,
flush = false,
}: { }: {
position: SelectionRangePosition position: SelectionRangePosition
flush?: boolean
}) { }) {
if (position === "none") { if (position === "none") {
return null return null
@@ -86,34 +77,34 @@ export function SelectionRangeHighlight({
aria-hidden aria-hidden
className={cn( className={cn(
"pointer-events-none bg-primary", "pointer-events-none bg-primary",
flush TRACK_ROW_HIGHLIGHT_INSET,
? FLUSH_ROW_HIGHLIGHT_INSET selectionHighlightRadiusClass(position)
: [TRACK_ROW_HIGHLIGHT_INSET, selectionHighlightRadiusClass(position)]
)} )}
/> />
) )
} }
export function TrackRowHoverHighlight({ flush = false }: { flush?: boolean }) { /** Inset rounded hover background matching the selection pill shape. */
export function TrackRowHoverHighlight() {
return ( return (
<div <div
aria-hidden aria-hidden
className={cn( className={cn(
"pointer-events-none bg-muted/60 opacity-0 transition-opacity group-hover:opacity-100", "pointer-events-none rounded-lg bg-muted/60 opacity-0 transition-opacity group-hover:opacity-100",
flush ? FLUSH_ROW_HIGHLIGHT_INSET : [TRACK_ROW_HIGHLIGHT_INSET, "rounded-lg"] TRACK_ROW_HIGHLIGHT_INSET
)} )}
/> />
) )
} }
/** Background for the active (focused or now playing) row. */ /** Inset rounded background for the active (now playing) row. */
export function TrackRowActiveHighlight({ flush = false }: { flush?: boolean }) { export function TrackRowActiveHighlight() {
return ( return (
<div <div
aria-hidden aria-hidden
className={cn( className={cn(
"pointer-events-none bg-muted/60", "pointer-events-none rounded-lg bg-muted/60",
flush ? FLUSH_ROW_HIGHLIGHT_INSET : [TRACK_ROW_HIGHLIGHT_INSET, "rounded-lg"] TRACK_ROW_HIGHLIGHT_INSET
)} )}
/> />
) )
@@ -125,6 +116,42 @@ export const TRACK_ROW_PADDING = "pl-8 pr-10"
/** Centers the track list in the main content area. */ /** Centers the track list in the main content area. */
export const TRACK_LIST_CONTAINER = "mx-auto w-full max-w-9/10" 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 (
<div
aria-hidden
className={cn(
"pointer-events-none bg-primary",
SONGS_ROW_HIGHLIGHT_INSET
)}
/>
)
}
/** Full-width hover background for library song rows (not rounded). */
export function SongsTrackRowHoverHighlight() {
return (
<div
aria-hidden
className={cn(
"pointer-events-none bg-muted/60 opacity-0 transition-opacity group-hover:opacity-100",
SONGS_ROW_HIGHLIGHT_INSET
)}
/>
)
}
/** Album track row: star, track #, title (flex), duration, menu. */ /** 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" export const ALBUM_TRACK_ROW = "flex w-full min-w-0 items-center gap-x-3"
@@ -133,3 +160,50 @@ export const ALBUM_TRACK_TITLE = "min-w-0 flex-1 truncate font-normal"
export function isInSelectionRange(position: SelectionRangePosition) { export function isInSelectionRange(position: SelectionRangePosition) {
return position !== "none" 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 (
<div
aria-hidden
className={cn(
"pointer-events-none bg-primary",
QUEUE_ROW_HIGHLIGHT_INSET
)}
/>
)
}
export function QueueTrackRowHoverHighlight() {
return (
<div
aria-hidden
className={cn(
"pointer-events-none bg-muted/60 opacity-0 transition-opacity group-hover:opacity-100",
QUEUE_ROW_HIGHLIGHT_INSET
)}
/>
)
}
export function QueueTrackRowActiveHighlight() {
return (
<div
aria-hidden
className={cn(
"pointer-events-none bg-muted/60",
QUEUE_ROW_HIGHLIGHT_INSET
)}
/>
)
}
-41
View File
@@ -1,41 +0,0 @@
import fs from "node:fs/promises"
import * as music from "music-metadata"
const MAX_ENTRIES = 1000
export type AudioInfo = {
codec: string | undefined
duration: number | undefined
}
const cache = new Map<string, Promise<AudioInfo>>()
/** Codec info for a file, parsed once per file version. */
export async function audioInfo(file: string): Promise<AudioInfo> {
const stat = await fs.stat(file)
const key = `${file}\0${stat.size}\0${stat.mtimeMs}`
const cached = cache.get(key)
if (cached) {
cache.delete(key)
cache.set(key, cached)
return cached
}
const info = music.parseFile(file).then(({ format }) => ({
codec: format.codec,
duration: format.duration,
}))
cache.set(key, info)
info.catch(() => {
if (cache.get(key) === info) {
cache.delete(key)
}
})
if (cache.size > MAX_ENTRIES) {
cache.delete(cache.keys().next().value!)
}
return info
}
+84 -84
View File
@@ -1,96 +1,96 @@
import { createReadStream } from "node:fs" import { type ChildProcessWithoutNullStreams } from "node:child_process"
import type { Readable } from "node:stream" import { createReadStream, ReadStream } from "node:fs"
import type { FfmpegProcess } from "@/lib/server-ffmpeg"
const HIGH_WATER_MARK_BYTES = 256 * 1024
export type ByteRange = { export type ByteRange = {
start: number start: number
end: number end: number
} }
/** async function* nodeStreamToIterator(stream: ReadStream) {
* Wraps a Node stream, pausing it while the consumer is behind. `cancel` runs for await (const chunk of stream) {
* when the consumer goes away (seek, track change, disconnect). `finish` runs yield new Uint8Array(chunk)
* when the source ends and may reject to error the stream. }
*/
function toWebStream(
source: Readable,
{
cancel,
finish,
}: { cancel: () => void; finish?: () => Promise<void> }
): ReadableStream<Uint8Array> {
let done = false
return new ReadableStream<Uint8Array>(
{
start(controller) {
const fail = (error: unknown) => {
if (done) {
return
}
done = true
controller.error(error)
cancel()
}
source.on("data", (chunk: Buffer) => {
if (done) {
return
}
controller.enqueue(new Uint8Array(chunk))
if ((controller.desiredSize ?? 0) <= 0) {
source.pause()
}
})
source.once("error", fail)
source.once("end", () => {
if (done) {
return
}
void (finish?.() ?? Promise.resolve()).then(() => {
if (!done) {
done = true
controller.close()
}
}, fail)
})
},
pull() {
source.resume()
},
cancel() {
if (done) {
return
}
done = true
cancel()
},
},
new ByteLengthQueuingStrategy({ highWaterMark: HIGH_WATER_MARK_BYTES })
)
} }
export function streamFile(path: string, range?: ByteRange) { // @ts-expect-error trust me bro
const file = createReadStream(path, range) function iteratorToStream(iterator) {
return toWebStream(file, { cancel: () => file.destroy() }) return new ReadableStream({
} async pull(controller) {
const { value, done } = await iterator.next()
/** Streams ffmpeg stdout and kills ffmpeg when the consumer goes away. */ if (done) {
export function ffmpegToReadableStream({ controller.close()
child, } else {
exited, controller.enqueue(value)
stderrTail,
}: FfmpegProcess) {
return toWebStream(child.stdout, {
cancel: () => child.kill("SIGKILL"),
finish: async () => {
const code = await exited
if (code !== 0) {
console.error(`ffmpeg transcode exited with code ${code}`, stderrTail())
throw new Error(`ffmpeg exited with code ${code}`)
} }
}, },
}) })
} }
export function streamFile(path: string, range?: ByteRange): ReadableStream {
const nodeStream = createReadStream(path, range)
return iteratorToStream(nodeStreamToIterator(nodeStream))
}
export function ffmpegToReadableStream(
ffmpegProcess: ChildProcessWithoutNullStreams
) {
let closed = false
return new ReadableStream({
start(controller) {
const finalize = (err?: Error) => {
if (closed) {
return
}
closed = true
try {
if (err) {
controller.error(err)
} else {
controller.close()
}
} catch {
// Consumer may have already closed the stream (e.g. track change).
}
}
ffmpegProcess.stdout.on("data", (chunk: Buffer) => {
if (closed) {
return
}
try {
controller.enqueue(new Uint8Array(chunk))
} catch {
closed = true
ffmpegProcess.kill("SIGKILL")
}
})
ffmpegProcess.stderr.on("data", (data) => {
console.error(`FFmpeg log: ${data.toString()}`)
})
ffmpegProcess.stdout.on("end", () => finalize())
ffmpegProcess.stdout.on("error", (err) => finalize(err))
ffmpegProcess.on("close", (code) => {
if (code !== 0 && !closed) {
finalize(new Error(`ffmpeg exited with code ${code}`))
} else {
finalize()
}
})
ffmpegProcess.on("error", (err) => finalize(err))
},
cancel() {
if (closed) {
return
}
closed = true
ffmpegProcess.kill("SIGKILL")
},
})
}
-132
View File
@@ -1,132 +0,0 @@
import fs from "node:fs/promises"
import os from "node:os"
import path from "node:path"
const DEFAULT_MAX_MB = 2048
const ORPHAN_MAX_AGE_MS = 60 * 60 * 1000
/** Prefix for in-progress entries. Pruning removes old unpinned ones as abandoned. */
export const CACHE_ORPHAN_PREFIX = "convert-"
type CacheState = {
pinned: Map<string, number>
pruning: Promise<void> | null
}
const globalState = globalThis as typeof globalThis & {
__otunesCache?: CacheState
}
const state = (globalState.__otunesCache ??= {
pinned: new Map(),
pruning: null,
})
/**
* Transcode cache root. Set OTUNES_CACHE_DIR to a persistent volume to keep
* transcodes across restarts.
*/
export function cacheRoot() {
return process.env.OTUNES_CACHE_DIR || path.join(os.tmpdir(), "otunes-cache")
}
export function cacheDir(kind: "hls" | "lossless") {
return path.join(cacheRoot(), kind)
}
function maxCacheBytes() {
const configured = Number(process.env.OTUNES_CACHE_MAX_MB)
const mb = Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_MAX_MB
return mb * 1024 * 1024
}
/** Pinned entries are never pruned. Pins are reference counted. */
export function pinCacheEntry(entry: string) {
state.pinned.set(entry, (state.pinned.get(entry) ?? 0) + 1)
}
export function unpinCacheEntry(entry: string) {
const count = state.pinned.get(entry) ?? 0
if (count <= 1) {
state.pinned.delete(entry)
} else {
state.pinned.set(entry, count - 1)
}
}
/** Marks an entry as recently used so pruning removes it last. */
export async function touchCacheEntry(entry: string) {
const now = new Date()
await fs.utimes(entry, now, now)
}
async function entrySize(entry: string): Promise<number> {
const stat = await fs.stat(entry).catch(() => null)
if (!stat) {
return 0
}
if (!stat.isDirectory()) {
return stat.size
}
const names = await fs.readdir(entry).catch(() => [])
const sizes = await Promise.all(
names.map((name) => entrySize(path.join(entry, name)))
)
return sizes.reduce((total, size) => total + size, 0)
}
async function prune() {
const entries: {
path: string
size: number
mtimeMs: number
orphan: boolean
}[] = []
for (const kind of ["hls", "lossless"] as const) {
const dir = cacheDir(kind)
const names = await fs.readdir(dir).catch(() => [])
for (const name of names) {
const entry = path.join(dir, name)
const stat = await fs.stat(entry).catch(() => null)
if (!stat) {
continue
}
entries.push({
path: entry,
size: await entrySize(entry),
mtimeMs: stat.mtimeMs,
orphan: name.startsWith(CACHE_ORPHAN_PREFIX),
})
}
}
const maxBytes = maxCacheBytes()
const now = Date.now()
let total = entries.reduce((sum, entry) => sum + entry.size, 0)
entries.sort((a, b) => a.mtimeMs - b.mtimeMs)
for (const entry of entries) {
if (state.pinned.has(entry.path)) {
continue
}
const remove = entry.orphan
? now - entry.mtimeMs > ORPHAN_MAX_AGE_MS
: total > maxBytes
if (remove) {
await fs.rm(entry.path, { recursive: true, force: true }).catch(() => {})
total -= entry.size
}
}
}
/**
* Removes least recently used entries until the cache fits under
* OTUNES_CACHE_MAX_MB, plus abandoned in-progress entries.
*/
export function pruneCache() {
state.pruning ??= prune()
.catch((error) => console.error("Transcode cache prune failed", error))
.finally(() => {
state.pruning = null
})
return state.pruning
}
-113
View File
@@ -1,113 +0,0 @@
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"
import os from "node:os"
const STDERR_TAIL_BYTES = 4096
export type FfmpegProcess = {
child: ChildProcessWithoutNullStreams
/** Resolves with the exit code, or null when killed by a signal. */
exited: Promise<number | null>
stderrTail: () => string
}
type Limiter = {
running: number
waiting: (() => void)[]
}
// Kept on globalThis so dev reloads share one limit with processes they spawned.
const globalState = globalThis as typeof globalThis & {
__otunesFfmpegLimiter?: Limiter
}
const limiter = (globalState.__otunesFfmpegLimiter ??= {
running: 0,
waiting: [],
})
function maxConcurrentFfmpeg() {
const configured = Number(process.env.OTUNES_MAX_FFMPEG)
if (Number.isInteger(configured) && configured > 0) {
return configured
}
return Math.max(2, os.availableParallelism())
}
async function acquireSlot(signal?: AbortSignal) {
signal?.throwIfAborted()
if (limiter.running < maxConcurrentFfmpeg()) {
limiter.running += 1
return
}
await new Promise<void>((resolve, reject) => {
const grant = () => {
signal?.removeEventListener("abort", onAbort)
resolve()
}
const onAbort = () => {
const index = limiter.waiting.indexOf(grant)
if (index !== -1) {
limiter.waiting.splice(index, 1)
}
reject(signal?.reason)
}
limiter.waiting.push(grant)
signal?.addEventListener("abort", onAbort, { once: true })
})
}
function releaseSlot() {
const next = limiter.waiting.shift()
if (next) {
// The slot passes straight to the next waiter.
next()
} else {
limiter.running -= 1
}
}
/**
* Spawns ffmpeg once a slot under the concurrency cap is free. The slot is
* held until the process exits. Rejects if `signal` aborts while queued.
*/
export async function spawnFfmpeg(
args: string[],
signal?: AbortSignal
): Promise<FfmpegProcess> {
await acquireSlot(signal)
let child: ChildProcessWithoutNullStreams
try {
child = spawn("ffmpeg", [
"-nostdin",
"-hide_banner",
"-loglevel",
"error",
...args,
])
} catch (error) {
releaseSlot()
throw error
}
// stderr must be drained or ffmpeg blocks once the pipe buffer fills.
let stderr = ""
child.stderr.on("data", (data: Buffer) => {
stderr = (stderr + data.toString()).slice(-STDERR_TAIL_BYTES)
})
const exited = new Promise<number | null>((resolve) => {
let released = false
const finish = (code: number | null) => {
if (!released) {
released = true
releaseSlot()
}
resolve(code)
}
child.once("error", () => finish(1))
child.once("close", (code) => finish(code))
})
return { child, exited, stderrTail: () => stderr.trim() }
}
+95 -188
View File
@@ -2,22 +2,12 @@ import type { Doc } from "@otunes/convex/_generated/dataModel"
import crypto from "node:crypto" import crypto from "node:crypto"
import fs from "node:fs/promises" import fs from "node:fs/promises"
import path from "node:path" import path from "node:path"
import { audioInfo } from "@/lib/server-audio-info" import { spawn } from "node:child_process"
import { import * as music from "music-metadata"
cacheDir,
pinCacheEntry,
pruneCache,
touchCacheEntry,
unpinCacheEntry,
} from "@/lib/server-cache"
import { spawnFfmpeg, type FfmpegProcess } from "@/lib/server-ffmpeg"
export const HLS_SEGMENT_SECONDS = 6 export const HLS_SEGMENT_SECONDS = 6
const HLS_MAX_IDLE_MS = 30 * 60 * 1000 const HLS_MAX_IDLE_MS = 30 * 60 * 1000
/** The server-only slice of a song needed to transcode it. */
export type SongSource = Pick<Doc<"songs">, "_id" | "files" | "length">
type HlsJob = { type HlsJob = {
key: string key: string
lookupKey: string lookupKey: string
@@ -27,28 +17,11 @@ type HlsJob = {
lastTouchedAt: number lastTouchedAt: number
processExited: boolean processExited: boolean
processExitCode: number | null processExitCode: number | null
process: FfmpegProcess | null
abort: AbortController
evicted: boolean
} }
type HlsState = { const jobs = new Map<string, HlsJob>()
/** In-flight and ready jobs by cache key, so overlapping requests share one ffmpeg. */ const jobsByLookup = new Map<string, HlsJob>()
pending: Map<string, Promise<HlsJob>> let lastCleanupAt = 0
jobs: Map<string, HlsJob>
jobsByLookup: Map<string, HlsJob>
lastCleanupAt: number
}
const globalState = globalThis as typeof globalThis & {
__otunesHls?: HlsState
}
const state = (globalState.__otunesHls ??= {
pending: new Map(),
jobs: new Map(),
jobsByLookup: new Map(),
lastCleanupAt: 0,
})
export function qualityKbps(quality: string | null) { export function qualityKbps(quality: string | null) {
if (quality === "low") { if (quality === "low") {
@@ -63,7 +36,7 @@ export function qualityKbps(quality: string | null) {
} }
export function selectHlsSourceCodec( export function selectHlsSourceCodec(
song: SongSource, song: Doc<"songs">,
quality: string | null, quality: string | null,
preferAtmos: boolean preferAtmos: boolean
) { ) {
@@ -77,6 +50,10 @@ export function selectHlsSourceCodec(
return sourceCodec return sourceCodec
} }
function hlsCacheRoot() {
return "/tmp/otunes"
}
function hlsLookupKey( function hlsLookupKey(
songId: string, songId: string,
quality: string | null, quality: string | null,
@@ -86,7 +63,7 @@ function hlsLookupKey(
} }
async function hlsJobKey( async function hlsJobKey(
song: SongSource, song: Doc<"songs">,
sourcePath: string, sourcePath: string,
kbps: number kbps: number
) { ) {
@@ -111,38 +88,31 @@ export function hlsSegmentPath(job: HlsJob, segmentIndex: number) {
async function touchHlsJob(job: HlsJob) { async function touchHlsJob(job: HlsJob) {
job.lastTouchedAt = Date.now() job.lastTouchedAt = Date.now()
await touchCacheEntry(job.dir).catch(() => {}) await fs.utimes(job.dir, new Date(job.lastTouchedAt), new Date(job.lastTouchedAt)).catch(
() => {}
)
}
function forgetJob(job: HlsJob) {
jobs.delete(job.key)
if (jobsByLookup.get(job.lookupKey) === job) {
jobsByLookup.delete(job.lookupKey)
}
} }
async function evictJob(job: HlsJob) { async function evictJob(job: HlsJob) {
if (job.evicted) { forgetJob(job)
return await fs.rm(job.dir, { recursive: true, force: true }).catch(() => {})
}
job.evicted = true
state.pending.delete(job.key)
state.jobs.delete(job.key)
if (state.jobsByLookup.get(job.lookupKey) === job) {
state.jobsByLookup.delete(job.lookupKey)
}
job.abort.abort()
job.process?.child.kill("SIGKILL")
const complete = job.processExited && job.processExitCode === 0
if (!complete) {
await job.process?.exited
await fs.rm(job.dir, { recursive: true, force: true }).catch(() => {})
}
unpinCacheEntry(job.dir)
} }
async function cleanupIdleHlsJobs() { async function cleanupIdleHlsJobs() {
const now = Date.now() const now = Date.now()
if (now - state.lastCleanupAt < 60_000) { if (now - lastCleanupAt < 60_000) {
return return
} }
state.lastCleanupAt = now lastCleanupAt = now
for (const job of [...state.jobs.values()]) { for (const job of [...jobs.values()]) {
if (now - job.lastTouchedAt > HLS_MAX_IDLE_MS) { if (now - job.lastTouchedAt > HLS_MAX_IDLE_MS) {
await evictJob(job) await evictJob(job)
} }
@@ -154,7 +124,7 @@ export function getExistingHlsJob(
quality: string | null, quality: string | null,
preferAtmos: boolean preferAtmos: boolean
) { ) {
return state.jobsByLookup.get(hlsLookupKey(songId, quality, preferAtmos)) ?? null return jobsByLookup.get(hlsLookupKey(songId, quality, preferAtmos)) ?? null
} }
export async function waitForHlsSegment( export async function waitForHlsSegment(
@@ -167,22 +137,18 @@ export async function waitForHlsSegment(
const startedAt = Date.now() const startedAt = Date.now()
while (Date.now() - startedAt < timeoutMs) { while (Date.now() - startedAt < timeoutMs) {
// Read before checking the file so a segment renamed just before exit is found.
const exited = job.processExited
try { try {
// ffmpeg writes to a .tmp file and renames it when complete. const firstStat = await fs.stat(segmentPath)
await fs.access(segmentPath) if (firstStat.size > 0) {
return segmentPath await new Promise((resolve) => setTimeout(resolve, 100))
} catch { const secondStat = await fs.stat(segmentPath)
if (job.evicted) { if (firstStat.size === secondStat.size) {
throw new Error("HLS job was evicted") return segmentPath
}
} }
if (exited) { } catch {
throw new Error( if (job.processExited && job.processExitCode !== 0) {
job.processExitCode === 0 throw new Error(`HLS transcode failed with code ${job.processExitCode}`)
? "HLS segment does not exist"
: `HLS transcode failed with code ${job.processExitCode}`
)
} }
} }
await new Promise((resolve) => setTimeout(resolve, 100)) await new Promise((resolve) => setTimeout(resolve, 100))
@@ -191,15 +157,52 @@ export async function waitForHlsSegment(
throw new Error("Timed out waiting for HLS segment") throw new Error("Timed out waiting for HLS segment")
} }
async function hasCompletePlaylist(dir: string) { export async function ensureHlsJob(
const playlist = await fs song: Doc<"songs">,
.readFile(path.join(dir, "index.m3u8"), "utf8") quality: string | null,
.catch(() => "") preferAtmos: boolean
return playlist.includes("#EXT-X-ENDLIST") ) {
} await cleanupIdleHlsJobs()
const kbps = qualityKbps(quality)
const sourceCodec = selectHlsSourceCodec(song, quality, preferAtmos)
const sourcePath = song.files[sourceCodec]
const key = await hlsJobKey(song, sourcePath, kbps)
const lookupKey = hlsLookupKey(song._id, quality, preferAtmos)
const existingJob = jobs.get(key)
if (existingJob) {
try {
await fs.access(existingJob.dir)
await touchHlsJob(existingJob)
return existingJob
} catch {
forgetJob(existingJob)
}
}
const metadata = await music.parseFile(sourcePath)
const duration = metadata.format.duration ?? song.length
const segmentCount = Math.max(1, Math.ceil(duration / HLS_SEGMENT_SECONDS))
const dir = path.join(hlsCacheRoot(), key)
await fs.mkdir(dir, { recursive: true })
const job: HlsJob = {
key,
lookupKey,
dir,
duration,
segmentCount,
lastTouchedAt: Date.now(),
processExited: false,
processExitCode: null,
}
jobs.set(key, job)
jobsByLookup.set(lookupKey, job)
await touchHlsJob(job)
function startTranscode(job: HlsJob, sourcePath: string, kbps: number) {
const ffmpegArgs = [ const ffmpegArgs = [
"-nostdin",
"-i", "-i",
sourcePath, sourcePath,
"-vn", "-vn",
@@ -219,121 +222,25 @@ function startTranscode(job: HlsJob, sourcePath: string, kbps: number) {
"0", "0",
"-hls_segment_type", "-hls_segment_type",
"mpegts", "mpegts",
"-hls_flags",
"temp_file",
"-hls_segment_filename", "-hls_segment_filename",
path.join(job.dir, "segment_%05d.ts"), path.join(dir, "segment_%05d.ts"),
path.join(job.dir, "index.m3u8"), path.join(dir, "index.m3u8"),
] ]
const ffmpegProcess = spawn("ffmpeg", ffmpegArgs)
spawnFfmpeg(ffmpegArgs, job.abort.signal).then( ffmpegProcess.stderr.on("data", (data) => {
async (ffmpeg) => { console.error(`FFmpeg HLS log: ${data.toString()}`)
job.process = ffmpeg })
if (job.evicted) {
ffmpeg.child.kill("SIGKILL")
}
const code = await ffmpeg.exited
job.process = null
job.processExited = true
job.processExitCode = code
if (job.evicted) {
return
}
if (code === 0) {
void pruneCache()
} else {
console.error(`ffmpeg HLS exited with code ${code}`, ffmpeg.stderrTail())
}
},
() => {
job.processExited = true
job.processExitCode = 1
}
)
}
async function createHlsJob( ffmpegProcess.on("close", (code) => {
song: SongSource, job.processExited = true
sourcePath: string, job.processExitCode = code
kbps: number, })
key: string,
lookupKey: string
): Promise<HlsJob> {
const info = await audioInfo(sourcePath)
const duration = info.duration ?? song.length
const segmentCount = Math.max(1, Math.ceil(duration / HLS_SEGMENT_SECONDS))
const dir = path.join(cacheDir("hls"), key)
pinCacheEntry(dir)
try { ffmpegProcess.on("error", () => {
const complete = await hasCompletePlaylist(dir) job.processExited = true
if (!complete) { job.processExitCode = 1
await fs.rm(dir, { recursive: true, force: true }) })
await fs.mkdir(dir, { recursive: true })
}
const job: HlsJob = {
key,
lookupKey,
dir,
duration,
segmentCount,
lastTouchedAt: Date.now(),
processExited: complete,
processExitCode: complete ? 0 : null,
process: null,
abort: new AbortController(),
evicted: false,
}
state.jobs.set(key, job)
await touchHlsJob(job)
if (!complete) {
startTranscode(job, sourcePath, kbps)
}
return job
} catch (error) {
unpinCacheEntry(dir)
throw error
}
}
export async function ensureHlsJob(
song: SongSource,
quality: string | null,
preferAtmos: boolean
): Promise<HlsJob> {
await cleanupIdleHlsJobs()
const kbps = qualityKbps(quality)
const sourceCodec = selectHlsSourceCodec(song, quality, preferAtmos)
const sourcePath = song.files[sourceCodec]
const key = await hlsJobKey(song, sourcePath, kbps)
const lookupKey = hlsLookupKey(song._id, quality, preferAtmos)
let pending = state.pending.get(key)
if (!pending) {
pending = createHlsJob(song, sourcePath, kbps, key, lookupKey)
state.pending.set(key, pending)
const created = pending
created.catch(() => {
if (state.pending.get(key) === created) {
state.pending.delete(key)
}
})
}
const job = await pending
const exists = await fs.access(job.dir).then(
() => true,
() => false
)
if (job.evicted || !exists) {
await evictJob(job)
return ensureHlsJob(song, quality, preferAtmos)
}
state.jobsByLookup.set(lookupKey, job)
await touchHlsJob(job)
return job return job
} }
+43 -32
View File
@@ -1,15 +1,8 @@
import { spawn } from "node:child_process"
import { createHash } from "node:crypto" import { createHash } from "node:crypto"
import fs from "node:fs/promises" import fs from "node:fs/promises"
import os from "node:os"
import path from "node:path" import path from "node:path"
import {
CACHE_ORPHAN_PREFIX,
cacheDir,
pinCacheEntry,
pruneCache,
touchCacheEntry,
unpinCacheEntry,
} from "@/lib/server-cache"
import { spawnFfmpeg } from "@/lib/server-ffmpeg"
const conversions = new Map<string, Promise<string>>() const conversions = new Map<string, Promise<string>>()
@@ -34,38 +27,56 @@ export async function seekableLosslessFile(source: string): Promise<string> {
} }
async function convert(source: string, key: string): Promise<string> { async function convert(source: string, key: string): Promise<string> {
const dir = cacheDir("lossless") const dir = path.join(os.tmpdir(), "otunes-lossless")
await fs.mkdir(dir, { recursive: true }) await fs.mkdir(dir, { recursive: true })
const cutoff = Date.now() - 30 * 60 * 1000
await Promise.all(
(await fs.readdir(dir))
.filter((name) => name.endsWith(".flac"))
.map(async (name) => {
const file = path.join(dir, name)
const stat = await fs.stat(file).catch(() => null)
if (stat && stat.mtimeMs < cutoff) await fs.rm(file, { force: true })
})
)
const output = path.join(dir, `${key}.flac`) const output = path.join(dir, `${key}.flac`)
try { try {
// Every range request touches the file so it stays cached while playing. await fs.access(output)
await touchCacheEntry(output)
return output return output
} catch { } catch {
// Publish only completed conversions so range requests always see a complete file. // Publish only completed conversions so range requests always see a complete file.
} }
const temporaryDir = await fs.mkdtemp(path.join(dir, CACHE_ORPHAN_PREFIX)) const temporary = path.join(
const temporary = path.join(temporaryDir, "audio.flac") await fs.mkdtemp(path.join(dir, "convert-")),
pinCacheEntry(temporaryDir) "audio.flac"
)
try { try {
const ffmpeg = await spawnFfmpeg([ await new Promise<void>((resolve, reject) => {
"-i", const child = spawn(
source, "ffmpeg",
"-map", [
"0:a:0", "-nostdin",
"-c:a", "-v",
"flac", "error",
temporary, "-i",
]) source,
const code = await ffmpeg.exited "-map",
if (code !== 0) { "0:a:0",
throw new Error(`Lossless conversion failed: ${code}: ${ffmpeg.stderrTail()}`) "-c:a",
} "flac",
temporary,
],
{ stdio: "ignore" }
)
child.on("error", reject)
child.on("close", (code) => {
if (code === 0) resolve()
else reject(new Error(`Lossless conversion failed: ${code}`))
})
})
await fs.rename(temporary, output) await fs.rename(temporary, output)
return output
} finally { } finally {
unpinCacheEntry(temporaryDir) await fs.rm(path.dirname(temporary), { recursive: true, force: true })
await fs.rm(temporaryDir, { recursive: true, force: true })
} }
void pruneCache()
return output
} }
-23
View File
@@ -1,23 +0,0 @@
import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { fetchQuery } from "convex/nextjs"
import { convexServerOptions } from "@/lib/convex-server"
import type { SongSource } from "@/lib/server-hls"
/**
* Loads a song's file paths as the requesting listener, so Convex enforces auth
* even if the proxy is bypassed. Throws when signed out or the song is missing.
*/
export async function getSongSource(id: string): Promise<SongSource> {
const token = await convexAuthNextjsToken()
const song = await fetchQuery(
api.library.getSongSource,
{ id: id as Id<"songs"> },
convexServerOptions(token)
)
if (!song) {
throw new Error("Song not found")
}
return song
}
+30
View File
@@ -0,0 +1,30 @@
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
)
})
-1
View File
@@ -14,7 +14,6 @@
"@base-ui/react": "^1.5.0", "@base-ui/react": "^1.5.0",
"@convex-dev/auth": "^0.0.93", "@convex-dev/auth": "^0.0.93",
"@otunes/convex": "workspace:*", "@otunes/convex": "workspace:*",
"@tanstack/react-virtual": "^3.14.26",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cmdk": "^1.1.1", "cmdk": "^1.1.1",
+1 -1
View File
@@ -12,7 +12,7 @@ const isPublic = createRouteMatcher([
"/api/playlist/:id/cover", "/api/playlist/:id/cover",
"/album/:id", "/album/:id",
"/artist/:id", "/artist/:id",
"/library/artists/:id", "/artists/:id",
"/playlist/:id", "/playlist/:id",
]) ])
+6 -30
View File
@@ -46,34 +46,22 @@ stop() {
} }
trap 'stop; exit 0' TERM INT trap 'stop; exit 0' TERM INT
as_convex=(setpriv --reuid=convex --regid=convex --init-groups env HOME=/home/convex)
convex_cli() { convex_cli() {
( (
cd "$FUNCTIONS_DIR" cd "$FUNCTIONS_DIR"
unset CONVEX_DEPLOYMENT CONVEX_DEPLOY_KEY unset CONVEX_DEPLOYMENT CONVEX_DEPLOY_KEY
CONVEX_SELF_HOSTED_URL="$BACKEND_URL" \ CONVEX_SELF_HOSTED_URL="$BACKEND_URL" \
CONVEX_SELF_HOSTED_ADMIN_KEY="$admin_key" \ CONVEX_SELF_HOSTED_ADMIN_KEY="$admin_key" \
"${as_convex[@]}" "$NODE" node_modules/convex/bin/main.js "$@" "$NODE" node_modules/convex/bin/main.js "$@"
) )
} }
# Only the convex user may read the database and instance secret. Volumes from # Only root (the backend) may read the database and instance secret.
# 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" mkdir -p "$CONVEX_DATA_DIR"
find "$CONVEX_DATA_DIR" \( ! -user convex -o ! -group convex \) \
-exec chown -h convex:convex {} +
chmod 700 "$CONVEX_DATA_DIR" 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" log "Starting Convex backend"
(cd /convex && umask 077 && exec "${as_convex[@]}" ./run_backend.sh) & (cd /convex && umask 077 && exec ./run_backend.sh) &
backend_pid=$! backend_pid=$!
for _ in $(seq 1 120); do for _ in $(seq 1 120); do
@@ -92,27 +80,17 @@ if ! curl -fsS "$BACKEND_URL/version" >/dev/null 2>&1; then
exit 1 exit 1
fi fi
admin_key=$(cd /convex && umask 077 && "${as_convex[@]}" ./generate_admin_key.sh) admin_key=$(cd /convex && ./generate_admin_key.sh)
log "Deploying Convex functions" log "Deploying Convex functions"
convex_cli deploy --typecheck disable --codegen disable convex_cli deploy --typecheck disable --codegen disable
log "Running data migrations" if [ -z "$(convex_cli env get JWKS 2>/dev/null || true)" ]; then
convex_cli run migrations:migrateUsers
# `env get` exits 0 with no output when the variable is unset. Any other failure
# must not be read as "no keys": regenerating them signs every user out.
if ! jwks=$(convex_cli env get JWKS); then
log "Could not read Convex Auth signing keys"
stop
exit 1
fi
if [ -z "$jwks" ]; then
log "Generating Convex Auth signing keys" log "Generating Convex Auth signing keys"
"$NODE" /opt/otunes/generate-auth-keys.mjs | convex_cli env set --force "$NODE" /opt/otunes/generate-auth-keys.mjs | convex_cli env set --force
fi fi
unset admin_key jwks unset admin_key
log "Starting web server" log "Starting web server"
( (
@@ -122,8 +100,6 @@ log "Starting web server"
# Server-side Convex helpers fall back to this at runtime. The browser bundle # Server-side Convex helpers fall back to this at runtime. The browser bundle
# is built without it, so browsers still derive their own URL. # is built without it, so browsers still derive their own URL.
export NEXT_PUBLIC_CONVEX_URL="$BACKEND_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 \ exec setpriv --reuid=otunes --regid=otunes --init-groups \
"$NODE" apps/web/server.js "$NODE" apps/web/server.js
) & ) &
+18 -66
View File
@@ -1,5 +1,4 @@
import type { Id } from "../convex/_generated/dataModel" import type { Id } from "../convex/_generated/dataModel"
import { MAX_QUEUE_LENGTH } from "../convex/limits"
import { import {
EMPTY_PLAYBACK_QUEUE, EMPTY_PLAYBACK_QUEUE,
type PlaybackQueueState, type PlaybackQueueState,
@@ -8,11 +7,6 @@ import {
import { loadPersistentCache, readCache, writeCache } from "./persistent-cache" import { loadPersistentCache, readCache, writeCache } from "./persistent-cache"
const SYNC_DELAY_MS = 300 const SYNC_DELAY_MS = 300
/**
* Backoff for failed syncs. Convex queues mutations while offline, so a
* rejection means the server refused the state; after the last retry the
* change is dropped until the next local edit instead of retrying forever.
*/
const RETRY_DELAYS_MS = [1_000, 3_000, 10_000, 30_000] const RETRY_DELAYS_MS = [1_000, 3_000, 10_000, 30_000]
export type ServerPlaybackState = { export type ServerPlaybackState = {
@@ -20,6 +14,7 @@ export type ServerPlaybackState = {
queueHistorySongIds: Id<"songs">[] queueHistorySongIds: Id<"songs">[]
shuffleEnabled: boolean shuffleEnabled: boolean
repeatEnabled: RepeatMode repeatEnabled: RepeatMode
currentSongProgress: number
revision: number revision: number
} }
@@ -35,12 +30,9 @@ type PersistedPlayback = PlaybackQueueState & {
dirty: boolean dirty: boolean
} }
export type PlaybackSyncTransport = { export type PlaybackSyncTransport = (
/** Saves the state and resolves with the new server revision. */ state: PlaybackQueueState
sync: (state: PlaybackQueueState) => Promise<number> ) => Promise<number>
/** One-shot read of the server's saved progress for its current song. */
loadProgress: () => Promise<number>
}
/** /**
* Client-owned playback queue. Changes apply locally (and persist on this * Client-owned playback queue. Changes apply locally (and persist on this
@@ -57,7 +49,6 @@ export class PlaybackStore {
private retryAttempt = 0 private retryAttempt = 0
private syncTimer: ReturnType<typeof setTimeout> | null = null private syncTimer: ReturnType<typeof setTimeout> | null = null
private latestServerState: ServerPlaybackState | null = null private latestServerState: ServerPlaybackState | null = null
private adopting = false
private transport: PlaybackSyncTransport | null = null private transport: PlaybackSyncTransport | null = null
private readonly listeners = new Set<() => void>() private readonly listeners = new Set<() => void>()
@@ -88,7 +79,7 @@ export class PlaybackStore {
} }
update(recipe: (state: PlaybackQueueState) => PlaybackQueueState) { update(recipe: (state: PlaybackQueueState) => PlaybackQueueState) {
const next = capQueue(recipe(this.state)) const next = recipe(this.state)
if (next === this.state) { if (next === this.state) {
return return
} }
@@ -111,7 +102,7 @@ export class PlaybackStore {
receiveServerState(serverState: ServerPlaybackState) { receiveServerState(serverState: ServerPlaybackState) {
this.latestServerState = serverState this.latestServerState = serverState
if (this.snapshot.hydrated) { if (this.snapshot.hydrated) {
void this.adoptServerState() this.adoptServerState()
} }
} }
@@ -125,52 +116,23 @@ export class PlaybackStore {
const { revision, dirty, ...state } = persisted const { revision, dirty, ...state } = persisted
this.revision = revision this.revision = revision
this.dirty = dirty this.dirty = dirty
this.state = capQueue({ ...EMPTY_PLAYBACK_QUEUE, ...state }) this.state = { ...EMPTY_PLAYBACK_QUEUE, ...state }
} }
this.snapshot = toSnapshot(this.state, true) this.snapshot = toSnapshot(this.state, true)
this.emit() this.emit()
void this.adoptServerState() this.adoptServerState()
if (this.dirty) { if (this.dirty) {
this.scheduleSync(0) this.scheduleSync(0)
} }
} }
private canAdopt(serverState: ServerPlaybackState | null) { private adoptServerState() {
return (
serverState !== null &&
!this.dirty &&
!this.inFlight &&
(this.revision === null || serverState.revision > this.revision)
)
}
/**
* Adopts the latest server queue. Progress is not part of the queue query
* (it changes every few seconds), so it is fetched once here.
*/
private async adoptServerState() {
const serverState = this.latestServerState const serverState = this.latestServerState
if (this.adopting || !serverState || !this.canAdopt(serverState)) { if (!serverState || this.dirty || this.inFlight) {
return return
} }
if (this.revision !== null && serverState.revision <= this.revision) {
this.adopting = true
let progressSeconds = 0
try {
progressSeconds = (await this.transport?.loadProgress()) ?? 0
} catch {
// Starting from 0 beats not adopting the queue at all.
} finally {
this.adopting = false
}
// Newer server state or local edits may have arrived while loading.
if (this.latestServerState !== serverState) {
void this.adoptServerState()
return
}
if (!this.canAdopt(serverState)) {
return return
} }
@@ -180,7 +142,7 @@ export class PlaybackStore {
history: serverState.queueHistorySongIds, history: serverState.queueHistorySongIds,
shuffleEnabled: serverState.shuffleEnabled, shuffleEnabled: serverState.shuffleEnabled,
repeatEnabled: serverState.repeatEnabled, repeatEnabled: serverState.repeatEnabled,
progressSeconds, progressSeconds: serverState.currentSongProgress,
}) })
} }
@@ -205,7 +167,7 @@ export class PlaybackStore {
let failed = false let failed = false
try { try {
const revision = await transport.sync(this.state) const revision = await transport(this.state)
this.revision = Math.max(revision, this.revision ?? 0) this.revision = Math.max(revision, this.revision ?? 0)
this.retryAttempt = 0 this.retryAttempt = 0
if (this.changeCount === changeCountAtStart) { if (this.changeCount === changeCountAtStart) {
@@ -219,17 +181,15 @@ export class PlaybackStore {
this.persist() this.persist()
if (failed && this.retryAttempt < RETRY_DELAYS_MS.length) { if (failed) {
this.scheduleSync(RETRY_DELAYS_MS[this.retryAttempt]) const delay =
RETRY_DELAYS_MS[Math.min(this.retryAttempt, RETRY_DELAYS_MS.length - 1)]
this.retryAttempt += 1 this.retryAttempt += 1
} else if (failed) { this.scheduleSync(delay)
this.retryAttempt = 0
this.dirty = false
this.persist()
} else if (this.dirty) { } else if (this.dirty) {
this.scheduleSync(SYNC_DELAY_MS) this.scheduleSync(SYNC_DELAY_MS)
} else { } else {
void this.adoptServerState() this.adoptServerState()
} }
} }
@@ -267,14 +227,6 @@ export class PlaybackStore {
} }
} }
/** Mirrors the server's queue cap so local and synced state agree. */
function capQueue(state: PlaybackQueueState): PlaybackQueueState {
if (state.queue.length <= MAX_QUEUE_LENGTH) {
return state
}
return { ...state, queue: state.queue.slice(0, MAX_QUEUE_LENGTH) }
}
function toSnapshot( function toSnapshot(
state: PlaybackQueueState, state: PlaybackQueueState,
hydrated: boolean hydrated: boolean
-6
View File
@@ -14,10 +14,7 @@ import type * as crons from "../crons.js";
import type * as favorites from "../favorites.js"; import type * as favorites from "../favorites.js";
import type * as http from "../http.js"; import type * as http from "../http.js";
import type * as library from "../library.js"; import type * as library from "../library.js";
import type * as limits from "../limits.js";
import type * as migrations from "../migrations.js";
import type * as playback from "../playback.js"; import type * as playback from "../playback.js";
import type * as playbackState from "../playbackState.js";
import type * as playlists from "../playlists.js"; import type * as playlists from "../playlists.js";
import type * as types from "../types.js"; import type * as types from "../types.js";
import type * as users from "../users.js"; import type * as users from "../users.js";
@@ -35,10 +32,7 @@ declare const fullApi: ApiFromModules<{
favorites: typeof favorites; favorites: typeof favorites;
http: typeof http; http: typeof http;
library: typeof library; library: typeof library;
limits: typeof limits;
migrations: typeof migrations;
playback: typeof playback; playback: typeof playback;
playbackState: typeof playbackState;
playlists: typeof playlists; playlists: typeof playlists;
types: typeof types; types: typeof types;
users: typeof users; users: typeof users;
+7
View File
@@ -578,6 +578,13 @@ export const updateLibrary = action({
}, },
}) })
export const cleanupHlsStreams = internalAction({
args: {},
handler: async () => {
return await cleanHlsStreamsOlderThan(HLS_MAX_IDLE_MS)
},
})
export const adminCleanupHlsStreams = action({ export const adminCleanupHlsStreams = action({
args: {}, args: {},
handler: async (ctx) => { handler: async (ctx) => {
+1 -2
View File
@@ -3,7 +3,6 @@ import { ConvexError } from "convex/values"
import { Password } from "@convex-dev/auth/providers/Password" import { Password } from "@convex-dev/auth/providers/Password"
import { query } from "./_generated/server" import { query } from "./_generated/server"
import type { MutationCtx } from "./_generated/server" import type { MutationCtx } from "./_generated/server"
import { profileImagePath } from "./users"
export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({ export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({
providers: [ providers: [
@@ -73,7 +72,7 @@ export const currentUser = query({
return { return {
_id: user._id, _id: user._id,
name: user.name, name: user.name,
image: profileImagePath(user), image: user.image,
email: user.email, email: user.email,
isAdmin: user.isAdmin, isAdmin: user.isAdmin,
playbackQuality: user.playbackQuality, playbackQuality: user.playbackQuality,
+25 -1
View File
@@ -1,10 +1,11 @@
import { getAuthUserId } from "@convex-dev/auth/server" import { getAuthUserId } from "@convex-dev/auth/server"
import { ConvexError, v } from "convex/values" import { ConvexError, v } from "convex/values"
import { paginationOptsValidator } from "convex/server"
import type { Doc, Id } from "./_generated/dataModel" import type { Doc, Id } from "./_generated/dataModel"
import type { MutationCtx, QueryCtx } from "./_generated/server" import type { MutationCtx, QueryCtx } from "./_generated/server"
import { mutation, query } from "./_generated/server" import { mutation, query } from "./_generated/server"
import type { BrowsePlaylistDetail, BrowsePlaylistSummary } from "./library" import type { BrowsePlaylistDetail, BrowsePlaylistSummary } from "./library"
import { browseSongsFromIds } from "./library" import { browseSongsFromIds, paginateSlice } from "./library"
function uniqueIds<T extends string>(ids: T[]): T[] { function uniqueIds<T extends string>(ids: T[]): T[] {
return [...new Set(ids)] return [...new Set(ids)]
@@ -180,6 +181,11 @@ async function browseFavoritesSummaryHandler(
} }
} }
export const browseFavoritesSummary = query({
args: {},
handler: async (ctx) => browseFavoritesSummaryHandler(ctx),
})
export const browseFavoritesPlaylistDetail = query({ export const browseFavoritesPlaylistDetail = query({
args: {}, args: {},
handler: async (ctx): Promise<BrowsePlaylistDetail | null> => { handler: async (ctx): Promise<BrowsePlaylistDetail | null> => {
@@ -203,6 +209,24 @@ 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({ export const favoriteSong = mutation({
args: { songId: v.id("songs") }, args: { songId: v.id("songs") },
handler: async (ctx, { songId }) => { handler: async (ctx, { songId }) => {
+298 -70
View File
@@ -8,6 +8,7 @@ import type { PaginationOptions, PaginationResult } from "convex/server"
import type { import type {
BrowseAlbum, BrowseAlbum,
BrowseAlbumDetail, BrowseAlbumDetail,
BrowseAlbumSummary,
BrowseAlbumTrack, BrowseAlbumTrack,
BrowseArtist, BrowseArtist,
BrowseArtistDetail, BrowseArtistDetail,
@@ -25,6 +26,7 @@ import type {
export type { export type {
BrowseAlbum, BrowseAlbum,
BrowseAlbumDetail, BrowseAlbumDetail,
BrowseAlbumSummary,
BrowseAlbumTrack, BrowseAlbumTrack,
BrowseArtist, BrowseArtist,
BrowseArtistDetail, BrowseArtistDetail,
@@ -39,20 +41,6 @@ export type {
SidebarPlaylists, SidebarPlaylists,
} from "./types" } from "./types"
const EMPTY_PAGE = { page: [], isDone: true, continueCursor: "" }
/** Reactive queries return empty data when signed out so sign-out doesn't throw mid-render. */
export async function isSignedIn(ctx: QueryCtx) {
return (await getAuthUserId(ctx)) !== null
}
/** Imperative lookups throw instead, so callers that cache results don't cache an empty one. */
export async function requireSignedIn(ctx: QueryCtx) {
if (!(await isSignedIn(ctx))) {
throw new ConvexError("Not authenticated")
}
}
function getSongArtistNames(artist: string | string[]): string[] { function getSongArtistNames(artist: string | string[]): string[] {
if (Array.isArray(artist)) { if (Array.isArray(artist)) {
return artist.map((name) => name.trim()).filter((name) => name.length > 0) return artist.map((name) => name.trim()).filter((name) => name.length > 0)
@@ -214,9 +202,6 @@ function toBrowseSong(
export const browseAlbums = query({ export const browseAlbums = query({
args: {}, args: {},
handler: async (ctx) => { handler: async (ctx) => {
if (!(await isSignedIn(ctx))) {
return []
}
const artistMap = await loadArtistMap(ctx) const artistMap = await loadArtistMap(ctx)
const albums = await ctx.db.query("albums").collect() const albums = await ctx.db.query("albums").collect()
@@ -232,9 +217,6 @@ export const browseAlbums = query({
export const browseArtists = query({ export const browseArtists = query({
args: {}, args: {},
handler: async (ctx) => { handler: async (ctx) => {
if (!(await isSignedIn(ctx))) {
return []
}
const artists = await ctx.db.query("artists").collect() const artists = await ctx.db.query("artists").collect()
return artists return artists
.map(toBrowseArtist) .map(toBrowseArtist)
@@ -242,7 +224,7 @@ export const browseArtists = query({
}, },
}) })
function paginateSlice<T>( export function paginateSlice<T>(
items: T[], items: T[],
paginationOpts: PaginationOptions paginationOpts: PaginationOptions
): PaginationResult<T> { ): PaginationResult<T> {
@@ -262,9 +244,6 @@ function paginateSlice<T>(
export const browseArtistsPaginated = query({ export const browseArtistsPaginated = query({
args: { paginationOpts: paginationOptsValidator }, args: { paginationOpts: paginationOptsValidator },
handler: async (ctx, args) => { handler: async (ctx, args) => {
if (!(await isSignedIn(ctx))) {
return EMPTY_PAGE
}
const result = await ctx.db const result = await ctx.db
.query("artists") .query("artists")
.withIndex("by_name") .withIndex("by_name")
@@ -281,9 +260,6 @@ export const browseArtistsPaginated = query({
export const browseAlbumsPaginated = query({ export const browseAlbumsPaginated = query({
args: { paginationOpts: paginationOptsValidator }, args: { paginationOpts: paginationOptsValidator },
handler: async (ctx, args) => { handler: async (ctx, args) => {
if (!(await isSignedIn(ctx))) {
return EMPTY_PAGE
}
const result = await ctx.db const result = await ctx.db
.query("albums") .query("albums")
.withIndex("by_name") .withIndex("by_name")
@@ -304,6 +280,27 @@ 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( export const songsSortKeyValidator = v.union(
v.literal("title"), v.literal("title"),
v.literal("artist"), v.literal("artist"),
@@ -484,9 +481,6 @@ export const browseSongsPaginated = query({
sortDirection: songsSortDirectionValidator, sortDirection: songsSortDirectionValidator,
}, },
handler: async (ctx, args) => { handler: async (ctx, args) => {
if (!(await isSignedIn(ctx))) {
return EMPTY_PAGE
}
if (args.sortKey === "title") { if (args.sortKey === "title") {
return paginateSongsByTitle(ctx, args.paginationOpts, args.sortDirection) return paginateSongsByTitle(ctx, args.paginationOpts, args.sortDirection)
} }
@@ -506,7 +500,6 @@ export const browseSortedSongIds = query({
sortDirection: songsSortDirectionValidator, sortDirection: songsSortDirectionValidator,
}, },
handler: async (ctx, args) => { handler: async (ctx, args) => {
await requireSignedIn(ctx)
return getSortedLibrarySongIds(ctx, args.sortKey, args.sortDirection) return getSortedLibrarySongIds(ctx, args.sortKey, args.sortDirection)
}, },
}) })
@@ -516,7 +509,6 @@ const MAX_SONGS_BY_IDS = 200
export const browseSongsByIds = query({ export const browseSongsByIds = query({
args: { ids: v.array(v.id("songs")) }, args: { ids: v.array(v.id("songs")) },
handler: async (ctx, args): Promise<BrowseSong[]> => { handler: async (ctx, args): Promise<BrowseSong[]> => {
await requireSignedIn(ctx)
if (args.ids.length > MAX_SONGS_BY_IDS) { if (args.ids.length > MAX_SONGS_BY_IDS) {
throw new ConvexError(`Request at most ${MAX_SONGS_BY_IDS} songs`) throw new ConvexError(`Request at most ${MAX_SONGS_BY_IDS} songs`)
} }
@@ -524,7 +516,6 @@ export const browseSongsByIds = query({
}, },
}) })
/** Public: shared /album links render this without a session. */
export const browseAlbumDetail = query({ export const browseAlbumDetail = query({
args: { id: v.id("albums") }, args: { id: v.id("albums") },
handler: async (ctx, args): Promise<BrowseAlbumDetail | null> => { handler: async (ctx, args): Promise<BrowseAlbumDetail | null> => {
@@ -554,7 +545,72 @@ export const browseAlbumDetail = query({
}, },
}) })
/** Public: shared /artist links render this without a session. */ async function browseAlbumSummaryHandler(
ctx: QueryCtx,
albumId: Id<"albums">
): Promise<BrowseAlbumSummary | null> {
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({ export const browseArtistDetail = query({
args: { id: v.id("artists") }, args: { id: v.id("artists") },
handler: async (ctx, args) => { handler: async (ctx, args) => {
@@ -608,7 +664,7 @@ export const searchLibrary = query({
args: { query: v.string() }, args: { query: v.string() },
handler: async (ctx, args) => { handler: async (ctx, args) => {
const queryText = args.query.trim().toLowerCase() const queryText = args.query.trim().toLowerCase()
if (!queryText || !(await isSignedIn(ctx))) { if (!queryText) {
return { return {
topResults: [], topResults: [],
artists: [], artists: [],
@@ -710,9 +766,6 @@ export const searchLibrary = query({
export const browseRecentlyAdded = query({ export const browseRecentlyAdded = query({
args: { limit: v.optional(v.number()) }, args: { limit: v.optional(v.number()) },
handler: async (ctx, args) => { handler: async (ctx, args) => {
if (!(await isSignedIn(ctx))) {
return []
}
const albumQuery = ctx.db.query("albums").order("desc") const albumQuery = ctx.db.query("albums").order("desc")
const albums = args.limit const albums = args.limit
? await albumQuery.take(args.limit) ? await albumQuery.take(args.limit)
@@ -732,9 +785,6 @@ export const browseRecentlyAdded = query({
export const browseRecentlyAddedPaginated = query({ export const browseRecentlyAddedPaginated = query({
args: { paginationOpts: paginationOptsValidator }, args: { paginationOpts: paginationOptsValidator },
handler: async (ctx, args) => { handler: async (ctx, args) => {
if (!(await isSignedIn(ctx))) {
return EMPTY_PAGE
}
const result = await ctx.db const result = await ctx.db
.query("albums") .query("albums")
.order("desc") .order("desc")
@@ -858,6 +908,16 @@ 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({ export const getSongs = internalQuery({
args: {}, args: {},
handler: async (ctx) => { handler: async (ctx) => {
@@ -865,53 +925,83 @@ export const getSongs = internalQuery({
}, },
}) })
/** Public: share-link previews load covers without a session. */ export const getSongsInArtist = internalQuery({
export const getArtistCover = query({ 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") }, args: { id: v.id("artists") },
handler: async (ctx, args) => { handler: async (ctx, args) => {
return (await ctx.db.get("artists", args.id))?.cover ?? null return await ctx.db.get("artists", args.id)
}, },
}) })
/** Public: share-link previews load covers without a session. */ export const getArtistByName = internalQuery({
export const getAlbumCover = query({ 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") }, args: { id: v.id("albums") },
handler: async (ctx, args) => { handler: async (ctx, args) => {
return (await ctx.db.get("albums", args.id))?.cover ?? null return await ctx.db.get("albums", args.id)
}, },
}) })
/** Public: share-link previews load covers without a session. */ export const getAlbumByName = internalQuery({
export const getPlaylistCover = query({ 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") }, args: { id: v.id("playlists") },
handler: async (ctx, args) => { handler: async (ctx, args) => {
return (await ctx.db.get("playlists", args.id))?.cover ?? null return await ctx.db.get("playlists", args.id)
}, },
}) })
/** Public: share-link previews read song metadata without a session. Never returns file paths. */
export const getSong = query({ export const getSong = query({
args: { id: v.id("songs") }, args: { id: v.id("songs") },
handler: async (ctx, args) => { handler: async (ctx, args) => {
const song = await ctx.db.get("songs", args.id) return await ctx.db.get("songs", args.id)
if (!song) {
return null
}
const { files: _files, ...clientSong } = song
return clientSong
},
})
/** Returns absolute file paths. Only the web streaming routes call this, as the listener. */
export const getSongSource = query({
args: { id: v.id("songs") },
handler: async (ctx, args) => {
await requireSignedIn(ctx)
const song = await ctx.db.get("songs", args.id)
if (!song) {
return null
}
return { _id: song._id, files: song.files, length: song.length }
}, },
}) })
@@ -1085,6 +1175,49 @@ 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({ export const createArtists = internalMutation({
args: { args: {
artists: v.array( artists: v.array(
@@ -1109,6 +1242,29 @@ 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({ export const createAlbums = internalMutation({
args: { args: {
albums: v.array( albums: v.array(
@@ -1138,6 +1294,50 @@ 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({ export const createSongs = internalMutation({
args: { args: {
songs: v.array( songs: v.array(
@@ -1285,6 +1485,13 @@ 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({ export const removeArtists = internalMutation({
args: { ids: v.array(v.id("artists")) }, args: { ids: v.array(v.id("artists")) },
handler: async (ctx, args) => { handler: async (ctx, args) => {
@@ -1294,6 +1501,13 @@ 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({ export const removeAlbums = internalMutation({
args: { ids: v.array(v.id("albums")) }, args: { ids: v.array(v.id("albums")) },
handler: async (ctx, args) => { handler: async (ctx, args) => {
@@ -1303,6 +1517,20 @@ 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({ export const changeFilesForSongs = internalMutation({
args: { args: {
songs: v.array( songs: v.array(
-10
View File
@@ -1,10 +0,0 @@
/**
* Limits shared by Convex functions and clients. Convex rejects arrays longer
* than 8,192 values in documents, arguments, and return values.
*/
/** Songs kept in the playback queue, including the current song. */
export const MAX_QUEUE_LENGTH = 5_000
/** Largest profile photo accepted, in bytes after base64 decoding. */
export const MAX_PROFILE_IMAGE_BYTES = 2 * 1024 * 1024
-39
View File
@@ -1,39 +0,0 @@
import { v } from "convex/values"
import { internal } from "./_generated/api"
import { internalMutation } from "./_generated/server"
import { hasLegacyPlayback, migrateUserPlayback } from "./playbackState"
const BATCH_SIZE = 25
/**
* Moves playback state off `users` into `playbackStates`/`playbackProgress`
* and legacy data URL avatars into file storage. Idempotent; the Docker
* entrypoint runs it on every boot. Run manually with
* `npx convex run migrations:migrateUsers`.
*/
export const migrateUsers = internalMutation({
args: { cursor: v.optional(v.union(v.string(), v.null())) },
handler: async (ctx, { cursor }) => {
const page = await ctx.db
.query("users")
.paginate({ cursor: cursor ?? null, numItems: BATCH_SIZE })
for (const user of page.page) {
if (hasLegacyPlayback(user)) {
await migrateUserPlayback(ctx, user)
}
if (!user.imageStorageId && user.image?.startsWith("data:")) {
await ctx.scheduler.runAfter(0, internal.users.storeProfileImage, {
userId: user._id,
image: user.image,
})
}
}
if (!page.isDone) {
await ctx.scheduler.runAfter(0, internal.migrations.migrateUsers, {
cursor: page.continueCursor,
})
}
},
})
+684 -42
View File
@@ -1,19 +1,21 @@
import { getAuthUserId } from "@convex-dev/auth/server" import { getAuthUserId } from "@convex-dev/auth/server"
import { paginationOptsValidator } from "convex/server"
import { ConvexError, v } from "convex/values" import { ConvexError, v } from "convex/values"
import type { Id } from "./_generated/dataModel" import type { Doc, Id } from "./_generated/dataModel"
import type { MutationCtx } from "./_generated/server" import type { MutationCtx } from "./_generated/server"
import { mutation, query } from "./_generated/server" import { mutation, query } from "./_generated/server"
import { browseSongsFromIds } from "./library" import type { QueueSong } from "./types"
import { import {
loadPlaybackForWrite, browseSongsFromIds,
readPlaybackProgress, compareAlbumSongs,
readPlaybackState, getSortedLibrarySongIds,
writePlayback, songsSortDirectionValidator,
writeProgress, songsSortKeyValidator,
} from "./playbackState" } from "./library"
export type { HistorySong, QueueSong } from "./types" export type { HistorySong, QueueSong } from "./types"
const MAX_QUEUE_HISTORY = 30
const MAX_RECENTLY_PLAYED = 30 const MAX_RECENTLY_PLAYED = 30
type RecentlyPlayedItem = Id<"albums"> | Id<"playlists"> type RecentlyPlayedItem = Id<"albums"> | Id<"playlists">
@@ -57,6 +59,35 @@ async function recordRecentlyPlayedFromSong(
await recordRecentlyPlayed(ctx, userId, song.album) 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<T>(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) { async function requireAuth(ctx: MutationCtx) {
const userId = await getAuthUserId(ctx) const userId = await getAuthUserId(ctx)
if (userId === null) { if (userId === null) {
@@ -65,15 +96,98 @@ async function requireAuth(ctx: MutationCtx) {
return userId return userId
} }
async function requirePlayback(ctx: MutationCtx, userId: Id<"users">) { function uniqueSongIds(songIds: Id<"songs">[]) {
const playback = await loadPlaybackForWrite(ctx, userId) return [...new Set(songIds)]
if (!playback) { }
function haveSameSongCounts(first: Id<"songs">[], second: Id<"songs">[]) {
if (first.length !== second.length) {
return false
}
const counts = new Map<Id<"songs">, number>()
for (const songId of first) {
counts.set(songId, (counts.get(songId) ?? 0) + 1)
}
for (const songId of second) {
const count = counts.get(songId)
if (!count) {
return false
}
if (count === 1) {
counts.delete(songId)
} else {
counts.set(songId, count - 1)
}
}
return counts.size === 0
}
function appendToQueueHistory(
history: Id<"songs">[],
songId: Id<"songs">
): Id<"songs">[] {
const next = [...history, songId]
if (next.length <= MAX_QUEUE_HISTORY) {
return next
}
return next.slice(next.length - MAX_QUEUE_HISTORY)
}
function appendManyToQueueHistory(
history: Id<"songs">[],
songIds: Id<"songs">[]
): Id<"songs">[] {
let next = history
for (const songId of songIds) {
next = appendToQueueHistory(next, songId)
}
return next
}
async function patchPlayback(
ctx: MutationCtx,
userId: Id<"users">,
patch: Partial<
Pick<
Doc<"users">,
| "songQueue"
| "queueHistory"
| "currentSongProgress"
| "shuffleEnabled"
| "repeatEnabled"
>
>
) {
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found") throw new ConvexError("User not found")
}
const playbackRevision = (user.playbackRevision ?? 0) + 1
await ctx.db.patch(userId, { ...patch, playbackRevision })
return playbackRevision
}
async function setQueueState(
ctx: MutationCtx,
userId: Id<"users">,
patch: {
songQueue: Id<"songs">[]
shuffleEnabled?: boolean
currentSongProgress?: number
resetHistory?: boolean
} }
return playback ) {
await patchPlayback(ctx, userId, {
songQueue: patch.songQueue,
currentSongProgress: patch.currentSongProgress ?? 0,
...(patch.resetHistory ? { queueHistory: [] } : {}),
...(patch.shuffleEnabled !== undefined
? { shuffleEnabled: patch.shuffleEnabled }
: {}),
})
} }
/** Queue state without progress; progress comes from `getSongProgress`. */
export const getPlaybackState = query({ export const getPlaybackState = query({
args: {}, args: {},
handler: async (ctx) => { handler: async (ctx) => {
@@ -82,8 +196,12 @@ export const getPlaybackState = query({
return null return null
} }
const playback = await readPlaybackState(ctx, userId) const user = await ctx.db.get(userId)
const songIds = playback.songQueue if (!user) {
return null
}
const songIds = user.songQueue ?? []
const currentSong = const currentSong =
songIds.length > 0 songIds.length > 0
? ((await browseSongsFromIds(ctx, [songIds[0]]))[0] ?? null) ? ((await browseSongsFromIds(ctx, [songIds[0]]))[0] ?? null)
@@ -91,16 +209,12 @@ export const getPlaybackState = query({
return { return {
queueSongIds: songIds, queueSongIds: songIds,
queueHistorySongIds: playback.queueHistory, queueHistorySongIds: user.queueHistory ?? [],
currentSong, currentSong,
shuffleEnabled: playback.shuffleEnabled, shuffleEnabled: user.shuffleEnabled ?? false,
repeatEnabled: playback.repeatEnabled, repeatEnabled: user.repeatEnabled ?? ("none" as const),
/** currentSongProgress: user.currentSongProgress ?? 0,
* @deprecated Always 0. Reading progress here would rerun this query on revision: user.playbackRevision ?? 0,
* every progress save. Kept for app builds that predate `getSongProgress`.
*/
currentSongProgress: 0,
revision: playback.revision,
} }
}, },
}) })
@@ -125,12 +239,12 @@ export const syncPlaybackState = mutation({
}, },
handler: async (ctx, args) => { handler: async (ctx, args) => {
const userId = await requireAuth(ctx) const userId = await requireAuth(ctx)
return await writePlayback(ctx, userId, { return await patchPlayback(ctx, userId, {
songQueue: args.songQueue, songQueue: args.songQueue,
queueHistory: args.queueHistory, queueHistory: args.queueHistory.slice(-MAX_QUEUE_HISTORY),
shuffleEnabled: args.shuffleEnabled, shuffleEnabled: args.shuffleEnabled,
repeatEnabled: args.repeatEnabled, repeatEnabled: args.repeatEnabled,
progressSeconds: args.currentSongProgress, currentSongProgress: Math.max(0, Math.floor(args.currentSongProgress)),
}) })
}, },
}) })
@@ -150,10 +264,537 @@ export const recordPlay = mutation({
}, },
}) })
/** export const getQueueHistory = query({
* Saved position of the current song. Subscribing reruns every few seconds args: {},
* during playback, so clients fetch it once when adopting a new queue. 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({ export const getSongProgress = query({
args: {}, args: {},
handler: async (ctx) => { handler: async (ctx) => {
@@ -162,11 +803,12 @@ export const getSongProgress = query({
throw new ConvexError("User not logged in") throw new ConvexError("User not logged in")
} }
const [{ songQueue }, progress] = await Promise.all([ const user = await ctx.db.get(userId)
readPlaybackState(ctx, userId), if (!user) {
readPlaybackProgress(ctx, userId), throw new ConvexError("User not found")
]) }
return progress.songId === songQueue[0] ? progress.progressSeconds : 0
return user.currentSongProgress ?? 0
}, },
}) })
@@ -177,15 +819,15 @@ export const updateSongProgress = mutation({
}, },
handler: async (ctx, args) => { handler: async (ctx, args) => {
const userId = await requireAuth(ctx) const userId = await requireAuth(ctx)
const playback = await requirePlayback(ctx, userId) const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
if (playback.songQueue[0] !== args.songId) { if ((user.songQueue ?? [])[0] !== args.songId) {
return return
} }
await writeProgress(ctx, userId, { await ctx.db.patch(userId, { currentSongProgress: args.progressSeconds })
songId: args.songId,
progressSeconds: args.progressSeconds,
})
}, },
}) })
-236
View File
@@ -1,236 +0,0 @@
import { ConvexError } from "convex/values"
import type { Doc, Id } from "./_generated/dataModel"
import type { MutationCtx, QueryCtx } from "./_generated/server"
import { MAX_QUEUE_LENGTH } from "./limits"
const MAX_QUEUE_HISTORY = 30
export type RepeatMode = Doc<"playbackStates">["repeatEnabled"]
export type PlaybackState = Pick<
Doc<"playbackStates">,
"songQueue" | "queueHistory" | "shuffleEnabled" | "repeatEnabled" | "revision"
>
export type PlaybackProgress = {
songId: Id<"songs"> | null
progressSeconds: number
}
export type PlaybackPatch = Partial<
Pick<
PlaybackState,
"songQueue" | "queueHistory" | "shuffleEnabled" | "repeatEnabled"
>
> & {
/** Saved position of the new `songQueue[0]`. */
progressSeconds?: number
}
const LEGACY_PLAYBACK_FIELDS = [
"songQueue",
"queueHistory",
"currentSongProgress",
"playbackRevision",
"shuffleEnabled",
"repeatEnabled",
] as const
const EMPTY_STATE: PlaybackState = {
songQueue: [],
queueHistory: [],
shuffleEnabled: false,
repeatEnabled: "none",
revision: 0,
}
function legacyState(user: Doc<"users"> | null): PlaybackState {
if (!user) {
return EMPTY_STATE
}
return {
songQueue: (user.songQueue ?? []).slice(0, MAX_QUEUE_LENGTH),
queueHistory: (user.queueHistory ?? []).slice(-MAX_QUEUE_HISTORY),
shuffleEnabled: user.shuffleEnabled ?? false,
repeatEnabled: user.repeatEnabled ?? "none",
revision: user.playbackRevision ?? 0,
}
}
function legacyProgress(user: Doc<"users"> | null): PlaybackProgress {
return {
songId: user?.songQueue?.[0] ?? null,
progressSeconds: user?.currentSongProgress ?? 0,
}
}
export function hasLegacyPlayback(user: Doc<"users">) {
return LEGACY_PLAYBACK_FIELDS.some((field) => user[field] !== undefined)
}
function stateDoc(ctx: QueryCtx, userId: Id<"users">) {
return ctx.db
.query("playbackStates")
.withIndex("by_user", (q) => q.eq("userId", userId))
.unique()
}
function progressDoc(ctx: QueryCtx, userId: Id<"users">) {
return ctx.db
.query("playbackProgress")
.withIndex("by_user", (q) => q.eq("userId", userId))
.unique()
}
/**
* Reads the queue without touching progress, so progress saves do not rerun
* the caller. Users that have not been migrated yet fall back to `users`.
*/
export async function readPlaybackState(
ctx: QueryCtx,
userId: Id<"users">
): Promise<PlaybackState> {
const doc = await stateDoc(ctx, userId)
if (doc) {
return doc
}
return legacyState(await ctx.db.get(userId))
}
export async function readPlaybackProgress(
ctx: QueryCtx,
userId: Id<"users">
): Promise<PlaybackProgress> {
const doc = await progressDoc(ctx, userId)
if (doc) {
return { songId: doc.songId ?? null, progressSeconds: doc.progressSeconds }
}
return legacyProgress(await ctx.db.get(userId))
}
/**
* Moves a user's playback fields from `users` into `playbackStates` and
* `playbackProgress`. Safe to call repeatedly.
*/
export async function migrateUserPlayback(
ctx: MutationCtx,
user: Doc<"users">
) {
const [existingState, existingProgress] = await Promise.all([
stateDoc(ctx, user._id),
progressDoc(ctx, user._id),
])
let state = existingState
if (!state) {
const stateId = await ctx.db.insert("playbackStates", {
userId: user._id,
...legacyState(user),
})
state = (await ctx.db.get(stateId))!
}
if (!existingProgress) {
const progress = legacyProgress(user)
await ctx.db.insert("playbackProgress", {
userId: user._id,
progressSeconds: progress.progressSeconds,
...(progress.songId ? { songId: progress.songId } : {}),
})
}
if (hasLegacyPlayback(user)) {
await ctx.db.patch(user._id, {
songQueue: undefined,
queueHistory: undefined,
currentSongProgress: undefined,
playbackRevision: undefined,
shuffleEnabled: undefined,
repeatEnabled: undefined,
})
}
return state
}
/** Loads the queue in a mutation, migrating the user first if needed. */
export async function loadPlaybackForWrite(
ctx: MutationCtx,
userId: Id<"users">
) {
const doc = await stateDoc(ctx, userId)
if (doc) {
return doc
}
const user = await ctx.db.get(userId)
if (!user) {
return null
}
return await migrateUserPlayback(ctx, user)
}
/** Applies `patch`, bumps the revision, and returns the new revision. */
export async function writePlayback(
ctx: MutationCtx,
userId: Id<"users">,
patch: PlaybackPatch
): Promise<number> {
const doc = await loadPlaybackForWrite(ctx, userId)
if (!doc) {
throw new ConvexError("User not found")
}
const { progressSeconds, ...fields } = patch
const revision = doc.revision + 1
const songQueue = fields.songQueue?.slice(0, MAX_QUEUE_LENGTH)
const queueHistory = fields.queueHistory?.slice(-MAX_QUEUE_HISTORY)
await ctx.db.patch(doc._id, {
...fields,
...(songQueue ? { songQueue } : {}),
...(queueHistory ? { queueHistory } : {}),
revision,
})
if (progressSeconds !== undefined) {
await writeProgress(ctx, userId, {
songId: (songQueue ?? doc.songQueue)[0] ?? null,
progressSeconds,
})
}
return revision
}
export async function writeProgress(
ctx: MutationCtx,
userId: Id<"users">,
progress: PlaybackProgress
) {
const value = {
songId: progress.songId ?? undefined,
progressSeconds: Math.max(0, Math.floor(progress.progressSeconds)),
}
const doc = await progressDoc(ctx, userId)
if (!doc) {
await ctx.db.insert("playbackProgress", { userId, ...value })
} else if (
doc.songId !== value.songId ||
doc.progressSeconds !== value.progressSeconds
) {
await ctx.db.patch(doc._id, value)
}
}
export async function deleteUserPlayback(
ctx: MutationCtx,
userId: Id<"users">
) {
const [state, progress] = await Promise.all([
stateDoc(ctx, userId),
progressDoc(ctx, userId),
])
if (state) {
await ctx.db.delete(state._id)
}
if (progress) {
await ctx.db.delete(progress._id)
}
}
+33 -12
View File
@@ -1,3 +1,4 @@
import { paginationOptsValidator } from "convex/server"
import { getAuthUserId } from "@convex-dev/auth/server" import { getAuthUserId } from "@convex-dev/auth/server"
import { ConvexError, v } from "convex/values" import { ConvexError, v } from "convex/values"
import type { Doc, Id } from "./_generated/dataModel" import type { Doc, Id } from "./_generated/dataModel"
@@ -10,11 +11,7 @@ import type {
PlaylistSummary, PlaylistSummary,
SidebarPlaylists, SidebarPlaylists,
} from "./library" } from "./library"
import { import { browseSongsFromIds, compareAlbumSongs, paginateSlice } from "./library"
browseSongsFromIds,
compareAlbumSongs,
requireSignedIn,
} from "./library"
function toPlaylistSummary( function toPlaylistSummary(
playlist: Doc<"playlists">, playlist: Doc<"playlists">,
@@ -112,16 +109,23 @@ async function browsePlaylistSummaryHandler(
} }
} }
/** Public: shared /playlist links render this without a session. */ export const browsePlaylistSummary = query({
export const browsePlaylistDetail = query({
args: { id: v.id("playlists") }, 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()) },
handler: async (ctx, args): Promise<BrowsePlaylistDetail | null> => { handler: async (ctx, args): Promise<BrowsePlaylistDetail | null> => {
const summary = await browsePlaylistSummaryHandler(ctx, args.id) const summary = await browsePlaylistSummaryHandler(ctx, args.id)
if (!summary) { if (!summary) {
return null return null
} }
const songs = await browseSongsFromIds(ctx, summary.songIds) const songs =
(args.includeSongs ?? true)
? await browseSongsFromIds(ctx, summary.songIds)
: []
return { return {
id: summary.id, id: summary.id,
@@ -135,6 +139,27 @@ 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({ export const listOwnedPlaylists = query({
args: {}, args: {},
handler: async (ctx) => { handler: async (ctx) => {
@@ -272,7 +297,6 @@ export const listAllPlaylists = query({
export const getAlbumSongIds = query({ export const getAlbumSongIds = query({
args: { albumId: v.id("albums") }, args: { albumId: v.id("albums") },
handler: async (ctx, args) => { handler: async (ctx, args) => {
await requireSignedIn(ctx)
const songs = await ctx.db const songs = await ctx.db
.query("songs") .query("songs")
.withIndex("by_album", (q) => q.eq("album", args.albumId)) .withIndex("by_album", (q) => q.eq("album", args.albumId))
@@ -285,7 +309,6 @@ export const getAlbumSongIds = query({
export const getArtistSongIds = query({ export const getArtistSongIds = query({
args: { artistId: v.id("artists") }, args: { artistId: v.id("artists") },
handler: async (ctx, args) => { handler: async (ctx, args) => {
await requireSignedIn(ctx)
const songs = await ctx.db const songs = await ctx.db
.query("songs") .query("songs")
.withIndex("by_artist", (q) => q.eq("albumArtist", args.artistId)) .withIndex("by_artist", (q) => q.eq("albumArtist", args.artistId))
@@ -297,7 +320,6 @@ export const getArtistSongIds = query({
export const getOrderedArtistSongIds = query({ export const getOrderedArtistSongIds = query({
args: { artistId: v.id("artists") }, args: { artistId: v.id("artists") },
handler: async (ctx, args) => { handler: async (ctx, args) => {
await requireSignedIn(ctx)
const songs = await ctx.db const songs = await ctx.db
.query("songs") .query("songs")
.withIndex("by_artist", (q) => q.eq("albumArtist", args.artistId)) .withIndex("by_artist", (q) => q.eq("albumArtist", args.artistId))
@@ -328,7 +350,6 @@ export const getOrderedArtistSongIds = query({
export const getPlaylistSongIds = query({ export const getPlaylistSongIds = query({
args: { playlistId: v.id("playlists") }, args: { playlistId: v.id("playlists") },
handler: async (ctx, args) => { handler: async (ctx, args) => {
await requireSignedIn(ctx)
const playlist = await ctx.db.get("playlists", args.playlistId) const playlist = await ctx.db.get("playlists", args.playlistId)
return playlist?.songs ?? [] return playlist?.songs ?? []
}, },
+5 -29
View File
@@ -2,19 +2,11 @@ import { defineSchema, defineTable } from "convex/server"
import { v } from "convex/values" import { v } from "convex/values"
import { authTables } from "@convex-dev/auth/server" import { authTables } from "@convex-dev/auth/server"
const repeatModeValidator = v.union(
v.literal("always"),
v.literal("once"),
v.literal("none")
)
export default defineSchema({ export default defineSchema({
...authTables, ...authTables,
users: defineTable({ users: defineTable({
name: v.string(), name: v.string(),
/** Legacy base64 data URL; `migrations.migrateUsers` moves it to storage. */
image: v.optional(v.string()), image: v.optional(v.string()),
imageStorageId: v.optional(v.id("_storage")),
email: v.string(), email: v.string(),
isAdmin: v.optional(v.boolean()), isAdmin: v.optional(v.boolean()),
playbackQuality: v.optional( playbackQuality: v.optional(
@@ -30,34 +22,18 @@ export default defineSchema({
favoriteArtists: v.optional(v.array(v.id("artists"))), favoriteArtists: v.optional(v.array(v.id("artists"))),
favoriteAlbums: v.optional(v.array(v.id("albums"))), favoriteAlbums: v.optional(v.array(v.id("albums"))),
favoriteSongs: v.optional(v.array(v.id("songs"))), favoriteSongs: v.optional(v.array(v.id("songs"))),
songQueue: v.optional(v.array(v.id("songs"))),
queueHistory: v.optional(v.array(v.id("songs"))),
recentlyPlayed: v.optional( recentlyPlayed: v.optional(
v.array(v.union(v.id("playlists"), v.id("albums"))) v.array(v.union(v.id("playlists"), v.id("albums")))
), ),
// Legacy playback fields, now in `playbackStates` and `playbackProgress`.
// `migrations.migrateUsers` clears them; drop them once every deployment
// has run it.
songQueue: v.optional(v.array(v.id("songs"))),
queueHistory: v.optional(v.array(v.id("songs"))),
currentSongProgress: v.optional(v.number()), currentSongProgress: v.optional(v.number()),
playbackRevision: v.optional(v.number()), playbackRevision: v.optional(v.number()),
shuffleEnabled: v.optional(v.boolean()), shuffleEnabled: v.optional(v.boolean()),
repeatEnabled: v.optional(repeatModeValidator), repeatEnabled: v.optional(
v.union(v.literal("always"), v.literal("once"), v.literal("none"))
),
}).index("email", ["email"]), }).index("email", ["email"]),
playbackStates: defineTable({
userId: v.id("users"),
songQueue: v.array(v.id("songs")),
queueHistory: v.array(v.id("songs")),
shuffleEnabled: v.boolean(),
repeatEnabled: repeatModeValidator,
revision: v.number(),
}).index("by_user", ["userId"]),
// Saved every few seconds during playback, so it lives apart from the queue
// to keep those writes from rerunning queue queries.
playbackProgress: defineTable({
userId: v.id("users"),
songId: v.optional(v.id("songs")),
progressSeconds: v.number(),
}).index("by_user", ["userId"]),
authVerifiers: defineTable({ authVerifiers: defineTable({
sessionId: v.optional(v.id("authSessions")), sessionId: v.optional(v.id("authSessions")),
signature: v.optional(v.string()), signature: v.optional(v.string()),
+4
View File
@@ -41,6 +41,10 @@ export type BrowseAlbumDetail = BrowseAlbum & {
tracks: BrowseAlbumTrack[] tracks: BrowseAlbumTrack[]
} }
export type BrowseAlbumSummary = Omit<BrowseAlbumDetail, "tracks"> & {
trackCount: number
}
export type BrowseArtistDetail = { export type BrowseArtistDetail = {
artist: BrowseArtist artist: BrowseArtist
albums: BrowseAlbum[] albums: BrowseAlbum[]
+4 -111
View File
@@ -5,18 +5,9 @@ import {
} from "@convex-dev/auth/server" } from "@convex-dev/auth/server"
import { ConvexError, v } from "convex/values" import { ConvexError, v } from "convex/values"
import { api, internal } from "./_generated/api" import { api, internal } from "./_generated/api"
import { import { action, internalQuery, mutation, query } from "./_generated/server"
action, import type { Id } from "./_generated/dataModel"
internalAction,
internalMutation,
internalQuery,
mutation,
query,
} from "./_generated/server"
import type { Doc, Id } from "./_generated/dataModel"
import type { ActionCtx, MutationCtx } from "./_generated/server" import type { ActionCtx, MutationCtx } from "./_generated/server"
import { MAX_PROFILE_IMAGE_BYTES } from "./limits"
import { deleteUserPlayback } from "./playbackState"
const playbackQualityValidator = v.union( const playbackQualityValidator = v.union(
v.literal("low"), v.literal("low"),
@@ -187,114 +178,18 @@ export const listUsers = query({
}, },
}) })
const DATA_URL_PATTERN = /^data:(image\/[\w.+-]+);base64,([A-Za-z0-9+/=]+)$/
/** Splits an image data URL, rejecting anything over the size cap. */
function parseImageDataUrl(image: string) {
const match = DATA_URL_PATTERN.exec(image)
if (!match) {
throw new ConvexError("Profile photo must be an image")
}
const [, contentType, base64] = match
if (Math.floor((base64.length * 3) / 4) > MAX_PROFILE_IMAGE_BYTES) {
throw new ConvexError(
`Profile photo must be ${MAX_PROFILE_IMAGE_BYTES / 1024 / 1024} MB or smaller`
)
}
return { contentType, base64 }
}
/**
* Path clients load the avatar from. The web server proxies it from Convex
* storage, since the backend's storage URLs are not reachable from browsers
* in every deployment. Legacy data URLs are returned as is until migrated.
*/
export function profileImagePath(user: Doc<"users">) {
if (user.imageStorageId) {
return `/api/user/${user._id}/avatar?v=${user.imageStorageId}`
}
return user.image
}
/**
* Takes a data URL so existing clients keep working. The image is moved into
* file storage in the background; `currentUser` updates once it lands.
*/
export const updateProfileImage = mutation({ export const updateProfileImage = mutation({
args: { args: {
image: v.union(v.string(), v.null()), image: v.union(v.string(), v.null()),
}, },
handler: async (ctx, { image }) => { handler: async (ctx, { image }) => {
const userId = await requireAuth(ctx) const userId = await requireAuth(ctx)
if (image === null) { await ctx.db.patch(userId, {
await setProfileImage(ctx, userId, null) image: image === null ? undefined : image,
return
}
parseImageDataUrl(image)
await ctx.scheduler.runAfter(0, internal.users.storeProfileImage, {
userId,
image,
}) })
}, },
}) })
/** Decodes a data URL into file storage and points the user at it. */
export const storeProfileImage = internalAction({
args: { userId: v.id("users"), image: v.string() },
handler: async (ctx, { userId, image }) => {
const { contentType, base64 } = parseImageDataUrl(image)
const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0))
const storageId = await ctx.storage.store(
new Blob([bytes], { type: contentType })
)
await ctx.runMutation(internal.users.attachProfileImage, {
userId,
storageId,
})
},
})
export const attachProfileImage = internalMutation({
args: { userId: v.id("users"), storageId: v.id("_storage") },
handler: async (ctx, { userId, storageId }) => {
await setProfileImage(ctx, userId, storageId)
},
})
/** Replaces the avatar, deleting the previous file. Clears it for `null`. */
async function setProfileImage(
ctx: MutationCtx,
userId: Id<"users">,
storageId: Id<"_storage"> | null
) {
const user = await ctx.db.get(userId)
if (!user) {
if (storageId) {
await ctx.storage.delete(storageId)
}
return
}
if (user.imageStorageId && user.imageStorageId !== storageId) {
await ctx.storage.delete(user.imageStorageId)
}
await ctx.db.patch(userId, {
image: undefined,
imageStorageId: storageId ?? undefined,
})
}
/** Storage URL behind `profileImagePath`, for the web server's proxy route. */
export const getProfileImageUrl = query({
args: { userId: v.id("users") },
handler: async (ctx, { userId }) => {
const user = await ctx.db.get(userId)
if (!user?.imageStorageId) {
return null
}
return await ctx.storage.getUrl(user.imageStorageId)
},
})
export const updateProfileName = mutation({ export const updateProfileName = mutation({
args: { name: v.string() }, args: { name: v.string() },
handler: async (ctx, { name }) => { handler: async (ctx, { name }) => {
@@ -399,8 +294,6 @@ export const deleteUser = mutation({
throw new ConvexError("You cannot delete your own account") throw new ConvexError("You cannot delete your own account")
} }
await deleteOwnedPlaylists(ctx, userId) await deleteOwnedPlaylists(ctx, userId)
await deleteUserPlayback(ctx, userId)
await setProfileImage(ctx, userId, null)
await deleteUserAuthData(ctx, userId) await deleteUserAuthData(ctx, userId)
}, },
}) })
-20
View File
@@ -179,9 +179,6 @@ importers:
'@otunes/convex': '@otunes/convex':
specifier: workspace:* specifier: workspace:*
version: link:../../packages/convex version: link:../../packages/convex
'@tanstack/react-virtual':
specifier: ^3.14.26
version: 3.14.26(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
class-variance-authority: class-variance-authority:
specifier: ^0.7.1 specifier: ^0.7.1
version: 0.7.1 version: 0.7.1
@@ -2660,15 +2657,6 @@ packages:
'@tailwindcss/postcss@4.3.2': '@tailwindcss/postcss@4.3.2':
resolution: {integrity: sha512-rjVWYCa7Ngbi5AarT6k8TkxUG3Wl1QKzHdIZVsjZSzf36Jmo2IKZt/NHRAwly8oDkbBOH0YTu+CHuf9jPxMc+g==} resolution: {integrity: sha512-rjVWYCa7Ngbi5AarT6k8TkxUG3Wl1QKzHdIZVsjZSzf36Jmo2IKZt/NHRAwly8oDkbBOH0YTu+CHuf9jPxMc+g==}
'@tanstack/react-virtual@3.14.26':
resolution: {integrity: sha512-HUDlfsrYH6ko5xH56L62Mcl/uzT+AGVNMHFuDNqDJMdZWc1AQa2oeVKNUvZ/RWBZQ4TYtyQerFrNvLnp39h65A==}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
'@tanstack/virtual-core@3.19.11':
resolution: {integrity: sha512-/5iHb0RHBvj8Di59FDs4ESNm45jls33aZAi4zccVXZjc/6ZvwQP6nzEYeT6weXjTf9E6/vrp2JhYWRyO+ZP13A==}
'@tokenizer/inflate@0.4.1': '@tokenizer/inflate@0.4.1':
resolution: {integrity: sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==} resolution: {integrity: sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==}
engines: {node: '>=18'} engines: {node: '>=18'}
@@ -9476,14 +9464,6 @@ snapshots:
postcss: 8.5.16 postcss: 8.5.16
tailwindcss: 4.3.2 tailwindcss: 4.3.2
'@tanstack/react-virtual@3.14.26(react-dom@19.3.1(react@19.3.1))(react@19.3.1)':
dependencies:
'@tanstack/virtual-core': 3.19.11
react: 19.3.1
react-dom: 19.3.1(react@19.3.1)
'@tanstack/virtual-core@3.19.11': {}
'@tokenizer/inflate@0.4.1': '@tokenizer/inflate@0.4.1':
dependencies: dependencies:
debug: 4.4.3 debug: 4.4.3