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

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