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

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