Facebook Event Exporter

Export Facebook events

目前为 2016-01-30 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Facebook Event Exporter
  3. // @namespace http://boris.joff3.com
  4. // @version 1.2.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. /* eslint-disable no-console, no-unused-vars */
  12. 'use strict';
  13.  
  14. /*
  15. The MIT License (MIT)
  16.  
  17. Copyright (c) 2015 Boris Joffe
  18.  
  19. Permission is hereby granted, free of charge, to any person obtaining a copy
  20. of this software and associated documentation files (the "Software"), to deal
  21. in the Software without restriction, including without limitation the rights
  22. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  23. copies of the Software, and to permit persons to whom the Software is
  24. furnished to do so, subject to the following conditions:
  25.  
  26. The above copyright notice and this permission notice shall be included in
  27. all copies or substantial portions of the Software.
  28.  
  29. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  30. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  31. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  32. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  33. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  34. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  35. THE SOFTWARE.
  36. */
  37.  
  38.  
  39. // Util
  40. var
  41. qs = document.querySelector.bind(document),
  42. qsa = document.querySelectorAll.bind(document),
  43. err = console.error.bind(console),
  44. log = console.log.bind(console),
  45. euc = encodeURIComponent;
  46.  
  47. var DEBUG = false;
  48. function dbg() {
  49. if (DEBUG)
  50. console.log.apply(console, arguments);
  51.  
  52. return arguments[0];
  53. }
  54.  
  55. function qsv(elmStr, parent) {
  56. var elm = parent ? parent.querySelector(elmStr) : qs(elmStr);
  57. if (!elm) err('(qs) Could not get element -', elmStr);
  58. return elm;
  59. }
  60.  
  61. function qsav(elmStr, parent) {
  62. var elm = parent ? parent.querySelectorAll(elmStr) : qsa(elmStr);
  63. if (!elm) err('(qsa) Could not get element -', elmStr);
  64. return elm;
  65. }
  66.  
  67. function setProp(parent, path, val) {
  68. if (!parent || typeof parent !== 'object')
  69. return;
  70. path = Array.isArray(path) ? Array.from(path) : path.split('.');
  71. var child, prop;
  72. while (path.length > 1) {
  73. prop = path.shift();
  74. child = parent[prop];
  75. if (!child || typeof child !== 'object')
  76. parent[prop] = {};
  77. parent = parent[prop];
  78. }
  79. parent[path.shift()] = val;
  80. }
  81.  
  82. function getProp(obj, path, defaultValue) {
  83. path = Array.isArray(path) ? Array.from(path) : path.split('.');
  84. var prop = obj;
  85.  
  86. while (path.length && obj) {
  87. prop = obj[path.shift()];
  88. }
  89.  
  90. return prop != null ? prop : defaultValue;
  91. }
  92.  
  93. function addExportLink() {
  94. log('Event Exporter running');
  95.  
  96. // Event Summary
  97. var evElm = qsv('#event_summary');
  98.  
  99. // Date & Time
  100. // TODO: convert to local time instead of UTC
  101. function convertDateString(dateObj) {
  102. return dateObj.toISOString()
  103. .replace(/-/g, '')
  104. .replace(/:/g, '')
  105. .replace('.000Z', '');
  106. }
  107.  
  108. var sdElm = qsv('[itemprop="startDate"]', evElm);
  109. var sdd = new Date(sdElm.getAttribute('content')),
  110. edd = new Date(sdd);
  111. edd.setHours(edd.getHours() + 1); // Add one hour as a default
  112. var evStartDate = convertDateString(sdd);
  113. var evEndDate = convertDateString(edd);
  114.  
  115. // Location
  116. var locElm = qsv('[data-hovercard]', evElm) || {};
  117. var addrElm = getProp(locElm, 'nextSibling', {});
  118.  
  119. // Description
  120. var descElm = qs('#event_description').querySelector('span'),
  121. desc;
  122.  
  123. // use innerText for proper formatting, innerText will ship in Firefox 45
  124. if (!descElm) {
  125. desc = '[No description specified]';
  126. } else if (descElm.innerText) {
  127. // Show full event text so that innerText sees it
  128. setProp(qs('.text_exposed_show', descElm), 'style.display', 'inline');
  129. setProp(qs('.text_exposed_link', descElm), 'style.display', 'none');
  130. desc = descElm.innerText;
  131. } else {
  132. // fallback, HTML encoded entities will appear broken
  133. desc = descElm.innerHTML
  134. .replace(/<br>\s*/g, '\n') // fix newlines
  135. .replace(/&nbsp;/g, ' ')
  136. .replace(/&amp;/g, '&')
  137. .replace(/<a href="([^"]*)"[^>]*>/g, '[$1] ') // show link urls
  138. .replace(/<[^>]*>/g, ''); // strip html tags
  139. }
  140.  
  141. var ev = {
  142. title : document.title,
  143. startDate : evStartDate,
  144. endDate : evEndDate,
  145. location : locElm.textContent || '',
  146. address : addrElm.textContent || 'No address specified',
  147. description : location.href + '\n\n' + desc
  148. };
  149.  
  150. ev.locationAndAddress = ev.location ?
  151. ev.location + ', ' + ev.address :
  152. ev.address;
  153.  
  154. for (var prop in ev) if (ev.hasOwnProperty(prop))
  155. ev[prop] = euc(dbg(ev[prop], ' - ' + prop));
  156.  
  157. // Create link, use UTC timezone to be compatible with toISOString()
  158. var exportUrl = 'https://calendar.google.com/calendar/render?action=TEMPLATE&text=[TITLE]&dates=[STARTDATE]/[ENDDATE]&details=[DETAILS]&location=[LOCATION]&ctz=UTC';
  159.  
  160. exportUrl = exportUrl
  161. .replace('[TITLE]', ev.title)
  162. .replace('[STARTDATE]', ev.startDate)
  163. .replace('[ENDDATE]', ev.endDate)
  164. .replace('[LOCATION]', ev.locationAndAddress)
  165. .replace('[DETAILS]', ev.description);
  166.  
  167. dbg(exportUrl, ' - Export URL');
  168.  
  169. var
  170. evBarElm = qsv('#event_button_bar'),
  171. exportElmLink = qsv('a', evBarElm),
  172. exportElmParent = exportElmLink.parentNode;
  173.  
  174. exportElmLink = exportElmLink.cloneNode();
  175. exportElmLink.href = exportUrl;
  176. exportElmLink.textContent = 'Export Event';
  177.  
  178. // Disable Facebook event listeners (that are attached due to cloning element)
  179. exportElmLink.removeAttribute('ajaxify');
  180. exportElmLink.removeAttribute('rel');
  181.  
  182. // Open in new tab
  183. exportElmLink.target = '_blank';
  184.  
  185. exportElmParent.appendChild(exportElmLink);
  186.  
  187. var evBarLinks = qsav('a', evBarElm);
  188. Array.from(evBarLinks).forEach(function (a) {
  189. // fix styles
  190. a.style.display = 'inline-block';
  191. });
  192. }
  193.  
  194.  
  195. (function (oldPushState) {
  196. // monkey patch pushState so that script works when navigating around Facebook
  197. window.history.pushState = function () {
  198. dbg('running pushState');
  199. oldPushState.apply(window.history, arguments);
  200. setTimeout(addExportLinkWhenLoaded, 1000);
  201. };
  202. dbg('monkey patched pushState');
  203. })(window.history.pushState);
  204.  
  205. window.onpopstate = function () {
  206. dbg('pop state');
  207. setTimeout(addExportLinkWhenLoaded, 1000);
  208. };
  209.  
  210. function addExportLinkWhenLoaded() {
  211. if (location.href.indexOf('/events/') === -1) {
  212. dbg('not an event page. skipping...');
  213. return;
  214. } else if (!qs('#event_button_bar') || !qs('#event_description') || !qs('[itemprop="startDate"]')) {
  215. // not loaded
  216. dbg('page not loaded...');
  217. setTimeout(addExportLinkWhenLoaded, 1000);
  218. } else {
  219. // loaded
  220. dbg('page loaded...adding link');
  221. addExportLink();
  222. }
  223. }
  224.  
  225.  
  226. window.addEventListener('load', addExportLinkWhenLoaded, true);