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.

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