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
use crate::client::AnyListClient;
use crate::error::{AnyListError, Result};
use crate::protobuf::anylist::{
    PbEmailUserIdPair, PbListItem, PbShoppingListsResponse, PbUserDataResponse,
};
use crate::utils::{current_timestamp, generate_id};
use prost::Message;
use serde_derive::{Deserialize, Serialize};

/// User information for list collaborators
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UserInfo {
    pub(crate) user_id: String,
    pub(crate) email: Option<String>,
    pub(crate) full_name: Option<String>,
}

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

    pub fn email(&self) -> Option<&str> {
        self.email.as_deref()
    }

    pub fn full_name(&self) -> Option<&str> {
        self.full_name.as_deref()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ListItem {
    pub(crate) id: String,
    pub(crate) list_id: String,
    pub(crate) name: String,
    pub(crate) details: String,
    pub(crate) is_checked: bool,
    pub(crate) quantity: Option<String>,
    pub(crate) category: Option<String>,
    pub(crate) user_id: Option<String>,
    pub(crate) product_upc: Option<String>,
}

impl ListItem {
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Get the list ID this item belongs to
    pub fn list_id(&self) -> &str {
        &self.list_id
    }

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

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

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

    pub fn quantity(&self) -> Option<&str> {
        self.quantity.as_deref()
    }

    pub fn category(&self) -> Option<&str> {
        self.category.as_deref()
    }

    /// Get the user ID who created/owns this item
    pub fn user_id(&self) -> Option<&str> {
        self.user_id.as_deref()
    }

    pub fn product_upc(&self) -> Option<&str> {
        self.product_upc.as_deref()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct List {
    pub(crate) id: String,
    pub(crate) name: String,
    pub(crate) items: Vec<ListItem>,
    pub(crate) shared_users: Vec<UserInfo>,
}

impl List {
    pub fn id(&self) -> &str {
        &self.id
    }

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

    pub fn items(&self) -> &[ListItem] {
        &self.items
    }

    pub fn shared_users(&self) -> &[UserInfo] {
        &self.shared_users
    }
}

impl AnyListClient {
    /// Get all shopping lists for the authenticated user
    ///
    /// # 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");
    /// for list in lists {
    ///     println!("List: {} ({} items)", list.name(), list.items().len());
    /// }
    /// # }
    /// ```
    pub async fn get_lists(&self) -> Result<Vec<List>> {
        let data = self.get_user_data().await?;
        let lists = match data.shopping_lists_response {
            Some(ref res) => lists_from_response(res.clone()),
            None => Vec::new(),
        };
        Ok(lists)
    }

    /// Get a specific list by ID
    ///
    /// # Arguments
    ///
    /// * `list_id` - The ID of the list to retrieve
    pub async fn get_list_by_id(&self, list_id: &str) -> Result<List> {
        let lists = self.get_lists().await?;
        lists
            .into_iter()
            .find(|l| l.id == list_id)
            .ok_or_else(|| AnyListError::NotFound(format!("List with ID {} not found", list_id)))
    }

    /// Get a specific list by name
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the list to retrieve
    pub async fn get_list_by_name(&self, name: &str) -> Result<List> {
        let lists = self.get_lists().await?;
        lists
            .into_iter()
            .find(|l| l.name == name)
            .ok_or_else(|| AnyListError::NotFound(format!("List with name '{}' not found", name)))
    }

    /// Create a new shopping list
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the new list
    ///
    /// # 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 list = client.create_list("Groceries").await.expect("Failed to create list");
    /// println!("Created list: {}", list.name());
    /// # }
    /// ```
    pub async fn create_list(&self, name: &str) -> Result<List> {
        let list_id = generate_id();
        let operation_id = generate_id();

        // Imperative shell: gather runtime values
        let params = crate::operations::CreateListParams {
            list_id: list_id.clone(),
            operation_id,
            user_id: self.user_id(),
            timestamp: current_timestamp(),
            name: name.to_string(),
        };

        // Functional core: pure operation building
        let operation_list = crate::operations::build_create_list_operation(params);

        // Imperative shell: side effects
        let mut buf = Vec::new();
        operation_list.encode(&mut buf).map_err(|e| {
            AnyListError::ProtobufError(format!("Failed to encode operation: {}", e))
        })?;

        self.post("data/shopping-lists/update", buf).await?;

        Ok(List {
            id: list_id,
            name: name.to_string(),
            items: vec![],
            shared_users: vec![],
        })
    }

    /// Delete a shopping list
    pub async fn delete_list(&self, list_id: &str) -> Result<()> {
        let user_data = self.get_user_data().await?;

        let list_data_id = user_data
            .list_folders_response
            .as_ref()
            .and_then(|r| r.list_data_id.clone())
            .ok_or_else(|| {
                AnyListError::NotFound("Could not find list_data_id for folder operations".into())
            })?;

        let settings_id = user_data
            .list_settings_response
            .as_ref()
            .and_then(|r| {
                r.settings
                    .iter()
                    .find(|s| s.list_id.as_deref() == Some(list_id))
                    .map(|s| s.identifier.clone())
            })
            .ok_or_else(|| {
                AnyListError::NotFound(format!("Could not find settings for list {}", list_id))
            })?;

        let folder_params = crate::operations::DeleteFolderItemsParams {
            list_id: list_id.to_string(),
            list_data_id,
            operation_id: generate_id(),
            user_id: self.user_id(),
        };
        let folder_operation_list = crate::operations::build_delete_folder_items_operation(folder_params);
        let mut folder_buf = Vec::new();
        folder_operation_list.encode(&mut folder_buf).map_err(|e| {
            AnyListError::ProtobufError(format!("Failed to encode folder operation: {}", e))
        })?;
        self.post("data/list-folders/update", folder_buf).await?;

        let settings_params = crate::operations::RemoveListSettingsParams {
            settings_id,
            list_id: list_id.to_string(),
            operation_id: generate_id(),
            user_id: self.user_id(),
        };
        let settings_operation_list = crate::operations::build_remove_list_settings_operation(settings_params);
        let mut settings_buf = Vec::new();
        settings_operation_list.encode(&mut settings_buf).map_err(|e| {
            AnyListError::ProtobufError(format!("Failed to encode settings operation: {}", e))
        })?;
        self.post("data/list-settings/update", settings_buf).await?;

        Ok(())
    }

    /// Rename a shopping list
    ///
    /// # Arguments
    ///
    /// * `list_id` - The ID of the list to rename
    /// * `new_name` - The new name for the list
    pub async fn rename_list(&self, list_id: &str, new_name: &str) -> Result<()> {
        let operation_id = generate_id();

        // Get the current list to preserve other fields
        let current_list = self.get_list_by_id(list_id).await?;

        // Imperative shell: gather runtime values
        let params = crate::operations::RenameListParams {
            list_id: list_id.to_string(),
            operation_id,
            user_id: self.user_id(),
            timestamp: current_timestamp(),
            old_name: current_list.name,
            new_name: new_name.to_string(),
        };

        // Functional core: pure operation building
        let operation_list = crate::operations::build_rename_list_operation(params);

        // Imperative shell: side effects
        let mut buf = Vec::new();
        operation_list.encode(&mut buf).map_err(|e| {
            AnyListError::ProtobufError(format!("Failed to encode operation: {}", e))
        })?;

        self.post("data/shopping-lists/update", buf).await?;
        Ok(())
    }

    /// Get user data from the API
    pub async fn get_user_data(&self) -> Result<PbUserDataResponse> {
        let bytes = self.post("data/user-data/get", vec![]).await?;
        let data = PbUserDataResponse::decode(bytes.as_ref())?;
        Ok(data)
    }
}

fn transform_api_list_item(items: Vec<PbListItem>) -> Vec<ListItem> {
    let mut result: Vec<ListItem> = Vec::new();
    for item in items {
        if let (Some(name), Some(list_id)) = (item.name, item.list_id) {
            let item = ListItem {
                id: item.identifier,
                list_id: list_id.clone(),
                name,
                details: item.details.unwrap_or("".to_string()),
                is_checked: item.checked.unwrap_or(false),
                quantity: item.quantity,
                category: item.category,
                user_id: item.user_id,
                product_upc: item.product_upc,
            };
            result.push(item);
        }
    }
    result
}

fn transform_shared_users(users: Vec<PbEmailUserIdPair>) -> Vec<UserInfo> {
    users
        .into_iter()
        .map(|user| UserInfo {
            user_id: user.user_id.unwrap_or_default(),
            email: user.email,
            full_name: user.full_name,
        })
        .collect()
}

fn lists_from_response(response: PbShoppingListsResponse) -> Vec<List> {
    let mut lists: Vec<List> = Vec::new();
    for list in response.new_lists {
        if let Some(name) = list.name {
            let list = List {
                id: list.identifier,
                name,
                items: transform_api_list_item(list.items),
                shared_users: transform_shared_users(list.shared_users),
            };
            lists.push(list);
        }
    }
    lists
}

#[cfg(test)]
mod tests {
    use super::*;
    use prost::Message;

    #[test]
    fn test_parse_list_with_shared_users() {
        // Response from webapp: POST /data/user-data/get with shared list
        let snapshot_content =
            include_str!("snapshots/webapp_captures__parse_list_with_shared_users.snap");

        // Find the hex data (after the "---\n" separator)
        let response_hex = snapshot_content
            .split("---")
            .nth(2) // Third section after two "---" markers
            .unwrap()
            .trim();

        let bytes = hex::decode(response_hex).unwrap();
        let user_data = PbUserDataResponse::decode(bytes.as_ref()).unwrap();

        let lists = lists_from_response(user_data.shopping_lists_response.unwrap());

        // Verify lists were parsed
        assert!(!lists.is_empty(), "Should have at least one list");

        // Find list with shared users
        let list_with_users = lists.iter().find(|l| !l.shared_users.is_empty());

        assert!(
            list_with_users.is_some(),
            "Expected at least one list with shared users"
        );

        let list = list_with_users.unwrap();

        // Verify shared_users structure
        assert!(
            !list.shared_users.is_empty(),
            "shared_users should not be empty"
        );

        let user = &list.shared_users[0];
        assert!(!user.user_id.is_empty(), "user_id should be populated");

        // Verify optional fields exist
        assert!(
            user.email.is_some() || user.full_name.is_some(),
            "Either email or full_name should be populated"
        );

        // Debug output for inspection
        println!("✓ Found {} lists", lists.len());
        println!(
            "✓ List '{}' has {} shared users",
            list.name,
            list.shared_users.len()
        );
        for shared_user in &list.shared_users {
            println!("  - user_id: {}", shared_user.user_id);
            if let Some(email) = &shared_user.email {
                println!("    email: {}", email);
            }
            if let Some(name) = &shared_user.full_name {
                println!("    name: {}", name);
            }
        }
    }
}