__init__.py 43 KB

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