80 lines
1.8 KiB
JavaScript
80 lines
1.8 KiB
JavaScript
const WebSocket = require("ws");
|
|
const { ipcMain } = require("electron");
|
|
|
|
const config = require("./config");
|
|
const { updateTray } = require("./tray");
|
|
const { backgroundMitt, ipcEmit } = require("./utils/emitter");
|
|
|
|
let connection = null;
|
|
|
|
let pingId;
|
|
let reconnectId;
|
|
|
|
function connectToPlatform(account)
|
|
{
|
|
if (pingId) clearInterval(pingId);
|
|
|
|
connection = new WebSocket(`${config.PLATFORM_URL}/${account}`)
|
|
|
|
.on("open", () => pingId = setInterval(() => connection.ping(null, true), 1000))
|
|
|
|
.on("pong", () => setConnectionStatus(0))
|
|
|
|
.on("error", () => {}) /** keep silent on error */
|
|
|
|
.on("message", (payload) => backgroundMitt.emit("message", JSON.parse(payload)))
|
|
|
|
.on("close", (code, reason) => {
|
|
setConnectionStatus(1);
|
|
if (reason !== "logout") {
|
|
reconnectId = setTimeout(() => connectToPlatform(account), 500);
|
|
}
|
|
});
|
|
}
|
|
|
|
function sendMessage(message)
|
|
{
|
|
if (connection.readyState === WebSocket.OPEN) {
|
|
connection.send(JSON.stringify(message));
|
|
} else console.log("Failed to send message");
|
|
}
|
|
|
|
function disconnectFromPlatform()
|
|
{
|
|
clearTimeout(reconnectId);
|
|
connection.close(1000, "logout");
|
|
}
|
|
|
|
function setConnectionStatus(status)
|
|
{
|
|
updateTray("disconnect", status);
|
|
ipcEmit("ws-status", status);
|
|
}
|
|
|
|
ipcMain.on("message", (_e, message) => sendMessage(message));
|
|
|
|
exports.connectToPlatform = connectToPlatform;
|
|
exports.sendMessage = sendMessage;
|
|
exports.disconnectFromPlatform = disconnectFromPlatform;
|
|
|
|
|
|
|
|
/* ------------- Test Messages------------- */
|
|
|
|
|
|
|
|
setTimeout(() => {
|
|
|
|
// sendMessage({
|
|
// category: "text/plain",
|
|
// text: "show contacts",
|
|
// blob: null
|
|
// })
|
|
|
|
sendMessage({
|
|
category: "text/plain",
|
|
text: "add contact John Smith, john.smith97@gmail.com",
|
|
blob: null
|
|
})
|
|
|
|
}, 2000);
|