Compare commits

...
15 changed files with 1419 additions and 980 deletions

No files matched your search

+4 -2
View File
@@ -4,7 +4,9 @@ This integration uses Expo 58 inline modules and `expo-app-intents`. Rebuild the
Playback and library changes open oTunes because they need its authenticated React runtime. Swift dispatches a request and waits for an app-owned completion acknowledgment. Playback waits for the native audio player to load the requested track; warmup waits for it to load while paused. Errors reach Siri, and requests that have expired are discarded before starting a side effect. Native catalog reads do not open the app.
The full entity catalog lives in Application Support. The backend supplies pages of 200 records. Expo's UserDefaults catalog holds at most 100 suggestions per kind, with favorites first, and mirrors those suggestions into Spotlight. Siri's native queries search the full disk catalog. Catalogs refresh on launch, foreground entry, favorite changes, and every five minutes while foregrounded.
The full entity catalog lives in Application Support. Expo's UserDefaults catalog holds at most 100 suggestions per kind, with favorites first, and mirrors those suggestions into Spotlight. Siri's native queries search the full disk catalog.
Sync is incremental. The app subscribes to `intentCatalog.head`, the newest insert, rename or deletion per kind, and fetches a kind only when it moves past the cursor stored in AsyncStorage. `intentCatalog.page` then returns records created after the cursor plus renames and deletions from the `intentCatalogChanges` log. The log keeps 30 days; older cursors, or more than 2,000 changes, rebuild that kind from scratch. Favorites are stamped onto records on device from the favorites subscription, so liking a song costs no catalog queries. Playlists come from the live `intentCatalog.playlists` query. Code lives in `components/app-intents/`: `catalog-sync.ts`, `now-playing.ts`, and `dispatch.ts`.
Songs, albums, artists, and playlists have Spotlight open intents and on-screen entity associations. Associations require iOS 18.4 and Xcode 27; Spotlight indexing requires iOS 18. Playback donations are made after the player starts, preserve shuffle, and resolve real catalog entities. Removed records trigger donation cleanup. Sign-out clears catalogs, Spotlight entries, donations, and pending invocations. On iOS 27, the query types also handle system requests to rebuild Spotlight indexes.
@@ -14,7 +16,7 @@ Audio schema intents require Xcode 27 and iOS 27. Custom intents remain availabl
Deploy the companion Convex changes before installing the new mobile build:
- `library.intentCatalogPage` supplies authenticated, paginated entity records.
- `intentCatalog.head`, `intentCatalog.page` and `intentCatalog.playlists` supply the entity catalog. Library mutations record renames and deletions in `intentCatalogChanges`, pruned daily.
- `appIntentPlaylists` records playlist-creation request IDs in the same transaction as creation. Replaying a request returns the original playlist ID.
- `playlists.createPlaylist` accepts an optional `invocationId`; existing callers can omit it.
+1 -1
View File
@@ -73,10 +73,10 @@ export default function AppLayout() {
return (
<ConvexAuthRecovery onInvalidate={invalidateSession}>
<PlaybackProvider>
<AppIntentBridge />
<AppNavigationSync />
<AddToPlaylistProvider>
<FavoritesProvider>
<AppIntentBridge />
<Stack screenOptions={stackOptions}>
<Stack.Screen
name="(tabs)"
+12 -799
View File
@@ -1,147 +1,21 @@
import { useConvex, useQuery } from "convex/react"
import { useQuery } from "convex/react"
import * as AppIntents from "expo-app-intents"
import type { AppIntentEntity, AppIntentInvocation } from "expo-app-intents"
import { useEffect, useMemo, useRef, useSyncExternalStore } from "react"
import { AppState } from "react-native"
import {
completeMusicInvocation,
publishMusicCatalog,
trackMusicCatalogSync,
} from "@/lib/app-intents"
import { useAppNavigation } from "@/lib/app-navigation"
import { useMemo, useSyncExternalStore } from "react"
import { useMusicCatalogSync } from "@/components/app-intents/catalog-sync"
import { useIntentDispatch } from "@/components/app-intents/dispatch"
import { useNowPlayingCatalog } from "@/components/app-intents/now-playing"
import {
ANONYMOUS_CACHE_SCOPE,
useCacheScope,
} from "@/contexts/persistent-cache"
import { usePlayback } from "@/contexts/playback"
import {
FAVORITES_PLAYLIST_ID,
loadHandledIntentIds,
rememberHandledIntentId,
} from "@/lib/app-intent-handled"
import { showError } from "@/lib/toast"
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
import { getPlaybackStore } from "@otunes/convex/client/playback-store"
import type { RepeatMode } from "@otunes/convex/client/playback-queue"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
const warmedAudioIds = new Set<string>()
class IntentRejected extends Error {}
const KNOWN_INTENTS = new Set([
"playMusic",
"warmupAudio",
"addToPlaylist",
"addToUpNext",
"clearUpNext",
"createPlaylist",
"createStation",
"updateAffinity",
"transport",
"openMusic",
])
type MusicSource = {
kind: string
id: string
}
function readString(value: unknown) {
return typeof value === "string" && value.trim() ? value : null
}
function readSources(value: unknown): MusicSource[] {
if (!Array.isArray(value)) {
return []
}
return value.flatMap((entry) => {
if (!entry || typeof entry !== "object") {
return []
}
const source = entry as { kind?: unknown; id?: unknown }
if (typeof source.kind !== "string" || typeof source.id !== "string") {
return []
}
if (!source.kind || !source.id) {
return []
}
return [{ kind: source.kind, id: source.id }]
})
}
function shuffleChoice(value: unknown, fallback: boolean) {
if (value === "songs") return true
if (value === "off") return false
if (value == null) return fallback
throw new IntentRejected("Shuffle must be Off or Songs.")
}
function repeatChoice(value: unknown): RepeatMode | null {
if (value == null) return null
if (value === "none") return "none"
if (value === "one") return "once"
if (value === "all") return "always"
throw new IntentRejected("Repeat must be None, One, or All.")
}
function ensureActive(invocation: AppIntentInvocation) {
const deadline = invocation.params.deadline
if (typeof deadline === "number" && Date.now() >= deadline) {
throw new IntentRejected("This request expired. Please try again.")
}
}
function isTransient(error: unknown) {
const message = (
error instanceof Error ? error.message : String(error)
).toLowerCase()
return (
message.includes("not authenticated") ||
message.includes("network") ||
message.includes("fetch") ||
message.includes("connection") ||
message.includes("timed out") ||
message.includes("timeout")
)
}
function songEntity(song: {
id: string
title: string
artistName: string
artistId: string
albumTitle: string
albumId: string
durationSeconds: number
genres?: string
year?: number
track?: number
diskNumber?: number | null
favorite?: boolean
}): AppIntentEntity {
return {
id: song.id,
title: song.title,
subtitle: song.artistName,
synonyms: song.artistName ? [song.artistName] : undefined,
metadata: {
artistName: song.artistName,
artistId: song.artistId,
albumTitle: song.albumTitle,
albumId: song.albumId,
duration: String(song.durationSeconds),
genres: song.genres ?? "",
year: song.year == null ? "" : String(song.year),
track: song.track == null ? "" : String(song.track),
disk: song.diskNumber == null ? "" : String(song.diskNumber),
favorite: song.favorite ? "1" : "0",
},
}
}
/**
* Siri and Shortcuts integration: the on-device entity catalog, the current
* song, and intent dispatch. Must render inside `FavoritesProvider`.
*/
export function AppIntentBridge() {
const scope = useCacheScope()
const store = useMemo(
@@ -154,669 +28,8 @@ export function AppIntentBridge() {
}
function ReadyAppIntentBridge() {
const convex = useConvex()
const cacheScope = useCacheScope()
const playback = usePlayback()
const user = useQuery(api.auth.currentUser)
const navigation = useAppNavigation()
const favorites = useQuery(api.favorites.getUserFavorites)
const catalogUserKey = user ? JSON.stringify([user._id, favorites]) : null
const store = useMemo(
() =>
getPlaybackStore(
cacheScope === ANONYMOUS_CACHE_SCOPE ? null : cacheScope
),
[cacheScope]
)
const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot)
const handledIds = useRef<Set<string> | null>(null)
const publishChain = useRef(Promise.resolve())
const publishGeneration = useRef(0)
const playbackRef = useRef(playback)
playbackRef.current = playback
useEffect(() => {
if (!AppIntents.isAvailable() || !user) return
const generation = ++publishGeneration.current
let stopped = false
let refreshing = false
const refresh = () => {
if (refreshing || stopped) return
refreshing = true
publishChain.current = publishChain.current
.catch(() => undefined)
.then(async () => {
for (const kind of ["artist", "album", "song", "playlist"] as const) {
const entities: AppIntentEntity[] = []
let cursor: string | null = null
do {
const result: {
page: AppIntentEntity[]
isDone: boolean
continueCursor: string
} = await convex.query(api.library.intentCatalogPage, {
kind,
paginationOpts: { cursor, numItems: 200 },
})
if (stopped || generation !== publishGeneration.current) return
entities.push(...result.page)
cursor = result.isDone ? null : result.continueCursor
} while (cursor !== null)
await publishMusicCatalog(kind, entities)
}
})
.catch((error) =>
console.warn("Could not publish music catalog.", error)
)
.finally(() => {
refreshing = false
})
trackMusicCatalogSync(publishChain.current)
}
refresh()
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active") refresh()
})
const timer = setInterval(() => {
if (AppState.currentState === "active") refresh()
}, 5 * 60_000)
return () => {
stopped = true
++publishGeneration.current
subscription.remove()
clearInterval(timer)
}
}, [convex, cacheScope, catalogUserKey])
const currentSongId = playback.queueSongIds[0] ?? null
const currentSong = playback.currentSong
useEffect(() => {
if (!snapshot.hydrated || !AppIntents.isAvailable()) {
return
}
if (!currentSongId) {
void publishMusicCatalog("nowPlaying", []).catch((error) => {
console.warn("Could not clear the current song.", error)
})
return
}
if (!currentSong || currentSong.id !== currentSongId) {
return
}
void publishMusicCatalog("nowPlaying", [
songEntity({
id: currentSong.id,
title: currentSong.title,
artistName: currentSong.artist.name,
artistId: currentSong.artist.id,
albumTitle: currentSong.album.title,
albumId: currentSong.album.id,
durationSeconds: currentSong.durationSeconds,
}),
]).catch((error) => {
console.warn("Could not publish the current song.", error)
})
}, [currentSong, currentSongId, snapshot.hydrated])
AppIntents.useAppIntents(async (pendingIntents) => {
if (!handledIds.current) {
handledIds.current = await loadHandledIntentIds()
}
const handled = handledIds.current
for (const invocation of pendingIntents) {
if (handled.has(invocation.id)) {
const token = readString(invocation.params.completionToken)
if (token) await completeMusicInvocation(token, null)
await AppIntents.removePendingInvocationAsync(invocation.id)
continue
}
if (!KNOWN_INTENTS.has(invocation.name)) {
await AppIntents.removePendingInvocationAsync(invocation.id)
continue
}
const token = readString(invocation.params.completionToken)
try {
ensureActive(invocation)
await performInvocation(invocation)
if (
["playMusic", "warmupAudio", "transport", "createStation"].includes(
invocation.name
)
) {
const id = store.getState().queue[0]
const song = playbackRef.current.currentSong
if (!id) await publishMusicCatalog("nowPlaying", [])
else if (song?.id === id)
await publishMusicCatalog("nowPlaying", [
songEntity({
id: song.id,
title: song.title,
artistName: song.artist.name,
artistId: song.artist.id,
albumTitle: song.album.title,
albumId: song.album.id,
durationSeconds: song.durationSeconds,
}),
])
}
await rememberHandledIntentId(handled, invocation.id)
if (token) await completeMusicInvocation(token, null)
await AppIntents.removePendingInvocationAsync(invocation.id)
} catch (error) {
if (token) {
await completeMusicInvocation(
token,
error instanceof Error ? error.message : "oTunes couldn't do that."
)
}
if (token || error instanceof IntentRejected || !isTransient(error)) {
const message =
error instanceof Error ? error.message : "oTunes couldn't do that."
if (!(error instanceof IntentRejected) || message) {
showError(message)
}
try {
await rememberHandledIntentId(handled, invocation.id)
await AppIntents.removePendingInvocationAsync(invocation.id)
} catch (removeError) {
console.warn(
"App Intent remains pending",
invocation.id,
removeError
)
}
continue
}
console.warn("App Intent remains pending", invocation.id, error)
}
}
async function songIdsFor(kind: string, id: string) {
if (kind === "song") {
return [id as Id<"songs">]
}
if (kind === "album") {
return fetchCachedQuery(
convex,
cacheScope,
api.playlists.getAlbumSongIds,
{
albumId: id as Id<"albums">,
}
)
}
if (kind === "artist") {
return fetchCachedQuery(
convex,
cacheScope,
api.playlists.getOrderedArtistSongIds,
{ artistId: id as Id<"artists"> }
)
}
if (kind === "playlist") {
if (id === FAVORITES_PLAYLIST_ID) {
const favorites = await fetchCachedQuery(
convex,
cacheScope,
api.favorites.getUserFavorites,
{}
)
return favorites.favoriteSongs
}
return fetchCachedQuery(
convex,
cacheScope,
api.playlists.getPlaylistSongIds,
{ playlistId: id as Id<"playlists"> }
)
}
throw new IntentRejected("Choose a song, album, artist, or playlist.")
}
async function uniqueSongIds(sources: MusicSource[]) {
const ids: Id<"songs">[] = []
for (const source of sources) {
ids.push(...(await songIdsFor(source.kind, source.id)))
}
return [...new Set(ids)]
}
async function performInvocation(invocation: AppIntentInvocation) {
const actions = playbackRef.current
switch (invocation.name) {
case "openMusic": {
const kind = readString(invocation.params.kind)
const id = readString(invocation.params.id)
if (!id || !kind) throw new IntentRejected("Choose music to open.")
if (kind === "song") {
const song = await convex.query(api.library.getSong, {
id: id as Id<"songs">,
})
if (!song)
throw new IntentRejected("This song is no longer available.")
navigation.push(`/album/${song.album}`)
} else if (kind === "playlist" && id === FAVORITES_PLAYLIST_ID) {
navigation.push("/playlist/favorites")
} else if (["album", "artist", "playlist"].includes(kind)) {
navigation.push(`/${kind}/${id}`)
} else throw new IntentRejected("Unknown music type.")
return
}
case "playMusic":
await playMusic(invocation)
if (!["next", "tail"].includes(String(invocation.params.queue))) {
ensureActive(invocation)
await playbackRef.current.waitForPlaybackReady(true)
}
return
case "warmupAudio":
await warmup(invocation)
ensureActive(invocation)
await playbackRef.current.waitForPlaybackReady(false)
warmedAudioIds.add(invocation.id)
return
case "addToPlaylist":
await addToPlaylist(invocation)
return
case "addToUpNext":
await addToUpNext(invocation)
return
case "clearUpNext":
ensureActive(invocation)
await actions.clearUpNext()
return
case "createPlaylist":
await createPlaylist(invocation)
return
case "createStation":
await createStation(invocation)
ensureActive(invocation)
await playbackRef.current.waitForPlaybackReady(true)
return
case "updateAffinity":
await updateAffinity(invocation)
return
case "transport":
await transport(invocation)
if (store.getState().queue.length > 0) {
const command = invocation.params.command
await playbackRef.current.waitForPlaybackReady(
command === "resume"
? true
: command === "pause"
? false
: undefined
)
}
return
default:
return
}
}
async function playMusic(invocation: AppIntentInvocation) {
const actions = playbackRef.current
const queue = readString(invocation.params.queue) ?? "now"
const warmupId = readString(invocation.params.warmupId)
const repeat = repeatChoice(invocation.params.repeat)
if (repeat) {
ensureActive(invocation)
await actions.setRepeatMode(repeat)
}
if (queue === "next" || queue === "tail") {
const kind = readString(invocation.params.kind)
const id = readString(invocation.params.id)
if (!kind || !id) {
throw new IntentRejected("Choose music to add to Up Next.")
}
const shuffled = shuffleChoice(
invocation.params.shuffle,
actions.shuffleEnabled
)
if (shuffled !== actions.shuffleEnabled) {
ensureActive(invocation)
await actions.setShuffleEnabled(shuffled)
}
const ids = await songIdsFor(kind, id)
if (ids.length === 0) {
throw new IntentRejected("Nothing to add to Up Next.")
}
if (queue === "next") {
ensureActive(invocation)
await actions.addToQueueNext(ids)
} else {
ensureActive(invocation)
await actions.addToQueueLast(ids)
}
return
}
if (warmupId && warmedAudioIds.has(warmupId)) {
const shuffled = shuffleChoice(
invocation.params.shuffle,
actions.shuffleEnabled
)
if (shuffled !== actions.shuffleEnabled) {
ensureActive(invocation)
await actions.setShuffleEnabled(shuffled)
}
ensureActive(invocation)
actions.setIsPlaying(true)
return
}
const kind = readString(invocation.params.kind) ?? "resume"
if (kind === "resume") {
const shuffled = shuffleChoice(
invocation.params.shuffle,
actions.shuffleEnabled
)
if (shuffled !== actions.shuffleEnabled) {
ensureActive(invocation)
await actions.setShuffleEnabled(shuffled)
}
if (actions.queueSongIds.length === 0) {
const favorites = await fetchCachedQuery(
convex,
cacheScope,
api.favorites.getUserFavorites,
{}
)
if (favorites.favoriteSongs.length === 0) {
throw new IntentRejected(
"Nothing is queued, and your favorites are empty."
)
}
if (shuffled) {
ensureActive(invocation)
await actions.playShuffled(favorites.favoriteSongs)
} else {
ensureActive(invocation)
await actions.playInOrder(favorites.favoriteSongs)
}
return
}
ensureActive(invocation)
actions.setIsPlaying(true)
return
}
const id = readString(invocation.params.id)
if (!id) {
throw new IntentRejected("Choose music to play.")
}
const shuffled = shuffleChoice(
invocation.params.shuffle,
actions.shuffleEnabled
)
if (kind === "song") {
const song = await fetchCachedQuery(
convex,
cacheScope,
api.library.getSong,
{
id: id as Id<"songs">,
}
)
if (!song) {
throw new IntentRejected("That song is no longer in your library.")
}
const albumSongIds = await fetchCachedQuery(
convex,
cacheScope,
api.playlists.getAlbumSongIds,
{ albumId: song.album }
)
ensureActive(invocation)
await actions.startFromSong(
song._id,
albumSongIds.length > 0 ? albumSongIds : [song._id],
shuffled,
true
)
return
}
const ids = await songIdsFor(kind, id)
if (ids.length === 0) {
throw new IntentRejected("Nothing to play.")
}
if (shuffled) {
ensureActive(invocation)
await actions.playShuffled(ids)
} else {
ensureActive(invocation)
await actions.playInOrder(ids)
}
}
async function warmup(invocation: AppIntentInvocation) {
const kind = readString(invocation.params.kind)
const id = readString(invocation.params.id)
if (!kind || !id) {
throw new IntentRejected("Choose music to get ready.")
}
const shuffled = shuffleChoice(invocation.params.shuffle, false)
if (kind === "song") {
const song = await fetchCachedQuery(
convex,
cacheScope,
api.library.getSong,
{
id: id as Id<"songs">,
}
)
if (!song) {
throw new IntentRejected("That song is no longer in your library.")
}
const albumSongIds = await fetchCachedQuery(
convex,
cacheScope,
api.playlists.getAlbumSongIds,
{ albumId: song.album }
)
ensureActive(invocation)
await playbackRef.current.startFromSong(
song._id,
albumSongIds.length > 0 ? albumSongIds : [song._id],
shuffled,
false
)
} else {
const ids = await songIdsFor(kind, id)
if (ids.length === 0) {
throw new IntentRejected("Nothing to get ready.")
}
ensureActive(invocation)
await playbackRef.current.prepareQueue(ids, shuffled)
}
}
async function addToPlaylist(invocation: AppIntentInvocation) {
const playlistId = readString(invocation.params.playlistId)
const sources = readSources(invocation.params.sources)
if (!playlistId || sources.length === 0) {
throw new IntentRejected("Choose music and a playlist.")
}
const songIds = await uniqueSongIds(sources)
if (songIds.length === 0) {
throw new IntentRejected("Those items have no songs to add.")
}
if (playlistId === FAVORITES_PLAYLIST_ID) {
for (const source of sources) {
if (source.kind === "song") {
ensureActive(invocation)
await convex.mutation(api.favorites.favoriteSong, {
songId: source.id as Id<"songs">,
})
} else if (source.kind === "album") {
ensureActive(invocation)
await convex.mutation(api.favorites.favoriteAlbum, {
albumId: source.id as Id<"albums">,
})
} else if (source.kind === "artist") {
ensureActive(invocation)
await convex.mutation(api.favorites.favoriteArtist, {
artistId: source.id as Id<"artists">,
})
} else if (source.kind === "playlist") {
const ids = await songIdsFor(source.kind, source.id)
if (ids.length > 0) {
ensureActive(invocation)
await convex.mutation(api.favorites.favoriteSongs, {
songIds: ids,
})
}
} else {
throw new IntentRejected(
"Choose a song, album, artist, or playlist."
)
}
}
return
}
ensureActive(invocation)
await convex.mutation(api.playlists.addSongsToPlaylist, {
playlistId: playlistId as Id<"playlists">,
songIds,
})
}
async function addToUpNext(invocation: AppIntentInvocation) {
const sources = readSources(invocation.params.sources)
if (sources.length === 0) {
throw new IntentRejected("Choose music to add to Up Next.")
}
const ids = await uniqueSongIds(sources)
if (ids.length === 0) {
throw new IntentRejected("Nothing to add to Up Next.")
}
const position =
readString(invocation.params.position) === "last" ? "last" : "next"
if (position === "last") {
ensureActive(invocation)
await playbackRef.current.addToQueueLast(ids)
} else {
ensureActive(invocation)
await playbackRef.current.addToQueueNext(ids)
}
}
async function createPlaylist(invocation: AppIntentInvocation) {
const name = readString(invocation.params.name)
if (!name) {
throw new IntentRejected("A playlist needs a name.")
}
const songIds = await uniqueSongIds(
readSources(invocation.params.sources)
)
ensureActive(invocation)
await convex.mutation(api.playlists.createPlaylist, {
name,
songIds,
invocationId: invocation.id,
})
}
async function createStation(invocation: AppIntentInvocation) {
const artistId = readString(invocation.params.artistId)
if (!artistId) {
throw new IntentRejected("Nothing is playing in oTunes.")
}
const ids = await songIdsFor("artist", artistId)
if (ids.length === 0)
throw new IntentRejected("This artist has no songs to play.")
ensureActive(invocation)
await playbackRef.current.playShuffled(ids)
}
async function updateAffinity(invocation: AppIntentInvocation) {
const kind = readString(invocation.params.kind)
const id = readString(invocation.params.id)
const state = readString(invocation.params.state)
if (!kind || !id || (state !== "like" && state !== "unset")) {
throw new IntentRejected(
"oTunes can love or unlike a song, album, or artist."
)
}
if (kind === "playlist") {
throw new IntentRejected("oTunes can love songs, albums, and artists.")
}
if (state === "like") {
if (kind === "song") {
ensureActive(invocation)
await convex.mutation(api.favorites.favoriteSong, {
songId: id as Id<"songs">,
})
} else if (kind === "album") {
ensureActive(invocation)
await convex.mutation(api.favorites.favoriteAlbum, {
albumId: id as Id<"albums">,
})
} else if (kind === "artist") {
ensureActive(invocation)
await convex.mutation(api.favorites.favoriteArtist, {
artistId: id as Id<"artists">,
})
} else {
throw new IntentRejected(
"oTunes can love songs, albums, and artists."
)
}
return
}
if (kind === "song") {
ensureActive(invocation)
await convex.mutation(api.favorites.unfavoriteSong, {
songId: id as Id<"songs">,
})
} else if (kind === "album") {
ensureActive(invocation)
await convex.mutation(api.favorites.unfavoriteAlbum, {
albumId: id as Id<"albums">,
})
} else if (kind === "artist") {
ensureActive(invocation)
await convex.mutation(api.favorites.unfavoriteArtist, {
artistId: id as Id<"artists">,
})
} else {
throw new IntentRejected("oTunes can love songs, albums, and artists.")
}
}
async function transport(invocation: AppIntentInvocation) {
const actions = playbackRef.current
const command = readString(invocation.params.command)
if (command === "pause") {
ensureActive(invocation)
actions.setIsPlaying(false)
return
}
if (command === "resume") {
if (actions.queueSongIds.length === 0) {
throw new IntentRejected("Nothing is queued in oTunes.")
}
ensureActive(invocation)
actions.setIsPlaying(true)
return
}
if (command === "next") {
ensureActive(invocation)
await actions.skipNext()
return
}
if (command === "previous") {
ensureActive(invocation)
await actions.skipPrevious()
return
}
throw new IntentRejected("oTunes doesn't know that playback control.")
}
})
useMusicCatalogSync()
useNowPlayingCatalog()
useIntentDispatch()
return null
}
@@ -0,0 +1,198 @@
import { useConvex, useQuery } from "convex/react"
import * as AppIntents from "expo-app-intents"
import type { AppIntentEntity } from "expo-app-intents"
import { useEffect, useRef } from "react"
import { AppState } from "react-native"
import { useCacheScope } from "@/contexts/persistent-cache"
import {
loadCatalogCursors,
saveCatalogCursors,
type CatalogCursors,
} from "@/lib/app-intent-handled"
import {
publishMusicCatalog,
readMusicCatalog,
trackMusicCatalogSync,
} from "@/lib/app-intents"
import { api } from "@otunes/convex/_generated/api"
import type { FunctionReturnType } from "convex/server"
const LIBRARY_KINDS = ["artist", "album", "song"] as const
type LibraryKind = (typeof LIBRARY_KINDS)[number]
const PAGE_SIZE = 500
type CatalogPage = FunctionReturnType<typeof api.intentCatalog.page>
type Favorites = {
favoriteSongs: string[]
favoriteAlbums: string[]
favoriteArtists: string[]
}
function favoriteIds(favorites: Favorites, kind: LibraryKind) {
return new Set<string>(
kind === "song"
? favorites.favoriteSongs
: kind === "album"
? favorites.favoriteAlbums
: favorites.favoriteArtists
)
}
/** Stamps `metadata.favorite`, which Siri uses to rank suggestions. */
function withFavorite(entity: AppIntentEntity, favorite: boolean) {
const flag = favorite ? "1" : "0"
return entity.metadata?.favorite === flag
? entity
: { ...entity, metadata: { ...entity.metadata, favorite: flag } }
}
/**
* Keeps the on-device Siri catalog in step with the server. `intentCatalog.head`
* is a live subscription, so the library is fetched only when it changes, and
* then only the records changed since the stored cursor. Favorites are applied
* locally from the existing favorites subscription.
*/
export function useMusicCatalogSync() {
const convex = useConvex()
const scope = useCacheScope()
const head = useQuery(api.intentCatalog.head)
const favorites = useQuery(api.favorites.getUserFavorites)
const playlists = useQuery(api.intentCatalog.playlists)
const latest = useRef({ head, favorites, playlists })
latest.current = { head, favorites, playlists }
const schedule = useRef<() => void>(() => undefined)
useEffect(() => {
if (!AppIntents.isAvailable()) return
let stopped = false
let running = false
let dirty = false
let cursors: CatalogCursors | null = null
// What the disk catalog reflects, to skip no-op republishes.
const appliedFavorites = new Map<LibraryKind, Set<string>>()
let publishedPlaylists: string | null = null
async function fetchChanges(kind: LibraryKind, since: number | undefined) {
const upserts: AppIntentEntity[] = []
let removed: string[] = []
let head = 0
let cursor: string | null = null
do {
const result: CatalogPage = await convex.query(api.intentCatalog.page, {
kind,
since,
paginationOpts: { cursor, numItems: PAGE_SIZE },
})
if (stopped) return null
if (cursor === null) {
if (result.reset) return fetchChanges(kind, undefined)
head = result.head ?? 0
removed = result.removed
}
upserts.push(...result.page)
cursor = result.isDone ? null : result.continueCursor
} while (cursor !== null)
return { upserts, removed, head, full: since === undefined }
}
async function syncKind(
kind: LibraryKind,
serverHead: number,
favorites: Favorites
) {
if (!cursors) return
const since = cursors[kind]
const stale = since === undefined || serverHead > since
const liked = favoriteIds(favorites, kind)
const previousLiked = appliedFavorites.get(kind)
const likesChanged =
!previousLiked ||
previousLiked.size !== liked.size ||
[...liked].some((id) => !previousLiked.has(id))
if (!stale && !likesChanged) return
const changes = stale ? await fetchChanges(kind, since) : null
if (stopped) return
const records = new Map<string, AppIntentEntity>()
if (!changes?.full) {
for (const entity of await readMusicCatalog(kind)) {
records.set(entity.id, entity)
}
}
for (const id of changes?.removed ?? []) records.delete(id)
for (const entity of changes?.upserts ?? [])
records.set(entity.id, entity)
let modified = changes !== null
for (const [id, entity] of records) {
const next = withFavorite(entity, liked.has(id))
if (next !== entity) {
records.set(id, next)
modified = true
}
}
if (stopped) return
if (modified) await publishMusicCatalog(kind, [...records.values()])
appliedFavorites.set(kind, liked)
if (changes && !stopped) {
cursors = { ...cursors, [kind]: changes.head }
await saveCatalogCursors(scope, cursors)
}
}
async function syncOnce() {
const { head, favorites, playlists } = latest.current
cursors ??= await loadCatalogCursors(scope)
if (head && favorites) {
for (const kind of LIBRARY_KINDS) {
if (stopped) return
await syncKind(kind, head[kind], favorites)
}
}
if (playlists && !stopped) {
const json = JSON.stringify(playlists)
if (json !== publishedPlaylists) {
await publishMusicCatalog("playlist", playlists)
publishedPlaylists = json
}
}
}
schedule.current = () => {
if (stopped) return
if (running) {
dirty = true
return
}
running = true
const sync = (async () => {
do {
dirty = false
await syncOnce()
} while (dirty && !stopped)
})()
.catch((error) =>
console.warn("Could not publish music catalog.", error)
)
.finally(() => {
running = false
})
trackMusicCatalogSync(sync)
}
schedule.current()
// Retries a failed sync; a no-op without server queries when current.
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active") schedule.current()
})
return () => {
stopped = true
schedule.current = () => undefined
subscription.remove()
}
}, [convex, scope])
useEffect(() => {
schedule.current()
}, [head, favorites, playlists])
}
@@ -0,0 +1,631 @@
import { useConvex } from "convex/react"
import * as AppIntents from "expo-app-intents"
import type { AppIntentInvocation } from "expo-app-intents"
import { useMemo, useRef } from "react"
import { useFavorites, type FavoriteKind } from "@/contexts/favorites"
import {
ANONYMOUS_CACHE_SCOPE,
useCacheScope,
} from "@/contexts/persistent-cache"
import { usePlayback } from "@/contexts/playback"
import {
FAVORITES_PLAYLIST_ID,
loadHandledIntentIds,
rememberHandledIntentId,
} from "@/lib/app-intent-handled"
import { completeMusicInvocation } from "@/lib/app-intents"
import { useAppNavigation } from "@/lib/app-navigation"
import { showError } from "@/lib/toast"
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
import { getPlaybackStore } from "@otunes/convex/client/playback-store"
import type { RepeatMode } from "@otunes/convex/client/playback-queue"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { publishNowPlaying } from "./now-playing"
const warmedAudioIds = new Set<string>()
class IntentRejected extends Error {}
const KNOWN_INTENTS = new Set([
"playMusic",
"warmupAudio",
"addToPlaylist",
"addToUpNext",
"clearUpNext",
"createPlaylist",
"createStation",
"updateAffinity",
"transport",
"openMusic",
])
type MusicSource = {
kind: string
id: string
}
function readString(value: unknown) {
return typeof value === "string" && value.trim() ? value : null
}
function readSources(value: unknown): MusicSource[] {
if (!Array.isArray(value)) {
return []
}
return value.flatMap((entry) => {
if (!entry || typeof entry !== "object") {
return []
}
const source = entry as { kind?: unknown; id?: unknown }
if (typeof source.kind !== "string" || typeof source.id !== "string") {
return []
}
if (!source.kind || !source.id) {
return []
}
return [{ kind: source.kind, id: source.id }]
})
}
function isFavoriteKind(kind: string): kind is FavoriteKind {
return kind === "song" || kind === "album" || kind === "artist"
}
function shuffleChoice(value: unknown, fallback: boolean) {
if (value === "songs") return true
if (value === "off") return false
if (value == null) return fallback
throw new IntentRejected("Shuffle must be Off or Songs.")
}
function repeatChoice(value: unknown): RepeatMode | null {
if (value == null) return null
if (value === "none") return "none"
if (value === "one") return "once"
if (value === "all") return "always"
throw new IntentRejected("Repeat must be None, One, or All.")
}
function ensureActive(invocation: AppIntentInvocation) {
const deadline = invocation.params.deadline
if (typeof deadline === "number" && Date.now() >= deadline) {
throw new IntentRejected("This request expired. Please try again.")
}
}
function isTransient(error: unknown) {
const message = (
error instanceof Error ? error.message : String(error)
).toLowerCase()
return (
message.includes("not authenticated") ||
message.includes("network") ||
message.includes("fetch") ||
message.includes("connection") ||
message.includes("timed out") ||
message.includes("timeout")
)
}
/** Runs Siri and Shortcuts invocations queued by the native intents. */
export function useIntentDispatch() {
const convex = useConvex()
const cacheScope = useCacheScope()
const playback = usePlayback()
const favorites = useFavorites()
const navigation = useAppNavigation()
const store = useMemo(
() =>
getPlaybackStore(
cacheScope === ANONYMOUS_CACHE_SCOPE ? null : cacheScope
),
[cacheScope]
)
const handledIds = useRef<Set<string> | null>(null)
const playbackRef = useRef(playback)
playbackRef.current = playback
/** Intent ids arrive as strings; the server validates them. */
function setFavorite(kind: FavoriteKind, id: string, favorite: boolean) {
return kind === "song"
? favorites.setFavorite(kind, id as Id<"songs">, favorite)
: kind === "album"
? favorites.setFavorite(kind, id as Id<"albums">, favorite)
: favorites.setFavorite(kind, id as Id<"artists">, favorite)
}
AppIntents.useAppIntents(async (pendingIntents) => {
if (!handledIds.current) {
handledIds.current = await loadHandledIntentIds()
}
const handled = handledIds.current
for (const invocation of pendingIntents) {
if (handled.has(invocation.id)) {
const token = readString(invocation.params.completionToken)
if (token) await completeMusicInvocation(token, null)
await AppIntents.removePendingInvocationAsync(invocation.id)
continue
}
if (!KNOWN_INTENTS.has(invocation.name)) {
await AppIntents.removePendingInvocationAsync(invocation.id)
continue
}
const token = readString(invocation.params.completionToken)
try {
ensureActive(invocation)
await performInvocation(invocation)
if (
["playMusic", "warmupAudio", "transport", "createStation"].includes(
invocation.name
)
) {
await publishNowPlaying(
store.getState().queue[0] ?? null,
playbackRef.current.currentSong
)
}
await rememberHandledIntentId(handled, invocation.id)
if (token) await completeMusicInvocation(token, null)
await AppIntents.removePendingInvocationAsync(invocation.id)
} catch (error) {
if (token) {
await completeMusicInvocation(
token,
error instanceof Error ? error.message : "oTunes couldn't do that."
)
}
if (token || error instanceof IntentRejected || !isTransient(error)) {
const message =
error instanceof Error ? error.message : "oTunes couldn't do that."
if (!(error instanceof IntentRejected) || message) {
showError(message)
}
try {
await rememberHandledIntentId(handled, invocation.id)
await AppIntents.removePendingInvocationAsync(invocation.id)
} catch (removeError) {
console.warn(
"App Intent remains pending",
invocation.id,
removeError
)
}
continue
}
console.warn("App Intent remains pending", invocation.id, error)
}
}
async function songIdsFor(kind: string, id: string) {
if (kind === "song") {
return [id as Id<"songs">]
}
if (kind === "album") {
return fetchCachedQuery(
convex,
cacheScope,
api.playlists.getAlbumSongIds,
{
albumId: id as Id<"albums">,
}
)
}
if (kind === "artist") {
return fetchCachedQuery(
convex,
cacheScope,
api.playlists.getOrderedArtistSongIds,
{ artistId: id as Id<"artists"> }
)
}
if (kind === "playlist") {
if (id === FAVORITES_PLAYLIST_ID) {
const favorites = await fetchCachedQuery(
convex,
cacheScope,
api.favorites.getUserFavorites,
{}
)
return favorites.favoriteSongs
}
return fetchCachedQuery(
convex,
cacheScope,
api.playlists.getPlaylistSongIds,
{ playlistId: id as Id<"playlists"> }
)
}
throw new IntentRejected("Choose a song, album, artist, or playlist.")
}
async function uniqueSongIds(sources: MusicSource[]) {
const ids: Id<"songs">[] = []
for (const source of sources) {
ids.push(...(await songIdsFor(source.kind, source.id)))
}
return [...new Set(ids)]
}
async function performInvocation(invocation: AppIntentInvocation) {
const actions = playbackRef.current
switch (invocation.name) {
case "openMusic": {
const kind = readString(invocation.params.kind)
const id = readString(invocation.params.id)
if (!id || !kind) throw new IntentRejected("Choose music to open.")
if (kind === "song") {
const song = await convex.query(api.library.getSong, {
id: id as Id<"songs">,
})
if (!song)
throw new IntentRejected("This song is no longer available.")
navigation.push(`/album/${song.album}`)
} else if (kind === "playlist" && id === FAVORITES_PLAYLIST_ID) {
navigation.push("/playlist/favorites")
} else if (["album", "artist", "playlist"].includes(kind)) {
navigation.push(`/${kind}/${id}`)
} else throw new IntentRejected("Unknown music type.")
return
}
case "playMusic":
await playMusic(invocation)
if (!["next", "tail"].includes(String(invocation.params.queue))) {
ensureActive(invocation)
await playbackRef.current.waitForPlaybackReady(true)
}
return
case "warmupAudio":
await warmup(invocation)
ensureActive(invocation)
await playbackRef.current.waitForPlaybackReady(false)
warmedAudioIds.add(invocation.id)
return
case "addToPlaylist":
await addToPlaylist(invocation)
return
case "addToUpNext":
await addToUpNext(invocation)
return
case "clearUpNext":
ensureActive(invocation)
await actions.clearUpNext()
return
case "createPlaylist":
await createPlaylist(invocation)
return
case "createStation":
await createStation(invocation)
ensureActive(invocation)
await playbackRef.current.waitForPlaybackReady(true)
return
case "updateAffinity":
await updateAffinity(invocation)
return
case "transport":
await transport(invocation)
if (store.getState().queue.length > 0) {
const command = invocation.params.command
await playbackRef.current.waitForPlaybackReady(
command === "resume"
? true
: command === "pause"
? false
: undefined
)
}
return
default:
return
}
}
async function playMusic(invocation: AppIntentInvocation) {
const actions = playbackRef.current
const queue = readString(invocation.params.queue) ?? "now"
const warmupId = readString(invocation.params.warmupId)
const repeat = repeatChoice(invocation.params.repeat)
if (repeat) {
ensureActive(invocation)
await actions.setRepeatMode(repeat)
}
if (queue === "next" || queue === "tail") {
const kind = readString(invocation.params.kind)
const id = readString(invocation.params.id)
if (!kind || !id) {
throw new IntentRejected("Choose music to add to Up Next.")
}
const shuffled = shuffleChoice(
invocation.params.shuffle,
actions.shuffleEnabled
)
if (shuffled !== actions.shuffleEnabled) {
ensureActive(invocation)
await actions.setShuffleEnabled(shuffled)
}
const ids = await songIdsFor(kind, id)
if (ids.length === 0) {
throw new IntentRejected("Nothing to add to Up Next.")
}
if (queue === "next") {
ensureActive(invocation)
await actions.addToQueueNext(ids)
} else {
ensureActive(invocation)
await actions.addToQueueLast(ids)
}
return
}
if (warmupId && warmedAudioIds.has(warmupId)) {
const shuffled = shuffleChoice(
invocation.params.shuffle,
actions.shuffleEnabled
)
if (shuffled !== actions.shuffleEnabled) {
ensureActive(invocation)
await actions.setShuffleEnabled(shuffled)
}
ensureActive(invocation)
actions.setIsPlaying(true)
return
}
const kind = readString(invocation.params.kind) ?? "resume"
if (kind === "resume") {
const shuffled = shuffleChoice(
invocation.params.shuffle,
actions.shuffleEnabled
)
if (shuffled !== actions.shuffleEnabled) {
ensureActive(invocation)
await actions.setShuffleEnabled(shuffled)
}
if (actions.queueSongIds.length === 0) {
const favorites = await fetchCachedQuery(
convex,
cacheScope,
api.favorites.getUserFavorites,
{}
)
if (favorites.favoriteSongs.length === 0) {
throw new IntentRejected(
"Nothing is queued, and your favorites are empty."
)
}
if (shuffled) {
ensureActive(invocation)
await actions.playShuffled(favorites.favoriteSongs)
} else {
ensureActive(invocation)
await actions.playInOrder(favorites.favoriteSongs)
}
return
}
ensureActive(invocation)
actions.setIsPlaying(true)
return
}
const id = readString(invocation.params.id)
if (!id) {
throw new IntentRejected("Choose music to play.")
}
const shuffled = shuffleChoice(
invocation.params.shuffle,
actions.shuffleEnabled
)
if (kind === "song") {
const song = await fetchCachedQuery(
convex,
cacheScope,
api.library.getSong,
{
id: id as Id<"songs">,
}
)
if (!song) {
throw new IntentRejected("That song is no longer in your library.")
}
const albumSongIds = await fetchCachedQuery(
convex,
cacheScope,
api.playlists.getAlbumSongIds,
{ albumId: song.album }
)
ensureActive(invocation)
await actions.startFromSong(
song._id,
albumSongIds.length > 0 ? albumSongIds : [song._id],
shuffled,
true
)
return
}
const ids = await songIdsFor(kind, id)
if (ids.length === 0) {
throw new IntentRejected("Nothing to play.")
}
if (shuffled) {
ensureActive(invocation)
await actions.playShuffled(ids)
} else {
ensureActive(invocation)
await actions.playInOrder(ids)
}
}
async function warmup(invocation: AppIntentInvocation) {
const kind = readString(invocation.params.kind)
const id = readString(invocation.params.id)
if (!kind || !id) {
throw new IntentRejected("Choose music to get ready.")
}
const shuffled = shuffleChoice(invocation.params.shuffle, false)
if (kind === "song") {
const song = await fetchCachedQuery(
convex,
cacheScope,
api.library.getSong,
{
id: id as Id<"songs">,
}
)
if (!song) {
throw new IntentRejected("That song is no longer in your library.")
}
const albumSongIds = await fetchCachedQuery(
convex,
cacheScope,
api.playlists.getAlbumSongIds,
{ albumId: song.album }
)
ensureActive(invocation)
await playbackRef.current.startFromSong(
song._id,
albumSongIds.length > 0 ? albumSongIds : [song._id],
shuffled,
false
)
} else {
const ids = await songIdsFor(kind, id)
if (ids.length === 0) {
throw new IntentRejected("Nothing to get ready.")
}
ensureActive(invocation)
await playbackRef.current.prepareQueue(ids, shuffled)
}
}
async function addToPlaylist(invocation: AppIntentInvocation) {
const playlistId = readString(invocation.params.playlistId)
const sources = readSources(invocation.params.sources)
if (!playlistId || sources.length === 0) {
throw new IntentRejected("Choose music and a playlist.")
}
const songIds = await uniqueSongIds(sources)
if (songIds.length === 0) {
throw new IntentRejected("Those items have no songs to add.")
}
if (playlistId === FAVORITES_PLAYLIST_ID) {
for (const source of sources) {
if (isFavoriteKind(source.kind)) {
ensureActive(invocation)
await setFavorite(source.kind, source.id, true)
} else if (source.kind === "playlist") {
const ids = await songIdsFor(source.kind, source.id)
ensureActive(invocation)
await favorites.addFavoriteSongs(ids)
} else {
throw new IntentRejected(
"Choose a song, album, artist, or playlist."
)
}
}
return
}
ensureActive(invocation)
await convex.mutation(api.playlists.addSongsToPlaylist, {
playlistId: playlistId as Id<"playlists">,
songIds,
})
}
async function addToUpNext(invocation: AppIntentInvocation) {
const sources = readSources(invocation.params.sources)
if (sources.length === 0) {
throw new IntentRejected("Choose music to add to Up Next.")
}
const ids = await uniqueSongIds(sources)
if (ids.length === 0) {
throw new IntentRejected("Nothing to add to Up Next.")
}
const position =
readString(invocation.params.position) === "last" ? "last" : "next"
if (position === "last") {
ensureActive(invocation)
await playbackRef.current.addToQueueLast(ids)
} else {
ensureActive(invocation)
await playbackRef.current.addToQueueNext(ids)
}
}
async function createPlaylist(invocation: AppIntentInvocation) {
const name = readString(invocation.params.name)
if (!name) {
throw new IntentRejected("A playlist needs a name.")
}
const songIds = await uniqueSongIds(
readSources(invocation.params.sources)
)
ensureActive(invocation)
await convex.mutation(api.playlists.createPlaylist, {
name,
songIds,
invocationId: invocation.id,
})
}
async function createStation(invocation: AppIntentInvocation) {
const artistId = readString(invocation.params.artistId)
if (!artistId) {
throw new IntentRejected("Nothing is playing in oTunes.")
}
const ids = await songIdsFor("artist", artistId)
if (ids.length === 0)
throw new IntentRejected("This artist has no songs to play.")
ensureActive(invocation)
await playbackRef.current.playShuffled(ids)
}
async function updateAffinity(invocation: AppIntentInvocation) {
const kind = readString(invocation.params.kind)
const id = readString(invocation.params.id)
const state = readString(invocation.params.state)
if (!kind || !id || (state !== "like" && state !== "unset")) {
throw new IntentRejected(
"oTunes can love or unlike a song, album, or artist."
)
}
if (!isFavoriteKind(kind)) {
throw new IntentRejected("oTunes can love songs, albums, and artists.")
}
ensureActive(invocation)
await setFavorite(kind, id, state === "like")
}
async function transport(invocation: AppIntentInvocation) {
const actions = playbackRef.current
const command = readString(invocation.params.command)
if (command === "pause") {
ensureActive(invocation)
actions.setIsPlaying(false)
return
}
if (command === "resume") {
if (actions.queueSongIds.length === 0) {
throw new IntentRejected("Nothing is queued in oTunes.")
}
ensureActive(invocation)
actions.setIsPlaying(true)
return
}
if (command === "next") {
ensureActive(invocation)
await actions.skipNext()
return
}
if (command === "previous") {
ensureActive(invocation)
await actions.skipPrevious()
return
}
throw new IntentRejected("oTunes doesn't know that playback control.")
}
})
}
@@ -0,0 +1,57 @@
import * as AppIntents from "expo-app-intents"
import type { AppIntentEntity } from "expo-app-intents"
import { useEffect } from "react"
import { usePlayback } from "@/contexts/playback"
import { publishMusicCatalog } from "@/lib/app-intents"
type CurrentSong = NonNullable<ReturnType<typeof usePlayback>["currentSong"]>
function nowPlayingEntity(song: CurrentSong): AppIntentEntity {
const artistName = song.artist.name
return {
id: song.id,
title: song.title,
subtitle: artistName,
synonyms: artistName ? [artistName] : undefined,
metadata: {
artistName,
artistId: song.artist.id,
albumTitle: song.album.title,
albumId: song.album.id,
duration: String(song.durationSeconds),
genres: "",
year: "",
track: "",
disk: "",
favorite: "0",
},
}
}
/**
* Publishes the "nowPlaying" catalog Siri reads for the current song. With an
* id but no matching `song` it leaves the catalog alone until the song loads.
*/
export async function publishNowPlaying(
queueHeadId: string | null,
song: CurrentSong | null
) {
if (!queueHeadId) await publishMusicCatalog("nowPlaying", [])
else if (song?.id === queueHeadId)
await publishMusicCatalog("nowPlaying", [nowPlayingEntity(song)])
}
/** Keeps the "nowPlaying" catalog in step with the playback queue. */
export function useNowPlayingCatalog() {
const playback = usePlayback()
const queueHeadId = playback.queueSongIds[0] ?? null
const song = playback.currentSong
useEffect(() => {
if (!AppIntents.isAvailable()) return
void publishNowPlaying(queueHeadId, song).catch((error) => {
console.warn("Could not publish the current song.", error)
})
}, [queueHeadId, song])
}
+75 -52
View File
@@ -28,6 +28,9 @@ function useOptimisticMutation<Mutation extends FunctionReference<"mutation">>(
return useMemo(() => base.withOptimisticUpdate(updateRef.current), [base])
}
type FavoriteTables = { song: "songs"; album: "albums"; artist: "artists" }
export type FavoriteKind = keyof FavoriteTables
type FavoritesContextValue = {
isSongFavorite: (songId: string) => boolean
isAlbumFavorite: (albumId: string) => boolean
@@ -36,6 +39,20 @@ type FavoritesContextValue = {
toggleAlbumFavorite: (albumId: Id<"albums">) => Promise<void>
toggleArtistFavorite: (artistId: Id<"artists">) => Promise<void>
favoriteSongs: (songIds: Id<"songs">[]) => Promise<void>
/** Idempotent; throws so callers like Siri can report failures. */
setFavorite: <Kind extends FavoriteKind>(
kind: Kind,
id: Id<FavoriteTables[Kind]>,
favorite: boolean
) => Promise<void>
/** Throws so callers like Siri can report failures. */
addFavoriteSongs: (songIds: Id<"songs">[]) => Promise<void>
}
function showFavoritesError(error: unknown) {
showError(
error instanceof Error ? error.message : "Failed to update favorites"
)
}
const FavoritesContext = createContext<FavoritesContextValue | null>(null)
@@ -173,70 +190,72 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
const idsRef = useRef({ songIds, albumIds, artistIds })
idsRef.current = { songIds, albumIds, artistIds }
const toggleSongFavorite = useCallback(
async (songId: Id<"songs">) => {
try {
if (idsRef.current.songIds.has(songId)) {
await unfavoriteSong({ songId })
} else {
await favoriteSong({ songId })
}
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to update favorites"
)
const setFavorite = useCallback(
async <Kind extends FavoriteKind>(
kind: Kind,
id: Id<FavoriteTables[Kind]>,
favorite: boolean
) => {
if (kind === "song") {
const songId = id as Id<"songs">
await (favorite ? favoriteSong : unfavoriteSong)({ songId })
} else if (kind === "album") {
const albumId = id as Id<"albums">
await (favorite ? favoriteAlbum : unfavoriteAlbum)({ albumId })
} else {
const artistId = id as Id<"artists">
await (favorite ? favoriteArtist : unfavoriteArtist)({ artistId })
}
},
[favoriteSong, unfavoriteSong]
[
favoriteSong,
unfavoriteSong,
favoriteAlbum,
unfavoriteAlbum,
favoriteArtist,
unfavoriteArtist,
]
)
const toggleSongFavorite = useCallback(
(songId: Id<"songs">) =>
setFavorite("song", songId, !idsRef.current.songIds.has(songId)).catch(
showFavoritesError
),
[setFavorite]
)
const toggleAlbumFavorite = useCallback(
async (albumId: Id<"albums">) => {
try {
if (idsRef.current.albumIds.has(albumId)) {
await unfavoriteAlbum({ albumId })
} else {
await favoriteAlbum({ albumId })
}
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to update favorites"
)
}
},
[favoriteAlbum, unfavoriteAlbum]
(albumId: Id<"albums">) =>
setFavorite(
"album",
albumId,
!idsRef.current.albumIds.has(albumId)
).catch(showFavoritesError),
[setFavorite]
)
const toggleArtistFavorite = useCallback(
async (artistId: Id<"artists">) => {
try {
if (idsRef.current.artistIds.has(artistId)) {
await unfavoriteArtist({ artistId })
} else {
await favoriteArtist({ artistId })
}
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to update favorites"
)
}
(artistId: Id<"artists">) =>
setFavorite(
"artist",
artistId,
!idsRef.current.artistIds.has(artistId)
).catch(showFavoritesError),
[setFavorite]
)
const addFavoriteSongs = useCallback(
async (ids: Id<"songs">[]) => {
const unique = [...new Set(ids)]
if (unique.length > 0) await favoriteSongsMutation({ songIds: unique })
},
[favoriteArtist, unfavoriteArtist]
[favoriteSongsMutation]
)
const favoriteSongs = useCallback(
async (ids: Id<"songs">[]) => {
const unique = [...new Set(ids)]
if (unique.length === 0) return
try {
await favoriteSongsMutation({ songIds: unique })
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to update favorites"
)
}
},
[favoriteSongsMutation]
(ids: Id<"songs">[]) => addFavoriteSongs(ids).catch(showFavoritesError),
[addFavoriteSongs]
)
const value = useMemo(
@@ -248,6 +267,8 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
toggleAlbumFavorite,
toggleArtistFavorite,
favoriteSongs,
setFavorite,
addFavoriteSongs,
}),
[
songIds,
@@ -257,6 +278,8 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
toggleAlbumFavorite,
toggleArtistFavorite,
favoriteSongs,
setFavorite,
addFavoriteSongs,
]
)
+35
View File
@@ -5,6 +5,7 @@ import { publishMusicCatalog } from "@/lib/app-intents"
export const FAVORITES_PLAYLIST_ID = "otunes:favorites"
const HANDLED_KEY = "otunes:handled-app-intents"
const CATALOG_CURSORS_KEY = "otunes:app-intent-catalog-cursors"
const MAX_HANDLED = 200
const CATALOG_KINDS = [
@@ -20,6 +21,7 @@ export async function clearAppIntentCatalogs() {
return
}
const results = await Promise.allSettled([
AsyncStorage.removeItem(CATALOG_CURSORS_KEY),
AppIntents.deleteDonationsAsync({ intent: "playMusic" }),
AppIntents.clearPendingInvocationsAsync(),
...CATALOG_KINDS.map((kind) => publishMusicCatalog(kind, [])),
@@ -28,6 +30,39 @@ export async function clearAppIntentCatalogs() {
if (failed?.status === "rejected") throw failed.reason
}
/**
* Server `head` values the disk catalog is synced to, per library kind. A
* missing kind means it has never synced and needs a full download.
*/
export type CatalogCursors = Partial<
Record<"song" | "album" | "artist", number>
>
/** Cursors for `scope`; another server or user's cursors read as empty. */
export async function loadCatalogCursors(
scope: string
): Promise<CatalogCursors> {
try {
const raw = await AsyncStorage.getItem(CATALOG_CURSORS_KEY)
const parsed = raw
? (JSON.parse(raw) as { scope?: unknown; cursors?: CatalogCursors })
: null
return parsed?.scope === scope ? (parsed.cursors ?? {}) : {}
} catch {
return {}
}
}
export async function saveCatalogCursors(
scope: string,
cursors: CatalogCursors
) {
await AsyncStorage.setItem(
CATALOG_CURSORS_KEY,
JSON.stringify({ scope, cursors })
)
}
export async function loadHandledIntentIds() {
const raw = await AsyncStorage.getItem(HANDLED_KEY)
if (!raw) {
+7
View File
@@ -50,6 +50,13 @@ export function publishMusicCatalog(kind: string, entities: AppIntentEntity[]) {
return write
}
/** The full disk catalog for `kind`, as last published. */
export async function readMusicCatalog(kind: string) {
await publishing.catch(() => undefined)
if (!native || !AppIntents.isAvailable()) return []
return JSON.parse(await native.catalogJSON(kind)) as AppIntentEntity[]
}
export async function completeMusicInvocation(
token: string,
error: string | null
+4
View File
@@ -13,6 +13,8 @@ import type * as auth from "../auth.js";
import type * as crons from "../crons.js";
import type * as favorites from "../favorites.js";
import type * as http from "../http.js";
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 migrations from "../migrations.js";
@@ -34,6 +36,8 @@ declare const fullApi: ApiFromModules<{
crons: typeof crons;
favorites: typeof favorites;
http: typeof http;
intentCatalog: typeof intentCatalog;
intentCatalogChanges: typeof intentCatalogChanges;
library: typeof library;
limits: typeof limits;
migrations: typeof migrations;
+6
View File
@@ -9,4 +9,10 @@ crons.interval(
internal.actions.scheduledUpdateLibrary
)
crons.daily(
"prune Siri catalog change log",
{ hourUTC: 9, minuteUTC: 0 },
internal.intentCatalogChanges.pruneIntentCatalogChanges
)
export default crons
+337
View File
@@ -0,0 +1,337 @@
import { getAuthUserId } from "@convex-dev/auth/server"
import { paginationOptsValidator } from "convex/server"
import { ConvexError, v } from "convex/values"
import type { Doc, Id } from "./_generated/dataModel"
import { query, type QueryCtx } from "./_generated/server"
import {
INTENT_CATALOG_CHANGE_RETENTION_MS,
type LibraryCatalogKind,
} from "./intentCatalogChanges"
import { getSongArtistNames, songArtistsMatchAlbum } from "./library"
/**
* Siri/App Intents entity catalog. Library records carry no per-user state, so
* clients sync them incrementally and overlay favorites locally.
*/
const FAVORITES_PLAYLIST_ID = "otunes:favorites"
/** More changes than this since a client's cursor and it rebuilds instead. */
const MAX_CHANGES_PER_SYNC = 2000
const libraryKindValidator = v.union(
v.literal("song"),
v.literal("album"),
v.literal("artist")
)
type IntentEntity = {
id: string
title: string
subtitle?: string
synonyms?: string[]
metadata: Record<string, string>
}
async function requireUser(ctx: QueryCtx) {
const userId = await getAuthUserId(ctx)
if (!userId) throw new ConvexError("Not authenticated")
return userId
}
function unique<T>(values: T[]) {
return [...new Set(values)]
}
async function getMany<Table extends "albums" | "artists" | "users">(
ctx: QueryCtx,
table: Table,
ids: Id<Table>[]
) {
const docs = await Promise.all(unique(ids).map((id) => ctx.db.get(table, id)))
return new Map(
docs.flatMap((doc) => (doc ? [[doc._id as Id<Table>, doc] as const] : []))
)
}
async function songEntities(ctx: QueryCtx, songs: Doc<"songs">[]) {
const [albums, artists] = await Promise.all([
getMany(
ctx,
"albums",
songs.map((song) => song.album)
),
getMany(
ctx,
"artists",
songs.map((song) => song.albumArtist)
),
])
return songs.flatMap((song): IntentEntity[] => {
const album = albums.get(song.album)
const artist = artists.get(song.albumArtist)
if (!album || !artist || !song.name.trim()) return []
const credits = getSongArtistNames(song.artist)
const artistName = songArtistsMatchAlbum(credits, artist.name)
? artist.name
: credits.join(", ") || artist.name
return [
{
id: song._id,
title: song.name,
subtitle: artistName,
metadata: {
artistName,
artistId: artist._id,
albumTitle: album.name,
albumId: album._id,
duration: String(Math.max(0, Math.round(song.length))),
genres: song.genres.join(", "),
year: String(song.year),
track: String(song.track),
disk: String(song.diskNumber ?? ""),
},
},
]
})
}
async function albumEntities(ctx: QueryCtx, albums: Doc<"albums">[]) {
const artists = await getMany(
ctx,
"artists",
albums.map((album) => album.artist)
)
return albums.flatMap((album): IntentEntity[] => {
const artist = artists.get(album.artist)
if (!artist || !album.name.trim()) return []
return [
{
id: album._id,
title: album.name,
subtitle: artist.name,
metadata: {
artistName: artist.name,
artistId: artist._id,
year: String(album.year),
},
},
]
})
}
function artistEntities(artists: Doc<"artists">[]) {
return artists.flatMap((artist): IntentEntity[] =>
artist.name.trim()
? [{ id: artist._id, title: artist.name, metadata: {} }]
: []
)
}
/** Rows in `ids` not already in `rows`, so renamed records are re-sent. */
async function withUpdatedRows<Row extends { _id: string }>(
rows: Row[],
ids: string[],
load: (id: string) => Promise<Row | null>
) {
const seen = new Set(rows.map((row) => row._id))
const updated: (Row | null)[] = await Promise.all(
ids.filter((id) => !seen.has(id)).map(load)
)
return [...rows, ...updated.flatMap((row) => (row ? [row] : []))]
}
async function newestCreationTime(ctx: QueryCtx, kind: LibraryCatalogKind) {
const table =
kind === "song" ? "songs" : kind === "album" ? "albums" : "artists"
const [row, change] = await Promise.all([
ctx.db.query(table).order("desc").first(),
ctx.db
.query("intentCatalogChanges")
.withIndex("by_kind", (q) => q.eq("kind", kind))
.order("desc")
.first(),
])
return Math.max(row?._creationTime ?? 0, change?._creationTime ?? 0)
}
/**
* Newest insert, rename or deletion per kind. Clients subscribe to this and
* fetch a kind only after it moves past their cursor.
*/
export const head = query({
args: {},
handler: async (ctx) => {
await requireUser(ctx)
const [song, album, artist] = await Promise.all([
newestCreationTime(ctx, "song"),
newestCreationTime(ctx, "album"),
newestCreationTime(ctx, "artist"),
])
return { song, album, artist }
},
})
/**
* One page of catalog records. Without `since` it walks the whole library;
* with it, only records created, renamed or removed after `since`. The first
* page reports `head`, the cursor to resume from once every page is read, and
* `reset` when the change log no longer covers `since` (stale or too many
* changes); the client then rebuilds without `since`.
*/
export const page = query({
args: {
kind: libraryKindValidator,
since: v.optional(v.number()),
paginationOpts: paginationOptsValidator,
},
handler: async (ctx, { kind, since, paginationOpts }) => {
await requireUser(ctx)
const firstPage = paginationOpts.cursor === null
let removed: string[] = []
let updatedIds: string[] = []
if (firstPage && since !== undefined) {
const changes = await ctx.db
.query("intentCatalogChanges")
.withIndex("by_kind", (q) =>
q.eq("kind", kind).gt("_creationTime", since)
)
.take(MAX_CHANGES_PER_SYNC + 1)
// Pruning may have dropped deletions older than the retention window.
const expired = since < Date.now() - INTENT_CATALOG_CHANGE_RETENTION_MS
if (expired || changes.length > MAX_CHANGES_PER_SYNC) {
return {
page: [],
isDone: true,
continueCursor: "",
head: await newestCreationTime(ctx, kind),
removed,
reset: true,
}
}
removed = unique(
changes.filter((change) => change.removed).map((c) => c.entityId)
)
const removedIds = new Set(removed)
updatedIds = unique(
changes
.filter((change) => !removedIds.has(change.entityId))
.map((change) => change.entityId)
)
}
const head = firstPage ? await newestCreationTime(ctx, kind) : undefined
const respond = (
rows: { isDone: boolean; continueCursor: string },
page: IntentEntity[]
) => ({
page,
isDone: rows.isDone,
continueCursor: rows.continueCursor,
head,
removed,
reset: false,
})
// Rows created after `since`, or every row when it is omitted.
if (kind === "song") {
const query = ctx.db.query("songs")
const rows = await (
since === undefined
? query
: query.withIndex("by_creation_time", (q) =>
q.gt("_creationTime", since)
)
).paginate(paginationOpts)
const docs = await withUpdatedRows(rows.page, updatedIds, (id) => {
const songId = ctx.db.normalizeId("songs", id)
return songId ? ctx.db.get("songs", songId) : Promise.resolve(null)
})
return respond(rows, await songEntities(ctx, docs))
}
if (kind === "album") {
const query = ctx.db.query("albums")
const rows = await (
since === undefined
? query
: query.withIndex("by_creation_time", (q) =>
q.gt("_creationTime", since)
)
).paginate(paginationOpts)
const docs = await withUpdatedRows(rows.page, updatedIds, (id) => {
const albumId = ctx.db.normalizeId("albums", id)
return albumId ? ctx.db.get("albums", albumId) : Promise.resolve(null)
})
return respond(rows, await albumEntities(ctx, docs))
}
const query = ctx.db.query("artists")
const rows = await (
since === undefined
? query
: query.withIndex("by_creation_time", (q) =>
q.gt("_creationTime", since)
)
).paginate(paginationOpts)
const docs = await withUpdatedRows(rows.page, updatedIds, (id) => {
const artistId = ctx.db.normalizeId("artists", id)
return artistId ? ctx.db.get("artists", artistId) : Promise.resolve(null)
})
return respond(rows, artistEntities(docs))
},
})
/** The signed-in user's own and subscribed playlists, plus Favorites. */
export const playlists = query({
args: {},
handler: async (ctx) => {
const userId = await requireUser(ctx)
const user = await ctx.db.get("users", userId)
if (!user) throw new ConvexError("Not authenticated")
const [owned, subscribed] = await Promise.all([
ctx.db
.query("playlists")
.withIndex("by_owner", (q) => q.eq("owner", userId))
.collect(),
Promise.all(
unique(user.subscribedPlaylists ?? []).map((id) =>
ctx.db.get("playlists", id)
)
),
])
const others = subscribed.filter(
(playlist): playlist is Doc<"playlists"> =>
playlist !== null && playlist.owner !== userId
)
const owners = await getMany(
ctx,
"users",
others.map((playlist) => playlist.owner)
)
owners.set(userId, user)
const entities: IntentEntity[] = [
{
id: FAVORITES_PLAYLIST_ID,
title: "Favorites",
synonyms: [
"favorites",
"favourite songs",
"liked songs",
"loved songs",
],
metadata: { ownerName: user.name, createdByMe: "1" },
},
]
for (const playlist of [...owned, ...others]) {
if (!playlist.name.trim()) continue
const ownerName = owners.get(playlist.owner)?.name ?? ""
entities.push({
id: playlist._id,
title: playlist.name,
subtitle: ownerName,
metadata: {
ownerName,
createdByMe: playlist.owner === userId ? "1" : "0",
},
})
}
return entities
},
})
@@ -0,0 +1,40 @@
import { internal } from "./_generated/api"
import { internalMutation, type MutationCtx } from "./_generated/server"
export type LibraryCatalogKind = "song" | "album" | "artist"
/** Clients that last synced before this must rebuild their catalog from scratch. */
export const INTENT_CATALOG_CHANGE_RETENTION_MS = 30 * 24 * 60 * 60_000
const PRUNE_BATCH = 500
export async function recordIntentCatalogChanges(
ctx: MutationCtx,
kind: LibraryCatalogKind,
entityIds: string[],
removed: boolean
) {
for (const entityId of entityIds) {
await ctx.db.insert("intentCatalogChanges", { kind, entityId, removed })
}
}
export const pruneIntentCatalogChanges = internalMutation({
args: {},
handler: async (ctx) => {
const cutoff = Date.now() - INTENT_CATALOG_CHANGE_RETENTION_MS
const stale = await ctx.db
.query("intentCatalogChanges")
.withIndex("by_creation_time", (q) => q.lt("_creationTime", cutoff))
.take(PRUNE_BATCH)
for (const change of stale) {
await ctx.db.delete("intentCatalogChanges", change._id)
}
if (stale.length === PRUNE_BATCH) {
await ctx.scheduler.runAfter(
0,
internal.intentCatalogChanges.pruneIntentCatalogChanges,
{}
)
}
},
})
+6 -126
View File
@@ -21,6 +21,7 @@ import type {
SearchTopResultItem,
SidebarPlaylists,
} from "./types"
import { recordIntentCatalogChanges } from "./intentCatalogChanges"
export type {
BrowseAlbum,
@@ -53,7 +54,7 @@ export async function requireSignedIn(ctx: QueryCtx) {
}
}
function getSongArtistNames(artist: string | string[]): string[] {
export function getSongArtistNames(artist: string | string[]): string[] {
if (Array.isArray(artist)) {
return artist.map((name) => name.trim()).filter((name) => name.length > 0)
}
@@ -61,7 +62,7 @@ function getSongArtistNames(artist: string | string[]): string[] {
return trimmed.length > 0 ? [trimmed] : []
}
function songArtistsMatchAlbum(
export function songArtistsMatchAlbum(
songArtists: string[],
albumArtistName: string
): boolean {
@@ -961,130 +962,6 @@ export const getSongsForPlayback = query({
},
})
const FAVORITES_PLAYLIST_ID = "otunes:favorites"
/** Bounded pages for the device's disk-backed Siri catalog. */
export const intentCatalogPage = query({
args: {
kind: v.union(
v.literal("song"),
v.literal("album"),
v.literal("artist"),
v.literal("playlist")
),
paginationOpts: paginationOptsValidator,
},
handler: async (ctx, { kind, paginationOpts }) => {
const userId = await getAuthUserId(ctx)
if (!userId) throw new ConvexError("Not authenticated")
const user = await ctx.db.get("users", userId)
if (!user) throw new ConvexError("Not authenticated")
type Entity = {
id: string
title: string
subtitle?: string
synonyms?: string[]
metadata: Record<string, string>
}
const page: Entity[] = []
if (kind === "song") {
const result = await ctx.db.query("songs").paginate(paginationOpts)
for (const song of result.page) {
const album = await ctx.db.get("albums", song.album)
const artist = await ctx.db.get("artists", song.albumArtist)
if (!album || !artist || !song.name.trim()) continue
const credits = getSongArtistNames(song.artist)
const artistName = songArtistsMatchAlbum(credits, artist.name)
? artist.name
: credits.join(", ") || artist.name
page.push({
id: song._id,
title: song.name,
subtitle: artistName,
metadata: {
artistName,
artistId: artist._id,
albumTitle: album.name,
albumId: album._id,
duration: String(Math.max(0, Math.round(song.length))),
genres: song.genres.join(", "),
year: String(song.year),
track: String(song.track),
disk: String(song.diskNumber ?? ""),
favorite: user.favoriteSongs?.includes(song._id) ? "1" : "0",
},
})
}
return { ...result, page }
}
if (kind === "album") {
const result = await ctx.db.query("albums").paginate(paginationOpts)
for (const album of result.page) {
const artist = await ctx.db.get("artists", album.artist)
if (!artist || !album.name.trim()) continue
page.push({
id: album._id,
title: album.name,
subtitle: artist.name,
metadata: {
artistName: artist.name,
artistId: artist._id,
year: String(album.year),
favorite: user.favoriteAlbums?.includes(album._id) ? "1" : "0",
},
})
}
return { ...result, page }
}
if (kind === "artist") {
const result = await ctx.db.query("artists").paginate(paginationOpts)
for (const artist of result.page) {
if (artist.name.trim())
page.push({
id: artist._id,
title: artist.name,
metadata: {
favorite: user.favoriteArtists?.includes(artist._id) ? "1" : "0",
},
})
}
return { ...result, page }
}
const result = await ctx.db.query("playlists").paginate(paginationOpts)
for (const playlist of result.page) {
if (
playlist.owner !== userId &&
!user.subscribedPlaylists?.includes(playlist._id)
)
continue
if (!playlist.name.trim()) continue
const owner = await ctx.db.get("users", playlist.owner)
page.push({
id: playlist._id,
title: playlist.name,
subtitle: owner?.name ?? "",
metadata: {
ownerName: owner?.name ?? "",
createdByMe: playlist.owner === userId ? "1" : "0",
},
})
}
if (paginationOpts.cursor === null)
page.unshift({
id: FAVORITES_PLAYLIST_ID,
title: "Favorites",
synonyms: [
"favorites",
"favourite songs",
"liked songs",
"loved songs",
],
metadata: { ownerName: user.name, createdByMe: "1" },
})
return { ...result, page }
},
})
export const createArtists = internalMutation({
args: {
artists: v.array(
@@ -1291,6 +1168,7 @@ export const removeArtists = internalMutation({
for (const id of args.ids) {
await ctx.db.delete("artists", id)
}
await recordIntentCatalogChanges(ctx, "artist", args.ids, true)
},
})
@@ -1300,6 +1178,7 @@ export const removeAlbums = internalMutation({
for (const id of args.ids) {
await ctx.db.delete("albums", id)
}
await recordIntentCatalogChanges(ctx, "album", args.ids, true)
},
})
@@ -1337,5 +1216,6 @@ export const removeSongs = internalMutation({
for (const id of args.ids) {
await ctx.db.delete("songs", id)
}
await recordIntentCatalogChanges(ctx, "song", args.ids, true)
},
})
+6
View File
@@ -69,6 +69,12 @@ export default defineSchema({
invocationId: v.string(),
playlistId: v.id("playlists"),
}).index("by_user_invocation", ["userId", "invocationId"]),
/** Renames and deletions; Siri catalog clients find inserts by `_creationTime`. */
intentCatalogChanges: defineTable({
kind: v.union(v.literal("song"), v.literal("album"), v.literal("artist")),
entityId: v.string(),
removed: v.boolean(),
}).index("by_kind", ["kind"]),
appSettings: defineTable({
disableAccountCreation: v.boolean(),
}),