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

app.js 51KB

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