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.

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