This repository has been archived by the owner on Nov 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
oncall.js
839 lines (704 loc) · 22.6 KB
/
oncall.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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
'use strict';
var CallScreen = {
_ticker: null,
_screenLock: null,
_typedNumber: '',
body: document.body,
screen: document.getElementById('call-screen'),
views: document.getElementById('views'),
calls: document.getElementById('calls'),
get activeCall() {
return OnCallHandler.activeCall();
},
mainContainer: document.getElementById('main-container'),
callToolbar: document.getElementById('co-advanced'),
muteButton: document.getElementById('mute'),
speakerButton: document.getElementById('speaker'),
keypadButton: document.getElementById('keypad-visibility'),
answerButton: document.getElementById('callbar-answer'),
rejectButton: document.getElementById('callbar-hang-up'),
incomingContainer: document.getElementById('incoming-container'),
incomingNumber: document.getElementById('incoming-number'),
incomingAnswer: document.getElementById('incoming-answer'),
incomingEnd: document.getElementById('incoming-end'),
incomingIgnore: document.getElementById('incoming-ignore'),
lockedContactPhoto: document.getElementById('locked-contact-photo'),
init: function cs_init() {
this.muteButton.addEventListener('click', this.toggleMute.bind(this));
this.keypadButton.addEventListener('click', this.showKeypad.bind(this));
this.speakerButton.addEventListener('click',
this.toggleSpeaker.bind(this));
this.answerButton.addEventListener('click',
OnCallHandler.answer.bind(OnCallHandler));
this.rejectButton.addEventListener('click',
OnCallHandler.end);
this.incomingAnswer.addEventListener('click',
OnCallHandler.holdAndAnswer);
this.incomingEnd.addEventListener('click',
OnCallHandler.endAndAnswer);
this.incomingIgnore.addEventListener('click',
OnCallHandler.ignore);
this.calls.addEventListener('click',
OnCallHandler.toggleCalls);
// If the phone is locked, show as an locked-style at very first.
if ((window.location.hash === '#locked') && !this.screen.dataset.layout) {
CallScreen.render('incoming-locked');
}
if (navigator.mozSettings) {
var req = navigator.mozSettings.createLock().get('wallpaper.image');
req.onsuccess = function cs_wi_onsuccess() {
CallScreen.setCallerContactImage(
req.result['wallpaper.image'], false, true);
};
}
// Handle resize events
window.addEventListener('resize', this.resizeHandler.bind(this));
},
resizeHandler: function cs_resizeHandler() {
// Handle attention screen switches between full screen/status bar mode.
// If a user is typing keypad during calling,
// we don't show the typed number in status bar mode.
if (window.innerHeight <= 40) {
if (this.body.classList.contains('showKeypad')) {
this._typedNumber = KeypadManager._phoneNumber;
KeypadManager.restorePhoneNumber();
}
} else if (this.body.classList.contains('showKeypad')) {
KeypadManager.updatePhoneNumber(this._typedNumber, 'begin', true);
}
},
setCallerContactImage: function cs_setContactImage(image_url, force, mask) {
var photoURL;
var isString = (typeof image_url == 'string');
var isLocked = (this.screen.dataset.layout === 'incoming-locked');
var target = isLocked ? this.lockedContactPhoto : this.mainContainer;
photoURL = isString ? image_url : URL.createObjectURL(image_url);
if (!target.style.backgroundImage || force) {
target.style.backgroundImage = 'url(' + photoURL + ')';
if (mask) {
target.classList.add('masked');
} else {
target.classList.remove('masked');
}
}
},
toggleMute: function cs_toggleMute() {
this.muteButton.classList.toggle('mute');
OnCallHandler.toggleMute();
},
unmute: function cs_unmute() {
this.muteButton.classList.remove('mute');
OnCallHandler.unmute();
},
toggleSpeaker: function cs_toggleSpeaker() {
this.speakerButton.classList.toggle('speak');
OnCallHandler.toggleSpeaker();
},
turnSpeakerOn: function cs_turnSpeakerOn() {
this.speakerButton.classList.add('speak');
OnCallHandler.turnSpeakerOn();
},
turnSpeakerOff: function cs_turnSpeakerOff() {
this.speakerButton.classList.remove('speak');
OnCallHandler.turnSpeakerOff();
},
showKeypad: function cs_showKeypad() {
KeypadManager.render('oncall');
this.body.classList.add('showKeypad');
},
hideKeypad: function cs_hideKeypad() {
KeypadManager.restorePhoneNumber();
KeypadManager.restoreAdditionalContactInfo();
this.body.classList.remove('showKeypad');
},
render: function cs_render(layout_type) {
this.screen.dataset.layout = layout_type;
if (layout_type !== 'connected') {
this.keypadButton.setAttribute('disabled', 'disabled');
}
},
showIncoming: function cs_showIncoming() {
// Hiding the keypad
this.body.classList.remove('showKeypad');
this.callToolbar.classList.add('transparent');
this.incomingContainer.classList.add('displayed');
this._screenLock = navigator.requestWakeLock('screen');
},
hideIncoming: function cs_hideIncoming() {
this.callToolbar.classList.remove('transparent');
this.incomingContainer.classList.remove('displayed');
if (this._screenLock) {
this._screenLock.unlock();
this._screenLock = null;
}
},
syncSpeakerEnabled: function cs_syncSpeakerEnabled() {
if (navigator.mozTelephony.speakerEnabled) {
this.speakerButton.classList.add('speak');
} else {
this.speakerButton.classList.remove('speak');
}
},
enableKeypad: function cs_enableKeypad() {
this.keypadButton.removeAttribute('disabled');
},
disableKeypad: function cs_disableKeypad() {
this.keypadButton.setAttribute('disabled', 'disabled');
}
};
var OnCallHandler = (function onCallHandler() {
var COMMS_APP_ORIGIN = 'app://communications.gaiamobile.org';
// Changing this will probably require markup changes
var CALLS_LIMIT = 2;
var handledCalls = [];
var telephony = window.navigator.mozTelephony;
telephony.oncallschanged = onCallsChanged;
var settings = window.navigator.mozSettings;
var displayed = false;
var closing = false;
var animating = false;
var ringing = false;
var busyNotificationLock = false;
/* === Settings === */
var activePhoneSound = null;
SettingsListener.observe('audio.volume.notification', 7, function(value) {
activePhoneSound = !!value;
if (ringing && activePhoneSound) {
ringtonePlayer.play();
}
});
var selectedPhoneSound = '';
SettingsListener.observe('dialer.ringtone', '', function(value) {
selectedPhoneSound = value;
ringtonePlayer.pause();
ringtonePlayer.src = value;
if (ringing && activePhoneSound) {
ringtonePlayer.play();
}
});
// Setting up the SimplePhoneMatcher
var conn = window.navigator.mozMobileConnection;
if (conn && conn.voice && conn.voice.network && conn.voice.network.mcc) {
SimplePhoneMatcher.mcc = conn.voice.network.mcc;
}
var ringtonePlayer = new Audio();
ringtonePlayer.mozAudioChannelType = 'ringer';
ringtonePlayer.src = selectedPhoneSound;
ringtonePlayer.loop = true;
var activateVibration = null;
SettingsListener.observe('vibration.enabled', true, function(value) {
activateVibration = !!value;
});
var screenLock;
/* === Setup === */
function setup() {
if (telephony) {
// Somehow the muted property appears to true after initialization.
// Set it to false.
telephony.muted = false;
}
postToMainWindow('ready');
}
function postToMainWindow(data) {
window.opener.postMessage(data, COMMS_APP_ORIGIN);
}
/* === Handled calls === */
var highPriorityWakeLock = null;
function onCallsChanged() {
// Acquire or release the high-priority wake lock, as necessary. This
// (mostly) prevents this process from being killed while we're on a call.
if (!highPriorityWakeLock && telephony.calls.length > 0) {
highPriorityWakeLock = navigator.requestWakeLock('high-priority');
}
if (highPriorityWakeLock && telephony.calls.length == 0) {
highPriorityWakeLock.unlock();
highPriorityWakeLock = null;
}
// Adding any new calls to handledCalls
telephony.calls.forEach(function callIterator(call) {
var alreadyAdded = handledCalls.some(function hcIterator(hc) {
return (hc.call == call);
});
if (!alreadyAdded) {
addCall(call);
}
});
// Removing any ended calls to handledCalls
handledCalls.forEach(function handledCallIterator(hc, index) {
var stillHere = telephony.calls.some(function hcIterator(call) {
return (call == hc.call);
});
if (!stillHere) {
removeCall(index);
}
});
// Letting the layout know how many calls we're handling
if (handledCalls.length === 0) {
exitCallScreen(false);
} else {
CallScreen.calls.dataset.count = handledCalls.length;
if (!displayed && !closing) {
toggleScreen();
}
}
}
function addCall(call) {
busyNotificationLock = false;
// Once we already have 1 call, we need to care about incoming
// calls and insert new dialing calls.
if (handledCalls.length &&
(call.state != 'incoming') && (call.state != 'dialing')) {
return;
}
// No more room
if (handledCalls.length >= CALLS_LIMIT) {
new HandledCall(call);
call.hangUp();
return;
}
// First incoming or outgoing call, reset mute and speaker.
if (handledCalls.length == 0) {
CallScreen.unmute();
CallScreen.turnSpeakerOff();
}
// Find an available node for displaying the call
var node = CallScreen.calls.querySelector('.call[data-occupied="false"]');
var hc = new HandledCall(call, node);
handledCalls.push(hc);
if (call.state === 'incoming') {
call.addEventListener('statechange', function callStateChange() {
call.removeEventListener('statechange', callStateChange);
// The call wasn't picked up
if (call.state == 'disconnected') {
var callInfo = {
type: 'notification',
number: call.number
};
postToMainWindow(callInfo);
}
});
// This is the initial incoming call, need to ring !
if (handledCalls.length === 1) {
handleFirstIncoming(call);
}
}
if (handledCalls.length > 1) {
// New incoming call, signaling the user.
if (call.state === 'incoming') {
handleCallWaiting(call);
// User performed another outgoing call. show its status.
} else {
hc.show();
}
} else {
if (window.location.hash === '#locked' &&
(call.state == 'incoming')) {
CallScreen.render('incoming-locked');
} else {
CallScreen.render(call.state);
}
}
}
function removeCall(index) {
var removedCall = handledCalls[index];
handledCalls.splice(index, 1);
if (handledCalls.length > 0) {
// Only hiding the call if we have another one to display
removedCall.hide();
CallScreen.hideIncoming();
var remainingCall = handledCalls[0];
if (remainingCall.call.state == 'incoming') {
// The active call ended, showing the incoming call
remainingCall.show();
// This is the difference between an endAndAnswer() and
// the active call being disconnected while a call is waiting
setTimeout(function nextTick() {
if (remainingCall.call.state == 'incoming') {
CallScreen.render('incoming');
}
});
return;
}
// The incoming call was rejected, resuming...
remainingCall.call.resume();
return;
}
exitCallScreen(true);
}
function handleFirstIncoming(call) {
var vibrateInterval = 0;
if (activateVibration != false) {
vibrateInterval = window.setInterval(function vibrate() {
// Wait for the setting value to return before starting a vibration.
if ('vibrate' in navigator && activateVibration) {
navigator.vibrate([200]);
}
}, 600);
}
if (activePhoneSound == true) {
ringtonePlayer.play();
ringing = true;
} else if (activePhoneSound == null) {
// Let's wait for the setting to return before playing any sound.
ringing = true;
}
screenLock = navigator.requestWakeLock('screen');
call.addEventListener('statechange', function callStateChange() {
call.removeEventListener('statechange', callStateChange);
ringtonePlayer.pause();
ringing = false;
window.clearInterval(vibrateInterval);
if (screenLock) {
screenLock.unlock();
screenLock = null;
}
});
}
function handleCallWaiting(call) {
LazyL10n.get(function localized(_) {
var number = call.number || _('withheld-number');
Contacts.findByNumber(number, function lookupContact(contact) {
if (contact && contact.name) {
CallScreen.incomingNumber.textContent = contact.name;
return;
}
CallScreen.incomingNumber.textContent = number;
});
});
CallScreen.showIncoming();
// ANSI call waiting tone for a 10 sec window
var sequence = [[440, 440, 100],
[0, 0, 100],
[440, 440, 100]];
var toneInterval = window.setInterval(function playTone() {
TonePlayer.playSequence(sequence);
}, 10000);
TonePlayer.playSequence(sequence);
call.addEventListener('statechange', function callStateChange() {
call.removeEventListener('statechange', callStateChange);
window.clearInterval(toneInterval);
});
}
/* === Call Screen === */
function toggleScreen() {
displayed = !displayed;
animating = true;
var callScreen = CallScreen.screen;
callScreen.classList.toggle('displayed');
callScreen.addEventListener('transitionend', function trWait() {
callScreen.removeEventListener('transitionend', trWait);
animating = false;
// We did animate the call screen off the viewport
// now closing the window.
if (!displayed) {
closeWindow();
}
});
}
function updateKeypadEnabled() {
if (telephony.active) {
CallScreen.enableKeypad();
} else {
CallScreen.disableKeypad();
}
}
function exitCallScreen(animate) {
if (closing || busyNotificationLock) {
return;
}
closing = true;
postToMainWindow('closing');
if (Swiper) {
Swiper.setElasticEnabled(false);
}
// If the screen is not displayed yet we close the window directly
if (animate && !animating && displayed) {
toggleScreen();
} else {
closeWindow();
}
}
function closeWindow() {
window.close();
}
/* Handle commands send to the callscreen via postmessage */
function handleCommand(evt) {
if (evt.origin !== COMMS_APP_ORIGIN) {
return;
}
var message = evt.data;
if (!message) {
return;
}
// Currently managing three kinds of commands:
// BT: bluetooth
// HS: headset
// * : general cases, not specific to hardware control
switch (message.type) {
case 'BT':
handleBTCommand(message.command);
break;
case 'HS':
handleHSCommand(message.command);
break;
case '*':
handleGeneralCommand(message.command);
break;
}
}
/* === Bluetooth Headset support ===*/
function handleBTCommand(message) {
switch (message) {
case 'CHUP':
end();
break;
case 'ATA':
answer();
break;
case 'CHUP+ATA':
// End the active call and answer the other one
if (handledCalls.length === 1) {
end();
} else {
endAndAnswer();
}
break;
case 'CHLD+ATA':
// Hold the active call and answer the other one
if (handledCalls.length === 1) {
holdOrResumeSingleCall();
} else {
holdAndAnswer();
}
break;
case 'CHLD=0':
hangupWaitingCalls();
break;
default:
var partialCommand = message.substring(0, 3);
if (partialCommand === 'VTS') {
KeypadManager.press(message.substring(4));
}
break;
}
}
var lastHeadsetPress = 0;
function handleHSCommand(message) {
/**
* See bug 853132: plugging / unplugging some headphones might send a
* 'headset-button-press' / 'headset-button-release' message
* => if these two events happen in the same second, it's a click;
* => if these two events are too distant, ignore them.
*/
switch (message) {
case 'headset-button-press':
lastHeadsetPress = Date.now();
return;
break;
case 'headset-button-release':
if ((Date.now() - lastHeadsetPress) > 1000)
return;
break;
default:
return;
}
if (telephony.active) {
end();
} else if (handledCalls.length > 1) {
holdAndAnswer();
} else {
answer();
}
}
function handleGeneralCommand(message) {
// Calls might be ended before callscreen is completely loaded or we
// register 'callschanged' event. To avoid leaving callscreen stuck open,
// we use a simple postMessage protocol to know when the call screen is
// supposed to be closed, in addition to 'callschanged' event.
if (message == 'exitCallScreen') {
exitCallScreen(false);
}
}
window.addEventListener('message', handleCommand);
/* === User Actions === */
function answer() {
// We should always have only 1 call here
if (!handledCalls.length) {
return;
}
handledCalls[0].call.answer();
if (CallScreen.screen.dataset.layout === 'incoming-locked') {
CallScreen.mainContainer.style.backgroundImage =
CallScreen.lockedContactPhoto.style.backgroundImage;
}
CallScreen.render('connected');
}
function holdAndAnswer() {
if (handledCalls.length < 2) {
return;
}
if (telephony.active) {
// connected, incoming
telephony.active.hold(); // the incoming call is answered by gecko
} else {
// held, incoming
var lastCall = handledCalls[handledCalls.length - 1].call;
lastCall.answer(); // the previous call is held by gecko
}
CallScreen.hideIncoming();
}
function endAndAnswer() {
if (handledCalls.length < 2) {
return;
}
var callToEnd = telephony.active || // connected, incoming
handledCalls[handledCalls.length - 2].call; // held, incoming
if (callToEnd) {
callToEnd.hangUp(); // the incoming call is answered automatically
}
CallScreen.hideIncoming();
}
function toggleCalls() {
if (CallScreen.incomingContainer.classList.contains('displayed')) {
return;
}
if (handledCalls.length < 2) {
// Putting a call on Hold when there are no other
// calls in progress has been disabled until a less
// accidental user-interface is implemented.
// See bug 894232 and bug 882056 for more background.
return;
}
telephony.active.hold();
}
function holdOrResumeSingleCall() {
if (handledCalls.length !== 1) {
return;
}
if (telephony.active) {
telephony.active.hold();
} else {
telephony.calls[0].resume();
}
}
// Hang up the held call or the second incomming call
function hangupWaitingCalls() {
handledCalls.forEach(function(handledCall) {
var callState = handledCall.call.state;
if (callState === 'held' ||
(callState === 'incoming' && handledCalls.length > 1)) {
handledCall.call.hangUp();
}
});
}
function ignore() {
var ignoreIndex = handledCalls.length - 1;
handledCalls[ignoreIndex].call.hangUp();
CallScreen.hideIncoming();
}
function end() {
busyNotificationLock = false;
// If there is an active call we end this one
if (telephony.active) {
telephony.active.hangUp();
return;
}
// If not we're rejecting the last incoming call
if (!handledCalls.length) {
exitCallScreen(true);
return;
}
var lastCallIndex = handledCalls.length - 1;
handledCalls[lastCallIndex].call.hangUp();
}
function unmute() {
telephony.muted = false;
}
function turnSpeakerOn() {
if (!telephony.speakerEnabled) {
telephony.speakerEnabled = true;
if (settings) {
settings.createLock().set({'telephony.speaker.enabled': true});
}
}
}
function turnSpeakerOff() {
if (telephony.speakerEnabled) {
telephony.speakerEnabled = false;
if (settings) {
settings.createLock().set({'telephony.speaker.enabled': false});
}
}
}
function toggleMute() {
telephony.muted = !telephony.muted;
}
function toggleSpeaker() {
if (telephony.speakerEnabled)
turnSpeakerOff();
else
turnSpeakerOn();
}
/* === Recents management === */
function addRecentEntry(entry) {
var message = {
type: 'recent',
entry: entry
};
postToMainWindow(message);
}
function notifyBusyLine() {
busyNotificationLock = true;
// ANSI call waiting tone for a 3 seconds window.
var sequence = [[480, 620, 500],
[0, 0, 500],
[480, 620, 500],
[0, 0, 500],
[480, 620, 500],
[0, 0, 500]];
TonePlayer.playSequence(sequence);
setTimeout(function busyLineStopped() {
busyNotificationLock = false;
if (handledCalls.length === 0) {
exitCallScreen(true);
}
}, 3000);
}
function activeCall() {
var telephonyActiveCall = telephony.active;
var activeCall = null;
for (var i = 0; i < handledCalls.length; i++) {
var handledCall = handledCalls[i];
if (telephonyActiveCall === handledCall.call) {
activeCall = handledCall;
break;
}
}
return activeCall;
}
return {
setup: setup,
answer: answer,
holdAndAnswer: holdAndAnswer,
endAndAnswer: endAndAnswer,
toggleCalls: toggleCalls,
ignore: ignore,
end: end,
updateKeypadEnabled: updateKeypadEnabled,
toggleMute: toggleMute,
toggleSpeaker: toggleSpeaker,
unmute: unmute,
turnSpeakerOn: turnSpeakerOn,
turnSpeakerOff: turnSpeakerOff,
addRecentEntry: addRecentEntry,
notifyBusyLine: notifyBusyLine,
activeCall: activeCall
};
})();
window.addEventListener('load', function callSetup(evt) {
window.removeEventListener('load', callSetup);
OnCallHandler.setup();
CallScreen.init();
CallScreen.syncSpeakerEnabled();
KeypadManager.init(true);
});