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

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