anylist_rs 0.4.0

Interact with the grocery list management app AnyList's undocumented API. Unofficial.
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
use crate::error::{AnyListError, Result};
use crate::login::login;
use crate::utils::generate_id;
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
use serde_derive::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};

// ============================================================================
// Public types for persistence and events
// ============================================================================

/// Tokens that can be saved and restored for persistent sessions
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SavedTokens {
    pub(crate) access_token: String,
    pub(crate) refresh_token: String,
    pub(crate) user_id: String,
    pub(crate) is_premium_user: bool,
}

impl SavedTokens {
    pub fn new(
        access_token: impl Into<String>,
        refresh_token: impl Into<String>,
        user_id: impl Into<String>,
        is_premium_user: bool,
    ) -> Self {
        Self {
            access_token: access_token.into(),
            refresh_token: refresh_token.into(),
            user_id: user_id.into(),
            is_premium_user,
        }
    }

    pub fn access_token(&self) -> &str {
        &self.access_token
    }

    pub fn refresh_token(&self) -> &str {
        &self.refresh_token
    }

    pub fn user_id(&self) -> &str {
        &self.user_id
    }

    pub fn is_premium_user(&self) -> bool {
        self.is_premium_user
    }
}

/// Authentication events that can be monitored
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthEvent {
    /// Tokens were successfully refreshed
    TokensRefreshed,
    /// Token refresh failed
    RefreshFailed(String),
}

// ============================================================================
// Internal auth types
// ============================================================================

#[derive(Clone)]
struct AuthState {
    access_token: String,
    refresh_token: String,
    user_id: String,
    is_premium_user: bool,
    auto_refresh_enabled: bool,
}

/// Main client for interacting with the AnyList API.
///
/// Automatically manages authentication tokens and handles token refresh.
/// Use `export_tokens()` to persist sessions and `from_tokens()` to restore them.
///
/// # Example
///
/// ```no_run
/// use anylist_rs::AnyListClient;
///
/// #[tokio::main]
/// async fn main() {
///     // Login with email and password
///     let client = AnyListClient::login("user@example.com", "password")
///         .await
///         .expect("Failed to login");
///
///     // Use the client - tokens are managed automatically
///     let lists = client.get_lists().await.expect("Failed to get lists");
///
///     // Export tokens for later use
///     let tokens = client.export_tokens().expect("Failed to export");
///     // Save tokens to disk/keychain...
///
///     // Restore from saved tokens
///     let client = AnyListClient::from_tokens(tokens).expect("Failed to restore");
/// }
/// ```
pub struct AnyListClient {
    /// Internal authentication state (managed automatically)
    auth: Arc<Mutex<AuthState>>,
    /// Optional callback for auth events
    auth_event_callback: Option<Arc<dyn Fn(AuthEvent) + Send + Sync>>,
    /// Unique client identifier (UUID)
    client_identifier: String,
    /// HTTP client for making requests
    client: reqwest::Client,
}

impl AnyListClient {
    /// Create a new AnyList client by logging in with email and password.
    ///
    /// This automatically acquires access and refresh tokens.
    ///
    /// # Arguments
    ///
    /// * `email` - User's email address
    /// * `password` - User's password
    ///
    /// # Example
    ///
    /// ```no_run
    /// use anylist_rs::AnyListClient;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let client = AnyListClient::login("user@example.com", "password")
    ///         .await
    ///         .expect("Failed to authenticate");
    ///
    ///     let lists = client.get_lists().await.expect("Failed to get lists");
    /// }
    /// ```
    pub async fn login(email: &str, password: &str) -> Result<Self> {
        let client_identifier = generate_id();

        let login_result = login(email, password, &client_identifier)
            .await
            .map_err(|e| AnyListError::AuthenticationFailed(e.to_string()))?;

        let auth = Arc::new(Mutex::new(AuthState {
            access_token: login_result.access_token,
            refresh_token: login_result.refresh_token,
            user_id: login_result.user_id,
            is_premium_user: login_result.is_premium_user,
            auto_refresh_enabled: true,
        }));

        Ok(Self {
            auth,
            auth_event_callback: None,
            client_identifier,
            client: reqwest::Client::new(),
        })
    }

