var socket; function load() { socket = init_websocket(); } /* Websocket setup */ function init_websocket() { let socket = new WebSocket('wss://' + window.location.hostname + ws_uri); socket.send_event = send_event; socket.onmessage = onmessage; socket.onclose = onclose; socket.onerror = onerror; socket.events = {}; socket.events['albums'] = albums_recv; return socket; } function send_event(event_title, data) { data = JSON.stringify({'event': event_title, 'data': data}); if (this.readyState == 0) { console.log("Socket is still opening!"); return; } this.send(data); } function onmessage(event) { let data; let event_title; try { data = JSON.parse(event.data); } catch(err) { // not JSON console.log(err); console.log(event); throw new Error("Error decoding JSON"); return; } if (!data.ok) { throw new Error("Socket error: event = " + event_title + ", error = " + data.error); } try { event_title = data.event; data = data.data; } catch(err) { // not proper event console.log(err); console.log(event); throw new Error("Event malformed"); return; } if (socket.events[event_title] === undefined) { console.log("Unknown socket event: " + event_title); return; } socket.events[event_title](data); } async function onclose(event) { if (event.wasClean) { return; } // no need to reconnect console.log(event); console.log('Websocket lost connection to server. Re-trying...'); await sleep(3000); socket = init_websocket(); } function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } function onerror(event) { console.log("Websocket error!") console.log(event); } /* Websocket receive */ function albums_recv(data) { let albums_list = document.querySelector('#albumList'); while (albums_list.firstChild) { albums_list.removeChild(albums_list.lastChild); } for (let album of data) { let option = document.createElement('option'); option.value = album; option.innerText = album; albums_list.appendChild(option); } } /* Websocket send */ function select_artist(option) { let artist = option.value; let data = {'type': 'artist', 'artist': artist}; socket.send_event('select', data); } /* DOM */