Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

app.js 52KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  1. /* jshint -W117 */
  2. /* application specific logic */
  3. var connection = null;
  4. var focus = null;
  5. var activecall = null;
  6. var RTC = null;
  7. var nickname = null;
  8. var sharedKey = '';
  9. var roomUrl = null;
  10. var ssrc2jid = {};
  11. /**
  12. * Indicates whether ssrc is camera video or desktop stream.
  13. * FIXME: remove those maps
  14. */
  15. var ssrc2videoType = {};
  16. var videoSrcToSsrc = {};
  17. var localVideoSrc = null;
  18. var flipXLocalVideo = true;
  19. var isFullScreen = false;
  20. var toolbarTimeout = null;
  21. var currentVideoWidth = null;
  22. var currentVideoHeight = null;
  23. /**
  24. * Method used to calculate large video size.
  25. * @type {function()}
  26. */
  27. var getVideoSize;
  28. /**
  29. * Method used to get large video position.
  30. * @type {function()}
  31. */
  32. var getVideoPosition;
  33. /* window.onbeforeunload = closePageWarning; */
  34. function init() {
  35. RTC = setupRTC();
  36. if (RTC === null) {
  37. window.location.href = 'webrtcrequired.html';
  38. return;
  39. } else if (RTC.browser !== 'chrome') {
  40. window.location.href = 'chromeonly.html';
  41. return;
  42. }
  43. connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
  44. if (nickname) {
  45. connection.emuc.addDisplayNameToPresence(nickname);
  46. }
  47. if (connection.disco) {
  48. // for chrome, add multistream cap
  49. }
  50. connection.jingle.pc_constraints = RTC.pc_constraints;
  51. if (config.useIPv6) {
  52. // https://code.google.com/p/webrtc/issues/detail?id=2828
  53. if (!connection.jingle.pc_constraints.optional) connection.jingle.pc_constraints.optional = [];
  54. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  55. }
  56. var jid = document.getElementById('jid').value || config.hosts.domain || window.location.hostname;
  57. connection.connect(jid, document.getElementById('password').value, function (status) {
  58. if (status === Strophe.Status.CONNECTED) {
  59. console.log('connected');
  60. if (config.useStunTurn) {
  61. connection.jingle.getStunAndTurnCredentials();
  62. }
  63. obtainAudioAndVideoPermissions(function(){
  64. getUserMediaWithConstraints( ['audio'], audioStreamReady,
  65. function(error){
  66. console.error('failed to obtain audio stream - stop', error);
  67. });
  68. });
  69. document.getElementById('connect').disabled = true;
  70. } else {
  71. console.log('status', status);
  72. }
  73. });
  74. }
  75. /**
  76. * HTTPS only:
  77. * We first ask for audio and video combined stream in order to get permissions and not to ask twice.
  78. * Then we dispose the stream and continue with separate audio, video streams(required for desktop sharing).
  79. */
  80. function obtainAudioAndVideoPermissions(callback){
  81. // This makes sense only on https sites otherwise we'll be asked for permissions every time
  82. if(location.protocol !== 'https:') {
  83. callback();
  84. return;
  85. }
  86. // Get AV
  87. getUserMediaWithConstraints(
  88. ['audio', 'video'],
  89. function(avStream) {
  90. avStream.stop();
  91. callback();
  92. },
  93. function(error){
  94. console.error('failed to obtain audio/video stream - stop', error);
  95. });
  96. }
  97. function audioStreamReady(stream) {
  98. change_local_audio(stream);
  99. if(RTC.browser !== 'firefox') {
  100. getUserMediaWithConstraints( ['video'], videoStreamReady, videoStreamFailed, config.resolution || '360' );
  101. } else {
  102. doJoin();
  103. }
  104. }
  105. function videoStreamReady(stream) {
  106. change_local_video(stream, true);
  107. doJoin();
  108. }
  109. function videoStreamFailed(error) {
  110. console.warn("Failed to obtain video stream - continue anyway", error);
  111. doJoin();
  112. }
  113. function doJoin() {
  114. var roomnode = null;
  115. var path = window.location.pathname;
  116. var roomjid;
  117. // determinde the room node from the url
  118. // TODO: just the roomnode or the whole bare jid?
  119. if (config.getroomnode && typeof config.getroomnode === 'function') {
  120. // custom function might be responsible for doing the pushstate
  121. roomnode = config.getroomnode(path);
  122. } else {
  123. /* fall back to default strategy
  124. * this is making assumptions about how the URL->room mapping happens.
  125. * It currently assumes deployment at root, with a rewrite like the
  126. * following one (for nginx):
  127. location ~ ^/([a-zA-Z0-9]+)$ {
  128. rewrite ^/(.*)$ / break;
  129. }
  130. */
  131. if (path.length > 1) {
  132. roomnode = path.substr(1).toLowerCase();
  133. } else {
  134. roomnode = Math.random().toString(36).substr(2, 20);
  135. window.history.pushState('VideoChat',
  136. 'Room: ' + roomnode, window.location.pathname + roomnode);
  137. }
  138. }
  139. roomjid = roomnode + '@' + config.hosts.muc;
  140. if (config.useNicks) {
  141. var nick = window.prompt('Your nickname (optional)');
  142. if (nick) {
  143. roomjid += '/' + nick;
  144. } else {
  145. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  146. }
  147. } else {
  148. roomjid += '/' + Strophe.getNodeFromJid(connection.jid).substr(0,8);
  149. }
  150. connection.emuc.doJoin(roomjid);
  151. }
  152. function change_local_audio(stream) {
  153. connection.jingle.localAudio = stream;
  154. RTC.attachMediaStream($('#localAudio'), stream);
  155. document.getElementById('localAudio').autoplay = true;
  156. document.getElementById('localAudio').volume = 0;
  157. }
  158. function change_local_video(stream, flipX) {
  159. connection.jingle.localVideo = stream;
  160. var localVideo = document.createElement('video');
  161. localVideo.id = 'localVideo_'+stream.id;
  162. localVideo.autoplay = true;
  163. localVideo.volume = 0; // is it required if audio is separated ?
  164. localVideo.oncontextmenu = function () { return false; };
  165. var localVideoContainer = document.getElementById('localVideoWrapper');
  166. localVideoContainer.appendChild(localVideo);
  167. var localVideoSelector = $('#' + localVideo.id);
  168. // Add click handler
  169. localVideoSelector.click(function () { handleVideoThumbClicked(localVideo.src); } );
  170. // Add stream ended handler
  171. stream.onended = function () {
  172. localVideoContainer.removeChild(localVideo);
  173. checkChangeLargeVideo(localVideo.src);
  174. };
  175. // Flip video x axis if needed
  176. flipXLocalVideo = flipX;
  177. if(flipX) {
  178. localVideoSelector.addClass("flipVideoX");
  179. }
  180. // Attach WebRTC stream
  181. RTC.attachMediaStream(localVideoSelector, stream);
  182. localVideoSrc = localVideo.src;
  183. updateLargeVideo(localVideoSrc, 0);
  184. }
  185. $(document).bind('remotestreamadded.jingle', function (event, data, sid) {
  186. function waitForRemoteVideo(selector, sid, ssrc) {
  187. if(selector.removed) {
  188. console.warn("media removed before had started", selector);
  189. return;
  190. }
  191. var sess = connection.jingle.sessions[sid];
  192. if (data.stream.id === 'mixedmslabel') return;
  193. var videoTracks = data.stream.getVideoTracks();
  194. console.log("waiting..", videoTracks, selector[0]);
  195. if (videoTracks.length === 0 || selector[0].currentTime > 0) {
  196. RTC.attachMediaStream(selector, data.stream); // FIXME: why do i have to do this for FF?
  197. // FIXME: add a class that will associate peer Jid, video.src, it's ssrc and video type
  198. // in order to get rid of too many maps
  199. if(ssrc) {
  200. videoSrcToSsrc[sel.attr('src')] = ssrc;
  201. } else {
  202. console.warn("No ssrc given for video", sel);
  203. }
  204. $(document).trigger('callactive.jingle', [selector, sid]);
  205. console.log('waitForremotevideo', sess.peerconnection.iceConnectionState, sess.peerconnection.signalingState);
  206. } else {
  207. setTimeout(function () { waitForRemoteVideo(selector, sid, ssrc); }, 250);
  208. }
  209. }
  210. var sess = connection.jingle.sessions[sid];
  211. var thessrc;
  212. // look up an associated JID for a stream id
  213. if (data.stream.id.indexOf('mixedmslabel') === -1) {
  214. var ssrclines = SDPUtil.find_lines(sess.peerconnection.remoteDescription.sdp, 'a=ssrc');
  215. ssrclines = ssrclines.filter(function (line) {
  216. return line.indexOf('mslabel:' + data.stream.label) !== -1;
  217. });
  218. if (ssrclines.length) {
  219. thessrc = ssrclines[0].substring(7).split(' ')[0];
  220. // ok to overwrite the one from focus? might save work in colibri.js
  221. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  222. if (ssrc2jid[thessrc]) {
  223. data.peerjid = ssrc2jid[thessrc];
  224. }
  225. }
  226. }
  227. var container;
  228. var remotes = document.getElementById('remoteVideos');
  229. if (data.peerjid) {
  230. container = document.getElementById(
  231. 'participant_' + Strophe.getResourceFromJid(data.peerjid));
  232. if (!container) {
  233. console.error('no container for', data.peerjid);
  234. } else {
  235. //console.log('found container for', data.peerjid);
  236. }
  237. } else {
  238. if (data.stream.id !== 'mixedmslabel') {
  239. console.error('can not associate stream', data.stream.id, 'with a participant');
  240. // We don't want to add it here since it will cause troubles
  241. return;
  242. }
  243. // FIXME: for the mixed ms we dont need a video -- currently
  244. container = document.createElement('span');
  245. container.className = 'videocontainer';
  246. remotes.appendChild(container);
  247. Util.playSoundNotification('userJoined');
  248. }
  249. var isVideo = data.stream.getVideoTracks().length > 0;
  250. var vid = isVideo ? document.createElement('video') : document.createElement('audio');
  251. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_') + sid + '_' + data.stream.id;
  252. vid.id = id;
  253. vid.autoplay = true;
  254. vid.oncontextmenu = function () { return false; };
  255. container.appendChild(vid);
  256. // TODO: make mixedstream display:none via css?
  257. if (id.indexOf('mixedmslabel') !== -1) {
  258. container.id = 'mixedstream';
  259. $(container).hide();
  260. }
  261. var sel = $('#' + id);
  262. sel.hide();
  263. RTC.attachMediaStream(sel, data.stream);
  264. if(isVideo) {
  265. waitForRemoteVideo(sel, sid, thessrc);
  266. }
  267. data.stream.onended = function () {
  268. console.log('stream ended', this.id);
  269. // Mark video as removed to cancel waiting loop(if video is removed before has started)
  270. sel.removed = true;
  271. sel.remove();
  272. var audioCount = $('#'+container.id+'>audio').length;
  273. var videoCount = $('#'+container.id+'>video').length;
  274. if(!audioCount && !videoCount) {
  275. console.log("Remove whole user");
  276. // Remove whole container
  277. container.remove();
  278. Util.playSoundNotification('userLeft');
  279. resizeThumbnails();
  280. }
  281. checkChangeLargeVideo(vid.src);
  282. };
  283. // Add click handler
  284. sel.click(function () { handleVideoThumbClicked(vid.src); });
  285. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  286. if (isVideo
  287. && data.peerjid && sess.peerjid === data.peerjid &&
  288. data.stream.getVideoTracks().length === 0 &&
  289. connection.jingle.localVideo.getVideoTracks().length > 0) {
  290. window.setTimeout(function() {
  291. sendKeyframe(sess.peerconnection);
  292. }, 3000);
  293. }
  294. });
  295. function handleVideoThumbClicked(videoSrc) {
  296. $(document).trigger("video.selected", [false]);
  297. updateLargeVideo(videoSrc, 1);
  298. $('audio').each(function (idx, el) {
  299. if (el.id.indexOf('mixedmslabel') !== -1) {
  300. el.volume = 0;
  301. el.volume = 1;
  302. }
  303. });
  304. }
  305. /**
  306. * Checks if removed video is currently displayed and tries to display another one instead.
  307. * @param removedVideoSrc src stream identifier of the video.
  308. */
  309. function checkChangeLargeVideo(removedVideoSrc){
  310. if (removedVideoSrc === $('#largeVideo').attr('src')) {
  311. // this is currently displayed as large
  312. // pick the last visible video in the row
  313. // if nobody else is left, this picks the local video
  314. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video').get(0);
  315. if(!pick) {
  316. console.info("Last visible video no longer exists");
  317. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  318. if(!pick) {
  319. // Try local video
  320. console.info("Fallback to local video...");
  321. pick = $('#remoteVideos>span>span>video').get(0);
  322. }
  323. }
  324. // mute if localvideo
  325. if (pick) {
  326. updateLargeVideo(pick.src, pick.volume);
  327. } else {
  328. console.warn("Failed to elect large video");
  329. }
  330. }
  331. }
  332. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  333. function sendKeyframe(pc) {
  334. console.log('sendkeyframe', pc.iceConnectionState);
  335. if (pc.iceConnectionState !== 'connected') return; // safe...
  336. pc.setRemoteDescription(
  337. pc.remoteDescription,
  338. function () {
  339. pc.createAnswer(
  340. function (modifiedAnswer) {
  341. pc.setLocalDescription(modifiedAnswer,
  342. function () {
  343. },
  344. function (error) {
  345. console.log('triggerKeyframe setLocalDescription failed', error);
  346. }
  347. );
  348. },
  349. function (error) {
  350. console.log('triggerKeyframe createAnswer failed', error);
  351. }
  352. );
  353. },
  354. function (error) {
  355. console.log('triggerKeyframe setRemoteDescription failed', error);
  356. }
  357. );
  358. }
  359. function demonstrateabug(pc) {
  360. // funny way of doing mute. the subsequent offer contains things like rtcp-mux
  361. // and triggers all new ice candidates (ice restart)
  362. // this code is here to demonstrate a bug
  363. pc.createOffer(
  364. function (offer) {
  365. console.log(offer);
  366. var sdp = new SDP(offer.sdp);
  367. if (sdp.media.length > 1) {
  368. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  369. sdp.raw = sdp.session + sdp.media.join('');
  370. offer.sdp = sdp.raw;
  371. pc.setLocalDescription(offer,
  372. function () {
  373. console.log('mute SLD ok');
  374. },
  375. function(error) {
  376. console.log('mute SLD error');
  377. }
  378. );
  379. }
  380. },
  381. function (error) {
  382. console.warn(error);
  383. },
  384. {mandatory: {OfferToReceiveAudio: true, OfferToReceiveVideo: false}}
  385. );
  386. }
  387. // really mute video, i.e. dont even send black frames
  388. function muteVideo(pc, unmute) {
  389. // FIXME: this probably needs another of those lovely state safeguards...
  390. // which checks for iceconn == connected and sigstate == stable
  391. pc.setRemoteDescription(pc.remoteDescription,
  392. function () {
  393. pc.createAnswer(
  394. function (answer) {
  395. var sdp = new SDP(answer.sdp);
  396. if (sdp.media.length > 1) {
  397. if (unmute)
  398. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  399. else
  400. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  401. sdp.raw = sdp.session + sdp.media.join('');
  402. answer.sdp = sdp.raw;
  403. }
  404. pc.setLocalDescription(answer,
  405. function () {
  406. console.log('mute SLD ok');
  407. },
  408. function(error) {
  409. console.log('mute SLD error');
  410. }
  411. );
  412. },
  413. function (error) {
  414. console.log(error);
  415. }
  416. );
  417. },
  418. function (error) {
  419. console.log('muteVideo SRD error');
  420. }
  421. );
  422. }
  423. $(document).bind('callincoming.jingle', function (event, sid) {
  424. var sess = connection.jingle.sessions[sid];
  425. // TODO: do we check activecall == null?
  426. activecall = sess;
  427. // TODO: check affiliation and/or role
  428. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  429. sess.usedrip = true; // not-so-naive trickle ice
  430. sess.sendAnswer();
  431. sess.accept();
  432. });
  433. $(document).bind('callactive.jingle', function (event, videoelem, sid) {
  434. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  435. // ignore mixedmslabela0 and v0
  436. videoelem.show();
  437. resizeThumbnails();
  438. updateLargeVideo(videoelem.attr('src'), 1);
  439. showFocusIndicator();
  440. }
  441. });
  442. $(document).bind('callterminated.jingle', function (event, sid, reason) {
  443. // FIXME
  444. });
  445. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  446. // put our ssrcs into presence so other clients can identify our stream
  447. var sess = connection.jingle.sessions[sid];
  448. var newssrcs = {};
  449. var directions = {};
  450. var localSDP = new SDP(sess.peerconnection.localDescription.sdp);
  451. localSDP.media.forEach(function (media) {
  452. var type = SDPUtil.parse_mline(media.split('\r\n')[0]).media;
  453. if (SDPUtil.find_line(media, 'a=ssrc:')) {
  454. // assumes a single local ssrc
  455. var ssrc = SDPUtil.find_line(media, 'a=ssrc:').substring(7).split(' ')[0];
  456. newssrcs[type] = ssrc;
  457. directions[type] = (
  458. SDPUtil.find_line(media, 'a=sendrecv')
  459. || SDPUtil.find_line(media, 'a=recvonly')
  460. || SDPUtil.find_line('a=sendonly')
  461. || SDPUtil.find_line('a=inactive')
  462. || 'a=sendrecv' ).substr(2);
  463. }
  464. });
  465. console.log('new ssrcs', newssrcs);
  466. // Have to clear presence map to get rid of removed streams
  467. connection.emuc.clearPresenceMedia();
  468. var i = 0;
  469. Object.keys(newssrcs).forEach(function (mtype) {
  470. i++;
  471. var type = mtype;
  472. // Change video type to screen
  473. if(mtype === 'video' && isUsingScreenStream) {
  474. type = 'screen';
  475. }
  476. connection.emuc.addMediaToPresence(i, type, newssrcs[mtype], directions[mtype]);
  477. });
  478. if (i > 0) {
  479. connection.emuc.sendPresence();
  480. }
  481. });
  482. $(document).bind('joined.muc', function (event, jid, info) {
  483. updateRoomUrl(window.location.href);
  484. document.getElementById('localNick').appendChild(
  485. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  486. );
  487. if (Object.keys(connection.emuc.members).length < 1) {
  488. focus = new ColibriFocus(connection, config.hosts.bridge);
  489. }
  490. if (focus && config.etherpad_base) {
  491. Etherpad.init();
  492. }
  493. showFocusIndicator();
  494. // Once we've joined the muc show the toolbar
  495. showToolbar();
  496. var displayName = '';
  497. if (info.displayName)
  498. displayName = info.displayName + ' (me)';
  499. showDisplayName('localVideoContainer', displayName);
  500. });
  501. $(document).bind('entered.muc', function (event, jid, info, pres) {
  502. console.log('entered', jid, info);
  503. console.log('is focus?' + focus ? 'true' : 'false');
  504. // Add Peer's container
  505. ensurePeerContainerExists(jid);
  506. if (focus !== null) {
  507. // FIXME: this should prepare the video
  508. if (focus.confid === null) {
  509. console.log('make new conference with', jid);
  510. focus.makeConference(Object.keys(connection.emuc.members));
  511. } else {
  512. console.log('invite', jid, 'into conference');
  513. focus.addNewParticipant(jid);
  514. }
  515. }
  516. else if (sharedKey) {
  517. updateLockButton();
  518. }
  519. });
  520. $(document).bind('left.muc', function (event, jid) {
  521. console.log('left', jid);
  522. connection.jingle.terminateByJid(jid);
  523. var container = document.getElementById('participant_' + Strophe.getResourceFromJid(jid));
  524. if (container) {
  525. // hide here, wait for video to close before removing
  526. $(container).hide();
  527. resizeThumbnails();
  528. }
  529. if (focus === null && connection.emuc.myroomjid === connection.emuc.list_members[0]) {
  530. console.log('welcome to our new focus... myself');
  531. focus = new ColibriFocus(connection, config.hosts.bridge);
  532. if (Object.keys(connection.emuc.members).length > 0) {
  533. focus.makeConference(Object.keys(connection.emuc.members));
  534. }
  535. $(document).trigger('focusechanged.muc', [focus]);
  536. }
  537. else if (focus && Object.keys(connection.emuc.members).length === 0) {
  538. console.log('everyone left');
  539. // FIXME: closing the connection is a hack to avoid some
  540. // problemswith reinit
  541. disposeConference();
  542. focus = new ColibriFocus(connection, config.hosts.bridge);
  543. }
  544. if (connection.emuc.getPrezi(jid)) {
  545. $(document).trigger('presentationremoved.muc', [jid, connection.emuc.getPrezi(jid)]);
  546. }
  547. });
  548. $(document).bind('presence.muc', function (event, jid, info, pres) {
  549. // Remove old ssrcs coming from the jid
  550. Object.keys(ssrc2jid).forEach(function(ssrc){
  551. if(ssrc2jid[ssrc] == jid){
  552. delete ssrc2jid[ssrc];
  553. }
  554. if(ssrc2videoType == jid){
  555. delete ssrc2videoType[ssrc];
  556. }
  557. });
  558. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  559. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  560. var ssrcV = ssrc.getAttribute('ssrc');
  561. ssrc2jid[ssrcV] = jid;
  562. var type = ssrc.getAttribute('type');
  563. ssrc2videoType[ssrcV] = type;
  564. // might need to update the direction if participant just went from sendrecv to recvonly
  565. if (type === 'video' || type === 'screen') {
  566. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  567. switch(ssrc.getAttribute('direction')) {
  568. case 'sendrecv':
  569. el.show();
  570. break;
  571. case 'recvonly':
  572. el.hide();
  573. // FIXME: Check if we have to change large video
  574. //checkChangeLargeVideo(el);
  575. break;
  576. }
  577. }
  578. });
  579. if (info.displayName) {
  580. if (jid === connection.emuc.myroomjid) {
  581. showDisplayName('localVideoContainer', info.displayName + ' (me)');
  582. } else {
  583. ensurePeerContainerExists(jid);
  584. showDisplayName('participant_' + Strophe.getResourceFromJid(jid), info.displayName);
  585. }
  586. }
  587. });
  588. $(document).bind('passwordrequired.muc', function (event, jid) {
  589. console.log('on password required', jid);
  590. $.prompt('<h2>Password required</h2>' +
  591. '<input id="lockKey" type="text" placeholder="shared key" autofocus>',
  592. {
  593. persistent: true,
  594. buttons: { "Ok": true , "Cancel": false},
  595. defaultButton: 1,
  596. loaded: function(event) {
  597. document.getElementById('lockKey').focus();
  598. },
  599. submit: function(e,v,m,f){
  600. if(v)
  601. {
  602. var lockKey = document.getElementById('lockKey');
  603. if (lockKey.value !== null)
  604. {
  605. setSharedKey(lockKey.value);
  606. connection.emuc.doJoin(jid, lockKey.value);
  607. }
  608. }
  609. }
  610. });
  611. });
  612. /**
  613. * Updates the large video with the given new video source.
  614. */
  615. function updateLargeVideo(newSrc, vol) {
  616. console.log('hover in', newSrc);
  617. if ($('#largeVideo').attr('src') != newSrc) {
  618. var isVisible = $('#largeVideo').is(':visible');
  619. $('#largeVideo').fadeOut(300, function () {
  620. $(this).attr('src', newSrc);
  621. // Screen stream is already rotated
  622. var flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  623. var videoTransform = document.getElementById('largeVideo').style.webkitTransform;
  624. if (flipX && videoTransform !== 'scaleX(-1)') {
  625. document.getElementById('largeVideo').style.webkitTransform = "scaleX(-1)";
  626. }
  627. else if (!flipX && videoTransform === 'scaleX(-1)') {
  628. document.getElementById('largeVideo').style.webkitTransform = "none";
  629. }
  630. // Change the way we'll be measuring and positioning large video
  631. var isDesktop = isVideoSrcDesktop(newSrc);
  632. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  633. getVideoPosition = isDesktop ? getDesktopVideoPosition : getCameraVideoPosition;
  634. if (isVisible)
  635. $(this).fadeIn(300);
  636. });
  637. }
  638. }
  639. /**
  640. * Checks if video identified by given src is desktop stream.
  641. * @param videoSrc eg. blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  642. * @returns {boolean}
  643. */
  644. function isVideoSrcDesktop(videoSrc){
  645. // FIXME: fix this mapping mess...
  646. // figure out if large video is desktop stream or just a camera
  647. var isDesktop = false;
  648. if(localVideoSrc === videoSrc) {
  649. // local video
  650. isDesktop = isUsingScreenStream;
  651. } else {
  652. // Do we have associations...
  653. var videoSsrc = videoSrcToSsrc[videoSrc];
  654. if(videoSsrc) {
  655. var videoType = ssrc2videoType[videoSsrc];
  656. if(videoType) {
  657. // Finally there...
  658. isDesktop = videoType === 'screen';
  659. } else {
  660. console.error("No video type for ssrc: " + videoSsrc);
  661. }
  662. } else {
  663. console.error("No ssrc for src: " + videoSrc);
  664. }
  665. }
  666. return isDesktop;
  667. }
  668. /**
  669. * Shows/hides the large video.
  670. */
  671. function setLargeVideoVisible(isVisible) {
  672. if (isVisible) {
  673. $('#largeVideo').css({visibility:'visible'});
  674. $('#watermark').css({visibility:'visible'});
  675. }
  676. else {
  677. $('#largeVideo').css({visibility:'hidden'});
  678. $('#watermark').css({visibility:'hidden'});
  679. }
  680. }
  681. function getConferenceHandler() {
  682. return focus ? focus : activecall;
  683. }
  684. function toggleVideo() {
  685. if (!(connection && connection.jingle.localVideo)) return;
  686. var sess = getConferenceHandler();
  687. if (sess) {
  688. sess.toggleVideoMute(
  689. function(isMuted){
  690. if(isMuted) {
  691. $('#video').removeClass("fa fa-video-camera fa-lg");
  692. $('#video').addClass("fa fa-video-camera no-fa-video-camera fa-lg");
  693. } else {
  694. $('#video').removeClass("fa fa-video-camera no-fa-video-camera fa-lg");
  695. $('#video').addClass("fa fa-video-camera fa-lg");
  696. }
  697. }
  698. );
  699. }
  700. var sess = focus || activecall;
  701. if (!sess) {
  702. return;
  703. }
  704. sess.pendingop = ismuted ? 'unmute' : 'mute';
  705. sess.modifySources();
  706. }
  707. function toggleAudio() {
  708. if (!(connection && connection.jingle.localAudio)) return;
  709. var localAudio = connection.jingle.localAudio;
  710. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  711. localAudio.getAudioTracks()[idx].enabled = !localAudio.getAudioTracks()[idx].enabled;
  712. }
  713. }
  714. /**
  715. * Positions the large video.
  716. *
  717. * @param videoWidth the stream video width
  718. * @param videoHeight the stream video height
  719. */
  720. var positionLarge = function(videoWidth, videoHeight) {
  721. var videoSpaceWidth = $('#videospace').width();
  722. var videoSpaceHeight = window.innerHeight;
  723. var videoSize = getVideoSize( videoWidth,
  724. videoHeight,
  725. videoSpaceWidth,
  726. videoSpaceHeight);
  727. var largeVideoWidth = videoSize[0];
  728. var largeVideoHeight = videoSize[1];
  729. var videoPosition = getVideoPosition( largeVideoWidth,
  730. largeVideoHeight,
  731. videoSpaceWidth,
  732. videoSpaceHeight);
  733. var horizontalIndent = videoPosition[0];
  734. var verticalIndent = videoPosition[1];
  735. positionVideo( $('#largeVideo'),
  736. largeVideoWidth,
  737. largeVideoHeight,
  738. horizontalIndent, verticalIndent);
  739. };
  740. /**
  741. * Returns an array of the video horizontal and vertical indents,
  742. * so that if fits its parent.
  743. *
  744. * @return an array with 2 elements, the horizontal indent and the vertical
  745. * indent
  746. */
  747. function getCameraVideoPosition( videoWidth,
  748. videoHeight,
  749. videoSpaceWidth,
  750. videoSpaceHeight) {
  751. // Parent height isn't completely calculated when we position the video in
  752. // full screen mode and this is why we use the screen height in this case.
  753. // Need to think it further at some point and implement it properly.
  754. var isFullScreen = document.fullScreen
  755. || document.mozFullScreen
  756. || document.webkitIsFullScreen;
  757. if (isFullScreen)
  758. videoSpaceHeight = window.innerHeight;
  759. var horizontalIndent = (videoSpaceWidth - videoWidth)/2;
  760. var verticalIndent = (videoSpaceHeight - videoHeight)/2;
  761. return [horizontalIndent, verticalIndent];
  762. }
  763. /**
  764. * Returns an array of the video horizontal and vertical indents.
  765. * Centers horizontally and top aligns vertically.
  766. *
  767. * @return an array with 2 elements, the horizontal indent and the vertical
  768. * indent
  769. */
  770. function getDesktopVideoPosition( videoWidth,
  771. videoHeight,
  772. videoSpaceWidth,
  773. videoSpaceHeight) {
  774. var horizontalIndent = (videoSpaceWidth - videoWidth)/2;
  775. var verticalIndent = 0;// Top aligned
  776. return [horizontalIndent, verticalIndent];
  777. }
  778. /**
  779. * Returns an array of the video dimensions, so that it covers the screen.
  780. * It leaves no empty areas, but some parts of the video might not be visible.
  781. *
  782. * @return an array with 2 elements, the video width and the video height
  783. */
  784. function getCameraVideoSize(videoWidth,
  785. videoHeight,
  786. videoSpaceWidth,
  787. videoSpaceHeight) {
  788. if (!videoWidth)
  789. videoWidth = currentVideoWidth;
  790. if (!videoHeight)
  791. videoHeight = currentVideoHeight;
  792. var aspectRatio = videoWidth / videoHeight;
  793. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  794. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  795. if (availableWidth / aspectRatio < videoSpaceHeight) {
  796. availableHeight = videoSpaceHeight;
  797. availableWidth = availableHeight*aspectRatio;
  798. }
  799. if (availableHeight*aspectRatio < videoSpaceWidth) {
  800. availableWidth = videoSpaceWidth;
  801. availableHeight = availableWidth / aspectRatio;
  802. }
  803. return [availableWidth, availableHeight];
  804. }
  805. /**
  806. * Returns an array of the video dimensions, so that it keeps it's aspect ratio and fits available area with it's
  807. * larger dimension. This method ensures that whole video will be visible and can leave empty areas.
  808. *
  809. * @return an array with 2 elements, the video width and the video height
  810. */
  811. function getDesktopVideoSize( videoWidth,
  812. videoHeight,
  813. videoSpaceWidth,
  814. videoSpaceHeight )
  815. {
  816. if (!videoWidth)
  817. videoWidth = currentVideoWidth;
  818. if (!videoHeight)
  819. videoHeight = currentVideoHeight;
  820. var aspectRatio = videoWidth / videoHeight;
  821. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  822. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  823. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  824. if (availableWidth / aspectRatio >= videoSpaceHeight)
  825. {
  826. availableHeight = videoSpaceHeight;
  827. availableWidth = availableHeight*aspectRatio;
  828. }
  829. if (availableHeight*aspectRatio >= videoSpaceWidth)
  830. {
  831. availableWidth = videoSpaceWidth;
  832. availableHeight = availableWidth / aspectRatio;
  833. }
  834. return [availableWidth, availableHeight];
  835. }
  836. /**
  837. * Sets the size and position of the given video element.
  838. *
  839. * @param video the video element to position
  840. * @param width the desired video width
  841. * @param height the desired video height
  842. * @param horizontalIndent the left and right indent
  843. * @param verticalIndent the top and bottom indent
  844. */
  845. function positionVideo( video,
  846. width,
  847. height,
  848. horizontalIndent,
  849. verticalIndent) {
  850. video.width(width);
  851. video.height(height);
  852. video.css({ top: verticalIndent + 'px',
  853. bottom: verticalIndent + 'px',
  854. left: horizontalIndent + 'px',
  855. right: horizontalIndent + 'px'});
  856. }
  857. var resizeLargeVideoContainer = function () {
  858. Chat.resizeChat();
  859. var availableHeight = window.innerHeight;
  860. var availableWidth = Util.getAvailableVideoWidth();
  861. if (availableWidth < 0 || availableHeight < 0) return;
  862. $('#videospace').width(availableWidth);
  863. $('#videospace').height(availableHeight);
  864. $('#largeVideoContainer').width(availableWidth);
  865. $('#largeVideoContainer').height(availableHeight);
  866. resizeThumbnails();
  867. };
  868. var calculateThumbnailSize = function() {
  869. // Calculate the available height, which is the inner window height minus
  870. // 39px for the header minus 2px for the delimiter lines on the top and
  871. // bottom of the large video, minus the 36px space inside the remoteVideos
  872. // container used for highlighting shadow.
  873. var availableHeight = 100;
  874. var numvids = $('#remoteVideos>span:visible').length;
  875. // Remove the 1px borders arround videos and the chat width.
  876. var availableWinWidth = $('#remoteVideos').width() - 2 * numvids - 50;
  877. var availableWidth = availableWinWidth / numvids;
  878. var aspectRatio = 16.0 / 9.0;
  879. var maxHeight = Math.min(160, availableHeight);
  880. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  881. if (availableHeight < availableWidth / aspectRatio) {
  882. availableWidth = Math.floor(availableHeight * aspectRatio);
  883. }
  884. return [availableWidth, availableHeight];
  885. };
  886. function resizeThumbnails() {
  887. var thumbnailSize = calculateThumbnailSize();
  888. var width = thumbnailSize[0];
  889. var height = thumbnailSize[1];
  890. // size videos so that while keeping AR and max height, we have a nice fit
  891. $('#remoteVideos').height(height);
  892. $('#remoteVideos>span').width(width);
  893. $('#remoteVideos>span').height(height);
  894. }
  895. $(document).ready(function () {
  896. Chat.init();
  897. // Set the defaults for prompt dialogs.
  898. jQuery.prompt.setDefaults({persistent: false});
  899. // Set default desktop sharing method
  900. setDesktopSharing(config.desktopSharing);
  901. // Initialize Chrome extension inline installs
  902. if(config.chromeExtensionId)
  903. {
  904. initInlineInstalls();
  905. }
  906. // By default we use camera
  907. getVideoSize = getCameraVideoSize;
  908. getVideoPosition = getCameraVideoPosition;
  909. resizeLargeVideoContainer();
  910. $(window).resize(function () {
  911. resizeLargeVideoContainer();
  912. positionLarge();
  913. });
  914. // Listen for large video size updates
  915. document.getElementById('largeVideo')
  916. .addEventListener('loadedmetadata', function(e){
  917. currentVideoWidth = this.videoWidth;
  918. currentVideoHeight = this.videoHeight;
  919. positionLarge(currentVideoWidth, currentVideoHeight);
  920. });
  921. if (!$('#settings').is(':visible')) {
  922. console.log('init');
  923. init();
  924. } else {
  925. loginInfo.onsubmit = function (e) {
  926. if (e.preventDefault) e.preventDefault();
  927. $('#settings').hide();
  928. init();
  929. };
  930. }
  931. });
  932. $(window).bind('beforeunload', function () {
  933. if (connection && connection.connected) {
  934. // ensure signout
  935. $.ajax({
  936. type: 'POST',
  937. url: config.bosh,
  938. async: false,
  939. cache: false,
  940. contentType: 'application/xml',
  941. data: "<body rid='" + (connection.rid || connection._proto.rid) + "' xmlns='http://jabber.org/protocol/httpbind' sid='" + (connection.sid || connection._proto.sid) + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  942. success: function (data) {
  943. console.log('signed out');
  944. console.log(data);
  945. },
  946. error: function (XMLHttpRequest, textStatus, errorThrown) {
  947. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  948. }
  949. });
  950. }
  951. disposeConference();
  952. });
  953. function disposeConference() {
  954. var handler = getConferenceHandler();
  955. if(handler && handler.peerconnection) {
  956. // FIXME: probably removing streams is not required and close() should be enough
  957. if(connection.jingle.localAudio) {
  958. handler.peerconnection.removeStream(connection.jingle.localAudio);
  959. }
  960. if(connection.jingle.localVideo) {
  961. handler.peerconnection.removeStream(connection.jingle.localVideo);
  962. }
  963. handler.peerconnection.close();
  964. }
  965. focus = null;
  966. activecall = null;
  967. }
  968. function dump(elem, filename){
  969. elem = elem.parentNode;
  970. elem.download = filename || 'meetlog.json';
  971. elem.href = 'data:application/json;charset=utf-8,\n';
  972. var data = {};
  973. if (connection.jingle) {
  974. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  975. var session = connection.jingle.sessions[sid];
  976. if (session.peerconnection && session.peerconnection.updateLog) {
  977. // FIXME: should probably be a .dump call
  978. data["jingle_" + session.sid] = {
  979. updateLog: session.peerconnection.updateLog,
  980. stats: session.peerconnection.stats,
  981. url: window.location.href}
  982. ;
  983. }
  984. });
  985. }
  986. metadata = {};
  987. metadata.time = new Date();
  988. metadata.url = window.location.href;
  989. metadata.ua = navigator.userAgent;
  990. if (connection.logger) {
  991. metadata.xmpp = connection.logger.log;
  992. }
  993. data.metadata = metadata;
  994. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  995. return false;
  996. }
  997. /**
  998. * Changes the style class of the element given by id.
  999. */
  1000. function buttonClick(id, classname) {
  1001. $(id).toggleClass(classname); // add the class to the clicked element
  1002. }
  1003. /**
  1004. * Opens the lock room dialog.
  1005. */
  1006. function openLockDialog() {
  1007. // Only the focus is able to set a shared key.
  1008. if (focus === null) {
  1009. if (sharedKey)
  1010. $.prompt("This conversation is currently protected by a shared secret key.",
  1011. {
  1012. title: "Secrect key",
  1013. persistent: false
  1014. });
  1015. else
  1016. $.prompt("This conversation isn't currently protected by a secret key. Only the owner of the conference could set a shared key.",
  1017. {
  1018. title: "Secrect key",
  1019. persistent: false
  1020. });
  1021. }
  1022. else {
  1023. if (sharedKey)
  1024. $.prompt("Are you sure you would like to remove your secret key?",
  1025. {
  1026. title: "Remove secrect key",
  1027. persistent: false,
  1028. buttons: { "Remove": true, "Cancel": false},
  1029. defaultButton: 1,
  1030. submit: function(e,v,m,f){
  1031. if(v)
  1032. {
  1033. setSharedKey('');
  1034. lockRoom(false);
  1035. }
  1036. }
  1037. });
  1038. else
  1039. $.prompt('<h2>Set a secrect key to lock your room</h2>' +
  1040. '<input id="lockKey" type="text" placeholder="your shared key" autofocus>',
  1041. {
  1042. persistent: false,
  1043. buttons: { "Save": true , "Cancel": false},
  1044. defaultButton: 1,
  1045. loaded: function(event) {
  1046. document.getElementById('lockKey').focus();
  1047. },
  1048. submit: function(e,v,m,f){
  1049. if(v)
  1050. {
  1051. var lockKey = document.getElementById('lockKey');
  1052. if (lockKey.value)
  1053. {
  1054. setSharedKey(Util.escapeHtml(lockKey.value));
  1055. lockRoom(true);
  1056. }
  1057. }
  1058. }
  1059. });
  1060. }
  1061. }
  1062. /**
  1063. * Opens the invite link dialog.
  1064. */
  1065. function openLinkDialog() {
  1066. $.prompt('<input id="inviteLinkRef" type="text" value="'
  1067. + encodeURI(roomUrl) + '" onclick="this.select();" readonly>',
  1068. {
  1069. title: "Share this link with everyone you want to invite",
  1070. persistent: false,
  1071. buttons: { "Cancel": false},
  1072. loaded: function(event) {
  1073. document.getElementById('inviteLinkRef').select();
  1074. }
  1075. });
  1076. }
  1077. /**
  1078. * Opens the settings dialog.
  1079. */
  1080. function openSettingsDialog() {
  1081. $.prompt('<h2>Configure your conference</h2>' +
  1082. '<input type="checkbox" id="initMuted"> Participants join muted<br/>' +
  1083. '<input type="checkbox" id="requireNicknames"> Require nicknames<br/><br/>' +
  1084. 'Set a secrect key to lock your room: <input id="lockKey" type="text" placeholder="your shared key" autofocus>',
  1085. {
  1086. persistent: false,
  1087. buttons: { "Save": true , "Cancel": false},
  1088. defaultButton: 1,
  1089. loaded: function(event) {
  1090. document.getElementById('lockKey').focus();
  1091. },
  1092. submit: function(e,v,m,f){
  1093. if(v)
  1094. {
  1095. if ($('#initMuted').is(":checked"))
  1096. {
  1097. // it is checked
  1098. }
  1099. if ($('#requireNicknames').is(":checked"))
  1100. {
  1101. // it is checked
  1102. }
  1103. /*
  1104. var lockKey = document.getElementById('lockKey');
  1105. if (lockKey.value)
  1106. {
  1107. setSharedKey(lockKey.value);
  1108. lockRoom(true);
  1109. }
  1110. */
  1111. }
  1112. }
  1113. });
  1114. }
  1115. /**
  1116. * Locks / unlocks the room.
  1117. */
  1118. function lockRoom(lock) {
  1119. if (lock)
  1120. connection.emuc.lockRoom(sharedKey);
  1121. else
  1122. connection.emuc.lockRoom('');
  1123. updateLockButton();
  1124. }
  1125. /**
  1126. * Sets the shared key.
  1127. */
  1128. function setSharedKey(sKey) {
  1129. sharedKey = sKey;
  1130. }
  1131. /**
  1132. * Updates the lock button state.
  1133. */
  1134. function updateLockButton() {
  1135. buttonClick("#lockIcon", "icon-security icon-security-locked");
  1136. }
  1137. /**
  1138. * Hides the toolbar.
  1139. */
  1140. var hideToolbar = function() {
  1141. var isToolbarHover = false;
  1142. $('#header').find('*').each(function(){
  1143. var id = $(this).attr('id');
  1144. if ($("#" + id + ":hover").length > 0) {
  1145. isToolbarHover = true;
  1146. }
  1147. });
  1148. clearTimeout(toolbarTimeout);
  1149. toolbarTimeout = null;
  1150. if (!isToolbarHover) {
  1151. $('#header').hide("slide", { direction: "up", duration: 300});
  1152. }
  1153. else {
  1154. toolbarTimeout = setTimeout(hideToolbar, 2000);
  1155. }
  1156. };
  1157. /**
  1158. * Shows the call main toolbar.
  1159. */
  1160. function showToolbar() {
  1161. if (!$('#header').is(':visible')) {
  1162. $('#header').show("slide", { direction: "up", duration: 300});
  1163. if (toolbarTimeout) {
  1164. clearTimeout(toolbarTimeout);
  1165. toolbarTimeout = null;
  1166. }
  1167. toolbarTimeout = setTimeout(hideToolbar, 2000);
  1168. }
  1169. if (focus != null)
  1170. {
  1171. // TODO: Enable settings functionality. Need to uncomment the settings button in index.html.
  1172. // $('#settingsButton').css({visibility:"visible"});
  1173. }
  1174. // Show/hide desktop sharing button
  1175. showDesktopSharingButton();
  1176. }
  1177. /**
  1178. * Docks/undocks the toolbar.
  1179. *
  1180. * @param isDock indicates what operation to perform
  1181. */
  1182. function dockToolbar(isDock) {
  1183. if (isDock) {
  1184. // First make sure the toolbar is shown.
  1185. if (!$('#header').is(':visible')) {
  1186. showToolbar();
  1187. }
  1188. // Then clear the time out, to dock the toolbar.
  1189. clearTimeout(toolbarTimeout);
  1190. toolbarTimeout = null;
  1191. }
  1192. else {
  1193. if (!$('#header').is(':visible')) {
  1194. showToolbar();
  1195. }
  1196. else {
  1197. toolbarTimeout = setTimeout(hideToolbar, 2000);
  1198. }
  1199. }
  1200. }
  1201. /**
  1202. * Updates the room invite url.
  1203. */
  1204. function updateRoomUrl(newRoomUrl) {
  1205. roomUrl = newRoomUrl;
  1206. }
  1207. /**
  1208. * Warning to the user that the conference window is about to be closed.
  1209. */
  1210. function closePageWarning() {
  1211. if (focus !== null)
  1212. return "You are the owner of this conference call and you are about to end it.";
  1213. else
  1214. return "You are about to leave this conversation.";
  1215. }
  1216. /**
  1217. * Shows a visual indicator for the focus of the conference.
  1218. * Currently if we're not the owner of the conference we obtain the focus
  1219. * from the connection.jingle.sessions.
  1220. */
  1221. function showFocusIndicator() {
  1222. if (focus !== null) {
  1223. var indicatorSpan = $('#localVideoContainer .focusindicator');
  1224. if (indicatorSpan.children().length === 0)
  1225. {
  1226. createFocusIndicatorElement(indicatorSpan[0]);
  1227. }
  1228. }
  1229. else if (Object.keys(connection.jingle.sessions).length > 0) {
  1230. // If we're only a participant the focus will be the only session we have.
  1231. var session = connection.jingle.sessions[Object.keys(connection.jingle.sessions)[0]];
  1232. var focusId = 'participant_' + Strophe.getResourceFromJid(session.peerjid);
  1233. var focusContainer = document.getElementById(focusId);
  1234. if(!focusContainer) {
  1235. console.error("No focus container!");
  1236. return;
  1237. }
  1238. var indicatorSpan = $('#' + focusId + ' .focusindicator');
  1239. if (!indicatorSpan || indicatorSpan.length === 0) {
  1240. indicatorSpan = document.createElement('span');
  1241. indicatorSpan.className = 'focusindicator';
  1242. focusContainer.appendChild(indicatorSpan);
  1243. createFocusIndicatorElement(indicatorSpan);
  1244. }
  1245. }
  1246. }
  1247. /**
  1248. * Checks if container for participant identified by given peerJid exists in the document and creates it eventually.
  1249. * @param peerJid peer Jid to check.
  1250. */
  1251. function ensurePeerContainerExists(peerJid){
  1252. var peerResource = Strophe.getResourceFromJid(peerJid);
  1253. var videoSpanId = 'participant_' + peerResource;
  1254. if($('#'+videoSpanId).length > 0) {
  1255. return;
  1256. }
  1257. var container = addRemoteVideoContainer(videoSpanId);
  1258. var nickfield = document.createElement('span');
  1259. nickfield.className = "nick";
  1260. nickfield.appendChild(document.createTextNode(peerResource));
  1261. container.appendChild(nickfield);
  1262. resizeThumbnails();
  1263. }
  1264. function addRemoteVideoContainer(id) {
  1265. var container = document.createElement('span');
  1266. container.id = id;
  1267. container.className = 'videocontainer';
  1268. var remotes = document.getElementById('remoteVideos');
  1269. remotes.appendChild(container);
  1270. return container;
  1271. }
  1272. /**
  1273. * Creates the element indicating the focus of the conference.
  1274. */
  1275. function createFocusIndicatorElement(parentElement) {
  1276. var focusIndicator = document.createElement('i');
  1277. focusIndicator.className = 'fa fa-star';
  1278. focusIndicator.title = "The owner of this conference";
  1279. parentElement.appendChild(focusIndicator);
  1280. }
  1281. /**
  1282. * Toggles the application in and out of full screen mode
  1283. * (a.k.a. presentation mode in Chrome).
  1284. */
  1285. function toggleFullScreen() {
  1286. var fsElement = document.documentElement;
  1287. if (!document.mozFullScreen && !document.webkitIsFullScreen){
  1288. //Enter Full Screen
  1289. if (fsElement.mozRequestFullScreen) {
  1290. fsElement.mozRequestFullScreen();
  1291. }
  1292. else {
  1293. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  1294. }
  1295. } else {
  1296. //Exit Full Screen
  1297. if (document.mozCancelFullScreen) {
  1298. document.mozCancelFullScreen();
  1299. } else {
  1300. document.webkitCancelFullScreen();
  1301. }
  1302. }
  1303. }
  1304. /**
  1305. * Shows the display name for the given video.
  1306. */
  1307. function showDisplayName(videoSpanId, displayName) {
  1308. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  1309. // If we already have a display name for this video.
  1310. if (nameSpan.length > 0) {
  1311. var nameSpanElement = nameSpan.get(0);
  1312. if (nameSpanElement.id === 'localDisplayName'
  1313. && $('#localDisplayName').text() !== displayName)
  1314. $('#localDisplayName').text(displayName);
  1315. else
  1316. $('#' + videoSpanId + '_name').text(displayName);
  1317. }
  1318. else {
  1319. var editButton = null;
  1320. if (videoSpanId === 'localVideoContainer') {
  1321. editButton = createEditDisplayNameButton();
  1322. }
  1323. if (displayName.length) {
  1324. nameSpan = document.createElement('span');
  1325. nameSpan.className = 'displayname';
  1326. nameSpan.innerText = displayName;
  1327. $('#' + videoSpanId)[0].appendChild(nameSpan);
  1328. }
  1329. if (!editButton) {
  1330. nameSpan.id = videoSpanId + '_name';
  1331. }
  1332. else {
  1333. nameSpan.id = 'localDisplayName';
  1334. $('#' + videoSpanId)[0].appendChild(editButton);
  1335. var editableText = document.createElement('input');
  1336. editableText.className = 'displayname';
  1337. editableText.id = 'editDisplayName';
  1338. if (displayName.length)
  1339. editableText.value
  1340. = displayName.substring(0, displayName.indexOf(' (me)'));
  1341. editableText.setAttribute('style', 'display:none;');
  1342. editableText.setAttribute('placeholder', 'ex. Jane Pink');
  1343. $('#' + videoSpanId)[0].appendChild(editableText);
  1344. $('#localVideoContainer .displayname').bind("click", function(e) {
  1345. e.preventDefault();
  1346. $('#localDisplayName').hide();
  1347. $('#editDisplayName').show();
  1348. $('#editDisplayName').focus();
  1349. $('#editDisplayName').select();
  1350. var inputDisplayNameHandler = function(name) {
  1351. if (nickname !== name) {
  1352. nickname = name;
  1353. window.localStorage.displayname = nickname;
  1354. connection.emuc.addDisplayNameToPresence(nickname);
  1355. connection.emuc.sendPresence();
  1356. Chat.setChatConversationMode(true);
  1357. }
  1358. if (!$('#localDisplayName').is(":visible")) {
  1359. $('#localDisplayName').text(nickname + " (me)");
  1360. $('#localDisplayName').show();
  1361. $('#editDisplayName').hide();
  1362. }
  1363. };
  1364. $('#editDisplayName').one("focusout", function (e) {
  1365. inputDisplayNameHandler(this.value);
  1366. });
  1367. $('#editDisplayName').on('keydown', function (e) {
  1368. if (e.keyCode === 13) {
  1369. e.preventDefault();
  1370. inputDisplayNameHandler(this.value);
  1371. }
  1372. });
  1373. });
  1374. }
  1375. }
  1376. }
  1377. /**
  1378. * Creates the edit display name button.
  1379. *
  1380. * @returns the edit button
  1381. */
  1382. function createEditDisplayNameButton() {
  1383. var editButton = document.createElement('a');
  1384. editButton.className = 'displayname';
  1385. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  1386. return editButton;
  1387. }
  1388. /**
  1389. * Resizes and repositions videos in full screen mode.
  1390. */
  1391. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1392. function() {
  1393. resizeLargeVideoContainer();
  1394. positionLarge();
  1395. isFullScreen = document.fullScreen
  1396. || document.mozFullScreen
  1397. || document.webkitIsFullScreen;
  1398. if (isFullScreen) {
  1399. setView("fullscreen");
  1400. }
  1401. else {
  1402. setView("default");
  1403. }
  1404. });
  1405. /**
  1406. * Sets the current view.
  1407. */
  1408. function setView(viewName) {
  1409. // if (viewName == "fullscreen") {
  1410. // document.getElementById('videolayout_fullscreen').disabled = false;
  1411. // document.getElementById('videolayout_default').disabled = true;
  1412. // }
  1413. // else {
  1414. // document.getElementById('videolayout_default').disabled = false;
  1415. // document.getElementById('videolayout_fullscreen').disabled = true;
  1416. // }
  1417. }