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.

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