__init__.py 6.5 KB

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