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.

app.js 52KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619
  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. // By default we use camera
  902. getVideoSize = getCameraVideoSize;
  903. getVideoPosition = getCameraVideoPosition;
  904. resizeLargeVideoContainer();
  905. $(window).resize(function () {
  906. resizeLargeVideoContainer();
  907. positionLarge();
  908. });
  909. // Listen for large video size updates
  910. document.getElementById('largeVideo')
  911. .addEventListener('loadedmetadata', function(e){
  912. currentVideoWidth = this.videoWidth;
  913. currentVideoHeight = this.videoHeight;
  914. positionLarge(currentVideoWidth, currentVideoHeight);
  915. });
  916. if (!$('#settings').is(':visible')) {
  917. console.log('init');
  918. init();
  919. } else {
  920. loginInfo.onsubmit = function (e) {
  921. if (e.preventDefault) e.preventDefault();
  922. $('#settings').hide();
  923. init();
  924. };
  925. }
  926. });
  927. $(window).bind('beforeunload', function () {
  928. if (connection && connection.connected) {
  929. // ensure signout
  930. $.ajax({
  931. type: 'POST',
  932. url: config.bosh,
  933. async: false,
  934. cache: false,
  935. contentType: 'application/xml',
  936. 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>",
  937. success: function (data) {
  938. console.log('signed out');
  939. console.log(data);
  940. },
  941. error: function (XMLHttpRequest, textStatus, errorThrown) {
  942. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  943. }
  944. });
  945. }
  946. disposeConference();
  947. });
  948. function disposeConference() {
  949. var handler = getConferenceHandler();
  950. if(handler && handler.peerconnection) {
  951. // FIXME: probably removing streams is not required and close() should be enough
  952. if(connection.jingle.localAudio) {
  953. handler.peerconnection.removeStream(connection.jingle.localAudio);
  954. }
  955. if(connection.jingle.localVideo) {
  956. handler.peerconnection.removeStream(connection.jingle.localVideo);
  957. }
  958. handler.peerconnection.close();
  959. }
  960. focus = null;
  961. activecall = null;
  962. }
  963. function dump(elem, filename){
  964. elem = elem.parentNode;
  965. elem.download = filename || 'meetlog.json';
  966. elem.href = 'data:application/json;charset=utf-8,\n';
  967. var data = {};
  968. if (connection.jingle) {
  969. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  970. var session = connection.jingle.sessions[sid];
  971. if (session.peerconnection && session.peerconnection.updateLog) {
  972. // FIXME: should probably be a .dump call
  973. data["jingle_" + session.sid] = {
  974. updateLog: session.peerconnection.updateLog,
  975. stats: session.peerconnection.stats,
  976. url: window.location.href}
  977. ;
  978. }
  979. });
  980. }
  981. metadata = {};
  982. metadata.time = new Date();
  983. metadata.url = window.location.href;
  984. metadata.ua = navigator.userAgent;
  985. if (connection.logger) {
  986. metadata.xmpp = connection.logger.log;
  987. }
  988. data.metadata = metadata;
  989. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  990. return false;
  991. }
  992. /**
  993. * Changes the style class of the element given by id.
  994. */
  995. function buttonClick(id, classname) {
  996. $(id).toggleClass(classname); // add the class to the clicked element
  997. }
  998. /**
  999. * Opens the lock room dialog.
  1000. */
  1001. function openLockDialog() {
  1002. // Only the focus is able to set a shared key.
  1003. if (focus === null) {
  1004. if (sharedKey)
  1005. $.prompt("This conversation is currently protected by a shared secret key.",
  1006. {
  1007. title: "Secrect key",
  1008. persistent: false
  1009. });
  1010. else
  1011. $.prompt("This conversation isn't currently protected by a secret key. Only the owner of the conference could set a shared key.",
  1012. {
  1013. title: "Secrect key",
  1014. persistent: false
  1015. });
  1016. }
  1017. else {
  1018. if (sharedKey)
  1019. $.prompt("Are you sure you would like to remove your secret key?",
  1020. {
  1021. title: "Remove secrect key",
  1022. persistent: false,
  1023. buttons: { "Remove": true, "Cancel": false},
  1024. defaultButton: 1,
  1025. submit: function(e,v,m,f){
  1026. if(v)
  1027. {
  1028. setSharedKey('');
  1029. lockRoom(false);
  1030. }
  1031. }
  1032. });
  1033. else
  1034. $.prompt('<h2>Set a secrect key to lock your room</h2>' +
  1035. '<input id="lockKey" type="text" placeholder="your shared key" autofocus>',
  1036. {
  1037. persistent: false,
  1038. buttons: { "Save": true , "Cancel": false},
  1039. defaultButton: 1,
  1040. loaded: function(event) {
  1041. document.getElementById('lockKey').focus();
  1042. },
  1043. submit: function(e,v,m,f){
  1044. if(v)
  1045. {
  1046. var lockKey = document.getElementById('lockKey');
  1047. if (lockKey.value)
  1048. {
  1049. setSharedKey(Util.escapeHtml(lockKey.value));
  1050. lockRoom(true);
  1051. }
  1052. }
  1053. }
  1054. });
  1055. }
  1056. }
  1057. /**
  1058. * Opens the invite link dialog.
  1059. */
  1060. function openLinkDialog() {
  1061. $.prompt('<input id="inviteLinkRef" type="text" value="'
  1062. + encodeURI(roomUrl) + '" onclick="this.select();" readonly>',
  1063. {
  1064. title: "Share this link with everyone you want to invite",
  1065. persistent: false,
  1066. buttons: { "Cancel": false},
  1067. loaded: function(event) {
  1068. document.getElementById('inviteLinkRef').select();
  1069. }
  1070. });
  1071. }
  1072. /**
  1073. * Opens the settings dialog.
  1074. */
  1075. function openSettingsDialog() {
  1076. $.prompt('<h2>Configure your conference</h2>' +
  1077. '<input type="checkbox" id="initMuted"> Participants join muted<br/>' +
  1078. '<input type="checkbox" id="requireNicknames"> Require nicknames<br/><br/>' +
  1079. 'Set a secrect key to lock your room: <input id="lockKey" type="text" placeholder="your shared key" autofocus>',
  1080. {
  1081. persistent: false,
  1082. buttons: { "Save": true , "Cancel": false},
  1083. defaultButton: 1,
  1084. loaded: function(event) {
  1085. document.getElementById('lockKey').focus();
  1086. },
  1087. submit: function(e,v,m,f){
  1088. if(v)
  1089. {
  1090. if ($('#initMuted').is(":checked"))
  1091. {
  1092. // it is checked
  1093. }
  1094. if ($('#requireNicknames').is(":checked"))
  1095. {
  1096. // it is checked
  1097. }
  1098. /*
  1099. var lockKey = document.getElementById('lockKey');
  1100. if (lockKey.value)
  1101. {
  1102. setSharedKey(lockKey.value);
  1103. lockRoom(true);
  1104. }
  1105. */
  1106. }
  1107. }
  1108. });
  1109. }
  1110. /**
  1111. * Locks / unlocks the room.
  1112. */
  1113. function lockRoom(lock) {
  1114. if (lock)
  1115. connection.emuc.lockRoom(sharedKey);
  1116. else
  1117. connection.emuc.lockRoom('');
  1118. updateLockButton();
  1119. }
  1120. /**
  1121. * Sets the shared key.
  1122. */
  1123. function setSharedKey(sKey) {
  1124. sharedKey = sKey;
  1125. }
  1126. /**
  1127. * Updates the lock button state.
  1128. */
  1129. function updateLockButton() {
  1130. buttonClick("#lockIcon", "icon-security icon-security-locked");
  1131. }
  1132. /**
  1133. * Hides the toolbar.
  1134. */
  1135. var hideToolbar = function() {
  1136. var isToolbarHover = false;
  1137. $('#header').find('*').each(function(){
  1138. var id = $(this).attr('id');
  1139. if ($("#" + id + ":hover").length > 0) {
  1140. isToolbarHover = true;
  1141. }
  1142. });
  1143. clearTimeout(toolbarTimeout);
  1144. toolbarTimeout = null;
  1145. if (!isToolbarHover) {
  1146. $('#header').hide("slide", { direction: "up", duration: 300});
  1147. }
  1148. else {
  1149. toolbarTimeout = setTimeout(hideToolbar, 2000);
  1150. }
  1151. };
  1152. /**
  1153. * Shows the call main toolbar.
  1154. */
  1155. function showToolbar() {
  1156. if (!$('#header').is(':visible')) {
  1157. $('#header').show("slide", { direction: "up", duration: 300});
  1158. if (toolbarTimeout) {
  1159. clearTimeout(toolbarTimeout);
  1160. toolbarTimeout = null;
  1161. }
  1162. toolbarTimeout = setTimeout(hideToolbar, 2000);
  1163. }
  1164. if (focus != null)
  1165. {
  1166. // TODO: Enable settings functionality. Need to uncomment the settings button in index.html.
  1167. // $('#settingsButton').css({visibility:"visible"});
  1168. }
  1169. // Show/hide desktop sharing button
  1170. showDesktopSharingButton();
  1171. }
  1172. /**
  1173. * Docks/undocks the toolbar.
  1174. *
  1175. * @param isDock indicates what operation to perform
  1176. */
  1177. function dockToolbar(isDock) {
  1178. if (isDock) {
  1179. // First make sure the toolbar is shown.
  1180. if (!$('#header').is(':visible')) {
  1181. showToolbar();
  1182. }
  1183. // Then clear the time out, to dock the toolbar.
  1184. clearTimeout(toolbarTimeout);
  1185. toolbarTimeout = null;
  1186. }
  1187. else {
  1188. if (!$('#header').is(':visible')) {
  1189. showToolbar();
  1190. }
  1191. else {
  1192. toolbarTimeout = setTimeout(hideToolbar, 2000);
  1193. }
  1194. }
  1195. }
  1196. /**
  1197. * Updates the room invite url.
  1198. */
  1199. function updateRoomUrl(newRoomUrl) {
  1200. roomUrl = newRoomUrl;
  1201. }
  1202. /**
  1203. * Warning to the user that the conference window is about to be closed.
  1204. */
  1205. function closePageWarning() {
  1206. if (focus !== null)
  1207. return "You are the owner of this conference call and you are about to end it.";
  1208. else
  1209. return "You are about to leave this conversation.";
  1210. }
  1211. /**
  1212. * Shows a visual indicator for the focus of the conference.
  1213. * Currently if we're not the owner of the conference we obtain the focus
  1214. * from the connection.jingle.sessions.
  1215. */
  1216. function showFocusIndicator() {
  1217. if (focus !== null) {
  1218. var indicatorSpan = $('#localVideoContainer .focusindicator');
  1219. if (indicatorSpan.children().length === 0)
  1220. {
  1221. createFocusIndicatorElement(indicatorSpan[0]);
  1222. }
  1223. }
  1224. else if (Object.keys(connection.jingle.sessions).length > 0) {
  1225. // If we're only a participant the focus will be the only session we have.
  1226. var session = connection.jingle.sessions[Object.keys(connection.jingle.sessions)[0]];
  1227. var focusId = 'participant_' + Strophe.getResourceFromJid(session.peerjid);
  1228. var focusContainer = document.getElementById(focusId);
  1229. if(!focusContainer) {
  1230. console.error("No focus container!");
  1231. return;
  1232. }
  1233. var indicatorSpan = $('#' + focusId + ' .focusindicator');
  1234. if (!indicatorSpan || indicatorSpan.length === 0) {
  1235. indicatorSpan = document.createElement('span');
  1236. indicatorSpan.className = 'focusindicator';
  1237. focusContainer.appendChild(indicatorSpan);
  1238. createFocusIndicatorElement(indicatorSpan);
  1239. }
  1240. }
  1241. }
  1242. /**
  1243. * Checks if container for participant identified by given peerJid exists in the document and creates it eventually.
  1244. * @param peerJid peer Jid to check.
  1245. */
  1246. function ensurePeerContainerExists(peerJid){
  1247. var peerResource = Strophe.getResourceFromJid(peerJid);
  1248. var videoSpanId = 'participant_' + peerResource;
  1249. if($('#'+videoSpanId).length > 0) {
  1250. return;
  1251. }
  1252. var container = addRemoteVideoContainer(videoSpanId);
  1253. var nickfield = document.createElement('span');
  1254. nickfield.className = "nick";
  1255. nickfield.appendChild(document.createTextNode(peerResource));
  1256. container.appendChild(nickfield);
  1257. resizeThumbnails();
  1258. }
  1259. function addRemoteVideoContainer(id) {
  1260. var container = document.createElement('span');
  1261. container.id = id;
  1262. container.className = 'videocontainer';
  1263. var remotes = document.getElementById('remoteVideos');
  1264. remotes.appendChild(container);
  1265. return container;
  1266. }
  1267. /**
  1268. * Creates the element indicating the focus of the conference.
  1269. */
  1270. function createFocusIndicatorElement(parentElement) {
  1271. var focusIndicator = document.createElement('i');
  1272. focusIndicator.className = 'fa fa-star';
  1273. focusIndicator.title = "The owner of this conference";
  1274. parentElement.appendChild(focusIndicator);
  1275. }
  1276. /**
  1277. * Toggles the application in and out of full screen mode
  1278. * (a.k.a. presentation mode in Chrome).
  1279. */
  1280. function toggleFullScreen() {
  1281. var fsElement = document.documentElement;
  1282. if (!document.mozFullScreen && !document.webkitIsFullScreen){
  1283. //Enter Full Screen
  1284. if (fsElement.mozRequestFullScreen) {
  1285. fsElement.mozRequestFullScreen();
  1286. }
  1287. else {
  1288. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  1289. }
  1290. } else {
  1291. //Exit Full Screen
  1292. if (document.mozCancelFullScreen) {
  1293. document.mozCancelFullScreen();
  1294. } else {
  1295. document.webkitCancelFullScreen();
  1296. }
  1297. }
  1298. }
  1299. /**
  1300. * Shows the display name for the given video.
  1301. */
  1302. function showDisplayName(videoSpanId, displayName) {
  1303. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  1304. // If we already have a display name for this video.
  1305. if (nameSpan.length > 0) {
  1306. var nameSpanElement = nameSpan.get(0);
  1307. if (nameSpanElement.id === 'localDisplayName'
  1308. && $('#localDisplayName').text() !== displayName)
  1309. $('#localDisplayName').text(displayName);
  1310. else
  1311. $('#' + videoSpanId + '_name').text(displayName);
  1312. }
  1313. else {
  1314. var editButton = null;
  1315. if (videoSpanId === 'localVideoContainer') {
  1316. editButton = createEditDisplayNameButton();
  1317. }
  1318. if (displayName.length) {
  1319. nameSpan = document.createElement('span');
  1320. nameSpan.className = 'displayname';
  1321. nameSpan.innerText = displayName;
  1322. $('#' + videoSpanId)[0].appendChild(nameSpan);
  1323. }
  1324. if (!editButton) {
  1325. nameSpan.id = videoSpanId + '_name';
  1326. }
  1327. else {
  1328. nameSpan.id = 'localDisplayName';
  1329. $('#' + videoSpanId)[0].appendChild(editButton);
  1330. var editableText = document.createElement('input');
  1331. editableText.className = 'displayname';
  1332. editableText.id = 'editDisplayName';
  1333. if (displayName.length)
  1334. editableText.value
  1335. = displayName.substring(0, displayName.indexOf(' (me)'));
  1336. editableText.setAttribute('style', 'display:none;');
  1337. editableText.setAttribute('placeholder', 'ex. Jane Pink');
  1338. $('#' + videoSpanId)[0].appendChild(editableText);
  1339. $('#localVideoContainer .displayname').bind("click", function(e) {
  1340. e.preventDefault();
  1341. $('#localDisplayName').hide();
  1342. $('#editDisplayName').show();
  1343. $('#editDisplayName').focus();
  1344. $('#editDisplayName').select();
  1345. var inputDisplayNameHandler = function(name) {
  1346. if (nickname !== name) {
  1347. nickname = name;
  1348. window.localStorage.displayname = nickname;
  1349. connection.emuc.addDisplayNameToPresence(nickname);
  1350. connection.emuc.sendPresence();
  1351. Chat.setChatConversationMode(true);
  1352. }
  1353. if (!$('#localDisplayName').is(":visible")) {
  1354. $('#localDisplayName').text(nickname + " (me)");
  1355. $('#localDisplayName').show();
  1356. $('#editDisplayName').hide();
  1357. }
  1358. };
  1359. $('#editDisplayName').one("focusout", function (e) {
  1360. inputDisplayNameHandler(this.value);
  1361. });
  1362. $('#editDisplayName').on('keydown', function (e) {
  1363. if (e.keyCode === 13) {
  1364. e.preventDefault();
  1365. inputDisplayNameHandler(this.value);
  1366. }
  1367. });
  1368. });
  1369. }
  1370. }
  1371. }
  1372. /**
  1373. * Creates the edit display name button.
  1374. *
  1375. * @returns the edit button
  1376. */
  1377. function createEditDisplayNameButton() {
  1378. var editButton = document.createElement('a');
  1379. editButton.className = 'displayname';
  1380. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  1381. return editButton;
  1382. }
  1383. /**
  1384. * Resizes and repositions videos in full screen mode.
  1385. */
  1386. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1387. function() {
  1388. resizeLargeVideoContainer();
  1389. positionLarge();
  1390. isFullScreen = document.fullScreen
  1391. || document.mozFullScreen
  1392. || document.webkitIsFullScreen;
  1393. if (isFullScreen) {
  1394. setView("fullscreen");
  1395. }
  1396. else {
  1397. setView("default");
  1398. }
  1399. });
  1400. /**
  1401. * Sets the current view.
  1402. */
  1403. function setView(viewName) {
  1404. // if (viewName == "fullscreen") {
  1405. // document.getElementById('videolayout_fullscreen').disabled = false;
  1406. // document.getElementById('videolayout_default').disabled = true;
  1407. // }
  1408. // else {
  1409. // document.getElementById('videolayout_default').disabled = false;
  1410. // document.getElementById('videolayout_fullscreen').disabled = true;
  1411. // }
  1412. }