__init__.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. # ical2vdir - convert .ics file to vdir directory
  2. #
  3. # Copyright (C) 2020 Fabian Peter Hammerle <fabian@hammerle.me>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. import argparse
  18. import datetime
  19. import logging
  20. import os
  21. import pathlib
  22. import sys
  23. import tempfile
  24. import icalendar
  25. _LOGGER = logging.getLogger(__name__)
  26. _VDIR_EVENT_FILE_EXTENSION = ".ics"
  27. def _event_prop_equal(prop_a, prop_b) -> bool:
  28. if isinstance(prop_a, list):
  29. return len(prop_a) == len(prop_b) and all(
  30. _event_prop_equal(*pair) for pair in zip(prop_a, prop_b)
  31. )
  32. if isinstance(prop_a, icalendar.prop.vDDDLists):
  33. # https://www.kanzaki.com/docs/ical/exdate.html
  34. return (
  35. isinstance(prop_b, icalendar.prop.vDDDLists)
  36. and len(prop_a.dts) == len(prop_b.dts)
  37. and all(_event_prop_equal(*pair) for pair in zip(prop_a.dts, prop_b.dts))
  38. and prop_a.params == prop_b.params
  39. )
  40. if isinstance(prop_a, (icalendar.prop.vDDDTypes, icalendar.prop.vCategory)):
  41. # pylint: disable=unidiomatic-typecheck
  42. return type(prop_a) == type(prop_b) and vars(prop_a) == vars(prop_b)
  43. return prop_a == prop_b and prop_a.params == prop_b.params
  44. def _events_equal(event_a: icalendar.cal.Event, event_b: icalendar.cal.Event) -> bool:
  45. for key, prop_a in event_a.items():
  46. if key == "DTSTAMP":
  47. continue
  48. try:
  49. prop_b = event_b[key]
  50. except KeyError:
  51. _LOGGER.debug("%s: new key %s", event_a["UID"], key)
  52. return False
  53. if not _event_prop_equal(prop_a, prop_b):
  54. _LOGGER.debug(
  55. "%s/%s: %r != %r", event_a["UID"], key, prop_a, prop_b,
  56. )
  57. return False
  58. return True
  59. def _datetime_basic_isoformat(dt_obj: datetime.datetime) -> str:
  60. # .isoformat() inserts unwanted separators
  61. return dt_obj.strftime("%Y%m%dT%H%M%S%z")
  62. def _event_vdir_filename(event: icalendar.cal.Event) -> str:
  63. # > An item should contain a UID property as described by the vCard and iCalendar standards.
  64. # > [...] The filename should have similar properties as the UID of the file content.
  65. # > However, there is no requirement for these two to be the same.
  66. # > Programs may choose to store additional metadata in that filename, [...]
  67. # https://vdirsyncer.readthedocs.io/en/stable/vdir.html#basic-structure
  68. output_filename = str(event["UID"])
  69. if "RECURRENCE-ID" in event:
  70. recurrence_id = event["RECURRENCE-ID"]
  71. assert isinstance(recurrence_id.dt, datetime.datetime), recurrence_id.dt
  72. output_filename += "." + _datetime_basic_isoformat(recurrence_id.dt)
  73. return output_filename + _VDIR_EVENT_FILE_EXTENSION
  74. def _write_event(event: icalendar.cal.Event, path: pathlib.Path):
  75. # > Creating and modifying items or metadata files should happen atomically.
  76. # https://vdirsyncer.readthedocs.io/en/stable/vdir.html#writing-to-vdirs
  77. temp_fd, temp_path = tempfile.mkstemp(
  78. prefix="ical2vdir-", suffix=_VDIR_EVENT_FILE_EXTENSION
  79. )
  80. try:
  81. # > Content lines are delimited by a line break,
  82. # > which is a CRLF sequence [...]
  83. # https://tools.ietf.org/html/rfc5545#section-3.1
  84. os.write(temp_fd, event.to_ical())
  85. os.close(temp_fd)
  86. os.rename(temp_path, path)
  87. finally:
  88. if os.path.exists(temp_path):
  89. os.unlink(temp_path)
  90. def _sync_event(
  91. event: icalendar.cal.Event, output_dir_path: pathlib.Path
  92. ) -> pathlib.Path:
  93. output_path = output_dir_path.joinpath(_event_vdir_filename(event))
  94. if not output_path.exists():
  95. _LOGGER.info("creating %s", output_path)
  96. _write_event(event, output_path)
  97. else:
  98. with open(output_path, "rb") as current_file:
  99. current_event = icalendar.Event.from_ical(current_file.read())
  100. if _events_equal(event, current_event):
  101. _LOGGER.debug("%s is up to date", output_path)
  102. else:
  103. _LOGGER.info("updating %s", output_path)
  104. _write_event(event, output_path)
  105. return output_path
  106. def _main():
  107. # https://docs.python.org/3/library/logging.html#levels
  108. logging.basicConfig(
  109. format="%(message)s",
  110. # datefmt='%Y-%m-%dT%H:%M:%S%z',
  111. level=logging.INFO,
  112. )
  113. argparser = argparse.ArgumentParser(
  114. description="Convert iCalendar .ics file to vdir directory."
  115. " Reads from stdin."
  116. )
  117. argparser.add_argument(
  118. "-o",
  119. "--output",
  120. "--output-dir",
  121. default=os.getcwd(),
  122. type=pathlib.Path,
  123. metavar="path",
  124. dest="output_dir_path",
  125. help="Path to output directory (default: current workings dir)",
  126. )
  127. argparser.add_argument(
  128. "--delete",
  129. action="store_true",
  130. help="Delete events not in input from output directory.",
  131. )
  132. argparser.add_argument(
  133. "-s",
  134. "--silent",
  135. "-q",
  136. "--quiet",
  137. action="store_true",
  138. help="Reduce verbosity.",
  139. )
  140. argparser.add_argument(
  141. "-v", "--verbose", action="store_true", help="Increase verbosity",
  142. )
  143. args = argparser.parse_args()
  144. if args.verbose:
  145. logging.getLogger().setLevel(level=logging.DEBUG)
  146. elif args.silent:
  147. logging.getLogger().setLevel(level=logging.WARNING)
  148. calendar = icalendar.Calendar.from_ical(sys.stdin.read())
  149. _LOGGER.debug("%d subcomponents", len(calendar.subcomponents))
  150. extra_paths = set(
  151. path
  152. for path in args.output_dir_path.iterdir()
  153. if path.is_file() and path.name.endswith(_VDIR_EVENT_FILE_EXTENSION)
  154. )
  155. for component in calendar.subcomponents:
  156. if isinstance(component, icalendar.cal.Event):
  157. extra_paths.discard(
  158. _sync_event(event=component, output_dir_path=args.output_dir_path)
  159. )
  160. else:
  161. _LOGGER.debug("%s", component)
  162. _LOGGER.debug(
  163. "%d pre-existing items not in input: %s",
  164. len(extra_paths),
  165. ", ".join(p.name for p in extra_paths),
  166. )
  167. if args.delete:
  168. for path in extra_paths:
  169. _LOGGER.info("removing %s", path)
  170. path.unlink()