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

app.js 58KB

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