aboutsummaryrefslogtreecommitdiffstats
path: root/htdocs/binding.js
blob: 2930ec64eb2786cd9e3bc743145bb2b164094a9c (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
var afbVshlCapabilities;
var ws;
var evtIdx = 0;
var count = 0;

//**********************************************
// Logger
//**********************************************
var log = {
  command: function (url, api, verb, query) {
    console.log("subscribe api=" + api + " verb=" + verb + " query=", query);
    var question = url + "/" + api + "/" + verb + "?query=" + JSON.stringify(query);
    log._write("question", count + ": " + log.syntaxHighlight(question));
  },

  event: function (obj) {
    console.log("gotevent:" + JSON.stringify(obj));
    log._write("outevt", (evtIdx++) + ": " + JSON.stringify(obj));
  },

  reply: function (obj) {
    console.log("replyok:" + JSON.stringify(obj));
    log._write("output", count + ": OK: " + log.syntaxHighlight(obj));
  },

  error: function (obj) {
    console.log("replyerr:" + JSON.stringify(obj));
    log._write("output", count + ": ERROR: " + log.syntaxHighlight(obj));
  },

  _write: function (element, msg) {
    var el = document.getElementById(element);
    el.innerHTML += msg + '\n';

    // auto scroll down
    setTimeout(function () {
      el.scrollTop = el.scrollHeight;
    }, 100);
  },

  syntaxHighlight: function (json) {
    if (typeof json !== 'string') {
      json = JSON.stringify(json, undefined, 2);
    }
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
      var cls = 'number';
      if (/^"/.test(match)) {
        if (/:$/.test(match)) {
          cls = 'key';
        } else {
          cls = 'string';
        }
      } else if (/true|false/.test(match)) {
        cls = 'boolean';
      } else if (/null/.test(match)) {
        cls = 'null';
      }
      return '<span class="' + cls + '">' + match + '</span>';
    });
  },
};

//**********************************************
// Generic function to call binder
//***********************************************
function callbinder(url, api, verb, query) {
  log.command(url, api, verb, query);

  // ws.call return a Promise
  return ws.call(api + '/' + verb, query)
    .then(function (res) {
      log.reply(res);
      count++;
      return res;
    })
    .catch(function (err) {
      log.reply(err);
      count++;
      throw err;
    });
};


//**********************************************
// connect - establish Websocket connection
//**********************************************

function connect(elemID, api, verb, query) {
  connectVshlCapabilities(elemID, api, verb, query);
}

//**********************************************

//
var lastCallId;

function onCapabilityEvent(eventDataObj) {
    log.event(eventDataObj);
    if (eventDataObj.event == "vshl-capabilities/dial") {
        lastCallId = JSON.parse(eventDataObj.data).callId;
        console.log("New Dial Directive received. Sending ringing state back");
        // send ringing state back.
        triggerCallStateChangedAction("OUTBOUND_RINGING");
    }
}

function triggerPhoneConnectionStateChanged(newState) {
  var paramsJson = {
      "action" : "connection_state_changed",
      "payload": {
          "state" : newState
      }
  }
  callbinder(afbVshlCapabilities.url, 'vshl-capabilities', 'phonecontrol/publish', paramsJson);     
}

function triggerCallStateChangedAction(newCallstate) {
    var query = {
        "action": "call_state_changed",
        "payload": {
             "callId": lastCallId,
             "state": newCallstate
        }
    }
    callbinder(afbVshlCapabilities.url, 'vshl-capabilities', 'phonecontrol/publish', query);
}

function guid() {
    function s4() {
      return Math.floor((1 + Math.random()) * 0x10000)
          .toString(16)
          .substring(1);
      }
    return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}

function triggerCallStateInBoundRingingAction() {
    var callId = guid();
    var state = "INBOUND_RINGING";
    var query = {
        "action": "call_state_changed",
        "payload": {
             "callId": callId,
             "state": state
        }
    }
    callbinder(afbVshlCapabilities.url, 'vshl-capabilities', 'phonecontrol/publish', query);
}

