Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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