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

app.js 51KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589
  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. messageHandler.showError('Oops',
  291. 'We could not associate the current stream with a participant.');
  292. // We don't want to add it here since it will cause troubles
  293. return;
  294. }
  295. // FIXME: for the mixed ms we dont need a video -- currently
  296. container = document.createElement('span');
  297. container.id = 'mixedstream';
  298. container.className = 'videocontainer';
  299. remotes.appendChild(container);
  300. Util.playSoundNotification('userJoined');
  301. }
  302. var isVideo = data.stream.getVideoTracks().length > 0;
  303. if (container) {
  304. VideoLayout.addRemoteStreamElement( container,
  305. sid,
  306. data.stream,
  307. data.peerjid,
  308. thessrc);
  309. }
  310. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  311. if (isVideo &&
  312. data.peerjid && sess.peerjid === data.peerjid &&
  313. data.stream.getVideoTracks().length === 0 &&
  314. connection.jingle.localVideo.getVideoTracks().length > 0) {
  315. //
  316. window.setTimeout(function () {
  317. sendKeyframe(sess.peerconnection);
  318. }, 3000);
  319. }
  320. }
  321. /**
  322. * Returns the JID of the user to whom given <tt>videoSrc</tt> belongs.
  323. * @param videoSrc the video "src" identifier.
  324. * @returns {null | String} the JID of the user to whom given <tt>videoSrc</tt>
  325. * belongs.
  326. */
  327. function getJidFromVideoSrc(videoSrc)
  328. {
  329. if (videoSrc === localVideoSrc)
  330. return connection.emuc.myroomjid;
  331. var ssrc = videoSrcToSsrc[videoSrc];
  332. if (!ssrc)
  333. {
  334. return null;
  335. }
  336. return ssrc2jid[ssrc];
  337. }
  338. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  339. function sendKeyframe(pc) {
  340. console.log('sendkeyframe', pc.iceConnectionState);
  341. if (pc.iceConnectionState !== 'connected') return; // safe...
  342. pc.setRemoteDescription(
  343. pc.remoteDescription,
  344. function () {
  345. pc.createAnswer(
  346. function (modifiedAnswer) {
  347. pc.setLocalDescription(
  348. modifiedAnswer,
  349. function () {
  350. // noop
  351. },
  352. function (error) {
  353. console.log('triggerKeyframe setLocalDescription failed', error);
  354. messageHandler.showError();
  355. }
  356. );
  357. },
  358. function (error) {
  359. console.log('triggerKeyframe createAnswer failed', error);
  360. messageHandler.showError();
  361. }
  362. );
  363. },
  364. function (error) {
  365. console.log('triggerKeyframe setRemoteDescription failed', error);
  366. messageHandler.showError();
  367. }
  368. );
  369. }
  370. // Really mute video, i.e. dont even send black frames
  371. function muteVideo(pc, unmute) {
  372. // FIXME: this probably needs another of those lovely state safeguards...
  373. // which checks for iceconn == connected and sigstate == stable
  374. pc.setRemoteDescription(pc.remoteDescription,
  375. function () {
  376. pc.createAnswer(
  377. function (answer) {
  378. var sdp = new SDP(answer.sdp);
  379. if (sdp.media.length > 1) {
  380. if (unmute)
  381. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  382. else
  383. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  384. sdp.raw = sdp.session + sdp.media.join('');
  385. answer.sdp = sdp.raw;
  386. }
  387. pc.setLocalDescription(answer,
  388. function () {
  389. console.log('mute SLD ok');
  390. },
  391. function (error) {
  392. console.log('mute SLD error');
  393. messageHandler.showError('Error',
  394. 'Oops! Something went wrong and we failed to ' +
  395. 'mute! (SLD Failure)');
  396. }
  397. );
  398. },
  399. function (error) {
  400. console.log(error);
  401. messageHandler.showError();
  402. }
  403. );
  404. },
  405. function (error) {
  406. console.log('muteVideo SRD error');
  407. messageHandler.showError('Error',
  408. 'Oops! Something went wrong and we failed to stop video!' +
  409. '(SRD Failure)');
  410. }
  411. );
  412. }
  413. /**
  414. * Callback for audio levels changed.
  415. * @param jid JID of the user
  416. * @param audioLevel the audio level value
  417. */
  418. function audioLevelUpdated(jid, audioLevel)
  419. {
  420. var resourceJid;
  421. if(jid === LocalStatsCollector.LOCAL_JID)
  422. {
  423. resourceJid = AudioLevels.LOCAL_LEVEL;
  424. if(isAudioMuted())
  425. {
  426. audioLevel = 0;
  427. }
  428. }
  429. else
  430. {
  431. resourceJid = Strophe.getResourceFromJid(jid);
  432. }
  433. AudioLevels.updateAudioLevel(resourceJid, audioLevel);
  434. }
  435. /**
  436. * Starts the {@link StatsCollector} if the feature is enabled in config.js.
  437. */
  438. function startRtpStatsCollector()
  439. {
  440. stopRTPStatsCollector();
  441. if (config.enableRtpStats)
  442. {
  443. statsCollector = new StatsCollector(
  444. getConferenceHandler().peerconnection, 200, audioLevelUpdated);
  445. statsCollector.start();
  446. }
  447. }
  448. /**
  449. * Stops the {@link StatsCollector}.
  450. */
  451. function stopRTPStatsCollector()
  452. {
  453. if (statsCollector)
  454. {
  455. statsCollector.stop();
  456. statsCollector = null;
  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. if (info.displayName)
  606. $(document).trigger('displaynamechanged',
  607. ['localVideoContainer', info.displayName + ' (me)']);
  608. });
  609. $(document).bind('entered.muc', function (event, jid, info, pres) {
  610. console.log('entered', jid, info);
  611. console.log('is focus? ' + (focus ? 'true' : 'false'));
  612. // Add Peer's container
  613. VideoLayout.ensurePeerContainerExists(jid);
  614. if (focus !== null) {
  615. // FIXME: this should prepare the video
  616. if (focus.confid === null) {
  617. console.log('make new conference with', jid);
  618. focus.makeConference(Object.keys(connection.emuc.members),
  619. function(error) {
  620. connection.emuc.addBridgeIsDownToPresence();
  621. connection.emuc.sendPresence();
  622. }
  623. );
  624. Toolbar.showRecordingButton(true);
  625. } else {
  626. console.log('invite', jid, 'into conference');
  627. focus.addNewParticipant(jid);
  628. }
  629. }
  630. else if (sharedKey) {
  631. Toolbar.updateLockButton();
  632. }
  633. });
  634. $(document).bind('left.muc', function (event, jid) {
  635. console.log('left.muc', jid);
  636. // Need to call this with a slight delay, otherwise the element couldn't be
  637. // found for some reason.
  638. window.setTimeout(function () {
  639. var container = document.getElementById(
  640. 'participant_' + Strophe.getResourceFromJid(jid));
  641. if (container) {
  642. // hide here, wait for video to close before removing
  643. $(container).hide();
  644. VideoLayout.resizeThumbnails();
  645. }
  646. }, 10);
  647. // Unlock large video
  648. if (focusedVideoSrc)
  649. {
  650. if (getJidFromVideoSrc(focusedVideoSrc) === jid)
  651. {
  652. console.info("Focused video owner has left the conference");
  653. focusedVideoSrc = null;
  654. }
  655. }
  656. connection.jingle.terminateByJid(jid);
  657. if (focus == null
  658. // I shouldn't be the one that left to enter here.
  659. && jid !== connection.emuc.myroomjid
  660. && connection.emuc.myroomjid === connection.emuc.list_members[0]
  661. // If our session has been terminated for some reason
  662. // (kicked, hangup), don't try to become the focus
  663. && !sessionTerminated) {
  664. console.log('welcome to our new focus... myself');
  665. focus = new ColibriFocus(connection, config.hosts.bridge);
  666. if (nickname !== null) {
  667. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  668. nickname);
  669. }
  670. Toolbar.showSipCallButton(true);
  671. if (Object.keys(connection.emuc.members).length > 0) {
  672. focus.makeConference(Object.keys(connection.emuc.members));
  673. Toolbar.showRecordingButton(true);
  674. }
  675. $(document).trigger('focusechanged.muc', [focus]);
  676. }
  677. else if (focus && Object.keys(connection.emuc.members).length === 0) {
  678. console.log('everyone left');
  679. // FIXME: closing the connection is a hack to avoid some
  680. // problems with reinit
  681. disposeConference();
  682. focus = new ColibriFocus(connection, config.hosts.bridge);
  683. if (nickname !== null) {
  684. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  685. nickname);
  686. }
  687. Toolbar.showSipCallButton(true);
  688. Toolbar.showRecordingButton(false);
  689. }
  690. if (connection.emuc.getPrezi(jid)) {
  691. $(document).trigger('presentationremoved.muc',
  692. [jid, connection.emuc.getPrezi(jid)]);
  693. }
  694. });
  695. $(document).bind('presence.muc', function (event, jid, info, pres) {
  696. // Remove old ssrcs coming from the jid
  697. Object.keys(ssrc2jid).forEach(function (ssrc) {
  698. if (ssrc2jid[ssrc] == jid) {
  699. delete ssrc2jid[ssrc];
  700. }
  701. if (ssrc2videoType[ssrc] == jid) {
  702. delete ssrc2videoType[ssrc];
  703. }
  704. });
  705. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  706. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  707. var ssrcV = ssrc.getAttribute('ssrc');
  708. ssrc2jid[ssrcV] = jid;
  709. var type = ssrc.getAttribute('type');
  710. ssrc2videoType[ssrcV] = type;
  711. // might need to update the direction if participant just went from sendrecv to recvonly
  712. if (type === 'video' || type === 'screen') {
  713. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  714. switch (ssrc.getAttribute('direction')) {
  715. case 'sendrecv':
  716. el.show();
  717. break;
  718. case 'recvonly':
  719. el.hide();
  720. // FIXME: Check if we have to change large video
  721. //VideoLayout.updateLargeVideo(el);
  722. break;
  723. }
  724. }
  725. });
  726. if (info.displayName && info.displayName.length > 0)
  727. $(document).trigger('displaynamechanged',
  728. [jid, info.displayName]);
  729. if (focus !== null && info.displayName !== null) {
  730. focus.setEndpointDisplayName(jid, info.displayName);
  731. }
  732. //check if the video bridge is available
  733. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  734. bridgeIsDown = true;
  735. messageHandler.showError("Error",
  736. "Jitsi Videobridge is currently unavailable. Please try again later!");
  737. }
  738. });
  739. $(document).bind('presence.status.muc', function (event, jid, info, pres) {
  740. VideoLayout.setPresenceStatus(
  741. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  742. });
  743. $(document).bind('passwordrequired.muc', function (event, jid) {
  744. console.log('on password required', jid);
  745. messageHandler.openTwoButtonDialog(null,
  746. '<h2>Password required</h2>' +
  747. '<input id="lockKey" type="text" placeholder="password" autofocus>',
  748. true,
  749. "Ok",
  750. function (e, v, m, f) {
  751. if (v) {
  752. var lockKey = document.getElementById('lockKey');
  753. if (lockKey.value !== null) {
  754. setSharedKey(lockKey.value);
  755. connection.emuc.doJoin(jid, lockKey.value);
  756. }
  757. }
  758. },
  759. function (event) {
  760. document.getElementById('lockKey').focus();
  761. }
  762. );
  763. });
  764. $(document).bind('passwordrequired.main', function (event) {
  765. console.log('password is required');
  766. messageHandler.openTwoButtonDialog(null,
  767. '<h2>Password required</h2>' +
  768. '<input id="passwordrequired.username" type="text" placeholder="user@domain.net" autofocus>' +
  769. '<input id="passwordrequired.password" type="password" placeholder="user password">',
  770. true,
  771. "Ok",
  772. function (e, v, m, f) {
  773. if (v) {
  774. var username = document.getElementById('passwordrequired.username');
  775. var password = document.getElementById('passwordrequired.password');
  776. if (username.value !== null && password.value != null) {
  777. connect(username.value, password.value);
  778. }
  779. }
  780. },
  781. function (event) {
  782. document.getElementById('passwordrequired.username').focus();
  783. }
  784. );
  785. });
  786. /**
  787. * Checks if video identified by given src is desktop stream.
  788. * @param videoSrc eg.
  789. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  790. * @returns {boolean}
  791. */
  792. function isVideoSrcDesktop(videoSrc) {
  793. // FIXME: fix this mapping mess...
  794. // figure out if large video is desktop stream or just a camera
  795. var isDesktop = false;
  796. if (localVideoSrc === videoSrc) {
  797. // local video
  798. isDesktop = isUsingScreenStream;
  799. } else {
  800. // Do we have associations...
  801. var videoSsrc = videoSrcToSsrc[videoSrc];
  802. if (videoSsrc) {
  803. var videoType = ssrc2videoType[videoSsrc];
  804. if (videoType) {
  805. // Finally there...
  806. isDesktop = videoType === 'screen';
  807. } else {
  808. console.error("No video type for ssrc: " + videoSsrc);
  809. }
  810. } else {
  811. console.error("No ssrc for src: " + videoSrc);
  812. }
  813. }
  814. return isDesktop;
  815. }
  816. function getConferenceHandler() {
  817. return focus ? focus : activecall;
  818. }
  819. function toggleVideo() {
  820. buttonClick("#video", "icon-camera icon-camera-disabled");
  821. if (!(connection && connection.jingle.localVideo))
  822. return;
  823. var sess = getConferenceHandler();
  824. if (sess) {
  825. sess.toggleVideoMute(
  826. function (isMuted) {
  827. if (isMuted) {
  828. $('#video').removeClass("icon-camera");
  829. $('#video').addClass("icon-camera icon-camera-disabled");
  830. } else {
  831. $('#video').removeClass("icon-camera icon-camera-disabled");
  832. $('#video').addClass("icon-camera");
  833. }
  834. connection.emuc.addVideoInfoToPresence(isMuted);
  835. connection.emuc.sendPresence();
  836. }
  837. );
  838. }
  839. }
  840. /**
  841. * Mutes / unmutes audio for the local participant.
  842. */
  843. function toggleAudio() {
  844. if (!(connection && connection.jingle.localAudio)) {
  845. // We still click the button.
  846. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  847. return;
  848. }
  849. // It is not clear what is the right way to handle multiple tracks.
  850. // So at least make sure that they are all muted or all unmuted and
  851. // that we send presence just once.
  852. var localAudioTracks = connection.jingle.localAudio.getAudioTracks();
  853. if (localAudioTracks.length > 0) {
  854. var audioEnabled = localAudioTracks[0].enabled;
  855. for (var idx = 0; idx < localAudioTracks.length; idx++) {
  856. localAudioTracks[idx].enabled = !audioEnabled;
  857. }
  858. // isMuted is the opposite of audioEnabled
  859. connection.emuc.addAudioInfoToPresence(audioEnabled);
  860. connection.emuc.sendPresence();
  861. VideoLayout.showLocalAudioIndicator(audioEnabled);
  862. }
  863. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  864. }
  865. /**
  866. * Checks whether the audio is muted or not.
  867. * @returns {boolean} true if audio is muted and false if not.
  868. */
  869. function isAudioMuted()
  870. {
  871. var localAudio = connection.jingle.localAudio;
  872. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  873. if(localAudio.getAudioTracks()[idx].enabled === true)
  874. return false;
  875. }
  876. return true;
  877. }
  878. // Starts or stops the recording for the conference.
  879. function toggleRecording() {
  880. if (focus === null || focus.confid === null) {
  881. console.log('non-focus, or conference not yet organized: not enabling recording');
  882. return;
  883. }
  884. if (!recordingToken)
  885. {
  886. messageHandler.openTwoButtonDialog(null,
  887. '<h2>Enter recording token</h2>' +
  888. '<input id="recordingToken" type="text" placeholder="token" autofocus>',
  889. false,
  890. "Save",
  891. function (e, v, m, f) {
  892. if (v) {
  893. var token = document.getElementById('recordingToken');
  894. if (token.value) {
  895. setRecordingToken(Util.escapeHtml(token.value));
  896. toggleRecording();
  897. }
  898. }
  899. },
  900. function (event) {
  901. document.getElementById('recordingToken').focus();
  902. }
  903. );
  904. return;
  905. }
  906. var oldState = focus.recordingEnabled;
  907. Toolbar.toggleRecordingButtonState();
  908. focus.setRecording(!oldState,
  909. recordingToken,
  910. function (state) {
  911. console.log("New recording state: ", state);
  912. if (state == oldState) //failed to change, reset the token because it might have been wrong
  913. {
  914. Toolbar.toggleRecordingButtonState();
  915. setRecordingToken(null);
  916. }
  917. }
  918. );
  919. }
  920. /**
  921. * Returns an array of the video horizontal and vertical indents,
  922. * so that if fits its parent.
  923. *
  924. * @return an array with 2 elements, the horizontal indent and the vertical
  925. * indent
  926. */
  927. function getCameraVideoPosition(videoWidth,
  928. videoHeight,
  929. videoSpaceWidth,
  930. videoSpaceHeight) {
  931. // Parent height isn't completely calculated when we position the video in
  932. // full screen mode and this is why we use the screen height in this case.
  933. // Need to think it further at some point and implement it properly.
  934. var isFullScreen = document.fullScreen ||
  935. document.mozFullScreen ||
  936. document.webkitIsFullScreen;
  937. if (isFullScreen)
  938. videoSpaceHeight = window.innerHeight;
  939. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  940. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  941. return [horizontalIndent, verticalIndent];
  942. }
  943. /**
  944. * Returns an array of the video horizontal and vertical indents.
  945. * Centers horizontally and top aligns vertically.
  946. *
  947. * @return an array with 2 elements, the horizontal indent and the vertical
  948. * indent
  949. */
  950. function getDesktopVideoPosition(videoWidth,
  951. videoHeight,
  952. videoSpaceWidth,
  953. videoSpaceHeight) {
  954. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  955. var verticalIndent = 0;// Top aligned
  956. return [horizontalIndent, verticalIndent];
  957. }
  958. /**
  959. * Returns an array of the video dimensions, so that it covers the screen.
  960. * It leaves no empty areas, but some parts of the video might not be visible.
  961. *
  962. * @return an array with 2 elements, the video width and the video height
  963. */
  964. function getCameraVideoSize(videoWidth,
  965. videoHeight,
  966. videoSpaceWidth,
  967. videoSpaceHeight) {
  968. if (!videoWidth)
  969. videoWidth = currentVideoWidth;
  970. if (!videoHeight)
  971. videoHeight = currentVideoHeight;
  972. var aspectRatio = videoWidth / videoHeight;
  973. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  974. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  975. if (availableWidth / aspectRatio < videoSpaceHeight) {
  976. availableHeight = videoSpaceHeight;
  977. availableWidth = availableHeight * aspectRatio;
  978. }
  979. if (availableHeight * aspectRatio < videoSpaceWidth) {
  980. availableWidth = videoSpaceWidth;
  981. availableHeight = availableWidth / aspectRatio;
  982. }
  983. return [availableWidth, availableHeight];
  984. }
  985. $(document).ready(function () {
  986. document.title = brand.appName;
  987. if(config.enableWelcomePage && window.location.pathname == "/" &&
  988. (!window.localStorage.welcomePageDisabled
  989. || window.localStorage.welcomePageDisabled == "false"))
  990. {
  991. $("#videoconference_page").hide();
  992. $("#domain_name").text(
  993. window.location.protocol + "//" + window.location.host + "/");
  994. $("span[name='appName']").text(brand.appName);
  995. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  996. var leftWatermarkDiv
  997. = $("#welcome_page_header div[class='watermark leftwatermark']");
  998. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  999. {
  1000. leftWatermarkDiv.css({display: 'block'});
  1001. leftWatermarkDiv.parent().get(0).href
  1002. = interfaceConfig.JITSI_WATERMARK_LINK;
  1003. }
  1004. }
  1005. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1006. var rightWatermarkDiv
  1007. = $("#welcome_page_header div[class='watermark rightwatermark']");
  1008. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  1009. rightWatermarkDiv.css({display: 'block'});
  1010. rightWatermarkDiv.parent().get(0).href
  1011. = interfaceConfig.BRAND_WATERMARK_LINK;
  1012. rightWatermarkDiv.get(0).style.backgroundImage
  1013. = "url(images/rightwatermark.png)";
  1014. }
  1015. }
  1016. if (interfaceConfig.SHOW_POWERED_BY) {
  1017. $("#welcome_page_header>a[class='poweredby']")
  1018. .css({display: 'block'});
  1019. }
  1020. function enter_room()
  1021. {
  1022. var val = $("#enter_room_field").val();
  1023. if(!val) {
  1024. val = $("#enter_room_field").attr("room_name");
  1025. }
  1026. if (val) {
  1027. window.location.pathname = "/" + val;
  1028. }
  1029. }
  1030. $("#enter_room_button").click(function()
  1031. {
  1032. enter_room();
  1033. });
  1034. $("#enter_room_field").keydown(function (event) {
  1035. if (event.keyCode === 13 /* enter */) {
  1036. enter_room();
  1037. }
  1038. });
  1039. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  1040. var updateTimeout;
  1041. var animateTimeout;
  1042. $("#reload_roomname").click(function () {
  1043. clearTimeout(updateTimeout);
  1044. clearTimeout(animateTimeout);
  1045. update_roomname();
  1046. });
  1047. $("#reload_roomname").show();
  1048. function animate(word) {
  1049. var currentVal = $("#enter_room_field").attr("placeholder");
  1050. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  1051. animateTimeout = setTimeout(function() {
  1052. animate(word.substring(1, word.length))
  1053. }, 70);
  1054. }
  1055. function update_roomname()
  1056. {
  1057. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1058. $("#enter_room_field").attr("room_name", word);
  1059. $("#enter_room_field").attr("placeholder", "");
  1060. clearTimeout(animateTimeout);
  1061. animate(word);
  1062. updateTimeout = setTimeout(update_roomname, 10000);
  1063. }
  1064. update_roomname();
  1065. }
  1066. $("#disable_welcome").click(function () {
  1067. window.localStorage.welcomePageDisabled
  1068. = $("#disable_welcome").is(":checked");
  1069. });
  1070. return;
  1071. }
  1072. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1073. var leftWatermarkDiv
  1074. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1075. leftWatermarkDiv.css({display: 'block'});
  1076. leftWatermarkDiv.parent().get(0).href
  1077. = interfaceConfig.JITSI_WATERMARK_LINK;
  1078. }
  1079. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1080. var rightWatermarkDiv
  1081. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1082. rightWatermarkDiv.css({display: 'block'});
  1083. rightWatermarkDiv.parent().get(0).href
  1084. = interfaceConfig.BRAND_WATERMARK_LINK;
  1085. rightWatermarkDiv.get(0).style.backgroundImage
  1086. = "url(images/rightwatermark.png)";
  1087. }
  1088. if (interfaceConfig.SHOW_POWERED_BY) {
  1089. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1090. }
  1091. $("#welcome_page").hide();
  1092. Chat.init();
  1093. $('body').popover({ selector: '[data-toggle=popover]',
  1094. trigger: 'click hover',
  1095. content: function() {
  1096. return this.getAttribute("content") +
  1097. KeyboardShortcut.getShortcut(this.getAttribute("shortcut"));
  1098. }
  1099. });
  1100. // Set the defaults for prompt dialogs.
  1101. jQuery.prompt.setDefaults({persistent: false});
  1102. // Set default desktop sharing method
  1103. setDesktopSharing(config.desktopSharing);
  1104. // Initialize Chrome extension inline installs
  1105. if (config.chromeExtensionId) {
  1106. initInlineInstalls();
  1107. }
  1108. // By default we use camera
  1109. getVideoSize = getCameraVideoSize;
  1110. getVideoPosition = getCameraVideoPosition;
  1111. VideoLayout.resizeLargeVideoContainer();
  1112. $(window).resize(function () {
  1113. VideoLayout.resizeLargeVideoContainer();
  1114. VideoLayout.positionLarge();
  1115. });
  1116. // Listen for large video size updates
  1117. document.getElementById('largeVideo')
  1118. .addEventListener('loadedmetadata', function (e) {
  1119. currentVideoWidth = this.videoWidth;
  1120. currentVideoHeight = this.videoHeight;
  1121. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  1122. });
  1123. if (!$('#settings').is(':visible')) {
  1124. console.log('init');
  1125. init();
  1126. } else {
  1127. loginInfo.onsubmit = function (e) {
  1128. if (e.preventDefault) e.preventDefault();
  1129. $('#settings').hide();
  1130. init();
  1131. };
  1132. }
  1133. });
  1134. $(window).bind('beforeunload', function () {
  1135. if (connection && connection.connected) {
  1136. // ensure signout
  1137. $.ajax({
  1138. type: 'POST',
  1139. url: config.bosh,
  1140. async: false,
  1141. cache: false,
  1142. contentType: 'application/xml',
  1143. data: "<body rid='" + (connection.rid || connection._proto.rid)
  1144. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  1145. + (connection.sid || connection._proto.sid)
  1146. + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  1147. success: function (data) {
  1148. console.log('signed out');
  1149. console.log(data);
  1150. },
  1151. error: function (XMLHttpRequest, textStatus, errorThrown) {
  1152. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  1153. }
  1154. });
  1155. }
  1156. disposeConference(true);
  1157. });
  1158. function disposeConference(onUnload) {
  1159. var handler = getConferenceHandler();
  1160. if (handler && handler.peerconnection) {
  1161. // FIXME: probably removing streams is not required and close() should
  1162. // be enough
  1163. if (connection.jingle.localAudio) {
  1164. handler.peerconnection.removeStream(connection.jingle.localAudio);
  1165. }
  1166. if (connection.jingle.localVideo) {
  1167. handler.peerconnection.removeStream(connection.jingle.localVideo);
  1168. }
  1169. handler.peerconnection.close();
  1170. }
  1171. stopRTPStatsCollector();
  1172. if(onUnload) {
  1173. stopLocalRtpStatsCollector();
  1174. }
  1175. focus = null;
  1176. activecall = null;
  1177. }
  1178. function dump(elem, filename) {
  1179. elem = elem.parentNode;
  1180. elem.download = filename || 'meetlog.json';
  1181. elem.href = 'data:application/json;charset=utf-8,\n';
  1182. var data = populateData();
  1183. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1184. return false;
  1185. }
  1186. /**
  1187. * Populates the log data
  1188. */
  1189. function populateData() {
  1190. var data = {};
  1191. if (connection.jingle) {
  1192. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  1193. var session = connection.jingle.sessions[sid];
  1194. if (session.peerconnection && session.peerconnection.updateLog) {
  1195. // FIXME: should probably be a .dump call
  1196. data["jingle_" + session.sid] = {
  1197. updateLog: session.peerconnection.updateLog,
  1198. stats: session.peerconnection.stats,
  1199. url: window.location.href
  1200. };
  1201. }
  1202. });
  1203. }
  1204. var metadata = {};
  1205. metadata.time = new Date();
  1206. metadata.url = window.location.href;
  1207. metadata.ua = navigator.userAgent;
  1208. if (connection.logger) {
  1209. metadata.xmpp = connection.logger.log;
  1210. }
  1211. data.metadata = metadata;
  1212. return data;
  1213. }
  1214. /**
  1215. * Changes the style class of the element given by id.
  1216. */
  1217. function buttonClick(id, classname) {
  1218. $(id).toggleClass(classname); // add the class to the clicked element
  1219. }
  1220. /**
  1221. * Locks / unlocks the room.
  1222. */
  1223. function lockRoom(lock) {
  1224. if (lock)
  1225. connection.emuc.lockRoom(sharedKey);
  1226. else
  1227. connection.emuc.lockRoom('');
  1228. Toolbar.updateLockButton();
  1229. }
  1230. /**
  1231. * Sets the shared key.
  1232. */
  1233. function setSharedKey(sKey) {
  1234. sharedKey = sKey;
  1235. }
  1236. function setRecordingToken(token) {
  1237. recordingToken = token;
  1238. }
  1239. /**
  1240. * Updates the room invite url.
  1241. */
  1242. function updateRoomUrl(newRoomUrl) {
  1243. roomUrl = newRoomUrl;
  1244. // If the invite dialog has been already opened we update the information.
  1245. var inviteLink = document.getElementById('inviteLinkRef');
  1246. if (inviteLink) {
  1247. inviteLink.value = roomUrl;
  1248. inviteLink.select();
  1249. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  1250. }
  1251. }
  1252. /**
  1253. * Warning to the user that the conference window is about to be closed.
  1254. */
  1255. function closePageWarning() {
  1256. if (focus !== null)
  1257. return "You are the owner of this conference call and"
  1258. + " you are about to end it.";
  1259. else
  1260. return "You are about to leave this conversation.";
  1261. }
  1262. /**
  1263. * Resizes and repositions videos in full screen mode.
  1264. */
  1265. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1266. function () {
  1267. VideoLayout.resizeLargeVideoContainer();
  1268. VideoLayout.positionLarge();
  1269. isFullScreen = document.fullScreen ||
  1270. document.mozFullScreen ||
  1271. document.webkitIsFullScreen;
  1272. if (isFullScreen) {
  1273. setView("fullscreen");
  1274. }
  1275. else {
  1276. setView("default");
  1277. }
  1278. }
  1279. );
  1280. /**
  1281. * Sets the current view.
  1282. */
  1283. function setView(viewName) {
  1284. // if (viewName == "fullscreen") {
  1285. // document.getElementById('videolayout_fullscreen').disabled = false;
  1286. // document.getElementById('videolayout_default').disabled = true;
  1287. // }
  1288. // else {
  1289. // document.getElementById('videolayout_default').disabled = false;
  1290. // document.getElementById('videolayout_fullscreen').disabled = true;
  1291. // }
  1292. }
  1293. function hangUp() {
  1294. if (connection && connection.connected) {
  1295. // ensure signout
  1296. $.ajax({
  1297. type: 'POST',
  1298. url: config.bosh,
  1299. async: false,
  1300. cache: false,
  1301. contentType: 'application/xml',
  1302. data: "<body rid='" + (connection.rid || connection._proto.rid) + "' xmlns='http://jabber.org/protocol/httpbind' sid='" + (connection.sid || connection._proto.sid) + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  1303. success: function (data) {
  1304. console.log('signed out');
  1305. console.log(data);
  1306. },
  1307. error: function (XMLHttpRequest, textStatus, errorThrown) {
  1308. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  1309. }
  1310. });
  1311. }
  1312. disposeConference(true);
  1313. }
  1314. $(document).bind('fatalError.jingle',
  1315. function (event, session, error)
  1316. {
  1317. sessionTerminated = true;
  1318. connection.emuc.doLeave();
  1319. messageHandler.showError( "Sorry",
  1320. "Your browser version is too old. Please update and try again...");
  1321. }
  1322. );
  1323. function onSelectedEndpointChanged(userJid)
  1324. {
  1325. console.log('selected endpoint changed: ', userJid);
  1326. if (_dataChannels && _dataChannels.length != 0)
  1327. {
  1328. _dataChannels.some(function (dataChannel) {
  1329. if (dataChannel.readyState == 'open')
  1330. {
  1331. dataChannel.send(JSON.stringify({
  1332. 'colibriClass': 'SelectedEndpointChangedEvent',
  1333. 'selectedEndpoint': (!userJid || userJid == null)
  1334. ? null : Strophe.getResourceFromJid(userJid)
  1335. }));
  1336. return true;
  1337. }
  1338. });
  1339. }
  1340. }
  1341. $(document).bind("selectedendpointchanged", function(event, userJid) {
  1342. onSelectedEndpointChanged(userJid);
  1343. });
  1344. function callSipButtonClicked()
  1345. {
  1346. var defaultNumber
  1347. = config.defaultSipNumber ? config.defaultSipNumber : '';
  1348. messageHandler.openTwoButtonDialog(null,
  1349. '<h2>Enter SIP number</h2>' +
  1350. '<input id="sipNumber" type="text"' +
  1351. ' value="' + defaultNumber + '" autofocus>',
  1352. false,
  1353. "Dial",
  1354. function (e, v, m, f) {
  1355. if (v) {
  1356. var numberInput = document.getElementById('sipNumber');
  1357. if (numberInput.value) {
  1358. connection.rayo.dial(
  1359. numberInput.value, 'fromnumber', roomName);
  1360. }
  1361. }
  1362. },
  1363. function (event) {
  1364. document.getElementById('sipNumber').focus();
  1365. }
  1366. );
  1367. }
  1368. function hangup() {
  1369. disposeConference();
  1370. sessionTerminated = true;
  1371. connection.emuc.doLeave();
  1372. if(config.enableWelcomePage)
  1373. {
  1374. setTimeout(function()
  1375. {
  1376. window.localStorage.welcomePageDisabled = false;
  1377. window.location.pathname = "/";
  1378. }, 10000);
  1379. }
  1380. $.prompt("Session Terminated",
  1381. {
  1382. title: "You hung up the call",
  1383. persistent: true,
  1384. buttons: {
  1385. "Join again": true
  1386. },
  1387. closeText: '',
  1388. submit: function(event, value, message, formVals)
  1389. {
  1390. window.location.reload();
  1391. return false;
  1392. }
  1393. }
  1394. );
  1395. }