filter.py 23 KB

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