Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

app.js 51KB

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