__init__.py 6.8 KB

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