Skip to content
Snippets Groups Projects
websocket.html 2.46 KiB
Newer Older
<script type="text/javascript">
    //Websocket connection
    $(document).ready(function(){

        if ('WebSocket' in window) {
            var ws = new WebSocket("{{=GET_URL(room_record)}}");
            ws.onopen = function () {
                ws.initialConnect = true;
            };
            ws.onmessage = function(e) {
                var firstColon = e.data.indexOf(":");
                if(firstColon === -1) {
                    if(e.data.startsWith("+") || e.data.startsWith("-")) {
                        return;
                    }
                    set_error("{{=T('Invalid WebSocket data received')}}: '" + e.data + "'");
                    return;
                }

                var type = e.data.substring(0, firstColon);
                var data = e.data.substring(firstColon + 1);

                switch(type) {
                    case "roles":
                        roles = JSON.parse(atob(data));
Nils G.'s avatar
Nils G. committed
                        break;
                    case "role":
                        role_definition = JSON.parse(atob(data));
                        if(PLAYER_UID in role_definition) {
                            role = role_definition[PLAYER_UID]["role"];
                            role_next = role_definition[PLAYER_UID]["role_next"];
                            prompts = role_definition[PLAYER_UID]["prompts"];
Nils G.'s avatar
Nils G. committed
                            currentPrompt = 0;
Nils G.'s avatar
Nils G. committed
                        }
Nils G.'s avatar
Nils G. committed
                    case "reload":
Nils G.'s avatar
Nils G. committed
                        break;
                    default:
                        set_error("{{=T('Invalid WebSocket data received')}}: '" + type + "'");
                        return;
                }
Nils G.'s avatar
Nils G. committed
                render(role, roles);

            };
            ws.onerror = function(e) {
                set_error("{{=T('Error')}}: "+e);
            };
            ws.onclose = function () {
                if(ws.initialConnect) {
                    window.setTimeout(function() {
                        set_error("{{=T('WebSocket has closed')}}. {{=T('Please refresh this website')}}.");
                    }, 1000);
                } else {
                    set_error("{{=T('WebSocket server is not responding')}}.");
                }
            };
        } else {
            /* not supported */
            set_error("{{=T('WebSocket is not supported by your browser')}}.");
        }

    });
</script>