-
Notifications
You must be signed in to change notification settings - Fork 3
/
background.js
469 lines (384 loc) · 14.5 KB
/
background.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
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
requirejs.config({
baseUrl: 'node_modules',
paths: {
jssip: "jssip/dist/jssip",
react: "react/dist/react-with-addons.min",
reactdom: "react-dom/dist/react-dom.min",
langHelper: "../helper/lang",
contactHelper: "../helper/contact",
helper: "../helper/all",
}
});
var globals = {
dialState: "idle",
callInfo: {}
};
chrome.storage.sync.get({
ws_servers: "",
uri: "",
password: ""
}, function (configuration) {
requirejs(['reactdom', 'jssip', 'helper'], function (reactdom, jssip, helper) {
jssip.debug.enable('*');
var setRegisterState = function (registerState) {
globals["registerState"] = registerState;
if (globals["registerStatePopupHandler"]) {
globals["registerStatePopupHandler"](registerState);
}
};
if (!configuration.uri || !configuration.password) {
setRegisterState("failed");
return;
}
var userAgent = new jssip.UA({
uri: configuration.uri,
password: configuration.password,
ws_servers: configuration.ws_servers
});
var session;
userAgent.start();
var audio = document.getElementById('webrtc_audio');
userAgent.on('newRTCSession', function (data) {
var newSession = data.session;
if (newSession.direction === "incoming") {
console.log('incoming!!!!');
if (session === undefined) {
//dialer.setDialState("incoming");
session = newSession;
reportIncomingCall((data.request.from + "").match(/sip:([0-9]+)@/)[1]);
var endEvents = ["ended", "failed", "removestream"];
for (var i in endEvents) {
newSession.on(endEvents[i], function () {
setDialState("idle");
});
}
newSession.on("confirmed", function () {
setDialState("confirmed");
});
newSession.on('addstream', function (e) {
var stream = e.stream;
addStream(audio, stream);
});
} else {
newSession.terminate();
}
}
}
);
userAgent.on('unregistered', function (response) {
setRegisterState("unregistered");
});
userAgent.on('registered', function (response, cause) {
setRegisterState("registered");
});
userAgent.on('registrationFailed', function (response, cause) {
setRegisterState("failed");
});
var addStream = function (audio, stream) {
jssip.rtcninja.attachMediaStream(audio, stream);
};
var setDialState = function (dialState, callInfo) {
if (dialState === "idle") {
session = undefined;
}
globals["dialState"] = dialState;
globals["callInfo"] = helper.lang.mergeObjects(globals["callInfo"], callInfo);
if (globals["dialStatePopupHandler"]) {
try {
globals["dialStatePopupHandler"](dialState, globals["callInfo"]);
} catch (err) {
console.log("error in dialStatePopupHandler: " + err);
}
}
if (dialState != "incoming") {
chrome.notifications.clear("newcallnotification");
}
var icon = dialState == "idle" ? "icon190.png" : "callIcon.gif";
chrome.browserAction.setIcon({
path: icon
});
};
globals["userAgent"] = userAgent;
globals["audio"] = audio;
globals["call"] = function (url) {
var urlToNumber = function(url) {
var number = url.match(/:(.*)@/)[1];
console.log("matched number: " + number);
return number;
};
if (globals["dialState"] !== "idle") {
console.log("call already in progress");
return;
}
var contact = helper.contact.findContactByNumber(globals["contacts"], urlToNumber(url));
setDialState("trying", {remote: url, remoteContact: contact});
var eventHandlers = {
'progress': function (e) {
setDialState("progress");
console.log('call is in progress');
},
'failed': function (e) {
setDialState("idle");
console.log('call failed with: ' + e);
console.log('call failed with cause: ' + e.cause);
},
'confirmed': function (e) {
setDialState("confirmed");
console.log('call confirmed');
console.log(e);
},
'addstream': function (e) {
console.log('remote stream added');
var stream = e.stream;
addStream(audio, stream);
},
'ended': function (e) {
setDialState("idle");
console.log('call ended with cause: ');
console.log(e);
if (e.cause === "RTP Timeout") {
console.log("rtp timeout, boooh! " + url + " " + configuration.uri);
askToReportErrors({
"user": configuration.uri,
"to": url,
"time": new Date().toGMTString(),
"cause": e.cause
});
}
}
};
var options = {
eventHandlers: eventHandlers,
mediaConstraints: {'audio': true, 'video': false},
pcConfig: {
iceServers: [
{urls: ['stun:stun.sipgate.net']}
]
},
};
try {
session = userAgent.call(url, options);
} catch (err) {
setDialState("idle");
console.log(err);
}
};
globals["hangup"] = function () {
userAgent.terminateSessions();
};
var reject = globals["reject"] = function () {
if (session) {
session.terminate();
}
};
var answer = globals["answer"] = function () {
if (session) {
session.answer();
}
};
var reportIncomingCall = function (caller) {
console.log("orignator: " + caller);
var contact = helper.contact.findContactByNumber(globals["contacts"], caller);
setDialState("incoming", {remote: caller, remoteContact: contact});
chrome.notifications.create("newcallnotification", {
type: "basic",
iconUrl: contact.photoLink ? contact.photoLink : "icon.png",
title: "incoming call",
message: contact.title["$t"],
buttons: [{title: "accept"}, {title: "reject"}],
requireInteraction: true,
})
};
var errors = [];
var askToReportErrors = function (error) {
errors.push(error);
chrome.notifications.create("reporterrornotification", {
type: "basic",
iconUrl: "icon.png",
title: "oops",
message: "something went wrong with the last call. may i report call errors now? this helps to improve the service.",
buttons: [{title: "yes"}, {title: "no"}],
requireInteraction: true,
})
};
var reportErrors = function () {
console.log("about to report errors");
console.log(errors);
var errorFormUrl = "https://docs.google.com/a/sipgate.de/forms/d/1uAIVvTHP-G7XYUX0SQ4A6LCxZuZxvXQRUh4h0GMvAn8/formResponse";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", errorFormUrl, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("entry.988598802=" + JSON.stringify(errors));
errors = [];
};
var notificationClickHandlers = {
"newcallnotification": function (buttonIndex) {
if (buttonIndex == 0) {
answer();
} else {
reject();
}
},
"reporterrornotification": function (buttonIndex) {
if (buttonIndex == 0) {
reportErrors();
}
chrome.notifications.clear("reporterrornotification");
}
};
chrome.notifications.onButtonClicked.addListener(function (notificationId, buttonIndex) {
if (notificationClickHandlers[notificationId]) {
notificationClickHandlers[notificationId](buttonIndex);
}
});
var checkForSuspend = function (lastCheckTime) {
var checkForSuspendInterval = 10000;
var now = Date.now();
var restartUA = function() {
console.log("restart ua");
userAgent.stop();
userAgent.start();
};
try {
if (now - lastCheckTime > checkForSuspendInterval + 100) {
console.log("suspend heuristic triggered");
restartUA();
} else if (!userAgent.isRegistered()) {
console.log("ua not connected. retrying...");
restartUA();
}
} catch (err) {
console.log("error checking ua status: " + err);
}
setTimeout(function() {
checkForSuspend(now)
}, checkForSuspendInterval);
};
checkForSuspend(Date.now());
});
});
var gapiAuthenticated = true;
var gapiAuthError = function () {
gapiAuthenticated = false;
};
var gapiAuthSuccess = function () {
if (!gapiAuthenticated) {
setTimeout(getContacts, 2000);
}
gapiAuthenticated = true;
};
var gapiRequest = function (method, url, data, onSuccess, onError, interactive) {
interactive = typeof interactive !== 'undefined' ? interactive : false;
var isAuthRetry = false;
var doRequest = function () {
chrome.identity.getAuthToken({
interactive: interactive
}, function (token) {
console.log("is retry: " + isAuthRetry);
if (chrome.runtime.lastError && (isAuthRetry || !interactive)) {
console.log("cannot get authtoken: " + chrome.runtime.lastError.message);
gapiAuthError();
onError();
return;
}
var x = new XMLHttpRequest();
x.open(method, url);
x.onload = function () {
if (x.status == 200) {
gapiAuthSuccess();
onSuccess(x.response, token);
} else {
if (x.status == 401) {
if (!isAuthRetry) {
console.log("access denied, token removed " + token);
isAuthRetry = true;
interactive = false;
if (token) {
chrome.identity.removeCachedAuthToken({token: token}, doRequest);
} else {
doRequest();
}
return;
} else {
gapiAuthError();
}
} else {
gapiAuthSuccess();
}
onError();
}
};
x.setRequestHeader('Authorization', "Bearer " + token);
x.send();
});
};
return doRequest();
};
var getContacts = function () {
var enrichContactPhoto = function (contact, token) {
if (contact.link && contact.link.length > 3) {
photolink = contact.link[0].href + "?access_token=" + token;
} else {
photolink = "defaultavatar.png";
}
contact.photoLink = photolink;
return contact;
};
gapiRequest("GET", 'https://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=1000',
[],
function (result, token) {
var response = JSON.parse(result);
globals["contacts"] = response.feed.entry.map(function (c) {
return enrichContactPhoto(c, token)
});
},
function () {
console.log("unable to get contacts");
}
);
};
var pollContacts = function () {
getContacts();
setTimeout(pollContacts, 600000);
};
pollContacts();
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (sender.tab) {
// from content-script
}
console.log("message received: " + request);
console.log(request);
if (request.dialNumber) {
globals["call"]("sip:" + request.dialNumber + "@sipgate.de");
} else if (request.request === "requestGoogleAuthorization") {
var response = function (autherror) {
console.log("sending response " + autherror);
sendResponse({autherror: autherror});
};
gapiRequest("GET", "https://www.google.com/m8/feeds/contacts", [],
function () {
response(false)
},
function () {
response(!gapiAuthenticated)
},
request.interactive);
} else {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
}
return true;
});
var showCallPopUp = function() {
chrome.windows.create({
url: "callpopup.html",
// left: -1,
// top: -400,
width: 400,
height: 200,
type: "panel"
});
};
//showCallPopUp();