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