1"""CAL-ADDRESS values from :rfc:`5545`."""
2
3from typing import Any, ClassVar
4
5from icalendar.compatibility import Self
6from icalendar.error import JCalParsingError
7from icalendar.parser import Parameters
8from icalendar.parser_tools import DEFAULT_ENCODING, to_unicode
9
10
11class vCalAddress(str):
12 r"""Calendar User Address
13
14 Value Name:
15 CAL-ADDRESS
16
17 Purpose:
18 This value type is used to identify properties that contain a
19 calendar user address.
20
21 Description:
22 The value is a URI as defined by [RFC3986] or any other
23 IANA-registered form for a URI. When used to address an Internet
24 email transport address for a calendar user, the value MUST be a
25 mailto URI, as defined by [RFC2368].
26
27 Example:
28 ``mailto:`` is in front of the address.
29
30 .. code-block:: ics
31
32 mailto:jane_doe@example.com
33
34 Parsing:
35
36 .. code-block:: pycon
37
38 >>> from icalendar import vCalAddress
39 >>> cal_address = vCalAddress.from_ical('mailto:jane_doe@example.com')
40 >>> cal_address
41 vCalAddress('mailto:jane_doe@example.com')
42
43 Encoding:
44
45 .. code-block:: pycon
46
47 >>> from icalendar import vCalAddress, Event
48 >>> event = Event()
49 >>> jane = vCalAddress("mailto:jane_doe@example.com")
50 >>> jane.name = "Jane"
51 >>> event["organizer"] = jane
52 >>> print(event.to_ical().decode().replace('\\r\\n', '\\n').strip())
53 BEGIN:VEVENT
54 ORGANIZER;CN=Jane:mailto:jane_doe@example.com
55 END:VEVENT
56 """
57
58 default_value: ClassVar[str] = "CAL-ADDRESS"
59 params: Parameters
60 __slots__ = ("params",)
61
62 def __new__(
63 cls,
64 value: str | bytes,
65 encoding: str = DEFAULT_ENCODING,
66 /,
67 params: dict[str, Any] | None = None,
68 ) -> Self:
69 value = to_unicode(value, encoding=encoding)
70 if "\r" in value or "\n" in value:
71 raise ValueError(
72 f"A CAL-ADDRESS value may not contain CR or LF characters: {value!r}"
73 )
74 self = super().__new__(cls, value)
75 self.params = Parameters(params)
76 return self
77
78 def __repr__(self) -> str:
79 return f"vCalAddress('{self}')"
80
81 def to_ical(self) -> bytes:
82 return self.encode(DEFAULT_ENCODING)
83
84 @classmethod
85 def from_ical(cls, ical: str | bytes) -> Self:
86 return cls(ical)
87
88 @property
89 def ical_value(self) -> str:
90 """The ``mailto:`` part of the address."""
91 return str(self)
92
93 @property
94 def email(self) -> str:
95 """The email address without ``mailto:`` at the start."""
96 if self.lower().startswith("mailto:"):
97 return self[7:]
98 return str(self)
99
100 from icalendar.param import (
101 CN,
102 CUTYPE,
103 DELEGATED_FROM,
104 DELEGATED_TO,
105 DIR,
106 LANGUAGE,
107 PARTSTAT,
108 ROLE,
109 RSVP,
110 SENT_BY,
111 VALUE,
112 )
113
114 name = CN
115
116 @staticmethod
117 def _get_email(email: str) -> str:
118 """Extract email and add mailto: prefix if needed.
119
120 Handles case-insensitive mailto: prefix checking.
121
122 Parameters:
123 email: Email string that may or may not have mailto: prefix
124
125 Returns:
126 Email string with mailto: prefix
127 """
128 if not email.lower().startswith("mailto:"):
129 return f"mailto:{email}"
130 return email
131
132 @classmethod
133 def new(
134 cls,
135 email: str,
136 /,
137 cn: str | None = None,
138 cutype: str | None = None,
139 delegated_from: str | None = None,
140 delegated_to: str | None = None,
141 directory: str | None = None,
142 language: str | None = None,
143 partstat: str | None = None,
144 role: str | None = None,
145 rsvp: bool | None = None, # noqa: FBT001, RUF100
146 sent_by: str | None = None,
147 ) -> Self:
148 """Create a new vCalAddress with RFC 5545 parameters.
149
150 Creates a vCalAddress instance with automatic mailto: prefix handling
151 and support for all standard RFC 5545 parameters.
152
153 Parameters:
154 email: The email address (mailto: prefix added automatically if missing)
155 cn: Common Name parameter
156 cutype: Calendar user type (INDIVIDUAL, GROUP, RESOURCE, ROOM)
157 delegated_from: Email of the calendar user that delegated
158 delegated_to: Email of the calendar user that was delegated to
159 directory: Reference to directory information
160 language: Language for text values
161 partstat: Participation status (NEEDS-ACTION, ACCEPTED, DECLINED, etc.)
162 role: Role (REQ-PARTICIPANT, OPT-PARTICIPANT, NON-PARTICIPANT, CHAIR)
163 rsvp: Whether RSVP is requested
164 sent_by: Email of the calendar user acting on behalf of this user
165
166 Returns:
167 vCalAddress: A new calendar address with specified parameters
168
169 Raises:
170 TypeError: If email is not a string
171
172 Examples:
173 Basic usage:
174
175 >>> from icalendar.prop import vCalAddress
176 >>> addr = vCalAddress.new("test@test.com")
177 >>> str(addr)
178 'mailto:test@test.com'
179
180 With parameters:
181
182 >>> addr = vCalAddress.new("test@test.com", cn="Test User", role="CHAIR")
183 >>> addr.params["CN"]
184 'Test User'
185 >>> addr.params["ROLE"]
186 'CHAIR'
187 """
188 if not isinstance(email, str):
189 raise TypeError(f"Email must be a string, not {type(email).__name__}")
190
191 # Handle mailto: prefix (case-insensitive)
192 email_with_prefix = cls._get_email(email)
193
194 # Create the address
195 addr = cls(email_with_prefix)
196
197 # Set parameters if provided
198 if cn is not None:
199 addr.params["CN"] = cn
200 if cutype is not None:
201 addr.params["CUTYPE"] = cutype
202 if delegated_from is not None:
203 addr.params["DELEGATED-FROM"] = cls._get_email(delegated_from)
204 if delegated_to is not None:
205 addr.params["DELEGATED-TO"] = cls._get_email(delegated_to)
206 if directory is not None:
207 addr.params["DIR"] = directory
208 if language is not None:
209 addr.params["LANGUAGE"] = language
210 if partstat is not None:
211 addr.params["PARTSTAT"] = partstat
212 if role is not None:
213 addr.params["ROLE"] = role
214 if rsvp is not None:
215 addr.params["RSVP"] = "TRUE" if rsvp else "FALSE"
216 if sent_by is not None:
217 addr.params["SENT-BY"] = cls._get_email(sent_by)
218
219 return addr
220
221 def to_jcal(self, name: str) -> list:
222 """Return this property in jCal format."""
223 return [name, self.params.to_jcal(), self.VALUE.lower(), self.ical_value]
224
225 @classmethod
226 def examples(cls) -> list[Self]:
227 """Examples of vCalAddress."""
228 return [cls.new("you@example.org", cn="You There")]
229
230 @classmethod
231 def from_jcal(cls, jcal_property: list) -> Self:
232 """Parse jCal from :rfc:`7265`.
233
234 Parameters:
235 jcal_property: The jCal property to parse.
236
237 Raises:
238 ~error.JCalParsingError: If the provided jCal is invalid.
239 """
240 JCalParsingError.validate_property(jcal_property, cls)
241 JCalParsingError.validate_value_type(jcal_property[3], str, cls, 3)
242 return cls(
243 jcal_property[3],
244 params=Parameters.from_jcal_property(jcal_property),
245 )
246
247
248__all__ = ["vCalAddress"]