websocket connection more resilient

This commit is contained in:
iou1name 2019-11-15 23:27:45 -05:00
parent 485d1e0e4f
commit d2ee6379db
3 changed files with 43 additions and 49 deletions

View File

@ -28,16 +28,11 @@ async def index(request):
tracker_stats = rtorrent.get_stats()
return render_template("index.html", request, locals())
@routes.get(config.prefix + "/get_active_torrents", name='active-torrents')
async def get_active_torrents(request):
"""Returns all active torrents formatted as JSON."""
data = [vars(t) for t in rtorrent.get_active()]
return web.json_response(data)
@routes.get(config.prefix + '/ws', name='ws')
async def websocket_handler(request):
"""The websocket endpoint."""
ws = web.WebSocketResponse()
ws = web.WebSocketResponse(heartbeat=30)
ws_ready = ws.can_prepare(request)
if not ws_ready.ok:
return web.Response(text="Cannot start websocket.")
@ -60,6 +55,7 @@ async def websocket_handler(request):
await ws.close()
return ws
app.router.add_routes(routes)
if __name__ == "__main__":

View File

@ -1,56 +1,55 @@
var socket;
function load() {
//let intervalID = window.setInterval(get_active_torrents_ajax, 20000);
socket = init_websocket();
let intervalID = window.setInterval(update, 5000);
}
function get_active_torrents_ajax() {
let httpRequest;
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState !== XMLHttpRequest.DONE) { return; }
if (httpRequest.status !== 200) { return; }
torrents = JSON.parse(httpRequest.responseText);
let html_str = '';
for (let i = 0; i < torrents.length; i++) {
html_str += '<tr>'
html_str += '<td class="name">' + torrents[i].name + '</td>';
html_str += '<td class="total_size_str">' + torrents[i].total_size_str + '</td>';
html_str += '<td class="state">' + torrents[i].state + '</td>';
html_str += '<td class="downrate_str">' + torrents[i].downrate_str + '</td>';
html_str += '<td class="down_percent">' + torrents[i].down_percent + '%</td>';
html_str += '<td class="eta_str">' + torrents[i].eta_str + '</td>';
html_str += '<td class="uprate_str">' + torrents[i].uprate_str + '</td>';
html_str += '<td class="tracker">' + torrents[i].tracker + '</td>';
html_str += '<td class="rtorrent_id">' + torrents[i].rtorrent_id + '</td>';
html_str += '</tr>';
}
document.getElementById('torrents').children[1].innerHTML = html_str;
};
httpRequest.open('GET', get_torrents_uri, true);
httpRequest.send();
}
var socket = new WebSocket('wss://' + window.location.hostname + ws_uri);
socket.oldSend = socket.send;
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});
socket.oldSend.apply(this, [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.onmessage = function(e) {
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) { return; }
if (socket.events[event] === undefined) {
console.log("Unknown socket event: " + event);
return;
}
socket.events[event](data);
}
socket.onclose = function(e) {
console.log('WebSocket lost connection to server. Re-trying...');
// TODO: reconnect
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 */
socket.events['active_torrents'] = function(data) {
function active_torrents_recv(data) {
let table = document.querySelector('#torrents tbody');
while (table.firstChild) {
table.removeChild(table.firstChild);
@ -64,7 +63,7 @@ socket.events['active_torrents'] = function(data) {
table.appendChild(node);
});
}
socket.events['tracker_stats'] = function(data) {
function tracker_stats(data) {
let table = document.querySelector('#tracker_stats tbody');
while (table.firstChild) {
table.removeChild(table.firstChild);

View File

@ -4,7 +4,6 @@
<title>Aberrant</title>
<link rel="stylesheet" type="text/css" href="/static/aberrant.css">
<script>
const get_torrents_uri = "{{ request.app.router['active-torrents'].url_for() }}";
const ws_uri = "{{ request.app.router['ws'].url_for() }}";
</script>
<script type="text/javascript" src="/static/aberrant.js"></script>