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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710
  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 focusedVideoSrc = 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. messageHandler.notify(info.displayName || 'Somebody',
  673. 'connected',
  674. 'connected');
  675. if (info.isFocus)
  676. {
  677. focusJid = jid;
  678. console.info("Ignore focus: " + jid +", real JID: " + info.jid);
  679. return;
  680. }
  681. // Add Peer's container
  682. var id = $(pres).find('>userID').text();
  683. var email = $(pres).find('>email');
  684. if(email.length > 0) {
  685. id = email.text();
  686. }
  687. VideoLayout.ensurePeerContainerExists(jid,id);
  688. if(APIConnector.isEnabled() && APIConnector.isEventEnabled("participantJoined"))
  689. {
  690. APIConnector.triggerEvent("participantJoined",{jid: jid});
  691. }
  692. /*if (focus !== null) {
  693. // FIXME: this should prepare the video
  694. if (focus.confid === null) {
  695. console.log('make new conference with', jid);
  696. focus.makeConference(Object.keys(connection.emuc.members),
  697. function(error) {
  698. connection.emuc.addBridgeIsDownToPresence();
  699. connection.emuc.sendPresence();
  700. }
  701. );
  702. Toolbar.showRecordingButton(true);
  703. } else {
  704. console.log('invite', jid, 'into conference');
  705. focus.addNewParticipant(jid);
  706. }
  707. }*/
  708. });
  709. $(document).bind('left.muc', function (event, jid) {
  710. console.log('left.muc', jid);
  711. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  712. '>.displayname').text();
  713. messageHandler.notify(displayName || 'Somebody',
  714. 'disconnected',
  715. 'disconnected');
  716. // Need to call this with a slight delay, otherwise the element couldn't be
  717. // found for some reason.
  718. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  719. window.setTimeout(function () {
  720. var container = document.getElementById(
  721. 'participant_' + Strophe.getResourceFromJid(jid));
  722. if (container) {
  723. VideoLayout.removeConnectionIndicator(jid);
  724. // hide here, wait for video to close before removing
  725. $(container).hide();
  726. VideoLayout.resizeThumbnails();
  727. }
  728. }, 10);
  729. if(APIConnector.isEnabled() && APIConnector.isEventEnabled("participantLeft"))
  730. {
  731. APIConnector.triggerEvent("participantLeft",{jid: jid});
  732. }
  733. delete jid2Ssrc[jid];
  734. // Unlock large video
  735. if (focusedVideoSrc && focusedVideoSrc.jid === jid)
  736. {
  737. console.info("Focused video owner has left the conference");
  738. focusedVideoSrc = null;
  739. }
  740. connection.jingle.terminateByJid(jid);
  741. if (connection.emuc.getPrezi(jid)) {
  742. $(document).trigger('presentationremoved.muc',
  743. [jid, connection.emuc.getPrezi(jid)]);
  744. }
  745. });
  746. $(document).bind('presence.muc', function (event, jid, info, pres) {
  747. // Remove old ssrcs coming from the jid
  748. Object.keys(ssrc2jid).forEach(function (ssrc) {
  749. if (ssrc2jid[ssrc] == jid) {
  750. delete ssrc2jid[ssrc];
  751. delete ssrc2videoType[ssrc];
  752. }
  753. });
  754. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  755. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  756. var ssrcV = ssrc.getAttribute('ssrc');
  757. ssrc2jid[ssrcV] = jid;
  758. notReceivedSSRCs.push(ssrcV);
  759. var type = ssrc.getAttribute('type');
  760. ssrc2videoType[ssrcV] = type;
  761. // might need to update the direction if participant just went from sendrecv to recvonly
  762. if (type === 'video' || type === 'screen') {
  763. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  764. switch (ssrc.getAttribute('direction')) {
  765. case 'sendrecv':
  766. el.show();
  767. break;
  768. case 'recvonly':
  769. el.hide();
  770. // FIXME: Check if we have to change large video
  771. //VideoLayout.updateLargeVideo(el);
  772. break;
  773. }
  774. }
  775. });
  776. var displayName = !config.displayJids
  777. ? info.displayName : Strophe.getResourceFromJid(jid);
  778. if (displayName && displayName.length > 0)
  779. $(document).trigger('displaynamechanged',
  780. [jid, info.displayName]);
  781. if (info.isFocus)
  782. {
  783. return;
  784. }
  785. /*if (focus !== null && info.displayName !== null) {
  786. focus.setEndpointDisplayName(jid, info.displayName);
  787. }*/
  788. //check if the video bridge is available
  789. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  790. bridgeIsDown = true;
  791. messageHandler.showError("Error",
  792. "Jitsi Videobridge is currently unavailable. Please try again later!");
  793. }
  794. var id = $(pres).find('>userID').text();
  795. var email = $(pres).find('>email');
  796. if(email.length > 0) {
  797. id = email.text();
  798. }
  799. Avatar.setUserAvatar(jid, id);
  800. });
  801. $(document).bind('presence.status.muc', function (event, jid, info, pres) {
  802. VideoLayout.setPresenceStatus(
  803. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  804. });
  805. $(document).bind('kicked.muc', function (event, jid) {
  806. console.info(jid + " has been kicked from MUC!");
  807. if (connection.emuc.myroomjid === jid) {
  808. sessionTerminated = true;
  809. disposeConference(false);
  810. connection.emuc.doLeave();
  811. messageHandler.openMessageDialog("Session Terminated",
  812. "Ouch! You have been kicked out of the meet!");
  813. }
  814. });
  815. $(document).bind('passwordrequired.muc', function (event, jid) {
  816. console.log('on password required', jid);
  817. // password is required
  818. Toolbar.lockLockButton();
  819. messageHandler.openTwoButtonDialog(null,
  820. '<h2>Password required</h2>' +
  821. '<input id="lockKey" type="text" placeholder="password" autofocus>',
  822. true,
  823. "Ok",
  824. function (e, v, m, f) {},
  825. function (event) {
  826. document.getElementById('lockKey').focus();
  827. },
  828. function (e, v, m, f) {
  829. if (v) {
  830. var lockKey = document.getElementById('lockKey');
  831. if (lockKey.value !== null) {
  832. setSharedKey(lockKey.value);
  833. connection.emuc.doJoin(jid, lockKey.value);
  834. }
  835. }
  836. }
  837. );
  838. });
  839. $(document).bind('passwordrequired.main', function (event) {
  840. console.log('password is required');
  841. messageHandler.openTwoButtonDialog(null,
  842. '<h2>Password required</h2>' +
  843. '<input id="passwordrequired.username" type="text" placeholder="user@domain.net" autofocus>' +
  844. '<input id="passwordrequired.password" type="password" placeholder="user password">',
  845. true,
  846. "Ok",
  847. function (e, v, m, f) {
  848. if (v) {
  849. var username = document.getElementById('passwordrequired.username');
  850. var password = document.getElementById('passwordrequired.password');
  851. if (username.value !== null && password.value != null) {
  852. connect(username.value, password.value);
  853. }
  854. }
  855. },
  856. function (event) {
  857. document.getElementById('passwordrequired.username').focus();
  858. }
  859. );
  860. });
  861. /**
  862. * Checks if video identified by given src is desktop stream.
  863. * @param videoSrc eg.
  864. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  865. * @returns {boolean}
  866. */
  867. function isVideoSrcDesktop(jid) {
  868. // FIXME: fix this mapping mess...
  869. // figure out if large video is desktop stream or just a camera
  870. if(!jid)
  871. return false;
  872. var isDesktop = false;
  873. if (connection.emuc.myroomjid &&
  874. Strophe.getResourceFromJid(connection.emuc.myroomjid) === jid) {
  875. // local video
  876. isDesktop = isUsingScreenStream;
  877. } else {
  878. // Do we have associations...
  879. var videoSsrc = jid2Ssrc[jid];
  880. if (videoSsrc) {
  881. var videoType = ssrc2videoType[videoSsrc];
  882. if (videoType) {
  883. // Finally there...
  884. isDesktop = videoType === 'screen';
  885. } else {
  886. console.error("No video type for ssrc: " + videoSsrc);
  887. }
  888. } else {
  889. console.error("No ssrc for jid: " + jid);
  890. }
  891. }
  892. return isDesktop;
  893. }
  894. function getConferenceHandler() {
  895. return activecall;
  896. }
  897. function toggleVideo() {
  898. buttonClick("#video", "icon-camera icon-camera-disabled");
  899. if (!(connection && connection.jingle.localVideo))
  900. return;
  901. var sess = getConferenceHandler();
  902. if (sess) {
  903. sess.toggleVideoMute(
  904. function (isMuted) {
  905. if (isMuted) {
  906. $('#video').removeClass("icon-camera");
  907. $('#video').addClass("icon-camera icon-camera-disabled");
  908. } else {
  909. $('#video').removeClass("icon-camera icon-camera-disabled");
  910. $('#video').addClass("icon-camera");
  911. }
  912. connection.emuc.addVideoInfoToPresence(isMuted);
  913. connection.emuc.sendPresence();
  914. }
  915. );
  916. }
  917. }
  918. /**
  919. * Mutes / unmutes audio for the local participant.
  920. */
  921. function toggleAudio() {
  922. setAudioMuted(!isAudioMuted());
  923. }
  924. /**
  925. * Sets muted audio state for the local participant.
  926. */
  927. function setAudioMuted(mute) {
  928. if (!(connection && connection.jingle.localAudio)) {
  929. preMuted = mute;
  930. // We still click the button.
  931. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  932. return;
  933. }
  934. if (forceMuted && !mute) {
  935. console.info("Asking focus for unmute");
  936. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  937. // FIXME: wait for result before resetting muted status
  938. forceMuted = false;
  939. }
  940. if (mute == isAudioMuted()) {
  941. // Nothing to do
  942. return;
  943. }
  944. // It is not clear what is the right way to handle multiple tracks.
  945. // So at least make sure that they are all muted or all unmuted and
  946. // that we send presence just once.
  947. var localAudioTracks = connection.jingle.localAudio.getAudioTracks();
  948. if (localAudioTracks.length > 0) {
  949. for (var idx = 0; idx < localAudioTracks.length; idx++) {
  950. localAudioTracks[idx].enabled = !mute;
  951. }
  952. }
  953. // isMuted is the opposite of audioEnabled
  954. connection.emuc.addAudioInfoToPresence(mute);
  955. connection.emuc.sendPresence();
  956. VideoLayout.showLocalAudioIndicator(mute);
  957. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  958. }
  959. /**
  960. * Checks whether the audio is muted or not.
  961. * @returns {boolean} true if audio is muted and false if not.
  962. */
  963. function isAudioMuted()
  964. {
  965. var localAudio = connection.jingle.localAudio;
  966. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  967. if(localAudio.getAudioTracks()[idx].enabled === true)
  968. return false;
  969. }
  970. return true;
  971. }
  972. // Starts or stops the recording for the conference.
  973. function toggleRecording() {
  974. Recording.toggleRecording();
  975. }
  976. /**
  977. * Returns an array of the video horizontal and vertical indents,
  978. * so that if fits its parent.
  979. *
  980. * @return an array with 2 elements, the horizontal indent and the vertical
  981. * indent
  982. */
  983. function getCameraVideoPosition(videoWidth,
  984. videoHeight,
  985. videoSpaceWidth,
  986. videoSpaceHeight) {
  987. // Parent height isn't completely calculated when we position the video in
  988. // full screen mode and this is why we use the screen height in this case.
  989. // Need to think it further at some point and implement it properly.
  990. var isFullScreen = document.fullScreen ||
  991. document.mozFullScreen ||
  992. document.webkitIsFullScreen;
  993. if (isFullScreen)
  994. videoSpaceHeight = window.innerHeight;
  995. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  996. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  997. return [horizontalIndent, verticalIndent];
  998. }
  999. /**
  1000. * Returns an array of the video horizontal and vertical indents.
  1001. * Centers horizontally and top aligns vertically.
  1002. *
  1003. * @return an array with 2 elements, the horizontal indent and the vertical
  1004. * indent
  1005. */
  1006. function getDesktopVideoPosition(videoWidth,
  1007. videoHeight,
  1008. videoSpaceWidth,
  1009. videoSpaceHeight) {
  1010. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  1011. var verticalIndent = 0;// Top aligned
  1012. return [horizontalIndent, verticalIndent];
  1013. }
  1014. /**
  1015. * Returns an array of the video dimensions, so that it covers the screen.
  1016. * It leaves no empty areas, but some parts of the video might not be visible.
  1017. *
  1018. * @return an array with 2 elements, the video width and the video height
  1019. */
  1020. function getCameraVideoSize(videoWidth,
  1021. videoHeight,
  1022. videoSpaceWidth,
  1023. videoSpaceHeight) {
  1024. if (!videoWidth)
  1025. videoWidth = currentVideoWidth;
  1026. if (!videoHeight)
  1027. videoHeight = currentVideoHeight;
  1028. var aspectRatio = videoWidth / videoHeight;
  1029. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  1030. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  1031. if (availableWidth / aspectRatio < videoSpaceHeight) {
  1032. availableHeight = videoSpaceHeight;
  1033. availableWidth = availableHeight * aspectRatio;
  1034. }
  1035. if (availableHeight * aspectRatio < videoSpaceWidth) {
  1036. availableWidth = videoSpaceWidth;
  1037. availableHeight = availableWidth / aspectRatio;
  1038. }
  1039. return [availableWidth, availableHeight];
  1040. }
  1041. $(document).ready(function () {
  1042. document.title = interfaceConfig.APP_NAME;
  1043. if(APIConnector.isEnabled())
  1044. APIConnector.init();
  1045. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1046. (!window.localStorage.welcomePageDisabled
  1047. || window.localStorage.welcomePageDisabled == "false"))
  1048. {
  1049. $("#videoconference_page").hide();
  1050. $("#domain_name").text(
  1051. window.location.protocol + "//" + window.location.host + "/");
  1052. $("span[name='appName']").text(interfaceConfig.APP_NAME);
  1053. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1054. var leftWatermarkDiv
  1055. = $("#welcome_page_header div[class='watermark leftwatermark']");
  1056. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  1057. {
  1058. leftWatermarkDiv.css({display: 'block'});
  1059. leftWatermarkDiv.parent().get(0).href
  1060. = interfaceConfig.JITSI_WATERMARK_LINK;
  1061. }
  1062. }
  1063. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1064. var rightWatermarkDiv
  1065. = $("#welcome_page_header div[class='watermark rightwatermark']");
  1066. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  1067. rightWatermarkDiv.css({display: 'block'});
  1068. rightWatermarkDiv.parent().get(0).href
  1069. = interfaceConfig.BRAND_WATERMARK_LINK;
  1070. rightWatermarkDiv.get(0).style.backgroundImage
  1071. = "url(images/rightwatermark.png)";
  1072. }
  1073. }
  1074. if (interfaceConfig.SHOW_POWERED_BY) {
  1075. $("#welcome_page_header>a[class='poweredby']")
  1076. .css({display: 'block'});
  1077. }
  1078. function enter_room()
  1079. {
  1080. var val = $("#enter_room_field").val();
  1081. if(!val) {
  1082. val = $("#enter_room_field").attr("room_name");
  1083. }
  1084. if (val) {
  1085. window.location.pathname = "/" + val;
  1086. }
  1087. }
  1088. $("#enter_room_button").click(function()
  1089. {
  1090. enter_room();
  1091. });
  1092. $("#enter_room_field").keydown(function (event) {
  1093. if (event.keyCode === 13 /* enter */) {
  1094. enter_room();
  1095. }
  1096. });
  1097. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  1098. var updateTimeout;
  1099. var animateTimeout;
  1100. $("#reload_roomname").click(function () {
  1101. clearTimeout(updateTimeout);
  1102. clearTimeout(animateTimeout);
  1103. update_roomname();
  1104. });
  1105. $("#reload_roomname").show();
  1106. function animate(word) {
  1107. var currentVal = $("#enter_room_field").attr("placeholder");
  1108. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  1109. animateTimeout = setTimeout(function() {
  1110. animate(word.substring(1, word.length))
  1111. }, 70);
  1112. }
  1113. function update_roomname()
  1114. {
  1115. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1116. $("#enter_room_field").attr("room_name", word);
  1117. $("#enter_room_field").attr("placeholder", "");
  1118. clearTimeout(animateTimeout);
  1119. animate(word);
  1120. updateTimeout = setTimeout(update_roomname, 10000);
  1121. }
  1122. update_roomname();
  1123. }
  1124. $("#disable_welcome").click(function () {
  1125. window.localStorage.welcomePageDisabled
  1126. = $("#disable_welcome").is(":checked");
  1127. });
  1128. return;
  1129. }
  1130. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1131. var leftWatermarkDiv
  1132. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1133. leftWatermarkDiv.css({display: 'block'});
  1134. leftWatermarkDiv.parent().get(0).href
  1135. = interfaceConfig.JITSI_WATERMARK_LINK;
  1136. }
  1137. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1138. var rightWatermarkDiv
  1139. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1140. rightWatermarkDiv.css({display: 'block'});
  1141. rightWatermarkDiv.parent().get(0).href
  1142. = interfaceConfig.BRAND_WATERMARK_LINK;
  1143. rightWatermarkDiv.get(0).style.backgroundImage
  1144. = "url(images/rightwatermark.png)";
  1145. }
  1146. if (interfaceConfig.SHOW_POWERED_BY) {
  1147. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1148. }
  1149. $("#welcome_page").hide();
  1150. Chat.init();
  1151. $('body').popover({ selector: '[data-toggle=popover]',
  1152. trigger: 'click hover',
  1153. content: function() {
  1154. return this.getAttribute("content") +
  1155. KeyboardShortcut.getShortcut(this.getAttribute("shortcut"));
  1156. }
  1157. });
  1158. Moderator.init();
  1159. // Set the defaults for prompt dialogs.
  1160. jQuery.prompt.setDefaults({persistent: false});
  1161. // Set default desktop sharing method
  1162. setDesktopSharing(config.desktopSharing);
  1163. // Initialize Chrome extension inline installs
  1164. if (config.chromeExtensionId) {
  1165. initInlineInstalls();
  1166. }
  1167. // By default we use camera
  1168. getVideoSize = getCameraVideoSize;
  1169. getVideoPosition = getCameraVideoPosition;
  1170. VideoLayout.resizeLargeVideoContainer();
  1171. $(window).resize(function () {
  1172. VideoLayout.resizeLargeVideoContainer();
  1173. VideoLayout.positionLarge();
  1174. });
  1175. // Listen for large video size updates
  1176. document.getElementById('largeVideo')
  1177. .addEventListener('loadedmetadata', function (e) {
  1178. currentVideoWidth = this.videoWidth;
  1179. currentVideoHeight = this.videoHeight;
  1180. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  1181. });
  1182. document.getElementById('largeVideo').volume = 0;
  1183. if (!$('#settings').is(':visible')) {
  1184. console.log('init');
  1185. init();
  1186. } else {
  1187. loginInfo.onsubmit = function (e) {
  1188. if (e.preventDefault) e.preventDefault();
  1189. $('#settings').hide();
  1190. init();
  1191. };
  1192. }
  1193. toastr.options = {
  1194. "closeButton": true,
  1195. "debug": false,
  1196. "positionClass": "notification-bottom-right",
  1197. "onclick": null,
  1198. "showDuration": "300",
  1199. "hideDuration": "1000",
  1200. "timeOut": "2000",
  1201. "extendedTimeOut": "1000",
  1202. "showEasing": "swing",
  1203. "hideEasing": "linear",
  1204. "showMethod": "fadeIn",
  1205. "hideMethod": "fadeOut",
  1206. "reposition": function() {
  1207. if(PanelToggler.isVisible()) {
  1208. $("#toast-container").addClass("notification-bottom-right-center");
  1209. } else {
  1210. $("#toast-container").removeClass("notification-bottom-right-center");
  1211. }
  1212. },
  1213. "newestOnTop": false
  1214. };
  1215. $('#settingsmenu>input').keyup(function(event){
  1216. if(event.keyCode === 13) {//enter
  1217. SettingsMenu.update();
  1218. }
  1219. })
  1220. });
  1221. $(window).bind('beforeunload', function () {
  1222. if (connection && connection.connected) {
  1223. // ensure signout
  1224. $.ajax({
  1225. type: 'POST',
  1226. url: config.bosh,
  1227. async: false,
  1228. cache: false,
  1229. contentType: 'application/xml',
  1230. data: "<body rid='" + (connection.rid || connection._proto.rid)
  1231. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  1232. + (connection.sid || connection._proto.sid)
  1233. + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  1234. success: function (data) {
  1235. console.log('signed out');
  1236. console.log(data);
  1237. },
  1238. error: function (XMLHttpRequest, textStatus, errorThrown) {
  1239. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  1240. }
  1241. });
  1242. }
  1243. disposeConference(true);
  1244. if(APIConnector.isEnabled())
  1245. APIConnector.dispose();
  1246. });
  1247. function disposeConference(onUnload) {
  1248. var handler = getConferenceHandler();
  1249. if (handler && handler.peerconnection) {
  1250. // FIXME: probably removing streams is not required and close() should
  1251. // be enough
  1252. if (connection.jingle.localAudio) {
  1253. handler.peerconnection.removeStream(connection.jingle.localAudio, onUnload);
  1254. }
  1255. if (connection.jingle.localVideo) {
  1256. handler.peerconnection.removeStream(connection.jingle.localVideo, onUnload);
  1257. }
  1258. handler.peerconnection.close();
  1259. }
  1260. stopRTPStatsCollector();
  1261. if(onUnload) {
  1262. stopLocalRtpStatsCollector();
  1263. }
  1264. activecall = null;
  1265. }
  1266. function dump(elem, filename) {
  1267. elem = elem.parentNode;
  1268. elem.download = filename || 'meetlog.json';
  1269. elem.href = 'data:application/json;charset=utf-8,\n';
  1270. var data = populateData();
  1271. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1272. return false;
  1273. }
  1274. /**
  1275. * Populates the log data
  1276. */
  1277. function populateData() {
  1278. var data = {};
  1279. if (connection.jingle) {
  1280. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  1281. var session = connection.jingle.sessions[sid];
  1282. if (session.peerconnection && session.peerconnection.updateLog) {
  1283. // FIXME: should probably be a .dump call
  1284. data["jingle_" + session.sid] = {
  1285. updateLog: session.peerconnection.updateLog,
  1286. stats: session.peerconnection.stats,
  1287. url: window.location.href
  1288. };
  1289. }
  1290. });
  1291. }
  1292. var metadata = {};
  1293. metadata.time = new Date();
  1294. metadata.url = window.location.href;
  1295. metadata.ua = navigator.userAgent;
  1296. if (connection.logger) {
  1297. metadata.xmpp = connection.logger.log;
  1298. }
  1299. data.metadata = metadata;
  1300. return data;
  1301. }
  1302. /**
  1303. * Changes the style class of the element given by id.
  1304. */
  1305. function buttonClick(id, classname) {
  1306. $(id).toggleClass(classname); // add the class to the clicked element
  1307. }
  1308. /**
  1309. * Locks / unlocks the room.
  1310. */
  1311. function lockRoom(lock) {
  1312. if (lock)
  1313. connection.emuc.lockRoom(sharedKey);
  1314. else
  1315. connection.emuc.lockRoom('');
  1316. }
  1317. /**
  1318. * Sets the shared key.
  1319. */
  1320. function setSharedKey(sKey) {
  1321. sharedKey = sKey;
  1322. }
  1323. /**
  1324. * Updates the room invite url.
  1325. */
  1326. function updateRoomUrl(newRoomUrl) {
  1327. roomUrl = newRoomUrl;
  1328. // If the invite dialog has been already opened we update the information.
  1329. var inviteLink = document.getElementById('inviteLinkRef');
  1330. if (inviteLink) {
  1331. inviteLink.value = roomUrl;
  1332. inviteLink.select();
  1333. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  1334. }
  1335. }
  1336. /**
  1337. * Warning to the user that the conference window is about to be closed.
  1338. */
  1339. function closePageWarning() {
  1340. /*
  1341. FIXME: do we need a warning when the focus is a server-side one now ?
  1342. if (focus !== null)
  1343. return "You are the owner of this conference call and"
  1344. + " you are about to end it.";
  1345. else*/
  1346. return "You are about to leave this conversation.";
  1347. }
  1348. /**
  1349. * Resizes and repositions videos in full screen mode.
  1350. */
  1351. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1352. function () {
  1353. VideoLayout.resizeLargeVideoContainer();
  1354. VideoLayout.positionLarge();
  1355. isFullScreen = document.fullScreen ||
  1356. document.mozFullScreen ||
  1357. document.webkitIsFullScreen;
  1358. if (isFullScreen) {
  1359. setView("fullscreen");
  1360. }
  1361. else {
  1362. setView("default");
  1363. }
  1364. }
  1365. );
  1366. /**
  1367. * Sets the current view.
  1368. */
  1369. function setView(viewName) {
  1370. // if (viewName == "fullscreen") {
  1371. // document.getElementById('videolayout_fullscreen').disabled = false;
  1372. // document.getElementById('videolayout_default').disabled = true;
  1373. // }
  1374. // else {
  1375. // document.getElementById('videolayout_default').disabled = false;
  1376. // document.getElementById('videolayout_fullscreen').disabled = true;
  1377. // }
  1378. }
  1379. $(document).bind('error.jingle',
  1380. function (event, session, error)
  1381. {
  1382. console.error("Jingle error", error);
  1383. }
  1384. );
  1385. $(document).bind('fatalError.jingle',
  1386. function (event, session, error)
  1387. {
  1388. sessionTerminated = true;
  1389. connection.emuc.doLeave();
  1390. messageHandler.showError( "Sorry",
  1391. "Your browser version is too old. Please update and try again...");
  1392. }
  1393. );
  1394. function onSelectedEndpointChanged(userJid)
  1395. {
  1396. console.log('selected endpoint changed: ', userJid);
  1397. if (_dataChannels && _dataChannels.length != 0)
  1398. {
  1399. _dataChannels.some(function (dataChannel) {
  1400. if (dataChannel.readyState == 'open')
  1401. {
  1402. dataChannel.send(JSON.stringify({
  1403. 'colibriClass': 'SelectedEndpointChangedEvent',
  1404. 'selectedEndpoint': (!userJid || userJid == null)
  1405. ? null : userJid
  1406. }));
  1407. return true;
  1408. }
  1409. });
  1410. }
  1411. }
  1412. $(document).bind("selectedendpointchanged", function(event, userJid) {
  1413. onSelectedEndpointChanged(userJid);
  1414. });
  1415. function onPinnedEndpointChanged(userJid)
  1416. {
  1417. console.log('pinned endpoint changed: ', userJid);
  1418. if (_dataChannels && _dataChannels.length != 0)
  1419. {
  1420. _dataChannels.some(function (dataChannel) {
  1421. if (dataChannel.readyState == 'open')
  1422. {
  1423. dataChannel.send(JSON.stringify({
  1424. 'colibriClass': 'PinnedEndpointChangedEvent',
  1425. 'pinnedEndpoint': (!userJid || userJid == null)
  1426. ? null : Strophe.getResourceFromJid(userJid)
  1427. }));
  1428. return true;
  1429. }
  1430. });
  1431. }
  1432. }
  1433. $(document).bind("pinnedendpointchanged", function(event, userJid) {
  1434. onPinnedEndpointChanged(userJid);
  1435. });
  1436. function callSipButtonClicked()
  1437. {
  1438. var defaultNumber
  1439. = config.defaultSipNumber ? config.defaultSipNumber : '';
  1440. messageHandler.openTwoButtonDialog(null,
  1441. '<h2>Enter SIP number</h2>' +
  1442. '<input id="sipNumber" type="text"' +
  1443. ' value="' + defaultNumber + '" autofocus>',
  1444. false,
  1445. "Dial",
  1446. function (e, v, m, f) {
  1447. if (v) {
  1448. var numberInput = document.getElementById('sipNumber');
  1449. if (numberInput.value) {
  1450. connection.rayo.dial(
  1451. numberInput.value, 'fromnumber', roomName);
  1452. }
  1453. }
  1454. },
  1455. function (event) {
  1456. document.getElementById('sipNumber').focus();
  1457. }
  1458. );
  1459. }
  1460. function hangup() {
  1461. disposeConference();
  1462. sessionTerminated = true;
  1463. connection.emuc.doLeave();
  1464. if(config.enableWelcomePage)
  1465. {
  1466. setTimeout(function()
  1467. {
  1468. window.localStorage.welcomePageDisabled = false;
  1469. window.location.pathname = "/";
  1470. }, 10000);
  1471. }
  1472. $.prompt("Session Terminated",
  1473. {
  1474. title: "You hung up the call",
  1475. persistent: true,
  1476. buttons: {
  1477. "Join again": true
  1478. },
  1479. closeText: '',
  1480. submit: function(event, value, message, formVals)
  1481. {
  1482. window.location.reload();
  1483. return false;
  1484. }
  1485. }
  1486. );
  1487. }
  1488. $(document).on('videomuted.muc', function(event, jid, value) {
  1489. if(mediaStreams[jid] && mediaStreams[jid][MediaStream.VIDEO_TYPE]) {
  1490. var stream = mediaStreams[jid][MediaStream.VIDEO_TYPE];
  1491. var isMuted = (value === "true");
  1492. if (isMuted != stream.muted) {
  1493. stream.muted = isMuted;
  1494. Avatar.showUserAvatar(jid, isMuted);
  1495. }
  1496. }
  1497. });