Debian Codegraph @

src/desktop/email.rs

raw
1 //! Compose an email.
2 //!
3 //! Wrapper of the DBus interface: [`org.freedesktop.portal.Email`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Email.html).
4 //!
5 //! # Examples
6 //!
7 //! Compose an email
8 //!
9 //! ```rust,no_run
10 //! use std::{fs::File, os::fd::OwnedFd};
11 //!
12 //! use ashpd::desktop::email::EmailRequest;
13 //!
14 //! async fn run() -> ashpd::Result<()> {
15 //! let file = File::open("/home/bilelmoussaoui/Downloads/adwaita-night.jpg").unwrap();
16 //! EmailRequest::default()
17 //! .address("[email protected]")
18 //! .subject("email subject")
19 //! .body("the pre-filled email body")
20 //! .attach(OwnedFd::from(file))
21 //! .send()
22 //! .await;
23 //! Ok(())
24 //! }
25 //! ```
26
27 use std::os::fd::OwnedFd;
28
29 use serde::{Deserialize, Serialize};
30 use zbus::zvariant::{
31 self, Optional, Type,
32 as_value::{self, optional},
33 };
34
35 use super::{HandleToken, Request};
36 use crate::{ActivationToken, Error, Uri, WindowIdentifier, proxy::Proxy};
37
38 /// Options for composing an email.
39 #[derive(Serialize, Deserialize, Type, Debug, Default)]
40 #[zvariant(signature = "dict")]
41 pub struct EmailOptions {
42 #[serde(with = "as_value", skip_deserializing)]
43 handle_token: HandleToken,
44 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
45 address: Option<String>,
46 #[serde(default, with = "as_value", skip_serializing_if = "Vec::is_empty")]
47 addresses: Vec<String>,
48 #[serde(default, with = "as_value", skip_serializing_if = "Vec::is_empty")]
49 cc: Vec<String>,
50 #[serde(default, with = "as_value", skip_serializing_if = "Vec::is_empty")]
51 bcc: Vec<String>,
52 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
53 subject: Option<String>,
54 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
55 body: Option<String>,
56 #[serde(
57 with = "as_value",
58 skip_serializing_if = "Vec::is_empty",
59 skip_deserializing
60 )]
61 attachment_fds: Vec<zvariant::OwnedFd>,
62 #[serde(default, with = "as_value", skip_serializing)]
63 #[cfg_attr(not(feature = "backend"), allow(dead_code))]
64 attachments: Vec<Uri>,
65 #[serde(default, with = "optional", skip_serializing_if = "Option::is_none")]
66 activation_token: Option<ActivationToken>,
67 }
68
69 impl EmailOptions {
70 /// Gets the email address.
71 #[cfg(feature = "backend")]
72 pub fn address(&self) -> Option<&str> {
73 self.address.as_deref()
74 }
75
76 /// Gets the list of email addresses.
77 #[cfg(feature = "backend")]
78 pub fn addresses(&self) -> &[String] {
79 &self.addresses
80 }
81
82 /// Gets the list of CC email addresses.
83 #[cfg(feature = "backend")]
84 pub fn cc(&self) -> &[String] {
85 &self.cc
86 }
87
88 /// Gets the list of BCC email addresses.
89 #[cfg(feature = "backend")]
90 pub fn bcc(&self) -> &[String] {
91 &self.bcc
92 }
93
94 /// Gets the email subject.
95 #[cfg(feature = "backend")]
96 pub fn subject(&self) -> Option<&str> {
97 self.subject.as_deref()
98 }
99
100 /// Gets the email body.
101 #[cfg(feature = "backend")]
102 pub fn body(&self) -> Option<&str> {
103 self.body.as_deref()
104 }
105
106 /// Gets the list of attachment URIs.
107 #[cfg(feature = "backend")]
108 pub fn attachments(&self) -> &[Uri] {
109 &self.attachments
110 }
111
112 /// Gets the activation token.
113 #[cfg(feature = "backend")]
114 pub fn activation_token(&self) -> Option<&ActivationToken> {
115 self.activation_token.as_ref()
116 }
117 }
118
119 /// Wrapper of the DBus interface: [`org.freedesktop.portal.Email`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Email.html).
120 #[derive(Debug)]
121 #[doc(alias = "org.freedesktop.portal.Email")]
122 pub struct EmailProxy(Proxy<'static>);
123
124 impl EmailProxy {
125 /// Create a new instance of [`EmailProxy`].
126 pub async fn new() -> Result<Self, Error> {
127 let proxy = Proxy::new_desktop("org.freedesktop.portal.Email").await?;
128 Ok(Self(proxy))
129 }
130
131 /// Create a new instance of [`EmailProxy`].
132 pub async fn with_connection(connection: zbus::Connection) -> Result<Self, Error> {
133 let proxy =
134 Proxy::new_desktop_with_connection(connection, "org.freedesktop.portal.Email").await?;
135 Ok(Self(proxy))
136 }
137
138 /// Returns the version of the portal interface.
139 pub fn version(&self) -> u32 {
140 self.0.version()
141 }
142
143 /// Presents a window that lets the user compose an email.
144 ///
145 /// **Note** the default email client for the host will need to support
146 /// `mailto:` URIs following RFC 2368.
147 ///
148 /// # Arguments
149 ///
150 /// * `identifier` - Identifier for the application window.
151 /// * `options` - An [`EmailOptions`].
152 ///
153 /// # Specifications
154 ///
155 /// See also [`ComposeEmail`](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Email.html#org-freedesktop-portal-email-composeemail).
156 #[doc(alias = "ComposeEmail")]
157 pub async fn compose(
158 &self,
159 identifier: Option<&WindowIdentifier>,
160 options: EmailOptions,
161 ) -> Result<Request<()>, Error> {
162 let identifier = Optional::from(identifier);
163 self.0
164 .empty_request(
165 &options.handle_token,
166 "ComposeEmail",
167 &(identifier, &options),
168 )
169 .await
170 }
171 }
172
173 impl std::ops::Deref for EmailProxy {
174 type Target = zbus::Proxy<'static>;
175
176 fn deref(&self) -> &Self::Target {
177 &self.0
178 }
179 }
180
181 #[derive(Debug, Default)]
182 #[doc(alias = "xdp_portal_compose_email")]
183 /// A [builder-pattern] type to compose an email.
184 ///
185 /// [builder-pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
186 pub struct EmailRequest {
187 identifier: Option<WindowIdentifier>,
188 options: EmailOptions,
189 connection: Option<zbus::Connection>,
190 }
191
192 impl EmailRequest {
193 /// Sets a window identifier.
194 #[must_use]
195 pub fn identifier(mut self, identifier: impl Into<Option<WindowIdentifier>>) -> Self {
196 self.identifier = identifier.into();
197 self
198 }
199
200 /// Sets the email address to send the email to.
201 #[must_use]
202 pub fn address<'a>(mut self, address: impl Into<Option<&'a str>>) -> Self {
203 self.options.address = address.into().map(ToOwned::to_owned);
204 self
205 }
206
207 /// Sets a list of email addresses to send the email to.
208 #[must_use]
209 pub fn addresses<P: IntoIterator<Item = I>, I: AsRef<str> + Type + Serialize>(
210 mut self,
211 addresses: impl Into<Option<P>>,
212 ) -> Self {
213 if let Some(a) = addresses.into() {
214 self.options.addresses = a.into_iter().map(|s| s.as_ref().to_owned()).collect();
215 }
216 self
217 }
218
219 /// Sets a list of email addresses to BCC.
220 #[must_use]
221 pub fn bcc<P: IntoIterator<Item = I>, I: AsRef<str> + Type + Serialize>(
222 mut self,
223 bcc: impl Into<Option<P>>,
224 ) -> Self {
225 if let Some(a) = bcc.into() {
226 self.options.bcc = a.into_iter().map(|s| s.as_ref().to_owned()).collect();
227 }
228 self
229 }
230
231 /// Sets a list of email addresses to CC.
232 #[must_use]
233 pub fn cc<P: IntoIterator<Item = I>, I: AsRef<str> + Type + Serialize>(
234 mut self,
235 cc: impl Into<Option<P>>,
236 ) -> Self {
237 if let Some(a) = cc.into() {
238 self.options.cc = a.into_iter().map(|s| s.as_ref().to_owned()).collect();
239 }
240 self
241 }
242
243 /// Sets the email subject.
244 #[must_use]
245 pub fn subject<'a>(mut self, subject: impl Into<Option<&'a str>>) -> Self {
246 self.options.subject = subject.into().map(ToOwned::to_owned);
247 self
248 }
249
250 /// Sets the email body.
251 #[must_use]
252 pub fn body<'a>(mut self, body: impl Into<Option<&'a str>>) -> Self {
253 self.options.body = body.into().map(ToOwned::to_owned);
254 self
255 }
256
257 #[must_use]
258 /// Attaches multiple files to the email.
259 pub fn attach_multiple(
260 mut self,
261 attachments: impl IntoIterator<Item = impl Into<OwnedFd>>,
262 ) -> Self {
263 self.options.attachment_fds = attachments
264 .into_iter()
265 .map(|fd| zvariant::OwnedFd::from(fd.into()))
266 .collect();
267 self
268 }
269
270 /// Attaches a file to the email.
271 #[must_use]
272 pub fn attach(mut self, attachment: OwnedFd) -> Self {
273 self.add_attachment(attachment);
274 self
275 }
276
277 /// Sets the token that can be used to activate the chosen application.
278 #[must_use]
279 pub fn activation_token(
280 mut self,
281 activation_token: impl Into<Option<ActivationToken>>,
282 ) -> Self {
283 self.options.activation_token = activation_token.into();
284 self
285 }
286
287 /// A different variant of [`Self::attach`].
288 pub fn add_attachment(&mut self, attachment: OwnedFd) {
289 let attachment = zvariant::OwnedFd::from(attachment);
290 self.options.attachment_fds.push(attachment);
291 }
292
293 #[must_use]
294 /// Sets a connection to use other than the internal one.
295 pub fn connection(mut self, connection: Option<zbus::Connection>) -> Self {
296 self.connection = connection;
297 self
298 }
299
300 /// Send the request.
301 pub async fn send(mut self) -> Result<Request<()>, Error> {
302 let proxy = if let Some(connection) = self.connection {
303 EmailProxy::with_connection(connection).await?
304 } else {
305 EmailProxy::new().await?
306 };
307
308 // activation_token requires version 4
309 if proxy.version() < 4 {
310 self.options.activation_token = None;
311 }
312
313 proxy.compose(self.identifier.as_ref(), self.options).await
314 }
315 }