var socket; function load() { socket = init_websocket(); let intervalID = window.setInterval(update, 5000); } function init_websocket() { let socket = new WebSocket('wss://' + window.location.hostname + ws_uri); socket._send = socket.send; socket.send = function(event_title, data) { data = JSON.stringify({event: event_title, data: data}); if (socket.readyState == 0) { console.log("Socket is still opening!"); return; } socket._send(data); } socket.onmessage = onmessage; socket.onclose = onclose; socket.onerror = onerror; socket.events = {}; socket.events['active_torrents'] = active_torrents_recv; socket.events['tracker_stats'] = tracker_stats_recv; return socket; } function onmessage (e) { let data = JSON.parse(e.data); let event = data.event; data = data.data; if (socket.events[event] === undefined) { console.log("Unknown socket event: " + event); return; } socket.events[event](data); } function onclose(e) { if (e.wasClean) { return; } // no need to reconnect console.log(e); console.log('Websocket lost connection to server. Re-trying...'); socket = init_websocket(); } function onerror(e) { console.log("Websocket error!") console.log(e); } /* Websocket receive */ function active_torrents_recv(data) { let table = document.querySelector('#torrents tbody'); while (table.firstChild) { table.removeChild(table.firstChild); } data.forEach(function(torrent) { let template = document.querySelector('#torrent_template'); let node = document.importNode(template.content, true); for (let field of node.children[0].children) { field.textContent = torrent[field.className]; } table.appendChild(node); }); } function tracker_stats(data) { let table = document.querySelector('#tracker_stats tbody'); while (table.firstChild) { table.removeChild(table.firstChild); } for (let [tracker, values] of Object.entries(data)) { let template = document.querySelector('#tracker_template'); let node = document.importNode(template.content, true); node.children[0].children[0].textContent = tracker; for (let i = 0; i < values.length; i++) { node.children[0].children[i+1].textContent = values[i]; } table.appendChild(node); } } /* Websocket send */ function get_active_torrents() { socket.send('active_torrents', {}); } function get_tracker_stats() { socket.send('tracker_stats', {}); } /* Helper */ function update() { get_active_torrents(); get_tracker_stats(); }