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

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