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

app.js 36KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  1. /* jshint -W117 */
  2. /* application specific logic */
  3. var connection = null;
  4. var focus = null;
  5. var RTC;
  6. var RTCPeerConnection = 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. RTCPeerconnection = TraceablePeerConnection;
  24. connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
  25. if (connection.disco) {
  26. // for chrome, add multistream cap
  27. }
  28. connection.jingle.pc_constraints = RTC.pc_constraints;
  29. var jid = document.getElementById('jid').value || config.hosts.domain || window.location.hostname;
  30. connection.connect(jid, document.getElementById('password').value, function (status) {
  31. if (status == Strophe.Status.CONNECTED) {
  32. console.log('connected');
  33. if (RTC.browser == 'firefox') {
  34. getUserMediaWithConstraints(['audio']);
  35. } else {
  36. getUserMediaWithConstraints(['audio', 'video'], '360');
  37. }
  38. document.getElementById('connect').disabled = true;
  39. } else {
  40. console.log('status', status);
  41. }
  42. });
  43. }
  44. function doJoin() {
  45. var roomnode = null;
  46. var path = window.location.pathname;
  47. var roomjid;
  48. // determinde the room node from the url
  49. // TODO: just the roomnode or the whole bare jid?
  50. if (config.getroomnode && typeof config.getroomnode === 'function') {
  51. // custom function might be responsible for doing the pushstate
  52. roomnode = config.getroomnode(path);
  53. } else {
  54. /* fall back to default strategy
  55. * this is making assumptions about how the URL->room mapping happens.
  56. * It currently assumes deployment at root, with a rewrite like the
  57. * following one (for nginx):
  58. location ~ ^/([a-zA-Z0-9]+)$ {
  59. rewrite ^/(.*)$ / break;
  60. }
  61. */
  62. if (path.length > 1) {
  63. roomnode = path.substr(1).toLowerCase();
  64. } else {
  65. roomnode = Math.random().toString(36).substr(2, 20);
  66. window.history.pushState('VideoChat', 'Room: ' + roomnode, window.location.pathname + roomnode);
  67. }
  68. }
  69. roomjid = roomnode + '@' + config.hosts.muc;
  70. if (config.useNicks) {
  71. var nick = window.prompt('Your nickname (optional)');
  72. if (nick) {
  73. roomjid += '/' + nick;
  74. } else {
  75. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  76. }
  77. } else {
  78. roomjid += '/' + Strophe.getNodeFromJid(connection.jid).substr(0,8);
  79. }
  80. connection.emuc.doJoin(roomjid);
  81. }
  82. $(document).bind('mediaready.jingle', function (event, stream) {
  83. connection.jingle.localStream = stream;
  84. RTC.attachMediaStream($('#localVideo'), stream);
  85. document.getElementById('localVideo').muted = true;
  86. document.getElementById('localVideo').autoplay = true;
  87. document.getElementById('localVideo').volume = 0;
  88. localVideoSrc = document.getElementById('localVideo').src;
  89. updateLargeVideo(localVideoSrc, true, 0);
  90. $('#localVideo').click(function () {
  91. updateLargeVideo($(this).attr('src'), true, 1);
  92. });
  93. doJoin();
  94. });
  95. $(document).bind('mediafailure.jingle', function () {
  96. // FIXME
  97. });
  98. $(document).bind('remotestreamadded.jingle', function (event, data, sid) {
  99. function waitForRemoteVideo(selector, sid) {
  100. var sess = connection.jingle.sessions[sid];
  101. videoTracks = data.stream.getVideoTracks();
  102. if (videoTracks.length === 0 || selector[0].currentTime > 0) {
  103. RTC.attachMediaStream(selector, data.stream); // FIXME: why do i have to do this for FF?
  104. $(document).trigger('callactive.jingle', [selector, sid]);
  105. console.log('waitForremotevideo', sess.peerconnection.iceConnectionState, sess.peerconnection.signalingState);
  106. } else {
  107. setTimeout(function () { waitForRemoteVideo(selector, sid); }, 100);
  108. }
  109. }
  110. var sess = connection.jingle.sessions[sid];
  111. // look up an associated JID for a stream id
  112. if (data.stream.id.indexOf('mixedmslabel') == -1) {
  113. var ssrclines = SDPUtil.find_lines(sess.peerconnection.remoteDescription.sdp, 'a=ssrc');
  114. ssrclines = ssrclines.filter(function (line) {
  115. return line.indexOf('mslabel:' + data.stream.label) != -1;
  116. });
  117. if (ssrclines.length) {
  118. thessrc = ssrclines[0].substring(7).split(' ')[0];
  119. // ok to overwrite the one from focus? might save work in colibri.js
  120. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  121. if (ssrc2jid[thessrc]) {
  122. data.peerjid = ssrc2jid[thessrc];
  123. }
  124. }
  125. }
  126. var container;
  127. var remotes = document.getElementById('remoteVideos');
  128. if (data.peerjid) {
  129. container = document.getElementById('participant_' + Strophe.getResourceFromJid(data.peerjid));
  130. if (!container) {
  131. console.warn('no container for', data.peerjid);
  132. // create for now...
  133. // FIXME: should be removed
  134. container = addRemoteVideoContainer('participant_' + Strophe.getResourceFromJid(data.peerjid));
  135. } else {
  136. //console.log('found container for', data.peerjid);
  137. }
  138. } else {
  139. if (data.stream.id != 'mixedmslabel') {
  140. console.warn('can not associate stream', data.stream.id, 'with a participant');
  141. }
  142. // FIXME: for the mixed ms we dont need a video -- currently
  143. container = document.createElement('span');
  144. container.className = 'videocontainer';
  145. remotes.appendChild(container);
  146. }
  147. var vid = document.createElement('video');
  148. var id = 'remoteVideo_' + sid + '_' + data.stream.id;
  149. vid.id = id;
  150. vid.autoplay = true;
  151. vid.oncontextmenu = function () { return false; };
  152. container.appendChild(vid);
  153. // TODO: make mixedstream display:none via css?
  154. if (id.indexOf('mixedmslabel') != -1) {
  155. container.id = 'mixedstream';
  156. $(container).hide();
  157. }
  158. var sel = $('#' + id);
  159. sel.hide();
  160. RTC.attachMediaStream(sel, data.stream);
  161. waitForRemoteVideo(sel, sid);
  162. data.stream.onended = function () {
  163. console.log('stream ended', this.id);
  164. var src = $('#' + id).attr('src');
  165. if (src === $('#largeVideo').attr('src')) {
  166. // this is currently displayed as large
  167. // pick the last visible video in the row
  168. // if nobody else is left, this picks the local video
  169. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video').get(0);
  170. // mute if localvideo
  171. var isLocalVideo = false;
  172. if (pick) {
  173. if (pick.src === localVideoSrc)
  174. isLocalVideo = true;
  175. updateLargeVideo(pick.src, isLocalVideo, pick.volume);
  176. }
  177. }
  178. $('#' + id).parent().remove();
  179. resizeThumbnails();
  180. };
  181. sel.click(
  182. function () {
  183. updateLargeVideo($(this).attr('src'), false, 1);
  184. }
  185. );
  186. });
  187. $(document).bind('callincoming.jingle', function (event, sid) {
  188. var sess = connection.jingle.sessions[sid];
  189. // TODO: check affiliation and/or role
  190. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  191. sess.sendAnswer();
  192. sess.accept();
  193. });
  194. $(document).bind('callactive.jingle', function (event, videoelem, sid) {
  195. if (videoelem.attr('id').indexOf('mixedmslabel') == -1) {
  196. // ignore mixedmslabela0 and v0
  197. videoelem.show();
  198. resizeThumbnails();
  199. updateLargeVideo(videoelem.attr('src'), false, 1);
  200. showFocusIndicator();
  201. }
  202. });
  203. $(document).bind('callterminated.jingle', function (event, sid, reason) {
  204. // FIXME
  205. });
  206. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  207. // put our ssrcs into presence so other clients can identify our stream
  208. var sess = connection.jingle.sessions[sid];
  209. var newssrcs = {};
  210. var localSDP = new SDP(sess.peerconnection.localDescription.sdp);
  211. localSDP.media.forEach(function (media) {
  212. var type = SDPUtil.parse_mline(media.split('\r\n')[0]).media;
  213. var ssrc = SDPUtil.find_line(media, 'a=ssrc:').substring(7).split(' ')[0];
  214. // assumes a single local ssrc
  215. newssrcs[type] = ssrc;
  216. });
  217. console.log('new ssrcs', newssrcs);
  218. var i = 0;
  219. Object.keys(newssrcs).forEach(function (mtype) {
  220. i++;
  221. connection.emuc.addMediaToPresence(i, mtype, newssrcs[mtype]);
  222. });
  223. connection.emuc.sendPresence();
  224. });
  225. $(document).bind('joined.muc', function (event, jid, info) {
  226. updateRoomUrl(window.location.href);
  227. document.getElementById('localNick').appendChild(
  228. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (you)')
  229. );
  230. if (Object.keys(connection.emuc.members).length < 1) {
  231. focus = new ColibriFocus(connection, config.hosts.bridge);
  232. }
  233. // Once we've joined the muc show the toolbar
  234. showToolbar();
  235. });
  236. $(document).bind('entered.muc', function (event, jid, info, pres) {
  237. console.log('entered', jid, info);
  238. console.log(focus);
  239. var container = addRemoteVideoContainer('participant_' + Strophe.getResourceFromJid(jid));
  240. var nickfield = document.createElement('span');
  241. nickfield.appendChild(document.createTextNode(Strophe.getResourceFromJid(jid)));
  242. container.appendChild(nickfield);
  243. resizeThumbnails();
  244. if (focus !== null) {
  245. // FIXME: this should prepare the video
  246. if (focus.confid === null) {
  247. console.log('make new conference with', jid);
  248. focus.makeConference(Object.keys(connection.emuc.members));
  249. } else {
  250. console.log('invite', jid, 'into conference');
  251. focus.addNewParticipant(jid);
  252. }
  253. }
  254. else if (sharedKey) {
  255. updateLockButton();
  256. }
  257. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  258. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  259. ssrc2jid[ssrc.getAttribute('ssrc')] = jid;
  260. });
  261. });
  262. $(document).bind('left.muc', function (event, jid) {
  263. console.log('left', jid);
  264. connection.jingle.terminateByJid(jid);
  265. var container = document.getElementById('participant_' + Strophe.getResourceFromJid(jid));
  266. if (container) {
  267. // hide here, wait for video to close before removing
  268. $(container).hide();
  269. resizeThumbnails();
  270. }
  271. if (Object.keys(connection.emuc.members).length === 0) {
  272. console.log('everyone left');
  273. if (focus !== null) {
  274. // FIXME: closing the connection is a hack to avoid some
  275. // problemswith reinit
  276. if (focus.peerconnection !== null) {
  277. focus.peerconnection.close();
  278. }
  279. focus = new ColibriFocus(connection, config.hosts.bridge);
  280. }
  281. }
  282. if (connection.emuc.getPrezi(jid)) {
  283. $(document).trigger('presentationremoved.muc', [jid, connection.emuc.getPrezi(jid)]);
  284. }
  285. });
  286. $(document).bind('presence.muc', function (event, jid, info, pres) {
  287. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  288. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  289. ssrc2jid[ssrc.getAttribute('ssrc')] = jid;
  290. });
  291. });
  292. $(document).bind('passwordrequired.muc', function (event, jid) {
  293. console.log('on password required', jid);
  294. $.prompt('<h2>Password required</h2>' +
  295. '<input id="lockKey" type="text" placeholder="shared key" autofocus>',
  296. {
  297. persistent: true,
  298. buttons: { "Ok": true , "Cancel": false},
  299. defaultButton: 1,
  300. loaded: function(event) {
  301. document.getElementById('lockKey').focus();
  302. },
  303. submit: function(e,v,m,f){
  304. if(v)
  305. {
  306. var lockKey = document.getElementById('lockKey');
  307. if (lockKey.value != null)
  308. {
  309. setSharedKey(lockKey);
  310. connection.emuc.doJoin(jid, lockKey.value);
  311. }
  312. }
  313. }
  314. });
  315. });
  316. /*
  317. * Presentation has been removed.
  318. */
  319. $(document).bind('presentationremoved.muc', function(event, jid, presUrl) {
  320. console.log('presentation removed', presUrl);
  321. var presId = getPresentationId(presUrl);
  322. setPresentationVisible(false);
  323. $('#participant_' + Strophe.getResourceFromJid(jid) + '_' + presId).remove();
  324. $('#presentation>iframe').remove();
  325. if (preziPlayer != null) {
  326. preziPlayer.destroy();
  327. preziPlayer = null;
  328. }
  329. });
  330. /*
  331. * Presentation has been added.
  332. */
  333. $(document).bind('presentationadded.muc', function (event, jid, presUrl, currentSlide) {
  334. console.log("presentation added", presUrl);
  335. var presId = getPresentationId(presUrl);
  336. var elementId = 'participant_' + Strophe.getResourceFromJid(jid) + '_' + presId;
  337. var container = addRemoteVideoContainer(elementId);
  338. resizeThumbnails();
  339. var controlsEnabled = false;
  340. if (jid === connection.emuc.myroomjid)
  341. controlsEnabled = true;
  342. setPresentationVisible(true);
  343. $('#largeVideoContainer').hover(
  344. function (event) {
  345. if ($('#largeVideo').css('visibility') == 'hidden')
  346. $('#reloadPresentation').css({display:'inline-block'});
  347. },
  348. function (event) {
  349. if ($('#largeVideo').css('visibility') == 'visible')
  350. $('#reloadPresentation').css({display:'none'});
  351. else {
  352. var e = event.toElement || event.relatedTarget;
  353. while(e && e.parentNode && e.parentNode != window) {
  354. if (e.parentNode == this || e == this) {
  355. return false;
  356. }
  357. e = e.parentNode;
  358. }
  359. $('#reloadPresentation').css({display:'none'});
  360. }
  361. });
  362. preziPlayer = new PreziPlayer(
  363. 'presentation',
  364. {preziId: presId,
  365. width: $('#largeVideoContainer').width(),
  366. height: $('#largeVideoContainer').height(),
  367. controls: controlsEnabled,
  368. debug: true
  369. });
  370. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  371. // $('#presentation>iframe').load(function (){
  372. // console.log("IFRAME LOADED!!!!!!!!!!!!!!!!");
  373. // });
  374. // $('#presentation>iframe').ready(function (){
  375. // console.log("IFRAME READY!!!!!!!!!!!!!!!!");
  376. // });
  377. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  378. console.log("prezi status", event.value);
  379. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  380. if (jid != connection.emuc.myroomjid)
  381. preziPlayer.flyToStep(currentSlide);
  382. }
  383. });
  384. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  385. console.log("event value", event.value);
  386. connection.emuc.addCurrentSlideToPresence(event.value);
  387. connection.emuc.sendPresence();
  388. });
  389. $("#" + elementId).css('background-image','url(../images/avatarprezi.png)');
  390. $("#" + elementId).click(
  391. function () {
  392. setPresentationVisible(true);
  393. }
  394. );
  395. });
  396. /*
  397. * Indicates presentation slide change.
  398. */
  399. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  400. if (preziPlayer) {
  401. preziPlayer.flyToStep(current);
  402. }
  403. });
  404. /**
  405. * Returns the presentation id from the given url.
  406. */
  407. function getPresentationId (presUrl) {
  408. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  409. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  410. }
  411. /*
  412. * Reloads the current presentation.
  413. */
  414. function reloadPresentation() {
  415. var iframe = document.getElementById(preziPlayer.options.preziId);
  416. iframe.src = iframe.src;
  417. }
  418. /*
  419. * Shows/hides a presentation.
  420. */
  421. function setPresentationVisible(visible) {
  422. if (visible) {
  423. $('#largeVideo').fadeOut(300, function () {
  424. $('#largeVideo').css({visibility:'hidden'});
  425. $('#presentation>iframe').fadeIn(300, function() {
  426. $('#presentation>iframe').css({opacity:'1'});
  427. });
  428. });
  429. }
  430. else {
  431. if ($('#presentation>iframe')) {
  432. $('#presentation>iframe').fadeOut(300, function () {
  433. $('#presentation>iframe').css({opacity:'0'});
  434. $('#largeVideo').fadeIn(300, function() {
  435. $('#largeVideo').css({visibility:'visible'});
  436. });
  437. });
  438. }
  439. }
  440. }
  441. /**
  442. * Updates the large video with the given new video source.
  443. */
  444. function updateLargeVideo(newSrc, localVideo, vol) {
  445. console.log('hover in', newSrc);
  446. setPresentationVisible(false);
  447. if ($('#largeVideo').attr('src') != newSrc) {
  448. document.getElementById('largeVideo').volume = vol;
  449. $('#largeVideo').fadeOut(300, function () {
  450. $(this).attr('src', newSrc);
  451. var videoTransform = document.getElementById('largeVideo').style.webkitTransform;
  452. if (localVideo && videoTransform != 'scaleX(-1)') {
  453. document.getElementById('largeVideo').style.webkitTransform = "scaleX(-1)";
  454. }
  455. else if (!localVideo && videoTransform == 'scaleX(-1)') {
  456. document.getElementById('largeVideo').style.webkitTransform = "none";
  457. }
  458. $(this).fadeIn(300);
  459. });
  460. }
  461. }
  462. function toggleVideo() {
  463. if (!(connection && connection.jingle.localStream)) return;
  464. for (var idx = 0; idx < connection.jingle.localStream.getVideoTracks().length; idx++) {
  465. connection.jingle.localStream.getVideoTracks()[idx].enabled = !connection.jingle.localStream.getVideoTracks()[idx].enabled;
  466. }
  467. }
  468. function toggleAudio() {
  469. if (!(connection && connection.jingle.localStream)) return;
  470. for (var idx = 0; idx < connection.jingle.localStream.getAudioTracks().length; idx++) {
  471. connection.jingle.localStream.getAudioTracks()[idx].enabled = !connection.jingle.localStream.getAudioTracks()[idx].enabled;
  472. }
  473. }
  474. function resizeLarge() {
  475. var availableHeight = window.innerHeight;
  476. var chatspaceWidth = $('#chatspace').width();
  477. var numvids = $('#remoteVideos>video:visible').length;
  478. if (numvids < 5)
  479. availableHeight -= 100; // min thumbnail height for up to 4 videos
  480. else
  481. availableHeight -= 50; // min thumbnail height for more than 5 videos
  482. availableHeight -= 79; // padding + link ontop
  483. var availableWidth = window.innerWidth - chatspaceWidth;
  484. var aspectRatio = 16.0 / 9.0;
  485. if (availableHeight < availableWidth / aspectRatio) {
  486. availableWidth = Math.floor(availableHeight * aspectRatio);
  487. }
  488. if (availableWidth < 0 || availableHeight < 0) return;
  489. $('#largeVideo').parent().width(availableWidth);
  490. $('#largeVideo').parent().height(availableWidth / aspectRatio);
  491. $('#presentation>iframe').width(availableWidth);
  492. $('#presentation>iframe').height(availableWidth / aspectRatio);
  493. resizeThumbnails();
  494. }
  495. function resizeThumbnails() {
  496. // Calculate the available height, which is the inner window height minus 39px for the header
  497. // minus 4px for the delimiter lines on the top and bottom of the large video,
  498. // minus the 36px space inside the remoteVideos container used for highlighting shadow.
  499. var availableHeight = window.innerHeight - $('#largeVideo').height() - 79;
  500. var numvids = $('#remoteVideos>span:visible').length;
  501. // Remove the 1px borders arround videos.
  502. var availableWinWidth = $('#remoteVideos').width() - 2 * numvids - 50;
  503. var availableWidth = availableWinWidth / numvids;
  504. var aspectRatio = 16.0 / 9.0;
  505. var maxHeight = Math.min(160, availableHeight);
  506. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  507. if (availableHeight < availableWidth / aspectRatio) {
  508. availableWidth = Math.floor(availableHeight * aspectRatio);
  509. }
  510. // size videos so that while keeping AR and max height, we have a nice fit
  511. $('#remoteVideos').height(availableHeight+26); // add the 2*18px-padding-top border used for highlighting shadow.
  512. $('#remoteVideos>span').width(availableWidth);
  513. $('#remoteVideos>span').height(availableHeight);
  514. }
  515. $(document).ready(function () {
  516. $('#nickinput').keydown(function(event) {
  517. if (event.keyCode == 13) {
  518. event.preventDefault();
  519. var val = this.value;
  520. this.value = '';
  521. if (!nickname) {
  522. nickname = val;
  523. $('#nickname').css({visibility:"hidden"});
  524. $('#chatconversation').css({visibility:'visible'});
  525. $('#usermsg').css({visibility:'visible'});
  526. $('#usermsg').focus();
  527. return;
  528. }
  529. }
  530. });
  531. $('#usermsg').keydown(function(event) {
  532. if (event.keyCode == 13) {
  533. event.preventDefault();
  534. var message = this.value;
  535. $('#usermsg').val('').trigger('autosize.resize');
  536. this.focus();
  537. connection.emuc.sendMessage(message, nickname);
  538. }
  539. });
  540. $('#usermsg').autosize();
  541. // Set the defaults for prompt dialogs.
  542. jQuery.prompt.setDefaults({persistent: false});
  543. resizeLarge();
  544. $(window).resize(function () {
  545. resizeLarge();
  546. });
  547. if (!$('#settings').is(':visible')) {
  548. console.log('init');
  549. init();
  550. } else {
  551. loginInfo.onsubmit = function (e) {
  552. if (e.preventDefault) e.preventDefault();
  553. $('#settings').hide();
  554. init();
  555. };
  556. }
  557. });
  558. $(window).bind('beforeunload', function () {
  559. if (connection && connection.connected) {
  560. // ensure signout
  561. $.ajax({
  562. type: 'POST',
  563. url: config.bosh,
  564. async: false,
  565. cache: false,
  566. contentType: 'application/xml',
  567. 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>",
  568. success: function (data) {
  569. console.log('signed out');
  570. console.log(data);
  571. },
  572. error: function (XMLHttpRequest, textStatus, errorThrown) {
  573. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  574. }
  575. });
  576. }
  577. });
  578. function dump(elem, filename){
  579. elem = elem.parentNode;
  580. elem.download = filename || 'meetlog.json';
  581. elem.href = 'data:application/json;charset=utf-8,\n';
  582. var data = {};
  583. if (connection.jingle) {
  584. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  585. var session = connection.jingle.sessions[sid];
  586. if (session.peerconnection && session.peerconnection.updateLog) {
  587. // FIXME: should probably be a .dump call
  588. data["jingle_" + session.sid] = {
  589. updateLog: session.peerconnection.updateLog,
  590. url: window.location.href}
  591. ;
  592. }
  593. });
  594. }
  595. metadata = {};
  596. metadata.time = new Date();
  597. metadata.url = window.location.href;
  598. metadata.ua = navigator.userAgent;
  599. if (connection.logger) {
  600. metadata.xmpp = connection.logger.log;
  601. }
  602. data.metadata = metadata;
  603. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  604. return false;
  605. }
  606. /*
  607. * Appends the given message to the chat conversation.
  608. */
  609. function updateChatConversation(nick, message)
  610. {
  611. var divClassName = '';
  612. if (nickname == nick)
  613. divClassName = "localuser";
  614. else
  615. divClassName = "remoteuser";
  616. $('#chatconversation').append('<div class="' + divClassName + '"><b>' + nick + ': </b>' + message + '</div>');
  617. $('#chatconversation').animate({ scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  618. }
  619. /*
  620. * Changes the style class of the element given by id.
  621. */
  622. function buttonClick(id, classname) {
  623. $(id).toggleClass(classname); // add the class to the clicked element
  624. }
  625. /*
  626. * Opens the lock room dialog.
  627. */
  628. function openLockDialog() {
  629. // Only the focus is able to set a shared key.
  630. if (focus == null) {
  631. if (sharedKey)
  632. $.prompt("This conversation is currently protected by a shared secret key.",
  633. {
  634. title: "Secrect key",
  635. persistent: false
  636. });
  637. else
  638. $.prompt("This conversation isn't currently protected by a secret key. Only the owner of the conference could set a shared key.",
  639. {
  640. title: "Secrect key",
  641. persistent: false
  642. });
  643. }
  644. else {
  645. if (sharedKey)
  646. $.prompt("Are you sure you would like to remove your secret key?",
  647. {
  648. title: "Remove secrect key",
  649. persistent: false,
  650. buttons: { "Remove": true, "Cancel": false},
  651. defaultButton: 1,
  652. submit: function(e,v,m,f){
  653. if(v)
  654. {
  655. setSharedKey('');
  656. lockRoom(false);
  657. }
  658. }
  659. });
  660. else
  661. $.prompt('<h2>Set a secrect key to lock your room</h2>' +
  662. '<input id="lockKey" type="text" placeholder="your shared key" autofocus>',
  663. {
  664. persistent: false,
  665. buttons: { "Save": true , "Cancel": false},
  666. defaultButton: 1,
  667. loaded: function(event) {
  668. document.getElementById('lockKey').focus();
  669. },
  670. submit: function(e,v,m,f){
  671. if(v)
  672. {
  673. var lockKey = document.getElementById('lockKey');
  674. if (lockKey.value)
  675. {
  676. setSharedKey(lockKey.value);
  677. lockRoom(true);
  678. }
  679. }
  680. }
  681. });
  682. }
  683. }
  684. /*
  685. * Opens the invite link dialog.
  686. */
  687. function openLinkDialog() {
  688. $.prompt('<input id="inviteLinkRef" type="text" value="' + roomUrl + '" onclick="this.select();">',
  689. {
  690. title: "Share this link with everyone you want to invite",
  691. persistent: false,
  692. buttons: { "Cancel": false},
  693. loaded: function(event) {
  694. document.getElementById('inviteLinkRef').select();
  695. }
  696. });
  697. }
  698. /*
  699. * Opens the settings dialog.
  700. */
  701. function openSettingsDialog() {
  702. $.prompt('<h2>Configure your conference</h2>' +
  703. '<input type="checkbox" id="initMuted"> Participants join muted<br/>' +
  704. '<input type="checkbox" id="requireNicknames"> Require nicknames<br/><br/>' +
  705. 'Set a secrect key to lock your room: <input id="lockKey" type="text" placeholder="your shared key" autofocus>',
  706. {
  707. persistent: false,
  708. buttons: { "Save": true , "Cancel": false},
  709. defaultButton: 1,
  710. loaded: function(event) {
  711. document.getElementById('lockKey').focus();
  712. },
  713. submit: function(e,v,m,f){
  714. if(v)
  715. {
  716. if ($('#initMuted').is(":checked"))
  717. {
  718. // it is checked
  719. }
  720. if ($('#requireNicknames').is(":checked"))
  721. {
  722. // it is checked
  723. }
  724. /*
  725. var lockKey = document.getElementById('lockKey');
  726. if (lockKey.value)
  727. {
  728. setSharedKey(lockKey.value);
  729. lockRoom(true);
  730. }
  731. */
  732. }
  733. }
  734. });
  735. }
  736. /*
  737. * Opens the Prezi dialog, from which the user could choose a presentation to load.
  738. */
  739. function openPreziDialog() {
  740. var myprezi = connection.emuc.getPrezi(connection.emuc.myroomjid);
  741. if (myprezi) {
  742. $.prompt("Are you sure you would like to remove your Prezi?",
  743. {
  744. title: "Remove Prezi",
  745. buttons: { "Remove": true, "Cancel": false},
  746. defaultButton: 1,
  747. submit: function(e,v,m,f){
  748. if(v)
  749. {
  750. connection.emuc.removePreziFromPresence();
  751. connection.emuc.sendPresence();
  752. }
  753. }
  754. });
  755. }
  756. else if (preziPlayer != null) {
  757. $.prompt("Another participant is already sharing a Prezi. This conference allows only one Prezi at a time.",
  758. {
  759. title: "Share a Prezi",
  760. buttons: { "Ok": true},
  761. defaultButton: 0,
  762. submit: function(e,v,m,f){
  763. $.prompt.close();
  764. }
  765. });
  766. }
  767. else {
  768. var openPreziState = {
  769. state0: {
  770. html: '<h2>Share a Prezi</h2>' +
  771. '<input id="preziUrl" type="text" placeholder="e.g. http://prezi.com/wz7vhjycl7e6/my-prezi" autofocus>',
  772. persistent: false,
  773. buttons: { "Share": true , "Cancel": false},
  774. defaultButton: 1,
  775. submit: function(e,v,m,f){
  776. e.preventDefault();
  777. if(v)
  778. {
  779. var preziUrl = document.getElementById('preziUrl');
  780. if (preziUrl.value)
  781. {
  782. if (preziUrl.value.indexOf('http://prezi.com/') != 0
  783. && preziUrl.value.indexOf('https://prezi.com/') != 0)
  784. {
  785. $.prompt.goToState('state1');
  786. return false;
  787. }
  788. else {
  789. var presIdTmp = preziUrl.value.substring(preziUrl.value.indexOf("prezi.com/") + 10);
  790. if (presIdTmp.indexOf('/') < 2) {
  791. $.prompt.goToState('state1');
  792. return false;
  793. }
  794. else {
  795. connection.emuc.addPreziToPresence(preziUrl.value, 0);
  796. connection.emuc.sendPresence();
  797. $.prompt.close();
  798. }
  799. }
  800. }
  801. }
  802. else
  803. $.prompt.close();
  804. }
  805. },
  806. state1: {
  807. html: '<h2>Share a Prezi</h2>' +
  808. 'Please provide a correct prezi link.',
  809. persistent: false,
  810. buttons: { "Back": true, "Cancel": false },
  811. defaultButton: 1,
  812. submit:function(e,v,m,f) {
  813. e.preventDefault();
  814. if(v==0)
  815. $.prompt.close();
  816. else
  817. $.prompt.goToState('state0');
  818. }
  819. }
  820. };
  821. var myPrompt = jQuery.prompt(openPreziState);
  822. myPrompt.on('impromptu:loaded', function(e) {
  823. document.getElementById('preziUrl').focus();
  824. });
  825. myPrompt.on('impromptu:statechanged', function(e) {
  826. document.getElementById('preziUrl').focus();
  827. });
  828. }
  829. }
  830. /*
  831. * Locks / unlocks the room.
  832. */
  833. function lockRoom(lock) {
  834. if (lock)
  835. connection.emuc.lockRoom(sharedKey);
  836. else
  837. connection.emuc.lockRoom('');
  838. updateLockButton();
  839. }
  840. /*
  841. * Sets the shared key.
  842. */
  843. function setSharedKey(sKey) {
  844. sharedKey = sKey;
  845. }
  846. /*
  847. * Updates the lock button state.
  848. */
  849. function updateLockButton() {
  850. buttonClick("#lockIcon", "fa fa-unlock fa-lg fa fa-lock fa-lg");
  851. }
  852. /*
  853. * Opens / closes the chat area.
  854. */
  855. function openChat() {
  856. var chatspace = $('#chatspace');
  857. var videospace = $('#videospace');
  858. var chatspaceWidth = chatspace.width();
  859. if (chatspace.css("opacity") == 1) {
  860. chatspace.animate({opacity: 0}, "fast");
  861. chatspace.animate({width: 0}, "slow");
  862. videospace.animate({right: 0, width:"100%"}, "slow");
  863. }
  864. else {
  865. chatspace.animate({width:"20%"}, "slow");
  866. chatspace.animate({opacity: 1}, "slow");
  867. videospace.animate({right:chatspaceWidth, width:"80%"}, "slow");
  868. }
  869. // Request the focus in the nickname field or the chat input field.
  870. if ($('#nickinput').is(':visible'))
  871. $('#nickinput').focus();
  872. else
  873. $('#usermsg').focus();
  874. }
  875. /*
  876. * Shows the call main toolbar.
  877. */
  878. function showToolbar() {
  879. $('#toolbar').css({visibility:"visible"});
  880. if (focus != null)
  881. {
  882. // TODO: Enable settings functionality. Need to uncomment the settings button in index.html.
  883. // $('#settingsButton').css({visibility:"visible"});
  884. }
  885. }
  886. /*
  887. * Updates the room invite url.
  888. */
  889. function updateRoomUrl(newRoomUrl) {
  890. roomUrl = newRoomUrl;
  891. }
  892. /*
  893. * Warning to the user that the conference window is about to be closed.
  894. */
  895. function closePageWarning() {
  896. if (focus != null)
  897. return "You are the owner of this conference call and you are about to end it.";
  898. else
  899. return "You are about to leave this conversation.";
  900. }
  901. /*
  902. * Shows a visual indicator for the focus of the conference.
  903. * Currently if we're not the owner of the conference we obtain the focus
  904. * from the connection.jingle.sessions.
  905. */
  906. function showFocusIndicator() {
  907. if (focus != null) {
  908. var localVideoToolbar = document.getElementById('localVideoToolbar');
  909. if (localVideoToolbar.childNodes.length === 0)
  910. {
  911. createFocusIndicatorElement(localVideoToolbar);
  912. }
  913. }
  914. else if (Object.keys(connection.jingle.sessions).length > 0) {
  915. // If we're only a participant the focus will be the only session we have.
  916. var session = connection.jingle.sessions[Object.keys(connection.jingle.sessions)[0]];
  917. var focusId = 'participant_' + Strophe.getResourceFromJid(session.peerjid);
  918. var focusContainer = document.getElementById(focusId);
  919. var indicatorSpan = $('#' + focusId + ' .focusindicator');
  920. if (!indicatorSpan || indicatorSpan.length == 0) {
  921. indicatorSpan = document.createElement('span');
  922. indicatorSpan.className = 'focusindicator';
  923. focusContainer.appendChild(indicatorSpan);
  924. createFocusIndicatorElement(indicatorSpan);
  925. }
  926. }
  927. }
  928. function addRemoteVideoContainer(id) {
  929. var container = document.createElement('span');
  930. container.id = id;
  931. container.className = 'videocontainer';
  932. var remotes = document.getElementById('remoteVideos');
  933. remotes.appendChild(container);
  934. return container;
  935. }
  936. /*
  937. * Creates the element indicating the focus of the conference.
  938. */
  939. function createFocusIndicatorElement(parentElement) {
  940. var focusIndicator = document.createElement('i');
  941. focusIndicator.className = 'fa fa-star';
  942. focusIndicator.title = "The owner of this conference"
  943. parentElement.appendChild(focusIndicator);
  944. }