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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  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 before has started)
  257. sel.removed = true;
  258. sel.remove();
  259. var audioCount = $('#' + container.id + '>audio').length;
  260. var videoCount = $('#' + container.id + '>video').length;
  261. if (!audioCount && !videoCount) {
  262. console.log("Remove whole user", container.id);
  263. // Remove whole container
  264. container.remove();
  265. Util.playSoundNotification('userLeft');
  266. VideoLayout.resizeThumbnails();
  267. }
  268. VideoLayout.checkChangeLargeVideo(vid.src);
  269. };
  270. // Add click handler.
  271. container.onclick = function (event) {
  272. VideoLayout.handleVideoThumbClicked(
  273. $('#' + container.id + '>video').get(0).src);
  274. event.preventDefault();
  275. return false;
  276. };
  277. // Add hover handler
  278. $(container).hover(
  279. function() {
  280. VideoLayout.showDisplayName(container.id, true);
  281. },
  282. function() {
  283. var videoSrc = null;
  284. if ($('#' + container.id + '>video')
  285. && $('#' + container.id + '>video').length > 0) {
  286. videoSrc = $('#' + container.id + '>video').get(0).src;
  287. }
  288. // If the video has been "pinned" by the user we want to keep the
  289. // display name on place.
  290. if (!VideoLayout.isLargeVideoVisible()
  291. || videoSrc !== $('#largeVideo').attr('src'))
  292. VideoLayout.showDisplayName(container.id, false);
  293. }
  294. );
  295. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  296. if (isVideo &&
  297. data.peerjid && sess.peerjid === data.peerjid &&
  298. data.stream.getVideoTracks().length === 0 &&
  299. connection.jingle.localVideo.getVideoTracks().length > 0) {
  300. //
  301. window.setTimeout(function () {
  302. sendKeyframe(sess.peerconnection);
  303. }, 3000);
  304. }
  305. });
  306. /**
  307. * Returns the JID of the user to whom given <tt>videoSrc</tt> belongs.
  308. * @param videoSrc the video "src" identifier.
  309. * @returns {null | String} the JID of the user to whom given <tt>videoSrc</tt>
  310. * belongs.
  311. */
  312. function getJidFromVideoSrc(videoSrc)
  313. {
  314. if (videoSrc === localVideoSrc)
  315. return connection.emuc.myroomjid;
  316. var ssrc = videoSrcToSsrc[videoSrc];
  317. if (!ssrc)
  318. {
  319. return null;
  320. }
  321. return ssrc2jid[ssrc];
  322. }
  323. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  324. function sendKeyframe(pc) {
  325. console.log('sendkeyframe', pc.iceConnectionState);
  326. if (pc.iceConnectionState !== 'connected') return; // safe...
  327. pc.setRemoteDescription(
  328. pc.remoteDescription,
  329. function () {
  330. pc.createAnswer(
  331. function (modifiedAnswer) {
  332. pc.setLocalDescription(
  333. modifiedAnswer,
  334. function () {
  335. // noop
  336. },
  337. function (error) {
  338. console.log('triggerKeyframe setLocalDescription failed', error);
  339. }
  340. );
  341. },
  342. function (error) {
  343. console.log('triggerKeyframe createAnswer failed', error);
  344. }
  345. );
  346. },
  347. function (error) {
  348. console.log('triggerKeyframe setRemoteDescription failed', error);
  349. }
  350. );
  351. }
  352. // Really mute video, i.e. dont even send black frames
  353. function muteVideo(pc, unmute) {
  354. // FIXME: this probably needs another of those lovely state safeguards...
  355. // which checks for iceconn == connected and sigstate == stable
  356. pc.setRemoteDescription(pc.remoteDescription,
  357. function () {
  358. pc.createAnswer(
  359. function (answer) {
  360. var sdp = new SDP(answer.sdp);
  361. if (sdp.media.length > 1) {
  362. if (unmute)
  363. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  364. else
  365. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  366. sdp.raw = sdp.session + sdp.media.join('');
  367. answer.sdp = sdp.raw;
  368. }
  369. pc.setLocalDescription(answer,
  370. function () {
  371. console.log('mute SLD ok');
  372. },
  373. function (error) {
  374. console.log('mute SLD error');
  375. }
  376. );
  377. },
  378. function (error) {
  379. console.log(error);
  380. }
  381. );
  382. },
  383. function (error) {
  384. console.log('muteVideo SRD error');
  385. }
  386. );
  387. }
  388. /**
  389. * Callback called by {@link StatsCollector} in intervals supplied to it's
  390. * constructor.
  391. * @param statsCollector {@link StatsCollector} source of the event.
  392. */
  393. function statsUpdated(statsCollector)
  394. {
  395. Object.keys(statsCollector.jid2stats).forEach(function (jid)
  396. {
  397. var peerStats = statsCollector.jid2stats[jid];
  398. Object.keys(peerStats.ssrc2AudioLevel).forEach(function (ssrc)
  399. {
  400. // console.info(jid + " audio level: " +
  401. // peerStats.ssrc2AudioLevel[ssrc] + " of ssrc: " + ssrc);
  402. });
  403. });
  404. }
  405. /**
  406. * Callback called by {@link LocalStatsCollector} in intervals supplied to it's
  407. * constructor.
  408. * @param statsCollector {@link LocalStatsCollector} source of the event.
  409. */
  410. function localStatsUpdated(statsCollector)
  411. {
  412. // console.info("Local audio level: " + statsCollector.audioLevel);
  413. }
  414. /**
  415. * Starts the {@link StatsCollector} if the feature is enabled in config.js.
  416. */
  417. function startRtpStatsCollector()
  418. {
  419. if (config.enableRtpStats && !statsCollector)
  420. {
  421. statsCollector = new StatsCollector(
  422. getConferenceHandler().peerconnection, 200, statsUpdated);
  423. stopLocalRtpStatsCollector();
  424. statsCollector.start();
  425. }
  426. }
  427. /**
  428. * Starts the {@link LocalStatsCollector} if the feature is enabled in config.js
  429. * @param stream the stream that will be used for collecting statistics.
  430. */
  431. function startLocalRtpStatsCollector(stream)
  432. {
  433. if(config.enableRtpStats)
  434. {
  435. localStatsCollector = new LocalStatsCollector(stream, 200, localStatsUpdated);
  436. localStatsCollector.start();
  437. }
  438. }
  439. /**
  440. * Stops the {@link LocalStatsCollector}.
  441. */
  442. function stopLocalRtpStatsCollector()
  443. {
  444. if(localStatsCollector)
  445. {
  446. localStatsCollector.stop();
  447. localStatsCollector = null;
  448. }
  449. }
  450. $(document).bind('callincoming.jingle', function (event, sid) {
  451. var sess = connection.jingle.sessions[sid];
  452. // TODO: do we check activecall == null?
  453. activecall = sess;
  454. startRtpStatsCollector();
  455. // Bind data channel listener in case we're a regular participant
  456. if (config.openSctp)
  457. {
  458. bindDataChannelListener(sess.peerconnection);
  459. }
  460. // TODO: check affiliation and/or role
  461. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  462. sess.usedrip = true; // not-so-naive trickle ice
  463. sess.sendAnswer();
  464. sess.accept();
  465. });
  466. $(document).bind('conferenceCreated.jingle', function (event, focus)
  467. {
  468. startRtpStatsCollector();
  469. });
  470. $(document).bind('conferenceCreated.jingle', function (event, focus)
  471. {
  472. // Bind data channel listener in case we're the focus
  473. if (config.openSctp)
  474. {
  475. bindDataChannelListener(focus.peerconnection);
  476. }
  477. });
  478. $(document).bind('callactive.jingle', function (event, videoelem, sid) {
  479. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  480. // ignore mixedmslabela0 and v0
  481. videoelem.show();
  482. VideoLayout.resizeThumbnails();
  483. // Update the large video to the last added video only if there's no
  484. // current active or focused speaker.
  485. if (!focusedVideoSrc && !VideoLayout.getActiveSpeakerResourceJid())
  486. VideoLayout.updateLargeVideo(videoelem.attr('src'), 1);
  487. VideoLayout.showFocusIndicator();
  488. }
  489. });
  490. $(document).bind('callterminated.jingle', function (event, sid, jid, reason) {
  491. // Leave the room if my call has been remotely terminated.
  492. if (connection.emuc.joined && focus == null && reason === 'kick') {
  493. sessionTerminated = true;
  494. connection.emuc.doLeave();
  495. openMessageDialog( "Session Terminated",
  496. "Ouch! You have been kicked out of the meet!");
  497. }
  498. });
  499. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  500. // put our ssrcs into presence so other clients can identify our stream
  501. var sess = connection.jingle.sessions[sid];
  502. var newssrcs = {};
  503. var directions = {};
  504. var localSDP = new SDP(sess.peerconnection.localDescription.sdp);
  505. localSDP.media.forEach(function (media) {
  506. var type = SDPUtil.parse_mid(SDPUtil.find_line(media, 'a=mid:'));
  507. if (SDPUtil.find_line(media, 'a=ssrc:')) {
  508. // assumes a single local ssrc
  509. var ssrc = SDPUtil.find_line(media, 'a=ssrc:').substring(7).split(' ')[0];
  510. newssrcs[type] = ssrc;
  511. directions[type] = (
  512. SDPUtil.find_line(media, 'a=sendrecv') ||
  513. SDPUtil.find_line(media, 'a=recvonly') ||
  514. SDPUtil.find_line(media, 'a=sendonly') ||
  515. SDPUtil.find_line(media, 'a=inactive') ||
  516. 'a=sendrecv').substr(2);
  517. }
  518. });
  519. console.log('new ssrcs', newssrcs);
  520. // Have to clear presence map to get rid of removed streams
  521. connection.emuc.clearPresenceMedia();
  522. var i = 0;
  523. Object.keys(newssrcs).forEach(function (mtype) {
  524. i++;
  525. var type = mtype;
  526. // Change video type to screen
  527. if (mtype === 'video' && isUsingScreenStream) {
  528. type = 'screen';
  529. }
  530. connection.emuc.addMediaToPresence(i, type, newssrcs[mtype], directions[mtype]);
  531. });
  532. if (i > 0) {
  533. connection.emuc.sendPresence();
  534. }
  535. });
  536. $(document).bind('joined.muc', function (event, jid, info) {
  537. updateRoomUrl(window.location.href);
  538. document.getElementById('localNick').appendChild(
  539. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  540. );
  541. if (Object.keys(connection.emuc.members).length < 1) {
  542. focus = new ColibriFocus(connection, config.hosts.bridge);
  543. showRecordingButton(false);
  544. }
  545. if (focus && config.etherpad_base) {
  546. Etherpad.init();
  547. }
  548. VideoLayout.showFocusIndicator();
  549. // Once we've joined the muc show the toolbar
  550. Toolbar.showToolbar();
  551. var displayName = '';
  552. if (info.displayName)
  553. displayName = info.displayName + ' (me)';
  554. VideoLayout.setDisplayName('localVideoContainer', displayName);
  555. });
  556. $(document).bind('entered.muc', function (event, jid, info, pres) {
  557. console.log('entered', jid, info);
  558. console.log('is focus?' + focus ? 'true' : 'false');
  559. // Add Peer's container
  560. VideoLayout.ensurePeerContainerExists(jid);
  561. if (focus !== null) {
  562. // FIXME: this should prepare the video
  563. if (focus.confid === null) {
  564. console.log('make new conference with', jid);
  565. focus.makeConference(Object.keys(connection.emuc.members));
  566. showRecordingButton(true);
  567. } else {
  568. console.log('invite', jid, 'into conference');
  569. focus.addNewParticipant(jid);
  570. }
  571. }
  572. else if (sharedKey) {
  573. Toolbar.updateLockButton();
  574. }
  575. });
  576. $(document).bind('left.muc', function (event, jid) {
  577. console.log('left.muc', jid);
  578. // Need to call this with a slight delay, otherwise the element couldn't be
  579. // found for some reason.
  580. window.setTimeout(function () {
  581. var container = document.getElementById(
  582. 'participant_' + Strophe.getResourceFromJid(jid));
  583. if (container) {
  584. // hide here, wait for video to close before removing
  585. $(container).hide();
  586. VideoLayout.resizeThumbnails();
  587. }
  588. }, 10);
  589. // Unlock large video
  590. if (focusedVideoSrc)
  591. {
  592. if (getJidFromVideoSrc(focusedVideoSrc) === jid)
  593. {
  594. console.info("Focused video owner has left the conference");
  595. focusedVideoSrc = null;
  596. }
  597. }
  598. connection.jingle.terminateByJid(jid);
  599. if (focus == null
  600. // I shouldn't be the one that left to enter here.
  601. && jid !== connection.emuc.myroomjid
  602. && connection.emuc.myroomjid === connection.emuc.list_members[0]
  603. // If our session has been terminated for some reason
  604. // (kicked, hangup), don't try to become the focus
  605. && !sessionTerminated) {
  606. console.log('welcome to our new focus... myself');
  607. focus = new ColibriFocus(connection, config.hosts.bridge);
  608. if (Object.keys(connection.emuc.members).length > 0) {
  609. focus.makeConference(Object.keys(connection.emuc.members));
  610. showRecordingButton(true);
  611. }
  612. $(document).trigger('focusechanged.muc', [focus]);
  613. }
  614. else if (focus && Object.keys(connection.emuc.members).length === 0) {
  615. console.log('everyone left');
  616. // FIXME: closing the connection is a hack to avoid some
  617. // problems with reinit
  618. disposeConference();
  619. focus = new ColibriFocus(connection, config.hosts.bridge);
  620. showRecordingButton(false);
  621. }
  622. if (connection.emuc.getPrezi(jid)) {
  623. $(document).trigger('presentationremoved.muc',
  624. [jid, connection.emuc.getPrezi(jid)]);
  625. }
  626. });
  627. $(document).bind('presence.muc', function (event, jid, info, pres) {
  628. // Remove old ssrcs coming from the jid
  629. Object.keys(ssrc2jid).forEach(function (ssrc) {
  630. if (ssrc2jid[ssrc] == jid) {
  631. delete ssrc2jid[ssrc];
  632. }
  633. if (ssrc2videoType == jid) {
  634. delete ssrc2videoType[ssrc];
  635. }
  636. });
  637. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  638. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  639. var ssrcV = ssrc.getAttribute('ssrc');
  640. ssrc2jid[ssrcV] = jid;
  641. var type = ssrc.getAttribute('type');
  642. ssrc2videoType[ssrcV] = type;
  643. // might need to update the direction if participant just went from sendrecv to recvonly
  644. if (type === 'video' || type === 'screen') {
  645. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  646. switch (ssrc.getAttribute('direction')) {
  647. case 'sendrecv':
  648. el.show();
  649. break;
  650. case 'recvonly':
  651. el.hide();
  652. // FIXME: Check if we have to change large video
  653. //VideoLayout.checkChangeLargeVideo(el);
  654. break;
  655. }
  656. }
  657. });
  658. if (jid === connection.emuc.myroomjid) {
  659. VideoLayout.setDisplayName('localVideoContainer',
  660. info.displayName);
  661. } else {
  662. VideoLayout.ensurePeerContainerExists(jid);
  663. VideoLayout.setDisplayName(
  664. 'participant_' + Strophe.getResourceFromJid(jid),
  665. info.displayName);
  666. }
  667. });
  668. $(document).bind('passwordrequired.muc', function (event, jid) {
  669. console.log('on password required', jid);
  670. $.prompt('<h2>Password required</h2>' +
  671. '<input id="lockKey" type="text" placeholder="shared key" autofocus>', {
  672. persistent: true,
  673. buttons: { "Ok": true, "Cancel": false},
  674. defaultButton: 1,
  675. loaded: function (event) {
  676. document.getElementById('lockKey').focus();
  677. },
  678. submit: function (e, v, m, f) {
  679. if (v) {
  680. var lockKey = document.getElementById('lockKey');
  681. if (lockKey.value !== null) {
  682. setSharedKey(lockKey.value);
  683. connection.emuc.doJoin(jid, lockKey.value);
  684. }
  685. }
  686. }
  687. });
  688. });
  689. /**
  690. * Checks if video identified by given src is desktop stream.
  691. * @param videoSrc eg.
  692. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  693. * @returns {boolean}
  694. */
  695. function isVideoSrcDesktop(videoSrc) {
  696. // FIXME: fix this mapping mess...
  697. // figure out if large video is desktop stream or just a camera
  698. var isDesktop = false;
  699. if (localVideoSrc === videoSrc) {
  700. // local video
  701. isDesktop = isUsingScreenStream;
  702. } else {
  703. // Do we have associations...
  704. var videoSsrc = videoSrcToSsrc[videoSrc];
  705. if (videoSsrc) {
  706. var videoType = ssrc2videoType[videoSsrc];
  707. if (videoType) {
  708. // Finally there...
  709. isDesktop = videoType === 'screen';
  710. } else {
  711. console.error("No video type for ssrc: " + videoSsrc);
  712. }
  713. } else {
  714. console.error("No ssrc for src: " + videoSrc);
  715. }
  716. }
  717. return isDesktop;
  718. }
  719. function getConferenceHandler() {
  720. return focus ? focus : activecall;
  721. }
  722. function toggleVideo() {
  723. if (!(connection && connection.jingle.localVideo))
  724. return;
  725. var sess = getConferenceHandler();
  726. if (sess) {
  727. sess.toggleVideoMute(
  728. function (isMuted) {
  729. if (isMuted) {
  730. $('#video').removeClass("icon-camera");
  731. $('#video').addClass("icon-camera icon-camera-disabled");
  732. } else {
  733. $('#video').removeClass("icon-camera icon-camera-disabled");
  734. $('#video').addClass("icon-camera");
  735. }
  736. }
  737. );
  738. }
  739. sess = focus || activecall;
  740. if (!sess) {
  741. return;
  742. }
  743. sess.pendingop = ismuted ? 'unmute' : 'mute';
  744. // connection.emuc.addVideoInfoToPresence(!ismuted);
  745. // connection.emuc.sendPresence();
  746. sess.modifySources();
  747. }
  748. /**
  749. * Mutes / unmutes audio for the local participant.
  750. */
  751. function toggleAudio() {
  752. if (!(connection && connection.jingle.localAudio)) {
  753. preMuted = true;
  754. // We still click the button.
  755. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  756. return;
  757. }
  758. var localAudio = connection.jingle.localAudio;
  759. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  760. var audioEnabled = localAudio.getAudioTracks()[idx].enabled;
  761. localAudio.getAudioTracks()[idx].enabled = !audioEnabled;
  762. // isMuted is the opposite of audioEnabled
  763. connection.emuc.addAudioInfoToPresence(audioEnabled);
  764. connection.emuc.sendPresence();
  765. }
  766. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  767. }
  768. // Starts or stops the recording for the conference.
  769. function toggleRecording() {
  770. if (focus === null || focus.confid === null) {
  771. console.log('non-focus, or conference not yet organized: not enabling recording');
  772. return;
  773. }
  774. if (!recordingToken)
  775. {
  776. $.prompt('<h2>Enter recording token</h2>' +
  777. '<input id="recordingToken" type="text" placeholder="token" autofocus>',
  778. {
  779. persistent: false,
  780. buttons: { "Save": true, "Cancel": false},
  781. defaultButton: 1,
  782. loaded: function (event) {
  783. document.getElementById('recordingToken').focus();
  784. },
  785. submit: function (e, v, m, f) {
  786. if (v) {
  787. var token = document.getElementById('recordingToken');
  788. if (token.value) {
  789. setRecordingToken(Util.escapeHtml(token.value));
  790. toggleRecording();
  791. }
  792. }
  793. }
  794. }
  795. );
  796. return;
  797. }
  798. var oldState = focus.recordingEnabled;
  799. buttonClick("#recordButton", "icon-recEnable icon-recDisable");
  800. focus.setRecording(!oldState,
  801. recordingToken,
  802. function (state) {
  803. console.log("New recording state: ", state);
  804. if (state == oldState) //failed to change, reset the token because it might have been wrong
  805. {
  806. buttonClick("#recordButton", "icon-recEnable icon-recDisable");
  807. setRecordingToken(null);
  808. }
  809. }
  810. );
  811. }
  812. /**
  813. * Returns an array of the video horizontal and vertical indents,
  814. * so that if fits its parent.
  815. *
  816. * @return an array with 2 elements, the horizontal indent and the vertical
  817. * indent
  818. */
  819. function getCameraVideoPosition(videoWidth,
  820. videoHeight,
  821. videoSpaceWidth,
  822. videoSpaceHeight) {
  823. // Parent height isn't completely calculated when we position the video in
  824. // full screen mode and this is why we use the screen height in this case.
  825. // Need to think it further at some point and implement it properly.
  826. var isFullScreen = document.fullScreen ||
  827. document.mozFullScreen ||
  828. document.webkitIsFullScreen;
  829. if (isFullScreen)
  830. videoSpaceHeight = window.innerHeight;
  831. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  832. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  833. return [horizontalIndent, verticalIndent];
  834. }
  835. /**
  836. * Returns an array of the video horizontal and vertical indents.
  837. * Centers horizontally and top aligns vertically.
  838. *
  839. * @return an array with 2 elements, the horizontal indent and the vertical
  840. * indent
  841. */
  842. function getDesktopVideoPosition(videoWidth,
  843. videoHeight,
  844. videoSpaceWidth,
  845. videoSpaceHeight) {
  846. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  847. var verticalIndent = 0;// Top aligned
  848. return [horizontalIndent, verticalIndent];
  849. }
  850. /**
  851. * Returns an array of the video dimensions, so that it covers the screen.
  852. * It leaves no empty areas, but some parts of the video might not be visible.
  853. *
  854. * @return an array with 2 elements, the video width and the video height
  855. */
  856. function getCameraVideoSize(videoWidth,
  857. videoHeight,
  858. videoSpaceWidth,
  859. videoSpaceHeight) {
  860. if (!videoWidth)
  861. videoWidth = currentVideoWidth;
  862. if (!videoHeight)
  863. videoHeight = currentVideoHeight;
  864. var aspectRatio = videoWidth / videoHeight;
  865. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  866. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  867. if (availableWidth / aspectRatio < videoSpaceHeight) {
  868. availableHeight = videoSpaceHeight;
  869. availableWidth = availableHeight * aspectRatio;
  870. }
  871. if (availableHeight * aspectRatio < videoSpaceWidth) {
  872. availableWidth = videoSpaceWidth;
  873. availableHeight = availableWidth / aspectRatio;
  874. }
  875. return [availableWidth, availableHeight];
  876. }
  877. $(document).ready(function () {
  878. Chat.init();
  879. $('body').popover({ selector: '[data-toggle=popover]',
  880. trigger: 'click hover'});
  881. // Set the defaults for prompt dialogs.
  882. jQuery.prompt.setDefaults({persistent: false});
  883. // Set default desktop sharing method
  884. setDesktopSharing(config.desktopSharing);
  885. // Initialize Chrome extension inline installs
  886. if (config.chromeExtensionId) {
  887. initInlineInstalls();
  888. }
  889. // By default we use camera
  890. getVideoSize = getCameraVideoSize;
  891. getVideoPosition = getCameraVideoPosition;
  892. VideoLayout.resizeLargeVideoContainer();
  893. $(window).resize(function () {
  894. VideoLayout.resizeLargeVideoContainer();
  895. VideoLayout.positionLarge();
  896. });
  897. // Listen for large video size updates
  898. document.getElementById('largeVideo')
  899. .addEventListener('loadedmetadata', function (e) {
  900. currentVideoWidth = this.videoWidth;
  901. currentVideoHeight = this.videoHeight;
  902. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  903. });
  904. if (!$('#settings').is(':visible')) {
  905. console.log('init');
  906. init();
  907. } else {
  908. loginInfo.onsubmit = function (e) {
  909. if (e.preventDefault) e.preventDefault();
  910. $('#settings').hide();
  911. init();
  912. };
  913. }
  914. });
  915. $(window).bind('beforeunload', function () {
  916. if (connection && connection.connected) {
  917. // ensure signout
  918. $.ajax({
  919. type: 'POST',
  920. url: config.bosh,
  921. async: false,
  922. cache: false,
  923. contentType: 'application/xml',
  924. 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>",
  925. success: function (data) {
  926. console.log('signed out');
  927. console.log(data);
  928. },
  929. error: function (XMLHttpRequest, textStatus, errorThrown) {
  930. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  931. }
  932. });
  933. }
  934. disposeConference(true);
  935. });
  936. function disposeConference(onUnload) {
  937. var handler = getConferenceHandler();
  938. if (handler && handler.peerconnection) {
  939. // FIXME: probably removing streams is not required and close() should be enough
  940. if (connection.jingle.localAudio) {
  941. handler.peerconnection.removeStream(connection.jingle.localAudio);
  942. }
  943. if (connection.jingle.localVideo) {
  944. handler.peerconnection.removeStream(connection.jingle.localVideo);
  945. }
  946. handler.peerconnection.close();
  947. }
  948. if (statsCollector)
  949. {
  950. statsCollector.stop();
  951. statsCollector = null;
  952. }
  953. if(!onUnload) {
  954. startLocalRtpStatsCollector(connection.jingle.localAudio);
  955. }
  956. else
  957. {
  958. stopLocalRtpStatsCollector();
  959. }
  960. focus = null;
  961. activecall = null;
  962. }
  963. function dump(elem, filename) {
  964. elem = elem.parentNode;
  965. elem.download = filename || 'meetlog.json';
  966. elem.href = 'data:application/json;charset=utf-8,\n';
  967. var data = {};
  968. if (connection.jingle) {
  969. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  970. var session = connection.jingle.sessions[sid];
  971. if (session.peerconnection && session.peerconnection.updateLog) {
  972. // FIXME: should probably be a .dump call
  973. data["jingle_" + session.sid] = {
  974. updateLog: session.peerconnection.updateLog,
  975. stats: session.peerconnection.stats,
  976. url: window.location.href
  977. };
  978. }
  979. });
  980. }
  981. metadata = {};
  982. metadata.time = new Date();
  983. metadata.url = window.location.href;
  984. metadata.ua = navigator.userAgent;
  985. if (connection.logger) {
  986. metadata.xmpp = connection.logger.log;
  987. }
  988. data.metadata = metadata;
  989. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  990. return false;
  991. }
  992. /**
  993. * Changes the style class of the element given by id.
  994. */
  995. function buttonClick(id, classname) {
  996. $(id).toggleClass(classname); // add the class to the clicked element
  997. }
  998. /**
  999. * Shows a message to the user.
  1000. *
  1001. * @param titleString the title of the message
  1002. * @param messageString the text of the message
  1003. */
  1004. function openMessageDialog(titleString, messageString) {
  1005. $.prompt(messageString,
  1006. {
  1007. title: titleString,
  1008. persistent: false
  1009. }
  1010. );
  1011. }
  1012. /**
  1013. * Locks / unlocks the room.
  1014. */
  1015. function lockRoom(lock) {
  1016. if (lock)
  1017. connection.emuc.lockRoom(sharedKey);
  1018. else
  1019. connection.emuc.lockRoom('');
  1020. Toolbar.updateLockButton();
  1021. }
  1022. /**
  1023. * Sets the shared key.
  1024. */
  1025. function setSharedKey(sKey) {
  1026. sharedKey = sKey;
  1027. }
  1028. function setRecordingToken(token) {
  1029. recordingToken = token;
  1030. }
  1031. /**
  1032. * Updates the room invite url.
  1033. */
  1034. function updateRoomUrl(newRoomUrl) {
  1035. roomUrl = newRoomUrl;
  1036. // If the invite dialog has been already opened we update the information.
  1037. var inviteLink = document.getElementById('inviteLinkRef');
  1038. if (inviteLink) {
  1039. inviteLink.value = roomUrl;
  1040. inviteLink.select();
  1041. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  1042. }
  1043. }
  1044. /**
  1045. * Warning to the user that the conference window is about to be closed.
  1046. */
  1047. function closePageWarning() {
  1048. if (focus !== null)
  1049. return "You are the owner of this conference call and"
  1050. + " you are about to end it.";
  1051. else
  1052. return "You are about to leave this conversation.";
  1053. }
  1054. /**
  1055. * Resizes and repositions videos in full screen mode.
  1056. */
  1057. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1058. function () {
  1059. VideoLayout.resizeLargeVideoContainer();
  1060. VideoLayout.positionLarge();
  1061. isFullScreen = document.fullScreen ||
  1062. document.mozFullScreen ||
  1063. document.webkitIsFullScreen;
  1064. if (isFullScreen) {
  1065. setView("fullscreen");
  1066. }
  1067. else {
  1068. setView("default");
  1069. }
  1070. }
  1071. );
  1072. /**
  1073. * Sets the current view.
  1074. */
  1075. function setView(viewName) {
  1076. // if (viewName == "fullscreen") {
  1077. // document.getElementById('videolayout_fullscreen').disabled = false;
  1078. // document.getElementById('videolayout_default').disabled = true;
  1079. // }
  1080. // else {
  1081. // document.getElementById('videolayout_default').disabled = false;
  1082. // document.getElementById('videolayout_fullscreen').disabled = true;
  1083. // }
  1084. }
  1085. function showRecordingButton(show) {
  1086. if (!config.enableRecording) {
  1087. return;
  1088. }
  1089. if (show) {
  1090. $('#recording').css({display: "inline"});
  1091. }
  1092. else {
  1093. $('#recording').css({display: "none"});
  1094. }
  1095. }
  1096. $(document).bind('fatalError.jingle',
  1097. function (event, session, error)
  1098. {
  1099. sessionTerminated = true;
  1100. connection.emuc.doLeave();
  1101. openMessageDialog( "Sorry",
  1102. "Your browser version is too old. Please update and try again...");
  1103. }
  1104. );