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.

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