您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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