Compare commits
2
Commits
No files matched your search
@@ -26,7 +26,6 @@ import {
|
||||
} from "@/lib/artwork-color-preference"
|
||||
import { initialsFromName } from "@/lib/format"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useProfileImageUrl } from "@/hooks/use-profile-image-url"
|
||||
import { changeServer, signOut } from "@/lib/session"
|
||||
import { radius, spacing, useThemeColors } from "@/lib/theme"
|
||||
import { showError } from "@/lib/toast"
|
||||
@@ -769,7 +768,6 @@ function ProfileAvatar({
|
||||
style?: StyleProp<ViewStyle>
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
const imageUrl = useProfileImageUrl(user.image)
|
||||
const avatarStyle = [
|
||||
styles.avatar,
|
||||
{
|
||||
@@ -781,11 +779,11 @@ function ProfileAvatar({
|
||||
style,
|
||||
]
|
||||
|
||||
if (imageUrl) {
|
||||
if (user.image) {
|
||||
return (
|
||||
<View style={avatarStyle}>
|
||||
<Image
|
||||
source={{ uri: imageUrl }}
|
||||
source={{ uri: user.image }}
|
||||
style={styles.avatarImage}
|
||||
contentFit="cover"
|
||||
/>
|
||||
|
||||
@@ -4,7 +4,6 @@ import { Image } from "expo-image"
|
||||
import { Pressable, StyleSheet, Text, View } from "react-native"
|
||||
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useProfileImageUrl } from "@/hooks/use-profile-image-url"
|
||||
import { initialsFromName } from "@/lib/format"
|
||||
import { radius, useThemeColors } from "@/lib/theme"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
@@ -14,7 +13,6 @@ export function ProfileHeaderButton() {
|
||||
const openSettings = useOpenSettings()
|
||||
const colors = useThemeColors()
|
||||
const user = useCachedQuery(api.auth.currentUser)
|
||||
const imageUrl = useProfileImageUrl(user?.image)
|
||||
|
||||
if (tabletLayout) return null
|
||||
|
||||
@@ -35,9 +33,9 @@ export function ProfileHeaderButton() {
|
||||
},
|
||||
]}
|
||||
>
|
||||
{imageUrl ? (
|
||||
{user?.image ? (
|
||||
<Image
|
||||
source={{ uri: imageUrl }}
|
||||
source={{ uri: user.image }}
|
||||
style={styles.image}
|
||||
contentFit="cover"
|
||||
/>
|
||||
|
||||
@@ -4,7 +4,6 @@ import { useIsFocused } from "expo-router"
|
||||
import { Platform, type ViewProps } from "react-native"
|
||||
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useProfileImageUrl } from "@/hooks/use-profile-image-url"
|
||||
import { initialsFromName } from "@/lib/format"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
@@ -23,7 +22,6 @@ const NativeSidebar =
|
||||
|
||||
export function TabletSidebar() {
|
||||
const user = useCachedQuery(api.auth.currentUser)
|
||||
const imageUrl = useProfileImageUrl(user?.image)
|
||||
const openSettings = useOpenSettings()
|
||||
const active = useIsFocused()
|
||||
|
||||
@@ -33,7 +31,7 @@ export function TabletSidebar() {
|
||||
style={{ position: "absolute", width: 0, height: 0 }}
|
||||
accountName={user?.name ?? "Account"}
|
||||
initials={initialsFromName(user?.name ?? "Me")}
|
||||
imageURL={imageUrl}
|
||||
imageURL={user?.image}
|
||||
active={active}
|
||||
onProfilePress={openSettings}
|
||||
/>
|
||||
|
||||
@@ -203,19 +203,17 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSignedIn) return
|
||||
store.setTransport({
|
||||
sync: (state) =>
|
||||
syncPlaybackStateMutation({
|
||||
songQueue: state.queue,
|
||||
queueHistory: state.history,
|
||||
shuffleEnabled: state.shuffleEnabled,
|
||||
repeatEnabled: state.repeatEnabled,
|
||||
currentSongProgress: state.progressSeconds,
|
||||
}),
|
||||
loadProgress: () => convex.query(api.playback.getSongProgress, {}),
|
||||
})
|
||||
store.setTransport((state) =>
|
||||
syncPlaybackStateMutation({
|
||||
songQueue: state.queue,
|
||||
queueHistory: state.history,
|
||||
shuffleEnabled: state.shuffleEnabled,
|
||||
repeatEnabled: state.repeatEnabled,
|
||||
currentSongProgress: state.progressSeconds,
|
||||
})
|
||||
)
|
||||
return () => store.setTransport(null)
|
||||
}, [store, isSignedIn, syncPlaybackStateMutation, convex])
|
||||
}, [store, isSignedIn, syncPlaybackStateMutation])
|
||||
|
||||
useEffect(() => {
|
||||
if (!serverPlayback) return
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
|
||||
/**
|
||||
* Resolves `currentUser.image` to a loadable URI. Stored avatars come back as
|
||||
* paths on the oTunes web server; legacy ones are data URLs.
|
||||
*/
|
||||
export function useProfileImageUrl(image: string | undefined) {
|
||||
const { config } = useServerConfig()
|
||||
if (!image?.startsWith("/")) {
|
||||
return image
|
||||
}
|
||||
return config ? `${config.serverUrl.replace(/\/+$/, "")}${image}` : undefined
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import { convexServerOptions } from "@/lib/convex-server"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { Metadata } from "next"
|
||||
|
||||
interface PageProps {
|
||||
@@ -12,12 +11,12 @@ export async function generateMetadata({
|
||||
params,
|
||||
}: PageProps): Promise<Metadata> {
|
||||
const { id } = await params
|
||||
const detail = await fetchQuery(
|
||||
api.library.browseArtistDetail,
|
||||
{ id: id as Id<"artists"> },
|
||||
const artists = await fetchQuery(
|
||||
api.library.browseArtists,
|
||||
{},
|
||||
convexServerOptions()
|
||||
).catch(() => null)
|
||||
const selectedArtist = detail?.artist
|
||||
)
|
||||
const selectedArtist = artists.find((artist) => artist.id === id)
|
||||
|
||||
return {
|
||||
title: `${selectedArtist ? `${selectedArtist.name}` : "oTunes"}`,
|
||||
|
||||
@@ -10,10 +10,10 @@ export async function GET(
|
||||
const { id } = await params
|
||||
|
||||
try {
|
||||
const cover = await getConvexClient().query(api.library.getAlbumCover, {
|
||||
const album = await getConvexClient().query(api.library.getAlbum, {
|
||||
id: id as Id<"albums">,
|
||||
})
|
||||
return serveCoverFile(cover, request)
|
||||
return serveCoverFile(album?.cover, request)
|
||||
} catch {
|
||||
return new Response("Not found", { status: 404 })
|
||||
}
|
||||
|
||||
@@ -10,10 +10,10 @@ export async function GET(
|
||||
const { id } = await params
|
||||
|
||||
try {
|
||||
const cover = await getConvexClient().query(api.library.getArtistCover, {
|
||||
const artist = await getConvexClient().query(api.library.getArtist, {
|
||||
id: id as Id<"artists">,
|
||||
})
|
||||
return serveCoverFile(cover, request)
|
||||
return serveCoverFile(artist?.cover, request)
|
||||
} catch {
|
||||
return new Response("Not found", { status: 404 })
|
||||
}
|
||||
|
||||
@@ -9,10 +9,10 @@ export async function GET(
|
||||
) {
|
||||
const { id } = await params
|
||||
try {
|
||||
const cover = await getConvexClient().query(api.library.getPlaylistCover, {
|
||||
const playlist = await getConvexClient().query(api.library.getPlaylist, {
|
||||
id: id as Id<"playlists">,
|
||||
})
|
||||
return serveCoverFile(cover, request)
|
||||
return serveCoverFile(playlist?.cover, request)
|
||||
} catch {
|
||||
return new Response("Not found", { status: 404 })
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { getSongSource } from "@/lib/server-song"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { getConvexClient } from "@/lib/convex-server"
|
||||
import { ensureHlsJob, HLS_SEGMENT_SECONDS } from "@/lib/server-hls"
|
||||
import { NextRequest } from "next/server"
|
||||
|
||||
@@ -15,7 +17,9 @@ export async function GET(
|
||||
const { id } = await params
|
||||
|
||||
try {
|
||||
const song = await getSongSource(id)
|
||||
const song = (await getConvexClient().query(api.library.getSong, {
|
||||
id: id as Id<"songs">,
|
||||
}))!
|
||||
|
||||
const quality = request.nextUrl.searchParams.get("quality")
|
||||
const preferAtmos =
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { getSongSource } from "@/lib/server-song"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { getConvexClient } from "@/lib/convex-server"
|
||||
import {
|
||||
ensureHlsJob,
|
||||
getExistingHlsJob,
|
||||
@@ -34,11 +36,16 @@ export async function GET(
|
||||
const quality = request.nextUrl.searchParams.get("quality")
|
||||
const preferAtmos =
|
||||
request.nextUrl.searchParams.get("preferAtmos") === "true"
|
||||
// Resolve the source even when a job is cached so every segment is authorized.
|
||||
const song = await getSongSource(id)
|
||||
const existingJob = getExistingHlsJob(id, quality, preferAtmos)
|
||||
const job =
|
||||
getExistingHlsJob(id, quality, preferAtmos) ??
|
||||
(await ensureHlsJob(song, quality, preferAtmos))
|
||||
existingJob ??
|
||||
(await ensureHlsJob(
|
||||
(await getConvexClient().query(api.library.getSong, {
|
||||
id: id as Id<"songs">,
|
||||
}))!,
|
||||
quality,
|
||||
preferAtmos
|
||||
))
|
||||
if (segmentIndex >= job.segmentCount) {
|
||||
return new Response("Segment not found", { status: 404 })
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { audioContentTypeForPath } from "@/lib/audio-content-type"
|
||||
import { seekableLosslessFile } from "@/lib/server-lossless"
|
||||
import { getSongSource } from "@/lib/server-song"
|
||||
import { audioInfo } from "@/lib/server-audio-info"
|
||||
import { getConvexClient } from "@/lib/convex-server"
|
||||
import { ffmpegToReadableStream, streamFile } from "@/lib/server-audio-stream"
|
||||
import { spawnFfmpeg } from "@/lib/server-ffmpeg"
|
||||
import { NextRequest, NextResponse, userAgent } from "next/server"
|
||||
import { spawn } from "node:child_process"
|
||||
import fs from "node:fs/promises"
|
||||
import * as music from "music-metadata"
|
||||
|
||||
function parseByteRange(rangeHeader: string | null, fileSize: number) {
|
||||
if (!rangeHeader) {
|
||||
@@ -116,7 +118,9 @@ export async function GET(
|
||||
const { browser } = userAgent(request)
|
||||
|
||||
try {
|
||||
const song = await getSongSource(id)
|
||||
const song = (await getConvexClient().query(api.library.getSong, {
|
||||
id: id as Id<"songs">,
|
||||
}))!
|
||||
|
||||
const quality = request.nextUrl.searchParams.get("quality") as
|
||||
"low" | "medium" | "high" | "lossless" | null
|
||||
@@ -147,15 +151,14 @@ export async function GET(
|
||||
transcodeNeeded = false
|
||||
}
|
||||
|
||||
const metadata = await music.parseFile(song.files[originalCodec])
|
||||
|
||||
if (!transcodeNeeded && originalCodec === "lossless") {
|
||||
// Native iOS playback does not identify itself as Safari.
|
||||
const acceptsAlac =
|
||||
browser.name === "Safari" ||
|
||||
request.nextUrl.searchParams.get("losslessFormat") === "alac"
|
||||
if (
|
||||
acceptsAlac &&
|
||||
(await audioInfo(song.files[originalCodec])).codec === "ALAC"
|
||||
) {
|
||||
if (acceptsAlac && metadata.format.codec === "ALAC") {
|
||||
try {
|
||||
return await streamFileResponse(
|
||||
request,
|
||||
@@ -180,6 +183,11 @@ export async function GET(
|
||||
(originalCodec === "atmos" || originalCodec === "normal")
|
||||
) {
|
||||
// TODO: Dolby Atmos doesn't work on Google Chrome
|
||||
console.log(
|
||||
metadata.format.codec,
|
||||
metadata.format.container,
|
||||
metadata.format.codecProfile
|
||||
)
|
||||
try {
|
||||
return await streamFileResponse(
|
||||
request,
|
||||
@@ -192,6 +200,7 @@ export async function GET(
|
||||
}
|
||||
|
||||
const ffmpegArgs = [
|
||||
"-nostdin",
|
||||
"-i",
|
||||
song.files[originalCodec],
|
||||
"-c:a",
|
||||
@@ -205,8 +214,8 @@ export async function GET(
|
||||
|
||||
try {
|
||||
// TODO: Fix seeking for this
|
||||
const ffmpeg = await spawnFfmpeg(ffmpegArgs, request.signal)
|
||||
const stream = ffmpegToReadableStream(ffmpeg)
|
||||
const ffmpegProcess = spawn("ffmpeg", ffmpegArgs)
|
||||
const stream = ffmpegToReadableStream(ffmpegProcess)
|
||||
|
||||
return new NextResponse(stream, {
|
||||
status: 200,
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import sharp from "sharp"
|
||||
import { getConvexClient, getConvexServerUrl } from "@/lib/convex-server"
|
||||
|
||||
const AVATAR_SIZE = 256
|
||||
|
||||
/**
|
||||
* Serves a profile photo from Convex storage, downscaled. URLs carry the
|
||||
* storage id (`?v=`), so a new photo gets a new URL and responses can be
|
||||
* cached for good.
|
||||
*/
|
||||
export async function GET(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const { id } = await params
|
||||
try {
|
||||
const storageUrl = await getConvexClient().query(
|
||||
api.users.getProfileImageUrl,
|
||||
{ userId: id as Id<"users"> }
|
||||
)
|
||||
if (!storageUrl) {
|
||||
return new Response("Not found", { status: 404 })
|
||||
}
|
||||
|
||||
// The backend builds storage URLs from its public origin, which may not
|
||||
// be reachable from here. Fetch the same path from the internal URL.
|
||||
const { pathname, search } = new URL(storageUrl)
|
||||
const upstream = await fetch(
|
||||
new URL(pathname + search, getConvexServerUrl())
|
||||
)
|
||||
if (!upstream.ok) {
|
||||
return new Response("Not found", { status: 404 })
|
||||
}
|
||||
|
||||
const data = await sharp(Buffer.from(await upstream.arrayBuffer()))
|
||||
.rotate()
|
||||
.resize(AVATAR_SIZE, AVATAR_SIZE, {
|
||||
fit: "cover",
|
||||
withoutEnlargement: true,
|
||||
})
|
||||
.webp({ quality: 85 })
|
||||
.toBuffer()
|
||||
|
||||
return new Response(new Uint8Array(data), {
|
||||
headers: {
|
||||
"Content-Type": "image/webp",
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
},
|
||||
})
|
||||
} catch {
|
||||
return new Response("Not found", { status: 404 })
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
MediaContextMenuItems,
|
||||
type MediaContextAction,
|
||||
} from "@/components/media-context-menu"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
@@ -48,7 +48,7 @@ export function AlbumCard({ album }: { album: BrowseAlbum }) {
|
||||
const cacheScope = useCacheScope()
|
||||
const { openAddAlbumToPlaylist } = useAddToPlaylist()
|
||||
const { isAlbumFavorite, toggleAlbumFavorite } = useFavorites()
|
||||
const { playAlbum } = usePlaybackActions()
|
||||
const { playAlbum } = usePlayback()
|
||||
const { runQueueAction, createStation } = useQueueMediaActions()
|
||||
const [menuOpen, setMenuOpen] = React.useState(false)
|
||||
const [hovered, setHovered] = React.useState(false)
|
||||
|
||||
@@ -11,10 +11,7 @@ import { MediaCollectionFooter } from "@/components/media-collection-footer"
|
||||
|
||||
import { FavoriteMediaButton } from "@/components/favorite-media-button"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import {
|
||||
useCurrentSongId,
|
||||
usePlaybackActions,
|
||||
} from "@/components/playback-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { copyAlbumLink } from "@/lib/media-links"
|
||||
|
||||
import {
|
||||
@@ -108,8 +105,8 @@ export function AlbumView({
|
||||
toggleSongFavorite,
|
||||
toggleAlbumFavorite,
|
||||
} = useFavorites()
|
||||
const currentSongId = useCurrentSongId()
|
||||
const { playFromSong, playAlbum, playAlbumShuffled } = usePlaybackActions()
|
||||
const { currentSong, playFromSong, playAlbum, playAlbumShuffled } =
|
||||
usePlayback()
|
||||
const { runSongsAction } = useMediaActions()
|
||||
const albumSongIds = React.useMemo(
|
||||
() => album.tracks.map((track) => track.id as Id<"songs">),
|
||||
@@ -369,7 +366,7 @@ export function AlbumView({
|
||||
isFavorite={isSongFavorite(track.id)}
|
||||
selectedCount={selectedCount}
|
||||
selectionStationArtistId={album.artist.id}
|
||||
isNowPlaying={currentSongId === track.id}
|
||||
isNowPlaying={currentSong?.id === track.id}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={handleRowSelect}
|
||||
onPlay={handleRowPlay}
|
||||
|
||||
@@ -6,7 +6,7 @@ import Image from "next/image"
|
||||
import { Play, Shuffle } from "lucide-react"
|
||||
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { useMediaActions } from "@/hooks/use-media-actions"
|
||||
import { AlbumCard } from "@/components/album-card"
|
||||
import { FavoriteMediaButton } from "@/components/favorite-media-button"
|
||||
@@ -26,7 +26,7 @@ export function ArtistView({
|
||||
albums: BrowseAlbum[]
|
||||
}) {
|
||||
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
|
||||
const { playArtist, playArtistShuffled } = usePlaybackActions()
|
||||
const { playArtist, playArtistShuffled } = usePlayback()
|
||||
const { runArtistAction } = useMediaActions()
|
||||
|
||||
return (
|
||||
|
||||
@@ -11,10 +11,8 @@ import { useFavorites } from "@/components/favorites-provider"
|
||||
import {
|
||||
MediaContextMenu,
|
||||
type MediaContextAction,
|
||||
MediaContextMenuArea,
|
||||
type MediaContextMenuProps,
|
||||
} from "@/components/media-context-menu"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { useMediaActions } from "@/hooks/use-media-actions"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
@@ -52,42 +50,36 @@ function ArtistListItem({
|
||||
onSelect: () => void
|
||||
onMediaAction: (action: MediaContextAction) => void
|
||||
}) {
|
||||
const menu: MediaContextMenuProps = {
|
||||
label: `More options for ${artist.name}`,
|
||||
selectedCount: albumCount,
|
||||
inSelectionRange: isSelected,
|
||||
onOpenMenu: () => {},
|
||||
onAction: onMediaAction,
|
||||
favorited: isFavorite,
|
||||
share: { type: "artist", artistId: artist.id },
|
||||
}
|
||||
|
||||
return (
|
||||
<MediaContextMenuArea menu={menu}>
|
||||
<div
|
||||
<div
|
||||
className={cn(
|
||||
"group flex w-full min-w-0 items-center gap-1 overflow-hidden pr-1",
|
||||
isSelected ? "bg-primary text-primary-foreground" : "hover:bg-muted/50"
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onSelect}
|
||||
className={cn(
|
||||
"group flex w-full min-w-0 items-center gap-1 overflow-hidden pr-1",
|
||||
isSelected
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "hover:bg-muted/50"
|
||||
"flex min-w-0 flex-1 items-center gap-3 overflow-hidden px-4 py-2.5 text-left text-sm transition-colors",
|
||||
isSelected ? "text-primary-foreground" : ""
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onSelect}
|
||||
className={cn(
|
||||
"flex min-w-0 flex-1 items-center gap-3 overflow-hidden px-4 py-2.5 text-left text-sm transition-colors",
|
||||
isSelected ? "text-primary-foreground" : ""
|
||||
)}
|
||||
>
|
||||
<ArtistAvatar artist={artist} />
|
||||
<span className="min-w-0 flex-1 truncate font-medium">
|
||||
{artist.name}
|
||||
</span>
|
||||
</button>
|
||||
<MediaContextMenu {...menu} />
|
||||
</div>
|
||||
</MediaContextMenuArea>
|
||||
<ArtistAvatar artist={artist} />
|
||||
<span className="min-w-0 flex-1 truncate font-medium">
|
||||
{artist.name}
|
||||
</span>
|
||||
</button>
|
||||
<MediaContextMenu
|
||||
label={`More options for ${artist.name}`}
|
||||
selectedCount={albumCount}
|
||||
inSelectionRange={isSelected}
|
||||
onOpenMenu={() => {}}
|
||||
onAction={onMediaAction}
|
||||
favorited={isFavorite}
|
||||
share={{ type: "artist", artistId: artist.id }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -114,7 +106,7 @@ export function ArtistsView({
|
||||
return sortedArtists[0]?.id ?? ""
|
||||
}, [artistId, sortedArtists])
|
||||
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
|
||||
const { playArtist, playArtistShuffled } = usePlaybackActions()
|
||||
const { playArtist, playArtistShuffled } = usePlayback()
|
||||
const { runArtistAction } = useMediaActions()
|
||||
|
||||
const selectedArtist = sortedArtists.find(
|
||||
|
||||
@@ -15,13 +15,6 @@ import {
|
||||
} from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuTrigger,
|
||||
} from "@/components/ui/context-menu"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -60,28 +53,6 @@ function shouldShowShare(
|
||||
return true
|
||||
}
|
||||
|
||||
// Lets the same items render inside a dropdown or a right-click menu.
|
||||
const MenuKindContext = React.createContext<"dropdown" | "context">("dropdown")
|
||||
|
||||
/** Menu item that works in both `MediaContextMenu` and `MediaContextMenuArea`. */
|
||||
export function MediaMenuItem(
|
||||
props: React.ComponentProps<typeof DropdownMenuItem>
|
||||
) {
|
||||
return React.use(MenuKindContext) === "context" ? (
|
||||
<ContextMenuItem {...props} />
|
||||
) : (
|
||||
<DropdownMenuItem {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
export function MediaMenuSeparator() {
|
||||
return React.use(MenuKindContext) === "context" ? (
|
||||
<ContextMenuSeparator />
|
||||
) : (
|
||||
<DropdownMenuSeparator />
|
||||
)
|
||||
}
|
||||
|
||||
function actionLabel(base: string, selectedCount: number) {
|
||||
return selectedCount > 1 ? `${base} (${selectedCount})` : base
|
||||
}
|
||||
@@ -112,86 +83,86 @@ export function MediaContextMenuItems({
|
||||
<>
|
||||
{showShare ? (
|
||||
<>
|
||||
<MediaMenuItem
|
||||
<DropdownMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => void copyMediaShareLink(share!)}
|
||||
>
|
||||
Share
|
||||
<Share2 />
|
||||
</MediaMenuItem>
|
||||
<MediaMenuSeparator />
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
) : null}
|
||||
<MediaMenuItem
|
||||
<DropdownMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => onAction("playlist")}
|
||||
>
|
||||
{actionLabel(playlistLabel, selectedCount)}
|
||||
<ListPlus />
|
||||
</MediaMenuItem>
|
||||
<MediaMenuSeparator />
|
||||
<MediaMenuItem
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => onAction("play-next")}
|
||||
>
|
||||
{actionLabel("Play Next", selectedCount)}
|
||||
<ListStart />
|
||||
</MediaMenuItem>
|
||||
<MediaMenuItem
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => onAction("play-last")}
|
||||
>
|
||||
{actionLabel("Play Last", selectedCount)}
|
||||
<ListEnd />
|
||||
</MediaMenuItem>
|
||||
<MediaMenuItem
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => onAction("shuffle")}
|
||||
>
|
||||
{actionLabel("Shuffle", selectedCount)}
|
||||
<Shuffle />
|
||||
</MediaMenuItem>
|
||||
</DropdownMenuItem>
|
||||
{stationArtistId ? (
|
||||
<MediaMenuItem
|
||||
<DropdownMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => onAction("create-station")}
|
||||
>
|
||||
Create Station
|
||||
<Shuffle />
|
||||
</MediaMenuItem>
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{artist || album ? (
|
||||
<>
|
||||
<MediaMenuSeparator />
|
||||
<DropdownMenuSeparator />
|
||||
{artist ? (
|
||||
<MediaMenuItem asChild className="justify-between">
|
||||
<DropdownMenuItem asChild className="justify-between">
|
||||
<Link href={`/artist/${artist.id}`}>
|
||||
Go to Artist
|
||||
<MicVocal />
|
||||
</Link>
|
||||
</MediaMenuItem>
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{album ? (
|
||||
<MediaMenuItem asChild className="justify-between">
|
||||
<DropdownMenuItem asChild className="justify-between">
|
||||
<Link href={`/album/${album.id}`}>
|
||||
Go to Album
|
||||
<GalleryVerticalEnd />
|
||||
</Link>
|
||||
</MediaMenuItem>
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
{showFavorite ? (
|
||||
<>
|
||||
<MediaMenuSeparator />
|
||||
<MediaMenuItem
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
variant={favorited ? "destructive" : "default"}
|
||||
className="justify-between"
|
||||
onClick={() => onAction("favorite")}
|
||||
>
|
||||
{actionLabel(favorited ? "Unfavorite" : "Favorite", selectedCount)}
|
||||
<Star />
|
||||
</MediaMenuItem>
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
@@ -223,67 +194,6 @@ export function mediaContextMenuTriggerClassName({
|
||||
)
|
||||
}
|
||||
|
||||
export type MediaContextMenuProps = {
|
||||
label: string
|
||||
selectedCount: number
|
||||
onOpenMenu: () => void
|
||||
onAction: (action: MediaContextAction) => void
|
||||
playlistLabel?: string
|
||||
showFavorite?: boolean
|
||||
favorited?: boolean
|
||||
stationArtistId?: string
|
||||
navigation?: MediaContextNavigation
|
||||
share?: MediaShareContext
|
||||
inSelectionRange?: boolean
|
||||
/** When false, the trigger uses default button/dropdown styling (page headers). */
|
||||
trackRowTrigger?: boolean
|
||||
triggerClassName?: string
|
||||
triggerVariant?: "ghost" | "secondary"
|
||||
triggerIconClassName?: string
|
||||
align?: "start" | "end"
|
||||
/** Extra items; use `MediaMenuItem` so they also work in the right-click menu. */
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens `menu` (the props given to the row's `MediaContextMenu`) when
|
||||
* `children`, a single element such as a track row, is right-clicked.
|
||||
*/
|
||||
export function MediaContextMenuArea({
|
||||
menu,
|
||||
children,
|
||||
}: {
|
||||
menu: MediaContextMenuProps
|
||||
children: React.ReactElement
|
||||
}) {
|
||||
return (
|
||||
<ContextMenu
|
||||
onOpenChange={(open) => {
|
||||
if (open) {
|
||||
menu.onOpenMenu()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
|
||||
<ContextMenuContent className="w-48">
|
||||
<MenuKindContext value="context">
|
||||
<MediaContextMenuItems
|
||||
selectedCount={menu.selectedCount}
|
||||
onAction={menu.onAction}
|
||||
playlistLabel={menu.playlistLabel}
|
||||
showFavorite={menu.showFavorite}
|
||||
favorited={menu.favorited}
|
||||
stationArtistId={menu.stationArtistId}
|
||||
navigation={menu.navigation}
|
||||
share={menu.share}
|
||||
/>
|
||||
{menu.children}
|
||||
</MenuKindContext>
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
)
|
||||
}
|
||||
|
||||
export function MediaContextMenu({
|
||||
label,
|
||||
selectedCount,
|
||||
@@ -302,7 +212,26 @@ export function MediaContextMenu({
|
||||
triggerIconClassName = "size-4",
|
||||
align = "end",
|
||||
children,
|
||||
}: MediaContextMenuProps) {
|
||||
}: {
|
||||
label: string
|
||||
selectedCount: number
|
||||
onOpenMenu: () => void
|
||||
onAction: (action: MediaContextAction) => void
|
||||
playlistLabel?: string
|
||||
showFavorite?: boolean
|
||||
favorited?: boolean
|
||||
stationArtistId?: string
|
||||
navigation?: MediaContextNavigation
|
||||
share?: MediaShareContext
|
||||
inSelectionRange?: boolean
|
||||
/** When false, the trigger uses default button/dropdown styling (page headers). */
|
||||
trackRowTrigger?: boolean
|
||||
triggerClassName?: string
|
||||
triggerVariant?: "ghost" | "secondary"
|
||||
triggerIconClassName?: string
|
||||
align?: "start" | "end"
|
||||
children?: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenu
|
||||
onOpenChange={(open) => {
|
||||
|
||||
@@ -102,26 +102,7 @@ type PlaybackContextValue = {
|
||||
dolbyAtmosSupported: boolean | null
|
||||
}
|
||||
|
||||
type PlaybackActions = Omit<
|
||||
PlaybackContextValue,
|
||||
| "queueSongIds"
|
||||
| "queueHistorySongIds"
|
||||
| "currentFormat"
|
||||
| "currentSong"
|
||||
| "shuffleEnabled"
|
||||
| "repeatEnabled"
|
||||
| "queueOpen"
|
||||
| "isPlaying"
|
||||
| "volume"
|
||||
| "dolbyAtmosSupported"
|
||||
>
|
||||
|
||||
const PlaybackContext = createContext<PlaybackContextValue | null>(null)
|
||||
// Long lists read these narrow contexts so playback state changes do not
|
||||
// re-render every row.
|
||||
const PlaybackActionsContext = createContext<PlaybackActions | null>(null)
|
||||
const CurrentSongIdContext = createContext<Id<"songs"> | null>(null)
|
||||
const IsPlayingContext = createContext(false)
|
||||
const PlaybackProgressContext = createContext<{
|
||||
currentTime: number
|
||||
duration: number
|
||||
@@ -320,22 +301,6 @@ export function usePlayback() {
|
||||
return context
|
||||
}
|
||||
|
||||
export function usePlaybackActions() {
|
||||
const context = useContext(PlaybackActionsContext)
|
||||
if (!context) {
|
||||
throw new Error("usePlaybackActions must be used within PlaybackProvider")
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
export function useCurrentSongId() {
|
||||
return useContext(CurrentSongIdContext)
|
||||
}
|
||||
|
||||
export function useIsPlaying() {
|
||||
return useContext(IsPlayingContext)
|
||||
}
|
||||
|
||||
export function usePlaybackProgress() {
|
||||
const context = useContext(PlaybackProgressContext)
|
||||
if (!context) {
|
||||
@@ -374,19 +339,17 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
if (!isSignedIn) {
|
||||
return
|
||||
}
|
||||
store.setTransport({
|
||||
sync: (state) =>
|
||||
syncPlaybackStateMutation({
|
||||
songQueue: state.queue,
|
||||
queueHistory: state.history,
|
||||
shuffleEnabled: state.shuffleEnabled,
|
||||
repeatEnabled: state.repeatEnabled,
|
||||
currentSongProgress: state.progressSeconds,
|
||||
}),
|
||||
loadProgress: () => convex.query(api.playback.getSongProgress, {}),
|
||||
})
|
||||
store.setTransport((state) =>
|
||||
syncPlaybackStateMutation({
|
||||
songQueue: state.queue,
|
||||
queueHistory: state.history,
|
||||
shuffleEnabled: state.shuffleEnabled,
|
||||
repeatEnabled: state.repeatEnabled,
|
||||
currentSongProgress: state.progressSeconds,
|
||||
})
|
||||
)
|
||||
return () => store.setTransport(null)
|
||||
}, [store, isSignedIn, syncPlaybackStateMutation, convex])
|
||||
}, [store, isSignedIn, syncPlaybackStateMutation])
|
||||
|
||||
useEffect(() => {
|
||||
if (!serverPlayback) {
|
||||
@@ -1398,8 +1361,17 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
: null
|
||||
|
||||
const actions = useMemo<PlaybackActions>(
|
||||
const value = useMemo<PlaybackContextValue>(
|
||||
() => ({
|
||||
queueSongIds: playback.queue,
|
||||
queueHistorySongIds: playback.history,
|
||||
currentSong,
|
||||
currentFormat,
|
||||
shuffleEnabled: playback.shuffleEnabled,
|
||||
repeatEnabled: playback.repeatEnabled,
|
||||
queueOpen,
|
||||
isPlaying: isPlaybackActive,
|
||||
volume,
|
||||
setQueueOpen,
|
||||
toggleQueueOpen,
|
||||
setIsPlaying,
|
||||
@@ -1423,8 +1395,15 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
skipToQueueIndex,
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
dolbyAtmosSupported,
|
||||
}),
|
||||
[
|
||||
playback,
|
||||
currentSong,
|
||||
currentFormat,
|
||||
queueOpen,
|
||||
isPlaybackActive,
|
||||
volume,
|
||||
toggleQueueOpen,
|
||||
setVolume,
|
||||
playInOrder,
|
||||
@@ -1446,31 +1425,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
skipToQueueIndex,
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
]
|
||||
)
|
||||
|
||||
const value = useMemo<PlaybackContextValue>(
|
||||
() => ({
|
||||
...actions,
|
||||
queueSongIds: playback.queue,
|
||||
queueHistorySongIds: playback.history,
|
||||
currentSong,
|
||||
currentFormat,
|
||||
shuffleEnabled: playback.shuffleEnabled,
|
||||
repeatEnabled: playback.repeatEnabled,
|
||||
queueOpen,
|
||||
isPlaying: isPlaybackActive,
|
||||
volume,
|
||||
dolbyAtmosSupported,
|
||||
}),
|
||||
[
|
||||
actions,
|
||||
playback,
|
||||
currentSong,
|
||||
currentFormat,
|
||||
queueOpen,
|
||||
isPlaybackActive,
|
||||
volume,
|
||||
dolbyAtmosSupported,
|
||||
]
|
||||
)
|
||||
@@ -1481,16 +1435,10 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
|
||||
return (
|
||||
<PlaybackActionsContext.Provider value={actions}>
|
||||
<CurrentSongIdContext.Provider value={currentSongId}>
|
||||
<IsPlayingContext.Provider value={isPlaybackActive}>
|
||||
<PlaybackContext.Provider value={value}>
|
||||
<PlaybackProgressContext.Provider value={progressValue}>
|
||||
{children}
|
||||
</PlaybackProgressContext.Provider>
|
||||
</PlaybackContext.Provider>
|
||||
</IsPlayingContext.Provider>
|
||||
</CurrentSongIdContext.Provider>
|
||||
</PlaybackActionsContext.Provider>
|
||||
<PlaybackContext.Provider value={value}>
|
||||
<PlaybackProgressContext.Provider value={progressValue}>
|
||||
{children}
|
||||
</PlaybackProgressContext.Provider>
|
||||
</PlaybackContext.Provider>
|
||||
)
|
||||
}
|
||||
@@ -33,39 +33,6 @@ import { albumCoverUrl } from "@/lib/cover-urls"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { formatDuration } from "@/lib/format-duration"
|
||||
|
||||
function PlayerSeekBar({ hasActiveSong }: { hasActiveSong: boolean }) {
|
||||
const { currentTime, duration, seekTo } = usePlaybackProgress()
|
||||
const [isSeeking, setIsSeeking] = React.useState(false)
|
||||
const [seekValue, setSeekValue] = React.useState(0)
|
||||
|
||||
const displayTime = hasActiveSong ? (isSeeking ? seekValue : currentTime) : 0
|
||||
const maxDuration = Math.max(duration, 1)
|
||||
|
||||
return (
|
||||
<Slider
|
||||
className={cn(
|
||||
"h-3 flex-1 [&_[data-slot=slider-range]]:bg-current/80 [&_[data-slot=slider-thumb]]:size-2 [&_[data-slot=slider-thumb]]:border-current [&_[data-slot=slider-thumb]]:bg-current [&_[data-slot=slider-thumb]]:opacity-0 focus-within:[&_[data-slot=slider-thumb]]:opacity-100 hover:[&_[data-slot=slider-thumb]]:opacity-100 [&_[data-slot=slider-track]]:h-[3px] [&_[data-slot=slider-track]]:bg-current/30 md:[&_[data-slot=slider-track]]:h-0.5",
|
||||
!hasActiveSong && "[&_[data-slot=slider-thumb]]:hidden"
|
||||
)}
|
||||
min={0}
|
||||
max={maxDuration}
|
||||
step={0.1}
|
||||
value={[displayTime]}
|
||||
disabled={!hasActiveSong}
|
||||
onValueChange={([value]) => {
|
||||
setIsSeeking(true)
|
||||
setSeekValue(value)
|
||||
}}
|
||||
onValueCommit={([value]) => {
|
||||
seekTo(value)
|
||||
setIsSeeking(false)
|
||||
}}
|
||||
aria-label="Seek"
|
||||
aria-valuetext={`${formatDuration(displayTime)} of ${formatDuration(duration)}`}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export function PlayerBar() {
|
||||
const {
|
||||
currentSong,
|
||||
@@ -84,10 +51,16 @@ export function PlayerBar() {
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
} = usePlayback()
|
||||
const { currentTime, duration, seekTo } = usePlaybackProgress()
|
||||
const { state, isMobile } = useSidebar()
|
||||
const [isSeeking, setIsSeeking] = React.useState(false)
|
||||
const [seekValue, setSeekValue] = React.useState(0)
|
||||
|
||||
const hasQueue = queueSongIds.length > 0
|
||||
const hasActiveSong = Boolean(currentSong)
|
||||
const sidebarExpanded = !isMobile && state === "expanded"
|
||||
const displayTime = hasActiveSong ? (isSeeking ? seekValue : currentTime) : 0
|
||||
const maxDuration = Math.max(duration, 1)
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -219,7 +192,27 @@ export function PlayerBar() {
|
||||
/>
|
||||
)}
|
||||
<div className="absolute inset-x-0 -bottom-1">
|
||||
<PlayerSeekBar hasActiveSong={Boolean(currentSong)} />
|
||||
<Slider
|
||||
className={cn(
|
||||
"h-3 flex-1 [&_[data-slot=slider-range]]:bg-current/80 [&_[data-slot=slider-thumb]]:size-2 [&_[data-slot=slider-thumb]]:border-current [&_[data-slot=slider-thumb]]:bg-current [&_[data-slot=slider-thumb]]:opacity-0 focus-within:[&_[data-slot=slider-thumb]]:opacity-100 hover:[&_[data-slot=slider-thumb]]:opacity-100 [&_[data-slot=slider-track]]:h-[3px] [&_[data-slot=slider-track]]:bg-current/30 md:[&_[data-slot=slider-track]]:h-0.5",
|
||||
!hasActiveSong && "[&_[data-slot=slider-thumb]]:hidden"
|
||||
)}
|
||||
min={0}
|
||||
max={maxDuration}
|
||||
step={0.1}
|
||||
value={[displayTime]}
|
||||
disabled={!hasActiveSong}
|
||||
onValueChange={([value]) => {
|
||||
setIsSeeking(true)
|
||||
setSeekValue(value)
|
||||
}}
|
||||
onValueCommit={([value]) => {
|
||||
seekTo(value)
|
||||
setIsSeeking(false)
|
||||
}}
|
||||
aria-label="Seek"
|
||||
aria-valuetext={`${formatDuration(displayTime)} of ${formatDuration(duration)}`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
MediaContextMenuItems,
|
||||
type MediaContextAction,
|
||||
} from "@/components/media-context-menu"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -30,7 +30,7 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
|
||||
const convex = useConvex()
|
||||
const cacheScope = useCacheScope()
|
||||
const { openAddPlaylistToPlaylist } = useAddToPlaylist()
|
||||
const { playPlaylist } = usePlaybackActions()
|
||||
const { playPlaylist } = usePlayback()
|
||||
const { runQueueAction } = useQueueMediaActions()
|
||||
|
||||
async function handleCardAction(action: MediaContextAction) {
|
||||
|
||||
@@ -10,17 +10,13 @@ import { Play, SearchIcon, Share2, Shuffle, Star, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import {
|
||||
useCurrentSongId,
|
||||
usePlaybackActions,
|
||||
} from "@/components/playback-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { MediaCollectionFooter } from "@/components/media-collection-footer"
|
||||
import {
|
||||
MediaContextMenu,
|
||||
type MediaContextAction,
|
||||
} from "@/components/media-context-menu"
|
||||
import { TrackRow } from "@/components/track-row"
|
||||
import { VirtualList } from "@/components/virtual-list"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenuItem,
|
||||
@@ -43,7 +39,6 @@ import { rememberSongs } from "@/lib/song-cache"
|
||||
import { getSelectionRangePositions } from "@/lib/selection-range-styles"
|
||||
|
||||
const ADD_TO_ANOTHER_PLAYLIST = "Add to Another Playlist"
|
||||
const estimatePlaylistRowSize = () => 60
|
||||
|
||||
export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
const router = useRouter()
|
||||
@@ -55,14 +50,14 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
: currentUser?._id === playlist.owner.id
|
||||
const { isSongFavorite, toggleSongFavorite, toggleSongsFavorite } =
|
||||
useFavorites()
|
||||
const currentSongId = useCurrentSongId()
|
||||
const {
|
||||
currentSong,
|
||||
playInOrder,
|
||||
playShuffled,
|
||||
playPlaylist,
|
||||
playPlaylistShuffled,
|
||||
playFromSong,
|
||||
} = usePlaybackActions()
|
||||
} = usePlayback()
|
||||
const { runSongsAction } = useMediaActions()
|
||||
const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist)
|
||||
const reorderSongs = useMutation(api.playlists.reorderPlaylistSongs)
|
||||
@@ -191,7 +186,10 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
: [songId]
|
||||
|
||||
if (isFavorites) {
|
||||
const succeeded = await toggleSongsFavorite(ids as Id<"songs">[], true)
|
||||
const succeeded = await toggleSongsFavorite(
|
||||
ids as Id<"songs">[],
|
||||
true
|
||||
)
|
||||
if (!succeeded) return
|
||||
return
|
||||
}
|
||||
@@ -204,9 +202,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
setPlaylistSongs((current) =>
|
||||
current.filter((song) => !ids.includes(song.id))
|
||||
)
|
||||
toast.success(
|
||||
ids.length > 1 ? `Removed ${ids.length} songs` : "Removed song"
|
||||
)
|
||||
toast.success(ids.length > 1 ? `Removed ${ids.length} songs` : "Removed song")
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to remove song"
|
||||
@@ -295,7 +291,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
<PageHeader openApp />
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<div className="pb-28">
|
||||
<div className="mx-auto w-full max-w-9/10 min-w-0">
|
||||
<div className="mx-auto w-full min-w-0 max-w-9/10">
|
||||
<div className="flex flex-col gap-8 px-6 pt-6 pb-8 sm:flex-row sm:items-end">
|
||||
<div className="relative mx-auto aspect-square w-full max-w-60 shrink-0 overflow-hidden rounded-lg ring-1 ring-foreground/10 sm:mx-0">
|
||||
{isFavorites ? (
|
||||
@@ -425,49 +421,40 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
</div>
|
||||
</div>
|
||||
{filteredSongs.length > 0 ? (
|
||||
<VirtualList
|
||||
count={filteredSongs.length}
|
||||
estimateSize={estimatePlaylistRowSize}
|
||||
getItemKey={(index) => filteredSongs[index].id}
|
||||
// Keep the drag source mounted so its drop still lands.
|
||||
keepMounted={dragIndex}
|
||||
renderItem={(index) => {
|
||||
const song = filteredSongs[index]
|
||||
return (
|
||||
<TrackRow
|
||||
variant="playlist"
|
||||
song={song}
|
||||
index={index}
|
||||
trackNumber={playlistPositionById.get(song.id)}
|
||||
isActive={song.id === activeTrackId}
|
||||
isNowPlaying={currentSongId === song.id}
|
||||
isFavorite={isSongFavorite(song.id)}
|
||||
isDragging={dragIndex === index}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
selectedCount={selectedCount}
|
||||
selectionStationArtistId={selectedStationArtistId}
|
||||
playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
|
||||
showFavoriteInMenu={!isFavorites}
|
||||
removeLabel={
|
||||
isFavorites
|
||||
? "Unfavorite"
|
||||
: isOwner
|
||||
? "Remove from Playlist"
|
||||
: undefined
|
||||
}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={handleRowSelect}
|
||||
onPlay={handleRowPlay}
|
||||
onToggleFavorite={handleToggleFavorite}
|
||||
onPrepareContextMenu={prepareContextMenu}
|
||||
onMediaAction={handleMediaAction}
|
||||
onRemove={handleRemoveSong}
|
||||
onDragStart={canReorder ? setDragIndex : undefined}
|
||||
onDrop={canReorder ? handleDrop : undefined}
|
||||
/>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
filteredSongs.map((song, index) => (
|
||||
<TrackRow
|
||||
key={song.id}
|
||||
variant="playlist"
|
||||
song={song}
|
||||
index={index}
|
||||
trackNumber={playlistPositionById.get(song.id)}
|
||||
isActive={song.id === activeTrackId}
|
||||
isNowPlaying={currentSong?.id === song.id}
|
||||
isFavorite={isSongFavorite(song.id)}
|
||||
isDragging={dragIndex === index}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
selectedCount={selectedCount}
|
||||
selectionStationArtistId={selectedStationArtistId}
|
||||
playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
|
||||
showFavoriteInMenu={!isFavorites}
|
||||
removeLabel={
|
||||
isFavorites
|
||||
? "Unfavorite"
|
||||
: isOwner
|
||||
? "Remove from Playlist"
|
||||
: undefined
|
||||
}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={handleRowSelect}
|
||||
onPlay={handleRowPlay}
|
||||
onToggleFavorite={handleToggleFavorite}
|
||||
onPrepareContextMenu={prepareContextMenu}
|
||||
onMediaAction={handleMediaAction}
|
||||
onRemove={handleRemoveSong}
|
||||
onDragStart={canReorder ? setDragIndex : undefined}
|
||||
onDrop={canReorder ? handleDrop : undefined}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<p className="px-6 py-8 text-sm text-muted-foreground">
|
||||
{normalizedQuery
|
||||
|
||||
@@ -8,8 +8,6 @@ import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||
import {
|
||||
MediaContextMenu,
|
||||
type MediaContextAction,
|
||||
MediaContextMenuArea,
|
||||
type MediaContextMenuProps,
|
||||
} from "@/components/media-context-menu"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
@@ -40,57 +38,52 @@ export function SearchSongItem({ song }: { song: BrowseSong }) {
|
||||
}
|
||||
}
|
||||
|
||||
const menu: MediaContextMenuProps = {
|
||||
label: `More options for ${song.title}`,
|
||||
stationArtistId: song.artist.id,
|
||||
selectedCount: 1,
|
||||
onOpenMenu: () => {},
|
||||
onAction: handleAction,
|
||||
favorited: isSongFavorite(song.id),
|
||||
navigation: {
|
||||
artist: { id: song.artist.id },
|
||||
album: { id: song.album.id },
|
||||
},
|
||||
share: {
|
||||
type: "song",
|
||||
albumId: song.album.id,
|
||||
songId: song.id,
|
||||
},
|
||||
triggerClassName:
|
||||
"size-8 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100",
|
||||
triggerVariant: "ghost",
|
||||
}
|
||||
|
||||
return (
|
||||
<MediaContextMenuArea menu={menu}>
|
||||
<div className="group flex items-center gap-3 rounded-lg px-1 py-1.5 transition-colors hover:bg-muted/50">
|
||||
<div className="group flex items-center gap-3 rounded-lg px-1 py-1.5 transition-colors hover:bg-muted/50">
|
||||
<Link
|
||||
href={`/album/${song.album.id}`}
|
||||
className="relative size-11 shrink-0 overflow-hidden rounded ring-1 ring-foreground/10"
|
||||
>
|
||||
<Image
|
||||
src={albumCoverUrl(song.album.id)}
|
||||
alt={song.album.title}
|
||||
fill
|
||||
sizes="44px"
|
||||
className="object-cover"
|
||||
/>
|
||||
</Link>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<Link href={`/album/${song.album.id}`} className="hover:underline">
|
||||
<p className="truncate text-sm font-medium">{song.title}</p>
|
||||
</Link>
|
||||
<Link
|
||||
href={`/album/${song.album.id}`}
|
||||
className="relative size-11 shrink-0 overflow-hidden rounded ring-1 ring-foreground/10"
|
||||
href={`/artist/${song.artist.id}`}
|
||||
className="text-muted-foreground hover:text-foreground hover:underline"
|
||||
>
|
||||
<Image
|
||||
src={albumCoverUrl(song.album.id)}
|
||||
alt={song.album.title}
|
||||
fill
|
||||
sizes="44px"
|
||||
className="object-cover"
|
||||
/>
|
||||
<p className="truncate text-sm">{song.artist.name}</p>
|
||||
</Link>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<Link href={`/album/${song.album.id}`} className="hover:underline">
|
||||
<p className="truncate text-sm font-medium">{song.title}</p>
|
||||
</Link>
|
||||
<Link
|
||||
href={`/artist/${song.artist.id}`}
|
||||
className="text-muted-foreground hover:text-foreground hover:underline"
|
||||
>
|
||||
<p className="truncate text-sm">{song.artist.name}</p>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<MediaContextMenu {...menu} />
|
||||
</div>
|
||||
</MediaContextMenuArea>
|
||||
|
||||
<MediaContextMenu
|
||||
label={`More options for ${song.title}`}
|
||||
stationArtistId={song.artist.id}
|
||||
selectedCount={1}
|
||||
onOpenMenu={() => {}}
|
||||
onAction={handleAction}
|
||||
favorited={isSongFavorite(song.id)}
|
||||
navigation={{
|
||||
artist: { id: song.artist.id },
|
||||
album: { id: song.album.id },
|
||||
}}
|
||||
share={{
|
||||
type: "song",
|
||||
albumId: song.album.id,
|
||||
songId: song.id,
|
||||
}}
|
||||
triggerClassName="size-8 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100"
|
||||
triggerVariant="ghost"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -13,9 +13,8 @@ import {
|
||||
import { ArrowUpDown } from "lucide-react"
|
||||
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { LibraryTrackListHeader, TrackRow } from "@/components/track-row"
|
||||
import { VirtualList } from "@/components/virtual-list"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -44,11 +43,10 @@ type SortKey = "title" | "artist" | "album"
|
||||
type SortDirection = "asc" | "desc"
|
||||
|
||||
const SONGS_PAGE_SIZE = 50
|
||||
const estimateSongRowSize = () => 56
|
||||
|
||||
export function SongsView() {
|
||||
const { isSongFavorite, toggleSongFavorite } = useFavorites()
|
||||
const { playFromLibrarySong } = usePlaybackActions()
|
||||
const { playFromLibrarySong } = usePlayback()
|
||||
const [sortKey, setSortKey] = useState<SortKey>("title")
|
||||
const [sortDirection, setSortDirection] =
|
||||
useState<SortDirection>("asc")
|
||||
@@ -129,7 +127,6 @@ export function SongsView() {
|
||||
(songId: string) => void toggleSongFavorite(songId as Id<"songs">),
|
||||
[toggleSongFavorite]
|
||||
)
|
||||
const getSongKey = useCallback((index: number) => songs[index].id, [songs])
|
||||
|
||||
if (status === "LoadingFirstPage" && !isCached) {
|
||||
return (
|
||||
@@ -200,7 +197,7 @@ export function SongsView() {
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<ScrollArea className="min-h-0 flex-1 [&_[data-slot=scroll-area-viewport]>div]:block!">
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<div
|
||||
className="w-full pb-28"
|
||||
onClick={(event) => {
|
||||
@@ -210,28 +207,24 @@ export function SongsView() {
|
||||
}}
|
||||
>
|
||||
<LibraryTrackListHeader />
|
||||
<VirtualList
|
||||
count={songs.length}
|
||||
estimateSize={estimateSongRowSize}
|
||||
getItemKey={getSongKey}
|
||||
renderItem={(index) => (
|
||||
<TrackRow
|
||||
variant="library"
|
||||
song={songs[index]}
|
||||
index={index}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
isFavorite={isSongFavorite(songs[index].id)}
|
||||
selectedCount={selectedCount}
|
||||
selectionStationArtistId={selectedStationArtistId}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={handleRowSelect}
|
||||
onPlay={handleRowPlay}
|
||||
onToggleFavorite={handleToggleFavorite}
|
||||
onPrepareContextMenu={prepareContextMenu}
|
||||
onMediaAction={handleMediaAction}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{songs.map((song, index) => (
|
||||
<TrackRow
|
||||
key={song.id}
|
||||
variant="library"
|
||||
song={song}
|
||||
index={index}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
isFavorite={isSongFavorite(song.id)}
|
||||
selectedCount={selectedCount}
|
||||
selectionStationArtistId={selectedStationArtistId}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={handleRowSelect}
|
||||
onPlay={handleRowPlay}
|
||||
onToggleFavorite={handleToggleFavorite}
|
||||
onPrepareContextMenu={prepareContextMenu}
|
||||
onMediaAction={handleMediaAction}
|
||||
/>
|
||||
))}
|
||||
<div
|
||||
ref={loadMoreRef}
|
||||
className="flex items-center justify-center py-4"
|
||||
|
||||
@@ -3,62 +3,10 @@
|
||||
import type { MouseEvent } from "react"
|
||||
import { AudioLines, Pause, Play } from "lucide-react"
|
||||
|
||||
import {
|
||||
useIsPlaying,
|
||||
usePlaybackActions,
|
||||
} from "@/components/playback-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function trackButtonClassName(showPlay: boolean, inRange: boolean) {
|
||||
return cn(
|
||||
"absolute size-8 opacity-0 transition-opacity group-hover:opacity-100",
|
||||
showPlay && "opacity-100",
|
||||
inRange
|
||||
? "text-primary-foreground hover:bg-white/15 hover:text-primary-foreground"
|
||||
: "text-primary hover:text-primary"
|
||||
)
|
||||
}
|
||||
|
||||
function NowPlayingButton({
|
||||
title,
|
||||
inRange,
|
||||
}: {
|
||||
title: string
|
||||
inRange: boolean
|
||||
}) {
|
||||
const isPlaying = useIsPlaying()
|
||||
const { setIsPlaying } = usePlaybackActions()
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className={trackButtonClassName(true, inRange)}
|
||||
aria-label={isPlaying ? `Pause ${title}` : `Play ${title}`}
|
||||
onClick={(event: MouseEvent) => {
|
||||
event.stopPropagation()
|
||||
setIsPlaying(!isPlaying)
|
||||
}}
|
||||
>
|
||||
<span className="absolute inset-0 flex items-center justify-center transition-opacity group-hover:opacity-0">
|
||||
{isPlaying ? (
|
||||
<AudioLines className="size-4" />
|
||||
) : (
|
||||
<Play className="size-4 fill-current" />
|
||||
)}
|
||||
</span>
|
||||
<span className="absolute inset-0 flex items-center justify-center opacity-0 transition-opacity group-hover:opacity-100">
|
||||
{isPlaying ? (
|
||||
<Pause className="size-4" />
|
||||
) : (
|
||||
<Play className="size-4 fill-current" />
|
||||
)}
|
||||
</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export function TrackNumberPlayButton({
|
||||
displayTrack,
|
||||
title,
|
||||
@@ -74,7 +22,26 @@ export function TrackNumberPlayButton({
|
||||
inRange: boolean
|
||||
onPlay: () => void
|
||||
}) {
|
||||
const { isPlaying, setIsPlaying } = usePlayback()
|
||||
const showPlay = isActive || isNowPlaying
|
||||
const isCurrentlyPlaying = isNowPlaying && isPlaying
|
||||
|
||||
const buttonClassName = cn(
|
||||
"absolute size-8 opacity-0 transition-opacity group-hover:opacity-100",
|
||||
showPlay && "opacity-100",
|
||||
inRange
|
||||
? "text-primary-foreground hover:bg-white/15 hover:text-primary-foreground"
|
||||
: "text-primary hover:text-primary"
|
||||
)
|
||||
|
||||
const handleClick = (event: MouseEvent) => {
|
||||
event.stopPropagation()
|
||||
if (isNowPlaying) {
|
||||
setIsPlaying(!isPlaying)
|
||||
return
|
||||
}
|
||||
onPlay()
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -92,17 +59,35 @@ export function TrackNumberPlayButton({
|
||||
{displayTrack}
|
||||
</span>
|
||||
{isNowPlaying ? (
|
||||
<NowPlayingButton title={title} inRange={inRange} />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className={buttonClassName}
|
||||
aria-label={isCurrentlyPlaying ? `Pause ${title}` : `Play ${title}`}
|
||||
onClick={handleClick}
|
||||
>
|
||||
<span className="absolute inset-0 flex items-center justify-center transition-opacity group-hover:opacity-0">
|
||||
{isCurrentlyPlaying ? (
|
||||
<AudioLines className="size-4" />
|
||||
) : (
|
||||
<Play className="size-4 fill-current" />
|
||||
)}
|
||||
</span>
|
||||
<span className="absolute inset-0 flex items-center justify-center opacity-0 transition-opacity group-hover:opacity-100">
|
||||
{isCurrentlyPlaying ? (
|
||||
<Pause className="size-4" />
|
||||
) : (
|
||||
<Play className="size-4 fill-current" />
|
||||
)}
|
||||
</span>
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className={trackButtonClassName(showPlay, inRange)}
|
||||
className={buttonClassName}
|
||||
aria-label={`Play ${title}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onPlay()
|
||||
}}
|
||||
onClick={handleClick}
|
||||
>
|
||||
<Play className="size-4 fill-current" />
|
||||
</Button>
|
||||
|
||||
@@ -7,15 +7,15 @@ import { Music2, Play, Star, Trash2 } from "lucide-react"
|
||||
|
||||
import {
|
||||
MediaContextMenu,
|
||||
MediaContextMenuArea,
|
||||
MediaMenuItem,
|
||||
MediaMenuSeparator,
|
||||
type MediaContextAction,
|
||||
type MediaContextMenuProps,
|
||||
} from "@/components/media-context-menu"
|
||||
import { PlaybackSongMeta } from "@/components/playback-song-meta"
|
||||
import { TrackNumberPlayButton } from "@/components/track-number-play-button"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { albumCoverUrl } from "@/lib/cover-urls"
|
||||
import {
|
||||
ALBUM_TRACK_ROW,
|
||||
@@ -68,7 +68,7 @@ export type TrackRowProps = {
|
||||
onPlay: (index: number) => void
|
||||
onToggleFavorite?: (songId: string) => void
|
||||
onPrepareContextMenu?: (songId: string) => void
|
||||
/** Renders the "more options" and right-click menus when provided. */
|
||||
/** Renders the "more options" menu when provided. */
|
||||
onMediaAction?: (action: MediaContextAction, songId: string) => void
|
||||
onRemove?: (songId: string) => void
|
||||
/** Makes the row draggable when provided. */
|
||||
@@ -304,40 +304,38 @@ function TrackRowComponent({
|
||||
</span>
|
||||
)
|
||||
|
||||
// Shared by the "more options" button and the right-click menu.
|
||||
const menuProps: MediaContextMenuProps | null = onMediaAction
|
||||
? {
|
||||
label: `More options for ${song.title}`,
|
||||
stationArtistId: inRange ? selectionStationArtistId : song.artist.id,
|
||||
selectedCount: inRange && selectedCount > 0 ? selectedCount : 1,
|
||||
inSelectionRange: inRange,
|
||||
onOpenMenu: () => onPrepareContextMenu?.(song.id),
|
||||
onAction: (action) => onMediaAction(action, song.id),
|
||||
playlistLabel,
|
||||
showFavorite: showFavoriteInMenu,
|
||||
favorited: isFavorite,
|
||||
navigation: {
|
||||
artist: { id: song.artist.id },
|
||||
album: { id: song.album.id },
|
||||
},
|
||||
share: { type: "song", albumId: song.album.id, songId: song.id },
|
||||
children:
|
||||
removeLabel && onRemove ? (
|
||||
<>
|
||||
<MediaMenuSeparator />
|
||||
<MediaMenuItem
|
||||
variant="destructive"
|
||||
className="justify-between"
|
||||
onClick={() => onRemove(song.id)}
|
||||
>
|
||||
{removeLabel}
|
||||
<Trash2 />
|
||||
</MediaMenuItem>
|
||||
</>
|
||||
) : null,
|
||||
}
|
||||
: null
|
||||
const menu = menuProps ? <MediaContextMenu {...menuProps} /> : null
|
||||
const menu = onMediaAction ? (
|
||||
<MediaContextMenu
|
||||
label={`More options for ${song.title}`}
|
||||
stationArtistId={inRange ? selectionStationArtistId : song.artist.id}
|
||||
selectedCount={inRange && selectedCount > 0 ? selectedCount : 1}
|
||||
inSelectionRange={inRange}
|
||||
onOpenMenu={() => onPrepareContextMenu?.(song.id)}
|
||||
onAction={(action) => onMediaAction(action, song.id)}
|
||||
playlistLabel={playlistLabel}
|
||||
showFavorite={showFavoriteInMenu}
|
||||
favorited={isFavorite}
|
||||
navigation={{
|
||||
artist: { id: song.artist.id },
|
||||
album: { id: song.album.id },
|
||||
}}
|
||||
share={{ type: "song", albumId: song.album.id, songId: song.id }}
|
||||
>
|
||||
{removeLabel && onRemove ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
className="justify-between"
|
||||
onClick={() => onRemove(song.id)}
|
||||
>
|
||||
{removeLabel}
|
||||
<Trash2 />
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
) : null}
|
||||
</MediaContextMenu>
|
||||
) : null
|
||||
|
||||
let content: React.ReactNode
|
||||
switch (variant) {
|
||||
@@ -493,21 +491,14 @@ function TrackRowComponent({
|
||||
</>
|
||||
)
|
||||
|
||||
const shell =
|
||||
variant === "queue" ? (
|
||||
<li ref={ref as React.Ref<HTMLLIElement>} {...shellProps}>
|
||||
{children}
|
||||
</li>
|
||||
) : (
|
||||
<div ref={ref as React.Ref<HTMLDivElement>} {...shellProps}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
|
||||
return menuProps ? (
|
||||
<MediaContextMenuArea menu={menuProps}>{shell}</MediaContextMenuArea>
|
||||
return variant === "queue" ? (
|
||||
<li ref={ref as React.Ref<HTMLLIElement>} {...shellProps}>
|
||||
{children}
|
||||
</li>
|
||||
) : (
|
||||
shell
|
||||
<div ref={ref as React.Ref<HTMLDivElement>} {...shellProps}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
defaultRangeExtractor,
|
||||
useVirtualizer,
|
||||
type Range,
|
||||
} from "@tanstack/react-virtual"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const scrollViewportSelector = '[data-slot="scroll-area-viewport"]'
|
||||
|
||||
/**
|
||||
* Renders only the visible items of a list placed inside a `ScrollArea`.
|
||||
* The list may sit below other content in the same viewport.
|
||||
*/
|
||||
export function VirtualList({
|
||||
count,
|
||||
estimateSize,
|
||||
getItemKey,
|
||||
renderItem,
|
||||
overscan = 10,
|
||||
keepMounted = null,
|
||||
className,
|
||||
}: {
|
||||
count: number
|
||||
estimateSize: (index: number) => number
|
||||
getItemKey: (index: number) => string
|
||||
renderItem: (index: number) => React.ReactNode
|
||||
overscan?: number
|
||||
/** Index rendered even when off screen, e.g. the source of a drag. */
|
||||
keepMounted?: number | null
|
||||
className?: string
|
||||
}) {
|
||||
const listRef = React.useRef<HTMLDivElement>(null)
|
||||
const [scrollMargin, setScrollMargin] = React.useState(0)
|
||||
|
||||
React.useLayoutEffect(() => {
|
||||
const list = listRef.current
|
||||
const viewport = list?.closest<HTMLElement>(scrollViewportSelector)
|
||||
if (!list || !viewport) return
|
||||
|
||||
const measure = () => {
|
||||
setScrollMargin(
|
||||
Math.round(
|
||||
list.getBoundingClientRect().top -
|
||||
viewport.getBoundingClientRect().top +
|
||||
viewport.scrollTop
|
||||
)
|
||||
)
|
||||
}
|
||||
const observer = new ResizeObserver(measure)
|
||||
observer.observe(viewport)
|
||||
if (viewport.firstElementChild) {
|
||||
observer.observe(viewport.firstElementChild)
|
||||
}
|
||||
return () => observer.disconnect()
|
||||
}, [])
|
||||
|
||||
const getScrollElement = () =>
|
||||
listRef.current?.closest<HTMLElement>(scrollViewportSelector) ?? null
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
count,
|
||||
getScrollElement,
|
||||
// The virtualizer scrolls to this offset on attach. Keep the viewport's
|
||||
// current position so `ScrollRestoration` is not reset to the top.
|
||||
initialOffset: () => getScrollElement()?.scrollTop ?? 0,
|
||||
estimateSize,
|
||||
getItemKey,
|
||||
overscan,
|
||||
scrollMargin,
|
||||
rangeExtractor: React.useCallback(
|
||||
(range: Range) => {
|
||||
const indexes = defaultRangeExtractor(range)
|
||||
if (
|
||||
keepMounted !== null &&
|
||||
keepMounted < range.count &&
|
||||
!indexes.includes(keepMounted)
|
||||
) {
|
||||
indexes.push(keepMounted)
|
||||
indexes.sort((a, b) => a - b)
|
||||
}
|
||||
return indexes
|
||||
},
|
||||
[keepMounted]
|
||||
),
|
||||
})
|
||||
|
||||
// The virtualizer caches its offset across a detach. Clear it so a
|
||||
// re-attach (e.g. StrictMode's effect replay) re-reads `initialOffset`
|
||||
// instead of scrolling back to a stale position.
|
||||
React.useLayoutEffect(
|
||||
() => () => {
|
||||
virtualizer.scrollOffset = null
|
||||
},
|
||||
[virtualizer]
|
||||
)
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={listRef}
|
||||
className={cn("relative w-full", className)}
|
||||
style={{ height: virtualizer.getTotalSize() }}
|
||||
>
|
||||
{virtualizer.getVirtualItems().map((item) => (
|
||||
<div
|
||||
key={item.key}
|
||||
data-index={item.index}
|
||||
ref={virtualizer.measureElement}
|
||||
className="absolute top-0 left-0 w-full"
|
||||
style={{ transform: `translateY(${item.start - scrollMargin}px)` }}
|
||||
>
|
||||
{renderItem(item.index)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -9,18 +9,13 @@ import {
|
||||
type PaginatedQueryReference,
|
||||
} from "convex/react"
|
||||
import type { FunctionReference } from "convex/server"
|
||||
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react"
|
||||
import { useCallback, useEffect, useSyncExternalStore } from "react"
|
||||
|
||||
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||
import { queryCacheKey } from "@otunes/convex/client/cached-query"
|
||||
import { readCache, subscribeCache, writeCache } from "@/lib/persistent-cache"
|
||||
|
||||
const MAX_CACHED_PAGINATED_ITEMS = 200
|
||||
const MAX_RESTORED_PAGINATED_ITEMS = 1000
|
||||
|
||||
// Items loaded per paginated query this session, so a remount (e.g. back
|
||||
// navigation) loads as much as before and scroll restoration can reach it.
|
||||
const loadedItemCounts = new Map<string, number>()
|
||||
|
||||
const noopUnsubscribe = () => {}
|
||||
|
||||
@@ -70,7 +65,6 @@ export function useCachedQuery<Query extends FunctionReference<"query">>(
|
||||
/**
|
||||
* `usePaginatedQuery` that shows the first persisted pages while the first live
|
||||
* page loads. `isCached` is true while those persisted results are shown.
|
||||
* Remounts start with as many items as were last loaded this session.
|
||||
*/
|
||||
export function useCachedPaginatedQuery<Query extends PaginatedQueryReference>(
|
||||
query: Query,
|
||||
@@ -78,28 +72,15 @@ export function useCachedPaginatedQuery<Query extends PaginatedQueryReference>(
|
||||
options: { initialNumItems: number }
|
||||
) {
|
||||
const scope = useCacheScope()
|
||||
const result = usePaginatedQuery(query, args, options)
|
||||
const key =
|
||||
args === "skip"
|
||||
? null
|
||||
: `${queryCacheKey(scope, query, args as Record<string, unknown>)}:pages`
|
||||
// Fixed per key: `usePaginatedQuery` restarts when this changes.
|
||||
const initialNumItems = useMemo(
|
||||
() =>
|
||||
Math.max(
|
||||
options.initialNumItems,
|
||||
Math.min(
|
||||
(key && loadedItemCounts.get(key)) || 0,
|
||||
MAX_RESTORED_PAGINATED_ITEMS
|
||||
)
|
||||
),
|
||||
[key, options.initialNumItems]
|
||||
)
|
||||
const result = usePaginatedQuery(query, args, { initialNumItems })
|
||||
const cached = useCachedValue<PaginatedQueryItem<Query>[]>(key)
|
||||
|
||||
useEffect(() => {
|
||||
if (key && result.status !== "LoadingFirstPage") {
|
||||
loadedItemCounts.set(key, result.results.length)
|
||||
writeCache(key, result.results.slice(0, MAX_CACHED_PAGINATED_ITEMS))
|
||||
}
|
||||
}, [key, result.status, result.results])
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import * as React from "react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import type { MediaContextAction } from "@/components/media-context-menu"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
|
||||
@@ -29,7 +29,7 @@ function queueActionMessage(action: QueueMediaAction, count: number) {
|
||||
|
||||
export function useQueueMediaActions() {
|
||||
const { addToQueueNext, addToQueueLast, playShuffled, playArtistShuffled } =
|
||||
usePlaybackActions()
|
||||
usePlayback()
|
||||
|
||||
const runQueueAction = React.useCallback(
|
||||
async (action: QueueMediaAction, songIds: Id<"songs">[]) => {
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
|
||||
/**
|
||||
* Returns a function with a stable identity that always calls the latest
|
||||
* `callback`. Only call it from event handlers, never during render.
|
||||
*/
|
||||
export function useStableCallback<Args extends unknown[], Result>(
|
||||
callback: (...args: Args) => Result
|
||||
): (...args: Args) => Result {
|
||||
const callbackRef = React.useRef(callback)
|
||||
|
||||
React.useLayoutEffect(() => {
|
||||
callbackRef.current = callback
|
||||
})
|
||||
|
||||
return React.useCallback((...args: Args) => callbackRef.current(...args), [])
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import fs from "node:fs/promises"
|
||||
import * as music from "music-metadata"
|
||||
|
||||
const MAX_ENTRIES = 1000
|
||||
|
||||
export type AudioInfo = {
|
||||
codec: string | undefined
|
||||
duration: number | undefined
|
||||
}
|
||||
|
||||
const cache = new Map<string, Promise<AudioInfo>>()
|
||||
|
||||
/** Codec info for a file, parsed once per file version. */
|
||||
export async function audioInfo(file: string): Promise<AudioInfo> {
|
||||
const stat = await fs.stat(file)
|
||||
const key = `${file}\0${stat.size}\0${stat.mtimeMs}`
|
||||
|
||||
const cached = cache.get(key)
|
||||
if (cached) {
|
||||
cache.delete(key)
|
||||
cache.set(key, cached)
|
||||
return cached
|
||||
}
|
||||
|
||||
const info = music.parseFile(file).then(({ format }) => ({
|
||||
codec: format.codec,
|
||||
duration: format.duration,
|
||||
}))
|
||||
cache.set(key, info)
|
||||
info.catch(() => {
|
||||
if (cache.get(key) === info) {
|
||||
cache.delete(key)
|
||||
}
|
||||
})
|
||||
|
||||
if (cache.size > MAX_ENTRIES) {
|
||||
cache.delete(cache.keys().next().value!)
|
||||
}
|
||||
|
||||
return info
|
||||
}
|
||||
@@ -1,96 +1,96 @@
|
||||
import { createReadStream } from "node:fs"
|
||||
import type { Readable } from "node:stream"
|
||||
import type { FfmpegProcess } from "@/lib/server-ffmpeg"
|
||||
|
||||
const HIGH_WATER_MARK_BYTES = 256 * 1024
|
||||
import { type ChildProcessWithoutNullStreams } from "node:child_process"
|
||||
import { createReadStream, ReadStream } from "node:fs"
|
||||
|
||||
export type ByteRange = {
|
||||
start: number
|
||||
end: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a Node stream, pausing it while the consumer is behind. `cancel` runs
|
||||
* when the consumer goes away (seek, track change, disconnect). `finish` runs
|
||||
* when the source ends and may reject to error the stream.
|
||||
*/
|
||||
function toWebStream(
|
||||
source: Readable,
|
||||
{
|
||||
cancel,
|
||||
finish,
|
||||
}: { cancel: () => void; finish?: () => Promise<void> }
|
||||
): ReadableStream<Uint8Array> {
|
||||
let done = false
|
||||
|
||||
return new ReadableStream<Uint8Array>(
|
||||
{
|
||||
start(controller) {
|
||||
const fail = (error: unknown) => {
|
||||
if (done) {
|
||||
return
|
||||
}
|
||||
done = true
|
||||
controller.error(error)
|
||||
cancel()
|
||||
}
|
||||
|
||||
source.on("data", (chunk: Buffer) => {
|
||||
if (done) {
|
||||
return
|
||||
}
|
||||
controller.enqueue(new Uint8Array(chunk))
|
||||
if ((controller.desiredSize ?? 0) <= 0) {
|
||||
source.pause()
|
||||
}
|
||||
})
|
||||
source.once("error", fail)
|
||||
source.once("end", () => {
|
||||
if (done) {
|
||||
return
|
||||
}
|
||||
void (finish?.() ?? Promise.resolve()).then(() => {
|
||||
if (!done) {
|
||||
done = true
|
||||
controller.close()
|
||||
}
|
||||
}, fail)
|
||||
})
|
||||
},
|
||||
pull() {
|
||||
source.resume()
|
||||
},
|
||||
cancel() {
|
||||
if (done) {
|
||||
return
|
||||
}
|
||||
done = true
|
||||
cancel()
|
||||
},
|
||||
},
|
||||
new ByteLengthQueuingStrategy({ highWaterMark: HIGH_WATER_MARK_BYTES })
|
||||
)
|
||||
async function* nodeStreamToIterator(stream: ReadStream) {
|
||||
for await (const chunk of stream) {
|
||||
yield new Uint8Array(chunk)
|
||||
}
|
||||
}
|
||||
|
||||
export function streamFile(path: string, range?: ByteRange) {
|
||||
const file = createReadStream(path, range)
|
||||
return toWebStream(file, { cancel: () => file.destroy() })
|
||||
}
|
||||
|
||||
/** Streams ffmpeg stdout and kills ffmpeg when the consumer goes away. */
|
||||
export function ffmpegToReadableStream({
|
||||
child,
|
||||
exited,
|
||||
stderrTail,
|
||||
}: FfmpegProcess) {
|
||||
return toWebStream(child.stdout, {
|
||||
cancel: () => child.kill("SIGKILL"),
|
||||
finish: async () => {
|
||||
const code = await exited
|
||||
if (code !== 0) {
|
||||
console.error(`ffmpeg transcode exited with code ${code}`, stderrTail())
|
||||
throw new Error(`ffmpeg exited with code ${code}`)
|
||||
// @ts-expect-error trust me bro
|
||||
function iteratorToStream(iterator) {
|
||||
return new ReadableStream({
|
||||
async pull(controller) {
|
||||
const { value, done } = await iterator.next()
|
||||
if (done) {
|
||||
controller.close()
|
||||
} else {
|
||||
controller.enqueue(value)
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function streamFile(path: string, range?: ByteRange): ReadableStream {
|
||||
const nodeStream = createReadStream(path, range)
|
||||
return iteratorToStream(nodeStreamToIterator(nodeStream))
|
||||
}
|
||||
|
||||
export function ffmpegToReadableStream(
|
||||
ffmpegProcess: ChildProcessWithoutNullStreams
|
||||
) {
|
||||
let closed = false
|
||||
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
const finalize = (err?: Error) => {
|
||||
if (closed) {
|
||||
return
|
||||
}
|
||||
closed = true
|
||||
|
||||
try {
|
||||
if (err) {
|
||||
controller.error(err)
|
||||
} else {
|
||||
controller.close()
|
||||
}
|
||||
} catch {
|
||||
// Consumer may have already closed the stream (e.g. track change).
|
||||
}
|
||||
}
|
||||
|
||||
ffmpegProcess.stdout.on("data", (chunk: Buffer) => {
|
||||
if (closed) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
controller.enqueue(new Uint8Array(chunk))
|
||||
} catch {
|
||||
closed = true
|
||||
ffmpegProcess.kill("SIGKILL")
|
||||
}
|
||||
})
|
||||
|
||||
ffmpegProcess.stderr.on("data", (data) => {
|
||||
console.error(`FFmpeg log: ${data.toString()}`)
|
||||
})
|
||||
|
||||
ffmpegProcess.stdout.on("end", () => finalize())
|
||||
ffmpegProcess.stdout.on("error", (err) => finalize(err))
|
||||
|
||||
ffmpegProcess.on("close", (code) => {
|
||||
if (code !== 0 && !closed) {
|
||||
finalize(new Error(`ffmpeg exited with code ${code}`))
|
||||
} else {
|
||||
finalize()
|
||||
}
|
||||
})
|
||||
|
||||
ffmpegProcess.on("error", (err) => finalize(err))
|
||||
},
|
||||
cancel() {
|
||||
if (closed) {
|
||||
return
|
||||
}
|
||||
closed = true
|
||||
ffmpegProcess.kill("SIGKILL")
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
import fs from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
|
||||
const DEFAULT_MAX_MB = 2048
|
||||
const ORPHAN_MAX_AGE_MS = 60 * 60 * 1000
|
||||
/** Prefix for in-progress entries. Pruning removes old unpinned ones as abandoned. */
|
||||
export const CACHE_ORPHAN_PREFIX = "convert-"
|
||||
|
||||
type CacheState = {
|
||||
pinned: Map<string, number>
|
||||
pruning: Promise<void> | null
|
||||
}
|
||||
|
||||
const globalState = globalThis as typeof globalThis & {
|
||||
__otunesCache?: CacheState
|
||||
}
|
||||
const state = (globalState.__otunesCache ??= {
|
||||
pinned: new Map(),
|
||||
pruning: null,
|
||||
})
|
||||
|
||||
/**
|
||||
* Transcode cache root. Set OTUNES_CACHE_DIR to a persistent volume to keep
|
||||
* transcodes across restarts.
|
||||
*/
|
||||
export function cacheRoot() {
|
||||
return process.env.OTUNES_CACHE_DIR || path.join(os.tmpdir(), "otunes-cache")
|
||||
}
|
||||
|
||||
export function cacheDir(kind: "hls" | "lossless") {
|
||||
return path.join(cacheRoot(), kind)
|
||||
}
|
||||
|
||||
function maxCacheBytes() {
|
||||
const configured = Number(process.env.OTUNES_CACHE_MAX_MB)
|
||||
const mb = Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_MAX_MB
|
||||
return mb * 1024 * 1024
|
||||
}
|
||||
|
||||
/** Pinned entries are never pruned. Pins are reference counted. */
|
||||
export function pinCacheEntry(entry: string) {
|
||||
state.pinned.set(entry, (state.pinned.get(entry) ?? 0) + 1)
|
||||
}
|
||||
|
||||
export function unpinCacheEntry(entry: string) {
|
||||
const count = state.pinned.get(entry) ?? 0
|
||||
if (count <= 1) {
|
||||
state.pinned.delete(entry)
|
||||
} else {
|
||||
state.pinned.set(entry, count - 1)
|
||||
}
|
||||
}
|
||||
|
||||
/** Marks an entry as recently used so pruning removes it last. */
|
||||
export async function touchCacheEntry(entry: string) {
|
||||
const now = new Date()
|
||||
await fs.utimes(entry, now, now)
|
||||
}
|
||||
|
||||
async function entrySize(entry: string): Promise<number> {
|
||||
const stat = await fs.stat(entry).catch(() => null)
|
||||
if (!stat) {
|
||||
return 0
|
||||
}
|
||||
if (!stat.isDirectory()) {
|
||||
return stat.size
|
||||
}
|
||||
const names = await fs.readdir(entry).catch(() => [])
|
||||
const sizes = await Promise.all(
|
||||
names.map((name) => entrySize(path.join(entry, name)))
|
||||
)
|
||||
return sizes.reduce((total, size) => total + size, 0)
|
||||
}
|
||||
|
||||
async function prune() {
|
||||
const entries: {
|
||||
path: string
|
||||
size: number
|
||||
mtimeMs: number
|
||||
orphan: boolean
|
||||
}[] = []
|
||||
|
||||
for (const kind of ["hls", "lossless"] as const) {
|
||||
const dir = cacheDir(kind)
|
||||
const names = await fs.readdir(dir).catch(() => [])
|
||||
for (const name of names) {
|
||||
const entry = path.join(dir, name)
|
||||
const stat = await fs.stat(entry).catch(() => null)
|
||||
if (!stat) {
|
||||
continue
|
||||
}
|
||||
entries.push({
|
||||
path: entry,
|
||||
size: await entrySize(entry),
|
||||
mtimeMs: stat.mtimeMs,
|
||||
orphan: name.startsWith(CACHE_ORPHAN_PREFIX),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const maxBytes = maxCacheBytes()
|
||||
const now = Date.now()
|
||||
let total = entries.reduce((sum, entry) => sum + entry.size, 0)
|
||||
entries.sort((a, b) => a.mtimeMs - b.mtimeMs)
|
||||
|
||||
for (const entry of entries) {
|
||||
if (state.pinned.has(entry.path)) {
|
||||
continue
|
||||
}
|
||||
const remove = entry.orphan
|
||||
? now - entry.mtimeMs > ORPHAN_MAX_AGE_MS
|
||||
: total > maxBytes
|
||||
if (remove) {
|
||||
await fs.rm(entry.path, { recursive: true, force: true }).catch(() => {})
|
||||
total -= entry.size
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes least recently used entries until the cache fits under
|
||||
* OTUNES_CACHE_MAX_MB, plus abandoned in-progress entries.
|
||||
*/
|
||||
export function pruneCache() {
|
||||
state.pruning ??= prune()
|
||||
.catch((error) => console.error("Transcode cache prune failed", error))
|
||||
.finally(() => {
|
||||
state.pruning = null
|
||||
})
|
||||
return state.pruning
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"
|
||||
import os from "node:os"
|
||||
|
||||
const STDERR_TAIL_BYTES = 4096
|
||||
|
||||
export type FfmpegProcess = {
|
||||
child: ChildProcessWithoutNullStreams
|
||||
/** Resolves with the exit code, or null when killed by a signal. */
|
||||
exited: Promise<number | null>
|
||||
stderrTail: () => string
|
||||
}
|
||||
|
||||
type Limiter = {
|
||||
running: number
|
||||
waiting: (() => void)[]
|
||||
}
|
||||
|
||||
// Kept on globalThis so dev reloads share one limit with processes they spawned.
|
||||
const globalState = globalThis as typeof globalThis & {
|
||||
__otunesFfmpegLimiter?: Limiter
|
||||
}
|
||||
const limiter = (globalState.__otunesFfmpegLimiter ??= {
|
||||
running: 0,
|
||||
waiting: [],
|
||||
})
|
||||
|
||||
function maxConcurrentFfmpeg() {
|
||||
const configured = Number(process.env.OTUNES_MAX_FFMPEG)
|
||||
if (Number.isInteger(configured) && configured > 0) {
|
||||
return configured
|
||||
}
|
||||
return Math.max(2, os.availableParallelism())
|
||||
}
|
||||
|
||||
async function acquireSlot(signal?: AbortSignal) {
|
||||
signal?.throwIfAborted()
|
||||
if (limiter.running < maxConcurrentFfmpeg()) {
|
||||
limiter.running += 1
|
||||
return
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const grant = () => {
|
||||
signal?.removeEventListener("abort", onAbort)
|
||||
resolve()
|
||||
}
|
||||
const onAbort = () => {
|
||||
const index = limiter.waiting.indexOf(grant)
|
||||
if (index !== -1) {
|
||||
limiter.waiting.splice(index, 1)
|
||||
}
|
||||
reject(signal?.reason)
|
||||
}
|
||||
limiter.waiting.push(grant)
|
||||
signal?.addEventListener("abort", onAbort, { once: true })
|
||||
})
|
||||
}
|
||||
|
||||
function releaseSlot() {
|
||||
const next = limiter.waiting.shift()
|
||||
if (next) {
|
||||
// The slot passes straight to the next waiter.
|
||||
next()
|
||||
} else {
|
||||
limiter.running -= 1
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawns ffmpeg once a slot under the concurrency cap is free. The slot is
|
||||
* held until the process exits. Rejects if `signal` aborts while queued.
|
||||
*/
|
||||
export async function spawnFfmpeg(
|
||||
args: string[],
|
||||
signal?: AbortSignal
|
||||
): Promise<FfmpegProcess> {
|
||||
await acquireSlot(signal)
|
||||
|
||||
let child: ChildProcessWithoutNullStreams
|
||||
try {
|
||||
child = spawn("ffmpeg", [
|
||||
"-nostdin",
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"error",
|
||||
...args,
|
||||
])
|
||||
} catch (error) {
|
||||
releaseSlot()
|
||||
throw error
|
||||
}
|
||||
|
||||
// stderr must be drained or ffmpeg blocks once the pipe buffer fills.
|
||||
let stderr = ""
|
||||
child.stderr.on("data", (data: Buffer) => {
|
||||
stderr = (stderr + data.toString()).slice(-STDERR_TAIL_BYTES)
|
||||
})
|
||||
|
||||
const exited = new Promise<number | null>((resolve) => {
|
||||
let released = false
|
||||
const finish = (code: number | null) => {
|
||||
if (!released) {
|
||||
released = true
|
||||
releaseSlot()
|
||||
}
|
||||
resolve(code)
|
||||
}
|
||||
child.once("error", () => finish(1))
|
||||
child.once("close", (code) => finish(code))
|
||||
})
|
||||
|
||||
return { child, exited, stderrTail: () => stderr.trim() }
|
||||
}
|
||||
+95
-188
@@ -2,22 +2,12 @@ import type { Doc } from "@otunes/convex/_generated/dataModel"
|
||||
import crypto from "node:crypto"
|
||||
import fs from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import { audioInfo } from "@/lib/server-audio-info"
|
||||
import {
|
||||
cacheDir,
|
||||
pinCacheEntry,
|
||||
pruneCache,
|
||||
touchCacheEntry,
|
||||
unpinCacheEntry,
|
||||
} from "@/lib/server-cache"
|
||||
import { spawnFfmpeg, type FfmpegProcess } from "@/lib/server-ffmpeg"
|
||||
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
|
||||
|
||||
/** The server-only slice of a song needed to transcode it. */
|
||||
export type SongSource = Pick<Doc<"songs">, "_id" | "files" | "length">
|
||||
|
||||
type HlsJob = {
|
||||
key: string
|
||||
lookupKey: string
|
||||
@@ -27,28 +17,11 @@ type HlsJob = {
|
||||
lastTouchedAt: number
|
||||
processExited: boolean
|
||||
processExitCode: number | null
|
||||
process: FfmpegProcess | null
|
||||
abort: AbortController
|
||||
evicted: boolean
|
||||
}
|
||||
|
||||
type HlsState = {
|
||||
/** In-flight and ready jobs by cache key, so overlapping requests share one ffmpeg. */
|
||||
pending: Map<string, Promise<HlsJob>>
|
||||
jobs: Map<string, HlsJob>
|
||||
jobsByLookup: Map<string, HlsJob>
|
||||
lastCleanupAt: number
|
||||
}
|
||||
|
||||
const globalState = globalThis as typeof globalThis & {
|
||||
__otunesHls?: HlsState
|
||||
}
|
||||
const state = (globalState.__otunesHls ??= {
|
||||
pending: new Map(),
|
||||
jobs: new Map(),
|
||||
jobsByLookup: new Map(),
|
||||
lastCleanupAt: 0,
|
||||
})
|
||||
const jobs = new Map<string, HlsJob>()
|
||||
const jobsByLookup = new Map<string, HlsJob>()
|
||||
let lastCleanupAt = 0
|
||||
|
||||
export function qualityKbps(quality: string | null) {
|
||||
if (quality === "low") {
|
||||
@@ -63,7 +36,7 @@ export function qualityKbps(quality: string | null) {
|
||||
}
|
||||
|
||||
export function selectHlsSourceCodec(
|
||||
song: SongSource,
|
||||
song: Doc<"songs">,
|
||||
quality: string | null,
|
||||
preferAtmos: boolean
|
||||
) {
|
||||
@@ -77,6 +50,10 @@ export function selectHlsSourceCodec(
|
||||
return sourceCodec
|
||||
}
|
||||
|
||||
function hlsCacheRoot() {
|
||||
return "/tmp/otunes"
|
||||
}
|
||||
|
||||
function hlsLookupKey(
|
||||
songId: string,
|
||||
quality: string | null,
|
||||
@@ -86,7 +63,7 @@ function hlsLookupKey(
|
||||
}
|
||||
|
||||
async function hlsJobKey(
|
||||
song: SongSource,
|
||||
song: Doc<"songs">,
|
||||
sourcePath: string,
|
||||
kbps: number
|
||||
) {
|
||||
@@ -111,38 +88,31 @@ export function hlsSegmentPath(job: HlsJob, segmentIndex: number) {
|
||||
|
||||
async function touchHlsJob(job: HlsJob) {
|
||||
job.lastTouchedAt = Date.now()
|
||||
await touchCacheEntry(job.dir).catch(() => {})
|
||||
await fs.utimes(job.dir, new Date(job.lastTouchedAt), new Date(job.lastTouchedAt)).catch(
|
||||
() => {}
|
||||
)
|
||||
}
|
||||
|
||||
function forgetJob(job: HlsJob) {
|
||||
jobs.delete(job.key)
|
||||
if (jobsByLookup.get(job.lookupKey) === job) {
|
||||
jobsByLookup.delete(job.lookupKey)
|
||||
}
|
||||
}
|
||||
|
||||
async function evictJob(job: HlsJob) {
|
||||
if (job.evicted) {
|
||||
return
|
||||
}
|
||||
job.evicted = true
|
||||
state.pending.delete(job.key)
|
||||
state.jobs.delete(job.key)
|
||||
if (state.jobsByLookup.get(job.lookupKey) === job) {
|
||||
state.jobsByLookup.delete(job.lookupKey)
|
||||
}
|
||||
|
||||
job.abort.abort()
|
||||
job.process?.child.kill("SIGKILL")
|
||||
const complete = job.processExited && job.processExitCode === 0
|
||||
if (!complete) {
|
||||
await job.process?.exited
|
||||
await fs.rm(job.dir, { recursive: true, force: true }).catch(() => {})
|
||||
}
|
||||
unpinCacheEntry(job.dir)
|
||||
forgetJob(job)
|
||||
await fs.rm(job.dir, { recursive: true, force: true }).catch(() => {})
|
||||
}
|
||||
|
||||
async function cleanupIdleHlsJobs() {
|
||||
const now = Date.now()
|
||||
if (now - state.lastCleanupAt < 60_000) {
|
||||
if (now - lastCleanupAt < 60_000) {
|
||||
return
|
||||
}
|
||||
state.lastCleanupAt = now
|
||||
lastCleanupAt = now
|
||||
|
||||
for (const job of [...state.jobs.values()]) {
|
||||
for (const job of [...jobs.values()]) {
|
||||
if (now - job.lastTouchedAt > HLS_MAX_IDLE_MS) {
|
||||
await evictJob(job)
|
||||
}
|
||||
@@ -154,7 +124,7 @@ export function getExistingHlsJob(
|
||||
quality: string | null,
|
||||
preferAtmos: boolean
|
||||
) {
|
||||
return state.jobsByLookup.get(hlsLookupKey(songId, quality, preferAtmos)) ?? null
|
||||
return jobsByLookup.get(hlsLookupKey(songId, quality, preferAtmos)) ?? null
|
||||
}
|
||||
|
||||
export async function waitForHlsSegment(
|
||||
@@ -167,22 +137,18 @@ export async function waitForHlsSegment(
|
||||
const startedAt = Date.now()
|
||||
|
||||
while (Date.now() - startedAt < timeoutMs) {
|
||||
// Read before checking the file so a segment renamed just before exit is found.
|
||||
const exited = job.processExited
|
||||
try {
|
||||
// ffmpeg writes to a .tmp file and renames it when complete.
|
||||
await fs.access(segmentPath)
|
||||
return segmentPath
|
||||
} catch {
|
||||
if (job.evicted) {
|
||||
throw new Error("HLS job was evicted")
|
||||
const firstStat = await fs.stat(segmentPath)
|
||||
if (firstStat.size > 0) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
const secondStat = await fs.stat(segmentPath)
|
||||
if (firstStat.size === secondStat.size) {
|
||||
return segmentPath
|
||||
}
|
||||
}
|
||||
if (exited) {
|
||||
throw new Error(
|
||||
job.processExitCode === 0
|
||||
? "HLS segment does not exist"
|
||||
: `HLS transcode failed with code ${job.processExitCode}`
|
||||
)
|
||||
} catch {
|
||||
if (job.processExited && job.processExitCode !== 0) {
|
||||
throw new Error(`HLS transcode failed with code ${job.processExitCode}`)
|
||||
}
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
@@ -191,15 +157,52 @@ export async function waitForHlsSegment(
|
||||
throw new Error("Timed out waiting for HLS segment")
|
||||
}
|
||||
|
||||
async function hasCompletePlaylist(dir: string) {
|
||||
const playlist = await fs
|
||||
.readFile(path.join(dir, "index.m3u8"), "utf8")
|
||||
.catch(() => "")
|
||||
return playlist.includes("#EXT-X-ENDLIST")
|
||||
}
|
||||
export async function ensureHlsJob(
|
||||
song: Doc<"songs">,
|
||||
quality: string | null,
|
||||
preferAtmos: boolean
|
||||
) {
|
||||
await cleanupIdleHlsJobs()
|
||||
|
||||
const kbps = qualityKbps(quality)
|
||||
const sourceCodec = selectHlsSourceCodec(song, quality, preferAtmos)
|
||||
const sourcePath = song.files[sourceCodec]
|
||||
const key = await hlsJobKey(song, sourcePath, kbps)
|
||||
const lookupKey = hlsLookupKey(song._id, quality, preferAtmos)
|
||||
const existingJob = jobs.get(key)
|
||||
|
||||
if (existingJob) {
|
||||
try {
|
||||
await fs.access(existingJob.dir)
|
||||
await touchHlsJob(existingJob)
|
||||
return existingJob
|
||||
} catch {
|
||||
forgetJob(existingJob)
|
||||
}
|
||||
}
|
||||
|
||||
const metadata = await music.parseFile(sourcePath)
|
||||
const duration = metadata.format.duration ?? song.length
|
||||
const segmentCount = Math.max(1, Math.ceil(duration / HLS_SEGMENT_SECONDS))
|
||||
const dir = path.join(hlsCacheRoot(), key)
|
||||
await fs.mkdir(dir, { recursive: true })
|
||||
|
||||
const job: HlsJob = {
|
||||
key,
|
||||
lookupKey,
|
||||
dir,
|
||||
duration,
|
||||
segmentCount,
|
||||
lastTouchedAt: Date.now(),
|
||||
processExited: false,
|
||||
processExitCode: null,
|
||||
}
|
||||
jobs.set(key, job)
|
||||
jobsByLookup.set(lookupKey, job)
|
||||
await touchHlsJob(job)
|
||||
|
||||
function startTranscode(job: HlsJob, sourcePath: string, kbps: number) {
|
||||
const ffmpegArgs = [
|
||||
"-nostdin",
|
||||
"-i",
|
||||
sourcePath,
|
||||
"-vn",
|
||||
@@ -219,121 +222,25 @@ function startTranscode(job: HlsJob, sourcePath: string, kbps: number) {
|
||||
"0",
|
||||
"-hls_segment_type",
|
||||
"mpegts",
|
||||
"-hls_flags",
|
||||
"temp_file",
|
||||
"-hls_segment_filename",
|
||||
path.join(job.dir, "segment_%05d.ts"),
|
||||
path.join(job.dir, "index.m3u8"),
|
||||
path.join(dir, "segment_%05d.ts"),
|
||||
path.join(dir, "index.m3u8"),
|
||||
]
|
||||
const ffmpegProcess = spawn("ffmpeg", ffmpegArgs)
|
||||
|
||||
spawnFfmpeg(ffmpegArgs, job.abort.signal).then(
|
||||
async (ffmpeg) => {
|
||||
job.process = ffmpeg
|
||||
if (job.evicted) {
|
||||
ffmpeg.child.kill("SIGKILL")
|
||||
}
|
||||
const code = await ffmpeg.exited
|
||||
job.process = null
|
||||
job.processExited = true
|
||||
job.processExitCode = code
|
||||
if (job.evicted) {
|
||||
return
|
||||
}
|
||||
if (code === 0) {
|
||||
void pruneCache()
|
||||
} else {
|
||||
console.error(`ffmpeg HLS exited with code ${code}`, ffmpeg.stderrTail())
|
||||
}
|
||||
},
|
||||
() => {
|
||||
job.processExited = true
|
||||
job.processExitCode = 1
|
||||
}
|
||||
)
|
||||
}
|
||||
ffmpegProcess.stderr.on("data", (data) => {
|
||||
console.error(`FFmpeg HLS log: ${data.toString()}`)
|
||||
})
|
||||
|
||||
async function createHlsJob(
|
||||
song: SongSource,
|
||||
sourcePath: string,
|
||||
kbps: number,
|
||||
key: string,
|
||||
lookupKey: string
|
||||
): Promise<HlsJob> {
|
||||
const info = await audioInfo(sourcePath)
|
||||
const duration = info.duration ?? song.length
|
||||
const segmentCount = Math.max(1, Math.ceil(duration / HLS_SEGMENT_SECONDS))
|
||||
const dir = path.join(cacheDir("hls"), key)
|
||||
pinCacheEntry(dir)
|
||||
ffmpegProcess.on("close", (code) => {
|
||||
job.processExited = true
|
||||
job.processExitCode = code
|
||||
})
|
||||
|
||||
try {
|
||||
const complete = await hasCompletePlaylist(dir)
|
||||
if (!complete) {
|
||||
await fs.rm(dir, { recursive: true, force: true })
|
||||
await fs.mkdir(dir, { recursive: true })
|
||||
}
|
||||
ffmpegProcess.on("error", () => {
|
||||
job.processExited = true
|
||||
job.processExitCode = 1
|
||||
})
|
||||
|
||||
const job: HlsJob = {
|
||||
key,
|
||||
lookupKey,
|
||||
dir,
|
||||
duration,
|
||||
segmentCount,
|
||||
lastTouchedAt: Date.now(),
|
||||
processExited: complete,
|
||||
processExitCode: complete ? 0 : null,
|
||||
process: null,
|
||||
abort: new AbortController(),
|
||||
evicted: false,
|
||||
}
|
||||
state.jobs.set(key, job)
|
||||
await touchHlsJob(job)
|
||||
|
||||
if (!complete) {
|
||||
startTranscode(job, sourcePath, kbps)
|
||||
}
|
||||
return job
|
||||
} catch (error) {
|
||||
unpinCacheEntry(dir)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function ensureHlsJob(
|
||||
song: SongSource,
|
||||
quality: string | null,
|
||||
preferAtmos: boolean
|
||||
): Promise<HlsJob> {
|
||||
await cleanupIdleHlsJobs()
|
||||
|
||||
const kbps = qualityKbps(quality)
|
||||
const sourceCodec = selectHlsSourceCodec(song, quality, preferAtmos)
|
||||
const sourcePath = song.files[sourceCodec]
|
||||
const key = await hlsJobKey(song, sourcePath, kbps)
|
||||
const lookupKey = hlsLookupKey(song._id, quality, preferAtmos)
|
||||
|
||||
let pending = state.pending.get(key)
|
||||
if (!pending) {
|
||||
pending = createHlsJob(song, sourcePath, kbps, key, lookupKey)
|
||||
state.pending.set(key, pending)
|
||||
const created = pending
|
||||
created.catch(() => {
|
||||
if (state.pending.get(key) === created) {
|
||||
state.pending.delete(key)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const job = await pending
|
||||
const exists = await fs.access(job.dir).then(
|
||||
() => true,
|
||||
() => false
|
||||
)
|
||||
if (job.evicted || !exists) {
|
||||
await evictJob(job)
|
||||
return ensureHlsJob(song, quality, preferAtmos)
|
||||
}
|
||||
|
||||
state.jobsByLookup.set(lookupKey, job)
|
||||
await touchHlsJob(job)
|
||||
return job
|
||||
}
|
||||
@@ -1,15 +1,8 @@
|
||||
import { spawn } from "node:child_process"
|
||||
import { createHash } from "node:crypto"
|
||||
import fs from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import {
|
||||
CACHE_ORPHAN_PREFIX,
|
||||
cacheDir,
|
||||
pinCacheEntry,
|
||||
pruneCache,
|
||||
touchCacheEntry,
|
||||
unpinCacheEntry,
|
||||
} from "@/lib/server-cache"
|
||||
import { spawnFfmpeg } from "@/lib/server-ffmpeg"
|
||||
|
||||
const conversions = new Map<string, Promise<string>>()
|
||||
|
||||
@@ -34,38 +27,56 @@ export async function seekableLosslessFile(source: string): Promise<string> {
|
||||
}
|
||||
|
||||
async function convert(source: string, key: string): Promise<string> {
|
||||
const dir = cacheDir("lossless")
|
||||
const dir = path.join(os.tmpdir(), "otunes-lossless")
|
||||
await fs.mkdir(dir, { recursive: true })
|
||||
const cutoff = Date.now() - 30 * 60 * 1000
|
||||
await Promise.all(
|
||||
(await fs.readdir(dir))
|
||||
.filter((name) => name.endsWith(".flac"))
|
||||
.map(async (name) => {
|
||||
const file = path.join(dir, name)
|
||||
const stat = await fs.stat(file).catch(() => null)
|
||||
if (stat && stat.mtimeMs < cutoff) await fs.rm(file, { force: true })
|
||||
})
|
||||
)
|
||||
const output = path.join(dir, `${key}.flac`)
|
||||
try {
|
||||
// Every range request touches the file so it stays cached while playing.
|
||||
await touchCacheEntry(output)
|
||||
await fs.access(output)
|
||||
return output
|
||||
} catch {
|
||||
// Publish only completed conversions so range requests always see a complete file.
|
||||
}
|
||||
const temporaryDir = await fs.mkdtemp(path.join(dir, CACHE_ORPHAN_PREFIX))
|
||||
const temporary = path.join(temporaryDir, "audio.flac")
|
||||
pinCacheEntry(temporaryDir)
|
||||
const temporary = path.join(
|
||||
await fs.mkdtemp(path.join(dir, "convert-")),
|
||||
"audio.flac"
|
||||
)
|
||||
try {
|
||||
const ffmpeg = await spawnFfmpeg([
|
||||
"-i",
|
||||
source,
|
||||
"-map",
|
||||
"0:a:0",
|
||||
"-c:a",
|
||||
"flac",
|
||||
temporary,
|
||||
])
|
||||
const code = await ffmpeg.exited
|
||||
if (code !== 0) {
|
||||
throw new Error(`Lossless conversion failed: ${code}: ${ffmpeg.stderrTail()}`)
|
||||
}
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const child = spawn(
|
||||
"ffmpeg",
|
||||
[
|
||||
"-nostdin",
|
||||
"-v",
|
||||
"error",
|
||||
"-i",
|
||||
source,
|
||||
"-map",
|
||||
"0:a:0",
|
||||
"-c:a",
|
||||
"flac",
|
||||
temporary,
|
||||
],
|
||||
{ stdio: "ignore" }
|
||||
)
|
||||
child.on("error", reject)
|
||||
child.on("close", (code) => {
|
||||
if (code === 0) resolve()
|
||||
else reject(new Error(`Lossless conversion failed: ${code}`))
|
||||
})
|
||||
})
|
||||
await fs.rename(temporary, output)
|
||||
return output
|
||||
} finally {
|
||||
unpinCacheEntry(temporaryDir)
|
||||
await fs.rm(temporaryDir, { recursive: true, force: true })
|
||||
await fs.rm(path.dirname(temporary), { recursive: true, force: true })
|
||||
}
|
||||
void pruneCache()
|
||||
return output
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import { fetchQuery } from "convex/nextjs"
|
||||
import { convexServerOptions } from "@/lib/convex-server"
|
||||
import type { SongSource } from "@/lib/server-hls"
|
||||
|
||||
/**
|
||||
* Loads a song's file paths as the requesting listener, so Convex enforces auth
|
||||
* even if the proxy is bypassed. Throws when signed out or the song is missing.
|
||||
*/
|
||||
export async function getSongSource(id: string): Promise<SongSource> {
|
||||
const token = await convexAuthNextjsToken()
|
||||
const song = await fetchQuery(
|
||||
api.library.getSongSource,
|
||||
{ id: id as Id<"songs"> },
|
||||
convexServerOptions(token)
|
||||
)
|
||||
if (!song) {
|
||||
throw new Error("Song not found")
|
||||
}
|
||||
return song
|
||||
}
|
||||
@@ -14,7 +14,6 @@
|
||||
"@base-ui/react": "^1.5.0",
|
||||
"@convex-dev/auth": "^0.0.93",
|
||||
"@otunes/convex": "workspace:*",
|
||||
"@tanstack/react-virtual": "^3.14.26",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ const isPublic = createRouteMatcher([
|
||||
"/api/playlist/:id/cover",
|
||||
"/album/:id",
|
||||
"/artist/:id",
|
||||
"/library/artists/:id",
|
||||
"/artists/:id",
|
||||
"/playlist/:id",
|
||||
])
|
||||
|
||||
|
||||
@@ -97,9 +97,6 @@ admin_key=$(cd /convex && umask 077 && "${as_convex[@]}" ./generate_admin_key.sh
|
||||
log "Deploying Convex functions"
|
||||
convex_cli deploy --typecheck disable --codegen disable
|
||||
|
||||
log "Running data migrations"
|
||||
convex_cli run migrations:migrateUsers
|
||||
|
||||
# `env get` exits 0 with no output when the variable is unset. Any other failure
|
||||
# must not be read as "no keys": regenerating them signs every user out.
|
||||
if ! jwks=$(convex_cli env get JWKS); then
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { Id } from "../convex/_generated/dataModel"
|
||||
import { MAX_QUEUE_LENGTH } from "../convex/limits"
|
||||
import {
|
||||
EMPTY_PLAYBACK_QUEUE,
|
||||
type PlaybackQueueState,
|
||||
@@ -8,11 +7,6 @@ import {
|
||||
import { loadPersistentCache, readCache, writeCache } from "./persistent-cache"
|
||||
|
||||
const SYNC_DELAY_MS = 300
|
||||
/**
|
||||
* Backoff for failed syncs. Convex queues mutations while offline, so a
|
||||
* rejection means the server refused the state; after the last retry the
|
||||
* change is dropped until the next local edit instead of retrying forever.
|
||||
*/
|
||||
const RETRY_DELAYS_MS = [1_000, 3_000, 10_000, 30_000]
|
||||
|
||||
export type ServerPlaybackState = {
|
||||
@@ -20,6 +14,7 @@ export type ServerPlaybackState = {
|
||||
queueHistorySongIds: Id<"songs">[]
|
||||
shuffleEnabled: boolean
|
||||
repeatEnabled: RepeatMode
|
||||
currentSongProgress: number
|
||||
revision: number
|
||||
}
|
||||
|
||||
@@ -35,12 +30,9 @@ type PersistedPlayback = PlaybackQueueState & {
|
||||
dirty: boolean
|
||||
}
|
||||
|
||||
export type PlaybackSyncTransport = {
|
||||
/** Saves the state and resolves with the new server revision. */
|
||||
sync: (state: PlaybackQueueState) => Promise<number>
|
||||
/** One-shot read of the server's saved progress for its current song. */
|
||||
loadProgress: () => Promise<number>
|
||||
}
|
||||
export type PlaybackSyncTransport = (
|
||||
state: PlaybackQueueState
|
||||
) => Promise<number>
|
||||
|
||||
/**
|
||||
* Client-owned playback queue. Changes apply locally (and persist on this
|
||||
@@ -57,7 +49,6 @@ export class PlaybackStore {
|
||||
private retryAttempt = 0
|
||||
private syncTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private latestServerState: ServerPlaybackState | null = null
|
||||
private adopting = false
|
||||
private transport: PlaybackSyncTransport | null = null
|
||||
private readonly listeners = new Set<() => void>()
|
||||
|
||||
@@ -88,7 +79,7 @@ export class PlaybackStore {
|
||||
}
|
||||
|
||||
update(recipe: (state: PlaybackQueueState) => PlaybackQueueState) {
|
||||
const next = capQueue(recipe(this.state))
|
||||
const next = recipe(this.state)
|
||||
if (next === this.state) {
|
||||
return
|
||||
}
|
||||
@@ -111,7 +102,7 @@ export class PlaybackStore {
|
||||
receiveServerState(serverState: ServerPlaybackState) {
|
||||
this.latestServerState = serverState
|
||||
if (this.snapshot.hydrated) {
|
||||
void this.adoptServerState()
|
||||
this.adoptServerState()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,52 +116,23 @@ export class PlaybackStore {
|
||||
const { revision, dirty, ...state } = persisted
|
||||
this.revision = revision
|
||||
this.dirty = dirty
|
||||
this.state = capQueue({ ...EMPTY_PLAYBACK_QUEUE, ...state })
|
||||
this.state = { ...EMPTY_PLAYBACK_QUEUE, ...state }
|
||||
}
|
||||
|
||||
this.snapshot = toSnapshot(this.state, true)
|
||||
this.emit()
|
||||
void this.adoptServerState()
|
||||
this.adoptServerState()
|
||||
if (this.dirty) {
|
||||
this.scheduleSync(0)
|
||||
}
|
||||
}
|
||||
|
||||
private canAdopt(serverState: ServerPlaybackState | null) {
|
||||
return (
|
||||
serverState !== null &&
|
||||
!this.dirty &&
|
||||
!this.inFlight &&
|
||||
(this.revision === null || serverState.revision > this.revision)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Adopts the latest server queue. Progress is not part of the queue query
|
||||
* (it changes every few seconds), so it is fetched once here.
|
||||
*/
|
||||
private async adoptServerState() {
|
||||
private adoptServerState() {
|
||||
const serverState = this.latestServerState
|
||||
if (this.adopting || !serverState || !this.canAdopt(serverState)) {
|
||||
if (!serverState || this.dirty || this.inFlight) {
|
||||
return
|
||||
}
|
||||
|
||||
this.adopting = true
|
||||
let progressSeconds = 0
|
||||
try {
|
||||
progressSeconds = (await this.transport?.loadProgress()) ?? 0
|
||||
} catch {
|
||||
// Starting from 0 beats not adopting the queue at all.
|
||||
} finally {
|
||||
this.adopting = false
|
||||
}
|
||||
|
||||
// Newer server state or local edits may have arrived while loading.
|
||||
if (this.latestServerState !== serverState) {
|
||||
void this.adoptServerState()
|
||||
return
|
||||
}
|
||||
if (!this.canAdopt(serverState)) {
|
||||
if (this.revision !== null && serverState.revision <= this.revision) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -180,7 +142,7 @@ export class PlaybackStore {
|
||||
history: serverState.queueHistorySongIds,
|
||||
shuffleEnabled: serverState.shuffleEnabled,
|
||||
repeatEnabled: serverState.repeatEnabled,
|
||||
progressSeconds,
|
||||
progressSeconds: serverState.currentSongProgress,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -205,7 +167,7 @@ export class PlaybackStore {
|
||||
let failed = false
|
||||
|
||||
try {
|
||||
const revision = await transport.sync(this.state)
|
||||
const revision = await transport(this.state)
|
||||
this.revision = Math.max(revision, this.revision ?? 0)
|
||||
this.retryAttempt = 0
|
||||
if (this.changeCount === changeCountAtStart) {
|
||||
@@ -219,17 +181,15 @@ export class PlaybackStore {
|
||||
|
||||
this.persist()
|
||||
|
||||
if (failed && this.retryAttempt < RETRY_DELAYS_MS.length) {
|
||||
this.scheduleSync(RETRY_DELAYS_MS[this.retryAttempt])
|
||||
if (failed) {
|
||||
const delay =
|
||||
RETRY_DELAYS_MS[Math.min(this.retryAttempt, RETRY_DELAYS_MS.length - 1)]
|
||||
this.retryAttempt += 1
|
||||
} else if (failed) {
|
||||
this.retryAttempt = 0
|
||||
this.dirty = false
|
||||
this.persist()
|
||||
this.scheduleSync(delay)
|
||||
} else if (this.dirty) {
|
||||
this.scheduleSync(SYNC_DELAY_MS)
|
||||
} else {
|
||||
void this.adoptServerState()
|
||||
this.adoptServerState()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,14 +227,6 @@ export class PlaybackStore {
|
||||
}
|
||||
}
|
||||
|
||||
/** Mirrors the server's queue cap so local and synced state agree. */
|
||||
function capQueue(state: PlaybackQueueState): PlaybackQueueState {
|
||||
if (state.queue.length <= MAX_QUEUE_LENGTH) {
|
||||
return state
|
||||
}
|
||||
return { ...state, queue: state.queue.slice(0, MAX_QUEUE_LENGTH) }
|
||||
}
|
||||
|
||||
function toSnapshot(
|
||||
state: PlaybackQueueState,
|
||||
hydrated: boolean
|
||||
|
||||
-6
@@ -14,10 +14,7 @@ import type * as crons from "../crons.js";
|
||||
import type * as favorites from "../favorites.js";
|
||||
import type * as http from "../http.js";
|
||||
import type * as library from "../library.js";
|
||||
import type * as limits from "../limits.js";
|
||||
import type * as migrations from "../migrations.js";
|
||||
import type * as playback from "../playback.js";
|
||||
import type * as playbackState from "../playbackState.js";
|
||||
import type * as playlists from "../playlists.js";
|
||||
import type * as types from "../types.js";
|
||||
import type * as users from "../users.js";
|
||||
@@ -35,10 +32,7 @@ declare const fullApi: ApiFromModules<{
|
||||
favorites: typeof favorites;
|
||||
http: typeof http;
|
||||
library: typeof library;
|
||||
limits: typeof limits;
|
||||
migrations: typeof migrations;
|
||||
playback: typeof playback;
|
||||
playbackState: typeof playbackState;
|
||||
playlists: typeof playlists;
|
||||
types: typeof types;
|
||||
users: typeof users;
|
||||
|
||||
@@ -3,7 +3,6 @@ import { ConvexError } from "convex/values"
|
||||
import { Password } from "@convex-dev/auth/providers/Password"
|
||||
import { query } from "./_generated/server"
|
||||
import type { MutationCtx } from "./_generated/server"
|
||||
import { profileImagePath } from "./users"
|
||||
|
||||
export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({
|
||||
providers: [
|
||||
@@ -73,7 +72,7 @@ export const currentUser = query({
|
||||
return {
|
||||
_id: user._id,
|
||||
name: user.name,
|
||||
image: profileImagePath(user),
|
||||
image: user.image,
|
||||
email: user.email,
|
||||
isAdmin: user.isAdmin,
|
||||
playbackQuality: user.playbackQuality,
|
||||
|
||||
@@ -39,20 +39,6 @@ export type {
|
||||
SidebarPlaylists,
|
||||
} from "./types"
|
||||
|
||||
const EMPTY_PAGE = { page: [], isDone: true, continueCursor: "" }
|
||||
|
||||
/** Reactive queries return empty data when signed out so sign-out doesn't throw mid-render. */
|
||||
export async function isSignedIn(ctx: QueryCtx) {
|
||||
return (await getAuthUserId(ctx)) !== null
|
||||
}
|
||||
|
||||
/** Imperative lookups throw instead, so callers that cache results don't cache an empty one. */
|
||||
export async function requireSignedIn(ctx: QueryCtx) {
|
||||
if (!(await isSignedIn(ctx))) {
|
||||
throw new ConvexError("Not authenticated")
|
||||
}
|
||||
}
|
||||
|
||||
function getSongArtistNames(artist: string | string[]): string[] {
|
||||
if (Array.isArray(artist)) {
|
||||
return artist.map((name) => name.trim()).filter((name) => name.length > 0)
|
||||
@@ -214,9 +200,6 @@ function toBrowseSong(
|
||||
export const browseAlbums = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
if (!(await isSignedIn(ctx))) {
|
||||
return []
|
||||
}
|
||||
const artistMap = await loadArtistMap(ctx)
|
||||
const albums = await ctx.db.query("albums").collect()
|
||||
|
||||
@@ -232,9 +215,6 @@ export const browseAlbums = query({
|
||||
export const browseArtists = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
if (!(await isSignedIn(ctx))) {
|
||||
return []
|
||||
}
|
||||
const artists = await ctx.db.query("artists").collect()
|
||||
return artists
|
||||
.map(toBrowseArtist)
|
||||
@@ -262,9 +242,6 @@ function paginateSlice<T>(
|
||||
export const browseArtistsPaginated = query({
|
||||
args: { paginationOpts: paginationOptsValidator },
|
||||
handler: async (ctx, args) => {
|
||||
if (!(await isSignedIn(ctx))) {
|
||||
return EMPTY_PAGE
|
||||
}
|
||||
const result = await ctx.db
|
||||
.query("artists")
|
||||
.withIndex("by_name")
|
||||
@@ -281,9 +258,6 @@ export const browseArtistsPaginated = query({
|
||||
export const browseAlbumsPaginated = query({
|
||||
args: { paginationOpts: paginationOptsValidator },
|
||||
handler: async (ctx, args) => {
|
||||
if (!(await isSignedIn(ctx))) {
|
||||
return EMPTY_PAGE
|
||||
}
|
||||
const result = await ctx.db
|
||||
.query("albums")
|
||||
.withIndex("by_name")
|
||||
@@ -484,9 +458,6 @@ export const browseSongsPaginated = query({
|
||||
sortDirection: songsSortDirectionValidator,
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
if (!(await isSignedIn(ctx))) {
|
||||
return EMPTY_PAGE
|
||||
}
|
||||
if (args.sortKey === "title") {
|
||||
return paginateSongsByTitle(ctx, args.paginationOpts, args.sortDirection)
|
||||
}
|
||||
@@ -506,7 +477,6 @@ export const browseSortedSongIds = query({
|
||||
sortDirection: songsSortDirectionValidator,
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
await requireSignedIn(ctx)
|
||||
return getSortedLibrarySongIds(ctx, args.sortKey, args.sortDirection)
|
||||
},
|
||||
})
|
||||
@@ -516,7 +486,6 @@ const MAX_SONGS_BY_IDS = 200
|
||||
export const browseSongsByIds = query({
|
||||
args: { ids: v.array(v.id("songs")) },
|
||||
handler: async (ctx, args): Promise<BrowseSong[]> => {
|
||||
await requireSignedIn(ctx)
|
||||
if (args.ids.length > MAX_SONGS_BY_IDS) {
|
||||
throw new ConvexError(`Request at most ${MAX_SONGS_BY_IDS} songs`)
|
||||
}
|
||||
@@ -524,7 +493,6 @@ export const browseSongsByIds = query({
|
||||
},
|
||||
})
|
||||
|
||||
/** Public: shared /album links render this without a session. */
|
||||
export const browseAlbumDetail = query({
|
||||
args: { id: v.id("albums") },
|
||||
handler: async (ctx, args): Promise<BrowseAlbumDetail | null> => {
|
||||
@@ -554,7 +522,6 @@ export const browseAlbumDetail = query({
|
||||
},
|
||||
})
|
||||
|
||||
/** Public: shared /artist links render this without a session. */
|
||||
export const browseArtistDetail = query({
|
||||
args: { id: v.id("artists") },
|
||||
handler: async (ctx, args) => {
|
||||
@@ -608,7 +575,7 @@ export const searchLibrary = query({
|
||||
args: { query: v.string() },
|
||||
handler: async (ctx, args) => {
|
||||
const queryText = args.query.trim().toLowerCase()
|
||||
if (!queryText || !(await isSignedIn(ctx))) {
|
||||
if (!queryText) {
|
||||
return {
|
||||
topResults: [],
|
||||
artists: [],
|
||||
@@ -710,9 +677,6 @@ export const searchLibrary = query({
|
||||
export const browseRecentlyAdded = query({
|
||||
args: { limit: v.optional(v.number()) },
|
||||
handler: async (ctx, args) => {
|
||||
if (!(await isSignedIn(ctx))) {
|
||||
return []
|
||||
}
|
||||
const albumQuery = ctx.db.query("albums").order("desc")
|
||||
const albums = args.limit
|
||||
? await albumQuery.take(args.limit)
|
||||
@@ -732,9 +696,6 @@ export const browseRecentlyAdded = query({
|
||||
export const browseRecentlyAddedPaginated = query({
|
||||
args: { paginationOpts: paginationOptsValidator },
|
||||
handler: async (ctx, args) => {
|
||||
if (!(await isSignedIn(ctx))) {
|
||||
return EMPTY_PAGE
|
||||
}
|
||||
const result = await ctx.db
|
||||
.query("albums")
|
||||
.order("desc")
|
||||
@@ -865,53 +826,31 @@ export const getSongs = internalQuery({
|
||||
},
|
||||
})
|
||||
|
||||
/** Public: share-link previews load covers without a session. */
|
||||
export const getArtistCover = query({
|
||||
export const getArtist = query({
|
||||
args: { id: v.id("artists") },
|
||||
handler: async (ctx, args) => {
|
||||
return (await ctx.db.get("artists", args.id))?.cover ?? null
|
||||
return await ctx.db.get("artists", args.id)
|
||||
},
|
||||
})
|
||||
|
||||
/** Public: share-link previews load covers without a session. */
|
||||
export const getAlbumCover = query({
|
||||
export const getAlbum = query({
|
||||
args: { id: v.id("albums") },
|
||||
handler: async (ctx, args) => {
|
||||
return (await ctx.db.get("albums", args.id))?.cover ?? null
|
||||
return await ctx.db.get("albums", args.id)
|
||||
},
|
||||
})
|
||||
|
||||
/** Public: share-link previews load covers without a session. */
|
||||
export const getPlaylistCover = query({
|
||||
export const getPlaylist = query({
|
||||
args: { id: v.id("playlists") },
|
||||
handler: async (ctx, args) => {
|
||||
return (await ctx.db.get("playlists", args.id))?.cover ?? null
|
||||
return await ctx.db.get("playlists", args.id)
|
||||
},
|
||||
})
|
||||
|
||||
/** Public: share-link previews read song metadata without a session. Never returns file paths. */
|
||||
export const getSong = query({
|
||||
args: { id: v.id("songs") },
|
||||
handler: async (ctx, args) => {
|
||||
const song = await ctx.db.get("songs", args.id)
|
||||
if (!song) {
|
||||
return null
|
||||
}
|
||||
const { files: _files, ...clientSong } = song
|
||||
return clientSong
|
||||
},
|
||||
})
|
||||
|
||||
/** Returns absolute file paths. Only the web streaming routes call this, as the listener. */
|
||||
export const getSongSource = query({
|
||||
args: { id: v.id("songs") },
|
||||
handler: async (ctx, args) => {
|
||||
await requireSignedIn(ctx)
|
||||
const song = await ctx.db.get("songs", args.id)
|
||||
if (!song) {
|
||||
return null
|
||||
}
|
||||
return { _id: song._id, files: song.files, length: song.length }
|
||||
return await ctx.db.get("songs", args.id)
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
/**
|
||||
* Limits shared by Convex functions and clients. Convex rejects arrays longer
|
||||
* than 8,192 values in documents, arguments, and return values.
|
||||
*/
|
||||
|
||||
/** Songs kept in the playback queue, including the current song. */
|
||||
export const MAX_QUEUE_LENGTH = 5_000
|
||||
|
||||
/** Largest profile photo accepted, in bytes after base64 decoding. */
|
||||
export const MAX_PROFILE_IMAGE_BYTES = 2 * 1024 * 1024
|
||||
@@ -1,39 +0,0 @@
|
||||
import { v } from "convex/values"
|
||||
import { internal } from "./_generated/api"
|
||||
import { internalMutation } from "./_generated/server"
|
||||
import { hasLegacyPlayback, migrateUserPlayback } from "./playbackState"
|
||||
|
||||
const BATCH_SIZE = 25
|
||||
|
||||
/**
|
||||
* Moves playback state off `users` into `playbackStates`/`playbackProgress`
|
||||
* and legacy data URL avatars into file storage. Idempotent; the Docker
|
||||
* entrypoint runs it on every boot. Run manually with
|
||||
* `npx convex run migrations:migrateUsers`.
|
||||
*/
|
||||
export const migrateUsers = internalMutation({
|
||||
args: { cursor: v.optional(v.union(v.string(), v.null())) },
|
||||
handler: async (ctx, { cursor }) => {
|
||||
const page = await ctx.db
|
||||
.query("users")
|
||||
.paginate({ cursor: cursor ?? null, numItems: BATCH_SIZE })
|
||||
|
||||
for (const user of page.page) {
|
||||
if (hasLegacyPlayback(user)) {
|
||||
await migrateUserPlayback(ctx, user)
|
||||
}
|
||||
if (!user.imageStorageId && user.image?.startsWith("data:")) {
|
||||
await ctx.scheduler.runAfter(0, internal.users.storeProfileImage, {
|
||||
userId: user._id,
|
||||
image: user.image,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (!page.isDone) {
|
||||
await ctx.scheduler.runAfter(0, internal.migrations.migrateUsers, {
|
||||
cursor: page.continueCursor,
|
||||
})
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -1,19 +1,13 @@
|
||||
import { getAuthUserId } from "@convex-dev/auth/server"
|
||||
import { ConvexError, v } from "convex/values"
|
||||
import type { Id } from "./_generated/dataModel"
|
||||
import type { Doc, Id } from "./_generated/dataModel"
|
||||
import type { MutationCtx } from "./_generated/server"
|
||||
import { mutation, query } from "./_generated/server"
|
||||
import { browseSongsFromIds } from "./library"
|
||||
import {
|
||||
loadPlaybackForWrite,
|
||||
readPlaybackProgress,
|
||||
readPlaybackState,
|
||||
writePlayback,
|
||||
writeProgress,
|
||||
} from "./playbackState"
|
||||
|
||||
export type { HistorySong, QueueSong } from "./types"
|
||||
|
||||
const MAX_QUEUE_HISTORY = 30
|
||||
const MAX_RECENTLY_PLAYED = 30
|
||||
|
||||
type RecentlyPlayedItem = Id<"albums"> | Id<"playlists">
|
||||
@@ -65,15 +59,30 @@ async function requireAuth(ctx: MutationCtx) {
|
||||
return userId
|
||||
}
|
||||
|
||||
async function requirePlayback(ctx: MutationCtx, userId: Id<"users">) {
|
||||
const playback = await loadPlaybackForWrite(ctx, userId)
|
||||
if (!playback) {
|
||||
async function patchPlayback(
|
||||
ctx: MutationCtx,
|
||||
userId: Id<"users">,
|
||||
patch: Partial<
|
||||
Pick<
|
||||
Doc<"users">,
|
||||
| "songQueue"
|
||||
| "queueHistory"
|
||||
| "currentSongProgress"
|
||||
| "shuffleEnabled"
|
||||
| "repeatEnabled"
|
||||
>
|
||||
>
|
||||
) {
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
return playback
|
||||
|
||||
const playbackRevision = (user.playbackRevision ?? 0) + 1
|
||||
await ctx.db.patch(userId, { ...patch, playbackRevision })
|
||||
return playbackRevision
|
||||
}
|
||||
|
||||
/** Queue state without progress; progress comes from `getSongProgress`. */
|
||||
export const getPlaybackState = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
@@ -82,8 +91,12 @@ export const getPlaybackState = query({
|
||||
return null
|
||||
}
|
||||
|
||||
const playback = await readPlaybackState(ctx, userId)
|
||||
const songIds = playback.songQueue
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
return null
|
||||
}
|
||||
|
||||
const songIds = user.songQueue ?? []
|
||||
const currentSong =
|
||||
songIds.length > 0
|
||||
? ((await browseSongsFromIds(ctx, [songIds[0]]))[0] ?? null)
|
||||
@@ -91,16 +104,12 @@ export const getPlaybackState = query({
|
||||
|
||||
return {
|
||||
queueSongIds: songIds,
|
||||
queueHistorySongIds: playback.queueHistory,
|
||||
queueHistorySongIds: user.queueHistory ?? [],
|
||||
currentSong,
|
||||
shuffleEnabled: playback.shuffleEnabled,
|
||||
repeatEnabled: playback.repeatEnabled,
|
||||
/**
|
||||
* @deprecated Always 0. Reading progress here would rerun this query on
|
||||
* every progress save. Kept for app builds that predate `getSongProgress`.
|
||||
*/
|
||||
currentSongProgress: 0,
|
||||
revision: playback.revision,
|
||||
shuffleEnabled: user.shuffleEnabled ?? false,
|
||||
repeatEnabled: user.repeatEnabled ?? ("none" as const),
|
||||
currentSongProgress: user.currentSongProgress ?? 0,
|
||||
revision: user.playbackRevision ?? 0,
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -125,12 +134,12 @@ export const syncPlaybackState = mutation({
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
return await writePlayback(ctx, userId, {
|
||||
return await patchPlayback(ctx, userId, {
|
||||
songQueue: args.songQueue,
|
||||
queueHistory: args.queueHistory,
|
||||
queueHistory: args.queueHistory.slice(-MAX_QUEUE_HISTORY),
|
||||
shuffleEnabled: args.shuffleEnabled,
|
||||
repeatEnabled: args.repeatEnabled,
|
||||
progressSeconds: args.currentSongProgress,
|
||||
currentSongProgress: Math.max(0, Math.floor(args.currentSongProgress)),
|
||||
})
|
||||
},
|
||||
})
|
||||
@@ -150,26 +159,6 @@ export const recordPlay = mutation({
|
||||
},
|
||||
})
|
||||
|
||||
/**
|
||||
* Saved position of the current song. Subscribing reruns every few seconds
|
||||
* during playback, so clients fetch it once when adopting a new queue.
|
||||
*/
|
||||
export const getSongProgress = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const userId = await getAuthUserId(ctx)
|
||||
if (userId === null) {
|
||||
throw new ConvexError("User not logged in")
|
||||
}
|
||||
|
||||
const [{ songQueue }, progress] = await Promise.all([
|
||||
readPlaybackState(ctx, userId),
|
||||
readPlaybackProgress(ctx, userId),
|
||||
])
|
||||
return progress.songId === songQueue[0] ? progress.progressSeconds : 0
|
||||
},
|
||||
})
|
||||
|
||||
export const updateSongProgress = mutation({
|
||||
args: {
|
||||
songId: v.id("songs"),
|
||||
@@ -177,15 +166,15 @@ export const updateSongProgress = mutation({
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const playback = await requirePlayback(ctx, userId)
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
if (playback.songQueue[0] !== args.songId) {
|
||||
if ((user.songQueue ?? [])[0] !== args.songId) {
|
||||
return
|
||||
}
|
||||
|
||||
await writeProgress(ctx, userId, {
|
||||
songId: args.songId,
|
||||
progressSeconds: args.progressSeconds,
|
||||
})
|
||||
await ctx.db.patch(userId, { currentSongProgress: args.progressSeconds })
|
||||
},
|
||||
})
|
||||
@@ -1,236 +0,0 @@
|
||||
import { ConvexError } from "convex/values"
|
||||
import type { Doc, Id } from "./_generated/dataModel"
|
||||
import type { MutationCtx, QueryCtx } from "./_generated/server"
|
||||
import { MAX_QUEUE_LENGTH } from "./limits"
|
||||
|
||||
const MAX_QUEUE_HISTORY = 30
|
||||
|
||||
export type RepeatMode = Doc<"playbackStates">["repeatEnabled"]
|
||||
|
||||
export type PlaybackState = Pick<
|
||||
Doc<"playbackStates">,
|
||||
"songQueue" | "queueHistory" | "shuffleEnabled" | "repeatEnabled" | "revision"
|
||||
>
|
||||
|
||||
export type PlaybackProgress = {
|
||||
songId: Id<"songs"> | null
|
||||
progressSeconds: number
|
||||
}
|
||||
|
||||
export type PlaybackPatch = Partial<
|
||||
Pick<
|
||||
PlaybackState,
|
||||
"songQueue" | "queueHistory" | "shuffleEnabled" | "repeatEnabled"
|
||||
>
|
||||
> & {
|
||||
/** Saved position of the new `songQueue[0]`. */
|
||||
progressSeconds?: number
|
||||
}
|
||||
|
||||
const LEGACY_PLAYBACK_FIELDS = [
|
||||
"songQueue",
|
||||
"queueHistory",
|
||||
"currentSongProgress",
|
||||
"playbackRevision",
|
||||
"shuffleEnabled",
|
||||
"repeatEnabled",
|
||||
] as const
|
||||
|
||||
const EMPTY_STATE: PlaybackState = {
|
||||
songQueue: [],
|
||||
queueHistory: [],
|
||||
shuffleEnabled: false,
|
||||
repeatEnabled: "none",
|
||||
revision: 0,
|
||||
}
|
||||
|
||||
function legacyState(user: Doc<"users"> | null): PlaybackState {
|
||||
if (!user) {
|
||||
return EMPTY_STATE
|
||||
}
|
||||
return {
|
||||
songQueue: (user.songQueue ?? []).slice(0, MAX_QUEUE_LENGTH),
|
||||
queueHistory: (user.queueHistory ?? []).slice(-MAX_QUEUE_HISTORY),
|
||||
shuffleEnabled: user.shuffleEnabled ?? false,
|
||||
repeatEnabled: user.repeatEnabled ?? "none",
|
||||
revision: user.playbackRevision ?? 0,
|
||||
}
|
||||
}
|
||||
|
||||
function legacyProgress(user: Doc<"users"> | null): PlaybackProgress {
|
||||
return {
|
||||
songId: user?.songQueue?.[0] ?? null,
|
||||
progressSeconds: user?.currentSongProgress ?? 0,
|
||||
}
|
||||
}
|
||||
|
||||
export function hasLegacyPlayback(user: Doc<"users">) {
|
||||
return LEGACY_PLAYBACK_FIELDS.some((field) => user[field] !== undefined)
|
||||
}
|
||||
|
||||
function stateDoc(ctx: QueryCtx, userId: Id<"users">) {
|
||||
return ctx.db
|
||||
.query("playbackStates")
|
||||
.withIndex("by_user", (q) => q.eq("userId", userId))
|
||||
.unique()
|
||||
}
|
||||
|
||||
function progressDoc(ctx: QueryCtx, userId: Id<"users">) {
|
||||
return ctx.db
|
||||
.query("playbackProgress")
|
||||
.withIndex("by_user", (q) => q.eq("userId", userId))
|
||||
.unique()
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the queue without touching progress, so progress saves do not rerun
|
||||
* the caller. Users that have not been migrated yet fall back to `users`.
|
||||
*/
|
||||
export async function readPlaybackState(
|
||||
ctx: QueryCtx,
|
||||
userId: Id<"users">
|
||||
): Promise<PlaybackState> {
|
||||
const doc = await stateDoc(ctx, userId)
|
||||
if (doc) {
|
||||
return doc
|
||||
}
|
||||
return legacyState(await ctx.db.get(userId))
|
||||
}
|
||||
|
||||
export async function readPlaybackProgress(
|
||||
ctx: QueryCtx,
|
||||
userId: Id<"users">
|
||||
): Promise<PlaybackProgress> {
|
||||
const doc = await progressDoc(ctx, userId)
|
||||
if (doc) {
|
||||
return { songId: doc.songId ?? null, progressSeconds: doc.progressSeconds }
|
||||
}
|
||||
return legacyProgress(await ctx.db.get(userId))
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves a user's playback fields from `users` into `playbackStates` and
|
||||
* `playbackProgress`. Safe to call repeatedly.
|
||||
*/
|
||||
export async function migrateUserPlayback(
|
||||
ctx: MutationCtx,
|
||||
user: Doc<"users">
|
||||
) {
|
||||
const [existingState, existingProgress] = await Promise.all([
|
||||
stateDoc(ctx, user._id),
|
||||
progressDoc(ctx, user._id),
|
||||
])
|
||||
|
||||
let state = existingState
|
||||
if (!state) {
|
||||
const stateId = await ctx.db.insert("playbackStates", {
|
||||
userId: user._id,
|
||||
...legacyState(user),
|
||||
})
|
||||
state = (await ctx.db.get(stateId))!
|
||||
}
|
||||
if (!existingProgress) {
|
||||
const progress = legacyProgress(user)
|
||||
await ctx.db.insert("playbackProgress", {
|
||||
userId: user._id,
|
||||
progressSeconds: progress.progressSeconds,
|
||||
...(progress.songId ? { songId: progress.songId } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
if (hasLegacyPlayback(user)) {
|
||||
await ctx.db.patch(user._id, {
|
||||
songQueue: undefined,
|
||||
queueHistory: undefined,
|
||||
currentSongProgress: undefined,
|
||||
playbackRevision: undefined,
|
||||
shuffleEnabled: undefined,
|
||||
repeatEnabled: undefined,
|
||||
})
|
||||
}
|
||||
|
||||
return state
|
||||
}
|
||||
|
||||
/** Loads the queue in a mutation, migrating the user first if needed. */
|
||||
export async function loadPlaybackForWrite(
|
||||
ctx: MutationCtx,
|
||||
userId: Id<"users">
|
||||
) {
|
||||
const doc = await stateDoc(ctx, userId)
|
||||
if (doc) {
|
||||
return doc
|
||||
}
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
return null
|
||||
}
|
||||
return await migrateUserPlayback(ctx, user)
|
||||
}
|
||||
|
||||
/** Applies `patch`, bumps the revision, and returns the new revision. */
|
||||
export async function writePlayback(
|
||||
ctx: MutationCtx,
|
||||
userId: Id<"users">,
|
||||
patch: PlaybackPatch
|
||||
): Promise<number> {
|
||||
const doc = await loadPlaybackForWrite(ctx, userId)
|
||||
if (!doc) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
const { progressSeconds, ...fields } = patch
|
||||
const revision = doc.revision + 1
|
||||
const songQueue = fields.songQueue?.slice(0, MAX_QUEUE_LENGTH)
|
||||
const queueHistory = fields.queueHistory?.slice(-MAX_QUEUE_HISTORY)
|
||||
await ctx.db.patch(doc._id, {
|
||||
...fields,
|
||||
...(songQueue ? { songQueue } : {}),
|
||||
...(queueHistory ? { queueHistory } : {}),
|
||||
revision,
|
||||
})
|
||||
|
||||
if (progressSeconds !== undefined) {
|
||||
await writeProgress(ctx, userId, {
|
||||
songId: (songQueue ?? doc.songQueue)[0] ?? null,
|
||||
progressSeconds,
|
||||
})
|
||||
}
|
||||
return revision
|
||||
}
|
||||
|
||||
export async function writeProgress(
|
||||
ctx: MutationCtx,
|
||||
userId: Id<"users">,
|
||||
progress: PlaybackProgress
|
||||
) {
|
||||
const value = {
|
||||
songId: progress.songId ?? undefined,
|
||||
progressSeconds: Math.max(0, Math.floor(progress.progressSeconds)),
|
||||
}
|
||||
const doc = await progressDoc(ctx, userId)
|
||||
if (!doc) {
|
||||
await ctx.db.insert("playbackProgress", { userId, ...value })
|
||||
} else if (
|
||||
doc.songId !== value.songId ||
|
||||
doc.progressSeconds !== value.progressSeconds
|
||||
) {
|
||||
await ctx.db.patch(doc._id, value)
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteUserPlayback(
|
||||
ctx: MutationCtx,
|
||||
userId: Id<"users">
|
||||
) {
|
||||
const [state, progress] = await Promise.all([
|
||||
stateDoc(ctx, userId),
|
||||
progressDoc(ctx, userId),
|
||||
])
|
||||
if (state) {
|
||||
await ctx.db.delete(state._id)
|
||||
}
|
||||
if (progress) {
|
||||
await ctx.db.delete(progress._id)
|
||||
}
|
||||
}
|
||||
@@ -10,11 +10,7 @@ import type {
|
||||
PlaylistSummary,
|
||||
SidebarPlaylists,
|
||||
} from "./library"
|
||||
import {
|
||||
browseSongsFromIds,
|
||||
compareAlbumSongs,
|
||||
requireSignedIn,
|
||||
} from "./library"
|
||||
import { browseSongsFromIds, compareAlbumSongs } from "./library"
|
||||
|
||||
function toPlaylistSummary(
|
||||
playlist: Doc<"playlists">,
|
||||
@@ -112,7 +108,6 @@ async function browsePlaylistSummaryHandler(
|
||||
}
|
||||
}
|
||||
|
||||
/** Public: shared /playlist links render this without a session. */
|
||||
export const browsePlaylistDetail = query({
|
||||
args: { id: v.id("playlists") },
|
||||
handler: async (ctx, args): Promise<BrowsePlaylistDetail | null> => {
|
||||
@@ -272,7 +267,6 @@ export const listAllPlaylists = query({
|
||||
export const getAlbumSongIds = query({
|
||||
args: { albumId: v.id("albums") },
|
||||
handler: async (ctx, args) => {
|
||||
await requireSignedIn(ctx)
|
||||
const songs = await ctx.db
|
||||
.query("songs")
|
||||
.withIndex("by_album", (q) => q.eq("album", args.albumId))
|
||||
@@ -285,7 +279,6 @@ export const getAlbumSongIds = query({
|
||||
export const getArtistSongIds = query({
|
||||
args: { artistId: v.id("artists") },
|
||||
handler: async (ctx, args) => {
|
||||
await requireSignedIn(ctx)
|
||||
const songs = await ctx.db
|
||||
.query("songs")
|
||||
.withIndex("by_artist", (q) => q.eq("albumArtist", args.artistId))
|
||||
@@ -297,7 +290,6 @@ export const getArtistSongIds = query({
|
||||
export const getOrderedArtistSongIds = query({
|
||||
args: { artistId: v.id("artists") },
|
||||
handler: async (ctx, args) => {
|
||||
await requireSignedIn(ctx)
|
||||
const songs = await ctx.db
|
||||
.query("songs")
|
||||
.withIndex("by_artist", (q) => q.eq("albumArtist", args.artistId))
|
||||
@@ -328,7 +320,6 @@ export const getOrderedArtistSongIds = query({
|
||||
export const getPlaylistSongIds = query({
|
||||
args: { playlistId: v.id("playlists") },
|
||||
handler: async (ctx, args) => {
|
||||
await requireSignedIn(ctx)
|
||||
const playlist = await ctx.db.get("playlists", args.playlistId)
|
||||
return playlist?.songs ?? []
|
||||
},
|
||||
|
||||
@@ -2,19 +2,11 @@ import { defineSchema, defineTable } from "convex/server"
|
||||
import { v } from "convex/values"
|
||||
import { authTables } from "@convex-dev/auth/server"
|
||||
|
||||
const repeatModeValidator = v.union(
|
||||
v.literal("always"),
|
||||
v.literal("once"),
|
||||
v.literal("none")
|
||||
)
|
||||
|
||||
export default defineSchema({
|
||||
...authTables,
|
||||
users: defineTable({
|
||||
name: v.string(),
|
||||
/** Legacy base64 data URL; `migrations.migrateUsers` moves it to storage. */
|
||||
image: v.optional(v.string()),
|
||||
imageStorageId: v.optional(v.id("_storage")),
|
||||
email: v.string(),
|
||||
isAdmin: v.optional(v.boolean()),
|
||||
playbackQuality: v.optional(
|
||||
@@ -30,34 +22,18 @@ export default defineSchema({
|
||||
favoriteArtists: v.optional(v.array(v.id("artists"))),
|
||||
favoriteAlbums: v.optional(v.array(v.id("albums"))),
|
||||
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")))
|
||||
),
|
||||
// Legacy playback fields, now in `playbackStates` and `playbackProgress`.
|
||||
// `migrations.migrateUsers` clears them; drop them once every deployment
|
||||
// has run it.
|
||||
songQueue: v.optional(v.array(v.id("songs"))),
|
||||
queueHistory: v.optional(v.array(v.id("songs"))),
|
||||
currentSongProgress: v.optional(v.number()),
|
||||
playbackRevision: v.optional(v.number()),
|
||||
shuffleEnabled: v.optional(v.boolean()),
|
||||
repeatEnabled: v.optional(repeatModeValidator),
|
||||
repeatEnabled: v.optional(
|
||||
v.union(v.literal("always"), v.literal("once"), v.literal("none"))
|
||||
),
|
||||
}).index("email", ["email"]),
|
||||
playbackStates: defineTable({
|
||||
userId: v.id("users"),
|
||||
songQueue: v.array(v.id("songs")),
|
||||
queueHistory: v.array(v.id("songs")),
|
||||
shuffleEnabled: v.boolean(),
|
||||
repeatEnabled: repeatModeValidator,
|
||||
revision: v.number(),
|
||||
}).index("by_user", ["userId"]),
|
||||
// Saved every few seconds during playback, so it lives apart from the queue
|
||||
// to keep those writes from rerunning queue queries.
|
||||
playbackProgress: defineTable({
|
||||
userId: v.id("users"),
|
||||
songId: v.optional(v.id("songs")),
|
||||
progressSeconds: v.number(),
|
||||
}).index("by_user", ["userId"]),
|
||||
authVerifiers: defineTable({
|
||||
sessionId: v.optional(v.id("authSessions")),
|
||||
signature: v.optional(v.string()),
|
||||
|
||||
@@ -5,18 +5,9 @@ import {
|
||||
} from "@convex-dev/auth/server"
|
||||
import { ConvexError, v } from "convex/values"
|
||||
import { api, internal } from "./_generated/api"
|
||||
import {
|
||||
action,
|
||||
internalAction,
|
||||
internalMutation,
|
||||
internalQuery,
|
||||
mutation,
|
||||
query,
|
||||
} from "./_generated/server"
|
||||
import type { Doc, Id } from "./_generated/dataModel"
|
||||
import { action, internalQuery, mutation, query } from "./_generated/server"
|
||||
import type { Id } from "./_generated/dataModel"
|
||||
import type { ActionCtx, MutationCtx } from "./_generated/server"
|
||||
import { MAX_PROFILE_IMAGE_BYTES } from "./limits"
|
||||
import { deleteUserPlayback } from "./playbackState"
|
||||
|
||||
const playbackQualityValidator = v.union(
|
||||
v.literal("low"),
|
||||
@@ -187,114 +178,18 @@ export const listUsers = query({
|
||||
},
|
||||
})
|
||||
|
||||
const DATA_URL_PATTERN = /^data:(image\/[\w.+-]+);base64,([A-Za-z0-9+/=]+)$/
|
||||
|
||||
/** Splits an image data URL, rejecting anything over the size cap. */
|
||||
function parseImageDataUrl(image: string) {
|
||||
const match = DATA_URL_PATTERN.exec(image)
|
||||
if (!match) {
|
||||
throw new ConvexError("Profile photo must be an image")
|
||||
}
|
||||
const [, contentType, base64] = match
|
||||
if (Math.floor((base64.length * 3) / 4) > MAX_PROFILE_IMAGE_BYTES) {
|
||||
throw new ConvexError(
|
||||
`Profile photo must be ${MAX_PROFILE_IMAGE_BYTES / 1024 / 1024} MB or smaller`
|
||||
)
|
||||
}
|
||||
return { contentType, base64 }
|
||||
}
|
||||
|
||||
/**
|
||||
* Path clients load the avatar from. The web server proxies it from Convex
|
||||
* storage, since the backend's storage URLs are not reachable from browsers
|
||||
* in every deployment. Legacy data URLs are returned as is until migrated.
|
||||
*/
|
||||
export function profileImagePath(user: Doc<"users">) {
|
||||
if (user.imageStorageId) {
|
||||
return `/api/user/${user._id}/avatar?v=${user.imageStorageId}`
|
||||
}
|
||||
return user.image
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes a data URL so existing clients keep working. The image is moved into
|
||||
* file storage in the background; `currentUser` updates once it lands.
|
||||
*/
|
||||
export const updateProfileImage = mutation({
|
||||
args: {
|
||||
image: v.union(v.string(), v.null()),
|
||||
},
|
||||
handler: async (ctx, { image }) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
if (image === null) {
|
||||
await setProfileImage(ctx, userId, null)
|
||||
return
|
||||
}
|
||||
parseImageDataUrl(image)
|
||||
await ctx.scheduler.runAfter(0, internal.users.storeProfileImage, {
|
||||
userId,
|
||||
image,
|
||||
await ctx.db.patch(userId, {
|
||||
image: image === null ? undefined : image,
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
/** Decodes a data URL into file storage and points the user at it. */
|
||||
export const storeProfileImage = internalAction({
|
||||
args: { userId: v.id("users"), image: v.string() },
|
||||
handler: async (ctx, { userId, image }) => {
|
||||
const { contentType, base64 } = parseImageDataUrl(image)
|
||||
const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0))
|
||||
const storageId = await ctx.storage.store(
|
||||
new Blob([bytes], { type: contentType })
|
||||
)
|
||||
await ctx.runMutation(internal.users.attachProfileImage, {
|
||||
userId,
|
||||
storageId,
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export const attachProfileImage = internalMutation({
|
||||
args: { userId: v.id("users"), storageId: v.id("_storage") },
|
||||
handler: async (ctx, { userId, storageId }) => {
|
||||
await setProfileImage(ctx, userId, storageId)
|
||||
},
|
||||
})
|
||||
|
||||
/** Replaces the avatar, deleting the previous file. Clears it for `null`. */
|
||||
async function setProfileImage(
|
||||
ctx: MutationCtx,
|
||||
userId: Id<"users">,
|
||||
storageId: Id<"_storage"> | null
|
||||
) {
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
if (storageId) {
|
||||
await ctx.storage.delete(storageId)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (user.imageStorageId && user.imageStorageId !== storageId) {
|
||||
await ctx.storage.delete(user.imageStorageId)
|
||||
}
|
||||
await ctx.db.patch(userId, {
|
||||
image: undefined,
|
||||
imageStorageId: storageId ?? undefined,
|
||||
})
|
||||
}
|
||||
|
||||
/** Storage URL behind `profileImagePath`, for the web server's proxy route. */
|
||||
export const getProfileImageUrl = query({
|
||||
args: { userId: v.id("users") },
|
||||
handler: async (ctx, { userId }) => {
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user?.imageStorageId) {
|
||||
return null
|
||||
}
|
||||
return await ctx.storage.getUrl(user.imageStorageId)
|
||||
},
|
||||
})
|
||||
|
||||
export const updateProfileName = mutation({
|
||||
args: { name: v.string() },
|
||||
handler: async (ctx, { name }) => {
|
||||
@@ -399,8 +294,6 @@ export const deleteUser = mutation({
|
||||
throw new ConvexError("You cannot delete your own account")
|
||||
}
|
||||
await deleteOwnedPlaylists(ctx, userId)
|
||||
await deleteUserPlayback(ctx, userId)
|
||||
await setProfileImage(ctx, userId, null)
|
||||
await deleteUserAuthData(ctx, userId)
|
||||
},
|
||||
})
|
||||
|
||||
Generated
-20
@@ -179,9 +179,6 @@ importers:
|
||||
'@otunes/convex':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/convex
|
||||
'@tanstack/react-virtual':
|
||||
specifier: ^3.14.26
|
||||
version: 3.14.26(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||
class-variance-authority:
|
||||
specifier: ^0.7.1
|
||||
version: 0.7.1
|
||||
@@ -2660,15 +2657,6 @@ packages:
|
||||
'@tailwindcss/postcss@4.3.2':
|
||||
resolution: {integrity: sha512-rjVWYCa7Ngbi5AarT6k8TkxUG3Wl1QKzHdIZVsjZSzf36Jmo2IKZt/NHRAwly8oDkbBOH0YTu+CHuf9jPxMc+g==}
|
||||
|
||||
'@tanstack/react-virtual@3.14.26':
|
||||
resolution: {integrity: sha512-HUDlfsrYH6ko5xH56L62Mcl/uzT+AGVNMHFuDNqDJMdZWc1AQa2oeVKNUvZ/RWBZQ4TYtyQerFrNvLnp39h65A==}
|
||||
peerDependencies:
|
||||
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
|
||||
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
|
||||
|
||||
'@tanstack/virtual-core@3.19.11':
|
||||
resolution: {integrity: sha512-/5iHb0RHBvj8Di59FDs4ESNm45jls33aZAi4zccVXZjc/6ZvwQP6nzEYeT6weXjTf9E6/vrp2JhYWRyO+ZP13A==}
|
||||
|
||||
'@tokenizer/inflate@0.4.1':
|
||||
resolution: {integrity: sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==}
|
||||
engines: {node: '>=18'}
|
||||
@@ -9476,14 +9464,6 @@ snapshots:
|
||||
postcss: 8.5.16
|
||||
tailwindcss: 4.3.2
|
||||
|
||||
'@tanstack/react-virtual@3.14.26(react-dom@19.3.1(react@19.3.1))(react@19.3.1)':
|
||||
dependencies:
|
||||
'@tanstack/virtual-core': 3.19.11
|
||||
react: 19.3.1
|
||||
react-dom: 19.3.1(react@19.3.1)
|
||||
|
||||
'@tanstack/virtual-core@3.19.11': {}
|
||||
|
||||
'@tokenizer/inflate@0.4.1':
|
||||
dependencies:
|
||||
debug: 4.4.3
|
||||
|
||||
Reference in new issue
Block a user