Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

app.js 61KB

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