Compare commits

..
75 changed files with 496 additions and 3153 deletions

No files matched your search

+1 -6
View File
@@ -41,9 +41,4 @@ apps/web/next-env.d.ts
/.convex
/.cursor
/database
docker-compose.yml
**/credentials.json
**/credentials/
**/*.ipa
**/*.apk
docker-compose.yml
+2 -2
View File
@@ -121,7 +121,7 @@ RUN curl -fsSL -o ffmpeg.tar.xz "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VER
# Decoders cover the library formats (FLAC, ALAC/AAC in m4a, MP3, Opus,
# Vorbis, WavPack, WMA, E-AC-3/TrueHD for Atmos). Encoders are only the two
# the app writes: AAC (HLS, ADTS and .m4a downloads) and FLAC.
# the app writes: AAC (HLS and ADTS) and FLAC.
RUN ./configure \
--prefix=/opt/ffmpeg \
--disable-shared \
@@ -138,7 +138,7 @@ RUN ./configure \
--enable-demuxer=aac,ac3,aiff,ape,asf,au,caf,dsf,flac,matroska,mov,mp3,ogg,wav,wv \
--enable-decoder=aac,aac_latm,ac3,alac,ape,dsd_lsbf,dsd_msbf,eac3,flac,mlp,mp3,opus,pcm_f32le,pcm_s16be,pcm_s16le,pcm_s24be,pcm_s24le,pcm_s32be,pcm_s32le,pcm_u8,truehd,vorbis,wavpack,wmav1,wmav2 \
--enable-encoder=aac,flac \
--enable-muxer=adts,flac,hls,ipod,mpegts \
--enable-muxer=adts,flac,hls,mpegts \
--enable-parser=aac,aac_latm,ac3,flac,mpegaudio,opus,vorbis \
--enable-bsf=aac_adtstoasc \
--enable-filter=aresample,aformat \
-7
View File
@@ -32,13 +32,6 @@ export default ({ config }: ConfigContext): ExpoConfig => {
...config,
plugins: [
...(config.plugins ?? []),
[
"react-native-continued-task",
{
// Matches TASK_PREFIX in hooks/use-background-downloads.ts.
identifierPrefixes: [`${bundleIdentifier}.downloads`],
},
],
...(process.env.MAC_CATALYST === "1"
? ["./plugins/with-mac-catalyst"]
: []),
@@ -1,6 +1,5 @@
import { Stack } from "expo-router"
import { TabStackContext } from "@/lib/app-navigation"
import { renderTabScreenContent } from "@/components/tab-screen-content"
import { useStackScreenOptions, tabStackScreenTitles } from "@/lib/navigation"
import { tabletSections, TabletSectionContext } from "@/lib/tablet-navigation"
@@ -11,18 +10,16 @@ export default function TabletSectionLayout({ segment }: { segment: string }) {
return (
<TabletSectionContext value={section}>
<TabStackContext value={section?.group}>
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...options,
title:
route.name === "index"
? section?.title
: tabStackScreenTitles[route.name],
})}
/>
</TabStackContext>
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...options,
title:
route.name === "index"
? section?.title
: tabStackScreenTitles[route.name],
})}
/>
</TabletSectionContext>
)
}
+8 -8
View File
@@ -193,14 +193,6 @@ function TabsContent() {
<NativeTabs.Trigger.Icon sf="music.note" />
<NativeTabs.Trigger.Label>Songs</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger
name="(downloads)"
hidden={!(Platform.OS === "ios" && Platform.isPad)}
disableTransparentOnScrollEdge
>
<NativeTabs.Trigger.Icon sf="arrow.down.circle" />
<NativeTabs.Trigger.Label>Downloads</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger
name="(playlists)"
hidden={!(Platform.OS === "ios" && Platform.isPad)}
@@ -225,6 +217,14 @@ function TabsContent() {
<NativeTabs.Trigger.Icon sf="clock" />
<NativeTabs.Trigger.Label>Recently Played</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger
name="(downloads)"
hidden={!(Platform.OS === "ios" && Platform.isPad)}
disableTransparentOnScrollEdge
>
<NativeTabs.Trigger.Icon sf="arrow.down.circle" />
<NativeTabs.Trigger.Label>Downloads</NativeTabs.Trigger.Label>
</NativeTabs.Trigger>
</NativeTabs>
{!keyboardVisible ? <AndroidMiniPlayer /> : null}
{tabletLayout ? <TabletMiniPlayer /> : null}
+19 -22
View File
@@ -1,7 +1,6 @@
import { renderTabScreenContent } from "@/components/tab-screen-content"
import { Stack } from "expo-router"
import { TabStackContext } from "@/lib/app-navigation"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
@@ -13,26 +12,24 @@ export default function HomeLayout() {
const baseOptions = useStackScreenOptions({ title: "Home" })
return (
<TabStackContext value="home">
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Home",
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
})}
/>
</TabStackContext>
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Home",
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
})}
/>
)
}
@@ -23,9 +23,9 @@ import {
} from "@/components/collection-list"
import { AudioFormatBadge } from "@/components/audio-format-badge"
import {
CollectionDownloadButton,
DownloadHeaderButton,
DownloadedQuality,
} from "@/components/collection-download-button"
} from "@/components/download-header-button"
import { useOpenedFromDownloads } from "@/lib/downloads-navigation"
import { downloadsQueueOrigin } from "@otunes/convex/download-quality"
import {
@@ -81,7 +81,8 @@ export default function AlbumScreen() {
const playOrigin = fromDownloads
? downloadsQueueOrigin(`album:${id}`)
: `album:${id}`
const { isSongFavorite } = useFavorites()
const { isAlbumFavorite, toggleAlbumFavorite, isSongFavorite } =
useFavorites()
const {
handleAlbumDetailAction,
handleAlbumTrackAction,
@@ -204,6 +205,7 @@ export default function AlbumScreen() {
}
const metadata = formatMetadata(album.genre, album.year)
const favorited = isAlbumFavorite(album.id)
return (
<>
@@ -224,35 +226,41 @@ export default function AlbumScreen() {
}
: {}),
headerRight: () => (
<MediaActionMenu
stationArtistId={album.artist.id}
selectedCount={album.tracks.length}
favorited={isAlbumFav(album.id)}
downloaded={albumDownloaded}
share={{ type: "album", albumId: album.id, title: album.title }}
onAction={(action) => {
if (action === "download") {
void requestDownload(downloadTarget)
} else if (action === "remove-download") {
void removeDownload(downloadTarget)
} else {
void handleAlbumDetailAction(
album.id as Id<"albums">,
songIds,
action,
album.artist.id as Id<"artists">
)
}
}}
>
<Pressable hitSlop={8}>
<Ionicons
name="ellipsis-horizontal"
size={22}
color={colors.foreground}
/>
</Pressable>
</MediaActionMenu>
<View style={styles.headerActions}>
<DownloadHeaderButton
target={downloadTarget}
color={colors.foreground}
/>
<MediaActionMenu
stationArtistId={album.artist.id}
selectedCount={album.tracks.length}
favorited={isAlbumFav(album.id)}
downloaded={albumDownloaded}
share={{ type: "album", albumId: album.id, title: album.title }}
onAction={(action) => {
if (action === "download") {
void requestDownload(downloadTarget)
} else if (action === "remove-download") {
void removeDownload(downloadTarget)
} else {
void handleAlbumDetailAction(
album.id as Id<"albums">,
songIds,
action,
album.artist.id as Id<"artists">
)
}
}}
>
<Pressable hitSlop={8}>
<Ionicons
name="ellipsis-horizontal"
size={22}
color={colors.foreground}
/>
</Pressable>
</MediaActionMenu>
</View>
),
}}
/>
@@ -299,6 +307,34 @@ export default function AlbumScreen() {
heroLayout.landscape && { flexDirection: "row-reverse" },
]}
>
<Pressable
onPress={() => void toggleAlbumFavorite(album.id)}
hitSlop={8}
style={[
styles.iconAction,
{ backgroundColor: palette.surface },
]}
>
<Ionicons
name={favorited ? "star" : "star-outline"}
size={24}
color={favorited ? palette.accent : palette.foreground}
/>
</Pressable>
<Button
title="Play"
icon="play"
onPress={() =>
void (fromDownloads
? playInOrder(songIds, playOrigin)
: playAlbum(album.id, songIds))
}
style={styles.playButton}
tint={{
background: palette.accent,
foreground: palette.accentForeground,
}}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
@@ -319,28 +355,6 @@ export default function AlbumScreen() {
color={palette.foreground}
/>
</Pressable>
<Button
title="Play"
icon="play"
onPress={() =>
void (fromDownloads
? playInOrder(songIds, playOrigin)
: playAlbum(album.id, songIds))
}
style={styles.playButton}
tint={{
background: palette.accent,
foreground: palette.accentForeground,
}}
/>
<CollectionDownloadButton
target={downloadTarget}
color={palette.foreground}
style={[
styles.iconAction,
{ backgroundColor: palette.surface },
]}
/>
</View>
}
>
@@ -590,6 +604,7 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
const styles = StyleSheet.create({
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
headerActions: { flexDirection: "row", alignItems: "center", gap: 16 },
cover: {
width: 220,
height: 220,
@@ -105,21 +105,21 @@ export default function OtherDownloadsScreen() {
ListHeaderComponent={
songs.length > 0 ? (
<View style={styles.actions}>
<Button
title="Play"
icon="play"
onPress={() => void playInOrder(playableIds, PLAY_ORIGIN)}
style={styles.play}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={() => void playShuffled(playableIds, PLAY_ORIGIN)}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
style={[styles.shuffle, { backgroundColor: colors.card }]}
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
<Button
title="Play"
icon="play"
onPress={() => void playInOrder(playableIds, PLAY_ORIGIN)}
style={styles.playButton}
/>
</View>
) : undefined
}
@@ -137,15 +137,14 @@ const styles = StyleSheet.create({
actions: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: spacing.sm,
padding: spacing.lg,
},
playButton: { borderRadius: 999, minWidth: 160 },
iconAction: {
width: 44,
height: 44,
borderRadius: 22,
play: { flex: 1 },
shuffle: {
width: 48,
height: 48,
borderRadius: 24,
alignItems: "center",
justifyContent: "center",
},
@@ -45,10 +45,9 @@ import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset, SongListRow } from "@/components/player"
import {
CollectionDownloadButton,
type CollectionDownloadTarget,
DownloadHeaderButton,
DownloadedQuality,
} from "@/components/collection-download-button"
} from "@/components/download-header-button"
import { useOpenedFromDownloads } from "@/lib/downloads-navigation"
import { downloadsQueueOrigin } from "@otunes/convex/download-quality"
import type { CollectionRef } from "@otunes/convex/client/download-queue"
@@ -350,26 +349,32 @@ function PlaylistContent({
}
: {}),
headerRight: () => (
<MediaActionMenu
selectedCount={songIds.length}
playlistLabel={PLAYLIST_LABEL}
downloaded={playlistDownloaded}
share={{
type: "playlist",
playlistId: playlistId ?? "favorites",
title: playlist?.title ?? "oTunes",
}}
includeActions={canEdit ? OWNER_MENU_ACTIONS : undefined}
onAction={handlePlaylistMenuAction}
>
<Pressable hitSlop={8}>
<Ionicons
name="ellipsis-horizontal"
size={22}
color={colors.foreground}
/>
</Pressable>
</MediaActionMenu>
<View style={styles.headerActions}>
<DownloadHeaderButton
target={downloadTarget}
color={colors.foreground}
/>
<MediaActionMenu
selectedCount={songIds.length}
playlistLabel={PLAYLIST_LABEL}
downloaded={playlistDownloaded}
share={{
type: "playlist",
playlistId: playlistId ?? "favorites",
title: playlist?.title ?? "oTunes",
}}
includeActions={canEdit ? OWNER_MENU_ACTIONS : undefined}
onAction={handlePlaylistMenuAction}
>
<Pressable hitSlop={8}>
<Ionicons
name="ellipsis-horizontal"
size={22}
color={colors.foreground}
/>
</Pressable>
</MediaActionMenu>
</View>
),
}
}, [
@@ -460,7 +465,7 @@ function PlaylistContent({
isSubscribed={isSubscribed}
showSubscribe={!playlist.isOwner && playlistId !== null}
onSubscribeToggle={handleSubscribeToggle}
downloadTarget={downloadTarget}
downloadRef={downloadRef}
onPlay={handlePlay}
onShuffle={handleShuffle}
/>
@@ -571,11 +576,11 @@ const PlaylistHero = memo(function PlaylistHero({
isSubscribed,
showSubscribe = false,
onSubscribeToggle,
downloadTarget,
downloadRef,
onPlay,
onShuffle,
}: {
downloadTarget: CollectionDownloadTarget
downloadRef: CollectionRef
entityId: string
coverUri: string
hasCover: boolean
@@ -643,15 +648,6 @@ const PlaylistHero = memo(function PlaylistHero({
/>
</Pressable>
) : null}
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={onShuffle}
style={[styles.iconAction, { backgroundColor: palette.surface }]}
>
<Ionicons name="shuffle" size={24} color={palette.foreground} />
</Pressable>
<Button
title="Play"
icon="play"
@@ -662,11 +658,15 @@ const PlaylistHero = memo(function PlaylistHero({
foreground: palette.accentForeground,
}}
/>
<CollectionDownloadButton
target={downloadTarget}
color={palette.foreground}
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
hitSlop={8}
onPress={onShuffle}
style={[styles.iconAction, { backgroundColor: palette.surface }]}
/>
>
<Ionicons name="shuffle" size={24} color={palette.foreground} />
</Pressable>
</View>
}
>
@@ -688,7 +688,7 @@ const PlaylistHero = memo(function PlaylistHero({
{ownerName}
</Text>
<DownloadedQuality
collection={downloadTarget}
collection={downloadRef}
color={palette.secondaryForeground}
backgroundColor={palette.background}
/>
@@ -701,6 +701,7 @@ const PlaylistHero = memo(function PlaylistHero({
const styles = StyleSheet.create({
emptyResults: { padding: spacing.lg, textAlign: "center" },
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
headerActions: { flexDirection: "row", alignItems: "center", gap: 16 },
listContent: { paddingBottom: contentBottomInset },
cover: {
width: 200,
@@ -17,10 +17,9 @@ import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset, SongListRow } from "@/components/player"
import {
CollectionDownloadButton,
type CollectionDownloadTarget,
DownloadHeaderButton,
DownloadedQuality,
} from "@/components/collection-download-button"
} from "@/components/download-header-button"
import { useOpenedFromDownloads } from "@/lib/downloads-navigation"
import { downloadsQueueOrigin } from "@otunes/convex/download-quality"
import { FAVORITES_DOWNLOAD_ID } from "@/contexts/downloads"
@@ -54,13 +53,22 @@ export default function FavoritesScreen() {
const playOrigin = fromDownloads
? downloadsQueueOrigin("playlist:favorites")
: undefined
const downloadTarget = useMemo(
const screenOptions = useMemo(
() => ({
...DOWNLOAD_REF,
title: favorites?.title ?? "Favorites",
songIds,
...SCREEN_OPTIONS,
headerRight: () => (
<DownloadHeaderButton
target={{
kind: "playlist",
id: FAVORITES_DOWNLOAD_ID,
title: favorites?.title ?? "Favorites",
songIds,
}}
color={colors.foreground}
/>
),
}),
[favorites?.title, songIds]
[colors.foreground, favorites?.title, songIds]
)
const { filteredSongs, onQueryChange, onSearchSubmit } =
usePlaylistSearch(songs)
@@ -126,7 +134,7 @@ export default function FavoritesScreen() {
return (
<>
<Stack.Screen options={SCREEN_OPTIONS} />
<Stack.Screen options={screenOptions} />
<PlaylistSearchBar
onQueryChange={onQueryChange}
onSearchSubmit={onSearchSubmit}
@@ -149,7 +157,6 @@ export default function FavoritesScreen() {
ListHeaderComponent={
<FavoritesHero
title={favorites.title}
downloadTarget={downloadTarget}
onPlay={handlePlay}
onShuffle={handleShuffle}
/>
@@ -165,12 +172,10 @@ function songKey(song: BrowseSong) {
const FavoritesHero = memo(function FavoritesHero({
title,
downloadTarget,
onPlay,
onShuffle,
}: {
title: string
downloadTarget: CollectionDownloadTarget
onPlay: () => void
onShuffle: () => void
}) {
@@ -197,6 +202,12 @@ const FavoritesHero = memo(function FavoritesHero({
backgroundColor={colors.background}
/>
<View style={styles.actions}>
<Button
title="Play"
icon="play"
onPress={onPlay}
style={styles.playButton}
/>
<Pressable
accessibilityRole="button"
accessibilityLabel="Shuffle"
@@ -206,17 +217,6 @@ const FavoritesHero = memo(function FavoritesHero({
>
<Ionicons name="shuffle" size={24} color={colors.foreground} />
</Pressable>
<Button
title="Play"
icon="play"
onPress={onPlay}
style={styles.playButton}
/>
<CollectionDownloadButton
target={downloadTarget}
color={colors.foreground}
style={[styles.iconAction, { backgroundColor: colors.muted }]}
/>
</View>
</View>
<CollectionDivider />
+6 -10
View File
@@ -1,8 +1,4 @@
import {
atmosEnabled,
deviceDownloadQualities,
dolbyAtmosSupported,
} from "@/lib/playback-capabilities"
import { atmosEnabled, dolbyAtmosSupported } from "@/lib/playback-capabilities"
import { Ionicons } from "@expo/vector-icons"
import { useAction, useMutation, useQuery } from "convex/react"
import { Image } from "expo-image"
@@ -29,6 +25,7 @@ import {
writeRememberedDownloadQuality,
} from "@/lib/downloads"
import {
DOWNLOAD_QUALITIES,
DOWNLOAD_QUALITY_DETAILS,
DOWNLOAD_QUALITY_LABELS,
formatBytes,
@@ -453,10 +450,9 @@ function QualitySection({ user }: { user: CurrentUser }) {
/** Shades of the text color, faintest for the smallest files. */
const QUALITY_OPACITY: Record<DownloadQuality, number> = {
low: 0.2,
medium: 0.35,
high: 0.5,
lossless: 0.75,
medium: 0.25,
high: 0.45,
lossless: 0.7,
atmos: 1,
}
@@ -511,7 +507,7 @@ function RememberedQualityCard() {
detail: string
}[] = [
{ value: null, label: "Ask every time", detail: "Choose when downloading" },
...deviceDownloadQualities.map((quality) => ({
...DOWNLOAD_QUALITIES.map((quality) => ({
value: quality,
label: DOWNLOAD_QUALITY_LABELS[quality],
detail: DOWNLOAD_QUALITY_DETAILS[quality],
@@ -2,7 +2,6 @@ import { useTabletLayout } from "@/hooks/use-tablet-layout"
import { renderTabScreenContent } from "@/components/tab-screen-content"
import { Stack } from "expo-router"
import { TabStackContext } from "@/lib/app-navigation"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
@@ -15,28 +14,26 @@ export default function LibraryLayout() {
const baseOptions = useStackScreenOptions({ title: "Library" })
return (
<TabStackContext value="library">
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...baseOptions,
title:
tabStackScreenTitles[route.name] ??
(tabletLayout ? "Recently Added" : "Library"),
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
})}
/>
</TabStackContext>
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...baseOptions,
title:
tabStackScreenTitles[route.name] ??
(tabletLayout ? "Recently Added" : "Library"),
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
})}
/>
)
}
@@ -24,17 +24,17 @@ const links = [
{ title: "Artists", href: "/browse/artists", icon: "mic.fill" as const },
{ title: "Albums", href: "/browse/albums", icon: "square.stack" as const },
{ title: "Songs", href: "/browse/songs", icon: "music.note" as const },
{
title: "Downloads",
href: "/downloads",
icon: "arrow.down.circle" as const,
},
{
title: "Recently Played",
href: "/recently-played",
icon: "clock" as const,
},
{ title: "Favorites", href: "/playlist/favorites", icon: "star" as const },
{
title: "Downloads",
href: "/downloads",
icon: "arrow.down.circle" as const,
},
]
function LibraryIcon({ name }: { name: (typeof links)[number]["icon"] }) {
+19 -22
View File
@@ -1,7 +1,6 @@
import { renderTabScreenContent } from "@/components/tab-screen-content"
import { Stack } from "expo-router"
import { TabStackContext } from "@/lib/app-navigation"
import { ProfileHeaderButton } from "@/components/profile-header-button"
import { tabStackScreenTitles, useStackScreenOptions } from "@/lib/navigation"
@@ -13,26 +12,24 @@ export default function SearchLayout() {
const baseOptions = useStackScreenOptions({ title: "Search" })
return (
<TabStackContext value="search">
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Search",
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
})}
/>
</TabStackContext>
<Stack
screenLayout={renderTabScreenContent}
screenOptions={({ route }) => ({
...baseOptions,
title: tabStackScreenTitles[route.name] ?? "Search",
headerRight:
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
unstable_headerRightItems:
route.name === "index"
? () => [
{
type: "custom",
element: <ProfileHeaderButton />,
hidesSharedBackground: true,
},
]
: undefined,
})}
/>
)
}
+15 -52
View File
@@ -1,8 +1,5 @@
import { useTabletLayout } from "@/hooks/use-tablet-layout"
import {
TabletNowPlaying,
type PlayerPanel,
} from "@/components/tablet-now-playing"
import { TabletNowPlaying } from "@/components/tablet-now-playing"
import { atmosEnabled } from "@/lib/playback-capabilities"
import { NavigationBar } from "expo-navigation-bar"
import { MusicEntityView } from "@/components/music-entity-view"
@@ -54,9 +51,7 @@ import { PlayerSymbol } from "@/components/player-symbol"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { LyricsView } from "@/components/lyrics-view"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { useLyrics } from "@/hooks/use-lyrics"
import { useCoverPalette } from "@/hooks/use-cover-palette"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { useSystemVolume } from "@/hooks/use-system-volume"
@@ -98,14 +93,8 @@ export default function PlayerScreen() {
queueSongIds,
} = usePlaybackQueue()
const { setIsPlaying, skipNext, skipPrevious } = usePlaybackActions()
const params = useLocalSearchParams<{ queue?: string; lyrics?: string }>()
// The queue or lyrics, shown in place of the artwork.
const [panel, setPanel] = useState<PlayerPanel | null>(
params.queue === "1" ? "queue" : params.lyrics === "1" ? "lyrics" : null
)
const showQueue = panel === "queue"
const showLyrics = panel === "lyrics"
const lyrics = useLyrics(currentSong?.id ?? null)
const { queue } = useLocalSearchParams<{ queue?: string }>()
const [showQueue, setShowQueue] = useState(queue === "1")
const [isDismissing, setIsDismissing] = useState(false)
const [stageHeight, setStageHeight] = useState(0)
const user = useCachedQuery(api.auth.currentUser)
@@ -198,8 +187,8 @@ export default function PlayerScreen() {
const handleGesture = useMemo(makeDismissGesture, [makeDismissGesture])
const controlsGesture = useMemo(makeDismissGesture, [makeDismissGesture])
const stageGesture = useMemo(
() => makeDismissGesture().enabled(panel === null),
[makeDismissGesture, panel]
() => makeDismissGesture().enabled(!showQueue),
[makeDismissGesture, showQueue]
)
const hasCover = currentSong ? currentSong.album.cover != null : false
@@ -254,9 +243,9 @@ export default function PlayerScreen() {
setIsPlaying(!isPlaying)
}
function togglePanel(next: PlayerPanel) {
function toggleQueue() {
void Haptics.selectionAsync()
setPanel((value) => (value === next ? null : next))
setShowQueue((value) => !value)
}
if (isTablet) {
@@ -267,9 +256,8 @@ export default function PlayerScreen() {
backgroundStyle={backgroundStyle}
dismissStyle={dismissStyle}
dismissGestures={{ handle: handleGesture, artwork: controlsGesture }}
panel={panel}
togglePanel={togglePanel}
lyrics={lyrics}
showQueue={showQueue}
toggleQueue={toggleQueue}
metadata={songMeta}
/>
</MusicEntityView>
@@ -334,20 +322,6 @@ export default function PlayerScreen() {
/>
</Animated.View>
) : null
) : showLyrics ? (
<Animated.View
key="lyrics"
entering={MODE_FADE_IN}
exiting={MODE_FADE_OUT}
style={[styles.fill, styles.artworkMode]}
>
{queueHeader}
<LyricsView
key={currentSong.id}
lyrics={lyrics}
colors={colors}
/>
</Animated.View>
) : (
<Animated.View
key="artwork"
@@ -435,29 +409,18 @@ export default function PlayerScreen() {
<View style={styles.footer}>
<Pressable
onPress={() => togglePanel("lyrics")}
disabled={!lyrics && !showLyrics}
hitSlop={8}
disabled
accessibilityRole="button"
accessibilityLabel={showLyrics ? "Hide lyrics" : "Show lyrics"}
accessibilityState={{
selected: showLyrics,
disabled: !lyrics && !showLyrics,
}}
style={[
styles.queueButton,
!lyrics && !showLyrics && styles.unavailable,
showLyrics && { backgroundColor: colors.selected },
]}
accessibilityLabel="Lyrics"
accessibilityState={{ disabled: true }}
style={[styles.queueButton, styles.unavailable]}
>
<PlayerSymbol
name="quote.bubble"
fallback={{ material: "lyrics" }}
size={27}
weight="semibold"
color={
showLyrics ? colors.selectedForeground : colors.foreground
}
color={colors.foreground}
/>
</Pressable>
<AudioOutputButton
@@ -465,7 +428,7 @@ export default function PlayerScreen() {
style={styles.queueButton}
/>
<Pressable
onPress={() => togglePanel("queue")}
onPress={toggleQueue}
hitSlop={8}
accessibilityRole="button"
accessibilityLabel={showQueue ? "Hide queue" : "Show queue"}
@@ -1,13 +1,5 @@
import { Ionicons } from "@expo/vector-icons"
import {
Alert,
Pressable,
StyleSheet,
Text,
View,
type StyleProp,
type ViewStyle,
} from "react-native"
import { Alert, Pressable, StyleSheet, Text, View } from "react-native"
import Svg, { Circle, Rect } from "react-native-svg"
import { AudioFormatBadge } from "@/components/audio-format-badge"
@@ -59,20 +51,13 @@ function ProgressRing({
)
}
export type CollectionDownloadTarget = Exclude<
DownloadTarget,
{ kind: "songs" }
>
/** Download, progress, and downloaded states for an album or playlist hero, beside Play. */
export function CollectionDownloadButton({
/** Download, progress, and downloaded states for an album or playlist header. */
export function DownloadHeaderButton({
target,
color,
style,
}: {
target: CollectionDownloadTarget
target: Exclude<DownloadTarget, { kind: "songs" }>
color: string
style?: StyleProp<ViewStyle>
}) {
const { queue, requestDownload, removeDownload } = useDownloads()
useDownloadsVersion()
@@ -111,7 +96,6 @@ export function CollectionDownloadButton({
}
disabled={target.songIds.length === 0}
onPress={handlePress}
style={style}
>
{inProgress && status ? (
<ProgressRing
@@ -120,8 +104,8 @@ export function CollectionDownloadButton({
/>
) : (
<Ionicons
name={done ? "checkmark" : "arrow-down"}
size={24}
name={done ? "checkmark-circle" : "arrow-down-circle-outline"}
size={SIZE + 2}
color={color}
/>
)}
-351
View File
@@ -1,351 +0,0 @@
import {
memo,
type ComponentType,
type ReactElement,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react"
import {
Pressable,
ScrollView,
StyleSheet,
Text,
View,
type ScrollViewInstance,
type ViewProps,
} from "react-native"
import MaskedViewClass from "@react-native-masked-view/masked-view"
import Animated, {
useAnimatedStyle,
type SharedValue,
} from "react-native-reanimated"
import {
usePlaybackActions,
usePlaybackProgress,
usePlaybackQueue,
} from "@/contexts/playback"
import { useLyricsTime, usePlaybackClock } from "@/hooks/use-lyrics"
import type { NowPlayingColors } from "@/lib/now-playing-colors"
import {
activeLineIndex,
type LyricLine,
type LyricWord,
type Lyrics,
} from "@otunes/convex/client/lyrics"
// The package's class typings predate React 19's; this is its documented API.
const MaskedView = MaskedViewClass as unknown as ComponentType<
ViewProps & { maskElement: ReactElement }
>
/** How long a manual scroll keeps the view from following the song. */
const MANUAL_SCROLL_HOLD_MS = 3000
/** Where the playing line sits, as a share of the view's height from the top. */
const ACTIVE_LINE_POSITION = 0.12
/** Blur radius by distance from the playing line; farther lines share the last. */
const LINE_BLUR = [0, 1, 2, 3]
/** Opacity of lines other than the one playing. */
const INACTIVE_LINE_OPACITY = 0.35
/** How long a line takes to brighten, dim, or change blur. */
const LINE_FADE_MS = 300
/**
* Lyrics in the player's own colors. Synced lines follow playback and seek
* when tapped; `null` lyrics show a short note instead.
*/
export function LyricsView({
lyrics,
colors,
fontSize = 30,
}: {
lyrics: Lyrics | null | undefined
colors: NowPlayingColors
fontSize?: number
}) {
if (lyrics === undefined) return null
if (lyrics === null) {
return (
<View style={styles.empty}>
<Text style={[styles.emptyText, { color: colors.secondaryForeground }]}>
No lyrics
</Text>
</View>
)
}
return <LyricsLines lyrics={lyrics} colors={colors} fontSize={fontSize} />
}
function LyricsLines({
lyrics,
colors,
fontSize,
}: {
lyrics: Lyrics
colors: NowPlayingColors
fontSize: number
}) {
const { currentTime } = usePlaybackProgress()
const { isPlaying } = usePlaybackQueue()
const { seekTo, setIsPlaying } = usePlaybackActions()
const time = useLyricsTime(lyrics, currentTime, isPlaying)
const clock = usePlaybackClock(currentTime, isPlaying)
const active = activeLineIndex(lyrics, time)
const synced = lyrics.synced !== "none"
const scrollRef = useRef<ScrollViewInstance>(null)
const lineOffsets = useRef<number[]>([])
const [height, setHeight] = useState(0)
// While the listener scrolls, lines stay sharp and the view stays put.
const [browsing, setBrowsing] = useState(false)
const browseTimer = useRef<ReturnType<typeof setTimeout>>(undefined)
useEffect(() => () => clearTimeout(browseTimer.current), [])
const scrollToLine = useCallback(
(index: number) => {
const y = lineOffsets.current[Math.max(index, 0)]
if (y === undefined || !synced || height === 0 || browsing) return
scrollRef.current?.scrollTo({
y: Math.max(0, y - height * ACTIVE_LINE_POSITION),
animated: true,
})
},
[height, synced, browsing]
)
useEffect(() => {
scrollToLine(active)
}, [active, scrollToLine])
const activeRef = useRef(active)
useEffect(() => {
activeRef.current = active
}, [active])
const handleLineLayout = useCallback(
(index: number, y: number) => {
lineOffsets.current[index] = y
// Opening mid-song: jump once the playing line has been measured.
if (index === Math.max(activeRef.current, 0)) scrollToLine(index)
},
[scrollToLine]
)
const playFrom = useCallback(
(seconds: number) => {
seekTo(seconds)
setIsPlaying(true)
clearTimeout(browseTimer.current)
setBrowsing(false)
},
[seekTo, setIsPlaying]
)
const releaseScroll = () => {
clearTimeout(browseTimer.current)
browseTimer.current = setTimeout(
() => setBrowsing(false),
MANUAL_SCROLL_HOLD_MS
)
}
const lineStyle = useMemo(
() => ({ fontSize, lineHeight: Math.round(fontSize * 1.18) }),
[fontSize]
)
return (
<ScrollView
ref={scrollRef}
style={styles.fill}
contentContainerStyle={{
paddingTop: height * ACTIVE_LINE_POSITION,
paddingBottom: height * 0.7,
}}
showsVerticalScrollIndicator={false}
onLayout={(event) => setHeight(event.nativeEvent.layout.height)}
onScrollBeginDrag={() => {
clearTimeout(browseTimer.current)
setBrowsing(true)
}}
// Hold from when the scroll settles, not when the finger lifted.
onScrollEndDrag={releaseScroll}
onMomentumScrollEnd={releaseScroll}
>
{lyrics.lines.map((line, index) =>
synced ? (
<SyncedLine
key={index}
index={index}
line={line}
distance={
browsing
? 0
: Math.min(Math.abs(index - active), LINE_BLUR.length - 1)
}
active={index === active}
clock={clock}
colors={colors}
textStyle={lineStyle}
onSelect={playFrom}
onLayoutY={handleLineLayout}
/>
) : (
<Text
key={index}
style={[
styles.plainLine,
{
color: colors.foreground,
fontSize: fontSize * 0.75,
lineHeight: Math.round(fontSize * 0.75 * 1.25),
},
line.text === "" && styles.stanzaGap,
]}
>
{line.text}
</Text>
)
)}
</ScrollView>
)
}
/**
* One timed line, laid out word by word whether or not it is playing, so it
* never re-wraps. It fades and blurs by its `distance` from the playing line,
* and only the playing line's words fill.
*/
const SyncedLine = memo(function SyncedLine({
index,
line,
distance,
active,
clock,
colors,
textStyle,
onSelect,
onLayoutY,
}: {
index: number
line: LyricLine
distance: number
active: boolean
clock: SharedValue<number>
colors: NowPlayingColors
textStyle: { fontSize: number; lineHeight: number }
onSelect: (seconds: number) => void
onLayoutY: (index: number, y: number) => void
}) {
const wordStyle = [styles.lineText, textStyle, { color: colors.foreground }]
return (
<Pressable
onPress={() => onSelect(line.start ?? 0)}
onLayout={(event) => onLayoutY(index, event.nativeEvent.layout.y)}
accessibilityRole="button"
accessibilityHint="Plays from this line"
style={styles.line}
>
<Animated.View
style={{
opacity: active ? 1 : INACTIVE_LINE_OPACITY,
filter: [{ blur: LINE_BLUR[distance] }],
transitionProperty: ["opacity", "filter"],
transitionDuration: LINE_FADE_MS,
}}
>
{line.words ? (
<View
style={[styles.words, { columnGap: textStyle.fontSize * 0.25 }]}
>
{line.words.map((word, wordIndex) =>
active ? (
<FilledWord
key={wordIndex}
word={word}
clock={clock}
colors={colors}
textStyle={textStyle}
/>
) : (
<Text key={wordIndex} style={wordStyle}>
{word.text.trim()}
</Text>
)
)}
</View>
) : (
<Text style={wordStyle}>{line.text}</Text>
)}
</Animated.View>
</Pressable>
)
})
/**
* A word of the playing line, filled from dim to bright with a soft edge as
* it is sung: a gradient 2.5 times its width slides under the word's
* shape, like the web panel's.
*/
function FilledWord({
word,
clock,
colors,
textStyle,
}: {
word: LyricWord
clock: SharedValue<number>
colors: NowPlayingColors
textStyle: { fontSize: number; lineHeight: number }
}) {
const text = word.text.trim()
const slide = useAnimatedStyle(() => {
const progress =
(clock.value - word.start) / Math.max(word.end - word.start, 0.05)
const sung = Math.min(Math.max(progress, 0), 1)
// -60% of the gradient's width shows its dim end; 0% its bright one.
return { transform: [{ translateX: `${-60 * (1 - sung)}%` }] }
})
return (
<MaskedView
maskElement={
<Text style={[styles.lineText, textStyle, styles.mask]}>{text}</Text>
}
>
{/* Sizes the word; the mask draws it. */}
<Text style={[styles.lineText, textStyle, styles.hidden]}>{text}</Text>
<Animated.View
style={[
styles.fillGradient,
{
backgroundImage: `linear-gradient(90deg, ${colors.foreground} 40%, ${colors.lyricsUnsung} 60%)`,
},
slide,
]}
/>
</MaskedView>
)
}
const styles = StyleSheet.create({
fill: { flex: 1 },
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
emptyText: { fontSize: 17, fontWeight: "600" },
line: { paddingVertical: 9 },
lineText: { fontWeight: "800" },
words: { flexDirection: "row", flexWrap: "wrap" },
mask: { color: "black" },
hidden: { opacity: 0 },
fillGradient: {
position: "absolute",
top: 0,
bottom: 0,
left: 0,
width: "250%",
},
plainLine: { fontWeight: "700", paddingVertical: 2 },
stanzaGap: { height: 18 },
})
+3 -12
View File
@@ -10,7 +10,7 @@ import {
} from "@/contexts/downloads"
import type { DownloadSource } from "@otunes/convex/client/download-queue"
import { useServerConfig } from "@/contexts/server-config"
import type { BrowseSong, SearchSong } from "@otunes/convex/types"
import type { BrowseSong } from "@otunes/convex/types"
import type { CoverPalette } from "@/lib/cover-palette"
import { formatDuration } from "@/lib/format"
import { albumCoverUrl } from "@/lib/urls"
@@ -41,8 +41,7 @@ export const SongRow = memo(function SongRow({
swipe,
downloadFrom,
}: {
/** Search results also show the lyrics line they matched. */
song: SearchSong
song: BrowseSong
onPress?: () => void
contextMenu?: Omit<MediaMenuConfig, "onAction"> & {
onAction: MediaMenuConfig["onAction"]
@@ -88,14 +87,6 @@ export const SongRow = memo(function SongRow({
>
{song.artist.name} · {song.album.title}
</Text>
{song.lyricsSnippet ? (
<Text
style={[styles.rowSubtitle, { color: secondaryForeground }]}
numberOfLines={1}
>
Lyrics: “{song.lyricsSnippet}”
</Text>
) : null}
</View>
{downloaded || downloadState === "device" ? (
<Ionicons
@@ -190,7 +181,7 @@ export const SongListRow = memo(function SongListRow({
onPlay,
onAction,
}: {
song: SearchSong
song: BrowseSong
favorited: boolean
playlistLabel?: string
palette?: Pick<CoverPalette, "foreground" | "secondaryForeground" | "divider">
@@ -2,23 +2,16 @@ import { useCallback, useMemo } from "react"
import { Platform } from "react-native"
import { Stack } from "expo-router"
import { useQuery } from "convex/react"
import { useDebouncedSearch } from "@/hooks/use-debounced-search"
import { api } from "@otunes/convex/_generated/api"
import { useThemeColors } from "@/lib/theme"
import { filterSongs } from "@otunes/convex/client/song-search"
import type { BrowseSong } from "@otunes/convex/types"
export function usePlaylistSearch(songs: BrowseSong[]) {
const search = useDebouncedSearch()
const lyricsMatches = useQuery(
api.lyrics.matchingSongIds,
search.searchQuery.trim() ? { query: search.searchQuery } : "skip"
)
const filteredSongs = useMemo(
() => filterSongs(songs, search.searchQuery, lyricsMatches),
[songs, search.searchQuery, lyricsMatches]
() => filterSongs(songs, search.searchQuery),
[songs, search.searchQuery]
)
return { ...search, filteredSongs }
+2 -2
View File
@@ -16,7 +16,7 @@ import { usePlaybackActions } from "@/contexts/playback"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { api } from "@otunes/convex/_generated/api"
import type { BrowseSong, SearchSong } from "@otunes/convex/types"
import type { BrowseSong } from "@otunes/convex/types"
import { spacing, useThemeColors } from "@/lib/theme"
function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
@@ -64,7 +64,7 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
[handleSongAction]
)
const renderItem = useCallback(
({ item: song }: ListRenderItemInfo<SearchSong>) => (
({ item: song }: ListRenderItemInfo<BrowseSong>) => (
<SongListRow
song={song}
favorited={isSongFavorite(song.id)}
+4 -12
View File
@@ -23,7 +23,6 @@ import { PlayerSymbol } from "@/components/player-symbol"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { useLyrics } from "@/hooks/use-lyrics"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { tabletMiniPlayerHeight } from "@/lib/theme"
import { albumCoverUrl } from "@/lib/urls"
@@ -59,7 +58,6 @@ export function TabletMiniPlayer() {
const { handleSongAction } = useMediaMenuActions()
const { isSongFavorite } = useFavorites()
const roomy = width - insets.left - insets.right >= 650
const lyrics = useLyrics(roomy ? (currentSong?.id ?? null) : null)
if (!focused || !config || !currentSong || queueSongIds.length === 0)
return null
@@ -168,22 +166,16 @@ export function TabletMiniPlayer() {
{roomy ? (
<Pressable
style={styles.control}
disabled={!lyrics}
onPress={() =>
router.push({
pathname: "/(app)/player",
params: { lyrics: "1" },
})
}
disabled
accessibilityRole="button"
accessibilityLabel="Show lyrics"
accessibilityState={{ disabled: !lyrics }}
accessibilityLabel="Lyrics"
accessibilityState={{ disabled: true }}
>
<PlayerSymbol
name="quote.bubble"
fallback="chatbox-outline"
size={23}
color={lyrics ? color : inactive}
color={inactive}
/>
</Pressable>
) : null}
+21 -46
View File
@@ -15,7 +15,6 @@ import { StatusBar } from "expo-status-bar"
import { AudioOutputButton } from "@/components/audio-output-button"
import { CoverImage } from "@/components/cover-image"
import { LyricsView } from "@/components/lyrics-view"
import { NowPlayingQueue } from "@/components/now-playing-queue"
import { PlayerProgress } from "@/components/player-progress"
import { PlayerSlider } from "@/components/player-slider"
@@ -25,10 +24,6 @@ import { useServerConfig } from "@/contexts/server-config"
import { useSystemVolume } from "@/hooks/use-system-volume"
import type { NowPlayingColors } from "@/lib/now-playing-colors"
import { albumCoverUrl } from "@/lib/urls"
import type { Lyrics } from "@otunes/convex/client/lyrics"
/** What the Now Playing screen shows beside or instead of the artwork. */
export type PlayerPanel = "queue" | "lyrics"
const queueMotion = {
duration: 420,
@@ -36,18 +31,14 @@ const queueMotion = {
reduceMotion: ReduceMotion.System,
}
/**
* Tablet player keeps transport controls visible while the queue or lyrics
* open beside them.
*/
/** Tablet player keeps transport controls visible while the queue opens beside them. */
export function TabletNowPlaying({
colors,
backgroundStyle,
dismissStyle,
dismissGestures,
panel,
togglePanel,
lyrics,
showQueue,
toggleQueue,
metadata,
}: {
colors: NowPlayingColors
@@ -57,9 +48,8 @@ export function TabletNowPlaying({
handle: ReturnType<typeof Gesture.Pan>
artwork: ReturnType<typeof Gesture.Pan>
}
panel: PlayerPanel | null
togglePanel: (panel: PlayerPanel) => void
lyrics: Lyrics | null | undefined
showQueue: boolean
toggleQueue: () => void
metadata: ReactNode
}) {
const router = useRouter()
@@ -73,9 +63,7 @@ export function TabletNowPlaying({
const { volume, setVolume, available: volumeAvailable } = useSystemVolume()
const [queueHeight, setQueueHeight] = useState(0)
const wideLayout = width >= 700
const showQueue = panel === "queue"
const showLyrics = panel === "lyrics"
const sideBySide = panel !== null && wideLayout
const sideBySide = showQueue && wideLayout
const progress = useSharedValue(sideBySide ? 1 : 0)
useEffect(() => {
progress.value = withTiming(sideBySide ? 1 : 0, queueMotion)
@@ -136,14 +124,7 @@ export function TabletNowPlaying({
/>
</Pressable>
)
const panelContent = showLyrics ? (
<LyricsView
key={currentSong.id}
lyrics={lyrics}
colors={colors}
fontSize={34}
/>
) : (
const queue = (
<NowPlayingQueue
tablet
colors={colors}
@@ -260,18 +241,20 @@ export function TabletNowPlaying({
</Animated.View>
{wideLayout ? (
<Animated.View
pointerEvents={panel ? "auto" : "none"}
accessibilityElementsHidden={!panel}
importantForAccessibility={panel ? "auto" : "no-hide-descendants"}
pointerEvents={showQueue ? "auto" : "none"}
accessibilityElementsHidden={!showQueue}
importantForAccessibility={
showQueue ? "auto" : "no-hide-descendants"
}
style={[styles.queue, queueStyle]}
onLayout={(event) =>
setQueueHeight(event.nativeEvent.layout.height)
}
>
{queueHeight > 0 ? panelContent : null}
{queueHeight > 0 ? queue : null}
</Animated.View>
) : null}
{panel && !sideBySide ? (
{showQueue && !sideBySide ? (
<View
style={[
styles.portraitQueue,
@@ -281,7 +264,7 @@ export function TabletNowPlaying({
setQueueHeight(event.nativeEvent.layout.height)
}
>
{queueHeight > 0 ? panelContent : null}
{queueHeight > 0 ? queue : null}
</View>
) : null}
</View>
@@ -297,29 +280,21 @@ export function TabletNowPlaying({
/>
<View style={styles.footerActions}>
<Pressable
onPress={() => togglePanel("lyrics")}
disabled={!lyrics && !showLyrics}
disabled
accessibilityRole="button"
accessibilityLabel={showLyrics ? "Hide lyrics" : "Show lyrics"}
accessibilityState={{
selected: showLyrics,
disabled: !lyrics && !showLyrics,
}}
style={[
styles.footerButton,
!lyrics && !showLyrics && { opacity: 0.4 },
showLyrics && { backgroundColor: colors.selected },
]}
accessibilityLabel="Lyrics"
accessibilityState={{ disabled: true }}
style={[styles.footerButton, { opacity: 0.4 }]}
>
<PlayerSymbol
name="quote.bubble"
fallback="chatbox-outline"
size={25}
color={showLyrics ? colors.selectedForeground : colors.foreground}
color={colors.foreground}
/>
</Pressable>
<Pressable
onPress={() => togglePanel("queue")}
onPress={toggleQueue}
accessibilityRole="button"
accessibilityLabel={showQueue ? "Hide queue" : "Show queue"}
accessibilityState={{ selected: showQueue }}
+53 -62
View File
@@ -25,7 +25,6 @@ import { AndroidSheet } from "@/components/android-sheet"
import { AudioFormatBadge } from "@/components/audio-format-badge"
import { useCacheScope } from "@/contexts/persistent-cache"
import { useServerConfig } from "@/contexts/server-config"
import { useBackgroundDownloads } from "@/hooks/use-background-downloads"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { getAuthCookieHeader } from "@/lib/auth-cookies"
import {
@@ -34,7 +33,6 @@ import {
writeRememberedDownloadQuality,
} from "@/lib/downloads"
import { loadPlaybackSongs } from "@/lib/playback-files"
import { downloadQualitySupported } from "@/lib/playback-capabilities"
import type { ServerConfig } from "@/lib/server-config"
import { showError } from "@/lib/toast"
import { useThemeColors } from "@/lib/theme"
@@ -200,8 +198,7 @@ function optionDetail(option: SizedDownloadOption, songCount: number) {
return `${included} of ${songCount} songs, ${option.fallbackCount} in High`
}
/** Centered popup asking which quality to download a target at. */
function DownloadQualityPopup({
function DownloadQualitySheet({
pending,
onClose,
onPick,
@@ -217,7 +214,7 @@ function DownloadQualityPopup({
return (
<Modal
visible={pending !== null}
animationType="fade"
animationType="slide"
transparent
onRequestClose={onClose}
>
@@ -225,11 +222,14 @@ function DownloadQualityPopup({
<Pressable style={styles.overlay} onPress={onClose}>
<Pressable
style={[
styles.popup,
styles.sheet,
{ backgroundColor: colors.card, borderColor: colors.border },
]}
onPress={(event) => event.stopPropagation()}
>
<View
style={[styles.grabber, { backgroundColor: colors.border }]}
/>
<Text style={[styles.title, { color: colors.foreground }]}>
Download Quality
</Text>
@@ -239,44 +239,36 @@ function DownloadQualityPopup({
>
{pending?.target.title}
</Text>
{pending?.response.options
.filter((option) => downloadQualitySupported(option.quality))
.map((option) => (
<Pressable
key={option.quality}
accessibilityRole="button"
style={[styles.row, { borderBottomColor: colors.border }]}
onPress={() => onPick(option.quality, remember)}
>
<View style={styles.rowText}>
{option.quality === "lossless" ||
option.quality === "atmos" ? (
<AudioFormatBadge
format={option.quality}
color={colors.foreground}
backgroundColor={colors.card}
/>
) : (
<Text
style={[styles.label, { color: colors.foreground }]}
>
{DOWNLOAD_QUALITY_LABELS[option.quality]}
</Text>
)}
<Text
style={{ color: colors.mutedForeground, fontSize: 12 }}
>
{optionDetail(option, songCount)}
{pending?.response.options.map((option) => (
<Pressable
key={option.quality}
accessibilityRole="button"
style={[styles.row, { borderBottomColor: colors.border }]}
onPress={() => onPick(option.quality, remember)}
>
<View style={styles.rowText}>
{option.quality === "lossless" ||
option.quality === "atmos" ? (
<AudioFormatBadge
format={option.quality}
color={colors.foreground}
backgroundColor={colors.card}
/>
) : (
<Text style={[styles.label, { color: colors.foreground }]}>
{DOWNLOAD_QUALITY_LABELS[option.quality]}
</Text>
</View>
<Text
style={[styles.size, { color: colors.mutedForeground }]}
>
{option.estimated ? "~" : ""}
{formatBytes(option.bytes)}
)}
<Text style={{ color: colors.mutedForeground, fontSize: 12 }}>
{optionDetail(option, songCount)}
</Text>
</Pressable>
))}
</View>
<Text style={[styles.size, { color: colors.mutedForeground }]}>
{option.estimated ? "~" : ""}
{formatBytes(option.bytes)}
</Text>
</Pressable>
))}
<View style={styles.rememberRow}>
<Text style={{ color: colors.foreground, fontSize: 15 }}>
Remember my choice
@@ -354,7 +346,6 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
target: DownloadTarget
response: DownloadOptionsResponse
} | null>(null)
const keepDownloading = useBackgroundDownloads(queue)
useEffect(() => {
if (!queue) return
@@ -402,7 +393,6 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
const remembered = await readRememberedDownloadQuality()
if (remembered) {
await startDownload(queue, target, response.songs, remembered)
keepDownloading()
toast(`Downloading ${target.title}`)
} else {
setPending({ target, response })
@@ -411,7 +401,7 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
showError(error instanceof Error ? error.message : "Download failed")
}
},
[cacheScope, config, convex, keepDownloading, queue]
[cacheScope, config, convex, queue]
)
const removeDownload = useCallback(
@@ -429,14 +419,9 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
if (!pending || !queue) return
setPending(null)
if (remember) void writeRememberedDownloadQuality(quality)
void startDownload(
queue,
pending.target,
pending.response.songs,
quality
).then(keepDownloading)
void startDownload(queue, pending.target, pending.response.songs, quality)
},
[keepDownloading, pending, queue]
[pending, queue]
)
const value = useMemo(
@@ -448,7 +433,7 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
<DownloadsContext.Provider value={value}>
{children}
{queue ? <DownloadSync queue={queue} /> : null}
<DownloadQualityPopup
<DownloadQualitySheet
pending={pending}
onClose={() => setPending(null)}
onPick={handlePick}
@@ -460,17 +445,23 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
const styles = StyleSheet.create({
overlay: {
flex: 1,
backgroundColor: "rgba(0,0,0,0.6)",
justifyContent: "center",
alignItems: "center",
padding: 24,
backgroundColor: "rgba(0,0,0,0.45)",
justifyContent: "flex-end",
},
popup: {
width: "100%",
maxWidth: 420,
borderRadius: 16,
sheet: {
borderTopLeftRadius: 16,
borderTopRightRadius: 16,
borderWidth: 1,
padding: 16,
paddingHorizontal: 16,
paddingTop: 8,
paddingBottom: 24,
},
grabber: {
width: 36,
height: 4,
borderRadius: 2,
alignSelf: "center",
marginBottom: 12,
},
title: { fontSize: 18, fontWeight: "700" },
subtitle: { fontSize: 13, marginBottom: 4 },
@@ -1,164 +0,0 @@
import { requireOptionalNativeModule } from "expo"
import Constants from "expo-constants"
import { useCallback, useEffect, useRef } from "react"
import { AppState, Platform } from "react-native"
import {
ContinuedTasks,
type ContinuedTask,
} from "react-native-continued-task"
import { setKeptRunning } from "@/lib/downloads"
import type { DownloadQueue } from "@otunes/convex/client/download-queue"
const downloadService = requireOptionalNativeModule<{
update: (remaining: number) => void
}>("DownloadService")
/** Songs downloading at once while the app runs, as the queue defaults to. */
const RUNNING_CONCURRENCY = 2
// Stopping right after starting can beat the service to `startForeground`,
// which Android treats as a crash.
const STOP_DELAY_MS = 2000
// Must match `identifierPrefixes` in app.config.ts.
const TASK_PREFIX = `${Constants.expoConfig?.ios?.bundleIdentifier}.downloads`
function songsLeft(count: number) {
return count === 1 ? "1 song left" : `${count} songs left`
}
/**
* Keeps downloads going while the app is in the background. Call the returned
* function right after the person starts a download.
*
* iOS 26+: a continued processing task keeps the app running, with progress
* in a Live Activity, so songs keep downloading a few at a time with fresh
* sign-in tokens. It must start from the person's action, so it covers
* downloads they start, not playlist syncs.
*
* iOS otherwise (and once that task ends): songs download in a background URL
* session. Songs started while suspended may wait for Wi-Fi and power, so
* every waiting song is handed over as the app leaves the screen.
*
* Android: a foreground service keeps the app running while songs are queued.
*/
export function useBackgroundDownloads(queue: DownloadQueue | null) {
const startTask = useRef<() => void>(() => {})
useEffect(() => {
if (!queue) return
if (Platform.OS === "ios") {
let active = AppState.currentState === "active"
let task: ContinuedTask | null = null
let submitting = false
let total = 0
let lastPending = 0
const updateConcurrency = () =>
queue.setConcurrency(
active || task?.state === "running" ? RUNNING_CONCURRENCY : Infinity
)
const end = () => {
task = null
setKeptRunning(false)
updateConcurrency()
}
const report = () => {
const pending = queue.pendingCount()
if (pending > lastPending) total += pending - lastPending
lastPending = pending
if (task?.state !== "running") return
if (pending === 0) {
task.complete(true)
end()
return
}
task.setProgress(total - pending, total)
task.updateTitle("Downloading", songsLeft(pending))
}
startTask.current = () => {
if (!ContinuedTasks.isSupported || task || submitting) return
const pending = queue.pendingCount()
if (pending === 0) return
submitting = true
total = pending
lastPending = pending
ContinuedTasks.submit({
identifierPrefix: TASK_PREFIX,
title: "Downloading",
subtitle: songsLeft(pending),
totalUnitCount: total,
// A task that cannot start now is no use once the app is closed.
ios: { submissionStrategy: "fail" },
})
.then((submitted) => {
task = submitted
submitted.addOnStartListener(() => {
setKeptRunning(true)
updateConcurrency()
report()
})
// iOS reports a cancel from the Live Activity as expiry too, so
// either way the songs carry on in the background session.
submitted.addOnStopListener(() => {
if (task === submitted) end()
})
})
.catch(() => {
// Not permitted or unavailable: the background session covers it.
})
.finally(() => {
submitting = false
})
}
updateConcurrency()
const unsubscribe = queue.subscribe(report)
const subscription = AppState.addEventListener("change", (state) => {
active = state === "active"
updateConcurrency()
})
return () => {
startTask.current = () => {}
unsubscribe()
subscription.remove()
task?.cancel()
end()
}
}
if (!downloadService) return
const service = downloadService
let shown = 0
let stopTimer: ReturnType<typeof setTimeout> | null = null
const update = () => {
const remaining = queue.pendingCount()
if (remaining === shown) return
if (stopTimer) clearTimeout(stopTimer)
stopTimer = null
if (remaining > 0) {
shown = remaining
service.update(remaining)
} else {
stopTimer = setTimeout(() => {
shown = 0
service.update(0)
}, STOP_DELAY_MS)
}
}
update()
const unsubscribe = queue.subscribe(update)
return () => {
unsubscribe()
if (stopTimer) clearTimeout(stopTimer)
service.update(0)
}
}, [queue])
return useCallback(() => startTask.current(), [])
}
-158
View File
@@ -1,158 +0,0 @@
import { File } from "expo-file-system"
import {
useEffect,
useMemo,
useRef,
useState,
useSyncExternalStore,
} from "react"
import {
cancelAnimation,
Easing,
useSharedValue,
withSequence,
withTiming,
} from "react-native-reanimated"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import {
followLyrics,
parseLyrics,
type Lyrics,
} from "@otunes/convex/client/lyrics"
import { readLyricsTag } from "@otunes/convex/client/lyrics-tags"
import { useDownloads } from "@/contexts/downloads"
import { useServerConfig } from "@/contexts/server-config"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { downloadedAudioUri } from "@/lib/downloads"
// Lyrics read from downloaded files, by file. Files do not change once saved.
const localLyrics = new Map<string, Promise<string | null>>()
async function readFileLyrics(uri: string) {
const handle = new File(uri).open()
try {
const text = await readLyricsTag({
size: handle.size ?? 0,
read: (offset, length) => {
handle.offset = offset
return handle.readBytes(length)
},
})
return text?.trim() || null
} finally {
handle.close()
}
}
function readLocalLyrics(uri: string) {
let lyrics = localLyrics.get(uri)
if (!lyrics) {
lyrics = readFileLyrics(uri).catch(() => null)
localLyrics.set(uri, lyrics)
}
return lyrics
}
const noopSubscribe = () => () => {}
/**
* A song's lyrics: from its downloaded file when there is one, otherwise from
* the server. `undefined` while loading, `null` when the song has none.
*/
export function useLyrics(songId: Id<"songs"> | null) {
const { config } = useServerConfig()
const { queue } = useDownloads()
const fileUri = useSyncExternalStore(queue?.subscribe ?? noopSubscribe, () =>
songId && config && queue?.getDownloaded(songId)
? downloadedAudioUri(config, songId)
: null
)
const [local, setLocal] = useState<{ uri: string; text: string | null }>()
useEffect(() => {
if (!fileUri) return
let current = true
void readLocalLyrics(fileUri).then((text) => {
if (current) setLocal({ uri: fileUri, text })
})
return () => {
current = false
}
}, [fileUri])
const localText = fileUri && local?.uri === fileUri ? local.text : undefined
// Songs without a downloaded copy, or whose copy has no lyrics tag.
const remote = useCachedQuery(
api.lyrics.forSong,
songId && (!fileUri || localText === null) ? { id: songId } : "skip"
)
const text = localText || remote
return useMemo<Lyrics | null | undefined>(() => {
if (!songId) return null
if (text === undefined) return undefined
return text ? parseLyrics(text) : null
}, [songId, text])
}
/**
* The playback time for highlighting lyrics: the player's `currentTime`,
* advanced by `followLyrics` between its progress updates.
*/
export function useLyricsTime(
lyrics: Lyrics | null | undefined,
currentTime: number,
isPlaying: boolean
) {
// Time reached since the player last reported `from`.
const [advanced, setAdvanced] = useState<{ from: number; time: number }>()
useEffect(() => {
if (!lyrics || !isPlaying) return
return followLyrics(lyrics, currentTime, (time) =>
setAdvanced({ from: currentTime, time })
)
}, [lyrics, currentTime, isPlaying])
return isPlaying && advanced?.from === currentTime
? advanced.time
: currentTime
}
/** How far the clock may drift from the player before it is reset. */
const CLOCK_DRIFT_SECONDS = 0.15
/** How far ahead the clock runs on its own; progress updates come long before. */
const CLOCK_RUN_SECONDS = 3600
/**
* Playback time in seconds on the UI thread, running smoothly between the
* player's progress updates. It is reset only when it drifts, so animations
* driven by it never restart mid-word.
*/
export function usePlaybackClock(currentTime: number, isPlaying: boolean) {
const clock = useSharedValue(currentTime)
const running = useRef(false)
useEffect(() => {
if (!isPlaying) {
running.current = false
cancelAnimation(clock)
clock.value = currentTime
return
}
const drift = Math.abs(clock.value - currentTime)
if (running.current && drift < CLOCK_DRIFT_SECONDS) return
running.current = true
clock.value = withSequence(
withTiming(currentTime, { duration: 0 }),
withTiming(currentTime + CLOCK_RUN_SECONDS, {
duration: CLOCK_RUN_SECONDS * 1000,
easing: Easing.linear,
})
)
}, [clock, currentTime, isPlaying])
return clock
}
+8 -22
View File
@@ -1,5 +1,5 @@
import { useRouter, useSegments, type Href } from "expo-router"
import { createContext, use, useCallback } from "react"
import { useCallback } from "react"
import { tabletSections } from "@/lib/tablet-navigation"
@@ -30,13 +30,6 @@ export function tabPath(tab: AppTab, path: string): Href {
return `/(app)/(tabs)/${tab}${normalized}` as Href
}
/**
* The tab whose stack a screen lives in. Each tab stack layout provides it so
* links resolve against the screen's own tab, even when the global segments
* ref has not caught up with a tab switch yet.
*/
export const TabStackContext = createContext<AppTab | undefined>(undefined)
function getActiveTabFromRef(): AppTab {
return getActiveTab(activeSegmentsRef.current)
}
@@ -48,15 +41,8 @@ export function AppNavigationSync() {
return null
}
/** Tab-aware navigation: paths resolve inside the caller's tab stack, falling back to the active tab outside one. */
export function useAppNavigation() {
const router = useRouter()
const stackTab = use(TabStackContext)
const currentTab = useCallback(
() => stackTab ?? getActiveTabFromRef(),
[stackTab]
)
const push = useCallback(
(path: string) => {
@@ -67,26 +53,26 @@ export function useAppNavigation() {
return
}
router.push(tabPath(currentTab(), path))
router.push(tabPath(getActiveTabFromRef(), path))
},
[router, currentTab]
[router]
)
const replace = useCallback(
(path: string) => {
router.replace(tabPath(currentTab(), path))
router.replace(tabPath(getActiveTabFromRef(), path))
},
[router, currentTab]
[router]
)
const href = useCallback(
(path: string) => tabPath(currentTab(), path),
[currentTab]
(path: string) => tabPath(getActiveTabFromRef(), path),
[]
)
return {
get tab() {
return currentTab()
return getActiveTabFromRef()
},
href,
push,
+2 -9
View File
@@ -16,16 +16,9 @@ function authCookieNames(serverUrl: string) {
}
}
/**
* Cookies that sign a request to the server in. Pass `refresh: false` for
* requests that may run after the JWT expires (iOS background downloads): the
* server would spend the refresh token, and the app's next refresh of the same
* token would then end the session.
*/
export async function getAuthCookieHeader(
serverUrl: string,
convexUrl: string,
{ refresh = true }: { refresh?: boolean } = {}
convexUrl: string
): Promise<string | null> {
const [jwt, refreshToken] = await Promise.all([
secureGetItem(authStorageKey(JWT_STORAGE_KEY, convexUrl)),
@@ -38,7 +31,7 @@ export async function getAuthCookieHeader(
const names = authCookieNames(serverUrl)
const parts = [`${names.jwt}=${jwt}`]
if (refresh && refreshToken) {
if (refreshToken) {
parts.push(`${names.refresh}=${refreshToken}`)
}
+2 -11
View File
@@ -12,28 +12,19 @@ const secureStoreOptions: SecureStore.SecureStoreOptions = {
keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK,
}
// The last value read or written per key, for when the keychain refuses a
// read (say, while the phone is locked and downloads continue).
const remembered = new Map<string, string>()
export async function secureGetItem(key: string): Promise<string | null> {
try {
const value = await SecureStore.getItemAsync(key, secureStoreOptions)
if (value === null) remembered.delete(key)
else remembered.set(key, value)
return value
return await SecureStore.getItemAsync(key, secureStoreOptions)
} catch {
return remembered.get(key) ?? null
return null
}
}
export async function secureSetItem(key: string, value: string): Promise<void> {
remembered.set(key, value)
await SecureStore.setItemAsync(key, value, secureStoreOptions)
}
export async function secureRemoveItem(key: string): Promise<void> {
remembered.delete(key)
try {
await SecureStore.deleteItemAsync(key, secureStoreOptions)
} catch {
+12 -100
View File
@@ -1,5 +1,5 @@
import AsyncStorage from "@react-native-async-storage/async-storage"
import { Directory, DownloadTask, File, Paths } from "expo-file-system"
import { Directory, File, Paths } from "expo-file-system"
import { Platform } from "react-native"
import {
@@ -16,7 +16,6 @@ import {
type DownloadQuality,
} from "@otunes/convex/download-quality"
import { getAuthCookieHeader } from "@/lib/auth-cookies"
import { downloadQualitySupported } from "@/lib/playback-capabilities"
import type { ServerConfig } from "@/lib/server-config"
const REMEMBERED_QUALITY_KEY = "otunes.download-quality"
@@ -74,82 +73,6 @@ function audioFile(folder: Directory) {
return folder.list().find((entry): entry is File => entry instanceof File)
}
type SongDownload = {
url: string
destination: Directory
headers: Record<string, string>
signal: AbortSignal
/** Checks and keeps the downloaded file, returning its size. */
finish: (file: File) => number
}
// Whether a continued processing task keeps the app running in the
// background (iOS 26+, see `useBackgroundDownloads`).
let keptRunning = false
const regularSessionDownloads = new Set<() => void>()
/**
* While a continued task keeps the app running, songs download through the
* regular session: iOS treats background session downloads started from the
* background as deferrable until Wi-Fi and power. When the task ends, running
* songs restart in the background session before iOS suspends the app.
*/
export function setKeptRunning(running: boolean) {
keptRunning = running
if (!running) for (const handOff of regularSessionDownloads) handOff()
}
/**
* Downloads through an iOS URL session. The background one keeps going while
* the app is suspended and wakes it when done; iOS keeps the app awake until
* `finish` returns (up to 25 seconds). Downloads still running when iOS
* terminates the app are lost.
*/
async function runDownloadTask(
{ url, destination, headers, signal, finish }: SongDownload,
sessionType: "foreground" | "background"
) {
const task = new DownloadTask(url, destination, {
headers,
signal,
sessionType,
deferBackgroundSessionCompletion: sessionType === "background",
})
const handOff = () => task.cancel()
if (sessionType === "foreground") regularSessionDownloads.add(handOff)
try {
const file = await task.downloadAsync()
if (!file) throw new Error("Download paused")
return finish(file)
} finally {
regularSessionDownloads.delete(handOff)
if (task.state === "completed") {
await task.acknowledgeBackgroundCompletionAsync().catch(() => {})
}
task.release()
}
}
async function downloadOnIOS(download: SongDownload) {
if (keptRunning) {
try {
return await runDownloadTask(download, "foreground")
} catch (error) {
// Still running means a real failure; otherwise it was handed off.
if (keptRunning || download.signal.aborted) throw error
}
}
return runDownloadTask(download, "background")
}
/** Android keeps the app running with a foreground service instead. */
async function downloadInForeground(download: SongDownload) {
const { url, destination, headers, signal, finish } = download
return finish(
await File.downloadFileAsync(url, destination, { headers, signal })
)
}
function createStorage(config: ServerConfig): DownloadStorage {
const root = serverDirectory(config)
const indexFile = new File(root, "index.json")
@@ -193,8 +116,7 @@ function createStorage(config: ServerConfig): DownloadStorage {
async save({ songId, requested, quality, albumId }, signal) {
const cookieHeader = await getAuthCookieHeader(
config.serverUrl,
config.convexUrl,
{ refresh: Platform.OS !== "ios" }
config.convexUrl
)
if (!cookieHeader) throw new Error("Sign in to download")
@@ -204,26 +126,17 @@ function createStorage(config: ServerConfig): DownloadStorage {
if (partial.exists) partial.delete()
partial.create()
try {
const url = `${config.serverUrl}${songDownloadPath(songId, requested, {
const path = songDownloadPath(songId, requested, {
losslessFormat: Platform.OS === "ios" ? "alac" : undefined,
})}`
const download =
Platform.OS === "ios" ? downloadOnIOS : downloadInForeground
return await download({
url,
destination: partial,
headers: { Cookie: cookieHeader },
signal,
finish(file) {
signal.throwIfAborted()
// A lapsed sign-in redirects to the sign-in page instead of failing.
if (file.extension === ".html") {
throw new Error("Sign in to download")
}
partial.rename(name)
return file.size ?? 0
},
})
const file = await File.downloadFileAsync(
`${config.serverUrl}${path}`,
partial,
{ headers: { Cookie: cookieHeader }, signal }
)
signal.throwIfAborted()
partial.rename(name)
return file.size ?? 0
} catch (error) {
if (partial.exists) partial.delete()
throw error
@@ -299,10 +212,9 @@ export function downloadedCoverUri(url: string) {
export async function readRememberedDownloadQuality() {
try {
const quality = parseDownloadQuality(
return parseDownloadQuality(
await AsyncStorage.getItem(REMEMBERED_QUALITY_KEY)
)
return quality && downloadQualitySupported(quality) ? quality : undefined
} catch {
return undefined
}
-3
View File
@@ -12,8 +12,6 @@ export type NowPlayingColors = {
selected: string
selectedForeground: string
highlight: string
/** Words of the playing line not yet sung. */
lyricsUnsung: string
isDark: boolean
}
@@ -30,7 +28,6 @@ export function nowPlayingColors(palette: CoverPalette): NowPlayingColors {
selected: withAlpha(foreground, 0.8),
selectedForeground: palette.background,
highlight: withAlpha(foreground, 0.1),
lyricsUnsung: withAlpha(foreground, 0.55),
isDark: palette.isDark,
}
}
-15
View File
@@ -1,10 +1,5 @@
import { Platform } from "react-native"
import {
DOWNLOAD_QUALITIES,
type DownloadQuality,
} from "@otunes/convex/download-quality"
// Android Dolby decoder reports do not reliably indicate working Atmos playback.
export const dolbyAtmosSupported = Platform.OS === "ios"
@@ -12,13 +7,3 @@ export const dolbyAtmosSupported = Platform.OS === "ios"
export function atmosEnabled(user: { preferAtmos?: boolean }) {
return dolbyAtmosSupported && (user.preferAtmos ?? false)
}
/** Whether this device may download in a quality. Android cannot download Atmos. */
export function downloadQualitySupported(quality: DownloadQuality) {
return quality !== "atmos" || dolbyAtmosSupported
}
/** Download qualities this device offers, lowest first. */
export const deviceDownloadQualities = DOWNLOAD_QUALITIES.filter(
downloadQualitySupported
)
+1 -1
View File
@@ -4,10 +4,10 @@ export const tabletSections = [
{ name: "albums", group: "(albums)", title: "Albums" },
{ name: "artists", group: "(artists)", title: "Artists" },
{ name: "songs", group: "(songs)", title: "Songs" },
{ name: "downloads", group: "(downloads)", title: "Downloads" },
{ name: "playlists", group: "(playlists)", title: "All Playlists" },
{ name: "favorites", group: "(favorites)", title: "Favorites" },
{ name: "recent", group: "(recent)", title: "Recently Played" },
{ name: "downloads", group: "(downloads)", title: "Downloads" },
] as const
export const TabletSectionContext = createContext<
@@ -1,11 +0,0 @@
plugins {
id 'com.android.library'
id 'expo-module-gradle-plugin'
}
group = 'expo.modules.downloadservice'
version = '1.0.0'
android {
namespace 'expo.modules.downloadservice'
}
@@ -1,11 +0,0 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<application>
<service
android:name="expo.modules.downloadservice.DownloadService"
android:exported="false"
android:foregroundServiceType="dataSync" />
</application>
</manifest>
@@ -1,88 +0,0 @@
package expo.modules.downloadservice
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
/**
* Keeps the app running while songs download, so Android does not freeze the
* JS downloads when the app leaves the screen. Started with the number of
* songs left, and stopped by the module once none are.
*/
class DownloadService : Service() {
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val remaining = intent?.getIntExtra(EXTRA_REMAINING, 0) ?: 0
val notification = notification(remaining)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
} else {
startForeground(NOTIFICATION_ID, notification)
}
// A restarted service would have no downloads to keep alive.
return START_NOT_STICKY
}
// Android 15 limits data sync services to six hours a day.
override fun onTimeout(startId: Int, fgsType: Int) {
stopSelf()
}
private fun notification(remaining: Int): Notification {
val manager = getSystemService(NotificationManager::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
manager.createNotificationChannel(
NotificationChannel(CHANNEL_ID, "Downloads", NotificationManager.IMPORTANCE_LOW)
)
}
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(this, CHANNEL_ID)
} else {
@Suppress("DEPRECATION")
Notification.Builder(this)
}
val launch = packageManager.getLaunchIntentForPackage(packageName)?.let {
PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_IMMUTABLE)
}
return builder
.setSmallIcon(android.R.drawable.stat_sys_download)
.setContentTitle(if (remaining == 1) "Downloading 1 song" else "Downloading $remaining songs")
.setContentIntent(launch)
.setOngoing(true)
.setOnlyAlertOnce(true)
.build()
}
companion object {
private const val CHANNEL_ID = "downloads"
private const val NOTIFICATION_ID = 7301
private const val EXTRA_REMAINING = "remaining"
fun update(context: Context, remaining: Int) {
val intent = Intent(context, DownloadService::class.java)
if (remaining == 0) {
context.stopService(intent)
return
}
intent.putExtra(EXTRA_REMAINING, remaining)
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent)
} else {
context.startService(intent)
}
} catch (_: IllegalStateException) {
// Android 12+ refuses to start one from the background (say, a
// playlist syncing); downloads then run only while the app does.
}
}
}
}
@@ -1,15 +0,0 @@
package expo.modules.downloadservice
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
class DownloadServiceModule : Module() {
override fun definition() = ModuleDefinition {
Name("DownloadService")
/** Shows how many songs are left, or stops the service at zero. */
Function("update") { remaining: Int ->
DownloadService.update(requireNotNull(appContext.reactContext), remaining)
}
}
}
@@ -1,6 +0,0 @@
{
"platforms": ["android"],
"android": {
"modules": ["expo.modules.downloadservice.DownloadServiceModule"]
}
}
@@ -1,5 +0,0 @@
{
"name": "otunes-download-service",
"version": "1.0.0",
"private": true
}
@@ -1,3 +0,0 @@
{
"platforms": ["apple"]
}
@@ -1,37 +0,0 @@
// React Native draws `filter: [{ blur }]` on iOS only with its SwiftUI
// filters flag, which the stable release leaves off. This keeps the stable
// flags and turns that one on.
#import <UIKit/UIKit.h>
#import <react/featureflags/ReactNativeFeatureFlags.h>
#import <react/featureflags/ReactNativeFeatureFlagsOverridesOSSStable.h>
using namespace facebook::react;
class SwiftUIFilterFlags : public ReactNativeFeatureFlagsOverridesOSSStable {
public:
bool enableSwiftUIBasedFilters() override {
return true;
}
};
@interface SwiftUIFilters : NSObject
@end
@implementation SwiftUIFilters
+ (void)load
{
// React Native sets its flags once while launching and throws if they were
// set first, so this waits for launch to finish. No views exist yet then.
[NSNotificationCenter.defaultCenter
addObserverForName:UIApplicationDidFinishLaunchingNotification
object:nil
queue:nil
usingBlock:^(NSNotification *notification) {
ReactNativeFeatureFlags::dangerouslyForceOverride(
std::make_unique<SwiftUIFilterFlags>());
}];
}
@end
@@ -1,14 +0,0 @@
Pod::Spec.new do |s|
s.name = 'SwiftUIFilters'
s.version = '1.0.0'
s.summary = 'Turns on React Native view filters like blur on iOS'
s.description = s.summary
s.license = { :type => 'MIT' }
s.author = 'oTunes'
s.homepage = 'https://otunes.abunchofknowitalls.com'
s.platforms = { :ios => '16.4' }
s.source = { :git => '' }
s.static_framework = true
install_modules_dependencies(s)
s.source_files = '**/*.{h,mm}'
end
-3
View File
@@ -20,7 +20,6 @@
"@otunes/convex": "workspace:*",
"@react-native-async-storage/async-storage": "2.2.0",
"@react-native-community/slider": "5.2.1",
"@react-native-masked-view/masked-view": "0.3.2",
"@react-native/metro-config": "0.88.0",
"convex": "^1.40.0",
"expo": "~58.0.17",
@@ -49,10 +48,8 @@
"react": "19.3.0",
"react-dom": "19.3.0",
"react-native": "0.88.0",
"react-native-continued-task": "0.1.0",
"react-native-gesture-handler": "~3.3.0",
"react-native-image-colors": "^2.6.0",
"react-native-nitro-modules": "0.37.2",
"react-native-reanimated": "4.7.1",
"react-native-safe-area-context": "~5.10.1",
"react-native-screens": "4.30.0",
+2 -13
View File
@@ -7,7 +7,7 @@ import { audioInfo } from "@/lib/server-audio-info"
import { streamFile } from "@/lib/server-audio-stream"
import { spawnFfmpeg } from "@/lib/server-ffmpeg"
import { seekableLosslessFile } from "@/lib/server-lossless"
import { getSongLyrics, getSongSource } from "@/lib/server-song"
import { getSongSource } from "@/lib/server-song"
import { NextRequest, NextResponse, userAgent } from "next/server"
import fs from "node:fs/promises"
import os from "node:os"
@@ -40,14 +40,9 @@ async function fileResponse(songId: string, file: string, contentType: string) {
})
}
/** Longest lyrics passed to ffmpeg; Linux caps one argument at 128 KiB. */
const MAX_LYRICS_ARGUMENT_BYTES = 100 * 1024
/**
* Transcodes to an AAC .m4a with its index up front, so the saved file has a
* duration and seeks offline. Tags carry over, and the stored lyrics are
* written too, since ffmpeg drops some formats' lyrics tags (like MP3 USLT)
* when writing MP4. The temporary file is removed once sent.
* duration and seeks offline. The temporary file is removed once sent.
*/
async function transcodeResponse(
songId: string,
@@ -55,11 +50,6 @@ async function transcodeResponse(
kbps: number,
signal: AbortSignal
) {
const lyrics = await getSongLyrics(songId)
const lyricsArgs =
lyrics && Buffer.byteLength(lyrics) <= MAX_LYRICS_ARGUMENT_BYTES
? ["-metadata", `lyrics=${lyrics}`]
: []
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "otunes-download-"))
const output = path.join(dir, "audio.m4a")
const cleanup = () => fs.rm(dir, { recursive: true, force: true })
@@ -74,7 +64,6 @@ async function transcodeResponse(
"aac",
"-b:a",
`${kbps}k`,
...lyricsArgs,
"-movflags",
"+faststart",
output,
-3
View File
@@ -114,7 +114,6 @@ export function AlbumView({
}) {
const {
isSongFavorite,
areSongsFavorite,
isAlbumFavorite,
toggleSongFavorite,
toggleAlbumFavorite,
@@ -155,7 +154,6 @@ export function AlbumView({
handlePointerDown,
prepareContextMenu,
} = useTrackSelection(album.tracks, validHighlightedSongId)
const selectionFavorited = areSongsFavorite(selectedIds)
const selectionPositions = React.useMemo(
() =>
@@ -415,7 +413,6 @@ export function AlbumView({
isFavorite={isSongFavorite(track.id)}
selectedCount={selectedCount}
selectionStationArtistId={album.artist.id}
selectionFavorited={selectionFavorited}
isNowPlaying={currentSongId === track.id}
onPointerDown={handlePointerDown}
onSelect={handleRowSelect}
+3 -4
View File
@@ -39,10 +39,9 @@ const ASK_EVERY_TIME = "ask"
/** Shades of the text color, darkest for the smallest files. */
const QUALITY_OPACITY: Record<DownloadQuality, number> = {
low: 0.2,
medium: 0.35,
high: 0.5,
lossless: 0.75,
medium: 0.25,
high: 0.45,
lossless: 0.7,
atmos: 1,
}
+21 -12
View File
@@ -37,8 +37,7 @@ type FavoritesContextValue = {
) => Promise<boolean>
toggleAlbumFavorite: (albumId: Id<"albums">) => Promise<void>
toggleArtistFavorite: (artistId: Id<"artists">) => Promise<void>
/** True when `songIds` is non-empty and every song is favorited. */
areSongsFavorite: (songIds: Iterable<string>) => boolean
favoriteSongs: (songIds: Id<"songs">[]) => Promise<void>
}
const FavoritesContext = React.createContext<FavoritesContextValue | null>(null)
@@ -131,16 +130,26 @@ export function FavoritesProvider({ children }: { children: React.ReactNode }) {
[songIds, favoriteSong, unfavoriteSong]
)
const areSongsFavorite = React.useCallback(
(ids: Iterable<string>) => {
let any = false
for (const id of ids) {
if (!songIds.has(id)) return false
any = true
const favoriteSongs = React.useCallback(
async (ids: Id<"songs">[]) => {
const unique = [...new Set(ids)]
if (unique.length === 0) {
return
}
try {
await favoriteSongsMutation({ songIds: unique })
toast.success(
unique.length > 1
? `Favorited ${unique.length} songs`
: "Added to favorites"
)
} catch (error) {
toast.error(
error instanceof Error ? error.message : "Failed to update favorites"
)
}
return any
},
[songIds]
[favoriteSongsMutation]
)
const toggleSongsFavorite = React.useCallback(
@@ -223,7 +232,7 @@ export function FavoritesProvider({ children }: { children: React.ReactNode }) {
toggleSongsFavorite,
toggleAlbumFavorite,
toggleArtistFavorite,
areSongsFavorite,
favoriteSongs,
}),
[
isSongFavorite,
@@ -233,7 +242,7 @@ export function FavoritesProvider({ children }: { children: React.ReactNode }) {
toggleSongsFavorite,
toggleAlbumFavorite,
toggleArtistFavorite,
areSongsFavorite,
favoriteSongs,
]
)
+1 -7
View File
@@ -8,14 +8,8 @@ const QueuePanel = dynamic(() =>
import("@/components/queue-panel").then((module) => module.QueuePanel)
)
const LyricsPanel = dynamic(() =>
import("@/components/lyrics-panel").then((module) => module.LyricsPanel)
)
/** The queue or lyrics panel beside the page, whichever is open. */
export function LazyQueuePanel() {
const { queueOpen, lyricsOpen } = usePlayback()
const { queueOpen } = usePlayback()
if (lyricsOpen) return <LyricsPanel />
return queueOpen ? <QueuePanel /> : null
}
-243
View File
@@ -1,243 +0,0 @@
"use client"
import * as React from "react"
import {
useIsPlaying,
usePlayback,
usePlaybackProgress,
} from "@/components/playback-provider"
import { useLyrics, useLyricsTime } from "@/hooks/use-lyrics"
import { cn } from "@/lib/utils"
import {
activeLineIndex,
type LyricLine,
type LyricWord,
type Lyrics,
} from "@otunes/convex/client/lyrics"
/** How long a manual scroll keeps the panel from following the song. */
const MANUAL_SCROLL_HOLD_MS = 3000
/** Blur by distance from the playing line; farther lines share the last. */
const LINE_BLUR = ["blur-none", "blur-[1px]", "blur-[2px]", "blur-[3px]"]
/** Unsung words wipe from dim to bright, soft edge first, as they are sung. */
const WORD_FILL = {
backgroundImage:
"linear-gradient(90deg, var(--foreground) 40%, color-mix(in oklab, var(--foreground) 45%, transparent) 60%)",
backgroundSize: "250% 100%",
}
const WORD_FILL_FRAMES = [
{ backgroundPosition: "100% 0" },
{ backgroundPosition: "0% 0" },
]
/** How far a word's fill may drift from playback before it is reset. */
const FILL_DRIFT_MS = 80
/** Lyrics beside the page, in the queue's place. Synced lines follow playback. */
export function LyricsPanel() {
const { currentSong } = usePlayback()
const lyrics = useLyrics(currentSong?.id ?? null)
return (
<aside
aria-label="Lyrics"
className={cn(
"flex h-svh w-72 shrink-0 flex-col border-l bg-background",
"max-md:fixed max-md:inset-y-0 max-md:right-0 max-md:z-20 max-md:shadow-xl"
)}
>
{lyrics === null ? (
<p className="m-auto text-sm text-muted-foreground">No lyrics</p>
) : lyrics ? (
<LyricsLines key={currentSong?.id} lyrics={lyrics} />
) : null}
</aside>
)
}
function LyricsLines({ lyrics }: { lyrics: Lyrics }) {
const { seekTo, currentTime } = usePlaybackProgress()
const isPlaying = useIsPlaying()
const { setIsPlaying } = usePlayback()
const time = useLyricsTime(lyrics, currentTime, isPlaying)
const active = activeLineIndex(lyrics, time)
const scrollRef = React.useRef<HTMLDivElement>(null)
const synced = lyrics.synced !== "none"
// While the listener scrolls, lines stay sharp and the panel stays put.
const [browsing, setBrowsing] = React.useState(false)
const browseTimer = React.useRef<ReturnType<typeof setTimeout>>(undefined)
React.useEffect(() => () => clearTimeout(browseTimer.current), [])
React.useEffect(() => {
const container = scrollRef.current
const line = container?.querySelector<HTMLElement>(
`[data-line="${Math.max(active, 0)}"]`
)
if (!container || !line || !synced || browsing) return
container.scrollTo({
top: line.offsetTop - container.clientHeight * 0.25,
behavior: "smooth",
})
}, [active, synced, browsing])
const playFrom = React.useCallback(
(seconds: number) => {
seekTo(seconds)
setIsPlaying(true)
clearTimeout(browseTimer.current)
setBrowsing(false)
},
[seekTo, setIsPlaying]
)
const holdScroll = () => {
setBrowsing(true)
clearTimeout(browseTimer.current)
browseTimer.current = setTimeout(
() => setBrowsing(false),
MANUAL_SCROLL_HOLD_MS
)
}
return (
<div
ref={scrollRef}
onWheel={holdScroll}
onTouchMove={holdScroll}
className="group relative min-h-0 flex-1 overflow-y-auto px-6 pt-[25svh] pb-[60svh]"
>
{lyrics.lines.map((line, index) =>
synced ? (
<SyncedLine
key={index}
index={index}
line={line}
distance={
browsing
? 0
: Math.min(Math.abs(index - active), LINE_BLUR.length - 1)
}
active={index === active}
time={index === active ? time : null}
isPlaying={isPlaying}
onSelect={playFrom}
/>
) : (
<p
key={index}
className={cn(
"text-lg leading-snug font-semibold text-foreground/85",
line.text === "" && "h-4"
)}
>
{line.text}
</p>
)
)}
</div>
)
}
/**
* One timed line, blurred by its `distance` from the playing line. Only the
* active line gets the playback time, so memoized lines elsewhere skip
* re-rendering as the song plays.
*/
const SyncedLine = React.memo(function SyncedLine({
index,
line,
distance,
active,
time,
isPlaying,
onSelect,
}: {
index: number
line: LyricLine
distance: number
active: boolean
time: number | null
isPlaying: boolean
onSelect: (seconds: number) => void
}) {
return (
<button
type="button"
data-line={index}
onClick={() => onSelect(line.start ?? 0)}
className={cn(
"-mx-2 my-1 block w-[calc(100%+1rem)] rounded-md px-2 py-1.5 text-left text-[22px] leading-tight font-bold transition-[color,filter] duration-300 group-hover:blur-none hover:bg-foreground/5",
LINE_BLUR[distance],
active && !line.words ? "text-foreground" : "text-foreground/30"
)}
>
{active && line.words && time !== null ? (
<FilledWords words={line.words} time={time} isPlaying={isPlaying} />
) : (
line.text
)}
</button>
)
})
/**
* The playing line's words, each filled as far as it has been sung. The
* browser runs the fills on the song's timeline (a word's start is its
* delay); playback updates only correct their drift.
*/
function FilledWords({
words,
time,
isPlaying,
}: {
words: LyricWord[]
time: number
isPlaying: boolean
}) {
const spans = React.useRef<(HTMLSpanElement | null)[]>([])
const fills = React.useRef<(Animation | undefined)[]>([])
React.useEffect(() => {
fills.current = words.map((word, index) =>
spans.current[index]?.animate(WORD_FILL_FRAMES, {
delay: word.start * 1000,
duration: Math.max(word.end - word.start, 0.05) * 1000,
easing: "linear",
fill: "both",
})
)
return () => fills.current.forEach((fill) => fill?.cancel())
}, [words])
React.useEffect(() => {
const at = time * 1000
fills.current.forEach((fill, index) => {
if (!fill) return
if (Math.abs(Number(fill.currentTime ?? 0) - at) > FILL_DRIFT_MS) {
fill.currentTime = at
}
// `play` on a finished fill would rewind it to the start.
if (isPlaying && time < words[index].end) fill.play()
else fill.pause()
})
}, [words, time, isPlaying])
return words.map((word, index) => {
const text = word.text.trimEnd()
return (
<React.Fragment key={index}>
<span
ref={(span) => {
spans.current[index] = span
}}
className="bg-clip-text text-transparent"
style={WORD_FILL}
>
{text}
</span>
{word.text.slice(text.length)}
</React.Fragment>
)
})
}
+1 -4
View File
@@ -48,8 +48,7 @@ export function OtherDownloadsView() {
[songs]
)
const { isSongFavorite, areSongsFavorite, toggleSongFavorite } =
useFavorites()
const { isSongFavorite, toggleSongFavorite } = useFavorites()
const { playFromSong, playInOrder, playShuffled } = usePlaybackActions()
const {
selectedIds,
@@ -63,7 +62,6 @@ export function OtherDownloadsView() {
() => stationArtistId(songs, selectedIds),
[songs, selectedIds]
)
const selectionFavorited = areSongsFavorite(selectedIds)
const selectionPositions = useMemo(
() =>
getSelectionRangePositions(
@@ -142,7 +140,6 @@ export function OtherDownloadsView() {
isFavorite={isSongFavorite(songs[index].id)}
selectedCount={selectedCount}
selectionStationArtistId={selectedStationArtistId}
selectionFavorited={selectionFavorited}
onPointerDown={handlePointerDown}
onSelect={handleRowSelect}
onPlay={handleRowPlay}
+2 -20
View File
@@ -60,13 +60,10 @@ type PlaybackContextValue = {
shuffleEnabled: boolean
repeatEnabled: RepeatMode
queueOpen: boolean
/** The lyrics panel, which shares the queue's place beside the page. */
lyricsOpen: boolean
isPlaying: boolean
volume: number
setQueueOpen: (open: boolean) => void
toggleQueueOpen: () => void
toggleLyricsOpen: () => void
setIsPlaying: (playing: boolean) => void
setVolume: (volume: number) => void
/** An origin from `downloadsQueueOrigin` plays downloads in any quality. */
@@ -125,7 +122,6 @@ type PlaybackActions = Omit<
| "shuffleEnabled"
| "repeatEnabled"
| "queueOpen"
| "lyricsOpen"
| "isPlaying"
| "volume"
| "dolbyAtmosSupported"
@@ -510,12 +506,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
const currentTimeRef = useRef(0)
const durationRef = useRef(0)
const [sidePanel, setSidePanel] = useState<"queue" | "lyrics" | null>(null)
const queueOpen = sidePanel === "queue"
const lyricsOpen = sidePanel === "lyrics"
const setQueueOpen = useCallback((open: boolean) => {
setSidePanel((panel) => (open ? "queue" : panel === "queue" ? null : panel))
}, [])
const [queueOpen, setQueueOpen] = useState(false)
const [isPlaying, setIsPlaying] = useState(false)
const [playbackStartVersion, setPlaybackStartVersion] = useState(0)
const [currentTime, setCurrentTime] = useState(0)
@@ -1450,11 +1441,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
)
const toggleQueueOpen = useCallback(() => {
setSidePanel((panel) => (panel === "queue" ? null : "queue"))
}, [])
const toggleLyricsOpen = useCallback(() => {
setSidePanel((panel) => (panel === "lyrics" ? null : "lyrics"))
setQueueOpen((open) => !open)
}, [])
const toggleShuffle = useCallback(async () => {
@@ -1560,7 +1547,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
() => ({
setQueueOpen,
toggleQueueOpen,
toggleLyricsOpen,
setIsPlaying,
setVolume,
playInOrder,
@@ -1586,9 +1572,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
skipPrevious,
}),
[
setQueueOpen,
toggleQueueOpen,
toggleLyricsOpen,
setVolume,
playInOrder,
playShuffled,
@@ -1624,7 +1608,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
shuffleEnabled: playback.shuffleEnabled,
repeatEnabled: playback.repeatEnabled,
queueOpen,
lyricsOpen,
isPlaying: isPlaybackActive,
volume,
dolbyAtmosSupported,
@@ -1635,7 +1618,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
currentSong,
currentFormat,
queueOpen,
lyricsOpen,
isPlaybackActive,
volume,
dolbyAtmosSupported,
+3 -12
View File
@@ -29,7 +29,6 @@ import {
import { Button } from "@/components/ui/button"
import { Slider } from "@/components/ui/slider"
import { useSidebar } from "@/components/ui/sidebar"
import { useLyrics } from "@/hooks/use-lyrics"
import { albumCoverUrl } from "@/lib/cover-urls"
import { cn } from "@/lib/utils"
import { formatDuration } from "@/lib/format-duration"
@@ -74,21 +73,18 @@ export function PlayerBar() {
shuffleEnabled,
repeatEnabled,
queueOpen,
lyricsOpen,
isPlaying,
volume,
queueSongIds,
setIsPlaying,
setVolume,
toggleQueueOpen,
toggleLyricsOpen,
toggleShuffle,
cycleRepeat,
skipNext,
skipPrevious,
} = usePlayback()
const { state, isMobile } = useSidebar()
const lyrics = useLyrics(currentSong?.id ?? null)
const hasQueue = queueSongIds.length > 0
const sidebarExpanded = !isMobile && state === "expanded"
@@ -98,7 +94,7 @@ export function PlayerBar() {
className={cn(
"@container pointer-events-none fixed bottom-4 z-50 flex justify-center px-4 transition-[left,right] duration-200 ease-linear",
sidebarExpanded ? "right-0 left-[16rem]" : "inset-x-0",
(queueOpen || lyricsOpen) && !isMobile && "right-72"
queueOpen && !isMobile && "right-72"
)}
>
<div className="pointer-events-auto flex w-full max-w-[40rem] items-center gap-2 rounded-full border border-foreground/20 bg-(--player-background) px-3 py-2 text-card-foreground shadow-lg [--player-background:var(--card)] md:gap-3 md:py-1.5 dark:border-white/20 dark:text-white dark:[--player-background:#303033]">
@@ -231,14 +227,9 @@ export function PlayerBar() {
<Button
variant="ghost"
size="icon"
className="hidden @min-[640px]:inline-flex"
aria-label="Lyrics"
aria-pressed={lyricsOpen}
className={cn(
"hidden @min-[640px]:inline-flex",
lyricsOpen && "text-primary"
)}
disabled={!lyrics && !lyricsOpen}
onClick={toggleLyricsOpen}
disabled
>
<MessageSquareQuote className="size-4" />
</Button>
+5 -16
View File
@@ -5,7 +5,7 @@ import { stationArtistId } from "@/lib/station-artist"
import * as React from "react"
import Image from "next/image"
import { useRouter } from "next/navigation"
import { useMutation, useQuery } from "convex/react"
import { useMutation } from "convex/react"
import {
ImageIcon,
Pencil,
@@ -74,12 +74,8 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
currentUser === undefined
? playlist.isOwner
: currentUser?._id === playlist.owner.id
const {
isSongFavorite,
areSongsFavorite,
toggleSongFavorite,
toggleSongsFavorite,
} = useFavorites()
const { isSongFavorite, toggleSongFavorite, toggleSongsFavorite } =
useFavorites()
const currentSongId = useCurrentSongId()
const {
playInOrder,
@@ -105,13 +101,9 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
: playlistSongs
const [searchQuery, setSearchQuery] = React.useState("")
const isSearching = searchQuery.trim() !== ""
const lyricsMatches = useQuery(
api.lyrics.matchingSongIds,
isSearching ? { query: searchQuery } : "skip"
)
const filteredSongs = React.useMemo(
() => filterSongs(songs, searchQuery, lyricsMatches),
[songs, searchQuery, lyricsMatches]
() => filterSongs(songs, searchQuery),
[songs, searchQuery]
)
const playlistSongIds = React.useMemo(
() => songs.map((song) => song.id as Id<"songs">),
@@ -147,7 +139,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
() => stationArtistId(songs, selectedIds),
[songs, selectedIds]
)
const selectionFavorited = areSongsFavorite(selectedIds)
const selectionPositions = React.useMemo(
() =>
@@ -470,7 +461,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
onAction={handlePlaylistMediaAction}
playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
showFavorite={!isFavorites}
favorited={areSongsFavorite(playlistSongIds)}
downloaded={playlistDownloaded}
trackRowTrigger={false}
triggerVariant="secondary"
@@ -528,7 +518,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
selectionPosition={selectionPositions[index]}
selectedCount={selectedCount}
selectionStationArtistId={selectedStationArtistId}
selectionFavorited={selectionFavorited}
playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
downloadCollection={downloadRef}
showFavoriteInMenu={!isFavorites}
+40 -167
View File
@@ -2,18 +2,11 @@
import * as React from "react"
import { useFavorites } from "@/components/favorites-provider"
import {
MediaContextMenuArea,
type MediaContextAction,
} from "@/components/media-context-menu"
import { PlaybackSongMeta } from "@/components/playback-song-meta"
import { usePlayback } from "@/components/playback-provider"
import { TrackCover, TrackRow } from "@/components/track-row"
import { Skeleton } from "@/components/ui/skeleton"
import { Spinner } from "@/components/ui/spinner"
import { useSongDownloadState } from "@/hooks/use-downloads"
import { useMediaActions } from "@/hooks/use-media-actions"
import { useTrackSelection } from "@/hooks/use-track-selection"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong, QueueSong } from "@otunes/convex/types"
@@ -22,7 +15,6 @@ import {
moveQueueBlock,
} from "@/lib/move-queue-block"
import { getSelectionRangePositions } from "@/lib/selection-range-styles"
import { stationArtistId } from "@/lib/station-artist"
import { useSongs } from "@/lib/song-cache"
import { cn } from "@/lib/utils"
@@ -54,51 +46,6 @@ function toSelectableQueue(
})
}
/**
* Opens the song's right-click menu over `children`, for the queue rows that
* stand alone (history and the current song) rather than in the selection.
*/
function SongMenuArea({
song,
children,
}: {
song: BrowseSong
children: React.ReactElement
}) {
const { isSongFavorite, toggleSongFavorite } = useFavorites()
const { runSongsAction } = useMediaActions()
const downloaded = useSongDownloadState(song.id) === "here"
function handleAction(action: MediaContextAction) {
if (action === "favorite") {
void toggleSongFavorite(song.id)
return
}
runSongsAction(action, [song.id], song.artist.id)
}
return (
<MediaContextMenuArea
menu={{
label: `More options for ${song.title}`,
stationArtistId: song.artist.id,
selectedCount: 1,
onOpenMenu: () => {},
onAction: handleAction,
favorited: isSongFavorite(song.id),
downloaded,
navigation: {
artist: { id: song.artist.id },
album: { id: song.album.id },
},
share: { type: "song", albumId: song.album.id, songId: song.id },
}}
>
{children}
</MediaContextMenuArea>
)
}
/** A played song; clicking it plays it again from that point in history. */
function HistorySongRow({
song,
@@ -114,27 +61,25 @@ function HistorySongRow({
}
return (
<SongMenuArea song={song}>
<li
role="button"
tabIndex={0}
className="flex cursor-pointer items-center gap-3 px-4 py-2 text-sm hover:bg-foreground/5 data-[state=open]:bg-foreground/5"
onClick={() => onPlay(historyIndex)}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault()
onPlay(historyIndex)
}
}}
>
<TrackCover
albumId={song.album.id}
alt={song.album.title}
inRange={false}
/>
<PlaybackSongMeta song={song} align="start" showAlbum={false} />
</li>
</SongMenuArea>
<li
role="button"
tabIndex={0}
className="flex cursor-pointer items-center gap-3 px-4 py-2 text-sm hover:bg-foreground/5"
onClick={() => onPlay(historyIndex)}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault()
onPlay(historyIndex)
}
}}
>
<TrackCover
albumId={song.album.id}
alt={song.album.title}
inRange={false}
/>
<PlaybackSongMeta song={song} align="start" showAlbum={false} />
</li>
)
}
@@ -236,71 +181,8 @@ export function QueuePanel() {
() => selectableQueue.map((item) => ({ id: item.selectionId })),
[selectableQueue]
)
const {
selectedIds,
selectedCount,
handleSelect,
handlePointerDown,
prepareContextMenu,
clearSelection,
} = useTrackSelection(selectionItems)
const { isSongFavorite, areSongsFavorite } = useFavorites()
const { runSongsAction } = useMediaActions()
/** The rows a menu acts on: the selection, else just the clicked row. */
const menuTargets = React.useCallback(
(selectionId: string) => {
const ids = selectedIds.has(selectionId)
? selectedIds
: new Set([selectionId])
return selectableQueue.filter((item) => ids.has(item.selectionId))
},
[selectableQueue, selectedIds]
)
const selectedStationArtistId = React.useMemo(
() =>
stationArtistId(
selectableQueue.flatMap((item) =>
item.song ? [{ id: item.selectionId, artist: item.song.artist }] : []
),
selectedIds
),
[selectableQueue, selectedIds]
)
const selectionFavorited = areSongsFavorite(
selectableQueue.flatMap((item) =>
item.song && selectedIds.has(item.selectionId) ? [item.song.id] : []
)
)
const handleMediaAction = React.useCallback(
(action: MediaContextAction, selectionId: string) => {
const songs = menuTargets(selectionId).flatMap((item) =>
item.song ? [item.song] : []
)
const artistId = songs[0]?.artist.id
runSongsAction(
action,
songs.map((song) => song.id),
songs.every((song) => song.artist.id === artistId)
? artistId
: undefined
)
},
[menuTargets, runSongsAction]
)
const handleRemove = React.useCallback(
(selectionId: string) => {
const removed = new Set(
menuTargets(selectionId).map((item) => item.queueIndex)
)
clearSelection()
void reorderQueue(queueSongIds.filter((_, index) => !removed.has(index)))
},
[clearSelection, menuTargets, queueSongIds, reorderQueue]
)
const { selectedIds, handleSelect, handlePointerDown } =
useTrackSelection(selectionItems)
const handleRowSelect = React.useCallback(
(index: number, event: React.MouseEvent) => {
@@ -410,25 +292,25 @@ export function QueuePanel() {
{/* Fills the viewport so the current song can always scroll to the top. */}
<div ref={currentRef} className="flex min-h-full flex-col">
{currentSong ? (
<SongMenuArea song={currentSong}>
<div className="flex items-center gap-3 px-4 py-3">
<TrackCover
albumId={currentSong.album.id}
alt={currentSong.album.title}
inRange={false}
size="lg"
/>
<PlaybackSongMeta
song={currentSong}
align="start"
showAlbum={false}
/>
</div>
</SongMenuArea>
) : currentQueueSongId ? (
<div className="px-4 py-3">
<Skeleton className="size-14 shrink-0 rounded-md" />
{currentQueueSongId ? (
<div className="flex items-center gap-3 px-4 py-3">
{currentSong ? (
<>
<TrackCover
albumId={currentSong.album.id}
alt={currentSong.album.title}
inRange={false}
size="lg"
/>
<PlaybackSongMeta
song={currentSong}
align="start"
showAlbum={false}
/>
</>
) : (
<Skeleton className="size-14 shrink-0 rounded-md" />
)}
</div>
) : null}
@@ -454,12 +336,6 @@ export function QueuePanel() {
variant="queue"
song={item.song}
index={index}
selectionId={item.selectionId}
isFavorite={isSongFavorite(item.song.id)}
selectedCount={selectedCount}
selectionStationArtistId={selectedStationArtistId}
selectionFavorited={selectionFavorited}
removeLabel="Remove from Queue"
selectionPosition={selectionPositions[index]}
isDragging={draggingIndices.has(index)}
onPointerDown={handlePointerDown}
@@ -467,9 +343,6 @@ export function QueuePanel() {
onPlay={handleRowPlay}
onDragStart={setDragIndex}
onDrop={handleDrop}
onPrepareContextMenu={prepareContextMenu}
onMediaAction={handleMediaAction}
onRemove={handleRemove}
/>
) : (
<QueueSongRowSkeleton key={item.selectionId} />
+2 -7
View File
@@ -14,10 +14,10 @@ import {
type MediaContextMenuProps,
} from "@/components/media-context-menu"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { SearchSong } from "@otunes/convex/types"
import type { BrowseSong } from "@otunes/convex/types"
import { albumCoverUrl } from "@/lib/cover-urls"
export function SearchSongItem({ song }: { song: SearchSong }) {
export function SearchSongItem({ song }: { song: BrowseSong }) {
const { openAddToPlaylist } = useAddToPlaylist()
const { isSongFavorite, toggleSongFavorite } = useFavorites()
const { runQueueAction, createStation } = useQueueMediaActions()
@@ -103,11 +103,6 @@ export function SearchSongItem({ song }: { song: SearchSong }) {
>
<p className="truncate text-sm">{song.artist.name}</p>
</Link>
{song.lyricsSnippet ? (
<p className="truncate text-xs text-muted-foreground">
Lyrics: “{song.lyricsSnippet}”
</p>
) : null}
</div>
<MediaContextMenu {...menu} />
+1 -4
View File
@@ -47,8 +47,7 @@ const SONGS_PAGE_SIZE = 50
const estimateSongRowSize = () => 56
export function SongsView() {
const { isSongFavorite, areSongsFavorite, toggleSongFavorite } =
useFavorites()
const { isSongFavorite, toggleSongFavorite } = useFavorites()
const { playFromLibrarySong } = usePlaybackActions()
const [sortKey, setSortKey] = useState<SortKey>("title")
const [sortDirection, setSortDirection] = useState<SortDirection>("asc")
@@ -99,7 +98,6 @@ export function SongsView() {
() => stationArtistId(songs, selectedIds),
[songs, selectedIds]
)
const selectionFavorited = areSongsFavorite(selectedIds)
const selectionPositions = useMemo(
() =>
@@ -224,7 +222,6 @@ export function SongsView() {
isFavorite={isSongFavorite(songs[index].id)}
selectedCount={selectedCount}
selectionStationArtistId={selectedStationArtistId}
selectionFavorited={selectionFavorited}
onPointerDown={handlePointerDown}
onSelect={handleRowSelect}
onPlay={handleRowPlay}
+10 -24
View File
@@ -38,7 +38,7 @@ import type { DownloadSource } from "@otunes/convex/client/download-queue"
* columns (use with `LibraryTrackListHeader`).
* - `album`: favorite star, track number, title with optional credits.
* - `playlist`: cover with favorite overlay, track number, title.
* - `queue`: cover, title and artist, duration, and a reorder grip.
* - `queue`: cover, title and artist, duration, and a reorder grip. No menu.
*/
export type TrackRowVariant = "library" | "album" | "playlist" | "queue"
@@ -47,12 +47,6 @@ export type TrackRowProps = {
song: BrowseSong
/** Position in the list the selection hook was given. */
index: number
/**
* The id the selection hook knows this row by, passed to the menu and
* remove callbacks. Defaults to the song id; the queue uses a per-position
* id since a song can appear more than once.
*/
selectionId?: string
/** Number shown in the track number column (`album` and `playlist`). */
trackNumber?: number
/** Secondary line under the title, e.g. album track credits. */
@@ -68,8 +62,6 @@ export type TrackRowProps = {
selectedCount?: number
/** Station artist for the selection when this row is selected. */
selectionStationArtistId?: string
/** Whether every selected song is favorited, when this row is selected. */
selectionFavorited?: boolean
playlistLabel?: string
showFavoriteInMenu?: boolean
/** Adds a destructive menu item calling `onRemove`. */
@@ -79,10 +71,10 @@ export type TrackRowProps = {
onPointerDown: (event: React.MouseEvent) => void
onPlay: (index: number) => void
onToggleFavorite?: (songId: string) => void
onPrepareContextMenu?: (selectionId: string) => void
onPrepareContextMenu?: (songId: string) => void
/** Renders the "more options" and right-click menus when provided. */
onMediaAction?: (action: MediaContextAction, selectionId: string) => void
onRemove?: (selectionId: string) => void
onMediaAction?: (action: MediaContextAction, songId: string) => void
onRemove?: (songId: string) => void
/** Makes the row draggable when provided. */
onDragStart?: (index: number) => void
onDrop?: (index: number) => void
@@ -259,7 +251,6 @@ function TrackRowComponent({
variant,
song,
index,
selectionId,
trackNumber,
subtitle,
downloadCollection,
@@ -270,7 +261,6 @@ function TrackRowComponent({
isDragging = false,
selectedCount = 0,
selectionStationArtistId,
selectionFavorited,
playlistLabel,
showFavoriteInMenu = true,
removeLabel,
@@ -294,7 +284,6 @@ function TrackRowComponent({
const flush = variant === "library" || variant === "queue"
const play = () => onPlay(index)
const toggleFavorite = () => onToggleFavorite?.(song.id)
const rowId = selectionId ?? song.id
const favoriteStar = (
<div className="flex shrink-0 items-center justify-center">
@@ -344,14 +333,11 @@ function TrackRowComponent({
stationArtistId: inRange ? selectionStationArtistId : song.artist.id,
selectedCount: inRange && selectedCount > 0 ? selectedCount : 1,
inSelectionRange: inRange,
onOpenMenu: () => onPrepareContextMenu?.(rowId),
onAction: (action) => onMediaAction(action, rowId),
onOpenMenu: () => onPrepareContextMenu?.(song.id),
onAction: (action) => onMediaAction(action, song.id),
playlistLabel,
showFavorite: showFavoriteInMenu,
favorited:
inRange && selectedCount > 0
? (selectionFavorited ?? isFavorite)
: isFavorite,
favorited: isFavorite,
navigation: {
artist: { id: song.artist.id },
album: { id: song.album.id },
@@ -365,7 +351,7 @@ function TrackRowComponent({
<MediaMenuItem
variant="destructive"
className="justify-between"
onClick={() => onRemove(rowId)}
onClick={() => onRemove(song.id)}
>
{removeLabel}
<Trash2 />
@@ -569,7 +555,7 @@ function TrackRowComponent({
}
/**
* Pass stable callbacks: they receive the row's `index`, song id or
* `selectionId`, so one handler can serve every row.
* Pass stable callbacks: they receive the row's `index` or song id, so one
* handler can serve every row.
*/
export const TrackRow = React.memo(TrackRowComponent)
-105
View File
@@ -1,105 +0,0 @@
"use client"
import { useEffect, useMemo, useState, useSyncExternalStore } from "react"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import {
followLyrics,
parseLyrics,
type Lyrics,
} from "@otunes/convex/client/lyrics"
import { readLyricsTag } from "@otunes/convex/client/lyrics-tags"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { downloadedAudioBlob, downloadQueue } from "@/lib/downloads"
// Lyrics read from downloaded files, by song. Files do not change once saved.
const localLyrics = new Map<string, Promise<string | null>>()
function readLocalLyrics(songId: string) {
let lyrics = localLyrics.get(songId)
if (!lyrics) {
lyrics = downloadedAudioBlob(songId)
.then((blob) =>
blob
? readLyricsTag({
size: blob.size,
read: async (offset, length) =>
new Uint8Array(
await blob.slice(offset, offset + length).arrayBuffer()
),
})
: null
)
.then((text) => text?.trim() || null)
.catch(() => null)
localLyrics.set(songId, lyrics)
}
return lyrics
}
/**
* A song's lyrics: from its downloaded file when there is one, otherwise from
* the server. `undefined` while loading, `null` when the song has none.
*/
export function useLyrics(songId: Id<"songs"> | null) {
const downloaded = useSyncExternalStore(
downloadQueue.subscribe,
() => (songId ? downloadQueue.getDownloaded(songId) !== undefined : false),
() => false
)
const [local, setLocal] = useState<{
songId: string
text: string | null
} | null>(null)
useEffect(() => {
if (!songId || !downloaded) return
let current = true
void readLocalLyrics(songId).then((text) => {
if (current) setLocal({ songId, text })
})
return () => {
current = false
}
}, [songId, downloaded])
const localText =
songId && downloaded && local?.songId === songId ? local.text : undefined
// Songs without a downloaded copy, or whose copy has no lyrics tag.
const remote = useCachedQuery(
api.lyrics.forSong,
songId && (!downloaded || localText === null) ? { id: songId } : "skip"
)
const text = localText || remote
return useMemo<Lyrics | null | undefined>(() => {
if (!songId) return null
if (text === undefined) return undefined
return text ? parseLyrics(text) : null
}, [songId, text])
}
/**
* The playback time for highlighting lyrics: the player's `currentTime`,
* advanced by `followLyrics` between its progress updates.
*/
export function useLyricsTime(
lyrics: Lyrics | null | undefined,
currentTime: number,
isPlaying: boolean
) {
// Time reached since the player last reported `from`.
const [advanced, setAdvanced] = useState<{ from: number; time: number }>()
useEffect(() => {
if (!lyrics || !isPlaying) return
return followLyrics(lyrics, currentTime, (time) =>
setAdvanced({ from: currentTime, time })
)
}, [lyrics, currentTime, isPlaying])
return isPlaying && advanced?.from === currentTime
? advanced.time
: currentTime
}
+3 -6
View File
@@ -26,8 +26,7 @@ function songsTitle(songIds: readonly string[]) {
export function useMediaActions() {
const { openAddToPlaylist, openAddArtistToPlaylist } = useAddToPlaylist()
const { areSongsFavorite, toggleSongsFavorite, toggleArtistFavorite } =
useFavorites()
const { favoriteSongs, toggleArtistFavorite } = useFavorites()
const { runQueueAction, createStation } = useQueueMediaActions()
const convex = useConvex()
const cacheScope = useCacheScope()
@@ -45,8 +44,7 @@ export function useMediaActions() {
if (stationArtist) void createStation(stationArtist)
break
case "favorite":
// Unfavorite only when every song already is, matching the menu label.
void toggleSongsFavorite(songIds, areSongsFavorite(songIds))
void favoriteSongs(songIds)
break
case "playlist":
openAddToPlaylist(songIds)
@@ -75,8 +73,7 @@ export function useMediaActions() {
},
[
createStation,
areSongsFavorite,
toggleSongsFavorite,
favoriteSongs,
openAddToPlaylist,
runQueueAction,
requestDownload,
+5 -11
View File
@@ -204,7 +204,11 @@ export async function downloadedAudioUrl(songId: string) {
audioUrls.set(songId, existing)
return existing
}
const blob = await downloadedAudioBlob(songId)
const db = await openDatabase()
const blob = await readRequest<Blob | undefined>(
db.transaction(AUDIO_STORE).objectStore(AUDIO_STORE),
songId
)
if (!blob) return null
const url = URL.createObjectURL(blob)
audioUrls.set(songId, url)
@@ -214,16 +218,6 @@ export async function downloadedAudioUrl(songId: string) {
return url
}
/** A downloaded song's audio file, or null when it is not downloaded. */
export async function downloadedAudioBlob(songId: string) {
const db = await openDatabase()
const blob = await readRequest<Blob | undefined>(
db.transaction(AUDIO_STORE).objectStore(AUDIO_STORE),
songId
)
return blob ?? null
}
export function readRememberedDownloadQuality() {
try {
return parseDownloadQuality(localStorage.getItem(REMEMBERED_QUALITY_KEY))
-10
View File
@@ -22,16 +22,6 @@ export async function getSongSource(id: string): Promise<SongSource> {
return song
}
/** The song's stored lyrics tag, or null without lyrics. */
export async function getSongLyrics(id: string): Promise<string | null> {
const token = await convexAuthNextjsToken()
return await fetchQuery(
api.lyrics.forSong,
{ id: id as Id<"songs"> },
convexServerOptions(token)
)
}
const SOURCE_BATCH_SIZE = 200
/** `getSongSource` for many songs, in batches. Missing songs are left out. */
-2
View File
@@ -10,8 +10,6 @@ const isPublic = createRouteMatcher([
"/api/album/:id/cover",
"/api/artist/:id/cover",
"/api/playlist/:id/cover",
// Mobile clients load avatars without the web auth cookie.
"/api/user/:id/avatar",
"/album/:id",
"/artist/:id",
"/library/artists/:id",
+1 -13
View File
@@ -125,9 +125,8 @@ function collectionKey({ kind, id }: CollectionRef) {
*/
export function createDownloadQueue(
storage: DownloadStorage,
options: { concurrency?: number } = {}
{ concurrency = 2 }: { concurrency?: number } = {}
) {
let concurrency = options.concurrency ?? 2
const downloaded = new Map<string, DownloadedSong>()
const collections = new Map<string, DownloadedCollection>()
const otherSongIds = new Set<string>()
@@ -373,17 +372,6 @@ export function createDownloadQueue(
collections: () => [...collections.values()],
isQueued,
status,
/** Songs downloading or waiting to. */
pendingCount: () => running.size + waiting.length,
/**
* How many songs download at once. Raising it starts waiting songs now;
* lowering it lets running songs finish.
*/
setConcurrency(limit: number) {
concurrency = limit
pump()
},
/** Songs downloaded on their own, in the order they were added. */
otherSongIds: () => [...otherSongIds],
-93
View File
@@ -1,93 +0,0 @@
/**
* Typo-tolerant word matching, shared by library search, lyrics search and
* in-list song filters.
*/
/**
* Lowercase words without accents or apostrophes, so "Don't Stop Beyoncé"
* gives ["dont", "stop", "beyonce"].
*/
export function searchWords(text: string): string[] {
return (
text
.normalize("NFKD")
.replace(/\p{M}/gu, "")
.toLowerCase()
.replace(/['’]/g, "")
.match(/[\p{L}\p{N}]+/gu) ?? []
)
}
/** Typos a query word may hold. Short words get none, or they match too much. */
function allowedTypos(term: string) {
if (term.length < 4) return 0
return term.length < 8 ? 1 : 2
}
/**
* Edits (insert, delete, substitute or swap neighbors) turning `a` into `b`,
* or `max + 1` once it is sure to exceed `max`.
*/
function editDistance(a: string, b: string, max: number): number {
if (Math.abs(a.length - b.length) > max) return max + 1
let before: number[] = []
let previous = Array.from({ length: b.length + 1 }, (_, j) => j)
for (let i = 1; i <= a.length; i++) {
const current = [i]
let rowMin = i
for (let j = 1; j <= b.length; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1
let distance = Math.min(
previous[j]! + 1,
current[j - 1]! + 1,
previous[j - 1]! + cost
)
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
distance = Math.min(distance, before[j - 2]! + 1)
}
current.push(distance)
rowMin = Math.min(rowMin, distance)
}
if (rowMin > max) return max + 1
before = previous
previous = current
}
return previous[b.length]!
}
/**
* Whether `word` is query `term` give or take a few typos. With `prefix` the
* word may also just start with the term, as when it is still being typed.
*/
function wordMatchesTerm(term: string, word: string, prefix: boolean) {
const typos = allowedTypos(term)
if (typos === 0) return false
if (editDistance(term, word, typos) <= typos) return true
return (
prefix &&
word.length > term.length &&
editDistance(term, word.slice(0, term.length), typos) <= typos
)
}
/**
* How every query term (from `searchWords`) appears among `words`: "exact"
* when each is a word, "fuzzy" when some only match give or take typos, or
* null when one is missing. The last term may be a word's prefix.
*/
export function matchWords(
words: readonly string[],
terms: readonly string[]
): "exact" | "fuzzy" | null {
let quality: "exact" | "fuzzy" = "exact"
for (const [index, term] of terms.entries()) {
const prefix = index === terms.length - 1
const exact = words.some((word) =>
prefix ? word.startsWith(term) : word === term
)
if (exact) continue
if (!words.some((word) => wordMatchesTerm(term, word, prefix))) return null
quality = "fuzzy"
}
return terms.length > 0 ? quality : null
}
-214
View File
@@ -1,214 +0,0 @@
/**
* Reads the lyrics tag from a downloaded audio file, so offline playback shows
* the same lyrics the server has. Downloads are MP4 (`©lyr`), FLAC (`LYRICS`
* Vorbis comment) or MP3 (ID3 `USLT`), and only the tag bytes are read.
*/
export type ByteReader = {
size: number
read: (offset: number, length: number) => Promise<Uint8Array>
}
const utf8 = new TextDecoder("utf-8")
function ascii(bytes: Uint8Array, start: number, length: number) {
let text = ""
for (let i = start; i < Math.min(start + length, bytes.length); i++) {
text += String.fromCharCode(bytes[i])
}
return text
}
function view(bytes: Uint8Array) {
return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
}
/** Most bytes read for a tag, so a corrupt length cannot load a whole file. */
const MAX_TAG_BYTES = 16 * 1024 * 1024
type Box = { type: string; start: number; size: number; header: number }
/** The boxes inside `bytes[start, end)`. */
function* boxes(bytes: Uint8Array, start: number, end: number) {
const data = view(bytes)
let offset = start
while (offset + 8 <= end) {
let size = data.getUint32(offset)
let header = 8
if (size === 1 && offset + 16 <= end) {
size = Number(data.getBigUint64(offset + 8))
header = 16
} else if (size === 0) {
size = end - offset
}
if (size < header) return
yield { type: ascii(bytes, offset + 4, 4), start: offset, size, header }
offset += size
}
}
function child(bytes: Uint8Array, parent: Box, type: string, skip = 0) {
for (const box of boxes(
bytes,
parent.start + parent.header + skip,
parent.start + parent.size
)) {
if (box.type === type) return box
}
return undefined
}
async function mp4Lyrics(file: ByteReader) {
// `moov` may sit after the audio, so walk the top-level box headers.
let offset = 0
while (offset + 8 <= file.size) {
const head = await file.read(offset, 16)
if (head.length < 8) return null
const data = view(head)
let size = data.getUint32(0)
if (size === 1 && head.length === 16) size = Number(data.getBigUint64(8))
else if (size === 0) size = file.size - offset
if (size < 8) return null
if (ascii(head, 4, 4) === "moov") {
if (size > MAX_TAG_BYTES) return null
const moov = await file.read(offset, size)
const root = [...boxes(moov, 0, moov.length)][0]
const udta = root && child(moov, root, "udta")
const meta = udta && child(moov, udta, "meta")
// `meta` is a full box: 4 bytes of version and flags precede children.
const ilst = meta && child(moov, meta, "ilst", 4)
const lyr = ilst && child(moov, ilst, "\u00a9lyr")
const text = lyr && child(moov, lyr, "data")
if (!text) return null
// Type (4 bytes) and locale (4 bytes) precede the UTF-8 text.
return utf8.decode(
moov.subarray(text.start + text.header + 8, text.start + text.size)
)
}
offset += size
}
return null
}
const VORBIS_LYRICS_KEYS = new Set(["LYRICS", "UNSYNCEDLYRICS"])
async function flacLyrics(file: ByteReader) {
let offset = 4
for (;;) {
const header = await file.read(offset, 4)
if (header.length < 4) return null
const last = (header[0] & 0x80) !== 0
const type = header[0] & 0x7f
const length = (header[1] << 16) | (header[2] << 8) | header[3]
offset += 4
if (type === 4) {
const block = await file.read(offset, Math.min(length, MAX_TAG_BYTES))
const data = view(block)
let at = 4 + data.getUint32(0, true)
const count = data.getUint32(at, true)
at += 4
for (let i = 0; i < count && at + 4 <= block.length; i++) {
const commentLength = data.getUint32(at, true)
const comment = utf8.decode(
block.subarray(at + 4, at + 4 + commentLength)
)
at += 4 + commentLength
const equals = comment.indexOf("=")
if (VORBIS_LYRICS_KEYS.has(comment.slice(0, equals).toUpperCase())) {
return comment.slice(equals + 1)
}
}
return null
}
if (last) return null
offset += length
}
}
function syncsafe(bytes: Uint8Array, at: number) {
return (
(bytes[at] << 21) |
(bytes[at + 1] << 14) |
(bytes[at + 2] << 7) |
bytes[at + 3]
)
}
/**
* Latin-1 (0), UTF-16 with a byte order mark (1) or UTF-16BE (2). Decoded by
* hand because React Native's TextDecoder only knows UTF-8.
*/
function decodeLegacy(raw: Uint8Array, encoding: number) {
let text = ""
if (encoding === 0) {
for (const byte of raw) text += String.fromCharCode(byte)
return text
}
let start = 0
let bigEndian = encoding === 2
if (encoding === 1 && raw.length >= 2) {
bigEndian = raw[0] === 0xfe && raw[1] === 0xff
if (bigEndian || (raw[0] === 0xff && raw[1] === 0xfe)) start = 2
}
for (let i = start; i + 1 < raw.length; i += 2) {
text += String.fromCharCode(
bigEndian ? (raw[i] << 8) | raw[i + 1] : raw[i] | (raw[i + 1] << 8)
)
}
return text
}
/** Decodes ID3 text in `encoding`, returning it and where its terminator ends. */
function id3Text(bytes: Uint8Array, encoding: number, terminated: boolean) {
const wide = encoding === 1 || encoding === 2
let end = bytes.length
if (terminated) {
for (let i = 0; i < bytes.length; i += wide ? 2 : 1) {
if (bytes[i] === 0 && (!wide || bytes[i + 1] === 0)) {
end = i
break
}
}
}
const raw = bytes.subarray(0, end)
const text = encoding === 3 ? utf8.decode(raw) : decodeLegacy(raw, encoding)
return { text, next: Math.min(bytes.length, end + (wide ? 2 : 1)) }
}
async function id3Lyrics(file: ByteReader) {
const header = await file.read(0, 10)
const version = header[3]
const size = syncsafe(header, 6)
if (size > MAX_TAG_BYTES) return null
const tag = await file.read(10, size)
const data = view(tag)
let at = 0
while (at + 10 <= tag.length) {
const id = ascii(tag, at, 4)
if (!/^[A-Z0-9]{4}$/.test(id)) return null
const frameSize =
version === 4 ? syncsafe(tag, at + 4) : data.getUint32(at + 4)
const body = tag.subarray(at + 10, at + 10 + frameSize)
at += 10 + frameSize
if (id !== "USLT" || body.length < 5) continue
const encoding = body[0]
// Encoding, a 3 letter language, then a terminated description.
const description = id3Text(body.subarray(4), encoding, true)
return id3Text(body.subarray(4 + description.next), encoding, false).text
}
return null
}
/** The raw lyrics tag of an audio file, or null when it has none. */
export async function readLyricsTag(file: ByteReader): Promise<string | null> {
const head = await file.read(0, 12)
const magic = ascii(head, 0, 4)
try {
if (magic === "fLaC") return await flacLyrics(file)
if (magic.startsWith("ID3")) return await id3Lyrics(file)
if (ascii(head, 4, 4) === "ftyp") return await mp4Lyrics(file)
} catch {
// An unexpected layout reads as no lyrics; the server copy is used instead.
}
return null
}
-259
View File
@@ -1,259 +0,0 @@
/**
* Lyrics as tagged in the music files: plain text, LRC (`[mm:ss.xx]line`), or
* word-timed LRC (`<mm:ss.xx>word`). The server stores that text unchanged and
* clients parse it here, so a downloaded file's tag and the server copy read
* the same.
*/
import { matchWords, searchWords } from "./fuzzy-search"
export type LyricWord = {
/** Includes its trailing space, so a line's words join back into its text. */
text: string
start: number
end: number
}
export type LyricLine = {
text: string
/** Seconds; `null` for plain lyrics. */
start: number | null
/**
* The line's words as they are sung. Line-timed lyrics get estimated
* ones (see `estimateWords`); plain lyrics have none.
*/
words: LyricWord[] | null
}
export type Lyrics = {
/** How the source was timed, whatever `words` were estimated. */
synced: "none" | "line" | "word"
lines: LyricLine[]
}
const LINE_STAMP = /^\[(\d+):(\d+(?:[.:]\d+)?)\]/
const WORD_STAMP = /<(\d+):(\d+(?:[.:]\d+)?)>/g
const HAS_WORD_STAMP = /<\d+:\d+(?:[.:]\d+)?>/
const ID_TAG = /^\[[a-z]+:.*\]$/i
/** A rough singing pace, so a line-timed line's fill tracks its words. */
const ESTIMATED_SECONDS_PER_CHAR = 0.07
function seconds(minutes: string, rest: string) {
return Number(minutes) * 60 + Number(rest.replace(":", "."))
}
/** Splits `<t>word <t>word<t>` into words; the last stamp ends the last word. */
function parseWords(body: string): LyricWord[] {
const stamps = [...body.matchAll(WORD_STAMP)]
const words: LyricWord[] = []
for (let i = 0; i < stamps.length; i++) {
const stamp = stamps[i]
const textStart = stamp.index + stamp[0].length
const next = stamps[i + 1]
const text = body.slice(textStart, next?.index ?? body.length)
const start = seconds(stamp[1], stamp[2])
if (text.trim()) {
words.push({
text,
start,
end: next ? seconds(next[1], next[2]) : start,
})
}
}
return words
}
export function parseLyrics(raw: string): Lyrics | null {
const rows = raw.replace(/\r\n?/g, "\n").split("\n")
const timed = rows.some((row) => LINE_STAMP.test(row.trim()))
const wordTimed = rows.some((row) => HAS_WORD_STAMP.test(row))
if (!timed && !wordTimed) {
const lines = rows.map((row) => ({
text: row.trim(),
start: null,
words: null,
}))
// Blank rows between stanzas stay as spacing; ones at the ends go.
while (lines[0]?.text === "") lines.shift()
while (lines.at(-1)?.text === "") lines.pop()
return lines.length > 0 ? { synced: "none", lines } : null
}
const lines: LyricLine[] = []
for (const row of rows) {
let body = row.trim()
if (ID_TAG.test(body) && !LINE_STAMP.test(body)) continue
// A line may repeat under several stamps: `[00:12.00][01:30.00]Chorus`.
const starts: number[] = []
for (let match = LINE_STAMP.exec(body); match;) {
starts.push(seconds(match[1], match[2]))
body = body.slice(match[0].length)
match = LINE_STAMP.exec(body)
}
const words = wordTimed ? parseWords(body) : []
const text = (
words.length > 0 ? words.map((word) => word.text).join("") : body
).trim()
if (!text) continue
if (starts.length === 0 && words.length > 0) starts.push(words[0].start)
for (const start of starts) {
const shift = words.length > 0 ? start - words[0].start : 0
lines.push({
text,
start,
words:
words.length > 0
? words.map((word) => ({
...word,
start: word.start + shift,
end: word.end + shift,
}))
: null,
})
}
}
lines.sort((a, b) => a.start! - b.start!)
if (lines.length === 0) return null
const synced = lines.every((line) => line.words) ? "word" : "line"
if (synced === "line") estimateWords(lines)
return { synced, lines }
}
/**
* Gives timed lines without word timing words spread over them by length,
* at a singing pace but never past the next line, so they fill as they play.
*/
function estimateWords(lines: LyricLine[]) {
lines.forEach((line, index) => {
if (line.words || line.start === null) return
const next = lines[index + 1]?.start ?? Infinity
const duration = Math.min(
next - line.start,
line.text.length * ESTIMATED_SECONDS_PER_CHAR
)
const perChar = duration / line.text.length
let at = line.start
line.words = (line.text.match(/\S+\s*/g) ?? []).map((text) => {
const start = at
at += text.length * perChar
return { text, start, end: at }
})
})
}
/** The text without timestamps, one line per row, for search and snippets. */
export function plainLyrics(lyrics: Lyrics) {
return lyrics.lines.map((line) => line.text).join("\n")
}
/** How well a tag's lyrics are timed, to keep the best of a song's files. */
export function lyricsRank(raw: string | null) {
const synced = raw ? parseLyrics(raw)?.synced : undefined
return synced === "word" ? 3 : synced === "line" ? 2 : synced ? 1 : 0
}
/**
* The line playing at `time` (the last one started), or -1 before the first.
* Plain lyrics never have one.
*/
export function activeLineIndex(lyrics: Lyrics, time: number) {
let active = -1
for (let i = 0; i < lyrics.lines.length; i++) {
const start = lyrics.lines[i].start
if (start === null || start > time) break
active = i
}
return active
}
/** When the highlighted line or word next changes after `time`, if ever. */
export function nextLyricsChange(lyrics: Lyrics, time: number) {
let next = Infinity
for (const line of lyrics.lines) {
if (line.start !== null && line.start > time) {
next = Math.min(next, line.start)
break
}
for (const word of line.words ?? []) {
if (word.start > time) {
next = Math.min(next, word.start)
break
}
}
}
return next
}
/**
* While audio plays on from `time` seconds, calls `onChange` with the playback
* time whenever the highlighted line or word changes. Players report progress
* only a few times a second, which is too coarse for word timing. Returns a
* function that stops it.
*/
export function followLyrics(
lyrics: Lyrics,
time: number,
onChange: (time: number) => void
) {
const startedAt = Date.now() - time * 1000
let timer: ReturnType<typeof setTimeout> | undefined
const schedule = (from: number) => {
const next = nextLyricsChange(lyrics, from)
if (!Number.isFinite(next)) return
timer = setTimeout(
() => {
const now = (Date.now() - startedAt) / 1000
onChange(now)
schedule(now)
},
(next - from) * 1000
)
}
if (lyrics.synced !== "none") schedule(time)
return () => clearTimeout(timer)
}
const SNIPPET_LEAD = 24
export type LyricsMatch = {
/** The matched line, trimmed to start near the match. */
snippet: string
/**
* 2 when the line holds the query as typed, 1 when it holds every word of
* it, 0 when it does give or take typos.
*/
score: 0 | 1 | 2
}
/**
* Where a search matched the lyrics: the best line holding the query as
* typed, or else every word of it (see `matchWords`). Null when no single
* line does.
*/
export function matchLyrics(plain: string, query: string): LyricsMatch | null {
const needle = query.trim().toLowerCase()
const terms = searchWords(needle)
// Most songs miss a word entirely, so skip them before checking lines.
if (!needle || !matchWords([...new Set(searchWords(plain))], terms)) {
return null
}
let loose: LyricsMatch | null = null
for (const line of plain.split("\n")) {
const column = line.toLowerCase().indexOf(needle)
if (column !== -1) {
const snippet =
column > SNIPPET_LEAD
? `…${line.slice(column - SNIPPET_LEAD).trimStart()}`
: line.trim()
return { snippet, score: 2 }
}
if (loose?.score === 1) continue
const quality = matchWords(searchWords(line), terms)
if (quality === "exact" || (quality && !loose)) {
loose = { snippet: line.trim(), score: quality === "exact" ? 1 : 0 }
}
}
return loose
}
+6 -19
View File
@@ -1,34 +1,21 @@
import { matchWords, searchWords } from "./fuzzy-search"
type SearchableSong = {
id: string
title: string
artist: { name: string }
album: { title: string }
}
/**
* Case-insensitive match on title, artist, or album, give or take typos (see
* `matchWords`), plus the songs in `lyricsMatches` (from
* `api.lyrics.matchingSongIds`). A blank query keeps every song.
*/
/** Case-insensitive match on title, artist, or album. A blank query keeps every song. */
export function filterSongs<T extends SearchableSong>(
songs: T[],
query: string,
lyricsMatches?: readonly string[]
query: string
) {
const normalized = query.trim().toLowerCase()
if (!normalized) {
return songs
}
const terms = searchWords(normalized)
const byLyrics = new Set(lyricsMatches)
return songs.filter((song) => {
if (byLyrics.has(song.id)) return true
const fields = [song.title, song.artist.name, song.album.title]
return (
fields.some((value) => value.toLowerCase().includes(normalized)) ||
matchWords(searchWords(fields.join(" ")), terms) !== null
return songs.filter((song) =>
[song.title, song.artist.name, song.album.title].some((value) =>
value.toLowerCase().includes(normalized)
)
})
)
}
-2
View File
@@ -19,7 +19,6 @@ import type * as intentCatalog from "../intentCatalog.js";
import type * as intentCatalogChanges from "../intentCatalogChanges.js";
import type * as library from "../library.js";
import type * as limits from "../limits.js";
import type * as lyrics from "../lyrics.js";
import type * as migrations from "../migrations.js";
import type * as playback from "../playback.js";
import type * as playbackState from "../playbackState.js";
@@ -47,7 +46,6 @@ declare const fullApi: ApiFromModules<{
intentCatalogChanges: typeof intentCatalogChanges;
library: typeof library;
limits: typeof limits;
lyrics: typeof lyrics;
migrations: typeof migrations;
playback: typeof playback;
playbackState: typeof playbackState;
+2 -114
View File
@@ -10,7 +10,6 @@ import { ConvexError } from "convex/values"
import type { Id } from "./_generated/dataModel"
import { action, internalAction, type ActionCtx } from "./_generated/server"
import { lyricsRank } from "../client/lyrics"
const DATA_DIR = process.env.DATA || "/data"
const HLS_CACHE_DIR = "/tmp/otunes"
@@ -68,8 +67,6 @@ const SCAN_LOCK_LEASE_MS = 15 * 60 * 1000
/** New files left unparsed after this are picked up by the next scan. */
const SCAN_PARSE_BUDGET_MS = 6 * 60 * 1000
const SCAN_BATCH_SIZE = 200
/** Lyrics text per mutation, well under Convex's argument size limit. */
const SCAN_BATCH_LYRICS_BYTES = 2 * 1024 * 1024
const FS_CONCURRENCY = 16
type Page<T> = { page: T[]; isDone: boolean; continueCursor: string }
@@ -223,55 +220,6 @@ function releaseDate(common: music.ICommonTagsResult) {
return common.year ? `01-01-${common.year}` : ""
}
const LYRICS_TAG_IDS = new Set(["©LYR", "LYRICS", "UNSYNCEDLYRICS", "USLT"])
function lrcStamp(milliseconds: number) {
const totalSeconds = milliseconds / 1000
const minutes = Math.floor(totalSeconds / 60)
const rest = (totalSeconds - minutes * 60).toFixed(2).padStart(5, "0")
return `[${String(minutes).padStart(2, "0")}:${rest}]`
}
/** One native tag's lyrics as text; ID3 synced lyrics become LRC. */
function lyricsTagText({ id, value }: music.ITag): string | null {
const key = id.toUpperCase()
if (typeof value === "string") {
return LYRICS_TAG_IDS.has(key) ? value : null
}
if (
(key !== "USLT" && key !== "SYLT") ||
!value ||
typeof value !== "object"
) {
return null
}
const lyrics = value as music.ILyricsTag
const synced = lyrics.syncText ?? []
// Timestamp format 2 is milliseconds; frame-based stamps cannot be used.
if (synced.length > 0 && lyrics.timeStampFormat === 2) {
return synced
.map((line) => `${lrcStamp(line.timestamp ?? 0)}${line.text}`)
.join("\n")
}
return lyrics.text ?? null
}
/** The best timed lyrics tag in a file, or null without one. */
function lyricsTag(metadata: music.IAudioMetadata): string | null {
let best: string | null = null
for (const tags of Object.values(metadata.native)) {
for (const tag of tags) {
const text = lyricsTagText(tag)?.trim() || null
if (lyricsRank(text) > lyricsRank(best)) best = text
}
}
return best
}
function betterLyrics(a: string | null, b: string | null) {
return lyricsRank(b) > lyricsRank(a) ? b : a
}
type NewSong = {
name: string
files: Record<string, string>
@@ -282,7 +230,6 @@ type NewSong = {
year: number
date: string
genres: string[]
lyrics: string | null
}
type ImportEntry = {
@@ -439,11 +386,9 @@ async function scanLibrary(ctx: ActionCtx) {
imports.set(key, entry)
}
const lyrics = lyricsTag(metadata)
const pending = entry.songs.get(title)
if (pending) {
pending.files[codec] ??= filePath
pending.lyrics = betterLyrics(pending.lyrics, lyrics)
continue
}
entry.songs.set(title, {
@@ -457,39 +402,9 @@ async function scanLibrary(ctx: ActionCtx) {
year: common.year || 0,
date: releaseDate(common),
genres: common.genre || [],
lyrics,
})
}
// Songs scanned before lyrics were stored, read once for their lyrics.
const unreadLyrics = songs.filter(
(song) =>
song.hasLyrics === undefined &&
Object.keys(songFiles.get(song._id)!).length > 0
)
const readLyrics = await mapLimit(
unreadLyrics,
FS_CONCURRENCY,
async (song) => {
let best: string | null = null
for (const filePath of Object.values(songFiles.get(song._id)!)) {
if (Date.now() > deadline) {
return null
}
try {
const metadata = await music.parseFile(filePath, {
skipCovers: true,
})
best = betterLyrics(best, lyricsTag(metadata))
} catch {
// An unreadable file contributes no lyrics.
}
}
return { id: song._id, lyrics: best }
}
)
const songLyrics = readLyrics.filter((song) => song !== null)
const deletedSongs = songs.flatMap((song) =>
Object.keys(songFiles.get(song._id)!).length === 0 ? [song._id] : []
)
@@ -554,7 +469,6 @@ async function scanLibrary(ctx: ActionCtx) {
let importBatch: ImportEntry[] = []
let importBatchSongs = 0
let importBatchBytes = 0
const flushImports = async () => {
if (importBatch.length === 0) {
return
@@ -567,41 +481,16 @@ async function scanLibrary(ctx: ActionCtx) {
})
importBatch = []
importBatchSongs = 0
importBatchBytes = 0
}
for (const entry of imports.values()) {
importBatch.push(entry)
importBatchSongs += entry.songs.size
for (const song of entry.songs.values()) {
importBatchBytes += song.lyrics?.length ?? 0
}
if (
importBatchSongs >= SCAN_BATCH_SIZE ||
importBatchBytes >= SCAN_BATCH_LYRICS_BYTES
) {
if (importBatchSongs >= SCAN_BATCH_SIZE) {
await flushImports()
}
}
await flushImports()
let lyricsBatch: typeof songLyrics = []
let lyricsBatchBytes = 0
for (const [index, song] of songLyrics.entries()) {
lyricsBatch.push(song)
lyricsBatchBytes += song.lyrics?.length ?? 0
if (
lyricsBatch.length >= SCAN_BATCH_SIZE ||
lyricsBatchBytes >= SCAN_BATCH_LYRICS_BYTES ||
index === songLyrics.length - 1
) {
await ctx.runMutation(internal.lyrics.setSongLyrics, {
songs: lyricsBatch,
})
lyricsBatch = []
lyricsBatchBytes = 0
}
}
for (const batch of chunk(artistCovers, SCAN_BATCH_SIZE)) {
await ctx.runMutation(internal.library.updateArtistCovers, {
artists: batch,
@@ -634,8 +523,7 @@ async function scanLibrary(ctx: ActionCtx) {
)
const summary =
`songs: ${importedSongs} added, ${updatedSongs.length} updated, ` +
`${deletedSongs.length} removed, ${songLyrics.length} read for lyrics ` +
`(${unreadLyrics.length - songLyrics.length} deferred); albums removed: ${removedAlbums}; ` +
`${deletedSongs.length} removed; albums removed: ${removedAlbums}; ` +
`artists removed: ${removedArtists}; covers updated: ` +
`${artistCovers.length + albumCovers.length}; ` +
`files deferred: ${skipped}; ${Date.now() - startedAt}ms`
+17 -64
View File
@@ -18,7 +18,6 @@ import type {
LibrarySearchResults,
OwnedPlaylistForAdd,
PlaylistSummary,
SearchSong,
SearchTopResultItem,
SidebarPlaylists,
} from "./types"
@@ -26,8 +25,6 @@ import { purgeFavoriteEntities } from "./favoriteStore"
import { chunk, type Chunked } from "./limits"
import { recordIntentCatalogChanges } from "./intentCatalogChanges"
import { playlistCoverVersion } from "./playlistCover"
import { deleteSongLyrics, searchSongLyrics, writeSongLyrics } from "./lyrics"
import { matchWords, searchWords } from "../client/fuzzy-search"
export type {
BrowseAlbum,
@@ -42,7 +39,6 @@ export type {
LibrarySearchResults,
OwnedPlaylistForAdd,
PlaylistSummary,
SearchSong,
SearchTopResultItem,
SidebarPlaylists,
} from "./types"
@@ -619,16 +615,7 @@ export const browseArtistDetail = query({
},
})
/**
* How well `text` matches a lowercase search, from 100 (the whole text) down
* to 20 (every word, give or take typos); 0 is no match. `terms` are the
* query's `searchWords`.
*/
function matchScore(
text: string,
query: string,
terms: readonly string[]
): number {
function matchScore(text: string, query: string): number {
const lower = text.toLowerCase()
if (lower === query) {
return 100
@@ -642,20 +629,15 @@ function matchScore(
if (lower.includes(query)) {
return 40
}
const words = matchWords(searchWords(text), terms)
if (words === "exact") {
return 30
}
return words === "fuzzy" ? 20 : 0
return 0
}
function matchScoreSongArtists(
artist: string | string[],
query: string,
terms: readonly string[]
query: string
): number {
return getSongArtistNames(artist).reduce(
(best, name) => Math.max(best, matchScore(name, query, terms)),
(best, name) => Math.max(best, matchScore(name, query)),
0
)
}
@@ -666,14 +648,10 @@ function matchScoreSongArtists(
*/
const MAX_SEARCH_RESULTS = 500
/** Songs found by lyrics alone, listed after title, artist and album matches. */
const MAX_LYRICS_SEARCH_RESULTS = 50
export const searchLibrary = query({
args: { query: v.string() },
handler: async (ctx, args) => {
const queryText = args.query.trim().toLowerCase()
const terms = searchWords(queryText)
if (!queryText || !(await isSignedIn(ctx))) {
return {
topResults: [],
@@ -694,7 +672,7 @@ export const searchLibrary = query({
.map((artist) => ({
kind: "artist" as const,
item: toBrowseArtist(artist),
score: matchScore(artist.name, queryText, terms),
score: matchScore(artist.name, queryText),
}))
.filter((result) => result.score > 0)
.sort(
@@ -708,8 +686,8 @@ export const searchLibrary = query({
return []
}
const score = Math.max(
matchScore(album.name, queryText, terms),
matchScore(artist.name, queryText, terms)
matchScore(album.name, queryText),
matchScore(artist.name, queryText)
)
if (score === 0) {
return []
@@ -734,10 +712,10 @@ export const searchLibrary = query({
return []
}
const score = Math.max(
matchScore(song.name, queryText, terms),
matchScoreSongArtists(song.artist, queryText, terms),
matchScore(album.name, queryText, terms),
matchScore(albumArtist.name, queryText, terms)
matchScore(song.name, queryText),
matchScoreSongArtists(song.artist, queryText),
matchScore(album.name, queryText),
matchScore(albumArtist.name, queryText)
)
if (score === 0) {
return []
@@ -754,25 +732,6 @@ export const searchLibrary = query({
(a, b) => b.score - a.score || a.item.title.localeCompare(b.item.title)
)
const songById = new Map(songs.map((song) => [song._id, song]))
const matchedSongIds = new Set(songResults.map((result) => result.item.id))
const lyricsResults: SearchSong[] = (
await searchSongLyrics(ctx, args.query, MAX_LYRICS_SEARCH_RESULTS)
).flatMap(({ song: songId, snippet }) => {
const song = songById.get(songId)
const album = song && albumMap.get(song.album)
const albumArtist = song && artistMap.get(song.albumArtist)
if (!song || !album || !albumArtist || matchedSongIds.has(songId)) {
return []
}
return [
{
...toBrowseSong(song, album, albumArtist),
lyricsSnippet: snippet,
},
]
})
const topResults: SearchTopResultItem[] = [
...songResults,
...albumResults,
@@ -790,10 +749,9 @@ export const searchLibrary = query({
albums: albumResults
.slice(0, MAX_SEARCH_RESULTS)
.map((result) => result.item),
songs: [
...songResults.map((result): SearchSong => result.item),
...lyricsResults,
].slice(0, MAX_SEARCH_RESULTS),
songs: songResults
.slice(0, MAX_SEARCH_RESULTS)
.map((result) => result.item),
}
return result
},
@@ -976,12 +934,11 @@ export const scanSongsPage = internalQuery({
const result = await ctx.db.query("songs").paginate(args.paginationOpts)
return {
...result,
page: result.page.map(({ _id, name, files, album, hasLyrics }) => ({
page: result.page.map(({ _id, name, files, album }) => ({
_id,
name,
files,
album,
hasLyrics,
})),
}
},
@@ -1143,8 +1100,6 @@ export const importAlbums = internalMutation({
year: v.number(),
date: v.string(),
genres: v.array(v.string()),
/** The best lyrics tag among the song's files. */
lyrics: v.nullable(v.string()),
})
),
})
@@ -1175,7 +1130,7 @@ export const importAlbums = internalMutation({
)?._id ??
(await ctx.db.insert("albums", { ...entry.album, artist: artistId }))
for (const { lyrics, ...song } of entry.songs) {
for (const song of entry.songs) {
const existing = await ctx.db
.query("songs")
.withIndex("by_all", (q) =>
@@ -1191,12 +1146,11 @@ export const importAlbums = internalMutation({
})
continue
}
const songId = await ctx.db.insert("songs", {
await ctx.db.insert("songs", {
...song,
album: albumId,
albumArtist: artistId,
})
await writeSongLyrics(ctx, songId, lyrics)
}
}
},
@@ -1208,7 +1162,6 @@ export const deleteSongs = internalMutation({
handler: async (ctx, args) => {
for (const id of args.ids) {
await ctx.db.delete("songs", id)
await deleteSongLyrics(ctx, id)
}
await purgeSongsFromUsersAndPlaylists(ctx, new Set(args.ids))
await recordIntentCatalogChanges(ctx, "song", args.ids, true)
-129
View File
@@ -1,129 +0,0 @@
import { getAuthUserId } from "@convex-dev/auth/server"
import { v } from "convex/values"
import type { Id } from "./_generated/dataModel"
import {
internalMutation,
query,
type MutationCtx,
type QueryCtx,
} from "./_generated/server"
import { matchLyrics, parseLyrics, plainLyrics } from "../client/lyrics"
/** Shorter searches match too much of every song to be useful. */
const MIN_LYRICS_QUERY_LENGTH = 3
/** The largest page a search index returns. */
const MAX_LYRICS_MATCHES = 1_024
/**
* Replaces a song's lyrics, or removes them when `text` is null or holds no
* lyrics, and marks the song as read for lyrics.
*/
export async function writeSongLyrics(
ctx: MutationCtx,
songId: Id<"songs">,
text: string | null
) {
const lyrics = text ? parseLyrics(text) : null
const [stored, searchable] = await Promise.all([
ctx.db
.query("lyrics")
.withIndex("by_song", (q) => q.eq("song", songId))
.first(),
ctx.db
.query("lyricsSearch")
.withIndex("by_song", (q) => q.eq("song", songId))
.first(),
])
await ctx.db.patch("songs", songId, { hasLyrics: lyrics !== null })
if (!lyrics || !text) {
if (stored) await ctx.db.delete("lyrics", stored._id)
if (searchable) await ctx.db.delete("lyricsSearch", searchable._id)
return
}
const plain = plainLyrics(lyrics)
if (stored) await ctx.db.patch("lyrics", stored._id, { text })
else await ctx.db.insert("lyrics", { song: songId, text })
if (searchable) await ctx.db.patch("lyricsSearch", searchable._id, { plain })
else await ctx.db.insert("lyricsSearch", { song: songId, plain })
}
/** Removes a deleted song's lyrics. */
export async function deleteSongLyrics(ctx: MutationCtx, songId: Id<"songs">) {
for (const table of ["lyrics", "lyricsSearch"] as const) {
const row = await ctx.db
.query(table)
.withIndex("by_song", (q) => q.eq("song", songId))
.first()
if (row) await ctx.db.delete(table, row._id)
}
}
/**
* Up to `limit` songs with a lyrics line matching `query` (see `matchLyrics`),
* with that line, best matches first. The search index matches any word
* anywhere in the lyrics and ranks common words poorly, so its whole page is
* checked line by line before trimming.
*/
export async function searchSongLyrics(
ctx: QueryCtx,
query: string,
limit: number
): Promise<{ song: Id<"songs">; snippet: string }[]> {
const text = query.trim()
if (text.length < MIN_LYRICS_QUERY_LENGTH) return []
const rows = await ctx.db
.query("lyricsSearch")
.withSearchIndex("search_plain", (q) => q.search("plain", text))
.take(MAX_LYRICS_MATCHES)
return rows
.flatMap((row) => {
const match = matchLyrics(row.plain, text)
return match ? [{ song: row.song, ...match }] : []
})
.sort((a, b) => b.score - a.score)
.slice(0, limit)
.map(({ song, snippet }) => ({ song, snippet }))
}
/** The song's lyrics tag (see `client/lyrics.ts`), or null without lyrics. */
export const forSong = query({
args: { id: v.id("songs") },
handler: async (ctx, args): Promise<string | null> => {
if ((await getAuthUserId(ctx)) === null) return null
const row = await ctx.db
.query("lyrics")
.withIndex("by_song", (q) => q.eq("song", args.id))
.first()
return row?.text ?? null
},
})
/** Songs whose lyrics match a search, so in-list filters can include them. */
export const matchingSongIds = query({
args: { query: v.string() },
handler: async (ctx, args): Promise<Id<"songs">[]> => {
if ((await getAuthUserId(ctx)) === null) return []
const matches = await searchSongLyrics(ctx, args.query, MAX_LYRICS_MATCHES)
return matches.map((match) => match.song)
},
})
/** Stores lyrics the library scan read from files; null marks none found. */
export const setSongLyrics = internalMutation({
args: {
songs: v.array(
v.object({ id: v.id("songs"), lyrics: v.nullable(v.string()) })
),
},
handler: async (ctx, args) => {
for (const song of args.songs) {
// The song may have been deleted since the scan read it.
if (await ctx.db.get("songs", song.id)) {
await writeSongLyrics(ctx, song.id, song.lyrics)
}
}
},
})
-17
View File
@@ -140,28 +140,11 @@ export default defineSchema({
year: v.number(),
date: v.string(),
genres: v.array(v.string()),
/**
* Whether the files have a lyrics tag, stored in `lyrics`. Unset until the
* library scan has read the files for lyrics.
*/
hasLyrics: v.optional(v.boolean()),
})
.index("by_name", ["name"])
.index("by_artist", ["albumArtist"])
.index("by_album", ["album"])
.index("by_all", ["name", "albumArtist", "album"]),
/** A song's lyrics tag as written in its file: plain, LRC, or word-timed LRC. */
lyrics: defineTable({
song: v.id("songs"),
text: v.string(),
}).index("by_song", ["song"]),
/** The same lyrics without timestamps. Kept apart so search reads only this. */
lyricsSearch: defineTable({
song: v.id("songs"),
plain: v.string(),
})
.index("by_song", ["song"])
.searchIndex("search_plain", { searchField: "plain" }),
playlists: defineTable({
name: v.string(),
owner: v.id("users"),
+1 -5
View File
@@ -95,15 +95,11 @@ export type SearchTopResultItem =
| { kind: "album"; item: BrowseAlbum }
| { kind: "artist"; item: BrowseArtist }
/** A song search result. Songs found only by their lyrics carry the matched line. */
export type SearchSong = BrowseSong & { lyricsSnippet?: string }
export type LibrarySearchResults = {
topResults: SearchTopResultItem[]
artists: BrowseArtist[]
albums: BrowseAlbum[]
/** Title, artist and album matches, then lyrics matches. */
songs: SearchSong[]
songs: BrowseSong[]
}
export type QueueSong = BrowseSong & { queueIndex: number }
+3 -10
View File
@@ -2,7 +2,6 @@ import type { PlaybackSource, PlaybackStreamPlan } from "./playback-stream"
/** Qualities a listener can pick when downloading, lowest first. */
export const DOWNLOAD_QUALITIES = [
"low",
"medium",
"high",
"lossless",
@@ -12,7 +11,6 @@ export const DOWNLOAD_QUALITIES = [
export type DownloadQuality = (typeof DOWNLOAD_QUALITIES)[number]
export const DOWNLOAD_QUALITY_LABELS: Record<DownloadQuality, string> = {
low: "Low",
medium: "Medium",
high: "High",
lossless: "Lossless",
@@ -20,14 +18,12 @@ export const DOWNLOAD_QUALITY_LABELS: Record<DownloadQuality, string> = {
}
export const DOWNLOAD_QUALITY_DETAILS: Record<DownloadQuality, string> = {
low: "AAC 64 kbps",
medium: "AAC 128 kbps",
high: "AAC 256 kbps",
lossless: "ALAC or FLAC",
atmos: "Spatial audio",
}
const LOW_KBPS = 64
const MEDIUM_KBPS = 128
const HIGH_KBPS = 256
@@ -58,14 +54,13 @@ function highPlan(files: Record<string, unknown>): DownloadPlan {
/**
* Picks the file for one song. Lossless and Dolby Atmos fall back to High when
* the song lacks them, and Low and Medium are always transcoded.
* the song lacks them, and Medium is always transcoded.
*/
export function downloadPlan(
files: Record<string, unknown>,
quality: DownloadQuality
): DownloadPlan {
switch (quality) {
case "low":
case "medium":
return {
quality,
@@ -75,7 +70,7 @@ export function downloadPlan(
: "normal" in files
? "normal"
: "atmos",
kbps: quality === "low" ? LOW_KBPS : MEDIUM_KBPS,
kbps: MEDIUM_KBPS,
}
case "high":
return highPlan(files)
@@ -89,7 +84,7 @@ export function downloadPlan(
/**
* The download quality holding the same audio a stream plan plays, so a
* download can stand in for streaming.
* download can stand in for streaming. Low has no download equivalent.
*/
export function streamDownloadQuality(
plan: PlaybackStreamPlan
@@ -100,7 +95,6 @@ export function streamDownloadQuality(
}
if (plan.kbps === HIGH_KBPS) return "high"
if (plan.kbps === MEDIUM_KBPS) return "medium"
if (plan.kbps === LOW_KBPS) return "low"
return undefined
}
@@ -135,7 +129,6 @@ export function downloadOptions(
).length
if (
fallbackCount === songs.length &&
quality !== "low" &&
quality !== "medium" &&
quality !== "high"
) {
-8
View File
@@ -51,14 +51,6 @@
"types": "./client/favorites.ts",
"default": "./client/favorites.ts"
},
"./client/lyrics": {
"types": "./client/lyrics.ts",
"default": "./client/lyrics.ts"
},
"./client/lyrics-tags": {
"types": "./client/lyrics-tags.ts",
"default": "./client/lyrics-tags.ts"
},
"./client/media-links": {
"types": "./client/media-links.ts",
"default": "./client/media-links.ts"
-43
View File
@@ -279,9 +279,6 @@ importers:
'@react-native-community/slider':
specifier: 5.2.1
version: 5.2.1(patch_hash=73deacaea9aae000a42050d343517da9e16e736e92a4fff3f61f81dba093a1c4)
'@react-native-masked-view/masked-view':
specifier: 0.3.2
version: 0.3.2(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)
'@react-native/metro-config':
specifier: 0.88.0
version: 0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)
@@ -366,18 +363,12 @@ importers:
react-native:
specifier: 0.88.0
version: 0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1)
react-native-continued-task:
specifier: 0.1.0
version: 0.1.0(react-native-nitro-modules@0.37.2(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)
react-native-gesture-handler:
specifier: ~3.3.0
version: 3.3.0(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)
react-native-image-colors:
specifier: ^2.6.0
version: 2.6.0(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)(supports-color@8.1.1)
react-native-nitro-modules:
specifier: 0.37.2
version: 0.37.2(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)
react-native-reanimated:
specifier: 4.7.1
version: 4.7.1(patch_hash=badfed6babfff7fa495b3a06ba8f324be0e5ff82cedb6084f9f4d1dad65984d3)(react-native-worklets@0.13.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)(supports-color@8.1.1))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)
@@ -5447,9 +5438,6 @@ packages:
sass:
optional: true
nitro-core@0.37.2:
resolution: {integrity: sha512-dhagikz9VXXzfidRH/vPNJfYWPmTBArDOo9wE/wEqeERU9C8uRWz9YccOyNUOvADccPAZq319yzhDMoJ9excSQ==}
node-exports-info@1.6.2:
resolution: {integrity: sha512-kXs9Go0cah0qHVV2v389IXQLdLCeE1xfFtjOAF+iobu0OIoG1pje8At2vMHyaPMiPMnG/LWP50twML21eMcAag==}
engines: {node: '>= 0.4'}
@@ -5901,16 +5889,6 @@ packages:
react-is@19.2.7:
resolution: {integrity: sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A==}
react-native-continued-task@0.1.0:
resolution: {integrity: sha512-6x9YesK++u6vraaReebWEKbcDjMeRInsQzd+uWXAbNiXasgZ2zulTextzK/zBZ2mBrCZqTZVK60eoPp07BF0MA==}
peerDependencies:
react: '*'
react-native: '*'
react-native-nitro-modules: '*'
peerDependenciesMeta:
react-native-nitro-modules:
optional: true
react-native-drawer-layout@4.2.12:
resolution: {integrity: sha512-qYmntEctkMSodN7pnC2llV21nswImLFPHJeT3PJXSJqZdU4jzDATR8iVi66sXkrtoOLJ2+EvXxgd7sMMpV4ViA==}
peerDependencies:
@@ -5938,12 +5916,6 @@ packages:
react: '*'
react-native: '*'
react-native-nitro-modules@0.37.2:
resolution: {integrity: sha512-Odnrq/p6/q0R01qZlkqeXu9VHHMuGEnZZmyxMvehEu6QiACNHhBCmAHgyBDqOSo9Lb3G0TscFAT+HG0uxsR/GA==}
peerDependencies:
react: '*'
react-native: '*'
react-native-reanimated@4.7.1:
resolution: {integrity: sha512-HviDFSZ6V4KTRsrLS6hRbBJ4j63l/L8a5az0EoWdJwaMLYnBNyYISTDxwXpEYkMbAbLzCMCviIdiOxXHYQWcNA==}
peerDependencies:
@@ -12501,8 +12473,6 @@ snapshots:
- '@types/node'
- babel-plugin-macros
nitro-core@0.37.2: {}
node-exports-info@1.6.2:
dependencies:
array.prototype.flatmap: 1.3.3
@@ -12966,13 +12936,6 @@ snapshots:
react-is@19.2.7: {}
react-native-continued-task@0.1.0(react-native-nitro-modules@0.37.2(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0):
dependencies:
react: 19.3.0
react-native: 0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1)
optionalDependencies:
react-native-nitro-modules: 0.37.2(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)
react-native-drawer-layout@4.2.12(309f9235979e0472ca5a2d24f8d225b6):
dependencies:
color: 4.2.3
@@ -13004,12 +12967,6 @@ snapshots:
react: 19.3.0
react-native: 0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1)
react-native-nitro-modules@0.37.2(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0):
dependencies:
nitro-core: 0.37.2
react: 19.3.0
react-native: 0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1)
react-native-reanimated@4.7.1(patch_hash=badfed6babfff7fa495b3a06ba8f324be0e5ff82cedb6084f9f4d1dad65984d3)(react-native-worklets@0.13.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)(supports-color@8.1.1))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0):
dependencies:
react: 19.3.0