filter.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2015 Guillaume Ayoub
  5. # Copyright © 2017-2021 Unrud <unrud@outlook.com>
  6. # Copyright © 2023-2024 Ray <ray@react0r.com>
  7. # Copyright © 2024-2025 Peter Bieringer <pb@bieringer.de>
  8. #
  9. # This library is free software: you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation, either version 3 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This library is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  21. import math
  22. import xml.etree.ElementTree as ET
  23. from datetime import date, datetime, timedelta, timezone
  24. from itertools import chain
  25. from typing import (Callable, Iterable, Iterator, List, Optional, Sequence,
  26. Tuple)
  27. import vobject
  28. from radicale import item, xmlutils
  29. from radicale.log import logger
  30. DAY: timedelta = timedelta(days=1)
  31. SECOND: timedelta = timedelta(seconds=1)
  32. DATETIME_MIN: datetime = datetime.min.replace(tzinfo=timezone.utc)
  33. DATETIME_MAX: datetime = datetime.max.replace(tzinfo=timezone.utc)
  34. TIMESTAMP_MIN: int = math.floor(DATETIME_MIN.timestamp())
  35. TIMESTAMP_MAX: int = math.ceil(DATETIME_MAX.timestamp())
  36. def date_to_datetime(d: date) -> datetime:
  37. """Transform any date to a UTC datetime.
  38. If ``d`` is a datetime without timezone, return as UTC datetime. If ``d``
  39. is already a datetime with timezone, return as is.
  40. """
  41. if not isinstance(d, datetime):
  42. d = datetime.combine(d, datetime.min.time())
  43. if not d.tzinfo:
  44. # NOTE: using vobject's UTC as it wasn't playing well with datetime's.
  45. d = d.replace(tzinfo=vobject.icalendar.utc)
  46. return d
  47. def parse_time_range(time_filter: ET.Element) -> Tuple[datetime, datetime]:
  48. start_text = time_filter.get("start")
  49. end_text = time_filter.get("end")
  50. if start_text:
  51. start = datetime.strptime(
  52. start_text, "%Y%m%dT%H%M%SZ").replace(
  53. tzinfo=timezone.utc)
  54. else:
  55. start = DATETIME_MIN
  56. if end_text:
  57. end = datetime.strptime(
  58. end_text, "%Y%m%dT%H%M%SZ").replace(
  59. tzinfo=timezone.utc)
  60. else:
  61. end = DATETIME_MAX
  62. return start, end
  63. def time_range_timestamps(time_filter: ET.Element) -> Tuple[int, int]:
  64. start, end = parse_time_range(time_filter)
  65. return (math.floor(start.timestamp()), math.ceil(end.timestamp()))
  66. def comp_match(item: "item.Item", filter_: ET.Element, level: int = 0) -> bool:
  67. """Check whether the ``item`` matches the comp ``filter_``.
  68. If ``level`` is ``0``, the filter is applied on the
  69. item's collection. Otherwise, it's applied on the item.
  70. See rfc4791-9.7.1.
  71. """
  72. # TODO: Filtering VALARM and VFREEBUSY is not implemented
  73. # HACK: the filters are tested separately against all components
  74. if level == 0:
  75. tag = item.name
  76. elif level == 1:
  77. tag = item.component_name
  78. else:
  79. logger.warning(
  80. "Filters with three levels of comp-filter are not supported")
  81. return True
  82. if not tag:
  83. return False
  84. name = filter_.get("name", "").upper()
  85. if len(filter_) == 0:
  86. # Point #1 of rfc4791-9.7.1
  87. return name == tag
  88. if len(filter_) == 1:
  89. if filter_[0].tag == xmlutils.make_clark("C:is-not-defined"):
  90. # Point #2 of rfc4791-9.7.1
  91. return name != tag
  92. if name != tag:
  93. return False
  94. if (level == 0 and name != "VCALENDAR" or
  95. level == 1 and name not in ("VTODO", "VEVENT", "VJOURNAL")):
  96. logger.warning("Filtering %s is not supported", name)
  97. return True
  98. # Point #3 and #4 of rfc4791-9.7.1
  99. components = ([item.vobject_item] if level == 0
  100. else list(getattr(item.vobject_item,
  101. "%s_list" % tag.lower())))
  102. for child in filter_:
  103. if child.tag == xmlutils.make_clark("C:prop-filter"):
  104. if not any(prop_match(comp, child, "C")
  105. for comp in components):
  106. return False
  107. elif child.tag == xmlutils.make_clark("C:time-range"):
  108. if not time_range_match(item.vobject_item, filter_[0], tag):
  109. return False
  110. elif child.tag == xmlutils.make_clark("C:comp-filter"):
  111. if not comp_match(item, child, level=level + 1):
  112. return False
  113. else:
  114. raise ValueError("Unexpected %r in comp-filter" % child.tag)
  115. return True
  116. def prop_match(vobject_item: vobject.base.Component,
  117. filter_: ET.Element, ns: str) -> bool:
  118. """Check whether the ``item`` matches the prop ``filter_``.
  119. See rfc4791-9.7.2 and rfc6352-10.5.1.
  120. """
  121. name = filter_.get("name", "").lower()
  122. if len(filter_) == 0:
  123. # Point #1 of rfc4791-9.7.2
  124. return name in vobject_item.contents
  125. if len(filter_) == 1:
  126. if filter_[0].tag == xmlutils.make_clark("%s:is-not-defined" % ns):
  127. # Point #2 of rfc4791-9.7.2
  128. return name not in vobject_item.contents
  129. if name not in vobject_item.contents:
  130. return False
  131. # Point #3 and #4 of rfc4791-9.7.2
  132. for child in filter_:
  133. if ns == "C" and child.tag == xmlutils.make_clark("C:time-range"):
  134. if not time_range_match(vobject_item, child, name):
  135. return False
  136. elif child.tag == xmlutils.make_clark("%s:text-match" % ns):
  137. if not text_match(vobject_item, child, name, ns):
  138. return False
  139. elif child.tag == xmlutils.make_clark("%s:param-filter" % ns):
  140. if not param_filter_match(vobject_item, child, name, ns):
  141. return False
  142. else:
  143. raise ValueError("Unexpected %r in prop-filter" % child.tag)
  144. return True
  145. def time_range_match(vobject_item: vobject.base.Component,
  146. filter_: ET.Element, child_name: str) -> bool:
  147. """Check whether the component/property ``child_name`` of
  148. ``vobject_item`` matches the time-range ``filter_``."""
  149. if not filter_.get("start") and not filter_.get("end"):
  150. return False
  151. start, end = parse_time_range(filter_)
  152. matched = False
  153. def range_fn(range_start: datetime, range_end: datetime,
  154. is_recurrence: bool) -> bool:
  155. nonlocal matched
  156. if start < range_end and range_start < end:
  157. matched = True
  158. return True
  159. if end < range_start and not is_recurrence:
  160. return True
  161. return False
  162. def infinity_fn(start: datetime) -> bool:
  163. return False
  164. visit_time_ranges(vobject_item, child_name, range_fn, infinity_fn)
  165. return matched
  166. def time_range_fill(vobject_item: vobject.base.Component,
  167. filter_: ET.Element, child_name: str, n: int = 1
  168. ) -> List[Tuple[datetime, datetime]]:
  169. """Create a list of ``n`` occurances from the component/property ``child_name``
  170. of ``vobject_item``."""
  171. if not filter_.get("start") and not filter_.get("end"):
  172. return []
  173. start, end = parse_time_range(filter_)
  174. ranges: List[Tuple[datetime, datetime]] = []
  175. def range_fn(range_start: datetime, range_end: datetime,
  176. is_recurrence: bool) -> bool:
  177. nonlocal ranges
  178. if start < range_end and range_start < end:
  179. ranges.append((range_start, range_end))
  180. if n > 0 and len(ranges) >= n:
  181. return True
  182. if end < range_start and not is_recurrence:
  183. return True
  184. return False
  185. def infinity_fn(range_start: datetime) -> bool:
  186. return False
  187. visit_time_ranges(vobject_item, child_name, range_fn, infinity_fn)
  188. return ranges
  189. def visit_time_ranges(vobject_item: vobject.base.Component, child_name: str,
  190. range_fn: Callable[[datetime, datetime, bool], bool],
  191. infinity_fn: Callable[[datetime], bool]) -> None:
  192. """Visit all time ranges in the component/property ``child_name`` of
  193. `vobject_item`` with visitors ``range_fn`` and ``infinity_fn``.
  194. ``range_fn`` gets called for every time_range with ``start`` and ``end``
  195. datetimes and ``is_recurrence`` as arguments. If the function returns True,
  196. the operation is cancelled.
  197. ``infinity_fn`` gets called when an infinite recurrence rule is detected
  198. with ``start`` datetime as argument. If the function returns True, the
  199. operation is cancelled.
  200. See rfc4791-9.9.
  201. """
  202. # HACK: According to rfc5545-3.8.4.4 a recurrence that is rescheduled
  203. # with Recurrence ID affects the recurrence itself and all following
  204. # recurrences too. This is not respected and client don't seem to bother
  205. # either.
  206. def getrruleset(child: vobject.base.Component, ignore: Sequence[date]
  207. ) -> Tuple[Iterable[date], bool]:
  208. infinite = False
  209. for rrule in child.contents.get("rrule", []):
  210. if (";UNTIL=" not in rrule.value.upper() and
  211. ";COUNT=" not in rrule.value.upper()):
  212. infinite = True
  213. break
  214. if infinite:
  215. for dtstart in child.getrruleset(addRDate=True):
  216. if dtstart in ignore:
  217. continue
  218. if infinity_fn(date_to_datetime(dtstart)):
  219. return (), True
  220. break
  221. return filter(lambda dtstart: dtstart not in ignore,
  222. child.getrruleset(addRDate=True)), False
  223. def get_children(components: Iterable[vobject.base.Component]) -> Iterator[
  224. Tuple[vobject.base.Component, bool, List[date]]]:
  225. main = None
  226. rec_main = None
  227. recurrences = []
  228. for comp in components:
  229. if hasattr(comp, "recurrence_id") and comp.recurrence_id.value:
  230. recurrences.append(comp.recurrence_id.value)
  231. if comp.rruleset:
  232. if comp.rruleset._len is None:
  233. logger.warning("Ignore empty RRULESET in item at RECURRENCE-ID with value '%s' and UID '%s'", comp.recurrence_id.value, comp.uid.value)
  234. else:
  235. # Prevent possible infinite loop
  236. raise ValueError("Overwritten recurrence with RRULESET")
  237. rec_main = comp
  238. yield comp, True, []
  239. else:
  240. if main is not None:
  241. raise ValueError("Multiple main components. Got comp: {}".format(comp))
  242. main = comp
  243. if main is None and len(recurrences) == 1:
  244. main = rec_main
  245. if main is None:
  246. raise ValueError("Main component missing")
  247. yield main, False, recurrences
  248. # Comments give the lines in the tables of the specification
  249. if child_name == "VEVENT":
  250. for child, is_recurrence, recurrences in get_children(
  251. vobject_item.vevent_list):
  252. # TODO: check if there's a timezone
  253. dtstart = child.dtstart.value
  254. if child.rruleset:
  255. dtstarts, infinity = getrruleset(child, recurrences)
  256. if infinity:
  257. return
  258. else:
  259. dtstarts = (dtstart,)
  260. dtend = getattr(child, "dtend", None)
  261. if dtend is not None:
  262. dtend = dtend.value
  263. original_duration = (dtend - dtstart).total_seconds()
  264. dtend = date_to_datetime(dtend)
  265. duration = getattr(child, "duration", None)
  266. if duration is not None:
  267. original_duration = duration = duration.value
  268. for dtstart in dtstarts:
  269. dtstart_is_datetime = isinstance(dtstart, datetime)
  270. dtstart = date_to_datetime(dtstart)
  271. if dtend is not None:
  272. # Line 1
  273. dtend = dtstart + timedelta(seconds=original_duration)
  274. if range_fn(dtstart, dtend, is_recurrence):
  275. return
  276. elif duration is not None:
  277. if original_duration is None:
  278. original_duration = duration.seconds
  279. if duration.seconds > 0:
  280. # Line 2
  281. if range_fn(dtstart, dtstart + duration,
  282. is_recurrence):
  283. return
  284. else:
  285. # Line 3
  286. if range_fn(dtstart, dtstart + SECOND, is_recurrence):
  287. return
  288. elif dtstart_is_datetime:
  289. # Line 4
  290. if range_fn(dtstart, dtstart + SECOND, is_recurrence):
  291. return
  292. else:
  293. # Line 5
  294. if range_fn(dtstart, dtstart + DAY, is_recurrence):
  295. return
  296. elif child_name == "VTODO":
  297. for child, is_recurrence, recurrences in get_children(
  298. vobject_item.vtodo_list):
  299. dtstart = getattr(child, "dtstart", None)
  300. duration = getattr(child, "duration", None)
  301. due = getattr(child, "due", None)
  302. completed = getattr(child, "completed", None)
  303. created = getattr(child, "created", None)
  304. if dtstart is not None:
  305. dtstart = date_to_datetime(dtstart.value)
  306. if duration is not None:
  307. duration = duration.value
  308. if due is not None:
  309. due = date_to_datetime(due.value)
  310. if dtstart is not None:
  311. original_duration = (due - dtstart).total_seconds()
  312. if completed is not None:
  313. completed = date_to_datetime(completed.value)
  314. if created is not None:
  315. created = date_to_datetime(created.value)
  316. original_duration = (completed - created).total_seconds()
  317. elif created is not None:
  318. created = date_to_datetime(created.value)
  319. if child.rruleset:
  320. reference_dates, infinity = getrruleset(child, recurrences)
  321. if infinity:
  322. return
  323. else:
  324. if dtstart is not None:
  325. reference_dates = (dtstart,)
  326. elif due is not None:
  327. reference_dates = (due,)
  328. elif completed is not None:
  329. reference_dates = (completed,)
  330. elif created is not None:
  331. reference_dates = (created,)
  332. else:
  333. # Line 8
  334. if range_fn(DATETIME_MIN, DATETIME_MAX, is_recurrence):
  335. return
  336. reference_dates = ()
  337. for reference_date in reference_dates:
  338. reference_date = date_to_datetime(reference_date)
  339. if dtstart is not None and duration is not None:
  340. # Line 1
  341. if range_fn(reference_date,
  342. reference_date + duration + SECOND,
  343. is_recurrence):
  344. return
  345. if range_fn(reference_date + duration - SECOND,
  346. reference_date + duration + SECOND,
  347. is_recurrence):
  348. return
  349. elif dtstart is not None and due is not None:
  350. # Line 2
  351. due = reference_date + timedelta(seconds=original_duration)
  352. if (range_fn(reference_date, due, is_recurrence) or
  353. range_fn(reference_date,
  354. reference_date + SECOND, is_recurrence) or
  355. range_fn(due - SECOND, due, is_recurrence) or
  356. range_fn(due - SECOND, reference_date + SECOND,
  357. is_recurrence)):
  358. return
  359. elif dtstart is not None:
  360. if range_fn(reference_date, reference_date + SECOND,
  361. is_recurrence):
  362. return
  363. elif due is not None:
  364. # Line 4
  365. if range_fn(reference_date - SECOND, reference_date,
  366. is_recurrence):
  367. return
  368. elif completed is not None and created is not None:
  369. # Line 5
  370. completed = reference_date + timedelta(
  371. seconds=original_duration)
  372. if (range_fn(reference_date - SECOND,
  373. reference_date + SECOND,
  374. is_recurrence) or
  375. range_fn(completed - SECOND, completed + SECOND,
  376. is_recurrence) or
  377. range_fn(reference_date - SECOND,
  378. reference_date + SECOND, is_recurrence) or
  379. range_fn(completed - SECOND, completed + SECOND,
  380. is_recurrence)):
  381. return
  382. elif completed is not None:
  383. # Line 6
  384. if range_fn(reference_date - SECOND,
  385. reference_date + SECOND, is_recurrence):
  386. return
  387. elif created is not None:
  388. # Line 7
  389. if range_fn(reference_date, DATETIME_MAX, is_recurrence):
  390. return
  391. elif child_name == "VJOURNAL":
  392. for child, is_recurrence, recurrences in get_children(
  393. vobject_item.vjournal_list):
  394. dtstart = getattr(child, "dtstart", None)
  395. if dtstart is not None:
  396. dtstart = dtstart.value
  397. if child.rruleset:
  398. dtstarts, infinity = getrruleset(child, recurrences)
  399. if infinity:
  400. return
  401. else:
  402. dtstarts = (dtstart,)
  403. for dtstart in dtstarts:
  404. dtstart_is_datetime = isinstance(dtstart, datetime)
  405. dtstart = date_to_datetime(dtstart)
  406. if dtstart_is_datetime:
  407. # Line 1
  408. if range_fn(dtstart, dtstart + SECOND, is_recurrence):
  409. return
  410. else:
  411. # Line 2
  412. if range_fn(dtstart, dtstart + DAY, is_recurrence):
  413. return
  414. else:
  415. # Match a property
  416. child = getattr(vobject_item, child_name.lower())
  417. if isinstance(child.value, date):
  418. child_is_datetime = isinstance(child.value, datetime)
  419. child = date_to_datetime(child.value)
  420. if child_is_datetime:
  421. range_fn(child, child + SECOND, False)
  422. else:
  423. range_fn(child, child + DAY, False)
  424. def text_match(vobject_item: vobject.base.Component,
  425. filter_: ET.Element, child_name: str, ns: str,
  426. attrib_name: Optional[str] = None) -> bool:
  427. """Check whether the ``item`` matches the text-match ``filter_``.
  428. See rfc4791-9.7.5.
  429. """
  430. # TODO: collations are not supported, but the default ones needed
  431. # for DAV servers are actually pretty useless. Texts are lowered to
  432. # be case-insensitive, almost as the "i;ascii-casemap" value.
  433. text = next(filter_.itertext()).lower()
  434. match_type = "contains"
  435. if ns == "CR":
  436. match_type = filter_.get("match-type", match_type)
  437. def match(value: str) -> bool:
  438. value = value.lower()
  439. if match_type == "equals":
  440. return value == text
  441. if match_type == "contains":
  442. return text in value
  443. if match_type == "starts-with":
  444. return value.startswith(text)
  445. if match_type == "ends-with":
  446. return value.endswith(text)
  447. raise ValueError("Unexpected text-match match-type: %r" % match_type)
  448. children = getattr(vobject_item, "%s_list" % child_name, [])
  449. if attrib_name is not None:
  450. condition = any(
  451. match(attrib) for child in children
  452. for attrib in child.params.get(attrib_name, []))
  453. else:
  454. res = []
  455. for child in children:
  456. # Some filters such as CATEGORIES provide a list in child.value
  457. if type(child.value) is list:
  458. for value in child.value:
  459. res.append(match(value))
  460. else:
  461. res.append(match(child.value))
  462. condition = any(res)
  463. if filter_.get("negate-condition") == "yes":
  464. return not condition
  465. return condition
  466. def param_filter_match(vobject_item: vobject.base.Component,
  467. filter_: ET.Element, parent_name: str, ns: str) -> bool:
  468. """Check whether the ``item`` matches the param-filter ``filter_``.
  469. See rfc4791-9.7.3.
  470. """
  471. name = filter_.get("name", "").upper()
  472. children = getattr(vobject_item, "%s_list" % parent_name, [])
  473. condition = any(name in child.params for child in children)
  474. if len(filter_) > 0:
  475. if filter_[0].tag == xmlutils.make_clark("%s:text-match" % ns):
  476. return condition and text_match(
  477. vobject_item, filter_[0], parent_name, ns, name)
  478. if filter_[0].tag == xmlutils.make_clark("%s:is-not-defined" % ns):
  479. return not condition
  480. return condition
  481. def simplify_prefilters(filters: Iterable[ET.Element], collection_tag: str
  482. ) -> Tuple[Optional[str], int, int, bool]:
  483. """Creates a simplified condition from ``filters``.
  484. Returns a tuple (``tag``, ``start``, ``end``, ``simple``) where ``tag`` is
  485. a string or None (match all) and ``start`` and ``end`` are POSIX
  486. timestamps (as int). ``simple`` is a bool that indicates that ``filters``
  487. and the simplified condition are identical.
  488. """
  489. flat_filters = list(chain.from_iterable(filters))
  490. simple = len(flat_filters) <= 1
  491. for col_filter in flat_filters:
  492. if collection_tag != "VCALENDAR":
  493. simple = False
  494. break
  495. if (col_filter.tag != xmlutils.make_clark("C:comp-filter") or
  496. col_filter.get("name", "").upper() != "VCALENDAR"):
  497. simple = False
  498. continue
  499. simple &= len(col_filter) <= 1
  500. for comp_filter in col_filter:
  501. if comp_filter.tag != xmlutils.make_clark("C:comp-filter"):
  502. simple = False
  503. continue
  504. tag = comp_filter.get("name", "").upper()
  505. if comp_filter.find(
  506. xmlutils.make_clark("C:is-not-defined")) is not None:
  507. simple = False
  508. continue
  509. simple &= len(comp_filter) <= 1
  510. for time_filter in comp_filter:
  511. if tag not in ("VTODO", "VEVENT", "VJOURNAL"):
  512. simple = False
  513. break
  514. if time_filter.tag != xmlutils.make_clark("C:time-range"):
  515. simple = False
  516. continue
  517. start, end = time_range_timestamps(time_filter)
  518. return tag, start, end, simple
  519. return tag, TIMESTAMP_MIN, TIMESTAMP_MAX, simple
  520. return None, TIMESTAMP_MIN, TIMESTAMP_MAX, simple