-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathbackground.js
More file actions
347 lines (327 loc) · 9.83 KB
/
background.js
File metadata and controls
347 lines (327 loc) · 9.83 KB
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/*
Copyright 2013, BroadSoft, Inc.
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://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 "ASIS" 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.
*/
var storageUrl = localStorage["url"];
var storageUsername = localStorage["username"];
var storagePassword = localStorage["password"];
var MODULE = "background.js";
var retryAttempt = 0;
var xsiEvents;
function onMessage(request, sender, sendResponse) {
var type = request.type;
if (type == "CALL") {
var destination = request.text.replace(/[- \(\)\.]/g, "");
var status = "ok";
try {
LOGGER.API.log(MODULE, "calling: " + destination);
XSIACTIONS.API.call(destination);
} catch (error) {
status = "error";
}
sendResponse({
status : status
});
} else if (type == "IS_CLICK_TO_DIAL_ENABLED") {
sendResponse({
status : localStorage["clicktodial"]
});
}
}
function onChange(text, suggest) {
if (text.length > 1) {
var suggestions = [];
var response = XSIACTIONS.API.searchEnterpriseDirectory(text);
$(response).find("directoryDetails").each(
function() {
var name = $(this).find("firstName").text() + " "
+ $(this).find("lastName").text();
var number = $(this).find("number").text();
var mobile = $(this).find("mobile").text();
if (number != "") {
suggestions.push({
content : number,
description : name + " (work: " + number + ")"
});
}
if (mobile != "") {
suggestions.push({
content : mobile,
description : name + " (mobile: " + mobile + ")"
});
}
});
var url = "https://www.google.com/m8/feeds/contacts/default/full?v=3.0&max-results=20&q="
+ text;
authenticatedXhr(
'GET',
url,
function(error, status, response) {
if (error == null) {
$(response)
.find("entry")
.each(
function() {
var title = $(this).find("title")
.text();
if (title == "") {
title = "Unknown";
}
$(this)
.find("gd\\:phoneNumber")
.each(
function() {
var number = $(
this)
.text();
var type = $(
this)
.attr(
"rel")
.replace(
"http://schemas.google.com/g/2005#",
"");
suggestions
.push({
content : number,
description : title
+ " ("
+ type
+ ": "
+ number
+ ")"
});
});
});
} else {
LOGGER.API.error(MODULE, error);
}
});
suggest(suggestions);
}
}
function onEntered(text) {
var normalized = text.replace("+", "");
LOGGER.API.log(MODULE, normalized);
try {
XSIACTIONS.API.call(normalized);
} catch (error) {
LOGGER.API.error(MODULE, "onEntered error: " + error.message);
}
}
// list to local storage changes. Jquery allows multiple handlers.
$(window)
.bind(
"storage",
function(e) {
if (e.originalEvent.key == "connectionStatus") {
if (e.originalEvent.newValue == "signedIn") {
LOGGER.API.log(MODULE,
"User credentials have been validated.");
} else if (e.originalEvent.newValue == "connected") {
LOGGER.API.log(MODULE,
"User is connected with XSI Events API");
} else if (e.originalEvent.newValue == "signedOut") {
LOGGER.API
.log(MODULE,
"User has signed out. Terminating XSIEVENTS Framework");
xsiEvents.terminate();
}
}
});
function setServiceStatesToUnknown() {
if (localStorage["dnd"] != "unassigned") {
localStorage["dnd"] = "unknown";
}
if (localStorage["ro"] != "unassigned") {
localStorage["ro"] = "unknown";
}
if (localStorage["cfa"] != "unassigned") {
localStorage["cfa"] = "unknown";
}
}
function connectXsiEvents() {
// init the worker, hosts contains all the XSP hosts
var creds = $.base64.encode(storageUsername + ":" + storagePassword);
xsiEvents.postMessage({
cmd : 'init',
config : {
hosts : [ storageUrl ],
username : storageUsername,
credentials : creds
}
});
sendStartMessage();
}
function contentLoaded() {
localStorage["restartRequired"] = "false";
// restore Xsi-Actions
var xsiactions_options = {
host : localStorage["url"],
username : localStorage["username"],
password : localStorage["password"],
};
XSIACTIONS.API.init(xsiactions_options);
chrome.omnibox.onInputChanged.addListener(onChange);
chrome.omnibox.onInputEntered.addListener(onEntered);
chrome.extension.onMessage.addListener(onMessage);
chrome.notifications.onButtonClicked.addListener(function(notificationId,
buttonIndex) {
if (notificationId.indexOf("callhalf") == 0) {
chrome.notifications.clear(notificationId, function() {
});
if (buttonIndex == 0) {
XSIACTIONS.API.talk(notificationId);
} else {
XSIACTIONS.API.transferToVoicemail(notificationId);
}
}
});
// add suspend listener
chrome.runtime.onSuspend.addListener(function() {
xsiEvents.terminate();
});
// create xsi events worker
xsiEvents = new Worker('xsi-events-api.js');
xsiEvents
.addEventListener(
'message',
function(e) {
switch (e.data.type) {
case 'disconnected':
// try to re-connect if the disconnect was NOT
// because of auth failure; so that we don't keep
// trying to connect with bad credentials and
// lock-out the user
if (e.data.value != '401' && e.data.value != '403') {
if (retryAttempt > 4) {
retryAttempt = 0;
}
var wait = (Math.pow(2, retryAttempt) * 5000)
+ Math.floor(Math.random() * 11) * 1000;
LOGGER.API.log(MODULE, 'waiting for ' + wait
+ 's before re-connect');
setTimeout(function() {
retryAttempt++;
sendStartMessage();
}, wait);
} else {
LOGGER.API
.log(MODULE,
"*** DISCONNECTED DUE TO AUTHORIZATION FAILURE ***");
LOGGER.API
.log(MODULE,
"*** Will not try to reconnect to protect from account lockout ***");
localStorage["errorMessage"] = "An authentication error occurred. Please login again.";
localStorage["connectionStatus"] = "signedOut";
}
setServiceStatesToUnknown();
break;
case 'DoNotDisturbEvent':
localStorage["dnd"] = e.data.value;
break;
case 'CallForwardingAlwaysEvent':
localStorage["cfa"] = e.data.value;
break;
case 'RemoteOfficeEvent':
localStorage["ro"] = e.data.value;
break;
case 'CallSubscriptionEvent':
localStorage["calls"] = JSON
.stringify(e.data.value);
break;
case 'CallReceivedEvent':
var lCalls = JSON.parse(localStorage["calls"]);
for ( var callId in e.data.value) {
var call = e.data.value[callId];
lCalls[callId] = call;
if (call.state == "Alerting") {
if (localStorage["notifications"] == "true") {
var opts = {
type : "basic",
title : "Incoming Call",
message : "Call from " + call.name
+ " " + call.number,
iconUrl : "images/bsft_logo_128x128.png",
buttons : [ {
title : "Answer"
}, {
title : "Decline"
} ]
};
chrome.notifications.create(callId,
opts, function() {
});
}
if (localStorage["texttospeech"] == "true") {
number = call.number.replace(
"+" + call.countryCode + "-",
"").replace(/([0-9])/g, "$1 ");
chrome.tts.speak("Call from "
+ call.name + " " + number, {
"lang" : "en-US"
});
}
}
}
localStorage["calls"] = JSON.stringify(lCalls);
break;
case 'CallAnsweredEvent':
var lCalls = JSON.parse(localStorage["calls"]);
for ( var callId in e.data.value) {
var call = e.data.value[callId];
// hack to override the answer time
// so that the timer is accurate (ish?)
// even if the PC clock is not in sync
// with AS
call.answerTime = new Date().getTime();
lCalls[callId] = call;
chrome.notifications.clear(callId, function() {
});
}
localStorage["calls"] = JSON.stringify(lCalls);
break;
case 'CallReleasedEvent':
var lCalls = JSON.parse(localStorage["calls"]);
for ( var callId in e.data.value) {
delete lCalls[callId];
chrome.notifications.clear(callId, function() {
});
}
localStorage["calls"] = JSON.stringify(lCalls);
break;
case 'CallOriginatingEvent':
case 'CallOriginatedEvent':
case 'CallHeldEvent':
case 'CallRetrievedEvent':
case 'CallUpdatedEvent':
var lCalls = JSON.parse(localStorage["calls"]);
for ( var callId in e.data.value) {
var call = e.data.value[callId];
lCalls[callId] = call;
}
localStorage["calls"] = JSON.stringify(lCalls);
break;
case 'log':
LOGGER.API.log(MODULE, e.data.value);
break;
}
}, false);
if (localStorage["connectionStatus"] == "signedIn") {
connectXsiEvents();
}
}
function sendStartMessage() {
xsiEvents.postMessage({
cmd : 'start'
});
}
document.addEventListener('DOMContentLoaded', contentLoaded);