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

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