Facebook Event Exporter

Export Facebook events

目前为 2018-06-23 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Facebook Event Exporter
  3. // @namespace http://boris.joff3.com
  4. // @version 1.3.9
  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.  
  100. // == Title ==
  101.  
  102. function getTitle() {
  103. // only include the first host for brevity
  104. return document.title + ' (' + getHostedByText()[0] + ')';
  105. }
  106.  
  107.  
  108. // == Dates ==
  109.  
  110. function convertDateString(dateObj) {
  111. return dateObj.toISOString()
  112. .replace(/-/g, '')
  113. .replace(/:/g, '')
  114. .replace('.000Z', '');
  115. }
  116.  
  117. function getDates() {
  118. return qsv('._publicProdFeedInfo__timeRowTitle')
  119. .getAttribute('content')
  120. .split(' to ')
  121. .map(date => new Date(date))
  122. .map(convertDateString);
  123. }
  124.  
  125. function getStartDate() { return getDates()[0]; }
  126. function getEndDate() { return getDates()[1]; }
  127.  
  128.  
  129. // == Location / Address ==
  130.  
  131. function getLocation() {
  132. var hovercard = qsv('[data-hovercard]', qs('#event_summary')),
  133. addr;
  134. if (hovercard)
  135. return hovercard.nextSibling.innerText || 'No Address Specified';
  136. else if (addr = qsv('#u_0_1h'))
  137. return addr.innerText;
  138. else
  139. // certain addresses like GPS coordinates
  140. // e.g. https://facebook.com/events/199708740636288/
  141. // HACK: don't have a unique way to get the text (matches time and address - address is second)
  142. return Array.from(qsav('._5xhk')).slice(-1)[0].innerText;
  143. return hovercard ? hovercard.innerText : '';
  144. }
  145.  
  146. function getAddress() {
  147. var hovercard = qsv('[data-hovercard]', qs('#event_summary'));
  148. if (hovercard)
  149. return hovercard.nextSibling.innerText || 'No Address Specified';
  150. else
  151. return qsv('#u_0_1h').innerText;
  152. }
  153.  
  154. function getLocationAndAddress() {
  155. return getLocation() ?
  156. (getLocation() + ', ' + getAddress())
  157. : getAddress();
  158. }
  159.  
  160.  
  161. // == Description ==
  162.  
  163. function getDescription() {
  164. var seeMore = qsv('.see_more_link');
  165. if (seeMore)
  166. seeMore.click(); // expand description
  167.  
  168. return location.href +
  169. '\n\n' +
  170. qsv('[data-testid="event-permalink-details"]').innerText;
  171. // Zip text array with links array?
  172. //'\n\nHosted By:\n' +
  173. //getHostedByText().join(', ') + '\n' + getHostedByLinks().join('\n') +
  174. }
  175.  
  176. function getHostedByText() {
  177. var el = qsv('._5gnb [content]');
  178. var text = el.getAttribute('content');
  179. if (text.lastIndexOf(' & ') !== -1)
  180. text = text.substr(0, text.lastIndexOf(' & ')); // chop off trailing ' & '
  181.  
  182. return text.split(' & ');
  183. }
  184.  
  185.  
  186. // ==== Make Export URL =====
  187. function makeExportUrl() {
  188. console.time('makeExportUrl');
  189. var ev = {
  190. title : getTitle(),
  191. startDate : getStartDate(),
  192. endDate : getEndDate() || getStartDate(), // set to startDate if undefined
  193. locAndAddr : getLocationAndAddress(),
  194. description : getDescription()
  195. };
  196.  
  197. var totalLength = 0;
  198. for (var prop in ev) if (ev.hasOwnProperty(prop)) {
  199. ev[prop] = euc(dbg(ev[prop], ' - ' + prop));
  200. totalLength += ev[prop].length;
  201. }
  202.  
  203. // max is about 8200 chars but allow some slack for the base URL
  204. const MAX_URL_LENGTH = 8000;
  205.  
  206. console.info('event props totalLength', totalLength);
  207. if (totalLength > MAX_URL_LENGTH) {
  208. var numCharsOverLimit = totalLength - MAX_URL_LENGTH;
  209. var maxEventDescriptionChars = ev.description.length - numCharsOverLimit;
  210.  
  211. // will only happen if event title or location is extremely long
  212. // FIXME: truncate event title / location if necessary
  213. if (maxEventDescriptionChars < 1) {
  214. console.warn('maxEventDescriptionChars is', maxEventDescriptionChars);
  215. }
  216.  
  217. console.warn('Event description truncated from', ev.description.length, 'characters to', maxEventDescriptionChars, 'characters');
  218.  
  219. ev.description = ev.description.substr(0, maxEventDescriptionChars) + '...';
  220. }
  221.  
  222.  
  223. // gcal format - http://stackoverflow.com/questions/10488831/link-to-add-to-google-calendar
  224.  
  225. // Create link, use UTC timezone to be compatible with toISOString()
  226. var exportUrl = 'https://calendar.google.com/calendar/render?action=TEMPLATE&text=[TITLE]&dates=[STARTDATE]/[ENDDATE]&details=[DETAILS]&location=[LOCATION]&ctz=UTC';
  227.  
  228. exportUrl = exportUrl
  229. .replace('[TITLE]', ev.title)
  230. .replace('[STARTDATE]', ev.startDate)
  231. .replace('[ENDDATE]', ev.endDate)
  232. .replace('[LOCATION]', ev.locAndAddr)
  233. .replace('[DETAILS]', ev.description);
  234.  
  235. console.info('exportUrl length =', exportUrl.length);
  236.  
  237. console.timeEnd('makeExportUrl');
  238. return dbg(exportUrl, ' - Export URL');
  239. }
  240.  
  241.  
  242. function addExportLink() {
  243. console.time('addExportLink');
  244. log('Event Exporter running');
  245.  
  246. var
  247. evBarElm = qsv('#event_button_bar'),
  248. exportElmLink = qsv('a', evBarElm),
  249. exportElmParent = exportElmLink.parentNode;
  250.  
  251. exportElmLink = exportElmLink.cloneNode();
  252. exportElmLink.href = makeExportUrl();
  253. exportElmLink.textContent = 'Export Event';
  254.  
  255. // Disable Facebook event listeners (that are attached due to cloning element)
  256. exportElmLink.removeAttribute('ajaxify');
  257. exportElmLink.removeAttribute('rel');
  258. exportElmLink.removeAttribute('data-onclick');
  259.  
  260. // Open in new tab
  261. exportElmLink.target = '_blank';
  262.  
  263. exportElmParent.appendChild(exportElmLink);
  264.  
  265. var evBarLinks = qsav('a', evBarElm);
  266. Array.from(evBarLinks).forEach(function (a) {
  267. // fix styles
  268. a.style.display = 'inline-block';
  269. });
  270. console.timeEnd('addExportLink');
  271. }
  272.  
  273.  
  274. (function (oldPushState) {
  275. // monkey patch pushState so that script works when navigating around Facebook
  276. window.history.pushState = function () {
  277. dbg('running pushState');
  278. oldPushState.apply(window.history, arguments);
  279. setTimeout(addExportLinkWhenLoaded, 1000);
  280. };
  281. dbg('monkey patched pushState');
  282. })(window.history.pushState);
  283.  
  284. // onpopstate is sometimes null causing the following error:
  285. // 'Cannot set property onpopstate of #<Object> which has only a getter'
  286. if (window.onpopstate) {
  287. window.onpopstate = function () {
  288. dbg('pop state event fired');
  289. setTimeout(addExportLinkWhenLoaded, 1000);
  290. };
  291. } else {
  292. dbg('Unable to set "onpopstate" event', window.onpopstate);
  293. }
  294.  
  295. function addExportLinkWhenLoaded() {
  296. if (location.href.indexOf('/events/') === -1) {
  297. dbg('not an event page. skipping...');
  298. return;
  299. } else if (!qs('#event_button_bar') || !qs('#event_summary')) {
  300. // not loaded
  301. dbg('page not loaded...');
  302. setTimeout(addExportLinkWhenLoaded, 1000);
  303. } else {
  304. // loaded
  305. dbg('page loaded...adding link');
  306. addExportLink();
  307. }
  308. }
  309.  
  310. var onLoad = addExportLinkWhenLoaded;
  311.  
  312. window.addEventListener('load', onLoad, true);