function connectVshlCapabilities(elemID, api, verb, query) {

  function onopen() {
    document.getElementById("main").style.visibility = "visible";
    document.getElementById("connected").innerHTML = "VSHL Capabilities Binder WS Active";
    document.getElementById("connected").style.background = "lightgreen";
    ws.onevent("*", onCapabilityEvent);
  }

  function onabort() {
    document.getElementById("main").style.visibility = "hidden";
    document.getElementById("connected").innerHTML = "Connected Closed";
    document.getElementById("connected").style.background = "red";
  }

  var urlparams = {
    base: "api",
    token: "HELLO",
  };
  const vshlCapabilitiesAddressInput = document.getElementById('vshl-capabilities-address');
  urlparams.host = vshlCapabilitiesAddressInput.value;

  afbVshlCapabilities = new AFB(urlparams, "HELLO");
  ws = new afbVshlCapabilities.ws(onopen, onabort);
}

function clearPre(preId) {
  const pre = document.getElementById(preId);
  while (pre && pre.firstChild) {
    pre.removeChild(pre.firstChild);
  }
}

function showTemplateUIEventChooserDialog() {
  const modal = document.getElementById('templateui-event-chooser');
  const subscribeBtn = document.getElementById('templateui-subscribe-btn');

  subscribeBtn.addEventListener('click', (evt) => {
    const renderTemplate = document.getElementById('render_template').checked;
    const clearTemplate = document.getElementById('clear_template').checked;
    const renderPlayerInfo = document.getElementById('render_player_info').checked;
    const clearPlayerInfo = document.getElementById('clear_player_info').checked;

    const query = {"actions":[]};

    if (renderTemplate)
      query.actions.push('render_template');
    if (clearTemplate)
      query.actions.push('clear_template');
    if (renderPlayerInfo)
      query.actions.push('render_player_info');
    if (clearPlayerInfo)
      query.actions.push('clear_player_info');

    callbinder(afbVshlCapabilities.url, 'vshl-capabilities', 'guiMetadata/subscribe', query);
    modal.close();
  });

  // makes modal appear (adds `open` attribute)
  modal.showModal();
}

function showPhoneControlEventChooserDialog() {
  const modal = document.getElementById('phonecontrol-event-chooser');
  const subscribeBtn = document.getElementById('phonecontrol-subscribe-btn');

  subscribeBtn.addEventListener('click', (evt) => {
    const dial = document.getElementById('phonecontrol-dial').checked;
    const redial = document.getElementById('phonecontrol-redial').checked;
    const answer = document.getElementById('phonecontrol-answer').checked;
    const stop = document.getElementById('phonecontrol-stop').checked;
    const sendDtmf = document.getElementById('phonecontrol-send_dtmf').checked;

    const query = {"actions":[]};

    if (dial)
      query.actions.push('dial');
    if (redial)
      query.actions.push('redial');
    if (answer)
      query.actions.push('answer');
    if (stop)
      query.actions.push('stop');
    if (sendDtmf)
      query.actions.push('send_dtmf');

    callbinder(afbVshlCapabilities.url, 'vshl-capabilities', 'phonecontrol/subscribe', query);
    modal.close();
  });

  // makes modal appear (adds `open` attribute)
  modal.showModal();
}

function showNavigationEventCHooserDialod() {
  const modal = document.getElementById('navigation-event-chooser');
  const subscribeBtn = document.getElementById('navigation-subscribe-btn');

  subscribeBtn.addEventListener('click', (evt) => {
    const setDestination = document.getElementById('setDestination').checked;
    const cancelNavigation = document.getElementById('cancelNavigation').checked;

    const query = {"actions":[]};

    if (setDestination)
      query.actions.push('setDestination');
    if (cancelNavigation)
      query.actions.push('cancelNavigation');

    callbinder(afbVshlCapabilities.url, 'vshl-capabilities', 'navigation/subscribe', query);
    modal.close();
  });

  // makes modal appear (adds `open` attribute)
  modal.showModal();
}

function triggerButtonPressedAction(button) {
    var paramsJson = {
        "action" : "button_pressed",
        "payload": {
            "button" : button
        }
    }
    callbinder(afbVshlCapabilities.url, 'vshl-capabilities', 'playbackcontroller/publish', paramsJson);     
}