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

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