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

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