-
Notifications
You must be signed in to change notification settings - Fork 12
/
socket.js
128 lines (120 loc) · 4.19 KB
/
socket.js
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
/**
* Copyright 2015 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* global $:false */
'use strict';
var utils = require('./utils');
var showerror = require('./views/showerror');
var showError = showerror.showError;
// Mini WS callback API, so we can initialize
// with model and token in URI, plus
// start message
// Initialize closure, which holds maximum getToken call count
var tokenGenerator = utils.createTokenGenerator();
var initSocket = exports.initSocket = function(options, onopen, onlistening, onmessage, onerror, onclose) {
var listening;
// function withDefault(val, defaultVal) {
// return typeof val === 'undefined' ? defaultVal : val;
// }
var socket;
var token = options.token;
var model = options.model || localStorage.getItem('currentModel');
var message = options.message || {'action': 'start'};
// var sessionPermissions = withDefault(options.sessionPermissions,
// JSON.parse(localStorage.getItem('sessionPermissions')));
// var sessionPermissionsQueryParam = sessionPermissions ? '0' : '1';
// TODO: add '&X-Watson-Learning-Opt-Out=' + sessionPermissionsQueryParam once
// we find why it's not accepted as query parameter
var url = options.serviceURI || 'wss:https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?watson-token=';
url += token + '&model=' + model;
console.log('URL model', model);
try {
socket = new WebSocket(url);
} catch (err) {
console.error('WS connection error: ', err);
}
socket.onopen = function() {
listening = false;
$.subscribe('hardsocketstop', function() {
console.log('MICROPHONE: close.');
socket.send(JSON.stringify({action:'stop'}));
socket.close();
});
$.subscribe('socketstop', function() {
console.log('MICROPHONE: close.');
socket.close();
});
socket.send(JSON.stringify(message));
onopen(socket);
};
socket.onmessage = function(evt) {
var msg = JSON.parse(evt.data);
if (msg.error) {
showError(msg.error);
$.publish('hardsocketstop');
return;
}
if (msg.state === 'listening') {
// Early cut off, without notification
if (!listening) {
onlistening(socket);
listening = true;
} else {
console.log('MICROPHONE: Closing socket.');
socket.close();
}
}
onmessage(msg, socket);
};
socket.onerror = function(evt) {
console.log('WS onerror: ', evt);
showError('Application error ' + evt.code + ': please refresh your browser and try again');
$.publish('clearscreen');
onerror(evt);
};
socket.onclose = function(evt) {
console.log('WS onclose: ', evt);
if (evt.code === 1006) {
// Authentication error, try to reconnect
console.log('generator count', tokenGenerator.getCount());
if (tokenGenerator.getCount() > 1) {
$.publish('hardsocketstop');
throw new Error('No authorization token is currently available');
}
tokenGenerator.getToken(function(err, token) {
if (err) {
$.publish('hardsocketstop');
return false;
}
console.log('Fetching additional token...');
options.token = token;
initSocket(options, onopen, onlistening, onmessage, onerror, onclose);
});
return false;
}
if (evt.code === 1011) {
console.error('Server error ' + evt.code + ': please refresh your browser and try again');
return false;
}
if (evt.code > 1000) {
console.error('Server error ' + evt.code + ': please refresh your browser and try again');
return false;
}
// Made it through, normal close
$.unsubscribe('hardsocketstop');
$.unsubscribe('socketstop');
onclose(evt);
};
};