ffrelay-api 0.0.4

Rust API client library for Firefox Relay email forwarding service
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! Firefox Relay API client implementation.

use log::info;
use reqwest::Client;

use crate::{
    error::{Error, Result},
    types::{FirefoxEmailRelay, FirefoxEmailRelayRequest, FirefoxRelayProfile},
};

/// The main API client for interacting with Firefox Relay.
///
/// This struct provides methods to create, list, and delete email relays,
/// as well as retrieve profile information.
///
/// # Example
///
/// ```no_run
/// use ffrelay_api::api::FFRelayApi;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let api = FFRelayApi::new("your-api-token");
/// let relays = api.list().await?;
/// # Ok(())
/// # }
/// ```
pub struct FFRelayApi {
    client: Client,
    token: String,
}

const FFRELAY_API_ENDPOINT: &str = "https://relay.firefox.com/api";

const FFRELAY_EMAIL_ENDPOINT: &str = "v1/relayaddresses";
const FFRELAY_EMAIL_DOMAIN_ENDPOINT: &str = "v1/domainaddresses";

impl FFRelayApi {
    /// Creates a new Firefox Relay API client.
    ///
    /// # Arguments
    ///
    /// * `token` - Your Firefox Relay API token
    ///
    /// # Example
    ///
    /// ```
    /// use ffrelay_api::api::FFRelayApi;
    ///
    /// let api = FFRelayApi::new("your-api-token");
    /// ```
    pub fn new<T>(token: T) -> Self
    where
        T: Into<String>,
    {
        let client = Client::new();

        Self {
            client,
            token: token.into(),
        }
    }

    /// Enables or disables an email relay via the specified API endpoint.
    ///
    /// This is a private helper function used by `enable()` and `disable()`.
    ///
    /// # Arguments
    ///
    /// * `endpoint` - The API endpoint to use (either standard or domain relays)
    /// * `email_id` - The unique ID of the relay to toggle
    /// * `enabled` - Whether to enable (`true`) or disable (`false`) the relay
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP request fails or is rejected by the server.
    async fn toggle_with_endpoint(
        &self,
        endpoint: &str,
        email_id: u64,
        enabled: bool,
    ) -> Result<()> {
        let token = format!("Token {}", &self.token);
        let url = format!("{FFRELAY_API_ENDPOINT}/{endpoint}/{email_id}/");

        info!("url: {url}");

        let request = FirefoxEmailRelayRequest::builder().enabled(enabled).build();

        let ret = self
            .client
            .patch(url)
            .header("content-type", "application/json")
            .header("authorization", token)
            .json(&request)
            .send()
            .await?;

        if ret.status().is_success() {
            Ok(())
        } else {
            Err(Error::EmailUpdateFailure {
                http_status: ret.status().as_u16(),
            })
        }
    }

    async fn create_with_endpoint(
        &self,
        endpoint: &str,
        request: FirefoxEmailRelayRequest,
    ) -> Result<String> {
        let token = format!("Token {}", &self.token);
        let url = format!("{FFRELAY_API_ENDPOINT}/{endpoint}/");

        info!("url: {url}");

        let resp_dict = self
            .client
            .post(url)
            .header("content-type", "application/json")
            .header("authorization", token)
            .json(&request)
            .send()
            .await?
            .json::<serde_json::Value>()
            .await?;

        //dbg!(&resp_dict);

        let res: FirefoxEmailRelay = serde_json::from_value(resp_dict)?;

        Ok(res.full_address)
    }

    async fn list_with_endpoint(&self, endpoint: &str) -> Result<Vec<FirefoxEmailRelay>> {
        let token = format!("Token {}", &self.token);

        let url = format!("{FFRELAY_API_ENDPOINT}/{endpoint}");

        let relay_array = self
            .client
            .get(url)
            .header("content-type", "application/json")
            .header("authorization", token)
            .send()
            .await?
            .json::<serde_json::Value>()
            .await?;

        //dbg!(&relay_array);

        let email_relays: Vec<FirefoxEmailRelay> = serde_json::from_value(relay_array)?;

        Ok(email_relays)
    }

