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.

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