Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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