    async fn delete_with_endpoint(&self, endpoint: &str, email_id: u64) -> Result<()> {
        let url = format!("{FFRELAY_API_ENDPOINT}/{endpoint}/{email_id}");

        let token = format!("Token {}", &self.token);

        let ret = self
            .client
            .delete(url)
            .header("content-type", "application/json")
            .header("authorization", token)
            .send()
            .await?;

        if ret.status().is_success() {
            Ok(())
        } else {
            Err(Error::EmailDeletionFailure {
                http_status: ret.status().as_u16(),
            })
        }
    }

    async fn find_email_relay(&self, email_id: u64) -> Result<FirefoxEmailRelay> {
        let relays = self.list().await?;

        for r in relays {
            if r.id == email_id {
                return Ok(r);
            }
        }

        Err(Error::RelayIdNotFound)
    }

    ////////////////////////////////////////////////////////////////////////////
    // PUBLIC
    ////////////////////////////////////////////////////////////////////////////

    /// Retrieves all Firefox Relay profiles associated with the API token.
    ///
    /// Returns detailed information about your Firefox Relay account including
    /// subscription status, usage statistics, and settings.
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP request fails or the response cannot be parsed.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ffrelay_api::api::FFRelayApi;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let api = FFRelayApi::new("your-api-token");
    /// let profiles = api.profiles().await?;
    /// for profile in profiles {
    ///     println!("Total masks: {}", profile.total_masks);
    ///     println!("Has premium: {}", profile.has_premium);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn profiles(&self) -> Result<Vec<FirefoxRelayProfile>> {
        let url = "https://relay.firefox.com/api/v1/profiles/";
        let token = format!("Token {}", &self.token);

        let profiles_dict = self
            .client
            .get(url)
            .header("content-type", "application/json")
            .header("authorization", token)
            .send()
            .await?
            .json::<serde_json::Value>()
            .await?;

        //dbg!(&profiles_dict);

        let profiles: Vec<FirefoxRelayProfile> = serde_json::from_value(profiles_dict)?;

