Merge remote-tracking branch 'origin/main' into pr94

# Conflicts:
#	apps/mobile/hooks/use-cover-palette.ts
This commit is contained in:
joshuafhiggins committed 2026-11-16 21:45:19 -05:00 Verified
commit e218a4a436
14 files changed
+442 -334

No files matched your search

+5 -6
View File
@@ -54,12 +54,11 @@ playwright.config.*
*~
*.log
# Environment variables (only commit template files)
.env
.env*.local
.env.development
.env.test
.env.production.local
# Environment variables, in any workspace. Next.js inlines NEXT_PUBLIC_* values
# into the bundle and the Convex CLI reads .env.local on deploy.
**/.env
**/.env.*
!**/.env.example
# Docker configuration files (not needed inside build context)
Dockerfile*
+6 -1
View File
@@ -195,7 +195,12 @@ RUN node --version \
&& ldd /convex/generate_key \
&& ! ldd /convex/convex-local-backend /convex/generate_key | grep -q 'not found'
RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes
# The backend gets its own user so the web server cannot read the database or
# instance secret. It joins the otunes group to clean up the web server's HLS
# cache in /tmp/otunes.
RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes \
&& useradd --system --user-group --groups otunes --create-home --home-dir /home/convex \
--shell /usr/sbin/nologin convex
COPY --from=convex-functions /app /opt/otunes/convex
COPY docker/generate-auth-keys.mjs /opt/otunes/generate-auth-keys.mjs
@@ -488,7 +488,7 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
action: MediaAction
) => Promise<void>
}) {
const Row = Platform.OS === "ios" ? SongSwipeRow : Pressable
const Row = Platform.OS !== "web" ? SongSwipeRow : Pressable
const { config } = useServerConfig()
return (
<MediaContextMenu
@@ -523,6 +523,7 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
group={swipeGroup}
backgroundColor={palette.background}
onPlayNext={() => void onAction(track, album, "play-next")}
onAddToQueue={() => void onAction(track, album, "play-last")}
style={styles.trackRow}
onPress={() => void onPlay(track.id as Id<"songs">, songIds)}
>
@@ -433,11 +433,18 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
palette={palette}
inset
swipe={
Platform.OS === "ios"
Platform.OS !== "web"
? {
group: swipeGroup,
backgroundColor: palette.background,
onPlayNext: () => onAction(song, "play-next"),
onAddToQueue: () => onAction(song, "play-last"),
onRemove:
Platform.OS === "android" && removable
? () => {
void onRemove(song.id)
}
: undefined,
}
: undefined
}
@@ -446,7 +453,7 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
/>
)
if (Platform.OS === "ios" || !removable) {
if (Platform.OS !== "web" || !removable) {
return row
}
@@ -23,7 +23,6 @@ import { useServerConfig } from "@/contexts/server-config"
import {
setArtworkColorsEnabled,
useArtworkColorsEnabled,
useArtworkColorPreferenceLoaded,
} from "@/lib/artwork-color-preference"
import { initialsFromName } from "@/lib/format"
import { useCachedQuery } from "@/hooks/use-cached-query"
@@ -172,7 +171,6 @@ export default function SettingsScreen() {
function AppearanceSection() {
const enabled = useArtworkColorsEnabled()
const loaded = useArtworkColorPreferenceLoaded()
const [saving, setSaving] = useState(false)
return (
@@ -180,8 +178,8 @@ function AppearanceSection() {
<SwitchRow
title="New artwork colors"
subtitle="Use the new color algorithm on this device."
value={enabled}
disabled={!loaded || saving}
value={enabled ?? false}
disabled={enabled === undefined || saving}
onValueChange={async (checked) => {
setSaving(true)
try {
+7 -1
View File
@@ -45,6 +45,8 @@ export const SongRow = memo(function SongRow({
swipe?: {
group: SwipeRowGroup
onPlayNext: () => void
onAddToQueue: () => void
onRemove?: () => void
backgroundColor: string
}
/** Album/playlist layout: the divider starts at the title, not the artwork. */
@@ -107,10 +109,12 @@ export const SongRow = memo(function SongRow({
? styles.insetRow
: [styles.row, { borderBottomColor: divider }]
const row =
swipe && Platform.OS === "ios" ? (
swipe && Platform.OS !== "web" ? (
<SongSwipeRow
group={swipe.group}
onPlayNext={swipe.onPlayNext}
onAddToQueue={swipe.onAddToQueue}
onRemove={swipe.onRemove}
backgroundColor={swipe.backgroundColor}
onPress={onPress}
style={rowStyle}
@@ -167,6 +171,8 @@ export const SongListRow = memo(function SongListRow({
swipe?: {
group: SwipeRowGroup
onPlayNext: () => void
onAddToQueue: () => void
onRemove?: () => void
backgroundColor: string
}
onPlay: (song: BrowseSong) => void
+160 -31
View File
@@ -1,3 +1,4 @@
import { Ionicons } from "@expo/vector-icons"
import * as Haptics from "expo-haptics"
import { SymbolView } from "expo-symbols"
import {
@@ -8,6 +9,7 @@ import {
type ReactNode,
} from "react"
import {
Platform,
Pressable,
StyleSheet,
type StyleProp,
@@ -26,7 +28,10 @@ import Animated, {
import { scheduleOnRN } from "react-native-worklets"
import type { SwipeRowGroup } from "@/components/ios-swipe-to-remove-row"
const IS_ANDROID = Platform.OS === "android"
const ACTION_WIDTH = 82
const LEADING_ACTION_WIDTH = 72
const SPRING = { duration: 450, dampingRatio: 1 }
function impact() {
@@ -41,6 +46,8 @@ export function SongSwipeRow({
group,
onPress,
onPlayNext,
onAddToQueue,
onRemove,
}: {
children: ReactNode
style?: StyleProp<ViewStyle>
@@ -48,7 +55,10 @@ export function SongSwipeRow({
group: SwipeRowGroup
onPress?: () => void
onPlayNext: () => void
onAddToQueue: () => void
onRemove?: () => void
}) {
const hasRemove = IS_ANDROID && !!onRemove
const x = useSharedValue(0)
const startX = useSharedValue(0)
const width = useSharedValue(0)
@@ -78,10 +88,10 @@ export function SongSwipeRow({
const activate = useCallback(
(side: number) => {
close()
if (side > 0) onPlayNext()
if (side > 0) onAddToQueue()
// Download is intentionally a placeholder.
},
[close, onPlayNext]
[close, onAddToQueue]
)
const tapRow = useCallback(() => {
if (open) close()
@@ -105,7 +115,13 @@ export function SongSwipeRow({
Math.min(width.value, startX.value + event.translationX)
)
const commit =
Math.abs(x.value) > Math.max(ACTION_WIDTH, width.value * 0.55)
Math.abs(x.value) >
Math.max(
x.value > 0
? LEADING_ACTION_WIDTH * 2
: ACTION_WIDTH * (hasRemove ? 2 : 1),
width.value * 0.55
)
if (commit !== committed.value) {
committed.value = commit
commitProgress.value = withSpring(commit ? 1 : 0, SPRING)
@@ -124,10 +140,16 @@ export function SongSwipeRow({
Math.abs(x.value) > 10 && projected * side > ACTION_WIDTH / 2
? side
: 0
x.value = withSpring(target * ACTION_WIDTH, {
...SPRING,
velocity: event.velocityX,
})
x.value = withSpring(
target *
(target > 0
? LEADING_ACTION_WIDTH * 2
: ACTION_WIDTH * (hasRemove ? 2 : 1)),
{
...SPRING,
velocity: event.velocityX,
}
)
scheduleOnRN(settle, target)
})
.onFinalize((_event, success) => {
@@ -145,6 +167,7 @@ export function SongSwipeRow({
return Gesture.Exclusive(pan, tap)
}, [
activate,
hasRemove,
begin,
close,
commitProgress,
@@ -158,12 +181,14 @@ export function SongSwipeRow({
const rowStyle = useAnimatedStyle(() => ({
transform: [{ translateX: x.value }],
borderRadius: interpolate(
Math.abs(x.value),
[0, 40],
[0, height.value / 2],
Extrapolation.CLAMP
),
borderRadius: IS_ANDROID
? 0
: interpolate(
Math.abs(x.value),
[0, 40],
[0, height.value / 2],
Extrapolation.CLAMP
),
}))
const fillStyle = useAnimatedStyle(() => ({
opacity: interpolate(
@@ -190,8 +215,37 @@ export function SongSwipeRow({
open={open === 1}
onPress={() => activate(1)}
/>
<SwipeAction
side={1}
secondary
x={x}
height={height}
progress={commitProgress}
open={open === 1}
onPress={() => {
close()
onPlayNext()
}}
/>
{hasRemove && (
<SwipeAction
side={-1}
secondary
paired
remove
x={x}
height={height}
progress={commitProgress}
open={open === -1}
onPress={() => {
close()
onRemove?.()
}}
/>
)}
<SwipeAction
side={-1}
paired={hasRemove}
x={x}
height={height}
progress={commitProgress}
@@ -204,11 +258,23 @@ export function SongSwipeRow({
accessibilityRole="button"
onAccessibilityTap={tapRow}
accessibilityActions={[
{ name: "addToQueue", label: "Add to Queue" },
{ name: "playNext", label: "Play Next" },
{ name: "download", label: "Download" },
...(hasRemove
? [{ name: "remove", label: "Remove from Playlist" }]
: []),
]}
onAccessibilityAction={(event) => {
if (event.nativeEvent.actionName === "playNext") activate(1)
if (event.nativeEvent.actionName === "remove" && hasRemove) {
close()
onRemove?.()
}
if (event.nativeEvent.actionName === "addToQueue") activate(1)
if (event.nativeEvent.actionName === "playNext") {
close()
onPlayNext()
}
}}
style={[styles.row, { backgroundColor }, rowStyle]}
>
@@ -225,6 +291,9 @@ export function SongSwipeRow({
function SwipeAction({
side,
secondary = false,
paired = side > 0,
remove = false,
x,
height,
progress,
@@ -232,22 +301,48 @@ function SwipeAction({
onPress,
}: {
side: 1 | -1
secondary?: boolean
paired?: boolean
remove?: boolean
x: SharedValue<number>
height: SharedValue<number>
progress: SharedValue<number>
open: boolean
onPress: () => void
}) {
const actionStyle = useAnimatedStyle(() => ({
width: Math.max(0, x.value * side),
}))
const pillStyle = useAnimatedStyle(() => {
const actionStyle = useAnimatedStyle(() => {
const revealed = Math.max(0, x.value * side)
const primaryWidth = (revealed * (1 + progress.value)) / 2
return {
width: !paired
? revealed
: secondary
? revealed - primaryWidth
: primaryWidth,
...(secondary
? side > 0
? { left: primaryWidth }
: { right: primaryWidth }
: {}),
}
})
const pillStyle = useAnimatedStyle(() => {
const total = Math.max(0, x.value * side)
const revealed = !paired
? total
: (total * (secondary ? 1 - progress.value : 1 + progress.value)) / 2
if (IS_ANDROID) {
return { width: revealed, height: height.value, borderRadius: 0 }
}
const resting = Math.max(
0,
Math.min(
revealed - 20,
interpolate(revealed, [24, ACTION_WIDTH, 220], [0, 62, 200])
revealed - (side > 0 ? 10 : 20),
interpolate(
revealed,
[24, side > 0 ? LEADING_ACTION_WIDTH : ACTION_WIDTH, 220],
[0, 62, 200]
)
)
)
const pillWidth =
@@ -292,27 +387,61 @@ function SwipeAction({
>
<Pressable
accessibilityRole="button"
accessibilityLabel={side > 0 ? "Play Next" : "Download"}
accessibilityLabel={
remove
? "Remove from Playlist"
: side > 0
? secondary
? "Play Next"
: "Add to Queue"
: "Download"
}
onPress={onPress}
style={styles.actionButton}
>
<Animated.View
style={[
styles.pill,
{ backgroundColor: side > 0 ? "#6b5bff" : "#008dff" },
{
backgroundColor: remove
? "#d32f2f"
: side > 0
? secondary
? "#6b5bff"
: "#f29943"
: "#008dff",
},
pillStyle,
]}
>
<Animated.View style={iconStyle}>
<SymbolView
name={
side > 0
? "text.line.first.and.arrowtriangle.forward"
: "arrow.down"
}
size={22}
tintColor="white"
/>
{IS_ANDROID ? (
<Ionicons
name={
remove
? "trash-outline"
: side < 0
? "arrow-down"
: secondary
? "play-forward"
: "list"
}
size={22}
color="white"
/>
) : (
<SymbolView
name={
side > 0
? secondary
? "text.line.first.and.arrowtriangle.forward"
: "text.line.last.and.arrowtriangle.forward"
: "arrow.down"
}
size={22}
tintColor="white"
/>
)}
</Animated.View>
</Animated.View>
</Pressable>
+11 -3
View File
@@ -376,7 +376,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
const handlePlaylistStatusUpdate = useCallback(
(status: AudioPlaylistStatus) => {
if (!status.isLoaded) return
// iOS may remove the finished item before delivering its final status.
if (!status.isLoaded && !status.didJustFinish) return
const state = storeRef.current.getState()
if (loadedSongIdsRef.current[status.currentIndex] !== state.queue[0]) {
return
@@ -427,7 +428,14 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
isPlayingRef.current = false
setIsPlayingState(false)
storeRef.current.update(playbackQueue.skipNext)
void playlistRef.current?.seekTo(0)
const playlist = playlistRef.current
if (playlist) {
playlist.pause()
// Reload the final item, which iOS removes when playback ends.
ignoreTrackChangeRef.current = true
playlist.skipTo(status.currentIndex)
scheduleTrackChangeHandling()
}
currentTimeRef.current = 0
setCurrentTime(0)
return
@@ -443,7 +451,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
playlist?.play()
}
},
[]
[scheduleTrackChangeHandling]
)
const handleTrackChanged = useCallback(
+142
View File
@@ -0,0 +1,142 @@
import { useEffect, useMemo, useState } from "react"
import { themeCoverPalette, type CoverPalette } from "@/lib/cover-palette"
import { readCache, writeCache } from "@/lib/persistent-cache"
import { useIsDark, useThemeColors } from "@/lib/theme"
import { withCoverImageSize } from "@/lib/urls"
// How long a screen holds its skeleton for the first extraction of a cover,
// so rows render once with final colors instead of flashing from the theme.
export const COVER_PALETTE_WAIT_MS = 400
export type CoverPaletteResult = { palette: CoverPalette; settled: boolean }
type CoverPaletteSourceOptions<Swatches> = {
/** Persistent cache key for a 64px cover URI. */
cacheKey: (colorSourceUri: string) => string
extract: (colorSourceUri: string) => Promise<Swatches | null>
derive: (swatches: Swatches, isDark: boolean) => CoverPalette | null
/** Reject persisted entries written in an older shape. */
isValidCache?: (swatches: Swatches) => boolean
}
/**
* One artwork color pipeline: an extractor and palette derivation with their
* own memory cache, persistent cache and in-flight requests.
*/
export function createCoverPaletteSource<Swatches>({
cacheKey,
extract,
derive,
isValidCache,
}: CoverPaletteSourceOptions<Swatches>) {
const swatchesByKey = new Map<string, Swatches | null>()
const pending = new Map<string, Promise<Swatches | null>>()
function cachedSwatches(key: string): Swatches | null | undefined {
if (swatchesByKey.has(key)) return swatchesByKey.get(key)
const cached = readCache<Swatches>(cacheKey(key))
return cached && isValidCache && !isValidCache(cached) ? undefined : cached
}
function extractSwatches(key: string) {
const inFlight = pending.get(key)
if (inFlight) return inFlight
const request = extract(key)
.catch(() => null)
.then((swatches) => {
swatchesByKey.set(key, swatches)
if (swatches) writeCache(cacheKey(key), swatches)
pending.delete(key)
return swatches
})
pending.set(key, request)
return request
}
function prefetch(uri: string) {
const key = withCoverImageSize(uri, 64)
if (cachedSwatches(key) !== undefined) return
void extractSwatches(key)
}
/**
* Colors for a screen tinted by `uri`'s cover art. Pass `uri` as "" to skip
* extraction. Pass `hasCover` as `undefined` while it isn't known yet so
* extraction can start early.
*
* `settled` turns true once the palette is final or after
* `COVER_PALETTE_WAIT_MS`, whichever comes first.
*/
function usePalette(
uri: string,
hasCover: boolean | undefined
): CoverPaletteResult {
const theme = useThemeColors()
const isDark = useIsDark()
const key = uri ? withCoverImageSize(uri, 64) : ""
const [resolved, setResolved] = useState(() => ({
key,
swatches: key ? cachedSwatches(key) : null,
}))
const [waitedKey, setWaitedKey] = useState<string | null>(null)
const swatches =
resolved.key === key ? resolved.swatches : key ? cachedSwatches(key) : null
useEffect(() => {
if (!key || hasCover === false) return
let cancelled = false
const known = cachedSwatches(key)
const show = (next: Swatches | null) =>
setResolved((prev) =>
prev.key === key && sameSwatches(prev.swatches, next)
? prev
: { key, swatches: next }
)
if (known !== undefined && swatchesByKey.has(key)) {
show(known)
return
}
// Persisted swatches render immediately; refresh them in the background
// in case the cover changed.
const timer =
known === undefined
? setTimeout(
() => !cancelled && setWaitedKey(key),
COVER_PALETTE_WAIT_MS
)
: null
void extractSwatches(key).then((next) => {
if (!cancelled) show(next ?? known ?? null)
})
return () => {
cancelled = true
if (timer) clearTimeout(timer)
}
}, [hasCover, key])
const palette = useMemo(() => {
const fromArt =
hasCover !== false && swatches ? derive(swatches, isDark) : null
return fromArt ?? themeCoverPalette(theme, isDark)
}, [hasCover, isDark, swatches, theme])
return {
palette,
settled:
!key ||
hasCover === false ||
swatches !== undefined ||
waitedKey === key,
}
}
return { prefetch, usePalette }
}
function sameSwatches(a: unknown, b: unknown) {
return a === b || JSON.stringify(a) === JSON.stringify(b)
}
+28 -129
View File
@@ -1,148 +1,47 @@
import { useEffect, useMemo, useState } from "react"
import {
artworkColorsEnabled,
useArtworkColorsEnabled,
} from "@/lib/artwork-color-preference"
createCoverPaletteSource,
type CoverPaletteResult,
} from "@/hooks/cover-palette-source"
import {
prefetchLegacyCoverPalette,
useLegacyCoverPalette,
} from "@/hooks/use-legacy-cover-palette"
import { extractCoverSwatches } from "@/lib/artwork-colors"
import {
deriveCoverPalette,
themeCoverPalette,
type CoverPalette,
type CoverSwatches,
} from "@/lib/cover-palette"
import { readCache, writeCache } from "@/lib/persistent-cache"
import { useIsDark, useThemeColors } from "@/lib/theme"
import { withCoverImageSize } from "@/lib/urls"
loadArtworkColorsEnabled,
useArtworkColorsEnabled,
} from "@/lib/artwork-color-preference"
import { extractCoverSwatches } from "@/lib/artwork-colors"
import { deriveCoverPalette, type CoverSwatches } from "@/lib/cover-palette"
// How long a screen holds its skeleton for the first extraction of a cover,
// so rows render once with final colors instead of flashing from the theme.
export const COVER_PALETTE_WAIT_MS = 400
export { COVER_PALETTE_WAIT_MS } from "@/hooks/cover-palette-source"
const swatchesByKey = new Map<string, CoverSwatches | null>()
const pending = new Map<string, Promise<CoverSwatches | null>>()
function cacheKey(colorSourceUri: string) {
return `palette:v2:${colorSourceUri}`
}
function sameSwatches(
a: CoverSwatches | null | undefined,
b: CoverSwatches | null | undefined
) {
return a === b || JSON.stringify(a) === JSON.stringify(b)
}
function cachedSwatches(key: string): CoverSwatches | null | undefined {
if (swatchesByKey.has(key)) return swatchesByKey.get(key)
return readCache<CoverSwatches>(cacheKey(key))
}
function extractSwatches(key: string) {
const inFlight = pending.get(key)
if (inFlight) return inFlight
const request = extractCoverSwatches(key)
.catch(() => null)
.then((swatches) => {
swatchesByKey.set(key, swatches)
if (swatches) writeCache(cacheKey(key), swatches)
pending.delete(key)
return swatches
})
pending.set(key, request)
return request
}
const region = createCoverPaletteSource<CoverSwatches>({
cacheKey: (colorSourceUri) => `palette:v2:${colorSourceUri}`,
extract: extractCoverSwatches,
derive: (swatches) => deriveCoverPalette(swatches),
})
/** Warm visible artwork colors before a detail page is pushed. */
export function prefetchCoverPalette(uri: string) {
if (!artworkColorsEnabled()) {
prefetchLegacyCoverPalette(uri)
return
}
const key = withCoverImageSize(uri, 64)
if (cachedSwatches(key) !== undefined) return
void extractSwatches(key)
void loadArtworkColorsEnabled().then((enabled) =>
enabled ? region.prefetch(uri) : prefetchLegacyCoverPalette(uri)
)
}
/**
* Colors for a screen tinted by `uri`'s cover art. Extraction runs once per
* cover and is cached on device. Pass `hasCover` as `undefined` while it isn't
* known yet so extraction can start early.
*
* `settled` turns true once the palette is final or after
* `COVER_PALETTE_WAIT_MS`, whichever comes first.
* Colors for a screen tinted by `uri`'s cover art, from whichever pipeline the
* device preference selects. Nothing is extracted until the preference loads,
* and the screen stays unsettled meanwhile so it doesn't flash theme colors.
*/
function useRegionCoverPalette(
export function useCoverPalette(
uri: string,
hasCover: boolean | undefined
): { palette: CoverPalette; settled: boolean } {
const theme = useThemeColors()
const isDark = useIsDark()
const key = uri ? withCoverImageSize(uri, 64) : ""
const [resolved, setResolved] = useState(() => ({
key,
swatches: key ? cachedSwatches(key) : null,
}))
const [waitedKey, setWaitedKey] = useState<string | null>(null)
const swatches =
resolved.key === key ? resolved.swatches : key ? cachedSwatches(key) : null
useEffect(() => {
if (!key || hasCover === false) return
let cancelled = false
const known = cachedSwatches(key)
const show = (next: CoverSwatches | null) =>
setResolved((prev) =>
prev.key === key && sameSwatches(prev.swatches, next)
? prev
: { key, swatches: next }
)
if (known !== undefined && swatchesByKey.has(key)) {
show(known)
return
}
// Persisted swatches render immediately; refresh them in the background in
// case the cover changed.
const timer =
known === undefined
? setTimeout(
() => !cancelled && setWaitedKey(key),
COVER_PALETTE_WAIT_MS
)
: null
void extractSwatches(key).then((next) => {
if (!cancelled) show(next ?? known ?? null)
})
return () => {
cancelled = true
if (timer) clearTimeout(timer)
}
}, [hasCover, key])
const palette = useMemo(() => {
const fromArt =
hasCover !== false && swatches ? deriveCoverPalette(swatches) : null
return fromArt ?? themeCoverPalette(theme, isDark)
}, [hasCover, isDark, swatches, theme])
return {
palette,
settled:
!key || hasCover === false || swatches !== undefined || waitedKey === key,
}
}
/** Switch both extraction and palette derivation without mixing their caches. */
export function useCoverPalette(uri: string, hasCover: boolean | undefined) {
): CoverPaletteResult {
const enabled = useArtworkColorsEnabled()
const region = useRegionCoverPalette(enabled ? uri : "", hasCover)
const legacy = useLegacyCoverPalette(enabled ? "" : uri, hasCover)
return enabled ? region : legacy
const current = region.usePalette(enabled === true ? uri : "", hasCover)
const legacy = useLegacyCoverPalette(enabled === false ? uri : "", hasCover)
if (enabled === undefined) {
return { palette: current.palette, settled: !uri || hasCover === false }
}
return enabled ? current : legacy
}
+21 -132
View File
@@ -1,29 +1,14 @@
import { useEffect, useMemo, useState } from "react"
import { getColors, type ImageColorsResult } from "react-native-image-colors"
import { createCoverPaletteSource } from "@/hooks/cover-palette-source"
import {
themeCoverPalette,
type CoverPalette,
} from "@/lib/cover-palette"
import { deriveCoverPalette, type LegacyCoverSwatches as CoverSwatches } from "@/lib/legacy-cover-palette"
import { readCache, writeCache } from "@/lib/persistent-cache"
import { useIsDark, useThemeColors } from "@/lib/theme"
import { withCoverImageSize } from "@/lib/urls"
// How long a screen holds its skeleton for the first extraction of a cover,
// so rows render once with final colors instead of flashing from the theme.
const COVER_PALETTE_WAIT_MS = 400
deriveCoverPalette,
type LegacyCoverSwatches as CoverSwatches,
} from "@/lib/legacy-cover-palette"
// image-colors substitutes this for swatches it couldn't find.
const MISSING = "#010203"
const swatchesByKey = new Map<string, CoverSwatches | null>()
const pending = new Map<string, Promise<CoverSwatches | null>>()
function cacheKey(colorSourceUri: string) {
return `palette:${colorSourceUri}`
}
function present(colors: (string | undefined)[]) {
return colors.filter(
(color): color is string => !!color && color.toLowerCase() !== MISSING
@@ -59,120 +44,24 @@ function toSwatches(result: ImageColorsResult): CoverSwatches | null {
}
}
function sameSwatches(
a: CoverSwatches | null | undefined,
b: CoverSwatches | null | undefined
) {
return a === b || JSON.stringify(a) === JSON.stringify(b)
}
function cachedSwatches(key: string): CoverSwatches | null | undefined {
if (swatchesByKey.has(key)) return swatchesByKey.get(key)
const cached = readCache<CoverSwatches>(cacheKey(key))
const legacy = createCoverPaletteSource<CoverSwatches>({
cacheKey: (colorSourceUri) => `palette:${colorSourceUri}`,
extract: (key) =>
getColors(key, {
fallback: MISSING,
cache: true,
key,
quality: "low",
pixelSpacing: 4,
}).then(toSwatches),
derive: deriveCoverPalette,
// Discard the background-only entries written by the tablet palette experiment.
return cached && (!Array.isArray(cached.text) || !Array.isArray(cached.accent))
? undefined
: cached
}
function extractSwatches(key: string) {
const inFlight = pending.get(key)
if (inFlight) return inFlight
const request = getColors(key, {
fallback: MISSING,
cache: true,
key,
quality: "low",
pixelSpacing: 4,
})
.then(toSwatches)
.catch(() => null)
.then((swatches) => {
swatchesByKey.set(key, swatches)
if (swatches) writeCache(cacheKey(key), swatches)
pending.delete(key)
return swatches
})
pending.set(key, request)
return request
}
isValidCache: (cached) =>
Array.isArray(cached.text) && Array.isArray(cached.accent),
})
/** Warm visible artwork colors before a detail page is pushed. */
export function prefetchLegacyCoverPalette(uri: string) {
const key = withCoverImageSize(uri, 64)
if (cachedSwatches(key) !== undefined) return
void extractSwatches(key)
}
export const prefetchLegacyCoverPalette = legacy.prefetch
/**
* Colors for a screen tinted by `uri`'s cover art. Extraction runs once per
* cover and is cached on device. Pass `hasCover` as `undefined` while it isn't
* known yet so extraction can start early.
*
* `settled` turns true once the palette is final or after
* `COVER_PALETTE_WAIT_MS`, whichever comes first.
*/
export function useLegacyCoverPalette(
uri: string,
hasCover: boolean | undefined
): { palette: CoverPalette; settled: boolean } {
const theme = useThemeColors()
const isDark = useIsDark()
const key = uri ? withCoverImageSize(uri, 64) : ""
const [resolved, setResolved] = useState(() => ({
key,
swatches: key ? cachedSwatches(key) : null,
}))
const [waitedKey, setWaitedKey] = useState<string | null>(null)
const swatches =
resolved.key === key ? resolved.swatches : key ? cachedSwatches(key) : null
useEffect(() => {
if (!key || hasCover === false) return
let cancelled = false
const known = cachedSwatches(key)
const show = (next: CoverSwatches | null) =>
setResolved((prev) =>
prev.key === key && sameSwatches(prev.swatches, next)
? prev
: { key, swatches: next }
)
if (known !== undefined && swatchesByKey.has(key)) {
show(known)
return
}
// Persisted swatches render immediately; refresh them in the background in
// case the cover changed.
const timer =
known === undefined
? setTimeout(
() => !cancelled && setWaitedKey(key),
COVER_PALETTE_WAIT_MS
)
: null
void extractSwatches(key).then((next) => {
if (!cancelled) show(next ?? known ?? null)
})
return () => {
cancelled = true
if (timer) clearTimeout(timer)
}
}, [hasCover, key])
const palette = useMemo(() => {
const fromArt =
hasCover !== false && swatches
? deriveCoverPalette(swatches, isDark)
: null
return fromArt ?? themeCoverPalette(theme, isDark)
}, [hasCover, isDark, swatches, theme])
return {
palette,
settled:
!key || hasCover === false || swatches !== undefined || waitedKey === key,
}
}
/** `react-native-image-colors` pipeline used when new artwork colors are off. */
export const useLegacyCoverPalette = legacy.usePalette
+21 -18
View File
@@ -3,8 +3,8 @@ import { useSyncExternalStore } from "react"
const STORAGE_KEY = "otunes:artwork-colors"
const listeners = new Set<() => void>()
let enabled = true
let loaded = false
// Undefined until storage has been read, so callers never act on a guess.
let enabled: boolean | undefined
let loading: Promise<void> | undefined
function notify() {
@@ -13,37 +13,40 @@ function notify() {
function load() {
return (loading ??= AsyncStorage.getItem(STORAGE_KEY)
.then((value) => value !== "false")
// Keep the default when local storage is unavailable.
.catch(() => true)
.then((value) => {
enabled = value !== "false"
})
.catch(() => {
// Keep the default when local storage is unavailable.
})
.finally(() => {
loaded = true
enabled = value
notify()
}))
}
void load()
function subscribe(listener: () => void) {
listeners.add(listener)
void load()
return () => {
listeners.delete(listener)
}
}
/** Device preference, kept outside account data and the disposable query cache. */
/**
* Device preference, kept outside account data and the disposable query cache.
* `undefined` until it has loaded.
*/
export function useArtworkColorsEnabled() {
return useSyncExternalStore(subscribe, () => loaded && enabled, () => false)
return useSyncExternalStore(
subscribe,
() => enabled,
() => undefined
)
}
export function useArtworkColorPreferenceLoaded() {
return useSyncExternalStore(subscribe, () => loaded, () => false)
}
export function artworkColorsEnabled() {
return loaded && enabled
/** Resolves with the preference once it has loaded. */
export async function loadArtworkColorsEnabled() {
await load()
return enabled ?? true
}
export async function setArtworkColorsEnabled(value: boolean) {
@@ -955,6 +955,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
if (!shouldContinuePlaying) {
autoPlayNextRef.current = false
isPlayingRef.current = false
audio.pause()
audio.currentTime = 0
currentTimeRef.current = 0
setCurrentTime(0)
+27 -6
View File
@@ -46,22 +46,34 @@ stop() {
}
trap 'stop; exit 0' TERM INT
as_convex=(setpriv --reuid=convex --regid=convex --init-groups env HOME=/home/convex)
convex_cli() {
(
cd "$FUNCTIONS_DIR"
unset CONVEX_DEPLOYMENT CONVEX_DEPLOY_KEY
CONVEX_SELF_HOSTED_URL="$BACKEND_URL" \
CONVEX_SELF_HOSTED_ADMIN_KEY="$admin_key" \
"$NODE" node_modules/convex/bin/main.js "$@"
"${as_convex[@]}" "$NODE" node_modules/convex/bin/main.js "$@"
)
}
# Only root (the backend) may read the database and instance secret.
# Only the convex user may read the database and instance secret. Volumes from
# images that ran the backend as root are still owned by root, and
# read_credentials.sh generates a new instance secret if it cannot read the old one.
mkdir -p "$CONVEX_DATA_DIR"
find "$CONVEX_DATA_DIR" \( ! -user convex -o ! -group convex \) \
-exec chown -h convex:convex {} +
chmod 700 "$CONVEX_DATA_DIR"
# The web server writes HLS streams here and a Convex cron deletes stale ones.
mkdir -p /tmp/otunes
chown otunes:otunes /tmp/otunes
chmod -R g+rwX /tmp/otunes
chmod g+s,o-rwx /tmp/otunes
log "Starting Convex backend"
(cd /convex && umask 077 && exec ./run_backend.sh) &
(cd /convex && umask 077 && exec "${as_convex[@]}" ./run_backend.sh) &
backend_pid=$!
for _ in $(seq 1 120); do
@@ -80,17 +92,24 @@ if ! curl -fsS "$BACKEND_URL/version" >/dev/null 2>&1; then
exit 1
fi
admin_key=$(cd /convex && ./generate_admin_key.sh)
admin_key=$(cd /convex && umask 077 && "${as_convex[@]}" ./generate_admin_key.sh)
log "Deploying Convex functions"
convex_cli deploy --typecheck disable --codegen disable
if [ -z "$(convex_cli env get JWKS 2>/dev/null || true)" ]; then
# `env get` exits 0 with no output when the variable is unset. Any other failure
# must not be read as "no keys": regenerating them signs every user out.
if ! jwks=$(convex_cli env get JWKS); then
log "Could not read Convex Auth signing keys"
stop
exit 1
fi
if [ -z "$jwks" ]; then
log "Generating Convex Auth signing keys"
"$NODE" /opt/otunes/generate-auth-keys.mjs | convex_cli env set --force
fi
unset admin_key
unset admin_key jwks
log "Starting web server"
(
@@ -100,6 +119,8 @@ log "Starting web server"
# Server-side Convex helpers fall back to this at runtime. The browser bundle
# is built without it, so browsers still derive their own URL.
export NEXT_PUBLIC_CONVEX_URL="$BACKEND_URL"
# Lets the convex group member delete stale HLS streams.
umask 0002
exec setpriv --reuid=otunes --regid=otunes --init-groups \
"$NODE" apps/web/server.js
) &