blowater/UI/event_syncer.ts

76 lines
2.6 KiB
TypeScript
Raw Normal View History

2023-08-28 17:58:05 +00:00
import { ConnectionPool, SubscriptionAlreadyExist } from "../lib/nostr-ts/relay.ts";
2023-07-11 09:49:58 +00:00
import { Database_Contextual_View } from "../database.ts";
import { NostrFilters, NostrKind, RelayResponse_REQ_Message, verifyEvent } from "../lib/nostr-ts/nostr.ts";
2023-08-28 17:58:05 +00:00
import { Channel } from "https://raw.githubusercontent.com/BlowaterNostr/csp/master/csp.ts";
import { NoteID } from "../lib/nostr-ts/nip19.ts";
export class EventSyncer {
2023-07-11 09:49:58 +00:00
constructor(private readonly pool: ConnectionPool, private readonly db: Database_Contextual_View) {}
2023-07-30 06:39:53 +00:00
syncEvent(id: NoteID) {
for (const e of this.db.events) {
if (e.id == id.hex) {
return e;
}
}
return (async () => {
2023-08-28 17:58:05 +00:00
let events: Error | {
filter: NostrFilters;
chan: Channel<{
res: RelayResponse_REQ_Message;
url: string;
}>;
} = await this.pool.newSub("EventSyncer", {
ids: [id.hex],
});
if (events instanceof SubscriptionAlreadyExist) {
events = await this.pool.updateSub("EventSyncer", {
ids: [id.hex],
});
}
if (events instanceof Error) {
return events;
}
2023-08-28 17:58:05 +00:00
for await (const { res, url } of events.chan) {
2023-09-04 21:32:47 +00:00
if (res.type != "EVENT") {
continue;
}
const ok = await verifyEvent(res.event);
if (!ok) {
console.warn(res.event, url, "not valid");
continue;
}
await this.db.addEvent(res.event);
return; // just need to read from 1 relay
}
})();
}
2023-07-30 06:39:53 +00:00
2023-08-03 09:13:16 +00:00
async syncEvents(filter: NostrFilters) {
2023-08-28 17:58:05 +00:00
let events: Error | {
filter: NostrFilters;
chan: Channel<{
res: RelayResponse_REQ_Message;
url: string;
}>;
} = await this.pool.newSub("syncEvents", filter);
2023-08-03 09:13:16 +00:00
if (events instanceof SubscriptionAlreadyExist) {
events = await this.pool.updateSub("syncEvents", filter);
}
if (events instanceof Error) {
return events;
}
2023-08-28 17:58:05 +00:00
for await (const { res, url } of events.chan) {
2023-09-04 21:32:47 +00:00
if (res.type != "EVENT") {
2023-08-03 09:13:16 +00:00
continue;
}
const ok = await verifyEvent(res.event);
if (!ok) {
console.warn(res.event, url, "not valid");
continue;
}
await this.db.addEvent(res.event);
}
2023-07-30 06:39:53 +00:00
}
}