Files
otunes/apps/mobile/lib/app-intents.ts
T

82 lines
2.8 KiB
TypeScript

import { requireOptionalNativeModule } from "expo"
import * as AppIntents from "expo-app-intents"
import type { AppIntentEntity } from "expo-app-intents"
type MusicIntentModule = {
replaceCatalog: (kind: string, json: string) => Promise<void>
catalogJSON: (kind: string) => Promise<string>
completeInvocation: (token: string, error: string | null) => Promise<void>
}
const native = requireOptionalNativeModule<MusicIntentModule>("AppIntentsSetup")
export type MusicEntityKind = "song" | "album" | "artist" | "playlist"
const SPOTLIGHT_LIMIT = 100
let publishing: Promise<void> = Promise.resolve()
let catalogSync: Promise<void> = Promise.resolve()
export function trackMusicCatalogSync(sync: Promise<void>) {
catalogSync = sync
}
/** Serialize writes so sign-out cleanup cannot be overtaken by an older publish. */
export function publishMusicCatalog(kind: string, entities: AppIntentEntity[]) {
const write = publishing
.catch(() => undefined)
.then(async () => {
if (!native || !AppIntents.isAvailable()) return
const oldDiskCatalog = JSON.parse(
await native.catalogJSON(kind)
) as AppIntentEntity[]
const suggestions = [...entities]
.sort(
(a, b) =>
Number(b.metadata?.favorite === "1") -
Number(a.metadata?.favorite === "1")
)
.slice(0, SPOTLIGHT_LIMIT)
const previous = await AppIntents.getEntityCatalogAsync(kind)
const remaining = new Set(entities.map((entity) => entity.id))
for (const entity of new Map(
[...oldDiskCatalog, ...previous].map((item) => [item.id, item])
).values()) {
if (!remaining.has(entity.id) && kind !== "nowPlaying") {
await AppIntents.deleteDonationsAsync({ entity: kind, id: entity.id })
}
}
await native.replaceCatalog(kind, JSON.stringify(entities))
await AppIntents.setEntityCatalogAsync(kind, suggestions)
})
publishing = write
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
) {
await native?.completeInvocation(token, error)
}
/** Donation errors never turn a completed user action into a playback failure. */
export async function donateMusicPlay(
kind: MusicEntityKind,
id: string,
shuffle = false
) {
if (!native || !AppIntents.isAvailable()) return
try {
await catalogSync
await publishing
await AppIntents.donateIntentAsync("playMusic", { kind, id, shuffle })
} catch (error) {
console.warn("Could not donate music playback.", error)
}
}