__init__.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. # This file is related to Radicale - CalDAV and CardDAV server
  2. # for email notifications
  3. # Copyright © 2025-2025 Nate Harris
  4. import re
  5. import smtplib
  6. from datetime import datetime, timedelta
  7. from email.encoders import encode_base64
  8. from email.mime.base import MIMEBase
  9. from email.mime.multipart import MIMEMultipart
  10. from email.mime.text import MIMEText
  11. from email.utils import formatdate
  12. from typing import Any, Dict, List, Optional, Tuple
  13. import vobject
  14. from radicale.hook import (BaseHook, DeleteHookNotificationItem,
  15. HookNotificationItem, HookNotificationItemTypes)
  16. from radicale.log import logger
  17. PLUGIN_CONFIG_SCHEMA = {
  18. "hook": {
  19. "smtp_server": {
  20. "value": "",
  21. "type": str
  22. },
  23. "smtp_port": {
  24. "value": "",
  25. "type": str
  26. },
  27. "smtp_username": {
  28. "value": "",
  29. "type": str
  30. },
  31. "smtp_password": {
  32. "value": "",
  33. "type": str
  34. },
  35. "from_email": {
  36. "value": "",
  37. "type": str
  38. },
  39. "added_template": {
  40. "value": """Hello $attendee_name,
  41. You have been added as an attendee to the following calendar event.
  42. $event_title
  43. $event_start_time - $event_end_time
  44. $event_location
  45. This is an automated message. Please do not reply.""",
  46. "type": str
  47. },
  48. "removed_template": {
  49. "value": """Hello $attendee_name,
  50. You have been removed as an attendee from the following calendar event.
  51. $event_title
  52. $event_start_time - $event_end_time
  53. $event_location
  54. This is an automated message. Please do not reply.""",
  55. "type": str
  56. },
  57. "mass_email": {
  58. "value": False,
  59. "type": bool,
  60. }
  61. }
  62. }
  63. MESSAGE_TEMPLATE_VARIABLES = [
  64. "organizer_name",
  65. "from_email",
  66. "attendee_name",
  67. "event_title",
  68. "event_start_time",
  69. "event_end_time",
  70. "event_location",
  71. ]
  72. def ics_contents_contains_invited_event(contents: str):
  73. """
  74. Check if the ICS contents contain an event (versus a VTODO or VJOURNAL).
  75. :param contents: The contents of the ICS file.
  76. :return: True if the ICS file contains an event, False otherwise.
  77. """
  78. cal = vobject.readOne(contents)
  79. return cal.vevent is not None
  80. def extract_email(value: str) -> Optional[str]:
  81. """Extract email address from a string."""
  82. if not value:
  83. return None
  84. value = value.strip().lower()
  85. match = re.search(r"mailto:([^;]+)", value)
  86. if match:
  87. return match.group(1)
  88. # Fallback to the whole value if no mailto found
  89. return value if "@" in value else None
  90. class ContentLine:
  91. _key: str
  92. value: Any
  93. _params: Dict[str, Any]
  94. def __init__(self, key: str, value: Any, params: Optional[Dict[str, Any]] = None):
  95. self._key = key
  96. self.value = value
  97. self._params = params or {}
  98. def _get_param(self, name: str) -> List[Optional[Any]]:
  99. """
  100. Get a parameter value by name.
  101. :param name: The name of the parameter to retrieve.
  102. :return: A list of all matching parameter values, or a single-entry (None) list if the parameter does not exist.
  103. """
  104. return self._params.get(name, [None])
  105. class VComponent:
  106. _vobject_item: vobject.base.Component
  107. def __init__(self,
  108. vobject_item: vobject.base.Component,
  109. component_type: str):
  110. """Initialize a VComponent."""
  111. if not isinstance(vobject_item, vobject.base.Component):
  112. raise ValueError("vobject_item must be a vobject.base.Component")
  113. if vobject_item.name != component_type:
  114. raise ValueError("Invalid component type: %r, expected %r" %
  115. (vobject_item.name, component_type))
  116. self._vobject_item = vobject_item
  117. def _get_content_lines(self, name: str) -> List[ContentLine]:
  118. """Get each matching content line."""
  119. name = name.lower().strip()
  120. _content_lines = self._vobject_item.contents.get(name, None)
  121. if not _content_lines:
  122. return [ContentLine("", None)]
  123. if not isinstance(_content_lines, (list, tuple)):
  124. _content_lines = [_content_lines]
  125. return [ContentLine(key=name, value=cl.value, params=cl.params)
  126. for cl in _content_lines if isinstance(cl, vobject.base.ContentLine)] or [ContentLine("", None)]
  127. def _get_sub_vobjects(self, attribute_name: str, _class: type['VComponent']) -> List[Optional['VComponent']]:
  128. """Get sub vobject items of the specified type if they exist."""
  129. sub_vobjects = getattr(self._vobject_item, attribute_name, None)
  130. if not sub_vobjects:
  131. return [None]
  132. if not isinstance(sub_vobjects, (list, tuple)):
  133. sub_vobjects = [sub_vobjects]
  134. return ([_class(vobject_item=so) for so in sub_vobjects if # type: ignore
  135. isinstance(so, vobject.base.Component)]
  136. or [None])
  137. class Attendee(ContentLine):
  138. def __init__(self, content_line: ContentLine):
  139. super().__init__(key=content_line._key, value=content_line.value,
  140. params=content_line._params)
  141. @property
  142. def email(self) -> Optional[str]:
  143. """Return the email address of the attendee."""
  144. return extract_email(self.value)
  145. @property
  146. def role(self) -> Optional[str]:
  147. """Return the role of the attendee."""
  148. return self._get_param("ROLE")[0]
  149. @property
  150. def participation_status(self) -> Optional[str]:
  151. """Return the participation status of the attendee."""
  152. return self._get_param("PARTSTAT")[0]
  153. @property
  154. def name(self) -> Optional[str]:
  155. return self._get_param("CN")[0]
  156. @property
  157. def delegated_from(self) -> Optional[str]:
  158. """Return the email address of the attendee who delegated this attendee."""
  159. delegate = self._get_param("DELEGATED-FROM")[0]
  160. return extract_email(delegate) if delegate else None
  161. class TimeWithTimezone(ContentLine):
  162. def __init__(self, content_line: ContentLine):
  163. """Initialize a time with timezone content line."""
  164. super().__init__(key=content_line._key, value=content_line.value,
  165. params=content_line._params)
  166. @property
  167. def timezone_id(self) -> Optional[str]:
  168. """Return the timezone of the time."""
  169. return self._get_param("TZID")[0]
  170. @property
  171. def time(self) -> Optional[datetime]:
  172. """Return the time value."""
  173. return self.value
  174. def time_string(self, _format: str = "%Y-%m-%d %H:%M:%S") -> Optional[str]:
  175. """Return the time as a formatted string."""
  176. if self.time:
  177. return self.time.strftime(_format)
  178. return None
  179. class Alarm(VComponent):
  180. def __init__(self,
  181. vobject_item: vobject.base.Component):
  182. """Initialize a VALARM item."""
  183. super().__init__(vobject_item, "VALARM")
  184. @property
  185. def action(self) -> Optional[str]:
  186. """Return the action of the alarm."""
  187. return self._get_content_lines("ACTION")[0].value
  188. @property
  189. def description(self) -> Optional[str]:
  190. """Return the description of the alarm."""
  191. return self._get_content_lines("DESCRIPTION")[0].value
  192. @property
  193. def trigger(self) -> Optional[timedelta]:
  194. """Return the trigger of the alarm."""
  195. return self._get_content_lines("TRIGGER")[0].value
  196. @property
  197. def repeat(self) -> Optional[int]:
  198. """Return the repeat interval of the alarm."""
  199. repeat = self._get_content_lines("REPEAT")[0].value
  200. return int(repeat) if repeat is not None else None
  201. @property
  202. def duration(self) -> Optional[str]:
  203. """Return the duration of the alarm."""
  204. return self._get_content_lines("DURATION")[0].value
  205. class SubTimezone(VComponent):
  206. def __init__(self,
  207. vobject_item: vobject.base.Component,
  208. component_type: str):
  209. """Initialize a sub VTIMEZONE item."""
  210. super().__init__(vobject_item, component_type)
  211. @property
  212. def datetime_start(self) -> Optional[datetime]:
  213. """Return the start datetime of the timezone."""
  214. return self._get_content_lines("DTSTART")[0].value
  215. @property
  216. def timezone_name(self) -> Optional[str]:
  217. """Return the timezone name."""
  218. return self._get_content_lines("TZNAME")[0].value
  219. @property
  220. def timezone_offset_from(self) -> Optional[str]:
  221. """Return the timezone offset from."""
  222. return self._get_content_lines("TZOFFSETFROM")[0].value
  223. @property
  224. def timezone_offset_to(self) -> Optional[str]:
  225. """Return the timezone offset to."""
  226. return self._get_content_lines("TZOFFSETTO")[0].value
  227. class StandardTimezone(SubTimezone):
  228. def __init__(self,
  229. vobject_item: vobject.base.Component):
  230. """Initialize a STANDARD item."""
  231. super().__init__(vobject_item, "STANDARD")
  232. class DaylightTimezone(SubTimezone):
  233. def __init__(self,
  234. vobject_item: vobject.base.Component):
  235. """Initialize a DAYLIGHT item."""
  236. super().__init__(vobject_item, "DAYLIGHT")
  237. class Timezone(VComponent):
  238. def __init__(self,
  239. vobject_item: vobject.base.Component):
  240. """Initialize a VTIMEZONE item."""
  241. super().__init__(vobject_item, "VTIMEZONE")
  242. @property
  243. def timezone_id(self) -> Optional[str]:
  244. """Return the timezone ID."""
  245. return self._get_content_lines("TZID")[0].value
  246. @property
  247. def standard(self) -> Optional[StandardTimezone]:
  248. """Return the STANDARD subcomponent if it exists."""
  249. return self._get_sub_vobjects("standard", StandardTimezone)[0] # type: ignore
  250. @property
  251. def daylight(self) -> Optional[DaylightTimezone]:
  252. """Return the DAYLIGHT subcomponent if it exists."""
  253. return self._get_sub_vobjects("daylight", DaylightTimezone)[0] # type: ignore
  254. class Event(VComponent):
  255. def __init__(self,
  256. vobject_item: vobject.base.Component):
  257. """Initialize a VEVENT item."""
  258. super().__init__(vobject_item, "VEVENT")
  259. @property
  260. def datetime_stamp(self) -> Optional[str]:
  261. """Return the last modification datetime of the event."""
  262. return self._get_content_lines("DTSTAMP")[0].value
  263. @property
  264. def datetime_start(self) -> Optional[TimeWithTimezone]:
  265. """Return the start datetime of the event."""
  266. _content_line = self._get_content_lines("DTSTART")[0]
  267. return TimeWithTimezone(_content_line) if _content_line.value else None
  268. @property
  269. def datetime_end(self) -> Optional[TimeWithTimezone]:
  270. """Return the end datetime of the event. Either this or duration will be available, but not both."""
  271. _content_line = self._get_content_lines("DTEND")[0]
  272. return TimeWithTimezone(_content_line) if _content_line.value else None
  273. @property
  274. def duration(self) -> Optional[int]:
  275. """Return the duration of the event. Either this or datetime_end will be available, but not both."""
  276. return self._get_content_lines("DURATION")[0].value
  277. @property
  278. def uid(self) -> Optional[str]:
  279. """Return the UID of the event."""
  280. return self._get_content_lines("UID")[0].value
  281. @property
  282. def status(self) -> Optional[str]:
  283. """Return the status of the event."""
  284. return self._get_content_lines("STATUS")[0].value
  285. @property
  286. def summary(self) -> Optional[str]:
  287. """Return the summary of the event."""
  288. return self._get_content_lines("SUMMARY")[0].value
  289. @property
  290. def location(self) -> Optional[str]:
  291. """Return the location of the event."""
  292. return self._get_content_lines("LOCATION")[0].value
  293. @property
  294. def organizer(self) -> Optional[str]:
  295. """Return the organizer of the event."""
  296. return self._get_content_lines("ORGANIZER")[0].value
  297. @property
  298. def alarms(self) -> List[Alarm]:
  299. """Return a list of VALARM items in the event."""
  300. return self._get_sub_vobjects("valarm", Alarm) # type: ignore # Can be multiple
  301. @property
  302. def attendees(self) -> List[Attendee]:
  303. """Return a list of ATTENDEE items in the event."""
  304. _content_lines = self._get_content_lines("ATTENDEE")
  305. return [Attendee(content_line=attendee) for attendee in _content_lines if attendee.value is not None]
  306. class Calendar(VComponent):
  307. def __init__(self,
  308. vobject_item: vobject.base.Component):
  309. """Initialize a VCALENDAR item."""
  310. super().__init__(vobject_item, "VCALENDAR")
  311. @property
  312. def version(self) -> Optional[str]:
  313. """Return the version of the calendar."""
  314. return self._get_content_lines("VERSION")[0].value
  315. @property
  316. def product_id(self) -> Optional[str]:
  317. """Return the product ID of the calendar."""
  318. return self._get_content_lines("PRODID")[0].value
  319. @property
  320. def event(self) -> Optional[Event]:
  321. """Return the VEVENT item in the calendar."""
  322. return self._get_sub_vobjects("vevent", Event)[0] # type: ignore
  323. # TODO: Add VTODO and VJOURNAL support if needed
  324. @property
  325. def timezone(self) -> Optional[Timezone]:
  326. """Return the VTIMEZONE item in the calendar."""
  327. return self._get_sub_vobjects("vtimezone", Timezone)[0] # type: ignore
  328. class EmailEvent:
  329. def __init__(self,
  330. event: Event,
  331. ics_content: str,
  332. ics_file_name: str):
  333. self.event = event
  334. self.ics_content = ics_content
  335. self.file_name = ics_file_name
  336. class ICSEmailAttachment:
  337. def __init__(self, file_content: str, file_name: str):
  338. self.file_content = file_content
  339. self.file_name = file_name
  340. def prepare_email_part(self) -> MIMEBase:
  341. # Add file as application/octet-stream
  342. # Email client can usually download this automatically as attachment
  343. part = MIMEBase("application", "octet-stream")
  344. part.set_payload(self.file_content)
  345. # Encode file in ASCII characters to send by email
  346. encode_base64(part)
  347. # Add header as key/value pair to attachment part
  348. part.add_header(
  349. "Content-Disposition",
  350. f"attachment; filename= {self.file_name}",
  351. )
  352. return part
  353. class MessageTemplate:
  354. def __init__(self, subject: str, body: str):
  355. self.subject = subject
  356. self.body = body
  357. if not self._validate_template(template=subject):
  358. raise ValueError(
  359. f"Invalid subject template: {subject}. Allowed variables are: {MESSAGE_TEMPLATE_VARIABLES}")
  360. if not self._validate_template(template=body):
  361. raise ValueError(f"Invalid body template: {body}. Allowed variables are: {MESSAGE_TEMPLATE_VARIABLES}")
  362. def __repr__(self):
  363. return f'MessageTemplate(subject={self.subject}, body={self.body})'
  364. def __str__(self):
  365. return f'{self.subject}: {self.body}'
  366. def _validate_template(self, template: str) -> bool:
  367. """
  368. Validate the template to ensure it contains only allowed variables.
  369. :param template: The template string to validate.
  370. :return: True if the template is valid, False otherwise.
  371. """
  372. # Find all variables in the template (starting with $)
  373. variables = re.findall(r'\$(\w+)', template)
  374. # Check if all variables are in the allowed list
  375. for var in variables:
  376. if var not in MESSAGE_TEMPLATE_VARIABLES:
  377. logger.error(
  378. f"Invalid variable '{var}' found in template. Allowed variables are: {MESSAGE_TEMPLATE_VARIABLES}")
  379. return False
  380. return True
  381. def _populate_template(self, template: str, context: dict) -> str:
  382. """
  383. Populate the template with the provided context.
  384. :param template: The template string to populate.
  385. :param context: A dictionary containing the context variables.
  386. :return: The populated template string.
  387. """
  388. for key, value in context.items():
  389. template = template.replace(f"${key}", str(value or ""))
  390. return template
  391. def build_message(self, event: EmailEvent, from_email: str, mass_email: bool,
  392. attendee: Optional[Attendee] = None) -> str:
  393. """
  394. Build the message body using the template.
  395. :param event: The event to include in the message.
  396. :param from_email: The email address of the sender.
  397. :param mass_email: Whether this is a mass email to multiple attendees.
  398. :param attendee: The specific attendee to include in the message, if not a mass email.
  399. :return: The formatted message body.
  400. """
  401. if mass_email:
  402. # If this is a mass email, we do not use individual attendee names
  403. attendee_name = "everyone"
  404. else:
  405. assert attendee is not None, "Attendee must be provided for non-mass emails"
  406. attendee_name = attendee.name if attendee else "Unknown Name" # type: ignore
  407. context = {
  408. "attendee_name": attendee_name,
  409. "from_email": from_email,
  410. "organizer_name": event.event.organizer or "Unknown Organizer",
  411. "event_title": event.event.summary or "No Title",
  412. "event_start_time": event.event.datetime_start.time_string(), # type: ignore
  413. "event_end_time": event.event.datetime_end.time_string() if event.event.datetime_end else "No End Time",
  414. "event_location": event.event.location or "No Location Specified",
  415. }
  416. return self._populate_template(template=self.body, context=context)
  417. def build_subject(self, event: EmailEvent, from_email: str, mass_email: bool,
  418. attendee: Optional[Attendee] = None) -> str:
  419. """
  420. Build the message subject using the template.
  421. :param attendee: The attendee to include in the subject.
  422. :param event: The event to include in the subject.
  423. :param from_email: The email address of the sender.
  424. :param mass_email: Whether this is a mass email to multiple attendees.
  425. :param attendee: The specific attendee to include in the message, if not a mass email.
  426. :return: The formatted message subject.
  427. """
  428. if mass_email:
  429. # If this is a mass email, we do not use individual attendee names
  430. attendee_name = "everyone"
  431. else:
  432. assert attendee is not None, "Attendee must be provided for non-mass emails"
  433. attendee_name = attendee.name if attendee else "Unknown Name" # type: ignore
  434. context = {
  435. "attendee_name": attendee_name,
  436. "from_email": from_email,
  437. "organizer_name": event.event.organizer or "Unknown Organizer",
  438. "event_title": event.event.summary or "No Title",
  439. "event_start_time": event.event.datetime_start.time_string(), # type: ignore
  440. "event_end_time": event.event.datetime_end.time_string() if event.event.datetime_end else "No End Time",
  441. "event_location": event.event.location or "No Location Specified",
  442. }
  443. return self._populate_template(template=self.subject, context=context)
  444. class EmailConfig:
  445. def __init__(self,
  446. host: str,
  447. port: int,
  448. username: str,
  449. password: str,
  450. from_email: str,
  451. send_mass_emails: bool,
  452. added_template: MessageTemplate,
  453. removed_template: MessageTemplate):
  454. self.host = host
  455. self.port = port
  456. self.username = username
  457. self.password = password
  458. self.from_email = from_email
  459. self.send_mass_emails = send_mass_emails
  460. self.added_template = added_template
  461. self.removed_template = removed_template
  462. self.updated_template = added_template # Reuse added template for updated events
  463. self.deleted_template = removed_template # Reuse removed template for deleted events
  464. def __str__(self) -> str:
  465. """
  466. Return a string representation of the EmailConfig.
  467. """
  468. return f"EmailConfig(host={self.host}, port={self.port}, username={self.username}, " \
  469. f"from_email={self.from_email}, send_mass_emails={self.send_mass_emails})"
  470. def send_added_email(self, attendees: List[Attendee], event: EmailEvent) -> bool:
  471. """
  472. Send a notification for added attendees.
  473. :param attendees: The attendees to inform.
  474. :param event: The event the attendee is being added to.
  475. :return: True if the email was sent successfully, False otherwise.
  476. """
  477. ics_attachment = ICSEmailAttachment(file_content=event.ics_content, file_name=f"{event.file_name}")
  478. return self._prepare_and_send_email(template=self.added_template, attendees=attendees, event=event,
  479. ics_attachment=ics_attachment)
  480. def send_removed_email(self, attendees: List[Attendee], event: EmailEvent) -> bool:
  481. """
  482. Send a notification for removed attendees.
  483. :param attendees: The attendees to inform.
  484. :param event: The event the attendee is being removed from.
  485. :return: True if the email was sent successfully, False otherwise.
  486. """
  487. return self._prepare_and_send_email(template=self.removed_template, attendees=attendees, event=event,
  488. ics_attachment=None)
  489. def send_updated_email(self, attendees: List[Attendee], event: EmailEvent) -> bool:
  490. """
  491. Send a notification for updated events.
  492. :param attendees: The attendees to inform.
  493. :param event: The event being updated.
  494. :return: True if the email was sent successfully, False otherwise.
  495. """
  496. ics_attachment = ICSEmailAttachment(file_content=event.ics_content, file_name=f"{event.file_name}")
  497. return self._prepare_and_send_email(template=self.updated_template, attendees=attendees, event=event,
  498. ics_attachment=ics_attachment)
  499. def send_deleted_email(self, attendees: List[Attendee], event: EmailEvent) -> bool:
  500. """
  501. Send a notification for deleted events.
  502. :param attendees: The attendees to inform.
  503. :param event: The event being deleted.
  504. :return: True if the email was sent successfully, False otherwise.
  505. """
  506. return self._prepare_and_send_email(template=self.deleted_template, attendees=attendees, event=event,
  507. ics_attachment=None)
  508. def _prepare_and_send_email(self, template: MessageTemplate, attendees: List[Attendee],
  509. event: EmailEvent, ics_attachment: Optional[ICSEmailAttachment] = None) -> bool:
  510. """
  511. Prepare the email message(s) and send them to the attendees.
  512. :param template: The message template to use for the email.
  513. :param attendees: The list of attendees to notify.
  514. :param event: The event to include in the email.
  515. :param ics_attachment: An optional ICS attachment to include in the email.
  516. :return: True if the email(s) were sent successfully, False otherwise.
  517. """
  518. if self.send_mass_emails:
  519. # If mass emails are enabled, we send one email to all attendees
  520. body = template.build_message(event=event, from_email=self.from_email,
  521. mass_email=self.send_mass_emails, attendee=None)
  522. subject = template.build_subject(event=event, from_email=self.from_email,
  523. mass_email=self.send_mass_emails, attendee=None)
  524. return self._send_email(subject=subject, body=body, attendees=attendees, ics_attachment=ics_attachment)
  525. else:
  526. failure_encountered = False
  527. for attendee in attendees:
  528. # For individual emails, we send one email per attendee
  529. body = template.build_message(event=event, from_email=self.from_email,
  530. mass_email=self.send_mass_emails, attendee=attendee)
  531. subject = template.build_subject(event=event, from_email=self.from_email,
  532. mass_email=self.send_mass_emails, attendee=attendee)
  533. if not self._send_email(subject=subject, body=body, attendees=[attendee],
  534. ics_attachment=ics_attachment):
  535. failure_encountered = True
  536. return not failure_encountered # Return True if all emails were sent successfully
  537. def _send_email(self,
  538. subject: str,
  539. body: str,
  540. attendees: List[Attendee],
  541. ics_attachment: Optional[ICSEmailAttachment] = None) -> bool:
  542. """
  543. Send the notification using the email service.
  544. :param subject: The subject of the notification.
  545. :param body: The body of the notification.
  546. :param attendees: The attendees to notify.
  547. :param ics_attachment: An optional ICS attachment to include in the email.
  548. :return: True if the email was sent successfully, False otherwise.
  549. """
  550. to_addresses = [attendee.email for attendee in attendees if attendee.email]
  551. if not to_addresses:
  552. logger.warning("No valid email addresses found in attendees. Cannot send email.")
  553. return False
  554. # Add headers
  555. message = MIMEMultipart("mixed")
  556. message["From"] = self.from_email
  557. message["Reply-To"] = self.from_email
  558. message["Subject"] = subject
  559. message["Date"] = formatdate(localtime=True)
  560. # Add body text
  561. message.attach(MIMEText(body, "plain"))
  562. # Add ICS attachment if provided
  563. if ics_attachment:
  564. ical_attachment = ics_attachment.prepare_email_part()
  565. message.attach(ical_attachment)
  566. # Convert message to text
  567. text = message.as_string()
  568. try:
  569. server = smtplib.SMTP(host=self.host, port=self.port)
  570. server.ehlo() # Identify self to server
  571. server.starttls() # Start TLS connection
  572. server.ehlo() # Identify again after starting TLS
  573. server.login(user=self.username, password=self.password)
  574. errors: Dict[str, Tuple[int, bytes]] = server.sendmail(from_addr=self.from_email, to_addrs=to_addresses,
  575. msg=text)
  576. logger.debug("Email sent successfully to %s", to_addresses)
  577. server.quit()
  578. except smtplib.SMTPException as e:
  579. logger.error(f"SMTP error occurred: {e}")
  580. return False
  581. if errors:
  582. for email, (code, error) in errors.items():
  583. logger.error(f"Failed to send email to {email}: {str(error)} (Code: {code})")
  584. return False
  585. return True
  586. def __repr__(self):
  587. return f'EmailConfig(host={self.host}, port={self.port}, from_email={self.from_email})'
  588. def __str__(self):
  589. return f'{self.from_email} ({self.host}:{self.port})'
  590. def _read_event(vobject_data: str) -> EmailEvent:
  591. """
  592. Read the vobject item from the provided string and create an EmailEvent.
  593. """
  594. v_cal: vobject.base.Component = vobject.readOne(vobject_data)
  595. cal: Calendar = Calendar(vobject_item=v_cal)
  596. event: Event = cal.event # type: ignore
  597. return EmailEvent(
  598. event=event,
  599. ics_content=vobject_data,
  600. ics_file_name="event.ics"
  601. )
  602. class Hook(BaseHook):
  603. def __init__(self, configuration):
  604. super().__init__(configuration)
  605. self.email_config = EmailConfig(
  606. host=self.configuration.get("hook", "smtp_server"),
  607. port=self.configuration.get("hook", "smtp_port"),
  608. username=self.configuration.get("hook", "smtp_username"),
  609. password=self.configuration.get("hook", "smtp_password"),
  610. from_email=self.configuration.get("hook", "from_email"),
  611. send_mass_emails=self.configuration.get("hook", "mass_email"),
  612. added_template=MessageTemplate(
  613. subject="You have been added to an event",
  614. body=self.configuration.get("hook", "added_template")
  615. ),
  616. removed_template=MessageTemplate(
  617. subject="You have been removed from an event",
  618. body=self.configuration.get("hook", "removed_template")
  619. ),
  620. )
  621. logger.info(
  622. "Email hook initialized with configuration: %s",
  623. self.email_config
  624. )
  625. def notify(self, notification_item) -> None:
  626. """
  627. Entrypoint for processing a single notification item.
  628. Overrides default notify method from BaseHook.
  629. Triggered by Radicale when a notifiable event occurs (e.g. item added, updated or deleted)
  630. """
  631. if isinstance(notification_item, HookNotificationItem):
  632. self._process_event_and_notify(notification_item)
  633. def _process_event_and_notify(self, notification_item: HookNotificationItem) -> None:
  634. """
  635. Process the event and send an email notification.
  636. :param notification_item: The single item to process.
  637. :type notification_item: HookNotificationItem
  638. :return: None
  639. """
  640. logger.debug("Received notification item: %s", notification_item)
  641. try:
  642. notification_type = HookNotificationItemTypes(value=notification_item.type)
  643. except ValueError:
  644. logger.warning("Unknown notification item type: %s", notification_item.type)
  645. return
  646. if notification_type == HookNotificationItemTypes.CPATCH:
  647. # Ignore cpatch notifications (PROPPATCH requests for WebDAV metadata updates)
  648. return
  649. elif notification_type == HookNotificationItemTypes.UPSERT:
  650. # Handle upsert notifications (POST request for new item and PUT for updating existing item)
  651. # We don't have access to the original content for a PUT request, just the incoming data
  652. item_str: str = notification_item.content # type: ignore # A serialized vobject.base.Component
  653. if not ics_contents_contains_invited_event(contents=item_str):
  654. # If the ICS file does not contain an event, we do not send any notifications.
  655. logger.debug("No event found in the ICS file, skipping notification.")
  656. return
  657. email_event: EmailEvent = _read_event(vobject_data=item_str) # type: ignore
  658. email_success: bool = self.email_config.send_updated_email( # type: ignore
  659. attendees=email_event.event.attendees,
  660. event=email_event
  661. )
  662. if not email_success:
  663. logger.error("Failed to send some or all email notifications for event: %s", email_event.event.uid)
  664. return
  665. elif notification_type == HookNotificationItemTypes.DELETE:
  666. # Handle delete notifications (DELETE requests)
  667. # Ensure it's a delete notification, as we need the old content
  668. if not isinstance(notification_item, DeleteHookNotificationItem):
  669. return
  670. item_str: str = notification_item.old_content # type: ignore # A serialized vobject.base.Component
  671. if not ics_contents_contains_invited_event(contents=item_str):
  672. # If the ICS file does not contain an event, we do not send any notifications.
  673. logger.debug("No event found in the ICS file, skipping notification.")
  674. return
  675. email_event: EmailEvent = _read_event(vobject_data=item_str) # type: ignore
  676. email_success: bool = self.email_config.send_deleted_email( # type: ignore
  677. attendees=email_event.event.attendees,
  678. event=email_event
  679. )
  680. if not email_success:
  681. logger.error("Failed to send some or all email notifications for event: %s", email_event.event.uid)
  682. return
  683. return