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.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691
  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. // really mute video, i.e. dont even send black frames
  360. function muteVideo(pc, unmute) {
  361. // FIXME: this probably needs another of those lovely state safeguards...
  362. // which checks for iceconn == connected and sigstate == stable
  363. pc.setRemoteDescription(pc.remoteDescription,
  364. function () {
  365. pc.createAnswer(
  366. function (answer) {
  367. var sdp = new SDP(answer.sdp);
  368. if (sdp.media.length > 1) {
  369. if (unmute)
  370. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  371. else
  372. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  373. sdp.raw = sdp.session + sdp.media.join('');
  374. answer.sdp = sdp.raw;
  375. }
  376. pc.setLocalDescription(answer,
  377. function () {
  378. console.log('mute SLD ok');
  379. },
  380. function(error) {
  381. console.log('mute SLD error');
  382. }
  383. );
  384. },
  385. function (error) {
  386. console.log(error);
  387. }
  388. );
  389. },
  390. function (error) {
  391. console.log('muteVideo SRD error');
  392. }
  393. );
  394. }
  395. $(document).bind('callincoming.jingle', function (event, sid) {
  396. var sess = connection.jingle.sessions[sid];
  397. // TODO: do we check activecall == null?
  398. activecall = sess;
  399. // TODO: check affiliation and/or role
  400. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  401. sess.usedrip = true; // not-so-naive trickle ice
  402. sess.sendAnswer();
  403. sess.accept();
  404. });
  405. $(document).bind('callactive.jingle', function (event, videoelem, sid) {
  406. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  407. // ignore mixedmslabela0 and v0
  408. videoelem.show();
  409. resizeThumbnails();
  410. updateLargeVideo(videoelem.attr('src'), 1);
  411. showFocusIndicator();
  412. }
  413. });
  414. $(document).bind('callterminated.jingle', function (event, sid, reason) {
  415. // FIXME
  416. });
  417. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  418. // put our ssrcs into presence so other clients can identify our stream
  419. var sess = connection.jingle.sessions[sid];
  420. var newssrcs = {};
  421. var directions = {};
  422. var localSDP = new SDP(sess.peerconnection.localDescription.sdp);
  423. localSDP.media.forEach(function (media) {
  424. var type = SDPUtil.parse_mline(media.split('\r\n')[0]).media;
  425. if (SDPUtil.find_line(media, 'a=ssrc:')) {
  426. // assumes a single local ssrc
  427. var ssrc = SDPUtil.find_line(media, 'a=ssrc:').substring(7).split(' ')[0];
  428. newssrcs[type] = ssrc;
  429. directions[type] = (
  430. SDPUtil.find_line(media, 'a=sendrecv')
  431. || SDPUtil.find_line(media, 'a=recvonly')
  432. || SDPUtil.find_line('a=sendonly')
  433. || SDPUtil.find_line('a=inactive')
  434. || 'a=sendrecv' ).substr(2);
  435. }
  436. });
  437. console.log('new ssrcs', newssrcs);
  438. // Have to clear presence map to get rid of removed streams
  439. connection.emuc.clearPresenceMedia();
  440. var i = 0;
  441. Object.keys(newssrcs).forEach(function (mtype) {
  442. i++;
  443. var type = mtype;
  444. // Change video type to screen
  445. if(mtype === 'video' && isUsingScreenStream) {
  446. type = 'screen';
  447. }
  448. connection.emuc.addMediaToPresence(i, type, newssrcs[mtype], directions[mtype]);
  449. });
  450. if (i > 0) {
  451. connection.emuc.sendPresence();
  452. }
  453. });
  454. $(document).bind('joined.muc', function (event, jid, info) {
  455. updateRoomUrl(window.location.href);
  456. document.getElementById('localNick').appendChild(
  457. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  458. );
  459. if (Object.keys(connection.emuc.members).length < 1) {
  460. focus = new ColibriFocus(connection, config.hosts.bridge);
  461. }
  462. if (focus && config.etherpad_base) {
  463. Etherpad.init();
  464. }
  465. showFocusIndicator();
  466. // Once we've joined the muc show the toolbar
  467. showToolbar();
  468. var displayName = '';
  469. if (info.displayName)
  470. displayName = info.displayName + ' (me)';
  471. showDisplayName('localVideoContainer', displayName);
  472. });
  473. $(document).bind('entered.muc', function (event, jid, info, pres) {
  474. console.log('entered', jid, info);
  475. console.log('is focus?' + focus ? 'true' : 'false');
  476. // Add Peer's container
  477. ensurePeerContainerExists(jid);
  478. if (focus !== null) {
  479. // FIXME: this should prepare the video
  480. if (focus.confid === null) {
  481. console.log('make new conference with', jid);
  482. focus.makeConference(Object.keys(connection.emuc.members));
  483. } else {
  484. console.log('invite', jid, 'into conference');
  485. focus.addNewParticipant(jid);
  486. }
  487. }
  488. else if (sharedKey) {
  489. updateLockButton();
  490. }
  491. });
  492. $(document).bind('left.muc', function (event, jid) {
  493. console.log('left', jid);
  494. connection.jingle.terminateByJid(jid);
  495. var container = document.getElementById('participant_' + Strophe.getResourceFromJid(jid));
  496. if (container) {
  497. // hide here, wait for video to close before removing
  498. $(container).hide();
  499. resizeThumbnails();
  500. }
  501. if (focus === null && connection.emuc.myroomjid === connection.emuc.list_members[0]) {
  502. console.log('welcome to our new focus... myself');
  503. focus = new ColibriFocus(connection, config.hosts.bridge);
  504. if (Object.keys(connection.emuc.members).length > 0) {
  505. focus.makeConference(Object.keys(connection.emuc.members));
  506. }
  507. $(document).trigger('focusechanged.muc', [focus]);
  508. }
  509. else if (focus && Object.keys(connection.emuc.members).length === 0) {
  510. console.log('everyone left');
  511. // FIXME: closing the connection is a hack to avoid some
  512. // problemswith reinit
  513. disposeConference();
  514. focus = new ColibriFocus(connection, config.hosts.bridge);
  515. }
  516. if (connection.emuc.getPrezi(jid)) {
  517. $(document).trigger('presentationremoved.muc', [jid, connection.emuc.getPrezi(jid)]);
  518. }
  519. });
  520. $(document).bind('presence.muc', function (event, jid, info, pres) {
  521. // Remove old ssrcs coming from the jid
  522. Object.keys(ssrc2jid).forEach(function(ssrc){
  523. if(ssrc2jid[ssrc] == jid){
  524. delete ssrc2jid[ssrc];
  525. }
  526. if(ssrc2videoType == jid){
  527. delete ssrc2videoType[ssrc];
  528. }
  529. });
  530. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  531. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  532. var ssrcV = ssrc.getAttribute('ssrc');
  533. ssrc2jid[ssrcV] = jid;
  534. var type = ssrc.getAttribute('type');
  535. ssrc2videoType[ssrcV] = type;
  536. // might need to update the direction if participant just went from sendrecv to recvonly
  537. if (type === 'video' || type === 'screen') {
  538. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  539. switch(ssrc.getAttribute('direction')) {
  540. case 'sendrecv':
  541. el.show();
  542. break;
  543. case 'recvonly':
  544. el.hide();
  545. // FIXME: Check if we have to change large video
  546. //checkChangeLargeVideo(el);
  547. break;
  548. }
  549. }
  550. });
  551. if (info.displayName) {
  552. if (jid === connection.emuc.myroomjid) {
  553. showDisplayName('localVideoContainer', info.displayName + ' (me)');
  554. } else {
  555. ensurePeerContainerExists(jid);
  556. showDisplayName('participant_' + Strophe.getResourceFromJid(jid), info.displayName);
  557. }
  558. }
  559. });
  560. $(document).bind('passwordrequired.muc', function (event, jid) {
  561. console.log('on password required', jid);
  562. $.prompt('<h2>Password required</h2>' +
  563. '<input id="lockKey" type="text" placeholder="shared key" autofocus>',
  564. {
  565. persistent: true,
  566. buttons: { "Ok": true , "Cancel": false},
  567. defaultButton: 1,
  568. loaded: function(event) {
  569. document.getElementById('lockKey').focus();
  570. },
  571. submit: function(e,v,m,f){
  572. if(v)
  573. {
  574. var lockKey = document.getElementById('lockKey');
  575. if (lockKey.value !== null)
  576. {
  577. setSharedKey(lockKey.value);
  578. connection.emuc.doJoin(jid, lockKey.value);
  579. }
  580. }
  581. }
  582. });
  583. });
  584. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  585. var videoSpanId = null;
  586. if (jid === connection.emuc.myroomjid) {
  587. videoSpanId = 'localVideoContainer';
  588. } else {
  589. ensurePeerContainerExists(jid);
  590. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  591. }
  592. if (videoSpanId)
  593. showAudioIndicator(videoSpanId, isMuted);
  594. });
  595. $(document).bind('videomuted.muc', function (event, jid, isMuted) {
  596. var videoSpanId = null;
  597. if (jid === connection.emuc.myroomjid) {
  598. videoSpanId = 'localVideoContainer';
  599. } else {
  600. ensurePeerContainerExists(jid);
  601. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  602. }
  603. if (videoSpanId)
  604. showAudioIndicator(videoSpanId, isMuted);
  605. });
  606. /**
  607. * Updates the large video with the given new video source.
  608. */
  609. function updateLargeVideo(newSrc, vol) {
  610. console.log('hover in', newSrc);
  611. if ($('#largeVideo').attr('src') != newSrc) {
  612. var isVisible = $('#largeVideo').is(':visible');
  613. $('#largeVideo').fadeOut(300, function () {
  614. $(this).attr('src', newSrc);
  615. // Screen stream is already rotated
  616. var flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  617. var videoTransform = document.getElementById('largeVideo').style.webkitTransform;
  618. if (flipX && videoTransform !== 'scaleX(-1)') {
  619. document.getElementById('largeVideo').style.webkitTransform = "scaleX(-1)";
  620. }
  621. else if (!flipX && videoTransform === 'scaleX(-1)') {
  622. document.getElementById('largeVideo').style.webkitTransform = "none";
  623. }
  624. // Change the way we'll be measuring and positioning large video
  625. var isDesktop = isVideoSrcDesktop(newSrc);
  626. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  627. getVideoPosition = isDesktop ? getDesktopVideoPosition : getCameraVideoPosition;
  628. if (isVisible)
  629. $(this).fadeIn(300);
  630. });
  631. }
  632. }
  633. /**
  634. * Checks if video identified by given src is desktop stream.
  635. * @param videoSrc eg. blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  636. * @returns {boolean}
  637. */
  638. function isVideoSrcDesktop(videoSrc){
  639. // FIXME: fix this mapping mess...
  640. // figure out if large video is desktop stream or just a camera
  641. var isDesktop = false;
  642. if(localVideoSrc === videoSrc) {
  643. // local video
  644. isDesktop = isUsingScreenStream;
  645. } else {
  646. // Do we have associations...
  647. var videoSsrc = videoSrcToSsrc[videoSrc];
  648. if(videoSsrc) {
  649. var videoType = ssrc2videoType[videoSsrc];
  650. if(videoType) {
  651. // Finally there...
  652. isDesktop = videoType === 'screen';
  653. } else {
  654. console.error("No video type for ssrc: " + videoSsrc);
  655. }
  656. } else {
  657. console.error("No ssrc for src: " + videoSrc);
  658. }
  659. }
  660. return isDesktop;
  661. }
  662. /**
  663. * Shows/hides the large video.
  664. */
  665. function setLargeVideoVisible(isVisible) {
  666. if (isVisible) {
  667. $('#largeVideo').css({visibility:'visible'});
  668. $('.watermark').css({visibility:'visible'});
  669. }
  670. else {
  671. $('#largeVideo').css({visibility:'hidden'});
  672. $('.watermark').css({visibility:'hidden'});
  673. }
  674. }
  675. function getConferenceHandler() {
  676. return focus ? focus : activecall;
  677. }
  678. function toggleVideo() {
  679. if (!(connection && connection.jingle.localVideo))
  680. return;
  681. var sess = getConferenceHandler();
  682. if (sess) {
  683. sess.toggleVideoMute(
  684. function(isMuted){
  685. if(isMuted) {
  686. $('#video').removeClass("icon-camera");
  687. $('#video').addClass("icon-camera icon-camera-disabled");
  688. } else {
  689. $('#video').removeClass("icon-camera icon-camera-disabled");
  690. $('#video').addClass("icon-camera");
  691. }
  692. }
  693. );
  694. }
  695. var sess = focus || activecall;
  696. if (!sess) {
  697. return;
  698. }
  699. sess.pendingop = ismuted ? 'unmute' : 'mute';
  700. // connection.emuc.addVideoInfoToPresence(!ismuted);
  701. // connection.emuc.sendPresence();
  702. sess.modifySources();
  703. }
  704. /**
  705. * Mutes / unmutes audio for the local participant.
  706. */
  707. function toggleAudio() {
  708. if (!(connection && connection.jingle.localAudio))
  709. return;
  710. var localAudio = connection.jingle.localAudio;
  711. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  712. var audioEnabled = localAudio.getAudioTracks()[idx].enabled;
  713. localAudio.getAudioTracks()[idx].enabled = !audioEnabled;
  714. connection.emuc.addAudioInfoToPresence(audioEnabled); //isMuted is the opposite of audioEnabled
  715. connection.emuc.sendPresence();
  716. }
  717. }
  718. /**
  719. * Positions the large video.
  720. *
  721. * @param videoWidth the stream video width
  722. * @param videoHeight the stream video height
  723. */
  724. var positionLarge = function(videoWidth, videoHeight) {
  725. var videoSpaceWidth = $('#videospace').width();
  726. var videoSpaceHeight = window.innerHeight;
  727. var videoSize = getVideoSize( videoWidth,
  728. videoHeight,
  729. videoSpaceWidth,
  730. videoSpaceHeight);
  731. var largeVideoWidth = videoSize[0];
  732. var largeVideoHeight = videoSize[1];
  733. var videoPosition = getVideoPosition( largeVideoWidth,
  734. largeVideoHeight,
  735. videoSpaceWidth,
  736. videoSpaceHeight);
  737. var horizontalIndent = videoPosition[0];
  738. var verticalIndent = videoPosition[1];
  739. positionVideo( $('#largeVideo'),
  740. largeVideoWidth,
  741. largeVideoHeight,
  742. horizontalIndent, verticalIndent);
  743. };
  744. /**
  745. * Returns an array of the video horizontal and vertical indents,
  746. * so that if fits its parent.
  747. *
  748. * @return an array with 2 elements, the horizontal indent and the vertical
  749. * indent
  750. */
  751. function getCameraVideoPosition( videoWidth,
  752. videoHeight,
  753. videoSpaceWidth,
  754. videoSpaceHeight) {
  755. // Parent height isn't completely calculated when we position the video in
  756. // full screen mode and this is why we use the screen height in this case.
  757. // Need to think it further at some point and implement it properly.
  758. var isFullScreen = document.fullScreen
  759. || document.mozFullScreen
  760. || document.webkitIsFullScreen;
  761. if (isFullScreen)
  762. videoSpaceHeight = window.innerHeight;
  763. var horizontalIndent = (videoSpaceWidth - videoWidth)/2;
  764. var verticalIndent = (videoSpaceHeight - videoHeight)/2;
  765. return [horizontalIndent, verticalIndent];
  766. }
  767. /**
  768. * Returns an array of the video horizontal and vertical indents.
  769. * Centers horizontally and top aligns vertically.
  770. *
  771. * @return an array with 2 elements, the horizontal indent and the vertical
  772. * indent
  773. */
  774. function getDesktopVideoPosition( videoWidth,
  775. videoHeight,
  776. videoSpaceWidth,
  777. videoSpaceHeight) {
  778. var horizontalIndent = (videoSpaceWidth - videoWidth)/2;
  779. var verticalIndent = 0;// Top aligned
  780. return [horizontalIndent, verticalIndent];
  781. }
  782. /**
  783. * Returns an array of the video dimensions, so that it covers the screen.
  784. * It leaves no empty areas, but some parts of the video might not be visible.
  785. *
  786. * @return an array with 2 elements, the video width and the video height
  787. */
  788. function getCameraVideoSize(videoWidth,
  789. videoHeight,
  790. videoSpaceWidth,
  791. videoSpaceHeight) {
  792. if (!videoWidth)
  793. videoWidth = currentVideoWidth;
  794. if (!videoHeight)
  795. videoHeight = currentVideoHeight;
  796. var aspectRatio = videoWidth / videoHeight;
  797. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  798. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  799. if (availableWidth / aspectRatio < videoSpaceHeight) {
  800. availableHeight = videoSpaceHeight;
  801. availableWidth = availableHeight*aspectRatio;
  802. }
  803. if (availableHeight*aspectRatio < videoSpaceWidth) {
  804. availableWidth = videoSpaceWidth;
  805. availableHeight = availableWidth / aspectRatio;
  806. }
  807. return [availableWidth, availableHeight];
  808. }
  809. /**
  810. * Returns an array of the video dimensions, so that it keeps it's aspect ratio and fits available area with it's
  811. * larger dimension. This method ensures that whole video will be visible and can leave empty areas.
  812. *
  813. * @return an array with 2 elements, the video width and the video height
  814. */
  815. function getDesktopVideoSize( videoWidth,
  816. videoHeight,
  817. videoSpaceWidth,
  818. videoSpaceHeight )
  819. {
  820. if (!videoWidth)
  821. videoWidth = currentVideoWidth;
  822. if (!videoHeight)
  823. videoHeight = currentVideoHeight;
  824. var aspectRatio = videoWidth / videoHeight;
  825. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  826. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  827. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  828. if (availableWidth / aspectRatio >= videoSpaceHeight)
  829. {
  830. availableHeight = videoSpaceHeight;
  831. availableWidth = availableHeight*aspectRatio;
  832. }
  833. if (availableHeight*aspectRatio >= videoSpaceWidth)
  834. {
  835. availableWidth = videoSpaceWidth;
  836. availableHeight = availableWidth / aspectRatio;
  837. }
  838. return [availableWidth, availableHeight];
  839. }
  840. /**
  841. * Sets the size and position of the given video element.
  842. *
  843. * @param video the video element to position
  844. * @param width the desired video width
  845. * @param height the desired video height
  846. * @param horizontalIndent the left and right indent
  847. * @param verticalIndent the top and bottom indent
  848. */
  849. function positionVideo( video,
  850. width,
  851. height,
  852. horizontalIndent,
  853. verticalIndent) {
  854. video.width(width);
  855. video.height(height);
  856. video.css({ top: verticalIndent + 'px',
  857. bottom: verticalIndent + 'px',
  858. left: horizontalIndent + 'px',
  859. right: horizontalIndent + 'px'});
  860. }
  861. var resizeLargeVideoContainer = function () {
  862. Chat.resizeChat();
  863. var availableHeight = window.innerHeight;
  864. var availableWidth = Util.getAvailableVideoWidth();
  865. if (availableWidth < 0 || availableHeight < 0) return;
  866. $('#videospace').width(availableWidth);
  867. $('#videospace').height(availableHeight);
  868. $('#largeVideoContainer').width(availableWidth);
  869. $('#largeVideoContainer').height(availableHeight);
  870. resizeThumbnails();
  871. };
  872. var calculateThumbnailSize = function() {
  873. // Calculate the available height, which is the inner window height minus
  874. // 39px for the header minus 2px for the delimiter lines on the top and
  875. // bottom of the large video, minus the 36px space inside the remoteVideos
  876. // container used for highlighting shadow.
  877. var availableHeight = 100;
  878. var numvids = $('#remoteVideos>span:visible').length;
  879. // Remove the 1px borders arround videos and the chat width.
  880. var availableWinWidth = $('#remoteVideos').width() - 2 * numvids - 50;
  881. var availableWidth = availableWinWidth / numvids;
  882. var aspectRatio = 16.0 / 9.0;
  883. var maxHeight = Math.min(160, availableHeight);
  884. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  885. if (availableHeight < availableWidth / aspectRatio) {
  886. availableWidth = Math.floor(availableHeight * aspectRatio);
  887. }
  888. return [availableWidth, availableHeight];
  889. };
  890. function resizeThumbnails() {
  891. var thumbnailSize = calculateThumbnailSize();
  892. var width = thumbnailSize[0];
  893. var height = thumbnailSize[1];
  894. // size videos so that while keeping AR and max height, we have a nice fit
  895. $('#remoteVideos').height(height);
  896. $('#remoteVideos>span').width(width);
  897. $('#remoteVideos>span').height(height);
  898. }
  899. $(document).ready(function () {
  900. Chat.init();
  901. // Set the defaults for prompt dialogs.
  902. jQuery.prompt.setDefaults({persistent: false});
  903. // Set default desktop sharing method
  904. setDesktopSharing(config.desktopSharing);
  905. // Initialize Chrome extension inline installs
  906. if(config.chromeExtensionId)
  907. {
  908. initInlineInstalls();
  909. }
  910. // By default we use camera
  911. getVideoSize = getCameraVideoSize;
  912. getVideoPosition = getCameraVideoPosition;
  913. resizeLargeVideoContainer();
  914. $(window).resize(function () {
  915. resizeLargeVideoContainer();
  916. positionLarge();
  917. });
  918. // Listen for large video size updates
  919. document.getElementById('largeVideo')
  920. .addEventListener('loadedmetadata', function(e){
  921. currentVideoWidth = this.videoWidth;
  922. currentVideoHeight = this.videoHeight;
  923. positionLarge(currentVideoWidth, currentVideoHeight);
  924. });
  925. if (!$('#settings').is(':visible')) {
  926. console.log('init');
  927. init();
  928. } else {
  929. loginInfo.onsubmit = function (e) {
  930. if (e.preventDefault) e.preventDefault();
  931. $('#settings').hide();
  932. init();
  933. };
  934. }
  935. });
  936. $(window).bind('beforeunload', function () {
  937. if (connection && connection.connected) {
  938. // ensure signout
  939. $.ajax({
  940. type: 'POST',
  941. url: config.bosh,
  942. async: false,
  943. cache: false,
  944. contentType: 'application/xml',
  945. 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>",
  946. success: function (data) {
  947. console.log('signed out');
  948. console.log(data);
  949. },
  950. error: function (XMLHttpRequest, textStatus, errorThrown) {
  951. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  952. }
  953. });
  954. }
  955. disposeConference();
  956. });
  957. function disposeConference() {
  958. var handler = getConferenceHandler();
  959. if(handler && handler.peerconnection) {
  960. // FIXME: probably removing streams is not required and close() should be enough
  961. if(connection.jingle.localAudio) {
  962. handler.peerconnection.removeStream(connection.jingle.localAudio);
  963. }
  964. if(connection.jingle.localVideo) {
  965. handler.peerconnection.removeStream(connection.jingle.localVideo);
  966. }
  967. handler.peerconnection.close();
  968. }
  969. focus = null;
  970. activecall = null;
  971. }
  972. function dump(elem, filename){
  973. elem = elem.parentNode;
  974. elem.download = filename || 'meetlog.json';
  975. elem.href = 'data:application/json;charset=utf-8,\n';
  976. var data = {};
  977. if (connection.jingle) {
  978. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  979. var session = connection.jingle.sessions[sid];
  980. if (session.peerconnection && session.peerconnection.updateLog) {
  981. // FIXME: should probably be a .dump call
  982. data["jingle_" + session.sid] = {
  983. updateLog: session.peerconnection.updateLog,
  984. stats: session.peerconnection.stats,
  985. url: window.location.href}
  986. ;
  987. }
  988. });
  989. }
  990. metadata = {};
  991. metadata.time = new Date();
  992. metadata.url = window.location.href;
  993. metadata.ua = navigator.userAgent;
  994. if (connection.logger) {
  995. metadata.xmpp = connection.logger.log;
  996. }
  997. data.metadata = metadata;
  998. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  999. return false;
  1000. }
  1001. /**
  1002. * Changes the style class of the element given by id.
  1003. */
  1004. function buttonClick(id, classname) {
  1005. $(id).toggleClass(classname); // add the class to the clicked element
  1006. }
  1007. /**
  1008. * Opens the lock room dialog.
  1009. */
  1010. function openLockDialog() {
  1011. // Only the focus is able to set a shared key.
  1012. if (focus === null) {
  1013. if (sharedKey)
  1014. $.prompt("This conversation is currently protected by a shared secret key.",
  1015. {
  1016. title: "Secrect key",
  1017. persistent: false
  1018. });
  1019. else
  1020. $.prompt("This conversation isn't currently protected by a secret key. Only the owner of the conference could set a shared key.",
  1021. {
  1022. title: "Secrect key",
  1023. persistent: false
  1024. });
  1025. }
  1026. else {
  1027. if (sharedKey)
  1028. $.prompt("Are you sure you would like to remove your secret key?",
  1029. {
  1030. title: "Remove secrect key",
  1031. persistent: false,
  1032. buttons: { "Remove": true, "Cancel": false},
  1033. defaultButton: 1,
  1034. submit: function(e,v,m,f){
  1035. if(v)
  1036. {
  1037. setSharedKey('');
  1038. lockRoom(false);
  1039. }
  1040. }
  1041. });
  1042. else
  1043. $.prompt('<h2>Set a secrect key to lock your room</h2>' +
  1044. '<input id="lockKey" type="text" placeholder="your shared key" autofocus>',
  1045. {
  1046. persistent: false,
  1047. buttons: { "Save": true , "Cancel": false},
  1048. defaultButton: 1,
  1049. loaded: function(event) {
  1050. document.getElementById('lockKey').focus();
  1051. },
  1052. submit: function(e,v,m,f){
  1053. if(v)
  1054. {
  1055. var lockKey = document.getElementById('lockKey');
  1056. if (lockKey.value)
  1057. {
  1058. setSharedKey(Util.escapeHtml(lockKey.value));
  1059. lockRoom(true);
  1060. }
  1061. }
  1062. }
  1063. });
  1064. }
  1065. }
  1066. /**
  1067. * Opens the invite link dialog.
  1068. */
  1069. function openLinkDialog() {
  1070. $.prompt('<input id="inviteLinkRef" type="text" value="'
  1071. + encodeURI(roomUrl) + '" onclick="this.select();" readonly>',
  1072. {
  1073. title: "Share this link with everyone you want to invite",
  1074. persistent: false,
  1075. buttons: { "Cancel": false},
  1076. loaded: function(event) {
  1077. document.getElementById('inviteLinkRef').select();
  1078. }
  1079. });
  1080. }
  1081. /**
  1082. * Opens the settings dialog.
  1083. */
  1084. function openSettingsDialog() {
  1085. $.prompt('<h2>Configure your conference</h2>' +
  1086. '<input type="checkbox" id="initMuted"> Participants join muted<br/>' +
  1087. '<input type="checkbox" id="requireNicknames"> Require nicknames<br/><br/>' +
  1088. 'Set a secrect key to lock your room: <input id="lockKey" type="text" placeholder="your shared key" autofocus>',
  1089. {
  1090. persistent: false,
  1091. buttons: { "Save": true , "Cancel": false},
  1092. defaultButton: 1,
  1093. loaded: function(event) {
  1094. document.getElementById('lockKey').focus();
  1095. },
  1096. submit: function(e,v,m,f){
  1097. if(v)
  1098. {
  1099. if ($('#initMuted').is(":checked"))
  1100. {
  1101. // it is checked
  1102. }
  1103. if ($('#requireNicknames').is(":checked"))
  1104. {
  1105. // it is checked
  1106. }
  1107. /*
  1108. var lockKey = document.getElementById('lockKey');
  1109. if (lockKey.value)
  1110. {
  1111. setSharedKey(lockKey.value);
  1112. lockRoom(true);
  1113. }
  1114. */
  1115. }
  1116. }
  1117. });
  1118. }
  1119. /**
  1120. * Locks / unlocks the room.
  1121. */
  1122. function lockRoom(lock) {
  1123. if (lock)
  1124. connection.emuc.lockRoom(sharedKey);
  1125. else
  1126. connection.emuc.lockRoom('');
  1127. updateLockButton();
  1128. }
  1129. /**
  1130. * Sets the shared key.
  1131. */
  1132. function setSharedKey(sKey) {
  1133. sharedKey = sKey;
  1134. }
  1135. /**
  1136. * Updates the lock button state.
  1137. */
  1138. function updateLockButton() {
  1139. buttonClick("#lockIcon", "icon-security icon-security-locked");
  1140. }
  1141. /**
  1142. * Hides the toolbar.
  1143. */
  1144. var hideToolbar = function() {
  1145. var isToolbarHover = false;
  1146. $('#header').find('*').each(function(){
  1147. var id = $(this).attr('id');
  1148. if ($("#" + id + ":hover").length > 0) {
  1149. isToolbarHover = true;
  1150. }
  1151. });
  1152. clearTimeout(toolbarTimeout);
  1153. toolbarTimeout = null;
  1154. if (!isToolbarHover) {
  1155. $('#header').hide("slide", { direction: "up", duration: 300});
  1156. }
  1157. else {
  1158. toolbarTimeout = setTimeout(hideToolbar, 2000);
  1159. }
  1160. };
  1161. /**
  1162. * Shows the call main toolbar.
  1163. */
  1164. function showToolbar() {
  1165. if (!$('#header').is(':visible')) {
  1166. $('#header').show("slide", { direction: "up", duration: 300});
  1167. if (toolbarTimeout) {
  1168. clearTimeout(toolbarTimeout);
  1169. toolbarTimeout = null;
  1170. }
  1171. toolbarTimeout = setTimeout(hideToolbar, 2000);
  1172. }
  1173. if (focus != null)
  1174. {
  1175. // TODO: Enable settings functionality. Need to uncomment the settings button in index.html.
  1176. // $('#settingsButton').css({visibility:"visible"});
  1177. }
  1178. // Show/hide desktop sharing button
  1179. showDesktopSharingButton();
  1180. }
  1181. /**
  1182. * Docks/undocks the toolbar.
  1183. *
  1184. * @param isDock indicates what operation to perform
  1185. */
  1186. function dockToolbar(isDock) {
  1187. if (isDock) {
  1188. // First make sure the toolbar is shown.
  1189. if (!$('#header').is(':visible')) {
  1190. showToolbar();
  1191. }
  1192. // Then clear the time out, to dock the toolbar.
  1193. clearTimeout(toolbarTimeout);
  1194. toolbarTimeout = null;
  1195. }
  1196. else {
  1197. if (!$('#header').is(':visible')) {
  1198. showToolbar();
  1199. }
  1200. else {
  1201. toolbarTimeout = setTimeout(hideToolbar, 2000);
  1202. }
  1203. }
  1204. }
  1205. /**
  1206. * Updates the room invite url.
  1207. */
  1208. function updateRoomUrl(newRoomUrl) {
  1209. roomUrl = newRoomUrl;
  1210. }
  1211. /**
  1212. * Warning to the user that the conference window is about to be closed.
  1213. */
  1214. function closePageWarning() {
  1215. if (focus !== null)
  1216. return "You are the owner of this conference call and you are about to end it.";
  1217. else
  1218. return "You are about to leave this conversation.";
  1219. }
  1220. /**
  1221. * Shows a visual indicator for the focus of the conference.
  1222. * Currently if we're not the owner of the conference we obtain the focus
  1223. * from the connection.jingle.sessions.
  1224. */
  1225. function showFocusIndicator() {
  1226. if (focus !== null) {
  1227. var indicatorSpan = $('#localVideoContainer .focusindicator');
  1228. if (indicatorSpan.children().length === 0)
  1229. {
  1230. createFocusIndicatorElement(indicatorSpan[0]);
  1231. }
  1232. }
  1233. else if (Object.keys(connection.jingle.sessions).length > 0) {
  1234. // If we're only a participant the focus will be the only session we have.
  1235. var session = connection.jingle.sessions[Object.keys(connection.jingle.sessions)[0]];
  1236. var focusId = 'participant_' + Strophe.getResourceFromJid(session.peerjid);
  1237. var focusContainer = document.getElementById(focusId);
  1238. if(!focusContainer) {
  1239. console.error("No focus container!");
  1240. return;
  1241. }
  1242. var indicatorSpan = $('#' + focusId + ' .focusindicator');
  1243. if (!indicatorSpan || indicatorSpan.length === 0) {
  1244. indicatorSpan = document.createElement('span');
  1245. indicatorSpan.className = 'focusindicator';
  1246. focusContainer.appendChild(indicatorSpan);
  1247. createFocusIndicatorElement(indicatorSpan);
  1248. }
  1249. }
  1250. }
  1251. /**
  1252. * Checks if container for participant identified by given peerJid exists in the document and creates it eventually.
  1253. * @param peerJid peer Jid to check.
  1254. */
  1255. function ensurePeerContainerExists(peerJid){
  1256. var peerResource = Strophe.getResourceFromJid(peerJid);
  1257. var videoSpanId = 'participant_' + peerResource;
  1258. if($('#'+videoSpanId).length > 0) {
  1259. return;
  1260. }
  1261. var container = addRemoteVideoContainer(videoSpanId);
  1262. var nickfield = document.createElement('span');
  1263. nickfield.className = "nick";
  1264. nickfield.appendChild(document.createTextNode(peerResource));
  1265. container.appendChild(nickfield);
  1266. resizeThumbnails();
  1267. }
  1268. function addRemoteVideoContainer(id) {
  1269. var container = document.createElement('span');
  1270. container.id = id;
  1271. container.className = 'videocontainer';
  1272. var remotes = document.getElementById('remoteVideos');
  1273. remotes.appendChild(container);
  1274. return container;
  1275. }
  1276. /**
  1277. * Creates the element indicating the focus of the conference.
  1278. */
  1279. function createFocusIndicatorElement(parentElement) {
  1280. var focusIndicator = document.createElement('i');
  1281. focusIndicator.className = 'fa fa-star';
  1282. focusIndicator.title = "The owner of this conference";
  1283. parentElement.appendChild(focusIndicator);
  1284. }
  1285. /**
  1286. * Toggles the application in and out of full screen mode
  1287. * (a.k.a. presentation mode in Chrome).
  1288. */
  1289. function toggleFullScreen() {
  1290. var fsElement = document.documentElement;
  1291. if (!document.mozFullScreen && !document.webkitIsFullScreen){
  1292. //Enter Full Screen
  1293. if (fsElement.mozRequestFullScreen) {
  1294. fsElement.mozRequestFullScreen();
  1295. }
  1296. else {
  1297. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  1298. }
  1299. } else {
  1300. //Exit Full Screen
  1301. if (document.mozCancelFullScreen) {
  1302. document.mozCancelFullScreen();
  1303. } else {
  1304. document.webkitCancelFullScreen();
  1305. }
  1306. }
  1307. }
  1308. /**
  1309. * Shows the display name for the given video.
  1310. */
  1311. function showDisplayName(videoSpanId, displayName) {
  1312. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  1313. // If we already have a display name for this video.
  1314. if (nameSpan.length > 0) {
  1315. var nameSpanElement = nameSpan.get(0);
  1316. if (nameSpanElement.id === 'localDisplayName'
  1317. && $('#localDisplayName').text() !== displayName)
  1318. $('#localDisplayName').text(displayName);
  1319. else
  1320. $('#' + videoSpanId + '_name').text(displayName);
  1321. }
  1322. else {
  1323. var editButton = null;
  1324. if (videoSpanId === 'localVideoContainer') {
  1325. editButton = createEditDisplayNameButton();
  1326. }
  1327. if (displayName.length) {
  1328. nameSpan = document.createElement('span');
  1329. nameSpan.className = 'displayname';
  1330. nameSpan.innerText = displayName;
  1331. $('#' + videoSpanId)[0].appendChild(nameSpan);
  1332. }
  1333. if (!editButton) {
  1334. nameSpan.id = videoSpanId + '_name';
  1335. }
  1336. else {
  1337. nameSpan.id = 'localDisplayName';
  1338. $('#' + videoSpanId)[0].appendChild(editButton);
  1339. var editableText = document.createElement('input');
  1340. editableText.className = 'displayname';
  1341. editableText.id = 'editDisplayName';
  1342. if (displayName.length)
  1343. editableText.value
  1344. = displayName.substring(0, displayName.indexOf(' (me)'));
  1345. editableText.setAttribute('style', 'display:none;');
  1346. editableText.setAttribute('placeholder', 'ex. Jane Pink');
  1347. $('#' + videoSpanId)[0].appendChild(editableText);
  1348. $('#localVideoContainer .displayname').bind("click", function(e) {
  1349. e.preventDefault();
  1350. $('#localDisplayName').hide();
  1351. $('#editDisplayName').show();
  1352. $('#editDisplayName').focus();
  1353. $('#editDisplayName').select();
  1354. var inputDisplayNameHandler = function(name) {
  1355. if (nickname !== name) {
  1356. nickname = name;
  1357. window.localStorage.displayname = nickname;
  1358. connection.emuc.addDisplayNameToPresence(nickname);
  1359. connection.emuc.sendPresence();
  1360. Chat.setChatConversationMode(true);
  1361. }
  1362. if (!$('#localDisplayName').is(":visible")) {
  1363. $('#localDisplayName').text(nickname + " (me)");
  1364. $('#localDisplayName').show();
  1365. $('#editDisplayName').hide();
  1366. }
  1367. };
  1368. $('#editDisplayName').one("focusout", function (e) {
  1369. inputDisplayNameHandler(this.value);
  1370. });
  1371. $('#editDisplayName').on('keydown', function (e) {
  1372. if (e.keyCode === 13) {
  1373. e.preventDefault();
  1374. inputDisplayNameHandler(this.value);
  1375. }
  1376. });
  1377. });
  1378. }
  1379. }
  1380. }
  1381. /**
  1382. * Creates the edit display name button.
  1383. *
  1384. * @returns the edit button
  1385. */
  1386. function createEditDisplayNameButton() {
  1387. var editButton = document.createElement('a');
  1388. editButton.className = 'displayname';
  1389. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  1390. return editButton;
  1391. }
  1392. /**
  1393. * Shows audio muted indicator over small videos.
  1394. */
  1395. function showAudioIndicator(videoSpanId, isMuted) {
  1396. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  1397. if (isMuted === 'false') {
  1398. if (audioMutedSpan.length > 0) {
  1399. audioMutedSpan.remove();
  1400. }
  1401. }
  1402. else {
  1403. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  1404. audioMutedSpan = document.createElement('span');
  1405. audioMutedSpan.className = 'audioMuted';
  1406. if (videoMutedSpan) {
  1407. audioMutedSpan.right = '30px';
  1408. }
  1409. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  1410. var mutedIndicator = document.createElement('i');
  1411. mutedIndicator.className = 'icon-mic-disabled';
  1412. mutedIndicator.title = "Participant is muted";
  1413. audioMutedSpan.appendChild(mutedIndicator);
  1414. }
  1415. }
  1416. /**
  1417. * Shows video muted indicator over small videos.
  1418. */
  1419. function showVideoIndicator(videoSpanId, isMuted) {
  1420. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  1421. if (isMuted === 'false') {
  1422. if (videoMutedSpan.length > 0) {
  1423. videoMutedSpan.remove();
  1424. }
  1425. }
  1426. else {
  1427. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  1428. videoMutedSpan = document.createElement('span');
  1429. videoMutedSpan.className = 'videoMuted';
  1430. if (audioMutedSpan) {
  1431. videoMutedSpan.right = '30px';
  1432. }
  1433. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  1434. var mutedIndicator = document.createElement('i');
  1435. mutedIndicator.className = 'icon-camera-disabled';
  1436. mutedIndicator.title = "Participant has stopped the camera.";
  1437. videoMutedSpan.appendChild(mutedIndicator);
  1438. }
  1439. }
  1440. /**
  1441. * Resizes and repositions videos in full screen mode.
  1442. */
  1443. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1444. function() {
  1445. resizeLargeVideoContainer();
  1446. positionLarge();
  1447. isFullScreen = document.fullScreen
  1448. || document.mozFullScreen
  1449. || document.webkitIsFullScreen;
  1450. if (isFullScreen) {
  1451. setView("fullscreen");
  1452. }
  1453. else {
  1454. setView("default");
  1455. }
  1456. });
  1457. /**
  1458. * Sets the current view.
  1459. */
  1460. function setView(viewName) {
  1461. // if (viewName == "fullscreen") {
  1462. // document.getElementById('videolayout_fullscreen').disabled = false;
  1463. // document.getElementById('videolayout_default').disabled = true;
  1464. // }
  1465. // else {
  1466. // document.getElementById('videolayout_default').disabled = false;
  1467. // document.getElementById('videolayout_fullscreen').disabled = true;
  1468. // }
  1469. }