import * as eventsDB from '@/db/events.ts'; import { type Event, findReplyTag } from '@/deps.ts'; import { type DittoFilter, type Relation } from '@/filter.ts'; import * as mixer from '@/mixer.ts'; interface GetEventOpts { /** Timeout in milliseconds. */ timeout?: number; /** Event kind. */ kind?: K; /** Relations to include on the event. */ relations?: Relation[]; } /** Get a Nostr event by its ID. */ const getEvent = async ( id: string, opts: GetEventOpts = {}, ): Promise | undefined> => { const { kind, relations, timeout = 1000 } = opts; const filter: DittoFilter = { ids: [id], relations, limit: 1 }; if (kind) { filter.kinds = [kind]; } const [event] = await mixer.getFilters([filter], { limit: 1, timeout }); return event; }; /** Get a Nostr `set_medatadata` event for a user's pubkey. */ const getAuthor = async (pubkey: string, timeout = 1000): Promise | undefined> => { const [event] = await mixer.getFilters([{ authors: [pubkey], kinds: [0], limit: 1 }], { limit: 1, timeout }); return event; }; /** Get users the given pubkey follows. */ const getFollows = async (pubkey: string, timeout = 1000): Promise | undefined> => { const [event] = await mixer.getFilters([{ authors: [pubkey], kinds: [3], limit: 1 }], { limit: 1, timeout }); return event; }; /** Get pubkeys the user follows. */ async function getFollowedPubkeys(pubkey: string): Promise { const event = await getFollows(pubkey); if (!event) return []; return event.tags .filter((tag) => tag[0] === 'p') .map((tag) => tag[1]); } /** Get pubkeys the user follows, including the user's own pubkey. */ async function getFeedPubkeys(pubkey: string): Promise { const authors = await getFollowedPubkeys(pubkey); return [...authors, pubkey]; } async function getAncestors(event: Event<1>, result = [] as Event<1>[]): Promise[]> { if (result.length < 100) { const replyTag = findReplyTag(event); const inReplyTo = replyTag ? replyTag[1] : undefined; if (inReplyTo) { const parentEvent = await getEvent(inReplyTo, { kind: 1, relations: ['author'] }); if (parentEvent) { result.push(parentEvent); return getAncestors(parentEvent, result); } } } return result.reverse(); } function getDescendants(eventId: string): Promise[]> { return mixer.getFilters([{ kinds: [1], '#e': [eventId], relations: ['author'] }], { limit: 200, timeout: 2000 }); } /** Returns whether the pubkey is followed by a local user. */ async function isLocallyFollowed(pubkey: string): Promise { const [event] = await eventsDB.getFilters([{ kinds: [3], '#p': [pubkey], local: true, limit: 1 }], { limit: 1 }); return Boolean(event); } export { getAncestors, getAuthor, getDescendants, getEvent, getFeedPubkeys, getFollowedPubkeys, getFollows, isLocallyFollowed, };