__init__.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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 typing
  25. import icalendar
  26. _LOGGER = logging.getLogger(__name__)
  27. _VDIR_EVENT_FILE_EXTENSION = ".ics"
  28. def _event_prop_equal(prop_a: typing.Any, prop_b: typing.Any) -> bool:
  29. if isinstance(prop_a, list):
  30. return len(prop_a) == len(prop_b) and all(
  31. _event_prop_equal(*pair) for pair in zip(prop_a, prop_b)
  32. )
  33. if isinstance(prop_a, icalendar.prop.vDDDLists):
  34. # https://www.kanzaki.com/docs/ical/exdate.html
  35. return (
  36. isinstance(prop_b, icalendar.prop.vDDDLists)
  37. and len(prop_a.dts) == len(prop_b.dts)
  38. and all(_event_prop_equal(*pair) for pair in zip(prop_a.dts, prop_b.dts))
  39. and prop_a.params == prop_b.params
  40. )
  41. if isinstance(prop_a, (icalendar.prop.vDDDTypes, icalendar.prop.vCategory)):
  42. # pylint: disable=unidiomatic-typecheck
  43. return type(prop_a) == type(prop_b) and vars(prop_a) == vars(prop_b)
  44. return typing.cast(bool, prop_a == prop_b and prop_a.params == prop_b.params)
  45. def _events_equal(event_a: icalendar.cal.Event, event_b: icalendar.cal.Event) -> bool:
  46. for key, prop_a in event_a.items():
  47. if key == "DTSTAMP":
  48. continue
  49. try:
  50. prop_b = event_b[key]
  51. except KeyError:
  52. _LOGGER.debug("%s: new key %s", event_a["UID"], key)
  53. return False
  54. if not _event_prop_equal(prop_a, prop_b):
  55. _LOGGER.debug(
  56. "%s/%s: %r != %r",
  57. event_a["UID"],
  58. key,
  59. prop_a,
  60. prop_b,
  61. )
  62. return False
  63. return True
  64. def _datetime_basic_isoformat(dt_obj: datetime.datetime) -> str:
  65. # .isoformat() inserts unwanted separators
  66. return dt_obj.strftime("%Y%m%dT%H%M%S%z")
  67. def _event_vdir_filename(event: icalendar.cal.Event) -> str:
  68. # > An item should contain a UID property as described by the vCard and iCalendar standards.
  69. # > [...] The filename should have similar properties as the UID of the file content.
  70. # > However, there is no requirement for these two to be the same.
  71. # > Programs may choose to store additional metadata in that filename, [...]
  72. # https://vdirsyncer.readthedocs.io/en/stable/vdir.html#basic-structure
  73. output_filename = str(event["UID"])
  74. if "RECURRENCE-ID" in event:
  75. recurrence_id = event["RECURRENCE-ID"]
  76. assert isinstance(recurrence_id.dt, datetime.datetime), recurrence_id.dt
  77. output_filename += "." + _datetime_basic_isoformat(recurrence_id.dt)
  78. return output_filename + _VDIR_EVENT_FILE_EXTENSION
  79. def _write_event(event: icalendar.cal.Event, path: pathlib.Path) -> None:
  80. # > Creating and modifying items or metadata files should happen atomically.
  81. # https://vdirsyncer.readthedocs.io/en/stable/vdir.html#writing-to-vdirs
  82. temp_fd, temp_path = tempfile.mkstemp(
  83. prefix="ical2vdir-", suffix=_VDIR_EVENT_FILE_EXTENSION
  84. )
  85. try:
  86. # > Content lines are delimited by a line break,
  87. # > which is a CRLF sequence [...]
  88. # https://tools.ietf.org/html/rfc5545#section-3.1
  89. os.write(temp_fd, event.to_ical())
  90. os.close(temp_fd)
  91. # python3.5 expects Union[bytes, str]
  92. os.rename(temp_path, str(path))
  93. finally:
  94. if os.path.exists(temp_path):
  95. os.unlink(temp_path)
  96. def _sync_event(
  97. event: icalendar.cal.Event, output_dir_path: pathlib.Path
  98. ) -> pathlib.Path:
  99. output_path = output_dir_path.joinpath(_event_vdir_filename(event))
  100. if not output_path.exists():
  101. _LOGGER.info("creating %s", output_path)
  102. _write_event(event, output_path)
  103. else:
  104. with output_path.open("rb") as current_file:
  105. current_event = icalendar.Event.from_ical(current_file.read())
  106. if _events_equal(event, current_event):
  107. _LOGGER.debug("%s is up to date", output_path)
  108. else:
  109. _LOGGER.info("updating %s", output_path)
  110. _write_event(event, output_path)
  111. return output_path
  112. def _main() -> None:
  113. # https://docs.python.org/3/library/logging.html#levels
  114. logging.basicConfig(
  115. format="%(message)s",
  116. # datefmt='%Y-%m-%dT%H:%M:%S%z',
  117. level=logging.INFO,
  118. )
  119. argparser = argparse.ArgumentParser(
  120. description="Convert iCalendar .ics file to vdir directory."
  121. " Reads from stdin."
  122. )
  123. argparser.add_argument(
  124. "-o",
  125. "--output",
  126. "--output-dir",
  127. default=os.getcwd(),
  128. type=pathlib.Path,
  129. metavar="path",
  130. dest="output_dir_path",
  131. help="Path to output directory (default: current workings dir)",
  132. )
  133. argparser.add_argument(
  134. "--delete",
  135. action="store_true",
  136. help="Delete events not in input from output directory.",
  137. )
  138. argparser.add_argument(
  139. "-s",
  140. "--silent",
  141. "-q",
  142. "--quiet",
  143. action="store_true",
  144. help="Reduce verbosity.",
  145. )
  146. argparser.add_argument(
  147. "-v",
  148. "--verbose",
  149. action="store_true",
  150. help="Increase verbosity",
  151. )
  152. args = argparser.parse_args()
  153. if args.verbose:
  154. logging.getLogger().setLevel(level=logging.DEBUG)
  155. elif args.silent:
  156. logging.getLogger().setLevel(level=logging.WARNING)
  157. calendar = icalendar.Calendar.from_ical(sys.stdin.read())
  158. _LOGGER.debug("%d subcomponents", len(calendar.subcomponents))
  159. extra_paths = set(
  160. path
  161. for path in args.output_dir_path.iterdir()
  162. if path.is_file() and path.name.endswith(_VDIR_EVENT_FILE_EXTENSION)
  163. )
  164. for component in calendar.subcomponents:
  165. if isinstance(component, icalendar.cal.Event):
  166. extra_paths.discard(
  167. _sync_event(event=component, output_dir_path=args.output_dir_path)
  168. )
  169. else:
  170. _LOGGER.debug("%s", component)
  171. _LOGGER.debug(
  172. "%d pre-existing items not in input: %s",
  173. len(extra_paths),
  174. ", ".join(p.name for p in extra_paths),
  175. )
  176. if args.delete:
  177. for path in extra_paths:
  178. _LOGGER.info("removing %s", path)
  179. path.unlink()