aboutsummaryrefslogtreecommitdiffstats
path: root/lib/nostr.js
blob: 677f14e57c53c0ea1f938656b7e7ac5791188a5b (plain) (blame)
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
import { Relay, RelayPool } from "nostr";
import { got } from "got";
import { broadcast } from "$lib/sockets";
import store from "$lib/store";
import redis from "$lib/redis";

const { relays } = await got("https://nostr.watch/relays.json").json();
export const pool = RelayPool(relays);

let coinos;
pool.on("open", relay => {
  if (relay.url.includes("coinos")) coinos = relay;
  relay.subscribe("live", { limit: 1 });
});

let seen = [];
let timeout;
pool.on("event", async (relay, sub, ev) => {
  try {
    if (sub === "live") {
      if (Math.abs(Math.floor(Date.now() / 1000) - ev.created_at) > 7200)
        return;

      if (seen.includes(ev.id)) return;
      seen.push(ev.id);
      seen.length > 1000 && seen.shift();

      if (coinos && ev.kind < 5) {
        let parsed;
        try {
          parsed = JSON.parse(ev.content);
        } catch (e) {
          parsed = ev.content;
        }

        coinos.send(["EVENT", ev]);
        if (ev.kind === 1) broadcast("event", ev);
      }
    } else {
      let pubkey = sub;
      clearTimeout(store.timeouts[pubkey]);

      store.fetching[pubkey] = true;
      await redis.sAdd(pubkey, ev.id);
      await redis.set(`ev:${ev.id}`, JSON.stringify(ev));

      store.timeouts[pubkey] = setTimeout(() => (store.fetching[pubkey] = false), 100);
    }
  } catch (e) {
    console.log(e);
  }
});