2024-07-01 03:51:25 +00:00
|
|
|
import util from "./util"
|
|
|
|
import {AdapterState, AdapterData} from "./adapter";
|
|
|
|
import {Message, Attachment, Author} from "./message"
|
|
|
|
|
|
|
|
var $ = util.$
|
|
|
|
var _ = util._
|
|
|
|
|
|
|
|
function connect() {
|
|
|
|
|
2024-07-05 01:27:29 +00:00
|
|
|
let datastore = <AdapterState>_("datastore", {});
|
2024-07-01 03:51:25 +00:00
|
|
|
|
|
|
|
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);
|
2024-07-05 01:27:29 +00:00
|
|
|
console.log(data);
|
2024-07-01 03:51:25 +00:00
|
|
|
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;
|
|
|
|
}
|
2024-07-06 18:43:25 +00:00
|
|
|
// if the adapter is active signal it that there's new data
|
2024-07-05 01:27:29 +00:00
|
|
|
let adapter = $(`adapter_${data.adapter}`);
|
|
|
|
if (adapter) {
|
|
|
|
adapter.setAttribute("data-latest", data.id);
|
|
|
|
}
|
2024-07-01 03:51:25 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
_conn.addEventListener("error", (e: any) => {
|
|
|
|
console.log("websocket connection error");
|
|
|
|
console.log(JSON.stringify(e));
|
|
|
|
});
|
|
|
|
_("websocket", _conn);
|
|
|
|
}
|
|
|
|
|
|
|
|
export default { connect }
|