Facebook Event Exporter

Export Facebook events

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