Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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