您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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