Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

app.js 58KB

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