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

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