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.

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