__init__.py 31 KB

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