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

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