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 40KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  1. /* jshint -W117 */
  2. /* application specific logic */
  3. var connection = null;
  4. var focus = null;
  5. var activecall = null;
  6. var RTC = null;
  7. var nickname = null;
  8. var sharedKey = '';
  9. var recordingToken ='';
  10. var roomUrl = null;
  11. var ssrc2jid = {};
  12. /**
  13. * The stats collector that process stats data and triggers updates to app.js.
  14. * @type {StatsCollector}
  15. */
  16. var statsCollector = null;
  17. /**
  18. * The stats collector for the local stream.
  19. * @type {LocalStatsCollector}
  20. */
  21. var localStatsCollector = null;
  22. /**
  23. * Indicates whether ssrc is camera video or desktop stream.
  24. * FIXME: remove those maps
  25. */
  26. var ssrc2videoType = {};
  27. var videoSrcToSsrc = {};
  28. /**
  29. * Currently focused video "src"(displayed in large video).
  30. * @type {String}
  31. */
  32. var focusedVideoSrc = null;
  33. var mutedAudios = {};
  34. var localVideoSrc = null;
  35. var flipXLocalVideo = true;
  36. var isFullScreen = false;
  37. var toolbarTimeout = null;
  38. var currentVideoWidth = null;
  39. var currentVideoHeight = null;
  40. /**
  41. * Method used to calculate large video size.
  42. * @type {function ()}
  43. */
  44. var getVideoSize;
  45. /**
  46. * Method used to get large video position.
  47. * @type {function ()}
  48. */
  49. var getVideoPosition;
  50. /* window.onbeforeunload = closePageWarning; */
  51. var sessionTerminated = false;
  52. function init() {
  53. RTC = setupRTC();
  54. if (RTC === null) {
  55. window.location.href = 'webrtcrequired.html';
  56. return;
  57. } else if (RTC.browser !== 'chrome') {
  58. window.location.href = 'chromeonly.html';
  59. return;
  60. }
  61. connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
  62. if (nickname) {
  63. connection.emuc.addDisplayNameToPresence(nickname);
  64. }
  65. if (connection.disco) {
  66. // for chrome, add multistream cap
  67. }
  68. connection.jingle.pc_constraints = RTC.pc_constraints;
  69. if (config.useIPv6) {
  70. // https://code.google.com/p/webrtc/issues/detail?id=2828
  71. if (!connection.jingle.pc_constraints.optional) connection.jingle.pc_constraints.optional = [];
  72. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  73. }
  74. var jid = document.getElementById('jid').value || config.hosts.domain || window.location.hostname;
  75. connection.connect(jid, document.getElementById('password').value, function (status) {
  76. if (status === Strophe.Status.CONNECTED) {
  77. console.log('connected');
  78. if (config.useStunTurn) {
  79. connection.jingle.getStunAndTurnCredentials();
  80. }
  81. obtainAudioAndVideoPermissions(function () {
  82. getUserMediaWithConstraints(['audio'], audioStreamReady,
  83. function (error) {
  84. console.error('failed to obtain audio stream - stop', error);
  85. });
  86. });
  87. document.getElementById('connect').disabled = true;
  88. } else {
  89. console.log('status', status);
  90. }
  91. });
  92. }
  93. /**
  94. * HTTPS only:
  95. * We first ask for audio and video combined stream in order to get permissions and not to ask twice.
  96. * Then we dispose the stream and continue with separate audio, video streams(required for desktop sharing).
  97. */
  98. function obtainAudioAndVideoPermissions(callback) {
  99. // This makes sense only on https sites otherwise we'll be asked for permissions every time
  100. if (location.protocol !== 'https:') {
  101. callback();
  102. return;
  103. }
  104. // Get AV
  105. getUserMediaWithConstraints(
  106. ['audio', 'video'],
  107. function (avStream) {
  108. avStream.stop();
  109. callback();
  110. },
  111. function (error) {
  112. console.error('failed to obtain audio/video stream - stop', error);
  113. });
  114. }
  115. function audioStreamReady(stream) {
  116. VideoLayout.changeLocalAudio(stream);
  117. startLocalRtpStatsCollector(stream);
  118. if (RTC.browser !== 'firefox') {
  119. getUserMediaWithConstraints(['video'],
  120. videoStreamReady,
  121. videoStreamFailed,
  122. config.resolution || '360');
  123. } else {
  124. doJoin();
  125. }
  126. }
  127. function videoStreamReady(stream) {
  128. VideoLayout.changeLocalVideo(stream, true);
  129. doJoin();
  130. }
  131. function videoStreamFailed(error) {
  132. console.warn("Failed to obtain video stream - continue anyway", error);
  133. doJoin();
  134. }
  135. function doJoin() {
  136. var roomnode = null;
  137. var path = window.location.pathname;
  138. var roomjid;
  139. // determinde the room node from the url
  140. // TODO: just the roomnode or the whole bare jid?
  141. if (config.getroomnode && typeof config.getroomnode === 'function') {
  142. // custom function might be responsible for doing the pushstate
  143. roomnode = config.getroomnode(path);
  144. } else {
  145. /* fall back to default strategy
  146. * this is making assumptions about how the URL->room mapping happens.
  147. * It currently assumes deployment at root, with a rewrite like the
  148. * following one (for nginx):
  149. location ~ ^/([a-zA-Z0-9]+)$ {
  150. rewrite ^/(.*)$ / break;
  151. }
  152. */
  153. if (path.length > 1) {
  154. roomnode = path.substr(1).toLowerCase();
  155. } else {
  156. roomnode = Math.random().toString(36).substr(2, 20);
  157. window.history.pushState('VideoChat',
  158. 'Room: ' + roomnode, window.location.pathname + roomnode);
  159. }
  160. }
  161. roomjid = roomnode + '@' + config.hosts.muc;
  162. if (config.useNicks) {
  163. var nick = window.prompt('Your nickname (optional)');
  164. if (nick) {
  165. roomjid += '/' + nick;
  166. } else {
  167. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  168. }
  169. } else {
  170. roomjid += '/' + Strophe.getNodeFromJid(connection.jid).substr(0, 8);
  171. }
  172. connection.emuc.doJoin(roomjid);
  173. }
  174. $(document).bind('remotestreamadded.jingle', function (event, data, sid) {
  175. function waitForRemoteVideo(selector, sid, ssrc) {
  176. if (selector.removed) {
  177. console.warn("media removed before had started", selector);
  178. return;
  179. }
  180. var sess = connection.jingle.sessions[sid];
  181. if (data.stream.id === 'mixedmslabel') return;
  182. var videoTracks = data.stream.getVideoTracks();
  183. // console.log("waiting..", videoTracks, selector[0]);
  184. if (videoTracks.length === 0 || selector[0].currentTime > 0) {
  185. RTC.attachMediaStream(selector, data.stream); // FIXME: why do i have to do this for FF?
  186. // FIXME: add a class that will associate peer Jid, video.src, it's ssrc and video type
  187. // in order to get rid of too many maps
  188. if (ssrc) {
  189. videoSrcToSsrc[sel.attr('src')] = ssrc;
  190. } else {
  191. console.warn("No ssrc given for video", sel);
  192. }
  193. $(document).trigger('callactive.jingle', [selector, sid]);
  194. console.log('waitForremotevideo', sess.peerconnection.iceConnectionState, sess.peerconnection.signalingState);
  195. } else {
  196. setTimeout(function () { waitForRemoteVideo(selector, sid, ssrc); }, 250);
  197. }
  198. }
  199. var sess = connection.jingle.sessions[sid];
  200. var thessrc;
  201. // look up an associated JID for a stream id
  202. if (data.stream.id.indexOf('mixedmslabel') === -1) {
  203. var ssrclines = SDPUtil.find_lines(sess.peerconnection.remoteDescription.sdp, 'a=ssrc');
  204. ssrclines = ssrclines.filter(function (line) {
  205. return line.indexOf('mslabel:' + data.stream.label) !== -1;
  206. });
  207. if (ssrclines.length) {
  208. thessrc = ssrclines[0].substring(7).split(' ')[0];
  209. // ok to overwrite the one from focus? might save work in colibri.js
  210. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  211. if (ssrc2jid[thessrc]) {
  212. data.peerjid = ssrc2jid[thessrc];
  213. }
  214. }
  215. }
  216. var container;
  217. var remotes = document.getElementById('remoteVideos');
  218. if (data.peerjid) {
  219. VideoLayout.ensurePeerContainerExists(data.peerjid);
  220. container = document.getElementById(
  221. 'participant_' + Strophe.getResourceFromJid(data.peerjid));
  222. } else {
  223. if (data.stream.id !== 'mixedmslabel') {
  224. console.error( 'can not associate stream',
  225. data.stream.id,
  226. 'with a participant');
  227. // We don't want to add it here since it will cause troubles
  228. return;
  229. }
  230. // FIXME: for the mixed ms we dont need a video -- currently
  231. container = document.createElement('span');
  232. container.className = 'videocontainer';
  233. remotes.appendChild(container);
  234. Util.playSoundNotification('userJoined');
  235. }
  236. var isVideo = data.stream.getVideoTracks().length > 0;
  237. var vid = isVideo ? document.createElement('video') : document.createElement('audio');
  238. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_') + sid + '_' + data.stream.id;
  239. vid.id = id;
  240. vid.autoplay = true;
  241. vid.oncontextmenu = function () { return false; };
  242. container.appendChild(vid);
  243. // TODO: make mixedstream display:none via css?
  244. if (id.indexOf('mixedmslabel') !== -1) {
  245. container.id = 'mixedstream';
  246. $(container).hide();
  247. }
  248. var sel = $('#' + id);
  249. sel.hide();
  250. RTC.attachMediaStream(sel, data.stream);
  251. if (isVideo) {
  252. waitForRemoteVideo(sel, sid, thessrc);
  253. }
  254. data.stream.onended = function () {
  255. console.log('stream ended', this.id);
  256. // Mark video as removed to cancel waiting loop(if video is removed
  257. // before has started)
  258. sel.removed = true;
  259. sel.remove();
  260. var audioCount = $('#' + container.id + '>audio').length;
  261. var videoCount = $('#' + container.id + '>video').length;
  262. if (!audioCount && !videoCount) {
  263. console.log("Remove whole user", container.id);
  264. // Remove whole container
  265. container.remove();
  266. Util.playSoundNotification('userLeft');
  267. VideoLayout.resizeThumbnails();
  268. }
  269. VideoLayout.checkChangeLargeVideo(vid.src);
  270. };
  271. // Add click handler.
  272. container.onclick = function (event) {
  273. /*
  274. * FIXME It turns out that videoThumb may not exist (if there is no
  275. * actual video).
  276. */
  277. var videoThumb = $('#' + container.id + '>video').get(0);
  278. if (videoThumb)
  279. VideoLayout.handleVideoThumbClicked(videoThumb.src);
  280. event.preventDefault();
  281. return false;
  282. };
  283. // Add hover handler
  284. $(container).hover(
  285. function() {
  286. VideoLayout.showDisplayName(container.id, true);
  287. },
  288. function() {
  289. var videoSrc = null;
  290. if ($('#' + container.id + '>video')
  291. && $('#' + container.id + '>video').length > 0) {
  292. videoSrc = $('#' + container.id + '>video').get(0).src;
  293. }
  294. // If the video has been "pinned" by the user we want to keep the
  295. // display name on place.
  296. if (!VideoLayout.isLargeVideoVisible()
  297. || videoSrc !== $('#largeVideo').attr('src'))
  298. VideoLayout.showDisplayName(container.id, false);
  299. }
  300. );
  301. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  302. if (isVideo &&
  303. data.peerjid && sess.peerjid === data.peerjid &&
  304. data.stream.getVideoTracks().length === 0 &&
  305. connection.jingle.localVideo.getVideoTracks().length > 0) {
  306. //
  307. window.setTimeout(function () {
  308. sendKeyframe(sess.peerconnection);
  309. }, 3000);
  310. }
  311. });
  312. /**
  313. * Returns the JID of the user to whom given <tt>videoSrc</tt> belongs.
  314. * @param videoSrc the video "src" identifier.
  315. * @returns {null | String} the JID of the user to whom given <tt>videoSrc</tt>
  316. * belongs.
  317. */
  318. function getJidFromVideoSrc(videoSrc)
  319. {
  320. if (videoSrc === localVideoSrc)
  321. return connection.emuc.myroomjid;
  322. var ssrc = videoSrcToSsrc[videoSrc];
  323. if (!ssrc)
  324. {
  325. return null;
  326. }
  327. return ssrc2jid[ssrc];
  328. }
  329. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  330. function sendKeyframe(pc) {
  331. console.log('sendkeyframe', pc.iceConnectionState);
  332. if (pc.iceConnectionState !== 'connected') return; // safe...
  333. pc.setRemoteDescription(
  334. pc.remoteDescription,
  335. function () {
  336. pc.createAnswer(
  337. function (modifiedAnswer) {
  338. pc.setLocalDescription(
  339. modifiedAnswer,
  340. function () {
  341. // noop
  342. },
  343. function (error) {
  344. console.log('triggerKeyframe setLocalDescription failed', error);
  345. }
  346. );
  347. },
  348. function (error) {
  349. console.log('triggerKeyframe createAnswer failed', error);
  350. }
  351. );
  352. },
  353. function (error) {
  354. console.log('triggerKeyframe setRemoteDescription failed', error);
  355. }
  356. );
  357. }
  358. // Really mute video, i.e. dont even send black frames
  359. function muteVideo(pc, unmute) {
  360. // FIXME: this probably needs another of those lovely state safeguards...
  361. // which checks for iceconn == connected and sigstate == stable
  362. pc.setRemoteDescription(pc.remoteDescription,
  363. function () {
  364. pc.createAnswer(
  365. function (answer) {
  366. var sdp = new SDP(answer.sdp);
  367. if (sdp.media.length > 1) {
  368. if (unmute)
  369. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  370. else
  371. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  372. sdp.raw = sdp.session + sdp.media.join('');
  373. answer.sdp = sdp.raw;
  374. }
  375. pc.setLocalDescription(answer,
  376. function () {
  377. console.log('mute SLD ok');
  378. },
  379. function (error) {
  380. console.log('mute SLD error');
  381. }
  382. );
  383. },
  384. function (error) {
  385. console.log(error);
  386. }
  387. );
  388. },
  389. function (error) {
  390. console.log('muteVideo SRD error');
  391. }
  392. );
  393. }
  394. /**
  395. * Callback called by {@link StatsCollector} in intervals supplied to it's
  396. * constructor.
  397. * @param statsCollector {@link StatsCollector} source of the event.
  398. */
  399. function statsUpdated(statsCollector)
  400. {
  401. Object.keys(statsCollector.jid2stats).forEach(function (jid)
  402. {
  403. var peerStats = statsCollector.jid2stats[jid];
  404. Object.keys(peerStats.ssrc2AudioLevel).forEach(function (ssrc)
  405. {
  406. AudioLevels.updateAudioLevel( Strophe.getResourceFromJid(jid),
  407. peerStats.ssrc2AudioLevel[ssrc]);
  408. });
  409. });
  410. }
  411. /**
  412. * Callback called by {@link LocalStatsCollector} in intervals supplied to it's
  413. * constructor.
  414. * @param statsCollector {@link LocalStatsCollector} source of the event.
  415. */
  416. function localStatsUpdated(statsCollector)
  417. {
  418. AudioLevels.updateAudioLevel(
  419. AudioLevels.LOCAL_LEVEL,
  420. statsCollector.audioLevel);
  421. }
  422. /**
  423. * Starts the {@link StatsCollector} if the feature is enabled in config.js.
  424. */
  425. function startRtpStatsCollector()
  426. {
  427. stopRTPStatsCollector();
  428. if (config.enableRtpStats)
  429. {
  430. statsCollector = new StatsCollector(
  431. getConferenceHandler().peerconnection, 200, statsUpdated);
  432. stopLocalRtpStatsCollector();
  433. statsCollector.start();
  434. }
  435. }
  436. /**
  437. * Stops the {@link StatsCollector}.
  438. */
  439. function stopRTPStatsCollector()
  440. {
  441. if (statsCollector)
  442. {
  443. statsCollector.stop();
  444. statsCollector = null;
  445. }
  446. }
  447. /**
  448. * Starts the {@link LocalStatsCollector} if the feature is enabled in config.js
  449. * @param stream the stream that will be used for collecting statistics.
  450. */
  451. function startLocalRtpStatsCollector(stream)
  452. {
  453. if(config.enableRtpStats)
  454. {
  455. localStatsCollector = new LocalStatsCollector(stream, 200, localStatsUpdated);
  456. localStatsCollector.start();
  457. }
  458. }
  459. /**
  460. * Stops the {@link LocalStatsCollector}.
  461. */
  462. function stopLocalRtpStatsCollector()
  463. {
  464. if(localStatsCollector)
  465. {
  466. localStatsCollector.stop();
  467. localStatsCollector = null;
  468. }
  469. }
  470. $(document).bind('callincoming.jingle', function (event, sid) {
  471. var sess = connection.jingle.sessions[sid];
  472. // TODO: do we check activecall == null?
  473. activecall = sess;
  474. startRtpStatsCollector();
  475. // Bind data channel listener in case we're a regular participant
  476. if (config.openSctp)
  477. {
  478. bindDataChannelListener(sess.peerconnection);
  479. }
  480. // TODO: check affiliation and/or role
  481. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  482. sess.usedrip = true; // not-so-naive trickle ice
  483. sess.sendAnswer();
  484. sess.accept();
  485. });
  486. $(document).bind('conferenceCreated.jingle', function (event, focus)
  487. {
  488. startRtpStatsCollector();
  489. });
  490. $(document).bind('conferenceCreated.jingle', function (event, focus)
  491. {
  492. // Bind data channel listener in case we're the focus
  493. if (config.openSctp)
  494. {
  495. bindDataChannelListener(focus.peerconnection);
  496. }
  497. });
  498. $(document).bind('callactive.jingle', function (event, videoelem, sid) {
  499. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  500. // ignore mixedmslabela0 and v0
  501. videoelem.show();
  502. VideoLayout.resizeThumbnails();
  503. // Update the large video to the last added video only if there's no
  504. // current active or focused speaker.
  505. if (!focusedVideoSrc && !VideoLayout.getDominantSpeakerResourceJid())
  506. VideoLayout.updateLargeVideo(videoelem.attr('src'), 1);
  507. VideoLayout.showFocusIndicator();
  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. 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 directions = {};
  524. var localSDP = new SDP(sess.peerconnection.localDescription.sdp);
  525. localSDP.media.forEach(function (media) {
  526. var type = SDPUtil.parse_mid(SDPUtil.find_line(media, 'a=mid:'));
  527. if (SDPUtil.find_line(media, 'a=ssrc:')) {
  528. // assumes a single local ssrc
  529. var ssrc = SDPUtil.find_line(media, 'a=ssrc:').substring(7).split(' ')[0];
  530. newssrcs[type] = ssrc;
  531. directions[type] = (
  532. SDPUtil.find_line(media, 'a=sendrecv') ||
  533. SDPUtil.find_line(media, 'a=recvonly') ||
  534. SDPUtil.find_line(media, 'a=sendonly') ||
  535. SDPUtil.find_line(media, 'a=inactive') ||
  536. 'a=sendrecv').substr(2);
  537. }
  538. });
  539. console.log('new ssrcs', newssrcs);
  540. // Have to clear presence map to get rid of removed streams
  541. connection.emuc.clearPresenceMedia();
  542. var i = 0;
  543. Object.keys(newssrcs).forEach(function (mtype) {
  544. i++;
  545. var type = mtype;
  546. // Change video type to screen
  547. if (mtype === 'video' && isUsingScreenStream) {
  548. type = 'screen';
  549. }
  550. connection.emuc.addMediaToPresence(i, type, newssrcs[mtype], directions[mtype]);
  551. });
  552. if (i > 0) {
  553. connection.emuc.sendPresence();
  554. }
  555. });
  556. $(document).bind('joined.muc', function (event, jid, info) {
  557. updateRoomUrl(window.location.href);
  558. document.getElementById('localNick').appendChild(
  559. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  560. );
  561. if (Object.keys(connection.emuc.members).length < 1) {
  562. focus = new ColibriFocus(connection, config.hosts.bridge);
  563. if (nickname !== null) {
  564. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  565. nickname);
  566. }
  567. Toolbar.showRecordingButton(false);
  568. }
  569. if (focus && config.etherpad_base) {
  570. Etherpad.init();
  571. }
  572. VideoLayout.showFocusIndicator();
  573. // Once we've joined the muc show the toolbar
  574. Toolbar.showToolbar();
  575. var displayName = '';
  576. if (info.displayName)
  577. displayName = info.displayName + ' (me)';
  578. VideoLayout.setDisplayName('localVideoContainer', displayName);
  579. });
  580. $(document).bind('entered.muc', function (event, jid, info, pres) {
  581. console.log('entered', jid, info);
  582. console.log('is focus?' + focus ? 'true' : 'false');
  583. // Add Peer's container
  584. VideoLayout.ensurePeerContainerExists(jid);
  585. if (focus !== null) {
  586. // FIXME: this should prepare the video
  587. if (focus.confid === null) {
  588. console.log('make new conference with', jid);
  589. focus.makeConference(Object.keys(connection.emuc.members));
  590. Toolbar.showRecordingButton(true);
  591. } else {
  592. console.log('invite', jid, 'into conference');
  593. focus.addNewParticipant(jid);
  594. }
  595. }
  596. else if (sharedKey) {
  597. Toolbar.updateLockButton();
  598. }
  599. });
  600. $(document).bind('left.muc', function (event, jid) {
  601. console.log('left.muc', jid);
  602. // Need to call this with a slight delay, otherwise the element couldn't be
  603. // found for some reason.
  604. window.setTimeout(function () {
  605. var container = document.getElementById(
  606. 'participant_' + Strophe.getResourceFromJid(jid));
  607. if (container) {
  608. // hide here, wait for video to close before removing
  609. $(container).hide();
  610. VideoLayout.resizeThumbnails();
  611. }
  612. }, 10);
  613. // Unlock large video
  614. if (focusedVideoSrc)
  615. {
  616. if (getJidFromVideoSrc(focusedVideoSrc) === jid)
  617. {
  618. console.info("Focused video owner has left the conference");
  619. focusedVideoSrc = null;
  620. }
  621. }
  622. connection.jingle.terminateByJid(jid);
  623. if (focus == null
  624. // I shouldn't be the one that left to enter here.
  625. && jid !== connection.emuc.myroomjid
  626. && connection.emuc.myroomjid === connection.emuc.list_members[0]
  627. // If our session has been terminated for some reason
  628. // (kicked, hangup), don't try to become the focus
  629. && !sessionTerminated) {
  630. console.log('welcome to our new focus... myself');
  631. focus = new ColibriFocus(connection, config.hosts.bridge);
  632. if (nickname !== null) {
  633. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  634. nickname);
  635. }
  636. if (Object.keys(connection.emuc.members).length > 0) {
  637. focus.makeConference(Object.keys(connection.emuc.members));
  638. Toolbar.showRecordingButton(true);
  639. }
  640. $(document).trigger('focusechanged.muc', [focus]);
  641. }
  642. else if (focus && Object.keys(connection.emuc.members).length === 0) {
  643. console.log('everyone left');
  644. // FIXME: closing the connection is a hack to avoid some
  645. // problems with reinit
  646. disposeConference();
  647. focus = new ColibriFocus(connection, config.hosts.bridge);
  648. if (nickname !== null) {
  649. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  650. nickname);
  651. }
  652. Toolbar.showRecordingButton(false);
  653. }
  654. if (connection.emuc.getPrezi(jid)) {
  655. $(document).trigger('presentationremoved.muc',
  656. [jid, connection.emuc.getPrezi(jid)]);
  657. }
  658. });
  659. $(document).bind('presence.muc', function (event, jid, info, pres) {
  660. // Remove old ssrcs coming from the jid
  661. Object.keys(ssrc2jid).forEach(function (ssrc) {
  662. if (ssrc2jid[ssrc] == jid) {
  663. delete ssrc2jid[ssrc];
  664. }
  665. if (ssrc2videoType[ssrc] == jid) {
  666. delete ssrc2videoType[ssrc];
  667. }
  668. });
  669. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  670. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  671. var ssrcV = ssrc.getAttribute('ssrc');
  672. ssrc2jid[ssrcV] = jid;
  673. var type = ssrc.getAttribute('type');
  674. ssrc2videoType[ssrcV] = type;
  675. // might need to update the direction if participant just went from sendrecv to recvonly
  676. if (type === 'video' || type === 'screen') {
  677. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  678. switch (ssrc.getAttribute('direction')) {
  679. case 'sendrecv':
  680. el.show();
  681. break;
  682. case 'recvonly':
  683. el.hide();
  684. // FIXME: Check if we have to change large video
  685. //VideoLayout.checkChangeLargeVideo(el);
  686. break;
  687. }
  688. }
  689. });
  690. if (jid === connection.emuc.myroomjid) {
  691. VideoLayout.setDisplayName('localVideoContainer',
  692. info.displayName);
  693. } else {
  694. VideoLayout.ensurePeerContainerExists(jid);
  695. VideoLayout.setDisplayName(
  696. 'participant_' + Strophe.getResourceFromJid(jid),
  697. info.displayName);
  698. }
  699. if (focus !== null && info.displayName !== null) {
  700. focus.setEndpointDisplayName(jid, info.displayName);
  701. }
  702. });
  703. $(document).bind('passwordrequired.muc', function (event, jid) {
  704. console.log('on password required', jid);
  705. $.prompt('<h2>Password required</h2>' +
  706. '<input id="lockKey" type="text" placeholder="shared key" autofocus>', {
  707. persistent: true,
  708. buttons: { "Ok": true, "Cancel": false},
  709. defaultButton: 1,
  710. loaded: function (event) {
  711. document.getElementById('lockKey').focus();
  712. },
  713. submit: function (e, v, m, f) {
  714. if (v) {
  715. var lockKey = document.getElementById('lockKey');
  716. if (lockKey.value !== null) {
  717. setSharedKey(lockKey.value);
  718. connection.emuc.doJoin(jid, lockKey.value);
  719. }
  720. }
  721. }
  722. });
  723. });
  724. /**
  725. * Checks if video identified by given src is desktop stream.
  726. * @param videoSrc eg.
  727. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  728. * @returns {boolean}
  729. */
  730. function isVideoSrcDesktop(videoSrc) {
  731. // FIXME: fix this mapping mess...
  732. // figure out if large video is desktop stream or just a camera
  733. var isDesktop = false;
  734. if (localVideoSrc === videoSrc) {
  735. // local video
  736. isDesktop = isUsingScreenStream;
  737. } else {
  738. // Do we have associations...
  739. var videoSsrc = videoSrcToSsrc[videoSrc];
  740. if (videoSsrc) {
  741. var videoType = ssrc2videoType[videoSsrc];
  742. if (videoType) {
  743. // Finally there...
  744. isDesktop = videoType === 'screen';
  745. } else {
  746. console.error("No video type for ssrc: " + videoSsrc);
  747. }
  748. } else {
  749. console.error("No ssrc for src: " + videoSrc);
  750. }
  751. }
  752. return isDesktop;
  753. }
  754. function getConferenceHandler() {
  755. return focus ? focus : activecall;
  756. }
  757. function toggleVideo() {
  758. if (!(connection && connection.jingle.localVideo))
  759. return;
  760. var sess = getConferenceHandler();
  761. if (sess) {
  762. sess.toggleVideoMute(
  763. function (isMuted) {
  764. if (isMuted) {
  765. $('#video').removeClass("icon-camera");
  766. $('#video').addClass("icon-camera icon-camera-disabled");
  767. } else {
  768. $('#video').removeClass("icon-camera icon-camera-disabled");
  769. $('#video').addClass("icon-camera");
  770. }
  771. }
  772. );
  773. }
  774. sess = focus || activecall;
  775. if (!sess) {
  776. return;
  777. }
  778. sess.pendingop = ismuted ? 'unmute' : 'mute';
  779. // connection.emuc.addVideoInfoToPresence(!ismuted);
  780. // connection.emuc.sendPresence();
  781. sess.modifySources();
  782. }
  783. /**
  784. * Mutes / unmutes audio for the local participant.
  785. */
  786. function toggleAudio() {
  787. if (!(connection && connection.jingle.localAudio)) {
  788. preMuted = true;
  789. // We still click the button.
  790. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  791. return;
  792. }
  793. var localAudio = connection.jingle.localAudio;
  794. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  795. var audioEnabled = localAudio.getAudioTracks()[idx].enabled;
  796. localAudio.getAudioTracks()[idx].enabled = !audioEnabled;
  797. // isMuted is the opposite of audioEnabled
  798. connection.emuc.addAudioInfoToPresence(audioEnabled);
  799. connection.emuc.sendPresence();
  800. }
  801. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  802. }
  803. // Starts or stops the recording for the conference.
  804. function toggleRecording() {
  805. if (focus === null || focus.confid === null) {
  806. console.log('non-focus, or conference not yet organized: not enabling recording');
  807. return;
  808. }
  809. if (!recordingToken)
  810. {
  811. $.prompt('<h2>Enter recording token</h2>' +
  812. '<input id="recordingToken" type="text" placeholder="token" autofocus>',
  813. {
  814. persistent: false,
  815. buttons: { "Save": true, "Cancel": false},
  816. defaultButton: 1,
  817. loaded: function (event) {
  818. document.getElementById('recordingToken').focus();
  819. },
  820. submit: function (e, v, m, f) {
  821. if (v) {
  822. var token = document.getElementById('recordingToken');
  823. if (token.value) {
  824. setRecordingToken(Util.escapeHtml(token.value));
  825. toggleRecording();
  826. }
  827. }
  828. }
  829. }
  830. );
  831. return;
  832. }
  833. var oldState = focus.recordingEnabled;
  834. Toolbar.toggleRecordingButtonState();
  835. focus.setRecording(!oldState,
  836. recordingToken,
  837. function (state) {
  838. console.log("New recording state: ", state);
  839. if (state == oldState) //failed to change, reset the token because it might have been wrong
  840. {
  841. Toolbar.toggleRecordingButtonState();
  842. setRecordingToken(null);
  843. }
  844. }
  845. );
  846. }
  847. /**
  848. * Returns an array of the video horizontal and vertical indents,
  849. * so that if fits its parent.
  850. *
  851. * @return an array with 2 elements, the horizontal indent and the vertical
  852. * indent
  853. */
  854. function getCameraVideoPosition(videoWidth,
  855. videoHeight,
  856. videoSpaceWidth,
  857. videoSpaceHeight) {
  858. // Parent height isn't completely calculated when we position the video in
  859. // full screen mode and this is why we use the screen height in this case.
  860. // Need to think it further at some point and implement it properly.
  861. var isFullScreen = document.fullScreen ||
  862. document.mozFullScreen ||
  863. document.webkitIsFullScreen;
  864. if (isFullScreen)
  865. videoSpaceHeight = window.innerHeight;
  866. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  867. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  868. return [horizontalIndent, verticalIndent];
  869. }
  870. /**
  871. * Returns an array of the video horizontal and vertical indents.
  872. * Centers horizontally and top aligns vertically.
  873. *
  874. * @return an array with 2 elements, the horizontal indent and the vertical
  875. * indent
  876. */
  877. function getDesktopVideoPosition(videoWidth,
  878. videoHeight,
  879. videoSpaceWidth,
  880. videoSpaceHeight) {
  881. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  882. var verticalIndent = 0;// Top aligned
  883. return [horizontalIndent, verticalIndent];
  884. }
  885. /**
  886. * Returns an array of the video dimensions, so that it covers the screen.
  887. * It leaves no empty areas, but some parts of the video might not be visible.
  888. *
  889. * @return an array with 2 elements, the video width and the video height
  890. */
  891. function getCameraVideoSize(videoWidth,
  892. videoHeight,
  893. videoSpaceWidth,
  894. videoSpaceHeight) {
  895. if (!videoWidth)
  896. videoWidth = currentVideoWidth;
  897. if (!videoHeight)
  898. videoHeight = currentVideoHeight;
  899. var aspectRatio = videoWidth / videoHeight;
  900. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  901. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  902. if (availableWidth / aspectRatio < videoSpaceHeight) {
  903. availableHeight = videoSpaceHeight;
  904. availableWidth = availableHeight * aspectRatio;
  905. }
  906. if (availableHeight * aspectRatio < videoSpaceWidth) {
  907. availableWidth = videoSpaceWidth;
  908. availableHeight = availableWidth / aspectRatio;
  909. }
  910. return [availableWidth, availableHeight];
  911. }
  912. $(document).ready(function () {
  913. Chat.init();
  914. $('body').popover({ selector: '[data-toggle=popover]',
  915. trigger: 'click hover'});
  916. // Set the defaults for prompt dialogs.
  917. jQuery.prompt.setDefaults({persistent: false});
  918. // Set default desktop sharing method
  919. setDesktopSharing(config.desktopSharing);
  920. // Initialize Chrome extension inline installs
  921. if (config.chromeExtensionId) {
  922. initInlineInstalls();
  923. }
  924. // By default we use camera
  925. getVideoSize = getCameraVideoSize;
  926. getVideoPosition = getCameraVideoPosition;
  927. VideoLayout.resizeLargeVideoContainer();
  928. $(window).resize(function () {
  929. VideoLayout.resizeLargeVideoContainer();
  930. VideoLayout.positionLarge();
  931. });
  932. // Listen for large video size updates
  933. document.getElementById('largeVideo')
  934. .addEventListener('loadedmetadata', function (e) {
  935. currentVideoWidth = this.videoWidth;
  936. currentVideoHeight = this.videoHeight;
  937. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  938. });
  939. if (!$('#settings').is(':visible')) {
  940. console.log('init');
  941. init();
  942. } else {
  943. loginInfo.onsubmit = function (e) {
  944. if (e.preventDefault) e.preventDefault();
  945. $('#settings').hide();
  946. init();
  947. };
  948. }
  949. });
  950. $(window).bind('beforeunload', function () {
  951. if (connection && connection.connected) {
  952. // ensure signout
  953. $.ajax({
  954. type: 'POST',
  955. url: config.bosh,
  956. async: false,
  957. cache: false,
  958. contentType: 'application/xml',
  959. data: "<body rid='" + (connection.rid || connection._proto.rid) + "' xmlns='http://jabber.org/protocol/httpbind' sid='" + (connection.sid || connection._proto.sid) + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  960. success: function (data) {
  961. console.log('signed out');
  962. console.log(data);
  963. },
  964. error: function (XMLHttpRequest, textStatus, errorThrown) {
  965. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  966. }
  967. });
  968. }
  969. disposeConference(true);
  970. });
  971. function disposeConference(onUnload) {
  972. var handler = getConferenceHandler();
  973. if (handler && handler.peerconnection) {
  974. // FIXME: probably removing streams is not required and close() should be enough
  975. if (connection.jingle.localAudio) {
  976. handler.peerconnection.removeStream(connection.jingle.localAudio);
  977. }
  978. if (connection.jingle.localVideo) {
  979. handler.peerconnection.removeStream(connection.jingle.localVideo);
  980. }
  981. handler.peerconnection.close();
  982. }
  983. stopRTPStatsCollector();
  984. if(!onUnload) {
  985. startLocalRtpStatsCollector(connection.jingle.localAudio);
  986. }
  987. else
  988. {
  989. stopLocalRtpStatsCollector();
  990. }
  991. focus = null;
  992. activecall = null;
  993. }
  994. function dump(elem, filename) {
  995. elem = elem.parentNode;
  996. elem.download = filename || 'meetlog.json';
  997. elem.href = 'data:application/json;charset=utf-8,\n';
  998. var data = {};
  999. if (connection.jingle) {
  1000. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  1001. var session = connection.jingle.sessions[sid];
  1002. if (session.peerconnection && session.peerconnection.updateLog) {
  1003. // FIXME: should probably be a .dump call
  1004. data["jingle_" + session.sid] = {
  1005. updateLog: session.peerconnection.updateLog,
  1006. stats: session.peerconnection.stats,
  1007. url: window.location.href
  1008. };
  1009. }
  1010. });
  1011. }
  1012. metadata = {};
  1013. metadata.time = new Date();
  1014. metadata.url = window.location.href;
  1015. metadata.ua = navigator.userAgent;
  1016. if (connection.logger) {
  1017. metadata.xmpp = connection.logger.log;
  1018. }
  1019. data.metadata = metadata;
  1020. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1021. return false;
  1022. }
  1023. /**
  1024. * Changes the style class of the element given by id.
  1025. */
  1026. function buttonClick(id, classname) {
  1027. $(id).toggleClass(classname); // add the class to the clicked element
  1028. }
  1029. /**
  1030. * Shows a message to the user.
  1031. *
  1032. * @param titleString the title of the message
  1033. * @param messageString the text of the message
  1034. */
  1035. function openMessageDialog(titleString, messageString) {
  1036. $.prompt(messageString,
  1037. {
  1038. title: titleString,
  1039. persistent: false
  1040. }
  1041. );
  1042. }
  1043. /**
  1044. * Locks / unlocks the room.
  1045. */
  1046. function lockRoom(lock) {
  1047. if (lock)
  1048. connection.emuc.lockRoom(sharedKey);
  1049. else
  1050. connection.emuc.lockRoom('');
  1051. Toolbar.updateLockButton();
  1052. }
  1053. /**
  1054. * Sets the shared key.
  1055. */
  1056. function setSharedKey(sKey) {
  1057. sharedKey = sKey;
  1058. }
  1059. function setRecordingToken(token) {
  1060. recordingToken = token;
  1061. }
  1062. /**
  1063. * Updates the room invite url.
  1064. */
  1065. function updateRoomUrl(newRoomUrl) {
  1066. roomUrl = newRoomUrl;
  1067. // If the invite dialog has been already opened we update the information.
  1068. var inviteLink = document.getElementById('inviteLinkRef');
  1069. if (inviteLink) {
  1070. inviteLink.value = roomUrl;
  1071. inviteLink.select();
  1072. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  1073. }
  1074. }
  1075. /**
  1076. * Warning to the user that the conference window is about to be closed.
  1077. */
  1078. function closePageWarning() {
  1079. if (focus !== null)
  1080. return "You are the owner of this conference call and"
  1081. + " you are about to end it.";
  1082. else
  1083. return "You are about to leave this conversation.";
  1084. }
  1085. /**
  1086. * Resizes and repositions videos in full screen mode.
  1087. */
  1088. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1089. function () {
  1090. VideoLayout.resizeLargeVideoContainer();
  1091. VideoLayout.positionLarge();
  1092. isFullScreen = document.fullScreen ||
  1093. document.mozFullScreen ||
  1094. document.webkitIsFullScreen;
  1095. if (isFullScreen) {
  1096. setView("fullscreen");
  1097. }
  1098. else {
  1099. setView("default");
  1100. }
  1101. }
  1102. );
  1103. /**
  1104. * Sets the current view.
  1105. */
  1106. function setView(viewName) {
  1107. // if (viewName == "fullscreen") {
  1108. // document.getElementById('videolayout_fullscreen').disabled = false;
  1109. // document.getElementById('videolayout_default').disabled = true;
  1110. // }
  1111. // else {
  1112. // document.getElementById('videolayout_default').disabled = false;
  1113. // document.getElementById('videolayout_fullscreen').disabled = true;
  1114. // }
  1115. }
  1116. $(document).bind('fatalError.jingle',
  1117. function (event, session, error)
  1118. {
  1119. sessionTerminated = true;
  1120. connection.emuc.doLeave();
  1121. openMessageDialog( "Sorry",
  1122. "Your browser version is too old. Please update and try again...");
  1123. }
  1124. );