-
Notifications
You must be signed in to change notification settings - Fork 228
/
flashphoner-core.js
1896 lines (1801 loc) · 63.5 KB
/
flashphoner-core.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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
var uuid = require('node-uuid');
var constants = require("./constants");
var util = require('./util');
var logger = require('./util').logger;
var loggerConf = {push: false, severity: "INFO"};
var Promise = require('promise-polyfill');
var browser = require('webrtc-adapter').browserDetails;
var LOG_PREFIX = "core";
/**
* @namespace Flashphoner
*/
var SESSION_STATUS = constants.SESSION_STATUS;
var STREAM_STATUS = constants.STREAM_STATUS;
var CALL_STATUS = constants.CALL_STATUS;
var MediaProvider = {};
var sessions = {};
var initialized = false;
/**
* Static initializer.
*
* @param {Object} options Global api options
* @param {Function=} options.webRTCPluginReadyCallback Callback of initialized WebRTC Plugin
* @param {String=} options.flashMediaProviderSwfLocation Location of media-provider.swf file
* @param {string=} options.preferredMediaProvider Use preferred media provider if available
* @param {String=} options.receiverLocation Location of WSReceiver.js file
* @param {String=} options.decoderLocation Location of video-worker2.js file
* @param {String=} options.screenSharingExtensionId Chrome screen sharing extension id
* @param {Object=} options.constraints Default local media constraints
* @param {Object=} options.logger Enable logging
* @throws {Error} Error if none of MediaProviders available
* @memberof Flashphoner
*/
var init = function(options) {
if (!initialized) {
if (!options) {
options = {};
}
loggerConf = options.logger || loggerConf;
// init logger
logger.init(loggerConf.severity, loggerConf.push);
try {
var audioContext = new (window.AudioContext || window.webkitAudioContext)();
} catch(e) {
console.warn("Failed to create audio context");
}
var webRtcProvider = require("./webrtc-media-provider");
if (webRtcProvider && webRtcProvider.hasOwnProperty('available') && webRtcProvider.available()) {
MediaProvider.WebRTC = webRtcProvider;
var webRtcConf = {
constraints: options.constraints || getDefaultMediaConstraints(),
extensionId: options.screenSharingExtensionId,
audioContext: audioContext,
logger: logger
};
webRtcProvider.configure(webRtcConf);
} else {
webRtcProvider = require("./temasys-media-provider");
if (webRtcProvider && webRtcProvider.hasOwnProperty('available')) {
var adapterjs = require('adapterjs');
adapterjs.webRTCReady(function (isUsingPlugin) {
if (isUsingPlugin || webRtcProvider.available()) {
MediaProvider.WebRTC = webRtcProvider;
var webRtcConf = {
constraints: options.constraints || getDefaultMediaConstraints(),
extensionId: options.screenSharingExtensionId,
logger: logger
};
webRtcProvider.configure(webRtcConf);
// Just reorder media provider list
var _MediaProvider = {};
_MediaProvider.WebRTC = MediaProvider.WebRTC;
for (var p in MediaProvider) {
_MediaProvider[p] = MediaProvider[p];
}
MediaProvider = _MediaProvider;
}
if (options.webRTCPluginReadyCallback) {
options.webRTCPluginReadyCallback(isUsingPlugin);
}
});
}
}
var flashProvider = require("./flash-media-provider");
if (flashProvider && flashProvider.hasOwnProperty('available') && flashProvider.available() && !MediaProvider.WebRTC) {
MediaProvider.Flash = flashProvider;
var flashConf = {
constraints: options.constraints || getDefaultMediaConstraints(),
flashMediaProviderSwfLocation: options.flashMediaProviderSwfLocation,
logger: logger
};
flashProvider.configure(flashConf);
}
var websocketProvider = require("./websocket-media-provider");
if (websocketProvider && websocketProvider.hasOwnProperty('available') && websocketProvider.available()) {
MediaProvider.WSPlayer = websocketProvider;
var wsConf = {
receiverLocation: options.receiverLocation,
decoderLocation: options.decoderLocation,
audioContext: audioContext,
logger: logger
};
websocketProvider.configure(wsConf);
}
//check at least 1 provider available
if (getMediaProviders().length == 0) {
throw new Error('None of MediaProviders available');
} else if (options.preferredMediaProvider) {
if (MediaProvider.hasOwnProperty(options.preferredMediaProvider)) {
if (getMediaProviders()[0] != options.preferredMediaProvider) {
// Just reorder media provider list
var _MediaProvider = {};
_MediaProvider[options.preferredMediaProvider] = MediaProvider[options.preferredMediaProvider];
for (var p in MediaProvider) {
_MediaProvider[p] = MediaProvider[p];
}
MediaProvider = _MediaProvider;
}
} else {
logger.warn(LOG_PREFIX, "Preferred media provider is not available.");
}
}
logger.info(LOG_PREFIX, "Initialized");
initialized = true;
}
};
/**
* Get available MediaProviders.
*
* @returns {Array} Available MediaProviders
* @memberof Flashphoner
*/
var getMediaProviders = function() {
return Object.keys(MediaProvider);
};
/**
* Play audio chunk
*
* @memberof Flashphoner
*/
var playFirstSound = function() {
var mediaProvider = getMediaProviders()[0];
MediaProvider[mediaProvider].playFirstSound();
}
/**
* Get logger
*
* @returns {Object} Logger
* @memberof Flashphoner
*/
var getLogger = function() {
if (!initialized) {
console.warn("Initialize API first.");
} else {
return logger;
}
}
/**
* @typedef Flashphoner.MediaDeviceList
* @type Object
* @property {Flashphoner.MediaDevice[]} audio Audio devices (microphones)
* @property {Flashphoner.MediaDevice[]} video Video devices (cameras)
*/
/**
* @typedef Flashphoner.MediaDevice
* @type Object
* @property {String} type Type of device: mic, camera, screen
* @property {String} id Unique id
* @property {String} label Device label
*/
/**
* Get available local media devices
*
* @param {String=} mediaProvider Media provider that will be asked for device list
* @param {Boolean=} labels Ask user for microphone access before getting device list.
* This will make device label available.
* @returns {Promise.<Flashphoner.MediaDeviceList>} Promise with media device list on fulfill
* @throws {Error} Error if API is not initialized
* @memberof Flashphoner
*/
var getMediaDevices = function(mediaProvider, labels) {
if (!initialized) {
throw new Error("Flashphoner API is not initialized");
}
if (!mediaProvider) {
mediaProvider = getMediaProviders()[0];
}
return MediaProvider[mediaProvider].listDevices(labels);
};
/**
* Get access to local media
*
* @param {Object} constraints Media constraints
* @param {Object} constraints.audio Audio constraints
* @param {String=} constraints.audio.deviceId Audio device id
* @param {Object} constraints.video Video constraints
* @param {String=} constraints.video.deviceId Video device id
* @param {number} constraints.video.width Video width
* @param {number} constraints.video.height Video height
* @param {number} constraints.video.frameRate Video fps
* @param {String} constraints.video.type Video device type: camera, screen
* @param {HTMLElement} display Div element local media should be displayed in
* @param {String} mediaProvider Media provider type
* @returns {Promise.<HTMLElement>} Promise with display on fulfill
* @throws {Error} Error if API is not initialized
* @memberof Flashphoner
*/
var getMediaAccess = function(constraints, display, mediaProvider) {
if (!initialized) {
throw new Error("Flashphoner API is not initialized");
}
if (!mediaProvider) {
mediaProvider = getMediaProviders()[0];
}
return MediaProvider[mediaProvider].getMediaAccess(constraints, display);
};
//default constraints helper
var getDefaultMediaConstraints = function() {
return {
audio: true,
video: {
width: 320,
height: 240
}
};
};
function getConstraintsProperty(constraints, property, defaultValue) {
if (!constraints || !property) return defaultValue;
var res;
var properties = property.split(".");
for (var prop in constraints) {
if (prop == properties[0]) {
res = constraints[prop];
if (properties.length > 1) res = getConstraintsProperty(constraints[prop], properties[1], defaultValue);
} else if (typeof constraints[prop] === "object") {
for (var p in constraints[prop]) {
if (p == property) res = constraints[prop][p];
}
}
}
if (typeof res === "boolean") return res;
return res || defaultValue;
}
/**
* Release local media
*
* @param {HTMLElement} display Div element with local media
* @param {String=} mediaProvider Media provider type
* @returns {Boolean} True if media was found and released
* @throws {Error} Error if API is not initialized
* @memberof Flashphoner
*/
var releaseLocalMedia = function(display, mediaProvider) {
if (!initialized) {
throw new Error("Flashphoner API is not initialized");
}
if (!mediaProvider) {
mediaProvider = getMediaProviders()[0];
}
return MediaProvider[mediaProvider].releaseMedia(display);
};
/**
* Get active sessions.
*
* @returns {Session[]} Array containing active sessions
* @memberof Flashphoner
*/
var getSessions = function() {
return util.copyObjectToArray(sessions);
};
/**
* Get session by id.
*
* @param {string} id Session id
* @returns {Session} Session
* @memberof Flashphoner
*/
var getSession = function(id) {
return sessions[id];
};
/**
* Create new session and connect to server.
*
* @param {Object} options Session options
* @param {string} options.urlServer Server address in form of [ws,wss]://host.domain:port
* @param {string=} options.appKey REST App key
* @param {Object=} options.custom User provided custom object that will be available in REST App code
* @param {Object=} options.sipOptions Sip configuration
* @param {Object=} options.mediaOptions Media connection configuration
* @returns {Session} Created session
* @throws {Error} Error if API is not initialized
* @throws {TypeError} Error if options.urlServer is not specified
* @memberof Flashphoner
*/
var createSession = function(options) {
if (!initialized) {
throw new Error("Flashphoner API is not initialized");
}
if (!options || !options.urlServer) {
throw new TypeError("options.urlServer must be provided");
}
var id_ = uuid.v1();
var sessionStatus = SESSION_STATUS.PENDING;
var urlServer = options.urlServer;
var appKey = options.appKey || "defaultApp";
var mediaOptions = options.mediaOptions;
//SIP config
var sipConfig;
if (options.sipOptions) {
sipConfig = {
sipLogin: options.sipOptions.login,
sipAuthenticationName: options.sipOptions.authenticationName,
sipPassword: options.sipOptions.password,
sipDomain: options.sipOptions.domain,
sipOutboundProxy: options.sipOptions.outboundProxy,
sipProxy: options.sipOptions.proxy,
sipPort: options.sipOptions.port,
sipRegisterRequired: options.sipOptions.registerRequired
}
}
//media provider auth token received from server
var authToken;
//object for storing new and active streams
var streams = {};
var calls = {};
var mediaConnections = {};
//session to stream callbacks
var streamRefreshHandlers = {};
//session to call callbacks
var callRefreshHandlers = {};
/**
* Represents connection to REST App.
* Can create and store Streams.
*
* @see Flashphoner.createSession
* @namespace Session
*/
var session = {};
//callbacks added using session.on()
var callbacks = {};
//connect session to server
var wsConnection = new WebSocket(urlServer);
wsConnection.onerror = function() {
onSessionStatusChange(SESSION_STATUS.FAILED);
};
wsConnection.onclose = function() {
if (sessionStatus !== SESSION_STATUS.FAILED) {
onSessionStatusChange(SESSION_STATUS.DISCONNECTED);
}
};
wsConnection.onopen = function() {
onSessionStatusChange(SESSION_STATUS.CONNECTED);
var cConfig = {
appKey: appKey,
mediaProviders: Object.keys(MediaProvider),
clientVersion: "0.5.16",
clientOSVersion: window.navigator.appVersion,
clientBrowserVersion: window.navigator.userAgent,
custom: options.custom,
};
if (getMediaProviders()[0] == "WSPlayer") {
cConfig.useWsTunnel = true;
cConfig.useWsTunnelPacketization2 = true;
cConfig.useBase64BinaryEncoding = false;
}
if (sipConfig) {
util.copyObjectPropsToAnotherObject(sipConfig, cConfig);
}
//connect to REST App
send("connection", cConfig);
logger.setConnection(wsConnection);
};
//todo remove
var remoteSdpCache = {};
wsConnection.onmessage = function(event) {
var data = {};
if (event.data instanceof Blob) {
data.message = "binaryData";
} else {
data = JSON.parse(event.data);
var obj = data.data[0];
}
switch (data.message) {
case 'ping':
send("pong", null);
break;
case 'getUserData':
authToken = obj.authToken;
onSessionStatusChange(SESSION_STATUS.ESTABLISHED);
break;
case 'setRemoteSDP':
var mediaSessionId = data.data[0];
var sdp = data.data[1];
if (streamRefreshHandlers[mediaSessionId]) {
//pass server's sdp to stream
streamRefreshHandlers[mediaSessionId](null, sdp);
} else if (callRefreshHandlers[mediaSessionId]) {
//pass server's sdp to call
callRefreshHandlers[mediaSessionId](null, sdp);
} else {
remoteSdpCache[mediaSessionId] = sdp;
logger.warn(LOG_PREFIX, "Media not found, id " + mediaSessionId);
}
break;
case 'notifyVideoFormat':
case 'notifyStreamStatusEvent':
if (streamRefreshHandlers[obj.mediaSessionId]) {
//update stream status
streamRefreshHandlers[obj.mediaSessionId](obj);
}
break;
case 'DataStatusEvent':
restAppCommunicator.resolveData(obj);
break;
case 'OnDataEvent':
if (callbacks[SESSION_STATUS.APP_DATA]) {
callbacks[SESSION_STATUS.APP_DATA](obj);
}
break;
case 'fail':
if (obj.apiMethod && obj.apiMethod == "StreamStatusEvent") {
if (streamRefreshHandlers[obj.id]) {
//update stream status
streamRefreshHandlers[obj.id](obj);
}
}
break;
case 'registered':
onSessionStatusChange(SESSION_STATUS.REGISTERED);
break;
case 'notifyAudioCodec':
// This case for Flash only
var mediaSessionId = data.data[0];
var codec = data.data[1];
if (callRefreshHandlers[mediaSessionId]) {
callRefreshHandlers[mediaSessionId](null, null, codec);
}
break;
case 'notifyTransferEvent':
callRefreshHandlers[obj.callId](null, null, null, obj);
break;
case 'notifyTryingResponse':
case 'hold':
case 'ring':
case 'talk':
case 'finish':
if (callRefreshHandlers[obj.callId]) {
//update call status
callRefreshHandlers[obj.callId](obj);
}
break;
case 'notifyIncomingCall':
if (callRefreshHandlers[obj.callId]) {
logger.error(LOG_PREFIX, "Call already exists, id " + obj.callId);
}
if (callbacks[SESSION_STATUS.INCOMING_CALL]) {
callbacks[SESSION_STATUS.INCOMING_CALL](createCall(obj));
} else {
//todo hangup call
}
break;
default:
//logger.info(LOG_PREFIX, "Unknown server message " + data.message);
}
};
//WebSocket send helper
function send(message, data) {
wsConnection.send(JSON.stringify({
message: message,
data: [data]
}));
}
//Session status update helper
function onSessionStatusChange(newStatus) {
sessionStatus = newStatus;
if (sessionStatus == SESSION_STATUS.DISCONNECTED || sessionStatus == SESSION_STATUS.FAILED) {
//remove streams
for (var prop in streamRefreshHandlers) {
if (streamRefreshHandlers.hasOwnProperty(prop) && typeof streamRefreshHandlers[prop] === 'function') {
streamRefreshHandlers[prop]({status: STREAM_STATUS.FAILED});
}
}
//remove session from list
delete sessions[id_];
}
if (callbacks[sessionStatus]) {
callbacks[sessionStatus](session);
}
}
/**
* Create call.
*
* @param {Object} options Call options
* @param {string} options.callee Call remote party id
* @param {string=} options.visibleName Call caller visible name
* @param {Object} options.constraints Call constraints
* @param {string} options.mediaProvider MediaProvider type to use with this call
* @param {Boolean=} options.receiveAudio Receive audio
* @param {Boolean=} options.receiveVideo Receive video
* @param {Boolean=} options.cacheLocalResources Display will contain local video after call release
* @param {HTMLElement} options.localVideoDisplay Div element local video should be displayed in
* @param {HTMLElement} options.remoteVideoDisplay Div element remote video should be displayed in
* @param {Object=} options.custom User provided custom object that will be available in REST App code
* @param {Array<string>=} options.stripCodecs Array of codecs which should be stripped from SDP (WebRTC)
* @returns {Call} Call
* @throws {TypeError} Error if no options provided
* @throws {Error} Error if session state is not REGISTERED
* @memberof Session
* @inner
*/
var createCall = function(options) {
//check session state
if (sessionStatus !== SESSION_STATUS.REGISTERED && sessionStatus !== SESSION_STATUS.ESTABLISHED) {
logger.info(LOG_PREFIX, "Status is " + sessionStatus);
throw new Error('Invalid session state');
}
//check options
if (!options) {
throw new TypeError("options must be provided");
}
var login = (appKey == 'clickToCallApp') ? '' : sipConfig.sipLogin;
var caller_ = (options.incoming) ? options.caller : login;
var callee_ = options.callee;
var visibleName_ = options.visibleName || login;
var id_ = options.callId || uuid.v1();
var mediaProvider = options.mediaProvider || getMediaProviders()[0];
var mediaConnection;
var localDisplay = options.localVideoDisplay;
var remoteDisplay = options.remoteVideoDisplay;
// Constraints
if (options.constraints) {
var constraints = options.constraints;
}
var stripCodecs = options.stripCodecs || [];
// Receive media
var receiveAudio = (typeof options.receiveAudio !== 'undefined') ? options.receiveAudio : true;
var receiveVideo = (typeof options.receiveVideo !== 'undefined') ? options.receiveVideo : true;
var cacheLocalResources = options.cacheLocalResources;
var status_ = CALL_STATUS.NEW;
var callbacks = {};
var hasTransferredCall = false;
/**
* Represents sip call.
*
* @namespace Call
* @see Session~createCall
*/
var call = {};
callRefreshHandlers[id_] = function(callInfo, sdp, codec, transfer) {
if (transfer) {
if (!mediaConnections[id_]) {
mediaConnections[id_] = mediaConnection;
}
if (transfer.status == "COMPLETED") {
delete mediaConnections[id_];
}
return;
}
//transferred call
if (!mediaConnection && Object.keys(mediaConnections).length != 0) {
for (var mc in mediaConnections) {
mediaConnection = mediaConnections[mc];
hasTransferredCall = true;
delete mediaConnections[mc];
}
}
//set audio codec (Flash only)
if (codec) {
if(mediaProvider == "Flash") {
mediaConnection.changeAudioCodec(codec.name);
}
return;
}
//set remote sdp
if (sdp && sdp !== '') {
mediaConnection.setRemoteSdp(sdp, hasTransferredCall, id_).then(function(){});
return;
}
var event = callInfo.status;
status_ = event;
//release call
if (event == CALL_STATUS.FAILED || event == CALL_STATUS.FINISH ||
event == CALL_STATUS.BUSY) {
delete calls[id_];
delete callRefreshHandlers[id_];
if (Object.keys(calls).length == 0) {
if (mediaConnection)
mediaConnection.close(cacheLocalResources);
}
}
//fire call event
if (callbacks[event]) {
callbacks[event](call);
}
};
/**
* Initiate outgoing call.
*
* @throws {Error} Error if call status is not {@link Flashphoner.constants.CALL_STATUS.NEW}
* @memberof Call
* @name call
* @inner
*/
var call_ = function() {
if (status_ !== CALL_STATUS.NEW) {
throw new Error("Invalid call state");
}
status_ = CALL_STATUS.PENDING;
var hasAudio = true;
//get access to camera
MediaProvider[mediaProvider].getMediaAccess(constraints, localDisplay).then(function(){
if (status_ == CALL_STATUS.FAILED) {
//call failed while we were waiting for media access, release media
if (!cacheLocalResources) {
releaseLocalMedia(localDisplay, mediaProvider);
}
return;
}
//create mediaProvider connection
MediaProvider[mediaProvider].createConnection({
id: id_,
localDisplay: localDisplay,
remoteDisplay: remoteDisplay,
authToken: authToken,
mainUrl: urlServer,
bidirectional: true,
login: login,
connectionConfig: mediaOptions
}).then(function(newConnection) {
mediaConnection = newConnection;
return mediaConnection.createOffer({
sendAudio: true,
sendVideo: true,
receiveAudio: receiveAudio,
receiveVideo: receiveVideo,
stripCodecs: stripCodecs
});
}).then(function (offer) {
send("call", {
callId: id_,
incoming: false,
hasVideo: offer.hasVideo,
hasAudio: offer.hasAudio,
status: status_,
mediaProvider: mediaProvider,
sdp: offer.sdp,
caller: login,
callee: callee_,
custom: options.custom,
visibleName: visibleName_
});
});
}).catch(function(error){
logger.error(LOG_PREFIX, error);
status_ = CALL_STATUS.FAILED;
callRefreshHandlers[id_]({status: CALL_STATUS.FAILED});
});
};
/**
* Hangup call.
*
* @memberof Call
* @inner
*/
var hangup = function() {
if (status_ == CALL_STATUS.NEW) {
callRefreshHandlers[id_]({status: CALL_STATUS.FAILED});
return;
} else if (status_ == CALL_STATUS.PENDING) {
if (!cacheLocalResources) {
releaseLocalMedia(localDisplay, mediaProvider);
}
callRefreshHandlers[id_]({status: CALL_STATUS.FAILED});
if (options.incoming) {
send("hangup", {
callId: id_
});
}
return;
}
send("hangup", {
callId: id_
});
//free media provider
if (mediaConnection) {
mediaConnection.close(cacheLocalResources);
}
};
/**
* Answer incoming call.
* @param {Object} answerOptions Call options
* @param {HTMLElement} answerOptions.localVideoDisplay Div element local video should be displayed in
* @param {HTMLElement} answerOptions.remoteVideoDisplay Div element remote video should be displayed in
* @param {Boolean=} answerOptions.receiveAudio Receive audio
* @param {Boolean=} answerOptions.receiveVideo Receive video
* @param {String=} answerOptions.constraints Answer call with constraints
* @param {Array<string>=} answerOptions.stripCodecs Array of codecs which should be stripped from SDP (WebRTC)
* @throws {Error} Error if call status is not {@link Flashphoner.constants.CALL_STATUS.NEW}
* @memberof Call
* @name call
* @inner
*/
var answer = function(answerOptions) {
if (status_ !== CALL_STATUS.NEW && status_ !== CALL_STATUS.RING) {
throw new Error("Invalid call state");
}
localDisplay = answerOptions.localVideoDisplay;
remoteDisplay = answerOptions.remoteVideoDisplay;
constraints = answerOptions.constraints || getDefaultMediaConstraints();
status_ = CALL_STATUS.PENDING;
var sdp;
if (!remoteSdpCache[id_]) {
logger.error(LOG_PREFIX, "No remote sdp available");
throw new Error("No remote sdp available");
} else {
sdp = remoteSdpCache[id_];
delete remoteSdpCache[id_];
}
if (util.SDP.matchPrefix(sdp,"m=video").length == 0) {
constraints.video = false;
}
var stripCodecs = answerOptions.stripCodecs || [];
var hasAudio = true;
//get access to camera
MediaProvider[mediaProvider].getMediaAccess(constraints, localDisplay).then(function(){
if (status_ == CALL_STATUS.FAILED) {
//call failed while we were waiting for media access, release media
if (!cacheLocalResources) {
releaseLocalMedia(localDisplay, mediaProvider);
}
return;
}
//create mediaProvider connection
MediaProvider[mediaProvider].createConnection({
id: id_,
localDisplay: localDisplay,
remoteDisplay: remoteDisplay,
authToken: authToken,
mainUrl: urlServer,
bidirectional: true,
login: sipConfig.sipLogin,
connectionConfig: mediaOptions
}).then(function(newConnection) {
mediaConnection = newConnection;
return mediaConnection.setRemoteSdp(sdp);
}).then(function(){
return mediaConnection.createAnswer({
receiveAudio: options.receiveAudio,
receiveVideo: options.receiveVideo,
stripCodecs: stripCodecs
});
}).then(function(sdp) {
if (status_ != CALL_STATUS.FINISH && status_ != CALL_STATUS.FAILED) {
send("answer", {
callId: id_,
incoming: true,
hasVideo: true,
hasAudio: hasAudio,
status: status_,
mediaProvider: mediaProvider,
sdp: sdp,
caller: sipConfig.login,
callee: callee_,
custom: options.custom
});
} else {
hangup();
}
});
}).catch(function(error){
logger.error(LOG_PREFIX, error);
status_ = CALL_STATUS.FAILED;
callRefreshHandlers[id_]({status: CALL_STATUS.FAILED});
});
};
/**
* Get call status.
*
* @returns {string} One of {@link Flashphoner.constants.CALL_STATUS}
* @memberof Call
* @inner
*/
var status = function() {
return status_;
};
/**
* Get call id.
*
* @returns {string} Call id
* @memberof Call
* @inner
*/
var id = function() {
return id_;
};
/**
* Get caller id.
*
* @returns {string} Caller id
* @memberof Call
* @inner
*/
var caller = function() {
return caller_;
};
/**
* Get callee id.
*
* @returns {string} Callee id
* @memberof Call
* @inner
*/
var callee = function() {
return callee_;
};
/**
* Get caller visible name.
*
* @returns {string} Caller visible name
* @memberof Call
* @inner
*/
var visibleName = function() {
return visibleName_;
};
/**
* Media controls
*/
/**
* Set volume of remote media
*
* @param {number} volume Volume between 0 and 100
* @memberof Call
* @inner
*/
var setVolume = function(volume) {
if (mediaConnection) {
mediaConnection.setVolume(volume);
}
};
/**
* Get current volume
*
* @returns {number} Volume or -1 if audio is not available
* @memberof Call
* @inner
*/
var getVolume = function() {
if (mediaConnection) {
return mediaConnection.getVolume();
}
return -1;
};
/**
* Mute outgoing audio
*
* @memberof Call
* @inner
*/
var muteAudio = function() {
if (mediaConnection) {
mediaConnection.muteAudio();
}
};
/**
* Unmute outgoing audio
*
* @memberof Call
* @inner
*/
var unmuteAudio = function() {
if (mediaConnection) {
mediaConnection.unmuteAudio();
}
};
/**
* Check outgoing audio mute state
*
* @returns {boolean} True if audio is muted or not available
* @memberof Call
* @inner
*/
var isAudioMuted = function() {
if (mediaConnection) {
return mediaConnection.isAudioMuted();
}
return true;
};
/**
* Mute outgoing video
*
* @memberof Call
* @inner
*/
var muteVideo = function() {
if (mediaConnection) {
mediaConnection.muteVideo();
}
};
/**
* Unmute outgoing video
*
* @memberof Call
* @inner
*/
var unmuteVideo = function() {
if (mediaConnection) {
mediaConnection.unmuteVideo();
}
};
/**
* Check outgoing video mute state
*
* @returns {boolean} True if video is muted or not available
* @memberof Call
* @inner
*/
var isVideoMuted = function() {
if (mediaConnection) {
return mediaConnection.isVideoMuted();
}
return true;
};
/**
* @callback callbackFn
* @param {Object} result
*/
/**
* Get statistics
*
* @param {callbackFn} callbackFn The callback that handles response
* @returns {Object} Call audio\video statistics
* @memberof Call
* @inner
*/
var getStats = function (callbackFn) {
if (mediaConnection) {
mediaConnection.getStats(callbackFn);
}
};
/**
* Place call on hold
*
* @memberof Call
* @inner
*/
var hold = function() {
send("hold", {callId: id_});
}
/**
* Place call on hold for transfer
*
* @memberof Call