| 1 | use serde_json::{Value, json}; |
| 2 | use session::{Method, Request}; |
| 3 | |
| 4 | use super::Pins; |
| 5 | use super::chats::{FOLDER_QUERY, NO_OP_CODES, api_error, ensure_success}; |
| 6 | use super::state::error_code; |
| 7 | use super::transport::CsaTransport; |
| 8 | use crate::error::{Error, Result}; |
| 9 | |
| 10 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 11 | pub enum FolderKind { |
| 12 | Favorites, |
| 13 | UserCreated, |
| 14 | } |
| 15 | |
| 16 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 17 | pub struct Folder { |
| 18 | pub id: String, |
| 19 | pub name: String, |
| 20 | pub kind: FolderKind, |
| 21 | pub conversation_ids: Vec<String>, |
| 22 | } |
| 23 | |
| 24 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 25 | pub struct Folders { |
| 26 | pub hierarchy_version: i64, |
| 27 | pub folders: Vec<Folder>, |
| 28 | } |
| 29 | |
| 30 | impl Folders { |
| 31 | fn containing(&self, conversation_id: &str) -> Option<&Folder> { |
| 32 | self.folders.iter().find(|folder| { |
| 33 | folder.kind == FolderKind::UserCreated |
| 34 | && folder |
| 35 | .conversation_ids |
| 36 | .iter() |
| 37 | .any(|id| id == conversation_id) |
| 38 | }) |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | pub fn parse_folders(body: &Value) -> Result<Folders> { |
| 43 | let hierarchy_version = body |
| 44 | .get("folderHierarchyVersion") |
| 45 | .and_then(Value::as_i64) |
| 46 | .ok_or_else(|| Error::UnexpectedAnswer("folderHierarchyVersion missing".into()))?; |
| 47 | let raw = body |
| 48 | .get("conversationFolders") |
| 49 | .and_then(Value::as_array) |
| 50 | .ok_or_else(|| Error::UnexpectedAnswer("conversationFolders missing".into()))?; |
| 51 | let mut folders: Vec<Folder> = raw.iter().filter_map(parse_folder).collect(); |
| 52 | if let Some(order) = body |
| 53 | .get("conversationFolderOrder") |
| 54 | .and_then(Value::as_array) |
| 55 | { |
| 56 | let rank = |folder: &Folder| { |
| 57 | order |
| 58 | .iter() |
| 59 | .position(|id| id.as_str() == Some(folder.id.as_str())) |
| 60 | .unwrap_or(usize::MAX) |
| 61 | }; |
| 62 | folders.sort_by_key(rank); |
| 63 | } |
| 64 | Ok(Folders { |
| 65 | hierarchy_version, |
| 66 | folders, |
| 67 | }) |
| 68 | } |
| 69 | |
| 70 | fn parse_folder(folder: &Value) -> Option<Folder> { |
| 71 | if folder.get("isDeleted").and_then(Value::as_bool) == Some(true) { |
| 72 | return None; |
| 73 | } |
| 74 | let kind = match folder.get("folderType").and_then(Value::as_str)? { |
| 75 | "Favorites" => FolderKind::Favorites, |
| 76 | "UserCreated" => FolderKind::UserCreated, |
| 77 | _ => return None, |
| 78 | }; |
| 79 | Some(Folder { |
| 80 | id: folder.get("id")?.as_str()?.to_owned(), |
| 81 | name: folder |
| 82 | .get("name") |
| 83 | .and_then(Value::as_str) |
| 84 | .unwrap_or_default() |
| 85 | .to_owned(), |
| 86 | kind, |
| 87 | conversation_ids: folder |
| 88 | .get("conversationFolderItems") |
| 89 | .and_then(Value::as_array) |
| 90 | .map(|items| { |
| 91 | items |
| 92 | .iter() |
| 93 | .filter_map(|item| item.get("conversationId").and_then(Value::as_str)) |
| 94 | .map(str::to_owned) |
| 95 | .collect() |
| 96 | }) |
| 97 | .unwrap_or_default(), |
| 98 | }) |
| 99 | } |
| 100 | |
| 101 | fn add_item(folder_id: &str, conversation_id: &str) -> Value { |
| 102 | json!({"action": "AddItem", "folderId": folder_id, "itemId": conversation_id}) |
| 103 | } |
| 104 | |
| 105 | fn remove_item(folder_id: &str, conversation_id: &str) -> Value { |
| 106 | json!({"action": "RemoveItem", "folderId": folder_id, "itemId": conversation_id}) |
| 107 | } |
| 108 | |
| 109 | impl<T: CsaTransport> Pins<T> { |
| 110 | pub async fn folders(&self) -> Result<Folders> { |
| 111 | let url = format!("{}/conversationFolders?{FOLDER_QUERY}", self.base_url); |
| 112 | let answer = self.transport.send(Request::get(url)).await?; |
| 113 | ensure_success(&answer)?; |
| 114 | parse_folders(&answer.body) |
| 115 | } |
| 116 | |
| 117 | pub async fn move_to_folder( |
| 118 | &self, |
| 119 | conversation_id: &str, |
| 120 | target_folder_id: &str, |
| 121 | ) -> Result<Folders> { |
| 122 | self.write_folders(|state| { |
| 123 | let target = state |
| 124 | .folders |
| 125 | .iter() |
| 126 | .find(|folder| folder.id == target_folder_id) |
| 127 | .ok_or_else(|| Error::UnknownFolder(target_folder_id.to_owned()))?; |
| 128 | if target |
| 129 | .conversation_ids |
| 130 | .iter() |
| 131 | .any(|id| id == conversation_id) |
| 132 | { |
| 133 | return Ok(Vec::new()); |
| 134 | } |
| 135 | let mut actions = Vec::new(); |
| 136 | if let Some(current) = state.containing(conversation_id) { |
| 137 | actions.push(remove_item(¤t.id, conversation_id)); |
| 138 | } |
| 139 | actions.push(add_item(target_folder_id, conversation_id)); |
| 140 | Ok(actions) |
| 141 | }) |
| 142 | .await |
| 143 | } |
| 144 | |
| 145 | pub async fn remove_from_folder( |
| 146 | &self, |
| 147 | conversation_id: &str, |
| 148 | folder_id: &str, |
| 149 | ) -> Result<Folders> { |
| 150 | self.write_folders(|state| { |
| 151 | let folder = state |
| 152 | .folders |
| 153 | .iter() |
| 154 | .find(|folder| folder.id == folder_id) |
| 155 | .ok_or_else(|| Error::UnknownFolder(folder_id.to_owned()))?; |
| 156 | if !folder |
| 157 | .conversation_ids |
| 158 | .iter() |
| 159 | .any(|id| id == conversation_id) |
| 160 | { |
| 161 | return Ok(Vec::new()); |
| 162 | } |
| 163 | Ok(vec![remove_item(folder_id, conversation_id)]) |
| 164 | }) |
| 165 | .await |
| 166 | } |
| 167 | |
| 168 | async fn write_folders( |
| 169 | &self, |
| 170 | plan: impl Fn(&Folders) -> Result<Vec<Value>>, |
| 171 | ) -> Result<Folders> { |
| 172 | let mut state = self.folders().await?; |
| 173 | for attempt in 0..2 { |
| 174 | let actions = plan(&state)?; |
| 175 | if actions.is_empty() { |
| 176 | return Ok(state); |
| 177 | } |
| 178 | let url = format!("{}/conversationFolders?{FOLDER_QUERY}", self.base_url); |
| 179 | let body = json!({ |
| 180 | "folderHierarchyVersion": state.hierarchy_version, |
| 181 | "supportsAdditionalSystemGeneratedFolders": true, |
| 182 | "supportsSliceItems": true, |
| 183 | "actions": actions, |
| 184 | }); |
| 185 | let answer = self |
| 186 | .transport |
| 187 | .send(Request::with_body(Method::Post, url, body)) |
| 188 | .await?; |
| 189 | match answer.status { |
| 190 | 200..=299 => return parse_folders(&answer.body), |
| 191 | 412 if attempt == 0 => { |
| 192 | state = match parse_folders(&answer.body) { |
| 193 | Ok(current) => current, |
| 194 | Err(_) => self.folders().await?, |
| 195 | }; |
| 196 | } |
| 197 | 412 => return Err(Error::VersionConflict), |
| 198 | 400 if error_code(&answer.body).is_some_and(|code| NO_OP_CODES.contains(&code)) => { |
| 199 | return self.folders().await; |
| 200 | } |
| 201 | _ => return Err(api_error(&answer)), |
| 202 | } |
| 203 | } |
| 204 | Err(Error::VersionConflict) |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | #[cfg(test)] |
| 209 | mod tests { |
| 210 | use super::*; |
| 211 | |
| 212 | #[test] |
| 213 | fn keeps_favorites_and_user_folders_in_server_order() { |
| 214 | let body = json!({ |
| 215 | "folderHierarchyVersion": 5, |
| 216 | "conversationFolderOrder": ["b", "a", "r"], |
| 217 | "conversationFolders": [ |
| 218 | {"id": "a", "name": "A", "folderType": "UserCreated", "conversationFolderItems": [{"conversationId": "c1"}, {"conversationId": "c2"}]}, |
| 219 | {"id": "r", "folderType": "RecentChats", "conversationFolderItems": []}, |
| 220 | {"id": "b", "name": "Pins", "folderType": "Favorites", "conversationFolderItems": []}, |
| 221 | {"id": "x", "folderType": "UserCreated", "isDeleted": true} |
| 222 | ] |
| 223 | }); |
| 224 | let parsed = parse_folders(&body).unwrap(); |
| 225 | let ids: Vec<&str> = parsed |
| 226 | .folders |
| 227 | .iter() |
| 228 | .map(|folder| folder.id.as_str()) |
| 229 | .collect(); |
| 230 | assert_eq!(ids, ["b", "a"]); |
| 231 | assert_eq!(parsed.folders[1].conversation_ids, ["c1", "c2"]); |
| 232 | assert_eq!(parsed.folders[0].kind, FolderKind::Favorites); |
| 233 | } |
| 234 | } |