thelounge/client/js/socket.js

60 lines
1.8 KiB
JavaScript
Raw Normal View History

2017-04-18 09:31:46 +02:00
"use strict";
const $ = require("jquery");
const io = require("socket.io-client");
const socket = io({
transports: $(document.body).data("transports"),
path: window.location.pathname + "socket.io/",
2017-04-18 09:31:46 +02:00
autoConnect: false,
reconnection: !$(document.body).hasClass("public"),
2017-04-18 09:31:46 +02:00
});
2018-07-08 19:53:23 +02:00
module.exports = socket;
const {vueApp} = require("./vue");
const {requestIdleCallback} = require("./utils");
2017-08-28 17:03:27 +02:00
socket.on("disconnect", handleDisconnect);
socket.on("connect_error", handleDisconnect);
socket.on("error", handleDisconnect);
socket.on("reconnecting", function(attempt) {
2018-09-09 15:09:19 +02:00
vueApp.currentUserVisibleError = `Reconnecting… (attempt ${attempt})`;
$("#loading-page-message").text(vueApp.currentUserVisibleError);
2017-04-18 09:31:46 +02:00
});
socket.on("connecting", function() {
2018-09-09 15:09:19 +02:00
vueApp.currentUserVisibleError = "Connecting…";
$("#loading-page-message").text(vueApp.currentUserVisibleError);
2017-04-18 09:31:46 +02:00
});
socket.on("connect", function() {
// Clear send buffer when reconnecting, socket.io would emit these
// immediately upon connection and it will have no effect, so we ensure
// nothing is sent to the server that might have happened.
socket.sendBuffer = [];
2018-09-09 15:09:19 +02:00
vueApp.currentUserVisibleError = "Finalizing connection…";
$("#loading-page-message").text(vueApp.currentUserVisibleError);
2017-04-18 09:31:46 +02:00
});
socket.on("authorized", function() {
2018-09-09 15:09:19 +02:00
vueApp.currentUserVisibleError = "Loading messages…";
$("#loading-page-message").text(vueApp.currentUserVisibleError);
2017-04-18 09:31:46 +02:00
});
2017-08-28 17:03:27 +02:00
function handleDisconnect(data) {
const message = data.message || data;
2018-09-09 15:09:19 +02:00
vueApp.isConnected = false;
vueApp.currentUserVisibleError = `Waiting to reconnect… (${message})`;
$("#loading-page-message").text(vueApp.currentUserVisibleError);
2017-09-10 17:28:28 +02:00
// If the server shuts down, socket.io skips reconnection
// and we have to manually call connect to start the process
if (socket.io.skipReconnect) {
2018-07-08 19:53:23 +02:00
requestIdleCallback(() => socket.connect(), 2000);
2017-09-10 17:28:28 +02:00
}
2017-08-28 17:03:27 +02:00
}