ashpd 0.2.0-alpha-2

XDG portals wrapper in Rust using zbus
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! # Examples
//!
//! ```rust,no_run
//! use ashpd::documents::{DocumentsProxy, Permission};
//!
//! async fn run() -> Result<(), ashpd::Error> {
//!     let connection = zbus::azync::Connection::new_session().await?;
//!     let proxy = DocumentsProxy::new(&connection).await?;
//!
//!     println!("{:#?}", proxy.mount_point().await?);
//!
//!     for (doc_id, host_path) in proxy.list("org.mozilla.firefox").await? {
//!         if doc_id == "f2ee988d" {
//!             let info = proxy.info(&doc_id).await?;
//!             println!("{:#?}", info);
//!         }
//!     }
//!
//!     proxy
//!         .grant_permissions(
//!             "f2ee988d",
//!             "org.mozilla.firefox",
//!             &[Permission::GrantPermissions],
//!         )
//!         .await?;
//!     proxy
//!         .revoke_permissions("f2ee988d", "org.mozilla.firefox", &[Permission::Write])
//!         .await?;
//!
//!     proxy.delete("f2ee988d").await?;
//!
//!     Ok(())
//! }
//! ```

pub(crate) const DESTINATION: &str = "org.freedesktop.portal.Documents";
pub(crate) const PATH: &str = "/org/freedesktop/portal/documents";

use crate::{helpers::call_method, Error};
use enumflags2::BitFlags;
use serde::{de::Deserializer, Deserialize, Serialize, Serializer};
use serde_repr::{Deserialize_repr, Serialize_repr};
use std::{collections::HashMap, os::unix::prelude::AsRawFd};
use std::{fmt::Debug, str::FromStr};
use strum_macros::{AsRefStr, EnumString, IntoStaticStr, ToString};
use zvariant::{Fd, Signature};
use zvariant_derive::Type;

#[derive(Serialize_repr, Deserialize_repr, PartialEq, Copy, Clone, BitFlags, Debug, Type)]
#[repr(u32)]
///
pub enum Flags {
    /// Reuse the existing document store entry for the file.
    ReuseExisting = 1,
    /// Persistent file.
    Persistent = 2,
    /// Depends on the application needs.
    AsNeededByApp = 4,
    /// Export a directory.
    ExportDirectory = 8,
}

/// A [`HashMap`] mapping application IDs to the permissions for that application
pub type Permissions = HashMap<String, Vec<Permission>>;

#[derive(Debug, Clone, AsRefStr, EnumString, IntoStaticStr, ToString, PartialEq, Eq)]
#[strum(serialize_all = "lowercase")]
/// The possible permissions to grant to a specific application for a specific
/// document.
pub enum Permission {
    /// Read access.
    Read,
    /// Write access.
    Write,
    #[strum(serialize = "grant-permissions")]
    /// The possibility to grant new permissions to the file.
    GrantPermissions,
    /// Delete access.
    Delete,
}

impl zvariant::Type for Permission {
    fn signature() -> Signature<'static> {
        String::signature()
    }
}

impl Serialize for Permission {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        String::serialize(&self.to_string(), serializer)
    }
}

impl<'de> Deserialize<'de> for Permission {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(Permission::from_str(&String::deserialize(deserializer)?).expect("invalid permission"))
    }
}

/// The interface lets sandboxed applications make files from the outside world
/// available to sandboxed applications in a controlled way.
///
/// Exported files will be made accessible to the application via a fuse
/// filesystem that gets mounted at `/run/user/$UID/doc/`. The filesystem gets
/// mounted both outside and inside the sandbox, but the view inside the sandbox
/// is restricted to just those files that the application is allowed to access.
///
/// Individual files will appear at `/run/user/$UID/doc/$DOC_ID/filename`,
/// where `$DOC_ID` is the ID of the file in the document store.
/// It is returned by the [`DocumentsProxy::add`] and [`DocumentsProxy::add_named`] calls.
///
/// The permissions that the application has for a document store entry (see
/// [`DocumentsProxy::grant_permissions`]) are reflected in the POSIX mode bits in the fuse
/// filesystem.
///
/// Wrapper of the DBus interface: [`org.freedesktop.portal.Documents`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-org.freedesktop.portal.Documents).
#[derive(Debug)]
#[doc(alias = "org.freedesktop.portal.Documents")]
pub struct DocumentsProxy<'a>(zbus::azync::Proxy<'a>);

