__init__.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. # This file is related to Radicale - CalDAV and CardDAV server
  2. # for email notifications
  3. # Copyright © 2025-2025 Nate Harris
  4. #
  5. # This library is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This library is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  17. import enum
  18. import re
  19. import smtplib
  20. import ssl
  21. from datetime import datetime, timedelta
  22. from email.encoders import encode_base64
  23. from email.mime.base import MIMEBase
  24. from email.mime.multipart import MIMEMultipart
  25. from email.mime.text import MIMEText
  26. from email.utils import formatdate
  27. from typing import Any, Dict, List, Optional, Sequence, Tuple
  28. import vobject
  29. from radicale.hook import (BaseHook, HookNotificationItem, HookNotificationItemTypes)
  30. from radicale.log import logger
  31. PLUGIN_CONFIG_SCHEMA = {
  32. "hook": {
  33. "smtp_server": {
  34. "value": "",
  35. "type": str
  36. },
  37. "smtp_port": {
  38. "value": "",
  39. "type": str
  40. },
  41. "smtp_security": {
  42. "value": "none",
  43. "type": str,
  44. },
  45. "smtp_ssl_verify_mode": {
  46. "value": "REQUIRED",
  47. "type": str,
  48. },
  49. "smtp_username": {
  50. "value": "",
  51. "type": str
  52. },
  53. "smtp_password": {
  54. "value": "",
  55. "type": str
  56. },
  57. "from_email": {
  58. "value": "",
  59. "type": str
  60. },
  61. "new_or_added_to_event_template": {
  62. "value": """Hello $attendee_name,
  63. You have been added as an attendee to the following calendar event.
  64. $event_title
  65. $event_start_time - $event_end_time
  66. $event_location
  67. This is an automated message. Please do not reply.""",
  68. "type": str
  69. },
  70. "deleted_or_removed_from_event_template": {
  71. "value": """Hello $attendee_name,
  72. The following event has been deleted.
  73. $event_title
  74. $event_start_time - $event_end_time
  75. $event_location
  76. This is an automated message. Please do not reply.""",
  77. "type": str
  78. },
  79. "updated_event_template": {
  80. "value": """Hello $attendee_name,
  81. The following event has been updated.
  82. $event_title
  83. $event_start_time - $event_end_time
  84. $event_location
  85. This is an automated message. Please do not reply.""",
  86. "type": str
  87. },
  88. "mass_email": {
  89. "value": False,
  90. "type": bool,
  91. }
  92. }
  93. }
  94. MESSAGE_TEMPLATE_VARIABLES = [
  95. "organizer_name",
  96. "from_email",
  97. "attendee_name",
  98. "event_title",
  99. "event_start_time",
  100. "event_end_time",
  101. "event_location",
  102. ]
  103. class SMTP_SECURITY_TYPE_ENUM(enum.Enum):
  104. EMPTY = ""
  105. NONE = "none"
  106. STARTTLS = "starttls"
  107. TLS = "tls"
  108. @classmethod
  109. def from_string(cls, value):
  110. """Convert a string to the corresponding enum value."""
  111. for member in cls:
  112. if member.value == value:
  113. return member
  114. raise ValueError(f"Invalid security type: {value}. Allowed values are: {[m.value for m in cls]}")
  115. class SMTP_SSL_VERIFY_MODE_ENUM(enum.Enum):
  116. EMPTY = ""
  117. NONE = "NONE"
  118. OPTIONAL = "OPTIONAL"
  119. REQUIRED = "REQUIRED"
  120. @classmethod
  121. def from_string(cls, value):
  122. """Convert a string to the corresponding enum value."""
  123. for member in cls:
  124. if member.value == value:
  125. return member
  126. raise ValueError(f"Invalid SSL verify mode: {value}. Allowed values are: {[m.value for m in cls]}")
  127. SMTP_SECURITY_TYPES: Sequence[str] = (SMTP_SECURITY_TYPE_ENUM.NONE.value,
  128. SMTP_SECURITY_TYPE_ENUM.STARTTLS.value,
  129. SMTP_SECURITY_TYPE_ENUM.TLS.value)
  130. SMTP_SSL_VERIFY_MODES: Sequence[str] = (SMTP_SSL_VERIFY_MODE_ENUM.NONE.value,
  131. SMTP_SSL_VERIFY_MODE_ENUM.OPTIONAL.value,
  132. SMTP_SSL_VERIFY_MODE_ENUM.REQUIRED.value)
  133. def read_ics_event(contents: str) -> Optional['Event']:
  134. """
  135. Read the vobject item from the provided string and create an Event.
  136. """
  137. v_cal: vobject.base.Component = vobject.readOne(contents)
  138. cal: Calendar = Calendar(vobject_item=v_cal)
  139. return cal.event if cal.event else None
  140. def ics_contents_contains_event(contents: str):
  141. """
  142. Check if the ICS contents contain an event (versus a VADDRESSBOOK, VTODO or VJOURNAL).
  143. :param contents: The contents of the ICS file.
  144. :return: True if the ICS file contains an event, False otherwise.
  145. """
  146. return read_ics_event(contents) is not None
  147. def extract_email(value: str) -> Optional[str]:
  148. """Extract email address from a string."""
  149. if not value:
  150. return None
  151. value = value.strip().lower()
  152. match = re.search(r"mailto:([^;]+)", value)
  153. if match:
  154. return match.group(1)
  155. # Fallback to the whole value if no mailto found
  156. return value if "@" in value else None
  157. def determine_added_removed_and_unaltered_attendees(original_event: 'Event',
  158. new_event: 'Event') -> (
  159. Tuple)[List['Attendee'], List['Attendee'], List['Attendee']]:
  160. """
  161. Determine the added, removed and unaltered attendees between two events.
  162. """
  163. original_event_attendees = {attendee.email: attendee for attendee in original_event.attendees}
  164. new_event_attendees = {attendee.email: attendee for attendee in new_event.attendees}
  165. # Added attendees are those who are in the new event but not in the original event
  166. added_attendees = [new_event_attendees[email] for email in new_event_attendees if
  167. email not in original_event_attendees]
  168. # Removed attendees are those who are in the original event but not in the new event
  169. removed_attendees = [original_event_attendees[email] for email in original_event_attendees if
  170. email not in new_event_attendees]
  171. # Unaltered attendees are those who are in both events
  172. unaltered_attendees = [original_event_attendees[email] for email in original_event_attendees if
  173. email in new_event_attendees]
  174. return added_attendees, removed_attendees, unaltered_attendees
  175. class ContentLine:
  176. _key: str
  177. value: Any
  178. _params: Dict[str, Any]
  179. def __init__(self, key: str, value: Any, params: Optional[Dict[str, Any]] = None):
  180. self._key = key
  181. self.value = value
  182. self._params = params or {}
  183. def _get_param(self, name: str) -> List[Optional[Any]]:
  184. """
  185. Get a parameter value by name.
  186. :param name: The name of the parameter to retrieve.
  187. :return: A list of all matching parameter values, or a single-entry (None) list if the parameter does not exist.
  188. """
  189. return self._params.get(name, [None])
  190. class VComponent:
  191. _vobject_item: vobject.base.Component
  192. def __init__(self,
  193. vobject_item: vobject.base.Component,
  194. component_type: str):
  195. """Initialize a VComponent."""
  196. if not isinstance(vobject_item, vobject.base.Component):
  197. raise ValueError("vobject_item must be a vobject.base.Component")
  198. if vobject_item.name != component_type:
  199. raise ValueError("Invalid component type: %r, expected %r" %
  200. (vobject_item.name, component_type))
  201. self._vobject_item = vobject_item
  202. def _get_content_lines(self, name: str) -> List[ContentLine]:
  203. """Get each matching content line."""
  204. name = name.lower().strip()
  205. _content_lines = self._vobject_item.contents.get(name, None)
  206. if not _content_lines:
  207. return [ContentLine("", None)]
  208. if not isinstance(_content_lines, (list, tuple)):
  209. _content_lines = [_content_lines]
  210. return [ContentLine(key=name, value=cl.value, params=cl.params)
  211. for cl in _content_lines if isinstance(cl, vobject.base.ContentLine)] or [ContentLine("", None)]
  212. def _get_sub_vobjects(self, attribute_name: str, _class: type['VComponent']) -> List[Optional['VComponent']]:
  213. """Get sub vobject items of the specified type if they exist."""
  214. sub_vobjects = getattr(self._vobject_item, attribute_name, None)
  215. if not sub_vobjects:
  216. return [None]
  217. if not isinstance(sub_vobjects, (list, tuple)):
  218. sub_vobjects = [sub_vobjects]
  219. return ([_class(vobject_item=so) for so in sub_vobjects if # type: ignore
  220. isinstance(so, vobject.base.Component)]
  221. or [None])
  222. class Attendee(ContentLine):
  223. def __init__(self, content_line: ContentLine):
  224. super().__init__(key=content_line._key, value=content_line.value,
  225. params=content_line._params)
  226. @property
  227. def email(self) -> Optional[str]:
  228. """Return the email address of the attendee."""
  229. return extract_email(self.value)
  230. @property
  231. def role(self) -> Optional[str]:
  232. """Return the role of the attendee."""
  233. return self._get_param("ROLE")[0]
  234. @property
  235. def participation_status(self) -> Optional[str]:
  236. """Return the participation status of the attendee."""
  237. return self._get_param("PARTSTAT")[0]
  238. @property
  239. def name(self) -> Optional[str]:
  240. return self._get_param("CN")[0]
  241. @property
  242. def delegated_from(self) -> Optional[str]:
  243. """Return the email address of the attendee who delegated this attendee."""
  244. delegate = self._get_param("DELEGATED-FROM")[0]
  245. return extract_email(delegate) if delegate else None
  246. class TimeWithTimezone(ContentLine):
  247. def __init__(self, content_line: ContentLine):
  248. """Initialize a time with timezone content line."""
  249. super().__init__(key=content_line._key, value=content_line.value,
  250. params=content_line._params)
  251. @property
  252. def timezone_id(self) -> Optional[str]:
  253. """Return the timezone of the time."""
  254. return self._get_param("TZID")[0]
  255. @property
  256. def time(self) -> Optional[datetime]:
  257. """Return the time value."""
  258. return self.value
  259. def time_string(self, _format: str = "%Y-%m-%d %H:%M:%S") -> Optional[str]:
  260. """Return the time as a formatted string."""
  261. if self.time:
  262. return self.time.strftime(_format)
  263. return None
  264. class Alarm(VComponent):
  265. def __init__(self,
  266. vobject_item: vobject.base.Component):
  267. """Initialize a VALARM item."""
  268. super().__init__(vobject_item, "VALARM")
  269. @property
  270. def action(self) -> Optional[str]:
  271. """Return the action of the alarm."""
  272. return self._get_content_lines("ACTION")[0].value
  273. @property
  274. def description(self) -> Optional[str]:
  275. """Return the description of the alarm."""
  276. return self._get_content_lines("DESCRIPTION")[0].value
  277. @property
  278. def trigger(self) -> Optional[timedelta]:
  279. """Return the trigger of the alarm."""
  280. return self._get_content_lines("TRIGGER")[0].value
  281. @property
  282. def repeat(self) -> Optional[int]:
  283. """Return the repeat interval of the alarm."""
  284. repeat = self._get_content_lines("REPEAT")[0].value
  285. return int(repeat) if repeat is not None else None
  286. @property
  287. def duration(self) -> Optional[str]:
  288. """Return the duration of the alarm."""
  289. return self._get_content_lines("DURATION")[0].value
  290. class SubTimezone(VComponent):
  291. def __init__(self,
  292. vobject_item: vobject.base.Component,
  293. component_type: str):
  294. """Initialize a sub VTIMEZONE item."""
  295. super().__init__(vobject_item, component_type)
  296. @property
  297. def datetime_start(self) -> Optional[datetime]:
  298. """Return the start datetime of the timezone."""
  299. return self._get_content_lines("DTSTART")[0].value
  300. @property
  301. def timezone_name(self) -> Optional[str]:
  302. """Return the timezone name."""
  303. return self._get_content_lines("TZNAME")[0].value
  304. @property
  305. def timezone_offset_from(self) -> Optional[str]:
  306. """Return the timezone offset from."""
  307. return self._get_content_lines("TZOFFSETFROM")[0].value
  308. @property
  309. def timezone_offset_to(self) -> Optional[str]:
  310. """Return the timezone offset to."""
  311. return self._get_content_lines("TZOFFSETTO")[0].value
  312. class StandardTimezone(SubTimezone):
  313. def __init__(self,
  314. vobject_item: vobject.base.Component):
  315. """Initialize a STANDARD item."""
  316. super().__init__(vobject_item, "STANDARD")
  317. class DaylightTimezone(SubTimezone):
  318. def __init__(self,
  319. vobject_item: vobject.base.Component):
  320. """Initialize a DAYLIGHT item."""
  321. super().__init__(vobject_item, "DAYLIGHT")
  322. class Timezone(VComponent):
  323. def __init__(self,
  324. vobject_item: vobject.base.Component):
  325. """Initialize a VTIMEZONE item."""
  326. super().__init__(vobject_item, "VTIMEZONE")
  327. @property
  328. def timezone_id(self) -> Optional[str]:
  329. """Return the timezone ID."""
  330. return self._get_content_lines("TZID")[0].value
  331. @property
  332. def standard(self) -> Optional[StandardTimezone]:
  333. """Return the STANDARD subcomponent if it exists."""
  334. return self._get_sub_vobjects("standard", StandardTimezone)[0] # type: ignore
  335. @property
  336. def daylight(self) -> Optional[DaylightTimezone]:
  337. """Return the DAYLIGHT subcomponent if it exists."""
  338. return self._get_sub_vobjects("daylight", DaylightTimezone)[0] # type: ignore
  339. class Event(VComponent):
  340. def __init__(self,
  341. vobject_item: vobject.base.Component):
  342. """Initialize a VEVENT item."""
  343. super().__init__(vobject_item, "VEVENT")
  344. @property
  345. def datetime_stamp(self) -> Optional[str]:
  346. """Return the last modification datetime of the event."""
  347. return self._get_content_lines("DTSTAMP")[0].value
  348. @property
  349. def datetime_start(self) -> Optional[TimeWithTimezone]:
  350. """Return the start datetime of the event."""
  351. _content_line = self._get_content_lines("DTSTART")[0]
  352. return TimeWithTimezone(_content_line) if _content_line.value else None
  353. @property
  354. def datetime_end(self) -> Optional[TimeWithTimezone]:
  355. """Return the end datetime of the event. Either this or duration will be available, but not both."""
  356. _content_line = self._get_content_lines("DTEND")[0]
  357. return TimeWithTimezone(_content_line) if _content_line.value else None
  358. @property
  359. def duration(self) -> Optional[int]:
  360. """Return the duration of the event. Either this or datetime_end will be available, but not both."""
  361. return self._get_content_lines("DURATION")[0].value
  362. @property
  363. def uid(self) -> Optional[str]:
  364. """Return the UID of the event."""
  365. return self._get_content_lines("UID")[0].value
  366. @property
  367. def status(self) -> Optional[str]:
  368. """Return the status of the event."""
  369. return self._get_content_lines("STATUS")[0].value
  370. @property
  371. def summary(self) -> Optional[str]:
  372. """Return the summary of the event."""
  373. return self._get_content_lines("SUMMARY")[0].value
  374. @property
  375. def location(self) -> Optional[str]:
  376. """Return the location of the event."""
  377. return self._get_content_lines("LOCATION")[0].value
  378. @property
  379. def organizer(self) -> Optional[str]:
  380. """Return the organizer of the event."""
  381. return self._get_content_lines("ORGANIZER")[0].value
  382. @property
  383. def alarms(self) -> List[Alarm]:
  384. """Return a list of VALARM items in the event."""
  385. return self._get_sub_vobjects("valarm", Alarm) # type: ignore # Can be multiple
  386. @property
  387. def attendees(self) -> List[Attendee]:
  388. """Return a list of ATTENDEE items in the event."""
  389. _content_lines = self._get_content_lines("ATTENDEE")
  390. return [Attendee(content_line=attendee) for attendee in _content_lines if attendee.value is not None]
  391. class Calendar(VComponent):
  392. def __init__(self,
  393. vobject_item: vobject.base.Component):
  394. """Initialize a VCALENDAR item."""
  395. super().__init__(vobject_item, "VCALENDAR")
  396. @property
  397. def version(self) -> Optional[str]:
  398. """Return the version of the calendar."""
  399. return self._get_content_lines("VERSION")[0].value
  400. @property
  401. def product_id(self) -> Optional[str]:
  402. """Return the product ID of the calendar."""
  403. return self._get_content_lines("PRODID")[0].value
  404. @property
  405. def event(self) -> Optional[Event]:
  406. """Return the VEVENT item in the calendar."""
  407. return self._get_sub_vobjects("vevent", Event)[0] # type: ignore
  408. # TODO: Add VTODO and VJOURNAL support if needed
  409. @property
  410. def timezone(self) -> Optional[Timezone]:
  411. """Return the VTIMEZONE item in the calendar."""
  412. return self._get_sub_vobjects("vtimezone", Timezone)[0] # type: ignore
  413. class EmailEvent:
  414. def __init__(self,
  415. event: Event,
  416. ics_content: str,
  417. ics_file_name: str):
  418. self.event = event
  419. self.ics_content = ics_content
  420. self.file_name = ics_file_name
  421. class ICSEmailAttachment:
  422. def __init__(self, file_content: str, file_name: str):
  423. self.file_content = file_content
  424. self.file_name = file_name
  425. def prepare_email_part(self) -> MIMEBase:
  426. # Add file as application/octet-stream
  427. # Email client can usually download this automatically as attachment
  428. part = MIMEBase("application", "octet-stream")
  429. part.set_payload(self.file_content)
  430. # Encode file in ASCII characters to send by email
  431. encode_base64(part)
  432. # Add header as key/value pair to attachment part
  433. part.add_header(
  434. "Content-Disposition",
  435. f"attachment; filename= {self.file_name}",
  436. )
  437. return part
  438. class MessageTemplate:
  439. def __init__(self, subject: str, body: str):
  440. self.subject = subject
  441. self.body = body
  442. if not self._validate_template(template=subject):
  443. raise ValueError(
  444. f"Invalid subject template: {subject}. Allowed variables are: {MESSAGE_TEMPLATE_VARIABLES}")
  445. if not self._validate_template(template=body):
  446. raise ValueError(f"Invalid body template: {body}. Allowed variables are: {MESSAGE_TEMPLATE_VARIABLES}")
  447. def __repr__(self):
  448. return f'MessageTemplate(subject={self.subject}, body={self.body})'
  449. def __str__(self):
  450. return f'{self.subject}: {self.body}'
  451. def _validate_template(self, template: str) -> bool:
  452. """
  453. Validate the template to ensure it contains only allowed variables.
  454. :param template: The template string to validate.
  455. :return: True if the template is valid, False otherwise.
  456. """
  457. # Find all variables in the template (starting with $)
  458. variables = re.findall(r'\$(\w+)', template)
  459. # Check if all variables are in the allowed list
  460. for var in variables:
  461. if var not in MESSAGE_TEMPLATE_VARIABLES:
  462. logger.error(
  463. f"Invalid variable '{var}' found in template. Allowed variables are: {MESSAGE_TEMPLATE_VARIABLES}")
  464. return False
  465. return True
  466. def _populate_template(self, template: str, context: dict) -> str:
  467. """
  468. Populate the template with the provided context.
  469. :param template: The template string to populate.
  470. :param context: A dictionary containing the context variables.
  471. :return: The populated template string.
  472. """
  473. for key, value in context.items():
  474. template = template.replace(f"${key}", str(value or ""))
  475. return template
  476. def build_message(self, event: EmailEvent, from_email: str, mass_email: bool,
  477. attendee: Optional[Attendee] = None) -> str:
  478. """
  479. Build the message body using the template.
  480. :param event: The event to include in the message.
  481. :param from_email: The email address of the sender.
  482. :param mass_email: Whether this is a mass email to multiple attendees.
  483. :param attendee: The specific attendee to include in the message, if not a mass email.
  484. :return: The formatted message body.
  485. """
  486. if mass_email:
  487. # If this is a mass email, we do not use individual attendee names
  488. attendee_name = "everyone"
  489. else:
  490. assert attendee is not None, "Attendee must be provided for non-mass emails"
  491. attendee_name = attendee.name if attendee else "Unknown Name" # type: ignore
  492. context = {
  493. "attendee_name": attendee_name,
  494. "from_email": from_email,
  495. "organizer_name": event.event.organizer or "Unknown Organizer",
  496. "event_title": event.event.summary or "No Title",
  497. "event_start_time": event.event.datetime_start.time_string(), # type: ignore
  498. "event_end_time": event.event.datetime_end.time_string() if event.event.datetime_end else "No End Time",
  499. "event_location": event.event.location or "No Location Specified",
  500. }
  501. return self._populate_template(template=self.body, context=context)
  502. def build_subject(self, event: EmailEvent, from_email: str, mass_email: bool,
  503. attendee: Optional[Attendee] = None) -> str:
  504. """
  505. Build the message subject using the template.
  506. :param attendee: The attendee to include in the subject.
  507. :param event: The event to include in the subject.
  508. :param from_email: The email address of the sender.
  509. :param mass_email: Whether this is a mass email to multiple attendees.
  510. :param attendee: The specific attendee to include in the message, if not a mass email.
  511. :return: The formatted message subject.
  512. """
  513. if mass_email:
  514. # If this is a mass email, we do not use individual attendee names
  515. attendee_name = "everyone"
  516. else:
  517. assert attendee is not None, "Attendee must be provided for non-mass emails"
  518. attendee_name = attendee.name if attendee else "Unknown Name" # type: ignore
  519. context = {
  520. "attendee_name": attendee_name,
  521. "from_email": from_email,
  522. "organizer_name": event.event.organizer or "Unknown Organizer",
  523. "event_title": event.event.summary or "No Title",
  524. "event_start_time": event.event.datetime_start.time_string(), # type: ignore
  525. "event_end_time": event.event.datetime_end.time_string() if event.event.datetime_end else "No End Time",
  526. "event_location": event.event.location or "No Location Specified",
  527. }
  528. return self._populate_template(template=self.subject, context=context)
  529. class EmailConfig:
  530. def __init__(self,
  531. host: str,
  532. port: int,
  533. security: str,
  534. ssl_verify_mode: str,
  535. username: str,
  536. password: str,
  537. from_email: str,
  538. send_mass_emails: bool,
  539. dryrun: bool,
  540. new_or_added_to_event_template: MessageTemplate,
  541. deleted_or_removed_from_event_template: MessageTemplate,
  542. updated_event_template: MessageTemplate):
  543. self.host = host
  544. self.port = port
  545. self.security = SMTP_SECURITY_TYPE_ENUM.from_string(value=security)
  546. self.ssl_verify_mode = SMTP_SSL_VERIFY_MODE_ENUM.from_string(value=ssl_verify_mode)
  547. self.username = username
  548. self.password = password
  549. self.from_email = from_email
  550. self.send_mass_emails = send_mass_emails
  551. self.dryrun = dryrun
  552. self.new_or_added_to_event_template = new_or_added_to_event_template
  553. self.deleted_or_removed_from_event_template = deleted_or_removed_from_event_template
  554. self.updated_event_template = updated_event_template
  555. def __str__(self) -> str:
  556. """
  557. Return a string representation of the EmailConfig.
  558. """
  559. return f"EmailConfig(host={self.host}, port={self.port}, username={self.username}, " \
  560. f"from_email={self.from_email}, send_mass_emails={self.send_mass_emails}, dryrun={self.dryrun})"
  561. def __repr__(self):
  562. return self.__str__()
  563. def send_added_email(self, attendees: List[Attendee], event: EmailEvent) -> bool:
  564. """
  565. Send a notification for created events (and/or adding attendees).
  566. :param attendees: The attendees to inform.
  567. :param event: The event being created (or the event the attendee is being added to).
  568. :return: True if the email was sent successfully, False otherwise.
  569. """
  570. ics_attachment = ICSEmailAttachment(file_content=event.ics_content, file_name=f"{event.file_name}")
  571. return self._prepare_and_send_email(template=self.new_or_added_to_event_template, attendees=attendees, event=event,
  572. ics_attachment=ics_attachment)
  573. def send_updated_email(self, attendees: List[Attendee], event: EmailEvent) -> bool:
  574. """
  575. Send a notification for updated events.
  576. :param attendees: The attendees to inform.
  577. :param event: The event being updated.
  578. :return: True if the email was sent successfully, False otherwise.
  579. """
  580. ics_attachment = ICSEmailAttachment(file_content=event.ics_content, file_name=f"{event.file_name}")
  581. return self._prepare_and_send_email(template=self.updated_event_template, attendees=attendees, event=event,
  582. ics_attachment=ics_attachment)
  583. def send_deleted_email(self, attendees: List[Attendee], event: EmailEvent) -> bool:
  584. """
  585. Send a notification for deleted events (and/or removing attendees).
  586. :param attendees: The attendees to inform.
  587. :param event: The event being deleted (or the event the attendee is being removed from).
  588. :return: True if the email was sent successfully, False otherwise.
  589. """
  590. return self._prepare_and_send_email(template=self.deleted_or_removed_from_event_template, attendees=attendees, event=event,
  591. ics_attachment=None)
  592. def _prepare_and_send_email(self, template: MessageTemplate, attendees: List[Attendee],
  593. event: EmailEvent, ics_attachment: Optional[ICSEmailAttachment] = None) -> bool:
  594. """
  595. Prepare the email message(s) and send them to the attendees.
  596. :param template: The message template to use for the email.
  597. :param attendees: The list of attendees to notify.
  598. :param event: The event to include in the email.
  599. :param ics_attachment: An optional ICS attachment to include in the email.
  600. :return: True if the email(s) were sent successfully, False otherwise.
  601. """
  602. if self.send_mass_emails:
  603. # If mass emails are enabled, we send one email to all attendees
  604. body = template.build_message(event=event, from_email=self.from_email,
  605. mass_email=self.send_mass_emails, attendee=None)
  606. subject = template.build_subject(event=event, from_email=self.from_email,
  607. mass_email=self.send_mass_emails, attendee=None)
  608. return self._send_email(subject=subject, body=body, attendees=attendees, ics_attachment=ics_attachment)
  609. else:
  610. failure_encountered = False
  611. for attendee in attendees:
  612. # For individual emails, we send one email per attendee
  613. body = template.build_message(event=event, from_email=self.from_email,
  614. mass_email=self.send_mass_emails, attendee=attendee)
  615. subject = template.build_subject(event=event, from_email=self.from_email,
  616. mass_email=self.send_mass_emails, attendee=attendee)
  617. if not self._send_email(subject=subject, body=body, attendees=[attendee],
  618. ics_attachment=ics_attachment):
  619. failure_encountered = True
  620. return not failure_encountered # Return True if all emails were sent successfully
  621. def _build_context(self) -> ssl.SSLContext:
  622. """
  623. Build the SSL context based on the configured security and SSL verify mode.
  624. :return: An SSLContext object configured for the SMTP connection.
  625. """
  626. context = ssl.create_default_context()
  627. if self.ssl_verify_mode == SMTP_SSL_VERIFY_MODE_ENUM.REQUIRED:
  628. context.check_hostname = True
  629. context.verify_mode = ssl.CERT_REQUIRED
  630. elif self.ssl_verify_mode == SMTP_SSL_VERIFY_MODE_ENUM.OPTIONAL:
  631. context.check_hostname = True
  632. context.verify_mode = ssl.CERT_OPTIONAL
  633. else:
  634. context.check_hostname = False
  635. context.verify_mode = ssl.CERT_NONE
  636. return context
  637. def _send_email(self,
  638. subject: str,
  639. body: str,
  640. attendees: List[Attendee],
  641. ics_attachment: Optional[ICSEmailAttachment] = None) -> bool:
  642. """
  643. Send the notification using the email service.
  644. :param subject: The subject of the notification.
  645. :param body: The body of the notification.
  646. :param attendees: The attendees to notify.
  647. :param ics_attachment: An optional ICS attachment to include in the email.
  648. :return: True if the email was sent successfully, False otherwise.
  649. """
  650. to_addresses = [attendee.email for attendee in attendees if attendee.email]
  651. if not to_addresses:
  652. logger.warning("No valid email addresses found in attendees. Cannot send email.")
  653. return False
  654. if self.dryrun is True:
  655. logger.warning("Hook 'email': DRY-RUN _send_email / to_addresses=%r", to_addresses)
  656. return True
  657. # Add headers
  658. message = MIMEMultipart("mixed")
  659. message["From"] = self.from_email
  660. message["Reply-To"] = self.from_email
  661. message["Subject"] = subject
  662. message["Date"] = formatdate(localtime=True)
  663. # Add body text
  664. message.attach(MIMEText(body, "plain"))
  665. # Add ICS attachment if provided
  666. if ics_attachment:
  667. ical_attachment = ics_attachment.prepare_email_part()
  668. message.attach(ical_attachment)
  669. # Convert message to text
  670. text = message.as_string()
  671. try:
  672. if self.security == SMTP_SECURITY_TYPE_ENUM.EMPTY:
  673. logger.warning("SMTP security type is empty, raising ValueError.")
  674. raise ValueError("SMTP security type cannot be empty. Please specify a valid security type.")
  675. elif self.security == SMTP_SECURITY_TYPE_ENUM.NONE:
  676. server = smtplib.SMTP(host=self.host, port=self.port)
  677. elif self.security == SMTP_SECURITY_TYPE_ENUM.STARTTLS:
  678. context = self._build_context()
  679. server = smtplib.SMTP(host=self.host, port=self.port)
  680. server.ehlo() # Identify self to server
  681. server.starttls(context=context) # Start TLS connection
  682. server.ehlo() # Identify again after starting TLS
  683. elif self.security == SMTP_SECURITY_TYPE_ENUM.TLS:
  684. context = self._build_context()
  685. server = smtplib.SMTP_SSL(host=self.host, port=self.port, context=context)
  686. if self.username and self.password:
  687. logger.debug("Logging in to SMTP server with username: %s", self.username)
  688. server.login(user=self.username, password=self.password)
  689. errors: Dict[str, Tuple[int, bytes]] = server.sendmail(from_addr=self.from_email, to_addrs=to_addresses,
  690. msg=text)
  691. logger.debug("Email sent successfully to %s", to_addresses)
  692. server.quit()
  693. except smtplib.SMTPException as e:
  694. logger.error(f"SMTP error occurred: {e}")
  695. return False
  696. if errors:
  697. for email, (code, error) in errors.items():
  698. logger.error(f"Failed to send email to {email}: {str(error)} (Code: {code})")
  699. return False
  700. return True
  701. def _read_event(vobject_data: str) -> EmailEvent:
  702. """
  703. Read the vobject item from the provided string and create an EmailEvent.
  704. """
  705. v_cal: vobject.base.Component = vobject.readOne(vobject_data)
  706. cal: Calendar = Calendar(vobject_item=v_cal)
  707. event: Event = cal.event # type: ignore
  708. return EmailEvent(
  709. event=event,
  710. ics_content=vobject_data,
  711. ics_file_name="event.ics"
  712. )
  713. class Hook(BaseHook):
  714. def __init__(self, configuration):
  715. super().__init__(configuration)
  716. self.email_config = EmailConfig(
  717. host=self.configuration.get("hook", "smtp_server"),
  718. port=self.configuration.get("hook", "smtp_port"),
  719. security=self.configuration.get("hook", "smtp_security"),
  720. ssl_verify_mode=self.configuration.get("hook", "smtp_ssl_verify_mode"),
  721. username=self.configuration.get("hook", "smtp_username"),
  722. password=self.configuration.get("hook", "smtp_password"),
  723. from_email=self.configuration.get("hook", "from_email"),
  724. send_mass_emails=self.configuration.get("hook", "mass_email"),
  725. dryrun=self.configuration.get("hook", "dryrun"),
  726. new_or_added_to_event_template=MessageTemplate(
  727. subject="You have been added to an event",
  728. body=self.configuration.get("hook", "new_or_added_to_event_template")
  729. ),
  730. deleted_or_removed_from_event_template=MessageTemplate(
  731. subject="An event you were invited to has been deleted",
  732. body=self.configuration.get("hook", "deleted_or_removed_from_event_template")
  733. ),
  734. updated_event_template=MessageTemplate(
  735. subject="An event you are invited to has been updated",
  736. body=self.configuration.get("hook", "updated_event_template")
  737. )
  738. )
  739. logger.info(
  740. "Email hook initialized with configuration: %s",
  741. self.email_config
  742. )
  743. def notify(self, notification_item) -> None:
  744. """
  745. Entrypoint for processing a single notification item.
  746. Overrides default notify method from BaseHook.
  747. Triggered by Radicale when a notifiable event occurs (e.g. item added, updated or deleted)
  748. """
  749. if isinstance(notification_item, HookNotificationItem):
  750. self._process_event_and_notify(notification_item)
  751. def _process_event_and_notify(self, notification_item: HookNotificationItem) -> None:
  752. """
  753. Process the event and send an email notification.
  754. :param notification_item: The single item to process.
  755. :type notification_item: HookNotificationItem
  756. :return: None
  757. """
  758. if self.dryrun:
  759. logger.warning("Hook 'email': DRY-RUN received notification_item: %r", vars(notification_item))
  760. else:
  761. logger.debug("Received notification_item: %r", vars(notification_item))
  762. try:
  763. notification_type = HookNotificationItemTypes(value=notification_item.type)
  764. except ValueError:
  765. logger.warning("Unknown notification item type: %s", notification_item.type)
  766. return
  767. if notification_type == HookNotificationItemTypes.CPATCH:
  768. # Ignore cpatch notifications (PROPPATCH requests for WebDAV metadata updates)
  769. return
  770. elif notification_type == HookNotificationItemTypes.UPSERT:
  771. # Handle upsert notifications
  772. new_item_str: str = notification_item.new_content # type: ignore # A serialized vobject.base.Component
  773. previous_item_str: Optional[str] = notification_item.old_content
  774. if not ics_contents_contains_event(contents=new_item_str):
  775. # If ICS file does not contain an event, do not send any notifications (regardless of previous content).
  776. logger.debug("No event found in the ICS file, skipping notification.")
  777. return
  778. email_event: EmailEvent = _read_event(vobject_data=new_item_str) # type: ignore
  779. if not previous_item_str:
  780. # Dealing with a completely new event, no previous content to compare against.
  781. # Email every attendee about the new event.
  782. logger.debug("New event detected, sending notifications to all attendees.")
  783. email_success: bool = self.email_config.send_added_email( # type: ignore
  784. attendees=email_event.event.attendees,
  785. event=email_event
  786. )
  787. if not email_success:
  788. logger.error("Failed to send some or all added email notifications for event: %s", email_event.event.uid)
  789. return
  790. # Dealing with an update to an existing event, compare new and previous content.
  791. new_event: Event = read_ics_event(contents=new_item_str)
  792. previous_event: Optional[Event] = read_ics_event(contents=previous_item_str)
  793. if not previous_event:
  794. # If we cannot parse the previous event for some reason, simply treat it as a new event.
  795. logger.warning("Previous event content could not be parsed, treating as a new event.")
  796. email_success: bool = self.email_config.send_added_email( # type: ignore
  797. attendees=email_event.event.attendees,
  798. event=email_event
  799. )
  800. if not email_success:
  801. logger.error("Failed to send some or all added email notifications for event: %s", email_event.event.uid)
  802. return
  803. # Determine added, removed, and unaltered attendees
  804. added_attendees, removed_attendees, unaltered_attendees = determine_added_removed_and_unaltered_attendees(
  805. original_event=previous_event, new_event=new_event)
  806. # Notify added attendees as "event created"
  807. if added_attendees:
  808. email_success: bool = self.email_config.send_added_email( # type: ignore
  809. attendees=added_attendees,
  810. event=email_event
  811. )
  812. if not email_success:
  813. logger.error("Failed to send some or all added email notifications for event: %s", email_event.event.uid)
  814. # Notify removed attendees as "event deleted"
  815. if removed_attendees:
  816. email_success: bool = self.email_config.send_deleted_email( # type: ignore
  817. attendees=removed_attendees,
  818. event=email_event
  819. )
  820. if not email_success:
  821. logger.error("Failed to send some or all removed email notifications for event: %s", email_event.event.uid)
  822. # Notify unaltered attendees as "event updated"
  823. if unaltered_attendees:
  824. # TODO: Determine WHAT was updated in the event and send a more specific message if needed
  825. # TODO: Don't send an email to unaltered attendees if only change was adding/removing other attendees
  826. email_success: bool = self.email_config.send_updated_email( # type: ignore
  827. attendees=unaltered_attendees,
  828. event=email_event
  829. )
  830. if not email_success:
  831. logger.error("Failed to send some or all updated email notifications for event: %s", email_event.event.uid)
  832. return
  833. elif notification_type == HookNotificationItemTypes.DELETE:
  834. # Handle delete notifications
  835. deleted_item_str: str = notification_item.old_content # type: ignore # A serialized vobject.base.Component
  836. if not ics_contents_contains_event(contents=deleted_item_str):
  837. # If the ICS file does not contain an event, we do not send any notifications.
  838. logger.debug("No event found in the ICS file, skipping notification.")
  839. return
  840. email_event: EmailEvent = _read_event(vobject_data=deleted_item_str) # type: ignore
  841. email_success: bool = self.email_config.send_deleted_email( # type: ignore
  842. attendees=email_event.event.attendees,
  843. event=email_event
  844. )
  845. if not email_success:
  846. logger.error("Failed to send some or all deleted email notifications for event: %s", email_event.event.uid)
  847. return
  848. return