import type { Event } from 'nostr-tools' import { nostrService } from './nostr' import type { SimplePoolWithSub } from '@/types/nostr-tools-extended' import type { Series } from '@/types/nostr' import { parseSeriesFromEvent } from './nostrEventParsing' import { buildTagFilter } from './nostrTagSystem' const RELAY_URL = process.env.NEXT_PUBLIC_NOSTR_RELAY_URL ?? 'wss://relay.damus.io' export function getSeriesByAuthor(authorPubkey: string, timeoutMs: number = 5000): Promise { const pool = nostrService.getPool() if (!pool) { throw new Error('Pool not initialized') } const poolWithSub = pool as SimplePoolWithSub const tagFilter = buildTagFilter({ type: 'series', authorPubkey, }) const filters: Array<{ kinds: number[] authors?: string[] '#series'?: string[] }> = [ { kinds: tagFilter.kinds as number[], ...(tagFilter.authors ? { authors: tagFilter.authors as string[] } : {}), ...(tagFilter['#series'] ? { '#series': tagFilter['#series'] as string[] } : {}), }, ] return new Promise((resolve) => { const results: Series[] = [] const sub = poolWithSub.sub([RELAY_URL], filters) let finished = false const done = () => { if (finished) { return } finished = true sub.unsub() resolve(results) } sub.on('event', (event: Event) => { const parsed = parseSeriesFromEvent(event) if (parsed) { results.push(parsed) } }) sub.on('eose', () => done()) setTimeout(() => done(), timeoutMs).unref?.() }) } export function getSeriesById(seriesId: string, timeoutMs: number = 5000): Promise { const pool = nostrService.getPool() if (!pool) { throw new Error('Pool not initialized') } const poolWithSub = pool as SimplePoolWithSub const filters = [ { kinds: [1], ids: [seriesId], ...buildTagFilter({ type: 'series', }), }, ] return new Promise((resolve) => { const sub = poolWithSub.sub([RELAY_URL], filters) let finished = false const done = (value: Series | null) => { if (finished) { return } finished = true sub.unsub() resolve(value) } sub.on('event', (event: Event) => { const parsed = parseSeriesFromEvent(event) if (parsed) { done(parsed) } }) sub.on('eose', () => done(null)) setTimeout(() => done(null), timeoutMs).unref?.() }) }