__init__.py 6.0 KB

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