    /// Create an AnyList client from previously saved tokens.
    ///
    /// Use this to restore a session without logging in again.
    ///
    /// # Arguments
    ///
    /// * `tokens` - Previously saved tokens from `export_tokens()`
    ///
    /// # Example
    ///
    /// ```no_run
    /// use anylist_rs::{AnyListClient, SavedTokens};
    ///
    /// # fn load_from_keychain() -> Result<SavedTokens, Box<dyn std::error::Error>> { todo!() }
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // Load tokens from storage
    /// let tokens: SavedTokens = load_from_keychain()?;
    ///
    /// let client = AnyListClient::from_tokens(tokens)?;
    /// let lists = client.get_lists().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_tokens(tokens: SavedTokens) -> Result<Self> {
        let auth = Arc::new(Mutex::new(AuthState {
            access_token: tokens.access_token,
            refresh_token: tokens.refresh_token,
            user_id: tokens.user_id,
            is_premium_user: tokens.is_premium_user,
            auto_refresh_enabled: true,
        }));

        Ok(Self {
            auth,
            auth_event_callback: None,
            client_identifier: generate_id(),
            client: reqwest::Client::new(),
        })
    }

    /// Export tokens for persistent storage.
    ///
    /// Save these tokens to restore the session later without re-authenticating.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use anylist_rs::AnyListClient;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = AnyListClient::login("user@example.com", "password").await?;
    ///
    /// // Export and save tokens
    /// let tokens = client.export_tokens()?;
    /// // save_to_keychain(&tokens)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn export_tokens(&self) -> Result<SavedTokens> {
        let auth = self.auth.lock().unwrap();

        Ok(SavedTokens {
            access_token: auth.access_token.clone(),
            refresh_token: auth.refresh_token.clone(),
            user_id: auth.user_id.clone(),
            is_premium_user: auth.is_premium_user,
        })
    }

    /// Register a callback for authentication events.
    ///
    /// The callback will be invoked when tokens are acquired, refreshed, or refresh fails.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use anylist_rs::{AnyListClient, AuthEvent};
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = AnyListClient::login("user@example.com", "password")
    ///     .await?
    ///     .on_auth_event(|event| {
    ///         match event {
    ///             AuthEvent::TokensRefreshed => println!("Tokens refreshed!"),
    ///             AuthEvent::RefreshFailed(err) => eprintln!("Refresh failed: {}", err),
    ///             _ => {}
    ///         }
    ///     });
    /// # Ok(())
    /// # }
    /// ```
    pub fn on_auth_event<F>(mut self, callback: F) -> Self
    where
        F: Fn(AuthEvent) + Send + Sync + 'static,
    {
        self.auth_event_callback = Some(Arc::new(callback));
        self
    }

    /// Disable automatic token refresh.
    ///
    /// When disabled, the client will return errors on 401 instead of automatically
    /// refreshing tokens. Useful if you want full control over when refreshes happen.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use anylist_rs::AnyListClient;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = AnyListClient::login("user@example.com", "password")
    ///     .await?
    ///     .disable_auto_refresh();
    /// # Ok(())
    /// # }
    /// ```
    pub fn disable_auto_refresh(self) -> Self {
        let mut auth = self.auth.lock().unwrap();
        auth.auto_refresh_enabled = false;
        drop(auth);
        self
    }

    /// Get the user ID for this client.
    pub fn user_id(&self) -> String {
        let auth = self.auth.lock().unwrap();
        auth.user_id.clone()
    }

    /// Check if the user has premium subscription.
    pub fn is_premium_user(&self) -> bool {
        let auth = self.auth.lock().unwrap();
        auth.is_premium_user
    }

    /// Get the client identifier for this client.
    pub fn client_identifier(&self) -> &str {
        &self.client_identifier
    }

    /// Set the client identifier.
    ///
    /// This changes the identifier used for all subsequent requests.
    /// If you have an active RealtimeSync connection, you'll need to
    /// reconnect for it to use the new identifier.
    pub fn set_client_identifier(&mut self, id: String) {
        self.client_identifier = id;
    }

    /// Start real-time sync with a callback for events
    ///
    /// The callback will be invoked whenever the server sends a change notification.
    /// It's the caller's responsibility to decide what to do (re-fetch data, update cache, etc.)
    ///
    /// # Example
    ///
    /// ```no_run
    /// use anylist_rs::{AnyListClient, SyncEvent};
    /// use std::sync::Arc;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Arc::new(
    ///         AnyListClient::login("user@example.com", "password").await?
    ///     );
    ///
    ///     let mut sync = client.start_realtime_sync(|event| {
    ///         match event {
    ///             SyncEvent::ShoppingListsChanged => {
    ///                 println!("Shopping lists changed - consider re-fetching");
    ///             }
    ///             SyncEvent::RecipeDataChanged => {
    ///                 println!("Recipes changed");
    ///             }
    ///             _ => {}
    ///         }
    ///     }).await?;
    ///
    ///     // Do work...
    ///
    ///     // Clean shutdown
    ///     sync.disconnect().await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn start_realtime_sync<F>(
        self: &Arc<Self>,
        callback: F,
    ) -> Result<crate::realtime::RealtimeSync>
    where
        F: Fn(crate::realtime::SyncEvent) + Send + Sync + 'static,
    {
        let mut sync = crate::realtime::RealtimeSync::new(Arc::clone(self), callback);
        sync.connect().await?;
        Ok(sync)
    }

    // ========================================================================
    // Internal authentication methods
    // ========================================================================

    /// Refresh the access token using the refresh token.
    ///
    /// This calls /auth/token/refresh endpoint with multipart form data
    pub async fn refresh_tokens(&self) -> Result<()> {
        let refresh_token = {
            let auth = self.auth.lock().unwrap();
            auth.refresh_token.clone()
        };

        let mut headers = HeaderMap::new();
        headers.insert("X-AnyLeaf-API-Version", HeaderValue::from_static("3"));
        headers.insert(
            "X-AnyLeaf-Client-Identifier",
            HeaderValue::from_str(&self.client_identifier).unwrap(),
        );

        let form = reqwest::multipart::Form::new().text("refresh_token", refresh_token);

        let response = self
            .client
            .post("https://www.anylist.com/auth/token/refresh")
            .headers(headers)
            .multipart(form)
            .send()
            .await?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await?;
            let error_msg = format!(
                "Token refresh failed with status: {}, body: {}",
                status, body
            );

            // Notify callback of failure
            if let Some(callback) = &self.auth_event_callback {
                callback(AuthEvent::RefreshFailed(error_msg.clone()));
            }

            return Err(AnyListError::AuthenticationFailed(error_msg));
        }

        #[derive(Deserialize)]
        struct RefreshResponse {
            access_token: String,
            refresh_token: String,
        }

        let token_response: RefreshResponse = response.json().await?;

        // Update auth state
        {
            let mut auth = self.auth.lock().unwrap();
            auth.access_token = token_response.access_token;
            auth.refresh_token = token_response.refresh_token;
        }

        // Notify callback
        if let Some(callback) = &self.auth_event_callback {
            callback(AuthEvent::TokensRefreshed);
        }

        Ok(())
    }

    /// Get default headers for API requests
    fn get_headers(&self) -> HeaderMap {
        let mut headers = HeaderMap::new();

        let auth = self.auth.lock().unwrap();
        let bearer_value = format!("Bearer {}", auth.access_token);
        headers.insert(AUTHORIZATION, HeaderValue::from_str(&bearer_value).unwrap());
        drop(auth);

        headers.insert("X-AnyLeaf-API-Version", HeaderValue::from_static("3"));
        headers.insert(
            "X-AnyLeaf-Client-Identifier",
            HeaderValue::from_str(&self.client_identifier).unwrap(),
        );

        headers
    }

    /// Make a POST request to the AnyList API.
    ///
    /// Automatically handles token refresh on 401 errors if auto_refresh is enabled.
    /// Sends the protobuf data as multipart/form-data with field name "operations".
    pub(crate) async fn post(&self, endpoint: &str, body: Vec<u8>) -> Result<Vec<u8>> {
        // Delegate to post_multipart with standard "operations" field name
        // Note: endpoint here doesn't have leading slash, so we add one
        self.post_multipart(&format!("/{}", endpoint), "operations", body).await
    }

    /// Make a POST request with custom multipart field name.
    ///
    /// Automatically handles token refresh on 401 errors if auto_refresh is enabled.
    /// The endpoint should include a leading slash (e.g., "/data/endpoint").
    pub(crate) async fn post_multipart(
        &self,
        endpoint: &str,
        field_name: &str,
        body: Vec<u8>,
    ) -> Result<Vec<u8>> {
        let url = format!("https://www.anylist.com{}", endpoint);
        // Convert to owned String since we need it for both initial request and potential retry
        let field_name_owned = field_name.to_string();

        // Create multipart form with the specified field name containing the protobuf data
        let form = reqwest::multipart::Form::new()
            .part(field_name_owned.clone(), reqwest::multipart::Part::bytes(body.clone()));

        let response = self
            .client
            .post(&url)
            .headers(self.get_headers())
            .multipart(form)
            .send()
            .await?;

        // Handle 401 with automatic token refresh
        if response.status() == 401 {
            let auto_refresh = {
                let auth = self.auth.lock().unwrap();
                auth.auto_refresh_enabled
            };

            if auto_refresh {
                // Try to refresh tokens
                self.refresh_tokens().await?;

                // Retry the request with new token
                let retry_form = reqwest::multipart::Form::new()
                    .part(field_name_owned, reqwest::multipart::Part::bytes(body));

                let retry_response = self
                    .client
                    .post(&url)
                    .headers(self.get_headers())
                    .multipart(retry_form)
                    .send()
                    .await?;

                if !retry_response.status().is_success() {
                    return Err(AnyListError::NetworkError(format!(
                        "Request failed after token refresh with status: {}",
                        retry_response.status()
                    )));
                }

                let bytes = retry_response.bytes().await?;
                return Ok(bytes.to_vec());
            } else {
                return Err(AnyListError::AuthenticationFailed(
                    "Unauthorized (auto-refresh disabled)".to_string(),
                ));
            }
        }

        if !response.status().is_success() {
            return Err(AnyListError::NetworkError(format!(
                "Request failed with status: {}",
                response.status()
            )));
        }

        let bytes = response.bytes().await?;
        Ok(bytes.to_vec())
    }

    /// Make a POST request with a pre-built multipart form.
    ///
    /// Used for complex multipart requests like photo uploads where
    /// we need more control over the form parts.
    ///
    /// Note: This method cannot automatically retry on 401 because
    /// `reqwest::multipart::Form` is not `Clone`. If authentication
    /// fails, the caller should retry the request.
    pub(crate) async fn post_multipart_form(
        &self,
        endpoint: &str,
        form: reqwest::multipart::Form,
    ) -> Result<Vec<u8>> {
        let url = format!("https://www.anylist.com{}", endpoint);

        let response = self
            .client
            .post(&url)
            .headers(self.get_headers())
            .multipart(form)
            .send()
            .await?;

        if response.status() == 401 {
            return Err(AnyListError::AuthenticationFailed(
                "Unauthorized - please refresh tokens and retry".to_string(),
            ));
        }

        if !response.status().is_success() {
            return Err(AnyListError::NetworkError(format!(
                "Request failed with status: {}",
                response.status()
            )));
        }

        let bytes = response.bytes().await?;
        Ok(bytes.to_vec())
    }
}