Facebook Event Exporter

Export Facebook events

目前为 2017-05-11 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Facebook Event Exporter
  3. // @namespace http://boris.joff3.com
  4. // @version 1.3.4
  5. // @description Export Facebook events
  6. // @author Boris Joffe
  7. // @match https://www.facebook.com/*
  8. // @grant unsafeWindow
  9. // ==/UserScript==
  10. /* jshint -W097 */
  11. /* globals console*/
  12. /* eslint-disable no-console, no-unused-vars */
  13. 'use strict';
  14.  
  15. /*
  16. The MIT License (MIT)
  17.  
  18. Copyright (c) 2015, 2017 Boris Joffe
  19.  
  20. Permission is hereby granted, free of charge, to any person obtaining a copy
  21. of this software and associated documentation files (the "Software"), to deal
  22. in the Software without restriction, including without limitation the rights
  23. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  24. copies of the Software, and to permit persons to whom the Software is
  25. furnished to do so, subject to the following conditions:
  26.  
  27. The above copyright notice and this permission notice shall be included in
  28. all copies or substantial portions of the Software.
  29.  
  30. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  31. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  32. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  33. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  34. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  35. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  36. THE SOFTWARE.
  37. */
  38.  
  39.  
  40. // Util
  41. var
  42. qs = document.querySelector.bind(document),
  43. qsa = document.querySelectorAll.bind(document),
  44. err = console.error.bind(console),
  45. log = console.log.bind(console),
  46. euc = encodeURIComponent;
  47.  
  48. var DEBUG = false;
  49. function dbg() {
  50. if (DEBUG)
  51. console.log.apply(console, arguments);
  52.  
  53. return arguments[0];
  54. }
  55.  
  56. function qsv(elmStr, parent) {
  57. var elm = parent ? parent.querySelector(elmStr) : qs(elmStr);
  58. if (!elm) err('(qs) Could not get element -', elmStr);
  59. return elm;
  60. }
  61.  
  62. function qsav(elmStr, parent) {
  63. var elm = parent ? parent.querySelectorAll(elmStr) : qsa(elmStr);
  64. if (!elm) err('(qsa) Could not get element -', elmStr);
  65. return elm;
  66. }
  67.  
  68. /*
  69. function setProp(parent, path, val) {
  70. if (!parent || typeof parent !== 'object')
  71. return;
  72. path = Array.isArray(path) ? Array.from(path) : path.split('.');
  73. var child, prop;
  74. while (path.length > 1) {
  75. prop = path.shift();
  76. child = parent[prop];
  77. if (!child || typeof child !== 'object')
  78. parent[prop] = {};
  79. parent = parent[prop];
  80. }
  81. parent[path.shift()] = val;
  82. }
  83.  
  84. function getProp(obj, path, defaultValue) {
  85. path = Array.isArray(path) ? Array.from(path) : path.split('.');
  86. var prop = obj;
  87.  
  88. while (path.length && obj) {
  89. prop = obj[path.shift()];
  90. }
  91.  
  92. return prop != null ? prop : defaultValue;
  93. }
  94.  
  95. */
  96.  
  97. // ==== Scrape =====
  98.  
  99. // == Title ==
  100. function getTitle() {
  101. // only include the first host for brevity
  102. return document.title + ' (' + getHostedByText()[0] + ')';
  103. }
  104.  
  105. // == Dates ==
  106.  
  107. function convertDateString(dateObj) {
  108. return dateObj.toISOString()
  109. .replace(/-/g, '')
  110. .replace(/:/g, '')
  111. .replace('.000Z', '');
  112. }
  113.  
  114. /*
  115. // Old way to get Date & Time
  116. // TODO: convert to local time instead of UTC
  117.  
  118. var sdElm = qsv('[itemprop="startDate"]', evElm);
  119. var sdd = new Date(sdElm.getAttribute('content')),
  120. edd = new Date(sdd);
  121. edd.setHours(edd.getHours() + 1); // Add one hour as a default
  122. var evStartDate = convertDateString(sdd);
  123. var evEndDate = convertDateString(edd);
  124. */
  125.  
  126. function getDates() {
  127. return qsv('._publicProdFeedInfo__timeRowTitle')
  128. .getAttribute('content')
  129. .split(' to ')
  130. .map(date => new Date(date))
  131. .map(convertDateString);
  132. }
  133.  
  134. function getStartDate() { return getDates()[0]; }
  135. function getEndDate() { return getDates()[1]; }
  136.  
  137.  
  138. // == Location / Address ==
  139.  
  140. // old way
  141. /*
  142. // Event Summary
  143. var evElm = qsv('#event_summary');
  144.  
  145. // Location
  146. var locElm = qsv('[data-hovercard]', evElm) || {};
  147. var addrElm = getProp(locElm, 'nextSibling', {});
  148. */
  149.  
  150.  
  151. function getLocation() {
  152. return qsv('[data-hovercard]', qs('#event_summary')).innerText;
  153. }
  154.  
  155. function getAddress() {
  156. return qsv('[data-hovercard]', qs('#event_summary')).nextSibling.innerText || 'No Address Specified';
  157. }
  158.  
  159. function getLocationAndAddress() {
  160. return getLocation() ?
  161. (getLocation() + ', ' + getAddress())
  162. : getAddress();
  163. }
  164.  
  165. // == Description ==
  166.  
  167. // old way
  168. /*
  169. // Description
  170. var descElm = qs('#event_description').querySelector('span'),
  171. desc;
  172.  
  173. // use innerText for proper formatting, innerText will ship in Firefox 45
  174. if (!descElm) {
  175. desc = '[No description specified]';
  176. } else if (descElm.innerText) {
  177. // Show full event text so that innerText sees it
  178. setProp(qs('.text_exposed_show', descElm), 'style.display', 'inline');
  179. setProp(qs('.text_exposed_link', descElm), 'style.display', 'none');
  180. desc = descElm.innerText;
  181. } else {
  182. // fallback, HTML encoded entities will appear broken
  183. desc = descElm.innerHTML
  184. */
  185. //.replace(/<br>\s*/g, '\n') // fix newlines
  186. /*
  187. .replace(/&nbsp;/g, ' ')
  188. .replace(/&amp;/g, '&')
  189. .replace(/<a href="([^"]*)"[^>]*>/g, '[$1] ') // show link urls
  190. .replace(/<[^>]*>/g, ''); // strip html tags
  191. }
  192. */
  193.  
  194. function getDescription() {
  195. var seeMore = qsv('.see_more_link');
  196. if (seeMore)
  197. seeMore.click(); // expand description
  198.  
  199. return location.href +
  200. '\n\n' +
  201. qsv('[data-testid="event-permalink-details"]').innerText;
  202. // Zip text array with links array?
  203. //'\n\nHosted By:\n' +
  204. //getHostedByText().join(', ') + '\n' + getHostedByLinks().join('\n') +
  205. }
  206.  
  207. function getHostedByText() {
  208. var el = qsv('._5gnb [content]');
  209. var text = el.getAttribute('content');
  210. if (text.lastIndexOf(' & ') !== -1)
  211. text = text.substr(0, text.lastIndexOf(' & ')); // chop off trailing ' & '
  212.  
  213. return text.split(' & ');
  214. }
  215.  
  216. /*
  217. function getHostedByLinks() {
  218. var el = qsv('._5gnb > div');
  219. return Array.from(qsav('a', el))
  220. .map(a => a.href);
  221. }
  222. */
  223.  
  224.  
  225. // ==== Make Export URL =====
  226. function makeExportUrl() {
  227. var ev = {
  228. title : getTitle(),
  229. startDate : getStartDate(),
  230. endDate : getEndDate(),
  231. locAndAddr : getLocationAndAddress(),
  232. description : getDescription()
  233. };
  234.  
  235. var totalLength = 0;
  236. for (var prop in ev) if (ev.hasOwnProperty(prop)) {
  237. ev[prop] = euc(dbg(ev[prop], ' - ' + prop));
  238. totalLength += ev[prop].length;
  239. }
  240.  
  241. // max is about 8200 chars but allow some slack for the base URL
  242. const MAX_URL_LENGTH = 8000;
  243.  
  244. console.info('event props totalLength', totalLength);
  245. if (totalLength > MAX_URL_LENGTH) {
  246. var numCharsOverLimit = totalLength - MAX_URL_LENGTH;
  247. var maxEventDescriptionChars = ev.description.length - numCharsOverLimit;
  248.  
  249. // will only happen if event title or location is extremely long
  250. // FIXME: truncate event title / location if necessary
  251. if (maxEventDescriptionChars < 1) {
  252. console.warn('maxEventDescriptionChars is', maxEventDescriptionChars);
  253. }
  254.  
  255. console.warn('Event description truncated from', ev.description.length, 'characters to', maxEventDescriptionChars, 'characters');
  256.  
  257. ev.description = ev.description.substr(0, maxEventDescriptionChars) + '...';
  258. }
  259.  
  260.  
  261. // gcal format - http://stackoverflow.com/questions/10488831/link-to-add-to-google-calendar
  262.  
  263. // Create link, use UTC timezone to be compatible with toISOString()
  264. var exportUrl = 'https://calendar.google.com/calendar/render?action=TEMPLATE&text=[TITLE]&dates=[STARTDATE]/[ENDDATE]&details=[DETAILS]&location=[LOCATION]&ctz=UTC';
  265.  
  266. exportUrl = exportUrl
  267. .replace('[TITLE]', ev.title)
  268. .replace('[STARTDATE]', ev.startDate)
  269. .replace('[ENDDATE]', ev.endDate)
  270. .replace('[LOCATION]', ev.locAndAddr)
  271. .replace('[DETAILS]', ev.description);
  272.  
  273. console.info('exportUrl length =', exportUrl.length);
  274.  
  275. return dbg(exportUrl, ' - Export URL');
  276. }
  277.  
  278.  
  279. function addExportLink() {
  280. log('Event Exporter running');
  281.  
  282. var
  283. evBarElm = qsv('#event_button_bar'),
  284. exportElmLink = qsv('a', evBarElm),
  285. exportElmParent = exportElmLink.parentNode;
  286.  
  287. exportElmLink = exportElmLink.cloneNode();
  288. exportElmLink.href = makeExportUrl();
  289. exportElmLink.textContent = 'Export Event';
  290.  
  291. // Disable Facebook event listeners (that are attached due to cloning element)
  292. exportElmLink.removeAttribute('ajaxify');
  293. exportElmLink.removeAttribute('rel');
  294.  
  295. // Open in new tab
  296. exportElmLink.target = '_blank';
  297.  
  298. exportElmParent.appendChild(exportElmLink);
  299.  
  300. var evBarLinks = qsav('a', evBarElm);
  301. Array.from(evBarLinks).forEach(function (a) {
  302. // fix styles
  303. a.style.display = 'inline-block';
  304. });
  305. }
  306.  
  307.  
  308. (function (oldPushState) {
  309. // monkey patch pushState so that script works when navigating around Facebook
  310. window.history.pushState = function () {
  311. dbg('running pushState');
  312. oldPushState.apply(window.history, arguments);
  313. setTimeout(addExportLinkWhenLoaded, 1000);
  314. };
  315. dbg('monkey patched pushState');
  316. })(window.history.pushState);
  317.  
  318. // onpopstate is sometimes null causing the following error:
  319. // 'Cannot set property onpopstate of #<Object> which has only a getter'
  320. if (window.onpopstate) {
  321. window.onpopstate = function () {
  322. dbg('pop state event fired');
  323. setTimeout(addExportLinkWhenLoaded, 1000);
  324. };
  325. } else {
  326. dbg('Unable to set "onpopstate" event', window.onpopstate);
  327. }
  328.  
  329. function addExportLinkWhenLoaded() {
  330. if (location.href.indexOf('/events/') === -1) {
  331. dbg('not an event page. skipping...');
  332. return;
  333. } else if (!qs('#event_button_bar') || !qs('#event_summary')) {
  334. // not loaded
  335. dbg('page not loaded...');
  336. setTimeout(addExportLinkWhenLoaded, 1000);
  337. } else {
  338. // loaded
  339. dbg('page loaded...adding link');
  340. addExportLink();
  341. }
  342. }
  343.  
  344. var onLoad = addExportLinkWhenLoaded;
  345.  
  346. window.addEventListener('load', onLoad, true);