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.

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