        Ok(profiles)
    }

    /// Creates a new email relay (alias).
    ///
    /// Creates either a random relay (ending in @mozmail.com) or a custom domain
    /// relay if you have a premium subscription and provide an address.
    ///
    /// # Arguments
    ///
    /// * `request` - Configuration for the new relay including description and optional custom address
    ///
    /// # Returns
    ///
    /// The full email address of the newly created relay.
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP request fails, the response cannot be parsed,
    /// or you've reached your relay limit.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ffrelay_api::api::FFRelayApi;
    /// use ffrelay_api::types::FirefoxEmailRelayRequest;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let api = FFRelayApi::new("your-api-token");
    ///
    /// // Create a random relay
    /// let request = FirefoxEmailRelayRequest::builder()
    ///     .description("For shopping sites".to_string())
    ///     .build();
    /// let email = api.create(request).await?;
    /// println!("Created: {}", email);
    ///
    /// // Create a custom domain relay (requires premium)
    /// let request = FirefoxEmailRelayRequest::builder()
    ///     .description("Newsletter".to_string())
    ///     .address("newsletter".to_string())
    ///     .build();
    /// let email = api.create(request).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn create(&self, request: FirefoxEmailRelayRequest) -> Result<String> {
        let endpoint = if request.address.is_some() {
            FFRELAY_EMAIL_DOMAIN_ENDPOINT
        } else {
            FFRELAY_EMAIL_ENDPOINT
        };

        self.create_with_endpoint(endpoint, request).await
    }

    /// Lists all email relays (both random and domain relays).
    ///
    /// Retrieves all active email relays associated with your account,
    /// including both standard relays (@mozmail.com) and custom domain relays.
    ///
    /// # Returns
    ///
    /// A vector of all email relays with their statistics and metadata.
    ///
    /// # Errors
    ///
    /// Returns an error only if both standard and domain relay requests fail.
    /// If one succeeds, returns the available relays.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ffrelay_api::api::FFRelayApi;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let api = FFRelayApi::new("your-api-token");
    /// let relays = api.list().await?;
    /// for relay in relays {
    ///     println!("{}: {} (forwarded: {})",
    ///         relay.id,
    ///         relay.full_address,
    ///         relay.num_forwarded
    ///     );
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list(&self) -> Result<Vec<FirefoxEmailRelay>> {
        let mut relays = vec![];

        if let Ok(email_relays) = self.list_with_endpoint(FFRELAY_EMAIL_ENDPOINT).await {
            relays.extend(email_relays);
        }

        if let Ok(domain_relays) = self.list_with_endpoint(FFRELAY_EMAIL_DOMAIN_ENDPOINT).await {
            relays.extend(domain_relays);
        }

        Ok(relays)
    }

    /// Deletes an email relay by its ID.
    ///
    /// Permanently removes the specified email relay. The relay will stop
    /// forwarding emails immediately. This action cannot be undone.
    ///
    /// # Arguments
    ///
    /// * `email_id` - The unique ID of the relay to delete
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The relay ID is not found
    /// - The HTTP request fails
    /// - The deletion request is rejected by the server
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ffrelay_api::api::FFRelayApi;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let api = FFRelayApi::new("your-api-token");
    ///
    /// // Delete a relay by ID
    /// api.delete(12345678).await?;
    /// println!("Relay deleted successfully");
    /// # Ok(())
    /// # }
    /// ```
    pub async fn delete(&self, email_id: u64) -> Result<()> {
        let relay = self.find_email_relay(email_id).await?;

        let endpoint = if relay.is_domain() {
            FFRELAY_EMAIL_DOMAIN_ENDPOINT
        } else {
            FFRELAY_EMAIL_ENDPOINT
        };

        self.delete_with_endpoint(endpoint, email_id).await
    }

    /// Disables an email relay by its ID.
    ///
    /// When a relay is disabled, it will stop forwarding emails but remain in your
    /// account. You can re-enable it later without losing its statistics or configuration.
    ///
    /// # Arguments
    ///
    /// * `email_id` - The unique ID of the relay to disable
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The relay ID is not found
    /// - The HTTP request fails
    /// - The update request is rejected by the server
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ffrelay_api::api::FFRelayApi;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let api = FFRelayApi::new("your-api-token");
    ///
    /// // Disable a relay temporarily
    /// api.disable(12345678).await?;
    /// println!("Relay disabled successfully");
    /// # Ok(())
    /// # }
    /// ```
    pub async fn disable(&self, email_id: u64) -> Result<()> {
        let relay = self.find_email_relay(email_id).await?;

        let endpoint = if relay.is_domain() {
            FFRELAY_EMAIL_DOMAIN_ENDPOINT
        } else {
            FFRELAY_EMAIL_ENDPOINT
        };

        self.toggle_with_endpoint(endpoint, email_id, false).await
    }

    /// Enables an email relay by its ID.
    ///
    /// When a relay is enabled, it will start forwarding emails to your real email address.
    /// This is useful for re-enabling a previously disabled relay.
    ///
    /// # Arguments
    ///
    /// * `email_id` - The unique ID of the relay to enable
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The relay ID is not found
    /// - The HTTP request fails
    /// - The update request is rejected by the server
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ffrelay_api::api::FFRelayApi;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let api = FFRelayApi::new("your-api-token");
    ///
    /// // Enable a previously disabled relay
    /// api.enable(12345678).await?;
    /// println!("Relay enabled successfully");
    /// # Ok(())
    /// # }
    /// ```
    pub async fn enable(&self, email_id: u64) -> Result<()> {
        let relay = self.find_email_relay(email_id).await?;

        let endpoint = if relay.is_domain() {
            FFRELAY_EMAIL_DOMAIN_ENDPOINT
        } else {
            FFRELAY_EMAIL_ENDPOINT
        };

        self.toggle_with_endpoint(endpoint, email_id, true).await
    }
}