Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

app.js 44KB

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