// The subscription records this extension reads and writes. // // The popup and the subscriptions page must create the same record shape and // delete by the same key, so the writes live here rather than in either page. // Every successful write also drops the worker's `own` subscription cache: the // popup reads that key to know whether a publication is subscribed, and a // manager that unsubscribes without dropping it would leave the popup // insisting the subscription is still there. import type { Agent } from '@atproto/api' import { blobUrl, getRecord, isBlobRef, listRecords, parseAtUri, resolveDid, } from './atproto' import { cached, invalidate } from './cache' import { SUBSCRIPTION_COLLECTION, type PublicationSummary, type SubscriptionEntry, hostOf, parseSubscription, safeHttpUrl, } from './subscription-list' import type { PublicationRecord } from './types' export { SUBSCRIPTION_COLLECTION } /** The signed-in account's subscription records, newest-first is not assumed. */ export async function loadSubscriptions(did: string): Promise { const { pds } = await resolveDid(did) const records = await listRecords(pds, did, SUBSCRIPTION_COLLECTION) const entries: SubscriptionEntry[] = [] for (const record of records) { const entry = parseSubscription(record) if (entry) entries.push(entry) else console.debug('[substandard] ignored malformed subscription record', record.uri) } console.debug(`[substandard] read ${entries.length} subscription records for ${did}`) return entries } /** * A publication's public details, cached under `world` for a day. A record * that cannot be read throws rather than returning a half-row; the page marks * that one row and keeps the rest of the list. */ export async function publicationSummary( uri: string, refresh = false, ): Promise { return cached( { scope: 'world', subject: uri, name: 'publication' }, () => fetchPublicationSummary(uri), { refresh }, ) } async function fetchPublicationSummary(uri: string): Promise { const parsed = parseAtUri(uri) if (!parsed || parsed.collection !== 'site.standard.publication') { throw new Error(`Not a publication at-uri: ${uri}`) } const { pds } = await resolveDid(parsed.did) const { value } = await getRecord( pds, parsed.did, parsed.collection, parsed.rkey, ) return summarizePublication(uri, pds, parsed.did, value) } /** * The record fields the page needs, defensively read: a missing or non-string * name falls back to the host, then to the account DID. */ export function summarizePublication( uri: string, pds: string, did: string, record: PublicationRecord, ): PublicationSummary { const url = safeHttpUrl(record?.url) const host = hostOf(url) const name = typeof record?.name === 'string' && record.name.trim() ? record.name : (host ?? did) const description = typeof record?.description === 'string' ? record.description : undefined const icon = record?.icon return { uri, name, description, url, host, iconUrl: isBlobRef(icon) ? blobUrl(pds, did, icon) : undefined, } } /** * Create the record shape the popup creates. `createdAt` is a parameter so * Undo can put the original subscription date back rather than moving the * publication to the top of the list. */ export async function createSubscription( agent: Agent, did: string, publication: string, createdAt: string = new Date().toISOString(), ): Promise { const { data } = await agent.com.atproto.repo.createRecord({ repo: did, collection: SUBSCRIPTION_COLLECTION, record: { $type: SUBSCRIPTION_COLLECTION, publication, createdAt, }, }) await invalidateOwnSubscriptions(did) const parsed = parseAtUri(data.uri) if (!parsed) throw new Error(`Unexpected subscription uri: ${data.uri}`) return { uri: data.uri, rkey: parsed.rkey, publication, createdAt } } export async function deleteSubscription( agent: Agent, did: string, rkey: string, ): Promise { await agent.com.atproto.repo.deleteRecord({ repo: did, collection: SUBSCRIPTION_COLLECTION, rkey, }) await invalidateOwnSubscriptions(did) } /** The record keys that point at one publication. */ export function rkeysForPublication( entries: readonly SubscriptionEntry[], publication: string, ): string[] { return entries .filter((entry) => entry.publication === publication) .map((entry) => entry.rkey) } /** * Remove every record that subscribes to one publication. Other clients can * leave duplicates; deleting only the rkey the popup cached would leave the * publication looking subscribed. */ export async function deleteSubscriptionsFor( agent: Agent, did: string, publication: string, ): Promise { const entries = await loadSubscriptions(did) const rkeys = rkeysForPublication(entries, publication) for (const rkey of rkeys) { await agent.com.atproto.repo.deleteRecord({ repo: did, collection: SUBSCRIPTION_COLLECTION, rkey, }) } await invalidateOwnSubscriptions(did) return rkeys.length } /** * The worker reads `own/subscriptions` to answer "is this publication * subscribed" for the toolbar badge. Best effort: the write already landed, * and throwing here would make an unsubscribe look like it failed. */ async function invalidateOwnSubscriptions(did: string): Promise { try { await invalidate({ scope: 'own', subject: did, name: 'subs' }) } catch (err) { console.debug('[substandard] could not invalidate subscriptions cache', err) } }