You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.js 50KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588
  1. /* jshint -W117 */
  2. /* application specific logic */
  3. var connection = null;
  4. var authenticatedUser = false;
  5. var focus = null;
  6. var activecall = null;
  7. var RTC = null;
  8. var nickname = null;
  9. var sharedKey = '';
  10. var recordingToken ='';
  11. var roomUrl = null;
  12. var roomName = null;
  13. var ssrc2jid = {};
  14. var mediaStreams = [];
  15. var bridgeIsDown = false;
  16. /**
  17. * The stats collector that process stats data and triggers updates to app.js.
  18. * @type {StatsCollector}
  19. */
  20. var statsCollector = null;
  21. /**
  22. * The stats collector for the local stream.
  23. * @type {LocalStatsCollector}
  24. */
  25. var localStatsCollector = null;
  26. /**
  27. * Indicates whether ssrc is camera video or desktop stream.
  28. * FIXME: remove those maps
  29. */
  30. var ssrc2videoType = {};
  31. var videoSrcToSsrc = {};
  32. /**
  33. * Currently focused video "src"(displayed in large video).
  34. * @type {String}
  35. */
  36. var focusedVideoSrc = null;
  37. var mutedAudios = {};
  38. var localVideoSrc = null;
  39. var flipXLocalVideo = true;
  40. var isFullScreen = false;
  41. var currentVideoWidth = null;
  42. var currentVideoHeight = null;
  43. /**
  44. * Method used to calculate large video size.
  45. * @type {function ()}
  46. */
  47. var getVideoSize;
  48. /**
  49. * Method used to get large video position.
  50. * @type {function ()}
  51. */
  52. var getVideoPosition;
  53. /* window.onbeforeunload = closePageWarning; */
  54. var sessionTerminated = false;
  55. function init() {
  56. Toolbar.setupButtonsFromConfig();
  57. RTC = setupRTC();
  58. if (RTC === null) {
  59. window.location.href = 'webrtcrequired.html';
  60. return;
  61. } else if (RTC.browser !== 'chrome') {
  62. window.location.href = 'chromeonly.html';
  63. return;
  64. }
  65. obtainAudioAndVideoPermissions(function (stream) {
  66. var audioStream = new webkitMediaStream();
  67. var videoStream = new webkitMediaStream();
  68. var audioTracks = stream.getAudioTracks();
  69. var videoTracks = stream.getVideoTracks();
  70. for (var i = 0; i < audioTracks.length; i++) {
  71. audioStream.addTrack(audioTracks[i]);
  72. }
  73. VideoLayout.changeLocalAudio(audioStream);
  74. startLocalRtpStatsCollector(audioStream);
  75. for (i = 0; i < videoTracks.length; i++) {
  76. videoStream.addTrack(videoTracks[i]);
  77. }
  78. VideoLayout.changeLocalVideo(videoStream, true);
  79. maybeDoJoin();
  80. });
  81. var jid = document.getElementById('jid').value || config.hosts.anonymousdomain || config.hosts.domain || window.location.hostname;
  82. connect(jid);
  83. }
  84. function connect(jid, password) {
  85. var localAudio, localVideo;
  86. if (connection && connection.jingle) {
  87. localAudio = connection.jingle.localAudio;
  88. localVideo = connection.jingle.localVideo;
  89. }
  90. connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
  91. if (nickname) {
  92. connection.emuc.addDisplayNameToPresence(nickname);
  93. }
  94. if (connection.disco) {
  95. // for chrome, add multistream cap
  96. }
  97. connection.jingle.pc_constraints = RTC.pc_constraints;
  98. if (config.useIPv6) {
  99. // https://code.google.com/p/webrtc/issues/detail?id=2828
  100. if (!connection.jingle.pc_constraints.optional) connection.jingle.pc_constraints.optional = [];
  101. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  102. }
  103. if (localAudio) connection.jingle.localAudio = localAudio;
  104. if (localVideo) connection.jingle.localVideo = localVideo;
  105. if(!password)
  106. password = document.getElementById('password').value;
  107. var anonymousConnectionFailed = false;
  108. connection.connect(jid, password, function (status, msg) {
  109. if (status === Strophe.Status.CONNECTED) {
  110. console.log('connected');
  111. if (config.useStunTurn) {
  112. connection.jingle.getStunAndTurnCredentials();
  113. }
  114. document.getElementById('connect').disabled = true;
  115. if(password)
  116. authenticatedUser = true;
  117. maybeDoJoin();
  118. } else if (status === Strophe.Status.CONNFAIL) {
  119. if(msg === 'x-strophe-bad-non-anon-jid') {
  120. anonymousConnectionFailed = true;
  121. }
  122. console.log('status', status);
  123. } else if (status === Strophe.Status.DISCONNECTED) {
  124. if(anonymousConnectionFailed) {
  125. // prompt user for username and password
  126. $(document).trigger('passwordrequired.main');
  127. }
  128. } else if (status === Strophe.Status.AUTHFAIL) {
  129. // wrong password or username, prompt user
  130. $(document).trigger('passwordrequired.main');
  131. } else {
  132. console.log('status', status);
  133. }
  134. });
  135. }
  136. /**
  137. * We ask for audio and video combined stream in order to get permissions and
  138. * not to ask twice.
  139. */
  140. function obtainAudioAndVideoPermissions(callback) {
  141. // Get AV
  142. getUserMediaWithConstraints(
  143. ['audio', 'video'],
  144. function (avStream) {
  145. callback(avStream);
  146. trackUsage('localMedia', {
  147. audio: avStream.getAudioTracks().length,
  148. video: avStream.getVideoTracks().length
  149. });
  150. },
  151. function (error) {
  152. console.error('failed to obtain audio/video stream - stop', error);
  153. trackUsage('localMediaError', {
  154. media: error.media || 'video',
  155. name : error.name
  156. });
  157. messageHandler.showError("Error",
  158. "Failed to obtain permissions to use the local microphone" +
  159. "and/or camera.");
  160. },
  161. config.resolution || '360');
  162. }
  163. function maybeDoJoin() {
  164. if (connection && connection.connected && Strophe.getResourceFromJid(connection.jid) // .connected is true while connecting?
  165. && (connection.jingle.localAudio || connection.jingle.localVideo)) {
  166. doJoin();
  167. }
  168. }
  169. function doJoin() {
  170. var roomnode = null;
  171. var path = window.location.pathname;
  172. var roomjid;
  173. // determinde the room node from the url
  174. // TODO: just the roomnode or the whole bare jid?
  175. if (config.getroomnode && typeof config.getroomnode === 'function') {
  176. // custom function might be responsible for doing the pushstate
  177. roomnode = config.getroomnode(path);
  178. } else {
  179. /* fall back to default strategy
  180. * this is making assumptions about how the URL->room mapping happens.
  181. * It currently assumes deployment at root, with a rewrite like the
  182. * following one (for nginx):
  183. location ~ ^/([a-zA-Z0-9]+)$ {
  184. rewrite ^/(.*)$ / break;
  185. }
  186. */
  187. if (path.length > 1) {
  188. roomnode = path.substr(1).toLowerCase();
  189. } else {
  190. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  191. roomnode = word.toLowerCase();
  192. window.history.pushState('VideoChat',
  193. 'Room: ' + word, window.location.pathname + word);
  194. }
  195. }
  196. roomName = roomnode + '@' + config.hosts.muc;
  197. roomjid = roomName;
  198. if (config.useNicks) {
  199. var nick = window.prompt('Your nickname (optional)');
  200. if (nick) {
  201. roomjid += '/' + nick;
  202. } else {
  203. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  204. }
  205. } else {
  206. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  207. if(!authenticatedUser)
  208. tmpJid = tmpJid.substr(0, 8);
  209. roomjid += '/' + tmpJid;
  210. }
  211. connection.emuc.doJoin(roomjid);
  212. }
  213. function waitForRemoteVideo(selector, ssrc, stream) {
  214. if (selector.removed || !selector.parent().is(":visible")) {
  215. console.warn("Media removed before had started", selector);
  216. return;
  217. }
  218. if (stream.id === 'mixedmslabel') return;
  219. if (selector[0].currentTime > 0) {
  220. var simulcast = new Simulcast();
  221. var videoStream = simulcast.getReceivingVideoStream(stream);
  222. RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  223. // FIXME: add a class that will associate peer Jid, video.src, it's ssrc and video type
  224. // in order to get rid of too many maps
  225. if (ssrc && selector.attr('src')) {
  226. videoSrcToSsrc[selector.attr('src')] = ssrc;
  227. } else {
  228. console.warn("No ssrc given for video", selector);
  229. messageHandler.showError('Warning', 'No ssrc was given for the video.');
  230. }
  231. $(document).trigger('videoactive.jingle', [selector]);
  232. } else {
  233. setTimeout(function () {
  234. waitForRemoteVideo(selector, ssrc, stream);
  235. }, 250);
  236. }
  237. }
  238. $(document).bind('remotestreamadded.jingle', function (event, data, sid) {
  239. waitForPresence(data, sid);
  240. });
  241. function waitForPresence(data, sid) {
  242. var sess = connection.jingle.sessions[sid];
  243. var thessrc;
  244. // look up an associated JID for a stream id
  245. if (data.stream.id.indexOf('mixedmslabel') === -1) {
  246. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  247. var ssrclines
  248. = SDPUtil.find_lines(sess.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  249. ssrclines = ssrclines.filter(function (line) {
  250. // NOTE(gp) previously we filtered on the mslabel, but that property
  251. // is not always present.
  252. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  253. return line.indexOf('msid:' + data.stream.id) !== -1;
  254. });
  255. if (ssrclines.length) {
  256. thessrc = ssrclines[0].substring(7).split(' ')[0];
  257. // We signal our streams (through Jingle to the focus) before we set
  258. // our presence (through which peers associate remote streams to
  259. // jids). So, it might arrive that a remote stream is added but
  260. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  261. // successfully set. Here we wait for up to a second for the
  262. // presence to arrive.
  263. if (!ssrc2jid[thessrc]) {
  264. // TODO(gp) limit wait duration to 1 sec.
  265. setTimeout(function(d, s) {
  266. return function() {
  267. waitForPresence(d, s);
  268. }
  269. }(data, sid), 250);
  270. return;
  271. }
  272. // ok to overwrite the one from focus? might save work in colibri.js
  273. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  274. if (ssrc2jid[thessrc]) {
  275. data.peerjid = ssrc2jid[thessrc];
  276. }
  277. }
  278. }
  279. // NOTE(gp) now that we have simulcast, a media stream can have more than 1
  280. // ssrc. We should probably take that into account in our MediaStream
  281. // wrapper.
  282. mediaStreams.push(new MediaStream(data, sid, thessrc));
  283. var container;
  284. var remotes = document.getElementById('remoteVideos');
  285. if (data.peerjid) {
  286. VideoLayout.ensurePeerContainerExists(data.peerjid);
  287. container = document.getElementById(
  288. 'participant_' + Strophe.getResourceFromJid(data.peerjid));
  289. } else {
  290. if (data.stream.id !== 'mixedmslabel') {
  291. console.error('can not associate stream',
  292. data.stream.id,
  293. 'with a participant');
  294. messageHandler.showError('Oops',
  295. 'We could not associate the current stream with a participant.');
  296. // We don't want to add it here since it will cause troubles
  297. return;
  298. }
  299. // FIXME: for the mixed ms we dont need a video -- currently
  300. container = document.createElement('span');
  301. container.id = 'mixedstream';
  302. container.className = 'videocontainer';
  303. remotes.appendChild(container);
  304. Util.playSoundNotification('userJoined');
  305. }
  306. var isVideo = data.stream.getVideoTracks().length > 0;
  307. if (container) {
  308. VideoLayout.addRemoteStreamElement( container,
  309. sid,
  310. data.stream,
  311. data.peerjid,
  312. thessrc);
  313. }
  314. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  315. if (isVideo &&
  316. data.peerjid && sess.peerjid === data.peerjid &&
  317. data.stream.getVideoTracks().length === 0 &&
  318. connection.jingle.localVideo.getVideoTracks().length > 0) {
  319. //
  320. window.setTimeout(function () {
  321. sendKeyframe(sess.peerconnection);
  322. }, 3000);
  323. }
  324. }
  325. /**
  326. * Returns the JID of the user to whom given <tt>videoSrc</tt> belongs.
  327. * @param videoSrc the video "src" identifier.
  328. * @returns {null | String} the JID of the user to whom given <tt>videoSrc</tt>
  329. * belongs.
  330. */
  331. function getJidFromVideoSrc(videoSrc)
  332. {
  333. if (videoSrc === localVideoSrc)
  334. return connection.emuc.myroomjid;
  335. var ssrc = videoSrcToSsrc[videoSrc];
  336. if (!ssrc)
  337. {
  338. return null;
  339. }
  340. return ssrc2jid[ssrc];
  341. }
  342. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  343. function sendKeyframe(pc) {
  344. console.log('sendkeyframe', pc.iceConnectionState);
  345. if (pc.iceConnectionState !== 'connected') return; // safe...
  346. pc.setRemoteDescription(
  347. pc.remoteDescription,
  348. function () {
  349. pc.createAnswer(
  350. function (modifiedAnswer) {
  351. pc.setLocalDescription(
  352. modifiedAnswer,
  353. function () {
  354. // noop
  355. },
  356. function (error) {
  357. console.log('triggerKeyframe setLocalDescription failed', error);
  358. messageHandler.showError();
  359. }
  360. );
  361. },
  362. function (error) {
  363. console.log('triggerKeyframe createAnswer failed', error);
  364. messageHandler.showError();
  365. }
  366. );
  367. },
  368. function (error) {
  369. console.log('triggerKeyframe setRemoteDescription failed', error);
  370. messageHandler.showError();
  371. }
  372. );
  373. }
  374. // Really mute video, i.e. dont even send black frames
  375. function muteVideo(pc, unmute) {
  376. // FIXME: this probably needs another of those lovely state safeguards...
  377. // which checks for iceconn == connected and sigstate == stable
  378. pc.setRemoteDescription(pc.remoteDescription,
  379. function () {
  380. pc.createAnswer(
  381. function (answer) {
  382. var sdp = new SDP(answer.sdp);
  383. if (sdp.media.length > 1) {
  384. if (unmute)
  385. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  386. else
  387. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  388. sdp.raw = sdp.session + sdp.media.join('');
  389. answer.sdp = sdp.raw;
  390. }
  391. pc.setLocalDescription(answer,
  392. function () {
  393. console.log('mute SLD ok');
  394. },
  395. function (error) {
  396. console.log('mute SLD error');
  397. messageHandler.showError('Error',
  398. 'Oops! Something went wrong and we failed to ' +
  399. 'mute! (SLD Failure)');
  400. }
  401. );
  402. },
  403. function (error) {
  404. console.log(error);
  405. messageHandler.showError();
  406. }
  407. );
  408. },
  409. function (error) {
  410. console.log('muteVideo SRD error');
  411. messageHandler.showError('Error',
  412. 'Oops! Something went wrong and we failed to stop video!' +
  413. '(SRD Failure)');
  414. }
  415. );
  416. }
  417. /**
  418. * Callback for audio levels changed.
  419. * @param jid JID of the user
  420. * @param audioLevel the audio level value
  421. */
  422. function audioLevelUpdated(jid, audioLevel)
  423. {
  424. var resourceJid;
  425. if(jid === LocalStatsCollector.LOCAL_JID)
  426. {
  427. resourceJid = AudioLevels.LOCAL_LEVEL;
  428. if(isAudioMuted())
  429. {
  430. audioLevel = 0;
  431. }
  432. }
  433. else
  434. {
  435. resourceJid = Strophe.getResourceFromJid(jid);
  436. }
  437. AudioLevels.updateAudioLevel(resourceJid, audioLevel);
  438. }
  439. /**
  440. * Starts the {@link StatsCollector} if the feature is enabled in config.js.
  441. */
  442. function startRtpStatsCollector()
  443. {
  444. stopRTPStatsCollector();
  445. if (config.enableRtpStats)
  446. {
  447. statsCollector = new StatsCollector(
  448. getConferenceHandler().peerconnection, 200, audioLevelUpdated);
  449. statsCollector.start();
  450. }
  451. }
  452. /**
  453. * Stops the {@link StatsCollector}.
  454. */
  455. function stopRTPStatsCollector()
  456. {
  457. if (statsCollector)
  458. {
  459. statsCollector.stop();
  460. statsCollector = null;
  461. }
  462. }
  463. /**
  464. * Starts the {@link LocalStatsCollector} if the feature is enabled in config.js
  465. * @param stream the stream that will be used for collecting statistics.
  466. */
  467. function startLocalRtpStatsCollector(stream)
  468. {
  469. if(config.enableRtpStats)
  470. {
  471. localStatsCollector = new LocalStatsCollector(stream, 100, audioLevelUpdated);
  472. localStatsCollector.start();
  473. }
  474. }
  475. /**
  476. * Stops the {@link LocalStatsCollector}.
  477. */
  478. function stopLocalRtpStatsCollector()
  479. {
  480. if(localStatsCollector)
  481. {
  482. localStatsCollector.stop();
  483. localStatsCollector = null;
  484. }
  485. }
  486. $(document).bind('callincoming.jingle', function (event, sid) {
  487. var sess = connection.jingle.sessions[sid];
  488. // TODO: do we check activecall == null?
  489. activecall = sess;
  490. startRtpStatsCollector();
  491. // Bind data channel listener in case we're a regular participant
  492. if (config.openSctp)
  493. {
  494. bindDataChannelListener(sess.peerconnection);
  495. }
  496. // TODO: check affiliation and/or role
  497. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  498. sess.usedrip = true; // not-so-naive trickle ice
  499. sess.sendAnswer();
  500. sess.accept();
  501. });
  502. $(document).bind('conferenceCreated.jingle', function (event, focus)
  503. {
  504. startRtpStatsCollector();
  505. });
  506. $(document).bind('conferenceCreated.jingle', function (event, focus)
  507. {
  508. // Bind data channel listener in case we're the focus
  509. if (config.openSctp)
  510. {
  511. bindDataChannelListener(focus.peerconnection);
  512. }
  513. });
  514. $(document).bind('callterminated.jingle', function (event, sid, jid, reason) {
  515. // Leave the room if my call has been remotely terminated.
  516. if (connection.emuc.joined && focus == null && reason === 'kick') {
  517. sessionTerminated = true;
  518. connection.emuc.doLeave();
  519. messageHandler.openMessageDialog("Session Terminated",
  520. "Ouch! You have been kicked out of the meet!");
  521. }
  522. });
  523. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  524. // put our ssrcs into presence so other clients can identify our stream
  525. var sess = connection.jingle.sessions[sid];
  526. var newssrcs = [];
  527. var simulcast = new Simulcast();
  528. var media = simulcast.parseMedia(sess.peerconnection.localDescription);
  529. media.forEach(function (media) {
  530. // TODO(gp) maybe exclude FID streams?
  531. Object.keys(media.sources).forEach(function(ssrc) {
  532. newssrcs.push({
  533. 'ssrc': ssrc,
  534. 'type': media.type,
  535. 'direction': media.direction
  536. });
  537. });
  538. });
  539. console.log('new ssrcs', newssrcs);
  540. // Have to clear presence map to get rid of removed streams
  541. connection.emuc.clearPresenceMedia();
  542. if (newssrcs.length > 0) {
  543. for (var i = 1; i <= newssrcs.length; i ++) {
  544. // Change video type to screen
  545. if (newssrcs[i-1].type === 'video' && isUsingScreenStream) {
  546. newssrcs[i-1].type = 'screen';
  547. }
  548. connection.emuc.addMediaToPresence(i,
  549. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  550. }
  551. connection.emuc.sendPresence();
  552. }
  553. });
  554. $(document).bind('iceconnectionstatechange.jingle', function (event, sid, session) {
  555. switch (session.peerconnection.iceConnectionState) {
  556. case 'checking':
  557. session.timeChecking = (new Date()).getTime();
  558. session.firstconnect = true;
  559. break;
  560. case 'completed': // on caller side
  561. case 'connected':
  562. if (session.firstconnect) {
  563. session.firstconnect = false;
  564. var metadata = {};
  565. metadata.setupTime = (new Date()).getTime() - session.timeChecking;
  566. session.peerconnection.getStats(function (res) {
  567. res.result().forEach(function (report) {
  568. if (report.type == 'googCandidatePair' && report.stat('googActiveConnection') == 'true') {
  569. metadata.localCandidateType = report.stat('googLocalCandidateType');
  570. metadata.remoteCandidateType = report.stat('googRemoteCandidateType');
  571. // log pair as well so we can get nice pie charts
  572. metadata.candidatePair = report.stat('googLocalCandidateType') + ';' + report.stat('googRemoteCandidateType');
  573. if (report.stat('googRemoteAddress').indexOf('[') === 0) {
  574. metadata.ipv6 = true;
  575. }
  576. }
  577. });
  578. trackUsage('iceConnected', metadata);
  579. });
  580. }
  581. break;
  582. }
  583. });
  584. $(document).bind('joined.muc', function (event, jid, info) {
  585. updateRoomUrl(window.location.href);
  586. document.getElementById('localNick').appendChild(
  587. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  588. );
  589. if (Object.keys(connection.emuc.members).length < 1) {
  590. focus = new ColibriFocus(connection, config.hosts.bridge);
  591. if (nickname !== null) {
  592. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  593. nickname);
  594. }
  595. Toolbar.showSipCallButton(true);
  596. Toolbar.showRecordingButton(false);
  597. }
  598. if (!focus)
  599. {
  600. Toolbar.showSipCallButton(false);
  601. }
  602. if (focus && config.etherpad_base) {
  603. Etherpad.init();
  604. }
  605. VideoLayout.showFocusIndicator();
  606. // Add myself to the contact list.
  607. ContactList.addContact(jid);
  608. // Once we've joined the muc show the toolbar
  609. ToolbarToggler.showToolbar();
  610. if (info.displayName)
  611. $(document).trigger('displaynamechanged',
  612. ['localVideoContainer', info.displayName + ' (me)']);
  613. });
  614. $(document).bind('entered.muc', function (event, jid, info, pres) {
  615. console.log('entered', jid, info);
  616. console.log('is focus? ' + (focus ? 'true' : 'false'));
  617. // Add Peer's container
  618. VideoLayout.ensurePeerContainerExists(jid);
  619. if (focus !== null) {
  620. // FIXME: this should prepare the video
  621. if (focus.confid === null) {
  622. console.log('make new conference with', jid);
  623. focus.makeConference(Object.keys(connection.emuc.members),
  624. function(error) {
  625. connection.emuc.addBridgeIsDownToPresence();
  626. connection.emuc.sendPresence();
  627. }
  628. );
  629. Toolbar.showRecordingButton(true);
  630. } else {
  631. console.log('invite', jid, 'into conference');
  632. focus.addNewParticipant(jid);
  633. }
  634. }
  635. else if (sharedKey) {
  636. Toolbar.updateLockButton();
  637. }
  638. });
  639. $(document).bind('left.muc', function (event, jid) {
  640. console.log('left.muc', jid);
  641. // Need to call this with a slight delay, otherwise the element couldn't be
  642. // found for some reason.
  643. window.setTimeout(function () {
  644. var container = document.getElementById(
  645. 'participant_' + Strophe.getResourceFromJid(jid));
  646. if (container) {
  647. // hide here, wait for video to close before removing
  648. $(container).hide();
  649. VideoLayout.resizeThumbnails();
  650. }
  651. }, 10);
  652. // Unlock large video
  653. if (focusedVideoSrc)
  654. {
  655. if (getJidFromVideoSrc(focusedVideoSrc) === jid)
  656. {
  657. console.info("Focused video owner has left the conference");
  658. focusedVideoSrc = null;
  659. }
  660. }
  661. connection.jingle.terminateByJid(jid);
  662. if (focus == null
  663. // I shouldn't be the one that left to enter here.
  664. && jid !== connection.emuc.myroomjid
  665. && connection.emuc.myroomjid === connection.emuc.list_members[0]
  666. // If our session has been terminated for some reason
  667. // (kicked, hangup), don't try to become the focus
  668. && !sessionTerminated) {
  669. console.log('welcome to our new focus... myself');
  670. focus = new ColibriFocus(connection, config.hosts.bridge);
  671. if (nickname !== null) {
  672. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  673. nickname);
  674. }
  675. Toolbar.showSipCallButton(true);
  676. if (Object.keys(connection.emuc.members).length > 0) {
  677. focus.makeConference(Object.keys(connection.emuc.members));
  678. Toolbar.showRecordingButton(true);
  679. }
  680. $(document).trigger('focusechanged.muc', [focus]);
  681. }
  682. else if (focus && Object.keys(connection.emuc.members).length === 0) {
  683. console.log('everyone left');
  684. // FIXME: closing the connection is a hack to avoid some
  685. // problems with reinit
  686. disposeConference();
  687. focus = new ColibriFocus(connection, config.hosts.bridge);
  688. if (nickname !== null) {
  689. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  690. nickname);
  691. }
  692. Toolbar.showSipCallButton(true);
  693. Toolbar.showRecordingButton(false);
  694. }
  695. if (connection.emuc.getPrezi(jid)) {
  696. $(document).trigger('presentationremoved.muc',
  697. [jid, connection.emuc.getPrezi(jid)]);
  698. }
  699. });
  700. $(document).bind('presence.muc', function (event, jid, info, pres) {
  701. // Remove old ssrcs coming from the jid
  702. Object.keys(ssrc2jid).forEach(function (ssrc) {
  703. if (ssrc2jid[ssrc] == jid) {
  704. delete ssrc2jid[ssrc];
  705. }
  706. if (ssrc2videoType[ssrc] == jid) {
  707. delete ssrc2videoType[ssrc];
  708. }
  709. });
  710. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  711. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  712. var ssrcV = ssrc.getAttribute('ssrc');
  713. ssrc2jid[ssrcV] = jid;
  714. var type = ssrc.getAttribute('type');
  715. ssrc2videoType[ssrcV] = type;
  716. // might need to update the direction if participant just went from sendrecv to recvonly
  717. if (type === 'video' || type === 'screen') {
  718. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  719. switch (ssrc.getAttribute('direction')) {
  720. case 'sendrecv':
  721. el.show();
  722. break;
  723. case 'recvonly':
  724. el.hide();
  725. // FIXME: Check if we have to change large video
  726. //VideoLayout.updateLargeVideo(el);
  727. break;
  728. }
  729. }
  730. });
  731. if (info.displayName && info.displayName.length > 0)
  732. $(document).trigger('displaynamechanged',
  733. [jid, info.displayName]);
  734. if (focus !== null && info.displayName !== null) {
  735. focus.setEndpointDisplayName(jid, info.displayName);
  736. }
  737. //check if the video bridge is available
  738. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  739. bridgeIsDown = true;
  740. messageHandler.showError("Error",
  741. "Jitsi Videobridge is currently unavailable. Please try again later!");
  742. }
  743. });
  744. $(document).bind('presence.status.muc', function (event, jid, info, pres) {
  745. VideoLayout.setPresenceStatus(
  746. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  747. });
  748. $(document).bind('passwordrequired.muc', function (event, jid) {
  749. console.log('on password required', jid);
  750. messageHandler.openTwoButtonDialog(null,
  751. '<h2>Password required</h2>' +
  752. '<input id="lockKey" type="text" placeholder="password" autofocus>',
  753. true,
  754. "Ok",
  755. function (e, v, m, f) {
  756. if (v) {
  757. var lockKey = document.getElementById('lockKey');
  758. if (lockKey.value !== null) {
  759. setSharedKey(lockKey.value);
  760. connection.emuc.doJoin(jid, lockKey.value);
  761. }
  762. }
  763. },
  764. function (event) {
  765. document.getElementById('lockKey').focus();
  766. }
  767. );
  768. });
  769. $(document).bind('passwordrequired.main', function (event) {
  770. console.log('password is required');
  771. messageHandler.openTwoButtonDialog(null,
  772. '<h2>Password required</h2>' +
  773. '<input id="passwordrequired.username" type="text" placeholder="user@domain.net" autofocus>' +
  774. '<input id="passwordrequired.password" type="password" placeholder="user password">',
  775. true,
  776. "Ok",
  777. function (e, v, m, f) {
  778. if (v) {
  779. var username = document.getElementById('passwordrequired.username');
  780. var password = document.getElementById('passwordrequired.password');
  781. if (username.value !== null && password.value != null) {
  782. connect(username.value, password.value);
  783. }
  784. }
  785. },
  786. function (event) {
  787. document.getElementById('passwordrequired.username').focus();
  788. }
  789. );
  790. });
  791. /**
  792. * Checks if video identified by given src is desktop stream.
  793. * @param videoSrc eg.
  794. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  795. * @returns {boolean}
  796. */
  797. function isVideoSrcDesktop(videoSrc) {
  798. // FIXME: fix this mapping mess...
  799. // figure out if large video is desktop stream or just a camera
  800. var isDesktop = false;
  801. if (localVideoSrc === videoSrc) {
  802. // local video
  803. isDesktop = isUsingScreenStream;
  804. } else {
  805. // Do we have associations...
  806. var videoSsrc = videoSrcToSsrc[videoSrc];
  807. if (videoSsrc) {
  808. var videoType = ssrc2videoType[videoSsrc];
  809. if (videoType) {
  810. // Finally there...
  811. isDesktop = videoType === 'screen';
  812. } else {
  813. console.error("No video type for ssrc: " + videoSsrc);
  814. }
  815. } else {
  816. console.error("No ssrc for src: " + videoSrc);
  817. }
  818. }
  819. return isDesktop;
  820. }
  821. function getConferenceHandler() {
  822. return focus ? focus : activecall;
  823. }
  824. function toggleVideo() {
  825. buttonClick("#video", "icon-camera icon-camera-disabled");
  826. if (!(connection && connection.jingle.localVideo))
  827. return;
  828. var sess = getConferenceHandler();
  829. if (sess) {
  830. sess.toggleVideoMute(
  831. function (isMuted) {
  832. if (isMuted) {
  833. $('#video').removeClass("icon-camera");
  834. $('#video').addClass("icon-camera icon-camera-disabled");
  835. } else {
  836. $('#video').removeClass("icon-camera icon-camera-disabled");
  837. $('#video').addClass("icon-camera");
  838. }
  839. connection.emuc.addVideoInfoToPresence(isMuted);
  840. connection.emuc.sendPresence();
  841. }
  842. );
  843. }
  844. }
  845. /**
  846. * Mutes / unmutes audio for the local participant.
  847. */
  848. function toggleAudio() {
  849. if (!(connection && connection.jingle.localAudio)) {
  850. preMuted = true;
  851. // We still click the button.
  852. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  853. return;
  854. }
  855. var localAudio = connection.jingle.localAudio;
  856. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  857. var audioEnabled = localAudio.getAudioTracks()[idx].enabled;
  858. localAudio.getAudioTracks()[idx].enabled = !audioEnabled;
  859. // isMuted is the opposite of audioEnabled
  860. connection.emuc.addAudioInfoToPresence(audioEnabled);
  861. connection.emuc.sendPresence();
  862. }
  863. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  864. }
  865. /**
  866. * Checks whether the audio is muted or not.
  867. * @returns {boolean} true if audio is muted and false if not.
  868. */
  869. function isAudioMuted()
  870. {
  871. var localAudio = connection.jingle.localAudio;
  872. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  873. if(localAudio.getAudioTracks()[idx].enabled === true)
  874. return false;
  875. }
  876. return true;
  877. }
  878. // Starts or stops the recording for the conference.
  879. function toggleRecording() {
  880. if (focus === null || focus.confid === null) {
  881. console.log('non-focus, or conference not yet organized: not enabling recording');
  882. return;
  883. }
  884. if (!recordingToken)
  885. {
  886. messageHandler.openTwoButtonDialog(null,
  887. '<h2>Enter recording token</h2>' +
  888. '<input id="recordingToken" type="text" placeholder="token" autofocus>',
  889. false,
  890. "Save",
  891. function (e, v, m, f) {
  892. if (v) {
  893. var token = document.getElementById('recordingToken');
  894. if (token.value) {
  895. setRecordingToken(Util.escapeHtml(token.value));
  896. toggleRecording();
  897. }
  898. }
  899. },
  900. function (event) {
  901. document.getElementById('recordingToken').focus();
  902. }
  903. );
  904. return;
  905. }
  906. var oldState = focus.recordingEnabled;
  907. Toolbar.toggleRecordingButtonState();
  908. focus.setRecording(!oldState,
  909. recordingToken,
  910. function (state) {
  911. console.log("New recording state: ", state);
  912. if (state == oldState) //failed to change, reset the token because it might have been wrong
  913. {
  914. Toolbar.toggleRecordingButtonState();
  915. setRecordingToken(null);
  916. }
  917. }
  918. );
  919. }
  920. /**
  921. * Returns an array of the video horizontal and vertical indents,
  922. * so that if fits its parent.
  923. *
  924. * @return an array with 2 elements, the horizontal indent and the vertical
  925. * indent
  926. */
  927. function getCameraVideoPosition(videoWidth,
  928. videoHeight,
  929. videoSpaceWidth,
  930. videoSpaceHeight) {
  931. // Parent height isn't completely calculated when we position the video in
  932. // full screen mode and this is why we use the screen height in this case.
  933. // Need to think it further at some point and implement it properly.
  934. var isFullScreen = document.fullScreen ||
  935. document.mozFullScreen ||
  936. document.webkitIsFullScreen;
  937. if (isFullScreen)
  938. videoSpaceHeight = window.innerHeight;
  939. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  940. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  941. return [horizontalIndent, verticalIndent];
  942. }
  943. /**
  944. * Returns an array of the video horizontal and vertical indents.
  945. * Centers horizontally and top aligns vertically.
  946. *
  947. * @return an array with 2 elements, the horizontal indent and the vertical
  948. * indent
  949. */
  950. function getDesktopVideoPosition(videoWidth,
  951. videoHeight,
  952. videoSpaceWidth,
  953. videoSpaceHeight) {
  954. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  955. var verticalIndent = 0;// Top aligned
  956. return [horizontalIndent, verticalIndent];
  957. }
  958. /**
  959. * Returns an array of the video dimensions, so that it covers the screen.
  960. * It leaves no empty areas, but some parts of the video might not be visible.
  961. *
  962. * @return an array with 2 elements, the video width and the video height
  963. */
  964. function getCameraVideoSize(videoWidth,
  965. videoHeight,
  966. videoSpaceWidth,
  967. videoSpaceHeight) {
  968. if (!videoWidth)
  969. videoWidth = currentVideoWidth;
  970. if (!videoHeight)
  971. videoHeight = currentVideoHeight;
  972. var aspectRatio = videoWidth / videoHeight;
  973. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  974. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  975. if (availableWidth / aspectRatio < videoSpaceHeight) {
  976. availableHeight = videoSpaceHeight;
  977. availableWidth = availableHeight * aspectRatio;
  978. }
  979. if (availableHeight * aspectRatio < videoSpaceWidth) {
  980. availableWidth = videoSpaceWidth;
  981. availableHeight = availableWidth / aspectRatio;
  982. }
  983. return [availableWidth, availableHeight];
  984. }
  985. $(document).ready(function () {
  986. document.title = brand.appName;
  987. if(config.enableWelcomePage && window.location.pathname == "/" &&
  988. (!window.localStorage.welcomePageDisabled
  989. || window.localStorage.welcomePageDisabled == "false"))
  990. {
  991. $("#videoconference_page").hide();
  992. $("#domain_name").text(
  993. window.location.protocol + "//" + window.location.host + "/");
  994. $("span[name='appName']").text(brand.appName);
  995. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  996. var leftWatermarkDiv
  997. = $("#welcome_page_header div[class='watermark leftwatermark']");
  998. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  999. {
  1000. leftWatermarkDiv.css({display: 'block'});
  1001. leftWatermarkDiv.parent().get(0).href
  1002. = interfaceConfig.JITSI_WATERMARK_LINK;
  1003. }
  1004. }
  1005. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1006. var rightWatermarkDiv
  1007. = $("#welcome_page_header div[class='watermark rightwatermark']");
  1008. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  1009. rightWatermarkDiv.css({display: 'block'});
  1010. rightWatermarkDiv.parent().get(0).href
  1011. = interfaceConfig.BRAND_WATERMARK_LINK;
  1012. rightWatermarkDiv.get(0).style.backgroundImage
  1013. = "url(images/rightwatermark.png)";
  1014. }
  1015. }
  1016. if (interfaceConfig.SHOW_POWERED_BY) {
  1017. $("#welcome_page_header>a[class='poweredby']")
  1018. .css({display: 'block'});
  1019. }
  1020. function enter_room()
  1021. {
  1022. var val = $("#enter_room_field").val();
  1023. if(!val) {
  1024. val = $("#enter_room_field").attr("room_name");
  1025. }
  1026. if (val) {
  1027. window.location.pathname = "/" + val;
  1028. }
  1029. }
  1030. $("#enter_room_button").click(function()
  1031. {
  1032. enter_room();
  1033. });
  1034. $("#enter_room_field").keydown(function (event) {
  1035. if (event.keyCode === 13 /* enter */) {
  1036. enter_room();
  1037. }
  1038. });
  1039. if (interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE){
  1040. var updateTimeout;
  1041. var animateTimeout;
  1042. $("#reload_roomname").click(function () {
  1043. clearTimeout(updateTimeout);
  1044. clearTimeout(animateTimeout);
  1045. update_roomname();
  1046. });
  1047. $("#reload_roomname").show();
  1048. function animate(word) {
  1049. var currentVal = $("#enter_room_field").attr("placeholder");
  1050. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  1051. animateTimeout = setTimeout(function() {
  1052. animate(word.substring(1, word.length))
  1053. }, 70);
  1054. }
  1055. function update_roomname()
  1056. {
  1057. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1058. $("#enter_room_field").attr("room_name", word);
  1059. $("#enter_room_field").attr("placeholder", "");
  1060. clearTimeout(animateTimeout);
  1061. animate(word);
  1062. updateTimeout = setTimeout(update_roomname, 10000);
  1063. }
  1064. update_roomname();
  1065. }
  1066. $("#disable_welcome").click(function () {
  1067. window.localStorage.welcomePageDisabled
  1068. = $("#disable_welcome").is(":checked");
  1069. });
  1070. return;
  1071. }
  1072. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1073. var leftWatermarkDiv
  1074. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1075. leftWatermarkDiv.css({display: 'block'});
  1076. leftWatermarkDiv.parent().get(0).href
  1077. = interfaceConfig.JITSI_WATERMARK_LINK;
  1078. }
  1079. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1080. var rightWatermarkDiv
  1081. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1082. rightWatermarkDiv.css({display: 'block'});
  1083. rightWatermarkDiv.parent().get(0).href
  1084. = interfaceConfig.BRAND_WATERMARK_LINK;
  1085. rightWatermarkDiv.get(0).style.backgroundImage
  1086. = "url(images/rightwatermark.png)";
  1087. }
  1088. if (interfaceConfig.SHOW_POWERED_BY) {
  1089. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1090. }
  1091. $("#welcome_page").hide();
  1092. Chat.init();
  1093. $('body').popover({ selector: '[data-toggle=popover]',
  1094. trigger: 'click hover',
  1095. content: function() {
  1096. return this.getAttribute("content") +
  1097. KeyboardShortcut.getShortcut(this.getAttribute("shortcut"));
  1098. }
  1099. });
  1100. // Set the defaults for prompt dialogs.
  1101. jQuery.prompt.setDefaults({persistent: false});
  1102. // Set default desktop sharing method
  1103. setDesktopSharing(config.desktopSharing);
  1104. // Initialize Chrome extension inline installs
  1105. if (config.chromeExtensionId) {
  1106. initInlineInstalls();
  1107. }
  1108. // By default we use camera
  1109. getVideoSize = getCameraVideoSize;
  1110. getVideoPosition = getCameraVideoPosition;
  1111. VideoLayout.resizeLargeVideoContainer();
  1112. $(window).resize(function () {
  1113. VideoLayout.resizeLargeVideoContainer();
  1114. VideoLayout.positionLarge();
  1115. });
  1116. // Listen for large video size updates
  1117. document.getElementById('largeVideo')
  1118. .addEventListener('loadedmetadata', function (e) {
  1119. currentVideoWidth = this.videoWidth;
  1120. currentVideoHeight = this.videoHeight;
  1121. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  1122. });
  1123. if (!$('#settings').is(':visible')) {
  1124. console.log('init');
  1125. init();
  1126. } else {
  1127. loginInfo.onsubmit = function (e) {
  1128. if (e.preventDefault) e.preventDefault();
  1129. $('#settings').hide();
  1130. init();
  1131. };
  1132. }
  1133. });
  1134. $(window).bind('beforeunload', function () {
  1135. if (connection && connection.connected) {
  1136. // ensure signout
  1137. $.ajax({
  1138. type: 'POST',
  1139. url: config.bosh,
  1140. async: false,
  1141. cache: false,
  1142. contentType: 'application/xml',
  1143. data: "<body rid='" + (connection.rid || connection._proto.rid)
  1144. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  1145. + (connection.sid || connection._proto.sid)
  1146. + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  1147. success: function (data) {
  1148. console.log('signed out');
  1149. console.log(data);
  1150. },
  1151. error: function (XMLHttpRequest, textStatus, errorThrown) {
  1152. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  1153. }
  1154. });
  1155. }
  1156. disposeConference(true);
  1157. });
  1158. function disposeConference(onUnload) {
  1159. var handler = getConferenceHandler();
  1160. if (handler && handler.peerconnection) {
  1161. // FIXME: probably removing streams is not required and close() should
  1162. // be enough
  1163. if (connection.jingle.localAudio) {
  1164. handler.peerconnection.removeStream(connection.jingle.localAudio);
  1165. }
  1166. if (connection.jingle.localVideo) {
  1167. handler.peerconnection.removeStream(connection.jingle.localVideo);
  1168. }
  1169. handler.peerconnection.close();
  1170. }
  1171. stopRTPStatsCollector();
  1172. if(onUnload) {
  1173. stopLocalRtpStatsCollector();
  1174. }
  1175. focus = null;
  1176. activecall = null;
  1177. }
  1178. function dump(elem, filename) {
  1179. elem = elem.parentNode;
  1180. elem.download = filename || 'meetlog.json';
  1181. elem.href = 'data:application/json;charset=utf-8,\n';
  1182. var data = populateData();
  1183. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1184. return false;
  1185. }
  1186. /**
  1187. * Populates the log data
  1188. */
  1189. function populateData() {
  1190. var data = {};
  1191. if (connection.jingle) {
  1192. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  1193. var session = connection.jingle.sessions[sid];
  1194. if (session.peerconnection && session.peerconnection.updateLog) {
  1195. // FIXME: should probably be a .dump call
  1196. data["jingle_" + session.sid] = {
  1197. updateLog: session.peerconnection.updateLog,
  1198. stats: session.peerconnection.stats,
  1199. url: window.location.href
  1200. };
  1201. }
  1202. });
  1203. }
  1204. var metadata = {};
  1205. metadata.time = new Date();
  1206. metadata.url = window.location.href;
  1207. metadata.ua = navigator.userAgent;
  1208. if (connection.logger) {
  1209. metadata.xmpp = connection.logger.log;
  1210. }
  1211. data.metadata = metadata;
  1212. return data;
  1213. }
  1214. /**
  1215. * Changes the style class of the element given by id.
  1216. */
  1217. function buttonClick(id, classname) {
  1218. $(id).toggleClass(classname); // add the class to the clicked element
  1219. }
  1220. /**
  1221. * Locks / unlocks the room.
  1222. */
  1223. function lockRoom(lock) {
  1224. if (lock)
  1225. connection.emuc.lockRoom(sharedKey);
  1226. else
  1227. connection.emuc.lockRoom('');
  1228. Toolbar.updateLockButton();
  1229. }
  1230. /**
  1231. * Sets the shared key.
  1232. */
  1233. function setSharedKey(sKey) {
  1234. sharedKey = sKey;
  1235. }
  1236. function setRecordingToken(token) {
  1237. recordingToken = token;
  1238. }
  1239. /**
  1240. * Updates the room invite url.
  1241. */
  1242. function updateRoomUrl(newRoomUrl) {
  1243. roomUrl = newRoomUrl;
  1244. // If the invite dialog has been already opened we update the information.
  1245. var inviteLink = document.getElementById('inviteLinkRef');
  1246. if (inviteLink) {
  1247. inviteLink.value = roomUrl;
  1248. inviteLink.select();
  1249. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  1250. }
  1251. }
  1252. /**
  1253. * Warning to the user that the conference window is about to be closed.
  1254. */
  1255. function closePageWarning() {
  1256. if (focus !== null)
  1257. return "You are the owner of this conference call and"
  1258. + " you are about to end it.";
  1259. else
  1260. return "You are about to leave this conversation.";
  1261. }
  1262. /**
  1263. * Resizes and repositions videos in full screen mode.
  1264. */
  1265. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1266. function () {
  1267. VideoLayout.resizeLargeVideoContainer();
  1268. VideoLayout.positionLarge();
  1269. isFullScreen = document.fullScreen ||
  1270. document.mozFullScreen ||
  1271. document.webkitIsFullScreen;
  1272. if (isFullScreen) {
  1273. setView("fullscreen");
  1274. }
  1275. else {
  1276. setView("default");
  1277. }
  1278. }
  1279. );
  1280. /**
  1281. * Sets the current view.
  1282. */
  1283. function setView(viewName) {
  1284. // if (viewName == "fullscreen") {
  1285. // document.getElementById('videolayout_fullscreen').disabled = false;
  1286. // document.getElementById('videolayout_default').disabled = true;
  1287. // }
  1288. // else {
  1289. // document.getElementById('videolayout_default').disabled = false;
  1290. // document.getElementById('videolayout_fullscreen').disabled = true;
  1291. // }
  1292. }
  1293. function hangUp() {
  1294. if (connection && connection.connected) {
  1295. // ensure signout
  1296. $.ajax({
  1297. type: 'POST',
  1298. url: config.bosh,
  1299. async: false,
  1300. cache: false,
  1301. contentType: 'application/xml',
  1302. 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>",
  1303. success: function (data) {
  1304. console.log('signed out');
  1305. console.log(data);
  1306. },
  1307. error: function (XMLHttpRequest, textStatus, errorThrown) {
  1308. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  1309. }
  1310. });
  1311. }
  1312. disposeConference(true);
  1313. }
  1314. $(document).bind('fatalError.jingle',
  1315. function (event, session, error)
  1316. {
  1317. sessionTerminated = true;
  1318. connection.emuc.doLeave();
  1319. messageHandler.showError( "Sorry",
  1320. "Your browser version is too old. Please update and try again...");
  1321. }
  1322. );
  1323. function onSelectedEndpointChanged(userJid)
  1324. {
  1325. console.log('selected endpoint changed: ', userJid);
  1326. if (_dataChannels && _dataChannels.length != 0)
  1327. {
  1328. _dataChannels.some(function (dataChannel) {
  1329. if (dataChannel.readyState == 'open')
  1330. {
  1331. dataChannel.send(JSON.stringify({
  1332. 'colibriClass': 'SelectedEndpointChangedEvent',
  1333. 'selectedEndpoint': (!userJid || userJid == null)
  1334. ? null : Strophe.getResourceFromJid(userJid)
  1335. }));
  1336. return true;
  1337. }
  1338. });
  1339. }
  1340. }
  1341. $(document).bind("selectedendpointchanged", function(event, userJid) {
  1342. onSelectedEndpointChanged(userJid);
  1343. });
  1344. function callSipButtonClicked()
  1345. {
  1346. var defaultNumber
  1347. = config.defaultSipNumber ? config.defaultSipNumber : '';
  1348. messageHandler.openTwoButtonDialog(null,
  1349. '<h2>Enter SIP number</h2>' +
  1350. '<input id="sipNumber" type="text"' +
  1351. ' value="' + defaultNumber + '" autofocus>',
  1352. false,
  1353. "Dial",
  1354. function (e, v, m, f) {
  1355. if (v) {
  1356. var numberInput = document.getElementById('sipNumber');
  1357. if (numberInput.value) {
  1358. connection.rayo.dial(
  1359. numberInput.value, 'fromnumber', roomName);
  1360. }
  1361. }
  1362. },
  1363. function (event) {
  1364. document.getElementById('sipNumber').focus();
  1365. }
  1366. );
  1367. }
  1368. function hangup() {
  1369. disposeConference();
  1370. sessionTerminated = true;
  1371. connection.emuc.doLeave();
  1372. if(config.enableWelcomePage)
  1373. {
  1374. setTimeout(function()
  1375. {
  1376. window.localStorage.welcomePageDisabled = false;
  1377. window.location.pathname = "/";
  1378. }, 10000);
  1379. }
  1380. $.prompt("Session Terminated",
  1381. {
  1382. title: "You hung up the call",
  1383. persistent: true,
  1384. buttons: {
  1385. "Join again": true
  1386. },
  1387. closeText: '',
  1388. submit: function(event, value, message, formVals)
  1389. {
  1390. window.location.reload();
  1391. return false;
  1392. }
  1393. }
  1394. );
  1395. }