impl<'a> DocumentsProxy<'a> {
    /// Create a new instance of [`DocumentsProxy`].
    pub async fn new(connection: &zbus::azync::Connection) -> Result<DocumentsProxy<'a>, Error> {
        let proxy = zbus::ProxyBuilder::new_bare(connection)
            .interface("org.freedesktop.portal.Documents")
            .path(PATH)?
            .destination(DESTINATION)
            .build_async()
            .await?;
        Ok(Self(proxy))
    }

    /// Get a reference to the underlying Proxy.
    pub fn inner(&self) -> &zbus::azync::Proxy<'_> {
        &self.0
    }

    /// Adds a file to the document store.
    /// The file is passed in the form of an open file descriptor
    /// to prove that the caller has access to the file.
    ///
    /// # Arguments
    ///
    /// * `o_path_fd` - Open file descriptor for the file to add.
    /// * `reuse_existing` - Whether to reuse an existing document store entry for the file.
    /// * `persistent` - Whether to add the file only for this session or permanently.
    ///
    /// # Returns
    ///
    /// The ID of the file in the document store.
    ///
    /// # Specifications
    ///
    /// See also [`Add`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.Add).
    #[doc(alias = "Add")]
    pub async fn add<F>(
        &self,
        o_path_fd: &F,
        reuse_existing: bool,
        persistent: bool,
    ) -> Result<String, Error>
    where
        F: AsRawFd + Debug,
    {
        call_method(
            &self.0,
            "Add",
            &(Fd::from(o_path_fd.as_raw_fd()), reuse_existing, persistent),
        )
        .await
    }

    /// Adds multiple files to the document store.
    /// The files are passed in the form of an open file descriptor
    /// to prove that the caller has access to the file.
    ///
    /// # Arguments
    ///
    /// * `o_path_fds` - Open file descriptors for the files to export.
    /// * `flags` - A [`Flags`].
    /// * `app_id` - An application ID, or empty string.
    /// * `permissions` - The permissions to grant.
    ///
    /// # Returns
    ///
    /// The IDs of the files in the document store along with other extra info.
    ///
    /// # Specifications
    ///
    /// See also [`AddFull`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.AddFull).
    #[doc(alias = "AddFull")]
    pub async fn add_full<F: AsRawFd>(
        &self,
        o_path_fds: &[&F],
        flags: BitFlags<Flags>,
        app_id: &str,
        permissions: &[Permission],
    ) -> Result<(Vec<String>, HashMap<String, zvariant::OwnedValue>), Error> {
        let o_path: Vec<Fd> = o_path_fds.iter().map(|f| Fd::from(f.as_raw_fd())).collect();
        call_method(&self.0, "AddFull", &(o_path, flags, app_id, permissions)).await
    }

    /// Creates an entry in the document store for writing a new file.
    ///
    /// # Arguments
    ///
    /// * `o_path_parent_fd` - Open file descriptor for the parent directory.
    /// * `filename` - The basename for the file.
    /// * `reuse_existing` - Whether to reuse an existing document store entry for the file.
    /// * `persistent` - Whether to add the file only for this session or permanently.
    ///
    /// # Returns
    ///
    /// The ID of the file in the document store.
    ///
    /// # Specifications
    ///
    /// See also [`AddNamed`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.AddNamed).
    #[doc(alias = "AddNamed")]
    pub async fn add_named<F>(
        &self,
        o_path_parent_fd: &F,
        filename: &str,
        reuse_existing: bool,
        persistent: bool,
    ) -> Result<String, Error>
    where
        F: AsRawFd + Debug,
    {
        call_method(
            &self.0,
            "AddNamed",
            &(
                Fd::from(o_path_parent_fd.as_raw_fd()),
                filename,
                reuse_existing,
                persistent,
            ),
        )
        .await
    }

    /// Adds multiple files to the document store.
    /// The files are passed in the form of an open file descriptor
    /// to prove that the caller has access to the file.
    ///
    /// # Arguments
    ///
    /// * `o_path_fd` - Open file descriptor for the parent directory.
    /// * `filename` - The basename for the file.
    /// * `flags` - A [`Flags`].
    /// * `app_id` - An application ID, or empty string.
    /// * `permissions` - The permissions to grant.
    ///
    /// # Returns
    ///
    /// The ID of the file in the document store along with other extra info.
    ///
    /// # Specifications
    ///
    /// See also [`AddNamedFull`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.AddNamedFull).
    #[doc(alias = "AddNamedFull")]
    pub async fn add_named_full<F>(
        &self,
        o_path_fd: &F,
        filename: &str,
        flags: BitFlags<Flags>,
        app_id: &str,
        permissions: &[Permission],
    ) -> Result<(String, HashMap<String, zvariant::OwnedValue>), Error>
    where
        F: AsRawFd + Debug,
    {
        call_method(
            &self.0,
            "AddNamedFull",
            &(
                Fd::from(o_path_fd.as_raw_fd()),
                filename,
                flags,
                app_id,
                permissions,
            ),
        )
        .await
    }

    /// Removes an entry from the document store. The file itself is not
    /// deleted.
    ///
    /// **Note** This call is available inside the sandbox if the
    /// application has the [`Permission::Delete`] for the document.
    ///
    /// # Arguments
    ///
    /// * `doc_id` - The ID of the file in the document store.
    ///
    /// # Specifications
    ///
    /// See also [`Delete`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.Delete).
    #[doc(alias = "Delete")]
    pub async fn delete(&self, doc_id: &str) -> Result<(), Error> {
        call_method(&self.0, "Delete", &(doc_id)).await
    }

    /// Returns the path at which the document store fuse filesystem is mounted.
    /// This will typically be `/run/user/$UID/doc/`.
    ///
    /// # Specifications
    ///
    /// See also [`GetMountPoint`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.GetMountPoint).
    #[doc(alias = "GetMountPoint")]
    #[doc(alias = "get_mount_point")]
    pub async fn mount_point(&self) -> Result<String, Error> {
        call_method(&self.0, "GetMountPoint", &()).await
    }

    /// Grants access permissions for a file in the document store to an
    /// application.
    ///
    /// **Note** This call is available inside the sandbox if the
    /// application has the [`Permission::GrantPermissions`] for the document.
    ///
    /// # Arguments
    ///
    /// * `doc_id` - The ID of the file in the document store.
    /// * `app_id` - The ID of the application to which permissions are granted.
    /// * `permissions` - The permissions to grant.
    ///
    /// # Specifications
    ///
    /// See also [`GrantPermissions`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.GrantPermissions).
    #[doc(alias = "GrantPermissions")]
    pub async fn grant_permissions(
        &self,
        doc_id: &str,
        app_id: &str,
        permissions: &[Permission],
    ) -> Result<(), Error> {
        call_method(&self.0, "GrantPermissions", &(doc_id, app_id, permissions)).await
    }

    /// Gets the filesystem path and application permissions for a document
    /// store entry.
    ///
    /// # Arguments
    ///
    /// * `doc_id` - The ID of the file in the document store.
    ///
    /// # Returns
    ///
    /// The path of the file in the host filesystem along with the [`Permissions`].
    ///
    /// # Specifications
    ///
    /// See also [`Info`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.Info).
    #[doc(alias = "Info")]
    pub async fn info(&self, doc_id: &str) -> Result<(String, Permissions), Error> {
        call_method(&self.0, "Info", &(doc_id)).await
    }

    /// Lists documents in the document store for an application (or for all
    /// applications).
    ///
    /// # Arguments
    ///
    /// * `app-id` - The application ID, or '' to list all documents.
    ///
    /// # Returns
    ///
    /// [`HashMap`] mapping document IDs to their filesystem path on the host system.
    ///
    /// # Specifications
    ///
    /// See also [`List`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.List).
    #[doc(alias = "List")]
    pub async fn list(&self, app_id: &str) -> Result<HashMap<String, String>, Error> {
        call_method(&self.0, "List", &(app_id)).await
    }

    /// Looks up the document ID for a file.
    ///
    /// **Note** This call is not available inside the sandbox.
    ///
    /// # Arguments
    ///
    /// * `filename` - A path in the host filesystem.
    ///
    /// # Returns
    ///
    /// The ID of the file in the document store, or [`None`] if the file is not in the document store.
    ///
    /// # Specifications
    ///
    /// See also [`Lookup`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.Lookup).
    #[doc(alias = "Lookup")]
    pub async fn lookup(&self, filename: &str) -> Result<Option<String>, Error> {
        let doc_id: String = call_method(&self.0, "Lookup", &(filename)).await?;
        if doc_id.is_empty() {
            Ok(None)
        } else {
            Ok(Some(doc_id))
        }
    }

    /// Revokes access permissions for a file in the document store from an
    /// application.
    ///
    /// **Note** This call is available inside the sandbox if the
    /// application has the [`Permission::GrantPermissions`] for the document.
    ///
    /// # Arguments
    ///
    /// * `doc_id` - The ID of the file in the document store.
    /// * `app_id` - The ID of the application from which the permissions are revoked.
    /// * `permissions` - The permissions to revoke.
    ///
    /// # Specifications
    ///
    /// See also [`RevokePermissions`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.RevokePermissions).
    #[doc(alias = "RevokePermissions")]
    pub async fn revoke_permissions(
        &self,
        doc_id: &str,
        app_id: &str,
        permissions: &[Permission],
    ) -> Result<(), Error> {
        call_method(&self.0, "RevokePermissions", &(doc_id, app_id, permissions)).await
    }
}

/// Interact with `org.freedesktop.portal.FileTransfer` interface.
mod file_transfer;

pub use file_transfer::FileTransferProxy;