Merge remote-tracking branch 'origin/main' into pr108
# Conflicts: # apps/mobile/app/(app)/(tabs)/home/album/[id].tsx # apps/mobile/app/(app)/(tabs)/home/settings.tsx # apps/mobile/hooks/use-cover-palette.ts # apps/mobile/hooks/use-legacy-cover-palette.ts
This commit is contained in:
125 files changed
+7509
-6854
No files matched your search
+5
-6
@@ -54,12 +54,11 @@ playwright.config.*
|
||||
*~
|
||||
*.log
|
||||
|
||||
# Environment variables (only commit template files)
|
||||
.env
|
||||
.env*.local
|
||||
.env.development
|
||||
.env.test
|
||||
.env.production.local
|
||||
# Environment variables, in any workspace. Next.js inlines NEXT_PUBLIC_* values
|
||||
# into the bundle and the Convex CLI reads .env.local on deploy.
|
||||
**/.env
|
||||
**/.env.*
|
||||
!**/.env.example
|
||||
|
||||
# Docker configuration files (not needed inside build context)
|
||||
Dockerfile*
|
||||
|
||||
+6
-1
@@ -195,7 +195,12 @@ RUN node --version \
|
||||
&& ldd /convex/generate_key \
|
||||
&& ! ldd /convex/convex-local-backend /convex/generate_key | grep -q 'not found'
|
||||
|
||||
RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes
|
||||
# The backend gets its own user so the web server cannot read the database or
|
||||
# instance secret. It joins the otunes group to clean up the web server's HLS
|
||||
# cache in /tmp/otunes.
|
||||
RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes \
|
||||
&& useradd --system --user-group --groups otunes --create-home --home-dir /home/convex \
|
||||
--shell /usr/sbin/nologin convex
|
||||
|
||||
COPY --from=convex-functions /app /opt/otunes/convex
|
||||
COPY docker/generate-auth-keys.mjs /opt/otunes/generate-auth-keys.mjs
|
||||
|
||||
@@ -4,7 +4,9 @@ This integration uses Expo 58 inline modules and `expo-app-intents`. Rebuild the
|
||||
|
||||
Playback and library changes open oTunes because they need its authenticated React runtime. Swift dispatches a request and waits for an app-owned completion acknowledgment. Playback waits for the native audio player to load the requested track; warmup waits for it to load while paused. Errors reach Siri, and requests that have expired are discarded before starting a side effect. Native catalog reads do not open the app.
|
||||
|
||||
The full entity catalog lives in Application Support. The backend supplies pages of 200 records. Expo's UserDefaults catalog holds at most 100 suggestions per kind, with favorites first, and mirrors those suggestions into Spotlight. Siri's native queries search the full disk catalog. Catalogs refresh on launch, foreground entry, favorite changes, and every five minutes while foregrounded.
|
||||
The full entity catalog lives in Application Support. Expo's UserDefaults catalog holds at most 100 suggestions per kind, with favorites first, and mirrors those suggestions into Spotlight. Siri's native queries search the full disk catalog.
|
||||
|
||||
Sync is incremental. The app subscribes to `intentCatalog.head`, the newest insert, rename or deletion per kind, and fetches a kind only when it moves past the cursor stored in AsyncStorage. `intentCatalog.page` then returns records created after the cursor plus renames and deletions from the `intentCatalogChanges` log. The log keeps 30 days; older cursors, or more than 2,000 changes, rebuild that kind from scratch. Favorites are stamped onto records on device from the favorites subscription, so liking a song costs no catalog queries. Playlists come from the live `intentCatalog.playlists` query. Code lives in `components/app-intents/`: `catalog-sync.ts`, `now-playing.ts`, and `dispatch.ts`.
|
||||
|
||||
Songs, albums, artists, and playlists have Spotlight open intents and on-screen entity associations. Associations require iOS 18.4 and Xcode 27; Spotlight indexing requires iOS 18. Playback donations are made after the player starts, preserve shuffle, and resolve real catalog entities. Removed records trigger donation cleanup. Sign-out clears catalogs, Spotlight entries, donations, and pending invocations. On iOS 27, the query types also handle system requests to rebuild Spotlight indexes.
|
||||
|
||||
@@ -14,7 +16,7 @@ Audio schema intents require Xcode 27 and iOS 27. Custom intents remain availabl
|
||||
|
||||
Deploy the companion Convex changes before installing the new mobile build:
|
||||
|
||||
- `library.intentCatalogPage` supplies authenticated, paginated entity records.
|
||||
- `intentCatalog.head`, `intentCatalog.page` and `intentCatalog.playlists` supply the entity catalog. Library mutations record renames and deletions in `intentCatalogChanges`, pruned daily.
|
||||
- `appIntentPlaylists` records playlist-creation request IDs in the same transaction as creation. Replaying a request returns the original playlist ID.
|
||||
- `playlists.createPlaylist` accepts an optional `invocationId`; existing callers can omit it.
|
||||
|
||||
|
||||
-1
@@ -1 +0,0 @@
|
||||
export { default } from "../library/queue"
|
||||
@@ -28,7 +28,7 @@ import {
|
||||
MediaActionMenu,
|
||||
MediaContextMenu,
|
||||
type MediaAction,
|
||||
} from "@/components/media-actions-sheet"
|
||||
} from "@/components/media-context-menu"
|
||||
import { CollectionDetailSkeleton } from "@/components/skeletons"
|
||||
import { Button } from "@/components/ui/primitives"
|
||||
import { contentBottomInset } from "@/components/player"
|
||||
@@ -82,20 +82,6 @@ export default function AlbumScreen() {
|
||||
[album]
|
||||
)
|
||||
|
||||
// Older servers do not include album format availability yet.
|
||||
const formatTracks = useCachedQuery(
|
||||
api.library.getSongsForPlayback,
|
||||
album && (album.hasLossless === undefined || album.hasAtmos === undefined)
|
||||
? { ids: songIds }
|
||||
: "skip"
|
||||
)
|
||||
const hasLossless =
|
||||
album?.hasLossless ??
|
||||
formatTracks?.some((track) => track && "lossless" in track.files)
|
||||
const hasAtmos =
|
||||
album?.hasAtmos ??
|
||||
formatTracks?.some((track) => track && "atmos" in track.files)
|
||||
|
||||
useEffect(() => {
|
||||
if (album) {
|
||||
rememberSongs(albumDetailSongs(album))
|
||||
@@ -104,6 +90,12 @@ export default function AlbumScreen() {
|
||||
|
||||
const listItems = useMemo(() => albumListItems(album?.tracks ?? []), [album])
|
||||
|
||||
const playTrack = useCallback(
|
||||
(songId: Id<"songs">, ids: Id<"songs">[]) =>
|
||||
playFromSong(songId, ids, `album:${id}`),
|
||||
[id, playFromSong]
|
||||
)
|
||||
|
||||
const renderItem = useCallback(
|
||||
({ item }: { item: AlbumListItem }) => {
|
||||
if (item.type === "disc") {
|
||||
@@ -118,9 +110,7 @@ export default function AlbumScreen() {
|
||||
songIds={songIds}
|
||||
palette={palette}
|
||||
favorited={isSongFavorite(item.track.id)}
|
||||
onPlay={(songId, ids) =>
|
||||
playFromSong(songId, ids, `album:${album.id}`)
|
||||
}
|
||||
onPlay={playTrack}
|
||||
onAction={handleAlbumTrackAction}
|
||||
/>
|
||||
) : null
|
||||
@@ -130,7 +120,7 @@ export default function AlbumScreen() {
|
||||
handleAlbumTrackAction,
|
||||
isSongFavorite,
|
||||
palette,
|
||||
playFromSong,
|
||||
playTrack,
|
||||
songIds,
|
||||
swipeGroup,
|
||||
]
|
||||
@@ -353,7 +343,7 @@ export default function AlbumScreen() {
|
||||
{metadata}
|
||||
</Text>
|
||||
) : null}
|
||||
{hasLossless ? (
|
||||
{album.hasLossless ? (
|
||||
<>
|
||||
{metadata ? (
|
||||
<Text style={{ color: palette.secondaryForeground }}>
|
||||
@@ -367,9 +357,9 @@ export default function AlbumScreen() {
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
{hasAtmos ? (
|
||||
{album.hasAtmos ? (
|
||||
<>
|
||||
{metadata || hasLossless ? (
|
||||
{metadata || album.hasLossless ? (
|
||||
<Text style={{ color: palette.secondaryForeground }}>
|
||||
·
|
||||
</Text>
|
||||
@@ -459,7 +449,7 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
|
||||
action: MediaAction
|
||||
) => Promise<void>
|
||||
}) {
|
||||
const Row = Platform.OS === "ios" ? SongSwipeRow : Pressable
|
||||
const Row = Platform.OS !== "web" ? SongSwipeRow : Pressable
|
||||
const { config } = useServerConfig()
|
||||
return (
|
||||
<MediaContextMenu
|
||||
@@ -494,6 +484,7 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
|
||||
group={swipeGroup}
|
||||
backgroundColor={palette.background}
|
||||
onPlayNext={() => void onAction(track, album, "play-next")}
|
||||
onAddToQueue={() => void onAction(track, album, "play-last")}
|
||||
style={styles.trackRow}
|
||||
onPress={() => void onPlay(track.id as Id<"songs">, songIds)}
|
||||
>
|
||||
|
||||
@@ -6,7 +6,7 @@ import { Ionicons } from "@expo/vector-icons"
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
|
||||
import { MediaGridList } from "@/components/media-cards"
|
||||
import { MediaActionMenu } from "@/components/media-actions-sheet"
|
||||
import { MediaActionMenu } from "@/components/media-context-menu"
|
||||
import { CollectionDetailSkeleton } from "@/components/skeletons"
|
||||
import { Button } from "@/components/ui/primitives"
|
||||
import { contentBottomInset } from "@/components/player"
|
||||
|
||||
@@ -40,7 +40,7 @@ import {
|
||||
import {
|
||||
MediaActionMenu,
|
||||
type MediaAction,
|
||||
} from "@/components/media-actions-sheet"
|
||||
} from "@/components/media-context-menu"
|
||||
import { CollectionDetailSkeleton } from "@/components/skeletons"
|
||||
import { Button } from "@/components/ui/primitives"
|
||||
import { contentBottomInset, SongListRow } from "@/components/player"
|
||||
@@ -193,12 +193,6 @@ function PlaylistContent({
|
||||
[playFromSong, songIds, playlistId]
|
||||
)
|
||||
|
||||
const handleSongMenuAction = useCallback(
|
||||
(song: BrowseSong, action: MediaAction) =>
|
||||
void handleSongAction(song, action),
|
||||
[handleSongAction]
|
||||
)
|
||||
|
||||
const handleRemoveSong = useCallback(
|
||||
async (songId: Id<"songs">) => {
|
||||
if (!playlistId) return false
|
||||
@@ -217,6 +211,14 @@ function PlaylistContent({
|
||||
[playlistId, removeSongs]
|
||||
)
|
||||
|
||||
const handleSongMenuAction = useCallback(
|
||||
(song: BrowseSong, action: MediaAction) => {
|
||||
if (action === "remove-from-playlist") void handleRemoveSong(song.id)
|
||||
else void handleSongAction(song, action)
|
||||
},
|
||||
[handleRemoveSong, handleSongAction]
|
||||
)
|
||||
|
||||
const handlePlay = useCallback(() => {
|
||||
if (playlistId) void playPlaylist(playlistId, songIds)
|
||||
}, [playPlaylist, playlistId, songIds])
|
||||
@@ -301,7 +303,6 @@ function PlaylistContent({
|
||||
deletePlaylist,
|
||||
handlePlaylistDetailAction,
|
||||
palette.foreground,
|
||||
palette.background,
|
||||
palette.isDark,
|
||||
playlistId,
|
||||
playlist?.title,
|
||||
@@ -419,12 +420,15 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
|
||||
playlistLabel={PLAYLIST_LABEL}
|
||||
palette={palette}
|
||||
inset
|
||||
removable={removable}
|
||||
swipe={
|
||||
Platform.OS === "ios"
|
||||
Platform.OS !== "web"
|
||||
? {
|
||||
group: swipeGroup,
|
||||
backgroundColor: palette.background,
|
||||
onPlayNext: () => onAction(song, "play-next"),
|
||||
onAddToQueue: () => onAction(song, "play-last"),
|
||||
onRemove: removable ? () => void handleRemove() : undefined,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
@@ -433,7 +437,7 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
|
||||
/>
|
||||
)
|
||||
|
||||
if (Platform.OS === "ios" || !removable) {
|
||||
if (Platform.OS !== "web" || !removable) {
|
||||
return row
|
||||
}
|
||||
|
||||
|
||||
@@ -1,186 +0,0 @@
|
||||
import { Stack, useRouter } from "expo-router"
|
||||
import { memo, useCallback, useMemo } from "react"
|
||||
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
|
||||
|
||||
import { Button } from "@/components/ui/primitives"
|
||||
import { contentBottomInset, SongRow } from "@/components/player"
|
||||
import { SongRowSkeleton } from "@/components/skeletons"
|
||||
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { longListProps } from "@/lib/list"
|
||||
import { useSong, useSongs } from "@/lib/song-cache"
|
||||
import { spacing, useThemeColors } from "@/lib/theme"
|
||||
|
||||
/** `key` stays stable when earlier songs leave the queue, so rows are not remounted on skip. */
|
||||
type QueueItem = { songId: Id<"songs">; queueIndex: number; key: string }
|
||||
|
||||
function queueItemKey(item: QueueItem) {
|
||||
return item.key
|
||||
}
|
||||
|
||||
const QueueRow = memo(function QueueRow({
|
||||
songId,
|
||||
queueIndex,
|
||||
isLast,
|
||||
isCurrent,
|
||||
onSkipTo,
|
||||
onMove,
|
||||
}: Omit<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 },
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { dolbyAtmosSupported } from "@/lib/playback-capabilities"
|
||||
import { atmosEnabled, dolbyAtmosSupported } from "@/lib/playback-capabilities"
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
import { useAction, useMutation, useQuery } from "convex/react"
|
||||
import { Image } from "expo-image"
|
||||
@@ -23,15 +23,15 @@ import { useServerConfig } from "@/contexts/server-config"
|
||||
import {
|
||||
setArtworkColorsEnabled,
|
||||
useArtworkColorsEnabled,
|
||||
useArtworkColorPreferenceLoaded,
|
||||
} from "@/lib/artwork-color-preference"
|
||||
import { initialsFromName } from "@/lib/format"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { clearCoverPaletteCache } from "@/hooks/use-cover-palette"
|
||||
import { useProfileImageUrl } from "@/hooks/use-profile-image-url"
|
||||
import { changeServer, signOut } from "@/lib/session"
|
||||
import { radius, spacing, useThemeColors } from "@/lib/theme"
|
||||
import { showError } from "@/lib/toast"
|
||||
import type { PlaybackQuality } from "@/lib/urls"
|
||||
import type { PlaybackQuality } from "@otunes/convex/playback-stream"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
|
||||
@@ -173,7 +173,6 @@ export default function SettingsScreen() {
|
||||
|
||||
function AppearanceSection() {
|
||||
const enabled = useArtworkColorsEnabled()
|
||||
const loaded = useArtworkColorPreferenceLoaded()
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
return (
|
||||
@@ -181,8 +180,8 @@ function AppearanceSection() {
|
||||
<SwitchRow
|
||||
title="New artwork colors"
|
||||
subtitle="Use the new color algorithm on this device."
|
||||
value={enabled}
|
||||
disabled={!loaded || saving}
|
||||
value={enabled ?? false}
|
||||
disabled={enabled === undefined || saving}
|
||||
onValueChange={async (checked) => {
|
||||
setSaving(true)
|
||||
try {
|
||||
@@ -421,7 +420,7 @@ function QualitySection({ user }: { user: CurrentUser }) {
|
||||
: "This device does not support Dolby Atmos playback."
|
||||
}
|
||||
disabled={!dolbyAtmosSupported}
|
||||
value={dolbyAtmosSupported && (user.preferAtmos ?? false)}
|
||||
value={atmosEnabled(user)}
|
||||
onValueChange={(checked) =>
|
||||
void updateAtmos({ preferAtmos: checked }).catch((error: Error) =>
|
||||
showError(error.message)
|
||||
@@ -772,6 +771,7 @@ function ProfileAvatar({
|
||||
style?: StyleProp<ViewStyle>
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
const imageUrl = useProfileImageUrl(user.image)
|
||||
const avatarStyle = [
|
||||
styles.avatar,
|
||||
{
|
||||
@@ -783,11 +783,11 @@ function ProfileAvatar({
|
||||
style,
|
||||
]
|
||||
|
||||
if (user.image) {
|
||||
if (imageUrl) {
|
||||
return (
|
||||
<View style={avatarStyle}>
|
||||
<Image
|
||||
source={{ uri: user.image }}
|
||||
source={{ uri: imageUrl }}
|
||||
style={styles.avatarImage}
|
||||
contentFit="cover"
|
||||
/>
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
export { default } from "../home/queue"
|
||||
@@ -1 +0,0 @@
|
||||
export { default } from "../home/queue"
|
||||
@@ -73,10 +73,10 @@ export default function AppLayout() {
|
||||
return (
|
||||
<ConvexAuthRecovery onInvalidate={invalidateSession}>
|
||||
<PlaybackProvider>
|
||||
<AppIntentBridge />
|
||||
<AppNavigationSync />
|
||||
<AddToPlaylistProvider>
|
||||
<FavoritesProvider>
|
||||
<AppIntentBridge />
|
||||
<Stack screenOptions={stackOptions}>
|
||||
<Stack.Screen
|
||||
name="(tabs)"
|
||||
|
||||
+120
-143
@@ -1,12 +1,12 @@
|
||||
import { useTabletLayout } from "@/hooks/use-tablet-layout"
|
||||
import { TabletNowPlaying } from "@/components/tablet-now-playing"
|
||||
import { dolbyAtmosSupported } from "@/lib/playback-capabilities"
|
||||
import { atmosEnabled } from "@/lib/playback-capabilities"
|
||||
import { NavigationBar } from "expo-navigation-bar"
|
||||
import { MusicEntityView } from "@/components/music-entity-view"
|
||||
import { Stack, useRouter, useLocalSearchParams } from "expo-router"
|
||||
import * as Haptics from "expo-haptics"
|
||||
import { StatusBar } from "expo-status-bar"
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler"
|
||||
import {
|
||||
Platform,
|
||||
@@ -39,22 +39,22 @@ import { MarqueeText } from "@/components/marquee-text"
|
||||
import {
|
||||
MediaActionMenu,
|
||||
type MediaAction,
|
||||
} from "@/components/media-actions-sheet"
|
||||
} from "@/components/media-context-menu"
|
||||
import {
|
||||
NowPlayingQueue,
|
||||
QUEUE_HORIZONTAL_INSET,
|
||||
} from "@/components/now-playing-queue"
|
||||
import { PlayerArtistMenu } from "@/components/player-artist-menu"
|
||||
import { PlayerProgress } from "@/components/player-progress"
|
||||
import { PlayerSlider } from "@/components/player-slider"
|
||||
import { PlayerSymbol } from "@/components/player-symbol"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlayback } from "@/contexts/playback"
|
||||
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useCoverPalette } from "@/hooks/use-cover-palette"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { useSystemVolume } from "@/hooks/use-system-volume"
|
||||
import { formatDuration, formatRemainingDuration } from "@/lib/format"
|
||||
import {
|
||||
nowPlayingColors,
|
||||
type NowPlayingColors,
|
||||
@@ -90,20 +90,13 @@ export default function PlayerScreen() {
|
||||
isPlaying,
|
||||
shuffleEnabled,
|
||||
repeatEnabled,
|
||||
currentTime,
|
||||
duration,
|
||||
queueSongIds,
|
||||
setIsPlaying,
|
||||
seekTo,
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
} = usePlayback()
|
||||
const { volume, setVolume, available: volumeAvailable } = useSystemVolume()
|
||||
} = usePlaybackQueue()
|
||||
const { setIsPlaying, skipNext, skipPrevious } = usePlaybackActions()
|
||||
const { queue } = useLocalSearchParams<{ queue?: string }>()
|
||||
const [showQueue, setShowQueue] = useState(queue === "1")
|
||||
const [isDismissing, setIsDismissing] = useState(false)
|
||||
const [stageHeight, setStageHeight] = useState(0)
|
||||
const [scrubTime, setScrubTime] = useState<number | null>(null)
|
||||
const user = useCachedQuery(api.auth.currentUser)
|
||||
const playbackInfo = useCachedQuery(
|
||||
api.library.getSongPlaybackInfo,
|
||||
@@ -114,7 +107,7 @@ export default function PlayerScreen() {
|
||||
? playbackFormat(
|
||||
playbackInfo.files,
|
||||
user.playbackQuality,
|
||||
dolbyAtmosSupported && (user.preferAtmos ?? false)
|
||||
atmosEnabled(user)
|
||||
)
|
||||
: null
|
||||
|
||||
@@ -126,7 +119,7 @@ export default function PlayerScreen() {
|
||||
coverUri,
|
||||
currentSong ? currentSong.album.cover != null : undefined
|
||||
)
|
||||
const colors = nowPlayingColors(palette)
|
||||
const colors = useMemo(() => nowPlayingColors(palette), [palette])
|
||||
|
||||
const background = useSharedValue(colors.background)
|
||||
useEffect(() => {
|
||||
@@ -159,33 +152,65 @@ export default function PlayerScreen() {
|
||||
}))
|
||||
|
||||
// The player covers the status bar, so it can't use the native sheet's
|
||||
// swipe to dismiss.
|
||||
function dismissGesture() {
|
||||
return Gesture.Pan()
|
||||
.activeOffsetY(12)
|
||||
.failOffsetY(-12)
|
||||
.failOffsetX([-20, 20])
|
||||
.onUpdate((event) => {
|
||||
dismissY.value = Math.max(0, event.translationY)
|
||||
})
|
||||
.onEnd((event) => {
|
||||
if (
|
||||
event.translationY > DISMISS_DISTANCE ||
|
||||
event.velocityY > DISMISS_VELOCITY
|
||||
) {
|
||||
scheduleOnRN(setIsDismissing, true)
|
||||
dismissY.value = withTiming(
|
||||
windowHeight,
|
||||
{ duration: 220 },
|
||||
(finished) => {
|
||||
if (finished) scheduleOnRN(router.back)
|
||||
}
|
||||
)
|
||||
} else {
|
||||
dismissY.value = withSpring(0, { duration: 350, dampingRatio: 0.85 })
|
||||
}
|
||||
})
|
||||
}
|
||||
// swipe to dismiss. Each GestureDetector needs its own gesture instance.
|
||||
const makeDismissGesture = useCallback(
|
||||
() =>
|
||||
Gesture.Pan()
|
||||
.activeOffsetY(12)
|
||||
.failOffsetY(-12)
|
||||
.failOffsetX([-20, 20])
|
||||
.onUpdate((event) => {
|
||||
dismissY.value = Math.max(0, event.translationY)
|
||||
})
|
||||
.onEnd((event) => {
|
||||
if (
|
||||
event.translationY > DISMISS_DISTANCE ||
|
||||
event.velocityY > DISMISS_VELOCITY
|
||||
) {
|
||||
scheduleOnRN(setIsDismissing, true)
|
||||
dismissY.value = withTiming(
|
||||
windowHeight,
|
||||
{ duration: 220 },
|
||||
(finished) => {
|
||||
if (finished) scheduleOnRN(router.back)
|
||||
}
|
||||
)
|
||||
} else {
|
||||
dismissY.value = withSpring(0, {
|
||||
duration: 350,
|
||||
dampingRatio: 0.85,
|
||||
})
|
||||
}
|
||||
}),
|
||||
[dismissY, router, windowHeight]
|
||||
)
|
||||
const handleGesture = useMemo(makeDismissGesture, [makeDismissGesture])
|
||||
const controlsGesture = useMemo(makeDismissGesture, [makeDismissGesture])
|
||||
const stageGesture = useMemo(
|
||||
() => makeDismissGesture().enabled(!showQueue),
|
||||
[makeDismissGesture, showQueue]
|
||||
)
|
||||
|
||||
const hasCover = currentSong ? currentSong.album.cover != null : false
|
||||
const queueHeader = useMemo(
|
||||
() =>
|
||||
currentSong ? (
|
||||
<View style={styles.queueHeader}>
|
||||
<CoverImage
|
||||
uri={coverUri}
|
||||
hasCover={hasCover}
|
||||
style={styles.queueArtwork}
|
||||
/>
|
||||
<SongMeta song={currentSong} colors={colors} compact />
|
||||
</View>
|
||||
) : null,
|
||||
[colors, coverUri, currentSong, hasCover]
|
||||
)
|
||||
const songMeta = useMemo(
|
||||
() =>
|
||||
currentSong ? <SongMeta song={currentSong} colors={colors} /> : null,
|
||||
[colors, currentSong]
|
||||
)
|
||||
|
||||
const hasQueue = queueSongIds.length > 0
|
||||
|
||||
@@ -204,7 +229,6 @@ export default function PlayerScreen() {
|
||||
return null
|
||||
}
|
||||
|
||||
const hasCover = currentSong.album.cover != null
|
||||
const bottomInset = Math.max(insets.bottom, spacing.md)
|
||||
const artworkSize = Math.max(
|
||||
0,
|
||||
@@ -213,9 +237,6 @@ export default function PlayerScreen() {
|
||||
stageHeight > 0 ? stageHeight - META_HEIGHT - spacing.xl : Infinity
|
||||
)
|
||||
)
|
||||
const displayedTime = scrubTime ?? currentTime
|
||||
const timeColor =
|
||||
scrubTime === null ? colors.secondaryForeground : colors.foreground
|
||||
|
||||
function togglePlayback() {
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light)
|
||||
@@ -234,10 +255,10 @@ export default function PlayerScreen() {
|
||||
colors={colors}
|
||||
backgroundStyle={backgroundStyle}
|
||||
dismissStyle={dismissStyle}
|
||||
dismissGesture={dismissGesture}
|
||||
dismissGestures={{ handle: handleGesture, artwork: controlsGesture }}
|
||||
showQueue={showQueue}
|
||||
toggleQueue={toggleQueue}
|
||||
metadata={<SongMeta song={currentSong} colors={colors} />}
|
||||
metadata={songMeta}
|
||||
/>
|
||||
</MusicEntityView>
|
||||
)
|
||||
@@ -264,7 +285,7 @@ export default function PlayerScreen() {
|
||||
id={currentSong.id}
|
||||
style={[styles.safe, { paddingTop: insets.top }]}
|
||||
>
|
||||
<GestureDetector gesture={dismissGesture()}>
|
||||
<GestureDetector gesture={handleGesture}>
|
||||
<Pressable
|
||||
onPress={() => router.back()}
|
||||
hitSlop={12}
|
||||
@@ -278,7 +299,7 @@ export default function PlayerScreen() {
|
||||
</Pressable>
|
||||
</GestureDetector>
|
||||
|
||||
<GestureDetector gesture={dismissGesture().enabled(!showQueue)}>
|
||||
<GestureDetector gesture={stageGesture}>
|
||||
<View
|
||||
style={styles.stage}
|
||||
onLayout={(event) =>
|
||||
@@ -297,20 +318,7 @@ export default function PlayerScreen() {
|
||||
<NowPlayingQueue
|
||||
colors={colors}
|
||||
viewportHeight={stageHeight}
|
||||
currentHeader={
|
||||
<View style={styles.queueHeader}>
|
||||
<CoverImage
|
||||
uri={coverUri}
|
||||
hasCover={hasCover}
|
||||
style={styles.queueArtwork}
|
||||
/>
|
||||
<SongMeta
|
||||
song={currentSong}
|
||||
colors={colors}
|
||||
compact
|
||||
/>
|
||||
</View>
|
||||
}
|
||||
currentHeader={queueHeader}
|
||||
/>
|
||||
</Animated.View>
|
||||
) : null
|
||||
@@ -334,50 +342,28 @@ export default function PlayerScreen() {
|
||||
/>
|
||||
</Animated.View>
|
||||
</View>
|
||||
<View style={styles.meta}>
|
||||
<SongMeta song={currentSong} colors={colors} />
|
||||
</View>
|
||||
<View style={styles.meta}>{songMeta}</View>
|
||||
</Animated.View>
|
||||
)}
|
||||
</LayoutAnimationConfig>
|
||||
</View>
|
||||
</GestureDetector>
|
||||
|
||||
<GestureDetector gesture={dismissGesture()}>
|
||||
<GestureDetector gesture={controlsGesture}>
|
||||
<View style={[styles.controls, { paddingBottom: bottomInset }]}>
|
||||
<PlayerSlider
|
||||
accessibilityLabel="Playback position"
|
||||
value={displayedTime}
|
||||
maximumValue={duration}
|
||||
fillColor={colors.sliderFill}
|
||||
activeFillColor={colors.foreground}
|
||||
trackColor={colors.sliderTrack}
|
||||
onValueChange={setScrubTime}
|
||||
onSlidingComplete={(value) => {
|
||||
void seekTo(value)
|
||||
setScrubTime(null)
|
||||
}}
|
||||
/>
|
||||
<View style={styles.timeRow}>
|
||||
<Text style={[styles.time, { color: timeColor }]}>
|
||||
{formatDuration(displayedTime)}
|
||||
</Text>
|
||||
{format ? (
|
||||
<View style={styles.format} pointerEvents="none">
|
||||
<PlayerProgress
|
||||
colors={colors}
|
||||
timeStyle={styles.time}
|
||||
center={
|
||||
format ? (
|
||||
<AudioFormatBadge
|
||||
format={format}
|
||||
color={colors.secondaryForeground}
|
||||
backgroundColor={colors.background}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<Text style={[styles.time, { color: timeColor }]}>
|
||||
{formatRemainingDuration(displayedTime, duration).replace(
|
||||
"-",
|
||||
"\u2212"
|
||||
)}
|
||||
</Text>
|
||||
</View>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
|
||||
<View style={styles.transport}>
|
||||
<TransportButton
|
||||
@@ -419,35 +405,7 @@ export default function PlayerScreen() {
|
||||
</TransportButton>
|
||||
</View>
|
||||
|
||||
{volumeAvailable ? (
|
||||
<PlayerSlider
|
||||
accessibilityLabel="Volume"
|
||||
commitHoldMs={0}
|
||||
animateValueChanges
|
||||
value={volume}
|
||||
maximumValue={1}
|
||||
fillColor={colors.sliderFill}
|
||||
activeFillColor={colors.foreground}
|
||||
trackColor={colors.sliderTrack}
|
||||
onValueChange={setVolume}
|
||||
leading={
|
||||
<PlayerSymbol
|
||||
name="speaker.fill"
|
||||
fallback="volume-low"
|
||||
size={14}
|
||||
color={colors.secondaryForeground}
|
||||
/>
|
||||
}
|
||||
trailing={
|
||||
<PlayerSymbol
|
||||
name="speaker.wave.3.fill"
|
||||
fallback="volume-high"
|
||||
size={14}
|
||||
color={colors.secondaryForeground}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
<VolumeSlider colors={colors} />
|
||||
|
||||
<View style={styles.footer}>
|
||||
<Pressable
|
||||
@@ -517,6 +475,41 @@ export default function PlayerScreen() {
|
||||
)
|
||||
}
|
||||
|
||||
/** Phone volume slider. Owns the volume listener so volume changes stay local. */
|
||||
function VolumeSlider({ colors }: { colors: NowPlayingColors }) {
|
||||
const { volume, setVolume, available } = useSystemVolume()
|
||||
if (!available) return null
|
||||
return (
|
||||
<PlayerSlider
|
||||
accessibilityLabel="Volume"
|
||||
commitHoldMs={0}
|
||||
animateValueChanges
|
||||
value={volume}
|
||||
maximumValue={1}
|
||||
fillColor={colors.sliderFill}
|
||||
activeFillColor={colors.foreground}
|
||||
trackColor={colors.sliderTrack}
|
||||
onValueChange={setVolume}
|
||||
leading={
|
||||
<PlayerSymbol
|
||||
name="speaker.fill"
|
||||
fallback="volume-low"
|
||||
size={14}
|
||||
color={colors.secondaryForeground}
|
||||
/>
|
||||
}
|
||||
trailing={
|
||||
<PlayerSymbol
|
||||
name="speaker.wave.3.fill"
|
||||
fallback="volume-high"
|
||||
size={14}
|
||||
color={colors.secondaryForeground}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** Title and artist with the favorite and more buttons. */
|
||||
function SongMeta({
|
||||
song,
|
||||
@@ -739,23 +732,7 @@ const styles = StyleSheet.create({
|
||||
paddingHorizontal: HORIZONTAL_INSET,
|
||||
paddingTop: spacing.md,
|
||||
},
|
||||
timeRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
marginTop: -4,
|
||||
},
|
||||
format: {
|
||||
position: "absolute",
|
||||
left: 0,
|
||||
right: 0,
|
||||
alignItems: "center",
|
||||
},
|
||||
time: {
|
||||
fontSize: 12,
|
||||
fontWeight: "600",
|
||||
fontVariant: ["tabular-nums"],
|
||||
},
|
||||
time: { fontWeight: "600" },
|
||||
transport: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
|
||||
@@ -1,147 +1,21 @@
|
||||
import { useConvex, useQuery } from "convex/react"
|
||||
import { useQuery } from "convex/react"
|
||||
import * as AppIntents from "expo-app-intents"
|
||||
import type { AppIntentEntity, AppIntentInvocation } from "expo-app-intents"
|
||||
import { useEffect, useMemo, useRef, useSyncExternalStore } from "react"
|
||||
import { AppState } from "react-native"
|
||||
import {
|
||||
completeMusicInvocation,
|
||||
publishMusicCatalog,
|
||||
trackMusicCatalogSync,
|
||||
} from "@/lib/app-intents"
|
||||
import { useAppNavigation } from "@/lib/app-navigation"
|
||||
import { useMemo, useSyncExternalStore } from "react"
|
||||
|
||||
import { useMusicCatalogSync } from "@/components/app-intents/catalog-sync"
|
||||
import { useIntentDispatch } from "@/components/app-intents/dispatch"
|
||||
import { useNowPlayingCatalog } from "@/components/app-intents/now-playing"
|
||||
import {
|
||||
ANONYMOUS_CACHE_SCOPE,
|
||||
useCacheScope,
|
||||
} from "@/contexts/persistent-cache"
|
||||
import { usePlayback } from "@/contexts/playback"
|
||||
import {
|
||||
FAVORITES_PLAYLIST_ID,
|
||||
loadHandledIntentIds,
|
||||
rememberHandledIntentId,
|
||||
} from "@/lib/app-intent-handled"
|
||||
import { showError } from "@/lib/toast"
|
||||
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
|
||||
import { getPlaybackStore } from "@otunes/convex/client/playback-store"
|
||||
import type { RepeatMode } from "@otunes/convex/client/playback-queue"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
|
||||
const warmedAudioIds = new Set<string>()
|
||||
|
||||
class IntentRejected extends Error {}
|
||||
|
||||
const KNOWN_INTENTS = new Set([
|
||||
"playMusic",
|
||||
"warmupAudio",
|
||||
"addToPlaylist",
|
||||
"addToUpNext",
|
||||
"clearUpNext",
|
||||
"createPlaylist",
|
||||
"createStation",
|
||||
"updateAffinity",
|
||||
"transport",
|
||||
"openMusic",
|
||||
])
|
||||
|
||||
type MusicSource = {
|
||||
kind: string
|
||||
id: string
|
||||
}
|
||||
|
||||
function readString(value: unknown) {
|
||||
return typeof value === "string" && value.trim() ? value : null
|
||||
}
|
||||
|
||||
function readSources(value: unknown): MusicSource[] {
|
||||
if (!Array.isArray(value)) {
|
||||
return []
|
||||
}
|
||||
return value.flatMap((entry) => {
|
||||
if (!entry || typeof entry !== "object") {
|
||||
return []
|
||||
}
|
||||
const source = entry as { kind?: unknown; id?: unknown }
|
||||
if (typeof source.kind !== "string" || typeof source.id !== "string") {
|
||||
return []
|
||||
}
|
||||
if (!source.kind || !source.id) {
|
||||
return []
|
||||
}
|
||||
return [{ kind: source.kind, id: source.id }]
|
||||
})
|
||||
}
|
||||
|
||||
function shuffleChoice(value: unknown, fallback: boolean) {
|
||||
if (value === "songs") return true
|
||||
if (value === "off") return false
|
||||
if (value == null) return fallback
|
||||
throw new IntentRejected("Shuffle must be Off or Songs.")
|
||||
}
|
||||
|
||||
function repeatChoice(value: unknown): RepeatMode | null {
|
||||
if (value == null) return null
|
||||
if (value === "none") return "none"
|
||||
if (value === "one") return "once"
|
||||
if (value === "all") return "always"
|
||||
throw new IntentRejected("Repeat must be None, One, or All.")
|
||||
}
|
||||
|
||||
function ensureActive(invocation: AppIntentInvocation) {
|
||||
const deadline = invocation.params.deadline
|
||||
if (typeof deadline === "number" && Date.now() >= deadline) {
|
||||
throw new IntentRejected("This request expired. Please try again.")
|
||||
}
|
||||
}
|
||||
|
||||
function isTransient(error: unknown) {
|
||||
const message = (
|
||||
error instanceof Error ? error.message : String(error)
|
||||
).toLowerCase()
|
||||
return (
|
||||
message.includes("not authenticated") ||
|
||||
message.includes("network") ||
|
||||
message.includes("fetch") ||
|
||||
message.includes("connection") ||
|
||||
message.includes("timed out") ||
|
||||
message.includes("timeout")
|
||||
)
|
||||
}
|
||||
|
||||
function songEntity(song: {
|
||||
id: string
|
||||
title: string
|
||||
artistName: string
|
||||
artistId: string
|
||||
albumTitle: string
|
||||
albumId: string
|
||||
durationSeconds: number
|
||||
genres?: string
|
||||
year?: number
|
||||
track?: number
|
||||
diskNumber?: number | null
|
||||
favorite?: boolean
|
||||
}): AppIntentEntity {
|
||||
return {
|
||||
id: song.id,
|
||||
title: song.title,
|
||||
subtitle: song.artistName,
|
||||
synonyms: song.artistName ? [song.artistName] : undefined,
|
||||
metadata: {
|
||||
artistName: song.artistName,
|
||||
artistId: song.artistId,
|
||||
albumTitle: song.albumTitle,
|
||||
albumId: song.albumId,
|
||||
duration: String(song.durationSeconds),
|
||||
genres: song.genres ?? "",
|
||||
year: song.year == null ? "" : String(song.year),
|
||||
track: song.track == null ? "" : String(song.track),
|
||||
disk: song.diskNumber == null ? "" : String(song.diskNumber),
|
||||
favorite: song.favorite ? "1" : "0",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Siri and Shortcuts integration: the on-device entity catalog, the current
|
||||
* song, and intent dispatch. Must render inside `FavoritesProvider`.
|
||||
*/
|
||||
export function AppIntentBridge() {
|
||||
const scope = useCacheScope()
|
||||
const store = useMemo(
|
||||
@@ -154,669 +28,8 @@ export function AppIntentBridge() {
|
||||
}
|
||||
|
||||
function ReadyAppIntentBridge() {
|
||||
const convex = useConvex()
|
||||
const cacheScope = useCacheScope()
|
||||
const playback = usePlayback()
|
||||
const user = useQuery(api.auth.currentUser)
|
||||
const navigation = useAppNavigation()
|
||||
const favorites = useQuery(api.favorites.getUserFavorites)
|
||||
const catalogUserKey = user ? JSON.stringify([user._id, favorites]) : null
|
||||
const store = useMemo(
|
||||
() =>
|
||||
getPlaybackStore(
|
||||
cacheScope === ANONYMOUS_CACHE_SCOPE ? null : cacheScope
|
||||
),
|
||||
[cacheScope]
|
||||
)
|
||||
const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot)
|
||||
const handledIds = useRef<Set<string> | null>(null)
|
||||
const publishChain = useRef(Promise.resolve())
|
||||
const publishGeneration = useRef(0)
|
||||
const playbackRef = useRef(playback)
|
||||
playbackRef.current = playback
|
||||
|
||||
useEffect(() => {
|
||||
if (!AppIntents.isAvailable() || !user) return
|
||||
const generation = ++publishGeneration.current
|
||||
let stopped = false
|
||||
let refreshing = false
|
||||
const refresh = () => {
|
||||
if (refreshing || stopped) return
|
||||
refreshing = true
|
||||
publishChain.current = publishChain.current
|
||||
.catch(() => undefined)
|
||||
.then(async () => {
|
||||
for (const kind of ["artist", "album", "song", "playlist"] as const) {
|
||||
const entities: AppIntentEntity[] = []
|
||||
let cursor: string | null = null
|
||||
do {
|
||||
const result: {
|
||||
page: AppIntentEntity[]
|
||||
isDone: boolean
|
||||
continueCursor: string
|
||||
} = await convex.query(api.library.intentCatalogPage, {
|
||||
kind,
|
||||
paginationOpts: { cursor, numItems: 200 },
|
||||
})
|
||||
if (stopped || generation !== publishGeneration.current) return
|
||||
entities.push(...result.page)
|
||||
cursor = result.isDone ? null : result.continueCursor
|
||||
} while (cursor !== null)
|
||||
await publishMusicCatalog(kind, entities)
|
||||
}
|
||||
})
|
||||
.catch((error) =>
|
||||
console.warn("Could not publish music catalog.", error)
|
||||
)
|
||||
.finally(() => {
|
||||
refreshing = false
|
||||
})
|
||||
trackMusicCatalogSync(publishChain.current)
|
||||
}
|
||||
refresh()
|
||||
const subscription = AppState.addEventListener("change", (state) => {
|
||||
if (state === "active") refresh()
|
||||
})
|
||||
const timer = setInterval(() => {
|
||||
if (AppState.currentState === "active") refresh()
|
||||
}, 5 * 60_000)
|
||||
return () => {
|
||||
stopped = true
|
||||
++publishGeneration.current
|
||||
subscription.remove()
|
||||
clearInterval(timer)
|
||||
}
|
||||
}, [convex, cacheScope, catalogUserKey])
|
||||
|
||||
const currentSongId = playback.queueSongIds[0] ?? null
|
||||
const currentSong = playback.currentSong
|
||||
|
||||
useEffect(() => {
|
||||
if (!snapshot.hydrated || !AppIntents.isAvailable()) {
|
||||
return
|
||||
}
|
||||
if (!currentSongId) {
|
||||
void publishMusicCatalog("nowPlaying", []).catch((error) => {
|
||||
console.warn("Could not clear the current song.", error)
|
||||
})
|
||||
return
|
||||
}
|
||||
if (!currentSong || currentSong.id !== currentSongId) {
|
||||
return
|
||||
}
|
||||
void publishMusicCatalog("nowPlaying", [
|
||||
songEntity({
|
||||
id: currentSong.id,
|
||||
title: currentSong.title,
|
||||
artistName: currentSong.artist.name,
|
||||
artistId: currentSong.artist.id,
|
||||
albumTitle: currentSong.album.title,
|
||||
albumId: currentSong.album.id,
|
||||
durationSeconds: currentSong.durationSeconds,
|
||||
}),
|
||||
]).catch((error) => {
|
||||
console.warn("Could not publish the current song.", error)
|
||||
})
|
||||
}, [currentSong, currentSongId, snapshot.hydrated])
|
||||
|
||||
AppIntents.useAppIntents(async (pendingIntents) => {
|
||||
if (!handledIds.current) {
|
||||
handledIds.current = await loadHandledIntentIds()
|
||||
}
|
||||
const handled = handledIds.current
|
||||
|
||||
for (const invocation of pendingIntents) {
|
||||
if (handled.has(invocation.id)) {
|
||||
const token = readString(invocation.params.completionToken)
|
||||
if (token) await completeMusicInvocation(token, null)
|
||||
await AppIntents.removePendingInvocationAsync(invocation.id)
|
||||
continue
|
||||
}
|
||||
if (!KNOWN_INTENTS.has(invocation.name)) {
|
||||
await AppIntents.removePendingInvocationAsync(invocation.id)
|
||||
continue
|
||||
}
|
||||
const token = readString(invocation.params.completionToken)
|
||||
try {
|
||||
ensureActive(invocation)
|
||||
await performInvocation(invocation)
|
||||
if (
|
||||
["playMusic", "warmupAudio", "transport", "createStation"].includes(
|
||||
invocation.name
|
||||
)
|
||||
) {
|
||||
const id = store.getState().queue[0]
|
||||
const song = playbackRef.current.currentSong
|
||||
if (!id) await publishMusicCatalog("nowPlaying", [])
|
||||
else if (song?.id === id)
|
||||
await publishMusicCatalog("nowPlaying", [
|
||||
songEntity({
|
||||
id: song.id,
|
||||
title: song.title,
|
||||
artistName: song.artist.name,
|
||||
artistId: song.artist.id,
|
||||
albumTitle: song.album.title,
|
||||
albumId: song.album.id,
|
||||
durationSeconds: song.durationSeconds,
|
||||
}),
|
||||
])
|
||||
}
|
||||
await rememberHandledIntentId(handled, invocation.id)
|
||||
if (token) await completeMusicInvocation(token, null)
|
||||
await AppIntents.removePendingInvocationAsync(invocation.id)
|
||||
} catch (error) {
|
||||
if (token) {
|
||||
await completeMusicInvocation(
|
||||
token,
|
||||
error instanceof Error ? error.message : "oTunes couldn't do that."
|
||||
)
|
||||
}
|
||||
if (token || error instanceof IntentRejected || !isTransient(error)) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "oTunes couldn't do that."
|
||||
if (!(error instanceof IntentRejected) || message) {
|
||||
showError(message)
|
||||
}
|
||||
try {
|
||||
await rememberHandledIntentId(handled, invocation.id)
|
||||
await AppIntents.removePendingInvocationAsync(invocation.id)
|
||||
} catch (removeError) {
|
||||
console.warn(
|
||||
"App Intent remains pending",
|
||||
invocation.id,
|
||||
removeError
|
||||
)
|
||||
}
|
||||
continue
|
||||
}
|
||||
console.warn("App Intent remains pending", invocation.id, error)
|
||||
}
|
||||
}
|
||||
|
||||
async function songIdsFor(kind: string, id: string) {
|
||||
if (kind === "song") {
|
||||
return [id as Id<"songs">]
|
||||
}
|
||||
if (kind === "album") {
|
||||
return fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getAlbumSongIds,
|
||||
{
|
||||
albumId: id as Id<"albums">,
|
||||
}
|
||||
)
|
||||
}
|
||||
if (kind === "artist") {
|
||||
return fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getOrderedArtistSongIds,
|
||||
{ artistId: id as Id<"artists"> }
|
||||
)
|
||||
}
|
||||
if (kind === "playlist") {
|
||||
if (id === FAVORITES_PLAYLIST_ID) {
|
||||
const favorites = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.favorites.getUserFavorites,
|
||||
{}
|
||||
)
|
||||
return favorites.favoriteSongs
|
||||
}
|
||||
return fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getPlaylistSongIds,
|
||||
{ playlistId: id as Id<"playlists"> }
|
||||
)
|
||||
}
|
||||
throw new IntentRejected("Choose a song, album, artist, or playlist.")
|
||||
}
|
||||
|
||||
async function uniqueSongIds(sources: MusicSource[]) {
|
||||
const ids: Id<"songs">[] = []
|
||||
for (const source of sources) {
|
||||
ids.push(...(await songIdsFor(source.kind, source.id)))
|
||||
}
|
||||
return [...new Set(ids)]
|
||||
}
|
||||
|
||||
async function performInvocation(invocation: AppIntentInvocation) {
|
||||
const actions = playbackRef.current
|
||||
switch (invocation.name) {
|
||||
case "openMusic": {
|
||||
const kind = readString(invocation.params.kind)
|
||||
const id = readString(invocation.params.id)
|
||||
if (!id || !kind) throw new IntentRejected("Choose music to open.")
|
||||
if (kind === "song") {
|
||||
const song = await convex.query(api.library.getSong, {
|
||||
id: id as Id<"songs">,
|
||||
})
|
||||
if (!song)
|
||||
throw new IntentRejected("This song is no longer available.")
|
||||
navigation.push(`/album/${song.album}`)
|
||||
} else if (kind === "playlist" && id === FAVORITES_PLAYLIST_ID) {
|
||||
navigation.push("/playlist/favorites")
|
||||
} else if (["album", "artist", "playlist"].includes(kind)) {
|
||||
navigation.push(`/${kind}/${id}`)
|
||||
} else throw new IntentRejected("Unknown music type.")
|
||||
return
|
||||
}
|
||||
case "playMusic":
|
||||
await playMusic(invocation)
|
||||
if (!["next", "tail"].includes(String(invocation.params.queue))) {
|
||||
ensureActive(invocation)
|
||||
await playbackRef.current.waitForPlaybackReady(true)
|
||||
}
|
||||
return
|
||||
case "warmupAudio":
|
||||
await warmup(invocation)
|
||||
ensureActive(invocation)
|
||||
await playbackRef.current.waitForPlaybackReady(false)
|
||||
warmedAudioIds.add(invocation.id)
|
||||
return
|
||||
case "addToPlaylist":
|
||||
await addToPlaylist(invocation)
|
||||
return
|
||||
case "addToUpNext":
|
||||
await addToUpNext(invocation)
|
||||
return
|
||||
case "clearUpNext":
|
||||
ensureActive(invocation)
|
||||
await actions.clearUpNext()
|
||||
return
|
||||
case "createPlaylist":
|
||||
await createPlaylist(invocation)
|
||||
return
|
||||
case "createStation":
|
||||
await createStation(invocation)
|
||||
ensureActive(invocation)
|
||||
await playbackRef.current.waitForPlaybackReady(true)
|
||||
return
|
||||
case "updateAffinity":
|
||||
await updateAffinity(invocation)
|
||||
return
|
||||
case "transport":
|
||||
await transport(invocation)
|
||||
if (store.getState().queue.length > 0) {
|
||||
const command = invocation.params.command
|
||||
await playbackRef.current.waitForPlaybackReady(
|
||||
command === "resume"
|
||||
? true
|
||||
: command === "pause"
|
||||
? false
|
||||
: undefined
|
||||
)
|
||||
}
|
||||
return
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
async function playMusic(invocation: AppIntentInvocation) {
|
||||
const actions = playbackRef.current
|
||||
const queue = readString(invocation.params.queue) ?? "now"
|
||||
const warmupId = readString(invocation.params.warmupId)
|
||||
const repeat = repeatChoice(invocation.params.repeat)
|
||||
if (repeat) {
|
||||
ensureActive(invocation)
|
||||
await actions.setRepeatMode(repeat)
|
||||
}
|
||||
|
||||
if (queue === "next" || queue === "tail") {
|
||||
const kind = readString(invocation.params.kind)
|
||||
const id = readString(invocation.params.id)
|
||||
if (!kind || !id) {
|
||||
throw new IntentRejected("Choose music to add to Up Next.")
|
||||
}
|
||||
const shuffled = shuffleChoice(
|
||||
invocation.params.shuffle,
|
||||
actions.shuffleEnabled
|
||||
)
|
||||
if (shuffled !== actions.shuffleEnabled) {
|
||||
ensureActive(invocation)
|
||||
await actions.setShuffleEnabled(shuffled)
|
||||
}
|
||||
const ids = await songIdsFor(kind, id)
|
||||
if (ids.length === 0) {
|
||||
throw new IntentRejected("Nothing to add to Up Next.")
|
||||
}
|
||||
if (queue === "next") {
|
||||
ensureActive(invocation)
|
||||
await actions.addToQueueNext(ids)
|
||||
} else {
|
||||
ensureActive(invocation)
|
||||
await actions.addToQueueLast(ids)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (warmupId && warmedAudioIds.has(warmupId)) {
|
||||
const shuffled = shuffleChoice(
|
||||
invocation.params.shuffle,
|
||||
actions.shuffleEnabled
|
||||
)
|
||||
if (shuffled !== actions.shuffleEnabled) {
|
||||
ensureActive(invocation)
|
||||
await actions.setShuffleEnabled(shuffled)
|
||||
}
|
||||
ensureActive(invocation)
|
||||
actions.setIsPlaying(true)
|
||||
return
|
||||
}
|
||||
|
||||
const kind = readString(invocation.params.kind) ?? "resume"
|
||||
if (kind === "resume") {
|
||||
const shuffled = shuffleChoice(
|
||||
invocation.params.shuffle,
|
||||
actions.shuffleEnabled
|
||||
)
|
||||
if (shuffled !== actions.shuffleEnabled) {
|
||||
ensureActive(invocation)
|
||||
await actions.setShuffleEnabled(shuffled)
|
||||
}
|
||||
if (actions.queueSongIds.length === 0) {
|
||||
const favorites = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.favorites.getUserFavorites,
|
||||
{}
|
||||
)
|
||||
if (favorites.favoriteSongs.length === 0) {
|
||||
throw new IntentRejected(
|
||||
"Nothing is queued, and your favorites are empty."
|
||||
)
|
||||
}
|
||||
if (shuffled) {
|
||||
ensureActive(invocation)
|
||||
await actions.playShuffled(favorites.favoriteSongs)
|
||||
} else {
|
||||
ensureActive(invocation)
|
||||
await actions.playInOrder(favorites.favoriteSongs)
|
||||
}
|
||||
return
|
||||
}
|
||||
ensureActive(invocation)
|
||||
actions.setIsPlaying(true)
|
||||
return
|
||||
}
|
||||
|
||||
const id = readString(invocation.params.id)
|
||||
if (!id) {
|
||||
throw new IntentRejected("Choose music to play.")
|
||||
}
|
||||
const shuffled = shuffleChoice(
|
||||
invocation.params.shuffle,
|
||||
actions.shuffleEnabled
|
||||
)
|
||||
if (kind === "song") {
|
||||
const song = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.library.getSong,
|
||||
{
|
||||
id: id as Id<"songs">,
|
||||
}
|
||||
)
|
||||
if (!song) {
|
||||
throw new IntentRejected("That song is no longer in your library.")
|
||||
}
|
||||
const albumSongIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getAlbumSongIds,
|
||||
{ albumId: song.album }
|
||||
)
|
||||
ensureActive(invocation)
|
||||
await actions.startFromSong(
|
||||
song._id,
|
||||
albumSongIds.length > 0 ? albumSongIds : [song._id],
|
||||
shuffled,
|
||||
true
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
const ids = await songIdsFor(kind, id)
|
||||
if (ids.length === 0) {
|
||||
throw new IntentRejected("Nothing to play.")
|
||||
}
|
||||
if (shuffled) {
|
||||
ensureActive(invocation)
|
||||
await actions.playShuffled(ids)
|
||||
} else {
|
||||
ensureActive(invocation)
|
||||
await actions.playInOrder(ids)
|
||||
}
|
||||
}
|
||||
|
||||
async function warmup(invocation: AppIntentInvocation) {
|
||||
const kind = readString(invocation.params.kind)
|
||||
const id = readString(invocation.params.id)
|
||||
if (!kind || !id) {
|
||||
throw new IntentRejected("Choose music to get ready.")
|
||||
}
|
||||
const shuffled = shuffleChoice(invocation.params.shuffle, false)
|
||||
if (kind === "song") {
|
||||
const song = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.library.getSong,
|
||||
{
|
||||
id: id as Id<"songs">,
|
||||
}
|
||||
)
|
||||
if (!song) {
|
||||
throw new IntentRejected("That song is no longer in your library.")
|
||||
}
|
||||
const albumSongIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getAlbumSongIds,
|
||||
{ albumId: song.album }
|
||||
)
|
||||
ensureActive(invocation)
|
||||
await playbackRef.current.startFromSong(
|
||||
song._id,
|
||||
albumSongIds.length > 0 ? albumSongIds : [song._id],
|
||||
shuffled,
|
||||
false
|
||||
)
|
||||
} else {
|
||||
const ids = await songIdsFor(kind, id)
|
||||
if (ids.length === 0) {
|
||||
throw new IntentRejected("Nothing to get ready.")
|
||||
}
|
||||
ensureActive(invocation)
|
||||
await playbackRef.current.prepareQueue(ids, shuffled)
|
||||
}
|
||||
}
|
||||
|
||||
async function addToPlaylist(invocation: AppIntentInvocation) {
|
||||
const playlistId = readString(invocation.params.playlistId)
|
||||
const sources = readSources(invocation.params.sources)
|
||||
if (!playlistId || sources.length === 0) {
|
||||
throw new IntentRejected("Choose music and a playlist.")
|
||||
}
|
||||
const songIds = await uniqueSongIds(sources)
|
||||
if (songIds.length === 0) {
|
||||
throw new IntentRejected("Those items have no songs to add.")
|
||||
}
|
||||
if (playlistId === FAVORITES_PLAYLIST_ID) {
|
||||
for (const source of sources) {
|
||||
if (source.kind === "song") {
|
||||
ensureActive(invocation)
|
||||
await convex.mutation(api.favorites.favoriteSong, {
|
||||
songId: source.id as Id<"songs">,
|
||||
})
|
||||
} else if (source.kind === "album") {
|
||||
ensureActive(invocation)
|
||||
await convex.mutation(api.favorites.favoriteAlbum, {
|
||||
albumId: source.id as Id<"albums">,
|
||||
})
|
||||
} else if (source.kind === "artist") {
|
||||
ensureActive(invocation)
|
||||
await convex.mutation(api.favorites.favoriteArtist, {
|
||||
artistId: source.id as Id<"artists">,
|
||||
})
|
||||
} else if (source.kind === "playlist") {
|
||||
const ids = await songIdsFor(source.kind, source.id)
|
||||
if (ids.length > 0) {
|
||||
ensureActive(invocation)
|
||||
await convex.mutation(api.favorites.favoriteSongs, {
|
||||
songIds: ids,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
throw new IntentRejected(
|
||||
"Choose a song, album, artist, or playlist."
|
||||
)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
ensureActive(invocation)
|
||||
await convex.mutation(api.playlists.addSongsToPlaylist, {
|
||||
playlistId: playlistId as Id<"playlists">,
|
||||
songIds,
|
||||
})
|
||||
}
|
||||
|
||||
async function addToUpNext(invocation: AppIntentInvocation) {
|
||||
const sources = readSources(invocation.params.sources)
|
||||
if (sources.length === 0) {
|
||||
throw new IntentRejected("Choose music to add to Up Next.")
|
||||
}
|
||||
const ids = await uniqueSongIds(sources)
|
||||
if (ids.length === 0) {
|
||||
throw new IntentRejected("Nothing to add to Up Next.")
|
||||
}
|
||||
const position =
|
||||
readString(invocation.params.position) === "last" ? "last" : "next"
|
||||
if (position === "last") {
|
||||
ensureActive(invocation)
|
||||
await playbackRef.current.addToQueueLast(ids)
|
||||
} else {
|
||||
ensureActive(invocation)
|
||||
await playbackRef.current.addToQueueNext(ids)
|
||||
}
|
||||
}
|
||||
|
||||
async function createPlaylist(invocation: AppIntentInvocation) {
|
||||
const name = readString(invocation.params.name)
|
||||
if (!name) {
|
||||
throw new IntentRejected("A playlist needs a name.")
|
||||
}
|
||||
const songIds = await uniqueSongIds(
|
||||
readSources(invocation.params.sources)
|
||||
)
|
||||
ensureActive(invocation)
|
||||
await convex.mutation(api.playlists.createPlaylist, {
|
||||
name,
|
||||
songIds,
|
||||
invocationId: invocation.id,
|
||||
})
|
||||
}
|
||||
|
||||
async function createStation(invocation: AppIntentInvocation) {
|
||||
const artistId = readString(invocation.params.artistId)
|
||||
if (!artistId) {
|
||||
throw new IntentRejected("Nothing is playing in oTunes.")
|
||||
}
|
||||
const ids = await songIdsFor("artist", artistId)
|
||||
if (ids.length === 0)
|
||||
throw new IntentRejected("This artist has no songs to play.")
|
||||
ensureActive(invocation)
|
||||
await playbackRef.current.playShuffled(ids)
|
||||
}
|
||||
|
||||
async function updateAffinity(invocation: AppIntentInvocation) {
|
||||
const kind = readString(invocation.params.kind)
|
||||
const id = readString(invocation.params.id)
|
||||
const state = readString(invocation.params.state)
|
||||
if (!kind || !id || (state !== "like" && state !== "unset")) {
|
||||
throw new IntentRejected(
|
||||
"oTunes can love or unlike a song, album, or artist."
|
||||
)
|
||||
}
|
||||
if (kind === "playlist") {
|
||||
throw new IntentRejected("oTunes can love songs, albums, and artists.")
|
||||
}
|
||||
if (state === "like") {
|
||||
if (kind === "song") {
|
||||
ensureActive(invocation)
|
||||
await convex.mutation(api.favorites.favoriteSong, {
|
||||
songId: id as Id<"songs">,
|
||||
})
|
||||
} else if (kind === "album") {
|
||||
ensureActive(invocation)
|
||||
await convex.mutation(api.favorites.favoriteAlbum, {
|
||||
albumId: id as Id<"albums">,
|
||||
})
|
||||
} else if (kind === "artist") {
|
||||
ensureActive(invocation)
|
||||
await convex.mutation(api.favorites.favoriteArtist, {
|
||||
artistId: id as Id<"artists">,
|
||||
})
|
||||
} else {
|
||||
throw new IntentRejected(
|
||||
"oTunes can love songs, albums, and artists."
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (kind === "song") {
|
||||
ensureActive(invocation)
|
||||
await convex.mutation(api.favorites.unfavoriteSong, {
|
||||
songId: id as Id<"songs">,
|
||||
})
|
||||
} else if (kind === "album") {
|
||||
ensureActive(invocation)
|
||||
await convex.mutation(api.favorites.unfavoriteAlbum, {
|
||||
albumId: id as Id<"albums">,
|
||||
})
|
||||
} else if (kind === "artist") {
|
||||
ensureActive(invocation)
|
||||
await convex.mutation(api.favorites.unfavoriteArtist, {
|
||||
artistId: id as Id<"artists">,
|
||||
})
|
||||
} else {
|
||||
throw new IntentRejected("oTunes can love songs, albums, and artists.")
|
||||
}
|
||||
}
|
||||
|
||||
async function transport(invocation: AppIntentInvocation) {
|
||||
const actions = playbackRef.current
|
||||
const command = readString(invocation.params.command)
|
||||
if (command === "pause") {
|
||||
ensureActive(invocation)
|
||||
actions.setIsPlaying(false)
|
||||
return
|
||||
}
|
||||
if (command === "resume") {
|
||||
if (actions.queueSongIds.length === 0) {
|
||||
throw new IntentRejected("Nothing is queued in oTunes.")
|
||||
}
|
||||
ensureActive(invocation)
|
||||
actions.setIsPlaying(true)
|
||||
return
|
||||
}
|
||||
if (command === "next") {
|
||||
ensureActive(invocation)
|
||||
await actions.skipNext()
|
||||
return
|
||||
}
|
||||
if (command === "previous") {
|
||||
ensureActive(invocation)
|
||||
await actions.skipPrevious()
|
||||
return
|
||||
}
|
||||
throw new IntentRejected("oTunes doesn't know that playback control.")
|
||||
}
|
||||
})
|
||||
|
||||
useMusicCatalogSync()
|
||||
useNowPlayingCatalog()
|
||||
useIntentDispatch()
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import { useConvex, useQuery } from "convex/react"
|
||||
import * as AppIntents from "expo-app-intents"
|
||||
import type { AppIntentEntity } from "expo-app-intents"
|
||||
import { useEffect, useRef } from "react"
|
||||
import { AppState } from "react-native"
|
||||
|
||||
import { useCacheScope } from "@/contexts/persistent-cache"
|
||||
import {
|
||||
loadCatalogCursors,
|
||||
saveCatalogCursors,
|
||||
type CatalogCursors,
|
||||
} from "@/lib/app-intent-handled"
|
||||
import {
|
||||
publishMusicCatalog,
|
||||
readMusicCatalog,
|
||||
trackMusicCatalogSync,
|
||||
} from "@/lib/app-intents"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { FunctionReturnType } from "convex/server"
|
||||
|
||||
const LIBRARY_KINDS = ["artist", "album", "song"] as const
|
||||
type LibraryKind = (typeof LIBRARY_KINDS)[number]
|
||||
const PAGE_SIZE = 500
|
||||
type CatalogPage = FunctionReturnType<typeof api.intentCatalog.page>
|
||||
|
||||
type Favorites = {
|
||||
favoriteSongs: string[]
|
||||
favoriteAlbums: string[]
|
||||
favoriteArtists: string[]
|
||||
}
|
||||
|
||||
function favoriteIds(favorites: Favorites, kind: LibraryKind) {
|
||||
return new Set<string>(
|
||||
kind === "song"
|
||||
? favorites.favoriteSongs
|
||||
: kind === "album"
|
||||
? favorites.favoriteAlbums
|
||||
: favorites.favoriteArtists
|
||||
)
|
||||
}
|
||||
|
||||
/** Stamps `metadata.favorite`, which Siri uses to rank suggestions. */
|
||||
function withFavorite(entity: AppIntentEntity, favorite: boolean) {
|
||||
const flag = favorite ? "1" : "0"
|
||||
return entity.metadata?.favorite === flag
|
||||
? entity
|
||||
: { ...entity, metadata: { ...entity.metadata, favorite: flag } }
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the on-device Siri catalog in step with the server. `intentCatalog.head`
|
||||
* is a live subscription, so the library is fetched only when it changes, and
|
||||
* then only the records changed since the stored cursor. Favorites are applied
|
||||
* locally from the existing favorites subscription.
|
||||
*/
|
||||
export function useMusicCatalogSync() {
|
||||
const convex = useConvex()
|
||||
const scope = useCacheScope()
|
||||
const head = useQuery(api.intentCatalog.head)
|
||||
const favorites = useQuery(api.favorites.getUserFavorites)
|
||||
const playlists = useQuery(api.intentCatalog.playlists)
|
||||
const latest = useRef({ head, favorites, playlists })
|
||||
latest.current = { head, favorites, playlists }
|
||||
const schedule = useRef<() => void>(() => undefined)
|
||||
|
||||
useEffect(() => {
|
||||
if (!AppIntents.isAvailable()) return
|
||||
let stopped = false
|
||||
let running = false
|
||||
let dirty = false
|
||||
let cursors: CatalogCursors | null = null
|
||||
// What the disk catalog reflects, to skip no-op republishes.
|
||||
const appliedFavorites = new Map<LibraryKind, Set<string>>()
|
||||
let publishedPlaylists: string | null = null
|
||||
|
||||
async function fetchChanges(kind: LibraryKind, since: number | undefined) {
|
||||
const upserts: AppIntentEntity[] = []
|
||||
let removed: string[] = []
|
||||
let head = 0
|
||||
let cursor: string | null = null
|
||||
do {
|
||||
const result: CatalogPage = await convex.query(api.intentCatalog.page, {
|
||||
kind,
|
||||
since,
|
||||
paginationOpts: { cursor, numItems: PAGE_SIZE },
|
||||
})
|
||||
if (stopped) return null
|
||||
if (cursor === null) {
|
||||
if (result.reset) return fetchChanges(kind, undefined)
|
||||
head = result.head ?? 0
|
||||
removed = result.removed
|
||||
}
|
||||
upserts.push(...result.page)
|
||||
cursor = result.isDone ? null : result.continueCursor
|
||||
} while (cursor !== null)
|
||||
return { upserts, removed, head, full: since === undefined }
|
||||
}
|
||||
|
||||
async function syncKind(
|
||||
kind: LibraryKind,
|
||||
serverHead: number,
|
||||
favorites: Favorites
|
||||
) {
|
||||
if (!cursors) return
|
||||
const since = cursors[kind]
|
||||
const stale = since === undefined || serverHead > since
|
||||
const liked = favoriteIds(favorites, kind)
|
||||
const previousLiked = appliedFavorites.get(kind)
|
||||
const likesChanged =
|
||||
!previousLiked ||
|
||||
previousLiked.size !== liked.size ||
|
||||
[...liked].some((id) => !previousLiked.has(id))
|
||||
if (!stale && !likesChanged) return
|
||||
|
||||
const changes = stale ? await fetchChanges(kind, since) : null
|
||||
if (stopped) return
|
||||
const records = new Map<string, AppIntentEntity>()
|
||||
if (!changes?.full) {
|
||||
for (const entity of await readMusicCatalog(kind)) {
|
||||
records.set(entity.id, entity)
|
||||
}
|
||||
}
|
||||
for (const id of changes?.removed ?? []) records.delete(id)
|
||||
for (const entity of changes?.upserts ?? [])
|
||||
records.set(entity.id, entity)
|
||||
|
||||
let modified = changes !== null
|
||||
for (const [id, entity] of records) {
|
||||
const next = withFavorite(entity, liked.has(id))
|
||||
if (next !== entity) {
|
||||
records.set(id, next)
|
||||
modified = true
|
||||
}
|
||||
}
|
||||
if (stopped) return
|
||||
if (modified) await publishMusicCatalog(kind, [...records.values()])
|
||||
appliedFavorites.set(kind, liked)
|
||||
if (changes && !stopped) {
|
||||
cursors = { ...cursors, [kind]: changes.head }
|
||||
await saveCatalogCursors(scope, cursors)
|
||||
}
|
||||
}
|
||||
|
||||
async function syncOnce() {
|
||||
const { head, favorites, playlists } = latest.current
|
||||
cursors ??= await loadCatalogCursors(scope)
|
||||
if (head && favorites) {
|
||||
for (const kind of LIBRARY_KINDS) {
|
||||
if (stopped) return
|
||||
await syncKind(kind, head[kind], favorites)
|
||||
}
|
||||
}
|
||||
if (playlists && !stopped) {
|
||||
const json = JSON.stringify(playlists)
|
||||
if (json !== publishedPlaylists) {
|
||||
await publishMusicCatalog("playlist", playlists)
|
||||
publishedPlaylists = json
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
schedule.current = () => {
|
||||
if (stopped) return
|
||||
if (running) {
|
||||
dirty = true
|
||||
return
|
||||
}
|
||||
running = true
|
||||
const sync = (async () => {
|
||||
do {
|
||||
dirty = false
|
||||
await syncOnce()
|
||||
} while (dirty && !stopped)
|
||||
})()
|
||||
.catch((error) =>
|
||||
console.warn("Could not publish music catalog.", error)
|
||||
)
|
||||
.finally(() => {
|
||||
running = false
|
||||
})
|
||||
trackMusicCatalogSync(sync)
|
||||
}
|
||||
schedule.current()
|
||||
// Retries a failed sync; a no-op without server queries when current.
|
||||
const subscription = AppState.addEventListener("change", (state) => {
|
||||
if (state === "active") schedule.current()
|
||||
})
|
||||
return () => {
|
||||
stopped = true
|
||||
schedule.current = () => undefined
|
||||
subscription.remove()
|
||||
}
|
||||
}, [convex, scope])
|
||||
|
||||
useEffect(() => {
|
||||
schedule.current()
|
||||
}, [head, favorites, playlists])
|
||||
}
|
||||
@@ -0,0 +1,631 @@
|
||||
import { useConvex } from "convex/react"
|
||||
import * as AppIntents from "expo-app-intents"
|
||||
import type { AppIntentInvocation } from "expo-app-intents"
|
||||
import { useMemo, useRef } from "react"
|
||||
|
||||
import { useFavorites, type FavoriteKind } from "@/contexts/favorites"
|
||||
import {
|
||||
ANONYMOUS_CACHE_SCOPE,
|
||||
useCacheScope,
|
||||
} from "@/contexts/persistent-cache"
|
||||
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
|
||||
import {
|
||||
FAVORITES_PLAYLIST_ID,
|
||||
loadHandledIntentIds,
|
||||
rememberHandledIntentId,
|
||||
} from "@/lib/app-intent-handled"
|
||||
import { completeMusicInvocation } from "@/lib/app-intents"
|
||||
import { useAppNavigation } from "@/lib/app-navigation"
|
||||
import { showError } from "@/lib/toast"
|
||||
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
|
||||
import { getPlaybackStore } from "@otunes/convex/client/playback-store"
|
||||
import type { RepeatMode } from "@otunes/convex/client/playback-queue"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { publishNowPlaying } from "./now-playing"
|
||||
|
||||
const warmedAudioIds = new Set<string>()
|
||||
|
||||
class IntentRejected extends Error {}
|
||||
|
||||
const KNOWN_INTENTS = new Set([
|
||||
"playMusic",
|
||||
"warmupAudio",
|
||||
"addToPlaylist",
|
||||
"addToUpNext",
|
||||
"clearUpNext",
|
||||
"createPlaylist",
|
||||
"createStation",
|
||||
"updateAffinity",
|
||||
"transport",
|
||||
"openMusic",
|
||||
])
|
||||
|
||||
type MusicSource = {
|
||||
kind: string
|
||||
id: string
|
||||
}
|
||||
|
||||
function readString(value: unknown) {
|
||||
return typeof value === "string" && value.trim() ? value : null
|
||||
}
|
||||
|
||||
function readSources(value: unknown): MusicSource[] {
|
||||
if (!Array.isArray(value)) {
|
||||
return []
|
||||
}
|
||||
return value.flatMap((entry) => {
|
||||
if (!entry || typeof entry !== "object") {
|
||||
return []
|
||||
}
|
||||
const source = entry as { kind?: unknown; id?: unknown }
|
||||
if (typeof source.kind !== "string" || typeof source.id !== "string") {
|
||||
return []
|
||||
}
|
||||
if (!source.kind || !source.id) {
|
||||
return []
|
||||
}
|
||||
return [{ kind: source.kind, id: source.id }]
|
||||
})
|
||||
}
|
||||
|
||||
function isFavoriteKind(kind: string): kind is FavoriteKind {
|
||||
return kind === "song" || kind === "album" || kind === "artist"
|
||||
}
|
||||
|
||||
function shuffleChoice(value: unknown, fallback: boolean) {
|
||||
if (value === "songs") return true
|
||||
if (value === "off") return false
|
||||
if (value == null) return fallback
|
||||
throw new IntentRejected("Shuffle must be Off or Songs.")
|
||||
}
|
||||
|
||||
function repeatChoice(value: unknown): RepeatMode | null {
|
||||
if (value == null) return null
|
||||
if (value === "none") return "none"
|
||||
if (value === "one") return "once"
|
||||
if (value === "all") return "always"
|
||||
throw new IntentRejected("Repeat must be None, One, or All.")
|
||||
}
|
||||
|
||||
function ensureActive(invocation: AppIntentInvocation) {
|
||||
const deadline = invocation.params.deadline
|
||||
if (typeof deadline === "number" && Date.now() >= deadline) {
|
||||
throw new IntentRejected("This request expired. Please try again.")
|
||||
}
|
||||
}
|
||||
|
||||
function isTransient(error: unknown) {
|
||||
const message = (
|
||||
error instanceof Error ? error.message : String(error)
|
||||
).toLowerCase()
|
||||
return (
|
||||
message.includes("not authenticated") ||
|
||||
message.includes("network") ||
|
||||
message.includes("fetch") ||
|
||||
message.includes("connection") ||
|
||||
message.includes("timed out") ||
|
||||
message.includes("timeout")
|
||||
)
|
||||
}
|
||||
|
||||
/** Runs Siri and Shortcuts invocations queued by the native intents. */
|
||||
export function useIntentDispatch() {
|
||||
const convex = useConvex()
|
||||
const cacheScope = useCacheScope()
|
||||
const playback = { ...usePlaybackQueue(), ...usePlaybackActions() }
|
||||
const favorites = useFavorites()
|
||||
const navigation = useAppNavigation()
|
||||
const store = useMemo(
|
||||
() =>
|
||||
getPlaybackStore(
|
||||
cacheScope === ANONYMOUS_CACHE_SCOPE ? null : cacheScope
|
||||
),
|
||||
[cacheScope]
|
||||
)
|
||||
const handledIds = useRef<Set<string> | null>(null)
|
||||
const playbackRef = useRef(playback)
|
||||
playbackRef.current = playback
|
||||
|
||||
/** Intent ids arrive as strings; the server validates them. */
|
||||
function setFavorite(kind: FavoriteKind, id: string, favorite: boolean) {
|
||||
return kind === "song"
|
||||
? favorites.setFavorite(kind, id as Id<"songs">, favorite)
|
||||
: kind === "album"
|
||||
? favorites.setFavorite(kind, id as Id<"albums">, favorite)
|
||||
: favorites.setFavorite(kind, id as Id<"artists">, favorite)
|
||||
}
|
||||
|
||||
AppIntents.useAppIntents(async (pendingIntents) => {
|
||||
if (!handledIds.current) {
|
||||
handledIds.current = await loadHandledIntentIds()
|
||||
}
|
||||
const handled = handledIds.current
|
||||
|
||||
for (const invocation of pendingIntents) {
|
||||
if (handled.has(invocation.id)) {
|
||||
const token = readString(invocation.params.completionToken)
|
||||
if (token) await completeMusicInvocation(token, null)
|
||||
await AppIntents.removePendingInvocationAsync(invocation.id)
|
||||
continue
|
||||
}
|
||||
if (!KNOWN_INTENTS.has(invocation.name)) {
|
||||
await AppIntents.removePendingInvocationAsync(invocation.id)
|
||||
continue
|
||||
}
|
||||
const token = readString(invocation.params.completionToken)
|
||||
try {
|
||||
ensureActive(invocation)
|
||||
await performInvocation(invocation)
|
||||
if (
|
||||
["playMusic", "warmupAudio", "transport", "createStation"].includes(
|
||||
invocation.name
|
||||
)
|
||||
) {
|
||||
await publishNowPlaying(
|
||||
store.getState().queue[0] ?? null,
|
||||
playbackRef.current.currentSong
|
||||
)
|
||||
}
|
||||
await rememberHandledIntentId(handled, invocation.id)
|
||||
if (token) await completeMusicInvocation(token, null)
|
||||
await AppIntents.removePendingInvocationAsync(invocation.id)
|
||||
} catch (error) {
|
||||
if (token) {
|
||||
await completeMusicInvocation(
|
||||
token,
|
||||
error instanceof Error ? error.message : "oTunes couldn't do that."
|
||||
)
|
||||
}
|
||||
if (token || error instanceof IntentRejected || !isTransient(error)) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "oTunes couldn't do that."
|
||||
if (!(error instanceof IntentRejected) || message) {
|
||||
showError(message)
|
||||
}
|
||||
try {
|
||||
await rememberHandledIntentId(handled, invocation.id)
|
||||
await AppIntents.removePendingInvocationAsync(invocation.id)
|
||||
} catch (removeError) {
|
||||
console.warn(
|
||||
"App Intent remains pending",
|
||||
invocation.id,
|
||||
removeError
|
||||
)
|
||||
}
|
||||
continue
|
||||
}
|
||||
console.warn("App Intent remains pending", invocation.id, error)
|
||||
}
|
||||
}
|
||||
|
||||
async function songIdsFor(kind: string, id: string) {
|
||||
if (kind === "song") {
|
||||
return [id as Id<"songs">]
|
||||
}
|
||||
if (kind === "album") {
|
||||
return fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getAlbumSongIds,
|
||||
{
|
||||
albumId: id as Id<"albums">,
|
||||
}
|
||||
)
|
||||
}
|
||||
if (kind === "artist") {
|
||||
return fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getOrderedArtistSongIds,
|
||||
{ artistId: id as Id<"artists"> }
|
||||
)
|
||||
}
|
||||
if (kind === "playlist") {
|
||||
if (id === FAVORITES_PLAYLIST_ID) {
|
||||
const favorites = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.favorites.getUserFavorites,
|
||||
{}
|
||||
)
|
||||
return favorites.favoriteSongs
|
||||
}
|
||||
return fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getPlaylistSongIds,
|
||||
{ playlistId: id as Id<"playlists"> }
|
||||
)
|
||||
}
|
||||
throw new IntentRejected("Choose a song, album, artist, or playlist.")
|
||||
}
|
||||
|
||||
async function uniqueSongIds(sources: MusicSource[]) {
|
||||
const ids: Id<"songs">[] = []
|
||||
for (const source of sources) {
|
||||
ids.push(...(await songIdsFor(source.kind, source.id)))
|
||||
}
|
||||
return [...new Set(ids)]
|
||||
}
|
||||
|
||||
async function performInvocation(invocation: AppIntentInvocation) {
|
||||
const actions = playbackRef.current
|
||||
switch (invocation.name) {
|
||||
case "openMusic": {
|
||||
const kind = readString(invocation.params.kind)
|
||||
const id = readString(invocation.params.id)
|
||||
if (!id || !kind) throw new IntentRejected("Choose music to open.")
|
||||
if (kind === "song") {
|
||||
const song = await convex.query(api.library.getSong, {
|
||||
id: id as Id<"songs">,
|
||||
})
|
||||
if (!song)
|
||||
throw new IntentRejected("This song is no longer available.")
|
||||
navigation.push(`/album/${song.album}`)
|
||||
} else if (kind === "playlist" && id === FAVORITES_PLAYLIST_ID) {
|
||||
navigation.push("/playlist/favorites")
|
||||
} else if (["album", "artist", "playlist"].includes(kind)) {
|
||||
navigation.push(`/${kind}/${id}`)
|
||||
} else throw new IntentRejected("Unknown music type.")
|
||||
return
|
||||
}
|
||||
case "playMusic":
|
||||
await playMusic(invocation)
|
||||
if (!["next", "tail"].includes(String(invocation.params.queue))) {
|
||||
ensureActive(invocation)
|
||||
await playbackRef.current.waitForPlaybackReady(true)
|
||||
}
|
||||
return
|
||||
case "warmupAudio":
|
||||
await warmup(invocation)
|
||||
ensureActive(invocation)
|
||||
await playbackRef.current.waitForPlaybackReady(false)
|
||||
warmedAudioIds.add(invocation.id)
|
||||
return
|
||||
case "addToPlaylist":
|
||||
await addToPlaylist(invocation)
|
||||
return
|
||||
case "addToUpNext":
|
||||
await addToUpNext(invocation)
|
||||
return
|
||||
case "clearUpNext":
|
||||
ensureActive(invocation)
|
||||
await actions.clearUpNext()
|
||||
return
|
||||
case "createPlaylist":
|
||||
await createPlaylist(invocation)
|
||||
return
|
||||
case "createStation":
|
||||
await createStation(invocation)
|
||||
ensureActive(invocation)
|
||||
await playbackRef.current.waitForPlaybackReady(true)
|
||||
return
|
||||
case "updateAffinity":
|
||||
await updateAffinity(invocation)
|
||||
return
|
||||
case "transport":
|
||||
await transport(invocation)
|
||||
if (store.getState().queue.length > 0) {
|
||||
const command = invocation.params.command
|
||||
await playbackRef.current.waitForPlaybackReady(
|
||||
command === "resume"
|
||||
? true
|
||||
: command === "pause"
|
||||
? false
|
||||
: undefined
|
||||
)
|
||||
}
|
||||
return
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
async function playMusic(invocation: AppIntentInvocation) {
|
||||
const actions = playbackRef.current
|
||||
const queue = readString(invocation.params.queue) ?? "now"
|
||||
const warmupId = readString(invocation.params.warmupId)
|
||||
const repeat = repeatChoice(invocation.params.repeat)
|
||||
if (repeat) {
|
||||
ensureActive(invocation)
|
||||
await actions.setRepeatMode(repeat)
|
||||
}
|
||||
|
||||
if (queue === "next" || queue === "tail") {
|
||||
const kind = readString(invocation.params.kind)
|
||||
const id = readString(invocation.params.id)
|
||||
if (!kind || !id) {
|
||||
throw new IntentRejected("Choose music to add to Up Next.")
|
||||
}
|
||||
const shuffled = shuffleChoice(
|
||||
invocation.params.shuffle,
|
||||
actions.shuffleEnabled
|
||||
)
|
||||
if (shuffled !== actions.shuffleEnabled) {
|
||||
ensureActive(invocation)
|
||||
await actions.setShuffleEnabled(shuffled)
|
||||
}
|
||||
const ids = await songIdsFor(kind, id)
|
||||
if (ids.length === 0) {
|
||||
throw new IntentRejected("Nothing to add to Up Next.")
|
||||
}
|
||||
if (queue === "next") {
|
||||
ensureActive(invocation)
|
||||
await actions.addToQueueNext(ids)
|
||||
} else {
|
||||
ensureActive(invocation)
|
||||
await actions.addToQueueLast(ids)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (warmupId && warmedAudioIds.has(warmupId)) {
|
||||
const shuffled = shuffleChoice(
|
||||
invocation.params.shuffle,
|
||||
actions.shuffleEnabled
|
||||
)
|
||||
if (shuffled !== actions.shuffleEnabled) {
|
||||
ensureActive(invocation)
|
||||
await actions.setShuffleEnabled(shuffled)
|
||||
}
|
||||
ensureActive(invocation)
|
||||
actions.setIsPlaying(true)
|
||||
return
|
||||
}
|
||||
|
||||
const kind = readString(invocation.params.kind) ?? "resume"
|
||||
if (kind === "resume") {
|
||||
const shuffled = shuffleChoice(
|
||||
invocation.params.shuffle,
|
||||
actions.shuffleEnabled
|
||||
)
|
||||
if (shuffled !== actions.shuffleEnabled) {
|
||||
ensureActive(invocation)
|
||||
await actions.setShuffleEnabled(shuffled)
|
||||
}
|
||||
if (actions.queueSongIds.length === 0) {
|
||||
const favorites = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.favorites.getUserFavorites,
|
||||
{}
|
||||
)
|
||||
if (favorites.favoriteSongs.length === 0) {
|
||||
throw new IntentRejected(
|
||||
"Nothing is queued, and your favorites are empty."
|
||||
)
|
||||
}
|
||||
if (shuffled) {
|
||||
ensureActive(invocation)
|
||||
await actions.playShuffled(favorites.favoriteSongs)
|
||||
} else {
|
||||
ensureActive(invocation)
|
||||
await actions.playInOrder(favorites.favoriteSongs)
|
||||
}
|
||||
return
|
||||
}
|
||||
ensureActive(invocation)
|
||||
actions.setIsPlaying(true)
|
||||
return
|
||||
}
|
||||
|
||||
const id = readString(invocation.params.id)
|
||||
if (!id) {
|
||||
throw new IntentRejected("Choose music to play.")
|
||||
}
|
||||
const shuffled = shuffleChoice(
|
||||
invocation.params.shuffle,
|
||||
actions.shuffleEnabled
|
||||
)
|
||||
if (kind === "song") {
|
||||
const song = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.library.getSong,
|
||||
{
|
||||
id: id as Id<"songs">,
|
||||
}
|
||||
)
|
||||
if (!song) {
|
||||
throw new IntentRejected("That song is no longer in your library.")
|
||||
}
|
||||
const albumSongIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getAlbumSongIds,
|
||||
{ albumId: song.album }
|
||||
)
|
||||
ensureActive(invocation)
|
||||
await actions.startFromSong(
|
||||
song._id,
|
||||
albumSongIds.length > 0 ? albumSongIds : [song._id],
|
||||
shuffled,
|
||||
true
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
const ids = await songIdsFor(kind, id)
|
||||
if (ids.length === 0) {
|
||||
throw new IntentRejected("Nothing to play.")
|
||||
}
|
||||
if (shuffled) {
|
||||
ensureActive(invocation)
|
||||
await actions.playShuffled(ids)
|
||||
} else {
|
||||
ensureActive(invocation)
|
||||
await actions.playInOrder(ids)
|
||||
}
|
||||
}
|
||||
|
||||
async function warmup(invocation: AppIntentInvocation) {
|
||||
const kind = readString(invocation.params.kind)
|
||||
const id = readString(invocation.params.id)
|
||||
if (!kind || !id) {
|
||||
throw new IntentRejected("Choose music to get ready.")
|
||||
}
|
||||
const shuffled = shuffleChoice(invocation.params.shuffle, false)
|
||||
if (kind === "song") {
|
||||
const song = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.library.getSong,
|
||||
{
|
||||
id: id as Id<"songs">,
|
||||
}
|
||||
)
|
||||
if (!song) {
|
||||
throw new IntentRejected("That song is no longer in your library.")
|
||||
}
|
||||
const albumSongIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getAlbumSongIds,
|
||||
{ albumId: song.album }
|
||||
)
|
||||
ensureActive(invocation)
|
||||
await playbackRef.current.startFromSong(
|
||||
song._id,
|
||||
albumSongIds.length > 0 ? albumSongIds : [song._id],
|
||||
shuffled,
|
||||
false
|
||||
)
|
||||
} else {
|
||||
const ids = await songIdsFor(kind, id)
|
||||
if (ids.length === 0) {
|
||||
throw new IntentRejected("Nothing to get ready.")
|
||||
}
|
||||
ensureActive(invocation)
|
||||
await playbackRef.current.prepareQueue(ids, shuffled)
|
||||
}
|
||||
}
|
||||
|
||||
async function addToPlaylist(invocation: AppIntentInvocation) {
|
||||
const playlistId = readString(invocation.params.playlistId)
|
||||
const sources = readSources(invocation.params.sources)
|
||||
if (!playlistId || sources.length === 0) {
|
||||
throw new IntentRejected("Choose music and a playlist.")
|
||||
}
|
||||
const songIds = await uniqueSongIds(sources)
|
||||
if (songIds.length === 0) {
|
||||
throw new IntentRejected("Those items have no songs to add.")
|
||||
}
|
||||
if (playlistId === FAVORITES_PLAYLIST_ID) {
|
||||
for (const source of sources) {
|
||||
if (isFavoriteKind(source.kind)) {
|
||||
ensureActive(invocation)
|
||||
await setFavorite(source.kind, source.id, true)
|
||||
} else if (source.kind === "playlist") {
|
||||
const ids = await songIdsFor(source.kind, source.id)
|
||||
ensureActive(invocation)
|
||||
await favorites.addFavoriteSongs(ids)
|
||||
} else {
|
||||
throw new IntentRejected(
|
||||
"Choose a song, album, artist, or playlist."
|
||||
)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
ensureActive(invocation)
|
||||
await convex.mutation(api.playlists.addSongsToPlaylist, {
|
||||
playlistId: playlistId as Id<"playlists">,
|
||||
songIds,
|
||||
})
|
||||
}
|
||||
|
||||
async function addToUpNext(invocation: AppIntentInvocation) {
|
||||
const sources = readSources(invocation.params.sources)
|
||||
if (sources.length === 0) {
|
||||
throw new IntentRejected("Choose music to add to Up Next.")
|
||||
}
|
||||
const ids = await uniqueSongIds(sources)
|
||||
if (ids.length === 0) {
|
||||
throw new IntentRejected("Nothing to add to Up Next.")
|
||||
}
|
||||
const position =
|
||||
readString(invocation.params.position) === "last" ? "last" : "next"
|
||||
if (position === "last") {
|
||||
ensureActive(invocation)
|
||||
await playbackRef.current.addToQueueLast(ids)
|
||||
} else {
|
||||
ensureActive(invocation)
|
||||
await playbackRef.current.addToQueueNext(ids)
|
||||
}
|
||||
}
|
||||
|
||||
async function createPlaylist(invocation: AppIntentInvocation) {
|
||||
const name = readString(invocation.params.name)
|
||||
if (!name) {
|
||||
throw new IntentRejected("A playlist needs a name.")
|
||||
}
|
||||
const songIds = await uniqueSongIds(
|
||||
readSources(invocation.params.sources)
|
||||
)
|
||||
ensureActive(invocation)
|
||||
await convex.mutation(api.playlists.createPlaylist, {
|
||||
name,
|
||||
songIds,
|
||||
invocationId: invocation.id,
|
||||
})
|
||||
}
|
||||
|
||||
async function createStation(invocation: AppIntentInvocation) {
|
||||
const artistId = readString(invocation.params.artistId)
|
||||
if (!artistId) {
|
||||
throw new IntentRejected("Nothing is playing in oTunes.")
|
||||
}
|
||||
const ids = await songIdsFor("artist", artistId)
|
||||
if (ids.length === 0)
|
||||
throw new IntentRejected("This artist has no songs to play.")
|
||||
ensureActive(invocation)
|
||||
await playbackRef.current.playShuffled(ids)
|
||||
}
|
||||
|
||||
async function updateAffinity(invocation: AppIntentInvocation) {
|
||||
const kind = readString(invocation.params.kind)
|
||||
const id = readString(invocation.params.id)
|
||||
const state = readString(invocation.params.state)
|
||||
if (!kind || !id || (state !== "like" && state !== "unset")) {
|
||||
throw new IntentRejected(
|
||||
"oTunes can love or unlike a song, album, or artist."
|
||||
)
|
||||
}
|
||||
if (!isFavoriteKind(kind)) {
|
||||
throw new IntentRejected("oTunes can love songs, albums, and artists.")
|
||||
}
|
||||
ensureActive(invocation)
|
||||
await setFavorite(kind, id, state === "like")
|
||||
}
|
||||
|
||||
async function transport(invocation: AppIntentInvocation) {
|
||||
const actions = playbackRef.current
|
||||
const command = readString(invocation.params.command)
|
||||
if (command === "pause") {
|
||||
ensureActive(invocation)
|
||||
actions.setIsPlaying(false)
|
||||
return
|
||||
}
|
||||
if (command === "resume") {
|
||||
if (actions.queueSongIds.length === 0) {
|
||||
throw new IntentRejected("Nothing is queued in oTunes.")
|
||||
}
|
||||
ensureActive(invocation)
|
||||
actions.setIsPlaying(true)
|
||||
return
|
||||
}
|
||||
if (command === "next") {
|
||||
ensureActive(invocation)
|
||||
await actions.skipNext()
|
||||
return
|
||||
}
|
||||
if (command === "previous") {
|
||||
ensureActive(invocation)
|
||||
await actions.skipPrevious()
|
||||
return
|
||||
}
|
||||
throw new IntentRejected("oTunes doesn't know that playback control.")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import * as AppIntents from "expo-app-intents"
|
||||
import type { AppIntentEntity } from "expo-app-intents"
|
||||
import { useEffect } from "react"
|
||||
|
||||
import { usePlaybackQueue } from "@/contexts/playback"
|
||||
import { publishMusicCatalog } from "@/lib/app-intents"
|
||||
|
||||
type CurrentSong = NonNullable<
|
||||
ReturnType<typeof usePlaybackQueue>["currentSong"]
|
||||
>
|
||||
|
||||
function nowPlayingEntity(song: CurrentSong): AppIntentEntity {
|
||||
const artistName = song.artist.name
|
||||
return {
|
||||
id: song.id,
|
||||
title: song.title,
|
||||
subtitle: artistName,
|
||||
synonyms: artistName ? [artistName] : undefined,
|
||||
metadata: {
|
||||
artistName,
|
||||
artistId: song.artist.id,
|
||||
albumTitle: song.album.title,
|
||||
albumId: song.album.id,
|
||||
duration: String(song.durationSeconds),
|
||||
genres: "",
|
||||
year: "",
|
||||
track: "",
|
||||
disk: "",
|
||||
favorite: "0",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes the "nowPlaying" catalog Siri reads for the current song. With an
|
||||
* id but no matching `song` it leaves the catalog alone until the song loads.
|
||||
*/
|
||||
export async function publishNowPlaying(
|
||||
queueHeadId: string | null,
|
||||
song: CurrentSong | null
|
||||
) {
|
||||
if (!queueHeadId) await publishMusicCatalog("nowPlaying", [])
|
||||
else if (song?.id === queueHeadId)
|
||||
await publishMusicCatalog("nowPlaying", [nowPlayingEntity(song)])
|
||||
}
|
||||
|
||||
/** Keeps the "nowPlaying" catalog in step with the playback queue. */
|
||||
export function useNowPlayingCatalog() {
|
||||
const playback = usePlaybackQueue()
|
||||
const queueHeadId = playback.queueSongIds[0] ?? null
|
||||
const song = playback.currentSong
|
||||
|
||||
useEffect(() => {
|
||||
if (!AppIntents.isAvailable()) return
|
||||
void publishNowPlaying(queueHeadId, song).catch((error) => {
|
||||
console.warn("Could not publish the current song.", error)
|
||||
})
|
||||
}, [queueHeadId, song])
|
||||
}
|
||||
@@ -1,39 +1,33 @@
|
||||
import { StyleSheet, Text, View } from "react-native"
|
||||
import Svg, { G, Path } from "react-native-svg"
|
||||
|
||||
import {
|
||||
DOLBY_PATHS,
|
||||
DOLBY_VIEW_BOX,
|
||||
DOLBY_WIDTH,
|
||||
LOSSLESS_FALL,
|
||||
LOSSLESS_FALL_GAP,
|
||||
LOSSLESS_PEAKS,
|
||||
LOSSLESS_STROKES,
|
||||
LOSSLESS_THIN_WIDTH,
|
||||
LOSSLESS_VIEW_BOX,
|
||||
LOSSLESS_WIDTH,
|
||||
MARK_HEIGHT,
|
||||
} from "@otunes/convex/client/audio-format-marks"
|
||||
import type { PlaybackFormat } from "@otunes/convex/playback-stream"
|
||||
|
||||
const LABEL_SIZE = 13
|
||||
const MARK_HEIGHT = 11
|
||||
|
||||
function DolbyMark({ color }: { color: string }) {
|
||||
return (
|
||||
<Svg
|
||||
width={(MARK_HEIGHT * 23) / 16}
|
||||
height={MARK_HEIGHT}
|
||||
viewBox="0 0 23 16"
|
||||
>
|
||||
<Path d="M0 0H2.5A8 8 0 0 1 2.5 16H0Z" fill={color} />
|
||||
<Path d="M23 0H20.5A8 8 0 0 0 20.5 16H23Z" fill={color} />
|
||||
<Svg width={DOLBY_WIDTH} height={MARK_HEIGHT} viewBox={DOLBY_VIEW_BOX}>
|
||||
{DOLBY_PATHS.map((d) => (
|
||||
<Path key={d} d={d} fill={color} />
|
||||
))}
|
||||
</Svg>
|
||||
)
|
||||
}
|
||||
|
||||
const LOSSLESS_PEAKS = [110, 215, 320]
|
||||
const LOSSLESS_THIN_WIDTH = 24
|
||||
const LOSSLESS_STROKES: [peak: number, d: string][] = [
|
||||
[110, "M-70 320C-62 245 -38 166 0 166"],
|
||||
[215, "M-70 320C-62 245 -38 166 0 166"],
|
||||
[320, "M-30 185C-22 173 -11 166 0 166"],
|
||||
[110, "M166 413C176 413 186 406 194 395"],
|
||||
[215, "M166 413C200 413 226 340 240 275"],
|
||||
[320, "M166 413C200 413 226 340 240 275"],
|
||||
]
|
||||
const LOSSLESS_FALL =
|
||||
"M0 178L4 179L8 181L12 184L16 189L20 196L23 204L27 213L30 223L34 233L39 243L43 254L48 266L53 278L58 289L62 301L66 313L71 325L75 336L79 347L83 357L86 364L89 370L93 377L97 382L101 387L105 392L109 397L113 401L117 405L121 408L126 412L130 415L134 417L139 419L143 421L148 423L152 424L157 424L161 425L166 425L166 401L163 401L161 400L159 400L157 399L154 397L152 396L151 394L149 392L147 389L145 386L143 383L142 380L140 376L138 371L137 367L135 362L134 357L132 351L130 345L127 339L124 330L120 319L116 308L111 297L107 285L102 272L98 260L93 248L88 235L82 223L76 212L69 201L61 192L53 183L45 175L37 168L28 163L19 158L10 155L0 154Z"
|
||||
const LOSSLESS_FALL_GAP =
|
||||
"M0 178L4 180L6 184L8 190L9 197L11 203L14 210L17 219L21 228L24 238L29 248L33 259L38 270L43 282L47 293L52 305L56 317L60 328L64 340L68 351L73 361L76 368L79 375L83 381L87 387L91 393L95 398L100 403L104 408L109 412L113 416L118 419L124 422L130 424L135 425L141 426L147 426L152 426L157 425L161 425L166 425L166 401L163 401L161 399L159 398L158 395L157 393L156 390L155 387L155 384L154 381L153 379L152 376L150 373L149 369L148 366L146 361L145 357L143 352L142 347L140 341L137 335L134 326L130 315L126 304L122 293L117 281L113 268L108 256L103 243L98 231L92 219L86 207L79 196L71 186L62 177L53 168L44 161L32 157L21 155L10 154L0 154Z"
|
||||
|
||||
/**
|
||||
* Three overlapping waves. Each thick downstroke is outlined in the
|
||||
* background color so it reads as passing over the strokes behind it.
|
||||
@@ -47,9 +41,9 @@ function LosslessMark({
|
||||
}) {
|
||||
return (
|
||||
<Svg
|
||||
width={(MARK_HEIGHT * 544) / 271}
|
||||
width={LOSSLESS_WIDTH}
|
||||
height={MARK_HEIGHT}
|
||||
viewBox="28 154 544 271"
|
||||
viewBox={LOSSLESS_VIEW_BOX}
|
||||
>
|
||||
{LOSSLESS_STROKES.map(([peak, d], index) => (
|
||||
<Path
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
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"
|
||||
@@ -32,6 +32,7 @@ export type MediaAction =
|
||||
| "favorite"
|
||||
| "go-artist"
|
||||
| "go-album"
|
||||
| "remove-from-playlist"
|
||||
| "delete-playlist"
|
||||
|
||||
export type MediaNavigation = {
|
||||
@@ -54,6 +55,7 @@ export type MediaMenuConfig = {
|
||||
playlistLabel?: string
|
||||
favorited?: boolean
|
||||
showFavorite?: boolean
|
||||
showRemoveFromPlaylist?: boolean
|
||||
stationArtistId?: string
|
||||
navigation?: MediaNavigation
|
||||
share?: MediaShareContext
|
||||
@@ -76,6 +78,7 @@ const MEDIA_ACTION_ITEMS: {
|
||||
playlistLabel: string
|
||||
) => string
|
||||
image: NonNullable<MenuAction["image"]> & string
|
||||
destructive?: boolean
|
||||
}[] = [
|
||||
{
|
||||
action: "playlist",
|
||||
@@ -119,6 +122,12 @@ const MEDIA_ACTION_ITEMS: {
|
||||
`${favorited ? "Unfavorite" : "Favorite"}${countSuffix}`,
|
||||
image: "star",
|
||||
},
|
||||
{
|
||||
action: "remove-from-playlist",
|
||||
label: () => "Remove from Playlist",
|
||||
image: "minus.circle",
|
||||
destructive: true,
|
||||
},
|
||||
{
|
||||
action: "delete-playlist",
|
||||
label: () => "Delete Playlist",
|
||||
@@ -134,6 +143,10 @@ function isActionIncluded(
|
||||
return false
|
||||
}
|
||||
|
||||
if (action === "remove-from-playlist") {
|
||||
return config.showRemoveFromPlaylist === true
|
||||
}
|
||||
|
||||
if (config.includeActions) {
|
||||
return config.includeActions.includes(action)
|
||||
}
|
||||
@@ -190,6 +203,7 @@ export function buildMediaMenuActions(
|
||||
id: item.action,
|
||||
title: item.label(countSuffix, favorited, playlistLabel),
|
||||
image: item.action === "favorite" && favorited ? "star.fill" : item.image,
|
||||
...(item.destructive ? { attributes: { destructive: true } } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -324,6 +338,7 @@ const NativeContextMenuAction: ComponentType<{
|
||||
identifier: string
|
||||
title: string
|
||||
icon?: string
|
||||
destructive?: boolean
|
||||
onSelected: () => void
|
||||
}> | null =
|
||||
Platform.OS === "ios"
|
||||
@@ -377,6 +392,7 @@ function NativeMediaContextMenu({
|
||||
identifier={action.id ?? action.title}
|
||||
title={action.title}
|
||||
icon={typeof action.image === "string" ? action.image : undefined}
|
||||
destructive={action.attributes?.destructive}
|
||||
onSelected={() => handleAction(action.id as MediaAction)}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -25,6 +25,7 @@ const actionIcons = {
|
||||
favorite: "star-outline",
|
||||
"go-artist": "person-outline",
|
||||
"go-album": "disc-outline",
|
||||
"remove-from-playlist": "remove-circle-outline",
|
||||
"delete-playlist": "trash-outline",
|
||||
} satisfies Record<MediaAction, ComponentProps<typeof Ionicons>["name"]>
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ import {
|
||||
type SwipeRowGroup,
|
||||
} from "@/components/ios-swipe-to-remove-row"
|
||||
import { PlayerSymbol } from "@/components/player-symbol"
|
||||
import { usePlayback } from "@/contexts/playback"
|
||||
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { NowPlayingColors } from "@/lib/now-playing-colors"
|
||||
@@ -110,18 +110,16 @@ export function NowPlayingQueue({
|
||||
tablet?: boolean
|
||||
fadeColor?: string
|
||||
}) {
|
||||
const { queueSongIds, queueHistorySongIds, shuffleEnabled, repeatEnabled } =
|
||||
usePlaybackQueue()
|
||||
const {
|
||||
queueSongIds,
|
||||
queueHistorySongIds,
|
||||
shuffleEnabled,
|
||||
repeatEnabled,
|
||||
toggleShuffle,
|
||||
cycleRepeat,
|
||||
clearHistory,
|
||||
reorderQueue,
|
||||
skipToQueueIndex,
|
||||
skipToHistoryIndex,
|
||||
} = usePlayback()
|
||||
} = usePlaybackActions()
|
||||
const [viewportWidth, setViewportWidth] = useState(0)
|
||||
const swipeGroup = useSwipeRowGroup()
|
||||
const [scrollEnabled, setScrollEnabled] = useState(true)
|
||||
@@ -307,100 +305,126 @@ export function NowPlayingQueue({
|
||||
[drag]
|
||||
)
|
||||
|
||||
const renderItem = ({ item }: { item: QueueListItem }) => {
|
||||
switch (item.type) {
|
||||
case "history-header":
|
||||
return (
|
||||
<View style={styles.historyHeader}>
|
||||
<Text style={[styles.sectionTitle, { color: colors.foreground }]}>
|
||||
History
|
||||
</Text>
|
||||
<Pressable onPress={() => void clearHistory()} hitSlop={10}>
|
||||
<Text
|
||||
style={[styles.clear, { color: colors.secondaryForeground }]}
|
||||
>
|
||||
Clear
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
)
|
||||
case "history":
|
||||
return (
|
||||
<HistoryRow
|
||||
songId={item.songId}
|
||||
historyIndex={item.historyIndex}
|
||||
colors={colors}
|
||||
onPress={skipToHistoryIndex}
|
||||
/>
|
||||
)
|
||||
case "current":
|
||||
return <View style={styles.current}>{currentHeader}</View>
|
||||
case "controls":
|
||||
return (
|
||||
<View
|
||||
style={[
|
||||
styles.controls,
|
||||
{
|
||||
height: itemHeight(item),
|
||||
backgroundColor: tablet ? "transparent" : colors.background,
|
||||
},
|
||||
]}
|
||||
>
|
||||
{!tablet ? (
|
||||
<View style={styles.toggles}>
|
||||
<QueueToggle
|
||||
colors={colors}
|
||||
selected={shuffleEnabled}
|
||||
label="Shuffle"
|
||||
symbol="shuffle"
|
||||
fallback="shuffle"
|
||||
onPress={toggleShuffle}
|
||||
/>
|
||||
<QueueToggle
|
||||
colors={colors}
|
||||
selected={repeatEnabled !== "none"}
|
||||
label={repeatEnabled === "once" ? "Repeat one" : "Repeat"}
|
||||
symbol={repeatEnabled === "once" ? "repeat.1" : "repeat"}
|
||||
fallback="repeat"
|
||||
onPress={cycleRepeat}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
{item.showTitle ? (
|
||||
const lastIndex = queueSongIds.length - 1
|
||||
const renderItem = useCallback(
|
||||
({ item }: { item: QueueListItem }) => {
|
||||
switch (item.type) {
|
||||
case "history-header":
|
||||
return (
|
||||
<View style={styles.historyHeader}>
|
||||
<Text style={[styles.sectionTitle, { color: colors.foreground }]}>
|
||||
Continue Playing
|
||||
History
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
)
|
||||
case "upcoming":
|
||||
return (
|
||||
<UpcomingRow
|
||||
songId={item.songId}
|
||||
queueIndex={item.queueIndex}
|
||||
lastIndex={queueSongIds.length - 1}
|
||||
tablet={tablet}
|
||||
colors={colors}
|
||||
drag={drag}
|
||||
swipeGroup={swipeGroup}
|
||||
onPress={skipToQueueIndex}
|
||||
onRemove={handleRemove}
|
||||
onDragStart={handleDragStart}
|
||||
onDrop={handleDrop}
|
||||
/>
|
||||
)
|
||||
case "empty":
|
||||
return (
|
||||
<View style={[styles.empty, { height: item.height }]}>
|
||||
<Text
|
||||
style={[styles.emptyText, { color: colors.secondaryForeground }]}
|
||||
<Pressable onPress={() => void clearHistory()} hitSlop={10}>
|
||||
<Text
|
||||
style={[styles.clear, { color: colors.secondaryForeground }]}
|
||||
>
|
||||
Clear
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
)
|
||||
case "history":
|
||||
return (
|
||||
<HistoryRow
|
||||
songId={item.songId}
|
||||
historyIndex={item.historyIndex}
|
||||
colors={colors}
|
||||
onPress={skipToHistoryIndex}
|
||||
/>
|
||||
)
|
||||
case "current":
|
||||
return <View style={styles.current}>{currentHeader}</View>
|
||||
case "controls":
|
||||
return (
|
||||
<View
|
||||
style={[
|
||||
styles.controls,
|
||||
{
|
||||
height: itemHeight(item),
|
||||
backgroundColor: tablet ? "transparent" : colors.background,
|
||||
},
|
||||
]}
|
||||
>
|
||||
Nothing else is queued.
|
||||
</Text>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
}
|
||||
{!tablet ? (
|
||||
<View style={styles.toggles}>
|
||||
<QueueToggle
|
||||
colors={colors}
|
||||
selected={shuffleEnabled}
|
||||
label="Shuffle"
|
||||
symbol="shuffle"
|
||||
fallback="shuffle"
|
||||
onPress={toggleShuffle}
|
||||
/>
|
||||
<QueueToggle
|
||||
colors={colors}
|
||||
selected={repeatEnabled !== "none"}
|
||||
label={repeatEnabled === "once" ? "Repeat one" : "Repeat"}
|
||||
symbol={repeatEnabled === "once" ? "repeat.1" : "repeat"}
|
||||
fallback="repeat"
|
||||
onPress={cycleRepeat}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
{item.showTitle ? (
|
||||
<Text
|
||||
style={[styles.sectionTitle, { color: colors.foreground }]}
|
||||
>
|
||||
Continue Playing
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
)
|
||||
case "upcoming":
|
||||
return (
|
||||
<UpcomingRow
|
||||
songId={item.songId}
|
||||
queueIndex={item.queueIndex}
|
||||
lastIndex={lastIndex}
|
||||
tablet={tablet}
|
||||
colors={colors}
|
||||
drag={drag}
|
||||
swipeGroup={swipeGroup}
|
||||
onPress={skipToQueueIndex}
|
||||
onRemove={handleRemove}
|
||||
onDragStart={handleDragStart}
|
||||
onDrop={handleDrop}
|
||||
/>
|
||||
)
|
||||
case "empty":
|
||||
return (
|
||||
<View style={[styles.empty, { height: item.height }]}>
|
||||
<Text
|
||||
style={[
|
||||
styles.emptyText,
|
||||
{ color: colors.secondaryForeground },
|
||||
]}
|
||||
>
|
||||
Nothing else is queued.
|
||||
</Text>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
},
|
||||
[
|
||||
clearHistory,
|
||||
colors,
|
||||
currentHeader,
|
||||
cycleRepeat,
|
||||
drag,
|
||||
handleDragStart,
|
||||
handleDrop,
|
||||
handleRemove,
|
||||
lastIndex,
|
||||
repeatEnabled,
|
||||
shuffleEnabled,
|
||||
skipToHistoryIndex,
|
||||
skipToQueueIndex,
|
||||
swipeGroup,
|
||||
tablet,
|
||||
toggleShuffle,
|
||||
]
|
||||
)
|
||||
|
||||
return (
|
||||
<View
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useState, type ReactNode } from "react"
|
||||
import {
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
type StyleProp,
|
||||
type TextStyle,
|
||||
} from "react-native"
|
||||
|
||||
import { PlayerSlider } from "@/components/player-slider"
|
||||
import { usePlaybackActions, usePlaybackProgress } from "@/contexts/playback"
|
||||
import { formatDuration, formatRemainingDuration } from "@/lib/format"
|
||||
import type { NowPlayingColors } from "@/lib/now-playing-colors"
|
||||
|
||||
/**
|
||||
* Position slider with elapsed and remaining labels. The only player piece
|
||||
* subscribed to the playback clock, so the rest of the player stays still
|
||||
* while audio plays.
|
||||
*/
|
||||
export function PlayerProgress({
|
||||
colors,
|
||||
center,
|
||||
timeStyle,
|
||||
}: {
|
||||
colors: NowPlayingColors
|
||||
/** Shown centered between the time labels. */
|
||||
center?: ReactNode
|
||||
timeStyle?: StyleProp<TextStyle>
|
||||
}) {
|
||||
const { currentTime, duration } = usePlaybackProgress()
|
||||
const { seekTo } = usePlaybackActions()
|
||||
const [scrubTime, setScrubTime] = useState<number | null>(null)
|
||||
const time = scrubTime ?? currentTime
|
||||
const timeColor =
|
||||
scrubTime === null ? colors.secondaryForeground : colors.foreground
|
||||
|
||||
return (
|
||||
<>
|
||||
<PlayerSlider
|
||||
accessibilityLabel="Playback position"
|
||||
value={time}
|
||||
maximumValue={duration}
|
||||
fillColor={colors.sliderFill}
|
||||
activeFillColor={colors.foreground}
|
||||
trackColor={colors.sliderTrack}
|
||||
onValueChange={setScrubTime}
|
||||
onSlidingComplete={(value) => {
|
||||
void seekTo(value)
|
||||
setScrubTime(null)
|
||||
}}
|
||||
/>
|
||||
<View style={styles.row}>
|
||||
<Text style={[styles.time, timeStyle, { color: timeColor }]}>
|
||||
{formatDuration(time)}
|
||||
</Text>
|
||||
{center ? (
|
||||
<View style={styles.center} pointerEvents="none">
|
||||
{center}
|
||||
</View>
|
||||
) : null}
|
||||
<Text style={[styles.time, timeStyle, { color: timeColor }]}>
|
||||
{formatRemainingDuration(time, duration).replace("-", "−")}
|
||||
</Text>
|
||||
</View>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
marginTop: -4,
|
||||
},
|
||||
center: {
|
||||
position: "absolute",
|
||||
left: 0,
|
||||
right: 0,
|
||||
alignItems: "center",
|
||||
},
|
||||
time: { fontSize: 12, fontVariant: ["tabular-nums"] },
|
||||
})
|
||||
@@ -44,6 +44,8 @@ export const SongRow = memo(function SongRow({
|
||||
swipe?: {
|
||||
group: SwipeRowGroup
|
||||
onPlayNext: () => void
|
||||
onAddToQueue: () => void
|
||||
onRemove?: () => void
|
||||
backgroundColor: string
|
||||
}
|
||||
/** Album/playlist layout: the divider starts at the title, not the artwork. */
|
||||
@@ -101,10 +103,12 @@ export const SongRow = memo(function SongRow({
|
||||
? styles.insetRow
|
||||
: [styles.row, { borderBottomColor: divider }]
|
||||
const row =
|
||||
swipe && Platform.OS === "ios" ? (
|
||||
swipe && Platform.OS !== "web" ? (
|
||||
<SongSwipeRow
|
||||
group={swipe.group}
|
||||
onPlayNext={swipe.onPlayNext}
|
||||
onAddToQueue={swipe.onAddToQueue}
|
||||
onRemove={swipe.onRemove}
|
||||
backgroundColor={swipe.backgroundColor}
|
||||
onPress={onPress}
|
||||
style={rowStyle}
|
||||
@@ -150,6 +154,7 @@ export const SongListRow = memo(function SongListRow({
|
||||
palette,
|
||||
inset,
|
||||
swipe,
|
||||
removable,
|
||||
onPlay,
|
||||
onAction,
|
||||
}: {
|
||||
@@ -161,8 +166,12 @@ export const SongListRow = memo(function SongListRow({
|
||||
swipe?: {
|
||||
group: SwipeRowGroup
|
||||
onPlayNext: () => void
|
||||
onAddToQueue: () => void
|
||||
onRemove?: () => void
|
||||
backgroundColor: string
|
||||
}
|
||||
/** Shows "Remove from Playlist" in the context menu. */
|
||||
removable?: boolean
|
||||
onPlay: (song: BrowseSong) => void
|
||||
onAction: (song: BrowseSong, action: MediaAction) => void
|
||||
}) {
|
||||
@@ -190,6 +199,7 @@ export const SongListRow = memo(function SongListRow({
|
||||
stationArtistId: song.artist.id,
|
||||
favorited,
|
||||
playlistLabel,
|
||||
showRemoveFromPlaylist: removable,
|
||||
navigation: {
|
||||
artist: { id: song.artist.id },
|
||||
album: { id: song.album.id },
|
||||
|
||||
@@ -4,19 +4,15 @@ import { Stack } from "expo-router"
|
||||
|
||||
import { useDebouncedSearch } from "@/hooks/use-debounced-search"
|
||||
import { useThemeColors } from "@/lib/theme"
|
||||
import { filterSongs } from "@otunes/convex/client/song-search"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
|
||||
export function usePlaylistSearch(songs: BrowseSong[]) {
|
||||
const search = useDebouncedSearch()
|
||||
const filteredSongs = useMemo(() => {
|
||||
const query = search.searchQuery.toLowerCase()
|
||||
if (!query) return songs
|
||||
return songs.filter((song) =>
|
||||
[song.title, song.artist.name, song.album.title].some((value) =>
|
||||
value.toLowerCase().includes(query)
|
||||
)
|
||||
)
|
||||
}, [songs, search.searchQuery])
|
||||
const filteredSongs = useMemo(
|
||||
() => filterSongs(songs, search.searchQuery),
|
||||
[songs, search.searchQuery]
|
||||
)
|
||||
|
||||
return { ...search, filteredSongs }
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Image } from "expo-image"
|
||||
import { Pressable, StyleSheet, Text, View } from "react-native"
|
||||
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useProfileImageUrl } from "@/hooks/use-profile-image-url"
|
||||
import { initialsFromName } from "@/lib/format"
|
||||
import { radius, useThemeColors } from "@/lib/theme"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
@@ -13,6 +14,7 @@ export function ProfileHeaderButton() {
|
||||
const openSettings = useOpenSettings()
|
||||
const colors = useThemeColors()
|
||||
const user = useCachedQuery(api.auth.currentUser)
|
||||
const imageUrl = useProfileImageUrl(user?.image)
|
||||
|
||||
if (tabletLayout) return null
|
||||
|
||||
@@ -33,9 +35,9 @@ export function ProfileHeaderButton() {
|
||||
},
|
||||
]}
|
||||
>
|
||||
{user?.image ? (
|
||||
{imageUrl ? (
|
||||
<Image
|
||||
source={{ uri: user.image }}
|
||||
source={{ uri: imageUrl }}
|
||||
style={styles.image}
|
||||
contentFit="cover"
|
||||
/>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
import * as Haptics from "expo-haptics"
|
||||
import { SymbolView } from "expo-symbols"
|
||||
import {
|
||||
@@ -8,6 +9,7 @@ import {
|
||||
type ReactNode,
|
||||
} from "react"
|
||||
import {
|
||||
Platform,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
type StyleProp,
|
||||
@@ -26,14 +28,22 @@ import Animated, {
|
||||
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
|
||||
/** Width of each action when two share a side. */
|
||||
const PAIRED_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. */
|
||||
/**
|
||||
* A tap competes with the swipe so dragging a moving row never starts playback.
|
||||
* A full swipe commits the outer action: Add to Queue on the leading side, and
|
||||
* Remove on the trailing side when `onRemove` is set.
|
||||
*/
|
||||
export function SongSwipeRow({
|
||||
children,
|
||||
style,
|
||||
@@ -41,6 +51,8 @@ export function SongSwipeRow({
|
||||
group,
|
||||
onPress,
|
||||
onPlayNext,
|
||||
onAddToQueue,
|
||||
onRemove,
|
||||
}: {
|
||||
children: ReactNode
|
||||
style?: StyleProp<ViewStyle>
|
||||
@@ -48,7 +60,11 @@ export function SongSwipeRow({
|
||||
group: SwipeRowGroup
|
||||
onPress?: () => void
|
||||
onPlayNext: () => void
|
||||
onAddToQueue: () => void
|
||||
onRemove?: () => void
|
||||
}) {
|
||||
const hasRemove = !!onRemove
|
||||
const trailingWidth = hasRemove ? PAIRED_ACTION_WIDTH * 2 : ACTION_WIDTH
|
||||
const x = useSharedValue(0)
|
||||
const startX = useSharedValue(0)
|
||||
const width = useSharedValue(0)
|
||||
@@ -78,10 +94,11 @@ export function SongSwipeRow({
|
||||
const activate = useCallback(
|
||||
(side: number) => {
|
||||
close()
|
||||
if (side > 0) onPlayNext()
|
||||
// Download is intentionally a placeholder.
|
||||
if (side > 0) onAddToQueue()
|
||||
// Without Remove, the trailing action is the Download placeholder.
|
||||
else onRemove?.()
|
||||
},
|
||||
[close, onPlayNext]
|
||||
[close, onAddToQueue, onRemove]
|
||||
)
|
||||
const tapRow = useCallback(() => {
|
||||
if (open) close()
|
||||
@@ -105,7 +122,11 @@ export function SongSwipeRow({
|
||||
Math.min(width.value, startX.value + event.translationX)
|
||||
)
|
||||
const commit =
|
||||
Math.abs(x.value) > Math.max(ACTION_WIDTH, width.value * 0.55)
|
||||
Math.abs(x.value) >
|
||||
Math.max(
|
||||
x.value > 0 ? PAIRED_ACTION_WIDTH * 2 : trailingWidth,
|
||||
width.value * 0.55
|
||||
)
|
||||
if (commit !== committed.value) {
|
||||
committed.value = commit
|
||||
commitProgress.value = withSpring(commit ? 1 : 0, SPRING)
|
||||
@@ -124,10 +145,13 @@ export function SongSwipeRow({
|
||||
Math.abs(x.value) > 10 && projected * side > ACTION_WIDTH / 2
|
||||
? side
|
||||
: 0
|
||||
x.value = withSpring(target * ACTION_WIDTH, {
|
||||
...SPRING,
|
||||
velocity: event.velocityX,
|
||||
})
|
||||
x.value = withSpring(
|
||||
target * (target > 0 ? PAIRED_ACTION_WIDTH * 2 : trailingWidth),
|
||||
{
|
||||
...SPRING,
|
||||
velocity: event.velocityX,
|
||||
}
|
||||
)
|
||||
scheduleOnRN(settle, target)
|
||||
})
|
||||
.onFinalize((_event, success) => {
|
||||
@@ -152,18 +176,21 @@ export function SongSwipeRow({
|
||||
settle,
|
||||
startX,
|
||||
tapRow,
|
||||
trailingWidth,
|
||||
width,
|
||||
x,
|
||||
])
|
||||
|
||||
const rowStyle = useAnimatedStyle(() => ({
|
||||
transform: [{ translateX: x.value }],
|
||||
borderRadius: interpolate(
|
||||
Math.abs(x.value),
|
||||
[0, 40],
|
||||
[0, height.value / 2],
|
||||
Extrapolation.CLAMP
|
||||
),
|
||||
borderRadius: IS_ANDROID
|
||||
? 0
|
||||
: interpolate(
|
||||
Math.abs(x.value),
|
||||
[0, 40],
|
||||
[0, height.value / 2],
|
||||
Extrapolation.CLAMP
|
||||
),
|
||||
}))
|
||||
const fillStyle = useAnimatedStyle(() => ({
|
||||
opacity: interpolate(
|
||||
@@ -190,25 +217,60 @@ export function SongSwipeRow({
|
||||
open={open === 1}
|
||||
onPress={() => activate(1)}
|
||||
/>
|
||||
<SwipeAction
|
||||
side={1}
|
||||
secondary
|
||||
x={x}
|
||||
height={height}
|
||||
progress={commitProgress}
|
||||
open={open === 1}
|
||||
onPress={() => {
|
||||
close()
|
||||
onPlayNext()
|
||||
}}
|
||||
/>
|
||||
<SwipeAction
|
||||
side={-1}
|
||||
paired={hasRemove}
|
||||
remove={hasRemove}
|
||||
x={x}
|
||||
height={height}
|
||||
progress={commitProgress}
|
||||
open={open === -1}
|
||||
onPress={() => activate(-1)}
|
||||
/>
|
||||
{hasRemove && (
|
||||
<SwipeAction
|
||||
side={-1}
|
||||
secondary
|
||||
paired
|
||||
x={x}
|
||||
height={height}
|
||||
progress={commitProgress}
|
||||
open={open === -1}
|
||||
onPress={close}
|
||||
/>
|
||||
)}
|
||||
<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 === "playNext") activate(1)
|
||||
if (event.nativeEvent.actionName === "remove") activate(-1)
|
||||
if (event.nativeEvent.actionName === "addToQueue") activate(1)
|
||||
if (event.nativeEvent.actionName === "playNext") {
|
||||
close()
|
||||
onPlayNext()
|
||||
}
|
||||
}}
|
||||
style={[styles.row, { backgroundColor }, rowStyle]}
|
||||
>
|
||||
@@ -225,6 +287,9 @@ export function SongSwipeRow({
|
||||
|
||||
function SwipeAction({
|
||||
side,
|
||||
secondary = false,
|
||||
paired = side > 0,
|
||||
remove = false,
|
||||
x,
|
||||
height,
|
||||
progress,
|
||||
@@ -232,22 +297,48 @@ function SwipeAction({
|
||||
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(() => ({
|
||||
width: Math.max(0, x.value * side),
|
||||
}))
|
||||
const pillStyle = useAnimatedStyle(() => {
|
||||
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 - 20,
|
||||
interpolate(revealed, [24, ACTION_WIDTH, 220], [0, 62, 200])
|
||||
revealed - (paired ? 10 : 20),
|
||||
interpolate(
|
||||
revealed,
|
||||
[24, paired ? PAIRED_ACTION_WIDTH : ACTION_WIDTH, 220],
|
||||
[0, 62, 200]
|
||||
)
|
||||
)
|
||||
)
|
||||
const pillWidth =
|
||||
@@ -292,27 +383,65 @@ function SwipeAction({
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={side > 0 ? "Play Next" : "Download"}
|
||||
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: side > 0 ? "#6b5bff" : "#008dff" },
|
||||
{
|
||||
backgroundColor: remove
|
||||
? IS_ANDROID
|
||||
? "#d32f2f"
|
||||
: "#ff3b30"
|
||||
: side > 0
|
||||
? secondary
|
||||
? "#6b5bff"
|
||||
: "#f29943"
|
||||
: "#008dff",
|
||||
},
|
||||
pillStyle,
|
||||
]}
|
||||
>
|
||||
<Animated.View style={iconStyle}>
|
||||
<SymbolView
|
||||
name={
|
||||
side > 0
|
||||
? "text.line.first.and.arrowtriangle.forward"
|
||||
: "arrow.down"
|
||||
}
|
||||
size={22}
|
||||
tintColor="white"
|
||||
/>
|
||||
{IS_ANDROID ? (
|
||||
<Ionicons
|
||||
name={
|
||||
remove
|
||||
? "trash-outline"
|
||||
: side < 0
|
||||
? "arrow-down"
|
||||
: secondary
|
||||
? "play-forward"
|
||||
: "list"
|
||||
}
|
||||
size={22}
|
||||
color="white"
|
||||
/>
|
||||
) : (
|
||||
<SymbolView
|
||||
name={
|
||||
remove
|
||||
? "trash"
|
||||
: 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>
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
import { useTabletPlayerInsets } from "@/contexts/tablet-player-layout"
|
||||
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
import { MediaActionMenu } from "@/components/media-actions-sheet"
|
||||
import { MediaActionMenu } from "@/components/media-context-menu"
|
||||
import { PlayerSymbol } from "@/components/player-symbol"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
import { useEffect, useState, type ComponentProps, type ReactNode } from "react"
|
||||
import {
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
useWindowDimensions,
|
||||
} from "react-native"
|
||||
import { Pressable, StyleSheet, View, useWindowDimensions } from "react-native"
|
||||
import Animated, {
|
||||
Easing,
|
||||
ReduceMotion,
|
||||
@@ -14,7 +8,7 @@ import Animated, {
|
||||
useSharedValue,
|
||||
withTiming,
|
||||
} from "react-native-reanimated"
|
||||
import { GestureDetector, Gesture } from "react-native-gesture-handler"
|
||||
import { GestureDetector, type Gesture } from "react-native-gesture-handler"
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context"
|
||||
import { useRouter } from "expo-router"
|
||||
import { StatusBar } from "expo-status-bar"
|
||||
@@ -22,12 +16,12 @@ import { StatusBar } from "expo-status-bar"
|
||||
import { AudioOutputButton } from "@/components/audio-output-button"
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
import { NowPlayingQueue } from "@/components/now-playing-queue"
|
||||
import { PlayerProgress } from "@/components/player-progress"
|
||||
import { PlayerSlider } from "@/components/player-slider"
|
||||
import { PlayerSymbol } from "@/components/player-symbol"
|
||||
import { usePlayback } from "@/contexts/playback"
|
||||
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { useSystemVolume } from "@/hooks/use-system-volume"
|
||||
import { formatDuration, formatRemainingDuration } from "@/lib/format"
|
||||
import type { NowPlayingColors } from "@/lib/now-playing-colors"
|
||||
import { albumCoverUrl } from "@/lib/urls"
|
||||
|
||||
@@ -42,7 +36,7 @@ export function TabletNowPlaying({
|
||||
colors,
|
||||
backgroundStyle,
|
||||
dismissStyle,
|
||||
dismissGesture,
|
||||
dismissGestures,
|
||||
showQueue,
|
||||
toggleQueue,
|
||||
metadata,
|
||||
@@ -50,7 +44,10 @@ export function TabletNowPlaying({
|
||||
colors: NowPlayingColors
|
||||
backgroundStyle: ComponentProps<typeof Animated.View>["style"]
|
||||
dismissStyle: ComponentProps<typeof Animated.View>["style"]
|
||||
dismissGesture: () => ReturnType<typeof Gesture.Pan>
|
||||
dismissGestures: {
|
||||
handle: ReturnType<typeof Gesture.Pan>
|
||||
artwork: ReturnType<typeof Gesture.Pan>
|
||||
}
|
||||
showQueue: boolean
|
||||
toggleQueue: () => void
|
||||
metadata: ReactNode
|
||||
@@ -59,22 +56,11 @@ export function TabletNowPlaying({
|
||||
const insets = useSafeAreaInsets()
|
||||
const { width, height } = useWindowDimensions()
|
||||
const { config } = useServerConfig()
|
||||
const {
|
||||
currentSong,
|
||||
currentTime,
|
||||
duration,
|
||||
isPlaying,
|
||||
setIsPlaying,
|
||||
seekTo,
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
shuffleEnabled,
|
||||
repeatEnabled,
|
||||
toggleShuffle,
|
||||
cycleRepeat,
|
||||
} = usePlayback()
|
||||
const { currentSong, isPlaying, shuffleEnabled, repeatEnabled } =
|
||||
usePlaybackQueue()
|
||||
const { setIsPlaying, skipNext, skipPrevious, toggleShuffle, cycleRepeat } =
|
||||
usePlaybackActions()
|
||||
const { volume, setVolume, available: volumeAvailable } = useSystemVolume()
|
||||
const [scrubTime, setScrubTime] = useState<number | null>(null)
|
||||
const [queueHeight, setQueueHeight] = useState(0)
|
||||
const wideLayout = width >= 700
|
||||
const sideBySide = showQueue && wideLayout
|
||||
@@ -113,7 +99,6 @@ export function TabletNowPlaying({
|
||||
opacity: interpolate(progress.value, [0, 0.15, 1], [0, 0, 1]),
|
||||
transform: [{ translateX: (1 - progress.value) * 48 }],
|
||||
}))
|
||||
const time = scrubTime ?? currentTime
|
||||
if (!currentSong || !config) return null
|
||||
const control = (
|
||||
label: string,
|
||||
@@ -150,7 +135,7 @@ export function TabletNowPlaying({
|
||||
return (
|
||||
<Animated.View style={[styles.root, backgroundStyle, dismissStyle]}>
|
||||
<StatusBar style={colors.isDark ? "light" : "dark"} />
|
||||
<GestureDetector gesture={dismissGesture()}>
|
||||
<GestureDetector gesture={dismissGestures.handle}>
|
||||
<Pressable
|
||||
onPress={() => router.back()}
|
||||
accessibilityRole="button"
|
||||
@@ -164,7 +149,7 @@ export function TabletNowPlaying({
|
||||
</GestureDetector>
|
||||
<View style={styles.body}>
|
||||
<Animated.View style={[styles.main, mainMotion]}>
|
||||
<GestureDetector gesture={dismissGesture()}>
|
||||
<GestureDetector gesture={dismissGestures.artwork}>
|
||||
<View style={styles.artworkArea}>
|
||||
<Animated.View style={artworkMotion}>
|
||||
<CoverImage
|
||||
@@ -177,31 +162,7 @@ export function TabletNowPlaying({
|
||||
</GestureDetector>
|
||||
<Animated.View style={[styles.controls, controlsMotion]}>
|
||||
<View style={styles.meta}>{metadata}</View>
|
||||
<PlayerSlider
|
||||
accessibilityLabel="Playback position"
|
||||
value={time}
|
||||
maximumValue={duration}
|
||||
fillColor={colors.sliderFill}
|
||||
activeFillColor={colors.foreground}
|
||||
trackColor={colors.sliderTrack}
|
||||
onValueChange={setScrubTime}
|
||||
onSlidingComplete={(value) => {
|
||||
void seekTo(value)
|
||||
setScrubTime(null)
|
||||
}}
|
||||
/>
|
||||
<View style={styles.times}>
|
||||
<Text
|
||||
style={[styles.time, { color: colors.secondaryForeground }]}
|
||||
>
|
||||
{formatDuration(time)}
|
||||
</Text>
|
||||
<Text
|
||||
style={[styles.time, { color: colors.secondaryForeground }]}
|
||||
>
|
||||
{formatRemainingDuration(time, duration).replace("-", "−")}
|
||||
</Text>
|
||||
</View>
|
||||
<PlayerProgress colors={colors} />
|
||||
<View style={styles.transport}>
|
||||
{control(
|
||||
"Shuffle",
|
||||
@@ -376,12 +337,6 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
controls: { width: "100%", maxWidth: 456, paddingHorizontal: 0 },
|
||||
meta: { height: 48 },
|
||||
times: {
|
||||
flexDirection: "row",
|
||||
justifyContent: "space-between",
|
||||
marginTop: -4,
|
||||
},
|
||||
time: { fontSize: 12, fontVariant: ["tabular-nums"] },
|
||||
transport: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useIsFocused } from "expo-router"
|
||||
import { Platform, type ViewProps } from "react-native"
|
||||
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useProfileImageUrl } from "@/hooks/use-profile-image-url"
|
||||
import { initialsFromName } from "@/lib/format"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
@@ -22,6 +23,7 @@ const NativeSidebar =
|
||||
|
||||
export function TabletSidebar() {
|
||||
const user = useCachedQuery(api.auth.currentUser)
|
||||
const imageUrl = useProfileImageUrl(user?.image)
|
||||
const openSettings = useOpenSettings()
|
||||
const active = useIsFocused()
|
||||
|
||||
@@ -31,7 +33,7 @@ export function TabletSidebar() {
|
||||
style={{ position: "absolute", width: 0, height: 0 }}
|
||||
accountName={user?.name ?? "Account"}
|
||||
initials={initialsFromName(user?.name ?? "Me")}
|
||||
imageURL={user?.image}
|
||||
imageURL={imageUrl}
|
||||
active={active}
|
||||
onProfilePress={openSettings}
|
||||
/>
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import { createContext, useContext, type ReactNode } from "react"
|
||||
import { createContext, useContext, useMemo, type ReactNode } from "react"
|
||||
|
||||
type ConvexAuthSessionContextValue = {
|
||||
invalidateSession: () => Promise<void>
|
||||
}
|
||||
|
||||
const ConvexAuthSessionContext = createContext<ConvexAuthSessionContextValue | null>(
|
||||
null
|
||||
)
|
||||
const ConvexAuthSessionContext =
|
||||
createContext<ConvexAuthSessionContextValue | null>(null)
|
||||
|
||||
export function ConvexAuthSessionProvider({
|
||||
children,
|
||||
@@ -15,8 +14,9 @@ export function ConvexAuthSessionProvider({
|
||||
children: ReactNode
|
||||
invalidateSession: () => Promise<void>
|
||||
}) {
|
||||
const value = useMemo(() => ({ invalidateSession }), [invalidateSession])
|
||||
return (
|
||||
<ConvexAuthSessionContext.Provider value={{ invalidateSession }}>
|
||||
<ConvexAuthSessionContext.Provider value={value}>
|
||||
{children}
|
||||
</ConvexAuthSessionContext.Provider>
|
||||
)
|
||||
@@ -25,7 +25,9 @@ export function ConvexAuthSessionProvider({
|
||||
export function useInvalidateAuthSession() {
|
||||
const context = useContext(ConvexAuthSessionContext)
|
||||
if (!context) {
|
||||
throw new Error("useInvalidateAuthSession must be used within ConvexAppProvider")
|
||||
throw new Error(
|
||||
"useInvalidateAuthSession must be used within ConvexAuthSessionProvider"
|
||||
)
|
||||
}
|
||||
return context
|
||||
}
|
||||
@@ -12,22 +12,28 @@ import {
|
||||
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { favoriteOptimisticUpdates } from "@otunes/convex/client/favorites"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { showError } from "@/lib/toast"
|
||||
|
||||
/**
|
||||
* `useMutation(...).withOptimisticUpdate(...)` with a stable identity. The
|
||||
* update is captured on first render, so it must not close over render state.
|
||||
* `useMutation(...).withOptimisticUpdate(...)` with a stable identity. Pass a
|
||||
* module-level update so it does not change between renders.
|
||||
*/
|
||||
function useOptimisticMutation<Mutation extends FunctionReference<"mutation">>(
|
||||
mutation: Mutation,
|
||||
optimisticUpdate: OptimisticUpdate<FunctionArgs<Mutation>>
|
||||
): ReactMutation<Mutation> {
|
||||
const base = useMutation(mutation)
|
||||
const updateRef = useRef(optimisticUpdate)
|
||||
return useMemo(() => base.withOptimisticUpdate(updateRef.current), [base])
|
||||
return useMemo(
|
||||
() => base.withOptimisticUpdate(optimisticUpdate),
|
||||
[base, optimisticUpdate]
|
||||
)
|
||||
}
|
||||
|
||||
type FavoriteTables = { song: "songs"; album: "albums"; artist: "artists" }
|
||||
export type FavoriteKind = keyof FavoriteTables
|
||||
|
||||
type FavoritesContextValue = {
|
||||
isSongFavorite: (songId: string) => boolean
|
||||
isAlbumFavorite: (albumId: string) => boolean
|
||||
@@ -36,6 +42,20 @@ type FavoritesContextValue = {
|
||||
toggleAlbumFavorite: (albumId: Id<"albums">) => Promise<void>
|
||||
toggleArtistFavorite: (artistId: Id<"artists">) => Promise<void>
|
||||
favoriteSongs: (songIds: Id<"songs">[]) => Promise<void>
|
||||
/** Idempotent; throws so callers like Siri can report failures. */
|
||||
setFavorite: <Kind extends FavoriteKind>(
|
||||
kind: Kind,
|
||||
id: Id<FavoriteTables[Kind]>,
|
||||
favorite: boolean
|
||||
) => Promise<void>
|
||||
/** Throws so callers like Siri can report failures. */
|
||||
addFavoriteSongs: (songIds: Id<"songs">[]) => Promise<void>
|
||||
}
|
||||
|
||||
function showFavoritesError(error: unknown) {
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to update favorites"
|
||||
)
|
||||
}
|
||||
|
||||
const FavoritesContext = createContext<FavoritesContextValue | null>(null)
|
||||
@@ -52,110 +72,31 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
|
||||
const favorites = useCachedQuery(api.favorites.getUserFavorites)
|
||||
const favoriteSong = useOptimisticMutation(
|
||||
api.favorites.favoriteSong,
|
||||
(store, { songId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current || current.favoriteSongs.includes(songId)) return
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
favoriteSongs: [...current.favoriteSongs, songId],
|
||||
}
|
||||
)
|
||||
}
|
||||
favoriteOptimisticUpdates.favoriteSong
|
||||
)
|
||||
const unfavoriteSong = useOptimisticMutation(
|
||||
api.favorites.unfavoriteSong,
|
||||
(store, { songId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current) return
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
favoriteSongs: current.favoriteSongs.filter((id) => id !== songId),
|
||||
}
|
||||
)
|
||||
}
|
||||
favoriteOptimisticUpdates.unfavoriteSong
|
||||
)
|
||||
const favoriteAlbum = useOptimisticMutation(
|
||||
api.favorites.favoriteAlbum,
|
||||
(store, { albumId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current || current.favoriteAlbums.includes(albumId)) return
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
favoriteAlbums: [...current.favoriteAlbums, albumId],
|
||||
}
|
||||
)
|
||||
}
|
||||
favoriteOptimisticUpdates.favoriteAlbum
|
||||
)
|
||||
const unfavoriteAlbum = useOptimisticMutation(
|
||||
api.favorites.unfavoriteAlbum,
|
||||
(store, { albumId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current) return
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
favoriteAlbums: current.favoriteAlbums.filter((id) => id !== albumId),
|
||||
}
|
||||
)
|
||||
}
|
||||
favoriteOptimisticUpdates.unfavoriteAlbum
|
||||
)
|
||||
const favoriteArtist = useOptimisticMutation(
|
||||
api.favorites.favoriteArtist,
|
||||
(store, { artistId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current || current.favoriteArtists.includes(artistId)) return
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
favoriteArtists: [...current.favoriteArtists, artistId],
|
||||
}
|
||||
)
|
||||
}
|
||||
favoriteOptimisticUpdates.favoriteArtist
|
||||
)
|
||||
const unfavoriteArtist = useOptimisticMutation(
|
||||
api.favorites.unfavoriteArtist,
|
||||
(store, { artistId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current) return
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
favoriteArtists: current.favoriteArtists.filter(
|
||||
(id) => id !== artistId
|
||||
),
|
||||
}
|
||||
)
|
||||
}
|
||||
favoriteOptimisticUpdates.unfavoriteArtist
|
||||
)
|
||||
const favoriteSongsMutation = useOptimisticMutation(
|
||||
api.favorites.favoriteSongs,
|
||||
(store, { songIds }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current) return
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
favoriteSongs: [...new Set([...current.favoriteSongs, ...songIds])],
|
||||
}
|
||||
)
|
||||
}
|
||||
favoriteOptimisticUpdates.favoriteSongs
|
||||
)
|
||||
|
||||
const songIds = useMemo(
|
||||
@@ -173,70 +114,72 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
|
||||
const idsRef = useRef({ songIds, albumIds, artistIds })
|
||||
idsRef.current = { songIds, albumIds, artistIds }
|
||||
|
||||
const toggleSongFavorite = useCallback(
|
||||
async (songId: Id<"songs">) => {
|
||||
try {
|
||||
if (idsRef.current.songIds.has(songId)) {
|
||||
await unfavoriteSong({ songId })
|
||||
} else {
|
||||
await favoriteSong({ songId })
|
||||
}
|
||||
} catch (error) {
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to update favorites"
|
||||
)
|
||||
const setFavorite = useCallback(
|
||||
async <Kind extends FavoriteKind>(
|
||||
kind: Kind,
|
||||
id: Id<FavoriteTables[Kind]>,
|
||||
favorite: boolean
|
||||
) => {
|
||||
if (kind === "song") {
|
||||
const songId = id as Id<"songs">
|
||||
await (favorite ? favoriteSong : unfavoriteSong)({ songId })
|
||||
} else if (kind === "album") {
|
||||
const albumId = id as Id<"albums">
|
||||
await (favorite ? favoriteAlbum : unfavoriteAlbum)({ albumId })
|
||||
} else {
|
||||
const artistId = id as Id<"artists">
|
||||
await (favorite ? favoriteArtist : unfavoriteArtist)({ artistId })
|
||||
}
|
||||
},
|
||||
[favoriteSong, unfavoriteSong]
|
||||
[
|
||||
favoriteSong,
|
||||
unfavoriteSong,
|
||||
favoriteAlbum,
|
||||
unfavoriteAlbum,
|
||||
favoriteArtist,
|
||||
unfavoriteArtist,
|
||||
]
|
||||
)
|
||||
|
||||
const toggleSongFavorite = useCallback(
|
||||
(songId: Id<"songs">) =>
|
||||
setFavorite("song", songId, !idsRef.current.songIds.has(songId)).catch(
|
||||
showFavoritesError
|
||||
),
|
||||
[setFavorite]
|
||||
)
|
||||
|
||||
const toggleAlbumFavorite = useCallback(
|
||||
async (albumId: Id<"albums">) => {
|
||||
try {
|
||||
if (idsRef.current.albumIds.has(albumId)) {
|
||||
await unfavoriteAlbum({ albumId })
|
||||
} else {
|
||||
await favoriteAlbum({ albumId })
|
||||
}
|
||||
} catch (error) {
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to update favorites"
|
||||
)
|
||||
}
|
||||
},
|
||||
[favoriteAlbum, unfavoriteAlbum]
|
||||
(albumId: Id<"albums">) =>
|
||||
setFavorite(
|
||||
"album",
|
||||
albumId,
|
||||
!idsRef.current.albumIds.has(albumId)
|
||||
).catch(showFavoritesError),
|
||||
[setFavorite]
|
||||
)
|
||||
|
||||
const toggleArtistFavorite = useCallback(
|
||||
async (artistId: Id<"artists">) => {
|
||||
try {
|
||||
if (idsRef.current.artistIds.has(artistId)) {
|
||||
await unfavoriteArtist({ artistId })
|
||||
} else {
|
||||
await favoriteArtist({ artistId })
|
||||
}
|
||||
} catch (error) {
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to update favorites"
|
||||
)
|
||||
}
|
||||
(artistId: Id<"artists">) =>
|
||||
setFavorite(
|
||||
"artist",
|
||||
artistId,
|
||||
!idsRef.current.artistIds.has(artistId)
|
||||
).catch(showFavoritesError),
|
||||
[setFavorite]
|
||||
)
|
||||
|
||||
const addFavoriteSongs = useCallback(
|
||||
async (ids: Id<"songs">[]) => {
|
||||
const unique = [...new Set(ids)]
|
||||
if (unique.length > 0) await favoriteSongsMutation({ songIds: unique })
|
||||
},
|
||||
[favoriteArtist, unfavoriteArtist]
|
||||
[favoriteSongsMutation]
|
||||
)
|
||||
|
||||
const favoriteSongs = useCallback(
|
||||
async (ids: Id<"songs">[]) => {
|
||||
const unique = [...new Set(ids)]
|
||||
if (unique.length === 0) return
|
||||
try {
|
||||
await favoriteSongsMutation({ songIds: unique })
|
||||
} catch (error) {
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to update favorites"
|
||||
)
|
||||
}
|
||||
},
|
||||
[favoriteSongsMutation]
|
||||
(ids: Id<"songs">[]) => addFavoriteSongs(ids).catch(showFavoritesError),
|
||||
[addFavoriteSongs]
|
||||
)
|
||||
|
||||
const value = useMemo(
|
||||
@@ -248,6 +191,8 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
|
||||
toggleAlbumFavorite,
|
||||
toggleArtistFavorite,
|
||||
favoriteSongs,
|
||||
setFavorite,
|
||||
addFavoriteSongs,
|
||||
}),
|
||||
[
|
||||
songIds,
|
||||
@@ -257,6 +202,8 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
|
||||
toggleAlbumFavorite,
|
||||
toggleArtistFavorite,
|
||||
favoriteSongs,
|
||||
setFavorite,
|
||||
addFavoriteSongs,
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useAuthToken } from "@convex-dev/auth/react"
|
||||
import { userIdFromToken } from "@otunes/convex/client/auth-token"
|
||||
import { createContext, useContext, useMemo, type ReactNode } from "react"
|
||||
|
||||
import { loadPersistentCache } from "@/lib/persistent-cache"
|
||||
@@ -9,21 +10,6 @@ const CacheScopeContext = createContext(ANONYMOUS_CACHE_SCOPE)
|
||||
|
||||
void loadPersistentCache()
|
||||
|
||||
function userIdFromToken(token: string | null) {
|
||||
const payload = token?.split(".")[1]
|
||||
if (!payload) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"))
|
||||
const subject = (JSON.parse(json) as { sub?: unknown }).sub
|
||||
return typeof subject === "string" ? (subject.split("|")[0] ?? null) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** Namespaces persisted client data by server and signed-in user. */
|
||||
export function PersistentCacheProvider({
|
||||
serverUrl,
|
||||
|
||||
+178
-827
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,148 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/** Forget in-memory swatches so covers are re-extracted. */
|
||||
function clear() {
|
||||
swatchesByKey.clear()
|
||||
pending.clear()
|
||||
}
|
||||
|
||||
return { prefetch, usePalette, clear }
|
||||
}
|
||||
|
||||
function sameSwatches(a: unknown, b: unknown) {
|
||||
return a === b || JSON.stringify(a) === JSON.stringify(b)
|
||||
}
|
||||
@@ -1,161 +1,59 @@
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import {
|
||||
artworkColorsEnabled,
|
||||
useArtworkColorsEnabled,
|
||||
} from "@/lib/artwork-color-preference"
|
||||
createCoverPaletteSource,
|
||||
type CoverPaletteResult,
|
||||
} from "@/hooks/cover-palette-source"
|
||||
import {
|
||||
clearLegacyCoverPaletteCache,
|
||||
prefetchLegacyCoverPalette,
|
||||
useLegacyCoverPalette,
|
||||
} from "@/hooks/use-legacy-cover-palette"
|
||||
import { extractCoverSwatches } from "@/lib/artwork-colors"
|
||||
|
||||
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"
|
||||
loadArtworkColorsEnabled,
|
||||
useArtworkColorsEnabled,
|
||||
} from "@/lib/artwork-color-preference"
|
||||
import { extractCoverSwatches } from "@/lib/artwork-colors"
|
||||
import { deriveCoverPalette, type CoverSwatches } from "@/lib/cover-palette"
|
||||
import { clearCachePrefix } from "@/lib/persistent-cache"
|
||||
|
||||
// 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 { COVER_PALETTE_WAIT_MS } from "@/hooks/cover-palette-source"
|
||||
|
||||
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
|
||||
}
|
||||
const region = createCoverPaletteSource<CoverSwatches>({
|
||||
cacheKey: (colorSourceUri) => `palette:v2:${colorSourceUri}`,
|
||||
extract: extractCoverSwatches,
|
||||
derive: (swatches) => deriveCoverPalette(swatches),
|
||||
})
|
||||
|
||||
/**
|
||||
* Forget every extracted palette, in memory and on device, so covers are
|
||||
* re-extracted. Both algorithms share the `palette:` cache prefix.
|
||||
* re-extracted. Both pipelines share the `palette:` cache prefix.
|
||||
*/
|
||||
export function clearCoverPaletteCache() {
|
||||
swatchesByKey.clear()
|
||||
pending.clear()
|
||||
region.clear()
|
||||
clearLegacyCoverPaletteCache()
|
||||
clearCachePrefix("palette")
|
||||
}
|
||||
|
||||
/** Warm visible artwork colors before a detail page is pushed. */
|
||||
export function prefetchCoverPalette(uri: string) {
|
||||
if (!artworkColorsEnabled()) {
|
||||
prefetchLegacyCoverPalette(uri)
|
||||
return
|
||||
}
|
||||
const key = withCoverImageSize(uri, 64)
|
||||
if (cachedSwatches(key) !== undefined) return
|
||||
void extractSwatches(key)
|
||||
void loadArtworkColorsEnabled().then((enabled) =>
|
||||
enabled ? region.prefetch(uri) : prefetchLegacyCoverPalette(uri)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Colors for a screen tinted by `uri`'s cover art, from whichever pipeline the
|
||||
* device preference selects. Nothing is extracted until the preference loads,
|
||||
* and the screen stays unsettled meanwhile so it doesn't flash theme colors.
|
||||
*/
|
||||
function useRegionCoverPalette(
|
||||
export function useCoverPalette(
|
||||
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)
|
||||
: null
|
||||
return fromArt ?? themeCoverPalette(theme, isDark)
|
||||
}, [hasCover, isDark, swatches, theme])
|
||||
|
||||
return {
|
||||
palette,
|
||||
settled:
|
||||
!key || hasCover === false || swatches !== undefined || waitedKey === key,
|
||||
}
|
||||
}
|
||||
|
||||
/** Switch both extraction and palette derivation without mixing their caches. */
|
||||
export function useCoverPalette(uri: string, hasCover: boolean | undefined) {
|
||||
): CoverPaletteResult {
|
||||
const enabled = useArtworkColorsEnabled()
|
||||
const region = useRegionCoverPalette(enabled ? uri : "", hasCover)
|
||||
const legacy = useLegacyCoverPalette(enabled ? "" : uri, hasCover)
|
||||
return enabled ? region : legacy
|
||||
const current = region.usePalette(enabled === true ? uri : "", hasCover)
|
||||
const legacy = useLegacyCoverPalette(enabled === false ? uri : "", hasCover)
|
||||
if (enabled === undefined) {
|
||||
return { palette: current.palette, settled: !uri || hasCover === false }
|
||||
}
|
||||
return enabled ? current : legacy
|
||||
}
|
||||
@@ -1,29 +1,14 @@
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { getColors, type ImageColorsResult } from "react-native-image-colors"
|
||||
|
||||
import { createCoverPaletteSource } from "@/hooks/cover-palette-source"
|
||||
import {
|
||||
themeCoverPalette,
|
||||
type CoverPalette,
|
||||
} from "@/lib/cover-palette"
|
||||
import { deriveCoverPalette, type LegacyCoverSwatches as CoverSwatches } from "@/lib/legacy-cover-palette"
|
||||
import { clearCachePrefix, 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
|
||||
deriveCoverPalette,
|
||||
type LegacyCoverSwatches as CoverSwatches,
|
||||
} from "@/lib/legacy-cover-palette"
|
||||
|
||||
// image-colors substitutes this for swatches it couldn't find.
|
||||
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)[]) {
|
||||
return colors.filter(
|
||||
(color): color is string => !!color && color.toLowerCase() !== MISSING
|
||||
@@ -59,127 +44,26 @@ function toSwatches(result: ImageColorsResult): CoverSwatches | null {
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
const cached = readCache<CoverSwatches>(cacheKey(key))
|
||||
const legacy = createCoverPaletteSource<CoverSwatches>({
|
||||
cacheKey: (colorSourceUri) => `palette:${colorSourceUri}`,
|
||||
extract: (key) =>
|
||||
getColors(key, {
|
||||
fallback: MISSING,
|
||||
cache: true,
|
||||
key,
|
||||
quality: "low",
|
||||
pixelSpacing: 4,
|
||||
}).then(toSwatches),
|
||||
derive: deriveCoverPalette,
|
||||
// Discard the background-only entries written by the tablet palette experiment.
|
||||
return cached && (!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
|
||||
}
|
||||
isValidCache: (cached) =>
|
||||
Array.isArray(cached.text) && Array.isArray(cached.accent),
|
||||
})
|
||||
|
||||
/** Warm visible artwork colors before a detail page is pushed. */
|
||||
/** Forget extracted legacy swatches, in memory and on device. */
|
||||
export function clearLegacyCoverPaletteCache() {
|
||||
swatchesByKey.clear()
|
||||
pending.clear()
|
||||
clearCachePrefix("palette")
|
||||
}
|
||||
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,
|
||||
}
|
||||
}
|
||||
export const clearLegacyCoverPaletteCache = legacy.clear
|
||||
@@ -0,0 +1,725 @@
|
||||
import { atmosEnabled } 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 durationRef = useRef(duration)
|
||||
durationRef.current = duration
|
||||
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, atmosEnabled(user)])
|
||||
: ""
|
||||
|
||||
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]
|
||||
)
|
||||
|
||||
// Reads duration from a ref so seekTo, and every action built on it, stays
|
||||
// stable across track changes.
|
||||
const seekTo = useCallback(async (seconds: number) => {
|
||||
const playlist = playlistRef.current
|
||||
if (!playlist) return
|
||||
const maxDuration = playlist.duration || durationRef.current || 0
|
||||
const clamped = Math.max(0, Math.min(seconds, maxDuration))
|
||||
await playlist.seekTo(clamped)
|
||||
currentTimeRef.current = clamped
|
||||
setCurrentTime(clamped)
|
||||
}, [])
|
||||
|
||||
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}:${atmosEnabled(user)}:${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,
|
||||
atmosEnabled(user)
|
||||
)
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
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 }
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { publishMusicCatalog } from "@/lib/app-intents"
|
||||
export const FAVORITES_PLAYLIST_ID = "otunes:favorites"
|
||||
|
||||
const HANDLED_KEY = "otunes:handled-app-intents"
|
||||
const CATALOG_CURSORS_KEY = "otunes:app-intent-catalog-cursors"
|
||||
const MAX_HANDLED = 200
|
||||
|
||||
const CATALOG_KINDS = [
|
||||
@@ -20,6 +21,7 @@ export async function clearAppIntentCatalogs() {
|
||||
return
|
||||
}
|
||||
const results = await Promise.allSettled([
|
||||
AsyncStorage.removeItem(CATALOG_CURSORS_KEY),
|
||||
AppIntents.deleteDonationsAsync({ intent: "playMusic" }),
|
||||
AppIntents.clearPendingInvocationsAsync(),
|
||||
...CATALOG_KINDS.map((kind) => publishMusicCatalog(kind, [])),
|
||||
@@ -28,6 +30,39 @@ export async function clearAppIntentCatalogs() {
|
||||
if (failed?.status === "rejected") throw failed.reason
|
||||
}
|
||||
|
||||
/**
|
||||
* Server `head` values the disk catalog is synced to, per library kind. A
|
||||
* missing kind means it has never synced and needs a full download.
|
||||
*/
|
||||
export type CatalogCursors = Partial<
|
||||
Record<"song" | "album" | "artist", number>
|
||||
>
|
||||
|
||||
/** Cursors for `scope`; another server or user's cursors read as empty. */
|
||||
export async function loadCatalogCursors(
|
||||
scope: string
|
||||
): Promise<CatalogCursors> {
|
||||
try {
|
||||
const raw = await AsyncStorage.getItem(CATALOG_CURSORS_KEY)
|
||||
const parsed = raw
|
||||
? (JSON.parse(raw) as { scope?: unknown; cursors?: CatalogCursors })
|
||||
: null
|
||||
return parsed?.scope === scope ? (parsed.cursors ?? {}) : {}
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveCatalogCursors(
|
||||
scope: string,
|
||||
cursors: CatalogCursors
|
||||
) {
|
||||
await AsyncStorage.setItem(
|
||||
CATALOG_CURSORS_KEY,
|
||||
JSON.stringify({ scope, cursors })
|
||||
)
|
||||
}
|
||||
|
||||
export async function loadHandledIntentIds() {
|
||||
const raw = await AsyncStorage.getItem(HANDLED_KEY)
|
||||
if (!raw) {
|
||||
|
||||
@@ -50,6 +50,13 @@ export function publishMusicCatalog(kind: string, entities: AppIntentEntity[]) {
|
||||
return write
|
||||
}
|
||||
|
||||
/** The full disk catalog for `kind`, as last published. */
|
||||
export async function readMusicCatalog(kind: string) {
|
||||
await publishing.catch(() => undefined)
|
||||
if (!native || !AppIntents.isAvailable()) return []
|
||||
return JSON.parse(await native.catalogJSON(kind)) as AppIntentEntity[]
|
||||
}
|
||||
|
||||
export async function completeMusicInvocation(
|
||||
token: string,
|
||||
error: string | null
|
||||
|
||||
@@ -3,8 +3,8 @@ import { useSyncExternalStore } from "react"
|
||||
|
||||
const STORAGE_KEY = "otunes:artwork-colors"
|
||||
const listeners = new Set<() => void>()
|
||||
let enabled = true
|
||||
let loaded = false
|
||||
// Undefined until storage has been read, so callers never act on a guess.
|
||||
let enabled: boolean | undefined
|
||||
let loading: Promise<void> | undefined
|
||||
|
||||
function notify() {
|
||||
@@ -13,37 +13,40 @@ function notify() {
|
||||
|
||||
function load() {
|
||||
return (loading ??= AsyncStorage.getItem(STORAGE_KEY)
|
||||
.then((value) => value !== "false")
|
||||
// Keep the default when local storage is unavailable.
|
||||
.catch(() => true)
|
||||
.then((value) => {
|
||||
enabled = value !== "false"
|
||||
})
|
||||
.catch(() => {
|
||||
// Keep the default when local storage is unavailable.
|
||||
})
|
||||
.finally(() => {
|
||||
loaded = true
|
||||
enabled = value
|
||||
notify()
|
||||
}))
|
||||
}
|
||||
|
||||
void load()
|
||||
|
||||
function subscribe(listener: () => void) {
|
||||
listeners.add(listener)
|
||||
void load()
|
||||
return () => {
|
||||
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() {
|
||||
return useSyncExternalStore(subscribe, () => loaded && enabled, () => false)
|
||||
return useSyncExternalStore(
|
||||
subscribe,
|
||||
() => enabled,
|
||||
() => undefined
|
||||
)
|
||||
}
|
||||
|
||||
export function useArtworkColorPreferenceLoaded() {
|
||||
return useSyncExternalStore(subscribe, () => loaded, () => false)
|
||||
}
|
||||
|
||||
export function artworkColorsEnabled() {
|
||||
return loaded && enabled
|
||||
/** Resolves with the preference once it has loaded. */
|
||||
export async function loadArtworkColorsEnabled() {
|
||||
await load()
|
||||
return enabled ?? true
|
||||
}
|
||||
|
||||
export async function setArtworkColorsEnabled(value: boolean) {
|
||||
|
||||
@@ -1,40 +1,9 @@
|
||||
export type MediaShareContext = (
|
||||
| { type: "album"; albumId: string }
|
||||
| { type: "song"; albumId: string; songId: string }
|
||||
| { type: "playlist"; playlistId: string; isFavorites?: boolean }
|
||||
| { type: "artist"; artistId: string }
|
||||
) & { title: string }
|
||||
import type { MediaShareTarget } from "@otunes/convex/client/media-links"
|
||||
|
||||
export function shouldShowShare(
|
||||
share: MediaShareContext | undefined,
|
||||
selectedCount: number
|
||||
) {
|
||||
if (!share) {
|
||||
return false
|
||||
}
|
||||
if (share.type === "song") {
|
||||
return selectedCount === 1
|
||||
}
|
||||
return true
|
||||
}
|
||||
export {
|
||||
mediaShareUrl,
|
||||
shouldShowShare,
|
||||
} from "@otunes/convex/client/media-links"
|
||||
|
||||
export function mediaShareUrl(
|
||||
serverUrl: string,
|
||||
share: MediaShareContext
|
||||
): string {
|
||||
const origin = serverUrl.replace(/\/+$/, "")
|
||||
|
||||
switch (share.type) {
|
||||
case "album":
|
||||
return `${origin}/album/${share.albumId}`
|
||||
case "song":
|
||||
return `${origin}/album/${share.albumId}?s=${share.songId}`
|
||||
case "playlist":
|
||||
if (share.isFavorites) {
|
||||
return `${origin}/playlist/favorites`
|
||||
}
|
||||
return `${origin}/playlist/${share.playlistId}`
|
||||
case "artist":
|
||||
return `${origin}/artist/${share.artistId}`
|
||||
}
|
||||
}
|
||||
/** A share target plus the title shown in the native share sheet. */
|
||||
export type MediaShareContext = MediaShareTarget & { title: string }
|
||||
@@ -2,3 +2,8 @@ import { Platform } from "react-native"
|
||||
|
||||
// Android Dolby decoder reports do not reliably indicate working Atmos playback.
|
||||
export const dolbyAtmosSupported = Platform.OS === "ios"
|
||||
|
||||
/** Whether to stream Atmos for this user: they opted in and the device can play it. */
|
||||
export function atmosEnabled(user: { preferAtmos?: boolean }) {
|
||||
return dolbyAtmosSupported && (user.preferAtmos ?? false)
|
||||
}
|
||||
@@ -5,8 +5,10 @@ import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
import {
|
||||
getCachedSong,
|
||||
getSongSnapshot,
|
||||
getSongsVersion,
|
||||
requestSongs,
|
||||
songFromSnapshot,
|
||||
subscribeSongs,
|
||||
} from "@otunes/convex/client/song-cache"
|
||||
import { isPersistentCacheLoaded } from "@/lib/persistent-cache"
|
||||
@@ -50,12 +52,10 @@ export function useSongs(songIds: readonly Id<"songs">[]) {
|
||||
*/
|
||||
export function useSong(songId: Id<"songs"> | null): BrowseSong | null {
|
||||
const convex = useConvex()
|
||||
// While the song is missing the snapshot is the cache version, so every
|
||||
// cache change re-renders and retries the fetch below.
|
||||
const snapshot = useSyncExternalStore(subscribeSongs, () =>
|
||||
songId ? (getCachedSong(songId) ?? getSongsVersion()) : null
|
||||
getSongSnapshot(songId)
|
||||
)
|
||||
const song = typeof snapshot === "object" ? snapshot : null
|
||||
const song = songFromSnapshot(snapshot)
|
||||
|
||||
useEffect(() => {
|
||||
if (songId && !song && isPersistentCacheLoaded()) {
|
||||
|
||||
+11
-33
@@ -1,9 +1,11 @@
|
||||
import { dolbyAtmosSupported } from "@/lib/playback-capabilities"
|
||||
import {
|
||||
type PlaybackQuality,
|
||||
songHlsPlaylistPath,
|
||||
songPlayPath,
|
||||
} from "@otunes/convex/playback-stream"
|
||||
import { Platform } from "react-native"
|
||||
import type { AudioSource } from "expo-audio"
|
||||
|
||||
export type PlaybackQuality = "low" | "medium" | "high" | "lossless"
|
||||
|
||||
export const coverImageSizes = [64, 128, 192, 256, 384, 512, 768, 1024] as const
|
||||
|
||||
export type CoverImageSize = (typeof coverImageSizes)[number]
|
||||
@@ -45,33 +47,6 @@ export function playlistCoverUrl(
|
||||
return sizedCoverUrl(`${serverUrl}/api/playlist/${playlistId}/cover`, size)
|
||||
}
|
||||
|
||||
export function songPlayUrl(
|
||||
serverUrl: string,
|
||||
songId: string,
|
||||
quality: PlaybackQuality | undefined,
|
||||
preferAtmos: boolean | undefined
|
||||
) {
|
||||
const params = new URLSearchParams()
|
||||
if (Platform.OS === "ios") params.set("losslessFormat", "alac")
|
||||
if (quality) params.set("quality", quality)
|
||||
if (dolbyAtmosSupported && preferAtmos) params.set("preferAtmos", "true")
|
||||
const query = params.toString()
|
||||
return `${serverUrl}/api/song/${songId}/play${query ? `?${query}` : ""}`
|
||||
}
|
||||
|
||||
export function songHlsPlaylistUrl(
|
||||
serverUrl: string,
|
||||
songId: string,
|
||||
quality: PlaybackQuality | undefined,
|
||||
preferAtmos: boolean | undefined
|
||||
) {
|
||||
const params = new URLSearchParams()
|
||||
if (quality) params.set("quality", quality)
|
||||
if (dolbyAtmosSupported && preferAtmos) params.set("preferAtmos", "true")
|
||||
const query = params.toString()
|
||||
return `${serverUrl}/api/song/${songId}/play/hls${query ? `?${query}` : ""}`
|
||||
}
|
||||
|
||||
export function songAudioSource(
|
||||
serverUrl: string,
|
||||
songId: string,
|
||||
@@ -80,9 +55,12 @@ export function songAudioSource(
|
||||
useHls: boolean,
|
||||
options?: { cookieHeader?: string | null; songTitle?: string }
|
||||
): AudioSource {
|
||||
const uri = useHls
|
||||
? songHlsPlaylistUrl(serverUrl, songId, quality, preferAtmos)
|
||||
: songPlayUrl(serverUrl, songId, quality, preferAtmos)
|
||||
const path = useHls
|
||||
? songHlsPlaylistPath(songId, quality, preferAtmos)
|
||||
: songPlayPath(songId, quality, preferAtmos, {
|
||||
losslessFormat: Platform.OS === "ios" ? "alac" : undefined,
|
||||
})
|
||||
const uri = `${serverUrl}${path}`
|
||||
|
||||
const headers = options?.cookieHeader
|
||||
? { Cookie: options.cookieHeader }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import { convexServerOptions } from "@/lib/convex-server"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { Metadata } from "next"
|
||||
|
||||
interface PageProps {
|
||||
@@ -11,12 +12,12 @@ export async function generateMetadata({
|
||||
params,
|
||||
}: PageProps): Promise<Metadata> {
|
||||
const { id } = await params
|
||||
const artists = await fetchQuery(
|
||||
api.library.browseArtists,
|
||||
{},
|
||||
const detail = await fetchQuery(
|
||||
api.library.browseArtistDetail,
|
||||
{ id: id as Id<"artists"> },
|
||||
convexServerOptions()
|
||||
)
|
||||
const selectedArtist = artists.find((artist) => artist.id === id)
|
||||
).catch(() => null)
|
||||
const selectedArtist = detail?.artist
|
||||
|
||||
return {
|
||||
title: `${selectedArtist ? `${selectedArtist.name}` : "oTunes"}`,
|
||||
|
||||
@@ -10,10 +10,10 @@ export async function GET(
|
||||
const { id } = await params
|
||||
|
||||
try {
|
||||
const album = await getConvexClient().query(api.library.getAlbum, {
|
||||
const cover = await getConvexClient().query(api.library.getAlbumCover, {
|
||||
id: id as Id<"albums">,
|
||||
})
|
||||
return serveCoverFile(album?.cover, request)
|
||||
return serveCoverFile(cover, request)
|
||||
} catch {
|
||||
return new Response("Not found", { status: 404 })
|
||||
}
|
||||
|
||||
@@ -10,10 +10,10 @@ export async function GET(
|
||||
const { id } = await params
|
||||
|
||||
try {
|
||||
const artist = await getConvexClient().query(api.library.getArtist, {
|
||||
const cover = await getConvexClient().query(api.library.getArtistCover, {
|
||||
id: id as Id<"artists">,
|
||||
})
|
||||
return serveCoverFile(artist?.cover, request)
|
||||
return serveCoverFile(cover, request)
|
||||
} catch {
|
||||
return new Response("Not found", { status: 404 })
|
||||
}
|
||||
|
||||
@@ -9,10 +9,10 @@ export async function GET(
|
||||
) {
|
||||
const { id } = await params
|
||||
try {
|
||||
const playlist = await getConvexClient().query(api.library.getPlaylist, {
|
||||
const cover = await getConvexClient().query(api.library.getPlaylistCover, {
|
||||
id: id as Id<"playlists">,
|
||||
})
|
||||
return serveCoverFile(playlist?.cover, request)
|
||||
return serveCoverFile(cover, request)
|
||||
} catch {
|
||||
return new Response("Not found", { status: 404 })
|
||||
}
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { getConvexClient } from "@/lib/convex-server"
|
||||
import { getSongSource } from "@/lib/server-song"
|
||||
import { ensureHlsJob, HLS_SEGMENT_SECONDS } from "@/lib/server-hls"
|
||||
import { NextRequest } from "next/server"
|
||||
|
||||
@@ -17,9 +15,7 @@ export async function GET(
|
||||
const { id } = await params
|
||||
|
||||
try {
|
||||
const song = (await getConvexClient().query(api.library.getSong, {
|
||||
id: id as Id<"songs">,
|
||||
}))!
|
||||
const song = await getSongSource(id)
|
||||
|
||||
const quality = request.nextUrl.searchParams.get("quality")
|
||||
const preferAtmos =
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { getConvexClient } from "@/lib/convex-server"
|
||||
import { getSongSource } from "@/lib/server-song"
|
||||
import {
|
||||
ensureHlsJob,
|
||||
getExistingHlsJob,
|
||||
@@ -36,16 +34,11 @@ export async function GET(
|
||||
const quality = request.nextUrl.searchParams.get("quality")
|
||||
const preferAtmos =
|
||||
request.nextUrl.searchParams.get("preferAtmos") === "true"
|
||||
const existingJob = getExistingHlsJob(id, quality, preferAtmos)
|
||||
// Resolve the source even when a job is cached so every segment is authorized.
|
||||
const song = await getSongSource(id)
|
||||
const job =
|
||||
existingJob ??
|
||||
(await ensureHlsJob(
|
||||
(await getConvexClient().query(api.library.getSong, {
|
||||
id: id as Id<"songs">,
|
||||
}))!,
|
||||
quality,
|
||||
preferAtmos
|
||||
))
|
||||
getExistingHlsJob(id, quality, preferAtmos) ??
|
||||
(await ensureHlsJob(song, quality, preferAtmos))
|
||||
if (segmentIndex >= job.segmentCount) {
|
||||
return new Response("Segment not found", { status: 404 })
|
||||
}
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import {
|
||||
parsePlaybackQuality,
|
||||
playbackStreamPlan,
|
||||
} from "@otunes/convex/playback-stream"
|
||||
import { audioContentTypeForPath } from "@/lib/audio-content-type"
|
||||
import { seekableLosslessFile } from "@/lib/server-lossless"
|
||||
import { getConvexClient } from "@/lib/convex-server"
|
||||
import { getSongSource } from "@/lib/server-song"
|
||||
import { audioInfo } from "@/lib/server-audio-info"
|
||||
import { ffmpegToReadableStream, streamFile } from "@/lib/server-audio-stream"
|
||||
import { spawnFfmpeg } from "@/lib/server-ffmpeg"
|
||||
import { NextRequest, NextResponse, userAgent } from "next/server"
|
||||
import { spawn } from "node:child_process"
|
||||
import fs from "node:fs/promises"
|
||||
import * as music from "music-metadata"
|
||||
|
||||
function parseByteRange(rangeHeader: string | null, fileSize: number) {
|
||||
if (!rangeHeader) {
|
||||
@@ -118,47 +120,29 @@ export async function GET(
|
||||
const { browser } = userAgent(request)
|
||||
|
||||
try {
|
||||
const song = (await getConvexClient().query(api.library.getSong, {
|
||||
id: id as Id<"songs">,
|
||||
}))!
|
||||
const song = await getSongSource(id)
|
||||
|
||||
const quality = request.nextUrl.searchParams.get("quality") as
|
||||
"low" | "medium" | "high" | "lossless" | null
|
||||
|
||||
const preferAtmos =
|
||||
const {
|
||||
source: originalCodec,
|
||||
kbps,
|
||||
transcodeNeeded,
|
||||
} = playbackStreamPlan(
|
||||
song.files,
|
||||
// Without a quality, serve the original file as this route always has.
|
||||
parsePlaybackQuality(request.nextUrl.searchParams.get("quality")) ??
|
||||
"lossless",
|
||||
request.nextUrl.searchParams.get("preferAtmos") === "true"
|
||||
|
||||
let kbps = 0
|
||||
if (quality === "low") {
|
||||
kbps = 64
|
||||
} else if (quality === "medium") {
|
||||
kbps = 128
|
||||
} else if (quality === "high") {
|
||||
kbps = 256
|
||||
}
|
||||
|
||||
let originalCodec = "lossless" in song.files ? "lossless" : "normal"
|
||||
|
||||
let transcodeNeeded = true
|
||||
if (preferAtmos && "atmos" in song.files) {
|
||||
originalCodec = "atmos"
|
||||
transcodeNeeded = false
|
||||
} else if (kbps === 0 && "lossless" in song.files) {
|
||||
originalCodec = "lossless"
|
||||
transcodeNeeded = false
|
||||
} else if (kbps === 0 || (kbps === 256 && "normal" in song.files)) {
|
||||
originalCodec = "normal"
|
||||
transcodeNeeded = false
|
||||
}
|
||||
|
||||
const metadata = await music.parseFile(song.files[originalCodec])
|
||||
)
|
||||
|
||||
if (!transcodeNeeded && originalCodec === "lossless") {
|
||||
// Native iOS playback does not identify itself as Safari.
|
||||
const acceptsAlac =
|
||||
browser.name === "Safari" ||
|
||||
request.nextUrl.searchParams.get("losslessFormat") === "alac"
|
||||
if (acceptsAlac && metadata.format.codec === "ALAC") {
|
||||
if (
|
||||
acceptsAlac &&
|
||||
(await audioInfo(song.files[originalCodec])).codec === "ALAC"
|
||||
) {
|
||||
try {
|
||||
return await streamFileResponse(
|
||||
request,
|
||||
@@ -183,11 +167,6 @@ export async function GET(
|
||||
(originalCodec === "atmos" || originalCodec === "normal")
|
||||
) {
|
||||
// TODO: Dolby Atmos doesn't work on Google Chrome
|
||||
console.log(
|
||||
metadata.format.codec,
|
||||
metadata.format.container,
|
||||
metadata.format.codecProfile
|
||||
)
|
||||
try {
|
||||
return await streamFileResponse(
|
||||
request,
|
||||
@@ -200,7 +179,6 @@ export async function GET(
|
||||
}
|
||||
|
||||
const ffmpegArgs = [
|
||||
"-nostdin",
|
||||
"-i",
|
||||
song.files[originalCodec],
|
||||
"-c:a",
|
||||
@@ -214,8 +192,8 @@ export async function GET(
|
||||
|
||||
try {
|
||||
// TODO: Fix seeking for this
|
||||
const ffmpegProcess = spawn("ffmpeg", ffmpegArgs)
|
||||
const stream = ffmpegToReadableStream(ffmpegProcess)
|
||||
const ffmpeg = await spawnFfmpeg(ffmpegArgs, request.signal)
|
||||
const stream = ffmpegToReadableStream(ffmpeg)
|
||||
|
||||
return new NextResponse(stream, {
|
||||
status: 200,
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
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 })
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
MediaContextMenuItems,
|
||||
type MediaContextAction,
|
||||
} from "@/components/media-context-menu"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
@@ -48,7 +48,7 @@ export function AlbumCard({ album }: { album: BrowseAlbum }) {
|
||||
const cacheScope = useCacheScope()
|
||||
const { openAddAlbumToPlaylist } = useAddToPlaylist()
|
||||
const { isAlbumFavorite, toggleAlbumFavorite } = useFavorites()
|
||||
const { playAlbum } = usePlayback()
|
||||
const { playAlbum } = usePlaybackActions()
|
||||
const { runQueueAction, createStation } = useQueueMediaActions()
|
||||
const [menuOpen, setMenuOpen] = React.useState(false)
|
||||
const [hovered, setHovered] = React.useState(false)
|
||||
|
||||
@@ -4,53 +4,46 @@ import { PageHeader } from "@/components/library-skeletons"
|
||||
import * as React from "react"
|
||||
import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
import { Play, Share2, Shuffle, Star } from "lucide-react"
|
||||
import { Play, Share2, Shuffle } from "lucide-react"
|
||||
|
||||
import { AudioFormatBadge } from "@/components/audio-format-badge"
|
||||
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 { useFavorites } from "@/components/favorites-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import {
|
||||
useCurrentSongId,
|
||||
usePlaybackActions,
|
||||
} from "@/components/playback-provider"
|
||||
import { copyAlbumLink } from "@/lib/media-links"
|
||||
|
||||
import {
|
||||
MediaContextMenu,
|
||||
type MediaContextAction,
|
||||
} from "@/components/media-context-menu"
|
||||
import { TrackRow } from "@/components/track-row"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||
import {
|
||||
useMediaActions,
|
||||
useTrackListMediaAction,
|
||||
} from "@/hooks/use-media-actions"
|
||||
import { useTrackSelection } from "@/hooks/use-track-selection"
|
||||
import { cn } from "@/lib/utils"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { BrowseAlbumDetail, BrowseAlbumTrack } from "@otunes/convex/types"
|
||||
import type {
|
||||
BrowseAlbumDetail,
|
||||
BrowseAlbumTrack,
|
||||
BrowseSong,
|
||||
} from "@otunes/convex/types"
|
||||
import {
|
||||
getSelectionRangePositions,
|
||||
isInSelectionRange,
|
||||
ALBUM_TRACK_ROW,
|
||||
ALBUM_TRACK_TITLE,
|
||||
SelectionRangeHighlight,
|
||||
TRACK_LIST_CONTAINER,
|
||||
TrackRowActiveHighlight,
|
||||
TrackRowHoverHighlight,
|
||||
TRACK_ROW_PADDING,
|
||||
type SelectionRangePosition,
|
||||
} from "@/lib/selection-range-styles"
|
||||
import { albumCoverUrl } from "@/lib/cover-urls"
|
||||
import { sumDurationSeconds } from "@/lib/media-summary"
|
||||
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 {
|
||||
const parts: string[] = []
|
||||
if (genre) {
|
||||
@@ -100,159 +93,6 @@ function groupAlbumTracksByDisk(tracks: BrowseAlbumTrack[]): AlbumTrackSection[]
|
||||
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({
|
||||
album,
|
||||
highlightedSongId,
|
||||
@@ -260,36 +100,20 @@ export function AlbumView({
|
||||
album: BrowseAlbumDetail
|
||||
highlightedSongId?: string
|
||||
}) {
|
||||
const { openAddToPlaylist } = useAddToPlaylist()
|
||||
const {
|
||||
isSongFavorite,
|
||||
isAlbumFavorite,
|
||||
toggleSongFavorite,
|
||||
toggleAlbumFavorite,
|
||||
favoriteSongs,
|
||||
} = useFavorites()
|
||||
const { currentSong, playFromSong, playAlbum, playAlbumShuffled } =
|
||||
usePlayback()
|
||||
const { runQueueAction, createStation } = useQueueMediaActions()
|
||||
const currentSongId = useCurrentSongId()
|
||||
const { playFromSong, playAlbum, playAlbumShuffled } = usePlaybackActions()
|
||||
const { runSongsAction } = useMediaActions()
|
||||
const albumSongIds = React.useMemo(
|
||||
() => album.tracks.map((track) => track.id as Id<"songs">),
|
||||
[album.tracks]
|
||||
)
|
||||
|
||||
// Older servers do not include album format availability yet.
|
||||
const formatTracks = useCachedQuery(
|
||||
api.library.getSongsForPlayback,
|
||||
album.hasLossless === undefined || album.hasAtmos === undefined
|
||||
? { ids: albumSongIds }
|
||||
: "skip"
|
||||
)
|
||||
const hasLossless =
|
||||
album.hasLossless ??
|
||||
formatTracks?.some((track) => track && "lossless" in track.files)
|
||||
const hasAtmos =
|
||||
album.hasAtmos ??
|
||||
formatTracks?.some((track) => track && "atmos" in track.files)
|
||||
|
||||
React.useEffect(() => {
|
||||
rememberSongs(albumDetailSongs(album))
|
||||
}, [album])
|
||||
@@ -308,7 +132,6 @@ export function AlbumView({
|
||||
const {
|
||||
selectedIds,
|
||||
selectedCount,
|
||||
isSelected,
|
||||
handleSelect,
|
||||
handlePointerDown,
|
||||
prepareContextMenu,
|
||||
@@ -336,55 +159,55 @@ export function AlbumView({
|
||||
return indexById
|
||||
}, [album.tracks])
|
||||
|
||||
function handleMediaAction(
|
||||
action: MediaContextAction,
|
||||
fallbackTrackId?: string
|
||||
) {
|
||||
const targetIds =
|
||||
selectedIds.size > 0
|
||||
? Array.from(selectedIds)
|
||||
: fallbackTrackId
|
||||
? [fallbackTrackId]
|
||||
: activeTrackId
|
||||
? [activeTrackId]
|
||||
: []
|
||||
switch (action) {
|
||||
case "create-station":
|
||||
void createStation(album.artist.id)
|
||||
break
|
||||
case "favorite":
|
||||
void favoriteSongs(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "playlist":
|
||||
openAddToPlaylist(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle":
|
||||
void runQueueAction(action, targetIds as Id<"songs">[])
|
||||
break
|
||||
}
|
||||
}
|
||||
const trackSongs = React.useMemo(
|
||||
() =>
|
||||
new Map<string, BrowseSong>(
|
||||
album.tracks.map((track) => [
|
||||
track.id,
|
||||
{
|
||||
id: track.id,
|
||||
title: track.title,
|
||||
durationSeconds: track.durationSeconds,
|
||||
artist: album.artist,
|
||||
album: { id: album.id, title: album.title, cover: album.cover },
|
||||
},
|
||||
])
|
||||
),
|
||||
[album.tracks, album.artist, album.id, album.title, album.cover]
|
||||
)
|
||||
|
||||
const handleMediaAction = useTrackListMediaAction({
|
||||
selectedIds,
|
||||
artistId: album.artist.id,
|
||||
})
|
||||
|
||||
const handleRowSelect = React.useCallback(
|
||||
(index: number, event: React.MouseEvent) => {
|
||||
const trackId = album.tracks[index].id
|
||||
handleSelect(trackId, index, event)
|
||||
setActiveTrackId(trackId)
|
||||
},
|
||||
[album.tracks, handleSelect]
|
||||
)
|
||||
|
||||
const handleRowPlay = React.useCallback(
|
||||
(index: number) => {
|
||||
void playFromSong(album.tracks[index].id, albumSongIds, `album:${album.id}`)
|
||||
},
|
||||
[album.tracks, album.id, albumSongIds, playFromSong]
|
||||
)
|
||||
|
||||
const handleToggleFavorite = React.useCallback(
|
||||
(songId: string) => void toggleSongFavorite(songId as Id<"songs">),
|
||||
[toggleSongFavorite]
|
||||
)
|
||||
|
||||
function handleAlbumMediaAction(action: MediaContextAction) {
|
||||
const targetIds = album.tracks.map((track) => track.id as Id<"songs">)
|
||||
|
||||
switch (action) {
|
||||
case "create-station":
|
||||
void createStation(album.artist.id)
|
||||
break
|
||||
case "favorite":
|
||||
void toggleAlbumFavorite(album.id as Id<"albums">)
|
||||
break
|
||||
case "playlist":
|
||||
openAddToPlaylist(targetIds)
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle":
|
||||
void runQueueAction(action, targetIds)
|
||||
break
|
||||
if (action === "favorite") {
|
||||
void toggleAlbumFavorite(album.id as Id<"albums">)
|
||||
return
|
||||
}
|
||||
runSongsAction(action, albumSongIds, album.artist.id)
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -421,15 +244,15 @@ export function AlbumView({
|
||||
</Link>
|
||||
<div className="flex flex-wrap items-center justify-center gap-2 text-sm text-muted-foreground sm:justify-start">
|
||||
{metadata ? <span>{metadata}</span> : null}
|
||||
{hasLossless ? (
|
||||
{album.hasLossless ? (
|
||||
<>
|
||||
{metadata ? <span aria-hidden>·</span> : null}
|
||||
<AudioFormatBadge format="lossless" />
|
||||
</>
|
||||
) : null}
|
||||
{hasAtmos ? (
|
||||
{album.hasAtmos ? (
|
||||
<>
|
||||
{metadata || hasLossless ? (
|
||||
{metadata || album.hasLossless ? (
|
||||
<span aria-hidden>·</span>
|
||||
) : null}
|
||||
<AudioFormatBadge format="atmos" />
|
||||
@@ -518,39 +341,25 @@ export function AlbumView({
|
||||
return (
|
||||
<TrackRow
|
||||
key={track.id}
|
||||
track={track}
|
||||
sectionIndex={sectionTrackIndex}
|
||||
artist={album.artist}
|
||||
albumId={album.id}
|
||||
variant="album"
|
||||
song={trackSongs.get(track.id)!}
|
||||
index={listIndex}
|
||||
trackNumber={
|
||||
track.track > 0 ? track.track : sectionTrackIndex + 1
|
||||
}
|
||||
subtitle={track.artists?.join(", ")}
|
||||
isActive={track.id === activeTrackId}
|
||||
isSelected={isSelected(track.id)}
|
||||
selectionPosition={selectionPositions[listIndex]}
|
||||
isFavorite={isSongFavorite(track.id)}
|
||||
selectedCount={
|
||||
isSelected(track.id) && selectedCount > 0
|
||||
? selectedCount
|
||||
: 1
|
||||
}
|
||||
selectedCount={selectedCount}
|
||||
selectionStationArtistId={album.artist.id}
|
||||
isNowPlaying={currentSongId === track.id}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={(event) => {
|
||||
handleSelect(track.id, listIndex, event)
|
||||
setActiveTrackId(track.id)
|
||||
}}
|
||||
onToggleFavorite={() =>
|
||||
void toggleSongFavorite(track.id as Id<"songs">)
|
||||
}
|
||||
onPrepareContextMenu={() =>
|
||||
prepareContextMenu(track.id)
|
||||
}
|
||||
onSelect={handleRowSelect}
|
||||
onPlay={handleRowPlay}
|
||||
onToggleFavorite={handleToggleFavorite}
|
||||
onPrepareContextMenu={prepareContextMenu}
|
||||
onMediaAction={handleMediaAction}
|
||||
isNowPlaying={currentSong?.id === track.id}
|
||||
onPlay={() =>
|
||||
void playFromSong(
|
||||
track.id as Id<"songs">,
|
||||
albumSongIds,
|
||||
`album:${album.id}`
|
||||
)
|
||||
}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
|
||||
@@ -4,27 +4,19 @@ import { PageHeader } from "@/components/library-skeletons"
|
||||
import * as React from "react"
|
||||
import Image from "next/image"
|
||||
import { Play, Shuffle } from "lucide-react"
|
||||
import { useConvex } from "convex/react"
|
||||
|
||||
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import { useMediaActions } from "@/hooks/use-media-actions"
|
||||
import { AlbumCard } from "@/components/album-card"
|
||||
import { FavoriteMediaButton } from "@/components/favorite-media-button"
|
||||
import {
|
||||
MediaContextMenu,
|
||||
type MediaContextAction,
|
||||
} from "@/components/media-context-menu"
|
||||
import { MediaContextMenu } from "@/components/media-context-menu"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
|
||||
import { albumGridClassName } from "@/lib/album-grid-classes"
|
||||
import { artistCoverUrl } from "@/lib/cover-urls"
|
||||
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
|
||||
|
||||
export function ArtistView({
|
||||
artist,
|
||||
@@ -34,34 +26,8 @@ export function ArtistView({
|
||||
albums: BrowseAlbum[]
|
||||
}) {
|
||||
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
|
||||
const { openAddArtistToPlaylist } = useAddToPlaylist()
|
||||
const { playArtist, playArtistShuffled } = 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
|
||||
}
|
||||
}
|
||||
}
|
||||
const { playArtist, playArtistShuffled } = usePlaybackActions()
|
||||
const { runArtistAction } = useMediaActions()
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
@@ -118,7 +84,7 @@ export function ArtistView({
|
||||
label={`More options for ${artist.name}`}
|
||||
selectedCount={albums.length}
|
||||
onOpenMenu={() => {}}
|
||||
onAction={handleMediaAction}
|
||||
onAction={(action) => void runArtistAction(action, artist.id)}
|
||||
favorited={isArtistFavorite(artist.id)}
|
||||
trackRowTrigger={false}
|
||||
triggerVariant="secondary"
|
||||
|
||||
@@ -4,27 +4,24 @@ import * as React from "react"
|
||||
import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
import { ChevronRightIcon, Play, Shuffle } from "lucide-react"
|
||||
import { useConvex } from "convex/react"
|
||||
|
||||
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||
import { AlbumCard } from "@/components/album-card"
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { FavoriteMediaButton } from "@/components/favorite-media-button"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import {
|
||||
MediaContextMenu,
|
||||
type MediaContextAction,
|
||||
MediaContextMenuArea,
|
||||
type MediaContextMenuProps,
|
||||
} from "@/components/media-context-menu"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import { useMediaActions } from "@/hooks/use-media-actions"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { cn } from "@/lib/utils"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
|
||||
import { artistCoverUrl } from "@/lib/cover-urls"
|
||||
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
|
||||
|
||||
function ArtistAvatar({ artist }: { artist: BrowseArtist }) {
|
||||
return (
|
||||
@@ -55,36 +52,42 @@ function ArtistListItem({
|
||||
onSelect: () => void
|
||||
onMediaAction: (action: MediaContextAction) => void
|
||||
}) {
|
||||
const menu: MediaContextMenuProps = {
|
||||
label: `More options for ${artist.name}`,
|
||||
selectedCount: albumCount,
|
||||
inSelectionRange: isSelected,
|
||||
onOpenMenu: () => {},
|
||||
onAction: onMediaAction,
|
||||
favorited: isFavorite,
|
||||
share: { type: "artist", artistId: artist.id },
|
||||
}
|
||||
|
||||
return (
|
||||
<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}
|
||||
<MediaContextMenuArea menu={menu}>
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-w-0 flex-1 items-center gap-3 overflow-hidden px-4 py-2.5 text-left text-sm transition-colors",
|
||||
isSelected ? "text-primary-foreground" : ""
|
||||
"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"
|
||||
)}
|
||||
>
|
||||
<ArtistAvatar artist={artist} />
|
||||
<span className="min-w-0 flex-1 truncate font-medium">
|
||||
{artist.name}
|
||||
</span>
|
||||
</button>
|
||||
<MediaContextMenu
|
||||
label={`More options for ${artist.name}`}
|
||||
selectedCount={albumCount}
|
||||
inSelectionRange={isSelected}
|
||||
onOpenMenu={() => {}}
|
||||
onAction={onMediaAction}
|
||||
favorited={isFavorite}
|
||||
share={{ type: "artist", artistId: artist.id }}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onSelect}
|
||||
className={cn(
|
||||
"flex min-w-0 flex-1 items-center gap-3 overflow-hidden px-4 py-2.5 text-left text-sm transition-colors",
|
||||
isSelected ? "text-primary-foreground" : ""
|
||||
)}
|
||||
>
|
||||
<ArtistAvatar artist={artist} />
|
||||
<span className="min-w-0 flex-1 truncate font-medium">
|
||||
{artist.name}
|
||||
</span>
|
||||
</button>
|
||||
<MediaContextMenu {...menu} />
|
||||
</div>
|
||||
</MediaContextMenuArea>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -110,12 +113,9 @@ export function ArtistsView({
|
||||
}
|
||||
return sortedArtists[0]?.id ?? ""
|
||||
}, [artistId, sortedArtists])
|
||||
const convex = useConvex()
|
||||
const cacheScope = useCacheScope()
|
||||
const { openAddArtistToPlaylist } = useAddToPlaylist()
|
||||
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
|
||||
const { playArtist, playArtistShuffled } = usePlayback()
|
||||
const { runQueueAction } = useQueueMediaActions()
|
||||
const { playArtist, playArtistShuffled } = usePlaybackActions()
|
||||
const { runArtistAction } = useMediaActions()
|
||||
|
||||
const selectedArtist = sortedArtists.find(
|
||||
(artist) => artist.id === selectedId
|
||||
@@ -130,32 +130,6 @@ export function ArtistsView({
|
||||
return counts
|
||||
}, [albums])
|
||||
|
||||
async function handleMediaAction(
|
||||
artistId: string,
|
||||
action: MediaContextAction
|
||||
) {
|
||||
switch (action) {
|
||||
case "favorite":
|
||||
void toggleArtistFavorite(artistId as Id<"artists">)
|
||||
break
|
||||
case "playlist":
|
||||
void openAddArtistToPlaylist(artistId as Id<"artists">)
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle": {
|
||||
const songIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getOrderedArtistSongIds,
|
||||
{ artistId: artistId as Id<"artists"> }
|
||||
)
|
||||
void runQueueAction(action, songIds)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1">
|
||||
<ScrollArea className="w-72 shrink-0 border-r">
|
||||
@@ -169,7 +143,7 @@ export function ArtistsView({
|
||||
isFavorite={isArtistFavorite(artist.id)}
|
||||
onSelect={() => onSelectArtist(artist.id)}
|
||||
onMediaAction={(action) =>
|
||||
void handleMediaAction(artist.id, action)
|
||||
void runArtistAction(action, artist.id)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
@@ -225,7 +199,7 @@ export function ArtistsView({
|
||||
selectedCount={artistAlbums.length}
|
||||
onOpenMenu={() => {}}
|
||||
onAction={(action) =>
|
||||
void handleMediaAction(selectedArtist.id, action)
|
||||
void runArtistAction(action, selectedArtist.id)
|
||||
}
|
||||
favorited={isArtistFavorite(selectedArtist.id)}
|
||||
trackRowTrigger={false}
|
||||
|
||||
@@ -1,35 +1,28 @@
|
||||
import {
|
||||
DOLBY_PATHS,
|
||||
DOLBY_VIEW_BOX,
|
||||
DOLBY_WIDTH,
|
||||
LOSSLESS_FALL,
|
||||
LOSSLESS_FALL_GAP,
|
||||
LOSSLESS_PEAKS,
|
||||
LOSSLESS_STROKES,
|
||||
LOSSLESS_THIN_WIDTH,
|
||||
LOSSLESS_VIEW_BOX,
|
||||
LOSSLESS_WIDTH,
|
||||
MARK_HEIGHT,
|
||||
} from "@otunes/convex/client/audio-format-marks"
|
||||
import type { PlaybackFormat } from "@otunes/convex/playback-stream"
|
||||
|
||||
const MARK_HEIGHT = 11
|
||||
|
||||
function DolbyMark({ color }: { color: string }) {
|
||||
return (
|
||||
<svg
|
||||
width={(MARK_HEIGHT * 23) / 16}
|
||||
height={MARK_HEIGHT}
|
||||
viewBox="0 0 23 16"
|
||||
>
|
||||
<path d="M0 0H2.5A8 8 0 0 1 2.5 16H0Z" fill={color} />
|
||||
<path d="M23 0H20.5A8 8 0 0 0 20.5 16H23Z" fill={color} />
|
||||
<svg width={DOLBY_WIDTH} height={MARK_HEIGHT} viewBox={DOLBY_VIEW_BOX}>
|
||||
{DOLBY_PATHS.map((d) => (
|
||||
<path key={d} d={d} fill={color} />
|
||||
))}
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
const LOSSLESS_PEAKS = [110, 215, 320]
|
||||
const LOSSLESS_THIN_WIDTH = 24
|
||||
const LOSSLESS_STROKES: [peak: number, d: string][] = [
|
||||
[110, "M-70 320C-62 245 -38 166 0 166"],
|
||||
[215, "M-70 320C-62 245 -38 166 0 166"],
|
||||
[320, "M-30 185C-22 173 -11 166 0 166"],
|
||||
[110, "M166 413C176 413 186 406 194 395"],
|
||||
[215, "M166 413C200 413 226 340 240 275"],
|
||||
[320, "M166 413C200 413 226 340 240 275"],
|
||||
]
|
||||
const LOSSLESS_FALL =
|
||||
"M0 178L4 179L8 181L12 184L16 189L20 196L23 204L27 213L30 223L34 233L39 243L43 254L48 266L53 278L58 289L62 301L66 313L71 325L75 336L79 347L83 357L86 364L89 370L93 377L97 382L101 387L105 392L109 397L113 401L117 405L121 408L126 412L130 415L134 417L139 419L143 421L148 423L152 424L157 424L161 425L166 425L166 401L163 401L161 400L159 400L157 399L154 397L152 396L151 394L149 392L147 389L145 386L143 383L142 380L140 376L138 371L137 367L135 362L134 357L132 351L130 345L127 339L124 330L120 319L116 308L111 297L107 285L102 272L98 260L93 248L88 235L82 223L76 212L69 201L61 192L53 183L45 175L37 168L28 163L19 158L10 155L0 154Z"
|
||||
const LOSSLESS_FALL_GAP =
|
||||
"M0 178L4 180L6 184L8 190L9 197L11 203L14 210L17 219L21 228L24 238L29 248L33 259L38 270L43 282L47 293L52 305L56 317L60 328L64 340L68 351L73 361L76 368L79 375L83 381L87 387L91 393L95 398L100 403L104 408L109 412L113 416L118 419L124 422L130 424L135 425L141 426L147 426L152 426L157 425L161 425L166 425L166 401L163 401L161 399L159 398L158 395L157 393L156 390L155 387L155 384L154 381L153 379L152 376L150 373L149 369L148 366L146 361L145 357L143 352L142 347L140 341L137 335L134 326L130 315L126 304L122 293L117 281L113 268L108 256L103 243L98 231L92 219L86 207L79 196L71 186L62 177L53 168L44 161L32 157L21 155L10 154L0 154Z"
|
||||
|
||||
/**
|
||||
* Three overlapping waves. Each thick downstroke is outlined in the
|
||||
* background color so it reads as passing over the strokes behind it.
|
||||
@@ -43,9 +36,9 @@ function LosslessMark({
|
||||
}) {
|
||||
return (
|
||||
<svg
|
||||
width={(MARK_HEIGHT * 544) / 271}
|
||||
width={LOSSLESS_WIDTH}
|
||||
height={MARK_HEIGHT}
|
||||
viewBox="28 154 544 271"
|
||||
viewBox={LOSSLESS_VIEW_BOX}
|
||||
>
|
||||
{LOSSLESS_STROKES.map(([peak, d], index) => (
|
||||
<path
|
||||
|
||||
@@ -1,13 +1,31 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { useMutation } from "convex/react"
|
||||
import type { OptimisticUpdate } from "convex/browser"
|
||||
import { useMutation, type ReactMutation } from "convex/react"
|
||||
import type { FunctionArgs, FunctionReference } from "convex/server"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { favoriteOptimisticUpdates } from "@otunes/convex/client/favorites"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
|
||||
/**
|
||||
* `useMutation(...).withOptimisticUpdate(...)` with a stable identity. Pass a
|
||||
* module-level update so it does not change between renders.
|
||||
*/
|
||||
function useOptimisticMutation<Mutation extends FunctionReference<"mutation">>(
|
||||
mutation: Mutation,
|
||||
optimisticUpdate: OptimisticUpdate<FunctionArgs<Mutation>>
|
||||
): ReactMutation<Mutation> {
|
||||
const base = useMutation(mutation)
|
||||
return React.useMemo(
|
||||
() => base.withOptimisticUpdate(optimisticUpdate),
|
||||
[base, optimisticUpdate]
|
||||
)
|
||||
}
|
||||
|
||||
type FavoritesContextValue = {
|
||||
isSongFavorite: (songId: string) => boolean
|
||||
isAlbumFavorite: (albumId: string) => boolean
|
||||
@@ -34,97 +52,38 @@ export function useFavorites() {
|
||||
|
||||
export function FavoritesProvider({ children }: { children: React.ReactNode }) {
|
||||
const favorites = useCachedQuery(api.favorites.getUserFavorites)
|
||||
const favoriteSong = useMutation(api.favorites.favoriteSong).withOptimisticUpdate(
|
||||
(store, { songId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (current && !current.favoriteSongs.includes(songId)) {
|
||||
store.setQuery(api.favorites.getUserFavorites, {}, {
|
||||
...current,
|
||||
favoriteSongs: [...current.favoriteSongs, songId],
|
||||
})
|
||||
}
|
||||
}
|
||||
const favoriteSong = useOptimisticMutation(
|
||||
api.favorites.favoriteSong,
|
||||
favoriteOptimisticUpdates.favoriteSong
|
||||
)
|
||||
const favoriteSongsMutation = useOptimisticMutation(
|
||||
api.favorites.favoriteSongs,
|
||||
favoriteOptimisticUpdates.favoriteSongs
|
||||
)
|
||||
const unfavoriteSong = useOptimisticMutation(
|
||||
api.favorites.unfavoriteSong,
|
||||
favoriteOptimisticUpdates.unfavoriteSong
|
||||
)
|
||||
const unfavoriteSongs = useOptimisticMutation(
|
||||
api.favorites.unfavoriteSongs,
|
||||
favoriteOptimisticUpdates.unfavoriteSongs
|
||||
)
|
||||
const favoriteAlbum = useOptimisticMutation(
|
||||
api.favorites.favoriteAlbum,
|
||||
favoriteOptimisticUpdates.favoriteAlbum
|
||||
)
|
||||
const unfavoriteAlbum = useOptimisticMutation(
|
||||
api.favorites.unfavoriteAlbum,
|
||||
favoriteOptimisticUpdates.unfavoriteAlbum
|
||||
)
|
||||
const favoriteArtist = useOptimisticMutation(
|
||||
api.favorites.favoriteArtist,
|
||||
favoriteOptimisticUpdates.favoriteArtist
|
||||
)
|
||||
const unfavoriteArtist = useOptimisticMutation(
|
||||
api.favorites.unfavoriteArtist,
|
||||
favoriteOptimisticUpdates.unfavoriteArtist
|
||||
)
|
||||
const favoriteSongsMutation = useMutation(
|
||||
api.favorites.favoriteSongs
|
||||
).withOptimisticUpdate((store, { songIds }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (current) {
|
||||
store.setQuery(api.favorites.getUserFavorites, {}, {
|
||||
...current,
|
||||
favoriteSongs: [...new Set([...current.favoriteSongs, ...songIds])],
|
||||
})
|
||||
}
|
||||
})
|
||||
const unfavoriteSong = useMutation(
|
||||
api.favorites.unfavoriteSong
|
||||
).withOptimisticUpdate((store, { songId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (current) {
|
||||
store.setQuery(api.favorites.getUserFavorites, {}, {
|
||||
...current,
|
||||
favoriteSongs: current.favoriteSongs.filter((id) => id !== songId),
|
||||
})
|
||||
}
|
||||
})
|
||||
const unfavoriteSongs = useMutation(
|
||||
api.favorites.unfavoriteSongs
|
||||
).withOptimisticUpdate((store, { songIds }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (current) {
|
||||
const removed = new Set(songIds)
|
||||
store.setQuery(api.favorites.getUserFavorites, {}, {
|
||||
...current,
|
||||
favoriteSongs: current.favoriteSongs.filter((id) => !removed.has(id)),
|
||||
})
|
||||
}
|
||||
})
|
||||
const favoriteAlbum = useMutation(
|
||||
api.favorites.favoriteAlbum
|
||||
).withOptimisticUpdate((store, { albumId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (current && !current.favoriteAlbums.includes(albumId)) {
|
||||
store.setQuery(api.favorites.getUserFavorites, {}, {
|
||||
...current,
|
||||
favoriteAlbums: [...current.favoriteAlbums, albumId],
|
||||
})
|
||||
}
|
||||
})
|
||||
const unfavoriteAlbum = useMutation(
|
||||
api.favorites.unfavoriteAlbum
|
||||
).withOptimisticUpdate((store, { albumId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (current) {
|
||||
store.setQuery(api.favorites.getUserFavorites, {}, {
|
||||
...current,
|
||||
favoriteAlbums: current.favoriteAlbums.filter((id) => id !== albumId),
|
||||
})
|
||||
}
|
||||
})
|
||||
const favoriteArtist = useMutation(
|
||||
api.favorites.favoriteArtist
|
||||
).withOptimisticUpdate((store, { artistId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (current && !current.favoriteArtists.includes(artistId)) {
|
||||
store.setQuery(api.favorites.getUserFavorites, {}, {
|
||||
...current,
|
||||
favoriteArtists: [...current.favoriteArtists, artistId],
|
||||
})
|
||||
}
|
||||
})
|
||||
const unfavoriteArtist = useMutation(
|
||||
api.favorites.unfavoriteArtist
|
||||
).withOptimisticUpdate((store, { artistId }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (current) {
|
||||
store.setQuery(api.favorites.getUserFavorites, {}, {
|
||||
...current,
|
||||
favoriteArtists: current.favoriteArtists.filter(
|
||||
(id) => id !== artistId
|
||||
),
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const songIds = React.useMemo(
|
||||
() => new Set(favorites?.favoriteSongs.map(String) ?? []),
|
||||
@@ -288,6 +247,8 @@ export function FavoritesProvider({ children }: { children: React.ReactNode }) {
|
||||
)
|
||||
|
||||
return (
|
||||
<FavoritesContext.Provider value={value}>{children}</FavoritesContext.Provider>
|
||||
<FavoritesContext.Provider value={value}>
|
||||
{children}
|
||||
</FavoritesContext.Provider>
|
||||
)
|
||||
}
|
||||
@@ -15,6 +15,13 @@ import {
|
||||
} from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuTrigger,
|
||||
} from "@/components/ui/context-menu"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -23,6 +30,7 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { copyMediaShareLink, type MediaShareContext } from "@/lib/media-links"
|
||||
import { shouldShowShare } from "@otunes/convex/client/media-links"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
export type MediaContextAction =
|
||||
@@ -40,17 +48,26 @@ export type MediaContextNavigation = {
|
||||
|
||||
export type { MediaShareContext } from "@/lib/media-links"
|
||||
|
||||
function shouldShowShare(
|
||||
share: MediaShareContext | undefined,
|
||||
selectedCount: number
|
||||
// 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>
|
||||
) {
|
||||
if (!share) {
|
||||
return false
|
||||
}
|
||||
if (share.type === "song") {
|
||||
return selectedCount === 1
|
||||
}
|
||||
return true
|
||||
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) {
|
||||
@@ -83,86 +100,86 @@ export function MediaContextMenuItems({
|
||||
<>
|
||||
{showShare ? (
|
||||
<>
|
||||
<DropdownMenuItem
|
||||
<MediaMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => void copyMediaShareLink(share!)}
|
||||
>
|
||||
Share
|
||||
<Share2 />
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
</MediaMenuItem>
|
||||
<MediaMenuSeparator />
|
||||
</>
|
||||
) : null}
|
||||
<DropdownMenuItem
|
||||
<MediaMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => onAction("playlist")}
|
||||
>
|
||||
{actionLabel(playlistLabel, selectedCount)}
|
||||
<ListPlus />
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
</MediaMenuItem>
|
||||
<MediaMenuSeparator />
|
||||
<MediaMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => onAction("play-next")}
|
||||
>
|
||||
{actionLabel("Play Next", selectedCount)}
|
||||
<ListStart />
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
</MediaMenuItem>
|
||||
<MediaMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => onAction("play-last")}
|
||||
>
|
||||
{actionLabel("Play Last", selectedCount)}
|
||||
<ListEnd />
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
</MediaMenuItem>
|
||||
<MediaMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => onAction("shuffle")}
|
||||
>
|
||||
{actionLabel("Shuffle", selectedCount)}
|
||||
<Shuffle />
|
||||
</DropdownMenuItem>
|
||||
</MediaMenuItem>
|
||||
{stationArtistId ? (
|
||||
<DropdownMenuItem
|
||||
<MediaMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => onAction("create-station")}
|
||||
>
|
||||
Create Station
|
||||
<Shuffle />
|
||||
</DropdownMenuItem>
|
||||
</MediaMenuItem>
|
||||
) : null}
|
||||
{artist || album ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<MediaMenuSeparator />
|
||||
{artist ? (
|
||||
<DropdownMenuItem asChild className="justify-between">
|
||||
<MediaMenuItem asChild className="justify-between">
|
||||
<Link href={`/artist/${artist.id}`}>
|
||||
Go to Artist
|
||||
<MicVocal />
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
</MediaMenuItem>
|
||||
) : null}
|
||||
{album ? (
|
||||
<DropdownMenuItem asChild className="justify-between">
|
||||
<MediaMenuItem asChild className="justify-between">
|
||||
<Link href={`/album/${album.id}`}>
|
||||
Go to Album
|
||||
<GalleryVerticalEnd />
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
</MediaMenuItem>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
{showFavorite ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
<MediaMenuSeparator />
|
||||
<MediaMenuItem
|
||||
variant={favorited ? "destructive" : "default"}
|
||||
className="justify-between"
|
||||
onClick={() => onAction("favorite")}
|
||||
>
|
||||
{actionLabel(favorited ? "Unfavorite" : "Favorite", selectedCount)}
|
||||
<Star />
|
||||
</DropdownMenuItem>
|
||||
</MediaMenuItem>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
@@ -194,6 +211,67 @@ 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({
|
||||
label,
|
||||
selectedCount,
|
||||
@@ -212,26 +290,7 @@ export function MediaContextMenu({
|
||||
triggerIconClassName = "size-4",
|
||||
align = "end",
|
||||
children,
|
||||
}: {
|
||||
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
|
||||
}) {
|
||||
}: MediaContextMenuProps) {
|
||||
return (
|
||||
<DropdownMenu
|
||||
onOpenChange={(open) => {
|
||||
|
||||
@@ -47,13 +47,12 @@ import {
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { PlaybackQuality } from "@otunes/convex/playback-stream"
|
||||
import { resizeProfileImageToDataUrl } from "@/lib/resize-profile-image"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
type Section = "profile" | "quality" | "users" | "library"
|
||||
|
||||
type PlaybackQuality = "low" | "medium" | "high" | "lossless"
|
||||
|
||||
type CurrentUser = {
|
||||
_id: Id<"users">
|
||||
name: string
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useAuthToken } from "@convex-dev/auth/react"
|
||||
import { userIdFromToken } from "@otunes/convex/client/auth-token"
|
||||
import { createContext, ReactNode, useContext, useEffect, useMemo } from "react"
|
||||
|
||||
import { loadPersistentCache } from "@/lib/persistent-cache"
|
||||
@@ -13,21 +14,6 @@ if (typeof window !== "undefined") {
|
||||
void loadPersistentCache()
|
||||
}
|
||||
|
||||
function userIdFromToken(token: string | null) {
|
||||
const payload = token?.split(".")[1]
|
||||
if (!payload) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"))
|
||||
const subject = (JSON.parse(json) as { sub?: unknown }).sub
|
||||
return typeof subject === "string" ? (subject.split("|")[0] ?? null) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** Namespaces persisted client data by the signed-in user. */
|
||||
export function PersistentCacheProvider({ children }: { children: ReactNode }) {
|
||||
const token = useAuthToken()
|
||||
|
||||
@@ -22,7 +22,10 @@ import type { BrowseSong } from "@otunes/convex/types"
|
||||
import {
|
||||
playbackFormat,
|
||||
type PlaybackFormat,
|
||||
type PlaybackQuality,
|
||||
playbackStreamPlan,
|
||||
songHlsPlaylistPath,
|
||||
songPlayPath,
|
||||
} from "@otunes/convex/playback-stream"
|
||||
import {
|
||||
ANONYMOUS_CACHE_SCOPE,
|
||||
@@ -40,7 +43,6 @@ import {
|
||||
getServerPlaybackSnapshot,
|
||||
} from "@otunes/convex/client/playback-store"
|
||||
import { rememberSongs, useSong } from "@/lib/song-cache"
|
||||
import { songHlsPlaylistUrl, songPlayUrl } from "@/lib/song-play-url"
|
||||
|
||||
const PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS = 5
|
||||
const PROGRESS_SAVE_INTERVAL_MS = 5000
|
||||
@@ -102,7 +104,26 @@ type PlaybackContextValue = {
|
||||
dolbyAtmosSupported: boolean | null
|
||||
}
|
||||
|
||||
type PlaybackActions = Omit<
|
||||
PlaybackContextValue,
|
||||
| "queueSongIds"
|
||||
| "queueHistorySongIds"
|
||||
| "currentFormat"
|
||||
| "currentSong"
|
||||
| "shuffleEnabled"
|
||||
| "repeatEnabled"
|
||||
| "queueOpen"
|
||||
| "isPlaying"
|
||||
| "volume"
|
||||
| "dolbyAtmosSupported"
|
||||
>
|
||||
|
||||
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<{
|
||||
currentTime: number
|
||||
duration: number
|
||||
@@ -164,14 +185,14 @@ function readStoredVolume(): number {
|
||||
|
||||
type PlaybackLoadSettings = {
|
||||
preferAtmos: boolean
|
||||
playbackQuality: "low" | "medium" | "high" | "lossless"
|
||||
playbackQuality: PlaybackQuality
|
||||
useHls: boolean
|
||||
}
|
||||
|
||||
function playbackLoadSettings(
|
||||
user: {
|
||||
preferAtmos?: boolean
|
||||
playbackQuality?: "low" | "medium" | "high" | "lossless"
|
||||
playbackQuality?: PlaybackQuality
|
||||
},
|
||||
dolbyAtmosSupported: boolean | null,
|
||||
files: Record<string, unknown>
|
||||
@@ -226,12 +247,12 @@ function loadAudioSource(
|
||||
): AudioSourceCleanup {
|
||||
let disposed = false
|
||||
let hlsInstance: Hls | null = null
|
||||
const directUrl = songPlayUrl(
|
||||
const directUrl = songPlayPath(
|
||||
songId,
|
||||
settings.playbackQuality,
|
||||
settings.preferAtmos
|
||||
)
|
||||
const hlsUrl = songHlsPlaylistUrl(
|
||||
const hlsUrl = songHlsPlaylistPath(
|
||||
songId,
|
||||
settings.playbackQuality,
|
||||
settings.preferAtmos
|
||||
@@ -301,6 +322,22 @@ export function usePlayback() {
|
||||
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() {
|
||||
const context = useContext(PlaybackProgressContext)
|
||||
if (!context) {
|
||||
@@ -339,17 +376,19 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
if (!isSignedIn) {
|
||||
return
|
||||
}
|
||||
store.setTransport((state) =>
|
||||
syncPlaybackStateMutation({
|
||||
songQueue: state.queue,
|
||||
queueHistory: state.history,
|
||||
shuffleEnabled: state.shuffleEnabled,
|
||||
repeatEnabled: state.repeatEnabled,
|
||||
currentSongProgress: state.progressSeconds,
|
||||
})
|
||||
)
|
||||
store.setTransport({
|
||||
sync: (state) =>
|
||||
syncPlaybackStateMutation({
|
||||
songQueue: state.queue,
|
||||
queueHistory: state.history,
|
||||
shuffleEnabled: state.shuffleEnabled,
|
||||
repeatEnabled: state.repeatEnabled,
|
||||
currentSongProgress: state.progressSeconds,
|
||||
}),
|
||||
loadProgress: () => convex.query(api.playback.getSongProgress, {}),
|
||||
})
|
||||
return () => store.setTransport(null)
|
||||
}, [store, isSignedIn, syncPlaybackStateMutation])
|
||||
}, [store, isSignedIn, syncPlaybackStateMutation, convex])
|
||||
|
||||
useEffect(() => {
|
||||
if (!serverPlayback) {
|
||||
@@ -955,6 +994,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
if (!shouldContinuePlaying) {
|
||||
autoPlayNextRef.current = false
|
||||
isPlayingRef.current = false
|
||||
audio.pause()
|
||||
audio.currentTime = 0
|
||||
currentTimeRef.current = 0
|
||||
setCurrentTime(0)
|
||||
@@ -1360,17 +1400,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
: null
|
||||
|
||||
const value = useMemo<PlaybackContextValue>(
|
||||
const actions = useMemo<PlaybackActions>(
|
||||
() => ({
|
||||
queueSongIds: playback.queue,
|
||||
queueHistorySongIds: playback.history,
|
||||
currentSong,
|
||||
currentFormat,
|
||||
shuffleEnabled: playback.shuffleEnabled,
|
||||
repeatEnabled: playback.repeatEnabled,
|
||||
queueOpen,
|
||||
isPlaying: isPlaybackActive,
|
||||
volume,
|
||||
setQueueOpen,
|
||||
toggleQueueOpen,
|
||||
setIsPlaying,
|
||||
@@ -1394,15 +1425,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
skipToQueueIndex,
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
dolbyAtmosSupported,
|
||||
}),
|
||||
[
|
||||
playback,
|
||||
currentSong,
|
||||
currentFormat,
|
||||
queueOpen,
|
||||
isPlaybackActive,
|
||||
volume,
|
||||
toggleQueueOpen,
|
||||
setVolume,
|
||||
playInOrder,
|
||||
@@ -1424,6 +1448,31 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
skipToQueueIndex,
|
||||
skipNext,
|
||||
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,
|
||||
]
|
||||
)
|
||||
@@ -1434,10 +1483,16 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
|
||||
return (
|
||||
<PlaybackContext.Provider value={value}>
|
||||
<PlaybackProgressContext.Provider value={progressValue}>
|
||||
{children}
|
||||
</PlaybackProgressContext.Provider>
|
||||
</PlaybackContext.Provider>
|
||||
<PlaybackActionsContext.Provider value={actions}>
|
||||
<CurrentSongIdContext.Provider value={currentSongId}>
|
||||
<IsPlayingContext.Provider value={isPlaybackActive}>
|
||||
<PlaybackContext.Provider value={value}>
|
||||
<PlaybackProgressContext.Provider value={progressValue}>
|
||||
{children}
|
||||
</PlaybackProgressContext.Provider>
|
||||
</PlaybackContext.Provider>
|
||||
</IsPlayingContext.Provider>
|
||||
</CurrentSongIdContext.Provider>
|
||||
</PlaybackActionsContext.Provider>
|
||||
)
|
||||
}
|
||||
@@ -31,12 +31,39 @@ import { Slider } from "@/components/ui/slider"
|
||||
import { useSidebar } from "@/components/ui/sidebar"
|
||||
import { albumCoverUrl } from "@/lib/cover-urls"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { formatDuration } from "@/lib/format-duration"
|
||||
|
||||
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")}`
|
||||
function PlayerSeekBar({ hasActiveSong }: { hasActiveSong: boolean }) {
|
||||
const { currentTime, duration, seekTo } = usePlaybackProgress()
|
||||
const [isSeeking, setIsSeeking] = React.useState(false)
|
||||
const [seekValue, setSeekValue] = React.useState(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() {
|
||||
@@ -57,16 +84,10 @@ export function PlayerBar() {
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
} = usePlayback()
|
||||
const { currentTime, duration, seekTo } = usePlaybackProgress()
|
||||
const { state, isMobile } = useSidebar()
|
||||
const [isSeeking, setIsSeeking] = React.useState(false)
|
||||
const [seekValue, setSeekValue] = React.useState(0)
|
||||
|
||||
const hasQueue = queueSongIds.length > 0
|
||||
const hasActiveSong = Boolean(currentSong)
|
||||
const sidebarExpanded = !isMobile && state === "expanded"
|
||||
const displayTime = hasActiveSong ? (isSeeking ? seekValue : currentTime) : 0
|
||||
const maxDuration = Math.max(duration, 1)
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -198,27 +219,7 @@ export function PlayerBar() {
|
||||
/>
|
||||
)}
|
||||
<div className="absolute inset-x-0 -bottom-1">
|
||||
<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)}`}
|
||||
/>
|
||||
<PlayerSeekBar hasActiveSong={Boolean(currentSong)} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
MediaContextMenuItems,
|
||||
type MediaContextAction,
|
||||
} from "@/components/media-context-menu"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -30,7 +30,7 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
|
||||
const convex = useConvex()
|
||||
const cacheScope = useCacheScope()
|
||||
const { openAddPlaylistToPlaylist } = useAddToPlaylist()
|
||||
const { playPlaylist } = usePlayback()
|
||||
const { playPlaylist } = usePlaybackActions()
|
||||
const { runQueueAction } = useQueueMediaActions()
|
||||
|
||||
async function handleCardAction(action: MediaContextAction) {
|
||||
|
||||
@@ -9,15 +9,18 @@ import { useMutation } from "convex/react"
|
||||
import { Play, SearchIcon, Share2, Shuffle, Star, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import {
|
||||
useCurrentSongId,
|
||||
usePlaybackActions,
|
||||
} from "@/components/playback-provider"
|
||||
import { MediaCollectionFooter } from "@/components/media-collection-footer"
|
||||
import { TrackNumberPlayButton } from "@/components/track-number-play-button"
|
||||
import {
|
||||
MediaContextMenu,
|
||||
type MediaContextAction,
|
||||
} from "@/components/media-context-menu"
|
||||
import { TrackRow } from "@/components/track-row"
|
||||
import { VirtualList } from "@/components/virtual-list"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenuItem,
|
||||
@@ -25,247 +28,23 @@ import {
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||
import {
|
||||
useMediaActions,
|
||||
useTrackListMediaAction,
|
||||
} from "@/hooks/use-media-actions"
|
||||
import { useTrackSelection } from "@/hooks/use-track-selection"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { BrowsePlaylistDetail, BrowseSong } from "@otunes/convex/types"
|
||||
import { albumCoverUrl, playlistCoverUrl } from "@/lib/cover-urls"
|
||||
import { playlistCoverUrl } from "@/lib/cover-urls"
|
||||
import { copyPlaylistLink } from "@/lib/media-links"
|
||||
import { sumDurationSeconds } from "@/lib/media-summary"
|
||||
import { rememberSongs } from "@/lib/song-cache"
|
||||
import { cn } from "@/lib/utils"
|
||||
import {
|
||||
getSelectionRangePositions,
|
||||
isInSelectionRange,
|
||||
ALBUM_TRACK_ROW,
|
||||
ALBUM_TRACK_TITLE,
|
||||
SelectionRangeHighlight,
|
||||
TrackRowActiveHighlight,
|
||||
TrackRowHoverHighlight,
|
||||
TRACK_ROW_PADDING,
|
||||
type SelectionRangePosition,
|
||||
} from "@/lib/selection-range-styles"
|
||||
import { filterSongs } from "@otunes/convex/client/song-search"
|
||||
import { getSelectionRangePositions } from "@/lib/selection-range-styles"
|
||||
|
||||
const ADD_TO_ANOTHER_PLAYLIST = "Add to Another Playlist"
|
||||
|
||||
function formatDuration(seconds: number): string {
|
||||
const minutes = Math.floor(seconds / 60)
|
||||
const remainingSeconds = seconds % 60
|
||||
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
function PlaylistSongCover({
|
||||
song,
|
||||
inRange,
|
||||
isFavorite,
|
||||
onToggleFavorite,
|
||||
}: {
|
||||
song: BrowseSong
|
||||
inRange: boolean
|
||||
isFavorite: boolean
|
||||
onToggleFavorite: () => void
|
||||
}) {
|
||||
return (
|
||||
<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>
|
||||
)
|
||||
}
|
||||
const estimatePlaylistRowSize = () => 60
|
||||
|
||||
export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
const router = useRouter()
|
||||
@@ -275,22 +54,17 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
currentUser === undefined
|
||||
? playlist.isOwner
|
||||
: currentUser?._id === playlist.owner.id
|
||||
const { openAddToPlaylist } = useAddToPlaylist()
|
||||
const { isSongFavorite, toggleSongFavorite, toggleSongsFavorite } =
|
||||
useFavorites()
|
||||
const currentSongId = useCurrentSongId()
|
||||
const {
|
||||
isSongFavorite,
|
||||
toggleSongFavorite,
|
||||
toggleSongsFavorite,
|
||||
favoriteSongs: addFavoriteSongs,
|
||||
} = useFavorites()
|
||||
const {
|
||||
currentSong,
|
||||
playInOrder,
|
||||
playShuffled,
|
||||
playPlaylist,
|
||||
playPlaylistShuffled,
|
||||
playFromSong,
|
||||
} = usePlayback()
|
||||
const { runQueueAction, createStation } = useQueueMediaActions()
|
||||
} = usePlaybackActions()
|
||||
const { runSongsAction } = useMediaActions()
|
||||
const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist)
|
||||
const reorderSongs = useMutation(api.playlists.reorderPlaylistSongs)
|
||||
const deletePlaylist = useMutation(api.playlists.deletePlaylist)
|
||||
@@ -306,22 +80,19 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
? playlist.songs.filter((song) => !hiddenFavoriteIds.has(song.id))
|
||||
: playlistSongs
|
||||
const [searchQuery, setSearchQuery] = React.useState("")
|
||||
const normalizedQuery = searchQuery.trim().toLowerCase()
|
||||
const isSearching = searchQuery.trim() !== ""
|
||||
const filteredSongs = React.useMemo(
|
||||
() =>
|
||||
normalizedQuery
|
||||
? songs.filter((song) =>
|
||||
[song.title, song.artist.name, song.album.title].some((value) =>
|
||||
value.toLowerCase().includes(normalizedQuery)
|
||||
)
|
||||
)
|
||||
: songs,
|
||||
[songs, normalizedQuery]
|
||||
() => filterSongs(songs, searchQuery),
|
||||
[songs, searchQuery]
|
||||
)
|
||||
const playlistSongIds = React.useMemo(
|
||||
() => songs.map((song) => song.id as Id<"songs">),
|
||||
[songs]
|
||||
)
|
||||
const playlistPositionById = React.useMemo(
|
||||
() => new Map(songs.map((song, index) => [song.id, index + 1])),
|
||||
[songs]
|
||||
)
|
||||
const [activeTrackId, setActiveTrackId] = React.useState("")
|
||||
const [dragIndex, setDragIndex] = React.useState<number | null>(null)
|
||||
const [isSubscribed, setIsSubscribed] = React.useState(playlist.isSubscribed)
|
||||
@@ -336,7 +107,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
const {
|
||||
selectedIds,
|
||||
selectedCount,
|
||||
isSelected,
|
||||
handleSelect,
|
||||
handlePointerDown,
|
||||
prepareContextMenu,
|
||||
@@ -374,57 +144,37 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
}
|
||||
}
|
||||
|
||||
function resolveTargetIds(fallbackSongId?: string) {
|
||||
return selectedIds.size > 0
|
||||
? Array.from(selectedIds)
|
||||
: fallbackSongId
|
||||
? [fallbackSongId]
|
||||
: activeTrackId
|
||||
? [activeTrackId]
|
||||
: []
|
||||
}
|
||||
|
||||
function handleMediaAction(
|
||||
action: MediaContextAction,
|
||||
fallbackSongId?: string
|
||||
) {
|
||||
const targetIds = resolveTargetIds(fallbackSongId)
|
||||
|
||||
switch (action) {
|
||||
case "create-station": {
|
||||
const artistId = stationArtistId(songs, new Set(targetIds))
|
||||
if (artistId) void createStation(artistId)
|
||||
break
|
||||
}
|
||||
case "favorite":
|
||||
void addFavoriteSongs(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "playlist":
|
||||
openAddToPlaylist(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle":
|
||||
void runQueueAction(action, targetIds as Id<"songs">[])
|
||||
break
|
||||
}
|
||||
}
|
||||
const handleMediaAction = useTrackListMediaAction({ selectedIds, songs })
|
||||
|
||||
function handlePlaylistMediaAction(action: MediaContextAction) {
|
||||
const targetIds = songs.map((song) => song.id as Id<"songs">)
|
||||
runSongsAction(action, playlistSongIds)
|
||||
}
|
||||
|
||||
switch (action) {
|
||||
case "favorite":
|
||||
void addFavoriteSongs(targetIds)
|
||||
break
|
||||
case "playlist":
|
||||
openAddToPlaylist(targetIds)
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle":
|
||||
void runQueueAction(action, targetIds)
|
||||
break
|
||||
const canReorder = isOwner && !isFavorites && !isSearching
|
||||
|
||||
function handleRowSelect(index: number, event: React.MouseEvent) {
|
||||
const songId = filteredSongs[index].id
|
||||
handleSelect(songId, index, event)
|
||||
setActiveTrackId(songId)
|
||||
}
|
||||
|
||||
function handleRowPlay(index: number) {
|
||||
void playFromSong(
|
||||
filteredSongs[index].id,
|
||||
playlistSongIds,
|
||||
`playlist:${playlist.id}`
|
||||
)
|
||||
}
|
||||
|
||||
function handleToggleFavorite(songId: string) {
|
||||
const wasFavorite = isSongFavorite(songId)
|
||||
void toggleSongFavorite(songId as Id<"songs">)
|
||||
if (isFavorites && wasFavorite) {
|
||||
setHiddenFavoriteIds((current) => {
|
||||
const next = new Set(current)
|
||||
next.add(songId)
|
||||
return next
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -435,10 +185,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
: [songId]
|
||||
|
||||
if (isFavorites) {
|
||||
const succeeded = await toggleSongsFavorite(
|
||||
ids as Id<"songs">[],
|
||||
true
|
||||
)
|
||||
const succeeded = await toggleSongsFavorite(ids as Id<"songs">[], true)
|
||||
if (!succeeded) return
|
||||
return
|
||||
}
|
||||
@@ -451,7 +198,9 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
setPlaylistSongs((current) =>
|
||||
current.filter((song) => !ids.includes(song.id))
|
||||
)
|
||||
toast.success(ids.length > 1 ? `Removed ${ids.length} songs` : "Removed song")
|
||||
toast.success(
|
||||
ids.length > 1 ? `Removed ${ids.length} songs` : "Removed song"
|
||||
)
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to remove song"
|
||||
@@ -479,13 +228,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
}
|
||||
|
||||
function handleDrop(targetIndex: number) {
|
||||
if (
|
||||
normalizedQuery ||
|
||||
isFavorites ||
|
||||
!isOwner ||
|
||||
dragIndex === null ||
|
||||
dragIndex === targetIndex
|
||||
) {
|
||||
if (!canReorder || dragIndex === null || dragIndex === targetIndex) {
|
||||
setDragIndex(null)
|
||||
return
|
||||
}
|
||||
@@ -546,7 +289,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
<PageHeader openApp />
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<div className="pb-28">
|
||||
<div className="mx-auto w-full min-w-0 max-w-9/10">
|
||||
<div className="mx-auto w-full max-w-9/10 min-w-0">
|
||||
<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">
|
||||
{isFavorites ? (
|
||||
@@ -676,80 +419,52 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
</div>
|
||||
</div>
|
||||
{filteredSongs.length > 0 ? (
|
||||
filteredSongs.map((song, index) => (
|
||||
<PlaylistSongRow
|
||||
key={song.id}
|
||||
song={song}
|
||||
index={index}
|
||||
isOwner={isOwner && !isFavorites && !normalizedQuery}
|
||||
canRemove={isFavorites || isOwner}
|
||||
showFavoriteInMenu={!isFavorites}
|
||||
removeLabel={
|
||||
isFavorites ? "Unfavorite" : "Remove from Playlist"
|
||||
}
|
||||
isActive={song.id === activeTrackId}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
isFavorite={isSongFavorite(song.id)}
|
||||
selectedCount={
|
||||
isSelected(song.id) && selectedCount > 0
|
||||
? selectedCount
|
||||
: 1
|
||||
}
|
||||
stationArtist={
|
||||
isSelected(song.id)
|
||||
? selectedStationArtistId
|
||||
: song.artist.id
|
||||
}
|
||||
isDragging={dragIndex === index}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={(event) => {
|
||||
handleSelect(song.id, index, event)
|
||||
setActiveTrackId(song.id)
|
||||
}}
|
||||
onToggleFavorite={() => {
|
||||
const wasFavorite = isSongFavorite(song.id)
|
||||
void toggleSongFavorite(song.id as Id<"songs">)
|
||||
if (isFavorites && wasFavorite) {
|
||||
setHiddenFavoriteIds((current) => {
|
||||
const next = new Set(current)
|
||||
next.add(song.id)
|
||||
return next
|
||||
})
|
||||
}
|
||||
}}
|
||||
onPrepareContextMenu={() => prepareContextMenu(song.id)}
|
||||
onMediaAction={handleMediaAction}
|
||||
onRemove={() => handleRemoveSong(song.id)}
|
||||
onDragStart={(event) => {
|
||||
if (normalizedQuery || isFavorites || !isOwner) {
|
||||
return
|
||||
}
|
||||
setDragIndex(index)
|
||||
event.dataTransfer.effectAllowed = "move"
|
||||
}}
|
||||
onDragOver={(event) => {
|
||||
if (normalizedQuery || isFavorites || !isOwner) {
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
}}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault()
|
||||
handleDrop(index)
|
||||
}}
|
||||
isNowPlaying={currentSong?.id === song.id}
|
||||
onPlay={() =>
|
||||
void playFromSong(
|
||||
song.id as Id<"songs">,
|
||||
playlistSongIds,
|
||||
`playlist:${playlist.id}`
|
||||
)
|
||||
}
|
||||
/>
|
||||
))
|
||||
<VirtualList
|
||||
count={filteredSongs.length}
|
||||
estimateSize={estimatePlaylistRowSize}
|
||||
getItemKey={(index) => filteredSongs[index].id}
|
||||
// Keep the drag source mounted so its drop still lands.
|
||||
keepMounted={dragIndex}
|
||||
renderItem={(index) => {
|
||||
const song = filteredSongs[index]
|
||||
return (
|
||||
<TrackRow
|
||||
variant="playlist"
|
||||
song={song}
|
||||
index={index}
|
||||
trackNumber={playlistPositionById.get(song.id)}
|
||||
isActive={song.id === activeTrackId}
|
||||
isNowPlaying={currentSongId === song.id}
|
||||
isFavorite={isSongFavorite(song.id)}
|
||||
isDragging={dragIndex === index}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
selectedCount={selectedCount}
|
||||
selectionStationArtistId={selectedStationArtistId}
|
||||
playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
|
||||
showFavoriteInMenu={!isFavorites}
|
||||
removeLabel={
|
||||
isFavorites
|
||||
? "Unfavorite"
|
||||
: isOwner
|
||||
? "Remove from Playlist"
|
||||
: undefined
|
||||
}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={handleRowSelect}
|
||||
onPlay={handleRowPlay}
|
||||
onToggleFavorite={handleToggleFavorite}
|
||||
onPrepareContextMenu={prepareContextMenu}
|
||||
onMediaAction={handleMediaAction}
|
||||
onRemove={handleRemoveSong}
|
||||
onDragStart={canReorder ? setDragIndex : undefined}
|
||||
onDrop={canReorder ? handleDrop : undefined}
|
||||
/>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<p className="px-6 py-8 text-sm text-muted-foreground">
|
||||
{normalizedQuery
|
||||
{isSearching
|
||||
? "No songs found."
|
||||
: "This playlist has no songs yet."}
|
||||
</p>
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import Image from "next/image"
|
||||
import { Music2 } from "lucide-react"
|
||||
|
||||
import { PlaybackSongMeta } from "@/components/playback-song-meta"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { TrackCover, TrackRow } from "@/components/track-row"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
@@ -13,21 +12,14 @@ import { Spinner } from "@/components/ui/spinner"
|
||||
import { useTrackSelection } from "@/hooks/use-track-selection"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { BrowseSong, HistorySong, QueueSong } from "@otunes/convex/types"
|
||||
import { albumCoverUrl } from "@/lib/cover-urls"
|
||||
import {
|
||||
getContiguousSelectedIndices,
|
||||
moveQueueBlock,
|
||||
} from "@/lib/move-queue-block"
|
||||
import {
|
||||
getSelectionRangePositions,
|
||||
isInSelectionRange,
|
||||
QueueSelectionRangeHighlight,
|
||||
QueueTrackRowActiveHighlight,
|
||||
QueueTrackRowHoverHighlight,
|
||||
type SelectionRangePosition,
|
||||
} from "@/lib/selection-range-styles"
|
||||
import { getSelectionRangePositions } from "@/lib/selection-range-styles"
|
||||
import { useSongs } from "@/lib/song-cache"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { formatDuration } from "@/lib/format-duration"
|
||||
|
||||
const QUEUE_INITIAL_VISIBLE_COUNT = 100
|
||||
const QUEUE_PAGE_SIZE = 50
|
||||
@@ -40,12 +32,6 @@ type QueueItem = {
|
||||
song: QueueSelectable | null
|
||||
}
|
||||
|
||||
function formatDuration(seconds: number): string {
|
||||
const minutes = Math.floor(seconds / 60)
|
||||
const remainingSeconds = seconds % 60
|
||||
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
function toSelectableQueue(
|
||||
songIds: Id<"songs">[],
|
||||
songs: (BrowseSong | undefined)[]
|
||||
@@ -61,48 +47,16 @@ function toSelectableQueue(
|
||||
})
|
||||
}
|
||||
|
||||
function QueueSongCover({
|
||||
albumId,
|
||||
title,
|
||||
inRange,
|
||||
}: {
|
||||
albumId: string
|
||||
title: string
|
||||
inRange: boolean
|
||||
}) {
|
||||
return (
|
||||
<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 }) {
|
||||
return (
|
||||
<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">
|
||||
{song.album.id ? (
|
||||
<QueueSongCover
|
||||
albumId={song.album.id}
|
||||
title={song.album.title}
|
||||
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>
|
||||
)}
|
||||
<TrackCover
|
||||
albumId={song.album.id}
|
||||
alt={song.album.title}
|
||||
inRange={false}
|
||||
square
|
||||
/>
|
||||
|
||||
<PlaybackSongMeta
|
||||
song={song}
|
||||
@@ -120,106 +74,6 @@ 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() {
|
||||
return (
|
||||
<li className="flex items-center gap-3 px-2 py-2" aria-hidden>
|
||||
@@ -243,7 +97,7 @@ export function QueuePanel() {
|
||||
skipToQueueIndex,
|
||||
} = usePlayback()
|
||||
const loadMoreRef = React.useRef<HTMLDivElement>(null)
|
||||
const nowPlayingRef = React.useRef<HTMLLIElement>(null)
|
||||
const nowPlayingRef = React.useRef<HTMLElement>(null)
|
||||
const [visibleCount, setVisibleCount] = React.useState(
|
||||
QUEUE_INITIAL_VISIBLE_COUNT
|
||||
)
|
||||
@@ -311,12 +165,25 @@ export function QueuePanel() {
|
||||
return () => observer.disconnect()
|
||||
}, [hasMore])
|
||||
|
||||
const {
|
||||
selectedIds,
|
||||
handleSelect,
|
||||
handlePointerDown,
|
||||
} = useTrackSelection(
|
||||
selectableQueue.map((item) => ({ id: item.selectionId }))
|
||||
const selectionItems = React.useMemo(
|
||||
() => selectableQueue.map((item) => ({ id: item.selectionId })),
|
||||
[selectableQueue]
|
||||
)
|
||||
const { selectedIds, handleSelect, handlePointerDown } =
|
||||
useTrackSelection(selectionItems)
|
||||
|
||||
const handleRowSelect = React.useCallback(
|
||||
(index: number, event: React.MouseEvent) => {
|
||||
handleSelect(selectableQueue[index].selectionId, index, event)
|
||||
},
|
||||
[selectableQueue, handleSelect]
|
||||
)
|
||||
|
||||
const handleRowPlay = React.useCallback(
|
||||
(index: number) => {
|
||||
void skipToQueueIndex(selectableQueue[index].queueIndex)
|
||||
},
|
||||
[selectableQueue, skipToQueueIndex]
|
||||
)
|
||||
|
||||
const selectionPositions = React.useMemo(
|
||||
@@ -403,27 +270,21 @@ export function QueuePanel() {
|
||||
<ul className="flex flex-col py-1">
|
||||
{selectableQueue.map((item, index) =>
|
||||
item.song ? (
|
||||
<QueueSongRow
|
||||
<TrackRow
|
||||
key={item.selectionId}
|
||||
ref={item.queueIndex === 0 ? nowPlayingRef : undefined}
|
||||
variant="queue"
|
||||
song={item.song}
|
||||
index={index}
|
||||
isActive={item.queueIndex === 0}
|
||||
isNowPlaying={item.queueIndex === 0}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
isDragging={draggingIndices.has(index)}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={(event) => {
|
||||
handleSelect(item.selectionId, index, event)
|
||||
}}
|
||||
onSkipTo={() => void skipToQueueIndex(item.queueIndex)}
|
||||
onDragStart={(event) => {
|
||||
setDragIndex(index)
|
||||
event.dataTransfer.effectAllowed = "move"
|
||||
}}
|
||||
onDragOver={(event) => event.preventDefault()}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault()
|
||||
handleDrop(index)
|
||||
}}
|
||||
onSelect={handleRowSelect}
|
||||
onPlay={handleRowPlay}
|
||||
onDragStart={setDragIndex}
|
||||
onDrop={handleDrop}
|
||||
/>
|
||||
) : (
|
||||
<QueueSongRowSkeleton key={item.selectionId} />
|
||||
|
||||
@@ -8,6 +8,8 @@ import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||
import {
|
||||
MediaContextMenu,
|
||||
type MediaContextAction,
|
||||
MediaContextMenuArea,
|
||||
type MediaContextMenuProps,
|
||||
} from "@/components/media-context-menu"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
@@ -38,52 +40,57 @@ export function SearchSongItem({ song }: { song: BrowseSong }) {
|
||||
}
|
||||
}
|
||||
|
||||
const menu: MediaContextMenuProps = {
|
||||
label: `More options for ${song.title}`,
|
||||
stationArtistId: song.artist.id,
|
||||
selectedCount: 1,
|
||||
onOpenMenu: () => {},
|
||||
onAction: handleAction,
|
||||
favorited: isSongFavorite(song.id),
|
||||
navigation: {
|
||||
artist: { id: song.artist.id },
|
||||
album: { id: song.album.id },
|
||||
},
|
||||
share: {
|
||||
type: "song",
|
||||
albumId: song.album.id,
|
||||
songId: song.id,
|
||||
},
|
||||
triggerClassName:
|
||||
"size-8 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100",
|
||||
triggerVariant: "ghost",
|
||||
}
|
||||
|
||||
return (
|
||||
<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>
|
||||
<MediaContextMenuArea menu={menu}>
|
||||
<div className="group flex items-center gap-3 rounded-lg px-1 py-1.5 transition-colors hover:bg-muted/50">
|
||||
<Link
|
||||
href={`/artist/${song.artist.id}`}
|
||||
className="text-muted-foreground hover:text-foreground hover:underline"
|
||||
href={`/album/${song.album.id}`}
|
||||
className="relative size-11 shrink-0 overflow-hidden rounded ring-1 ring-foreground/10"
|
||||
>
|
||||
<p className="truncate text-sm">{song.artist.name}</p>
|
||||
<Image
|
||||
src={albumCoverUrl(song.album.id)}
|
||||
alt={song.album.title}
|
||||
fill
|
||||
sizes="44px"
|
||||
className="object-cover"
|
||||
/>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<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>
|
||||
<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>
|
||||
</MediaContextMenuArea>
|
||||
)
|
||||
}
|
||||
@@ -2,18 +2,20 @@
|
||||
|
||||
import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger"
|
||||
import { stationArtistId } from "@/lib/station-artist"
|
||||
import { useEffect, useMemo, useState, useRef, MouseEvent } from "react"
|
||||
import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
import { ArrowUpDown, Play, Star } from "lucide-react"
|
||||
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import {
|
||||
MediaContextMenu,
|
||||
type MediaContextAction,
|
||||
} from "@/components/media-context-menu"
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
useRef,
|
||||
type MouseEvent,
|
||||
} from "react"
|
||||
import { ArrowUpDown } from "lucide-react"
|
||||
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import { LibraryTrackListHeader, TrackRow } from "@/components/track-row"
|
||||
import { VirtualList } from "@/components/virtual-list"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -25,252 +27,28 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
|
||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||
import { useTrackListMediaAction } from "@/hooks/use-media-actions"
|
||||
import { useTrackSelection } from "@/hooks/use-track-selection"
|
||||
import { SongListSkeleton } from "@/components/library-skeletons"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { Spinner } from "@/components/ui/spinner"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import { cn } from "@/lib/utils"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
import { albumCoverUrl } from "@/lib/cover-urls"
|
||||
import {
|
||||
getSelectionRangePositions,
|
||||
isInSelectionRange,
|
||||
ALBUM_TRACK_TITLE,
|
||||
SongsSelectionRangeHighlight,
|
||||
SongsTrackRowHoverHighlight,
|
||||
TRACK_ROW_PADDING,
|
||||
type SelectionRangePosition,
|
||||
} from "@/lib/selection-range-styles"
|
||||
|
||||
type SortKey = "title" | "artist" | "album"
|
||||
type SortDirection = "asc" | "desc"
|
||||
|
||||
const SONGS_PAGE_SIZE = 50
|
||||
|
||||
const songRowLayout =
|
||||
"flex w-full items-center gap-x-4"
|
||||
const nameColumnLayout =
|
||||
"grid grid-cols-[2rem_2.5rem_minmax(0,10rem)] items-center gap-x-2"
|
||||
const songColumnClass = "w-36 shrink-0 truncate"
|
||||
|
||||
function formatDuration(seconds: number): string {
|
||||
const minutes = Math.floor(seconds / 60)
|
||||
const remainingSeconds = seconds % 60
|
||||
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
function SongCover({
|
||||
song,
|
||||
inRange,
|
||||
onPlay,
|
||||
}: {
|
||||
song: BrowseSong
|
||||
inRange: boolean
|
||||
onPlay: () => void
|
||||
}) {
|
||||
return (
|
||||
<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>
|
||||
)
|
||||
}
|
||||
const estimateSongRowSize = () => 56
|
||||
|
||||
export function SongsView() {
|
||||
const { openAddToPlaylist } = useAddToPlaylist()
|
||||
const { isSongFavorite, toggleSongFavorite, favoriteSongs } = useFavorites()
|
||||
const { playFromLibrarySong } = usePlayback()
|
||||
const { runQueueAction, createStation } = useQueueMediaActions()
|
||||
const { isSongFavorite, toggleSongFavorite } = useFavorites()
|
||||
const { playFromLibrarySong } = usePlaybackActions()
|
||||
const [sortKey, setSortKey] = useState<SortKey>("title")
|
||||
const [sortDirection, setSortDirection] =
|
||||
useState<SortDirection>("asc")
|
||||
@@ -311,7 +89,6 @@ export function SongsView() {
|
||||
const {
|
||||
selectedIds,
|
||||
selectedCount,
|
||||
isSelected,
|
||||
handleSelect,
|
||||
handlePointerDown,
|
||||
prepareContextMenu,
|
||||
@@ -332,32 +109,27 @@ export function SongsView() {
|
||||
[songs, selectedIds]
|
||||
)
|
||||
|
||||
function handleMediaAction(action: MediaContextAction, fallbackSongId?: string) {
|
||||
const targetIds =
|
||||
selectedIds.size > 0
|
||||
? Array.from(selectedIds)
|
||||
: fallbackSongId
|
||||
? [fallbackSongId]
|
||||
: []
|
||||
switch (action) {
|
||||
case "create-station": {
|
||||
const artistId = stationArtistId(songs, new Set(targetIds))
|
||||
if (artistId) void createStation(artistId)
|
||||
break
|
||||
}
|
||||
case "favorite":
|
||||
void favoriteSongs(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "playlist":
|
||||
openAddToPlaylist(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle":
|
||||
void runQueueAction(action, targetIds as Id<"songs">[])
|
||||
break
|
||||
}
|
||||
}
|
||||
const handleMediaAction = useTrackListMediaAction({ selectedIds, songs })
|
||||
|
||||
const handleRowSelect = useCallback(
|
||||
(index: number, event: MouseEvent) => {
|
||||
handleSelect(songs[index].id, index, event)
|
||||
},
|
||||
[songs, handleSelect]
|
||||
)
|
||||
|
||||
const handleRowPlay = useCallback(
|
||||
(index: number) => {
|
||||
void playFromLibrarySong(songs[index].id, { sortKey, sortDirection })
|
||||
},
|
||||
[songs, sortKey, sortDirection, playFromLibrarySong]
|
||||
)
|
||||
|
||||
const handleToggleFavorite = useCallback(
|
||||
(songId: string) => void toggleSongFavorite(songId as Id<"songs">),
|
||||
[toggleSongFavorite]
|
||||
)
|
||||
const getSongKey = useCallback((index: number) => songs[index].id, [songs])
|
||||
|
||||
if (status === "LoadingFirstPage" && !isCached) {
|
||||
return (
|
||||
@@ -428,7 +200,7 @@ export function SongsView() {
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<ScrollArea className="min-h-0 flex-1 [&_[data-slot=scroll-area-viewport]>div]:block!">
|
||||
<div
|
||||
className="w-full pb-28"
|
||||
onClick={(event) => {
|
||||
@@ -437,68 +209,29 @@ export function SongsView() {
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="border-none hover:bg-transparent">
|
||||
<TableHead colSpan={4} className="h-9 p-0 font-normal">
|
||||
<div className={cn(songRowLayout, TRACK_ROW_PADDING)}>
|
||||
<div className={nameColumnLayout}>
|
||||
<span aria-hidden />
|
||||
<span aria-hidden />
|
||||
<span className="text-xs text-muted-foreground">Name</span>
|
||||
</div>
|
||||
<span className={cn(songColumnClass, "text-xs text-muted-foreground")}>
|
||||
Artist
|
||||
</span>
|
||||
<span className={cn(songColumnClass, "text-xs text-muted-foreground")}>
|
||||
Album
|
||||
</span>
|
||||
<div className="min-w-4 flex-1" />
|
||||
<span className="shrink-0 text-right text-xs text-muted-foreground">
|
||||
Time
|
||||
</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>
|
||||
<LibraryTrackListHeader />
|
||||
<VirtualList
|
||||
count={songs.length}
|
||||
estimateSize={estimateSongRowSize}
|
||||
getItemKey={getSongKey}
|
||||
renderItem={(index) => (
|
||||
<TrackRow
|
||||
variant="library"
|
||||
song={songs[index]}
|
||||
index={index}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
isFavorite={isSongFavorite(songs[index].id)}
|
||||
selectedCount={selectedCount}
|
||||
selectionStationArtistId={selectedStationArtistId}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={handleRowSelect}
|
||||
onPlay={handleRowPlay}
|
||||
onToggleFavorite={handleToggleFavorite}
|
||||
onPrepareContextMenu={prepareContextMenu}
|
||||
onMediaAction={handleMediaAction}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
ref={loadMoreRef}
|
||||
className="flex items-center justify-center py-4"
|
||||
|
||||
@@ -3,10 +3,62 @@
|
||||
import type { MouseEvent } from "react"
|
||||
import { AudioLines, Pause, Play } from "lucide-react"
|
||||
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import {
|
||||
useIsPlaying,
|
||||
usePlaybackActions,
|
||||
} from "@/components/playback-provider"
|
||||
import { Button } from "@/components/ui/button"
|
||||
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({
|
||||
displayTrack,
|
||||
title,
|
||||
@@ -22,26 +74,7 @@ export function TrackNumberPlayButton({
|
||||
inRange: boolean
|
||||
onPlay: () => void
|
||||
}) {
|
||||
const { isPlaying, setIsPlaying } = usePlayback()
|
||||
const showPlay = isActive || isNowPlaying
|
||||
const isCurrentlyPlaying = isNowPlaying && isPlaying
|
||||
|
||||
const buttonClassName = cn(
|
||||
"absolute size-8 opacity-0 transition-opacity group-hover:opacity-100",
|
||||
showPlay && "opacity-100",
|
||||
inRange
|
||||
? "text-primary-foreground hover:bg-white/15 hover:text-primary-foreground"
|
||||
: "text-primary hover:text-primary"
|
||||
)
|
||||
|
||||
const handleClick = (event: MouseEvent) => {
|
||||
event.stopPropagation()
|
||||
if (isNowPlaying) {
|
||||
setIsPlaying(!isPlaying)
|
||||
return
|
||||
}
|
||||
onPlay()
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -59,35 +92,17 @@ export function TrackNumberPlayButton({
|
||||
{displayTrack}
|
||||
</span>
|
||||
{isNowPlaying ? (
|
||||
<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>
|
||||
<NowPlayingButton title={title} inRange={inRange} />
|
||||
) : (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className={buttonClassName}
|
||||
className={trackButtonClassName(showPlay, inRange)}
|
||||
aria-label={`Play ${title}`}
|
||||
onClick={handleClick}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onPlay()
|
||||
}}
|
||||
>
|
||||
<Play className="size-4 fill-current" />
|
||||
</Button>
|
||||
|
||||
@@ -0,0 +1,518 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
import { Music2, Play, Star, Trash2 } from "lucide-react"
|
||||
|
||||
import {
|
||||
MediaContextMenu,
|
||||
MediaContextMenuArea,
|
||||
MediaMenuItem,
|
||||
MediaMenuSeparator,
|
||||
type MediaContextAction,
|
||||
type MediaContextMenuProps,
|
||||
} from "@/components/media-context-menu"
|
||||
import { PlaybackSongMeta } from "@/components/playback-song-meta"
|
||||
import { TrackNumberPlayButton } from "@/components/track-number-play-button"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { albumCoverUrl } from "@/lib/cover-urls"
|
||||
import {
|
||||
ALBUM_TRACK_ROW,
|
||||
ALBUM_TRACK_TITLE,
|
||||
isInSelectionRange,
|
||||
SelectionRangeHighlight,
|
||||
TrackRowActiveHighlight,
|
||||
TrackRowHoverHighlight,
|
||||
TRACK_ROW_PADDING,
|
||||
type SelectionRangePosition,
|
||||
} from "@/lib/selection-range-styles"
|
||||
import { formatDuration } from "@/lib/format-duration"
|
||||
import { cn } from "@/lib/utils"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
|
||||
/**
|
||||
* - `library`: favorite star, cover with play overlay, title, artist and album
|
||||
* columns (use with `LibraryTrackListHeader`).
|
||||
* - `album`: favorite star, track number, title with optional credits.
|
||||
* - `playlist`: cover with favorite overlay, track number, title.
|
||||
* - `queue`: square cover, title and artist, no menu.
|
||||
*/
|
||||
export type TrackRowVariant = "library" | "album" | "playlist" | "queue"
|
||||
|
||||
export type TrackRowProps = {
|
||||
variant: TrackRowVariant
|
||||
song: BrowseSong
|
||||
/** Position in the list the selection hook was given. */
|
||||
index: number
|
||||
/** Number shown in the track number column (`album` and `playlist`). */
|
||||
trackNumber?: number
|
||||
/** Secondary line under the title, e.g. album track credits. */
|
||||
subtitle?: string
|
||||
selectionPosition: SelectionRangePosition
|
||||
isActive?: boolean
|
||||
isNowPlaying?: boolean
|
||||
isFavorite?: boolean
|
||||
isDragging?: boolean
|
||||
/** Total selected songs; the menu acts on these when this row is selected. */
|
||||
selectedCount?: number
|
||||
/** Station artist for the selection when this row is selected. */
|
||||
selectionStationArtistId?: string
|
||||
playlistLabel?: string
|
||||
showFavoriteInMenu?: boolean
|
||||
/** Adds a destructive menu item calling `onRemove`. */
|
||||
removeLabel?: string
|
||||
ref?: React.Ref<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)
|
||||
@@ -0,0 +1,120 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
defaultRangeExtractor,
|
||||
useVirtualizer,
|
||||
type Range,
|
||||
} from "@tanstack/react-virtual"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const scrollViewportSelector = '[data-slot="scroll-area-viewport"]'
|
||||
|
||||
/**
|
||||
* Renders only the visible items of a list placed inside a `ScrollArea`.
|
||||
* The list may sit below other content in the same viewport.
|
||||
*/
|
||||
export function VirtualList({
|
||||
count,
|
||||
estimateSize,
|
||||
getItemKey,
|
||||
renderItem,
|
||||
overscan = 10,
|
||||
keepMounted = null,
|
||||
className,
|
||||
}: {
|
||||
count: number
|
||||
estimateSize: (index: number) => number
|
||||
getItemKey: (index: number) => string
|
||||
renderItem: (index: number) => React.ReactNode
|
||||
overscan?: number
|
||||
/** Index rendered even when off screen, e.g. the source of a drag. */
|
||||
keepMounted?: number | null
|
||||
className?: string
|
||||
}) {
|
||||
const listRef = React.useRef<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>
|
||||
)
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import { exportJWK, exportPKCS8, generateKeyPair } from "jose";
|
||||
|
||||
const keys = await generateKeyPair("RS256", {
|
||||
extractable: true,
|
||||
});
|
||||
const privateKey = await exportPKCS8(keys.privateKey);
|
||||
const publicKey = await exportJWK(keys.publicKey);
|
||||
const jwks = JSON.stringify({ keys: [{ use: "sig", ...publicKey }] });
|
||||
|
||||
process.stdout.write(
|
||||
`JWT_PRIVATE_KEY="${privateKey.trimEnd().replace(/\n/g, " ")}"`,
|
||||
);
|
||||
process.stdout.write("\n");
|
||||
process.stdout.write(`JWKS=${jwks}`);
|
||||
process.stdout.write("\n");
|
||||
@@ -9,13 +9,18 @@ import {
|
||||
type PaginatedQueryReference,
|
||||
} from "convex/react"
|
||||
import type { FunctionReference } from "convex/server"
|
||||
import { useCallback, useEffect, useSyncExternalStore } from "react"
|
||||
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react"
|
||||
|
||||
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||
import { queryCacheKey } from "@otunes/convex/client/cached-query"
|
||||
import { readCache, subscribeCache, writeCache } from "@/lib/persistent-cache"
|
||||
|
||||
const MAX_CACHED_PAGINATED_ITEMS = 200
|
||||
const MAX_RESTORED_PAGINATED_ITEMS = 1000
|
||||
|
||||
// Items loaded per paginated query this session, so a remount (e.g. back
|
||||
// navigation) loads as much as before and scroll restoration can reach it.
|
||||
const loadedItemCounts = new Map<string, number>()
|
||||
|
||||
const noopUnsubscribe = () => {}
|
||||
|
||||
@@ -65,6 +70,7 @@ export function useCachedQuery<Query extends FunctionReference<"query">>(
|
||||
/**
|
||||
* `usePaginatedQuery` that shows the first persisted pages while the first live
|
||||
* page loads. `isCached` is true while those persisted results are shown.
|
||||
* Remounts start with as many items as were last loaded this session.
|
||||
*/
|
||||
export function useCachedPaginatedQuery<Query extends PaginatedQueryReference>(
|
||||
query: Query,
|
||||
@@ -72,15 +78,28 @@ export function useCachedPaginatedQuery<Query extends PaginatedQueryReference>(
|
||||
options: { initialNumItems: number }
|
||||
) {
|
||||
const scope = useCacheScope()
|
||||
const result = usePaginatedQuery(query, args, options)
|
||||
const key =
|
||||
args === "skip"
|
||||
? null
|
||||
: `${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)
|
||||
|
||||
useEffect(() => {
|
||||
if (key && result.status !== "LoadingFirstPage") {
|
||||
loadedItemCounts.set(key, result.results.length)
|
||||
writeCache(key, result.results.slice(0, MAX_CACHED_PAGINATED_ITEMS))
|
||||
}
|
||||
}, [key, result.status, result.results])
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { useConvex } from "convex/react"
|
||||
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import type { MediaContextAction } from "@/components/media-context-menu"
|
||||
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||
import { stationArtistId } from "@/lib/station-artist"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
|
||||
|
||||
export function useMediaActions() {
|
||||
const { openAddToPlaylist, openAddArtistToPlaylist } = useAddToPlaylist()
|
||||
const { favoriteSongs, toggleArtistFavorite } = useFavorites()
|
||||
const { runQueueAction, createStation } = useQueueMediaActions()
|
||||
const convex = useConvex()
|
||||
const cacheScope = useCacheScope()
|
||||
|
||||
const runSongsAction = React.useCallback(
|
||||
(
|
||||
action: MediaContextAction,
|
||||
songIds: Id<"songs">[],
|
||||
stationArtist?: string
|
||||
) => {
|
||||
switch (action) {
|
||||
case "create-station":
|
||||
if (stationArtist) void createStation(stationArtist)
|
||||
break
|
||||
case "favorite":
|
||||
void favoriteSongs(songIds)
|
||||
break
|
||||
case "playlist":
|
||||
openAddToPlaylist(songIds)
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle":
|
||||
void runQueueAction(action, songIds)
|
||||
break
|
||||
}
|
||||
},
|
||||
[createStation, favoriteSongs, openAddToPlaylist, runQueueAction]
|
||||
)
|
||||
|
||||
const runArtistAction = React.useCallback(
|
||||
async (action: MediaContextAction, artistId: string) => {
|
||||
switch (action) {
|
||||
case "favorite":
|
||||
void toggleArtistFavorite(artistId as Id<"artists">)
|
||||
break
|
||||
case "playlist":
|
||||
void openAddArtistToPlaylist(artistId as Id<"artists">)
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle": {
|
||||
const songIds = await fetchCachedQuery(
|
||||
convex,
|
||||
cacheScope,
|
||||
api.playlists.getOrderedArtistSongIds,
|
||||
{ artistId: artistId as Id<"artists"> }
|
||||
)
|
||||
void runQueueAction(action, songIds)
|
||||
break
|
||||
}
|
||||
}
|
||||
},
|
||||
[convex, cacheScope, toggleArtistFavorite, openAddArtistToPlaylist, runQueueAction]
|
||||
)
|
||||
|
||||
return { runSongsAction, runArtistAction }
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a track row menu action, targeting the current selection or else the
|
||||
* row's song. The station artist is `artistId` when given, otherwise the artist
|
||||
* every targeted song in `songs` shares.
|
||||
*/
|
||||
export function useTrackListMediaAction({
|
||||
selectedIds,
|
||||
songs,
|
||||
artistId,
|
||||
}: {
|
||||
selectedIds: ReadonlySet<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]
|
||||
)
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
import * as React from "react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import type { MediaContextAction } from "@/components/media-context-menu"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
|
||||
@@ -29,7 +29,7 @@ function queueActionMessage(action: QueueMediaAction, count: number) {
|
||||
|
||||
export function useQueueMediaActions() {
|
||||
const { addToQueueNext, addToQueueLast, playShuffled, playArtistShuffled } =
|
||||
usePlayback()
|
||||
usePlaybackActions()
|
||||
|
||||
const runQueueAction = React.useCallback(
|
||||
async (action: QueueMediaAction, songIds: Id<"songs">[]) => {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
|
||||
/**
|
||||
* Returns a function with a stable identity that always calls the latest
|
||||
* `callback`. Only call it from event handlers, never during render.
|
||||
*/
|
||||
export function useStableCallback<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), [])
|
||||
}
|
||||
@@ -1,9 +1,3 @@
|
||||
/** Shared layout for album grids and carousel slides (gap-x-6 = 1.5rem). */
|
||||
/** Shared layout for album grids. */
|
||||
export const albumGridClassName =
|
||||
"grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6"
|
||||
|
||||
/** Slide width matches one cell of `albumGridClassName` inside an `@container` ancestor. */
|
||||
export const albumGridCarouselSlideClassName =
|
||||
"w-[calc((100cqw-1.5rem)/2)] shrink-0 grow-0 basis-auto pl-6 sm:w-[calc((100cqw-3rem)/3)] md:w-[calc((100cqw-4.5rem)/4)] lg:w-[calc((100cqw-6rem)/5)] xl:w-[calc((100cqw-7.5rem)/6)]"
|
||||
|
||||
export const albumGridCarouselContentClassName = "-ml-6"
|
||||
@@ -1,19 +0,0 @@
|
||||
import type {
|
||||
BrowseAlbum,
|
||||
BrowseAlbumDetail,
|
||||
BrowseAlbumTrack,
|
||||
BrowseArtist,
|
||||
BrowsePlaylistDetail,
|
||||
BrowsePlaylistOwner,
|
||||
BrowseSong,
|
||||
PlaylistSummary,
|
||||
} from "@otunes/convex/types"
|
||||
|
||||
export type Artist = BrowseArtist
|
||||
export type Album = BrowseAlbum
|
||||
export type Song = BrowseSong
|
||||
export type Playlist = PlaylistSummary
|
||||
export type PlaylistOwner = BrowsePlaylistOwner
|
||||
export type PlaylistDetail = BrowsePlaylistDetail
|
||||
export type AlbumTrack = BrowseAlbumTrack
|
||||
export type AlbumDetail = BrowseAlbumDetail
|
||||
@@ -0,0 +1,7 @@
|
||||
/** Formats seconds as `m:ss`, flooring fractional and negative input. */
|
||||
export function formatDuration(seconds: number): string {
|
||||
const total = Math.max(0, Math.floor(seconds))
|
||||
const minutes = Math.floor(total / 60)
|
||||
const remainingSeconds = total % 60
|
||||
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
|
||||
}
|
||||
@@ -1,72 +1,22 @@
|
||||
import { toast } from "sonner"
|
||||
import {
|
||||
mediaShareUrl,
|
||||
type MediaShareTarget,
|
||||
} from "@otunes/convex/client/media-links"
|
||||
|
||||
export type MediaShareContext =
|
||||
| { type: "album"; albumId: string }
|
||||
| { type: "song"; albumId: string; songId: string }
|
||||
| { type: "playlist"; playlistId: string; isFavorites?: boolean }
|
||||
| { type: "artist"; artistId: string }
|
||||
|
||||
function mediaOrigin() {
|
||||
if (typeof window === "undefined") {
|
||||
return ""
|
||||
}
|
||||
return window.location.origin
|
||||
}
|
||||
|
||||
export function albumShareUrl(albumId: string) {
|
||||
return `${mediaOrigin()}/album/${albumId}`
|
||||
}
|
||||
|
||||
export function songShareUrl(albumId: string, songId: string) {
|
||||
return `${mediaOrigin()}/album/${albumId}?s=${songId}`
|
||||
}
|
||||
|
||||
export function playlistShareUrl(
|
||||
playlistId: string,
|
||||
options?: { isFavorites?: boolean }
|
||||
) {
|
||||
if (options?.isFavorites) {
|
||||
return `${mediaOrigin()}/playlist/favorites`
|
||||
}
|
||||
return `${mediaOrigin()}/playlist/${playlistId}`
|
||||
}
|
||||
|
||||
export function artistShareUrl(artistId: string) {
|
||||
return `${mediaOrigin()}/artist/${artistId}`
|
||||
}
|
||||
|
||||
export function mediaShareUrl(share: MediaShareContext) {
|
||||
switch (share.type) {
|
||||
case "album":
|
||||
return albumShareUrl(share.albumId)
|
||||
case "song":
|
||||
return songShareUrl(share.albumId, share.songId)
|
||||
case "playlist":
|
||||
return playlistShareUrl(share.playlistId, {
|
||||
isFavorites: share.isFavorites,
|
||||
})
|
||||
case "artist":
|
||||
return artistShareUrl(share.artistId)
|
||||
}
|
||||
}
|
||||
|
||||
export async function copyTextToClipboard(text: string) {
|
||||
await navigator.clipboard.writeText(text)
|
||||
toast.success("Link Copied")
|
||||
}
|
||||
export type MediaShareContext = MediaShareTarget
|
||||
|
||||
export async function copyMediaShareLink(share: MediaShareContext) {
|
||||
await copyTextToClipboard(mediaShareUrl(share))
|
||||
await navigator.clipboard.writeText(
|
||||
mediaShareUrl(window.location.origin, share)
|
||||
)
|
||||
toast.success("Link Copied")
|
||||
}
|
||||
|
||||
export async function copyAlbumLink(albumId: string) {
|
||||
await copyMediaShareLink({ type: "album", albumId })
|
||||
}
|
||||
|
||||
export async function copySongLink(albumId: string, songId: string) {
|
||||
await copyMediaShareLink({ type: "song", albumId, songId })
|
||||
}
|
||||
|
||||
export async function copyPlaylistLink(
|
||||
playlistId: string,
|
||||
options?: { isFavorites?: boolean }
|
||||
@@ -77,7 +27,3 @@ export async function copyPlaylistLink(
|
||||
isFavorites: options?.isFavorites,
|
||||
})
|
||||
}
|
||||
|
||||
export async function copyArtistLink(artistId: string) {
|
||||
await copyMediaShareLink({ type: "artist", artistId })
|
||||
}
|
||||
@@ -63,10 +63,19 @@ export function selectionHighlightRadiusClass(
|
||||
|
||||
export const TRACK_ROW_HIGHLIGHT_INSET = "absolute inset-y-0 left-2 right-2"
|
||||
|
||||
/** Full-width, square-corner highlight used by the library and queue lists. */
|
||||
export const FLUSH_ROW_HIGHLIGHT_INSET = "absolute inset-0"
|
||||
|
||||
/**
|
||||
* Track row highlights are inset rounded pills by default; `flush` makes them
|
||||
* full-width with square corners.
|
||||
*/
|
||||
export function SelectionRangeHighlight({
|
||||
position,
|
||||
flush = false,
|
||||
}: {
|
||||
position: SelectionRangePosition
|
||||
flush?: boolean
|
||||
}) {
|
||||
if (position === "none") {
|
||||
return null
|
||||
@@ -77,34 +86,34 @@ export function SelectionRangeHighlight({
|
||||
aria-hidden
|
||||
className={cn(
|
||||
"pointer-events-none bg-primary",
|
||||
TRACK_ROW_HIGHLIGHT_INSET,
|
||||
selectionHighlightRadiusClass(position)
|
||||
flush
|
||||
? FLUSH_ROW_HIGHLIGHT_INSET
|
||||
: [TRACK_ROW_HIGHLIGHT_INSET, selectionHighlightRadiusClass(position)]
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** Inset rounded hover background matching the selection pill shape. */
|
||||
export function TrackRowHoverHighlight() {
|
||||
export function TrackRowHoverHighlight({ flush = false }: { flush?: boolean }) {
|
||||
return (
|
||||
<div
|
||||
aria-hidden
|
||||
className={cn(
|
||||
"pointer-events-none rounded-lg bg-muted/60 opacity-0 transition-opacity group-hover:opacity-100",
|
||||
TRACK_ROW_HIGHLIGHT_INSET
|
||||
"pointer-events-none bg-muted/60 opacity-0 transition-opacity group-hover:opacity-100",
|
||||
flush ? FLUSH_ROW_HIGHLIGHT_INSET : [TRACK_ROW_HIGHLIGHT_INSET, "rounded-lg"]
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** Inset rounded background for the active (now playing) row. */
|
||||
export function TrackRowActiveHighlight() {
|
||||
/** Background for the active (focused or now playing) row. */
|
||||
export function TrackRowActiveHighlight({ flush = false }: { flush?: boolean }) {
|
||||
return (
|
||||
<div
|
||||
aria-hidden
|
||||
className={cn(
|
||||
"pointer-events-none rounded-lg bg-muted/60",
|
||||
TRACK_ROW_HIGHLIGHT_INSET
|
||||
"pointer-events-none bg-muted/60",
|
||||
flush ? FLUSH_ROW_HIGHLIGHT_INSET : [TRACK_ROW_HIGHLIGHT_INSET, "rounded-lg"]
|
||||
)}
|
||||
/>
|
||||
)
|
||||
@@ -116,42 +125,6 @@ export const TRACK_ROW_PADDING = "pl-8 pr-10"
|
||||
/** Centers the track list in the main content area. */
|
||||
export const TRACK_LIST_CONTAINER = "mx-auto w-full max-w-9/10"
|
||||
|
||||
/** Full-width highlight for library song rows (no horizontal inset). */
|
||||
export const SONGS_ROW_HIGHLIGHT_INSET = "absolute inset-0"
|
||||
|
||||
export function SongsSelectionRangeHighlight({
|
||||
position,
|
||||
}: {
|
||||
position: SelectionRangePosition
|
||||
}) {
|
||||
if (position === "none") {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<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. */
|
||||
export const ALBUM_TRACK_ROW = "flex w-full min-w-0 items-center gap-x-3"
|
||||
|
||||
@@ -160,50 +133,3 @@ export const ALBUM_TRACK_TITLE = "min-w-0 flex-1 truncate font-normal"
|
||||
export function isInSelectionRange(position: SelectionRangePosition) {
|
||||
return position !== "none"
|
||||
}
|
||||
|
||||
/** Full-width, square-corner highlights for the queue sidebar. */
|
||||
export const QUEUE_ROW_HIGHLIGHT_INSET = "absolute inset-0"
|
||||
|
||||
export function QueueSelectionRangeHighlight({
|
||||
position,
|
||||
}: {
|
||||
position: SelectionRangePosition
|
||||
}) {
|
||||
if (position === "none") {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<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
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import fs from "node:fs/promises"
|
||||
import * as music from "music-metadata"
|
||||
|
||||
const MAX_ENTRIES = 1000
|
||||
|
||||
export type AudioInfo = {
|
||||
codec: string | undefined
|
||||
duration: number | undefined
|
||||
}
|
||||
|
||||
const cache = new Map<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
|
||||
}
|
||||
@@ -1,96 +1,96 @@
|
||||
import { type ChildProcessWithoutNullStreams } from "node:child_process"
|
||||
import { createReadStream, ReadStream } from "node:fs"
|
||||
import { createReadStream } from "node:fs"
|
||||
import type { Readable } from "node:stream"
|
||||
import type { FfmpegProcess } from "@/lib/server-ffmpeg"
|
||||
|
||||
const HIGH_WATER_MARK_BYTES = 256 * 1024
|
||||
|
||||
export type ByteRange = {
|
||||
start: number
|
||||
end: number
|
||||
}
|
||||
|
||||
async function* nodeStreamToIterator(stream: ReadStream) {
|
||||
for await (const chunk of stream) {
|
||||
yield new Uint8Array(chunk)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Wraps a Node stream, pausing it while the consumer is behind. `cancel` runs
|
||||
* when the consumer goes away (seek, track change, disconnect). `finish` runs
|
||||
* when the source ends and may reject to error the stream.
|
||||
*/
|
||||
function toWebStream(
|
||||
source: Readable,
|
||||
{
|
||||
cancel,
|
||||
finish,
|
||||
}: { cancel: () => void; finish?: () => Promise<void> }
|
||||
): ReadableStream<Uint8Array> {
|
||||
let done = false
|
||||
|
||||
// @ts-expect-error trust me bro
|
||||
function iteratorToStream(iterator) {
|
||||
return new ReadableStream({
|
||||
async pull(controller) {
|
||||
const { value, done } = await iterator.next()
|
||||
if (done) {
|
||||
controller.close()
|
||||
} else {
|
||||
controller.enqueue(value)
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function streamFile(path: string, range?: ByteRange): ReadableStream {
|
||||
const nodeStream = createReadStream(path, range)
|
||||
return iteratorToStream(nodeStreamToIterator(nodeStream))
|
||||
}
|
||||
|
||||
export function ffmpegToReadableStream(
|
||||
ffmpegProcess: ChildProcessWithoutNullStreams
|
||||
) {
|
||||
let closed = false
|
||||
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
const finalize = (err?: Error) => {
|
||||
if (closed) {
|
||||
return
|
||||
}
|
||||
closed = true
|
||||
|
||||
try {
|
||||
if (err) {
|
||||
controller.error(err)
|
||||
} else {
|
||||
controller.close()
|
||||
return new ReadableStream<Uint8Array>(
|
||||
{
|
||||
start(controller) {
|
||||
const fail = (error: unknown) => {
|
||||
if (done) {
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// Consumer may have already closed the stream (e.g. track change).
|
||||
done = true
|
||||
controller.error(error)
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
ffmpegProcess.stdout.on("data", (chunk: Buffer) => {
|
||||
if (closed) {
|
||||
source.on("data", (chunk: Buffer) => {
|
||||
if (done) {
|
||||
return
|
||||
}
|
||||
controller.enqueue(new Uint8Array(chunk))
|
||||
if ((controller.desiredSize ?? 0) <= 0) {
|
||||
source.pause()
|
||||
}
|
||||
})
|
||||
source.once("error", fail)
|
||||
source.once("end", () => {
|
||||
if (done) {
|
||||
return
|
||||
}
|
||||
void (finish?.() ?? Promise.resolve()).then(() => {
|
||||
if (!done) {
|
||||
done = true
|
||||
controller.close()
|
||||
}
|
||||
}, fail)
|
||||
})
|
||||
},
|
||||
pull() {
|
||||
source.resume()
|
||||
},
|
||||
cancel() {
|
||||
if (done) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
controller.enqueue(new Uint8Array(chunk))
|
||||
} catch {
|
||||
closed = true
|
||||
ffmpegProcess.kill("SIGKILL")
|
||||
}
|
||||
})
|
||||
|
||||
ffmpegProcess.stderr.on("data", (data) => {
|
||||
console.error(`FFmpeg log: ${data.toString()}`)
|
||||
})
|
||||
|
||||
ffmpegProcess.stdout.on("end", () => finalize())
|
||||
ffmpegProcess.stdout.on("error", (err) => finalize(err))
|
||||
|
||||
ffmpegProcess.on("close", (code) => {
|
||||
if (code !== 0 && !closed) {
|
||||
finalize(new Error(`ffmpeg exited with code ${code}`))
|
||||
} else {
|
||||
finalize()
|
||||
}
|
||||
})
|
||||
|
||||
ffmpegProcess.on("error", (err) => finalize(err))
|
||||
done = true
|
||||
cancel()
|
||||
},
|
||||
},
|
||||
cancel() {
|
||||
if (closed) {
|
||||
return
|
||||
new ByteLengthQueuingStrategy({ highWaterMark: HIGH_WATER_MARK_BYTES })
|
||||
)
|
||||
}
|
||||
|
||||
export function streamFile(path: string, range?: ByteRange) {
|
||||
const file = createReadStream(path, range)
|
||||
return toWebStream(file, { cancel: () => file.destroy() })
|
||||
}
|
||||
|
||||
/** Streams ffmpeg stdout and kills ffmpeg when the consumer goes away. */
|
||||
export function ffmpegToReadableStream({
|
||||
child,
|
||||
exited,
|
||||
stderrTail,
|
||||
}: FfmpegProcess) {
|
||||
return toWebStream(child.stdout, {
|
||||
cancel: () => child.kill("SIGKILL"),
|
||||
finish: async () => {
|
||||
const code = await exited
|
||||
if (code !== 0) {
|
||||
console.error(`ffmpeg transcode exited with code ${code}`, stderrTail())
|
||||
throw new Error(`ffmpeg exited with code ${code}`)
|
||||
}
|
||||
closed = true
|
||||
ffmpegProcess.kill("SIGKILL")
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import fs from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
|
||||
const DEFAULT_MAX_MB = 2048
|
||||
const ORPHAN_MAX_AGE_MS = 60 * 60 * 1000
|
||||
/** Prefix for in-progress entries. Pruning removes old unpinned ones as abandoned. */
|
||||
export const CACHE_ORPHAN_PREFIX = "convert-"
|
||||
|
||||
type CacheState = {
|
||||
pinned: Map<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
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"
|
||||
import os from "node:os"
|
||||
|
||||
const STDERR_TAIL_BYTES = 4096
|
||||
|
||||
export type FfmpegProcess = {
|
||||
child: ChildProcessWithoutNullStreams
|
||||
/** Resolves with the exit code, or null when killed by a signal. */
|
||||
exited: Promise<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() }
|
||||
}
|
||||
+194
-118
@@ -1,13 +1,28 @@
|
||||
import type { Doc } from "@otunes/convex/_generated/dataModel"
|
||||
import {
|
||||
parsePlaybackQuality,
|
||||
playbackStreamPlan,
|
||||
qualityKbps,
|
||||
} from "@otunes/convex/playback-stream"
|
||||
import crypto from "node:crypto"
|
||||
import fs from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import { spawn } from "node:child_process"
|
||||
import * as music from "music-metadata"
|
||||
import { audioInfo } from "@/lib/server-audio-info"
|
||||
import {
|
||||
cacheDir,
|
||||
pinCacheEntry,
|
||||
pruneCache,
|
||||
touchCacheEntry,
|
||||
unpinCacheEntry,
|
||||
} from "@/lib/server-cache"
|
||||
import { spawnFfmpeg, type FfmpegProcess } from "@/lib/server-ffmpeg"
|
||||
|
||||
export const HLS_SEGMENT_SECONDS = 6
|
||||
const HLS_MAX_IDLE_MS = 30 * 60 * 1000
|
||||
|
||||
/** The server-only slice of a song needed to transcode it. */
|
||||
export type SongSource = Pick<Doc<"songs">, "_id" | "files" | "length">
|
||||
|
||||
type HlsJob = {
|
||||
key: string
|
||||
lookupKey: string
|
||||
@@ -17,42 +32,28 @@ type HlsJob = {
|
||||
lastTouchedAt: number
|
||||
processExited: boolean
|
||||
processExitCode: number | null
|
||||
process: FfmpegProcess | null
|
||||
abort: AbortController
|
||||
evicted: boolean
|
||||
}
|
||||
|
||||
const jobs = new Map<string, HlsJob>()
|
||||
const jobsByLookup = new Map<string, HlsJob>()
|
||||
let lastCleanupAt = 0
|
||||
|
||||
export function qualityKbps(quality: string | null) {
|
||||
if (quality === "low") {
|
||||
return 64
|
||||
}
|
||||
|
||||
if (quality === "high") {
|
||||
return 256
|
||||
}
|
||||
|
||||
return 128
|
||||
type HlsState = {
|
||||
/** In-flight and ready jobs by cache key, so overlapping requests share one ffmpeg. */
|
||||
pending: Map<string, Promise<HlsJob>>
|
||||
jobs: Map<string, HlsJob>
|
||||
jobsByLookup: Map<string, HlsJob>
|
||||
lastCleanupAt: number
|
||||
}
|
||||
|
||||
export function selectHlsSourceCodec(
|
||||
song: Doc<"songs">,
|
||||
quality: string | null,
|
||||
preferAtmos: boolean
|
||||
) {
|
||||
let sourceCodec = "lossless" in song.files ? "lossless" : "normal"
|
||||
if (preferAtmos && "atmos" in song.files) {
|
||||
sourceCodec = "atmos"
|
||||
} else if (quality === "high" && "normal" in song.files) {
|
||||
sourceCodec = "normal"
|
||||
}
|
||||
|
||||
return sourceCodec
|
||||
}
|
||||
|
||||
function hlsCacheRoot() {
|
||||
return "/tmp/otunes"
|
||||
const globalState = globalThis as typeof globalThis & {
|
||||
__otunesHls?: HlsState
|
||||
}
|
||||
const state = (globalState.__otunesHls ??= {
|
||||
pending: new Map(),
|
||||
jobs: new Map(),
|
||||
jobsByLookup: new Map(),
|
||||
lastCleanupAt: 0,
|
||||
})
|
||||
|
||||
function hlsLookupKey(
|
||||
songId: string,
|
||||
@@ -63,7 +64,7 @@ function hlsLookupKey(
|
||||
}
|
||||
|
||||
async function hlsJobKey(
|
||||
song: Doc<"songs">,
|
||||
song: SongSource,
|
||||
sourcePath: string,
|
||||
kbps: number
|
||||
) {
|
||||
@@ -88,31 +89,38 @@ export function hlsSegmentPath(job: HlsJob, segmentIndex: number) {
|
||||
|
||||
async function touchHlsJob(job: HlsJob) {
|
||||
job.lastTouchedAt = Date.now()
|
||||
await fs.utimes(job.dir, new Date(job.lastTouchedAt), new Date(job.lastTouchedAt)).catch(
|
||||
() => {}
|
||||
)
|
||||
}
|
||||
|
||||
function forgetJob(job: HlsJob) {
|
||||
jobs.delete(job.key)
|
||||
if (jobsByLookup.get(job.lookupKey) === job) {
|
||||
jobsByLookup.delete(job.lookupKey)
|
||||
}
|
||||
await touchCacheEntry(job.dir).catch(() => {})
|
||||
}
|
||||
|
||||
async function evictJob(job: HlsJob) {
|
||||
forgetJob(job)
|
||||
await fs.rm(job.dir, { recursive: true, force: true }).catch(() => {})
|
||||
if (job.evicted) {
|
||||
return
|
||||
}
|
||||
job.evicted = true
|
||||
state.pending.delete(job.key)
|
||||
state.jobs.delete(job.key)
|
||||
if (state.jobsByLookup.get(job.lookupKey) === job) {
|
||||
state.jobsByLookup.delete(job.lookupKey)
|
||||
}
|
||||
|
||||
job.abort.abort()
|
||||
job.process?.child.kill("SIGKILL")
|
||||
const complete = job.processExited && job.processExitCode === 0
|
||||
if (!complete) {
|
||||
await job.process?.exited
|
||||
await fs.rm(job.dir, { recursive: true, force: true }).catch(() => {})
|
||||
}
|
||||
unpinCacheEntry(job.dir)
|
||||
}
|
||||
|
||||
async function cleanupIdleHlsJobs() {
|
||||
const now = Date.now()
|
||||
if (now - lastCleanupAt < 60_000) {
|
||||
if (now - state.lastCleanupAt < 60_000) {
|
||||
return
|
||||
}
|
||||
lastCleanupAt = now
|
||||
state.lastCleanupAt = now
|
||||
|
||||
for (const job of [...jobs.values()]) {
|
||||
for (const job of [...state.jobs.values()]) {
|
||||
if (now - job.lastTouchedAt > HLS_MAX_IDLE_MS) {
|
||||
await evictJob(job)
|
||||
}
|
||||
@@ -124,7 +132,7 @@ export function getExistingHlsJob(
|
||||
quality: string | null,
|
||||
preferAtmos: boolean
|
||||
) {
|
||||
return jobsByLookup.get(hlsLookupKey(songId, quality, preferAtmos)) ?? null
|
||||
return state.jobsByLookup.get(hlsLookupKey(songId, quality, preferAtmos)) ?? null
|
||||
}
|
||||
|
||||
export async function waitForHlsSegment(
|
||||
@@ -137,18 +145,22 @@ export async function waitForHlsSegment(
|
||||
const startedAt = Date.now()
|
||||
|
||||
while (Date.now() - startedAt < timeoutMs) {
|
||||
// Read before checking the file so a segment renamed just before exit is found.
|
||||
const exited = job.processExited
|
||||
try {
|
||||
const firstStat = await fs.stat(segmentPath)
|
||||
if (firstStat.size > 0) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
const secondStat = await fs.stat(segmentPath)
|
||||
if (firstStat.size === secondStat.size) {
|
||||
return segmentPath
|
||||
}
|
||||
}
|
||||
// ffmpeg writes to a .tmp file and renames it when complete.
|
||||
await fs.access(segmentPath)
|
||||
return segmentPath
|
||||
} catch {
|
||||
if (job.processExited && job.processExitCode !== 0) {
|
||||
throw new Error(`HLS transcode failed with code ${job.processExitCode}`)
|
||||
if (job.evicted) {
|
||||
throw new Error("HLS job was evicted")
|
||||
}
|
||||
if (exited) {
|
||||
throw new Error(
|
||||
job.processExitCode === 0
|
||||
? "HLS segment does not exist"
|
||||
: `HLS transcode failed with code ${job.processExitCode}`
|
||||
)
|
||||
}
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
@@ -157,52 +169,15 @@ export async function waitForHlsSegment(
|
||||
throw new Error("Timed out waiting for HLS segment")
|
||||
}
|
||||
|
||||
export async function ensureHlsJob(
|
||||
song: Doc<"songs">,
|
||||
quality: string | null,
|
||||
preferAtmos: boolean
|
||||
) {
|
||||
await cleanupIdleHlsJobs()
|
||||
|
||||
const kbps = qualityKbps(quality)
|
||||
const sourceCodec = selectHlsSourceCodec(song, quality, preferAtmos)
|
||||
const sourcePath = song.files[sourceCodec]
|
||||
const key = await hlsJobKey(song, sourcePath, kbps)
|
||||
const lookupKey = hlsLookupKey(song._id, quality, preferAtmos)
|
||||
const existingJob = jobs.get(key)
|
||||
|
||||
if (existingJob) {
|
||||
try {
|
||||
await fs.access(existingJob.dir)
|
||||
await touchHlsJob(existingJob)
|
||||
return existingJob
|
||||
} catch {
|
||||
forgetJob(existingJob)
|
||||
}
|
||||
}
|
||||
|
||||
const metadata = await music.parseFile(sourcePath)
|
||||
const duration = metadata.format.duration ?? song.length
|
||||
const segmentCount = Math.max(1, Math.ceil(duration / HLS_SEGMENT_SECONDS))
|
||||
const dir = path.join(hlsCacheRoot(), key)
|
||||
await fs.mkdir(dir, { recursive: true })
|
||||
|
||||
const job: HlsJob = {
|
||||
key,
|
||||
lookupKey,
|
||||
dir,
|
||||
duration,
|
||||
segmentCount,
|
||||
lastTouchedAt: Date.now(),
|
||||
processExited: false,
|
||||
processExitCode: null,
|
||||
}
|
||||
jobs.set(key, job)
|
||||
jobsByLookup.set(lookupKey, job)
|
||||
await touchHlsJob(job)
|
||||
async function hasCompletePlaylist(dir: string) {
|
||||
const playlist = await fs
|
||||
.readFile(path.join(dir, "index.m3u8"), "utf8")
|
||||
.catch(() => "")
|
||||
return playlist.includes("#EXT-X-ENDLIST")
|
||||
}
|
||||
|
||||
function startTranscode(job: HlsJob, sourcePath: string, kbps: number) {
|
||||
const ffmpegArgs = [
|
||||
"-nostdin",
|
||||
"-i",
|
||||
sourcePath,
|
||||
"-vn",
|
||||
@@ -222,25 +197,126 @@ export async function ensureHlsJob(
|
||||
"0",
|
||||
"-hls_segment_type",
|
||||
"mpegts",
|
||||
"-hls_flags",
|
||||
"temp_file",
|
||||
"-hls_segment_filename",
|
||||
path.join(dir, "segment_%05d.ts"),
|
||||
path.join(dir, "index.m3u8"),
|
||||
path.join(job.dir, "segment_%05d.ts"),
|
||||
path.join(job.dir, "index.m3u8"),
|
||||
]
|
||||
const ffmpegProcess = spawn("ffmpeg", ffmpegArgs)
|
||||
|
||||
ffmpegProcess.stderr.on("data", (data) => {
|
||||
console.error(`FFmpeg HLS log: ${data.toString()}`)
|
||||
})
|
||||
spawnFfmpeg(ffmpegArgs, job.abort.signal).then(
|
||||
async (ffmpeg) => {
|
||||
job.process = ffmpeg
|
||||
if (job.evicted) {
|
||||
ffmpeg.child.kill("SIGKILL")
|
||||
}
|
||||
const code = await ffmpeg.exited
|
||||
job.process = null
|
||||
job.processExited = true
|
||||
job.processExitCode = code
|
||||
if (job.evicted) {
|
||||
return
|
||||
}
|
||||
if (code === 0) {
|
||||
void pruneCache()
|
||||
} else {
|
||||
console.error(`ffmpeg HLS exited with code ${code}`, ffmpeg.stderrTail())
|
||||
}
|
||||
},
|
||||
() => {
|
||||
job.processExited = true
|
||||
job.processExitCode = 1
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
ffmpegProcess.on("close", (code) => {
|
||||
job.processExited = true
|
||||
job.processExitCode = code
|
||||
})
|
||||
async function createHlsJob(
|
||||
song: SongSource,
|
||||
sourcePath: string,
|
||||
kbps: number,
|
||||
key: string,
|
||||
lookupKey: string
|
||||
): Promise<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)
|
||||
|
||||
ffmpegProcess.on("error", () => {
|
||||
job.processExited = true
|
||||
job.processExitCode = 1
|
||||
})
|
||||
try {
|
||||
const complete = await hasCompletePlaylist(dir)
|
||||
if (!complete) {
|
||||
await fs.rm(dir, { recursive: true, force: true })
|
||||
await fs.mkdir(dir, { recursive: true })
|
||||
}
|
||||
|
||||
const job: HlsJob = {
|
||||
key,
|
||||
lookupKey,
|
||||
dir,
|
||||
duration,
|
||||
segmentCount,
|
||||
lastTouchedAt: Date.now(),
|
||||
processExited: complete,
|
||||
processExitCode: complete ? 0 : null,
|
||||
process: null,
|
||||
abort: new AbortController(),
|
||||
evicted: false,
|
||||
}
|
||||
state.jobs.set(key, job)
|
||||
await touchHlsJob(job)
|
||||
|
||||
if (!complete) {
|
||||
startTranscode(job, sourcePath, kbps)
|
||||
}
|
||||
return job
|
||||
} catch (error) {
|
||||
unpinCacheEntry(dir)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function ensureHlsJob(
|
||||
song: SongSource,
|
||||
quality: string | null,
|
||||
preferAtmos: boolean
|
||||
): Promise<HlsJob> {
|
||||
await cleanupIdleHlsJobs()
|
||||
|
||||
const plan = playbackStreamPlan(
|
||||
song.files,
|
||||
parsePlaybackQuality(quality),
|
||||
preferAtmos
|
||||
)
|
||||
// HLS always transcodes, and lossless quality has no target bitrate.
|
||||
const kbps = plan.kbps || qualityKbps("medium")
|
||||
const sourcePath = song.files[plan.source]
|
||||
const key = await hlsJobKey(song, sourcePath, kbps)
|
||||
const lookupKey = hlsLookupKey(song._id, quality, preferAtmos)
|
||||
|
||||
let pending = state.pending.get(key)
|
||||
if (!pending) {
|
||||
pending = createHlsJob(song, sourcePath, kbps, key, lookupKey)
|
||||
state.pending.set(key, pending)
|
||||
const created = pending
|
||||
created.catch(() => {
|
||||
if (state.pending.get(key) === created) {
|
||||
state.pending.delete(key)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const job = await pending
|
||||
const exists = await fs.access(job.dir).then(
|
||||
() => true,
|
||||
() => false
|
||||
)
|
||||
if (job.evicted || !exists) {
|
||||
await evictJob(job)
|
||||
return ensureHlsJob(song, quality, preferAtmos)
|
||||
}
|
||||
|
||||
state.jobsByLookup.set(lookupKey, job)
|
||||
await touchHlsJob(job)
|
||||
return job
|
||||
}
|
||||
@@ -1,8 +1,15 @@
|
||||
import { spawn } from "node:child_process"
|
||||
import { createHash } from "node:crypto"
|
||||
import fs from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import {
|
||||
CACHE_ORPHAN_PREFIX,
|
||||
cacheDir,
|
||||
pinCacheEntry,
|
||||
pruneCache,
|
||||
touchCacheEntry,
|
||||
unpinCacheEntry,
|
||||
} from "@/lib/server-cache"
|
||||
import { spawnFfmpeg } from "@/lib/server-ffmpeg"
|
||||
|
||||
const conversions = new Map<string, Promise<string>>()
|
||||
|
||||
@@ -27,56 +34,38 @@ export async function seekableLosslessFile(source: string): Promise<string> {
|
||||
}
|
||||
|
||||
async function convert(source: string, key: string): Promise<string> {
|
||||
const dir = path.join(os.tmpdir(), "otunes-lossless")
|
||||
const dir = cacheDir("lossless")
|
||||
await fs.mkdir(dir, { recursive: true })
|
||||
const cutoff = Date.now() - 30 * 60 * 1000
|
||||
await Promise.all(
|
||||
(await fs.readdir(dir))
|
||||
.filter((name) => name.endsWith(".flac"))
|
||||
.map(async (name) => {
|
||||
const file = path.join(dir, name)
|
||||
const stat = await fs.stat(file).catch(() => null)
|
||||
if (stat && stat.mtimeMs < cutoff) await fs.rm(file, { force: true })
|
||||
})
|
||||
)
|
||||
const output = path.join(dir, `${key}.flac`)
|
||||
try {
|
||||
await fs.access(output)
|
||||
// Every range request touches the file so it stays cached while playing.
|
||||
await touchCacheEntry(output)
|
||||
return output
|
||||
} catch {
|
||||
// Publish only completed conversions so range requests always see a complete file.
|
||||
}
|
||||
const temporary = path.join(
|
||||
await fs.mkdtemp(path.join(dir, "convert-")),
|
||||
"audio.flac"
|
||||
)
|
||||
const temporaryDir = await fs.mkdtemp(path.join(dir, CACHE_ORPHAN_PREFIX))
|
||||
const temporary = path.join(temporaryDir, "audio.flac")
|
||||
pinCacheEntry(temporaryDir)
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const child = spawn(
|
||||
"ffmpeg",
|
||||
[
|
||||
"-nostdin",
|
||||
"-v",
|
||||
"error",
|
||||
"-i",
|
||||
source,
|
||||
"-map",
|
||||
"0:a:0",
|
||||
"-c:a",
|
||||
"flac",
|
||||
temporary,
|
||||
],
|
||||
{ stdio: "ignore" }
|
||||
)
|
||||
child.on("error", reject)
|
||||
child.on("close", (code) => {
|
||||
if (code === 0) resolve()
|
||||
else reject(new Error(`Lossless conversion failed: ${code}`))
|
||||
})
|
||||
})
|
||||
const ffmpeg = await spawnFfmpeg([
|
||||
"-i",
|
||||
source,
|
||||
"-map",
|
||||
"0:a:0",
|
||||
"-c:a",
|
||||
"flac",
|
||||
temporary,
|
||||
])
|
||||
const code = await ffmpeg.exited
|
||||
if (code !== 0) {
|
||||
throw new Error(`Lossless conversion failed: ${code}: ${ffmpeg.stderrTail()}`)
|
||||
}
|
||||
await fs.rename(temporary, output)
|
||||
return output
|
||||
} finally {
|
||||
await fs.rm(path.dirname(temporary), { recursive: true, force: true })
|
||||
unpinCacheEntry(temporaryDir)
|
||||
await fs.rm(temporaryDir, { recursive: true, force: true })
|
||||
}
|
||||
void pruneCache()
|
||||
return output
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import { convexServerOptions } from "@/lib/convex-server"
|
||||
import type { SongSource } from "@/lib/server-hls"
|
||||
|
||||
/**
|
||||
* Loads a song's file paths as the requesting listener, so Convex enforces auth
|
||||
* even if the proxy is bypassed. Throws when signed out or the song is missing.
|
||||
*/
|
||||
export async function getSongSource(id: string): Promise<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
|
||||
}
|
||||
@@ -2,10 +2,13 @@ import { useConvex } from "convex/react"
|
||||
import { useEffect, useMemo, useSyncExternalStore } from "react"
|
||||
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
import {
|
||||
getCachedSong,
|
||||
getSongSnapshot,
|
||||
getSongsVersion,
|
||||
requestSongs,
|
||||
songFromSnapshot,
|
||||
subscribeSongs,
|
||||
} from "@otunes/convex/client/song-cache"
|
||||
import { isPersistentCacheLoaded } from "@/lib/persistent-cache"
|
||||
@@ -48,7 +51,24 @@ export function useSongs(songIds: readonly Id<"songs">[]) {
|
||||
return songs
|
||||
}
|
||||
|
||||
export function useSong(songId: Id<"songs"> | null) {
|
||||
const songIds = useMemo(() => (songId ? [songId] : []), [songId])
|
||||
return useSongs(songIds)[0] ?? null
|
||||
/**
|
||||
* Like `useSongs` for one song, but only re-renders when that song changes
|
||||
* once it is cached.
|
||||
*/
|
||||
export function useSong(songId: Id<"songs"> | null): BrowseSong | null {
|
||||
const convex = useConvex()
|
||||
const snapshot = useSyncExternalStore(
|
||||
subscribeSongs,
|
||||
() => getSongSnapshot(songId),
|
||||
() => null
|
||||
)
|
||||
const song = songFromSnapshot(snapshot)
|
||||
|
||||
useEffect(() => {
|
||||
if (songId && !song && isPersistentCacheLoaded()) {
|
||||
requestSongs(convex, [songId])
|
||||
}
|
||||
}, [convex, songId, song, snapshot])
|
||||
|
||||
return song
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
export type PlaybackQuality = "low" | "medium" | "high" | "lossless"
|
||||
|
||||
export function songPlayUrl(
|
||||
songId: string,
|
||||
quality: PlaybackQuality | undefined,
|
||||
preferAtmos: boolean | undefined
|
||||
) {
|
||||
const params = new URLSearchParams()
|
||||
if (quality) {
|
||||
params.set("quality", quality)
|
||||
}
|
||||
if (preferAtmos) {
|
||||
params.set("preferAtmos", "true")
|
||||
}
|
||||
const query = params.toString()
|
||||
return `/api/song/${songId}/play${query ? `?${query}` : ""}`
|
||||
}
|
||||
|
||||
export function songHlsPlaylistUrl(
|
||||
songId: string,
|
||||
quality: PlaybackQuality | undefined,
|
||||
preferAtmos: boolean | undefined
|
||||
) {
|
||||
const params = new URLSearchParams()
|
||||
if (quality) {
|
||||
params.set("quality", quality)
|
||||
}
|
||||
if (preferAtmos) {
|
||||
params.set("preferAtmos", "true")
|
||||
}
|
||||
const query = params.toString()
|
||||
return `/api/song/${songId}/play/hls${query ? `?${query}` : ""}`
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
|
||||
import { stationArtistId } from "./station-artist.ts"
|
||||
|
||||
const songs = [
|
||||
{ id: "song-a", artist: { id: "artist-a" } },
|
||||
{ id: "song-b", artist: { id: "artist-a" } },
|
||||
{ id: "song-c", artist: { id: "artist-b" } },
|
||||
]
|
||||
|
||||
test("a single song or a selection sharing one artist can create a station", () => {
|
||||
assert.equal(stationArtistId(songs, new Set(["song-c"])), "artist-b")
|
||||
assert.equal(
|
||||
stationArtistId(songs, new Set(["song-a", "song-b"])),
|
||||
"artist-a"
|
||||
)
|
||||
})
|
||||
|
||||
test("mixed artists cannot create a station", () => {
|
||||
assert.equal(stationArtistId(songs, new Set(["song-a", "song-c"])), undefined)
|
||||
})
|
||||
|
||||
test("empty or partially missing selections cannot create a station", () => {
|
||||
assert.equal(stationArtistId(songs, new Set()), undefined)
|
||||
assert.equal(
|
||||
stationArtistId(songs, new Set(["song-a", "missing"])),
|
||||
undefined
|
||||
)
|
||||
})
|
||||
@@ -14,6 +14,7 @@
|
||||
"@base-ui/react": "^1.5.0",
|
||||
"@convex-dev/auth": "^0.0.93",
|
||||
"@otunes/convex": "workspace:*",
|
||||
"@tanstack/react-virtual": "^3.14.26",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ const isPublic = createRouteMatcher([
|
||||
"/api/playlist/:id/cover",
|
||||
"/album/:id",
|
||||
"/artist/:id",
|
||||
"/artists/:id",
|
||||
"/library/artists/:id",
|
||||
"/playlist/:id",
|
||||
])
|
||||
|
||||
|
||||
+30
-6
@@ -46,22 +46,34 @@ stop() {
|
||||
}
|
||||
trap 'stop; exit 0' TERM INT
|
||||
|
||||
as_convex=(setpriv --reuid=convex --regid=convex --init-groups env HOME=/home/convex)
|
||||
|
||||
convex_cli() {
|
||||
(
|
||||
cd "$FUNCTIONS_DIR"
|
||||
unset CONVEX_DEPLOYMENT CONVEX_DEPLOY_KEY
|
||||
CONVEX_SELF_HOSTED_URL="$BACKEND_URL" \
|
||||
CONVEX_SELF_HOSTED_ADMIN_KEY="$admin_key" \
|
||||
"$NODE" node_modules/convex/bin/main.js "$@"
|
||||
"${as_convex[@]}" "$NODE" node_modules/convex/bin/main.js "$@"
|
||||
)
|
||||
}
|
||||
|
||||
# Only root (the backend) may read the database and instance secret.
|
||||
# Only the convex user may read the database and instance secret. Volumes from
|
||||
# images that ran the backend as root are still owned by root, and
|
||||
# read_credentials.sh generates a new instance secret if it cannot read the old one.
|
||||
mkdir -p "$CONVEX_DATA_DIR"
|
||||
find "$CONVEX_DATA_DIR" \( ! -user convex -o ! -group convex \) \
|
||||
-exec chown -h convex:convex {} +
|
||||
chmod 700 "$CONVEX_DATA_DIR"
|
||||
|
||||
# The web server writes HLS streams here and a Convex cron deletes stale ones.
|
||||
mkdir -p /tmp/otunes
|
||||
chown otunes:otunes /tmp/otunes
|
||||
chmod -R g+rwX /tmp/otunes
|
||||
chmod g+s,o-rwx /tmp/otunes
|
||||
|
||||
log "Starting Convex backend"
|
||||
(cd /convex && umask 077 && exec ./run_backend.sh) &
|
||||
(cd /convex && umask 077 && exec "${as_convex[@]}" ./run_backend.sh) &
|
||||
backend_pid=$!
|
||||
|
||||
for _ in $(seq 1 120); do
|
||||
@@ -80,17 +92,27 @@ if ! curl -fsS "$BACKEND_URL/version" >/dev/null 2>&1; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
admin_key=$(cd /convex && ./generate_admin_key.sh)
|
||||
admin_key=$(cd /convex && umask 077 && "${as_convex[@]}" ./generate_admin_key.sh)
|
||||
|
||||
log "Deploying Convex functions"
|
||||
convex_cli deploy --typecheck disable --codegen disable
|
||||
|
||||
if [ -z "$(convex_cli env get JWKS 2>/dev/null || true)" ]; then
|
||||
log "Running data migrations"
|
||||
convex_cli run migrations:migrateUsers
|
||||
|
||||
# `env get` exits 0 with no output when the variable is unset. Any other failure
|
||||
# must not be read as "no keys": regenerating them signs every user out.
|
||||
if ! jwks=$(convex_cli env get JWKS); then
|
||||
log "Could not read Convex Auth signing keys"
|
||||
stop
|
||||
exit 1
|
||||
fi
|
||||
if [ -z "$jwks" ]; then
|
||||
log "Generating Convex Auth signing keys"
|
||||
"$NODE" /opt/otunes/generate-auth-keys.mjs | convex_cli env set --force
|
||||
fi
|
||||
|
||||
unset admin_key
|
||||
unset admin_key jwks
|
||||
|
||||
log "Starting web server"
|
||||
(
|
||||
@@ -100,6 +122,8 @@ log "Starting web server"
|
||||
# Server-side Convex helpers fall back to this at runtime. The browser bundle
|
||||
# is built without it, so browsers still derive their own URL.
|
||||
export NEXT_PUBLIC_CONVEX_URL="$BACKEND_URL"
|
||||
# Lets the convex group member delete stale HLS streams.
|
||||
umask 0002
|
||||
exec setpriv --reuid=otunes --regid=otunes --init-groups \
|
||||
"$NODE" apps/web/server.js
|
||||
) &
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Path data for the Dolby Atmos and Lossless badge marks, drawn with each
|
||||
* platform's own SVG primitives.
|
||||
*/
|
||||
|
||||
export const MARK_HEIGHT = 11
|
||||
|
||||
export const DOLBY_VIEW_BOX = "0 0 23 16"
|
||||
export const DOLBY_WIDTH = (MARK_HEIGHT * 23) / 16
|
||||
export const DOLBY_PATHS = [
|
||||
"M0 0H2.5A8 8 0 0 1 2.5 16H0Z",
|
||||
"M23 0H20.5A8 8 0 0 0 20.5 16H23Z",
|
||||
]
|
||||
|
||||
export const LOSSLESS_VIEW_BOX = "28 154 544 271"
|
||||
export const LOSSLESS_WIDTH = (MARK_HEIGHT * 544) / 271
|
||||
export const LOSSLESS_PEAKS = [110, 215, 320]
|
||||
export const LOSSLESS_THIN_WIDTH = 24
|
||||
export const LOSSLESS_STROKES: [peak: number, d: string][] = [
|
||||
[110, "M-70 320C-62 245 -38 166 0 166"],
|
||||
[215, "M-70 320C-62 245 -38 166 0 166"],
|
||||
[320, "M-30 185C-22 173 -11 166 0 166"],
|
||||
[110, "M166 413C176 413 186 406 194 395"],
|
||||
[215, "M166 413C200 413 226 340 240 275"],
|
||||
[320, "M166 413C200 413 226 340 240 275"],
|
||||
]
|
||||
export const LOSSLESS_FALL =
|
||||
"M0 178L4 179L8 181L12 184L16 189L20 196L23 204L27 213L30 223L34 233L39 243L43 254L48 266L53 278L58 289L62 301L66 313L71 325L75 336L79 347L83 357L86 364L89 370L93 377L97 382L101 387L105 392L109 397L113 401L117 405L121 408L126 412L130 415L134 417L139 419L143 421L148 423L152 424L157 424L161 425L166 425L166 401L163 401L161 400L159 400L157 399L154 397L152 396L151 394L149 392L147 389L145 386L143 383L142 380L140 376L138 371L137 367L135 362L134 357L132 351L130 345L127 339L124 330L120 319L116 308L111 297L107 285L102 272L98 260L93 248L88 235L82 223L76 212L69 201L61 192L53 183L45 175L37 168L28 163L19 158L10 155L0 154Z"
|
||||
export const LOSSLESS_FALL_GAP =
|
||||
"M0 178L4 180L6 184L8 190L9 197L11 203L14 210L17 219L21 228L24 238L29 248L33 259L38 270L43 282L47 293L52 305L56 317L60 328L64 340L68 351L73 361L76 368L79 375L83 381L87 387L91 393L95 398L100 403L104 408L109 412L113 416L118 419L124 422L130 424L135 425L141 426L147 426L152 426L157 425L161 425L166 425L166 401L163 401L161 399L159 398L158 395L157 393L156 390L155 387L155 384L154 381L153 379L152 376L150 373L149 369L148 366L146 361L145 357L143 352L142 347L140 341L137 335L134 326L130 315L126 304L122 293L117 281L113 268L108 256L103 243L98 231L92 219L86 207L79 196L71 186L62 177L53 168L44 161L32 157L21 155L10 154L0 154Z"
|
||||
@@ -0,0 +1,15 @@
|
||||
/** Reads the user id from a Convex Auth JWT without verifying it, for scoping client caches. */
|
||||
export function userIdFromToken(token: string | null | undefined) {
|
||||
const payload = token?.split(".")[1]
|
||||
if (!payload) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"))
|
||||
const subject = (JSON.parse(json) as { sub?: unknown }).sub
|
||||
return typeof subject === "string" ? (subject.split("|")[0] ?? null) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import type { OptimisticLocalStore, OptimisticUpdate } from "convex/browser"
|
||||
import type { FunctionArgs, FunctionReference } from "convex/server"
|
||||
|
||||
import { api } from "../convex/_generated/api"
|
||||
import type { Id } from "../convex/_generated/dataModel"
|
||||
|
||||
type FavoriteIds = {
|
||||
favoriteSongs: Id<"songs">[]
|
||||
favoriteAlbums: Id<"albums">[]
|
||||
favoriteArtists: Id<"artists">[]
|
||||
}
|
||||
|
||||
type FavoriteList = keyof FavoriteIds
|
||||
|
||||
function patchFavorites<List extends FavoriteList>(
|
||||
store: OptimisticLocalStore,
|
||||
list: List,
|
||||
update: (ids: FavoriteIds[List]) => FavoriteIds[List]
|
||||
) {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current) return
|
||||
const next = update(current[list])
|
||||
if (next !== current[list]) {
|
||||
store.setQuery(
|
||||
api.favorites.getUserFavorites,
|
||||
{},
|
||||
{
|
||||
...current,
|
||||
[list]: next,
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function addFavorites<List extends FavoriteList>(
|
||||
store: OptimisticLocalStore,
|
||||
list: List,
|
||||
ids: FavoriteIds[List]
|
||||
) {
|
||||
patchFavorites(store, list, (current) => {
|
||||
const added = ids.filter((id) => !(current as string[]).includes(id))
|
||||
return added.length === 0
|
||||
? current
|
||||
: ([...new Set([...current, ...added])] as FavoriteIds[List])
|
||||
})
|
||||
}
|
||||
|
||||
function removeFavorites<List extends FavoriteList>(
|
||||
store: OptimisticLocalStore,
|
||||
list: List,
|
||||
ids: FavoriteIds[List]
|
||||
) {
|
||||
const removed = new Set<string>(ids)
|
||||
patchFavorites(
|
||||
store,
|
||||
list,
|
||||
(current) =>
|
||||
(current as string[]).filter(
|
||||
(id) => !removed.has(id)
|
||||
) as FavoriteIds[List]
|
||||
)
|
||||
}
|
||||
|
||||
type FavoritesApi = typeof api.favorites
|
||||
type FavoriteMutation = {
|
||||
[
|
||||
Name in keyof FavoritesApi
|
||||
]: FavoritesApi[Name] extends FunctionReference<"mutation"> ? Name : never
|
||||
}[keyof FavoritesApi]
|
||||
|
||||
/**
|
||||
* Optimistic updates for the favorites mutations, so toggles show instantly.
|
||||
* Pass them to `useMutation(...).withOptimisticUpdate(...)`.
|
||||
*/
|
||||
export const favoriteOptimisticUpdates = {
|
||||
favoriteSong: (store, { songId }) =>
|
||||
addFavorites(store, "favoriteSongs", [songId]),
|
||||
favoriteSongs: (store, { songIds }) =>
|
||||
addFavorites(store, "favoriteSongs", songIds),
|
||||
unfavoriteSong: (store, { songId }) =>
|
||||
removeFavorites(store, "favoriteSongs", [songId]),
|
||||
unfavoriteSongs: (store, { songIds }) =>
|
||||
removeFavorites(store, "favoriteSongs", songIds),
|
||||
favoriteAlbum: (store, { albumId }) =>
|
||||
addFavorites(store, "favoriteAlbums", [albumId]),
|
||||
unfavoriteAlbum: (store, { albumId }) =>
|
||||
removeFavorites(store, "favoriteAlbums", [albumId]),
|
||||
favoriteArtist: (store, { artistId }) =>
|
||||
addFavorites(store, "favoriteArtists", [artistId]),
|
||||
unfavoriteArtist: (store, { artistId }) =>
|
||||
removeFavorites(store, "favoriteArtists", [artistId]),
|
||||
} satisfies {
|
||||
[Name in FavoriteMutation]?: OptimisticUpdate<
|
||||
FunctionArgs<FavoritesApi[Name]>
|
||||
>
|
||||
}
|
||||
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user