YouTube Live Event to Calendar

YouTube Live Event to Calendar...but semi-automatic

  1. // ==UserScript==
  2. // @name YouTube Live Event to Calendar
  3. // @namespace https://defaultcf.github.io
  4. // @match https://www.youtube.com/watch*
  5. // @grant GM_registerMenuCommand
  6. // @grant GM_openInTab
  7. // @version 0.1.1
  8. // @author defaultcf
  9. // @description YouTube Live Event to Calendar...but semi-automatic
  10. // ==/UserScript==
  11.  
  12. 'use strict';
  13.  
  14. (() => {
  15. const _debug = (...obj) => console.log('[YT Live Event to Calendar]', ...obj);
  16.  
  17. class Utility {
  18. static get_body(url) {
  19. return new Promise(async resolve => {
  20. const res = await fetch(url, { cache: 'no-cache' });
  21. const raw_body = await res.text();
  22. const domparser = new DOMParser();
  23. const body = domparser.parseFromString(raw_body, 'text/html');
  24. resolve(body);
  25. });
  26. }
  27.  
  28. static async get_metas(body) {
  29. const metas = {};
  30. await body.querySelectorAll('meta').forEach(meta => {
  31. const key = meta.getAttribute('name') || meta.getAttribute('itemprop');
  32. metas[key] = meta.content;
  33. });
  34. return metas;
  35. }
  36.  
  37. static get_date_string(date) {
  38. return date.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
  39. }
  40.  
  41. static create_event(text, date, details, location) {
  42. date = new Date(date);
  43. const start_datetime = this.get_date_string(date);
  44. date.setHours(date.getHours() + 1);
  45. const end_datetime = this.get_date_string(date);
  46. const dates = `${start_datetime}/${end_datetime}`;
  47. const url = new URL('https://www.google.com/calendar/render');
  48. url.searchParams.append('action', 'TEMPLATE');
  49. url.searchParams.append('text', text);
  50. url.searchParams.append('dates', dates);
  51. url.searchParams.append('details', details);
  52. url.searchParams.append('location', location);
  53. GM_openInTab(url.href);
  54. }
  55. }
  56.  
  57. const menu_event = async () => {
  58. const body = await Utility.get_body(document.location);
  59. const metas = await Utility.get_metas(body);
  60. Utility.create_event(
  61. metas['title'],
  62. metas['startDate'],
  63. metas['description'],
  64. `https://www.youtube.com/watch?v=${metas['videoId']}`,
  65. );
  66. }
  67.  
  68. GM_registerMenuCommand('Add Google Calendar', menu_event);
  69. })();