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

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