summaryrefslogtreecommitdiff
path: root/www/js/rhctl.js
blob: 103f12c2af9e5f607214f66b7f964a9f2683db7d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
 *  rhrdweb
 *
 *  Copyright (C) 2016 Christian Pointner <equinox@helsinki.at>
 *
 *  This file is part of rhrdweb.
 *
 *  rhrdweb is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  any later version.
 *
 *  rhrdweb is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with rhrdweb. If not, see <http://www.gnu.org/licenses/>.
 */

'use strict';

function Rhctl() {
  this.draw_callbacks = $.Callbacks('unique');
  this.state = 'NEW';

  this.sock_onmessage = function(event) {
    var msg = JSON.parse(event.data);
    if (msg.RESPONSE_CODE != 200) {
      console.log("got error message: ", event.data)
    } else {
      switch(msg.TYPE) {
      case 'state':
        this.draw_callbacks.fireWith(window, [ msg.STATE ]);
        break;
      case 'ack':
        break;
      default:
        console.log("rhctl: got unexpected message type '" + msg.TYPE + "'")
      }
    }
  }

  this.addCallback = function(cb) {
    this.draw_callbacks.add(cb);
  }

  this.sock_onopen = function() {
    this.state = 'CONNECTED';
    console.log('rhctl: ' + this.state)
    this.sock.onmessage = this.sock_onmessage.bind(this);
    this.sock.send(JSON.stringify({ COMMAND: 'subscribe', ARGS: [ 'state' ] }));
    this.sock.send(JSON.stringify({ COMMAND: 'state' }));
  }

  this.sock_onclose = function(event) {
    this.sock.close();
    delete this.sock;
    setTimeout(this.connect.bind(this), 1000);
    this.state = 'RECONNECTING';
    console.log('rhctl: ' + this.state)
  }

  this.connect = function() {
    this.sock = new WebSocket('wss://' + window.location.host + '/rhctl/socket');
    this.sock.onopen = this.sock_onopen.bind(this);
    this.sock.onclose = this.sock_onclose.bind(this);
    this.state = 'CONNECTING';
    console.log('rhctl: ' + this.state)
  }
}

var rhctl = new Rhctl();

function rhctl_init() {
  rhctl.connect();
  $('#rhctl').text("loading...");
  rhctl.addCallback(rhctl_draw_state);
}

function rhctl_draw_state(state) {
    console.log(state);
    $('#rhctl').text(JSON.stringify(state, null, '\t'));
}