all repos — underbbs @ 529c031c41c76b307bfbc3725a88544479b51dc1

decentralized social media client

ts/index.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import {Adapter} from "./adapter";
import {Message, Attachment} from "./message"

function _(key: string, value: any | null | undefined = undefined): any | null {
  const x = <any>window;
  if (value !== undefined) {
    x[key] = value;
  }
  return x[key];
}

function $(id: string): HTMLElement | null {
  return document.getElementById(id);
}

function main():void  {
  const settings = _("settings", JSON.parse(localStorage.getItem("settings") ?? "{}"));
  const adapters = _("adapters", []);
  
  if (settings != null) {
    for (let s of settings.adapters ?? []) {
      let a: Adapter = Adapter.create()
      switch (s.protocol) {
        case "nostr": 
          adapters.push(Adapter.toNostr(a, s));
          break;
        case "mastodon":
          adapters.push(Adapter.toMasto(a, s));
      }
    }
    if (adapters.length > 0) {
      _("currentAdapter", 0);
      // update tabbar and tabcontent with first adapter
    }
  } else {
    console.log("no settings exist for this client");
    _("settings", { adapters: [] });
    showSettings();
  }
  registerServiceWorker();
};

async function registerServiceWorker() {
  if ("serviceWorker" in navigator) {
    try {
      const registration = await navigator.serviceWorker.register("/serviceWorker.js", {
        scope: "/",
      });
      if (registration.installing) {
        console.log("Service worker installing");
      } else if (registration.waiting) {
        console.log("Service worker installed");
      } else if (registration.active) {
        console.log("Service worker active");
      }
    } catch (error) {
      console.error(`Registration failed with ${error}`);
    }
    const registration = await navigator.serviceWorker.ready;
    (registration as any).sync.register("testdata").then((r:any)=>{console.log("but i will see this!")});
  }
};


function showSettings():void {
  // tab bar hidden
  const tabbar = $("tabbar");
  if (tabbar) {
  tabbar.style.display = "none";
  }
  
  // tabcontent to show settings ui
  const tabcontent = $("tabcontent");
  const adapters = _("adapters") as Adapter[] ?? [];
  
  if (tabcontent) {
    let html = "<p>this is our settings dialogue</p>";
    html += "<button onclick='addAdapter()'>New</button>";
    html += adapters.reduce((self: string, a: Adapter) => {
      self += `<li><a href='#' onclick='editAdapter(${a.nickname})'>${a.nickname}</a></li>`
      return self;
    }, "<ul id='settings_adapterlist'>");
    html += "</ul>";
    html += "<button onclick='saveSettings()'>save</button>";
    tabcontent.innerHTML = html;
  }
}

function addAdapter(): void {
  const tabcontent = $("tabcontent");
  if (tabcontent) {
    // dropdown for protocol
    let html = "<select id='settings_newadapter_protocolselect' onchange='fillAdapterProtocolOptions()'>";
    html += [ "nostr", "mastodon" ].reduce((self, p)=>{
      self += `<option value='${p}'>${p}</option>`;
      return self;
    }, "");
    html += "</select>";
    
    // nostr is the first protocol, so show its options by default
    html += "<div id='settings_newadapter_protocoloptions'>";
    html += "  <label>nickname<input id='settings_newadapter_nickname'/></label>";
    html += "  <label>privkey<input id='settings_newadapter_nostr_privkey'/></label>";
    html += "  <label>default relays<input id='settings_newadapter_nostr_default_relays'/></label>";
    html += "</div>";
    
    html += "<button onclick='saveAdapter()'>Add</button>";
    html += "<button onclick='showSettings()'>Back</button>";
  
    tabcontent.innerHTML = html;
  }
}

function fillAdapterProtocolOptions(): void {
  const proto = $("settings_newadapter_protocolselect") as HTMLSelectElement;
  
  let html = "";
  
  switch(proto?.options[proto.selectedIndex].value) {
    case "nostr":
      html += "  <label>nickname<input id='settings_newadapter_nickname'/></label>";
      html += "  <label>privkey<input id='settings_newadapter_nostr_privkey'/></label>";
      html += "  <label>default relays<input id='settings_newadapter_nostr_default_relays'/></label>";
      break;
    case "mastodon":
      html += "  <label>nickname<input id='settings_newadapter_nickname'/></label>";
      html += "  <label>server<input id='settings_newadapter_masto_server'/></label>";
      html += "  <label>API key<input id='settings_newadapter_masto_apikey'/></label>";
      break;
  }
  
  
  const div = $("settings_newadapter_protocoloptions");
  if (div) {
    div.innerHTML = html;
  }
}

function saveSettings(): void {
  const settings = _("settings");
  if (settings) {
    localStorage.setItem("settings", JSON.stringify(settings));
  }
  // tab bar hidden
  const tabbar = $("tabbar");
  if (tabbar) {
    tabbar.style.display = "block";
  }
  
  // tabcontent to show settings ui
  const tabcontent = $("tabcontent");
  if (tabcontent) {
    tabcontent.innerHTML = "";
  }
}

function saveAdapter(): void {
  let self: any = {};
  // get selected adapter protocol
  const proto = $("settings_newadapter_protocolselect") as HTMLSelectElement;
  console.log(proto.options[proto.selectedIndex]);
  
  
  const nickname = ($("settings_newadapter_nickname") as HTMLInputElement)?.value ?? "" ;
  
  // switch protocol
  switch (proto.options[proto.selectedIndex].value) {
    case "nostr":
        const privkey = ($("settings_newadapter_nostr_privkey") as HTMLInputElement)?.value ?? "";
        const relays = ($("settings_newadapter_nostr_default_relays") as HTMLInputElement)?.value ?? "";
        self = { nickname: nickname, protocol: "nostr", privkey: privkey, relays: relays.split(",").map(r=>r.trim()) };
      break;
    case "mastodon":
      const server = ($("settings_newadapter_masto_server") as HTMLInputElement)?.value ?? "";
      const apiKey = ($("settings_newadapter_masto_apikey") as HTMLInputElement)?.value ?? "";
      self = { nickname: nickname, protocol: "mastodon", server: server, apiKey: apiKey };
      break;
  }
  const settings = _("settings");
  const adapters = _("adapters");
  if (settings && adapters) {
    if (!settings.adapters) {
      settings.adapters = [];
    }
    settings.adapters.push(self);
    let a: Adapter = Adapter.create();
    switch (self.protocol) {
      case "nostr":
        adapters.push(Adapter.toNostr(a, self));
        break;
      case "mastodon":
        adapters.push(Adapter.toMasto(a, self));
        break;
    }
    localStorage.setItem("settings", JSON.stringify(settings));
    showSettings();
  }
}


let _conn: WebSocket | null = null;

function connect() {
  // import the data from the settings
  const settings = _("settings");
  if (settings) {
  
  // base64 encode the settings data
    let subprotocol: string = "[";
    for (let a of settings.adapters) {
      subprotocol += JSON.stringify(a) + ",";
    }
    subprotocol += "]";
    subprotocol = btoa(subprotocol);
    
    // open the websocket connection with settings as subprotocol
    const wsProto = location.protocol == "https:" ? "wss" : "ws";
    _conn = new WebSocket(`${wsProto}://${location.host}/subscribe`, subprotocol);
    _("websocket", _conn);
  }
}

_("addAdapter", addAdapter);
_("saveAdapter", saveAdapter);
_("fillAdapterProtocolOptions", fillAdapterProtocolOptions);
_("showSettings", showSettings);
_("saveSettings", saveSettings);
_("connect", connect);
main();