You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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