perf: optimize app rendering and data loading (#18)
- Virtualize mobile lists and defer queue loading - Split playback state from actions to reduce rerenders - Skip invalid or unnecessary Convex queries Reviewed-on: #18
This commit was merged in pull request #18.
This commit is contained in:
1 parent
55eccf4b7b
commit
9da758b196
65 files changed
+3130
-1603
No files matched your search
@@ -4,7 +4,7 @@ import { DynamicColorIOS, Platform, useColorScheme } from "react-native"
|
||||
import { useMemo } from "react"
|
||||
|
||||
import { TabBottomAccessory } from "@/components/mini-player"
|
||||
import { usePlayback } from "@/contexts/playback"
|
||||
import { usePlaybackQueue } from "@/contexts/playback"
|
||||
import { appleMusic, colors } from "@/lib/theme"
|
||||
|
||||
function useRouterTheme() {
|
||||
@@ -76,7 +76,7 @@ function useNativeTabColors() {
|
||||
export default function TabsLayout() {
|
||||
const routerTheme = useRouterTheme()
|
||||
const tabColors = useNativeTabColors()
|
||||
const { currentSong, queueSongIds } = usePlayback()
|
||||
const { currentSong, queueSongIds } = usePlaybackQueue()
|
||||
const showBottomAccessory = Boolean(currentSong && queueSongIds.length > 0)
|
||||
|
||||
return (
|
||||
@@ -84,8 +84,7 @@ export default function TabsLayout() {
|
||||
<NativeTabs
|
||||
blurEffect={
|
||||
tabColors.blurEffect as
|
||||
| "systemChromeMaterialDark"
|
||||
| "systemChromeMaterialLight"
|
||||
"systemChromeMaterialDark" | "systemChromeMaterialLight"
|
||||
}
|
||||
backgroundColor={tabColors.backgroundColor}
|
||||
iconColor={tabColors.iconColor}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useQuery } from "convex/react"
|
||||
import { Stack, useLocalSearchParams } from "expo-router"
|
||||
import { Pressable, ScrollView, StyleSheet, Text, View } from "react-native"
|
||||
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
import { Button, LoadingView } from "@/components/ui/primitives"
|
||||
import { contentBottomInset } from "@/components/player"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlayback } from "@/contexts/playback"
|
||||
import { usePlaybackActions } from "@/contexts/playback"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
@@ -33,12 +33,21 @@ export default function AlbumScreen() {
|
||||
api.library.browseAlbumDetail,
|
||||
typeof id === "string" ? { id: id as Id<"albums"> } : "skip"
|
||||
)
|
||||
const { playAlbum, playAlbumShuffled, playFromSong } = usePlayback()
|
||||
const { isAlbumFavorite, toggleAlbumFavorite, isSongFavorite } = useFavorites()
|
||||
const { handleAlbumDetailAction, handleAlbumTrackAction, isAlbumFavorite: isAlbumFav } =
|
||||
useMediaMenuActions()
|
||||
const coverUri = config && album ? albumCoverUrl(config.serverUrl, album.id) : ""
|
||||
const backgroundColor = useCoverBackgroundColor(coverUri, album?.cover != null, colors.background)
|
||||
const { playAlbum, playAlbumShuffled, playFromSong } = usePlaybackActions()
|
||||
const { isAlbumFavorite, toggleAlbumFavorite, isSongFavorite } =
|
||||
useFavorites()
|
||||
const {
|
||||
handleAlbumDetailAction,
|
||||
handleAlbumTrackAction,
|
||||
isAlbumFavorite: isAlbumFav,
|
||||
} = useMediaMenuActions()
|
||||
const coverUri =
|
||||
config && album ? albumCoverUrl(config.serverUrl, album.id) : ""
|
||||
const backgroundColor = useCoverBackgroundColor(
|
||||
coverUri,
|
||||
album?.cover != null,
|
||||
colors.background
|
||||
)
|
||||
|
||||
if (album === undefined || !config) {
|
||||
return (
|
||||
@@ -72,7 +81,9 @@ export default function AlbumScreen() {
|
||||
)
|
||||
}
|
||||
|
||||
const songIds = album.tracks.map((track: BrowseAlbumTrack) => track.id as Id<"songs">)
|
||||
const songIds = album.tracks.map(
|
||||
(track: BrowseAlbumTrack) => track.id as Id<"songs">
|
||||
)
|
||||
const metadata = formatMetadata(album.genre, album.year)
|
||||
|
||||
return (
|
||||
@@ -87,67 +98,84 @@ export default function AlbumScreen() {
|
||||
favorited={isAlbumFav(album.id)}
|
||||
share={{ type: "album", albumId: album.id }}
|
||||
onAction={(action) =>
|
||||
void handleAlbumDetailAction(album.id as Id<"albums">, songIds, action)
|
||||
void handleAlbumDetailAction(
|
||||
album.id as Id<"albums">,
|
||||
songIds,
|
||||
action
|
||||
)
|
||||
}
|
||||
>
|
||||
<Pressable hitSlop={8}>
|
||||
<Ionicons name="ellipsis-horizontal" size={22} color={colors.foreground} />
|
||||
<Ionicons
|
||||
name="ellipsis-horizontal"
|
||||
size={22}
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
</MediaActionMenu>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
<ScrollView
|
||||
<FlatList
|
||||
data={album.tracks}
|
||||
keyExtractor={(track) => track.id}
|
||||
style={{ flex: 1, backgroundColor }}
|
||||
contentContainerStyle={{ paddingBottom: contentBottomInset }}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
>
|
||||
<View style={styles.hero}>
|
||||
<CoverImage
|
||||
uri={coverUri}
|
||||
hasCover={album.cover != null}
|
||||
style={styles.cover}
|
||||
/>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>{album.title}</Text>
|
||||
<Pressable onPress={() => push(`/artist/${album.artist.id}`)}>
|
||||
<Text style={[styles.artist, { color: colors.mutedForeground }]}>{album.artist.name}</Text>
|
||||
</Pressable>
|
||||
{metadata ? (
|
||||
<Text style={{ color: colors.mutedForeground }}>{metadata}</Text>
|
||||
) : null}
|
||||
<View style={styles.actions}>
|
||||
<Pressable
|
||||
onPress={() => void toggleAlbumFavorite(album.id)}
|
||||
hitSlop={8}
|
||||
style={[styles.iconAction, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Ionicons
|
||||
name={isAlbumFavorite(album.id) ? "star" : "star-outline"}
|
||||
size={24}
|
||||
color={isAlbumFavorite(album.id) ? colors.primary : colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
<Button
|
||||
title="Play"
|
||||
icon="play"
|
||||
onPress={() => void playAlbum(album.id)}
|
||||
style={styles.playButton}
|
||||
ListHeaderComponent={
|
||||
<View style={styles.hero}>
|
||||
<CoverImage
|
||||
uri={coverUri}
|
||||
hasCover={album.cover != null}
|
||||
style={styles.cover}
|
||||
/>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Shuffle"
|
||||
hitSlop={8}
|
||||
onPress={() => void playAlbumShuffled(album.id)}
|
||||
style={[styles.iconAction, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Ionicons name="shuffle" size={24} color={colors.foreground} />
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>
|
||||
{album.title}
|
||||
</Text>
|
||||
<Pressable onPress={() => push(`/artist/${album.artist.id}`)}>
|
||||
<Text style={[styles.artist, { color: colors.mutedForeground }]}>
|
||||
{album.artist.name}
|
||||
</Text>
|
||||
</Pressable>
|
||||
{metadata ? (
|
||||
<Text style={{ color: colors.mutedForeground }}>{metadata}</Text>
|
||||
) : null}
|
||||
<View style={styles.actions}>
|
||||
<Pressable
|
||||
onPress={() => void toggleAlbumFavorite(album.id)}
|
||||
hitSlop={8}
|
||||
style={[styles.iconAction, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Ionicons
|
||||
name={isAlbumFavorite(album.id) ? "star" : "star-outline"}
|
||||
size={24}
|
||||
color={
|
||||
isAlbumFavorite(album.id)
|
||||
? colors.primary
|
||||
: colors.foreground
|
||||
}
|
||||
/>
|
||||
</Pressable>
|
||||
<Button
|
||||
title="Play"
|
||||
icon="play"
|
||||
onPress={() => void playAlbum(album.id)}
|
||||
style={styles.playButton}
|
||||
/>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Shuffle"
|
||||
hitSlop={8}
|
||||
onPress={() => void playAlbumShuffled(album.id)}
|
||||
style={[styles.iconAction, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Ionicons name="shuffle" size={24} color={colors.foreground} />
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{album.tracks.map((track: BrowseAlbumTrack, index: number) => (
|
||||
}
|
||||
renderItem={({ item: track, index }) => (
|
||||
<MediaContextMenu
|
||||
key={track.id}
|
||||
favorited={isSongFavorite(track.id)}
|
||||
navigation={{
|
||||
artist: { id: album.artist.id },
|
||||
@@ -158,21 +186,31 @@ export default function AlbumScreen() {
|
||||
albumId: album.id,
|
||||
songId: track.id,
|
||||
}}
|
||||
onAction={(action) => void handleAlbumTrackAction(track, album, action)}
|
||||
onAction={(action) =>
|
||||
void handleAlbumTrackAction(track, album, action)
|
||||
}
|
||||
>
|
||||
<Pressable
|
||||
style={[styles.trackRow, { borderBottomColor: colors.border }]}
|
||||
onPress={() => void playFromSong(track.id, songIds)}
|
||||
>
|
||||
<Text style={[styles.trackNumber, { color: colors.mutedForeground }]}>
|
||||
<Text
|
||||
style={[styles.trackNumber, { color: colors.mutedForeground }]}
|
||||
>
|
||||
{track.track || index + 1}
|
||||
</Text>
|
||||
<View style={styles.trackMeta}>
|
||||
<Text style={[styles.trackTitle, { color: colors.foreground }]} numberOfLines={1}>
|
||||
<Text
|
||||
style={[styles.trackTitle, { color: colors.foreground }]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{track.title}
|
||||
</Text>
|
||||
{track.artists ? (
|
||||
<Text style={{ color: colors.mutedForeground }} numberOfLines={1}>
|
||||
<Text
|
||||
style={{ color: colors.mutedForeground }}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{track.artists.join(", ")}
|
||||
</Text>
|
||||
) : null}
|
||||
@@ -182,8 +220,8 @@ export default function AlbumScreen() {
|
||||
</Text>
|
||||
</Pressable>
|
||||
</MediaContextMenu>
|
||||
))}
|
||||
</ScrollView>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import { useQuery } from "convex/react"
|
||||
import { Stack, useLocalSearchParams } from "expo-router"
|
||||
import { Pressable, ScrollView, StyleSheet, Text, View } from "react-native"
|
||||
import { Pressable, StyleSheet, Text, View } from "react-native"
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
|
||||
import { MediaGrid } from "@/components/media-cards"
|
||||
import { MediaGridList } from "@/components/media-cards"
|
||||
import { MediaActionMenu } from "@/components/media-actions-sheet"
|
||||
import { Button, LoadingView } from "@/components/ui/primitives"
|
||||
import { contentBottomInset } from "@/components/player"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlayback } from "@/contexts/playback"
|
||||
import { usePlaybackActions } from "@/contexts/playback"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
@@ -22,10 +22,14 @@ export default function ArtistScreen() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>()
|
||||
const colors = useThemeColors()
|
||||
const { config } = useServerConfig()
|
||||
const data = useQuery(api.library.browseArtistDetail, { id: id as Id<"artists"> })
|
||||
const { playArtist, playArtistShuffled } = usePlayback()
|
||||
const data = useQuery(
|
||||
api.library.browseArtistDetail,
|
||||
typeof id === "string" ? { id: id as Id<"artists"> } : "skip"
|
||||
)
|
||||
const { playArtist, playArtistShuffled } = usePlaybackActions()
|
||||
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
|
||||
const { handleArtistAction, isArtistFavorite: isArtistFav } = useMediaMenuActions()
|
||||
const { handleArtistAction, isArtistFavorite: isArtistFav } =
|
||||
useMediaMenuActions()
|
||||
|
||||
if (data === undefined || !config) {
|
||||
return (
|
||||
@@ -70,61 +74,72 @@ export default function ArtistScreen() {
|
||||
selectedCount={data.albums.length}
|
||||
favorited={isArtistFav(data.artist.id)}
|
||||
share={{ type: "artist", artistId: data.artist.id }}
|
||||
onAction={(action) => void handleArtistAction(data.artist, action)}
|
||||
onAction={(action) =>
|
||||
void handleArtistAction(data.artist, action)
|
||||
}
|
||||
>
|
||||
<Pressable hitSlop={8}>
|
||||
<Ionicons name="ellipsis-horizontal" size={22} color={colors.foreground} />
|
||||
<Ionicons
|
||||
name="ellipsis-horizontal"
|
||||
size={22}
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
</MediaActionMenu>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
<ScrollView
|
||||
style={{ flex: 1, backgroundColor: colors.background }}
|
||||
contentContainerStyle={{ paddingBottom: contentBottomInset }}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
>
|
||||
<View style={styles.hero}>
|
||||
<CoverImage
|
||||
uri={artistCoverUrl(config.serverUrl, data.artist.id)}
|
||||
hasCover={data.artist.photo != null}
|
||||
style={styles.avatar}
|
||||
/>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>{data.artist.name}</Text>
|
||||
<View style={styles.actions}>
|
||||
<Pressable
|
||||
onPress={() => void toggleArtistFavorite(data.artist.id)}
|
||||
hitSlop={8}
|
||||
style={[styles.iconAction, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Ionicons
|
||||
name={isArtistFavorite(data.artist.id) ? "star" : "star-outline"}
|
||||
size={24}
|
||||
color={isArtistFavorite(data.artist.id) ? colors.primary : colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
<Button
|
||||
title="Play"
|
||||
icon="play"
|
||||
onPress={() => void playArtist(data.artist.id)}
|
||||
style={styles.playButton}
|
||||
<MediaGridList
|
||||
content={data.albums}
|
||||
paddingBottom={contentBottomInset}
|
||||
contentInset={false}
|
||||
ListHeaderComponent={
|
||||
<View style={styles.hero}>
|
||||
<CoverImage
|
||||
uri={artistCoverUrl(config.serverUrl, data.artist.id)}
|
||||
hasCover={data.artist.photo != null}
|
||||
style={styles.avatar}
|
||||
/>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Shuffle"
|
||||
hitSlop={8}
|
||||
onPress={() => void playArtistShuffled(data.artist.id)}
|
||||
style={[styles.iconAction, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Ionicons name="shuffle" size={24} color={colors.foreground} />
|
||||
</Pressable>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>
|
||||
{data.artist.name}
|
||||
</Text>
|
||||
<View style={styles.actions}>
|
||||
<Pressable
|
||||
onPress={() => void toggleArtistFavorite(data.artist.id)}
|
||||
hitSlop={8}
|
||||
style={[styles.iconAction, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Ionicons
|
||||
name={
|
||||
isArtistFavorite(data.artist.id) ? "star" : "star-outline"
|
||||
}
|
||||
size={24}
|
||||
color={
|
||||
isArtistFavorite(data.artist.id)
|
||||
? colors.primary
|
||||
: colors.foreground
|
||||
}
|
||||
/>
|
||||
</Pressable>
|
||||
<Button
|
||||
title="Play"
|
||||
icon="play"
|
||||
onPress={() => void playArtist(data.artist.id)}
|
||||
style={styles.playButton}
|
||||
/>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Shuffle"
|
||||
hitSlop={8}
|
||||
onPress={() => void playArtistShuffled(data.artist.id)}
|
||||
style={[styles.iconAction, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Ionicons name="shuffle" size={24} color={colors.foreground} />
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={styles.section}>
|
||||
<MediaGrid content={data.albums} />
|
||||
</View>
|
||||
</ScrollView>
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -153,6 +168,4 @@ const styles = StyleSheet.create({
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
section: { padding: spacing.lg, gap: spacing.md },
|
||||
sectionTitle: { fontSize: 20, fontWeight: "700" },
|
||||
})
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useQuery } from "convex/react"
|
||||
import { Pressable, ScrollView, StyleSheet } from "react-native"
|
||||
import { Pressable } from "react-native"
|
||||
|
||||
import { MediaGrid } from "@/components/media-cards"
|
||||
import { MediaGridList } from "@/components/media-cards"
|
||||
import { LoadingView } from "@/components/ui/primitives"
|
||||
import { tabContentBottomInset } from "@/components/player"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { spacing, useThemeColors } from "@/lib/theme"
|
||||
import { useThemeColors } from "@/lib/theme"
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
import { Stack } from "expo-router"
|
||||
import { SymbolView } from "expo-symbols"
|
||||
@@ -60,20 +60,10 @@ export default function PlaylistsTabScreen() {
|
||||
),
|
||||
}}
|
||||
/>
|
||||
<ScrollView
|
||||
style={{ flex: 1, backgroundColor: colors.background }}
|
||||
contentContainerStyle={[
|
||||
styles.content,
|
||||
{ paddingBottom: tabContentBottomInset },
|
||||
]}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
>
|
||||
<MediaGrid content={playlists} />
|
||||
</ScrollView>
|
||||
<MediaGridList
|
||||
content={playlists}
|
||||
paddingBottom={tabContentBottomInset}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
content: { padding: spacing.lg },
|
||||
})
|
||||
@@ -6,7 +6,7 @@ import { FlatList, StyleSheet } from "react-native"
|
||||
import { contentBottomInset, SongRow } from "@/components/player"
|
||||
import { LoadingView } from "@/components/ui/primitives"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlayback } from "@/contexts/playback"
|
||||
import { usePlaybackActions } from "@/contexts/playback"
|
||||
import { useDebouncedSearch } from "@/hooks/use-debounced-search"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
@@ -16,7 +16,7 @@ import { spacing } from "@/lib/theme"
|
||||
const PAGE_SIZE = 50
|
||||
|
||||
export default function SongsScreen() {
|
||||
const { playFromLibrarySong } = usePlayback()
|
||||
const { playFromLibrarySong } = usePlaybackActions()
|
||||
const { isSongFavorite } = useFavorites()
|
||||
const { handleSongAction } = useMediaMenuActions()
|
||||
const { searchQuery, onQueryChange, onSearchSubmit } = useDebouncedSearch()
|
||||
|
||||
@@ -19,7 +19,14 @@ import {
|
||||
scrollContentBackground,
|
||||
} from "@expo/ui/swift-ui/modifiers"
|
||||
import { Stack, useLocalSearchParams, useRouter } from "expo-router"
|
||||
import { FlatList, Platform, Pressable, StyleSheet, Text, View } from "react-native"
|
||||
import {
|
||||
FlatList,
|
||||
Platform,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
} from "react-native"
|
||||
import ReanimatedSwipeable from "react-native-gesture-handler/ReanimatedSwipeable"
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
|
||||
@@ -32,7 +39,7 @@ import {
|
||||
import { Button, LoadingView } from "@/components/ui/primitives"
|
||||
import { contentBottomInset, SongRow } from "@/components/player"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlayback } from "@/contexts/playback"
|
||||
import { usePlaybackActions } from "@/contexts/playback"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
@@ -52,33 +59,53 @@ export default function PlaylistScreen() {
|
||||
const router = useRouter()
|
||||
const colors = useThemeColors()
|
||||
const { config } = useServerConfig()
|
||||
const playlist = useQuery(api.playlists.browsePlaylistDetail, {
|
||||
id: id as Id<"playlists">,
|
||||
includeSongs: false,
|
||||
})
|
||||
const playlistId = typeof id === "string" ? (id as Id<"playlists">) : null
|
||||
const playlist = useQuery(
|
||||
api.playlists.browsePlaylistDetail,
|
||||
playlistId
|
||||
? {
|
||||
id: playlistId,
|
||||
includeSongs: false,
|
||||
}
|
||||
: "skip"
|
||||
)
|
||||
const {
|
||||
results: songs,
|
||||
status,
|
||||
loadMore,
|
||||
} = usePaginatedQuery(
|
||||
api.playlists.browsePlaylistSongsPaginated,
|
||||
{ id: id as Id<"playlists"> },
|
||||
playlistId ? { id: playlistId } : "skip",
|
||||
{ initialNumItems: PAGE_SIZE }
|
||||
)
|
||||
const allSongIds = useQuery(api.playlists.getPlaylistSongIds, {
|
||||
playlistId: id as Id<"playlists">,
|
||||
})
|
||||
const { playPlaylist, playPlaylistShuffled, playFromSong } = usePlayback()
|
||||
const allSongIds = useQuery(
|
||||
api.playlists.getPlaylistSongIds,
|
||||
playlistId ? { playlistId } : "skip"
|
||||
)
|
||||
const { playPlaylist, playPlaylistShuffled, playFromSong } =
|
||||
usePlaybackActions()
|
||||
const { isSongFavorite } = useFavorites()
|
||||
const { handleSongAction, handlePlaylistDetailAction } = useMediaMenuActions()
|
||||
const subscribe = useMutation(api.playlists.subscribeToPlaylist)
|
||||
const unsubscribe = useMutation(api.playlists.unsubscribeFromPlaylist)
|
||||
const deletePlaylist = useMutation(api.playlists.deletePlaylist)
|
||||
const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist)
|
||||
const coverUri = config && playlist ? playlistCoverUrl(config.serverUrl, playlist.id ?? "favorites") : ""
|
||||
const backgroundColor = useCoverBackgroundColor(coverUri, playlist?.cover != null, colors.background)
|
||||
const coverUri =
|
||||
config && playlist
|
||||
? playlistCoverUrl(config.serverUrl, playlist.id ?? "favorites")
|
||||
: ""
|
||||
const backgroundColor = useCoverBackgroundColor(
|
||||
coverUri,
|
||||
playlist?.cover != null,
|
||||
colors.background
|
||||
)
|
||||
|
||||
if (playlist === undefined || songs === undefined || allSongIds === undefined || !config) {
|
||||
if (
|
||||
playlist === undefined ||
|
||||
songs === undefined ||
|
||||
allSongIds === undefined ||
|
||||
!config
|
||||
) {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
@@ -128,7 +155,9 @@ export default function PlaylistScreen() {
|
||||
showSuccess("Subscribed")
|
||||
}
|
||||
} catch (error) {
|
||||
showError(error instanceof Error ? error.message : "Failed to update subscription")
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to update subscription"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,7 +168,9 @@ export default function PlaylistScreen() {
|
||||
showSuccess("Playlist deleted")
|
||||
router.back()
|
||||
} catch (error) {
|
||||
showError(error instanceof Error ? error.message : "Failed to delete playlist")
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to delete playlist"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,7 +189,11 @@ export default function PlaylistScreen() {
|
||||
await removeSongs({ playlistId: playlist.id, songIds: [songId] })
|
||||
showSuccess("Removed from playlist")
|
||||
} catch (error) {
|
||||
showError(error instanceof Error ? error.message : "Failed to remove from playlist")
|
||||
showError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Failed to remove from playlist"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -249,9 +284,7 @@ export default function PlaylistScreen() {
|
||||
listRowInsets({ top: 0, leading: 0, bottom: 0, trailing: 0 }),
|
||||
listRowSeparator("hidden"),
|
||||
]
|
||||
const nativeSongRowModifiers = [
|
||||
frame({ height: 32 }),
|
||||
]
|
||||
const nativeSongRowModifiers = [frame({ height: 32 })]
|
||||
const shouldUseNativeSwipeList =
|
||||
Platform.OS === "ios" && playlist.isOwner && playlist.id
|
||||
|
||||
@@ -285,7 +318,11 @@ export default function PlaylistScreen() {
|
||||
onAction={handlePlaylistMenuAction}
|
||||
>
|
||||
<Pressable hitSlop={8}>
|
||||
<Ionicons name="ellipsis-horizontal" size={22} color={colors.foreground} />
|
||||
<Ionicons
|
||||
name="ellipsis-horizontal"
|
||||
size={22}
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
</MediaActionMenu>
|
||||
),
|
||||
@@ -310,7 +347,9 @@ export default function PlaylistScreen() {
|
||||
ownerName={playlist.owner.name}
|
||||
colors={colors}
|
||||
onPlay={() => playlist.id && void playPlaylist(playlist.id)}
|
||||
onShuffle={() => playlist.id && void playPlaylistShuffled(playlist.id)}
|
||||
onShuffle={() =>
|
||||
playlist.id && void playPlaylistShuffled(playlist.id)
|
||||
}
|
||||
/>
|
||||
</RNHostView>
|
||||
</SwipeActions>
|
||||
@@ -367,7 +406,9 @@ export default function PlaylistScreen() {
|
||||
showSubscribe={!playlist.isOwner && !!playlist.id}
|
||||
onSubscribeToggle={() => void handleSubscribeToggle()}
|
||||
onPlay={() => playlist.id && void playPlaylist(playlist.id)}
|
||||
onShuffle={() => playlist.id && void playPlaylistShuffled(playlist.id)}
|
||||
onShuffle={() =>
|
||||
playlist.id && void playPlaylistShuffled(playlist.id)
|
||||
}
|
||||
/>
|
||||
}
|
||||
renderItem={({ item: song }) => {
|
||||
@@ -398,8 +439,17 @@ export default function PlaylistScreen() {
|
||||
{ backgroundColor: colors.destructive },
|
||||
]}
|
||||
>
|
||||
<Ionicons name="trash" size={22} color={colors.primaryForeground} />
|
||||
<Text style={[styles.removeActionText, { color: colors.primaryForeground }]}>
|
||||
<Ionicons
|
||||
name="trash"
|
||||
size={22}
|
||||
color={colors.primaryForeground}
|
||||
/>
|
||||
<Text
|
||||
style={[
|
||||
styles.removeActionText,
|
||||
{ color: colors.primaryForeground },
|
||||
]}
|
||||
>
|
||||
Remove
|
||||
</Text>
|
||||
</Pressable>
|
||||
@@ -440,11 +490,7 @@ function PlaylistHero({
|
||||
}) {
|
||||
return (
|
||||
<View style={styles.hero}>
|
||||
<CoverImage
|
||||
uri={coverUri}
|
||||
hasCover={hasCover}
|
||||
style={styles.cover}
|
||||
/>
|
||||
<CoverImage uri={coverUri} hasCover={hasCover} style={styles.cover} />
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>{title}</Text>
|
||||
<Text style={{ color: colors.mutedForeground }}>{ownerName}</Text>
|
||||
<View style={styles.actions}>
|
||||
@@ -458,9 +504,7 @@ function PlaylistHero({
|
||||
style={[
|
||||
styles.iconAction,
|
||||
{
|
||||
backgroundColor: isSubscribed
|
||||
? colors.muted
|
||||
: colors.primary,
|
||||
backgroundColor: isSubscribed ? colors.muted : colors.primary,
|
||||
},
|
||||
]}
|
||||
>
|
||||
@@ -468,9 +512,7 @@ function PlaylistHero({
|
||||
name={isSubscribed ? "checkmark" : "add"}
|
||||
size={24}
|
||||
color={
|
||||
isSubscribed
|
||||
? colors.foreground
|
||||
: colors.primaryForeground
|
||||
isSubscribed ? colors.foreground : colors.primaryForeground
|
||||
}
|
||||
/>
|
||||
</Pressable>
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { useQuery } from "convex/react"
|
||||
import { Pressable, ScrollView, StyleSheet, Text, View } from "react-native"
|
||||
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
|
||||
|
||||
import { Button, LoadingView } from "@/components/ui/primitives"
|
||||
import { contentBottomInset, SongRow } from "@/components/player"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlayback } from "@/contexts/playback"
|
||||
import { usePlaybackActions } from "@/contexts/playback"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
@@ -17,7 +17,7 @@ export default function FavoritesScreen() {
|
||||
const colors = useThemeColors()
|
||||
const { config } = useServerConfig()
|
||||
const favorites = useQuery(api.favorites.browseFavoritesPlaylistDetail)
|
||||
const { playInOrder, playShuffled, playFromSong } = usePlayback()
|
||||
const { playInOrder, playShuffled, playFromSong } = usePlaybackActions()
|
||||
const { isSongFavorite } = useFavorites()
|
||||
const { handleSongAction } = useMediaMenuActions()
|
||||
|
||||
@@ -63,54 +63,51 @@ export default function FavoritesScreen() {
|
||||
headerLargeTitle: false,
|
||||
}}
|
||||
/>
|
||||
<ScrollView
|
||||
<FlatList
|
||||
data={favorites.songs}
|
||||
keyExtractor={(song) => song.id}
|
||||
style={{ flex: 1, backgroundColor: colors.background }}
|
||||
contentContainerStyle={{ paddingBottom: contentBottomInset }}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
>
|
||||
<View style={styles.hero}>
|
||||
<View
|
||||
style={[
|
||||
styles.cover,
|
||||
{
|
||||
backgroundColor: colors.coverPlaceholder,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
overflow: "hidden",
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Ionicons
|
||||
name="star"
|
||||
size={120}
|
||||
color={colors.primary}
|
||||
/>
|
||||
</View>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>
|
||||
{favorites.title}
|
||||
</Text>
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
title="Play"
|
||||
icon="play"
|
||||
onPress={() => void playInOrder(songIds)}
|
||||
style={styles.playButton}
|
||||
/>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Shuffle"
|
||||
hitSlop={8}
|
||||
onPress={() => void playShuffled(songIds)}
|
||||
style={[styles.iconAction, { backgroundColor: colors.muted }]}
|
||||
ListHeaderComponent={
|
||||
<View style={styles.hero}>
|
||||
<View
|
||||
style={[
|
||||
styles.cover,
|
||||
{
|
||||
backgroundColor: colors.coverPlaceholder,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
overflow: "hidden",
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Ionicons name="shuffle" size={24} color={colors.foreground} />
|
||||
</Pressable>
|
||||
<Ionicons name="star" size={120} color={colors.primary} />
|
||||
</View>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>
|
||||
{favorites.title}
|
||||
</Text>
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
title="Play"
|
||||
icon="play"
|
||||
onPress={() => void playInOrder(songIds)}
|
||||
style={styles.playButton}
|
||||
/>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Shuffle"
|
||||
hitSlop={8}
|
||||
onPress={() => void playShuffled(songIds)}
|
||||
style={[styles.iconAction, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Ionicons name="shuffle" size={24} color={colors.foreground} />
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{favorites.songs.map((song: BrowseSong) => (
|
||||
}
|
||||
renderItem={({ item: song }: { item: BrowseSong }) => (
|
||||
<SongRow
|
||||
key={song.id}
|
||||
song={song}
|
||||
onPress={() => void playFromSong(song.id, songIds)}
|
||||
contextMenu={{
|
||||
@@ -128,8 +125,8 @@ export default function FavoritesScreen() {
|
||||
onAction: (action) => void handleSongAction(song, action),
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</ScrollView>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,46 +1,58 @@
|
||||
import { usePaginatedQuery, useQuery } from "convex/react"
|
||||
import { Stack, useRouter } from "expo-router"
|
||||
import { useState } from "react"
|
||||
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
|
||||
|
||||
import { Button, LoadingView } from "@/components/ui/primitives"
|
||||
import { contentBottomInset, SongRow } from "@/components/player"
|
||||
import { usePlayback } from "@/contexts/playback"
|
||||
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
import { spacing, useThemeColors } from "@/lib/theme"
|
||||
import { showError } from "@/lib/toast"
|
||||
|
||||
const PAGE_SIZE = 50
|
||||
|
||||
export default function QueueScreen() {
|
||||
const router = useRouter()
|
||||
const colors = useThemeColors()
|
||||
const {
|
||||
queueSongIds,
|
||||
currentSong,
|
||||
skipToQueueIndex,
|
||||
clearQueue,
|
||||
reorderQueue,
|
||||
} = usePlayback()
|
||||
const { queueSongIds, currentSong } = usePlaybackQueue()
|
||||
const { skipToQueueIndex, clearQueue, reorderQueue } = usePlaybackActions()
|
||||
const [reordering, setReordering] = useState(false)
|
||||
|
||||
const queueVersion = queueSongIds.length
|
||||
? `${queueSongIds.length}:${queueSongIds[0]}:${queueSongIds[queueSongIds.length - 1]}`
|
||||
: "empty"
|
||||
|
||||
const { results: queueSongs, status, loadMore } = usePaginatedQuery(
|
||||
const {
|
||||
results: queueSongs,
|
||||
status,
|
||||
loadMore,
|
||||
} = usePaginatedQuery(
|
||||
api.playback.getQueuePaginated,
|
||||
{ queueVersion },
|
||||
queueSongIds.length > 0 ? { queueVersion } : "skip",
|
||||
{ initialNumItems: PAGE_SIZE }
|
||||
)
|
||||
|
||||
const historySongs = useQuery(api.playback.getQueueHistory)
|
||||
|
||||
function moveSong(fromIndex: number, direction: -1 | 1) {
|
||||
async function moveSong(fromIndex: number, direction: -1 | 1) {
|
||||
if (reordering) return
|
||||
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)
|
||||
setReordering(true)
|
||||
try {
|
||||
await reorderQueue(next)
|
||||
} catch (error) {
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to reorder queue"
|
||||
)
|
||||
} finally {
|
||||
setReordering(false)
|
||||
}
|
||||
}
|
||||
|
||||
function handleClearQueue() {
|
||||
@@ -55,7 +67,7 @@ export default function QueueScreen() {
|
||||
void clearQueue()
|
||||
}
|
||||
|
||||
if (queueSongs === undefined) {
|
||||
if (queueSongIds.length > 0 && queueSongs === undefined) {
|
||||
return <LoadingView />
|
||||
}
|
||||
|
||||
@@ -65,7 +77,11 @@ export default function QueueScreen() {
|
||||
options={{
|
||||
headerRight: () =>
|
||||
queueSongIds.length > 0 ? (
|
||||
<Button title="Clear" variant="ghost" onPress={handleClearQueue} />
|
||||
<Button
|
||||
title="Clear"
|
||||
variant="ghost"
|
||||
onPress={handleClearQueue}
|
||||
/>
|
||||
) : null,
|
||||
}}
|
||||
/>
|
||||
@@ -73,7 +89,9 @@ export default function QueueScreen() {
|
||||
style={{ flex: 1, backgroundColor: colors.background }}
|
||||
ListHeaderComponent={
|
||||
<View>
|
||||
<Text style={[styles.section, { color: colors.mutedForeground }]}>Up Next</Text>
|
||||
<Text style={[styles.section, { color: colors.mutedForeground }]}>
|
||||
Up Next
|
||||
</Text>
|
||||
{queueSongIds.length === 0 ? (
|
||||
<Text style={[styles.empty, { color: colors.mutedForeground }]}>
|
||||
Queue is empty
|
||||
@@ -81,31 +99,38 @@ export default function QueueScreen() {
|
||||
) : null}
|
||||
</View>
|
||||
}
|
||||
data={queueSongs}
|
||||
data={queueSongs ?? []}
|
||||
keyExtractor={(item) => `${item.id}-${item.queueIndex}`}
|
||||
contentContainerStyle={{ paddingBottom: contentBottomInset }}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
onEndReached={() => {
|
||||
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
|
||||
}}
|
||||
renderItem={({ item, index }) => (
|
||||
renderItem={({ item }) => (
|
||||
<View>
|
||||
<SongRow
|
||||
song={item}
|
||||
onPress={() => void skipToQueueIndex(item.queueIndex)}
|
||||
/>
|
||||
<View style={styles.queueActions}>
|
||||
<Pressable disabled={index === 0} onPress={() => moveSong(index, -1)}>
|
||||
<Pressable
|
||||
disabled={reordering || item.queueIndex === 0}
|
||||
onPress={() => void moveSong(item.queueIndex, -1)}
|
||||
>
|
||||
<Text style={{ color: colors.foreground }}>Move up</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
disabled={index === queueSongIds.length - 1}
|
||||
onPress={() => moveSong(index, 1)}
|
||||
disabled={
|
||||
reordering || item.queueIndex === queueSongIds.length - 1
|
||||
}
|
||||
onPress={() => void moveSong(item.queueIndex, 1)}
|
||||
>
|
||||
<Text style={{ color: colors.foreground }}>Move down</Text>
|
||||
</Pressable>
|
||||
{currentSong?.id === item.id ? (
|
||||
<Text style={{ color: colors.primary, fontWeight: "700" }}>Now playing</Text>
|
||||
<Text style={{ color: colors.primary, fontWeight: "700" }}>
|
||||
Now playing
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
@@ -113,7 +138,9 @@ export default function QueueScreen() {
|
||||
ListFooterComponent={
|
||||
historySongs && historySongs.length > 0 ? (
|
||||
<View style={styles.history}>
|
||||
<Text style={[styles.section, { color: colors.mutedForeground }]}>History</Text>
|
||||
<Text style={[styles.section, { color: colors.mutedForeground }]}>
|
||||
History
|
||||
</Text>
|
||||
{historySongs.map((song: BrowseSong) => (
|
||||
<SongRow key={song.id} song={song} />
|
||||
))}
|
||||
|
||||
@@ -24,10 +24,27 @@ import { radius, spacing, useThemeColors } from "@/lib/theme"
|
||||
import { showError, showSuccess } from "@/lib/toast"
|
||||
import type { PlaybackQuality } from "@/lib/urls"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Doc, Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
|
||||
type Section = "profile" | "quality" | "library" | "users"
|
||||
|
||||
type CurrentUser = {
|
||||
_id: Id<"users">
|
||||
name: string
|
||||
image?: string
|
||||
email: string
|
||||
isAdmin?: boolean
|
||||
playbackQuality?: PlaybackQuality
|
||||
preferAtmos?: boolean
|
||||
}
|
||||
|
||||
type AdminUser = {
|
||||
_id: Id<"users">
|
||||
name: string
|
||||
email: string
|
||||
isAdmin?: boolean
|
||||
}
|
||||
|
||||
type SectionConfig = {
|
||||
id: Section
|
||||
label: string
|
||||
@@ -57,10 +74,13 @@ export default function SettingsScreen() {
|
||||
const colors = useThemeColors()
|
||||
const router = useRouter()
|
||||
const user = useQuery(api.auth.currentUser)
|
||||
const allUsers = useQuery(api.users.listUsers)
|
||||
const { invalidateSession } = useInvalidateAuthSession()
|
||||
const { clearServer } = useServerConfig()
|
||||
const [section, setSection] = useState<Section>("profile")
|
||||
const allUsers = useQuery(
|
||||
api.users.listUsers,
|
||||
user?.isAdmin === true && section === "users" ? {} : "skip"
|
||||
)
|
||||
|
||||
if (!user) {
|
||||
return <LoadingView />
|
||||
@@ -106,7 +126,9 @@ export default function SettingsScreen() {
|
||||
<Ionicons
|
||||
name={item.icon}
|
||||
size={26}
|
||||
color={selected ? colors.primaryForeground : colors.mutedForeground}
|
||||
color={
|
||||
selected ? colors.primaryForeground : colors.mutedForeground
|
||||
}
|
||||
/>
|
||||
</Pressable>
|
||||
)
|
||||
@@ -130,7 +152,7 @@ export default function SettingsScreen() {
|
||||
)
|
||||
}
|
||||
|
||||
function ProfileSection({ user }: { user: Doc<"users"> }) {
|
||||
function ProfileSection({ user }: { user: CurrentUser }) {
|
||||
const colors = useThemeColors()
|
||||
const updateName = useMutation(api.users.updateProfileName)
|
||||
const updateEmail = useMutation(api.users.updateProfileEmail)
|
||||
@@ -152,10 +174,14 @@ function ProfileSection({ user }: { user: Doc<"users"> }) {
|
||||
|
||||
const mime = result.assets[0].mimeType ?? "image/jpeg"
|
||||
try {
|
||||
await updateImage({ image: `data:${mime};base64,${result.assets[0].base64}` })
|
||||
await updateImage({
|
||||
image: `data:${mime};base64,${result.assets[0].base64}`,
|
||||
})
|
||||
showSuccess("Profile photo updated")
|
||||
} catch (error) {
|
||||
showError(error instanceof Error ? error.message : "Failed to update photo")
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to update photo"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,7 +190,9 @@ function ProfileSection({ user }: { user: Doc<"users"> }) {
|
||||
await updateImage({ image: null })
|
||||
showSuccess("Profile photo removed")
|
||||
} catch (error) {
|
||||
showError(error instanceof Error ? error.message : "Failed to remove photo")
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to remove photo"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,7 +209,9 @@ function ProfileSection({ user }: { user: Doc<"users"> }) {
|
||||
setConfirmPassword("")
|
||||
showSuccess("Password updated")
|
||||
} catch (error) {
|
||||
showError(error instanceof Error ? error.message : "Failed to update password")
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to update password"
|
||||
)
|
||||
} finally {
|
||||
setChangingPassword(false)
|
||||
}
|
||||
@@ -214,7 +244,10 @@ function ProfileSection({ user }: { user: Doc<"users"> }) {
|
||||
</View>
|
||||
</SettingsCard>
|
||||
|
||||
<SettingsCard title="Account Details" subtitle="Keep your profile information up to date.">
|
||||
<SettingsCard
|
||||
title="Account Details"
|
||||
subtitle="Keep your profile information up to date."
|
||||
>
|
||||
<Field label="Name">
|
||||
<Input value={name} onChangeText={setName} placeholder="Name" />
|
||||
</Field>
|
||||
@@ -252,7 +285,10 @@ function ProfileSection({ user }: { user: Doc<"users"> }) {
|
||||
/>
|
||||
</SettingsCard>
|
||||
|
||||
<SettingsCard title="Password" subtitle="Choose a new password for this account.">
|
||||
<SettingsCard
|
||||
title="Password"
|
||||
subtitle="Choose a new password for this account."
|
||||
>
|
||||
<Field label="New Password">
|
||||
<Input
|
||||
value={newPassword}
|
||||
@@ -280,7 +316,7 @@ function ProfileSection({ user }: { user: Doc<"users"> }) {
|
||||
)
|
||||
}
|
||||
|
||||
function QualitySection({ user }: { user: Doc<"users"> }) {
|
||||
function QualitySection({ user }: { user: CurrentUser }) {
|
||||
const colors = useThemeColors()
|
||||
const updateQuality = useMutation(api.users.updatePlaybackQuality)
|
||||
const updateAtmos = useMutation(api.users.updatePreferAtmos)
|
||||
@@ -300,8 +336,8 @@ function QualitySection({ user }: { user: Doc<"users"> }) {
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected }}
|
||||
onPress={() =>
|
||||
void updateQuality({ playbackQuality: option.value }).catch((error: Error) =>
|
||||
showError(error.message)
|
||||
void updateQuality({ playbackQuality: option.value }).catch(
|
||||
(error: Error) => showError(error.message)
|
||||
)
|
||||
}
|
||||
style={[
|
||||
@@ -313,13 +349,21 @@ function QualitySection({ user }: { user: Doc<"users"> }) {
|
||||
]}
|
||||
>
|
||||
<View style={styles.optionCopy}>
|
||||
<Text style={[styles.optionTitle, { color: colors.foreground }]}>
|
||||
<Text
|
||||
style={[styles.optionTitle, { color: colors.foreground }]}
|
||||
>
|
||||
{option.label}
|
||||
</Text>
|
||||
<Text style={{ color: colors.mutedForeground }}>{option.description}</Text>
|
||||
<Text style={{ color: colors.mutedForeground }}>
|
||||
{option.description}
|
||||
</Text>
|
||||
</View>
|
||||
{selected ? (
|
||||
<Ionicons name="checkmark-circle" size={22} color={colors.primary} />
|
||||
<Ionicons
|
||||
name="checkmark-circle"
|
||||
size={22}
|
||||
color={colors.primary}
|
||||
/>
|
||||
) : null}
|
||||
</Pressable>
|
||||
)
|
||||
@@ -363,7 +407,11 @@ function LibrarySection() {
|
||||
await updateLibrary({})
|
||||
showSuccess("Library updated")
|
||||
} catch (error) {
|
||||
showError(error instanceof Error ? error.message : "Failed to update library")
|
||||
showError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Failed to update library"
|
||||
)
|
||||
} finally {
|
||||
setUpdating(false)
|
||||
}
|
||||
@@ -380,7 +428,11 @@ function LibrarySection() {
|
||||
const result = await cleanupHlsStreams({})
|
||||
showSuccess(`Removed ${result.removed} idle HLS streams`)
|
||||
} catch (error) {
|
||||
showError(error instanceof Error ? error.message : "Failed to clean HLS streams")
|
||||
showError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Failed to clean HLS streams"
|
||||
)
|
||||
} finally {
|
||||
setCleaningHls(false)
|
||||
}
|
||||
@@ -394,7 +446,7 @@ function UsersSection({
|
||||
users,
|
||||
currentUserId,
|
||||
}: {
|
||||
users: Doc<"users">[]
|
||||
users: AdminUser[]
|
||||
currentUserId: Id<"users">
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
@@ -411,35 +463,53 @@ function UsersSection({
|
||||
subtitle="Prevent new users from creating accounts."
|
||||
value={appSettings?.disableAccountCreation ?? false}
|
||||
onValueChange={(checked) =>
|
||||
void setDisableCreation({ disabled: checked }).catch((error: Error) =>
|
||||
showError(error.message)
|
||||
void setDisableCreation({ disabled: checked }).catch(
|
||||
(error: Error) => showError(error.message)
|
||||
)
|
||||
}
|
||||
/>
|
||||
</SettingsCard>
|
||||
|
||||
<SettingsCard title="People" subtitle="Manage who can access this server.">
|
||||
<SettingsCard
|
||||
title="People"
|
||||
subtitle="Manage who can access this server."
|
||||
>
|
||||
{users.map((user, index) => (
|
||||
<View key={user._id}>
|
||||
{index > 0 ? (
|
||||
<View style={[styles.divider, { backgroundColor: colors.border }]} />
|
||||
<View
|
||||
style={[styles.divider, { backgroundColor: colors.border }]}
|
||||
/>
|
||||
) : null}
|
||||
<View style={styles.userRow}>
|
||||
<ProfileAvatar user={user} size={44} />
|
||||
<View style={styles.userCopy}>
|
||||
<View style={styles.userNameRow}>
|
||||
<Text style={[styles.userName, { color: colors.foreground }]} numberOfLines={1}>
|
||||
<Text
|
||||
style={[styles.userName, { color: colors.foreground }]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{user.name}
|
||||
</Text>
|
||||
{user.isAdmin ? (
|
||||
<View style={[styles.badge, { backgroundColor: colors.muted }]}>
|
||||
<Text style={[styles.badgeText, { color: colors.mutedForeground }]}>
|
||||
<View
|
||||
style={[styles.badge, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Text
|
||||
style={[
|
||||
styles.badgeText,
|
||||
{ color: colors.mutedForeground },
|
||||
]}
|
||||
>
|
||||
Admin
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
<Text style={{ color: colors.mutedForeground }} numberOfLines={1}>
|
||||
<Text
|
||||
style={{ color: colors.mutedForeground }}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{user.email}
|
||||
</Text>
|
||||
</View>
|
||||
@@ -450,7 +520,10 @@ function UsersSection({
|
||||
title={user.isAdmin ? "Remove Admin" : "Make Admin"}
|
||||
variant="secondary"
|
||||
onPress={() =>
|
||||
void setAdmin({ userId: user._id, isAdmin: !user.isAdmin }).then(
|
||||
void setAdmin({
|
||||
userId: user._id,
|
||||
isAdmin: !user.isAdmin,
|
||||
}).then(
|
||||
() => showSuccess("Updated permissions"),
|
||||
(error: Error) => showError(error.message)
|
||||
)
|
||||
@@ -520,9 +593,15 @@ function SettingsCard({
|
||||
return (
|
||||
<View style={[styles.card, { backgroundColor: colors.card }]}>
|
||||
<View style={styles.cardHeader}>
|
||||
<Text style={[styles.cardTitle, { color: colors.foreground }]}>{title}</Text>
|
||||
<Text style={[styles.cardTitle, { color: colors.foreground }]}>
|
||||
{title}
|
||||
</Text>
|
||||
{subtitle ? (
|
||||
<Text style={[styles.cardSubtitle, { color: colors.mutedForeground }]}>{subtitle}</Text>
|
||||
<Text
|
||||
style={[styles.cardSubtitle, { color: colors.mutedForeground }]}
|
||||
>
|
||||
{subtitle}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
{children}
|
||||
@@ -530,12 +609,20 @@ function SettingsCard({
|
||||
)
|
||||
}
|
||||
|
||||
function Field({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
function Field({
|
||||
label,
|
||||
children,
|
||||
}: {
|
||||
label: string
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
|
||||
return (
|
||||
<View style={styles.field}>
|
||||
<Text style={[styles.fieldLabel, { color: colors.mutedForeground }]}>{label}</Text>
|
||||
<Text style={[styles.fieldLabel, { color: colors.mutedForeground }]}>
|
||||
{label}
|
||||
</Text>
|
||||
{children}
|
||||
</View>
|
||||
)
|
||||
@@ -557,8 +644,12 @@ function SwitchRow({
|
||||
return (
|
||||
<View style={styles.switchRow}>
|
||||
<View style={styles.optionCopy}>
|
||||
<Text style={[styles.optionTitle, { color: colors.foreground }]}>{title}</Text>
|
||||
{subtitle ? <Text style={{ color: colors.mutedForeground }}>{subtitle}</Text> : null}
|
||||
<Text style={[styles.optionTitle, { color: colors.foreground }]}>
|
||||
{title}
|
||||
</Text>
|
||||
{subtitle ? (
|
||||
<Text style={{ color: colors.mutedForeground }}>{subtitle}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Switch value={value} onValueChange={onValueChange} />
|
||||
</View>
|
||||
@@ -585,7 +676,10 @@ function ActionRow({
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={onPress}
|
||||
style={({ pressed }) => [styles.actionRow, { opacity: pressed ? 0.75 : 1 }]}
|
||||
style={({ pressed }) => [
|
||||
styles.actionRow,
|
||||
{ opacity: pressed ? 0.75 : 1 },
|
||||
]}
|
||||
>
|
||||
<View style={[styles.actionIcon, { backgroundColor: colors.muted }]}>
|
||||
<Ionicons name={icon} size={20} color={tint} />
|
||||
@@ -594,7 +688,11 @@ function ActionRow({
|
||||
<Text style={[styles.optionTitle, { color: tint }]}>{title}</Text>
|
||||
<Text style={{ color: colors.mutedForeground }}>{subtitle}</Text>
|
||||
</View>
|
||||
<Ionicons name="chevron-forward" size={18} color={colors.mutedForeground} />
|
||||
<Ionicons
|
||||
name="chevron-forward"
|
||||
size={18}
|
||||
color={colors.mutedForeground}
|
||||
/>
|
||||
</Pressable>
|
||||
)
|
||||
}
|
||||
@@ -604,7 +702,7 @@ function ProfileAvatar({
|
||||
size,
|
||||
style,
|
||||
}: {
|
||||
user: Pick<Doc<"users">, "name" | "image">
|
||||
user: Pick<CurrentUser, "name" | "image">
|
||||
size: number
|
||||
style?: StyleProp<ViewStyle>
|
||||
}) {
|
||||
@@ -623,14 +721,23 @@ function ProfileAvatar({
|
||||
if (user.image) {
|
||||
return (
|
||||
<View style={avatarStyle}>
|
||||
<Image source={{ uri: user.image }} style={styles.avatarImage} contentFit="cover" />
|
||||
<Image
|
||||
source={{ uri: user.image }}
|
||||
style={styles.avatarImage}
|
||||
contentFit="cover"
|
||||
/>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={avatarStyle}>
|
||||
<Text style={[styles.avatarInitials, { color: colors.foreground, fontSize: size * 0.34 }]}>
|
||||
<Text
|
||||
style={[
|
||||
styles.avatarInitials,
|
||||
{ color: colors.foreground, fontSize: size * 0.34 },
|
||||
]}
|
||||
>
|
||||
{initialsFromName(user.name)}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
@@ -17,7 +17,7 @@ export default function SearchScreen() {
|
||||
return (
|
||||
<>
|
||||
<Stack.SearchBar
|
||||
placeholder="Artists, Alubms, Songs, and More"
|
||||
placeholder="Artists, Albums, Songs, and More"
|
||||
onChangeText={handleChangeText}
|
||||
onSearchButtonPress={onSearchSubmit}
|
||||
autoCapitalize="none"
|
||||
|
||||
+36
-11
@@ -1,6 +1,12 @@
|
||||
import { useRouter } from "expo-router"
|
||||
import { useEffect, useState } from "react"
|
||||
import { KeyboardAvoidingView, Platform, StyleSheet, Text, View } from "react-native"
|
||||
import {
|
||||
KeyboardAvoidingView,
|
||||
Platform,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
} from "react-native"
|
||||
import { SafeAreaView } from "react-native-safe-area-context"
|
||||
|
||||
import { Button, Card, Input } from "@/components/ui/primitives"
|
||||
@@ -24,15 +30,22 @@ export default function ServerScreen() {
|
||||
async function handleContinue() {
|
||||
setError(null)
|
||||
setSubmitting(true)
|
||||
const ok = await setServerHostname(hostname)
|
||||
setSubmitting(false)
|
||||
if (!ok) {
|
||||
try {
|
||||
const ok = await setServerHostname(hostname)
|
||||
if (!ok) {
|
||||
setError(
|
||||
"Enter a valid server address, e.g. music.example.com, localhost:3000"
|
||||
)
|
||||
return
|
||||
}
|
||||
router.replace("/signin")
|
||||
} catch {
|
||||
setError(
|
||||
"Enter a valid server address, e.g. music.example.com, localhost:3000"
|
||||
"Could not save the server address. Check device storage and try again."
|
||||
)
|
||||
return
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
router.replace("/signin")
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
@@ -46,14 +59,18 @@ export default function ServerScreen() {
|
||||
style={styles.container}
|
||||
>
|
||||
<View style={styles.hero}>
|
||||
<Text style={[styles.brand, { color: colors.foreground }]}>oTunes</Text>
|
||||
<Text style={[styles.brand, { color: colors.foreground }]}>
|
||||
oTunes
|
||||
</Text>
|
||||
<Text style={[styles.subtitle, { color: colors.mutedForeground }]}>
|
||||
Connect to your oTunes server to start listening.
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<Card>
|
||||
<Text style={[styles.label, { color: colors.foreground }]}>Server address</Text>
|
||||
<Text style={[styles.label, { color: colors.foreground }]}>
|
||||
Server address
|
||||
</Text>
|
||||
<Input
|
||||
value={hostname}
|
||||
onChangeText={setHostname}
|
||||
@@ -67,8 +84,16 @@ export default function ServerScreen() {
|
||||
<Text style={[styles.hint, { color: colors.mutedForeground }]}>
|
||||
Convex will connect to convex.{"{your hostname}"}
|
||||
</Text>
|
||||
{error ? <Text style={[styles.error, { color: colors.destructive }]}>{error}</Text> : null}
|
||||
<Button title="Continue" loading={submitting} onPress={() => void handleContinue()} />
|
||||
{error ? (
|
||||
<Text style={[styles.error, { color: colors.destructive }]}>
|
||||
{error}
|
||||
</Text>
|
||||
) : null}
|
||||
<Button
|
||||
title="Continue"
|
||||
loading={submitting}
|
||||
onPress={() => void handleContinue()}
|
||||
/>
|
||||
</Card>
|
||||
</KeyboardAvoidingView>
|
||||
</SafeAreaView>
|
||||
|
||||
@@ -97,7 +97,7 @@ export const CoverImage = memo(function CoverImage({
|
||||
contentFit={contentFit}
|
||||
transition={150}
|
||||
blurRadius={blurRadius}
|
||||
cachePolicy="disk"
|
||||
cachePolicy="memory-disk"
|
||||
recyclingKey={sourceUri}
|
||||
enforceEarlyResizing
|
||||
/>
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
import { memo, useCallback, type ReactElement } from "react"
|
||||
import { FlatList, Pressable, ScrollView, StyleSheet, Text, View } from "react-native"
|
||||
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
|
||||
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
import { MediaContextMenu } from "@/components/media-context-menu"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { useAppNavigation } from "@/lib/app-navigation"
|
||||
import type { BrowseAlbum, BrowseArtist, PlaylistSummary } from "@otunes/convex/types"
|
||||
import type {
|
||||
BrowseAlbum,
|
||||
BrowseArtist,
|
||||
PlaylistSummary,
|
||||
} from "@otunes/convex/types"
|
||||
import { albumCoverUrl, artistCoverUrl, playlistCoverUrl } from "@/lib/urls"
|
||||
import { carouselCardWidth, radius, spacing, useThemeColors, useTwoColumnCardWidth } from "@/lib/theme"
|
||||
import {
|
||||
carouselCardWidth,
|
||||
radius,
|
||||
spacing,
|
||||
useThemeColors,
|
||||
useTwoColumnCardWidth,
|
||||
} from "@/lib/theme"
|
||||
|
||||
export type MediaItem = BrowseAlbum | BrowseArtist | PlaylistSummary
|
||||
|
||||
@@ -30,19 +40,22 @@ export const AlbumCard = memo(function AlbumCard({
|
||||
if (!config) return null
|
||||
|
||||
const card = (
|
||||
<Pressable
|
||||
style={[styles.card, { width }]}
|
||||
onPress={onPress}
|
||||
>
|
||||
<Pressable style={[styles.card, { width }]} onPress={onPress}>
|
||||
<CoverImage
|
||||
uri={albumCoverUrl(config.serverUrl, album.id)}
|
||||
hasCover={album.cover != null}
|
||||
style={{ width, height: width, borderRadius: radius.md }}
|
||||
/>
|
||||
<Text style={[styles.title, { color: colors.foreground }]} numberOfLines={2}>
|
||||
<Text
|
||||
style={[styles.title, { color: colors.foreground }]}
|
||||
numberOfLines={2}
|
||||
>
|
||||
{album.title}
|
||||
</Text>
|
||||
<Text style={[styles.subtitle, { color: colors.mutedForeground }]} numberOfLines={1}>
|
||||
<Text
|
||||
style={[styles.subtitle, { color: colors.mutedForeground }]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{album.artist.name}
|
||||
</Text>
|
||||
</Pressable>
|
||||
@@ -77,16 +90,16 @@ export const ArtistCard = memo(function ArtistCard({
|
||||
if (!config) return null
|
||||
|
||||
const card = (
|
||||
<Pressable
|
||||
style={[styles.card, { width }]}
|
||||
onPress={onPress}
|
||||
>
|
||||
<Pressable style={[styles.card, { width }]} onPress={onPress}>
|
||||
<CoverImage
|
||||
uri={artistCoverUrl(config.serverUrl, artist.id)}
|
||||
hasCover={artist.photo != null}
|
||||
style={{ width, height: width, borderRadius: width / 2 }}
|
||||
/>
|
||||
<Text style={[styles.title, { color: colors.foreground }]} numberOfLines={2}>
|
||||
<Text
|
||||
style={[styles.title, { color: colors.foreground }]}
|
||||
numberOfLines={2}
|
||||
>
|
||||
{artist.name}
|
||||
</Text>
|
||||
</Pressable>
|
||||
@@ -120,19 +133,22 @@ export const PlaylistCard = memo(function PlaylistCard({
|
||||
if (!config) return null
|
||||
|
||||
const card = (
|
||||
<Pressable
|
||||
style={[styles.card, { width }]}
|
||||
onPress={onPress}
|
||||
>
|
||||
<Pressable style={[styles.card, { width }]} onPress={onPress}>
|
||||
<CoverImage
|
||||
uri={playlistCoverUrl(config.serverUrl, playlist.id)}
|
||||
hasCover={playlist.cover != null}
|
||||
style={{ width, height: width, borderRadius: radius.md }}
|
||||
/>
|
||||
<Text style={[styles.title, { color: colors.foreground }]} numberOfLines={2}>
|
||||
<Text
|
||||
style={[styles.title, { color: colors.foreground }]}
|
||||
numberOfLines={2}
|
||||
>
|
||||
{playlist.title}
|
||||
</Text>
|
||||
<Text style={[styles.subtitle, { color: colors.mutedForeground }]} numberOfLines={1}>
|
||||
<Text
|
||||
style={[styles.subtitle, { color: colors.mutedForeground }]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{playlist.owner}
|
||||
</Text>
|
||||
</Pressable>
|
||||
@@ -242,20 +258,29 @@ function ContentCarouselBody({
|
||||
onPress={onHeaderPress}
|
||||
style={styles.sectionHeader}
|
||||
>
|
||||
<Text style={[styles.sectionTitle, { color: colors.foreground }]}>{title}</Text>
|
||||
{href ? <Ionicons name="chevron-forward" size={18} color={colors.mutedForeground} /> : null}
|
||||
<Text style={[styles.sectionTitle, { color: colors.foreground }]}>
|
||||
{title}
|
||||
</Text>
|
||||
{href ? (
|
||||
<Ionicons
|
||||
name="chevron-forward"
|
||||
size={18}
|
||||
color={colors.mutedForeground}
|
||||
/>
|
||||
) : null}
|
||||
</Pressable>
|
||||
<ScrollView
|
||||
<FlatList
|
||||
data={content}
|
||||
keyExtractor={(item) => item.id}
|
||||
horizontal
|
||||
showsHorizontalScrollIndicator={false}
|
||||
contentContainerStyle={styles.carouselContent}
|
||||
>
|
||||
{content.map((item) => (
|
||||
<View key={item.id}>
|
||||
renderItem={({ item }) => (
|
||||
<View>
|
||||
<CarouselCard item={item} width={carouselCardWidth} />
|
||||
</View>
|
||||
))}
|
||||
</ScrollView>
|
||||
)}
|
||||
/>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -5,10 +5,16 @@ import { Platform, Pressable, StyleSheet, Text, View } from "react-native"
|
||||
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
|
||||
import { usePlayback } from "@/contexts/playback"
|
||||
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { albumCoverUrl } from "@/lib/urls"
|
||||
import { miniPlayerHeight, tabBarHeight, useBlurTint, useMiniPlayerBackground, useThemeColors } from "@/lib/theme"
|
||||
import {
|
||||
miniPlayerHeight,
|
||||
tabBarHeight,
|
||||
useBlurTint,
|
||||
useMiniPlayerBackground,
|
||||
useThemeColors,
|
||||
} from "@/lib/theme"
|
||||
|
||||
function MiniPlayerContent({
|
||||
placement,
|
||||
@@ -21,12 +27,8 @@ function MiniPlayerContent({
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
const { config } = useServerConfig()
|
||||
const {
|
||||
currentSong,
|
||||
isPlaying,
|
||||
setIsPlaying,
|
||||
skipNext,
|
||||
} = usePlayback()
|
||||
const { currentSong, isPlaying } = usePlaybackQueue()
|
||||
const { setIsPlaying, skipNext } = usePlaybackActions()
|
||||
|
||||
if (!currentSong || !config) {
|
||||
return null
|
||||
@@ -35,7 +37,11 @@ function MiniPlayerContent({
|
||||
const compact = placement === "inline"
|
||||
const isAccessory = variant === "accessory"
|
||||
const artworkStyle = isAccessory ? styles.accessoryArtwork : styles.artwork
|
||||
const rowStyle = compact ? styles.inlineContent : isAccessory ? styles.accessoryContent : styles.content
|
||||
const rowStyle = compact
|
||||
? styles.inlineContent
|
||||
: isAccessory
|
||||
? styles.accessoryContent
|
||||
: styles.content
|
||||
|
||||
if (compact) {
|
||||
return (
|
||||
@@ -43,9 +49,13 @@ function MiniPlayerContent({
|
||||
<CoverImage
|
||||
uri={albumCoverUrl(config.serverUrl, currentSong.album.id)}
|
||||
hasCover={currentSong.album.cover != null}
|
||||
style={isAccessory ? styles.accessoryInlineArtwork : styles.inlineArtwork}
|
||||
style={
|
||||
isAccessory ? styles.accessoryInlineArtwork : styles.inlineArtwork
|
||||
}
|
||||
/>
|
||||
<View style={isAccessory ? styles.accessoryInlineMeta : styles.inlineMeta}>
|
||||
<View
|
||||
style={isAccessory ? styles.accessoryInlineMeta : styles.inlineMeta}
|
||||
>
|
||||
<Text
|
||||
style={[
|
||||
isAccessory ? styles.accessoryTitle : styles.title,
|
||||
@@ -145,7 +155,7 @@ function MiniPlayerChrome({ children }: { children: React.ReactNode }) {
|
||||
|
||||
export function TabBottomAccessory() {
|
||||
const router = useRouter()
|
||||
const { currentSong, queueSongIds } = usePlayback()
|
||||
const { currentSong, queueSongIds } = usePlaybackQueue()
|
||||
const placement = NativeTabs.BottomAccessory.usePlacement()
|
||||
|
||||
if (!currentSong || queueSongIds.length === 0) {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useQuery } from "convex/react"
|
||||
import { memo, useMemo } from "react"
|
||||
import { ScrollView, StyleSheet, Text, View } from "react-native"
|
||||
import { FlatList, StyleSheet, Text, View } from "react-native"
|
||||
|
||||
import { ContentCarousel } from "@/components/media-cards"
|
||||
import { tabContentBottomInset, SongRow } from "@/components/player"
|
||||
import { LoadingView } from "@/components/ui/primitives"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlayback } from "@/contexts/playback"
|
||||
import { usePlaybackActions } from "@/contexts/playback"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
@@ -14,7 +14,7 @@ import { spacing, useThemeColors } from "@/lib/theme"
|
||||
|
||||
function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
|
||||
const colors = useThemeColors()
|
||||
const { playFromSong } = usePlayback()
|
||||
const { playFromSong } = usePlaybackActions()
|
||||
const { isSongFavorite } = useFavorites()
|
||||
const { handleSongAction } = useMediaMenuActions()
|
||||
const hasQuery = searchQuery.length > 0
|
||||
@@ -28,18 +28,24 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
|
||||
hasQuery ? { query: searchQuery } : "skip"
|
||||
)
|
||||
|
||||
const isSearching = hasQuery && results === undefined
|
||||
const isSearching =
|
||||
hasQuery && (results === undefined || playlistResults === undefined)
|
||||
|
||||
const hasLibraryResults = useMemo(
|
||||
const hasResults = useMemo(
|
||||
() =>
|
||||
Boolean(
|
||||
results &&
|
||||
(results.topResults.length > 0 ||
|
||||
results.artists.length > 0 ||
|
||||
results.albums.length > 0 ||
|
||||
results.songs.length > 0)
|
||||
(results &&
|
||||
(results.topResults.length > 0 ||
|
||||
results.artists.length > 0 ||
|
||||
results.albums.length > 0 ||
|
||||
results.songs.length > 0)) ||
|
||||
(playlistResults && playlistResults.length > 0)
|
||||
),
|
||||
[results]
|
||||
[playlistResults, results]
|
||||
)
|
||||
const songIds = useMemo(
|
||||
() => results?.songs.map((song) => song.id) ?? [],
|
||||
[results?.songs]
|
||||
)
|
||||
|
||||
if (isSearching) {
|
||||
@@ -51,68 +57,65 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
<FlatList
|
||||
data={results?.songs ?? []}
|
||||
keyExtractor={(song) => song.id}
|
||||
style={{ flex: 1, backgroundColor: colors.background }}
|
||||
contentContainerStyle={{ paddingBottom: tabContentBottomInset }}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
>
|
||||
{!hasLibraryResults ? (
|
||||
<View style={styles.empty}>
|
||||
<Text style={[styles.emptyText, { color: colors.mutedForeground }]}>
|
||||
No results for "{searchQuery}"
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
ListHeaderComponent={
|
||||
<>
|
||||
{!hasResults ? (
|
||||
<View style={styles.empty}>
|
||||
<Text
|
||||
style={[styles.emptyText, { color: colors.mutedForeground }]}
|
||||
>
|
||||
No results for "{searchQuery}"
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{results?.artists.length ? (
|
||||
<View style={styles.section}>
|
||||
<ContentCarousel title="Artists" content={results.artists} />
|
||||
</View>
|
||||
) : null}
|
||||
{results?.artists.length ? (
|
||||
<View style={styles.section}>
|
||||
<ContentCarousel title="Artists" content={results.artists} />
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{results?.albums.length ? (
|
||||
<View style={styles.section}>
|
||||
<ContentCarousel title="Albums" content={results.albums} />
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{results?.songs.length ? (
|
||||
<View style={styles.section}>
|
||||
{results.songs.map((song: BrowseSong) => (
|
||||
<SongRow
|
||||
key={song.id}
|
||||
song={song}
|
||||
onPress={() =>
|
||||
void playFromSong(
|
||||
song.id,
|
||||
results.songs.map((s: BrowseSong) => s.id)
|
||||
)
|
||||
}
|
||||
contextMenu={{
|
||||
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,
|
||||
},
|
||||
onAction: (action) => void handleSongAction(song, action),
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{playlistResults && playlistResults.length > 0 ? (
|
||||
<View style={styles.section}>
|
||||
<ContentCarousel title="Playlists" content={playlistResults} />
|
||||
</View>
|
||||
) : null}
|
||||
</ScrollView>
|
||||
{results?.albums.length ? (
|
||||
<View style={styles.section}>
|
||||
<ContentCarousel title="Albums" content={results.albums} />
|
||||
</View>
|
||||
) : null}
|
||||
</>
|
||||
}
|
||||
renderItem={({ item: song }: { item: BrowseSong }) => (
|
||||
<SongRow
|
||||
song={song}
|
||||
onPress={() => void playFromSong(song.id, songIds)}
|
||||
contextMenu={{
|
||||
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,
|
||||
},
|
||||
onAction: (action) => void handleSongAction(song, action),
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
ListFooterComponent={
|
||||
playlistResults && playlistResults.length > 0 ? (
|
||||
<View style={styles.section}>
|
||||
<ContentCarousel title="Playlists" content={playlistResults} />
|
||||
</View>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,11 +3,20 @@ import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react"
|
||||
import { Modal, Pressable, ScrollView, StyleSheet, Text, View } from "react-native"
|
||||
import {
|
||||
FlatList,
|
||||
Modal,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
} from "react-native"
|
||||
|
||||
import { Button, Input } from "@/components/ui/primitives"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
@@ -25,12 +34,16 @@ type AddToPlaylistContextValue = {
|
||||
openCreatePlaylist: () => void
|
||||
}
|
||||
|
||||
const AddToPlaylistContext = createContext<AddToPlaylistContextValue | null>(null)
|
||||
const AddToPlaylistContext = createContext<AddToPlaylistContextValue | null>(
|
||||
null
|
||||
)
|
||||
|
||||
export function useAddToPlaylist() {
|
||||
const context = useContext(AddToPlaylistContext)
|
||||
if (!context) {
|
||||
throw new Error("useAddToPlaylist must be used within AddToPlaylistProvider")
|
||||
throw new Error(
|
||||
"useAddToPlaylist must be used within AddToPlaylistProvider"
|
||||
)
|
||||
}
|
||||
return context
|
||||
}
|
||||
@@ -39,7 +52,6 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
|
||||
const convex = useConvex()
|
||||
const { push } = useAppNavigation()
|
||||
const colors = useThemeColors()
|
||||
const ownedPlaylists = useQuery(api.playlists.listOwnedPlaylists)
|
||||
const addSongs = useMutation(api.playlists.addSongsToPlaylist)
|
||||
const createPlaylist = useMutation(api.playlists.createPlaylist)
|
||||
|
||||
@@ -48,57 +60,117 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
|
||||
const [pendingSongIds, setPendingSongIds] = useState<Id<"songs">[]>([])
|
||||
const [newPlaylistName, setNewPlaylistName] = useState("")
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [addingToPlaylistId, setAddingToPlaylistId] =
|
||||
useState<Id<"playlists"> | null>(null)
|
||||
const selectionRequestIdRef = useRef(0)
|
||||
const ownedPlaylists = useQuery(
|
||||
api.playlists.listOwnedPlaylists,
|
||||
open ? {} : "skip"
|
||||
)
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
selectionRequestIdRef.current += 1
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
const openAddToPlaylist = useCallback((songIds: Id<"songs">[]) => {
|
||||
selectionRequestIdRef.current += 1
|
||||
setPendingSongIds(songIds)
|
||||
setOpen(true)
|
||||
}, [])
|
||||
|
||||
const closeAddToPlaylist = useCallback(() => {
|
||||
selectionRequestIdRef.current += 1
|
||||
setOpen(false)
|
||||
setAddingToPlaylistId(null)
|
||||
setPendingSongIds([])
|
||||
}, [])
|
||||
|
||||
const openAddAlbumToPlaylist = useCallback(
|
||||
async (albumId: Id<"albums">) => {
|
||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
||||
albumId,
|
||||
})
|
||||
openAddToPlaylist(songIds)
|
||||
const requestId = ++selectionRequestIdRef.current
|
||||
try {
|
||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
||||
albumId,
|
||||
})
|
||||
if (selectionRequestIdRef.current !== requestId) return
|
||||
setPendingSongIds(songIds)
|
||||
setOpen(true)
|
||||
} catch (error) {
|
||||
if (selectionRequestIdRef.current !== requestId) return
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to load album"
|
||||
)
|
||||
}
|
||||
},
|
||||
[convex, openAddToPlaylist]
|
||||
[convex]
|
||||
)
|
||||
|
||||
const openAddPlaylistToPlaylist = useCallback(
|
||||
async (playlistId: Id<"playlists">) => {
|
||||
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
||||
playlistId,
|
||||
})
|
||||
openAddToPlaylist(songIds)
|
||||
const requestId = ++selectionRequestIdRef.current
|
||||
try {
|
||||
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
||||
playlistId,
|
||||
})
|
||||
if (selectionRequestIdRef.current !== requestId) return
|
||||
setPendingSongIds(songIds)
|
||||
setOpen(true)
|
||||
} catch (error) {
|
||||
if (selectionRequestIdRef.current !== requestId) return
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to load playlist"
|
||||
)
|
||||
}
|
||||
},
|
||||
[convex, openAddToPlaylist]
|
||||
[convex]
|
||||
)
|
||||
|
||||
const openAddArtistToPlaylist = useCallback(
|
||||
async (artistId: Id<"artists">) => {
|
||||
const songIds = await convex.query(
|
||||
api.playlists.getOrderedArtistSongIds,
|
||||
{ artistId }
|
||||
)
|
||||
openAddToPlaylist(songIds)
|
||||
const requestId = ++selectionRequestIdRef.current
|
||||
try {
|
||||
const songIds = await convex.query(
|
||||
api.playlists.getOrderedArtistSongIds,
|
||||
{ artistId }
|
||||
)
|
||||
if (selectionRequestIdRef.current !== requestId) return
|
||||
setPendingSongIds(songIds)
|
||||
setOpen(true)
|
||||
} catch (error) {
|
||||
if (selectionRequestIdRef.current !== requestId) return
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to load artist"
|
||||
)
|
||||
}
|
||||
},
|
||||
[convex, openAddToPlaylist]
|
||||
[convex]
|
||||
)
|
||||
|
||||
const openCreatePlaylist = useCallback(() => {
|
||||
selectionRequestIdRef.current += 1
|
||||
setPendingSongIds([])
|
||||
setNewPlaylistName("")
|
||||
setCreateOpen(true)
|
||||
}, [])
|
||||
|
||||
const handleAddToPlaylist = useCallback(
|
||||
async (playlistId: Id<"playlists">, title: string, existing: Id<"songs">[]) => {
|
||||
async (
|
||||
playlistId: Id<"playlists">,
|
||||
title: string,
|
||||
existing: Id<"songs">[]
|
||||
) => {
|
||||
if (addingToPlaylistId) return
|
||||
const existingSet = new Set(existing)
|
||||
const toAdd = pendingSongIds.filter((id) => !existingSet.has(id))
|
||||
if (toAdd.length === 0) {
|
||||
showSuccess(`All selected songs are already in ${title}`)
|
||||
setOpen(false)
|
||||
closeAddToPlaylist()
|
||||
return
|
||||
}
|
||||
setAddingToPlaylistId(playlistId)
|
||||
try {
|
||||
await addSongs({ playlistId, songIds: toAdd })
|
||||
showSuccess(
|
||||
@@ -106,12 +178,16 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
|
||||
? `Added ${toAdd.length} songs to ${title}`
|
||||
: `Added to ${title}`
|
||||
)
|
||||
setOpen(false)
|
||||
closeAddToPlaylist()
|
||||
} catch (error) {
|
||||
showError(error instanceof Error ? error.message : "Failed to add to playlist")
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to add to playlist"
|
||||
)
|
||||
} finally {
|
||||
setAddingToPlaylistId(null)
|
||||
}
|
||||
},
|
||||
[addSongs, pendingSongIds]
|
||||
[addSongs, addingToPlaylistId, closeAddToPlaylist, pendingSongIds]
|
||||
)
|
||||
|
||||
const handleCreatePlaylist = useCallback(async () => {
|
||||
@@ -119,20 +195,28 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
|
||||
if (!name) return
|
||||
setSubmitting(true)
|
||||
try {
|
||||
const playlistId = await createPlaylist({ name })
|
||||
if (pendingSongIds.length > 0) {
|
||||
await addSongs({ playlistId, songIds: pendingSongIds })
|
||||
}
|
||||
const playlistId = await createPlaylist({
|
||||
name,
|
||||
songIds: pendingSongIds,
|
||||
})
|
||||
showSuccess("Playlist created")
|
||||
setCreateOpen(false)
|
||||
setOpen(false)
|
||||
closeAddToPlaylist()
|
||||
push(`/playlist/${playlistId}`)
|
||||
} catch (error) {
|
||||
showError(error instanceof Error ? error.message : "Failed to create playlist")
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to create playlist"
|
||||
)
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}, [newPlaylistName, createPlaylist, pendingSongIds, addSongs, push])
|
||||
}, [
|
||||
closeAddToPlaylist,
|
||||
createPlaylist,
|
||||
newPlaylistName,
|
||||
pendingSongIds,
|
||||
push,
|
||||
])
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
@@ -155,38 +239,80 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
|
||||
<AddToPlaylistContext.Provider value={value}>
|
||||
{children}
|
||||
|
||||
<Modal visible={open} animationType="slide" transparent onRequestClose={() => setOpen(false)}>
|
||||
<Pressable style={styles.overlay} onPress={() => setOpen(false)}>
|
||||
<Modal
|
||||
visible={open}
|
||||
animationType="slide"
|
||||
transparent
|
||||
onRequestClose={closeAddToPlaylist}
|
||||
>
|
||||
<Pressable style={styles.overlay} onPress={closeAddToPlaylist}>
|
||||
<Pressable
|
||||
style={[styles.sheet, { backgroundColor: colors.card, borderColor: colors.border }]}
|
||||
style={[
|
||||
styles.sheet,
|
||||
{ backgroundColor: colors.card, borderColor: colors.border },
|
||||
]}
|
||||
onPress={(event) => event.stopPropagation()}
|
||||
>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>Add to Playlist</Text>
|
||||
<ScrollView style={styles.list}>
|
||||
{ownedPlaylists?.map((playlist: OwnedPlaylistForAdd) => (
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>
|
||||
Add to Playlist
|
||||
</Text>
|
||||
<FlatList
|
||||
style={styles.list}
|
||||
data={ownedPlaylists ?? []}
|
||||
keyExtractor={(playlist) => playlist.id}
|
||||
renderItem={({
|
||||
item: playlist,
|
||||
}: {
|
||||
item: OwnedPlaylistForAdd
|
||||
}) => (
|
||||
<Pressable
|
||||
key={playlist.id}
|
||||
style={styles.row}
|
||||
disabled={addingToPlaylistId !== null}
|
||||
onPress={() =>
|
||||
void handleAddToPlaylist(playlist.id, playlist.title, playlist.songIds)
|
||||
void handleAddToPlaylist(
|
||||
playlist.id,
|
||||
playlist.title,
|
||||
playlist.songIds
|
||||
)
|
||||
}
|
||||
>
|
||||
<Text style={{ color: colors.foreground }}>{playlist.title}</Text>
|
||||
<Text style={{ color: colors.foreground }}>
|
||||
{playlist.title}
|
||||
</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</ScrollView>
|
||||
<Button title="New Playlist" variant="secondary" onPress={() => { setOpen(false); openCreatePlaylist() }} />
|
||||
)}
|
||||
/>
|
||||
<Button
|
||||
title="New Playlist"
|
||||
variant="secondary"
|
||||
onPress={() => {
|
||||
selectionRequestIdRef.current += 1
|
||||
setOpen(false)
|
||||
setNewPlaylistName("")
|
||||
setCreateOpen(true)
|
||||
}}
|
||||
/>
|
||||
</Pressable>
|
||||
</Pressable>
|
||||
</Modal>
|
||||
|
||||
<Modal visible={createOpen} animationType="fade" transparent onRequestClose={() => setCreateOpen(false)}>
|
||||
<Modal
|
||||
visible={createOpen}
|
||||
animationType="fade"
|
||||
transparent
|
||||
onRequestClose={() => setCreateOpen(false)}
|
||||
>
|
||||
<Pressable style={styles.overlay} onPress={() => setCreateOpen(false)}>
|
||||
<Pressable
|
||||
style={[styles.createSheet, { backgroundColor: colors.card, borderColor: colors.border }]}
|
||||
style={[
|
||||
styles.createSheet,
|
||||
{ backgroundColor: colors.card, borderColor: colors.border },
|
||||
]}
|
||||
onPress={(event) => event.stopPropagation()}
|
||||
>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>New Playlist</Text>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>
|
||||
New Playlist
|
||||
</Text>
|
||||
<Input
|
||||
value={newPlaylistName}
|
||||
onChangeText={setNewPlaylistName}
|
||||
@@ -194,7 +320,11 @@ export function AddToPlaylistProvider({ children }: { children: ReactNode }) {
|
||||
autoFocus
|
||||
/>
|
||||
<View style={styles.createActions}>
|
||||
<Button title="Cancel" variant="ghost" onPress={() => setCreateOpen(false)} />
|
||||
<Button
|
||||
title="Cancel"
|
||||
variant="ghost"
|
||||
onPress={() => setCreateOpen(false)}
|
||||
/>
|
||||
<Button
|
||||
title="Create"
|
||||
loading={submitting}
|
||||
|
||||
@@ -18,6 +18,7 @@ type FavoritesContextValue = {
|
||||
toggleSongFavorite: (songId: Id<"songs">) => Promise<void>
|
||||
toggleAlbumFavorite: (albumId: Id<"albums">) => Promise<void>
|
||||
toggleArtistFavorite: (artistId: Id<"artists">) => Promise<void>
|
||||
favoriteSongs: (songIds: Id<"songs">[]) => Promise<void>
|
||||
}
|
||||
|
||||
const FavoritesContext = createContext<FavoritesContextValue | null>(null)
|
||||
@@ -32,12 +33,102 @@ export function useFavorites() {
|
||||
|
||||
export function FavoritesProvider({ children }: { children: ReactNode }) {
|
||||
const favorites = useQuery(api.favorites.getUserFavorites)
|
||||
const favoriteSong = useMutation(api.favorites.favoriteSong)
|
||||
const unfavoriteSong = useMutation(api.favorites.unfavoriteSong)
|
||||
const favoriteAlbum = useMutation(api.favorites.favoriteAlbum)
|
||||
const unfavoriteAlbum = useMutation(api.favorites.unfavoriteAlbum)
|
||||
const favoriteArtist = useMutation(api.favorites.favoriteArtist)
|
||||
const unfavoriteArtist = useMutation(api.favorites.unfavoriteArtist)
|
||||
const favoriteSong = useMutation(
|
||||
api.favorites.favoriteSong
|
||||
).withOptimisticUpdate((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],
|
||||
}
|
||||
)
|
||||
})
|
||||
const unfavoriteSong = useMutation(
|
||||
api.favorites.unfavoriteSong
|
||||
).withOptimisticUpdate((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),
|
||||
}
|
||||
)
|
||||
})
|
||||
const favoriteAlbum = useMutation(
|
||||
api.favorites.favoriteAlbum
|
||||
).withOptimisticUpdate((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],
|
||||
}
|
||||
)
|
||||
})
|
||||
const unfavoriteAlbum = useMutation(
|
||||
api.favorites.unfavoriteAlbum
|
||||
).withOptimisticUpdate((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),
|
||||
}
|
||||
)
|
||||
})
|
||||
const favoriteArtist = useMutation(
|
||||
api.favorites.favoriteArtist
|
||||
).withOptimisticUpdate((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],
|
||||
}
|
||||
)
|
||||
})
|
||||
const unfavoriteArtist = useMutation(
|
||||
api.favorites.unfavoriteArtist
|
||||
).withOptimisticUpdate((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
|
||||
),
|
||||
}
|
||||
)
|
||||
})
|
||||
const favoriteSongsMutation = useMutation(
|
||||
api.favorites.favoriteSongs
|
||||
).withOptimisticUpdate((store, { songIds }) => {
|
||||
const current = store.getQuery(api.favorites.getUserFavorites, {})
|
||||
if (!current) return
|
||||
store.setQuery(api.favorites.getUserFavorites, {}, {
|
||||
...current,
|
||||
favoriteSongs: [...new Set([...current.favoriteSongs, ...songIds])],
|
||||
})
|
||||
})
|
||||
|
||||
const songIds = useMemo(
|
||||
() => new Set(favorites?.favoriteSongs.map(String) ?? []),
|
||||
@@ -63,7 +154,9 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
|
||||
showSuccess("Added to favorites")
|
||||
}
|
||||
} catch (error) {
|
||||
showError(error instanceof Error ? error.message : "Failed to update favorites")
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to update favorites"
|
||||
)
|
||||
}
|
||||
},
|
||||
[songIds, favoriteSong, unfavoriteSong]
|
||||
@@ -80,7 +173,9 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
|
||||
showSuccess("Added to favorites")
|
||||
}
|
||||
} catch (error) {
|
||||
showError(error instanceof Error ? error.message : "Failed to update favorites")
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to update favorites"
|
||||
)
|
||||
}
|
||||
},
|
||||
[albumIds, favoriteAlbum, unfavoriteAlbum]
|
||||
@@ -97,12 +192,34 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
|
||||
showSuccess("Added to favorites")
|
||||
}
|
||||
} catch (error) {
|
||||
showError(error instanceof Error ? error.message : "Failed to update favorites")
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to update favorites"
|
||||
)
|
||||
}
|
||||
},
|
||||
[artistIds, favoriteArtist, unfavoriteArtist]
|
||||
)
|
||||
|
||||
const favoriteSongs = useCallback(
|
||||
async (ids: Id<"songs">[]) => {
|
||||
const unique = [...new Set(ids)]
|
||||
if (unique.length === 0) return
|
||||
try {
|
||||
await favoriteSongsMutation({ songIds: unique })
|
||||
showSuccess(
|
||||
unique.length > 1
|
||||
? `Favorited ${unique.length} songs`
|
||||
: "Added to favorites"
|
||||
)
|
||||
} catch (error) {
|
||||
showError(
|
||||
error instanceof Error ? error.message : "Failed to update favorites"
|
||||
)
|
||||
}
|
||||
},
|
||||
[favoriteSongsMutation]
|
||||
)
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
isSongFavorite: (songId: string) => songIds.has(songId),
|
||||
@@ -111,8 +228,17 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
|
||||
toggleSongFavorite,
|
||||
toggleAlbumFavorite,
|
||||
toggleArtistFavorite,
|
||||
favoriteSongs,
|
||||
}),
|
||||
[songIds, albumIds, artistIds, toggleSongFavorite, toggleAlbumFavorite, toggleArtistFavorite]
|
||||
[
|
||||
songIds,
|
||||
albumIds,
|
||||
artistIds,
|
||||
toggleSongFavorite,
|
||||
toggleAlbumFavorite,
|
||||
toggleArtistFavorite,
|
||||
favoriteSongs,
|
||||
]
|
||||
)
|
||||
|
||||
return (
|
||||
|
||||
+386
-134
@@ -98,11 +98,36 @@ type PlaybackContextValue = {
|
||||
|
||||
type PlaybackActionsValue = Pick<
|
||||
PlaybackContextValue,
|
||||
"addToQueueNext" | "addToQueueLast" | "playShuffled"
|
||||
| "setIsPlaying"
|
||||
| "playInOrder"
|
||||
| "playShuffled"
|
||||
| "addToQueueNext"
|
||||
| "addToQueueLast"
|
||||
| "playFromSong"
|
||||
| "playFromLibrarySong"
|
||||
| "playAlbum"
|
||||
| "playAlbumShuffled"
|
||||
| "playArtist"
|
||||
| "playArtistShuffled"
|
||||
| "playPlaylist"
|
||||
| "playPlaylistShuffled"
|
||||
| "toggleShuffle"
|
||||
| "cycleRepeat"
|
||||
| "clearQueue"
|
||||
| "reorderQueue"
|
||||
| "skipToQueueIndex"
|
||||
| "skipNext"
|
||||
| "skipPrevious"
|
||||
>
|
||||
|
||||
type PlaybackQueueValue = Pick<
|
||||
PlaybackContextValue,
|
||||
"queueSongIds" | "queueHistorySongIds" | "currentSong" | "isPlaying"
|
||||
>
|
||||
|
||||
const PlaybackContext = createContext<PlaybackContextValue | null>(null)
|
||||
const PlaybackActionsContext = createContext<PlaybackActionsValue | null>(null)
|
||||
const PlaybackQueueContext = createContext<PlaybackQueueValue | null>(null)
|
||||
|
||||
export function usePlayback() {
|
||||
const context = useContext(PlaybackContext)
|
||||
@@ -120,6 +145,14 @@ export function usePlaybackActions() {
|
||||
return context
|
||||
}
|
||||
|
||||
export function usePlaybackQueue() {
|
||||
const context = useContext(PlaybackQueueContext)
|
||||
if (!context) {
|
||||
throw new Error("usePlaybackQueue must be used within PlaybackProvider")
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
const convex = useConvex()
|
||||
const { config } = useServerConfig()
|
||||
@@ -146,6 +179,11 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
const loadRequestIdRef = useRef(0)
|
||||
const handlingEndRef = useRef(false)
|
||||
const volumeRef = useRef(DEFAULT_VOLUME)
|
||||
const volumeChangedRef = useRef(false)
|
||||
const volumeSaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const ignoreTrackChangeTimerRef = useRef<ReturnType<
|
||||
typeof setTimeout
|
||||
> | null>(null)
|
||||
|
||||
const [isPlaying, setIsPlayingState] = useState(false)
|
||||
const [currentTime, setCurrentTime] = useState(0)
|
||||
@@ -163,8 +201,42 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
const playFromLibrarySongMutation = useMutation(
|
||||
api.playback.playFromLibrarySong
|
||||
)
|
||||
const toggleShuffleMutation = useMutation(api.playback.toggleShuffle)
|
||||
const cycleRepeatMutation = useMutation(api.playback.cycleRepeat)
|
||||
const playAlbumMutation = useMutation(api.playback.playAlbum)
|
||||
const playAlbumShuffledMutation = useMutation(api.playback.playAlbumShuffled)
|
||||
const playArtistMutation = useMutation(api.playback.playArtist)
|
||||
const playArtistShuffledMutation = useMutation(
|
||||
api.playback.playArtistShuffled
|
||||
)
|
||||
const playPlaylistMutation = useMutation(api.playback.playPlaylist)
|
||||
const playPlaylistShuffledMutation = useMutation(
|
||||
api.playback.playPlaylistShuffled
|
||||
)
|
||||
const toggleShuffleMutation = useMutation(
|
||||
api.playback.toggleShuffle
|
||||
).withOptimisticUpdate((store) => {
|
||||
const current = store.getQuery(api.playback.getPlaybackState, {})
|
||||
if (!current) return
|
||||
store.setQuery(api.playback.getPlaybackState, {}, {
|
||||
...current,
|
||||
shuffleEnabled: !current.shuffleEnabled,
|
||||
})
|
||||
})
|
||||
const cycleRepeatMutation = useMutation(
|
||||
api.playback.cycleRepeat
|
||||
).withOptimisticUpdate((store) => {
|
||||
const current = store.getQuery(api.playback.getPlaybackState, {})
|
||||
if (!current) return
|
||||
const next =
|
||||
current.repeatEnabled === "none"
|
||||
? "once"
|
||||
: current.repeatEnabled === "once"
|
||||
? "always"
|
||||
: "none"
|
||||
store.setQuery(api.playback.getPlaybackState, {}, {
|
||||
...current,
|
||||
repeatEnabled: next,
|
||||
})
|
||||
})
|
||||
const clearQueueMutation = useMutation(api.playback.clearQueue)
|
||||
const reorderQueueMutation = useMutation(api.playback.reorderQueue)
|
||||
const skipToQueueIndexMutation = useMutation(api.playback.skipToQueueIndex)
|
||||
@@ -179,6 +251,32 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
const queueLength = playback?.queueSongIds.length ?? 0
|
||||
const queueSongIds = playback?.queueSongIds ?? []
|
||||
const queueHistorySongIds = playback?.queueHistorySongIds ?? []
|
||||
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 ?? "",
|
||||
currentSong.durationSeconds,
|
||||
])
|
||||
: ""
|
||||
const userPlaybackKey = user
|
||||
? JSON.stringify([
|
||||
user._id,
|
||||
user.playbackQuality,
|
||||
user.preferAtmos ?? false,
|
||||
])
|
||||
: ""
|
||||
|
||||
useEffect(() => {
|
||||
currentSongIdRef.current = currentSong?.id ?? null
|
||||
@@ -215,7 +313,21 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
skipToQueueIndexMutationRef.current = skipToQueueIndexMutation
|
||||
}, [skipToQueueIndexMutation])
|
||||
|
||||
const scheduleTrackChangeHandling = useCallback(() => {
|
||||
if (ignoreTrackChangeTimerRef.current) {
|
||||
clearTimeout(ignoreTrackChangeTimerRef.current)
|
||||
}
|
||||
ignoreTrackChangeTimerRef.current = setTimeout(() => {
|
||||
ignoreTrackChangeTimerRef.current = null
|
||||
ignoreTrackChangeRef.current = false
|
||||
}, 150)
|
||||
}, [])
|
||||
|
||||
const destroyPlaylist = useCallback(() => {
|
||||
if (ignoreTrackChangeTimerRef.current) {
|
||||
clearTimeout(ignoreTrackChangeTimerRef.current)
|
||||
ignoreTrackChangeTimerRef.current = null
|
||||
}
|
||||
statusSubscriptionRef.current?.remove()
|
||||
statusSubscriptionRef.current = null
|
||||
trackChangedSubscriptionRef.current?.remove()
|
||||
@@ -364,31 +476,53 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
handleTrackChanged
|
||||
)
|
||||
playlistRef.current = playlist
|
||||
setTimeout(() => {
|
||||
ignoreTrackChangeRef.current = false
|
||||
}, 150)
|
||||
scheduleTrackChangeHandling()
|
||||
return playlist
|
||||
},
|
||||
[handlePlaylistStatusUpdate, handleTrackChanged]
|
||||
[
|
||||
handlePlaylistStatusUpdate,
|
||||
handleTrackChanged,
|
||||
scheduleTrackChangeHandling,
|
||||
]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
void setAudioModeAsync({
|
||||
playsInSilentMode: true,
|
||||
shouldPlayInBackground: true,
|
||||
interruptionMode: "doNotMix",
|
||||
})
|
||||
|
||||
void AsyncStorage.getItem(VOLUME_STORAGE_KEY).then((stored) => {
|
||||
if (stored) {
|
||||
const parsed = Number(stored)
|
||||
if (Number.isFinite(parsed)) {
|
||||
setVolumeState(Math.min(1, Math.max(0, parsed)))
|
||||
}
|
||||
}).catch(() => {
|
||||
if (!cancelled) {
|
||||
showError("Audio playback could not be initialized.")
|
||||
}
|
||||
})
|
||||
|
||||
void AsyncStorage.getItem(VOLUME_STORAGE_KEY)
|
||||
.then((stored) => {
|
||||
if (!cancelled && !volumeChangedRef.current && stored) {
|
||||
const parsed = Number(stored)
|
||||
if (Number.isFinite(parsed)) {
|
||||
const restoredVolume = Math.min(1, Math.max(0, parsed))
|
||||
volumeRef.current = restoredVolume
|
||||
setVolumeState(restoredVolume)
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(() => {})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
if (volumeSaveTimerRef.current) {
|
||||
clearTimeout(volumeSaveTimerRef.current)
|
||||
volumeSaveTimerRef.current = null
|
||||
}
|
||||
if (volumeChangedRef.current) {
|
||||
void AsyncStorage.setItem(
|
||||
VOLUME_STORAGE_KEY,
|
||||
String(volumeRef.current)
|
||||
).catch(() => {})
|
||||
}
|
||||
destroyPlaylist()
|
||||
}
|
||||
}, [destroyPlaylist])
|
||||
@@ -421,8 +555,18 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
const setVolume = useCallback((nextVolume: number) => {
|
||||
const clamped = Math.min(1, Math.max(0, nextVolume))
|
||||
volumeChangedRef.current = true
|
||||
volumeRef.current = clamped
|
||||
setVolumeState(clamped)
|
||||
void AsyncStorage.setItem(VOLUME_STORAGE_KEY, String(clamped))
|
||||
if (volumeSaveTimerRef.current) {
|
||||
clearTimeout(volumeSaveTimerRef.current)
|
||||
}
|
||||
volumeSaveTimerRef.current = setTimeout(() => {
|
||||
volumeSaveTimerRef.current = null
|
||||
void AsyncStorage.setItem(VOLUME_STORAGE_KEY, String(clamped)).catch(
|
||||
() => {}
|
||||
)
|
||||
}, 250)
|
||||
if (playlistRef.current) {
|
||||
playlistRef.current.volume = clamped
|
||||
}
|
||||
@@ -443,14 +587,28 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
const saveProgress = useCallback(
|
||||
(seconds: number) => {
|
||||
const songId = currentSongIdRef.current
|
||||
if (!songId) return
|
||||
const progressSeconds = Math.max(0, Math.floor(seconds))
|
||||
if (progressSeconds === lastSavedProgressRef.current) return
|
||||
lastSavedProgressRef.current = progressSeconds
|
||||
void updateSongProgressMutation({ progressSeconds })
|
||||
void updateSongProgressMutation({
|
||||
songId,
|
||||
progressSeconds,
|
||||
}).catch(() => {})
|
||||
},
|
||||
[updateSongProgressMutation]
|
||||
)
|
||||
|
||||
const handlePlaybackLoadFailure = useCallback(() => {
|
||||
autoPlayNextRef.current = false
|
||||
isPlayingRef.current = false
|
||||
destroyPlaylist()
|
||||
setIsPlayingState(false)
|
||||
showError("Could not play this track. The queue has been cleared.")
|
||||
void clearQueueMutation().catch(() => {})
|
||||
}, [clearQueueMutation, destroyPlaylist])
|
||||
|
||||
useEffect(() => {
|
||||
if (!currentSong) {
|
||||
progressRestoredForSongRef.current = null
|
||||
@@ -471,7 +629,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
return
|
||||
}
|
||||
setProgressToRestore(playback?.currentSongProgress ?? 0)
|
||||
}, [currentSong?.id, currentSong, destroyPlaylist, playback])
|
||||
}, [currentSong?.id, currentSong?.durationSeconds, destroyPlaylist])
|
||||
|
||||
useEffect(() => {
|
||||
if (progressToRestore === null || progressToRestore <= 0) return
|
||||
@@ -539,9 +697,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
playlist.loop = repeatToPlaylistLoop(repeatEnabled)
|
||||
playlist.volume = volumeRef.current
|
||||
updatePlaylistLockScreenMetadata(playlist, metadata)
|
||||
setTimeout(() => {
|
||||
ignoreTrackChangeRef.current = false
|
||||
}, 150)
|
||||
scheduleTrackChangeHandling()
|
||||
if (shouldPlay) {
|
||||
isPlayingRef.current = true
|
||||
setIsPlayingState(true)
|
||||
@@ -559,9 +715,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
for (let i = 0; i < windowSongIds.length; i++) {
|
||||
const song = songs[i]
|
||||
if (!song) {
|
||||
showError("Could not play this track. The queue has been cleared.")
|
||||
void clearQueueMutation()
|
||||
setIsPlayingState(false)
|
||||
handlePlaybackLoadFailure()
|
||||
return
|
||||
}
|
||||
const plan = playbackStreamPlan(
|
||||
@@ -597,9 +751,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
playlist.skipTo(currentIndex)
|
||||
}
|
||||
activatePlaylistLockScreen(playlist, metadata)
|
||||
setTimeout(() => {
|
||||
ignoreTrackChangeRef.current = false
|
||||
}, 150)
|
||||
scheduleTrackChangeHandling()
|
||||
|
||||
if (shouldPlay) {
|
||||
isPlayingRef.current = true
|
||||
@@ -613,21 +765,27 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
|
||||
void syncPlaylist().catch(() => {
|
||||
showError("Could not play this track. The queue has been cleared.")
|
||||
void clearQueueMutation()
|
||||
setIsPlayingState(false)
|
||||
if (!isCurrentLoad()) return
|
||||
handlePlaybackLoadFailure()
|
||||
})
|
||||
|
||||
return () => {
|
||||
if (loadRequestIdRef.current === loadRequestId) {
|
||||
loadRequestIdRef.current += 1
|
||||
}
|
||||
}
|
||||
}, [
|
||||
clearQueueMutation,
|
||||
config,
|
||||
convex,
|
||||
currentSong,
|
||||
currentSongSyncKey,
|
||||
destroyPlaylist,
|
||||
ensurePlaylist,
|
||||
queueHistorySongIds,
|
||||
queueSongIds,
|
||||
handlePlaybackLoadFailure,
|
||||
historySyncKey,
|
||||
queueSyncKey,
|
||||
repeatEnabled,
|
||||
user,
|
||||
scheduleTrackChangeHandling,
|
||||
userPlaybackKey,
|
||||
])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -641,26 +799,39 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
const playInOrder = useCallback(
|
||||
async (songIds: Id<"songs">[]) => {
|
||||
if (songIds.length === 0) return
|
||||
const restartsCurrentSong =
|
||||
currentSongIdRef.current === songIds[0]
|
||||
await playInOrderMutation({ songIds })
|
||||
if (restartsCurrentSong) {
|
||||
await seekTo(0)
|
||||
}
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[playInOrderMutation, setIsPlaying]
|
||||
[playInOrderMutation, seekTo, setIsPlaying]
|
||||
)
|
||||
|
||||
const playShuffled = useCallback(
|
||||
async (songIds: Id<"songs">[]) => {
|
||||
if (songIds.length === 0) return
|
||||
const restartsCurrentSong =
|
||||
songIds.length === 1 && currentSongIdRef.current === songIds[0]
|
||||
await playShuffledMutation({ songIds })
|
||||
if (restartsCurrentSong) {
|
||||
await seekTo(0)
|
||||
}
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[playShuffledMutation, setIsPlaying]
|
||||
[playShuffledMutation, seekTo, setIsPlaying]
|
||||
)
|
||||
|
||||
const addToQueueNext = useCallback(
|
||||
async (songIds: Id<"songs">[]) => {
|
||||
if (songIds.length === 0) return
|
||||
const shouldStartPlayback = currentSongIdRef.current === null
|
||||
await addToQueueNextMutation({ songIds })
|
||||
setIsPlaying(true)
|
||||
if (shouldStartPlayback) {
|
||||
setIsPlaying(true)
|
||||
}
|
||||
},
|
||||
[addToQueueNextMutation, setIsPlaying]
|
||||
)
|
||||
@@ -668,18 +839,25 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
const addToQueueLast = useCallback(
|
||||
async (songIds: Id<"songs">[]) => {
|
||||
if (songIds.length === 0) return
|
||||
const shouldStartPlayback = currentSongIdRef.current === null
|
||||
await addToQueueLastMutation({ songIds })
|
||||
setIsPlaying(true)
|
||||
if (shouldStartPlayback) {
|
||||
setIsPlaying(true)
|
||||
}
|
||||
},
|
||||
[addToQueueLastMutation, setIsPlaying]
|
||||
)
|
||||
|
||||
const playFromSong = useCallback(
|
||||
async (songId: Id<"songs">, songIds: Id<"songs">[]) => {
|
||||
const restartsCurrentSong = currentSongIdRef.current === songId
|
||||
await playFromSongMutation({ songId, songIds })
|
||||
if (restartsCurrentSong) {
|
||||
await seekTo(0)
|
||||
}
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[playFromSongMutation, setIsPlaying]
|
||||
[playFromSongMutation, seekTo, setIsPlaying]
|
||||
)
|
||||
|
||||
const playFromLibrarySong = useCallback(
|
||||
@@ -690,83 +868,197 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
sortDirection: "asc" | "desc"
|
||||
}
|
||||
) => {
|
||||
const restartsCurrentSong = currentSongIdRef.current === songId
|
||||
await playFromLibrarySongMutation({ songId, ...sort })
|
||||
if (restartsCurrentSong) {
|
||||
await seekTo(0)
|
||||
}
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[playFromLibrarySongMutation, setIsPlaying]
|
||||
[playFromLibrarySongMutation, seekTo, setIsPlaying]
|
||||
)
|
||||
|
||||
const playAlbum = useCallback(
|
||||
async (albumId: Id<"albums">) => {
|
||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
||||
albumId,
|
||||
})
|
||||
await playInOrder(songIds)
|
||||
await playAlbumMutation({ albumId })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[convex, playInOrder]
|
||||
[playAlbumMutation, setIsPlaying]
|
||||
)
|
||||
|
||||
const playAlbumShuffled = useCallback(
|
||||
async (albumId: Id<"albums">) => {
|
||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
||||
albumId,
|
||||
})
|
||||
await playShuffled(songIds)
|
||||
await playAlbumShuffledMutation({ albumId })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[convex, playShuffled]
|
||||
[playAlbumShuffledMutation, setIsPlaying]
|
||||
)
|
||||
|
||||
const playArtist = useCallback(
|
||||
async (artistId: Id<"artists">) => {
|
||||
const songIds = await convex.query(
|
||||
api.playlists.getOrderedArtistSongIds,
|
||||
{ artistId }
|
||||
)
|
||||
await playInOrder(songIds)
|
||||
await playArtistMutation({ artistId })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[convex, playInOrder]
|
||||
[playArtistMutation, setIsPlaying]
|
||||
)
|
||||
|
||||
const playArtistShuffled = useCallback(
|
||||
async (artistId: Id<"artists">) => {
|
||||
const songIds = await convex.query(
|
||||
api.playlists.getOrderedArtistSongIds,
|
||||
{ artistId }
|
||||
)
|
||||
await playShuffled(songIds)
|
||||
await playArtistShuffledMutation({ artistId })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[convex, playShuffled]
|
||||
[playArtistShuffledMutation, setIsPlaying]
|
||||
)
|
||||
|
||||
const playPlaylist = useCallback(
|
||||
async (playlistId: Id<"playlists">) => {
|
||||
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
||||
playlistId,
|
||||
})
|
||||
await playInOrderMutation({ songIds, playlistId })
|
||||
await playPlaylistMutation({ playlistId })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[convex, playInOrderMutation, setIsPlaying]
|
||||
[playPlaylistMutation, setIsPlaying]
|
||||
)
|
||||
|
||||
const playPlaylistShuffled = useCallback(
|
||||
async (playlistId: Id<"playlists">) => {
|
||||
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
||||
playlistId,
|
||||
})
|
||||
await playShuffledMutation({ songIds, playlistId })
|
||||
await playPlaylistShuffledMutation({ playlistId })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[convex, playShuffledMutation, setIsPlaying]
|
||||
[playPlaylistShuffledMutation, setIsPlaying]
|
||||
)
|
||||
|
||||
const toggleShuffle = useCallback(async () => {
|
||||
await toggleShuffleMutation()
|
||||
}, [toggleShuffleMutation])
|
||||
|
||||
const cycleRepeat = useCallback(async () => {
|
||||
await cycleRepeatMutation()
|
||||
}, [cycleRepeatMutation])
|
||||
|
||||
const clearQueue = useCallback(async () => {
|
||||
await clearQueueMutation()
|
||||
setIsPlaying(false)
|
||||
}, [clearQueueMutation, setIsPlaying])
|
||||
|
||||
const reorderQueue = useCallback(
|
||||
async (songIds: Id<"songs">[]) => {
|
||||
await reorderQueueMutation({ songIds })
|
||||
},
|
||||
[reorderQueueMutation]
|
||||
)
|
||||
|
||||
const skipToQueueIndex = useCallback(
|
||||
async (index: number) => {
|
||||
if (index <= 0) return
|
||||
autoPlayNextRef.current = true
|
||||
try {
|
||||
await skipToQueueIndexMutation({ index })
|
||||
} catch (error) {
|
||||
autoPlayNextRef.current = false
|
||||
throw error
|
||||
}
|
||||
},
|
||||
[skipToQueueIndexMutation]
|
||||
)
|
||||
|
||||
const skipNext = useCallback(async () => {
|
||||
const isFinishingQueue =
|
||||
repeatEnabledRef.current === "none" && queueLengthRef.current <= 1
|
||||
if (isFinishingQueue) {
|
||||
setIsPlaying(false)
|
||||
await seekTo(0)
|
||||
await skipNextMutation()
|
||||
await seekTo(0)
|
||||
return
|
||||
}
|
||||
if (repeatEnabledRef.current === "once" || queueLengthRef.current <= 1) {
|
||||
await seekTo(0)
|
||||
await skipNextMutation()
|
||||
setIsPlaying(true)
|
||||
return
|
||||
}
|
||||
autoPlayNextRef.current = true
|
||||
try {
|
||||
await skipNextMutation()
|
||||
} catch (error) {
|
||||
autoPlayNextRef.current = false
|
||||
throw error
|
||||
}
|
||||
}, [seekTo, setIsPlaying, skipNextMutation])
|
||||
|
||||
const skipPrevious = useCallback(async () => {
|
||||
if (currentTimeRef.current > PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS) {
|
||||
await seekTo(0)
|
||||
return
|
||||
}
|
||||
if (historyLengthRef.current === 0) {
|
||||
await seekTo(0)
|
||||
await skipPreviousMutation()
|
||||
return
|
||||
}
|
||||
autoPlayNextRef.current = true
|
||||
try {
|
||||
await skipPreviousMutation()
|
||||
} catch (error) {
|
||||
autoPlayNextRef.current = false
|
||||
throw error
|
||||
}
|
||||
}, [seekTo, skipPreviousMutation])
|
||||
|
||||
const actionsValue = useMemo<PlaybackActionsValue>(
|
||||
() => ({
|
||||
setIsPlaying,
|
||||
playInOrder,
|
||||
playShuffled,
|
||||
addToQueueNext,
|
||||
addToQueueLast,
|
||||
playShuffled,
|
||||
playFromSong,
|
||||
playFromLibrarySong,
|
||||
playAlbum,
|
||||
playAlbumShuffled,
|
||||
playArtist,
|
||||
playArtistShuffled,
|
||||
playPlaylist,
|
||||
playPlaylistShuffled,
|
||||
toggleShuffle,
|
||||
cycleRepeat,
|
||||
clearQueue,
|
||||
reorderQueue,
|
||||
skipToQueueIndex,
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
}),
|
||||
[addToQueueNext, addToQueueLast, playShuffled]
|
||||
[
|
||||
addToQueueNext,
|
||||
addToQueueLast,
|
||||
clearQueue,
|
||||
cycleRepeat,
|
||||
playAlbum,
|
||||
playAlbumShuffled,
|
||||
playArtist,
|
||||
playArtistShuffled,
|
||||
playFromLibrarySong,
|
||||
playFromSong,
|
||||
playInOrder,
|
||||
playPlaylist,
|
||||
playPlaylistShuffled,
|
||||
playShuffled,
|
||||
reorderQueue,
|
||||
setIsPlaying,
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
skipToQueueIndex,
|
||||
toggleShuffle,
|
||||
]
|
||||
)
|
||||
|
||||
const queueValue = useMemo<PlaybackQueueValue>(
|
||||
() => ({
|
||||
queueSongIds,
|
||||
queueHistorySongIds,
|
||||
currentSong,
|
||||
isPlaying: Boolean(currentSong && isPlaying),
|
||||
}),
|
||||
[currentSong, isPlaying, queueHistorySongIds, queueSongIds]
|
||||
)
|
||||
|
||||
const value = useMemo<PlaybackContextValue>(
|
||||
@@ -795,62 +1087,20 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
playArtistShuffled,
|
||||
playPlaylist,
|
||||
playPlaylistShuffled,
|
||||
toggleShuffle: async () => {
|
||||
await toggleShuffleMutation()
|
||||
},
|
||||
cycleRepeat: async () => {
|
||||
await cycleRepeatMutation()
|
||||
},
|
||||
clearQueue: async () => {
|
||||
await clearQueueMutation()
|
||||
setIsPlaying(false)
|
||||
},
|
||||
reorderQueue: async (songIds) => {
|
||||
await reorderQueueMutation({ songIds })
|
||||
},
|
||||
skipToQueueIndex: async (index) => {
|
||||
if (index <= 0) return
|
||||
autoPlayNextRef.current = true
|
||||
await skipToQueueIndexMutation({ index })
|
||||
},
|
||||
skipNext: async () => {
|
||||
const isFinishingQueue = repeatEnabled === "none" && queueLength <= 1
|
||||
if (isFinishingQueue) {
|
||||
setIsPlaying(false)
|
||||
await seekTo(0)
|
||||
await skipNextMutation()
|
||||
await seekTo(0)
|
||||
return
|
||||
}
|
||||
if (repeatEnabled === "once" || queueLength <= 1) {
|
||||
await seekTo(0)
|
||||
await skipNextMutation()
|
||||
setIsPlaying(true)
|
||||
return
|
||||
}
|
||||
autoPlayNextRef.current = true
|
||||
await skipNextMutation()
|
||||
},
|
||||
skipPrevious: async () => {
|
||||
if (currentTime > PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS) {
|
||||
await seekTo(0)
|
||||
return
|
||||
}
|
||||
if (queueHistorySongIds.length === 0) {
|
||||
await seekTo(0)
|
||||
await skipPreviousMutation()
|
||||
return
|
||||
}
|
||||
autoPlayNextRef.current = true
|
||||
await skipPreviousMutation()
|
||||
},
|
||||
toggleShuffle,
|
||||
cycleRepeat,
|
||||
clearQueue,
|
||||
reorderQueue,
|
||||
skipToQueueIndex,
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
}),
|
||||
[
|
||||
addToQueueLast,
|
||||
addToQueueNext,
|
||||
currentSong,
|
||||
currentTime,
|
||||
cycleRepeatMutation,
|
||||
cycleRepeat,
|
||||
duration,
|
||||
isPlaying,
|
||||
playAlbum,
|
||||
@@ -867,25 +1117,27 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
queueHistorySongIds,
|
||||
queueLength,
|
||||
queueSongIds,
|
||||
reorderQueueMutation,
|
||||
reorderQueue,
|
||||
repeatEnabled,
|
||||
seekTo,
|
||||
setIsPlaying,
|
||||
setVolume,
|
||||
skipNextMutation,
|
||||
skipPreviousMutation,
|
||||
skipToQueueIndexMutation,
|
||||
toggleShuffleMutation,
|
||||
clearQueueMutation,
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
skipToQueueIndex,
|
||||
toggleShuffle,
|
||||
clearQueue,
|
||||
volume,
|
||||
]
|
||||
)
|
||||
|
||||
return (
|
||||
<PlaybackActionsContext.Provider value={actionsValue}>
|
||||
<PlaybackContext.Provider value={value}>
|
||||
{children}
|
||||
</PlaybackContext.Provider>
|
||||
<PlaybackQueueContext.Provider value={queueValue}>
|
||||
<PlaybackContext.Provider value={value}>
|
||||
{children}
|
||||
</PlaybackContext.Provider>
|
||||
</PlaybackQueueContext.Provider>
|
||||
</PlaybackActionsContext.Provider>
|
||||
)
|
||||
}
|
||||
@@ -9,7 +9,11 @@ import {
|
||||
} from "react"
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage"
|
||||
|
||||
import { secureGetItem, secureRemoveItem, secureSetItem } from "@/lib/auth-storage"
|
||||
import {
|
||||
secureGetItem,
|
||||
secureRemoveItem,
|
||||
secureSetItem,
|
||||
} from "@/lib/auth-storage"
|
||||
import {
|
||||
clearServerConfig,
|
||||
loadServerConfig,
|
||||
@@ -35,21 +39,26 @@ export function ServerConfigProvider({ children }: { children: ReactNode }) {
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
void (async () => {
|
||||
let loaded = await loadServerConfig(secureGetItem)
|
||||
if (!loaded) {
|
||||
const legacy = await AsyncStorage.getItem(LEGACY_SERVER_CONFIG_KEY)
|
||||
if (legacy) {
|
||||
try {
|
||||
const parsed = JSON.parse(legacy) as ServerConfig
|
||||
if (parsed.hostname && parsed.serverUrl && parsed.convexUrl) {
|
||||
await saveServerConfig(secureSetItem, parsed)
|
||||
await AsyncStorage.removeItem(LEGACY_SERVER_CONFIG_KEY)
|
||||
loaded = parsed
|
||||
let loaded: ServerConfig | null = null
|
||||
try {
|
||||
loaded = await loadServerConfig(secureGetItem)
|
||||
if (!loaded) {
|
||||
const legacy = await AsyncStorage.getItem(LEGACY_SERVER_CONFIG_KEY)
|
||||
if (legacy) {
|
||||
try {
|
||||
const parsed = JSON.parse(legacy) as ServerConfig
|
||||
if (parsed.hostname && parsed.serverUrl && parsed.convexUrl) {
|
||||
await saveServerConfig(secureSetItem, parsed)
|
||||
await AsyncStorage.removeItem(LEGACY_SERVER_CONFIG_KEY)
|
||||
loaded = parsed
|
||||
}
|
||||
} catch {
|
||||
// Ignore invalid or inaccessible legacy data.
|
||||
}
|
||||
} catch {
|
||||
// Ignore invalid legacy data.
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Storage failures should not leave startup blocked indefinitely.
|
||||
}
|
||||
if (!cancelled) {
|
||||
setConfig(loaded)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useConvex, useMutation } from "convex/react"
|
||||
import { useConvex } from "convex/react"
|
||||
import { useCallback } from "react"
|
||||
|
||||
import type { MediaAction } from "@/components/media-context-menu"
|
||||
@@ -6,7 +6,7 @@ import { useAddToPlaylist } from "@/contexts/add-to-playlist"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlaybackActions } from "@/contexts/playback"
|
||||
import { useAppNavigation } from "@/lib/app-navigation"
|
||||
import { showSuccess } from "@/lib/toast"
|
||||
import { showError, showSuccess } from "@/lib/toast"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type {
|
||||
@@ -18,39 +18,53 @@ import type {
|
||||
PlaylistSummary,
|
||||
} from "@otunes/convex/types"
|
||||
|
||||
async function runMediaAction(action: () => Promise<void>) {
|
||||
try {
|
||||
await action()
|
||||
} catch (error) {
|
||||
showError(error instanceof Error ? error.message : "Media action failed")
|
||||
}
|
||||
}
|
||||
|
||||
export function useMediaMenuActions() {
|
||||
const convex = useConvex()
|
||||
const { push } = useAppNavigation()
|
||||
const { openAddToPlaylist, openAddAlbumToPlaylist, openAddArtistToPlaylist, openAddPlaylistToPlaylist } =
|
||||
useAddToPlaylist()
|
||||
const {
|
||||
openAddToPlaylist,
|
||||
openAddAlbumToPlaylist,
|
||||
openAddArtistToPlaylist,
|
||||
openAddPlaylistToPlaylist,
|
||||
} = useAddToPlaylist()
|
||||
const {
|
||||
isAlbumFavorite,
|
||||
isArtistFavorite,
|
||||
toggleAlbumFavorite,
|
||||
toggleArtistFavorite,
|
||||
toggleSongFavorite,
|
||||
favoriteSongs,
|
||||
} = useFavorites()
|
||||
const { addToQueueNext, addToQueueLast, playShuffled } = usePlaybackActions()
|
||||
const favoriteSongs = useMutation(api.favorites.favoriteSongs)
|
||||
|
||||
const runQueueAction = useCallback(
|
||||
async (action: MediaAction, songIds: Id<"songs">[]) => {
|
||||
if (songIds.length === 0) return
|
||||
switch (action) {
|
||||
case "play-next":
|
||||
await addToQueueNext(songIds)
|
||||
showSuccess("Queued to play next")
|
||||
break
|
||||
case "play-last":
|
||||
await addToQueueLast(songIds)
|
||||
showSuccess("Queued to play last")
|
||||
break
|
||||
case "shuffle":
|
||||
await playShuffled(songIds)
|
||||
break
|
||||
default:
|
||||
break
|
||||
}
|
||||
await runMediaAction(async () => {
|
||||
switch (action) {
|
||||
case "play-next":
|
||||
await addToQueueNext(songIds)
|
||||
showSuccess("Queued to play next")
|
||||
break
|
||||
case "play-last":
|
||||
await addToQueueLast(songIds)
|
||||
showSuccess("Queued to play last")
|
||||
break
|
||||
case "shuffle":
|
||||
await playShuffled(songIds)
|
||||
break
|
||||
default:
|
||||
break
|
||||
}
|
||||
})
|
||||
},
|
||||
[addToQueueLast, addToQueueNext, playShuffled]
|
||||
)
|
||||
@@ -85,87 +99,85 @@ export function useMediaMenuActions() {
|
||||
|
||||
const handleAlbumAction = useCallback(
|
||||
async (album: BrowseAlbum, action: MediaAction) => {
|
||||
switch (action) {
|
||||
case "playlist":
|
||||
await openAddAlbumToPlaylist(album.id as Id<"albums">)
|
||||
break
|
||||
case "favorite":
|
||||
await toggleAlbumFavorite(album.id as Id<"albums">)
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle": {
|
||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
||||
albumId: album.id as Id<"albums">,
|
||||
})
|
||||
await runQueueAction(action, songIds)
|
||||
break
|
||||
await runMediaAction(async () => {
|
||||
switch (action) {
|
||||
case "playlist":
|
||||
await openAddAlbumToPlaylist(album.id as Id<"albums">)
|
||||
break
|
||||
case "favorite":
|
||||
await toggleAlbumFavorite(album.id as Id<"albums">)
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle": {
|
||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
||||
albumId: album.id as Id<"albums">,
|
||||
})
|
||||
await runQueueAction(action, songIds)
|
||||
break
|
||||
}
|
||||
case "go-artist":
|
||||
push(`/artist/${album.artist.id}`)
|
||||
break
|
||||
default:
|
||||
break
|
||||
}
|
||||
case "go-artist":
|
||||
push(`/artist/${album.artist.id}`)
|
||||
break
|
||||
default:
|
||||
break
|
||||
}
|
||||
})
|
||||
},
|
||||
[
|
||||
convex,
|
||||
openAddAlbumToPlaylist,
|
||||
push,
|
||||
runQueueAction,
|
||||
toggleAlbumFavorite,
|
||||
]
|
||||
[convex, openAddAlbumToPlaylist, push, runQueueAction, toggleAlbumFavorite]
|
||||
)
|
||||
|
||||
const handleArtistAction = useCallback(
|
||||
async (artist: BrowseArtist, action: MediaAction) => {
|
||||
switch (action) {
|
||||
case "playlist":
|
||||
await openAddArtistToPlaylist(artist.id as Id<"artists">)
|
||||
break
|
||||
case "favorite":
|
||||
await toggleArtistFavorite(artist.id as Id<"artists">)
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle": {
|
||||
const songIds = await convex.query(
|
||||
api.playlists.getOrderedArtistSongIds,
|
||||
{ artistId: artist.id as Id<"artists"> }
|
||||
)
|
||||
await runQueueAction(action, songIds)
|
||||
break
|
||||
await runMediaAction(async () => {
|
||||
switch (action) {
|
||||
case "playlist":
|
||||
await openAddArtistToPlaylist(artist.id as Id<"artists">)
|
||||
break
|
||||
case "favorite":
|
||||
await toggleArtistFavorite(artist.id as Id<"artists">)
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle": {
|
||||
const songIds = await convex.query(
|
||||
api.playlists.getOrderedArtistSongIds,
|
||||
{ artistId: artist.id as Id<"artists"> }
|
||||
)
|
||||
await runQueueAction(action, songIds)
|
||||
break
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
})
|
||||
},
|
||||
[
|
||||
convex,
|
||||
openAddArtistToPlaylist,
|
||||
runQueueAction,
|
||||
toggleArtistFavorite,
|
||||
]
|
||||
[convex, openAddArtistToPlaylist, runQueueAction, toggleArtistFavorite]
|
||||
)
|
||||
|
||||
const handlePlaylistAction = useCallback(
|
||||
async (playlist: PlaylistSummary, action: MediaAction) => {
|
||||
switch (action) {
|
||||
case "playlist":
|
||||
await openAddPlaylistToPlaylist(playlist.id as Id<"playlists">)
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle": {
|
||||
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
||||
playlistId: playlist.id as Id<"playlists">,
|
||||
})
|
||||
await runQueueAction(action, songIds)
|
||||
break
|
||||
await runMediaAction(async () => {
|
||||
switch (action) {
|
||||
case "playlist":
|
||||
await openAddPlaylistToPlaylist(playlist.id as Id<"playlists">)
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle": {
|
||||
const songIds = await convex.query(
|
||||
api.playlists.getPlaylistSongIds,
|
||||
{
|
||||
playlistId: playlist.id as Id<"playlists">,
|
||||
}
|
||||
)
|
||||
await runQueueAction(action, songIds)
|
||||
break
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
})
|
||||
},
|
||||
[convex, openAddPlaylistToPlaylist, runQueueAction]
|
||||
)
|
||||
@@ -219,24 +231,25 @@ export function useMediaMenuActions() {
|
||||
|
||||
const handlePlaylistDetailAction = useCallback(
|
||||
async (songIds: Id<"songs">[], action: MediaAction) => {
|
||||
switch (action) {
|
||||
case "favorite":
|
||||
if (songIds.length > 0) {
|
||||
await favoriteSongs({ songIds })
|
||||
showSuccess("Added to favorites")
|
||||
}
|
||||
break
|
||||
case "playlist":
|
||||
openAddToPlaylist(songIds)
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle":
|
||||
await runQueueAction(action, songIds)
|
||||
break
|
||||
default:
|
||||
break
|
||||
}
|
||||
await runMediaAction(async () => {
|
||||
switch (action) {
|
||||
case "favorite":
|
||||
if (songIds.length > 0) {
|
||||
await favoriteSongs(songIds)
|
||||
}
|
||||
break
|
||||
case "playlist":
|
||||
openAddToPlaylist(songIds)
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle":
|
||||
await runQueueAction(action, songIds)
|
||||
break
|
||||
default:
|
||||
break
|
||||
}
|
||||
})
|
||||
},
|
||||
[favoriteSongs, openAddToPlaylist, runQueueAction]
|
||||
)
|
||||
|
||||
@@ -4,21 +4,26 @@ import { api } from "@otunes/convex/_generated/api"
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { Metadata } from "next"
|
||||
import { cache } from "react"
|
||||
|
||||
interface PageProps {
|
||||
params: Promise<{ id: string }>
|
||||
searchParams: Promise<{ s?: string }>
|
||||
}
|
||||
|
||||
const fetchAlbumDetail = cache((id: Id<"albums">) =>
|
||||
fetchQuery(api.library.browseAlbumDetail, { id })
|
||||
)
|
||||
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
searchParams,
|
||||
}: PageProps): Promise<Metadata> {
|
||||
const { id } = await params
|
||||
const { s: songId } = await searchParams
|
||||
const album = await fetchQuery(api.library.browseAlbumDetail, {
|
||||
id: id as Id<"albums">,
|
||||
})
|
||||
const [{ s: songId }, album] = await Promise.all([
|
||||
searchParams,
|
||||
fetchAlbumDetail(id as Id<"albums">),
|
||||
])
|
||||
|
||||
const sharedTrack =
|
||||
album && songId
|
||||
@@ -44,10 +49,10 @@ export async function generateMetadata({
|
||||
|
||||
export default async function Page({ params, searchParams }: PageProps) {
|
||||
const { id } = await params
|
||||
const { s: highlightedSongId } = await searchParams
|
||||
const album = await fetchQuery(api.library.browseAlbumDetail, {
|
||||
id: id as Id<"albums">,
|
||||
})
|
||||
const [{ s: highlightedSongId }, album] = await Promise.all([
|
||||
searchParams,
|
||||
fetchAlbumDetail(id as Id<"albums">),
|
||||
])
|
||||
|
||||
if (album === undefined) {
|
||||
return (
|
||||
|
||||
@@ -4,18 +4,21 @@ import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { Metadata } from "next"
|
||||
import { cache } from "react"
|
||||
|
||||
interface PageProps {
|
||||
params: Promise<{ id: string }>
|
||||
}
|
||||
|
||||
const fetchArtistDetail = cache((id: Id<"artists">) =>
|
||||
fetchQuery(api.library.browseArtistDetail, { id })
|
||||
)
|
||||
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
}: PageProps): Promise<Metadata> {
|
||||
const { id } = await params
|
||||
const data = await fetchQuery(api.library.browseArtistDetail, {
|
||||
id: id as Id<"artists">,
|
||||
})
|
||||
const data = await fetchArtistDetail(id as Id<"artists">)
|
||||
|
||||
return {
|
||||
title: `${data ? `${data.artist.name}` : "oTunes"}`,
|
||||
@@ -35,9 +38,7 @@ export async function generateMetadata({
|
||||
|
||||
export default async function Page({ params }: PageProps) {
|
||||
const { id } = await params
|
||||
const data = await fetchQuery(api.library.browseArtistDetail, {
|
||||
id: id as Id<"artists">,
|
||||
})
|
||||
const data = await fetchArtistDetail(id as Id<"artists">)
|
||||
|
||||
if (data === undefined) {
|
||||
return (
|
||||
@@ -57,21 +58,5 @@ export default async function Page({ params }: PageProps) {
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<title>{`${data.artist.name}`}</title>
|
||||
<meta property="og:title" content={`${data.artist.name}`} />
|
||||
{/*<meta property="og:description" content={`${playlist.owner.name}`} />*/}
|
||||
<meta
|
||||
property="og:image"
|
||||
content={`/api/artist/${data.artist.id}/cover`}
|
||||
/>
|
||||
<ArtistView
|
||||
artist={data.artist}
|
||||
albums={data.albums}
|
||||
recentlyAdded={data.recentlyAdded}
|
||||
recentlyPlayed={data.recentlyPlayed}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
return <ArtistView artist={data.artist} albums={data.albums} />
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { AddToPlaylistProvider } from "@/components/add-to-playlist-provider"
|
||||
import { FavoritesProvider } from "@/components/favorites-provider"
|
||||
import { PlaybackProvider } from "@/components/playback-provider"
|
||||
import { PlayerBar } from "@/components/player-bar"
|
||||
import { QueuePanel } from "@/components/queue-panel"
|
||||
import { LazyQueuePanel } from "@/components/lazy-queue-panel"
|
||||
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
|
||||
import { AppSidebar } from "@/components/app-sidebar"
|
||||
|
||||
@@ -19,7 +19,7 @@ export default function AppLayout({
|
||||
<AppSidebar />
|
||||
<div className="flex min-h-svh min-w-0 flex-1">
|
||||
<SidebarInset className="min-w-0 flex-1">{children}</SidebarInset>
|
||||
<QueuePanel />
|
||||
<LazyQueuePanel />
|
||||
</div>
|
||||
<PlayerBar />
|
||||
</FavoritesProvider>
|
||||
|
||||
@@ -2,16 +2,19 @@ import { fetchQuery } from "convex/nextjs"
|
||||
import { ArtistsView } from "@/components/artists-view"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { Metadata } from "next"
|
||||
import { cache } from "react"
|
||||
|
||||
interface PageProps {
|
||||
params: Promise<{ id: string }>
|
||||
}
|
||||
|
||||
const fetchArtists = cache(() => fetchQuery(api.library.browseArtists))
|
||||
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
}: PageProps): Promise<Metadata> {
|
||||
const { id } = await params
|
||||
const artists = await fetchQuery(api.library.browseArtists)
|
||||
const artists = await fetchArtists()
|
||||
const selectedArtist = artists.find((artist) => artist.id === id)
|
||||
|
||||
return {
|
||||
@@ -32,8 +35,10 @@ export async function generateMetadata({
|
||||
|
||||
export default async function Page({ params }: PageProps) {
|
||||
const { id } = await params
|
||||
const artists = await fetchQuery(api.library.browseArtists)
|
||||
const albums = await fetchQuery(api.library.browseAlbums)
|
||||
const [artists, albums] = await Promise.all([
|
||||
fetchArtists(),
|
||||
fetchQuery(api.library.browseAlbums),
|
||||
])
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
|
||||
@@ -4,8 +4,10 @@ import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
export default async function Page() {
|
||||
const artists = await fetchQuery(api.library.browseArtists)
|
||||
const albums = await fetchQuery(api.library.browseAlbums)
|
||||
const [artists, albums] = await Promise.all([
|
||||
fetchQuery(api.library.browseArtists),
|
||||
fetchQuery(api.library.browseAlbums),
|
||||
])
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
|
||||
@@ -7,8 +7,10 @@ import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
export default function Page() {
|
||||
const recentlyAdded = useQuery(api.library.browseRecentlyAdded)
|
||||
const recentlyPlayed = useQuery(api.library.browseRecentlyPlayed)
|
||||
const recentlyAdded = useQuery(api.library.browseRecentlyAdded, { limit: 9 })
|
||||
const recentlyPlayed = useQuery(api.library.browseRecentlyPlayed, {
|
||||
limit: 9,
|
||||
})
|
||||
|
||||
if (recentlyAdded === undefined || recentlyPlayed === undefined) {
|
||||
return (
|
||||
@@ -33,13 +35,13 @@ export default function Page() {
|
||||
<ContentCarousel
|
||||
title="Recently Played"
|
||||
href="/recently-played"
|
||||
content={recentlyPlayed.slice(0, 9)}
|
||||
content={recentlyPlayed}
|
||||
/>
|
||||
) : null}
|
||||
<ContentCarousel
|
||||
title="Recently Added"
|
||||
href="/recently-added"
|
||||
content={recentlyAdded.slice(0, 9)}
|
||||
content={recentlyAdded}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -5,19 +5,20 @@ import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server"
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { Metadata } from "next"
|
||||
import { cache } from "react"
|
||||
|
||||
interface PageProps {
|
||||
params: Promise<{ id: string }>
|
||||
}
|
||||
|
||||
async function fetchPlaylistDetail(id: Id<"playlists">) {
|
||||
const fetchPlaylistDetail = cache(async (id: Id<"playlists">) => {
|
||||
const token = await convexAuthNextjsToken()
|
||||
return fetchQuery(
|
||||
api.playlists.browsePlaylistDetail,
|
||||
{ id },
|
||||
{ token }
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
@@ -29,7 +30,7 @@ export async function generateMetadata({
|
||||
title: `${playlist ? `${playlist.title}` : "oTunes"}`,
|
||||
openGraph: {
|
||||
title: `${playlist ? `${playlist.title}` : "oTunes"}`,
|
||||
description: `${playlist ? playlist.owner : null}`,
|
||||
description: playlist ? `Playlist by ${playlist.owner.name}` : "oTunes",
|
||||
images: playlist
|
||||
? { url: `/api/playlist/${playlist.id}/cover`, width: 512, height: 512 }
|
||||
: [],
|
||||
@@ -59,5 +60,5 @@ export default async function Page({ params }: PageProps) {
|
||||
)
|
||||
}
|
||||
|
||||
return <PlaylistView playlist={playlist} />
|
||||
return <PlaylistView key={playlist.id} playlist={playlist} />
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
export default function Page() {
|
||||
const albums = useQuery(api.library.browseRecentlyAdded)
|
||||
const albums = useQuery(api.library.browseRecentlyAdded, {})
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
|
||||
@@ -20,7 +20,7 @@ function RecentlyPlayedCard({
|
||||
}
|
||||
|
||||
export default function Page() {
|
||||
const recentlyPlayed = useQuery(api.library.browseRecentlyPlayed)
|
||||
const recentlyPlayed = useQuery(api.library.browseRecentlyPlayed, {})
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
|
||||
@@ -170,6 +170,10 @@ function SearchPageContent() {
|
||||
|
||||
useEffect(() => {
|
||||
function onPopState() {
|
||||
if (debounceRef.current) {
|
||||
clearTimeout(debounceRef.current)
|
||||
debounceRef.current = null
|
||||
}
|
||||
const nextQuery = readUrlQuery()
|
||||
urlQueryRef.current = nextQuery
|
||||
setQuery(nextQuery)
|
||||
@@ -186,6 +190,7 @@ function SearchPageContent() {
|
||||
|
||||
if (debounceRef.current) {
|
||||
clearTimeout(debounceRef.current)
|
||||
debounceRef.current = null
|
||||
}
|
||||
|
||||
debounceRef.current = setTimeout(() => {
|
||||
@@ -203,6 +208,7 @@ function SearchPageContent() {
|
||||
|
||||
if (debounceRef.current) {
|
||||
clearTimeout(debounceRef.current)
|
||||
debounceRef.current = null
|
||||
}
|
||||
commitSearch(query, "push")
|
||||
},
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { getConvexClient } from "@/lib/convex-server"
|
||||
import { ensureHlsJob, waitForHlsSegment } from "@/lib/server-hls"
|
||||
import {
|
||||
ensureHlsJob,
|
||||
getExistingHlsJob,
|
||||
waitForHlsSegment,
|
||||
} from "@/lib/server-hls"
|
||||
import { streamFile } from "@/lib/server-audio-stream"
|
||||
import { NextRequest, NextResponse } from "next/server"
|
||||
import fs from "node:fs/promises"
|
||||
@@ -29,14 +33,19 @@ export async function GET(
|
||||
}
|
||||
|
||||
try {
|
||||
const song = (await getConvexClient().query(api.library.getSong, {
|
||||
id: id as Id<"songs">,
|
||||
}))!
|
||||
|
||||
const quality = request.nextUrl.searchParams.get("quality")
|
||||
const preferAtmos =
|
||||
request.nextUrl.searchParams.get("preferAtmos") === "true"
|
||||
const job = await ensureHlsJob(song, quality, preferAtmos)
|
||||
const existingJob = getExistingHlsJob(id, quality, preferAtmos)
|
||||
const job =
|
||||
existingJob ??
|
||||
(await ensureHlsJob(
|
||||
(await getConvexClient().query(api.library.getSong, {
|
||||
id: id as Id<"songs">,
|
||||
}))!,
|
||||
quality,
|
||||
preferAtmos
|
||||
))
|
||||
if (segmentIndex >= job.segmentCount) {
|
||||
return new Response("Segment not found", { status: 404 })
|
||||
}
|
||||
@@ -47,7 +56,7 @@ export async function GET(
|
||||
return new NextResponse(streamFile(segmentPath), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Cache-Control": "no-cache",
|
||||
"Cache-Control": "private, max-age=86400, immutable",
|
||||
"Content-Length": String(size),
|
||||
"Content-Type": "video/mp2t",
|
||||
},
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Geist, Geist_Mono, Inter } from "next/font/google"
|
||||
import { Geist_Mono, Inter } from "next/font/google"
|
||||
|
||||
import "./globals.css"
|
||||
import { ConvexAuthNextjsServerProvider } from "@convex-dev/auth/nextjs/server"
|
||||
@@ -21,9 +21,7 @@ export const metadata: Metadata = {
|
||||
appleWebApp: {
|
||||
capable: true,
|
||||
title: "oTunes",
|
||||
startupImage:
|
||||
process.env.HOSTED_URL + "/logo-dark.png" ||
|
||||
"http://localhost:3000/logo-dark.png",
|
||||
startupImage: "/logo-dark.png",
|
||||
statusBarStyle: "default",
|
||||
},
|
||||
openGraph: {
|
||||
@@ -34,9 +32,7 @@ export const metadata: Metadata = {
|
||||
siteName: "oTunes",
|
||||
images: [
|
||||
{
|
||||
url:
|
||||
process.env.HOSTED_URL + "/logo-dark.png" ||
|
||||
"http://localhost:3000/logo-dark.png",
|
||||
url: "/logo-dark.png",
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -81,7 +81,6 @@ export function AddToPlaylistProvider({
|
||||
}) {
|
||||
const convex = useConvex()
|
||||
const router = useRouter()
|
||||
const ownedPlaylists = useQuery(api.playlists.listOwnedPlaylists)
|
||||
const addSongs = useMutation(api.playlists.addSongsToPlaylist)
|
||||
const createPlaylist = useMutation(api.playlists.createPlaylist)
|
||||
|
||||
@@ -90,8 +89,13 @@ export function AddToPlaylistProvider({
|
||||
const [newPlaylistName, setNewPlaylistName] = React.useState("")
|
||||
const [pendingSongIds, setPendingSongIds] = React.useState<Id<"songs">[]>([])
|
||||
const [isSubmitting, setIsSubmitting] = React.useState(false)
|
||||
const selectionRequestRef = React.useRef(0)
|
||||
const ownedPlaylists = useQuery(
|
||||
api.playlists.listOwnedPlaylists,
|
||||
open ? {} : "skip"
|
||||
)
|
||||
|
||||
const openAddToPlaylist = React.useCallback((songIds: Id<"songs">[]) => {
|
||||
const showAddToPlaylist = React.useCallback((songIds: Id<"songs">[]) => {
|
||||
const unique = [...new Set(songIds)]
|
||||
if (unique.length === 0) {
|
||||
toast.error("No songs selected")
|
||||
@@ -101,37 +105,79 @@ export function AddToPlaylistProvider({
|
||||
setOpen(true)
|
||||
}, [])
|
||||
|
||||
const openAddToPlaylist = React.useCallback(
|
||||
(songIds: Id<"songs">[]) => {
|
||||
selectionRequestRef.current += 1
|
||||
showAddToPlaylist(songIds)
|
||||
},
|
||||
[showAddToPlaylist]
|
||||
)
|
||||
|
||||
const openAddAlbumToPlaylist = React.useCallback(
|
||||
async (albumId: Id<"albums">) => {
|
||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
||||
albumId,
|
||||
})
|
||||
openAddToPlaylist(songIds)
|
||||
const requestId = ++selectionRequestRef.current
|
||||
try {
|
||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
||||
albumId,
|
||||
})
|
||||
if (requestId === selectionRequestRef.current) {
|
||||
showAddToPlaylist(songIds)
|
||||
}
|
||||
} catch (error) {
|
||||
if (requestId === selectionRequestRef.current) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to load album"
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
[convex, openAddToPlaylist]
|
||||
[convex, showAddToPlaylist]
|
||||
)
|
||||
|
||||
const openAddPlaylistToPlaylist = React.useCallback(
|
||||
async (playlistId: Id<"playlists">) => {
|
||||
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
||||
playlistId,
|
||||
})
|
||||
openAddToPlaylist(songIds)
|
||||
const requestId = ++selectionRequestRef.current
|
||||
try {
|
||||
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
||||
playlistId,
|
||||
})
|
||||
if (requestId === selectionRequestRef.current) {
|
||||
showAddToPlaylist(songIds)
|
||||
}
|
||||
} catch (error) {
|
||||
if (requestId === selectionRequestRef.current) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to load playlist"
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
[convex, openAddToPlaylist]
|
||||
[convex, showAddToPlaylist]
|
||||
)
|
||||
|
||||
const openAddArtistToPlaylist = React.useCallback(
|
||||
async (artistId: Id<"artists">) => {
|
||||
const songIds = await convex.query(api.playlists.getArtistSongIds, {
|
||||
artistId,
|
||||
})
|
||||
openAddToPlaylist(songIds)
|
||||
const requestId = ++selectionRequestRef.current
|
||||
try {
|
||||
const songIds = await convex.query(api.playlists.getArtistSongIds, {
|
||||
artistId,
|
||||
})
|
||||
if (requestId === selectionRequestRef.current) {
|
||||
showAddToPlaylist(songIds)
|
||||
}
|
||||
} catch (error) {
|
||||
if (requestId === selectionRequestRef.current) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to load artist"
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
[convex, openAddToPlaylist]
|
||||
[convex, showAddToPlaylist]
|
||||
)
|
||||
|
||||
const openCreatePlaylist = React.useCallback(() => {
|
||||
selectionRequestRef.current += 1
|
||||
setPendingSongIds([])
|
||||
setNewPlaylistName("")
|
||||
setCreateOpen(true)
|
||||
@@ -214,6 +260,7 @@ export function AddToPlaylistProvider({
|
||||
onOpenChange={(next) => {
|
||||
setOpen(next)
|
||||
if (!next) {
|
||||
selectionRequestRef.current += 1
|
||||
setPendingSongIds([])
|
||||
}
|
||||
}}
|
||||
|
||||
@@ -287,7 +287,6 @@ export function AlbumView({
|
||||
handleSelect,
|
||||
handlePointerDown,
|
||||
prepareContextMenu,
|
||||
clearSelection,
|
||||
} = useTrackSelection(album.tracks, validHighlightedSongId)
|
||||
|
||||
const selectionPositions = React.useMemo(
|
||||
@@ -370,7 +369,7 @@ export function AlbumView({
|
||||
fill
|
||||
sizes="240px"
|
||||
className="object-cover"
|
||||
priority
|
||||
preload
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
} from "lucide-react"
|
||||
|
||||
import { usePathname, useRouter } from "next/navigation"
|
||||
import dynamic from "next/dynamic"
|
||||
import { useAuthActions } from "@convex-dev/auth/react"
|
||||
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
|
||||
@@ -23,7 +24,6 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { OptionsModal } from "@/components/options-modal"
|
||||
import {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
@@ -43,6 +43,11 @@ import { useTheme } from "next-themes"
|
||||
import * as React from "react"
|
||||
import { useQuery } from "convex/react"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { useMounted } from "@/hooks/use-mounted"
|
||||
|
||||
const OptionsModal = dynamic(() =>
|
||||
import("@/components/options-modal").then((module) => module.OptionsModal)
|
||||
)
|
||||
|
||||
const browse = [
|
||||
{ title: "Home", path: "/", icon: House },
|
||||
@@ -61,10 +66,10 @@ export function AppSidebar() {
|
||||
const { signOut } = useAuthActions()
|
||||
const user = useQuery(api.auth.currentUser)
|
||||
const sidebarPlaylists = useQuery(api.playlists.listSidebarPlaylists)
|
||||
const fallbackLetters = user?.name?.match(/\b(\w)/g)!.join('') || "NA"
|
||||
const fallbackLetters = user?.name?.match(/\b(\w)/g)?.join("") || "NA"
|
||||
|
||||
const { resolvedTheme } = useTheme()
|
||||
const [mounted, setMounted] = React.useState(false)
|
||||
const mounted = useMounted()
|
||||
const [optionsOpen, setOptionsOpen] = React.useState(false)
|
||||
|
||||
async function handleSignOut() {
|
||||
@@ -72,10 +77,6 @@ export function AppSidebar() {
|
||||
router.push("/signin")
|
||||
}
|
||||
|
||||
React.useEffect(() => {
|
||||
setMounted(true)
|
||||
}, [])
|
||||
|
||||
const isDark = mounted && resolvedTheme === "dark"
|
||||
|
||||
const playlistNav = [
|
||||
@@ -202,7 +203,9 @@ export function AppSidebar() {
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<OptionsModal open={optionsOpen} onOpenChange={setOptionsOpen} />
|
||||
{optionsOpen ? (
|
||||
<OptionsModal open onOpenChange={setOptionsOpen} />
|
||||
) : null}
|
||||
<ThemeToggle />
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
|
||||
@@ -11,7 +11,6 @@ import { usePlayback } from "@/components/playback-provider"
|
||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||
import { AlbumCard } from "@/components/album-card"
|
||||
import { FavoriteMediaButton } from "@/components/favorite-media-button"
|
||||
import { ContentCarousel } from "@/components/content-carousel"
|
||||
import {
|
||||
MediaContextMenu,
|
||||
type MediaContextAction,
|
||||
@@ -21,23 +20,15 @@ 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 {
|
||||
albumGridCarouselContentClassName,
|
||||
albumGridCarouselSlideClassName,
|
||||
albumGridClassName,
|
||||
} from "@/lib/album-grid-classes"
|
||||
import { albumGridClassName } from "@/lib/album-grid-classes"
|
||||
import { artistCoverUrl } from "@/lib/cover-urls"
|
||||
|
||||
export function ArtistView({
|
||||
artist,
|
||||
albums,
|
||||
recentlyAdded,
|
||||
recentlyPlayed,
|
||||
}: {
|
||||
artist: BrowseArtist
|
||||
albums: BrowseAlbum[]
|
||||
recentlyAdded: BrowseAlbum[]
|
||||
recentlyPlayed: BrowseAlbum[]
|
||||
}) {
|
||||
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
|
||||
const { openAddArtistToPlaylist } = useAddToPlaylist()
|
||||
@@ -78,7 +69,7 @@ export function ArtistView({
|
||||
fill
|
||||
sizes="160px"
|
||||
className="object-cover"
|
||||
priority
|
||||
preload
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ function ArtistAvatar({ artist }: { artist: BrowseArtist }) {
|
||||
src={artistCoverUrl(artist.id)}
|
||||
alt={artist.name}
|
||||
fill
|
||||
sizes="(max-width: 512px) 100vw, (max-width: 256px) 50vw, (max-width: 128px) 33vw"
|
||||
sizes="32px"
|
||||
className="object-cover"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -12,7 +12,10 @@ type FavoritesContextValue = {
|
||||
isAlbumFavorite: (albumId: string) => boolean
|
||||
isArtistFavorite: (artistId: string) => boolean
|
||||
toggleSongFavorite: (songId: Id<"songs">) => Promise<void>
|
||||
toggleSongsFavorite: (songIds: Id<"songs">[], favorited: boolean) => Promise<void>
|
||||
toggleSongsFavorite: (
|
||||
songIds: Id<"songs">[],
|
||||
favorited: boolean
|
||||
) => Promise<boolean>
|
||||
toggleAlbumFavorite: (albumId: Id<"albums">) => Promise<void>
|
||||
toggleArtistFavorite: (artistId: Id<"artists">) => Promise<void>
|
||||
favoriteSongs: (songIds: Id<"songs">[]) => Promise<void>
|
||||
@@ -30,14 +33,97 @@ export function useFavorites() {
|
||||
|
||||
export function FavoritesProvider({ children }: { children: React.ReactNode }) {
|
||||
const favorites = useQuery(api.favorites.getUserFavorites)
|
||||
const favoriteSong = useMutation(api.favorites.favoriteSong)
|
||||
const favoriteSongsMutation = useMutation(api.favorites.favoriteSongs)
|
||||
const unfavoriteSong = useMutation(api.favorites.unfavoriteSong)
|
||||
const unfavoriteSongs = useMutation(api.favorites.unfavoriteSongs)
|
||||
const favoriteAlbum = useMutation(api.favorites.favoriteAlbum)
|
||||
const unfavoriteAlbum = useMutation(api.favorites.unfavoriteAlbum)
|
||||
const favoriteArtist = useMutation(api.favorites.favoriteArtist)
|
||||
const unfavoriteArtist = useMutation(api.favorites.unfavoriteArtist)
|
||||
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 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) ?? []),
|
||||
@@ -110,7 +196,7 @@ export function FavoritesProvider({ children }: { children: React.ReactNode }) {
|
||||
async (ids: Id<"songs">[], favorited: boolean) => {
|
||||
const unique = [...new Set(ids)]
|
||||
if (unique.length === 0) {
|
||||
return
|
||||
return true
|
||||
}
|
||||
try {
|
||||
if (favorited) {
|
||||
@@ -128,10 +214,12 @@ export function FavoritesProvider({ children }: { children: React.ReactNode }) {
|
||||
: "Added to favorites"
|
||||
)
|
||||
}
|
||||
return true
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to update favorites"
|
||||
)
|
||||
return false
|
||||
}
|
||||
},
|
||||
[favoriteSongsMutation, unfavoriteSongs]
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
"use client"
|
||||
|
||||
import dynamic from "next/dynamic"
|
||||
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
|
||||
const QueuePanel = dynamic(() =>
|
||||
import("@/components/queue-panel").then((module) => module.QueuePanel)
|
||||
)
|
||||
|
||||
export function LazyQueuePanel() {
|
||||
const { queueOpen } = usePlayback()
|
||||
|
||||
return queueOpen ? <QueuePanel /> : null
|
||||
}
|
||||
@@ -46,7 +46,7 @@ import {
|
||||
} from "@/components/ui/table"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Doc, Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { resizeProfileImageToDataUrl } from "@/lib/resize-profile-image"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
@@ -54,6 +54,23 @@ type Section = "profile" | "quality" | "users" | "library"
|
||||
|
||||
type PlaybackQuality = "low" | "medium" | "high" | "lossless"
|
||||
|
||||
type CurrentUser = {
|
||||
_id: Id<"users">
|
||||
name: string
|
||||
image?: string
|
||||
email: string
|
||||
isAdmin?: boolean
|
||||
playbackQuality?: PlaybackQuality
|
||||
preferAtmos?: boolean
|
||||
}
|
||||
|
||||
type AdminUser = {
|
||||
_id: Id<"users">
|
||||
name: string
|
||||
email: string
|
||||
isAdmin?: boolean
|
||||
}
|
||||
|
||||
const QUALITY_OPTIONS: {
|
||||
value: PlaybackQuality
|
||||
label: string
|
||||
@@ -122,7 +139,7 @@ function UserAvatar({
|
||||
user,
|
||||
size = "default",
|
||||
}: {
|
||||
user: Pick<Doc<"users">, "name" | "image">
|
||||
user: Pick<CurrentUser, "name" | "image">
|
||||
size?: "default" | "sm"
|
||||
}) {
|
||||
const initials = user.name
|
||||
@@ -145,7 +162,7 @@ function UserAvatar({
|
||||
)
|
||||
}
|
||||
|
||||
function ProfileSection({ user }: { user: Doc<"users"> }) {
|
||||
function ProfileSection({ user }: { user: CurrentUser }) {
|
||||
const updateName = useMutation(api.users.updateProfileName)
|
||||
const updateEmail = useMutation(api.users.updateProfileEmail)
|
||||
const updateImage = useMutation(api.users.updateProfileImage)
|
||||
@@ -369,7 +386,7 @@ function ProfileSection({ user }: { user: Doc<"users"> }) {
|
||||
)
|
||||
}
|
||||
|
||||
function QualitySection({ user }: { user: Doc<"users"> }) {
|
||||
function QualitySection({ user }: { user: CurrentUser }) {
|
||||
const { dolbyAtmosSupported } = usePlayback()
|
||||
const updateQuality = useMutation(api.users.updatePlaybackQuality)
|
||||
const updateAtmos = useMutation(api.users.updatePreferAtmos)
|
||||
@@ -561,7 +578,7 @@ function ChangePasswordDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
}: {
|
||||
user: Doc<"users">
|
||||
user: AdminUser
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}) {
|
||||
@@ -649,7 +666,7 @@ function UserRowActions({
|
||||
user,
|
||||
currentUserId,
|
||||
}: {
|
||||
user: Doc<"users">
|
||||
user: AdminUser
|
||||
currentUserId: Id<"users">
|
||||
}) {
|
||||
const setAdmin = useMutation(api.users.setUserAdmin)
|
||||
@@ -798,7 +815,7 @@ function UsersSection({
|
||||
users,
|
||||
currentUserId,
|
||||
}: {
|
||||
users: Doc<"users">[]
|
||||
users: AdminUser[]
|
||||
currentUserId: Id<"users">
|
||||
}) {
|
||||
const appSettings = useQuery(api.users.getAppSettings)
|
||||
@@ -884,7 +901,6 @@ export function OptionsModal({
|
||||
onOpenChange: (open: boolean) => void
|
||||
}) {
|
||||
const user = useQuery(api.auth.currentUser)
|
||||
const allUsers = useQuery(api.users.listUsers)
|
||||
const [section, setSection] = useState<Section>("profile")
|
||||
|
||||
const isAdmin = user?.isAdmin === true
|
||||
@@ -892,6 +908,10 @@ export function OptionsModal({
|
||||
!isAdmin && (section === "users" || section === "library")
|
||||
? "profile"
|
||||
: section
|
||||
const allUsers = useQuery(
|
||||
api.users.listUsers,
|
||||
open && isAdmin && activeSection === "users" ? {} : "skip"
|
||||
)
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
if (!nextOpen) {
|
||||
|
||||
@@ -12,8 +12,8 @@ import {
|
||||
useSyncExternalStore,
|
||||
useMemo,
|
||||
} from "react"
|
||||
import { useConvex, useMutation, useQuery } from "convex/react"
|
||||
import Hls from "hls.js"
|
||||
import { useMutation, useQuery } from "convex/react"
|
||||
import type Hls from "hls.js"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
@@ -37,9 +37,6 @@ type PlaybackContextValue = {
|
||||
queueOpen: boolean
|
||||
isPlaying: boolean
|
||||
volume: number
|
||||
currentTime: number
|
||||
duration: number
|
||||
seekTo: (seconds: number) => void
|
||||
setQueueOpen: (open: boolean) => void
|
||||
toggleQueueOpen: () => void
|
||||
setIsPlaying: (playing: boolean) => void
|
||||
@@ -73,11 +70,26 @@ type PlaybackContextValue = {
|
||||
}
|
||||
|
||||
const PlaybackContext = createContext<PlaybackContextValue | null>(null)
|
||||
const PlaybackProgressContext = createContext<{
|
||||
currentTime: number
|
||||
duration: number
|
||||
seekTo: (seconds: number) => void
|
||||
} | null>(null)
|
||||
|
||||
const VOLUME_STORAGE_KEY = "otunes:volume"
|
||||
const DEFAULT_VOLUME = 80
|
||||
|
||||
const volumeListeners = new Set<() => void>()
|
||||
let dolbyAtmosSnapshot: boolean | undefined
|
||||
|
||||
function subscribePlaybackCapabilities() {
|
||||
return () => {}
|
||||
}
|
||||
|
||||
function getDolbyAtmosSnapshot() {
|
||||
dolbyAtmosSnapshot ??= supportsDolbyAtmosPlayback(new Audio())
|
||||
return dolbyAtmosSnapshot
|
||||
}
|
||||
|
||||
function subscribeVolume(listener: () => void) {
|
||||
volumeListeners.add(listener)
|
||||
@@ -129,7 +141,7 @@ function playbackLoadSettings(
|
||||
playbackQuality?: "low" | "medium" | "high" | "lossless"
|
||||
},
|
||||
dolbyAtmosSupported: boolean | null,
|
||||
files: Record<string, string>
|
||||
files: Record<string, unknown>
|
||||
): PlaybackLoadSettings {
|
||||
const preferAtmos =
|
||||
dolbyAtmosSupported === true && (user.preferAtmos ?? false)
|
||||
@@ -179,6 +191,8 @@ function loadAudioSource(
|
||||
settings: PlaybackLoadSettings,
|
||||
onReady: () => void
|
||||
): AudioSourceCleanup {
|
||||
let disposed = false
|
||||
let hlsInstance: Hls | null = null
|
||||
const directUrl = songPlayUrl(
|
||||
songId,
|
||||
settings.playbackQuality,
|
||||
@@ -201,26 +215,47 @@ function loadAudioSource(
|
||||
audio.addEventListener("loadeddata", onReadyToPlay)
|
||||
audio.addEventListener("canplay", onReadyToPlay)
|
||||
|
||||
if (settings.useHls && audio.canPlayType("application/vnd.apple.mpegurl")) {
|
||||
audio.src = hlsUrl
|
||||
audio.load()
|
||||
} else if (settings.useHls && Hls.isSupported()) {
|
||||
const hls = new Hls()
|
||||
hlsRef.current = hls
|
||||
hls.on(Hls.Events.MANIFEST_PARSED, onReady)
|
||||
hls.loadSource(hlsUrl)
|
||||
hls.attachMedia(audio)
|
||||
} else {
|
||||
const loadDirectSource = () => {
|
||||
if (disposed) {
|
||||
return
|
||||
}
|
||||
audio.src = directUrl
|
||||
audio.load()
|
||||
}
|
||||
|
||||
if (settings.useHls && audio.canPlayType("application/vnd.apple.mpegurl")) {
|
||||
audio.src = hlsUrl
|
||||
audio.load()
|
||||
} else if (settings.useHls) {
|
||||
void import("hls.js")
|
||||
.then(({ default: HlsConstructor }) => {
|
||||
if (disposed) {
|
||||
return
|
||||
}
|
||||
if (!HlsConstructor.isSupported()) {
|
||||
loadDirectSource()
|
||||
return
|
||||
}
|
||||
const hls = new HlsConstructor()
|
||||
hlsInstance = hls
|
||||
hlsRef.current = hls
|
||||
hls.on(HlsConstructor.Events.MANIFEST_PARSED, onReady)
|
||||
hls.loadSource(hlsUrl)
|
||||
hls.attachMedia(audio)
|
||||
})
|
||||
.catch(loadDirectSource)
|
||||
} else {
|
||||
loadDirectSource()
|
||||
}
|
||||
|
||||
return () => {
|
||||
disposed = true
|
||||
audio.removeEventListener("loadedmetadata", onReadyToPlay)
|
||||
audio.removeEventListener("loadeddata", onReadyToPlay)
|
||||
audio.removeEventListener("canplay", onReadyToPlay)
|
||||
if (hlsRef.current) {
|
||||
hlsRef.current.off(Hls.Events.MANIFEST_PARSED, onReady)
|
||||
if (hlsInstance && hlsRef.current === hlsInstance) {
|
||||
hlsInstance.destroy()
|
||||
hlsRef.current = null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -233,8 +268,17 @@ export function usePlayback() {
|
||||
return context
|
||||
}
|
||||
|
||||
export function usePlaybackProgress() {
|
||||
const context = useContext(PlaybackProgressContext)
|
||||
if (!context) {
|
||||
throw new Error(
|
||||
"usePlaybackProgress must be used within PlaybackProvider"
|
||||
)
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
const convex = useConvex()
|
||||
const user = useQuery(api.auth.currentUser)
|
||||
const playback = useQuery(api.playback.getPlaybackState)
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null)
|
||||
@@ -256,8 +300,42 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
const playFromLibrarySongMutation = useMutation(
|
||||
api.playback.playFromLibrarySong
|
||||
)
|
||||
const toggleShuffleMutation = useMutation(api.playback.toggleShuffle)
|
||||
const cycleRepeatMutation = useMutation(api.playback.cycleRepeat)
|
||||
const playAlbumMutation = useMutation(api.playback.playAlbum)
|
||||
const playAlbumShuffledMutation = useMutation(api.playback.playAlbumShuffled)
|
||||
const playArtistMutation = useMutation(api.playback.playArtist)
|
||||
const playArtistShuffledMutation = useMutation(
|
||||
api.playback.playArtistShuffled
|
||||
)
|
||||
const playPlaylistMutation = useMutation(api.playback.playPlaylist)
|
||||
const playPlaylistShuffledMutation = useMutation(
|
||||
api.playback.playPlaylistShuffled
|
||||
)
|
||||
const toggleShuffleMutation = useMutation(
|
||||
api.playback.toggleShuffle
|
||||
).withOptimisticUpdate((store) => {
|
||||
const current = store.getQuery(api.playback.getPlaybackState, {})
|
||||
if (!current) return
|
||||
store.setQuery(api.playback.getPlaybackState, {}, {
|
||||
...current,
|
||||
shuffleEnabled: !current.shuffleEnabled,
|
||||
})
|
||||
})
|
||||
const cycleRepeatMutation = useMutation(
|
||||
api.playback.cycleRepeat
|
||||
).withOptimisticUpdate((store) => {
|
||||
const current = store.getQuery(api.playback.getPlaybackState, {})
|
||||
if (!current) return
|
||||
const next =
|
||||
current.repeatEnabled === "none"
|
||||
? "once"
|
||||
: current.repeatEnabled === "once"
|
||||
? "always"
|
||||
: "none"
|
||||
store.setQuery(api.playback.getPlaybackState, {}, {
|
||||
...current,
|
||||
repeatEnabled: next,
|
||||
})
|
||||
})
|
||||
const clearQueueMutation = useMutation(api.playback.clearQueue)
|
||||
const reorderQueueMutation = useMutation(api.playback.reorderQueue)
|
||||
const skipToQueueIndexMutation = useMutation(api.playback.skipToQueueIndex)
|
||||
@@ -268,17 +346,24 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
const progressRestoredForSongRef = useRef<Id<"songs"> | null>(null)
|
||||
const lastSavedProgressRef = useRef(-1)
|
||||
const prevIsPlayingRef = useRef(false)
|
||||
const currentTimeRef = useRef(0)
|
||||
const durationRef = useRef(0)
|
||||
|
||||
const [queueOpen, setQueueOpen] = useState(false)
|
||||
const [isPlaying, setIsPlaying] = useState(false)
|
||||
const [currentTime, setCurrentTime] = useState(0)
|
||||
const [duration, setDuration] = useState(0)
|
||||
const [measuredDuration, setMeasuredDuration] = useState<{
|
||||
songId: string
|
||||
seconds: number
|
||||
} | null>(null)
|
||||
const [progressToRestore, setProgressToRestore] = useState<number | null>(
|
||||
null
|
||||
)
|
||||
const [dolbyAtmosSupported, setDolbyAtmosSupported] = useState<
|
||||
boolean | null
|
||||
>(null)
|
||||
const dolbyAtmosSupported = useSyncExternalStore(
|
||||
subscribePlaybackCapabilities,
|
||||
getDolbyAtmosSnapshot,
|
||||
() => null
|
||||
)
|
||||
const volume = useSyncExternalStore(
|
||||
subscribeVolume,
|
||||
readStoredVolume,
|
||||
@@ -297,8 +382,19 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
}, [])
|
||||
|
||||
const currentSong = playback?.currentSong ?? null
|
||||
const currentSongId = currentSong?.id ?? null
|
||||
const playbackQuality = user?.playbackQuality
|
||||
const preferAtmos = user?.preferAtmos
|
||||
const duration =
|
||||
currentSong && measuredDuration?.songId === currentSong.id
|
||||
? measuredDuration.seconds
|
||||
: (currentSong?.durationSeconds ?? 0)
|
||||
|
||||
useEffect(() => {
|
||||
durationRef.current = duration
|
||||
}, [duration])
|
||||
const currentSongDoc = useQuery(
|
||||
api.library.getSong,
|
||||
api.library.getSongPlaybackInfo,
|
||||
currentSong ? { id: currentSong.id } : "skip"
|
||||
)
|
||||
const isPlaybackActive = Boolean(currentSong && isPlaying)
|
||||
@@ -308,7 +404,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
const nextQueueSongId =
|
||||
queueSongIds.length > 1 ? queueSongIds[1] : null
|
||||
const nextQueueSongDoc = useQuery(
|
||||
api.library.getSong,
|
||||
api.library.getSongPlaybackInfo,
|
||||
nextQueueSongId ? { id: nextQueueSongId } : "skip"
|
||||
)
|
||||
|
||||
@@ -322,40 +418,48 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
const maxDuration =
|
||||
Number.isFinite(audio.duration) && audio.duration > 0
|
||||
? audio.duration
|
||||
: duration
|
||||
: durationRef.current
|
||||
const clamped = Math.max(0, Math.min(seconds, maxDuration || 0))
|
||||
audio.currentTime = clamped
|
||||
currentTimeRef.current = clamped
|
||||
setCurrentTime(clamped)
|
||||
},
|
||||
[duration]
|
||||
[]
|
||||
)
|
||||
|
||||
const saveProgress = useCallback(
|
||||
(seconds: number) => {
|
||||
if (!currentSongId) {
|
||||
return
|
||||
}
|
||||
|
||||
const progressSeconds = Math.max(0, Math.floor(seconds))
|
||||
if (progressSeconds === lastSavedProgressRef.current) {
|
||||
return
|
||||
}
|
||||
|
||||
lastSavedProgressRef.current = progressSeconds
|
||||
void updateSongProgressMutation({ progressSeconds })
|
||||
void updateSongProgressMutation({
|
||||
songId: currentSongId,
|
||||
progressSeconds,
|
||||
})
|
||||
},
|
||||
[updateSongProgressMutation]
|
||||
[currentSongId, updateSongProgressMutation]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!currentSong || !playback) {
|
||||
if (!currentSongId || !playback) {
|
||||
return
|
||||
}
|
||||
|
||||
if (progressRestoredForSongRef.current === currentSong.id) {
|
||||
if (progressRestoredForSongRef.current === currentSongId) {
|
||||
return
|
||||
}
|
||||
|
||||
progressRestoredForSongRef.current = currentSong.id
|
||||
progressRestoredForSongRef.current = currentSongId
|
||||
lastSavedProgressRef.current = -1
|
||||
setProgressToRestore(playback.currentSongProgress ?? 0)
|
||||
}, [currentSong?.id, playback])
|
||||
}, [currentSongId, playback])
|
||||
|
||||
useEffect(() => {
|
||||
if (progressToRestore === null || progressToRestore <= 0) {
|
||||
@@ -363,7 +467,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
|
||||
const audio = audioRef.current
|
||||
if (!audio || !currentSong) {
|
||||
if (!audio || !currentSongId) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -374,6 +478,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
: progressToRestore
|
||||
const clamped = Math.min(progressToRestore, maxDuration)
|
||||
audio.currentTime = clamped
|
||||
currentTimeRef.current = clamped
|
||||
setCurrentTime(clamped)
|
||||
setProgressToRestore(null)
|
||||
}
|
||||
@@ -387,11 +492,11 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
return () => {
|
||||
audio.removeEventListener("loadedmetadata", applyProgress)
|
||||
}
|
||||
}, [progressToRestore, currentSong?.id])
|
||||
}, [progressToRestore, currentSongId])
|
||||
|
||||
useEffect(() => {
|
||||
const audio = audioRef.current
|
||||
if (!audio || !currentSong) {
|
||||
if (!audio || !currentSongId) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -401,10 +506,10 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
prevIsPlayingRef.current = isPlaying
|
||||
saveProgress(audio.currentTime)
|
||||
}, [isPlaying, currentSong?.id, saveProgress])
|
||||
}, [isPlaying, currentSongId, saveProgress])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPlaying || !currentSong) {
|
||||
if (!isPlaying || !currentSongId) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -420,11 +525,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
return () => {
|
||||
window.clearInterval(interval)
|
||||
}
|
||||
}, [isPlaying, currentSong?.id, saveProgress])
|
||||
|
||||
useEffect(() => {
|
||||
setDuration(currentSong?.durationSeconds ?? 0)
|
||||
}, [currentSong?.id, currentSong?.durationSeconds])
|
||||
}, [isPlaying, currentSongId, saveProgress])
|
||||
|
||||
useEffect(() => {
|
||||
isPlayingRef.current = isPlaying
|
||||
@@ -463,7 +564,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
preloadAudio.preload = "auto"
|
||||
audioRef.current = audio
|
||||
preloadAudioRef.current = preloadAudio
|
||||
setDolbyAtmosSupported(supportsDolbyAtmosPlayback(audio))
|
||||
|
||||
const syncPlayingFromAudio = () => {
|
||||
if (ignoreAudioSyncRef.current) {
|
||||
@@ -551,7 +651,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!currentSong) {
|
||||
if (!currentSongId) {
|
||||
autoPlayNextRef.current = false
|
||||
intentionalLoadRef.current = false
|
||||
destroyHls()
|
||||
@@ -562,16 +662,16 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
return
|
||||
}
|
||||
|
||||
if (user === undefined || !user || !currentSongDoc) {
|
||||
if (!user || !currentSongDoc) {
|
||||
return
|
||||
}
|
||||
|
||||
const settings = playbackLoadSettings(
|
||||
user,
|
||||
{ playbackQuality, preferAtmos },
|
||||
dolbyAtmosSupported,
|
||||
currentSongDoc.files
|
||||
)
|
||||
const loadKey = songLoadKey(currentSong.id, settings)
|
||||
const loadKey = songLoadKey(currentSongId, settings)
|
||||
|
||||
if (loadedSongKeyRef.current === loadKey) {
|
||||
return
|
||||
@@ -613,7 +713,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
const cleanupSource = loadAudioSource(
|
||||
audio,
|
||||
hlsRef,
|
||||
currentSong.id,
|
||||
currentSongId,
|
||||
settings,
|
||||
requestPlay
|
||||
)
|
||||
@@ -623,11 +723,11 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
cleanupSource()
|
||||
}
|
||||
}, [
|
||||
currentSong?.id,
|
||||
currentSongId,
|
||||
currentSongDoc,
|
||||
user === undefined,
|
||||
user?.playbackQuality,
|
||||
user?.preferAtmos,
|
||||
user,
|
||||
playbackQuality,
|
||||
preferAtmos,
|
||||
dolbyAtmosSupported,
|
||||
runWithoutAudioSync,
|
||||
destroyHls,
|
||||
@@ -637,17 +737,17 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
useEffect(() => {
|
||||
const preloadAudio = preloadAudioRef.current
|
||||
if (!preloadAudio || !nextQueueSongId || !currentSong) {
|
||||
if (!preloadAudio || !nextQueueSongId || !currentSongId) {
|
||||
clearPreload()
|
||||
return
|
||||
}
|
||||
|
||||
if (user === undefined || !user || !nextQueueSongDoc) {
|
||||
if (!user || !nextQueueSongDoc) {
|
||||
return
|
||||
}
|
||||
|
||||
const settings = playbackLoadSettings(
|
||||
user,
|
||||
{ playbackQuality, preferAtmos },
|
||||
dolbyAtmosSupported,
|
||||
nextQueueSongDoc.files
|
||||
)
|
||||
@@ -684,12 +784,12 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
preloadAudio.removeAttribute("src")
|
||||
}
|
||||
}, [
|
||||
currentSong?.id,
|
||||
currentSongId,
|
||||
nextQueueSongId,
|
||||
nextQueueSongDoc,
|
||||
user === undefined,
|
||||
user?.playbackQuality,
|
||||
user?.preferAtmos,
|
||||
user,
|
||||
playbackQuality,
|
||||
preferAtmos,
|
||||
dolbyAtmosSupported,
|
||||
clearPreload,
|
||||
destroyPreloadHls,
|
||||
@@ -797,6 +897,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
autoPlayNextRef.current = false
|
||||
isPlayingRef.current = false
|
||||
audio.currentTime = 0
|
||||
currentTimeRef.current = 0
|
||||
setCurrentTime(0)
|
||||
setIsPlaying(false)
|
||||
})
|
||||
@@ -850,6 +951,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
currentSong,
|
||||
queueLength,
|
||||
nextQueueSongId,
|
||||
nextQueueSongDoc,
|
||||
user,
|
||||
dolbyAtmosSupported,
|
||||
skipNextMutation,
|
||||
@@ -867,13 +969,22 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
const syncDuration = () => {
|
||||
if (Number.isFinite(audio.duration) && audio.duration > 0) {
|
||||
setDuration(audio.duration)
|
||||
if (currentSong) {
|
||||
setMeasuredDuration({
|
||||
songId: currentSong.id,
|
||||
seconds: audio.duration,
|
||||
})
|
||||
}
|
||||
} else if (currentSong) {
|
||||
setDuration(currentSong.durationSeconds)
|
||||
setMeasuredDuration({
|
||||
songId: currentSong.id,
|
||||
seconds: currentSong.durationSeconds,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const syncTime = () => {
|
||||
currentTimeRef.current = audio.currentTime
|
||||
setCurrentTime(audio.currentTime)
|
||||
}
|
||||
|
||||
@@ -958,70 +1069,50 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
const playAlbum = useCallback(
|
||||
async (albumId: Id<"albums">) => {
|
||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
||||
albumId,
|
||||
})
|
||||
await playInOrder(songIds)
|
||||
await playAlbumMutation({ albumId })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[convex, playInOrder]
|
||||
[playAlbumMutation]
|
||||
)
|
||||
|
||||
const playAlbumShuffled = useCallback(
|
||||
async (albumId: Id<"albums">) => {
|
||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
||||
albumId,
|
||||
})
|
||||
await playShuffled(songIds)
|
||||
await playAlbumShuffledMutation({ albumId })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[convex, playShuffled]
|
||||
[playAlbumShuffledMutation]
|
||||
)
|
||||
|
||||
const playArtist = useCallback(
|
||||
async (artistId: Id<"artists">) => {
|
||||
const songIds = await convex.query(
|
||||
api.playlists.getOrderedArtistSongIds,
|
||||
{
|
||||
artistId,
|
||||
}
|
||||
)
|
||||
await playInOrder(songIds)
|
||||
await playArtistMutation({ artistId })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[convex, playInOrder]
|
||||
[playArtistMutation]
|
||||
)
|
||||
|
||||
const playArtistShuffled = useCallback(
|
||||
async (artistId: Id<"artists">) => {
|
||||
const songIds = await convex.query(
|
||||
api.playlists.getOrderedArtistSongIds,
|
||||
{
|
||||
artistId,
|
||||
}
|
||||
)
|
||||
await playShuffled(songIds)
|
||||
await playArtistShuffledMutation({ artistId })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[convex, playShuffled]
|
||||
[playArtistShuffledMutation]
|
||||
)
|
||||
|
||||
const playPlaylist = useCallback(
|
||||
async (playlistId: Id<"playlists">) => {
|
||||
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
||||
playlistId,
|
||||
})
|
||||
await playInOrderMutation({ songIds, playlistId })
|
||||
await playPlaylistMutation({ playlistId })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[convex, playInOrderMutation]
|
||||
[playPlaylistMutation]
|
||||
)
|
||||
|
||||
const playPlaylistShuffled = useCallback(
|
||||
async (playlistId: Id<"playlists">) => {
|
||||
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
||||
playlistId,
|
||||
})
|
||||
await playShuffledMutation({ songIds, playlistId })
|
||||
await playPlaylistShuffledMutation({ playlistId })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[convex, playShuffledMutation]
|
||||
[playPlaylistShuffledMutation]
|
||||
)
|
||||
|
||||
const toggleQueueOpen = useCallback(() => {
|
||||
@@ -1042,12 +1133,12 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
}, [repeatEnabled, queueSongIds.length, seekTo, skipNextMutation])
|
||||
|
||||
const skipPrevious = useCallback(async () => {
|
||||
if (currentTime > PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS) {
|
||||
if (currentTimeRef.current > PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS) {
|
||||
seekTo(0)
|
||||
return
|
||||
}
|
||||
await skipPreviousMutation()
|
||||
}, [currentTime, seekTo, skipPreviousMutation])
|
||||
}, [seekTo, skipPreviousMutation])
|
||||
|
||||
useMediaSession({
|
||||
song: currentSong,
|
||||
@@ -1070,9 +1161,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
queueOpen,
|
||||
isPlaying: isPlaybackActive,
|
||||
volume,
|
||||
currentTime,
|
||||
duration,
|
||||
seekTo,
|
||||
setQueueOpen,
|
||||
toggleQueueOpen,
|
||||
setIsPlaying,
|
||||
@@ -1114,9 +1202,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
queueOpen,
|
||||
isPlaybackActive,
|
||||
volume,
|
||||
currentTime,
|
||||
duration,
|
||||
seekTo,
|
||||
toggleQueueOpen,
|
||||
setVolume,
|
||||
playInOrder,
|
||||
@@ -1142,9 +1227,16 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
]
|
||||
)
|
||||
|
||||
const progressValue = useMemo(
|
||||
() => ({ currentTime, duration, seekTo }),
|
||||
[currentTime, duration, seekTo]
|
||||
)
|
||||
|
||||
return (
|
||||
<PlaybackContext.Provider value={value}>
|
||||
{children}
|
||||
<PlaybackProgressContext.Provider value={progressValue}>
|
||||
{children}
|
||||
</PlaybackProgressContext.Provider>
|
||||
</PlaybackContext.Provider>
|
||||
)
|
||||
}
|
||||
@@ -16,7 +16,10 @@ import {
|
||||
} from "lucide-react"
|
||||
|
||||
import { PlaybackSongMeta } from "@/components/playback-song-meta"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import {
|
||||
usePlayback,
|
||||
usePlaybackProgress,
|
||||
} from "@/components/playback-provider"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Slider } from "@/components/ui/slider"
|
||||
import { useSidebar } from "@/components/ui/sidebar"
|
||||
@@ -40,18 +43,16 @@ export function PlayerBar() {
|
||||
queueOpen,
|
||||
isPlaying,
|
||||
volume,
|
||||
currentTime,
|
||||
duration,
|
||||
queueSongIds,
|
||||
setIsPlaying,
|
||||
setVolume,
|
||||
seekTo,
|
||||
toggleQueueOpen,
|
||||
toggleShuffle,
|
||||
cycleRepeat,
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
} = usePlayback()
|
||||
const { currentTime, duration, seekTo } = usePlaybackProgress()
|
||||
const { state, isMobile } = useSidebar()
|
||||
const [isSeeking, setIsSeeking] = React.useState(false)
|
||||
const [seekValue, setSeekValue] = React.useState(0)
|
||||
|
||||
@@ -119,7 +119,6 @@ function PlaylistSongRow({
|
||||
isOwner,
|
||||
canRemove,
|
||||
isActive,
|
||||
isSelected,
|
||||
selectionPosition,
|
||||
isFavorite,
|
||||
selectedCount,
|
||||
@@ -143,7 +142,6 @@ function PlaylistSongRow({
|
||||
isOwner: boolean
|
||||
canRemove: boolean
|
||||
isActive: boolean
|
||||
isSelected: boolean
|
||||
selectionPosition: SelectionRangePosition
|
||||
isFavorite: boolean
|
||||
selectedCount: number
|
||||
@@ -290,7 +288,13 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
const subscribe = useMutation(api.playlists.subscribeToPlaylist)
|
||||
const unsubscribe = useMutation(api.playlists.unsubscribeFromPlaylist)
|
||||
|
||||
const [songs, setSongs] = React.useState(playlist.songs)
|
||||
const [playlistSongs, setPlaylistSongs] = React.useState(playlist.songs)
|
||||
const [hiddenFavoriteIds, setHiddenFavoriteIds] = React.useState(
|
||||
() => new Set<string>()
|
||||
)
|
||||
const songs = isFavorites
|
||||
? playlist.songs.filter((song) => !hiddenFavoriteIds.has(song.id))
|
||||
: playlistSongs
|
||||
const playlistSongIds = React.useMemo(
|
||||
() => songs.map((song) => song.id as Id<"songs">),
|
||||
[songs]
|
||||
@@ -298,14 +302,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
const [activeTrackId, setActiveTrackId] = React.useState("")
|
||||
const [dragIndex, setDragIndex] = React.useState<number | null>(null)
|
||||
const [isSubscribed, setIsSubscribed] = React.useState(playlist.isSubscribed)
|
||||
|
||||
React.useEffect(() => {
|
||||
setSongs(playlist.songs)
|
||||
setIsSubscribed(playlist.isSubscribed)
|
||||
setActiveTrackId((current) =>
|
||||
playlist.songs.some((song) => song.id === current) ? current : ""
|
||||
)
|
||||
}, [playlist])
|
||||
const [subscriptionPending, setSubscriptionPending] = React.useState(false)
|
||||
|
||||
const {
|
||||
selectedIds,
|
||||
@@ -381,8 +378,11 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
: [songId]
|
||||
|
||||
if (isFavorites) {
|
||||
await toggleSongsFavorite(ids as Id<"songs">[], true)
|
||||
setSongs((current) => current.filter((song) => !ids.includes(song.id)))
|
||||
const succeeded = await toggleSongsFavorite(
|
||||
ids as Id<"songs">[],
|
||||
true
|
||||
)
|
||||
if (!succeeded) return
|
||||
return
|
||||
}
|
||||
|
||||
@@ -391,7 +391,9 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
playlistId: playlist.id as Id<"playlists">,
|
||||
songIds: ids as Id<"songs">[],
|
||||
})
|
||||
setSongs((current) => current.filter((song) => !ids.includes(song.id)))
|
||||
setPlaylistSongs((current) =>
|
||||
current.filter((song) => !ids.includes(song.id))
|
||||
)
|
||||
toast.success(ids.length > 1 ? `Removed ${ids.length} songs` : "Removed song")
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
@@ -400,14 +402,19 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
}
|
||||
}
|
||||
|
||||
async function persistOrder(nextSongs: BrowseSong[]) {
|
||||
async function persistOrder(
|
||||
previousSongs: BrowseSong[],
|
||||
nextSongs: BrowseSong[]
|
||||
) {
|
||||
try {
|
||||
await reorderSongs({
|
||||
playlistId: playlist.id as Id<"playlists">,
|
||||
songIds: nextSongs.map((song) => song.id as Id<"songs">),
|
||||
})
|
||||
setSongs(nextSongs)
|
||||
} catch (error) {
|
||||
setPlaylistSongs((current) =>
|
||||
current === nextSongs ? previousSongs : current
|
||||
)
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to reorder songs"
|
||||
)
|
||||
@@ -420,11 +427,13 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
return
|
||||
}
|
||||
|
||||
const next = [...songs]
|
||||
const previous = songs
|
||||
const next = [...previous]
|
||||
const [moved] = next.splice(dragIndex, 1)
|
||||
next.splice(targetIndex, 0, moved)
|
||||
setDragIndex(null)
|
||||
void persistOrder(next)
|
||||
setPlaylistSongs(next)
|
||||
void persistOrder(previous, next)
|
||||
}
|
||||
|
||||
async function handleDeletePlaylist() {
|
||||
@@ -442,6 +451,10 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
}
|
||||
|
||||
async function handleSubscribeToggle() {
|
||||
if (subscriptionPending) {
|
||||
return
|
||||
}
|
||||
setSubscriptionPending(true)
|
||||
try {
|
||||
if (isSubscribed) {
|
||||
await unsubscribe({
|
||||
@@ -460,6 +473,8 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to update subscription"
|
||||
)
|
||||
} finally {
|
||||
setSubscriptionPending(false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -481,7 +496,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
fill
|
||||
sizes="240px"
|
||||
className="object-cover"
|
||||
priority
|
||||
preload
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -527,7 +542,8 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
<Button
|
||||
variant={isSubscribed ? "secondary" : "default"}
|
||||
className="h-10 rounded-full px-6"
|
||||
onClick={handleSubscribeToggle}
|
||||
onClick={() => void handleSubscribeToggle()}
|
||||
disabled={subscriptionPending}
|
||||
>
|
||||
{isSubscribed ? "Subscribed" : "Subscribe"}
|
||||
</Button>
|
||||
@@ -594,7 +610,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
isFavorites ? "Unfavorite" : "Remove from Playlist"
|
||||
}
|
||||
isActive={song.id === activeTrackId}
|
||||
isSelected={isSelected(song.id)}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
isFavorite={isSongFavorite(song.id)}
|
||||
selectedCount={
|
||||
@@ -609,11 +624,14 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
setActiveTrackId(song.id)
|
||||
}}
|
||||
onToggleFavorite={() => {
|
||||
const wasFavorite = isSongFavorite(song.id)
|
||||
void toggleSongFavorite(song.id as Id<"songs">)
|
||||
if (isFavorites && isSongFavorite(song.id)) {
|
||||
setSongs((current) =>
|
||||
current.filter((item) => item.id !== song.id)
|
||||
)
|
||||
if (isFavorites && wasFavorite) {
|
||||
setHiddenFavoriteIds((current) => {
|
||||
const next = new Set(current)
|
||||
next.add(song.id)
|
||||
return next
|
||||
})
|
||||
}
|
||||
}}
|
||||
onPrepareContextMenu={() => prepareContextMenu(song.id)}
|
||||
|
||||
@@ -243,13 +243,14 @@ export function QueuePanel() {
|
||||
{ initialNumItems: initialPageSize }
|
||||
)
|
||||
|
||||
const queueSongs = results ?? []
|
||||
const queueSongs = React.useMemo(() => results ?? [], [results])
|
||||
const selectableQueue = React.useMemo(
|
||||
() => toSelectableQueue(queueSongs),
|
||||
[queueSongs]
|
||||
)
|
||||
|
||||
const [dragIndex, setDragIndex] = React.useState<number | null>(null)
|
||||
const currentQueueSongId = queueSongIds[0]
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!queueOpen || queueSongIds.length === 0) {
|
||||
@@ -261,7 +262,7 @@ export function QueuePanel() {
|
||||
})
|
||||
|
||||
return () => cancelAnimationFrame(frame)
|
||||
}, [queueOpen, queueSongIds[0]])
|
||||
}, [queueOpen, queueSongIds.length, currentQueueSongId])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!shouldPaginate) {
|
||||
|
||||
@@ -45,6 +45,7 @@ export function SearchSongItem({ song }: { song: BrowseSong }) {
|
||||
src={albumCoverUrl(song.album.id)}
|
||||
alt={song.album.title}
|
||||
fill
|
||||
sizes="44px"
|
||||
className="object-cover"
|
||||
/>
|
||||
</Link>
|
||||
|
||||
@@ -79,7 +79,13 @@ export function SearchTopResultCard({ result }: { result: TopResult }) {
|
||||
image.rounded ? "rounded-full" : "rounded-md"
|
||||
)}
|
||||
>
|
||||
<Image src={image.src} alt={image.alt} fill className="object-cover" />
|
||||
<Image
|
||||
src={image.src}
|
||||
alt={image.alt}
|
||||
fill
|
||||
sizes="56px"
|
||||
className="object-cover"
|
||||
/>
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate font-medium">{resultTitle(result)}</p>
|
||||
|
||||
@@ -88,7 +88,7 @@ function SongCover({
|
||||
src={albumCoverUrl(song.album.id)}
|
||||
alt={song.album.title}
|
||||
fill
|
||||
sizes="(max-width: 640px) 50vw, (max-width: 1024px) 25vw, 16vw"
|
||||
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">
|
||||
@@ -111,7 +111,6 @@ function SongCover({
|
||||
|
||||
function SongRow({
|
||||
song,
|
||||
index,
|
||||
isSelected,
|
||||
selectionPosition,
|
||||
isFavorite,
|
||||
@@ -124,7 +123,6 @@ function SongRow({
|
||||
onPlay,
|
||||
}: {
|
||||
song: BrowseSong
|
||||
index: number
|
||||
isSelected: boolean
|
||||
selectionPosition: SelectionRangePosition
|
||||
isFavorite: boolean
|
||||
@@ -448,7 +446,6 @@ export function SongsView() {
|
||||
<SongRow
|
||||
key={song.id}
|
||||
song={song}
|
||||
index={index}
|
||||
isSelected={isSelected(song.id)}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
isFavorite={isSongFavorite(song.id)}
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Moon, Sun } from "lucide-react"
|
||||
import { useTheme } from "next-themes"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { useMounted } from "@/hooks/use-mounted"
|
||||
|
||||
export function ThemeToggle() {
|
||||
const { resolvedTheme, setTheme } = useTheme()
|
||||
const [mounted, setMounted] = React.useState(false)
|
||||
|
||||
React.useEffect(() => {
|
||||
setMounted(true)
|
||||
}, [])
|
||||
const mounted = useMounted()
|
||||
|
||||
const isDark = mounted && resolvedTheme === "dark"
|
||||
|
||||
|
||||
@@ -95,12 +95,19 @@ function Carousel({
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!api) return
|
||||
onSelect(api)
|
||||
api.on("reInit", onSelect)
|
||||
api.on("select", onSelect)
|
||||
let active = true
|
||||
queueMicrotask(() => {
|
||||
if (active) {
|
||||
onSelect(api)
|
||||
}
|
||||
})
|
||||
|
||||
return () => {
|
||||
api?.off("select", onSelect)
|
||||
active = false
|
||||
api.off("reInit", onSelect)
|
||||
api.off("select", onSelect)
|
||||
}
|
||||
}, [api, onSelect])
|
||||
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
import * as React from "react"
|
||||
|
||||
const MOBILE_BREAKPOINT = 768
|
||||
const MOBILE_QUERY = `(max-width: ${MOBILE_BREAKPOINT - 1}px)`
|
||||
|
||||
function subscribe(listener: () => void) {
|
||||
const mediaQuery = window.matchMedia(MOBILE_QUERY)
|
||||
mediaQuery.addEventListener("change", listener)
|
||||
return () => mediaQuery.removeEventListener("change", listener)
|
||||
}
|
||||
|
||||
function getSnapshot() {
|
||||
return window.matchMedia(MOBILE_QUERY).matches
|
||||
}
|
||||
|
||||
export function useIsMobile() {
|
||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
|
||||
|
||||
React.useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
|
||||
const onChange = () => {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
}
|
||||
mql.addEventListener("change", onChange)
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
return () => mql.removeEventListener("change", onChange)
|
||||
}, [])
|
||||
|
||||
return !!isMobile
|
||||
return React.useSyncExternalStore(subscribe, getSnapshot, () => false)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
|
||||
const subscribe = () => () => {}
|
||||
const getClientSnapshot = () => true
|
||||
const getServerSnapshot = () => false
|
||||
|
||||
export function useMounted() {
|
||||
return React.useSyncExternalStore(
|
||||
subscribe,
|
||||
getClientSnapshot,
|
||||
getServerSnapshot
|
||||
)
|
||||
}
|
||||
@@ -8,6 +8,8 @@ export const PLACEHOLDER_PATH = path.join(
|
||||
)
|
||||
|
||||
const COVER_IMAGE_SIZES = new Set([64, 128, 192, 256, 384, 512, 768, 1024])
|
||||
const COVER_CACHE_CONTROL =
|
||||
"public, max-age=300, stale-while-revalidate=86400"
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
".jpg": "image/jpeg",
|
||||
@@ -53,7 +55,7 @@ export async function serveCoverFile(
|
||||
return new Response(new Uint8Array(data), {
|
||||
headers: {
|
||||
"Content-Type": "image/webp",
|
||||
"Cache-Control": "public, max-age=86400, immutable",
|
||||
"Cache-Control": COVER_CACHE_CONTROL,
|
||||
},
|
||||
})
|
||||
} catch {
|
||||
@@ -66,7 +68,7 @@ export async function serveCoverFile(
|
||||
return new Response(data, {
|
||||
headers: {
|
||||
"Content-Type": contentTypeFor(coverPath),
|
||||
"Cache-Control": "public, max-age=86400, immutable",
|
||||
"Cache-Control": COVER_CACHE_CONTROL,
|
||||
},
|
||||
})
|
||||
} catch {
|
||||
|
||||
@@ -1,23 +1,27 @@
|
||||
import type { Doc } from "@otunes/convex/_generated/dataModel"
|
||||
import crypto from "node:crypto"
|
||||
import fs from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { spawn } from "node:child_process"
|
||||
import * as music from "music-metadata"
|
||||
|
||||
export const HLS_SEGMENT_SECONDS = 6
|
||||
const HLS_MAX_IDLE_MS = 30 * 60 * 1000
|
||||
|
||||
type HlsJob = {
|
||||
key: string
|
||||
lookupKey: string
|
||||
dir: string
|
||||
duration: number
|
||||
segmentCount: number
|
||||
startedAt: number
|
||||
lastTouchedAt: number
|
||||
processExited: boolean
|
||||
processExitCode: number | null
|
||||
}
|
||||
|
||||
const jobs = new Map<string, HlsJob>()
|
||||
const jobsByLookup = new Map<string, HlsJob>()
|
||||
let lastCleanupAt = 0
|
||||
|
||||
export function qualityKbps(quality: string | null) {
|
||||
if (quality === "low") {
|
||||
@@ -50,6 +54,14 @@ function hlsCacheRoot() {
|
||||
return "/tmp/otunes"
|
||||
}
|
||||
|
||||
function hlsLookupKey(
|
||||
songId: string,
|
||||
quality: string | null,
|
||||
preferAtmos: boolean
|
||||
) {
|
||||
return `${songId}:${quality ?? ""}:${preferAtmos ? "1" : "0"}`
|
||||
}
|
||||
|
||||
async function hlsJobKey(
|
||||
song: Doc<"songs">,
|
||||
sourcePath: string,
|
||||
@@ -75,8 +87,44 @@ export function hlsSegmentPath(job: HlsJob, segmentIndex: number) {
|
||||
}
|
||||
|
||||
async function touchHlsJob(job: HlsJob) {
|
||||
const now = new Date()
|
||||
await fs.utimes(job.dir, now, now).catch(() => {})
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
async function evictJob(job: HlsJob) {
|
||||
forgetJob(job)
|
||||
await fs.rm(job.dir, { recursive: true, force: true }).catch(() => {})
|
||||
}
|
||||
|
||||
async function cleanupIdleHlsJobs() {
|
||||
const now = Date.now()
|
||||
if (now - lastCleanupAt < 60_000) {
|
||||
return
|
||||
}
|
||||
lastCleanupAt = now
|
||||
|
||||
for (const job of [...jobs.values()]) {
|
||||
if (now - job.lastTouchedAt > HLS_MAX_IDLE_MS) {
|
||||
await evictJob(job)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function getExistingHlsJob(
|
||||
songId: string,
|
||||
quality: string | null,
|
||||
preferAtmos: boolean
|
||||
) {
|
||||
return jobsByLookup.get(hlsLookupKey(songId, quality, preferAtmos)) ?? null
|
||||
}
|
||||
|
||||
export async function waitForHlsSegment(
|
||||
@@ -114,15 +162,23 @@ export async function ensureHlsJob(
|
||||
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) {
|
||||
await touchHlsJob(existingJob)
|
||||
return existingJob
|
||||
try {
|
||||
await fs.access(existingJob.dir)
|
||||
await touchHlsJob(existingJob)
|
||||
return existingJob
|
||||
} catch {
|
||||
forgetJob(existingJob)
|
||||
}
|
||||
}
|
||||
|
||||
const metadata = await music.parseFile(sourcePath)
|
||||
@@ -132,14 +188,17 @@ export async function ensureHlsJob(
|
||||
await fs.mkdir(dir, { recursive: true })
|
||||
|
||||
const job: HlsJob = {
|
||||
key,
|
||||
lookupKey,
|
||||
dir,
|
||||
duration,
|
||||
segmentCount,
|
||||
startedAt: Date.now(),
|
||||
lastTouchedAt: Date.now(),
|
||||
processExited: false,
|
||||
processExitCode: null,
|
||||
}
|
||||
jobs.set(key, job)
|
||||
jobsByLookup.set(lookupKey, job)
|
||||
await touchHlsJob(job)
|
||||
|
||||
const ffmpegArgs = [
|
||||
|
||||
@@ -5,6 +5,7 @@ const nextConfig: NextConfig = {
|
||||
output: "standalone",
|
||||
outputFileTracingRoot: path.join(__dirname, "../../"),
|
||||
images: {
|
||||
minimumCacheTTL: 60,
|
||||
dangerouslyAllowSVG: true,
|
||||
contentDispositionType: "attachment",
|
||||
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use node"
|
||||
|
||||
import { api } from "./_generated/api"
|
||||
import { api, internal } from "./_generated/api"
|
||||
|
||||
import * as fs from "node:fs/promises"
|
||||
import * as fsSync from "node:fs"
|
||||
@@ -9,7 +9,7 @@ import * as path from "node:path"
|
||||
import { ConvexError } from "convex/values"
|
||||
|
||||
import type { Id } from "./_generated/dataModel"
|
||||
import { action, type ActionCtx } from "./_generated/server"
|
||||
import { action, internalAction, type ActionCtx } from "./_generated/server"
|
||||
|
||||
const DATA_DIR = process.env.CONVEX_SITE_URL?.includes("127.0.0.1")
|
||||
? "/Volumes/FastStorage/Apple Music"
|
||||
@@ -17,6 +17,13 @@ const DATA_DIR = process.env.CONVEX_SITE_URL?.includes("127.0.0.1")
|
||||
const HLS_CACHE_DIR = "/tmp/otunes"
|
||||
const HLS_MAX_IDLE_MS = 30 * 60 * 1000
|
||||
|
||||
async function requireAdmin(ctx: ActionCtx) {
|
||||
const user = await ctx.runQuery(api.auth.currentUser)
|
||||
if (!user?.isAdmin) {
|
||||
throw new ConvexError("Not authorized")
|
||||
}
|
||||
}
|
||||
|
||||
async function cleanHlsStreamsOlderThan(maxIdleMs: number) {
|
||||
const now = Date.now()
|
||||
let checked = 0
|
||||
@@ -27,9 +34,10 @@ async function cleanHlsStreamsOlderThan(maxIdleMs: number) {
|
||||
try {
|
||||
entries = await fs.readdir(HLS_CACHE_DIR, { withFileTypes: true })
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
||||
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
|
||||
throw error
|
||||
}
|
||||
return { checked, removed, failed }
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
@@ -72,13 +80,16 @@ async function syncArtistCover(
|
||||
const onDisk = await coverPathIfExists(diskPath)
|
||||
if (onDisk !== null) {
|
||||
if (dbCover !== onDisk) {
|
||||
await ctx.runMutation(api.library.updateArtistCover, {
|
||||
await ctx.runMutation(internal.library.updateArtistCover, {
|
||||
id,
|
||||
cover: onDisk,
|
||||
})
|
||||
}
|
||||
} else if (dbCover !== null && dbCover.includes(codec)) {
|
||||
await ctx.runMutation(api.library.updateArtistCover, { id, cover: null })
|
||||
await ctx.runMutation(internal.library.updateArtistCover, {
|
||||
id,
|
||||
cover: null,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,10 +103,16 @@ async function syncAlbumCover(
|
||||
const onDisk = await coverPathIfExists(diskPath)
|
||||
if (onDisk !== null) {
|
||||
if (dbCover !== onDisk) {
|
||||
await ctx.runMutation(api.library.updateAlbumCover, { id, cover: onDisk })
|
||||
await ctx.runMutation(internal.library.updateAlbumCover, {
|
||||
id,
|
||||
cover: onDisk,
|
||||
})
|
||||
}
|
||||
} else if (dbCover !== null && dbCover.includes(codec)) {
|
||||
await ctx.runMutation(api.library.updateAlbumCover, { id, cover: null })
|
||||
await ctx.runMutation(internal.library.updateAlbumCover, {
|
||||
id,
|
||||
cover: null,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,27 +120,30 @@ async function purgeRemovedSongs(ctx: ActionCtx, ids: Id<"songs">[]) {
|
||||
if (ids.length === 0) {
|
||||
return
|
||||
}
|
||||
await ctx.runMutation(api.library.purgeSongsFromUsersAndPlaylists, { ids })
|
||||
await ctx.runMutation(internal.library.purgeSongsFromUsersAndPlaylists, {
|
||||
ids,
|
||||
})
|
||||
}
|
||||
|
||||
async function purgeRemovedAlbums(ctx: ActionCtx, ids: Id<"albums">[]) {
|
||||
if (ids.length === 0) {
|
||||
return
|
||||
}
|
||||
await ctx.runMutation(api.library.purgeAlbumsFromUsers, { ids })
|
||||
await ctx.runMutation(internal.library.purgeAlbumsFromUsers, { ids })
|
||||
}
|
||||
|
||||
async function purgeRemovedArtists(ctx: ActionCtx, ids: Id<"artists">[]) {
|
||||
if (ids.length === 0) {
|
||||
return
|
||||
}
|
||||
await ctx.runMutation(api.library.purgeArtistsFromUsers, { ids })
|
||||
await ctx.runMutation(internal.library.purgeArtistsFromUsers, { ids })
|
||||
}
|
||||
|
||||
async function removeCodecFromDatabase(ctx: ActionCtx, codec: string) {
|
||||
const allSongs = await ctx.runQuery(api.library.getSongs)
|
||||
const allSongs = await ctx.runQuery(internal.library.getSongs)
|
||||
|
||||
const songsToRemove: Id<"songs">[] = []
|
||||
const songsToUpdate: { id: Id<"songs">; files: Record<string, string> }[] = []
|
||||
for (const song of allSongs) {
|
||||
if (!(codec in song.files)) {
|
||||
continue
|
||||
@@ -133,44 +153,49 @@ async function removeCodecFromDatabase(ctx: ActionCtx, codec: string) {
|
||||
if (Object.keys(update).length === 0) {
|
||||
songsToRemove.push(song._id)
|
||||
} else {
|
||||
await ctx.runMutation(api.library.changeFilesForSong, {
|
||||
songsToUpdate.push({
|
||||
id: song._id,
|
||||
files: update,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
await ctx.runMutation(internal.library.changeFilesForSongs, {
|
||||
songs: songsToUpdate,
|
||||
})
|
||||
await purgeRemovedSongs(ctx, songsToRemove)
|
||||
await ctx.runMutation(api.library.removeSongs, { ids: songsToRemove })
|
||||
await ctx.runMutation(internal.library.removeSongs, { ids: songsToRemove })
|
||||
|
||||
const allAlbums = await ctx.runQuery(api.library.getAlbums)
|
||||
const albumsToRemove: Id<"albums">[] = []
|
||||
for (const album of allAlbums) {
|
||||
const songsLeft = await ctx.runQuery(api.library.getSongsInAlbum, {
|
||||
albumID: album._id,
|
||||
})
|
||||
if (songsLeft.length === 0) {
|
||||
albumsToRemove.push(album._id)
|
||||
}
|
||||
}
|
||||
const allAlbums = await ctx.runQuery(internal.library.getAlbums)
|
||||
const removedSongIds = new Set(songsToRemove)
|
||||
const albumsWithSongs = new Set(
|
||||
allSongs.flatMap((song) =>
|
||||
removedSongIds.has(song._id) ? [] : [song.album]
|
||||
)
|
||||
)
|
||||
const albumsToRemove = allAlbums
|
||||
.filter((album) => !albumsWithSongs.has(album._id))
|
||||
.map((album) => album._id)
|
||||
await purgeRemovedAlbums(ctx, albumsToRemove)
|
||||
for (const albumId of albumsToRemove) {
|
||||
await ctx.runMutation(api.library.removeAlbum, { id: albumId })
|
||||
}
|
||||
await ctx.runMutation(internal.library.removeAlbums, { ids: albumsToRemove })
|
||||
|
||||
const allArtists = await ctx.runQuery(api.library.getArtists)
|
||||
for (const artist of allArtists) {
|
||||
const albumsLeft = await ctx.runQuery(api.library.getAlbumsInArtist, {
|
||||
artistID: artist._id,
|
||||
})
|
||||
if (albumsLeft.length === 0) {
|
||||
await purgeRemovedArtists(ctx, [artist._id])
|
||||
await ctx.runMutation(api.library.removeArtist, { id: artist._id })
|
||||
}
|
||||
}
|
||||
const allArtists = await ctx.runQuery(internal.library.getArtists)
|
||||
const removedAlbumIds = new Set(albumsToRemove)
|
||||
const artistsWithAlbums = new Set(
|
||||
allAlbums.flatMap((album) =>
|
||||
removedAlbumIds.has(album._id) ? [] : [album.artist]
|
||||
)
|
||||
)
|
||||
const artistsToRemove = allArtists
|
||||
.filter((artist) => !artistsWithAlbums.has(artist._id))
|
||||
.map((artist) => artist._id)
|
||||
await purgeRemovedArtists(ctx, artistsToRemove)
|
||||
await ctx.runMutation(internal.library.removeArtists, {
|
||||
ids: artistsToRemove,
|
||||
})
|
||||
}
|
||||
|
||||
export const updateLibrary = action({
|
||||
export const scheduledUpdateLibrary = internalAction({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const codecs = (await fs.readdir(DATA_DIR, { withFileTypes: true }))
|
||||
@@ -179,7 +204,7 @@ export const updateLibrary = action({
|
||||
|
||||
const dbCodecs = Array.from(
|
||||
new Map(
|
||||
(await ctx.runQuery(api.library.getSongs))
|
||||
(await ctx.runQuery(internal.library.getSongs))
|
||||
.map((song) => {
|
||||
return Object.keys(song.files)
|
||||
})
|
||||
@@ -196,9 +221,9 @@ export const updateLibrary = action({
|
||||
|
||||
// Removals
|
||||
for (const codec of codecs) {
|
||||
const dbArtists = await ctx.runQuery(api.library.getArtists)
|
||||
const dbAlbums = await ctx.runQuery(api.library.getAlbums)
|
||||
const dbSongs = await ctx.runQuery(api.library.getSongs)
|
||||
const dbArtists = await ctx.runQuery(internal.library.getArtists)
|
||||
const dbAlbums = await ctx.runQuery(internal.library.getAlbums)
|
||||
const dbSongs = await ctx.runQuery(internal.library.getSongs)
|
||||
|
||||
const dirtySongs = dbSongs
|
||||
.filter((song) => {
|
||||
@@ -218,43 +243,47 @@ export const updateLibrary = action({
|
||||
const songsToDeleteIDs = songsToDelete.map((song) => song.id)
|
||||
|
||||
await purgeRemovedSongs(ctx, songsToDeleteIDs)
|
||||
await ctx.runMutation(api.library.removeSongs, { ids: songsToDeleteIDs })
|
||||
await ctx.runMutation(api.library.changeFilesForSongs, {
|
||||
await ctx.runMutation(internal.library.removeSongs, {
|
||||
ids: songsToDeleteIDs,
|
||||
})
|
||||
await ctx.runMutation(internal.library.changeFilesForSongs, {
|
||||
songs: songsToUpdate,
|
||||
})
|
||||
|
||||
const albumsToDelete = []
|
||||
for (const dbAlbum of dbAlbums) {
|
||||
const songsLeft = await ctx.runQuery(api.library.getSongsInAlbum, {
|
||||
albumID: dbAlbum._id,
|
||||
})
|
||||
|
||||
if (songsLeft.length === 0) {
|
||||
albumsToDelete.push(dbAlbum._id)
|
||||
}
|
||||
}
|
||||
const deletedSongIds = new Set(songsToDeleteIDs)
|
||||
const albumsWithSongs = new Set(
|
||||
dbSongs.flatMap((song) =>
|
||||
deletedSongIds.has(song._id) ? [] : [song.album]
|
||||
)
|
||||
)
|
||||
const albumsToDelete = dbAlbums
|
||||
.filter((album) => !albumsWithSongs.has(album._id))
|
||||
.map((album) => album._id)
|
||||
await purgeRemovedAlbums(ctx, albumsToDelete)
|
||||
await ctx.runMutation(api.library.removeAlbums, { ids: albumsToDelete })
|
||||
await ctx.runMutation(internal.library.removeAlbums, {
|
||||
ids: albumsToDelete,
|
||||
})
|
||||
|
||||
const artistsToDelete = []
|
||||
for (const dbArtist of dbArtists) {
|
||||
const artistsLeft = await ctx.runQuery(api.library.getAlbumsInArtist, {
|
||||
artistID: dbArtist._id,
|
||||
})
|
||||
|
||||
if (artistsLeft.length === 0) {
|
||||
artistsToDelete.push(dbArtist._id)
|
||||
}
|
||||
}
|
||||
const deletedAlbumIds = new Set(albumsToDelete)
|
||||
const artistsWithAlbums = new Set(
|
||||
dbAlbums.flatMap((album) =>
|
||||
deletedAlbumIds.has(album._id) ? [] : [album.artist]
|
||||
)
|
||||
)
|
||||
const artistsToDelete = dbArtists
|
||||
.filter((artist) => !artistsWithAlbums.has(artist._id))
|
||||
.map((artist) => artist._id)
|
||||
await purgeRemovedArtists(ctx, artistsToDelete)
|
||||
await ctx.runMutation(api.library.removeArtists, { ids: artistsToDelete })
|
||||
await ctx.runMutation(internal.library.removeArtists, {
|
||||
ids: artistsToDelete,
|
||||
})
|
||||
}
|
||||
|
||||
// Additions
|
||||
for (const codec of codecs) {
|
||||
// Artists
|
||||
console.log(`${codec}: artists`)
|
||||
let dbArtists = await ctx.runQuery(api.library.getArtists)
|
||||
let dbArtists = await ctx.runQuery(internal.library.getArtists)
|
||||
const dbArtistFolders = dbArtists.map((artist) => artist.folder)
|
||||
const artists = (
|
||||
await fs.readdir(`${DATA_DIR}/${codec}`, { withFileTypes: true })
|
||||
@@ -312,21 +341,18 @@ export const updateLibrary = action({
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
await ctx.runMutation(api.library.createArtists, {
|
||||
await ctx.runMutation(internal.library.createArtists, {
|
||||
artists: newArtists,
|
||||
})
|
||||
dbArtists = await ctx.runQuery(api.library.getArtists)
|
||||
dbArtists = await ctx.runQuery(internal.library.getArtists)
|
||||
|
||||
// Albums
|
||||
console.log(`${codec}: albums`)
|
||||
let dbAlbums = await ctx.runQuery(api.library.getAlbums)
|
||||
let dbAlbums = await ctx.runQuery(internal.library.getAlbums)
|
||||
const newAlbums = []
|
||||
for (const dbArtist of dbArtists) {
|
||||
const dbAlbumsInArtist = await ctx.runQuery(
|
||||
api.library.getAlbumsInArtist,
|
||||
{
|
||||
artistID: dbArtist._id,
|
||||
}
|
||||
const dbAlbumsInArtist = dbAlbums.filter(
|
||||
(album) => album.artist === dbArtist._id
|
||||
)
|
||||
const dbAlbumFolders = dbAlbumsInArtist.map((album) => album.folder)
|
||||
|
||||
@@ -379,16 +405,18 @@ export const updateLibrary = action({
|
||||
folder: potentialAlbum,
|
||||
cover,
|
||||
year: metadata.common.year || 2026,
|
||||
date: metadata.common.date || `01-01-${metadata.common.year || 2026}`,
|
||||
date:
|
||||
metadata.common.date || `01-01-${metadata.common.year || 2026}`,
|
||||
artist: dbArtist._id,
|
||||
})
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
await ctx.runMutation(api.library.createAlbums, {
|
||||
await ctx.runMutation(internal.library.createAlbums, {
|
||||
albums: newAlbums,
|
||||
})
|
||||
dbAlbums = await ctx.runQuery(api.library.getAlbums)
|
||||
dbAlbums = await ctx.runQuery(internal.library.getAlbums)
|
||||
const dbSongs = await ctx.runQuery(internal.library.getSongs)
|
||||
|
||||
const dbAlbumsArtists = dbAlbums.map((album) => {
|
||||
return {
|
||||
@@ -434,9 +462,9 @@ export const updateLibrary = action({
|
||||
const newSongs = []
|
||||
const updateSongs = []
|
||||
for (const dbAlbum of dbAlbumsArtists) {
|
||||
const dbSongsInAlbum = await ctx.runQuery(api.library.getSongsInAlbum, {
|
||||
albumID: dbAlbum._id,
|
||||
})
|
||||
const dbSongsInAlbum = dbSongs.filter(
|
||||
(song) => song.album === dbAlbum._id
|
||||
)
|
||||
const dbAlreadyTracked = dbSongsInAlbum
|
||||
.filter((song) => codec in song.files)
|
||||
.map((song) => song.files[codec])
|
||||
@@ -525,15 +553,17 @@ export const updateLibrary = action({
|
||||
: metadata.common.disk.no,
|
||||
track: metadata.common.track.no || 0,
|
||||
year: metadata.common.year || 2026,
|
||||
date: metadata.common.date || `01-01-${metadata.common.year || 2026}`,
|
||||
date:
|
||||
metadata.common.date ||
|
||||
`01-01-${metadata.common.year || 2026}`,
|
||||
genres: metadata.common.genre || [],
|
||||
})
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
await ctx.runMutation(api.library.createSongs, { songs: newSongs })
|
||||
await ctx.runMutation(api.library.changeFilesForSongs, {
|
||||
await ctx.runMutation(internal.library.createSongs, { songs: newSongs })
|
||||
await ctx.runMutation(internal.library.changeFilesForSongs, {
|
||||
songs: updateSongs,
|
||||
})
|
||||
}
|
||||
@@ -542,7 +572,15 @@ export const updateLibrary = action({
|
||||
},
|
||||
})
|
||||
|
||||
export const cleanupHlsStreams = action({
|
||||
export const updateLibrary = action({
|
||||
args: {},
|
||||
handler: async (ctx): Promise<string> => {
|
||||
await requireAdmin(ctx)
|
||||
return ctx.runAction(internal.actions.scheduledUpdateLibrary)
|
||||
},
|
||||
})
|
||||
|
||||
export const cleanupHlsStreams = internalAction({
|
||||
args: {},
|
||||
handler: async () => {
|
||||
return await cleanHlsStreamsOlderThan(HLS_MAX_IDLE_MS)
|
||||
@@ -552,11 +590,7 @@ export const cleanupHlsStreams = action({
|
||||
export const adminCleanupHlsStreams = action({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const user = await ctx.runQuery(api.auth.currentUser)
|
||||
if (!user?.isAdmin) {
|
||||
throw new ConvexError("Not authorized")
|
||||
}
|
||||
|
||||
await requireAdmin(ctx)
|
||||
return await cleanHlsStreamsOlderThan(HLS_MAX_IDLE_MS)
|
||||
},
|
||||
})
|
||||
@@ -2,6 +2,7 @@ import { convexAuth, getAuthUserId } from "@convex-dev/auth/server"
|
||||
import { ConvexError } from "convex/values"
|
||||
import { Password } from "@convex-dev/auth/providers/Password"
|
||||
import { query } from "./_generated/server"
|
||||
import type { MutationCtx } from "./_generated/server"
|
||||
|
||||
export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({
|
||||
providers: [
|
||||
@@ -15,36 +16,34 @@ export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({
|
||||
}),
|
||||
],
|
||||
callbacks: {
|
||||
async afterUserCreatedOrUpdated(ctx, { userId, existingUserId }) {
|
||||
async afterUserCreatedOrUpdated(ctx, { userId, existingUserId, profile }) {
|
||||
const db = ctx.db as MutationCtx["db"]
|
||||
if (existingUserId === null) {
|
||||
const settings = await ctx.db.query("appSettings").first()
|
||||
const settings = await db.query("appSettings").first()
|
||||
if (settings?.disableAccountCreation) {
|
||||
const sessions = await ctx.db
|
||||
const sessions = await db
|
||||
.query("authSessions")
|
||||
.filter((q) => q.eq(q.field("userId"), userId))
|
||||
.withIndex("userId", (q) => q.eq("userId", userId))
|
||||
.collect()
|
||||
for (const session of sessions) {
|
||||
await ctx.db.delete(session._id)
|
||||
await db.delete(session._id)
|
||||
}
|
||||
const accounts = await ctx.db
|
||||
const accounts = await db
|
||||
.query("authAccounts")
|
||||
.filter((q) => q.eq(q.field("userId"), userId))
|
||||
.withIndex("userIdAndProvider", (q) => q.eq("userId", userId))
|
||||
.collect()
|
||||
for (const account of accounts) {
|
||||
await ctx.db.delete(account._id)
|
||||
await db.delete(account._id)
|
||||
}
|
||||
await ctx.db.delete(userId)
|
||||
await db.delete(userId)
|
||||
throw new ConvexError("Account creation is currently disabled")
|
||||
}
|
||||
|
||||
const users = await ctx.db.query("users").collect()
|
||||
if (users.length === 1) {
|
||||
await ctx.db.patch(userId, { isAdmin: true })
|
||||
} else {
|
||||
await ctx.db.patch(userId, { isAdmin: false })
|
||||
}
|
||||
|
||||
await ctx.db.patch(userId, { playbackQuality: "high" })
|
||||
const users = await db.query("users").take(2)
|
||||
await db.patch(userId, {
|
||||
isAdmin: users.length === 1 || profile.isAdmin === true,
|
||||
playbackQuality: "high",
|
||||
})
|
||||
return
|
||||
}
|
||||
},
|
||||
@@ -58,6 +57,20 @@ export const currentUser = query({
|
||||
if (userId === null) {
|
||||
return null
|
||||
}
|
||||
return await ctx.db.get(userId)
|
||||
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
_id: user._id,
|
||||
name: user.name,
|
||||
image: user.image,
|
||||
email: user.email,
|
||||
isAdmin: user.isAdmin,
|
||||
playbackQuality: user.playbackQuality,
|
||||
preferAtmos: user.preferAtmos,
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -1,18 +1,12 @@
|
||||
import { cronJobs } from "convex/server"
|
||||
import { api } from "./_generated/api"
|
||||
import { internal } from "./_generated/api"
|
||||
|
||||
const crons = cronJobs()
|
||||
|
||||
crons.interval(
|
||||
"update library file tracking",
|
||||
{ minutes: 15 },
|
||||
api.actions.updateLibrary
|
||||
)
|
||||
|
||||
crons.interval(
|
||||
"cleanup idle hls streams",
|
||||
{ minutes: 15 },
|
||||
api.actions.cleanupHlsStreams
|
||||
internal.actions.scheduledUpdateLibrary
|
||||
)
|
||||
|
||||
export default crons
|
||||
@@ -4,8 +4,8 @@ import { paginationOptsValidator } from "convex/server"
|
||||
import type { Doc, Id } from "./_generated/dataModel"
|
||||
import type { MutationCtx, QueryCtx } from "./_generated/server"
|
||||
import { mutation, query } from "./_generated/server"
|
||||
import type { BrowsePlaylistDetail, BrowsePlaylistSummary, BrowseSong } from "./library"
|
||||
import { paginateSlice } from "./library"
|
||||
import type { BrowsePlaylistDetail, BrowsePlaylistSummary } from "./library"
|
||||
import { browseSongsFromIds, paginateSlice } from "./library"
|
||||
|
||||
function uniqueIds<T extends string>(ids: T[]): T[] {
|
||||
return [...new Set(ids)]
|
||||
@@ -103,65 +103,27 @@ async function cascadeUpFromSongs(
|
||||
|
||||
const albumIds = new Set(songs.map((song) => song.album))
|
||||
for (const albumId of albumIds) {
|
||||
albums = await promoteAlbumIfAllSongsFavorited(ctx, favoriteSongs, albums, albumId)
|
||||
albums = await promoteAlbumIfAllSongsFavorited(
|
||||
ctx,
|
||||
favoriteSongs,
|
||||
albums,
|
||||
albumId
|
||||
)
|
||||
}
|
||||
|
||||
const artistIds = new Set(songs.map((song) => song.albumArtist))
|
||||
for (const artistId of artistIds) {
|
||||
artists = await promoteArtistIfAllAlbumsFavorited(ctx, albums, artists, artistId)
|
||||
artists = await promoteArtistIfAllAlbumsFavorited(
|
||||
ctx,
|
||||
albums,
|
||||
artists,
|
||||
artistId
|
||||
)
|
||||
}
|
||||
|
||||
return { favoriteAlbums: albums, favoriteArtists: artists }
|
||||
}
|
||||
|
||||
function toBrowseArtist(artist: Doc<"artists">) {
|
||||
return {
|
||||
id: artist._id,
|
||||
name: artist.name,
|
||||
photo: artist.cover,
|
||||
}
|
||||
}
|
||||
|
||||
async function loadArtistMap(ctx: QueryCtx) {
|
||||
const artists = await ctx.db.query("artists").collect()
|
||||
return new Map(artists.map((artist) => [artist._id, artist]))
|
||||
}
|
||||
|
||||
async function loadAlbumMap(ctx: QueryCtx) {
|
||||
const albums = await ctx.db.query("albums").collect()
|
||||
return new Map(albums.map((album) => [album._id, album]))
|
||||
}
|
||||
|
||||
async function toBrowseSong(
|
||||
ctx: QueryCtx,
|
||||
songId: Id<"songs">,
|
||||
artistMap: Map<Id<"artists">, Doc<"artists">>,
|
||||
albumMap: Map<Id<"albums">, Doc<"albums">>
|
||||
): Promise<BrowseSong | null> {
|
||||
const song = await ctx.db.get("songs", songId)
|
||||
if (!song) {
|
||||
return null
|
||||
}
|
||||
|
||||
const album = albumMap.get(song.album)
|
||||
const albumArtist = artistMap.get(song.albumArtist)
|
||||
if (!album || !albumArtist) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
id: song._id,
|
||||
title: song.name,
|
||||
artist: toBrowseArtist(albumArtist),
|
||||
album: {
|
||||
id: album._id,
|
||||
title: album.name,
|
||||
cover: album.cover,
|
||||
},
|
||||
durationSeconds: Math.round(song.length),
|
||||
}
|
||||
}
|
||||
|
||||
export const getUserFavorites = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
@@ -232,16 +194,7 @@ export const browseFavoritesPlaylistDetail = query({
|
||||
return null
|
||||
}
|
||||
|
||||
const artistMap = await loadArtistMap(ctx)
|
||||
const albumMap = await loadAlbumMap(ctx)
|
||||
|
||||
const songs: BrowseSong[] = []
|
||||
for (const songId of summary.songIds) {
|
||||
const song = await toBrowseSong(ctx, songId, artistMap, albumMap)
|
||||
if (song) {
|
||||
songs.push(song)
|
||||
}
|
||||
}
|
||||
const songs = await browseSongsFromIds(ctx, summary.songIds)
|
||||
|
||||
return {
|
||||
id: summary.id,
|
||||
@@ -265,16 +218,7 @@ export const browseFavoritesSongsPaginated = query({
|
||||
}
|
||||
|
||||
const slice = paginateSlice(summary.songIds, args.paginationOpts)
|
||||
const artistMap = await loadArtistMap(ctx)
|
||||
const albumMap = await loadAlbumMap(ctx)
|
||||
|
||||
const page: BrowseSong[] = []
|
||||
for (const songId of slice.page) {
|
||||
const song = await toBrowseSong(ctx, songId, artistMap, albumMap)
|
||||
if (song) {
|
||||
page.push(song)
|
||||
}
|
||||
}
|
||||
const page = await browseSongsFromIds(ctx, slice.page)
|
||||
|
||||
return {
|
||||
...slice,
|
||||
@@ -323,15 +267,19 @@ export const favoriteSongs = mutation({
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
const songs: Doc<"songs">[] = []
|
||||
for (const id of songIds) {
|
||||
const song = await ctx.db.get("songs", id)
|
||||
if (song) {
|
||||
songs.push(song)
|
||||
}
|
||||
}
|
||||
const uniqueRequestedIds = uniqueIds(songIds)
|
||||
const loadedSongs = await Promise.all(
|
||||
uniqueRequestedIds.map((id) => ctx.db.get("songs", id))
|
||||
)
|
||||
const songs = loadedSongs.filter(
|
||||
(song): song is Doc<"songs"> => song !== null
|
||||
)
|
||||
const validSongIds = songs.map((song) => song._id)
|
||||
|
||||
const favoriteSongs = uniqueIds([...(user.favoriteSongs ?? []), ...songIds])
|
||||
const favoriteSongs = uniqueIds([
|
||||
...(user.favoriteSongs ?? []),
|
||||
...validSongIds,
|
||||
])
|
||||
const cascaded = await cascadeUpFromSongs(
|
||||
ctx,
|
||||
favoriteSongs,
|
||||
@@ -351,48 +299,48 @@ export const favoriteSongs = mutation({
|
||||
export const unfavoriteSong = mutation({
|
||||
args: { songId: v.id("songs") },
|
||||
handler: async (ctx, { songId }) => {
|
||||
await unfavoriteSongHandler(ctx, songId)
|
||||
await unfavoriteSongsHandler(ctx, [songId])
|
||||
},
|
||||
})
|
||||
|
||||
export const unfavoriteSongs = mutation({
|
||||
args: { songIds: v.array(v.id("songs")) },
|
||||
handler: async (ctx, { songIds }) => {
|
||||
for (const songId of songIds) {
|
||||
await unfavoriteSongHandler(ctx, songId)
|
||||
}
|
||||
await unfavoriteSongsHandler(ctx, songIds)
|
||||
},
|
||||
})
|
||||
|
||||
async function unfavoriteSongHandler(ctx: MutationCtx, songId: Id<"songs">) {
|
||||
async function unfavoriteSongsHandler(
|
||||
ctx: MutationCtx,
|
||||
songIds: Id<"songs">[]
|
||||
) {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get("users", userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
const song = await ctx.db.get("songs", songId)
|
||||
if (!song) {
|
||||
return
|
||||
}
|
||||
|
||||
const favoriteSongs = (user.favoriteSongs ?? []).filter((id) => id !== songId)
|
||||
let favoriteAlbums = user.favoriteAlbums ?? []
|
||||
let favoriteArtists = user.favoriteArtists ?? []
|
||||
|
||||
if (favoriteAlbums.includes(song.album)) {
|
||||
favoriteAlbums = favoriteAlbums.filter((id) => id !== song.album)
|
||||
}
|
||||
|
||||
if (favoriteArtists.includes(song.albumArtist)) {
|
||||
favoriteArtists = favoriteArtists.filter((id) => id !== song.albumArtist)
|
||||
favoriteAlbums = favoriteAlbums.filter((id) => id !== song.album)
|
||||
}
|
||||
const removeSongs = new Set(songIds)
|
||||
const loadedSongs = await Promise.all(
|
||||
[...removeSongs].map((songId) => ctx.db.get("songs", songId))
|
||||
)
|
||||
const removeAlbums = new Set(
|
||||
loadedSongs.flatMap((song) => (song ? [song.album] : []))
|
||||
)
|
||||
const removeArtists = new Set(
|
||||
loadedSongs.flatMap((song) => (song ? [song.albumArtist] : []))
|
||||
)
|
||||
|
||||
await ctx.db.patch(userId, {
|
||||
favoriteSongs,
|
||||
favoriteAlbums,
|
||||
favoriteArtists,
|
||||
favoriteSongs: (user.favoriteSongs ?? []).filter(
|
||||
(id) => !removeSongs.has(id)
|
||||
),
|
||||
favoriteAlbums: (user.favoriteAlbums ?? []).filter(
|
||||
(id) => !removeAlbums.has(id)
|
||||
),
|
||||
favoriteArtists: (user.favoriteArtists ?? []).filter(
|
||||
(id) => !removeArtists.has(id)
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -446,8 +394,12 @@ export const unfavoriteAlbum = mutation({
|
||||
const albumSongIds = await getSongIdsForAlbum(ctx, albumId)
|
||||
const removeSongs = new Set(albumSongIds)
|
||||
|
||||
const favoriteAlbums = (user.favoriteAlbums ?? []).filter((id) => id !== albumId)
|
||||
const favoriteSongs = (user.favoriteSongs ?? []).filter((id) => !removeSongs.has(id))
|
||||
const favoriteAlbums = (user.favoriteAlbums ?? []).filter(
|
||||
(id) => id !== albumId
|
||||
)
|
||||
const favoriteSongs = (user.favoriteSongs ?? []).filter(
|
||||
(id) => !removeSongs.has(id)
|
||||
)
|
||||
let favoriteArtists = user.favoriteArtists ?? []
|
||||
|
||||
if (favoriteArtists.includes(album.artist)) {
|
||||
@@ -502,9 +454,15 @@ export const unfavoriteArtist = mutation({
|
||||
const removeSongs = new Set(songIds)
|
||||
|
||||
await ctx.db.patch(userId, {
|
||||
favoriteArtists: (user.favoriteArtists ?? []).filter((id) => id !== artistId),
|
||||
favoriteAlbums: (user.favoriteAlbums ?? []).filter((id) => !removeAlbums.has(id)),
|
||||
favoriteSongs: (user.favoriteSongs ?? []).filter((id) => !removeSongs.has(id)),
|
||||
favoriteArtists: (user.favoriteArtists ?? []).filter(
|
||||
(id) => id !== artistId
|
||||
),
|
||||
favoriteAlbums: (user.favoriteAlbums ?? []).filter(
|
||||
(id) => !removeAlbums.has(id)
|
||||
),
|
||||
favoriteSongs: (user.favoriteSongs ?? []).filter(
|
||||
(id) => !removeSongs.has(id)
|
||||
),
|
||||
})
|
||||
},
|
||||
})
|
||||
+395
-228
File diff suppressed because it is too large.
Load diff
@@ -7,6 +7,7 @@ import { mutation, query } from "./_generated/server"
|
||||
import type { QueueSong } from "./types"
|
||||
import {
|
||||
browseSongsFromIds,
|
||||
compareAlbumSongs,
|
||||
getSortedLibrarySongIds,
|
||||
songsSortDirectionValidator,
|
||||
songsSortKeyValidator,
|
||||
@@ -99,6 +100,28 @@ function uniqueSongIds(songIds: Id<"songs">[]) {
|
||||
return [...new Set(songIds)]
|
||||
}
|
||||
|
||||
function haveSameSongCounts(first: Id<"songs">[], second: Id<"songs">[]) {
|
||||
if (first.length !== second.length) {
|
||||
return false
|
||||
}
|
||||
const counts = new Map<Id<"songs">, number>()
|
||||
for (const songId of first) {
|
||||
counts.set(songId, (counts.get(songId) ?? 0) + 1)
|
||||
}
|
||||
for (const songId of second) {
|
||||
const count = counts.get(songId)
|
||||
if (!count) {
|
||||
return false
|
||||
}
|
||||
if (count === 1) {
|
||||
counts.delete(songId)
|
||||
} else {
|
||||
counts.set(songId, count - 1)
|
||||
}
|
||||
}
|
||||
return counts.size === 0
|
||||
}
|
||||
|
||||
function appendToQueueHistory(
|
||||
history: Id<"songs">[],
|
||||
songId: Id<"songs">
|
||||
@@ -263,6 +286,7 @@ export const playShuffled = mutation({
|
||||
const queue = shuffleArray(uniqueSongIds(songIds))
|
||||
await setQueueState(ctx, userId, {
|
||||
songQueue: queue,
|
||||
shuffleEnabled: true,
|
||||
resetHistory: true,
|
||||
})
|
||||
await recordPlaybackStart(ctx, userId, { songIds: queue, playlistId })
|
||||
@@ -350,6 +374,135 @@ export const playFromSong = mutation({
|
||||
},
|
||||
})
|
||||
|
||||
async function albumSongIds(ctx: MutationCtx, albumId: Id<"albums">) {
|
||||
const songs = await ctx.db
|
||||
.query("songs")
|
||||
.withIndex("by_album", (q) => q.eq("album", albumId))
|
||||
.collect()
|
||||
songs.sort(compareAlbumSongs)
|
||||
return songs.map((song) => song._id)
|
||||
}
|
||||
|
||||
async function orderedArtistSongIds(
|
||||
ctx: MutationCtx,
|
||||
artistId: Id<"artists">
|
||||
) {
|
||||
const songs = await ctx.db
|
||||
.query("songs")
|
||||
.withIndex("by_artist", (q) => q.eq("albumArtist", artistId))
|
||||
.collect()
|
||||
|
||||
const albums = await ctx.db
|
||||
.query("albums")
|
||||
.withIndex("by_artist", (q) => q.eq("artist", artistId))
|
||||
.collect()
|
||||
const albumMap = new Map(albums.map((album) => [album._id, album]))
|
||||
|
||||
songs.sort((a, b) => {
|
||||
const albumA = albumMap.get(a.album)?.name ?? ""
|
||||
const albumB = albumMap.get(b.album)?.name ?? ""
|
||||
if (albumA !== albumB) {
|
||||
return albumA.localeCompare(albumB)
|
||||
}
|
||||
if (a.track !== b.track) {
|
||||
return a.track - b.track
|
||||
}
|
||||
return a.name.localeCompare(b.name)
|
||||
})
|
||||
|
||||
return songs.map((song) => song._id)
|
||||
}
|
||||
|
||||
async function playCollection(
|
||||
ctx: MutationCtx,
|
||||
options: {
|
||||
songIds: Id<"songs">[]
|
||||
shuffled: boolean
|
||||
playlistId?: Id<"playlists">
|
||||
}
|
||||
) {
|
||||
const userId = await requireAuth(ctx)
|
||||
const unique = uniqueSongIds(options.songIds)
|
||||
if (unique.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const queue = options.shuffled ? shuffleArray(unique) : unique
|
||||
await setQueueState(ctx, userId, {
|
||||
songQueue: queue,
|
||||
shuffleEnabled: options.shuffled,
|
||||
resetHistory: true,
|
||||
})
|
||||
await recordPlaybackStart(ctx, userId, {
|
||||
songIds: queue,
|
||||
playlistId: options.playlistId,
|
||||
})
|
||||
}
|
||||
|
||||
export const playAlbum = mutation({
|
||||
args: { albumId: v.id("albums") },
|
||||
handler: async (ctx, { albumId }) => {
|
||||
await playCollection(ctx, {
|
||||
songIds: await albumSongIds(ctx, albumId),
|
||||
shuffled: false,
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export const playAlbumShuffled = mutation({
|
||||
args: { albumId: v.id("albums") },
|
||||
handler: async (ctx, { albumId }) => {
|
||||
await playCollection(ctx, {
|
||||
songIds: await albumSongIds(ctx, albumId),
|
||||
shuffled: true,
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export const playArtist = mutation({
|
||||
args: { artistId: v.id("artists") },
|
||||
handler: async (ctx, { artistId }) => {
|
||||
await playCollection(ctx, {
|
||||
songIds: await orderedArtistSongIds(ctx, artistId),
|
||||
shuffled: false,
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export const playArtistShuffled = mutation({
|
||||
args: { artistId: v.id("artists") },
|
||||
handler: async (ctx, { artistId }) => {
|
||||
await playCollection(ctx, {
|
||||
songIds: await orderedArtistSongIds(ctx, artistId),
|
||||
shuffled: true,
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export const playPlaylist = mutation({
|
||||
args: { playlistId: v.id("playlists") },
|
||||
handler: async (ctx, { playlistId }) => {
|
||||
const playlist = await ctx.db.get("playlists", playlistId)
|
||||
await playCollection(ctx, {
|
||||
songIds: playlist?.songs ?? [],
|
||||
shuffled: false,
|
||||
playlistId,
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export const playPlaylistShuffled = mutation({
|
||||
args: { playlistId: v.id("playlists") },
|
||||
handler: async (ctx, { playlistId }) => {
|
||||
const playlist = await ctx.db.get("playlists", playlistId)
|
||||
await playCollection(ctx, {
|
||||
songIds: playlist?.songs ?? [],
|
||||
shuffled: true,
|
||||
playlistId,
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export const playFromLibrarySong = mutation({
|
||||
args: {
|
||||
songId: v.id("songs"),
|
||||
@@ -440,8 +593,10 @@ export const reorderQueue = mutation({
|
||||
}
|
||||
|
||||
const queue = user.songQueue ?? []
|
||||
const currentSongChanged =
|
||||
songIds.length > 0 && songIds[0] !== queue[0]
|
||||
if (!haveSameSongCounts(queue, songIds)) {
|
||||
throw new ConvexError("Invalid queue order")
|
||||
}
|
||||
const currentSongChanged = songIds.length > 0 && songIds[0] !== queue[0]
|
||||
const history =
|
||||
currentSongChanged && queue.length > 0
|
||||
? appendToQueueHistory(user.queueHistory ?? [], queue[0])
|
||||
@@ -580,7 +735,10 @@ export const getSongProgress = query({
|
||||
})
|
||||
|
||||
export const updateSongProgress = mutation({
|
||||
args: { progressSeconds: v.number() },
|
||||
args: {
|
||||
songId: v.id("songs"),
|
||||
progressSeconds: v.number(),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get(userId)
|
||||
@@ -588,6 +746,10 @@ export const updateSongProgress = mutation({
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
if ((user.songQueue ?? [])[0] !== args.songId) {
|
||||
return
|
||||
}
|
||||
|
||||
await ctx.db.patch(userId, { currentSongProgress: args.progressSeconds })
|
||||
},
|
||||
})
|
||||
@@ -5,63 +5,13 @@ import type { Doc, Id } from "./_generated/dataModel"
|
||||
import type { MutationCtx, QueryCtx } from "./_generated/server"
|
||||
import { mutation, query } from "./_generated/server"
|
||||
import type {
|
||||
BrowseArtist,
|
||||
BrowsePlaylistDetail,
|
||||
BrowsePlaylistSummary,
|
||||
BrowseSong,
|
||||
OwnedPlaylistForAdd,
|
||||
PlaylistSummary,
|
||||
SidebarPlaylists,
|
||||
} from "./library"
|
||||
import { compareAlbumSongs, paginateSlice } from "./library"
|
||||
|
||||
function toBrowseArtist(artist: Doc<"artists">): BrowseArtist {
|
||||
return {
|
||||
id: artist._id,
|
||||
name: artist.name,
|
||||
photo: artist.cover,
|
||||
}
|
||||
}
|
||||
|
||||
async function loadArtistMap(ctx: QueryCtx) {
|
||||
const artists = await ctx.db.query("artists").collect()
|
||||
return new Map(artists.map((artist) => [artist._id, artist]))
|
||||
}
|
||||
|
||||
async function toBrowseSong(
|
||||
ctx: QueryCtx,
|
||||
songId: Id<"songs">,
|
||||
artistMap: Map<Id<"artists">, Doc<"artists">>,
|
||||
albumMap: Map<Id<"albums">, Doc<"albums">>
|
||||
): Promise<BrowseSong | null> {
|
||||
const song = await ctx.db.get("songs", songId)
|
||||
if (!song) {
|
||||
return null
|
||||
}
|
||||
|
||||
const album = albumMap.get(song.album)
|
||||
const albumArtist = artistMap.get(song.albumArtist)
|
||||
if (!album || !albumArtist) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
id: song._id,
|
||||
title: song.name,
|
||||
artist: toBrowseArtist(albumArtist),
|
||||
album: {
|
||||
id: album._id,
|
||||
title: album.name,
|
||||
cover: album.cover,
|
||||
},
|
||||
durationSeconds: Math.round(song.length),
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAlbumMap(ctx: QueryCtx) {
|
||||
const albums = await ctx.db.query("albums").collect()
|
||||
return new Map(albums.map((album) => [album._id, album]))
|
||||
}
|
||||
import { browseSongsFromIds, compareAlbumSongs, paginateSlice } from "./library"
|
||||
|
||||
function toPlaylistSummary(
|
||||
playlist: Doc<"playlists">,
|
||||
@@ -75,6 +25,33 @@ function toPlaylistSummary(
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPlaylists(ctx: QueryCtx, playlistIds: Id<"playlists">[]) {
|
||||
const playlists = await Promise.all(
|
||||
[...new Set(playlistIds)].map((playlistId) =>
|
||||
ctx.db.get("playlists", playlistId)
|
||||
)
|
||||
)
|
||||
return playlists.filter(
|
||||
(playlist): playlist is Doc<"playlists"> => playlist !== null
|
||||
)
|
||||
}
|
||||
|
||||
async function summarizePlaylists(
|
||||
ctx: QueryCtx,
|
||||
playlists: Doc<"playlists">[]
|
||||
) {
|
||||
const ownerIds = [...new Set(playlists.map((playlist) => playlist.owner))]
|
||||
const owners = await Promise.all(
|
||||
ownerIds.map((ownerId) => ctx.db.get("users", ownerId))
|
||||
)
|
||||
const ownerMap = new Map(
|
||||
owners.flatMap((owner) => (owner ? [[owner._id, owner] as const] : []))
|
||||
)
|
||||
return playlists.map((playlist) =>
|
||||
toPlaylistSummary(playlist, ownerMap.get(playlist.owner)?.name ?? "Unknown")
|
||||
)
|
||||
}
|
||||
|
||||
async function requireAuth(ctx: MutationCtx) {
|
||||
const userId = await getAuthUserId(ctx)
|
||||
if (userId === null) {
|
||||
@@ -145,18 +122,10 @@ export const browsePlaylistDetail = query({
|
||||
return null
|
||||
}
|
||||
|
||||
const songs: BrowseSong[] = []
|
||||
if (args.includeSongs ?? true) {
|
||||
const artistMap = await loadArtistMap(ctx)
|
||||
const albumMap = await loadAlbumMap(ctx)
|
||||
|
||||
for (const songId of summary.songIds) {
|
||||
const song = await toBrowseSong(ctx, songId, artistMap, albumMap)
|
||||
if (song) {
|
||||
songs.push(song)
|
||||
}
|
||||
}
|
||||
}
|
||||
const songs =
|
||||
(args.includeSongs ?? true)
|
||||
? await browseSongsFromIds(ctx, summary.songIds)
|
||||
: []
|
||||
|
||||
return {
|
||||
id: summary.id,
|
||||
@@ -182,16 +151,7 @@ export const browsePlaylistSongsPaginated = query({
|
||||
}
|
||||
|
||||
const slice = paginateSlice(playlist.songs, args.paginationOpts)
|
||||
const artistMap = await loadArtistMap(ctx)
|
||||
const albumMap = await loadAlbumMap(ctx)
|
||||
|
||||
const page: BrowseSong[] = []
|
||||
for (const songId of slice.page) {
|
||||
const song = await toBrowseSong(ctx, songId, artistMap, albumMap)
|
||||
if (song) {
|
||||
page.push(song)
|
||||
}
|
||||
}
|
||||
const page = await browseSongsFromIds(ctx, slice.page)
|
||||
|
||||
return {
|
||||
...slice,
|
||||
@@ -247,18 +207,10 @@ export const listSidebarPlaylists = query({
|
||||
.map((playlist) => toPlaylistSummary(playlist, user.name))
|
||||
.sort((a, b) => a.title.localeCompare(b.title))
|
||||
|
||||
const subscribed: PlaylistSummary[] = []
|
||||
for (const playlistId of user.subscribedPlaylists ?? []) {
|
||||
const playlist = await ctx.db.get("playlists", playlistId)
|
||||
if (!playlist || playlist.owner === userId) {
|
||||
continue
|
||||
}
|
||||
const owner = await ctx.db.get("users", playlist.owner)
|
||||
subscribed.push(
|
||||
toPlaylistSummary(playlist, owner?.name ?? "Unknown")
|
||||
)
|
||||
}
|
||||
|
||||
const subscribedDocs = (
|
||||
await loadPlaylists(ctx, user.subscribedPlaylists ?? [])
|
||||
).filter((playlist) => playlist.owner !== userId)
|
||||
const subscribed = await summarizePlaylists(ctx, subscribedDocs)
|
||||
subscribed.sort((a, b) => a.title.localeCompare(b.title))
|
||||
|
||||
return { owned, subscribed }
|
||||
@@ -297,19 +249,14 @@ export const searchPlaylists = query({
|
||||
}
|
||||
}
|
||||
|
||||
for (const playlistId of user.subscribedPlaylists ?? []) {
|
||||
if (ownedIds.has(playlistId)) {
|
||||
continue
|
||||
}
|
||||
const playlist = await ctx.db.get("playlists", playlistId)
|
||||
if (!playlist || !playlist.name.toLowerCase().includes(queryText)) {
|
||||
continue
|
||||
}
|
||||
const owner = await ctx.db.get("users", playlist.owner)
|
||||
matches.push(
|
||||
toPlaylistSummary(playlist, owner?.name ?? "Unknown")
|
||||
)
|
||||
}
|
||||
const subscribedDocs = (
|
||||
await loadPlaylists(ctx, user.subscribedPlaylists ?? [])
|
||||
).filter(
|
||||
(playlist) =>
|
||||
!ownedIds.has(playlist._id) &&
|
||||
playlist.name.toLowerCase().includes(queryText)
|
||||
)
|
||||
matches.push(...(await summarizePlaylists(ctx, subscribedDocs)))
|
||||
|
||||
return matches.sort((a, b) => a.title.localeCompare(b.title))
|
||||
},
|
||||
@@ -338,19 +285,10 @@ export const listAllPlaylists = query({
|
||||
toPlaylistSummary(playlist, user.name)
|
||||
)
|
||||
|
||||
for (const playlistId of user.subscribedPlaylists ?? []) {
|
||||
if (ownedIds.has(playlistId)) {
|
||||
continue
|
||||
}
|
||||
const playlist = await ctx.db.get("playlists", playlistId)
|
||||
if (!playlist) {
|
||||
continue
|
||||
}
|
||||
const owner = await ctx.db.get("users", playlist.owner)
|
||||
summaries.push(
|
||||
toPlaylistSummary(playlist, owner?.name ?? "Unknown")
|
||||
)
|
||||
}
|
||||
const subscribedDocs = (
|
||||
await loadPlaylists(ctx, user.subscribedPlaylists ?? [])
|
||||
).filter((playlist) => !ownedIds.has(playlist._id))
|
||||
summaries.push(...(await summarizePlaylists(ctx, subscribedDocs)))
|
||||
|
||||
return summaries.sort((a, b) => a.title.localeCompare(b.title))
|
||||
},
|
||||
@@ -488,6 +426,7 @@ export const reorderPlaylistSongs = mutation({
|
||||
const existing = new Set(playlist.songs)
|
||||
if (
|
||||
args.songIds.length !== playlist.songs.length ||
|
||||
new Set(args.songIds).size !== args.songIds.length ||
|
||||
!args.songIds.every((songId) => existing.has(songId))
|
||||
) {
|
||||
throw new ConvexError("Invalid song order")
|
||||
@@ -504,11 +443,28 @@ export const deletePlaylist = mutation({
|
||||
const users = await ctx.db.query("users").collect()
|
||||
for (const user of users) {
|
||||
const subscribed = user.subscribedPlaylists
|
||||
if (!subscribed?.includes(args.playlistId)) {
|
||||
const recentlyPlayed = user.recentlyPlayed
|
||||
const isSubscribed = subscribed?.includes(args.playlistId) ?? false
|
||||
const isRecentlyPlayed =
|
||||
recentlyPlayed?.includes(args.playlistId) ?? false
|
||||
if (!isSubscribed && !isRecentlyPlayed) {
|
||||
continue
|
||||
}
|
||||
await ctx.db.patch(user._id, {
|
||||
subscribedPlaylists: subscribed.filter((id) => id !== args.playlistId),
|
||||
...(isSubscribed
|
||||
? {
|
||||
subscribedPlaylists: subscribed!.filter(
|
||||
(id) => id !== args.playlistId
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
...(isRecentlyPlayed
|
||||
? {
|
||||
recentlyPlayed: recentlyPlayed!.filter(
|
||||
(id) => id !== args.playlistId
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -24,13 +24,21 @@ export default defineSchema({
|
||||
favoriteSongs: v.optional(v.array(v.id("songs"))),
|
||||
songQueue: v.optional(v.array(v.id("songs"))),
|
||||
queueHistory: v.optional(v.array(v.id("songs"))),
|
||||
recentlyPlayed: v.optional(v.array(v.union(v.id("playlists"), v.id("albums")))),
|
||||
recentlyPlayed: v.optional(
|
||||
v.array(v.union(v.id("playlists"), v.id("albums")))
|
||||
),
|
||||
currentSongProgress: v.optional(v.number()),
|
||||
shuffleEnabled: v.optional(v.boolean()),
|
||||
repeatEnabled: v.optional(
|
||||
v.union(v.literal("always"), v.literal("once"), v.literal("none"))
|
||||
),
|
||||
}).index("email", ["email"]),
|
||||
authVerifiers: defineTable({
|
||||
sessionId: v.optional(v.id("authSessions")),
|
||||
signature: v.optional(v.string()),
|
||||
})
|
||||
.index("signature", ["signature"])
|
||||
.index("sessionId", ["sessionId"]),
|
||||
appSettings: defineTable({
|
||||
disableAccountCreation: v.boolean(),
|
||||
}),
|
||||
@@ -38,7 +46,9 @@ export default defineSchema({
|
||||
name: v.string(),
|
||||
folder: v.string(),
|
||||
cover: v.nullable(v.string()),
|
||||
}).index("by_name", ["name"]),
|
||||
})
|
||||
.index("by_name", ["name"])
|
||||
.index("by_folder", ["folder"]),
|
||||
albums: defineTable({
|
||||
name: v.string(),
|
||||
folder: v.string(),
|
||||
|
||||
@@ -46,8 +46,6 @@ export type BrowseAlbumSummary = Omit<BrowseAlbumDetail, "tracks"> & {
|
||||
export type BrowseArtistDetail = {
|
||||
artist: BrowseArtist
|
||||
albums: BrowseAlbum[]
|
||||
recentlyAdded: BrowseAlbum[]
|
||||
recentlyPlayed: BrowseAlbum[]
|
||||
}
|
||||
|
||||
export type PlaylistSummary = {
|
||||
|
||||
@@ -4,10 +4,10 @@ import {
|
||||
modifyAccountCredentials,
|
||||
} from "@convex-dev/auth/server"
|
||||
import { ConvexError, v } from "convex/values"
|
||||
import { api } from "./_generated/api"
|
||||
import { action, mutation, query } from "./_generated/server"
|
||||
import { api, internal } from "./_generated/api"
|
||||
import { action, internalQuery, mutation, query } from "./_generated/server"
|
||||
import type { Id } from "./_generated/dataModel"
|
||||
import type { MutationCtx } from "./_generated/server"
|
||||
import type { ActionCtx, MutationCtx } from "./_generated/server"
|
||||
|
||||
const playbackQualityValidator = v.union(
|
||||
v.literal("low"),
|
||||
@@ -33,6 +33,14 @@ async function requireAdmin(ctx: MutationCtx) {
|
||||
return { userId, user }
|
||||
}
|
||||
|
||||
async function requireAdminAction(ctx: ActionCtx) {
|
||||
const user = await ctx.runQuery(api.auth.currentUser)
|
||||
if (!user?.isAdmin) {
|
||||
throw new ConvexError("Not authorized")
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
async function deleteUserAuthData(ctx: MutationCtx, userId: Id<"users">) {
|
||||
const sessions = await ctx.db
|
||||
.query("authSessions")
|
||||
@@ -50,7 +58,7 @@ async function deleteUserAuthData(ctx: MutationCtx, userId: Id<"users">) {
|
||||
|
||||
const verifiers = await ctx.db
|
||||
.query("authVerifiers")
|
||||
.filter((q) => q.eq(q.field("sessionId"), session._id))
|
||||
.withIndex("sessionId", (q) => q.eq("sessionId", session._id))
|
||||
.collect()
|
||||
for (const verifier of verifiers) {
|
||||
await ctx.db.delete(verifier._id)
|
||||
@@ -61,7 +69,7 @@ async function deleteUserAuthData(ctx: MutationCtx, userId: Id<"users">) {
|
||||
|
||||
const accounts = await ctx.db
|
||||
.query("authAccounts")
|
||||
.filter((q) => q.eq(q.field("userId"), userId))
|
||||
.withIndex("userIdAndProvider", (q) => q.eq("userId", userId))
|
||||
.collect()
|
||||
|
||||
for (const account of accounts) {
|
||||
@@ -78,6 +86,52 @@ async function deleteUserAuthData(ctx: MutationCtx, userId: Id<"users">) {
|
||||
await ctx.db.delete(userId)
|
||||
}
|
||||
|
||||
async function deleteOwnedPlaylists(ctx: MutationCtx, userId: Id<"users">) {
|
||||
const owned = await ctx.db
|
||||
.query("playlists")
|
||||
.withIndex("by_owner", (q) => q.eq("owner", userId))
|
||||
.collect()
|
||||
if (owned.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const ownedIds = new Set(owned.map((playlist) => playlist._id))
|
||||
const users = await ctx.db.query("users").collect()
|
||||
for (const user of users) {
|
||||
const subscribed = user.subscribedPlaylists
|
||||
const recentlyPlayed = user.recentlyPlayed
|
||||
const hasSubscription =
|
||||
subscribed?.some((playlistId) => ownedIds.has(playlistId)) ?? false
|
||||
const hasRecentlyPlayed =
|
||||
recentlyPlayed?.some((itemId) =>
|
||||
ownedIds.has(itemId as Id<"playlists">)
|
||||
) ?? false
|
||||
if (!hasSubscription && !hasRecentlyPlayed) {
|
||||
continue
|
||||
}
|
||||
await ctx.db.patch(user._id, {
|
||||
...(hasSubscription
|
||||
? {
|
||||
subscribedPlaylists: subscribed!.filter(
|
||||
(playlistId) => !ownedIds.has(playlistId)
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
...(hasRecentlyPlayed
|
||||
? {
|
||||
recentlyPlayed: recentlyPlayed!.filter(
|
||||
(itemId) => !ownedIds.has(itemId as Id<"playlists">)
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
}
|
||||
|
||||
for (const playlist of owned) {
|
||||
await ctx.db.delete(playlist._id)
|
||||
}
|
||||
}
|
||||
|
||||
export const getAppSettings = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
@@ -88,7 +142,7 @@ export const getAppSettings = query({
|
||||
},
|
||||
})
|
||||
|
||||
export const getUserByEmail = query({
|
||||
export const getUserByEmail = internalQuery({
|
||||
args: { email: v.string() },
|
||||
handler: async (ctx, { email }) => {
|
||||
return await ctx.db
|
||||
@@ -98,6 +152,11 @@ export const getUserByEmail = query({
|
||||
},
|
||||
})
|
||||
|
||||
export const getUser = internalQuery({
|
||||
args: { id: v.id("users") },
|
||||
handler: async (ctx, { id }) => ctx.db.get(id),
|
||||
})
|
||||
|
||||
export const listUsers = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
@@ -109,7 +168,13 @@ export const listUsers = query({
|
||||
if (!currentUser?.isAdmin) {
|
||||
return null
|
||||
}
|
||||
return await ctx.db.query("users").collect()
|
||||
const users = await ctx.db.query("users").collect()
|
||||
return users.map((user) => ({
|
||||
_id: user._id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
isAdmin: user.isAdmin,
|
||||
}))
|
||||
},
|
||||
})
|
||||
|
||||
@@ -228,6 +293,7 @@ export const deleteUser = mutation({
|
||||
if (userId === adminId) {
|
||||
throw new ConvexError("You cannot delete your own account")
|
||||
}
|
||||
await deleteOwnedPlaylists(ctx, userId)
|
||||
await deleteUserAuthData(ctx, userId)
|
||||
},
|
||||
})
|
||||
@@ -257,12 +323,9 @@ export const adminChangeUserPassword = action({
|
||||
newPassword: v.string(),
|
||||
},
|
||||
handler: async (ctx, { userId, newPassword }) => {
|
||||
const users = await ctx.runQuery(api.users.listUsers)
|
||||
if (!users) {
|
||||
throw new ConvexError("Not authorized")
|
||||
}
|
||||
await requireAdminAction(ctx)
|
||||
|
||||
const target = users.find((u) => u._id === userId)
|
||||
const target = await ctx.runQuery(internal.users.getUser, { id: userId })
|
||||
if (!target) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
@@ -286,10 +349,7 @@ export const adminCreateUser = action({
|
||||
isAdmin: v.optional(v.boolean()),
|
||||
},
|
||||
handler: async (ctx, { name, email, password, isAdmin }) => {
|
||||
const users = await ctx.runQuery(api.users.listUsers)
|
||||
if (!users) {
|
||||
throw new ConvexError("Not authorized")
|
||||
}
|
||||
await requireAdminAction(ctx)
|
||||
|
||||
const trimmedName = name.trim()
|
||||
const trimmedEmail = email.trim().toLowerCase()
|
||||
@@ -304,14 +364,14 @@ export const adminCreateUser = action({
|
||||
throw new ConvexError("Password must be at least 8 characters")
|
||||
}
|
||||
|
||||
const existing = await ctx.runQuery(api.users.getUserByEmail, {
|
||||
const existing = await ctx.runQuery(internal.users.getUserByEmail, {
|
||||
email: trimmedEmail,
|
||||
})
|
||||
if (existing) {
|
||||
throw new ConvexError("Email is already in use")
|
||||
}
|
||||
|
||||
const { user } = await createAccount(ctx, {
|
||||
await createAccount(ctx, {
|
||||
provider: "password",
|
||||
account: { id: trimmedEmail, secret: password },
|
||||
profile: {
|
||||
@@ -320,6 +380,5 @@ export const adminCreateUser = action({
|
||||
isAdmin: isAdmin ?? false,
|
||||
},
|
||||
})
|
||||
|
||||
},
|
||||
})
|
||||
@@ -24,17 +24,18 @@ export type PlaybackStreamPlan = {
|
||||
}
|
||||
|
||||
export function playbackStreamPlan(
|
||||
files: Record<string, string>,
|
||||
files: Record<string, unknown>,
|
||||
quality: PlaybackQuality | undefined,
|
||||
preferAtmos: boolean
|
||||
): PlaybackStreamPlan {
|
||||
const playbackQuality = quality ?? "medium"
|
||||
const kbps =
|
||||
playbackQuality === "lossless" ? 0 : qualityKbps(playbackQuality)
|
||||
const effectivePreferAtmos = preferAtmos && "atmos" in files
|
||||
|
||||
let transcodeNeeded = true
|
||||
|
||||
if (preferAtmos && "atmos" in files) {
|
||||
if (effectivePreferAtmos) {
|
||||
transcodeNeeded = false
|
||||
} else if (kbps === 0 && "lossless" in files) {
|
||||
transcodeNeeded = false
|
||||
@@ -44,8 +45,8 @@ export function playbackStreamPlan(
|
||||
|
||||
return {
|
||||
playbackQuality,
|
||||
preferAtmos,
|
||||
preferAtmos: effectivePreferAtmos,
|
||||
transcodeNeeded,
|
||||
useHls: transcodeNeeded && !preferAtmos,
|
||||
useHls: transcodeNeeded,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user