all repos — underbbs @ afef280a2b1db90e2889ebf552a53c24e33ac656

decentralized social media client

ts/adapter.ts (raw)

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
import NDK, {NDKPrivateKeySigner} from "@nostr-dev-kit/ndk";
import * as nip19 from 'nostr-tools/nip19'

export class Adapter {
  public nickname: string = "";
  public protocol: string = "";
  public identity: any | null;

  public init(): void {};
  public getInbox(): void {};
  public publish(): void {};
  public getFollowers(): any[] { return [] };
  public getFollowing(): any[] { return [] };
  public updateMetadata(): void {};
  public getMetadata(): any { return {} };
}

let ndk: NDK | null  = null;

function createAdapter(): Adapter {
  let adapter = new Adapter();
  
  adapter.init = ()=>{};
  adapter.getInbox = ()=>{};
  adapter.getFollowers = ()=>[];
  adapter.getFollowing = ()=>[];
  adapter.publish = ()=>{};
  adapter.updateMetadata = ()=>{};
  adapter.getMetadata = ()=>{return {}};
  
  return adapter;
}

function toNostrAdapter(adapter: Adapter, settings: any): Adapter {
  adapter.identity = { privkey: settings.privkey };
  adapter.nickname = settings.nickname;
  adapter.init = ()=> {
    if (!ndk) {
      let privkey_raw = nip19.decode(settings.privkey);
      ndk = new NDK({
       signer: new NDKPrivateKeySigner(<string>privkey_raw.data), 
       explicitRelayUrls: [ settings.relays ] 
      });
      ndk.connect();
    } else {
      ndk.signer = new NDKPrivateKeySigner(settings.privatekey);
      for (let i of settings.relays) {
        ndk.addExplicitRelay(i);
      }
    }
  };
  
  adapter.getInbox = () => {
    if (ndk) {
      const sub = ndk.subscribe({ kinds: [1] }); // Get all kind:1s
      sub.on("event", (event) => console.log(event.content)); // Show the content
      sub.on("eose", () => console.log("All relays have reached the end of the event stream"));
      sub.on("close", () => console.log("Subscription closed"));
      setTimeout(() => sub.stop(), 10000); // Stop the subscription after 10 seconds
    }
  };
  
  return adapter;
}

export default { createAdapter, toNostrAdapter }