-
Notifications
You must be signed in to change notification settings - Fork 0
/
nostrrepo.ts
91 lines (78 loc) · 2.71 KB
/
nostrrepo.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import NDK, { NDKEvent, NDKFilter } from "@nostr-dev-kit/ndk";
import { passes_reply, text_filter } from "./filters.ts";
import { getTagsMultiple } from "./utils.ts";
class NostrRepository {
//TODO: Make private. its public just for dummy opml repo
public ndk: NDK;
constructor(ndk: NDK) {
this.ndk = ndk;
}
async getOpenEndedEvents(
filter,
whereToStoreEvents: Set<NDKEvent>,
): Promise<boolean> {
// Create a filter
console.log(`nostr repo: filter is: ${filter.listownerid}`);
const subscribedToUsers: string[] =
await (this.getSubscriptionsOf(filter.listownerid));
const ndkfilter: NDKFilter = {
kinds: [1, 30023],
authors: subscribedToUsers,
};
const p: Promise<boolean> = new Promise((resolve, reject) => {
//console.log(`nostr repo: subscribing to ${subscribedToUsers}`);
const sub = this.ndk.subscribe(ndkfilter, { closeOnEose: true });
console.log("nostr repo: subscribed");
sub.on("event", (event: NDKEvent) => {
whereToStoreEvents.add(event);
//console.log("nostr repo: got an event");
});
sub.on("eose", () => {
console.log("End of stream reached. Subscription will now close.");
resolve(true);
});
});
return p;
}
static async fetchNostrEvents(
ndk: NDK,
filter,
whitelist: string[],
replies: boolean,
blacklist: string[],
) {
const events = await ndk.fetchEvents(filter);
const filteredevents = Array.from(events).filter((item) => {
return passes_reply(item.tags, replies) &&
text_filter(item.content, whitelist, blacklist);
}).sort((a, b) => b.created_at - a.created_at);
const approval_ratio: number = filteredevents.length / events.size;
console.log(
`Current filter approved ${approval_ratio * 100} pct of events`,
);
return new Set(filteredevents);
}
async getSubscriptionsOf(listownerid: string) {
let subscribedToUsers: string[] = [];
if (listownerid !== undefined) {
//Gets pubkey if userid is a nip05
const nip05_separator = ".";
let userpubkey: string;
if (listownerid.includes(nip05_separator)) {
userpubkey = (await this.ndk.getUserFromNip05(listownerid)).pubkey;
} else if (listownerid.startsWith("npub")) {
userpubkey = this.ndk.getUser({ npub: listownerid }).pubkey;
}
const userListEvent: NDKEvent = await this.ndk.fetchEvent({
kinds: [3, 30023],
authors: [userpubkey],
});
subscribedToUsers = getTagsMultiple(userListEvent.tags, "p").flat();
console.log(
`NOST REPO: LIst subscribe to ${subscribedToUsers.length} users`,
);
}
return subscribedToUsers;
}
}
export { NostrRepository };