all repos — underbbs @ 2976d438d90bea2beb4e67272fd628ff163459f2

decentralized social media client

frontend/ts/websocket.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
68
69
70
71
72
73
74
75
import util from "./util"
import {AdapterState, AdapterData} from "./adapter";
import {Message, Attachment, Author} from "./message"
import {Settings} from "./settings"


export class DatagramSocket {
  public static skey: string | null = null;
  public static conn: WebSocket | null;


  private static onOpen(e: Event) {
    console.log("websocket connection opened");
    console.log(JSON.stringify(e));
  }
  
  private static onMsg(e: MessageEvent) {
    const data = JSON.parse(e.data);
    console.log(data);
    if (data.key) {
      DatagramSocket.skey = data.key;
      util.authorizedFetch("POST", "/api/adapters", JSON.stringify(Settings._instance.adapters))
      .then(r=> {
        if (r.ok) {
          const tabbar = document.querySelector("underbbs-tabbar");
          if (tabbar) {
            tabbar.setAttribute("data-adapters", Settings._instance.adapters.map(a=>a.nickname).join(","));
          }
        }
      })
      .catch(e => {
        util.errMsg(e.message);
      });
    } else {
      let store = AdapterState._instance.data.get(data.adapter);
      if (!store) {
        AdapterState._instance.data.set(data.adapter, new AdapterData(data.protocol));
        store = AdapterState._instance.data.get(data.adapter);
      } else {      
        // typeswitch on the incoming data type and fill the memory
        switch (data.type) {
          case "message":
            store.messages.set(data.id, <Message>data);
            break;
          case "author":
            store.profileCache.set(data.id, <Author>data);
            break;
          default:
            break;
        }
      }
      // if the adapter is active signal it that there's new data
      let adapter = util.$(`adapter_${data.adapter}`);
      if (adapter) {
        adapter.setAttribute("data-latest", data.id);
      }
    }
  }

  static connect(): void {



    const wsProto = location.protocol == "https:" ? "wss" : "ws";
    const _conn = new WebSocket(`${wsProto}://${location.host}/subscribe`, "underbbs");
    _conn.addEventListener("open", DatagramSocket.onOpen);
    _conn.addEventListener("message", DatagramSocket.onMsg);
    _conn.addEventListener("error", (e: any) => {
      console.log("websocket connection error");
      console.log(JSON.stringify(e));
    });
    DatagramSocket.conn = _conn;
  }
}