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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  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. /**
  16. * The stats collector that process stats data and triggers updates to app.js.
  17. * @type {StatsCollector}
  18. */
  19. var statsCollector = null;
  20. /**
  21. * The stats collector for the local stream.
  22. * @type {LocalStatsCollector}
  23. */
  24. var localStatsCollector = null;
  25. /**
  26. * Indicates whether ssrc is camera video or desktop stream.
  27. * FIXME: remove those maps
  28. */
  29. var ssrc2videoType = {};
  30. var videoSrcToSsrc = {};
  31. /**
  32. * Currently focused video "src"(displayed in large video).
  33. * @type {String}
  34. */
  35. var focusedVideoSrc = null;
  36. var mutedAudios = {};
  37. var localVideoSrc = null;
  38. var flipXLocalVideo = true;
  39. var isFullScreen = false;
  40. var toolbarTimeout = null;
  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. RTC = setupRTC();
  57. if (RTC === null) {
  58. window.location.href = 'webrtcrequired.html';
  59. return;
  60. } else if (RTC.browser !== 'chrome') {
  61. window.location.href = 'chromeonly.html';
  62. return;
  63. }
  64. obtainAudioAndVideoPermissions(function (stream) {
  65. var audioStream = new webkitMediaStream(stream);
  66. var videoStream = new webkitMediaStream(stream);
  67. var videoTracks = stream.getVideoTracks();
  68. var audioTracks = stream.getAudioTracks();
  69. for (var i = 0; i < videoTracks.length; i++) {
  70. audioStream.removeTrack(videoTracks[i]);
  71. }
  72. VideoLayout.changeLocalAudio(audioStream);
  73. startLocalRtpStatsCollector(audioStream);
  74. for (i = 0; i < audioTracks.length; i++) {
  75. videoStream.removeTrack(audioTracks[i]);
  76. }
  77. VideoLayout.changeLocalVideo(videoStream, true);
  78. maybeDoJoin();
  79. });
  80. var jid = document.getElementById('jid').value || config.hosts.anonymousdomain || config.hosts.domain || window.location.hostname;
  81. connect(jid);
  82. }
  83. function connect(jid, password) {
  84. connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
  85. if (nickname) {
  86. connection.emuc.addDisplayNameToPresence(nickname);
  87. }
  88. if (connection.disco) {
  89. // for chrome, add multistream cap
  90. }
  91. connection.jingle.pc_constraints = RTC.pc_constraints;
  92. if (config.useIPv6) {
  93. // https://code.google.com/p/webrtc/issues/detail?id=2828
  94. if (!connection.jingle.pc_constraints.optional) connection.jingle.pc_constraints.optional = [];
  95. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  96. }
  97. if(!password)
  98. password = document.getElementById('password').value;
  99. var anonymousConnectionFailed = false;
  100. connection.connect(jid, password, function (status, msg) {
  101. if (status === Strophe.Status.CONNECTED) {
  102. console.log('connected');
  103. if (config.useStunTurn) {
  104. connection.jingle.getStunAndTurnCredentials();
  105. }
  106. document.getElementById('connect').disabled = true;
  107. if(password)
  108. authenticatedUser = true;
  109. maybeDoJoin();
  110. } else if (status === Strophe.Status.CONNFAIL) {
  111. if(msg === 'x-strophe-bad-non-anon-jid') {
  112. anonymousConnectionFailed = true;
  113. }
  114. console.log('status', status);
  115. } else if (status === Strophe.Status.DISCONNECTED) {
  116. if(anonymousConnectionFailed) {
  117. // prompt user for username and password
  118. $(document).trigger('passwordrequired.main');
  119. }
  120. } else if (status === Strophe.Status.AUTHFAIL) {
  121. // wrong password or username, prompt user
  122. $(document).trigger('passwordrequired.main');
  123. } else {
  124. console.log('status', status);
  125. }
  126. });
  127. }
  128. /**
  129. * HTTPS only:
  130. * We first ask for audio and video combined stream in order to get permissions and not to ask twice.
  131. * Then we dispose the stream and continue with separate audio, video streams(required for desktop sharing).
  132. */
  133. function obtainAudioAndVideoPermissions(callback) {
  134. // This makes sense only on https sites otherwise we'll be asked for permissions every time
  135. if (location.protocol !== 'https:') {
  136. callback();
  137. return;
  138. }
  139. // Get AV
  140. getUserMediaWithConstraints(
  141. ['audio', 'video'],
  142. function (avStream) {
  143. callback(avStream);
  144. },
  145. function (error) {
  146. console.error('failed to obtain audio/video stream - stop', error);
  147. },
  148. config.resolution || '360');
  149. }
  150. function maybeDoJoin() {
  151. if (connection && connection.connected && Strophe.getResourceFromJid(connection.jid) // .connected is true while connecting?
  152. && (connection.jingle.localAudio || connection.jingle.localVideo)) {
  153. doJoin();
  154. }
  155. }
  156. function doJoin() {
  157. var roomnode = null;
  158. var path = window.location.pathname;
  159. var roomjid;
  160. // determinde the room node from the url
  161. // TODO: just the roomnode or the whole bare jid?
  162. if (config.getroomnode && typeof config.getroomnode === 'function') {
  163. // custom function might be responsible for doing the pushstate
  164. roomnode = config.getroomnode(path);
  165. } else {
  166. /* fall back to default strategy
  167. * this is making assumptions about how the URL->room mapping happens.
  168. * It currently assumes deployment at root, with a rewrite like the
  169. * following one (for nginx):
  170. location ~ ^/([a-zA-Z0-9]+)$ {
  171. rewrite ^/(.*)$ / break;
  172. }
  173. */
  174. if (path.length > 1) {
  175. roomnode = path.substr(1).toLowerCase();
  176. } else {
  177. roomnode = Math.random().toString(36).substr(2, 20);
  178. window.history.pushState('VideoChat',
  179. 'Room: ' + roomnode, window.location.pathname + roomnode);
  180. }
  181. }
  182. roomName = roomnode + '@' + config.hosts.muc;
  183. roomjid = roomName;
  184. if (config.useNicks) {
  185. var nick = window.prompt('Your nickname (optional)');
  186. if (nick) {
  187. roomjid += '/' + nick;
  188. } else {
  189. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  190. }
  191. } else {
  192. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  193. if(!authenticatedUser)
  194. tmpJid = tmpJid.substr(0, 8);
  195. roomjid += '/' + tmpJid;
  196. }
  197. connection.emuc.doJoin(roomjid);
  198. }
  199. function waitForRemoteVideo(selector, ssrc, stream) {
  200. if (selector.removed || !selector.parent().is(":visible")) {
  201. console.warn("Media removed before had started", selector);
  202. return;
  203. }
  204. if (stream.id === 'mixedmslabel') return;
  205. if (selector[0].currentTime > 0) {
  206. RTC.attachMediaStream(selector, stream); // FIXME: why do i have to do this for FF?
  207. // FIXME: add a class that will associate peer Jid, video.src, it's ssrc and video type
  208. // in order to get rid of too many maps
  209. if (ssrc && selector.attr('src')) {
  210. videoSrcToSsrc[selector.attr('src')] = ssrc;
  211. } else {
  212. console.warn("No ssrc given for video", selector);
  213. }
  214. $(document).trigger('videoactive.jingle', [selector]);
  215. } else {
  216. setTimeout(function () {
  217. waitForRemoteVideo(selector, ssrc, stream);
  218. }, 250);
  219. }
  220. }
  221. $(document).bind('remotestreamadded.jingle', function (event, data, sid) {
  222. var sess = connection.jingle.sessions[sid];
  223. var thessrc;
  224. // look up an associated JID for a stream id
  225. if (data.stream.id.indexOf('mixedmslabel') === -1) {
  226. var ssrclines
  227. = SDPUtil.find_lines(sess.peerconnection.remoteDescription.sdp, 'a=ssrc');
  228. ssrclines = ssrclines.filter(function (line) {
  229. return line.indexOf('mslabel:' + data.stream.label) !== -1;
  230. });
  231. if (ssrclines.length) {
  232. thessrc = ssrclines[0].substring(7).split(' ')[0];
  233. // ok to overwrite the one from focus? might save work in colibri.js
  234. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  235. if (ssrc2jid[thessrc]) {
  236. data.peerjid = ssrc2jid[thessrc];
  237. }
  238. }
  239. }
  240. mediaStreams.push(new MediaStream(data, sid, thessrc));
  241. var container;
  242. var remotes = document.getElementById('remoteVideos');
  243. if (data.peerjid) {
  244. VideoLayout.ensurePeerContainerExists(data.peerjid);
  245. container = document.getElementById(
  246. 'participant_' + Strophe.getResourceFromJid(data.peerjid));
  247. } else {
  248. if (data.stream.id !== 'mixedmslabel') {
  249. console.error( 'can not associate stream',
  250. data.stream.id,
  251. 'with a participant');
  252. // We don't want to add it here since it will cause troubles
  253. return;
  254. }
  255. // FIXME: for the mixed ms we dont need a video -- currently
  256. container = document.createElement('span');
  257. container.id = 'mixedstream';
  258. container.className = 'videocontainer';
  259. remotes.appendChild(container);
  260. Util.playSoundNotification('userJoined');
  261. }
  262. var isVideo = data.stream.getVideoTracks().length > 0;
  263. if (container) {
  264. VideoLayout.addRemoteStreamElement( container,
  265. sid,
  266. data.stream,
  267. data.peerjid,
  268. thessrc);
  269. }
  270. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  271. if (isVideo &&
  272. data.peerjid && sess.peerjid === data.peerjid &&
  273. data.stream.getVideoTracks().length === 0 &&
  274. connection.jingle.localVideo.getVideoTracks().length > 0) {
  275. //
  276. window.setTimeout(function () {
  277. sendKeyframe(sess.peerconnection);
  278. }, 3000);
  279. }
  280. });
  281. /**
  282. * Returns the JID of the user to whom given <tt>videoSrc</tt> belongs.
  283. * @param videoSrc the video "src" identifier.
  284. * @returns {null | String} the JID of the user to whom given <tt>videoSrc</tt>
  285. * belongs.
  286. */
  287. function getJidFromVideoSrc(videoSrc)
  288. {
  289. if (videoSrc === localVideoSrc)
  290. return connection.emuc.myroomjid;
  291. var ssrc = videoSrcToSsrc[videoSrc];
  292. if (!ssrc)
  293. {
  294. return null;
  295. }
  296. return ssrc2jid[ssrc];
  297. }
  298. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  299. function sendKeyframe(pc) {
  300. console.log('sendkeyframe', pc.iceConnectionState);
  301. if (pc.iceConnectionState !== 'connected') return; // safe...
  302. pc.setRemoteDescription(
  303. pc.remoteDescription,
  304. function () {
  305. pc.createAnswer(
  306. function (modifiedAnswer) {
  307. pc.setLocalDescription(
  308. modifiedAnswer,
  309. function () {
  310. // noop
  311. },
  312. function (error) {
  313. console.log('triggerKeyframe setLocalDescription failed', error);
  314. }
  315. );
  316. },
  317. function (error) {
  318. console.log('triggerKeyframe createAnswer failed', error);
  319. }
  320. );
  321. },
  322. function (error) {
  323. console.log('triggerKeyframe setRemoteDescription failed', error);
  324. }
  325. );
  326. }
  327. // Really mute video, i.e. dont even send black frames
  328. function muteVideo(pc, unmute) {
  329. // FIXME: this probably needs another of those lovely state safeguards...
  330. // which checks for iceconn == connected and sigstate == stable
  331. pc.setRemoteDescription(pc.remoteDescription,
  332. function () {
  333. pc.createAnswer(
  334. function (answer) {
  335. var sdp = new SDP(answer.sdp);
  336. if (sdp.media.length > 1) {
  337. if (unmute)
  338. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  339. else
  340. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  341. sdp.raw = sdp.session + sdp.media.join('');
  342. answer.sdp = sdp.raw;
  343. }
  344. pc.setLocalDescription(answer,
  345. function () {
  346. console.log('mute SLD ok');
  347. },
  348. function (error) {
  349. console.log('mute SLD error');
  350. }
  351. );
  352. },
  353. function (error) {
  354. console.log(error);
  355. }
  356. );
  357. },
  358. function (error) {
  359. console.log('muteVideo SRD error');
  360. }
  361. );
  362. }
  363. /**
  364. * Callback for audio levels changed.
  365. * @param jid JID of the user
  366. * @param audioLevel the audio level value
  367. */
  368. function audioLevelUpdated(jid, audioLevel)
  369. {
  370. var resourceJid;
  371. if(jid === LocalStatsCollector.LOCAL_JID)
  372. {
  373. resourceJid = AudioLevels.LOCAL_LEVEL;
  374. if(isAudioMuted())
  375. return;
  376. }
  377. else
  378. {
  379. resourceJid = Strophe.getResourceFromJid(jid);
  380. }
  381. AudioLevels.updateAudioLevel(resourceJid, audioLevel);
  382. }
  383. /**
  384. * Starts the {@link StatsCollector} if the feature is enabled in config.js.
  385. */
  386. function startRtpStatsCollector()
  387. {
  388. stopRTPStatsCollector();
  389. if (config.enableRtpStats)
  390. {
  391. statsCollector = new StatsCollector(
  392. getConferenceHandler().peerconnection, 200, audioLevelUpdated);
  393. statsCollector.start();
  394. }
  395. }
  396. /**
  397. * Stops the {@link StatsCollector}.
  398. */
  399. function stopRTPStatsCollector()
  400. {
  401. if (statsCollector)
  402. {
  403. statsCollector.stop();
  404. statsCollector = null;
  405. }
  406. }
  407. /**
  408. * Starts the {@link LocalStatsCollector} if the feature is enabled in config.js
  409. * @param stream the stream that will be used for collecting statistics.
  410. */
  411. function startLocalRtpStatsCollector(stream)
  412. {
  413. if(config.enableRtpStats)
  414. {
  415. localStatsCollector = new LocalStatsCollector(stream, 100, audioLevelUpdated);
  416. localStatsCollector.start();
  417. }
  418. }
  419. /**
  420. * Stops the {@link LocalStatsCollector}.
  421. */
  422. function stopLocalRtpStatsCollector()
  423. {
  424. if(localStatsCollector)
  425. {
  426. localStatsCollector.stop();
  427. localStatsCollector = null;
  428. }
  429. }
  430. $(document).bind('callincoming.jingle', function (event, sid) {
  431. var sess = connection.jingle.sessions[sid];
  432. // TODO: do we check activecall == null?
  433. activecall = sess;
  434. startRtpStatsCollector();
  435. // Bind data channel listener in case we're a regular participant
  436. if (config.openSctp)
  437. {
  438. bindDataChannelListener(sess.peerconnection);
  439. }
  440. // TODO: check affiliation and/or role
  441. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  442. sess.usedrip = true; // not-so-naive trickle ice
  443. sess.sendAnswer();
  444. sess.accept();
  445. });
  446. $(document).bind('conferenceCreated.jingle', function (event, focus)
  447. {
  448. startRtpStatsCollector();
  449. });
  450. $(document).bind('conferenceCreated.jingle', function (event, focus)
  451. {
  452. // Bind data channel listener in case we're the focus
  453. if (config.openSctp)
  454. {
  455. bindDataChannelListener(focus.peerconnection);
  456. }
  457. });
  458. $(document).bind('callterminated.jingle', function (event, sid, jid, reason) {
  459. // Leave the room if my call has been remotely terminated.
  460. if (connection.emuc.joined && focus == null && reason === 'kick') {
  461. sessionTerminated = true;
  462. connection.emuc.doLeave();
  463. openMessageDialog( "Session Terminated",
  464. "Ouch! You have been kicked out of the meet!");
  465. }
  466. });
  467. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  468. // put our ssrcs into presence so other clients can identify our stream
  469. var sess = connection.jingle.sessions[sid];
  470. var newssrcs = {};
  471. var directions = {};
  472. var localSDP = new SDP(sess.peerconnection.localDescription.sdp);
  473. localSDP.media.forEach(function (media) {
  474. var type = SDPUtil.parse_mid(SDPUtil.find_line(media, 'a=mid:'));
  475. if (SDPUtil.find_line(media, 'a=ssrc:')) {
  476. // assumes a single local ssrc
  477. var ssrc = SDPUtil.find_line(media, 'a=ssrc:').substring(7).split(' ')[0];
  478. newssrcs[type] = ssrc;
  479. directions[type] = (
  480. SDPUtil.find_line(media, 'a=sendrecv') ||
  481. SDPUtil.find_line(media, 'a=recvonly') ||
  482. SDPUtil.find_line(media, 'a=sendonly') ||
  483. SDPUtil.find_line(media, 'a=inactive') ||
  484. 'a=sendrecv').substr(2);
  485. }
  486. });
  487. console.log('new ssrcs', newssrcs);
  488. // Have to clear presence map to get rid of removed streams
  489. connection.emuc.clearPresenceMedia();
  490. var i = 0;
  491. Object.keys(newssrcs).forEach(function (mtype) {
  492. i++;
  493. var type = mtype;
  494. // Change video type to screen
  495. if (mtype === 'video' && isUsingScreenStream) {
  496. type = 'screen';
  497. }
  498. connection.emuc.addMediaToPresence(i, type, newssrcs[mtype], directions[mtype]);
  499. });
  500. if (i > 0) {
  501. connection.emuc.sendPresence();
  502. }
  503. });
  504. $(document).bind('joined.muc', function (event, jid, info) {
  505. updateRoomUrl(window.location.href);
  506. document.getElementById('localNick').appendChild(
  507. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  508. );
  509. if (Object.keys(connection.emuc.members).length < 1) {
  510. focus = new ColibriFocus(connection, config.hosts.bridge);
  511. if (nickname !== null) {
  512. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  513. nickname);
  514. }
  515. Toolbar.showSipCallButton(true);
  516. Toolbar.showRecordingButton(false);
  517. }
  518. if (!focus)
  519. {
  520. Toolbar.showSipCallButton(false);
  521. }
  522. if (focus && config.etherpad_base) {
  523. Etherpad.init();
  524. }
  525. VideoLayout.showFocusIndicator();
  526. // Add myself to the contact list.
  527. ContactList.addContact(jid);
  528. // Once we've joined the muc show the toolbar
  529. Toolbar.showToolbar();
  530. var displayName = '';
  531. if (info.displayName)
  532. displayName = info.displayName + ' (me)';
  533. else
  534. displayName = "Me";
  535. $(document).trigger('displaynamechanged',
  536. ['localVideoContainer', displayName]);
  537. });
  538. $(document).bind('entered.muc', function (event, jid, info, pres) {
  539. console.log('entered', jid, info);
  540. console.log('is focus?' + focus ? 'true' : 'false');
  541. // Add Peer's container
  542. VideoLayout.ensurePeerContainerExists(jid);
  543. if (focus !== null) {
  544. // FIXME: this should prepare the video
  545. if (focus.confid === null) {
  546. console.log('make new conference with', jid);
  547. focus.makeConference(Object.keys(connection.emuc.members));
  548. Toolbar.showRecordingButton(true);
  549. } else {
  550. console.log('invite', jid, 'into conference');
  551. focus.addNewParticipant(jid);
  552. }
  553. }
  554. else if (sharedKey) {
  555. Toolbar.updateLockButton();
  556. }
  557. });
  558. $(document).bind('left.muc', function (event, jid) {
  559. console.log('left.muc', jid);
  560. // Need to call this with a slight delay, otherwise the element couldn't be
  561. // found for some reason.
  562. window.setTimeout(function () {
  563. var container = document.getElementById(
  564. 'participant_' + Strophe.getResourceFromJid(jid));
  565. if (container) {
  566. // hide here, wait for video to close before removing
  567. $(container).hide();
  568. VideoLayout.resizeThumbnails();
  569. }
  570. }, 10);
  571. // Unlock large video
  572. if (focusedVideoSrc)
  573. {
  574. if (getJidFromVideoSrc(focusedVideoSrc) === jid)
  575. {
  576. console.info("Focused video owner has left the conference");
  577. focusedVideoSrc = null;
  578. }
  579. }
  580. connection.jingle.terminateByJid(jid);
  581. if (focus == null
  582. // I shouldn't be the one that left to enter here.
  583. && jid !== connection.emuc.myroomjid
  584. && connection.emuc.myroomjid === connection.emuc.list_members[0]
  585. // If our session has been terminated for some reason
  586. // (kicked, hangup), don't try to become the focus
  587. && !sessionTerminated) {
  588. console.log('welcome to our new focus... myself');
  589. focus = new ColibriFocus(connection, config.hosts.bridge);
  590. if (nickname !== null) {
  591. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  592. nickname);
  593. }
  594. Toolbar.showSipCallButton(true);
  595. if (Object.keys(connection.emuc.members).length > 0) {
  596. focus.makeConference(Object.keys(connection.emuc.members));
  597. Toolbar.showRecordingButton(true);
  598. }
  599. $(document).trigger('focusechanged.muc', [focus]);
  600. }
  601. else if (focus && Object.keys(connection.emuc.members).length === 0) {
  602. console.log('everyone left');
  603. // FIXME: closing the connection is a hack to avoid some
  604. // problems with reinit
  605. disposeConference();
  606. focus = new ColibriFocus(connection, config.hosts.bridge);
  607. if (nickname !== null) {
  608. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  609. nickname);
  610. }
  611. Toolbar.showSipCallButton(true);
  612. Toolbar.showRecordingButton(false);
  613. }
  614. if (connection.emuc.getPrezi(jid)) {
  615. $(document).trigger('presentationremoved.muc',
  616. [jid, connection.emuc.getPrezi(jid)]);
  617. }
  618. });
  619. $(document).bind('presence.muc', function (event, jid, info, pres) {
  620. // Remove old ssrcs coming from the jid
  621. Object.keys(ssrc2jid).forEach(function (ssrc) {
  622. if (ssrc2jid[ssrc] == jid) {
  623. delete ssrc2jid[ssrc];
  624. }
  625. if (ssrc2videoType[ssrc] == jid) {
  626. delete ssrc2videoType[ssrc];
  627. }
  628. });
  629. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  630. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  631. var ssrcV = ssrc.getAttribute('ssrc');
  632. ssrc2jid[ssrcV] = jid;
  633. var type = ssrc.getAttribute('type');
  634. ssrc2videoType[ssrcV] = type;
  635. // might need to update the direction if participant just went from sendrecv to recvonly
  636. if (type === 'video' || type === 'screen') {
  637. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  638. switch (ssrc.getAttribute('direction')) {
  639. case 'sendrecv':
  640. el.show();
  641. break;
  642. case 'recvonly':
  643. el.hide();
  644. // FIXME: Check if we have to change large video
  645. //VideoLayout.updateLargeVideo(el);
  646. break;
  647. }
  648. }
  649. });
  650. if (info.displayName && info.displayName.length > 0)
  651. $(document).trigger('displaynamechanged',
  652. [jid, info.displayName]);
  653. if (focus !== null && info.displayName !== null) {
  654. focus.setEndpointDisplayName(jid, info.displayName);
  655. }
  656. });
  657. $(document).bind('presence.status.muc', function (event, jid, info, pres) {
  658. VideoLayout.setPresenceStatus(
  659. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  660. });
  661. $(document).bind('passwordrequired.muc', function (event, jid) {
  662. console.log('on password required', jid);
  663. $.prompt('<h2>Password required</h2>' +
  664. '<input id="lockKey" type="text" placeholder="shared key" autofocus>', {
  665. persistent: true,
  666. buttons: { "Ok": true, "Cancel": false},
  667. defaultButton: 1,
  668. loaded: function (event) {
  669. document.getElementById('lockKey').focus();
  670. },
  671. submit: function (e, v, m, f) {
  672. if (v) {
  673. var lockKey = document.getElementById('lockKey');
  674. if (lockKey.value !== null) {
  675. setSharedKey(lockKey.value);
  676. connection.emuc.doJoin(jid, lockKey.value);
  677. }
  678. }
  679. }
  680. });
  681. });
  682. $(document).bind('passwordrequired.main', function (event) {
  683. console.log('password is required');
  684. $.prompt('<h2>Password required</h2>' +
  685. '<input id="passwordrequired.username" type="text" placeholder="user@domain.net" autofocus>' +
  686. '<input id="passwordrequired.password" type="password" placeholder="user password">', {
  687. persistent: true,
  688. buttons: { "Ok": true, "Cancel": false},
  689. defaultButton: 1,
  690. loaded: function (event) {
  691. document.getElementById('passwordrequired.username').focus();
  692. },
  693. submit: function (e, v, m, f) {
  694. if (v) {
  695. var username = document.getElementById('passwordrequired.username');
  696. var password = document.getElementById('passwordrequired.password');
  697. if (username.value !== null && password.value != null) {
  698. connect(username.value, password.value);
  699. }
  700. }
  701. }
  702. });
  703. });
  704. /**
  705. * Checks if video identified by given src is desktop stream.
  706. * @param videoSrc eg.
  707. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  708. * @returns {boolean}
  709. */
  710. function isVideoSrcDesktop(videoSrc) {
  711. // FIXME: fix this mapping mess...
  712. // figure out if large video is desktop stream or just a camera
  713. var isDesktop = false;
  714. if (localVideoSrc === videoSrc) {
  715. // local video
  716. isDesktop = isUsingScreenStream;
  717. } else {
  718. // Do we have associations...
  719. var videoSsrc = videoSrcToSsrc[videoSrc];
  720. if (videoSsrc) {
  721. var videoType = ssrc2videoType[videoSsrc];
  722. if (videoType) {
  723. // Finally there...
  724. isDesktop = videoType === 'screen';
  725. } else {
  726. console.error("No video type for ssrc: " + videoSsrc);
  727. }
  728. } else {
  729. console.error("No ssrc for src: " + videoSrc);
  730. }
  731. }
  732. return isDesktop;
  733. }
  734. function getConferenceHandler() {
  735. return focus ? focus : activecall;
  736. }
  737. function toggleVideo() {
  738. if (!(connection && connection.jingle.localVideo))
  739. return;
  740. var sess = getConferenceHandler();
  741. if (sess) {
  742. sess.toggleVideoMute(
  743. function (isMuted) {
  744. if (isMuted) {
  745. $('#video').removeClass("icon-camera");
  746. $('#video').addClass("icon-camera icon-camera-disabled");
  747. } else {
  748. $('#video').removeClass("icon-camera icon-camera-disabled");
  749. $('#video').addClass("icon-camera");
  750. }
  751. }
  752. );
  753. }
  754. sess = focus || activecall;
  755. if (!sess) {
  756. return;
  757. }
  758. sess.pendingop = ismuted ? 'unmute' : 'mute';
  759. // connection.emuc.addVideoInfoToPresence(!ismuted);
  760. // connection.emuc.sendPresence();
  761. sess.modifySources();
  762. }
  763. /**
  764. * Mutes / unmutes audio for the local participant.
  765. */
  766. function toggleAudio() {
  767. if (!(connection && connection.jingle.localAudio)) {
  768. preMuted = true;
  769. // We still click the button.
  770. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  771. return;
  772. }
  773. var localAudio = connection.jingle.localAudio;
  774. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  775. var audioEnabled = localAudio.getAudioTracks()[idx].enabled;
  776. localAudio.getAudioTracks()[idx].enabled = !audioEnabled;
  777. // isMuted is the opposite of audioEnabled
  778. connection.emuc.addAudioInfoToPresence(audioEnabled);
  779. connection.emuc.sendPresence();
  780. }
  781. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  782. }
  783. /**
  784. * Checks whether the audio is muted or not.
  785. * @returns {boolean} true if audio is muted and false if not.
  786. */
  787. function isAudioMuted()
  788. {
  789. var localAudio = connection.jingle.localAudio;
  790. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  791. if(localAudio.getAudioTracks()[idx].enabled === true)
  792. return false;
  793. }
  794. return true;
  795. }
  796. // Starts or stops the recording for the conference.
  797. function toggleRecording() {
  798. if (focus === null || focus.confid === null) {
  799. console.log('non-focus, or conference not yet organized: not enabling recording');
  800. return;
  801. }
  802. if (!recordingToken)
  803. {
  804. $.prompt('<h2>Enter recording token</h2>' +
  805. '<input id="recordingToken" type="text" placeholder="token" autofocus>',
  806. {
  807. persistent: false,
  808. buttons: { "Save": true, "Cancel": false},
  809. defaultButton: 1,
  810. loaded: function (event) {
  811. document.getElementById('recordingToken').focus();
  812. },
  813. submit: function (e, v, m, f) {
  814. if (v) {
  815. var token = document.getElementById('recordingToken');
  816. if (token.value) {
  817. setRecordingToken(Util.escapeHtml(token.value));
  818. toggleRecording();
  819. }
  820. }
  821. }
  822. }
  823. );
  824. return;
  825. }
  826. var oldState = focus.recordingEnabled;
  827. Toolbar.toggleRecordingButtonState();
  828. focus.setRecording(!oldState,
  829. recordingToken,
  830. function (state) {
  831. console.log("New recording state: ", state);
  832. if (state == oldState) //failed to change, reset the token because it might have been wrong
  833. {
  834. Toolbar.toggleRecordingButtonState();
  835. setRecordingToken(null);
  836. }
  837. }
  838. );
  839. }
  840. /**
  841. * Returns an array of the video horizontal and vertical indents,
  842. * so that if fits its parent.
  843. *
  844. * @return an array with 2 elements, the horizontal indent and the vertical
  845. * indent
  846. */
  847. function getCameraVideoPosition(videoWidth,
  848. videoHeight,
  849. videoSpaceWidth,
  850. videoSpaceHeight) {
  851. // Parent height isn't completely calculated when we position the video in
  852. // full screen mode and this is why we use the screen height in this case.
  853. // Need to think it further at some point and implement it properly.
  854. var isFullScreen = document.fullScreen ||
  855. document.mozFullScreen ||
  856. document.webkitIsFullScreen;
  857. if (isFullScreen)
  858. videoSpaceHeight = window.innerHeight;
  859. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  860. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  861. return [horizontalIndent, verticalIndent];
  862. }
  863. /**
  864. * Returns an array of the video horizontal and vertical indents.
  865. * Centers horizontally and top aligns vertically.
  866. *
  867. * @return an array with 2 elements, the horizontal indent and the vertical
  868. * indent
  869. */
  870. function getDesktopVideoPosition(videoWidth,
  871. videoHeight,
  872. videoSpaceWidth,
  873. videoSpaceHeight) {
  874. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  875. var verticalIndent = 0;// Top aligned
  876. return [horizontalIndent, verticalIndent];
  877. }
  878. /**
  879. * Returns an array of the video dimensions, so that it covers the screen.
  880. * It leaves no empty areas, but some parts of the video might not be visible.
  881. *
  882. * @return an array with 2 elements, the video width and the video height
  883. */
  884. function getCameraVideoSize(videoWidth,
  885. videoHeight,
  886. videoSpaceWidth,
  887. videoSpaceHeight) {
  888. if (!videoWidth)
  889. videoWidth = currentVideoWidth;
  890. if (!videoHeight)
  891. videoHeight = currentVideoHeight;
  892. var aspectRatio = videoWidth / videoHeight;
  893. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  894. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  895. if (availableWidth / aspectRatio < videoSpaceHeight) {
  896. availableHeight = videoSpaceHeight;
  897. availableWidth = availableHeight * aspectRatio;
  898. }
  899. if (availableHeight * aspectRatio < videoSpaceWidth) {
  900. availableWidth = videoSpaceWidth;
  901. availableHeight = availableWidth / aspectRatio;
  902. }
  903. return [availableWidth, availableHeight];
  904. }
  905. $(document).ready(function () {
  906. if(config.enableWelcomePage && window.location.pathname == "/" &&
  907. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  908. {
  909. $("#videoconference_page").hide();
  910. $("#enter_room_button").click(function()
  911. {
  912. var val = Util.escapeHtml($("#enter_room_field").val());
  913. window.location.pathname = "/" + val;
  914. });
  915. $("#enter_room_field").keydown(function (event) {
  916. if (event.keyCode === 13) {
  917. var val = Util.escapeHtml(this.value);
  918. window.location.pathname = "/" + val;
  919. }
  920. });
  921. $("#disable_welcome").click(function () {
  922. window.localStorage.welcomePageDisabled = $("#disable_welcome").is(":checked");
  923. });
  924. return;
  925. }
  926. $("#welcome_page").hide();
  927. Chat.init();
  928. $('body').popover({ selector: '[data-toggle=popover]',
  929. trigger: 'click hover'});
  930. // Set the defaults for prompt dialogs.
  931. jQuery.prompt.setDefaults({persistent: false});
  932. // Set default desktop sharing method
  933. setDesktopSharing(config.desktopSharing);
  934. // Initialize Chrome extension inline installs
  935. if (config.chromeExtensionId) {
  936. initInlineInstalls();
  937. }
  938. // By default we use camera
  939. getVideoSize = getCameraVideoSize;
  940. getVideoPosition = getCameraVideoPosition;
  941. VideoLayout.resizeLargeVideoContainer();
  942. $(window).resize(function () {
  943. VideoLayout.resizeLargeVideoContainer();
  944. VideoLayout.positionLarge();
  945. });
  946. // Listen for large video size updates
  947. document.getElementById('largeVideo')
  948. .addEventListener('loadedmetadata', function (e) {
  949. currentVideoWidth = this.videoWidth;
  950. currentVideoHeight = this.videoHeight;
  951. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  952. });
  953. if (!$('#settings').is(':visible')) {
  954. console.log('init');
  955. init();
  956. } else {
  957. loginInfo.onsubmit = function (e) {
  958. if (e.preventDefault) e.preventDefault();
  959. $('#settings').hide();
  960. init();
  961. };
  962. }
  963. });
  964. $(window).bind('beforeunload', function () {
  965. if (connection && connection.connected) {
  966. // ensure signout
  967. $.ajax({
  968. type: 'POST',
  969. url: config.bosh,
  970. async: false,
  971. cache: false,
  972. contentType: 'application/xml',
  973. 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>",
  974. success: function (data) {
  975. console.log('signed out');
  976. console.log(data);
  977. },
  978. error: function (XMLHttpRequest, textStatus, errorThrown) {
  979. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  980. }
  981. });
  982. }
  983. disposeConference(true);
  984. });
  985. function disposeConference(onUnload) {
  986. var handler = getConferenceHandler();
  987. if (handler && handler.peerconnection) {
  988. // FIXME: probably removing streams is not required and close() should be enough
  989. if (connection.jingle.localAudio) {
  990. handler.peerconnection.removeStream(connection.jingle.localAudio);
  991. }
  992. if (connection.jingle.localVideo) {
  993. handler.peerconnection.removeStream(connection.jingle.localVideo);
  994. }
  995. handler.peerconnection.close();
  996. }
  997. stopRTPStatsCollector();
  998. if(onUnload) {
  999. stopLocalRtpStatsCollector();
  1000. }
  1001. focus = null;
  1002. activecall = null;
  1003. }
  1004. function dump(elem, filename) {
  1005. elem = elem.parentNode;
  1006. elem.download = filename || 'meetlog.json';
  1007. elem.href = 'data:application/json;charset=utf-8,\n';
  1008. var data = {};
  1009. if (connection.jingle) {
  1010. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  1011. var session = connection.jingle.sessions[sid];
  1012. if (session.peerconnection && session.peerconnection.updateLog) {
  1013. // FIXME: should probably be a .dump call
  1014. data["jingle_" + session.sid] = {
  1015. updateLog: session.peerconnection.updateLog,
  1016. stats: session.peerconnection.stats,
  1017. url: window.location.href
  1018. };
  1019. }
  1020. });
  1021. }
  1022. metadata = {};
  1023. metadata.time = new Date();
  1024. metadata.url = window.location.href;
  1025. metadata.ua = navigator.userAgent;
  1026. if (connection.logger) {
  1027. metadata.xmpp = connection.logger.log;
  1028. }
  1029. data.metadata = metadata;
  1030. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1031. return false;
  1032. }
  1033. /**
  1034. * Changes the style class of the element given by id.
  1035. */
  1036. function buttonClick(id, classname) {
  1037. $(id).toggleClass(classname); // add the class to the clicked element
  1038. }
  1039. /**
  1040. * Shows a message to the user.
  1041. *
  1042. * @param titleString the title of the message
  1043. * @param messageString the text of the message
  1044. */
  1045. function openMessageDialog(titleString, messageString) {
  1046. $.prompt(messageString,
  1047. {
  1048. title: titleString,
  1049. persistent: false
  1050. }
  1051. );
  1052. }
  1053. /**
  1054. * Locks / unlocks the room.
  1055. */
  1056. function lockRoom(lock) {
  1057. if (lock)
  1058. connection.emuc.lockRoom(sharedKey);
  1059. else
  1060. connection.emuc.lockRoom('');
  1061. Toolbar.updateLockButton();
  1062. }
  1063. /**
  1064. * Sets the shared key.
  1065. */
  1066. function setSharedKey(sKey) {
  1067. sharedKey = sKey;
  1068. }
  1069. function setRecordingToken(token) {
  1070. recordingToken = token;
  1071. }
  1072. /**
  1073. * Updates the room invite url.
  1074. */
  1075. function updateRoomUrl(newRoomUrl) {
  1076. roomUrl = newRoomUrl;
  1077. // If the invite dialog has been already opened we update the information.
  1078. var inviteLink = document.getElementById('inviteLinkRef');
  1079. if (inviteLink) {
  1080. inviteLink.value = roomUrl;
  1081. inviteLink.select();
  1082. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  1083. }
  1084. }
  1085. /**
  1086. * Warning to the user that the conference window is about to be closed.
  1087. */
  1088. function closePageWarning() {
  1089. if (focus !== null)
  1090. return "You are the owner of this conference call and"
  1091. + " you are about to end it.";
  1092. else
  1093. return "You are about to leave this conversation.";
  1094. }
  1095. /**
  1096. * Resizes and repositions videos in full screen mode.
  1097. */
  1098. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1099. function () {
  1100. VideoLayout.resizeLargeVideoContainer();
  1101. VideoLayout.positionLarge();
  1102. isFullScreen = document.fullScreen ||
  1103. document.mozFullScreen ||
  1104. document.webkitIsFullScreen;
  1105. if (isFullScreen) {
  1106. setView("fullscreen");
  1107. }
  1108. else {
  1109. setView("default");
  1110. }
  1111. }
  1112. );
  1113. /**
  1114. * Sets the current view.
  1115. */
  1116. function setView(viewName) {
  1117. // if (viewName == "fullscreen") {
  1118. // document.getElementById('videolayout_fullscreen').disabled = false;
  1119. // document.getElementById('videolayout_default').disabled = true;
  1120. // }
  1121. // else {
  1122. // document.getElementById('videolayout_default').disabled = false;
  1123. // document.getElementById('videolayout_fullscreen').disabled = true;
  1124. // }
  1125. }
  1126. function hangUp() {
  1127. if (connection && connection.connected) {
  1128. // ensure signout
  1129. $.ajax({
  1130. type: 'POST',
  1131. url: config.bosh,
  1132. async: false,
  1133. cache: false,
  1134. contentType: 'application/xml',
  1135. 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>",
  1136. success: function (data) {
  1137. console.log('signed out');
  1138. console.log(data);
  1139. },
  1140. error: function (XMLHttpRequest, textStatus, errorThrown) {
  1141. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  1142. }
  1143. });
  1144. }
  1145. disposeConference(true);
  1146. }
  1147. $(document).bind('fatalError.jingle',
  1148. function (event, session, error)
  1149. {
  1150. sessionTerminated = true;
  1151. connection.emuc.doLeave();
  1152. openMessageDialog( "Sorry",
  1153. "Your browser version is too old. Please update and try again...");
  1154. }
  1155. );
  1156. function callSipButtonClicked()
  1157. {
  1158. $.prompt('<h2>Enter SIP number</h2>' +
  1159. '<input id="sipNumber" type="text" value="" autofocus>',
  1160. {
  1161. persistent: false,
  1162. buttons: { "Dial": true, "Cancel": false},
  1163. defaultButton: 2,
  1164. loaded: function (event)
  1165. {
  1166. document.getElementById('sipNumber').focus();
  1167. },
  1168. submit: function (e, v, m, f)
  1169. {
  1170. if (v)
  1171. {
  1172. var numberInput = document.getElementById('sipNumber');
  1173. if (numberInput.value && numberInput.value.length)
  1174. {
  1175. connection.rayo.dial(
  1176. numberInput.value, 'fromnumber', roomName);
  1177. }
  1178. }
  1179. }
  1180. }
  1181. );
  1182. }
  1183. function hangup() {
  1184. disposeConference();
  1185. sessionTerminated = true;
  1186. connection.emuc.doLeave();
  1187. var buttons = {};
  1188. if(config.enableWelcomePage)
  1189. {
  1190. setTimeout(function()
  1191. {
  1192. window.localStorage.welcomePageDisabled = false;
  1193. window.location.pathname = "/";
  1194. }, 10000);
  1195. }
  1196. $.prompt("Session Terminated",
  1197. {
  1198. title: "You hang up the call",
  1199. persistent: true,
  1200. buttons: {},
  1201. closeText: ''
  1202. }
  1203. );
  1204. }