ditto/src/firehose.ts

70 lines
1.9 KiB
TypeScript
Raw Normal View History

import { insertEvent, isLocallyFollowed } from '@/db/events.ts';
import { addRelays, getAllRelays } from '@/db/relays.ts';
2023-08-09 19:24:49 +00:00
import { findUser } from '@/db/users.ts';
import { RelayPool } from '@/deps.ts';
import { trends } from '@/trends.ts';
import { isRelay, nostrDate, nostrNow } from '@/utils.ts';
2023-08-06 20:03:29 +00:00
import type { SignedEvent } from '@/event.ts';
2023-07-25 23:22:05 +00:00
const relays = await getAllRelays();
const pool = new RelayPool(relays);
2023-07-25 23:22:05 +00:00
// This file watches all events on your Ditto relay and triggers
// side-effects based on them. This can be used for things like
// notifications, trending hashtag tracking, etc.
pool.subscribe(
[{ kinds: [1], since: nostrNow() }],
relays,
handleEvent,
undefined,
undefined,
);
2023-08-14 16:02:09 +00:00
/** Handle events through the firehose pipeline. */
async function handleEvent(event: SignedEvent): Promise<void> {
2023-08-14 16:02:09 +00:00
console.info('firehose event:', event.id);
2023-07-25 23:22:05 +00:00
trackHashtags(event);
trackRelays(event);
2023-08-09 19:24:49 +00:00
if (await findUser({ pubkey: event.pubkey }) || await isLocallyFollowed(event.pubkey)) {
insertEvent(event).catch(console.warn);
}
2023-07-25 23:22:05 +00:00
}
/** Track whenever a hashtag is used, for processing trending tags. */
2023-08-06 20:03:29 +00:00
function trackHashtags(event: SignedEvent): void {
const date = nostrDate(event.created_at);
const tags = event.tags
.filter((tag) => tag[0] === 't')
2023-07-26 14:40:52 +00:00
.map((tag) => tag[1])
.slice(0, 5);
2023-07-26 01:55:12 +00:00
if (!tags.length) return;
try {
2023-07-26 01:55:12 +00:00
console.info('tracking tags:', tags);
trends.addTagUsages(event.pubkey, tags, date);
} catch (_e) {
// do nothing
}
2023-07-25 23:22:05 +00:00
}
/** Tracks nown relays in the database. */
function trackRelays(event: SignedEvent) {
const relays = new Set<`wss://${string}`>();
event.tags.forEach((tag) => {
if (['p', 'e', 'a'].includes(tag[0]) && isRelay(tag[2])) {
relays.add(tag[2]);
}
if (event.kind === 10002 && tag[0] === 'r' && isRelay(tag[1])) {
relays.add(tag[1]);
}
});
return addRelays([...relays]);
}