DB Trips iCal Saver

Adds "Add to Calendar" option for DB trips

  1. // ==UserScript==
  2. // @name DB Trips iCal Saver
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.2
  5. // @description Adds "Add to Calendar" option for DB trips
  6. // @author You
  7. // @match https://int.bahn.de/en/buchung/fahrplan/*
  8. // @icon https://www.google.com/s2/favicons?sz=64&domain=bahn.de
  9. // @grant none
  10. // @license MIT
  11. // ==/UserScript==
  12.  
  13. (function() {
  14. 'use strict';
  15. /**
  16.  
  17. Here I use a slightly modified icsFormatter by @matthiasanderer
  18.  
  19. Credits: matthiasanderer (https://github.com/matthiasanderer/icsFormatter)
  20.  
  21. **/
  22. window.icsFormatter = function() {
  23. 'use strict';
  24.  
  25. if (navigator.userAgent.indexOf('MSIE') > -1 && navigator.userAgent.indexOf('MSIE 10') == -1) {
  26. console.log('Unsupported Browser');
  27. return;
  28. }
  29.  
  30. var SEPARATOR = (navigator.appVersion.indexOf('Win') !== -1) ? '\r\n' : '\n';
  31. var calendarEvents = [];
  32. var calendarStart = [
  33. 'BEGIN:VCALENDAR',
  34. 'VERSION:2.0'
  35. ].join(SEPARATOR);
  36. var calendarEnd = SEPARATOR + 'END:VCALENDAR';
  37.  
  38. return {
  39. 'events': function() {
  40. return calendarEvents;
  41. },
  42.  
  43. 'calendar': function() {
  44. return calendarStart + SEPARATOR + calendarEvents.join(SEPARATOR) + calendarEnd;
  45. },
  46. 'addEvent': function(subject, description, location, begin, stop) {
  47. if (typeof subject === 'undefined' ||
  48. typeof description === 'undefined' ||
  49. typeof location === 'undefined' ||
  50. typeof begin === 'undefined' ||
  51. typeof stop === 'undefined'
  52. ) {
  53. return false;
  54. }
  55. var start_date = new Date(begin);
  56. var end_date = new Date(stop);
  57.  
  58. var start_year = ("0000" + (start_date.getFullYear().toString())).slice(-4);
  59. var start_month = ("00" + ((start_date.getMonth() + 1).toString())).slice(-2);
  60. var start_day = ("00" + ((start_date.getDate()).toString())).slice(-2);
  61. var start_hours = ("00" + (start_date.getHours().toString())).slice(-2);
  62. var start_minutes = ("00" + (start_date.getMinutes().toString())).slice(-2);
  63. var start_seconds = ("00" + (start_date.getMinutes().toString())).slice(-2);
  64.  
  65. var end_year = ("0000" + (end_date.getFullYear().toString())).slice(-4);
  66. var end_month = ("00" + ((end_date.getMonth() + 1).toString())).slice(-2);
  67. var end_day = ("00" + ((end_date.getDate()).toString())).slice(-2);
  68. var end_hours = ("00" + (end_date.getHours().toString())).slice(-2);
  69. var end_minutes = ("00" + (end_date.getMinutes().toString())).slice(-2);
  70. var end_seconds = ("00" + (end_date.getMinutes().toString())).slice(-2);
  71.  
  72. var start_time = '';
  73. var end_time = '';
  74. if (start_minutes + start_seconds + end_minutes + end_seconds !== 0) {
  75. start_time = 'T' + start_hours + start_minutes + start_seconds;
  76. end_time = 'T' + end_hours + end_minutes + end_seconds;
  77. }
  78.  
  79. var start = start_year + start_month + start_day + start_time;
  80. var end = end_year + end_month + end_day + end_time;
  81.  
  82. var calendarEvent = [
  83. 'BEGIN:VEVENT',
  84. 'CLASS:PUBLIC',
  85. 'DESCRIPTION:' + description,
  86. 'DTSTART:' + start,
  87. 'DTEND:' + end,
  88. 'LOCATION:' + location,
  89. 'SUMMARY;LANGUAGE=en-us:' + subject,
  90. 'TRANSP:TRANSPARENT',
  91. 'END:VEVENT'
  92. ].join(SEPARATOR);
  93.  
  94. calendarEvents.push(calendarEvent);
  95. return calendarEvent;
  96. },
  97.  
  98. 'download': function(filename) {
  99. if (calendarEvents.length < 1) {
  100. return false;
  101. }
  102. var calendar = calendarStart + SEPARATOR + calendarEvents.join(SEPARATOR) + calendarEnd;
  103. var a = document.createElement('a');
  104. a.href = "data:text/calendar;charset=utf8," + escape(calendar);
  105. a.download = filename + '.ics';
  106. document.getElementsByTagName('body')[0].appendChild(a);
  107. a.click();
  108. }
  109. };
  110. };
  111.  
  112. function parent (el, n) {
  113. while (n > 0) {
  114. el = el.parentNode;
  115. n --;
  116. }
  117. return el;
  118. }
  119.  
  120. function main () {
  121. var actionMenuUl = document.querySelectorAll(".ActionMenu div div ul");
  122. actionMenuUl.forEach((element, i) => {
  123. if (element.querySelectorAll("li").length > 2) return;
  124. var addCalendarOption = document.createElement("li");
  125. addCalendarOption.className = "_content-button _content-button--with-icons add_to_calendar";
  126. addCalendarOption.setAttribute("style", "align-items: center; column-gap: .5rem; cursor: pointer; display: flex; padding: .75rem 1.0rem;");
  127. var spanEl = document.createElement("span");
  128. spanEl.className = "db-color--dbRed db-web-icon--custom-size icon-action-share db-web-icon";
  129. var spanElWithDesc = document.createElement("span");
  130. spanElWithDesc.innerHTML = "Add to calendar";
  131. addCalendarOption.appendChild(spanEl);
  132. addCalendarOption.appendChild(spanElWithDesc);
  133. addCalendarOption.addEventListener("click", function (e) { saveTripToICS(e.target) });
  134. element.appendChild(addCalendarOption);
  135.  
  136. parent(element, 3).setAttribute("style", "--item-count: 3;");
  137.  
  138. var style = document.createElement("style");
  139. style.innerHTML = '.add_to_calendar:hover { background: #f0f3f5; }';
  140. document.head.appendChild(style);
  141. });
  142. };
  143.  
  144. setInterval(main, 1000);
  145.  
  146. function waitFor (selectorFunc, applyFunc) {
  147. var itl = setInterval(function () {
  148. if (selectorFunc()) {
  149. clearInterval(itl);
  150. applyFunc();
  151. }
  152. }, 50);
  153. }
  154.  
  155. function formatGermanString(german) {
  156. let mp = {"ü": "ue", "ö": "oe", "ä": "ae", "ß": "ss"};
  157. for (let repl in mp) {
  158. german = german.replace(new RegExp(repl, "g"), mp[repl]);
  159. }
  160. return german.toLowerCase().split(/\s+/g)[0];
  161. }
  162.  
  163.  
  164. function saveTripToICS (targetElement) {
  165. var trip = parent(targetElement, 7);
  166. trip.querySelector(".reiseplan__details").style.display = "none";
  167. trip.querySelector(".reiseplan__details button").click();
  168. waitFor(
  169. function () {
  170. return trip.querySelector(".reise-details__infos") !== null && trip.querySelector("ri-transport-chip").getAttribute("transport-text") !== null
  171. },
  172. function () {
  173. trip.querySelector(".reise-details__infos").style.display = "none";
  174. trip.querySelector(".reise-details__actions").style.display = "none";
  175. var tripParts = trip.querySelectorAll(".verbindungs-abschnitt");
  176. var parsedTripParts = parseTripParts(tripParts);
  177.  
  178.  
  179. window.calEntry = window.icsFormatter();
  180.  
  181. var lastTimestamp = null;
  182. var firstStation = null;
  183. var lastStation = null;
  184. var firstDate = null;
  185. parsedTripParts.forEach((part, i) => {
  186. var stringDate = document.querySelector(".default-reiseloesung-list-page-controls__title-date").innerText;
  187. var begin = new Date(stringDate + ", " + part.startTime);
  188. while (lastTimestamp !== null && lastTimestamp > begin) {
  189. begin.setDate(begin.getDate() + 1);
  190. }
  191. if (i === 0) {
  192. firstDate = Math.floor(begin.getTime() / 1000);
  193. }
  194. lastTimestamp = begin;
  195. var end = new Date(stringDate + ", " + part.endTime);
  196. while (lastTimestamp > end) {
  197. end.setDate(end.getDate() + 1);
  198. }
  199. lastTimestamp = end;
  200. var title = part.eventName;
  201. window.calEntry.addEvent(title, part.eventDescription, "", begin.toUTCString(), end.toUTCString());
  202. if (i === 0) {
  203. firstStation = formatGermanString(part.fromStation);
  204. }
  205. if (i === (parsedTripParts.length - 1)) {
  206. lastStation = formatGermanString(part.toStation);
  207. }
  208. });
  209.  
  210. window.calEntry.download(`db_trip_${firstStation}_${lastStation}_${firstDate}`);
  211. trip.querySelector(".reiseplan__details button").click();
  212. trip.querySelector(".reiseplan__details").style.display = "";
  213. trip.querySelector(".reise-details__infos").style.display = "";
  214. trip.querySelector(".reise-details__actions").style.display = "";
  215.  
  216. }
  217. );
  218. }
  219.  
  220. function parseTripParts(tripParts) {
  221.  
  222. var result = [];
  223.  
  224. tripParts.forEach((part, i) => {
  225. var trainName = part.querySelector("ri-transport-chip").getAttribute("transport-text");
  226. var timeEls = part.querySelectorAll("time");
  227. var startTime = timeEls[0].innerText;
  228. var endTime = timeEls[timeEls.length - 1].innerText;
  229. var stopsEls = part.querySelectorAll(".verbindungs-halt");
  230. var fromStation = stopsEls[0].querySelector(".verbindungs-halt-bahnhofsinfos__name--abfahrt").innerText;
  231. var fromTrack = stopsEls[0].querySelector(".verbindungs-abschnitt-zeile__gleis").innerText;
  232. var toStation = stopsEls[1].querySelector(".verbindungs-halt-bahnhofsinfos__name--ankunft").innerText;
  233. var toTrack = stopsEls[1].querySelector(".verbindungs-abschnitt-zeile__gleis").innerText;
  234. result.push({
  235. startTime: startTime,
  236. endTime: endTime,
  237. eventName: `(${trainName}) ${fromStation} - ${toStation}`,
  238. eventDescription: `${trainName} ${fromStation} (${fromTrack}) - ${toStation} (${toTrack})`,
  239. fromStation: fromStation,
  240. toStation: toStation
  241. });
  242. });
  243.  
  244. return result;
  245. }
  246.  
  247.  
  248. })();