95 lines
2.6 KiB
TypeScript
95 lines
2.6 KiB
TypeScript
import AsyncStorage from "@react-native-async-storage/async-storage"
|
|
import * as AppIntents from "expo-app-intents"
|
|
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 = [
|
|
"song",
|
|
"album",
|
|
"artist",
|
|
"playlist",
|
|
"nowPlaying",
|
|
] as const
|
|
|
|
export async function clearAppIntentCatalogs() {
|
|
if (!AppIntents.isAvailable()) {
|
|
return
|
|
}
|
|
const results = await Promise.allSettled([
|
|
AsyncStorage.removeItem(CATALOG_CURSORS_KEY),
|
|
AppIntents.deleteDonationsAsync({ intent: "playMusic" }),
|
|
AppIntents.clearPendingInvocationsAsync(),
|
|
...CATALOG_KINDS.map((kind) => publishMusicCatalog(kind, [])),
|
|
])
|
|
const failed = results.find((result) => result.status === "rejected")
|
|
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) {
|
|
return new Set<string>()
|
|
}
|
|
try {
|
|
const parsed = JSON.parse(raw) as unknown
|
|
if (!Array.isArray(parsed)) {
|
|
return new Set<string>()
|
|
}
|
|
return new Set(parsed.filter((id) => typeof id === "string"))
|
|
} catch {
|
|
return new Set<string>()
|
|
}
|
|
}
|
|
|
|
export async function rememberHandledIntentId(ids: Set<string>, id: string) {
|
|
ids.add(id)
|
|
const list = [...ids]
|
|
const trimmed =
|
|
list.length > MAX_HANDLED ? list.slice(list.length - MAX_HANDLED) : list
|
|
if (trimmed.length !== list.length) {
|
|
ids.clear()
|
|
for (const item of trimmed) {
|
|
ids.add(item)
|
|
}
|
|
}
|
|
await AsyncStorage.setItem(HANDLED_KEY, JSON.stringify(trimmed))
|
|
}
|