From 73c7283d4d166bddd71638e42ddbcbe9bc693a39 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Sun, 14 Jun 2026 19:44:53 -0400 Subject: [PATCH 01/41] Add Expo mobile app and extract shared Convex package - Replace mobile placeholder with Expo Router app (tabs, playback, auth, library) - Move Convex backend to @otunes/convex for web and mobile reuse - Update web app imports and API routes to use shared package --- README.md | 7 + apps/mobile/App.tsx | 30 - apps/mobile/app.json | 27 +- apps/mobile/app/(app)/(tabs)/_layout.tsx | 68 + apps/mobile/app/(app)/(tabs)/index.tsx | 55 + apps/mobile/app/(app)/(tabs)/library.tsx | 67 + apps/mobile/app/(app)/(tabs)/more.tsx | 137 ++ apps/mobile/app/(app)/(tabs)/playlists.tsx | 48 + apps/mobile/app/(app)/(tabs)/search.tsx | 127 ++ apps/mobile/app/(app)/_layout.tsx | 40 + apps/mobile/app/(app)/album/[id].tsx | 180 +++ apps/mobile/app/(app)/artist/[id].tsx | 147 +++ apps/mobile/app/(app)/library/albums.tsx | 39 + apps/mobile/app/(app)/library/artists.tsx | 66 + apps/mobile/app/(app)/library/songs.tsx | 136 ++ apps/mobile/app/(app)/playlist/[id].tsx | 202 +++ apps/mobile/app/(app)/playlist/favorites.tsx | 115 ++ apps/mobile/app/(app)/queue.tsx | 133 ++ apps/mobile/app/(app)/recently-added.tsx | 33 + apps/mobile/app/(app)/recently-played.tsx | 33 + apps/mobile/app/(app)/settings.tsx | 395 ++++++ apps/mobile/app/(auth)/_layout.tsx | 5 + apps/mobile/app/(auth)/signin.tsx | 5 + apps/mobile/app/(auth)/signup.tsx | 5 + apps/mobile/app/_layout.tsx | 22 + apps/mobile/app/index.tsx | 28 + apps/mobile/app/server.tsx | 80 ++ apps/mobile/babel.config.js | 7 + apps/mobile/components/auth-form.tsx | 185 +++ .../mobile/components/media-actions-sheet.tsx | 111 ++ apps/mobile/components/media-cards.tsx | 151 +++ apps/mobile/components/player.tsx | 270 ++++ apps/mobile/components/screen-header.tsx | 34 + apps/mobile/components/ui/primitives.tsx | 140 ++ apps/mobile/contexts/add-to-playlist.tsx | 250 ++++ apps/mobile/contexts/convex-app.tsx | 29 + apps/mobile/contexts/favorites.tsx | 123 ++ apps/mobile/contexts/playback.tsx | 521 ++++++++ apps/mobile/contexts/server-config.tsx | 80 ++ apps/mobile/index.ts | 8 - apps/mobile/lib/auth-storage.ts | 14 + apps/mobile/lib/format.ts | 30 + apps/mobile/lib/server-config.ts | 84 ++ apps/mobile/lib/shuffle-array.ts | 8 + apps/mobile/lib/theme.ts | 53 + apps/mobile/lib/toast.ts | 13 + apps/mobile/lib/urls.ts | 39 + apps/mobile/metro.config.js | 15 + apps/mobile/package.json | 22 +- apps/mobile/tsconfig.json | 10 +- apps/web/app/(app)/album/[id]/page.tsx | 4 +- apps/web/app/(app)/artist/[id]/page.tsx | 4 +- apps/web/app/(app)/library/albums/page.tsx | 2 +- .../app/(app)/library/artists/[id]/page.tsx | 2 +- apps/web/app/(app)/library/artists/page.tsx | 2 +- apps/web/app/(app)/page.tsx | 2 +- apps/web/app/(app)/playlist/[id]/page.tsx | 4 +- .../web/app/(app)/playlist/favorites/page.tsx | 2 +- apps/web/app/(app)/playlists/page.tsx | 2 +- apps/web/app/(app)/recently-added/page.tsx | 2 +- apps/web/app/(app)/recently-played/page.tsx | 4 +- apps/web/app/(app)/search/page.tsx | 2 +- apps/web/app/api/album/[id]/cover/route.ts | 4 +- apps/web/app/api/artist/[id]/cover/route.ts | 4 +- apps/web/app/api/playlist/[id]/cover/route.ts | 4 +- apps/web/app/api/song/[id]/play/hls/route.ts | 4 +- .../[id]/play/hls/segment/[segment]/route.ts | 4 +- apps/web/app/api/song/[id]/play/route.ts | 4 +- .../components/add-to-playlist-provider.tsx | 4 +- apps/web/components/album-card.tsx | 6 +- apps/web/components/album-view.tsx | 4 +- apps/web/components/app-sidebar.tsx | 2 +- apps/web/components/artist-card.tsx | 2 +- apps/web/components/artist-view.tsx | 6 +- apps/web/components/artists-view.tsx | 6 +- apps/web/components/auth-form.tsx | 2 +- apps/web/components/content-carousel.tsx | 2 +- apps/web/components/favorites-provider.tsx | 4 +- apps/web/components/options-modal.tsx | 4 +- apps/web/components/playback-provider.tsx | 6 +- apps/web/components/playback-song-meta.tsx | 2 +- apps/web/components/playlist-card.tsx | 6 +- apps/web/components/playlist-view.tsx | 6 +- apps/web/components/queue-panel.tsx | 6 +- apps/web/components/search-song-item.tsx | 4 +- .../web/components/search-top-result-card.tsx | 2 +- apps/web/components/songs-view.tsx | 6 +- apps/web/hooks/use-queue-media-actions.ts | 2 +- apps/web/lib/data.ts | 2 +- apps/web/lib/server-hls.ts | 2 +- apps/web/package.json | 1 + package.json | 1 + packages/convex/convex.json | 3 + .../convex}/convex/_generated/api.d.ts | 0 .../convex}/convex/_generated/api.js | 0 .../convex}/convex/_generated/dataModel.d.ts | 0 .../convex}/convex/_generated/server.d.ts | 0 .../convex}/convex/_generated/server.js | 0 .../web => packages/convex}/convex/actions.ts | 0 .../convex}/convex/auth.config.ts | 0 {apps/web => packages/convex}/convex/auth.ts | 0 {apps/web => packages/convex}/convex/crons.ts | 0 .../convex}/convex/favorites.ts | 0 {apps/web => packages/convex}/convex/http.ts | 0 .../web => packages/convex}/convex/library.ts | 119 +- .../convex}/convex/playback.ts | 5 +- .../convex}/convex/playlists.ts | 0 .../web => packages/convex}/convex/schema.ts | 0 .../convex}/convex/tsconfig.json | 0 packages/convex/convex/types.ts | 94 ++ {apps/web => packages/convex}/convex/users.ts | 0 packages/convex/package.json | 35 + pnpm-lock.yaml | 1127 +++++++++++++++-- pnpm-workspace.yaml | 1 + 114 files changed, 5660 insertions(+), 295 deletions(-) delete mode 100644 apps/mobile/App.tsx create mode 100644 apps/mobile/app/(app)/(tabs)/_layout.tsx create mode 100644 apps/mobile/app/(app)/(tabs)/index.tsx create mode 100644 apps/mobile/app/(app)/(tabs)/library.tsx create mode 100644 apps/mobile/app/(app)/(tabs)/more.tsx create mode 100644 apps/mobile/app/(app)/(tabs)/playlists.tsx create mode 100644 apps/mobile/app/(app)/(tabs)/search.tsx create mode 100644 apps/mobile/app/(app)/_layout.tsx create mode 100644 apps/mobile/app/(app)/album/[id].tsx create mode 100644 apps/mobile/app/(app)/artist/[id].tsx create mode 100644 apps/mobile/app/(app)/library/albums.tsx create mode 100644 apps/mobile/app/(app)/library/artists.tsx create mode 100644 apps/mobile/app/(app)/library/songs.tsx create mode 100644 apps/mobile/app/(app)/playlist/[id].tsx create mode 100644 apps/mobile/app/(app)/playlist/favorites.tsx create mode 100644 apps/mobile/app/(app)/queue.tsx create mode 100644 apps/mobile/app/(app)/recently-added.tsx create mode 100644 apps/mobile/app/(app)/recently-played.tsx create mode 100644 apps/mobile/app/(app)/settings.tsx create mode 100644 apps/mobile/app/(auth)/_layout.tsx create mode 100644 apps/mobile/app/(auth)/signin.tsx create mode 100644 apps/mobile/app/(auth)/signup.tsx create mode 100644 apps/mobile/app/_layout.tsx create mode 100644 apps/mobile/app/index.tsx create mode 100644 apps/mobile/app/server.tsx create mode 100644 apps/mobile/babel.config.js create mode 100644 apps/mobile/components/auth-form.tsx create mode 100644 apps/mobile/components/media-actions-sheet.tsx create mode 100644 apps/mobile/components/media-cards.tsx create mode 100644 apps/mobile/components/player.tsx create mode 100644 apps/mobile/components/screen-header.tsx create mode 100644 apps/mobile/components/ui/primitives.tsx create mode 100644 apps/mobile/contexts/add-to-playlist.tsx create mode 100644 apps/mobile/contexts/convex-app.tsx create mode 100644 apps/mobile/contexts/favorites.tsx create mode 100644 apps/mobile/contexts/playback.tsx create mode 100644 apps/mobile/contexts/server-config.tsx delete mode 100644 apps/mobile/index.ts create mode 100644 apps/mobile/lib/auth-storage.ts create mode 100644 apps/mobile/lib/format.ts create mode 100644 apps/mobile/lib/server-config.ts create mode 100644 apps/mobile/lib/shuffle-array.ts create mode 100644 apps/mobile/lib/theme.ts create mode 100644 apps/mobile/lib/toast.ts create mode 100644 apps/mobile/lib/urls.ts create mode 100644 apps/mobile/metro.config.js create mode 100644 packages/convex/convex.json rename {apps/web => packages/convex}/convex/_generated/api.d.ts (100%) rename {apps/web => packages/convex}/convex/_generated/api.js (100%) rename {apps/web => packages/convex}/convex/_generated/dataModel.d.ts (100%) rename {apps/web => packages/convex}/convex/_generated/server.d.ts (100%) rename {apps/web => packages/convex}/convex/_generated/server.js (100%) rename {apps/web => packages/convex}/convex/actions.ts (100%) rename {apps/web => packages/convex}/convex/auth.config.ts (100%) rename {apps/web => packages/convex}/convex/auth.ts (100%) rename {apps/web => packages/convex}/convex/crons.ts (100%) rename {apps/web => packages/convex}/convex/favorites.ts (100%) rename {apps/web => packages/convex}/convex/http.ts (100%) rename {apps/web => packages/convex}/convex/library.ts (93%) rename {apps/web => packages/convex}/convex/playback.ts (99%) rename {apps/web => packages/convex}/convex/playlists.ts (100%) rename {apps/web => packages/convex}/convex/schema.ts (100%) rename {apps/web => packages/convex}/convex/tsconfig.json (100%) create mode 100644 packages/convex/convex/types.ts rename {apps/web => packages/convex}/convex/users.ts (100%) create mode 100644 packages/convex/package.json diff --git a/README.md b/README.md index 4f2b6df..18eb6e3 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ This project uses [pnpm workspaces](https://pnpm.io/workspaces): | --- | --- | --- | | `@otunes/web` | `apps/web` | Next.js web app | | `@otunes/mobile` | `apps/mobile` | Expo React Native mobile app | +| `@otunes/convex` | `packages/convex` | Shared Convex backend and client types | ### Development @@ -33,6 +34,12 @@ Run the mobile app: pnpm dev:mobile ``` +Run the Convex backend (from the shared package): + +```bash +pnpm dev:convex +``` + Other commands: ```bash diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsx deleted file mode 100644 index 591fa9b..0000000 --- a/apps/mobile/App.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import { StatusBar } from "expo-status-bar" -import { StyleSheet, Text, View } from "react-native" - -export default function App() { - return ( - - oTunes - Mobile app coming soon - - - ) -} - -const styles = StyleSheet.create({ - container: { - flex: 1, - backgroundColor: "#fff", - alignItems: "center", - justifyContent: "center", - gap: 8, - }, - title: { - fontSize: 28, - fontWeight: "700", - }, - subtitle: { - fontSize: 16, - color: "#666", - }, -}) diff --git a/apps/mobile/app.json b/apps/mobile/app.json index 70e533c..0dd12f4 100644 --- a/apps/mobile/app.json +++ b/apps/mobile/app.json @@ -4,24 +4,31 @@ "slug": "otunes", "version": "0.0.1", "orientation": "portrait", - "icon": "./assets/icon.png", + "scheme": "otunes", "userInterfaceStyle": "automatic", "ios": { "supportsTablet": true, - "bundleIdentifier": "com.abunchofknowitalls.otunes" + "bundleIdentifier": "com.abunchofknowitalls.otunes", + "infoPlist": { + "UIBackgroundModes": ["audio"] + } }, "android": { - "adaptiveIcon": { - "backgroundColor": "#E6F4FE", - "foregroundImage": "./assets/android-icon-foreground.png", - "backgroundImage": "./assets/android-icon-background.png", - "monochromeImage": "./assets/android-icon-monochrome.png" - }, "package": "com.abunchofknowitalls.otunes", "predictiveBackGestureEnabled": false }, - "web": { - "favicon": "./assets/favicon.png" + "plugins": [ + "expo-router", + "expo-secure-store", + [ + "expo-av", + { + "microphonePermission": false + } + ] + ], + "experiments": { + "typedRoutes": true } } } diff --git a/apps/mobile/app/(app)/(tabs)/_layout.tsx b/apps/mobile/app/(app)/(tabs)/_layout.tsx new file mode 100644 index 0000000..daf3aa3 --- /dev/null +++ b/apps/mobile/app/(app)/(tabs)/_layout.tsx @@ -0,0 +1,68 @@ +import { Ionicons } from "@expo/vector-icons" +import { Tabs } from "expo-router" + +import { useThemeColors } from "@/lib/theme" + +export default function TabsLayout() { + const colors = useThemeColors() + + return ( + + ( + + ), + }} + /> + ( + + ), + }} + /> + ( + + ), + }} + /> + ( + + ), + }} + /> + ( + + ), + }} + /> + + ) +} diff --git a/apps/mobile/app/(app)/(tabs)/index.tsx b/apps/mobile/app/(app)/(tabs)/index.tsx new file mode 100644 index 0000000..bd93a04 --- /dev/null +++ b/apps/mobile/app/(app)/(tabs)/index.tsx @@ -0,0 +1,55 @@ +import { useQuery } from "convex/react" +import { ScrollView, StyleSheet } from "react-native" +import { SafeAreaView } from "react-native-safe-area-context" + +import { ContentCarousel } from "@/components/media-cards" +import { ScreenHeader } from "@/components/screen-header" +import { LoadingView } from "@/components/ui/primitives" +import { contentBottomInset } from "@/components/player" +import { api } from "@otunes/convex/_generated/api" +import { spacing, useThemeColors } from "@/lib/theme" + +export default function HomeScreen() { + const colors = useThemeColors() + const recentlyAdded = useQuery(api.library.browseRecentlyAdded) + const recentlyPlayed = useQuery(api.library.browseRecentlyPlayed) + + if (recentlyAdded === undefined || recentlyPlayed === undefined) { + return ( + + + + + ) + } + + return ( + + + + {recentlyPlayed.length > 0 ? ( + + ) : null} + + + + ) +} + +const styles = StyleSheet.create({ + safe: { flex: 1 }, + content: { + padding: spacing.lg, + gap: spacing.xl, + }, +}) diff --git a/apps/mobile/app/(app)/(tabs)/library.tsx b/apps/mobile/app/(app)/(tabs)/library.tsx new file mode 100644 index 0000000..696b91b --- /dev/null +++ b/apps/mobile/app/(app)/(tabs)/library.tsx @@ -0,0 +1,67 @@ +import { useRouter } from "expo-router" +import { Pressable, ScrollView, StyleSheet, Text, View } from "react-native" +import { SafeAreaView } from "react-native-safe-area-context" +import { Ionicons } from "@expo/vector-icons" + +import { ScreenHeader } from "@/components/screen-header" +import { contentBottomInset } from "@/components/player" +import { radius, spacing, useThemeColors } from "@/lib/theme" + +const links = [ + { title: "Albums", href: "/library/albums", icon: "disc" as const }, + { title: "Artists", href: "/library/artists", icon: "mic" as const }, + { title: "Songs", href: "/library/songs", icon: "musical-notes" as const }, + { title: "Recently Played", href: "/recently-played", icon: "time" as const }, + { title: "Recently Added", href: "/recently-added", icon: "sparkles" as const }, + { title: "Favorites", href: "/playlist/favorites", icon: "star" as const }, +] + +export default function LibraryScreen() { + const router = useRouter() + const colors = useThemeColors() + + return ( + + + + {links.map((link) => ( + router.push(link.href as never)} + > + + + + {link.title} + + + ))} + + + ) +} + +const styles = StyleSheet.create({ + safe: { flex: 1 }, + row: { + flexDirection: "row", + alignItems: "center", + gap: spacing.md, + paddingHorizontal: spacing.lg, + paddingVertical: spacing.md, + borderBottomWidth: StyleSheet.hairlineWidth, + }, + iconWrap: { + width: 40, + height: 40, + borderRadius: radius.md, + alignItems: "center", + justifyContent: "center", + }, + rowTitle: { + flex: 1, + fontSize: 16, + fontWeight: "600", + }, +}) diff --git a/apps/mobile/app/(app)/(tabs)/more.tsx b/apps/mobile/app/(app)/(tabs)/more.tsx new file mode 100644 index 0000000..2eb2cee --- /dev/null +++ b/apps/mobile/app/(app)/(tabs)/more.tsx @@ -0,0 +1,137 @@ +import { useAuthActions } from "@convex-dev/auth/react" +import { useQuery } from "convex/react" +import { useRouter } from "expo-router" +import { Pressable, ScrollView, StyleSheet, Text, View } from "react-native" +import { SafeAreaView } from "react-native-safe-area-context" +import { Ionicons } from "@expo/vector-icons" + +import { ScreenHeader } from "@/components/screen-header" +import { contentBottomInset } from "@/components/player" +import { useServerConfig } from "@/contexts/server-config" +import { api } from "@otunes/convex/_generated/api" +import type { PlaylistSummary } from "@otunes/convex/types" +import { initialsFromName } from "@/lib/format" +import { radius, spacing, useThemeColors } from "@/lib/theme" + +export default function MoreScreen() { + const router = useRouter() + const colors = useThemeColors() + const { signOut } = useAuthActions() + const { clearServer } = useServerConfig() + const user = useQuery(api.auth.currentUser) + const sidebarPlaylists = useQuery(api.playlists.listSidebarPlaylists) + + async function handleSignOut() { + await signOut() + router.replace("/signin") + } + + async function handleChangeServer() { + await signOut() + await clearServer() + router.replace("/server") + } + + const subscribed = sidebarPlaylists?.subscribed ?? [] + const owned = sidebarPlaylists?.owned ?? [] + + return ( + + + + + + + {initialsFromName(user?.name ?? "NA")} + + + + {user?.name ?? "..."} + {user?.email} + + + + router.push("/settings")}> + + Settings + + router.push("/queue")}> + + Queue + + + {owned.length > 0 ? ( + Your playlists + ) : null} + {owned.map((playlist: PlaylistSummary) => ( + router.push(`/playlist/${playlist.id}`)} + > + + {playlist.title} + + ))} + + {subscribed.length > 0 ? ( + Subscribed + ) : null} + {subscribed.map((playlist: PlaylistSummary) => ( + router.push(`/playlist/${playlist.id}`)} + > + + {playlist.title} + + ))} + + void handleSignOut()}> + + Sign out + + void handleChangeServer()}> + + Change server + + + + ) +} + +const styles = StyleSheet.create({ + safe: { flex: 1 }, + profileCard: { + margin: spacing.lg, + borderRadius: radius.lg, + padding: spacing.lg, + flexDirection: "row", + alignItems: "center", + gap: spacing.md, + }, + avatar: { + width: 48, + height: 48, + borderRadius: 24, + alignItems: "center", + justifyContent: "center", + }, + name: { fontSize: 18, fontWeight: "700" }, + row: { + flexDirection: "row", + alignItems: "center", + gap: spacing.md, + paddingHorizontal: spacing.lg, + paddingVertical: spacing.md, + }, + rowText: { fontSize: 16, fontWeight: "500" }, + sectionLabel: { + paddingHorizontal: spacing.lg, + paddingTop: spacing.lg, + fontSize: 12, + fontWeight: "700", + textTransform: "uppercase", + }, +}) diff --git a/apps/mobile/app/(app)/(tabs)/playlists.tsx b/apps/mobile/app/(app)/(tabs)/playlists.tsx new file mode 100644 index 0000000..415f00a --- /dev/null +++ b/apps/mobile/app/(app)/(tabs)/playlists.tsx @@ -0,0 +1,48 @@ +import { useQuery } from "convex/react" +import { ScrollView, StyleSheet, View } from "react-native" +import { SafeAreaView } from "react-native-safe-area-context" + +import { PlaylistCard } from "@/components/media-cards" +import { ScreenHeader } from "@/components/screen-header" +import { Button, LoadingView } from "@/components/ui/primitives" +import { contentBottomInset } from "@/components/player" +import { useAddToPlaylist } from "@/contexts/add-to-playlist" +import { api } from "@otunes/convex/_generated/api" +import type { PlaylistSummary } from "@otunes/convex/types" +import { spacing, useThemeColors } from "@/lib/theme" + +export default function PlaylistsTabScreen() { + const colors = useThemeColors() + const playlists = useQuery(api.playlists.listAllPlaylists) + const { openCreatePlaylist } = useAddToPlaylist() + + return ( + + } + /> + {playlists === undefined ? ( + + ) : ( + + + {playlists.map((playlist: PlaylistSummary) => ( + + ))} + + + )} + + ) +} + +const styles = StyleSheet.create({ + safe: { flex: 1 }, + content: { padding: spacing.lg }, + grid: { + flexDirection: "row", + flexWrap: "wrap", + gap: spacing.lg, + }, +}) diff --git a/apps/mobile/app/(app)/(tabs)/search.tsx b/apps/mobile/app/(app)/(tabs)/search.tsx new file mode 100644 index 0000000..6fe2f3a --- /dev/null +++ b/apps/mobile/app/(app)/(tabs)/search.tsx @@ -0,0 +1,127 @@ +import { useQuery } from "convex/react" +import { useMemo, useState } from "react" +import { ScrollView, StyleSheet, View } from "react-native" +import { SafeAreaView } from "react-native-safe-area-context" + +import { ContentCarousel } from "@/components/media-cards" +import { contentBottomInset, SongRow } from "@/components/player" +import { ScreenHeader } from "@/components/screen-header" +import { Input, LoadingView } from "@/components/ui/primitives" +import { usePlayback } from "@/contexts/playback" +import { api } from "@otunes/convex/_generated/api" +import type { BrowseSong } from "@otunes/convex/types" +import { spacing, useThemeColors } from "@/lib/theme" + +const SEARCH_DEBOUNCE_MS = 300 + +export default function SearchScreen() { + const colors = useThemeColors() + const { playFromSong } = usePlayback() + const [query, setQuery] = useState("") + const [searchQuery, setSearchQuery] = useState("") + const [debounceId, setDebounceId] = useState | null>(null) + + const hasQuery = searchQuery.length > 0 + const results = useQuery( + api.library.searchLibrary, + hasQuery ? { query: searchQuery } : "skip" + ) + const playlistResults = useQuery( + api.playlists.searchPlaylists, + hasQuery ? { query: searchQuery } : "skip" + ) + + const isSearching = hasQuery && results === undefined + + function handleQueryChange(value: string) { + setQuery(value) + if (debounceId) clearTimeout(debounceId) + const id = setTimeout(() => setSearchQuery(value.trim()), SEARCH_DEBOUNCE_MS) + setDebounceId(id) + } + + const hasLibraryResults = useMemo( + () => + Boolean( + results && + (results.topResults.length > 0 || + results.artists.length > 0 || + results.albums.length > 0 || + results.songs.length > 0) + ), + [results] + ) + + return ( + + + + setSearchQuery(query.trim())} + /> + + + {isSearching ? ( + + ) : !hasQuery ? ( + + + + ) : ( + + {!hasLibraryResults ? ( + + + + ) : null} + + {results?.artists.length ? ( + + + + ) : null} + + {results?.albums.length ? ( + + + + ) : null} + + {results?.songs.length ? ( + + {results.songs.map((song: BrowseSong) => ( + + void playFromSong( + song.id, + results.songs.map((s: BrowseSong) => s.id) + ) + } + /> + ))} + + ) : null} + + {playlistResults && playlistResults.length > 0 ? ( + + + + ) : null} + + )} + + ) +} + +const styles = StyleSheet.create({ + safe: { flex: 1 }, + searchBox: { paddingHorizontal: spacing.lg, paddingBottom: spacing.md }, + empty: { padding: spacing.lg }, + section: { paddingHorizontal: spacing.lg, paddingBottom: spacing.lg, gap: spacing.md }, +}) diff --git a/apps/mobile/app/(app)/_layout.tsx b/apps/mobile/app/(app)/_layout.tsx new file mode 100644 index 0000000..e31307f --- /dev/null +++ b/apps/mobile/app/(app)/_layout.tsx @@ -0,0 +1,40 @@ +import { useConvexAuth } from "@convex-dev/auth/react" +import { Redirect, Stack } from "expo-router" +import { View } from "react-native" + +import { PlayerBar } from "@/components/player" +import { LoadingView } from "@/components/ui/primitives" +import { AddToPlaylistProvider } from "@/contexts/add-to-playlist" +import { FavoritesProvider } from "@/contexts/favorites" +import { PlaybackProvider } from "@/contexts/playback" +import { useServerConfig } from "@/contexts/server-config" + +export default function AppLayout() { + const { config } = useServerConfig() + const { isLoading, isAuthenticated } = useConvexAuth() + + if (!config) { + return + } + + if (isLoading) { + return + } + + if (!isAuthenticated) { + return + } + + return ( + + + + + + + + + + + ) +} diff --git a/apps/mobile/app/(app)/album/[id].tsx b/apps/mobile/app/(app)/album/[id].tsx new file mode 100644 index 0000000..bece4a1 --- /dev/null +++ b/apps/mobile/app/(app)/album/[id].tsx @@ -0,0 +1,180 @@ +import { useQuery } from "convex/react" +import { Image } from "expo-image" +import { useLocalSearchParams, useRouter } from "expo-router" +import { useState } from "react" +import { Pressable, ScrollView, StyleSheet, Text, View } from "react-native" +import { SafeAreaView } from "react-native-safe-area-context" +import { Ionicons } from "@expo/vector-icons" + +import { MediaActionsSheet, type MediaAction } from "@/components/media-actions-sheet" +import { ScreenHeader } from "@/components/screen-header" +import { Button, LoadingView } from "@/components/ui/primitives" +import { contentBottomInset } from "@/components/player" +import { useAddToPlaylist } from "@/contexts/add-to-playlist" +import { useFavorites } from "@/contexts/favorites" +import { usePlayback } from "@/contexts/playback" +import { useServerConfig } from "@/contexts/server-config" +import { api } from "@otunes/convex/_generated/api" +import type { Id } from "@otunes/convex/_generated/dataModel" +import type { BrowseAlbumTrack } from "@otunes/convex/types" +import { formatDuration, formatMetadata } from "@/lib/format" +import { albumCoverUrl } from "@/lib/urls" +import { radius, spacing, useThemeColors } from "@/lib/theme" + +export default function AlbumScreen() { + const { id } = useLocalSearchParams<{ id: string }>() + const router = useRouter() + const colors = useThemeColors() + const { config } = useServerConfig() + const album = useQuery(api.library.browseAlbumDetail, { id: id as Id<"albums"> }) + const { playAlbum, playAlbumShuffled, playFromSong } = usePlayback() + const { isAlbumFavorite, toggleAlbumFavorite } = useFavorites() + const { openAddAlbumToPlaylist } = useAddToPlaylist() + const [actionsOpen, setActionsOpen] = useState(false) + + if (album === undefined || !config) { + return ( + + + + + ) + } + + if (album === null) { + return ( + + + + Album not found. + + + ) + } + + const songIds = album.tracks.map((track: BrowseAlbumTrack) => track.id) + const metadata = formatMetadata(album.genre, album.year) + + function handleAlbumAction(action: MediaAction) { + if (!album) return + switch (action) { + case "playlist": + void openAddAlbumToPlaylist(album.id) + break + case "favorite": + void toggleAlbumFavorite(album.id) + break + default: + break + } + } + + return ( + + setActionsOpen(true)} hitSlop={8}> + + + } + /> + + + + {album.title} + router.push(`/artist/${album.artist.id}`)}> + {album.artist.name} + + {metadata ? ( + {metadata} + ) : null} + + @@ -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)} diff --git a/apps/web/components/queue-panel.tsx b/apps/web/components/queue-panel.tsx index e0b4363..f255859 100644 --- a/apps/web/components/queue-panel.tsx +++ b/apps/web/components/queue-panel.tsx @@ -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(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) { diff --git a/apps/web/components/search-song-item.tsx b/apps/web/components/search-song-item.tsx index e8398f9..3023ab2 100644 --- a/apps/web/components/search-song-item.tsx +++ b/apps/web/components/search-song-item.tsx @@ -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" /> diff --git a/apps/web/components/search-top-result-card.tsx b/apps/web/components/search-top-result-card.tsx index 4299877..0d9065c 100644 --- a/apps/web/components/search-top-result-card.tsx +++ b/apps/web/components/search-top-result-card.tsx @@ -79,7 +79,13 @@ export function SearchTopResultCard({ result }: { result: TopResult }) { image.rounded ? "rounded-full" : "rounded-md" )} > - {image.alt} + {image.alt}

{resultTitle(result)}

diff --git a/apps/web/components/songs-view.tsx b/apps/web/components/songs-view.tsx index e32e933..e5de43f 100644 --- a/apps/web/components/songs-view.tsx +++ b/apps/web/components/songs-view.tsx @@ -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" />
@@ -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() { { - setMounted(true) - }, []) + const mounted = useMounted() const isDark = mounted && resolvedTheme === "dark" diff --git a/apps/web/components/ui/carousel.tsx b/apps/web/components/ui/carousel.tsx index 7bea93a..6ffa896 100644 --- a/apps/web/components/ui/carousel.tsx +++ b/apps/web/components/ui/carousel.tsx @@ -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]) diff --git a/apps/web/hooks/use-mobile.ts b/apps/web/hooks/use-mobile.ts index 2b0fe1d..eaf1273 100644 --- a/apps/web/hooks/use-mobile.ts +++ b/apps/web/hooks/use-mobile.ts @@ -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(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) } diff --git a/apps/web/hooks/use-mounted.ts b/apps/web/hooks/use-mounted.ts new file mode 100644 index 0000000..79a18e5 --- /dev/null +++ b/apps/web/hooks/use-mounted.ts @@ -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 + ) +} diff --git a/apps/web/lib/serve-cover.ts b/apps/web/lib/serve-cover.ts index 59f2b73..550c394 100644 --- a/apps/web/lib/serve-cover.ts +++ b/apps/web/lib/serve-cover.ts @@ -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 = { ".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 { diff --git a/apps/web/lib/server-hls.ts b/apps/web/lib/server-hls.ts index f22d375..df3b876 100644 --- a/apps/web/lib/server-hls.ts +++ b/apps/web/lib/server-hls.ts @@ -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() +const jobsByLookup = new Map() +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 = [ diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index 5688811..3790c6a 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -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;", diff --git a/packages/convex/convex/actions.ts b/packages/convex/convex/actions.ts index 878456b..6abfa86 100644 --- a/packages/convex/convex/actions.ts +++ b/packages/convex/convex/actions.ts @@ -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 }[] = [] 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 => { + 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) }, }) diff --git a/packages/convex/convex/auth.ts b/packages/convex/convex/auth.ts index 83be786..870873e 100644 --- a/packages/convex/convex/auth.ts +++ b/packages/convex/convex/auth.ts @@ -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, + } }, }) diff --git a/packages/convex/convex/crons.ts b/packages/convex/convex/crons.ts index 604dfea..d9e88f7 100644 --- a/packages/convex/convex/crons.ts +++ b/packages/convex/convex/crons.ts @@ -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 diff --git a/packages/convex/convex/favorites.ts b/packages/convex/convex/favorites.ts index c4bfed3..ee5e79d 100644 --- a/packages/convex/convex/favorites.ts +++ b/packages/convex/convex/favorites.ts @@ -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(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, Doc<"artists">>, - albumMap: Map, Doc<"albums">> -): Promise { - 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) + ), }) }, }) diff --git a/packages/convex/convex/library.ts b/packages/convex/convex/library.ts index d53fa39..d3748e6 100644 --- a/packages/convex/convex/library.ts +++ b/packages/convex/convex/library.ts @@ -1,6 +1,6 @@ import { paginationOptsValidator } from "convex/server" import { getAuthUserId } from "@convex-dev/auth/server" -import { mutation, query } from "./_generated/server" +import { internalMutation, internalQuery, query } from "./_generated/server" import { v } from "convex/values" import type { Doc, Id } from "./_generated/dataModel" import type { QueryCtx } from "./_generated/server" @@ -113,6 +113,14 @@ async function loadArtistMap(ctx: QueryCtx) { return new Map(artists.map((artist) => [artist._id, artist])) } +async function loadArtistMapForIds(ctx: QueryCtx, artistIds: Id<"artists">[]) { + const ids = [...new Set(artistIds)] + const artists = await Promise.all(ids.map((id) => ctx.db.get("artists", id))) + return new Map( + artists.flatMap((artist) => (artist ? [[artist._id, artist] as const] : [])) + ) +} + function toBrowseArtist(artist: Doc<"artists">): BrowseArtist { return { id: artist._id, @@ -137,20 +145,36 @@ export async function browseSongsFromIds( ctx: QueryCtx, songIds: Id<"songs">[] ): Promise { - const songs: BrowseSong[] = [] - for (const songId of songIds) { - const song = await ctx.db.get("songs", songId) - if (!song) { - continue - } - const album = await ctx.db.get("albums", song.album) - const albumArtist = await ctx.db.get("artists", song.albumArtist) - if (!album || !albumArtist) { - continue - } - songs.push(toBrowseSong(song, album, albumArtist)) - } - return songs + const songs = await Promise.all( + songIds.map((songId) => ctx.db.get("songs", songId)) + ) + return browseSongDocs( + ctx, + songs.filter((song): song is Doc<"songs"> => song !== null) + ) +} + +async function browseSongDocs( + ctx: QueryCtx, + songs: Doc<"songs">[] +): Promise { + const albumIds = [...new Set(songs.map((song) => song.album))] + const albums = await Promise.all( + albumIds.map((albumId) => ctx.db.get("albums", albumId)) + ) + const albumMap = new Map( + albums.flatMap((album) => (album ? [[album._id, album] as const] : [])) + ) + const artistMap = await loadArtistMapForIds( + ctx, + songs.map((song) => song.albumArtist) + ) + + return songs.flatMap((song) => { + const album = albumMap.get(song.album) + const albumArtist = artistMap.get(song.albumArtist) + return album && albumArtist ? [toBrowseSong(song, album, albumArtist)] : [] + }) } function toBrowseSong( @@ -205,8 +229,7 @@ export function paginateSlice( paginationOpts: PaginationOptions ): PaginationResult { const cursor = paginationOpts.cursor - const start = - cursor && cursor.length > 0 ? Number.parseInt(cursor, 10) : 0 + const start = cursor && cursor.length > 0 ? Number.parseInt(cursor, 10) : 0 const safeStart = Number.isFinite(start) ? start : 0 const page = items.slice(safeStart, safeStart + paginationOpts.numItems) const next = safeStart + page.length @@ -237,12 +260,15 @@ export const browseArtistsPaginated = query({ export const browseAlbumsPaginated = query({ args: { paginationOpts: paginationOptsValidator }, handler: async (ctx, args) => { - const artistMap = await loadArtistMap(ctx) const result = await ctx.db .query("albums") .withIndex("by_name") .order("asc") .paginate(args.paginationOpts) + const artistMap = await loadArtistMapForIds( + ctx, + result.page.map((album) => album.artist) + ) return { ...result, @@ -289,7 +315,7 @@ export type SongsSortKey = "title" | "artist" | "album" export type SongsSortDirection = "asc" | "desc" type GroupedSongsCursor = { - groupIndex: number + groupCursor: string | null songIndex: number } @@ -302,25 +328,10 @@ function compareSongNames( return direction === "asc" ? comparison : -comparison } -function mapSongToBrowse( - song: Doc<"songs">, - artistMap: Map, Doc<"artists">>, - albumMap: Map, Doc<"albums">> -): BrowseSong | null { - const album = albumMap.get(song.album) - const albumArtist = artistMap.get(song.albumArtist) - if (!album || !albumArtist) { - return null - } - return toBrowseSong(song, album, albumArtist) -} - async function paginateSongsByTitle( ctx: QueryCtx, paginationOpts: PaginationOptions, - sortDirection: SongsSortDirection, - artistMap: Map, Doc<"artists">>, - albumMap: Map, Doc<"albums">> + sortDirection: SongsSortDirection ): Promise> { const result = await ctx.db .query("songs") @@ -330,10 +341,7 @@ async function paginateSongsByTitle( return { ...result, - page: result.page.flatMap((song) => { - const mapped = mapSongToBrowse(song, artistMap, albumMap) - return mapped ? [mapped] : [] - }), + page: await browseSongDocs(ctx, result.page), } } @@ -341,61 +349,83 @@ async function paginateSongsByGroup( ctx: QueryCtx, paginationOpts: PaginationOptions, sortDirection: SongsSortDirection, - artistMap: Map, Doc<"artists">>, - albumMap: Map, Doc<"albums">>, sortKey: "artist" | "album" ): Promise> { - const cursor: GroupedSongsCursor = paginationOpts.cursor - ? (JSON.parse(paginationOpts.cursor) as GroupedSongsCursor) - : { groupIndex: 0, songIndex: 0 } + let cursor: GroupedSongsCursor = { groupCursor: null, songIndex: 0 } + if (paginationOpts.cursor) { + const parsed = JSON.parse( + paginationOpts.cursor + ) as Partial + if ( + (typeof parsed.groupCursor === "string" || parsed.groupCursor === null) && + Number.isInteger(parsed.songIndex) && + (parsed.songIndex ?? -1) >= 0 + ) { + cursor = parsed as GroupedSongsCursor + } + } - const groups = - sortKey === "artist" - ? [...artistMap.values()].sort((a, b) => - compareSongNames(a.name, b.name, sortDirection) - ) - : [...albumMap.values()].sort((a, b) => - compareSongNames(a.name, b.name, sortDirection) - ) + const songDocs: Doc<"songs">[] = [] + let { groupCursor, songIndex } = cursor + let isDone = false - const page: BrowseSong[] = [] - let { groupIndex, songIndex } = cursor + while (songDocs.length < paginationOpts.numItems && !isDone) { + const groupResult = + sortKey === "artist" + ? await ctx.db + .query("artists") + .withIndex("by_name") + .order(sortDirection) + .paginate({ cursor: groupCursor, numItems: 1 }) + : await ctx.db + .query("albums") + .withIndex("by_name") + .order(sortDirection) + .paginate({ cursor: groupCursor, numItems: 1 }) + const group = groupResult.page[0] + if (!group) { + isDone = true + break + } - while (page.length < paginationOpts.numItems && groupIndex < groups.length) { - const group = groups[groupIndex] - const songs = await ctx.db - .query("songs") - .withIndex(sortKey === "artist" ? "by_artist" : "by_album", (q) => - sortKey === "artist" - ? q.eq("albumArtist", group._id as Id<"artists">) - : q.eq("album", group._id as Id<"albums">) - ) - .collect() + const songs = + sortKey === "artist" + ? await ctx.db + .query("songs") + .withIndex("by_artist", (q) => + q.eq("albumArtist", group._id as Id<"artists">) + ) + .collect() + : await ctx.db + .query("songs") + .withIndex("by_album", (q) => + q.eq("album", group._id as Id<"albums">) + ) + .collect() songs.sort((a, b) => compareSongNames(a.name, b.name, sortDirection)) - while (songIndex < songs.length && page.length < paginationOpts.numItems) { - const mapped = mapSongToBrowse(songs[songIndex], artistMap, albumMap) - if (mapped) { - page.push(mapped) - } + while ( + songIndex < songs.length && + songDocs.length < paginationOpts.numItems + ) { + songDocs.push(songs[songIndex]) songIndex++ } if (songIndex >= songs.length) { - groupIndex++ + groupCursor = groupResult.continueCursor || null songIndex = 0 + isDone = groupResult.isDone } } - const isDone = groupIndex >= groups.length - return { - page, + page: await browseSongDocs(ctx, songDocs), isDone, continueCursor: isDone ? "" - : JSON.stringify({ groupIndex, songIndex } satisfies GroupedSongsCursor), + : JSON.stringify({ groupCursor, songIndex } satisfies GroupedSongsCursor), } } @@ -413,38 +443,35 @@ export async function getSortedLibrarySongIds( return songs.map((song) => song._id) } - const artistMap = await loadArtistMap(ctx) - const albums = await ctx.db.query("albums").collect() - const albumMap = new Map(albums.map((album) => [album._id, album])) - - const groups = + const songs = await ctx.db.query("songs").collect() + const groupNames = sortKey === "artist" - ? [...artistMap.values()].sort((a, b) => - compareSongNames(a.name, b.name, sortDirection) + ? new Map( + [...(await loadArtistMap(ctx)).values()].map((artist) => [ + artist._id as string, + artist.name, + ]) ) - : [...albumMap.values()].sort((a, b) => - compareSongNames(a.name, b.name, sortDirection) + : new Map( + (await ctx.db.query("albums").collect()).map((album) => [ + album._id as string, + album.name, + ]) ) - - const songIds: Id<"songs">[] = [] - - for (const group of groups) { - const songs = await ctx.db - .query("songs") - .withIndex(sortKey === "artist" ? "by_artist" : "by_album", (q) => - sortKey === "artist" - ? q.eq("albumArtist", group._id as Id<"artists">) - : q.eq("album", group._id as Id<"albums">) - ) - .collect() - - songs.sort((a, b) => compareSongNames(a.name, b.name, sortDirection)) - for (const song of songs) { - songIds.push(song._id) - } - } - - return songIds + const validSongs = songs.filter((song) => + groupNames.has(sortKey === "artist" ? song.albumArtist : song.album) + ) + validSongs.sort((a, b) => { + const groupA = + groupNames.get(sortKey === "artist" ? a.albumArtist : a.album) ?? "" + const groupB = + groupNames.get(sortKey === "artist" ? b.albumArtist : b.album) ?? "" + return ( + compareSongNames(groupA, groupB, sortDirection) || + compareSongNames(a.name, b.name, sortDirection) + ) + }) + return validSongs.map((song) => song._id) } export const browseSongsPaginated = query({ @@ -454,26 +481,14 @@ export const browseSongsPaginated = query({ sortDirection: songsSortDirectionValidator, }, handler: async (ctx, args) => { - const artistMap = await loadArtistMap(ctx) - const albums = await ctx.db.query("albums").collect() - const albumMap = new Map(albums.map((album) => [album._id, album])) - if (args.sortKey === "title") { - return paginateSongsByTitle( - ctx, - args.paginationOpts, - args.sortDirection, - artistMap, - albumMap - ) + return paginateSongsByTitle(ctx, args.paginationOpts, args.sortDirection) } return paginateSongsByGroup( ctx, args.paginationOpts, args.sortDirection, - artistMap, - albumMap, args.sortKey ) }, @@ -482,11 +497,6 @@ export const browseSongsPaginated = query({ export const browseAlbumDetail = query({ args: { id: v.id("albums") }, handler: async (ctx, args): Promise => { - const summary = await browseAlbumSummaryHandler(ctx, args.id) - if (!summary) { - return null - } - const album = await ctx.db.get("albums", args.id) const artist = album ? await ctx.db.get("artists", album.artist) : null if (!album || !artist) { @@ -499,9 +509,13 @@ export const browseAlbumDetail = query({ .collect() songs.sort(compareAlbumSongs) + const primarySong = songs[0] return { - ...summary, + ...toBrowseAlbum(album, artist), + year: primarySong?.year ?? null, + genre: primarySong?.genres[0] ?? null, + releaseDate: album.date, tracks: songs.map((song) => toBrowseAlbumTrack(song, artist.name)), } }, @@ -584,19 +598,11 @@ export const browseArtistDetail = query({ .withIndex("by_artist", (q) => q.eq("artist", args.id)) .collect() - const recentlyAdded = [...albums] - .sort((a, b) => b._creationTime - a._creationTime) - .map((album) => toBrowseAlbum(album, artist)) - - const recentlyPlayed = [...albums] - .sort((a, b) => a.name.localeCompare(b.name)) - .map((album) => toBrowseAlbum(album, artist)) + albums.sort((a, b) => a.name.localeCompare(b.name)) return { artist: toBrowseArtist(artist), - albums: recentlyPlayed, - recentlyAdded, - recentlyPlayed, + albums: albums.map((album) => toBrowseAlbum(album, artist)), } }, }) @@ -732,40 +738,47 @@ export const searchLibrary = query({ }) export const browseRecentlyAdded = query({ - args: {}, - handler: async (ctx) => { - const artistMap = await loadArtistMap(ctx) - const albums = await ctx.db.query("albums").collect() + args: { limit: v.optional(v.number()) }, + handler: async (ctx, args) => { + const albumQuery = ctx.db.query("albums").order("desc") + const albums = args.limit + ? await albumQuery.take(args.limit) + : await albumQuery.collect() + const artistMap = await loadArtistMapForIds( + ctx, + albums.map((album) => album.artist) + ) - return albums - .flatMap((album) => { - const artist = artistMap.get(album.artist) - return artist ? [{ album, artist, addedAt: album._creationTime }] : [] - }) - .sort((a, b) => b.addedAt - a.addedAt) - .map(({ album, artist }) => toBrowseAlbum(album, artist)) + return albums.flatMap((album) => { + const artist = artistMap.get(album.artist) + return artist ? [toBrowseAlbum(album, artist)] : [] + }) }, }) export const browseRecentlyAddedPaginated = query({ args: { paginationOpts: paginationOptsValidator }, handler: async (ctx, args) => { - const artistMap = await loadArtistMap(ctx) - const albums = await ctx.db.query("albums").collect() + const result = await ctx.db + .query("albums") + .order("desc") + .paginate(args.paginationOpts) + const artistMap = await loadArtistMapForIds( + ctx, + result.page.map((album) => album.artist) + ) - const recentlyAdded = albums - .flatMap((album) => { + return { + ...result, + page: result.page.flatMap((album) => { const artist = artistMap.get(album.artist) - return artist ? [{ album, artist, addedAt: album._creationTime }] : [] - }) - .sort((a, b) => b.addedAt - a.addedAt) - .map(({ album, artist }) => toBrowseAlbum(album, artist)) - - return paginateSlice(recentlyAdded, args.paginationOpts) + return artist ? [toBrowseAlbum(album, artist)] : [] + }), + } }, }) -async function browseRecentlyPlayedItems(ctx: QueryCtx) { +async function browseRecentlyPlayedItems(ctx: QueryCtx, limit?: number) { const userId = await getAuthUserId(ctx) if (userId === null) { return [] @@ -776,50 +789,75 @@ async function browseRecentlyPlayedItems(ctx: QueryCtx) { return [] } - const recentlyPlayed = user.recentlyPlayed ?? [] + const recentlyPlayed = (user.recentlyPlayed ?? []).slice(0, limit) if (recentlyPlayed.length === 0) { return [] } - const artistMap = await loadArtistMap(ctx) - const items: (BrowseAlbum | PlaylistSummary)[] = [] + const loaded = await Promise.all( + recentlyPlayed.map(async (id) => { + const albumId = ctx.db.normalizeId("albums", id) + if (albumId !== null) { + const album = await ctx.db.get("albums", albumId) + return album ? ({ kind: "album", album } as const) : null + } - for (const id of recentlyPlayed) { - const albumId = ctx.db.normalizeId("albums", id) - if (albumId !== null) { - const album = await ctx.db.get("albums", albumId) - if (album) { - const artist = artistMap.get(album.artist) - if (artist) { - items.push(toBrowseAlbum(album, artist)) - } + const playlistId = ctx.db.normalizeId("playlists", id) + if (playlistId === null) { + return null + } + + const playlist = await ctx.db.get("playlists", playlistId) + return playlist ? ({ kind: "playlist", playlist } as const) : null + }) + ) + + const artistMap = await loadArtistMapForIds( + ctx, + loaded.flatMap((entry) => + entry?.kind === "album" ? [entry.album.artist] : [] + ) + ) + const ownerIds = [ + ...new Set( + loaded.flatMap((entry) => + entry?.kind === "playlist" ? [entry.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] : [])) + ) + + const items: (BrowseAlbum | PlaylistSummary)[] = [] + for (const entry of loaded) { + if (!entry) { + continue + } + if (entry.kind === "album") { + const artist = artistMap.get(entry.album.artist) + if (artist) { + items.push(toBrowseAlbum(entry.album, artist)) } continue } - - const playlistId = ctx.db.normalizeId("playlists", id) - if (playlistId === null) { - continue - } - - const playlist = await ctx.db.get("playlists", playlistId) - if (playlist) { - const owner = await ctx.db.get("users", playlist.owner) - items.push({ - id: playlist._id, - title: playlist.name, - owner: owner?.name ?? "Unknown", - cover: playlist.cover, - }) - } + items.push({ + id: entry.playlist._id, + title: entry.playlist.name, + owner: ownerMap.get(entry.playlist.owner)?.name ?? "Unknown", + cover: entry.playlist.cover, + }) } return items } export const browseRecentlyPlayed = query({ - args: {}, - handler: async (ctx) => browseRecentlyPlayedItems(ctx), + args: { limit: v.optional(v.number()) }, + handler: async (ctx, args) => browseRecentlyPlayedItems(ctx, args.limit), }) export const browseRecentlyPlayedPaginated = query({ @@ -830,21 +868,21 @@ export const browseRecentlyPlayedPaginated = query({ }, }) -export const getArtists = query({ +export const getArtists = internalQuery({ args: {}, handler: async (ctx) => { return await ctx.db.query("artists").collect() }, }) -export const getAlbums = query({ +export const getAlbums = internalQuery({ args: {}, handler: async (ctx) => { return await ctx.db.query("albums").collect() }, }) -export const getAlbumsInArtist = query({ +export const getAlbumsInArtist = internalQuery({ args: { artistID: v.id("artists") }, handler: async (ctx, args) => { return await ctx.db @@ -854,14 +892,14 @@ export const getAlbumsInArtist = query({ }, }) -export const getSongs = query({ +export const getSongs = internalQuery({ args: {}, handler: async (ctx) => { return await ctx.db.query("songs").collect() }, }) -export const getSongsInArtist = query({ +export const getSongsInArtist = internalQuery({ args: { artistID: v.id("artists") }, handler: async (ctx, args) => { return await ctx.db @@ -871,7 +909,7 @@ export const getSongsInArtist = query({ }, }) -export const getSongsInAlbum = query({ +export const getSongsInAlbum = internalQuery({ args: { albumID: v.id("albums") }, handler: async (ctx, args) => { return await ctx.db @@ -888,7 +926,7 @@ export const getArtist = query({ }, }) -export const getArtistByName = query({ +export const getArtistByName = internalQuery({ args: { name: v.string() }, handler: async (ctx, args) => { return await ctx.db @@ -905,7 +943,7 @@ export const getAlbum = query({ }, }) -export const getAlbumByName = query({ +export const getAlbumByName = internalQuery({ args: { name: v.string() }, handler: async (ctx, args) => { return await ctx.db @@ -915,15 +953,13 @@ export const getAlbumByName = query({ }, }) -export const getAlbumByAll = query({ +export const getAlbumByAll = internalQuery({ args: { folder: v.string(), artist: v.id("artists") }, handler: async (ctx, args) => { return await ctx.db .query("albums") .withIndex("by_all", (q) => - q - .eq("artist", args.artist) - .eq("folder", args.folder) + q.eq("artist", args.artist).eq("folder", args.folder) ) .first() }, @@ -943,9 +979,38 @@ export const getSong = query({ }, }) +function playbackCodecMap(files: Record) { + return Object.fromEntries(Object.keys(files).map((codec) => [codec, true])) +} + +export const getSongPlaybackInfo = query({ + args: { id: v.id("songs") }, + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx) + if (userId === null) { + return null + } + + const song = await ctx.db.get("songs", args.id) + if (!song) { + return null + } + + return { + id: song._id, + files: playbackCodecMap(song.files), + } + }, +}) + export const getSongsForPlayback = query({ args: { ids: v.array(v.id("songs")) }, handler: async (ctx, { ids }) => { + const userId = await getAuthUserId(ctx) + if (userId === null) { + return ids.map(() => null) + } + const songs = await Promise.all(ids.map((id) => ctx.db.get(id))) return songs.map((song, index) => { if (!song) { @@ -954,13 +1019,13 @@ export const getSongsForPlayback = query({ return { id: ids[index], title: song.name, - files: song.files, + files: playbackCodecMap(song.files), } }) }, }) -export const getSongByName = query({ +export const getSongByName = internalQuery({ args: { name: v.string() }, handler: async (ctx, args) => { return await ctx.db @@ -970,7 +1035,7 @@ export const getSongByName = query({ }, }) -export const getSongByAll = query({ +export const getSongByAll = internalQuery({ args: { name: v.string(), albumArtist: v.id("artists"), @@ -989,27 +1054,45 @@ export const getSongByAll = query({ }, }) -export const createArtist = mutation({ +export const createArtist = internalMutation({ args: { name: v.string(), folder: v.string(), cover: v.nullable(v.string()) }, handler: async (ctx, args) => { + const existing = await ctx.db + .query("artists") + .withIndex("by_folder", (q) => q.eq("folder", args.folder)) + .first() + if (existing) { + return existing._id + } return await ctx.db.insert("artists", args) }, }) -export const createArtists = mutation({ +export const createArtists = internalMutation({ args: { artists: v.array( - v.object({ name: v.string(), folder: v.string(), cover: v.nullable(v.string()) }) + v.object({ + name: v.string(), + folder: v.string(), + cover: v.nullable(v.string()), + }) ), }, handler: async (ctx, args) => { for (const artist of args.artists) { + const existing = await ctx.db + .query("artists") + .withIndex("by_folder", (q) => q.eq("folder", artist.folder)) + .first() + if (existing) { + continue + } await ctx.db.insert("artists", artist) } }, }) -export const createAlbum = mutation({ +export const createAlbum = internalMutation({ args: { name: v.string(), folder: v.string(), @@ -1019,11 +1102,20 @@ export const createAlbum = mutation({ artist: v.id("artists"), }, handler: async (ctx, args) => { + const existing = await ctx.db + .query("albums") + .withIndex("by_all", (q) => + q.eq("artist", args.artist).eq("folder", args.folder) + ) + .first() + if (existing) { + return existing._id + } return await ctx.db.insert("albums", args) }, }) -export const createAlbums = mutation({ +export const createAlbums = internalMutation({ args: { albums: v.array( v.object({ @@ -1038,12 +1130,21 @@ export const createAlbums = mutation({ }, handler: async (ctx, args) => { for (const album of args.albums) { + const existing = await ctx.db + .query("albums") + .withIndex("by_all", (q) => + q.eq("artist", album.artist).eq("folder", album.folder) + ) + .first() + if (existing) { + continue + } await ctx.db.insert("albums", album) } }, }) -export const updateAlbumName = mutation({ +export const updateAlbumName = internalMutation({ args: { id: v.id("albums"), newName: v.string(), @@ -1053,7 +1154,7 @@ export const updateAlbumName = mutation({ }, }) -export const createSong = mutation({ +export const createSong = internalMutation({ args: { name: v.string(), files: v.record(v.string(), v.string()), @@ -1068,11 +1169,26 @@ export const createSong = mutation({ genres: v.array(v.string()), }, handler: async (ctx, args) => { + const existing = await ctx.db + .query("songs") + .withIndex("by_all", (q) => + q + .eq("name", args.name) + .eq("albumArtist", args.albumArtist) + .eq("album", args.album) + ) + .first() + if (existing) { + await ctx.db.patch(existing._id, { + files: { ...existing.files, ...args.files }, + }) + return existing._id + } return await ctx.db.insert("songs", args) }, }) -export const createSongs = mutation({ +export const createSongs = internalMutation({ args: { songs: v.array( v.object({ @@ -1092,6 +1208,21 @@ export const createSongs = mutation({ }, handler: async (ctx, args) => { for (const song of args.songs) { + const existing = await ctx.db + .query("songs") + .withIndex("by_all", (q) => + q + .eq("name", song.name) + .eq("albumArtist", song.albumArtist) + .eq("album", song.album) + ) + .first() + if (existing) { + await ctx.db.patch(existing._id, { + files: { ...existing.files, ...song.files }, + }) + continue + } await ctx.db.insert("songs", song) } @@ -1099,7 +1230,7 @@ export const createSongs = mutation({ }, }) -export const purgeSongsFromUsersAndPlaylists = mutation({ +export const purgeSongsFromUsersAndPlaylists = internalMutation({ args: { ids: v.array(v.id("songs")) }, handler: async (ctx, args) => { const remove = new Set(args.ids) @@ -1117,16 +1248,40 @@ export const purgeSongsFromUsersAndPlaylists = mutation({ for (const user of await ctx.db.query("users").collect()) { const favoriteSongs = user.favoriteSongs + const songQueue = user.songQueue + const queueHistory = user.queueHistory + const patch: Partial< + Pick< + Doc<"users">, + "favoriteSongs" | "songQueue" | "queueHistory" | "currentSongProgress" + > + > = {} + if (favoriteSongs?.some((songId) => remove.has(songId))) { - await ctx.db.patch(user._id, { - favoriteSongs: favoriteSongs.filter((songId) => !remove.has(songId)), - }) + patch.favoriteSongs = favoriteSongs.filter( + (songId) => !remove.has(songId) + ) + } + if (songQueue?.some((songId) => remove.has(songId))) { + const currentRemoved = remove.has(songQueue[0]) + patch.songQueue = songQueue.filter((songId) => !remove.has(songId)) + if (currentRemoved) { + patch.currentSongProgress = 0 + } + } + if (queueHistory?.some((songId) => remove.has(songId))) { + patch.queueHistory = queueHistory.filter( + (songId) => !remove.has(songId) + ) + } + if (Object.keys(patch).length > 0) { + await ctx.db.patch(user._id, patch) } } }, }) -export const purgeAlbumsFromUsers = mutation({ +export const purgeAlbumsFromUsers = internalMutation({ args: { ids: v.array(v.id("albums")) }, handler: async (ctx, args) => { const remove = new Set(args.ids) @@ -1136,18 +1291,30 @@ export const purgeAlbumsFromUsers = mutation({ for (const user of await ctx.db.query("users").collect()) { const favoriteAlbums = user.favoriteAlbums + const recentlyPlayed = user.recentlyPlayed + const patch: Partial< + Pick, "favoriteAlbums" | "recentlyPlayed"> + > = {} if (favoriteAlbums?.some((albumId) => remove.has(albumId))) { - await ctx.db.patch(user._id, { - favoriteAlbums: favoriteAlbums.filter( - (albumId) => !remove.has(albumId) - ), - }) + patch.favoriteAlbums = favoriteAlbums.filter( + (albumId) => !remove.has(albumId) + ) + } + if ( + recentlyPlayed?.some((itemId) => remove.has(itemId as Id<"albums">)) + ) { + patch.recentlyPlayed = recentlyPlayed.filter( + (itemId) => !remove.has(itemId as Id<"albums">) + ) + } + if (Object.keys(patch).length > 0) { + await ctx.db.patch(user._id, patch) } } }, }) -export const purgeArtistsFromUsers = mutation({ +export const purgeArtistsFromUsers = internalMutation({ args: { ids: v.array(v.id("artists")) }, handler: async (ctx, args) => { const remove = new Set(args.ids) @@ -1168,14 +1335,14 @@ export const purgeArtistsFromUsers = mutation({ }, }) -export const removeArtist = mutation({ +export const removeArtist = internalMutation({ args: { id: v.id("artists") }, handler: async (ctx, args) => { return await ctx.db.delete("artists", args.id) }, }) -export const removeArtists = mutation({ +export const removeArtists = internalMutation({ args: { ids: v.array(v.id("artists")) }, handler: async (ctx, args) => { for (const id of args.ids) { @@ -1184,14 +1351,14 @@ export const removeArtists = mutation({ }, }) -export const removeAlbum = mutation({ +export const removeAlbum = internalMutation({ args: { id: v.id("albums") }, handler: async (ctx, args) => { return await ctx.db.delete("albums", args.id) }, }) -export const removeAlbums = mutation({ +export const removeAlbums = internalMutation({ args: { ids: v.array(v.id("albums")) }, handler: async (ctx, args) => { for (const id of args.ids) { @@ -1200,21 +1367,21 @@ export const removeAlbums = mutation({ }, }) -export const removeSong = mutation({ +export const removeSong = internalMutation({ args: { id: v.id("songs") }, handler: async (ctx, args) => { return await ctx.db.delete("songs", args.id) }, }) -export const changeFilesForSong = mutation({ +export const changeFilesForSong = internalMutation({ args: { id: v.id("songs"), files: v.record(v.string(), v.string()) }, handler: async (ctx, args) => { return await ctx.db.patch("songs", args.id, { files: args.files }) }, }) -export const changeFilesForSongs = mutation({ +export const changeFilesForSongs = internalMutation({ args: { songs: v.array( v.object({ id: v.id("songs"), files: v.record(v.string(), v.string()) }) @@ -1228,21 +1395,21 @@ export const changeFilesForSongs = mutation({ }, }) -export const updateArtistCover = mutation({ +export const updateArtistCover = internalMutation({ args: { id: v.id("artists"), cover: v.nullable(v.string()) }, handler: async (ctx, args) => { return await ctx.db.patch("artists", args.id, { cover: args.cover }) }, }) -export const updateAlbumCover = mutation({ +export const updateAlbumCover = internalMutation({ args: { id: v.id("albums"), cover: v.nullable(v.string()) }, handler: async (ctx, args) => { return await ctx.db.patch("albums", args.id, { cover: args.cover }) }, }) -export const removeSongs = mutation({ +export const removeSongs = internalMutation({ args: { ids: v.array(v.id("songs")) }, handler: async (ctx, args) => { for (const id of args.ids) { diff --git a/packages/convex/convex/playback.ts b/packages/convex/convex/playback.ts index b67cb08..119238d 100644 --- a/packages/convex/convex/playback.ts +++ b/packages/convex/convex/playback.ts @@ -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, 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 }) }, }) diff --git a/packages/convex/convex/playlists.ts b/packages/convex/convex/playlists.ts index 7c91763..c90b733 100644 --- a/packages/convex/convex/playlists.ts +++ b/packages/convex/convex/playlists.ts @@ -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, Doc<"artists">>, - albumMap: Map, Doc<"albums">> -): Promise { - 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 + ), + } + : {}), }) } diff --git a/packages/convex/convex/schema.ts b/packages/convex/convex/schema.ts index 4ba4ca5..4ef725c 100644 --- a/packages/convex/convex/schema.ts +++ b/packages/convex/convex/schema.ts @@ -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(), diff --git a/packages/convex/convex/types.ts b/packages/convex/convex/types.ts index 42da5eb..f165925 100644 --- a/packages/convex/convex/types.ts +++ b/packages/convex/convex/types.ts @@ -46,8 +46,6 @@ export type BrowseAlbumSummary = Omit & { export type BrowseArtistDetail = { artist: BrowseArtist albums: BrowseAlbum[] - recentlyAdded: BrowseAlbum[] - recentlyPlayed: BrowseAlbum[] } export type PlaylistSummary = { diff --git a/packages/convex/convex/users.ts b/packages/convex/convex/users.ts index fb1c83d..8836f81 100644 --- a/packages/convex/convex/users.ts +++ b/packages/convex/convex/users.ts @@ -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, }, }) - }, }) diff --git a/packages/convex/playback-stream.ts b/packages/convex/playback-stream.ts index b97862e..9e7a461 100644 --- a/packages/convex/playback-stream.ts +++ b/packages/convex/playback-stream.ts @@ -24,17 +24,18 @@ export type PlaybackStreamPlan = { } export function playbackStreamPlan( - files: Record, + files: Record, 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, } }