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.

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