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 50KB

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