all repos — underbbs @ 9dc27a4b9a016a92b6ab8f0041e3c5319e147913

decentralized social media client

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
import util from "./util"
import {AdapterState, AdapterData} from "./adapter";
import {Message, Attachment, Author} from "./message"

var $ = util.$
var _ = util._

function connect() {

   let datastore = <AdapterState>_("datastore", {});

    const wsProto = location.protocol == "https:" ? "wss" : "ws";
    const _conn = new WebSocket(`${wsProto}://${location.host}/subscribe`, "underbbs");
    _conn.addEventListener("open", (e: any) => {
      console.log("websocket connection opened");
      console.log(JSON.stringify(e));
    });
    _conn.addEventListener("message", (e: any) => {
      const data = JSON.parse(e.data);
      console.log(data);
      if (data.key) {
        _("skey", data.key)
        util.authorizedFetch("POST", "/api/adapters", JSON.stringify(_("settings").adapters))
      } else {
        if (!datastore[data.adapter]) {
          datastore[data.adapter] = new AdapterData(data.protocol);
        }
      
        // typeswitch on the incoming data type and fill the memory
        switch (data.type) {
          case "message":
            datastore[data.adapter].messages.set(data.id, <Message>data);
            break;
          case "author":
            datastore[data.adapter].profileCache.set(data.id, <Author>data);
            break;
          default:
            break;
        }
        // if the adapter is active signal it that there's new data
        let adapter = $(`adapter_${data.adapter}`);
        if (adapter) {
          adapter.setAttribute("data-latest", data.id);
        }
      }
    });
    _conn.addEventListener("error", (e: any) => {
      console.log("websocket connection error");
      console.log(JSON.stringify(e));
    });
    _("websocket", _conn);
}

export default { connect }