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

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