You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.js 50KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582
  1. /* jshint -W117 */
  2. /* application specific logic */
  3. var connection = null;
  4. var authenticatedUser = false;
  5. var focus = null;
  6. var activecall = null;
  7. var RTC = null;
  8. var nickname = null;
  9. var sharedKey = '';
  10. var recordingToken ='';
  11. var roomUrl = null;
  12. var roomName = null;
  13. var ssrc2jid = {};
  14. var mediaStreams = [];
  15. var bridgeIsDown = false;
  16. /**
  17. * The stats collector that process stats data and triggers updates to app.js.
  18. * @type {StatsCollector}
  19. */
  20. var statsCollector = null;
  21. /**
  22. * The stats collector for the local stream.
  23. * @type {LocalStatsCollector}
  24. */
  25. var localStatsCollector = null;
  26. /**
  27. * Indicates whether ssrc is camera video or desktop stream.
  28. * FIXME: remove those maps
  29. */
  30. var ssrc2videoType = {};
  31. var videoSrcToSsrc = {};
  32. /**
  33. * Currently focused video "src"(displayed in large video).
  34. * @type {String}
  35. */
  36. var focusedVideoSrc = null;
  37. var mutedAudios = {};
  38. var localVideoSrc = null;
  39. var flipXLocalVideo = true;
  40. var isFullScreen = false;
  41. var currentVideoWidth = null;
  42. var currentVideoHeight = null;
  43. /**
  44. * Method used to calculate large video size.
  45. * @type {function ()}
  46. */
  47. var getVideoSize;
  48. /**
  49. * Method used to get large video position.
  50. * @type {function ()}
  51. */
  52. var getVideoPosition;
  53. /* window.onbeforeunload = closePageWarning; */
  54. var sessionTerminated = false;
  55. function init() {
  56. Toolbar.setupButtonsFromConfig();
  57. RTC = setupRTC();
  58. if (RTC === null) {
  59. window.location.href = 'webrtcrequired.html';
  60. return;
  61. } else if (RTC.browser !== 'chrome') {
  62. window.location.href = 'chromeonly.html';
  63. return;
  64. }
  65. obtainAudioAndVideoPermissions(function (stream) {
  66. var audioStream = new webkitMediaStream();
  67. var videoStream = new webkitMediaStream();
  68. var audioTracks = stream.getAudioTracks();
  69. var videoTracks = stream.getVideoTracks();
  70. for (var i = 0; i < audioTracks.length; i++) {
  71. audioStream.addTrack(audioTracks[i]);
  72. }
  73. VideoLayout.changeLocalAudio(audioStream);
  74. startLocalRtpStatsCollector(audioStream);
  75. for (i = 0; i < videoTracks.length; i++) {
  76. videoStream.addTrack(videoTracks[i]);
  77. }
  78. VideoLayout.changeLocalVideo(videoStream, true);
  79. maybeDoJoin();
  80. });
  81. var jid = document.getElementById('jid').value || config.hosts.anonymousdomain || config.hosts.domain || window.location.hostname;
  82. connect(jid);
  83. }
  84. function connect(jid, password) {
  85. var localAudio, localVideo;
  86. if (connection && connection.jingle) {
  87. localAudio = connection.jingle.localAudio;
  88. localVideo = connection.jingle.localVideo;
  89. }
  90. connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
  91. if (nickname) {
  92. connection.emuc.addDisplayNameToPresence(nickname);
  93. }
  94. if (connection.disco) {
  95. // for chrome, add multistream cap
  96. }
  97. connection.jingle.pc_constraints = RTC.pc_constraints;
  98. if (config.useIPv6) {
  99. // https://code.google.com/p/webrtc/issues/detail?id=2828
  100. if (!connection.jingle.pc_constraints.optional) connection.jingle.pc_constraints.optional = [];
  101. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  102. }
  103. if (localAudio) connection.jingle.localAudio = localAudio;
  104. if (localVideo) connection.jingle.localVideo = localVideo;
  105. if(!password)
  106. password = document.getElementById('password').value;
  107. var anonymousConnectionFailed = false;
  108. connection.connect(jid, password, function (status, msg) {
  109. console.log('Strophe status changed to', Strophe.getStatusString(status));
  110. if (status === Strophe.Status.CONNECTED) {
  111. if (config.useStunTurn) {
  112. connection.jingle.getStunAndTurnCredentials();
  113. }
  114. document.getElementById('connect').disabled = true;
  115. if(password)
  116. authenticatedUser = true;
  117. maybeDoJoin();
  118. } else if (status === Strophe.Status.CONNFAIL) {
  119. if(msg === 'x-strophe-bad-non-anon-jid') {
  120. anonymousConnectionFailed = true;
  121. }
  122. } else if (status === Strophe.Status.DISCONNECTED) {
  123. if(anonymousConnectionFailed) {
  124. // prompt user for username and password
  125. $(document).trigger('passwordrequired.main');
  126. }
  127. } else if (status === Strophe.Status.AUTHFAIL) {
  128. // wrong password or username, prompt user
  129. $(document).trigger('passwordrequired.main');
  130. }
  131. });
  132. }
  133. /**
  134. * We ask for audio and video combined stream in order to get permissions and
  135. * not to ask twice.
  136. */
  137. function obtainAudioAndVideoPermissions(callback) {
  138. // Get AV
  139. getUserMediaWithConstraints(
  140. ['audio', 'video'],
  141. function (avStream) {
  142. callback(avStream);
  143. trackUsage('localMedia', {
  144. audio: avStream.getAudioTracks().length,
  145. video: avStream.getVideoTracks().length
  146. });
  147. },
  148. function (error) {
  149. console.error('failed to obtain audio/video stream - stop', error);
  150. trackUsage('localMediaError', {
  151. media: error.media || 'video',
  152. name : error.name
  153. });
  154. messageHandler.showError("Error",
  155. "Failed to obtain permissions to use the local microphone" +
  156. "and/or camera.");
  157. },
  158. config.resolution || '360');
  159. }
  160. function maybeDoJoin() {
  161. if (connection && connection.connected && Strophe.getResourceFromJid(connection.jid) // .connected is true while connecting?
  162. && (connection.jingle.localAudio || connection.jingle.localVideo)) {
  163. doJoin();
  164. }
  165. }
  166. function doJoin() {
  167. var roomnode = null;
  168. var path = window.location.pathname;
  169. var roomjid;
  170. // determinde the room node from the url
  171. // TODO: just the roomnode or the whole bare jid?
  172. if (config.getroomnode && typeof config.getroomnode === 'function') {
  173. // custom function might be responsible for doing the pushstate
  174. roomnode = config.getroomnode(path);
  175. } else {
  176. /* fall back to default strategy
  177. * this is making assumptions about how the URL->room mapping happens.
  178. * It currently assumes deployment at root, with a rewrite like the
  179. * following one (for nginx):
  180. location ~ ^/([a-zA-Z0-9]+)$ {
  181. rewrite ^/(.*)$ / break;
  182. }
  183. */
  184. if (path.length > 1) {
  185. roomnode = path.substr(1).toLowerCase();
  186. } else {
  187. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  188. roomnode = word.toLowerCase();
  189. window.history.pushState('VideoChat',
  190. 'Room: ' + word, window.location.pathname + word);
  191. }
  192. }
  193. roomName = roomnode + '@' + config.hosts.muc;
  194. roomjid = roomName;
  195. if (config.useNicks) {
  196. var nick = window.prompt('Your nickname (optional)');
  197. if (nick) {
  198. roomjid += '/' + nick;
  199. } else {
  200. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  201. }
  202. } else {
  203. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  204. if(!authenticatedUser)
  205. tmpJid = tmpJid.substr(0, 8);
  206. roomjid += '/' + tmpJid;
  207. }
  208. connection.emuc.doJoin(roomjid);
  209. }
  210. function waitForRemoteVideo(selector, ssrc, stream) {
  211. if (selector.removed || !selector.parent().is(":visible")) {
  212. console.warn("Media removed before had started", selector);
  213. return;
  214. }
  215. if (stream.id === 'mixedmslabel') return;
  216. if (selector[0].currentTime > 0) {
  217. var videoStream = simulcast.getReceivingVideoStream(stream);
  218. RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  219. // FIXME: add a class that will associate peer Jid, video.src, it's ssrc and video type
  220. // in order to get rid of too many maps
  221. if (ssrc && selector.attr('src')) {
  222. videoSrcToSsrc[selector.attr('src')] = ssrc;
  223. } else {
  224. console.warn("No ssrc given for video", selector);
  225. messageHandler.showError('Warning', 'No ssrc was given for the video.');
  226. }
  227. $(document).trigger('videoactive.jingle', [selector]);
  228. } else {
  229. setTimeout(function () {
  230. waitForRemoteVideo(selector, ssrc, stream);
  231. }, 250);
  232. }
  233. }
  234. $(document).bind('remotestreamadded.jingle', function (event, data, sid) {
  235. waitForPresence(data, sid);
  236. });
  237. function waitForPresence(data, sid) {
  238. var sess = connection.jingle.sessions[sid];
  239. var thessrc;
  240. // look up an associated JID for a stream id
  241. if (data.stream.id.indexOf('mixedmslabel') === -1) {
  242. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  243. var ssrclines
  244. = SDPUtil.find_lines(sess.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  245. ssrclines = ssrclines.filter(function (line) {
  246. // NOTE(gp) previously we filtered on the mslabel, but that property
  247. // is not always present.
  248. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  249. return line.indexOf('msid:' + data.stream.id) !== -1;
  250. });
  251. if (ssrclines.length) {
  252. thessrc = ssrclines[0].substring(7).split(' ')[0];
  253. // We signal our streams (through Jingle to the focus) before we set
  254. // our presence (through which peers associate remote streams to
  255. // jids). So, it might arrive that a remote stream is added but
  256. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  257. // successfully set. Here we wait for up to a second for the
  258. // presence to arrive.
  259. if (!ssrc2jid[thessrc]) {
  260. // TODO(gp) limit wait duration to 1 sec.
  261. setTimeout(function(d, s) {
  262. return function() {
  263. waitForPresence(d, s);
  264. }
  265. }(data, sid), 250);
  266. return;
  267. }
  268. // ok to overwrite the one from focus? might save work in colibri.js
  269. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  270. if (ssrc2jid[thessrc]) {
  271. data.peerjid = ssrc2jid[thessrc];
  272. }
  273. }
  274. }
  275. // NOTE(gp) now that we have simulcast, a media stream can have more than 1
  276. // ssrc. We should probably take that into account in our MediaStream
  277. // wrapper.
  278. mediaStreams.push(new MediaStream(data, sid, thessrc));
  279. var container;
  280. var remotes = document.getElementById('remoteVideos');
  281. if (data.peerjid) {
  282. VideoLayout.ensurePeerContainerExists(data.peerjid);
  283. container = document.getElementById(
  284. 'participant_' + Strophe.getResourceFromJid(data.peerjid));
  285. } else {
  286. if (data.stream.id !== 'mixedmslabel') {
  287. console.error('can not associate stream',
  288. data.stream.id,
  289. 'with a participant');
  290. // We don't want to add it here since it will cause troubles
  291. return;
  292. }
  293. // FIXME: for the mixed ms we dont need a video -- currently
  294. container = document.createElement('span');
  295. container.id = 'mixedstream';
  296. container.className = 'videocontainer';
  297. remotes.appendChild(container);
  298. Util.playSoundNotification('userJoined');
  299. }
  300. var isVideo = data.stream.getVideoTracks().length > 0;
  301. if (container) {
  302. VideoLayout.addRemoteStreamElement( container,
  303. sid,
  304. data.stream,
  305. data.peerjid,
  306. thessrc);
  307. }
  308. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  309. if (isVideo &&
  310. data.peerjid && sess.peerjid === data.peerjid &&
  311. data.stream.getVideoTracks().length === 0 &&
  312. connection.jingle.localVideo.getVideoTracks().length > 0) {
  313. //
  314. window.setTimeout(function () {
  315. sendKeyframe(sess.peerconnection);
  316. }, 3000);
  317. }
  318. }
  319. /**
  320. * Returns the JID of the user to whom given <tt>videoSrc</tt> belongs.
  321. * @param videoSrc the video "src" identifier.
  322. * @returns {null | String} the JID of the user to whom given <tt>videoSrc</tt>
  323. * belongs.
  324. */
  325. function getJidFromVideoSrc(videoSrc)
  326. {
  327. if (videoSrc === localVideoSrc)
  328. return connection.emuc.myroomjid;
  329. var ssrc = videoSrcToSsrc[videoSrc];
  330. if (!ssrc)
  331. {
  332. return null;
  333. }
  334. return ssrc2jid[ssrc];
  335. }
  336. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  337. function sendKeyframe(pc) {
  338. console.log('sendkeyframe', pc.iceConnectionState);
  339. if (pc.iceConnectionState !== 'connected') return; // safe...
  340. pc.setRemoteDescription(
  341. pc.remoteDescription,
  342. function () {
  343. pc.createAnswer(
  344. function (modifiedAnswer) {
  345. pc.setLocalDescription(
  346. modifiedAnswer,
  347. function () {
  348. // noop
  349. },
  350. function (error) {
  351. console.log('triggerKeyframe setLocalDescription failed', error);
  352. messageHandler.showError();
  353. }
  354. );
  355. },
  356. function (error) {
  357. console.log('triggerKeyframe createAnswer failed', error);
  358. messageHandler.showError();
  359. }
  360. );
  361. },
  362. function (error) {
  363. console.log('triggerKeyframe setRemoteDescription failed', error);
  364. messageHandler.showError();
  365. }
  366. );
  367. }
  368. // Really mute video, i.e. dont even send black frames
  369. function muteVideo(pc, unmute) {
  370. // FIXME: this probably needs another of those lovely state safeguards...
  371. // which checks for iceconn == connected and sigstate == stable
  372. pc.setRemoteDescription(pc.remoteDescription,
  373. function () {
  374. pc.createAnswer(
  375. function (answer) {
  376. var sdp = new SDP(answer.sdp);
  377. if (sdp.media.length > 1) {
  378. if (unmute)
  379. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  380. else
  381. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  382. sdp.raw = sdp.session + sdp.media.join('');
  383. answer.sdp = sdp.raw;
  384. }
  385. pc.setLocalDescription(answer,
  386. function () {
  387. console.log('mute SLD ok');
  388. },
  389. function (error) {
  390. console.log('mute SLD error');
  391. messageHandler.showError('Error',
  392. 'Oops! Something went wrong and we failed to ' +
  393. 'mute! (SLD Failure)');
  394. }
  395. );
  396. },
  397. function (error) {
  398. console.log(error);
  399. messageHandler.showError();
  400. }
  401. );
  402. },
  403. function (error) {
  404. console.log('muteVideo SRD error');
  405. messageHandler.showError('Error',
  406. 'Oops! Something went wrong and we failed to stop video!' +
  407. '(SRD Failure)');
  408. }
  409. );
  410. }
  411. /**
  412. * Callback for audio levels changed.
  413. * @param jid JID of the user
  414. * @param audioLevel the audio level value
  415. */
  416. function audioLevelUpdated(jid, audioLevel)
  417. {
  418. var resourceJid;
  419. if(jid === LocalStatsCollector.LOCAL_JID)
  420. {
  421. resourceJid = AudioLevels.LOCAL_LEVEL;
  422. if(isAudioMuted())
  423. {
  424. audioLevel = 0;
  425. }
  426. }
  427. else
  428. {
  429. resourceJid = Strophe.getResourceFromJid(jid);
  430. }
  431. AudioLevels.updateAudioLevel(resourceJid, audioLevel);
  432. }
  433. /**
  434. * Starts the {@link StatsCollector} if the feature is enabled in config.js.
  435. */
  436. function startRtpStatsCollector()
  437. {
  438. stopRTPStatsCollector();
  439. if (config.enableRtpStats)
  440. {
  441. statsCollector = new StatsCollector(
  442. getConferenceHandler().peerconnection, 200, audioLevelUpdated, 2000,
  443. ConnectionQuality.updateLocalStats);
  444. statsCollector.start();
  445. }
  446. }
  447. /**
  448. * Stops the {@link StatsCollector}.
  449. */
  450. function stopRTPStatsCollector()
  451. {
  452. if (statsCollector)
  453. {
  454. statsCollector.stop();
  455. statsCollector = null;
  456. ConnectionQuality.stopSendingStats();
  457. }
  458. }
  459. /**
  460. * Starts the {@link LocalStatsCollector} if the feature is enabled in config.js
  461. * @param stream the stream that will be used for collecting statistics.
  462. */
  463. function startLocalRtpStatsCollector(stream)
  464. {
  465. if(config.enableRtpStats)
  466. {
  467. localStatsCollector = new LocalStatsCollector(stream, 100, audioLevelUpdated);
  468. localStatsCollector.start();
  469. }
  470. }
  471. /**
  472. * Stops the {@link LocalStatsCollector}.
  473. */
  474. function stopLocalRtpStatsCollector()
  475. {
  476. if(localStatsCollector)
  477. {
  478. localStatsCollector.stop();
  479. localStatsCollector = null;
  480. }
  481. }
  482. $(document).bind('callincoming.jingle', function (event, sid) {
  483. var sess = connection.jingle.sessions[sid];
  484. // TODO: do we check activecall == null?
  485. activecall = sess;
  486. startRtpStatsCollector();
  487. // Bind data channel listener in case we're a regular participant
  488. if (config.openSctp)
  489. {
  490. bindDataChannelListener(sess.peerconnection);
  491. }
  492. // TODO: check affiliation and/or role
  493. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  494. sess.usedrip = true; // not-so-naive trickle ice
  495. sess.sendAnswer();
  496. sess.accept();
  497. });
  498. $(document).bind('conferenceCreated.jingle', function (event, focus)
  499. {
  500. startRtpStatsCollector();
  501. });
  502. $(document).bind('conferenceCreated.jingle', function (event, focus)
  503. {
  504. // Bind data channel listener in case we're the focus
  505. if (config.openSctp)
  506. {
  507. bindDataChannelListener(focus.peerconnection);
  508. }
  509. });
  510. $(document).bind('callterminated.jingle', function (event, sid, jid, reason) {
  511. // Leave the room if my call has been remotely terminated.
  512. if (connection.emuc.joined && focus == null && reason === 'kick') {
  513. sessionTerminated = true;
  514. connection.emuc.doLeave();
  515. messageHandler.openMessageDialog("Session Terminated",
  516. "Ouch! You have been kicked out of the meet!");
  517. }
  518. });
  519. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  520. // put our ssrcs into presence so other clients can identify our stream
  521. var sess = connection.jingle.sessions[sid];
  522. var newssrcs = [];
  523. var media = simulcast.parseMedia(sess.peerconnection.localDescription);
  524. media.forEach(function (media) {
  525. // TODO(gp) maybe exclude FID streams?
  526. Object.keys(media.sources).forEach(function(ssrc) {
  527. newssrcs.push({
  528. 'ssrc': ssrc,
  529. 'type': media.type,
  530. 'direction': media.direction
  531. });
  532. });
  533. });
  534. console.log('new ssrcs', newssrcs);
  535. // Have to clear presence map to get rid of removed streams
  536. connection.emuc.clearPresenceMedia();
  537. if (newssrcs.length > 0) {
  538. for (var i = 1; i <= newssrcs.length; i ++) {
  539. // Change video type to screen
  540. if (newssrcs[i-1].type === 'video' && isUsingScreenStream) {
  541. newssrcs[i-1].type = 'screen';
  542. }
  543. connection.emuc.addMediaToPresence(i,
  544. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  545. }
  546. connection.emuc.sendPresence();
  547. }
  548. });
  549. $(document).bind('iceconnectionstatechange.jingle', function (event, sid, session) {
  550. switch (session.peerconnection.iceConnectionState) {
  551. case 'checking':
  552. session.timeChecking = (new Date()).getTime();
  553. session.firstconnect = true;
  554. break;
  555. case 'completed': // on caller side
  556. case 'connected':
  557. if (session.firstconnect) {
  558. session.firstconnect = false;
  559. var metadata = {};
  560. metadata.setupTime = (new Date()).getTime() - session.timeChecking;
  561. session.peerconnection.getStats(function (res) {
  562. res.result().forEach(function (report) {
  563. if (report.type == 'googCandidatePair' && report.stat('googActiveConnection') == 'true') {
  564. metadata.localCandidateType = report.stat('googLocalCandidateType');
  565. metadata.remoteCandidateType = report.stat('googRemoteCandidateType');
  566. // log pair as well so we can get nice pie charts
  567. metadata.candidatePair = report.stat('googLocalCandidateType') + ';' + report.stat('googRemoteCandidateType');
  568. if (report.stat('googRemoteAddress').indexOf('[') === 0) {
  569. metadata.ipv6 = true;
  570. }
  571. }
  572. });
  573. trackUsage('iceConnected', metadata);
  574. });
  575. }
  576. break;
  577. }
  578. });
  579. $(document).bind('joined.muc', function (event, jid, info) {
  580. updateRoomUrl(window.location.href);
  581. document.getElementById('localNick').appendChild(
  582. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  583. );
  584. if (Object.keys(connection.emuc.members).length < 1) {
  585. focus = new ColibriFocus(connection, config.hosts.bridge);
  586. if (nickname !== null) {
  587. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  588. nickname);
  589. }
  590. Toolbar.showSipCallButton(true);
  591. Toolbar.showRecordingButton(false);
  592. }
  593. if (!focus)
  594. {
  595. Toolbar.showSipCallButton(false);
  596. }
  597. if (focus && config.etherpad_base) {
  598. Etherpad.init();
  599. }
  600. VideoLayout.showFocusIndicator();
  601. // Add myself to the contact list.
  602. ContactList.addContact(jid);
  603. // Once we've joined the muc show the toolbar
  604. ToolbarToggler.showToolbar();
  605. if (info.displayName)
  606. $(document).trigger('displaynamechanged',
  607. ['localVideoContainer', info.displayName + ' (me)']);
  608. });
  609. $(document).bind('entered.muc', function (event, jid, info, pres) {
  610. console.log('entered', jid, info);
  611. console.log('is focus? ' + (focus ? 'true' : 'false'));
  612. // Add Peer's container
  613. VideoLayout.ensurePeerContainerExists(jid);
  614. if(APIConnector.isEnabled() && APIConnector.isEventEnabled("participantJoined"))
  615. {
  616. APIConnector.triggerEvent("participantJoined",{jid: jid});
  617. }
  618. if (focus !== null) {
  619. // FIXME: this should prepare the video
  620. if (focus.confid === null) {
  621. console.log('make new conference with', jid);
  622. focus.makeConference(Object.keys(connection.emuc.members),
  623. function(error) {
  624. connection.emuc.addBridgeIsDownToPresence();
  625. connection.emuc.sendPresence();
  626. }
  627. );
  628. Toolbar.showRecordingButton(true);
  629. } else {
  630. console.log('invite', jid, 'into conference');
  631. focus.addNewParticipant(jid);
  632. }
  633. }
  634. });
  635. $(document).bind('left.muc', function (event, jid) {
  636. console.log('left.muc', jid);
  637. // Need to call this with a slight delay, otherwise the element couldn't be
  638. // found for some reason.
  639. window.setTimeout(function () {
  640. var container = document.getElementById(
  641. 'participant_' + Strophe.getResourceFromJid(jid));
  642. if (container) {
  643. VideoLayout.removeConnectionIndicator(jid);
  644. // hide here, wait for video to close before removing
  645. $(container).hide();
  646. VideoLayout.resizeThumbnails();
  647. }
  648. }, 10);
  649. if(APIConnector.isEnabled() && APIConnector.isEventEnabled("participantLeft"))
  650. {
  651. APIConnector.triggerEvent("participantLeft",{jid: jid});
  652. }
  653. // Unlock large video
  654. if (focusedVideoSrc)
  655. {
  656. if (getJidFromVideoSrc(focusedVideoSrc) === jid)
  657. {
  658. console.info("Focused video owner has left the conference");
  659. focusedVideoSrc = null;
  660. }
  661. }
  662. connection.jingle.terminateByJid(jid);
  663. if (focus == null
  664. // I shouldn't be the one that left to enter here.
  665. && jid !== connection.emuc.myroomjid
  666. && connection.emuc.myroomjid === connection.emuc.list_members[0]
  667. // If our session has been terminated for some reason
  668. // (kicked, hangup), don't try to become the focus
  669. && !sessionTerminated) {
  670. console.log('welcome to our new focus... myself');
  671. focus = new ColibriFocus(connection, config.hosts.bridge);
  672. if (nickname !== null) {
  673. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  674. nickname);
  675. }
  676. Toolbar.showSipCallButton(true);
  677. if (Object.keys(connection.emuc.members).length > 0) {
  678. focus.makeConference(Object.keys(connection.emuc.members));
  679. Toolbar.showRecordingButton(true);
  680. }
  681. $(document).trigger('focusechanged.muc', [focus]);
  682. }
  683. else if (focus && Object.keys(connection.emuc.members).length === 0) {
  684. console.log('everyone left');
  685. // FIXME: closing the connection is a hack to avoid some
  686. // problems with reinit
  687. disposeConference();
  688. focus = new ColibriFocus(connection, config.hosts.bridge);
  689. if (nickname !== null) {
  690. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  691. nickname);
  692. }
  693. Toolbar.showSipCallButton(true);
  694. Toolbar.showRecordingButton(false);
  695. }
  696. if (connection.emuc.getPrezi(jid)) {
  697. $(document).trigger('presentationremoved.muc',
  698. [jid, connection.emuc.getPrezi(jid)]);
  699. }
  700. });
  701. $(document).bind('presence.muc', function (event, jid, info, pres) {
  702. // Remove old ssrcs coming from the jid
  703. Object.keys(ssrc2jid).forEach(function (ssrc) {
  704. if (ssrc2jid[ssrc] == jid) {
  705. delete ssrc2jid[ssrc];
  706. }
  707. if (ssrc2videoType[ssrc] == jid) {
  708. delete ssrc2videoType[ssrc];
  709. }
  710. });
  711. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  712. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  713. var ssrcV = ssrc.getAttribute('ssrc');
  714. ssrc2jid[ssrcV] = jid;
  715. var type = ssrc.getAttribute('type');
  716. ssrc2videoType[ssrcV] = type;
  717. // might need to update the direction if participant just went from sendrecv to recvonly
  718. if (type === 'video' || type === 'screen') {
  719. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  720. switch (ssrc.getAttribute('direction')) {
  721. case 'sendrecv':
  722. el.show();
  723. break;
  724. case 'recvonly':
  725. el.hide();
  726. // FIXME: Check if we have to change large video
  727. //VideoLayout.updateLargeVideo(el);
  728. break;
  729. }
  730. }
  731. });
  732. if (info.displayName && info.displayName.length > 0)
  733. $(document).trigger('displaynamechanged',
  734. [jid, info.displayName]);
  735. if (focus !== null && info.displayName !== null) {
  736. focus.setEndpointDisplayName(jid, info.displayName);
  737. }
  738. //check if the video bridge is available
  739. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  740. bridgeIsDown = true;
  741. messageHandler.showError("Error",
  742. "Jitsi Videobridge is currently unavailable. Please try again later!");
  743. }
  744. });
  745. $(document).bind('presence.status.muc', function (event, jid, info, pres) {
  746. VideoLayout.setPresenceStatus(
  747. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  748. });
  749. $(document).bind('passwordrequired.muc', function (event, jid) {
  750. console.log('on password required', jid);
  751. // password is required
  752. Toolbar.lockLockButton();
  753. messageHandler.openTwoButtonDialog(null,
  754. '<h2>Password required</h2>' +
  755. '<input id="lockKey" type="text" placeholder="password" autofocus>',
  756. true,
  757. "Ok",
  758. function (e, v, m, f) {},
  759. function (event) {
  760. document.getElementById('lockKey').focus();
  761. },
  762. function (e, v, m, f) {
  763. if (v) {
  764. var lockKey = document.getElementById('lockKey');
  765. if (lockKey.value !== null) {
  766. setSharedKey(lockKey.value);
  767. connection.emuc.doJoin(jid, lockKey.value);
  768. }
  769. }
  770. }
  771. );
  772. });
  773. $(document).bind('passwordrequired.main', function (event) {
  774. console.log('password is required');
  775. messageHandler.openTwoButtonDialog(null,
  776. '<h2>Password required</h2>' +
  777. '<input id="passwordrequired.username" type="text" placeholder="user@domain.net" autofocus>' +
  778. '<input id="passwordrequired.password" type="password" placeholder="user password">',
  779. true,
  780. "Ok",
  781. function (e, v, m, f) {
  782. if (v) {
  783. var username = document.getElementById('passwordrequired.username');
  784. var password = document.getElementById('passwordrequired.password');
  785. if (username.value !== null && password.value != null) {
  786. connect(username.value, password.value);
  787. }
  788. }
  789. },
  790. function (event) {
  791. document.getElementById('passwordrequired.username').focus();
  792. }
  793. );
  794. });
  795. /**
  796. * Checks if video identified by given src is desktop stream.
  797. * @param videoSrc eg.
  798. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  799. * @returns {boolean}
  800. */
  801. function isVideoSrcDesktop(videoSrc) {
  802. // FIXME: fix this mapping mess...
  803. // figure out if large video is desktop stream or just a camera
  804. var isDesktop = false;
  805. if (localVideoSrc === videoSrc) {
  806. // local video
  807. isDesktop = isUsingScreenStream;
  808. } else {
  809. // Do we have associations...
  810. var videoSsrc = videoSrcToSsrc[videoSrc];
  811. if (videoSsrc) {
  812. var videoType = ssrc2videoType[videoSsrc];
  813. if (videoType) {
  814. // Finally there...
  815. isDesktop = videoType === 'screen';
  816. } else {
  817. console.error("No video type for ssrc: " + videoSsrc);
  818. }
  819. } else {
  820. console.error("No ssrc for src: " + videoSrc);
  821. }
  822. }
  823. return isDesktop;
  824. }
  825. function getConferenceHandler() {
  826. return focus ? focus : activecall;
  827. }
  828. function toggleVideo() {
  829. buttonClick("#video", "icon-camera icon-camera-disabled");
  830. if (!(connection && connection.jingle.localVideo))
  831. return;
  832. var sess = getConferenceHandler();
  833. if (sess) {
  834. sess.toggleVideoMute(
  835. function (isMuted) {
  836. if (isMuted) {
  837. $('#video').removeClass("icon-camera");
  838. $('#video').addClass("icon-camera icon-camera-disabled");
  839. } else {
  840. $('#video').removeClass("icon-camera icon-camera-disabled");
  841. $('#video').addClass("icon-camera");
  842. }
  843. connection.emuc.addVideoInfoToPresence(isMuted);
  844. connection.emuc.sendPresence();
  845. }
  846. );
  847. }
  848. }
  849. /**
  850. * Mutes / unmutes audio for the local participant.
  851. */
  852. function toggleAudio() {
  853. if (!(connection && connection.jingle.localAudio)) {
  854. // We still click the button.
  855. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  856. return;
  857. }
  858. // It is not clear what is the right way to handle multiple tracks.
  859. // So at least make sure that they are all muted or all unmuted and
  860. // that we send presence just once.
  861. var localAudioTracks = connection.jingle.localAudio.getAudioTracks();
  862. if (localAudioTracks.length > 0) {
  863. var audioEnabled = localAudioTracks[0].enabled;
  864. for (var idx = 0; idx < localAudioTracks.length; idx++) {
  865. localAudioTracks[idx].enabled = !audioEnabled;
  866. }
  867. // isMuted is the opposite of audioEnabled
  868. connection.emuc.addAudioInfoToPresence(audioEnabled);
  869. connection.emuc.sendPresence();
  870. VideoLayout.showLocalAudioIndicator(audioEnabled);
  871. }
  872. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  873. }
  874. /**
  875. * Checks whether the audio is muted or not.
  876. * @returns {boolean} true if audio is muted and false if not.
  877. */
  878. function isAudioMuted()
  879. {
  880. var localAudio = connection.jingle.localAudio;
  881. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  882. if(localAudio.getAudioTracks()[idx].enabled === true)
  883. return false;
  884. }
  885. return true;
  886. }
  887. // Starts or stops the recording for the conference.
  888. function toggleRecording() {
  889. if (focus === null || focus.confid === null) {
  890. console.log('non-focus, or conference not yet organized: not enabling recording');
  891. return;
  892. }
  893. if (!recordingToken)
  894. {
  895. messageHandler.openTwoButtonDialog(null,
  896. '<h2>Enter recording token</h2>' +
  897. '<input id="recordingToken" type="text" placeholder="token" autofocus>',
  898. false,
  899. "Save",
  900. function (e, v, m, f) {
  901. if (v) {
  902. var token = document.getElementById('recordingToken');
  903. if (token.value) {
  904. setRecordingToken(Util.escapeHtml(token.value));
  905. toggleRecording();
  906. }
  907. }
  908. },
  909. function (event) {
  910. document.getElementById('recordingToken').focus();
  911. }
  912. );
  913. return;
  914. }
  915. var oldState = focus.recordingEnabled;
  916. Toolbar.toggleRecordingButtonState();
  917. focus.setRecording(!oldState,
  918. recordingToken,
  919. function (state) {
  920. console.log("New recording state: ", state);
  921. if (state == oldState) //failed to change, reset the token because it might have been wrong
  922. {
  923. Toolbar.toggleRecordingButtonState();
  924. setRecordingToken(null);
  925. }
  926. }
  927. );
  928. }
  929. /**
  930. * Returns an array of the video horizontal and vertical indents,
  931. * so that if fits its parent.
  932. *
  933. * @return an array with 2 elements, the horizontal indent and the vertical
  934. * indent
  935. */
  936. function getCameraVideoPosition(videoWidth,
  937. videoHeight,
  938. videoSpaceWidth,
  939. videoSpaceHeight) {
  940. // Parent height isn't completely calculated when we position the video in
  941. // full screen mode and this is why we use the screen height in this case.
  942. // Need to think it further at some point and implement it properly.
  943. var isFullScreen = document.fullScreen ||
  944. document.mozFullScreen ||
  945. document.webkitIsFullScreen;
  946. if (isFullScreen)
  947. videoSpaceHeight = window.innerHeight;
  948. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  949. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  950. return [horizontalIndent, verticalIndent];
  951. }
  952. /**
  953. * Returns an array of the video horizontal and vertical indents.
  954. * Centers horizontally and top aligns vertically.
  955. *
  956. * @return an array with 2 elements, the horizontal indent and the vertical
  957. * indent
  958. */
  959. function getDesktopVideoPosition(videoWidth,
  960. videoHeight,
  961. videoSpaceWidth,
  962. videoSpaceHeight) {
  963. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  964. var verticalIndent = 0;// Top aligned
  965. return [horizontalIndent, verticalIndent];
  966. }
  967. /**
  968. * Returns an array of the video dimensions, so that it covers the screen.
  969. * It leaves no empty areas, but some parts of the video might not be visible.
  970. *
  971. * @return an array with 2 elements, the video width and the video height
  972. */
  973. function getCameraVideoSize(videoWidth,
  974. videoHeight,
  975. videoSpaceWidth,
  976. videoSpaceHeight) {
  977. if (!videoWidth)
  978. videoWidth = currentVideoWidth;
  979. if (!videoHeight)
  980. videoHeight = currentVideoHeight;
  981. var aspectRatio = videoWidth / videoHeight;
  982. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  983. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  984. if (availableWidth / aspectRatio < videoSpaceHeight) {
  985. availableHeight = videoSpaceHeight;
  986. availableWidth = availableHeight * aspectRatio;
  987. }
  988. if (availableHeight * aspectRatio < videoSpaceWidth) {
  989. availableWidth = videoSpaceWidth;
  990. availableHeight = availableWidth / aspectRatio;
  991. }
  992. return [availableWidth, availableHeight];
  993. }
  994. $(document).ready(function () {
  995. document.title = brand.appName;
  996. if(APIConnector.isEnabled())
  997. APIConnector.init();
  998. if(config.enableWelcomePage && window.location.pathname == "/" &&
  999. (!window.localStorage.welcomePageDisabled
  1000. || window.localStorage.welcomePageDisabled == "false"))
  1001. {
  1002. $("#videoconference_page").hide();
  1003. $("#domain_name").text(
  1004. window.location.protocol + "//" + window.location.host + "/");
  1005. $("span[name='appName']").text(brand.appName);
  1006. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1007. var leftWatermarkDiv
  1008. = $("#welcome_page_header div[class='watermark leftwatermark']");
  1009. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  1010. {
  1011. leftWatermarkDiv.css({display: 'block'});
  1012. leftWatermarkDiv.parent().get(0).href
  1013. = interfaceConfig.JITSI_WATERMARK_LINK;
  1014. }
  1015. }
  1016. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1017. var rightWatermarkDiv
  1018. = $("#welcome_page_header div[class='watermark rightwatermark']");
  1019. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  1020. rightWatermarkDiv.css({display: 'block'});
  1021. rightWatermarkDiv.parent().get(0).href
  1022. = interfaceConfig.BRAND_WATERMARK_LINK;
  1023. rightWatermarkDiv.get(0).style.backgroundImage
  1024. = "url(images/rightwatermark.png)";
  1025. }
  1026. }
  1027. if (interfaceConfig.SHOW_POWERED_BY) {
  1028. $("#welcome_page_header>a[class='poweredby']")
  1029. .css({display: 'block'});
  1030. }
  1031. function enter_room()
  1032. {
  1033. var val = $("#enter_room_field").val();
  1034. if(!val) {
  1035. val = $("#enter_room_field").attr("room_name");
  1036. }
  1037. if (val) {
  1038. window.location.pathname = "/" + val;
  1039. }
  1040. }
  1041. $("#enter_room_button").click(function()
  1042. {
  1043. enter_room();
  1044. });
  1045. $("#enter_room_field").keydown(function (event) {
  1046. if (event.keyCode === 13 /* enter */) {
  1047. enter_room();
  1048. }
  1049. });
  1050. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  1051. var updateTimeout;
  1052. var animateTimeout;
  1053. $("#reload_roomname").click(function () {
  1054. clearTimeout(updateTimeout);
  1055. clearTimeout(animateTimeout);
  1056. update_roomname();
  1057. });
  1058. $("#reload_roomname").show();
  1059. function animate(word) {
  1060. var currentVal = $("#enter_room_field").attr("placeholder");
  1061. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  1062. animateTimeout = setTimeout(function() {
  1063. animate(word.substring(1, word.length))
  1064. }, 70);
  1065. }
  1066. function update_roomname()
  1067. {
  1068. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1069. $("#enter_room_field").attr("room_name", word);
  1070. $("#enter_room_field").attr("placeholder", "");
  1071. clearTimeout(animateTimeout);
  1072. animate(word);
  1073. updateTimeout = setTimeout(update_roomname, 10000);
  1074. }
  1075. update_roomname();
  1076. }
  1077. $("#disable_welcome").click(function () {
  1078. window.localStorage.welcomePageDisabled
  1079. = $("#disable_welcome").is(":checked");
  1080. });
  1081. return;
  1082. }
  1083. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1084. var leftWatermarkDiv
  1085. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1086. leftWatermarkDiv.css({display: 'block'});
  1087. leftWatermarkDiv.parent().get(0).href
  1088. = interfaceConfig.JITSI_WATERMARK_LINK;
  1089. }
  1090. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1091. var rightWatermarkDiv
  1092. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1093. rightWatermarkDiv.css({display: 'block'});
  1094. rightWatermarkDiv.parent().get(0).href
  1095. = interfaceConfig.BRAND_WATERMARK_LINK;
  1096. rightWatermarkDiv.get(0).style.backgroundImage
  1097. = "url(images/rightwatermark.png)";
  1098. }
  1099. if (interfaceConfig.SHOW_POWERED_BY) {
  1100. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1101. }
  1102. $("#welcome_page").hide();
  1103. Chat.init();
  1104. $('body').popover({ selector: '[data-toggle=popover]',
  1105. trigger: 'click hover',
  1106. content: function() {
  1107. return this.getAttribute("content") +
  1108. KeyboardShortcut.getShortcut(this.getAttribute("shortcut"));
  1109. }
  1110. });
  1111. // Set the defaults for prompt dialogs.
  1112. jQuery.prompt.setDefaults({persistent: false});
  1113. // Set default desktop sharing method
  1114. setDesktopSharing(config.desktopSharing);
  1115. // Initialize Chrome extension inline installs
  1116. if (config.chromeExtensionId) {
  1117. initInlineInstalls();
  1118. }
  1119. // By default we use camera
  1120. getVideoSize = getCameraVideoSize;
  1121. getVideoPosition = getCameraVideoPosition;
  1122. VideoLayout.resizeLargeVideoContainer();
  1123. $(window).resize(function () {
  1124. VideoLayout.resizeLargeVideoContainer();
  1125. VideoLayout.positionLarge();
  1126. });
  1127. // Listen for large video size updates
  1128. document.getElementById('largeVideo')
  1129. .addEventListener('loadedmetadata', function (e) {
  1130. currentVideoWidth = this.videoWidth;
  1131. currentVideoHeight = this.videoHeight;
  1132. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  1133. });
  1134. if (!$('#settings').is(':visible')) {
  1135. console.log('init');
  1136. init();
  1137. } else {
  1138. loginInfo.onsubmit = function (e) {
  1139. if (e.preventDefault) e.preventDefault();
  1140. $('#settings').hide();
  1141. init();
  1142. };
  1143. }
  1144. });
  1145. $(window).bind('beforeunload', function () {
  1146. if (connection && connection.connected) {
  1147. // ensure signout
  1148. $.ajax({
  1149. type: 'POST',
  1150. url: config.bosh,
  1151. async: false,
  1152. cache: false,
  1153. contentType: 'application/xml',
  1154. data: "<body rid='" + (connection.rid || connection._proto.rid)
  1155. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  1156. + (connection.sid || connection._proto.sid)
  1157. + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  1158. success: function (data) {
  1159. console.log('signed out');
  1160. console.log(data);
  1161. },
  1162. error: function (XMLHttpRequest, textStatus, errorThrown) {
  1163. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  1164. }
  1165. });
  1166. }
  1167. disposeConference(true);
  1168. if(APIConnector.isEnabled())
  1169. APIConnector.dispose();
  1170. });
  1171. function disposeConference(onUnload) {
  1172. var handler = getConferenceHandler();
  1173. if (handler && handler.peerconnection) {
  1174. // FIXME: probably removing streams is not required and close() should
  1175. // be enough
  1176. if (connection.jingle.localAudio) {
  1177. handler.peerconnection.removeStream(connection.jingle.localAudio);
  1178. }
  1179. if (connection.jingle.localVideo) {
  1180. handler.peerconnection.removeStream(connection.jingle.localVideo);
  1181. }
  1182. handler.peerconnection.close();
  1183. }
  1184. stopRTPStatsCollector();
  1185. if(onUnload) {
  1186. stopLocalRtpStatsCollector();
  1187. }
  1188. focus = null;
  1189. activecall = null;
  1190. }
  1191. function dump(elem, filename) {
  1192. elem = elem.parentNode;
  1193. elem.download = filename || 'meetlog.json';
  1194. elem.href = 'data:application/json;charset=utf-8,\n';
  1195. var data = populateData();
  1196. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1197. return false;
  1198. }
  1199. /**
  1200. * Populates the log data
  1201. */
  1202. function populateData() {
  1203. var data = {};
  1204. if (connection.jingle) {
  1205. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  1206. var session = connection.jingle.sessions[sid];
  1207. if (session.peerconnection && session.peerconnection.updateLog) {
  1208. // FIXME: should probably be a .dump call
  1209. data["jingle_" + session.sid] = {
  1210. updateLog: session.peerconnection.updateLog,
  1211. stats: session.peerconnection.stats,
  1212. url: window.location.href
  1213. };
  1214. }
  1215. });
  1216. }
  1217. var metadata = {};
  1218. metadata.time = new Date();
  1219. metadata.url = window.location.href;
  1220. metadata.ua = navigator.userAgent;
  1221. if (connection.logger) {
  1222. metadata.xmpp = connection.logger.log;
  1223. }
  1224. data.metadata = metadata;
  1225. return data;
  1226. }
  1227. /**
  1228. * Changes the style class of the element given by id.
  1229. */
  1230. function buttonClick(id, classname) {
  1231. $(id).toggleClass(classname); // add the class to the clicked element
  1232. }
  1233. /**
  1234. * Locks / unlocks the room.
  1235. */
  1236. function lockRoom(lock) {
  1237. if (lock)
  1238. connection.emuc.lockRoom(sharedKey);
  1239. else
  1240. connection.emuc.lockRoom('');
  1241. Toolbar.updateLockButton();
  1242. }
  1243. /**
  1244. * Sets the shared key.
  1245. */
  1246. function setSharedKey(sKey) {
  1247. sharedKey = sKey;
  1248. }
  1249. function setRecordingToken(token) {
  1250. recordingToken = token;
  1251. }
  1252. /**
  1253. * Updates the room invite url.
  1254. */
  1255. function updateRoomUrl(newRoomUrl) {
  1256. roomUrl = newRoomUrl;
  1257. // If the invite dialog has been already opened we update the information.
  1258. var inviteLink = document.getElementById('inviteLinkRef');
  1259. if (inviteLink) {
  1260. inviteLink.value = roomUrl;
  1261. inviteLink.select();
  1262. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  1263. }
  1264. }
  1265. /**
  1266. * Warning to the user that the conference window is about to be closed.
  1267. */
  1268. function closePageWarning() {
  1269. if (focus !== null)
  1270. return "You are the owner of this conference call and"
  1271. + " you are about to end it.";
  1272. else
  1273. return "You are about to leave this conversation.";
  1274. }
  1275. /**
  1276. * Resizes and repositions videos in full screen mode.
  1277. */
  1278. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1279. function () {
  1280. VideoLayout.resizeLargeVideoContainer();
  1281. VideoLayout.positionLarge();
  1282. isFullScreen = document.fullScreen ||
  1283. document.mozFullScreen ||
  1284. document.webkitIsFullScreen;
  1285. if (isFullScreen) {
  1286. setView("fullscreen");
  1287. }
  1288. else {
  1289. setView("default");
  1290. }
  1291. }
  1292. );
  1293. /**
  1294. * Sets the current view.
  1295. */
  1296. function setView(viewName) {
  1297. // if (viewName == "fullscreen") {
  1298. // document.getElementById('videolayout_fullscreen').disabled = false;
  1299. // document.getElementById('videolayout_default').disabled = true;
  1300. // }
  1301. // else {
  1302. // document.getElementById('videolayout_default').disabled = false;
  1303. // document.getElementById('videolayout_fullscreen').disabled = true;
  1304. // }
  1305. }
  1306. $(document).bind('fatalError.jingle',
  1307. function (event, session, error)
  1308. {
  1309. sessionTerminated = true;
  1310. connection.emuc.doLeave();
  1311. messageHandler.showError( "Sorry",
  1312. "Your browser version is too old. Please update and try again...");
  1313. }
  1314. );
  1315. function onSelectedEndpointChanged(userJid)
  1316. {
  1317. console.log('selected endpoint changed: ', userJid);
  1318. if (_dataChannels && _dataChannels.length != 0)
  1319. {
  1320. _dataChannels.some(function (dataChannel) {
  1321. if (dataChannel.readyState == 'open')
  1322. {
  1323. dataChannel.send(JSON.stringify({
  1324. 'colibriClass': 'SelectedEndpointChangedEvent',
  1325. 'selectedEndpoint': (!userJid || userJid == null)
  1326. ? null : Strophe.getResourceFromJid(userJid)
  1327. }));
  1328. return true;
  1329. }
  1330. });
  1331. }
  1332. }
  1333. $(document).bind("selectedendpointchanged", function(event, userJid) {
  1334. onSelectedEndpointChanged(userJid);
  1335. });
  1336. function callSipButtonClicked()
  1337. {
  1338. var defaultNumber
  1339. = config.defaultSipNumber ? config.defaultSipNumber : '';
  1340. messageHandler.openTwoButtonDialog(null,
  1341. '<h2>Enter SIP number</h2>' +
  1342. '<input id="sipNumber" type="text"' +
  1343. ' value="' + defaultNumber + '" autofocus>',
  1344. false,
  1345. "Dial",
  1346. function (e, v, m, f) {
  1347. if (v) {
  1348. var numberInput = document.getElementById('sipNumber');
  1349. if (numberInput.value) {
  1350. connection.rayo.dial(
  1351. numberInput.value, 'fromnumber', roomName);
  1352. }
  1353. }
  1354. },
  1355. function (event) {
  1356. document.getElementById('sipNumber').focus();
  1357. }
  1358. );
  1359. }
  1360. function hangup() {
  1361. disposeConference();
  1362. sessionTerminated = true;
  1363. connection.emuc.doLeave();
  1364. if(config.enableWelcomePage)
  1365. {
  1366. setTimeout(function()
  1367. {
  1368. window.localStorage.welcomePageDisabled = false;
  1369. window.location.pathname = "/";
  1370. }, 10000);
  1371. }
  1372. $.prompt("Session Terminated",
  1373. {
  1374. title: "You hung up the call",
  1375. persistent: true,
  1376. buttons: {
  1377. "Join again": true
  1378. },
  1379. closeText: '',
  1380. submit: function(event, value, message, formVals)
  1381. {
  1382. window.location.reload();
  1383. return false;
  1384. }
  1385. }
  1386. );
  1387. }