You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.js 58KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845
  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. container = document.getElementById(
  240. 'participant_' + Strophe.getResourceFromJid(data.peerjid));
  241. if (!container) {
  242. console.error('no container for', data.peerjid);
  243. } else {
  244. //console.log('found container for', data.peerjid);
  245. }
  246. } else {
  247. if (data.stream.id !== 'mixedmslabel') {
  248. console.error('can not associate stream', data.stream.id, 'with a participant');
  249. // We don't want to add it here since it will cause troubles
  250. return;
  251. }
  252. // FIXME: for the mixed ms we dont need a video -- currently
  253. container = document.createElement('span');
  254. container.className = 'videocontainer';
  255. remotes.appendChild(container);
  256. Util.playSoundNotification('userJoined');
  257. }
  258. var isVideo = data.stream.getVideoTracks().length > 0;
  259. var vid = isVideo ? document.createElement('video') : document.createElement('audio');
  260. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_') + sid + '_' + data.stream.id;
  261. vid.id = id;
  262. vid.autoplay = true;
  263. vid.oncontextmenu = function () { return false; };
  264. container.appendChild(vid);
  265. // TODO: make mixedstream display:none via css?
  266. if (id.indexOf('mixedmslabel') !== -1) {
  267. container.id = 'mixedstream';
  268. $(container).hide();
  269. }
  270. var sel = $('#' + id);
  271. sel.hide();
  272. RTC.attachMediaStream(sel, data.stream);
  273. if (isVideo) {
  274. waitForRemoteVideo(sel, sid, thessrc);
  275. }
  276. data.stream.onended = function () {
  277. console.log('stream ended', this.id);
  278. // Mark video as removed to cancel waiting loop(if video is removed before has started)
  279. sel.removed = true;
  280. sel.remove();
  281. var audioCount = $('#' + container.id + '>audio').length;
  282. var videoCount = $('#' + container.id + '>video').length;
  283. if (!audioCount && !videoCount) {
  284. console.log("Remove whole user");
  285. // Remove whole container
  286. container.remove();
  287. Util.playSoundNotification('userLeft');
  288. resizeThumbnails();
  289. }
  290. checkChangeLargeVideo(vid.src);
  291. };
  292. // Add click handler
  293. sel.click(function () {
  294. handleVideoThumbClicked(vid.src);
  295. });
  296. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  297. if (isVideo &&
  298. data.peerjid && sess.peerjid === data.peerjid &&
  299. data.stream.getVideoTracks().length === 0 &&
  300. connection.jingle.localVideo.getVideoTracks().length > 0) {
  301. //
  302. window.setTimeout(function () {
  303. sendKeyframe(sess.peerconnection);
  304. }, 3000);
  305. }
  306. });
  307. function handleVideoThumbClicked(videoSrc) {
  308. $(document).trigger("video.selected", [false]);
  309. updateLargeVideo(videoSrc, 1);
  310. $('audio').each(function (idx, el) {
  311. if (el.id.indexOf('mixedmslabel') !== -1) {
  312. el.volume = 0;
  313. el.volume = 1;
  314. }
  315. });
  316. }
  317. /**
  318. * Checks if removed video is currently displayed and tries to display another one instead.
  319. * @param removedVideoSrc src stream identifier of the video.
  320. */
  321. function checkChangeLargeVideo(removedVideoSrc) {
  322. if (removedVideoSrc === $('#largeVideo').attr('src')) {
  323. // this is currently displayed as large
  324. // pick the last visible video in the row
  325. // if nobody else is left, this picks the local video
  326. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video').get(0);
  327. if (!pick) {
  328. console.info("Last visible video no longer exists");
  329. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  330. if (!pick) {
  331. // Try local video
  332. console.info("Fallback to local video...");
  333. pick = $('#remoteVideos>span>span>video').get(0);
  334. }
  335. }
  336. // mute if localvideo
  337. if (pick) {
  338. updateLargeVideo(pick.src, pick.volume);
  339. } else {
  340. console.warn("Failed to elect large video");
  341. }
  342. }
  343. }
  344. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  345. function sendKeyframe(pc) {
  346. console.log('sendkeyframe', pc.iceConnectionState);
  347. if (pc.iceConnectionState !== 'connected') return; // safe...
  348. pc.setRemoteDescription(
  349. pc.remoteDescription,
  350. function () {
  351. pc.createAnswer(
  352. function (modifiedAnswer) {
  353. pc.setLocalDescription(
  354. modifiedAnswer,
  355. function () {
  356. // noop
  357. },
  358. function (error) {
  359. console.log('triggerKeyframe setLocalDescription failed', error);
  360. }
  361. );
  362. },
  363. function (error) {
  364. console.log('triggerKeyframe createAnswer failed', error);
  365. }
  366. );
  367. },
  368. function (error) {
  369. console.log('triggerKeyframe setRemoteDescription failed', error);
  370. }
  371. );
  372. }
  373. // really mute video, i.e. dont even send black frames
  374. function muteVideo(pc, unmute) {
  375. // FIXME: this probably needs another of those lovely state safeguards...
  376. // which checks for iceconn == connected and sigstate == stable
  377. pc.setRemoteDescription(pc.remoteDescription,
  378. function () {
  379. pc.createAnswer(
  380. function (answer) {
  381. var sdp = new SDP(answer.sdp);
  382. if (sdp.media.length > 1) {
  383. if (unmute)
  384. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  385. else
  386. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  387. sdp.raw = sdp.session + sdp.media.join('');
  388. answer.sdp = sdp.raw;
  389. }
  390. pc.setLocalDescription(answer,
  391. function () {
  392. console.log('mute SLD ok');
  393. },
  394. function (error) {
  395. console.log('mute SLD error');
  396. }
  397. );
  398. },
  399. function (error) {
  400. console.log(error);
  401. }
  402. );
  403. },
  404. function (error) {
  405. console.log('muteVideo SRD error');
  406. }
  407. );
  408. }
  409. $(document).bind('callincoming.jingle', function (event, sid) {
  410. var sess = connection.jingle.sessions[sid];
  411. // TODO: do we check activecall == null?
  412. activecall = sess;
  413. // TODO: check affiliation and/or role
  414. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  415. sess.usedrip = true; // not-so-naive trickle ice
  416. sess.sendAnswer();
  417. sess.accept();
  418. });
  419. $(document).bind('callactive.jingle', function (event, videoelem, sid) {
  420. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  421. // ignore mixedmslabela0 and v0
  422. videoelem.show();
  423. resizeThumbnails();
  424. updateLargeVideo(videoelem.attr('src'), 1);
  425. showFocusIndicator();
  426. }
  427. });
  428. $(document).bind('callterminated.jingle', function (event, sid, jid, reason) {
  429. // Leave the room if my call has been remotely terminated.
  430. if (connection.emuc.joined && focus == null && reason === 'kick') {
  431. sessionTerminated = true;
  432. connection.emuc.doLeave();
  433. openMessageDialog( "Session Terminated",
  434. "Ouch! You have been kicked out of the meet!");
  435. }
  436. });
  437. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  438. // put our ssrcs into presence so other clients can identify our stream
  439. var sess = connection.jingle.sessions[sid];
  440. var newssrcs = {};
  441. var directions = {};
  442. var localSDP = new SDP(sess.peerconnection.localDescription.sdp);
  443. localSDP.media.forEach(function (media) {
  444. var type = SDPUtil.parse_mline(media.split('\r\n')[0]).media;
  445. if (SDPUtil.find_line(media, 'a=ssrc:')) {
  446. // assumes a single local ssrc
  447. var ssrc = SDPUtil.find_line(media, 'a=ssrc:').substring(7).split(' ')[0];
  448. newssrcs[type] = ssrc;
  449. directions[type] = (
  450. SDPUtil.find_line(media, 'a=sendrecv') ||
  451. SDPUtil.find_line(media, 'a=recvonly') ||
  452. SDPUtil.find_line('a=sendonly') ||
  453. SDPUtil.find_line('a=inactive') ||
  454. 'a=sendrecv').substr(2);
  455. }
  456. });
  457. console.log('new ssrcs', newssrcs);
  458. // Have to clear presence map to get rid of removed streams
  459. connection.emuc.clearPresenceMedia();
  460. var i = 0;
  461. Object.keys(newssrcs).forEach(function (mtype) {
  462. i++;
  463. var type = mtype;
  464. // Change video type to screen
  465. if (mtype === 'video' && isUsingScreenStream) {
  466. type = 'screen';
  467. }
  468. connection.emuc.addMediaToPresence(i, type, newssrcs[mtype], directions[mtype]);
  469. });
  470. if (i > 0) {
  471. connection.emuc.sendPresence();
  472. }
  473. });
  474. $(document).bind('joined.muc', function (event, jid, info) {
  475. updateRoomUrl(window.location.href);
  476. document.getElementById('localNick').appendChild(
  477. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  478. );
  479. if (Object.keys(connection.emuc.members).length < 1) {
  480. focus = new ColibriFocus(connection, config.hosts.bridge);
  481. }
  482. if (focus && config.etherpad_base) {
  483. Etherpad.init();
  484. }
  485. showFocusIndicator();
  486. // Once we've joined the muc show the toolbar
  487. showToolbar();
  488. var displayName = '';
  489. if (info.displayName)
  490. displayName = info.displayName + ' (me)';
  491. showDisplayName('localVideoContainer', displayName);
  492. });
  493. $(document).bind('entered.muc', function (event, jid, info, pres) {
  494. console.log('entered', jid, info);
  495. console.log('is focus?' + focus ? 'true' : 'false');
  496. // Add Peer's container
  497. ensurePeerContainerExists(jid);
  498. if (focus !== null) {
  499. // FIXME: this should prepare the video
  500. if (focus.confid === null) {
  501. console.log('make new conference with', jid);
  502. focus.makeConference(Object.keys(connection.emuc.members));
  503. } else {
  504. console.log('invite', jid, 'into conference');
  505. focus.addNewParticipant(jid);
  506. }
  507. }
  508. else if (sharedKey) {
  509. updateLockButton();
  510. }
  511. });
  512. $(document).bind('left.muc', function (event, jid) {
  513. console.log('left.muc', jid);
  514. // Need to call this with a slight delay, otherwise the element couldn't be
  515. // found for some reason.
  516. window.setTimeout(function () {
  517. var container = document.getElementById(
  518. 'participant_' + Strophe.getResourceFromJid(jid));
  519. if (container) {
  520. // hide here, wait for video to close before removing
  521. $(container).hide();
  522. resizeThumbnails();
  523. }
  524. }, 10);
  525. connection.jingle.terminateByJid(jid);
  526. if (focus == null
  527. // I shouldn't be the one that left to enter here.
  528. && jid !== connection.emuc.myroomjid
  529. && connection.emuc.myroomjid === connection.emuc.list_members[0]
  530. // If our session has been terminated for some reason
  531. // (kicked, hangup), don't try to become the focus
  532. && !sessionTerminated) {
  533. console.log('welcome to our new focus... myself');
  534. focus = new ColibriFocus(connection, config.hosts.bridge);
  535. if (Object.keys(connection.emuc.members).length > 0) {
  536. focus.makeConference(Object.keys(connection.emuc.members));
  537. }
  538. $(document).trigger('focusechanged.muc', [focus]);
  539. }
  540. else if (focus && Object.keys(connection.emuc.members).length === 0) {
  541. console.log('everyone left');
  542. // FIXME: closing the connection is a hack to avoid some
  543. // problemswith reinit
  544. disposeConference();
  545. focus = new ColibriFocus(connection, config.hosts.bridge);
  546. }
  547. if (connection.emuc.getPrezi(jid)) {
  548. $(document).trigger('presentationremoved.muc',
  549. [jid, connection.emuc.getPrezi(jid)]);
  550. }
  551. });
  552. $(document).bind('presence.muc', function (event, jid, info, pres) {
  553. // Remove old ssrcs coming from the jid
  554. Object.keys(ssrc2jid).forEach(function (ssrc) {
  555. if (ssrc2jid[ssrc] == jid) {
  556. delete ssrc2jid[ssrc];
  557. }
  558. if (ssrc2videoType == jid) {
  559. delete ssrc2videoType[ssrc];
  560. }
  561. });
  562. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  563. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  564. var ssrcV = ssrc.getAttribute('ssrc');
  565. ssrc2jid[ssrcV] = jid;
  566. var type = ssrc.getAttribute('type');
  567. ssrc2videoType[ssrcV] = type;
  568. // might need to update the direction if participant just went from sendrecv to recvonly
  569. if (type === 'video' || type === 'screen') {
  570. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  571. switch (ssrc.getAttribute('direction')) {
  572. case 'sendrecv':
  573. el.show();
  574. break;
  575. case 'recvonly':
  576. el.hide();
  577. // FIXME: Check if we have to change large video
  578. //checkChangeLargeVideo(el);
  579. break;
  580. }
  581. }
  582. });
  583. if (info.displayName) {
  584. if (jid === connection.emuc.myroomjid) {
  585. showDisplayName('localVideoContainer', info.displayName + ' (me)');
  586. } else {
  587. ensurePeerContainerExists(jid);
  588. showDisplayName('participant_' + Strophe.getResourceFromJid(jid), info.displayName);
  589. }
  590. }
  591. });
  592. $(document).bind('passwordrequired.muc', function (event, jid) {
  593. console.log('on password required', jid);
  594. $.prompt('<h2>Password required</h2>' +
  595. '<input id="lockKey" type="text" placeholder="shared key" autofocus>', {
  596. persistent: true,
  597. buttons: { "Ok": true, "Cancel": false},
  598. defaultButton: 1,
  599. loaded: function (event) {
  600. document.getElementById('lockKey').focus();
  601. },
  602. submit: function (e, v, m, f) {
  603. if (v) {
  604. var lockKey = document.getElementById('lockKey');
  605. if (lockKey.value !== null) {
  606. setSharedKey(lockKey.value);
  607. connection.emuc.doJoin(jid, lockKey.value);
  608. }
  609. }
  610. }
  611. });
  612. });
  613. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  614. var videoSpanId = null;
  615. if (jid === connection.emuc.myroomjid) {
  616. videoSpanId = 'localVideoContainer';
  617. } else {
  618. ensurePeerContainerExists(jid);
  619. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  620. }
  621. if (focus) {
  622. mutedAudios[jid] = isMuted;
  623. updateRemoteVideoMenu(jid, isMuted);
  624. }
  625. if (videoSpanId)
  626. showAudioIndicator(videoSpanId, isMuted);
  627. });
  628. $(document).bind('videomuted.muc', function (event, jid, isMuted) {
  629. var videoSpanId = null;
  630. if (jid === connection.emuc.myroomjid) {
  631. videoSpanId = 'localVideoContainer';
  632. } else {
  633. ensurePeerContainerExists(jid);
  634. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  635. }
  636. if (videoSpanId)
  637. showVideoIndicator(videoSpanId, isMuted);
  638. });
  639. /**
  640. * Updates the large video with the given new video source.
  641. */
  642. function updateLargeVideo(newSrc, vol) {
  643. console.log('hover in', newSrc);
  644. if ($('#largeVideo').attr('src') != newSrc) {
  645. var isVisible = $('#largeVideo').is(':visible');
  646. $('#largeVideo').fadeOut(300, function () {
  647. $(this).attr('src', newSrc);
  648. // Screen stream is already rotated
  649. var flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  650. var videoTransform = document.getElementById('largeVideo').style.webkitTransform;
  651. if (flipX && videoTransform !== 'scaleX(-1)') {
  652. document.getElementById('largeVideo').style.webkitTransform = "scaleX(-1)";
  653. }
  654. else if (!flipX && videoTransform === 'scaleX(-1)') {
  655. document.getElementById('largeVideo').style.webkitTransform = "none";
  656. }
  657. // Change the way we'll be measuring and positioning large video
  658. var isDesktop = isVideoSrcDesktop(newSrc);
  659. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  660. getVideoPosition = isDesktop ? getDesktopVideoPosition : getCameraVideoPosition;
  661. if (isVisible)
  662. $(this).fadeIn(300);
  663. });
  664. }
  665. }
  666. /**
  667. * Checks if video identified by given src is desktop stream.
  668. * @param videoSrc eg. blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  669. * @returns {boolean}
  670. */
  671. function isVideoSrcDesktop(videoSrc) {
  672. // FIXME: fix this mapping mess...
  673. // figure out if large video is desktop stream or just a camera
  674. var isDesktop = false;
  675. if (localVideoSrc === videoSrc) {
  676. // local video
  677. isDesktop = isUsingScreenStream;
  678. } else {
  679. // Do we have associations...
  680. var videoSsrc = videoSrcToSsrc[videoSrc];
  681. if (videoSsrc) {
  682. var videoType = ssrc2videoType[videoSsrc];
  683. if (videoType) {
  684. // Finally there...
  685. isDesktop = videoType === 'screen';
  686. } else {
  687. console.error("No video type for ssrc: " + videoSsrc);
  688. }
  689. } else {
  690. console.error("No ssrc for src: " + videoSrc);
  691. }
  692. }
  693. return isDesktop;
  694. }
  695. /**
  696. * Shows/hides the large video.
  697. */
  698. function setLargeVideoVisible(isVisible) {
  699. if (isVisible) {
  700. $('#largeVideo').css({visibility: 'visible'});
  701. $('.watermark').css({visibility: 'visible'});
  702. }
  703. else {
  704. $('#largeVideo').css({visibility: 'hidden'});
  705. $('.watermark').css({visibility: 'hidden'});
  706. }
  707. }
  708. function getConferenceHandler() {
  709. return focus ? focus : activecall;
  710. }
  711. function toggleVideo() {
  712. if (!(connection && connection.jingle.localVideo))
  713. return;
  714. var sess = getConferenceHandler();
  715. if (sess) {
  716. sess.toggleVideoMute(
  717. function (isMuted) {
  718. if (isMuted) {
  719. $('#video').removeClass("icon-camera");
  720. $('#video').addClass("icon-camera icon-camera-disabled");
  721. } else {
  722. $('#video').removeClass("icon-camera icon-camera-disabled");
  723. $('#video').addClass("icon-camera");
  724. }
  725. }
  726. );
  727. }
  728. sess = focus || activecall;
  729. if (!sess) {
  730. return;
  731. }
  732. sess.pendingop = ismuted ? 'unmute' : 'mute';
  733. // connection.emuc.addVideoInfoToPresence(!ismuted);
  734. // connection.emuc.sendPresence();
  735. sess.modifySources();
  736. }
  737. /**
  738. * Mutes / unmutes audio for the local participant.
  739. */
  740. function toggleAudio() {
  741. if (!(connection && connection.jingle.localAudio)) {
  742. preMuted = true;
  743. return;
  744. }
  745. var localAudio = connection.jingle.localAudio;
  746. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  747. var audioEnabled = localAudio.getAudioTracks()[idx].enabled;
  748. localAudio.getAudioTracks()[idx].enabled = !audioEnabled;
  749. connection.emuc.addAudioInfoToPresence(audioEnabled); //isMuted is the opposite of 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. if (roomUrl == null)
  1120. openMessageDialog( "Invite others",
  1121. "Your conference is currently being created."
  1122. + " Please try again in a few seconds.");
  1123. else
  1124. $.prompt('<input id="inviteLinkRef" type="text" value="' +
  1125. encodeURI(roomUrl) + '" onclick="this.select();" readonly>',
  1126. {
  1127. title: "Share this link with everyone you want to invite",
  1128. persistent: false,
  1129. buttons: { "Cancel": false},
  1130. loaded: function (event) {
  1131. document.getElementById('inviteLinkRef').select();
  1132. }
  1133. }
  1134. );
  1135. }
  1136. /**
  1137. * Opens the settings dialog.
  1138. */
  1139. function openSettingsDialog() {
  1140. $.prompt('<h2>Configure your conference</h2>' +
  1141. '<input type="checkbox" id="initMuted"> Participants join muted<br/>' +
  1142. '<input type="checkbox" id="requireNicknames"> Require nicknames<br/><br/>' +
  1143. 'Set a secrect key to lock your room: <input id="lockKey" type="text" placeholder="your shared key" autofocus>',
  1144. {
  1145. persistent: false,
  1146. buttons: { "Save": true, "Cancel": false},
  1147. defaultButton: 1,
  1148. loaded: function (event) {
  1149. document.getElementById('lockKey').focus();
  1150. },
  1151. submit: function (e, v, m, f) {
  1152. if (v) {
  1153. if ($('#initMuted').is(":checked")) {
  1154. // it is checked
  1155. }
  1156. if ($('#requireNicknames').is(":checked")) {
  1157. // it is checked
  1158. }
  1159. /*
  1160. var lockKey = document.getElementById('lockKey');
  1161. if (lockKey.value)
  1162. {
  1163. setSharedKey(lockKey.value);
  1164. lockRoom(true);
  1165. }
  1166. */
  1167. }
  1168. }
  1169. }
  1170. );
  1171. }
  1172. /**
  1173. * Locks / unlocks the room.
  1174. */
  1175. function lockRoom(lock) {
  1176. if (lock)
  1177. connection.emuc.lockRoom(sharedKey);
  1178. else
  1179. connection.emuc.lockRoom('');
  1180. updateLockButton();
  1181. }
  1182. /**
  1183. * Sets the shared key.
  1184. */
  1185. function setSharedKey(sKey) {
  1186. sharedKey = sKey;
  1187. }
  1188. /**
  1189. * Updates the lock button state.
  1190. */
  1191. function updateLockButton() {
  1192. buttonClick("#lockIcon", "icon-security icon-security-locked");
  1193. }
  1194. /**
  1195. * Hides the toolbar.
  1196. */
  1197. var hideToolbar = function () {
  1198. var isToolbarHover = false;
  1199. $('#header').find('*').each(function () {
  1200. var id = $(this).attr('id');
  1201. if ($("#" + id + ":hover").length > 0) {
  1202. isToolbarHover = true;
  1203. }
  1204. });
  1205. clearTimeout(toolbarTimeout);
  1206. toolbarTimeout = null;
  1207. if (!isToolbarHover) {
  1208. $('#header').hide("slide", { direction: "up", duration: 300});
  1209. }
  1210. else {
  1211. toolbarTimeout = setTimeout(hideToolbar, 2000);
  1212. }
  1213. };
  1214. /**
  1215. * Shows the call main toolbar.
  1216. */
  1217. function showToolbar() {
  1218. if (!$('#header').is(':visible')) {
  1219. $('#header').show("slide", { direction: "up", duration: 300});
  1220. if (toolbarTimeout) {
  1221. clearTimeout(toolbarTimeout);
  1222. toolbarTimeout = null;
  1223. }
  1224. toolbarTimeout = setTimeout(hideToolbar, 2000);
  1225. }
  1226. if (focus != null)
  1227. {
  1228. // TODO: Enable settings functionality. Need to uncomment the settings button in index.html.
  1229. // $('#settingsButton').css({visibility:"visible"});
  1230. }
  1231. // Show/hide desktop sharing button
  1232. showDesktopSharingButton();
  1233. }
  1234. /**
  1235. * Docks/undocks the toolbar.
  1236. *
  1237. * @param isDock indicates what operation to perform
  1238. */
  1239. function dockToolbar(isDock) {
  1240. if (isDock) {
  1241. // First make sure the toolbar is shown.
  1242. if (!$('#header').is(':visible')) {
  1243. showToolbar();
  1244. }
  1245. // Then clear the time out, to dock the toolbar.
  1246. clearTimeout(toolbarTimeout);
  1247. toolbarTimeout = null;
  1248. }
  1249. else {
  1250. if (!$('#header').is(':visible')) {
  1251. showToolbar();
  1252. }
  1253. else {
  1254. toolbarTimeout = setTimeout(hideToolbar, 2000);
  1255. }
  1256. }
  1257. }
  1258. /**
  1259. * Updates the room invite url.
  1260. */
  1261. function updateRoomUrl(newRoomUrl) {
  1262. roomUrl = newRoomUrl;
  1263. }
  1264. /**
  1265. * Warning to the user that the conference window is about to be closed.
  1266. */
  1267. function closePageWarning() {
  1268. if (focus !== null)
  1269. return "You are the owner of this conference call and you are about to end it.";
  1270. else
  1271. return "You are about to leave this conversation.";
  1272. }
  1273. /**
  1274. * Shows a visual indicator for the focus of the conference.
  1275. * Currently if we're not the owner of the conference we obtain the focus
  1276. * from the connection.jingle.sessions.
  1277. */
  1278. function showFocusIndicator() {
  1279. if (focus !== null) {
  1280. var indicatorSpan = $('#localVideoContainer .focusindicator');
  1281. if (indicatorSpan.children().length === 0)
  1282. {
  1283. createFocusIndicatorElement(indicatorSpan[0]);
  1284. }
  1285. }
  1286. else if (Object.keys(connection.jingle.sessions).length > 0) {
  1287. // If we're only a participant the focus will be the only session we have.
  1288. var session = connection.jingle.sessions[Object.keys(connection.jingle.sessions)[0]];
  1289. var focusId = 'participant_' + Strophe.getResourceFromJid(session.peerjid);
  1290. var focusContainer = document.getElementById(focusId);
  1291. if (!focusContainer) {
  1292. console.error("No focus container!");
  1293. return;
  1294. }
  1295. var indicatorSpan = $('#' + focusId + ' .focusindicator');
  1296. if (!indicatorSpan || indicatorSpan.length === 0) {
  1297. indicatorSpan = document.createElement('span');
  1298. indicatorSpan.className = 'focusindicator';
  1299. focusContainer.appendChild(indicatorSpan);
  1300. createFocusIndicatorElement(indicatorSpan);
  1301. }
  1302. }
  1303. }
  1304. /**
  1305. * Checks if container for participant identified by given peerJid exists in the document and creates it eventually.
  1306. * @param peerJid peer Jid to check.
  1307. */
  1308. function ensurePeerContainerExists(peerJid) {
  1309. var peerResource = Strophe.getResourceFromJid(peerJid);
  1310. var videoSpanId = 'participant_' + peerResource;
  1311. if ($('#' + videoSpanId).length > 0) {
  1312. return;
  1313. }
  1314. var container = addRemoteVideoContainer(peerJid, videoSpanId);
  1315. var nickfield = document.createElement('span');
  1316. nickfield.className = "nick";
  1317. nickfield.appendChild(document.createTextNode(peerResource));
  1318. container.appendChild(nickfield);
  1319. resizeThumbnails();
  1320. }
  1321. function addRemoteVideoContainer(peerJid, spanId) {
  1322. var container = document.createElement('span');
  1323. container.id = spanId;
  1324. container.className = 'videocontainer';
  1325. var remotes = document.getElementById('remoteVideos');
  1326. if (focus)
  1327. addRemoteVideoMenu(peerJid, container);
  1328. remotes.appendChild(container);
  1329. return container;
  1330. }
  1331. /**
  1332. * Creates the element indicating the focus of the conference.
  1333. */
  1334. function createFocusIndicatorElement(parentElement) {
  1335. var focusIndicator = document.createElement('i');
  1336. focusIndicator.className = 'fa fa-star';
  1337. focusIndicator.title = "The owner of this conference";
  1338. parentElement.appendChild(focusIndicator);
  1339. }
  1340. function addRemoteVideoMenu(jid, parentElement) {
  1341. var spanElement = document.createElement('span');
  1342. spanElement.className = 'remotevideomenu';
  1343. parentElement.appendChild(spanElement);
  1344. var menuElement = document.createElement('i');
  1345. menuElement.className = 'fa fa-angle-down';
  1346. menuElement.title = 'Remote user controls';
  1347. spanElement.appendChild(menuElement);
  1348. // <ul class="popupmenu">
  1349. // <li><a href="#">Mute</a></li>
  1350. // <li><a href="#">Eject</a></li>
  1351. // </ul>
  1352. var popupmenuElement = document.createElement('ul');
  1353. popupmenuElement.className = 'popupmenu';
  1354. popupmenuElement.id = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  1355. spanElement.appendChild(popupmenuElement);
  1356. var muteMenuItem = document.createElement('li');
  1357. var muteLinkItem = document.createElement('a');
  1358. var mutedIndicator = "<span><i class='icon-mic-disabled'></i></span>";
  1359. if (!mutedAudios[jid]) {
  1360. muteLinkItem.innerHTML = mutedIndicator + 'Mute';
  1361. muteLinkItem.className = 'mutelink';
  1362. }
  1363. else {
  1364. muteLinkItem.innerHTML = mutedIndicator + 'Muted';
  1365. muteLinkItem.className = 'mutelink disabled';
  1366. }
  1367. muteLinkItem.onclick = function(){
  1368. if ($(this).attr('disabled') != undefined) {
  1369. event.preventDefault();
  1370. }
  1371. var isMute = !mutedAudios[jid];
  1372. connection.moderate.setMute(jid, isMute);
  1373. popupmenuElement.setAttribute('style', 'display:none;');
  1374. if (isMute) {
  1375. this.innerHTML = mutedIndicator + 'Muted';
  1376. this.className = 'mutelink disabled';
  1377. }
  1378. else {
  1379. this.innerHTML = mutedIndicator + 'Mute';
  1380. this.className = 'mutelink';
  1381. }
  1382. };
  1383. muteMenuItem.appendChild(muteLinkItem);
  1384. popupmenuElement.appendChild(muteMenuItem);
  1385. var ejectIndicator = "<span><i class='icon-kick'></i></span>";
  1386. var ejectMenuItem = document.createElement('li');
  1387. var ejectLinkItem = document.createElement('a');
  1388. ejectLinkItem.innerHTML = ejectIndicator + 'Kick out';
  1389. ejectLinkItem.onclick = function(){
  1390. connection.moderate.eject(jid);
  1391. popupmenuElement.setAttribute('style', 'display:none;');
  1392. };
  1393. ejectMenuItem.appendChild(ejectLinkItem);
  1394. popupmenuElement.appendChild(ejectMenuItem);
  1395. }
  1396. function updateRemoteVideoMenu(jid, isMuted) {
  1397. var muteMenuItem
  1398. = $('#remote_popupmenu_'
  1399. + Strophe.getResourceFromJid(jid)
  1400. + '>li>a.mutelink');
  1401. var mutedIndicator = "<span><i class='icon-mic-disabled'></i></span>";
  1402. if (muteMenuItem.length) {
  1403. var muteLink = muteMenuItem.get(0);
  1404. if (isMuted === 'true') {
  1405. muteLink.innerHTML = mutedIndicator + 'Muted';
  1406. muteLink.className = 'mutelink disabled';
  1407. }
  1408. else {
  1409. muteLink.innerHTML = mutedIndicator + 'Mute';
  1410. muteLink.className = 'mutelink';
  1411. }
  1412. }
  1413. }
  1414. /**
  1415. * Toggles the application in and out of full screen mode
  1416. * (a.k.a. presentation mode in Chrome).
  1417. */
  1418. function toggleFullScreen() {
  1419. var fsElement = document.documentElement;
  1420. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  1421. //Enter Full Screen
  1422. if (fsElement.mozRequestFullScreen) {
  1423. fsElement.mozRequestFullScreen();
  1424. }
  1425. else {
  1426. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  1427. }
  1428. } else {
  1429. //Exit Full Screen
  1430. if (document.mozCancelFullScreen) {
  1431. document.mozCancelFullScreen();
  1432. } else {
  1433. document.webkitCancelFullScreen();
  1434. }
  1435. }
  1436. }
  1437. /**
  1438. * Shows the display name for the given video.
  1439. */
  1440. function showDisplayName(videoSpanId, displayName) {
  1441. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  1442. // If we already have a display name for this video.
  1443. if (nameSpan.length > 0) {
  1444. var nameSpanElement = nameSpan.get(0);
  1445. if (nameSpanElement.id === 'localDisplayName' &&
  1446. $('#localDisplayName').text() !== displayName) {
  1447. $('#localDisplayName').text(displayName);
  1448. } else {
  1449. $('#' + videoSpanId + '_name').text(displayName);
  1450. }
  1451. } else {
  1452. var editButton = null;
  1453. if (videoSpanId === 'localVideoContainer') {
  1454. editButton = createEditDisplayNameButton();
  1455. }
  1456. if (displayName.length) {
  1457. nameSpan = document.createElement('span');
  1458. nameSpan.className = 'displayname';
  1459. nameSpan.innerText = displayName;
  1460. $('#' + videoSpanId)[0].appendChild(nameSpan);
  1461. }
  1462. if (!editButton) {
  1463. nameSpan.id = videoSpanId + '_name';
  1464. } else {
  1465. nameSpan.id = 'localDisplayName';
  1466. $('#' + videoSpanId)[0].appendChild(editButton);
  1467. var editableText = document.createElement('input');
  1468. editableText.className = 'displayname';
  1469. editableText.id = 'editDisplayName';
  1470. if (displayName.length) {
  1471. editableText.value = displayName.substring(0, displayName.indexOf(' (me)'));
  1472. }
  1473. editableText.setAttribute('style', 'display:none;');
  1474. editableText.setAttribute('placeholder', 'ex. Jane Pink');
  1475. $('#' + videoSpanId)[0].appendChild(editableText);
  1476. $('#localVideoContainer .displayname').bind("click", function (e) {
  1477. e.preventDefault();
  1478. $('#localDisplayName').hide();
  1479. $('#editDisplayName').show();
  1480. $('#editDisplayName').focus();
  1481. $('#editDisplayName').select();
  1482. var inputDisplayNameHandler = function (name) {
  1483. if (nickname !== name) {
  1484. nickname = name;
  1485. window.localStorage.displayname = nickname;
  1486. connection.emuc.addDisplayNameToPresence(nickname);
  1487. connection.emuc.sendPresence();
  1488. Chat.setChatConversationMode(true);
  1489. }
  1490. if (!$('#localDisplayName').is(":visible")) {
  1491. $('#localDisplayName').text(nickname + " (me)");
  1492. $('#localDisplayName').show();
  1493. $('#editDisplayName').hide();
  1494. }
  1495. };
  1496. $('#editDisplayName').one("focusout", function (e) {
  1497. inputDisplayNameHandler(this.value);
  1498. });
  1499. $('#editDisplayName').on('keydown', function (e) {
  1500. if (e.keyCode === 13) {
  1501. e.preventDefault();
  1502. inputDisplayNameHandler(this.value);
  1503. }
  1504. });
  1505. });
  1506. }
  1507. }
  1508. }
  1509. /**
  1510. * Creates the edit display name button.
  1511. *
  1512. * @returns the edit button
  1513. */
  1514. function createEditDisplayNameButton() {
  1515. var editButton = document.createElement('a');
  1516. editButton.className = 'displayname';
  1517. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  1518. return editButton;
  1519. }
  1520. /**
  1521. * Shows audio muted indicator over small videos.
  1522. */
  1523. function showAudioIndicator(videoSpanId, isMuted) {
  1524. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  1525. if (isMuted === 'false') {
  1526. if (audioMutedSpan.length > 0) {
  1527. audioMutedSpan.remove();
  1528. }
  1529. }
  1530. else {
  1531. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  1532. audioMutedSpan = document.createElement('span');
  1533. audioMutedSpan.className = 'audioMuted';
  1534. if (videoMutedSpan) {
  1535. audioMutedSpan.right = '30px';
  1536. }
  1537. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  1538. var mutedIndicator = document.createElement('i');
  1539. mutedIndicator.className = 'icon-mic-disabled';
  1540. mutedIndicator.title = "Participant is muted";
  1541. audioMutedSpan.appendChild(mutedIndicator);
  1542. }
  1543. }
  1544. /**
  1545. * Shows video muted indicator over small videos.
  1546. */
  1547. function showVideoIndicator(videoSpanId, isMuted) {
  1548. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  1549. if (isMuted === 'false') {
  1550. if (videoMutedSpan.length > 0) {
  1551. videoMutedSpan.remove();
  1552. }
  1553. }
  1554. else {
  1555. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  1556. videoMutedSpan = document.createElement('span');
  1557. videoMutedSpan.className = 'videoMuted';
  1558. if (audioMutedSpan) {
  1559. videoMutedSpan.right = '30px';
  1560. }
  1561. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  1562. var mutedIndicator = document.createElement('i');
  1563. mutedIndicator.className = 'icon-camera-disabled';
  1564. mutedIndicator.title = "Participant has stopped the camera.";
  1565. videoMutedSpan.appendChild(mutedIndicator);
  1566. }
  1567. }
  1568. /**
  1569. * Resizes and repositions videos in full screen mode.
  1570. */
  1571. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1572. function () {
  1573. resizeLargeVideoContainer();
  1574. positionLarge();
  1575. isFullScreen = document.fullScreen ||
  1576. document.mozFullScreen ||
  1577. document.webkitIsFullScreen;
  1578. if (isFullScreen) {
  1579. setView("fullscreen");
  1580. }
  1581. else {
  1582. setView("default");
  1583. }
  1584. }
  1585. );
  1586. /**
  1587. * Sets the current view.
  1588. */
  1589. function setView(viewName) {
  1590. // if (viewName == "fullscreen") {
  1591. // document.getElementById('videolayout_fullscreen').disabled = false;
  1592. // document.getElementById('videolayout_default').disabled = true;
  1593. // }
  1594. // else {
  1595. // document.getElementById('videolayout_default').disabled = false;
  1596. // document.getElementById('videolayout_fullscreen').disabled = true;
  1597. // }
  1598. }