| 1 | use serde_json::{Value, json}; |
| 2 | use session::{ApiResponse, Method, Request}; |
| 3 | |
| 4 | use super::Pins; |
| 5 | use super::state::{PinnedChats, error_code, parse_pinned_chats}; |
| 6 | use super::transport::CsaTransport; |
| 7 | use crate::error::{Error, Result}; |
| 8 | |
| 9 | pub(super) const FOLDER_QUERY: &str = |
| 10 | "supportsAdditionalSystemGeneratedFolders=true&supportsSliceItems=true"; |
| 11 | pub(super) const NO_OP_CODES: [&str; 2] = ["ConversationAlreadyLinkedWithFolder", "ItemNotFound"]; |
| 12 | |
| 13 | #[derive(Debug, Clone, PartialEq)] |
| 14 | pub(super) enum FolderAction { |
| 15 | Pin { |
| 16 | chat_id: String, |
| 17 | index: Option<usize>, |
| 18 | }, |
| 19 | Unpin { |
| 20 | chat_id: String, |
| 21 | }, |
| 22 | Reorder { |
| 23 | chat_ids: Vec<String>, |
| 24 | }, |
| 25 | } |
| 26 | |
| 27 | impl FolderAction { |
| 28 | fn to_json(&self, folder_id: &str) -> Value { |
| 29 | match self { |
| 30 | FolderAction::Pin { chat_id, index } => { |
| 31 | let mut action = |
| 32 | json!({"action": "AddItem", "folderId": folder_id, "itemId": chat_id}); |
| 33 | if let Some(index) = index { |
| 34 | action["itemIndex"] = json!(index); |
| 35 | } |
| 36 | action |
| 37 | } |
| 38 | FolderAction::Unpin { chat_id } => { |
| 39 | json!({"action": "RemoveItem", "folderId": folder_id, "itemId": chat_id}) |
| 40 | } |
| 41 | FolderAction::Reorder { chat_ids } => { |
| 42 | json!({"action": "ReorderItems", "folderId": folder_id, "newItemsOrder": chat_ids}) |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | pub(super) fn write_body(action: &FolderAction, state: &PinnedChats) -> Value { |
| 49 | json!({ |
| 50 | "folderHierarchyVersion": state.hierarchy_version, |
| 51 | "supportsAdditionalSystemGeneratedFolders": true, |
| 52 | "supportsSliceItems": true, |
| 53 | "actions": [action.to_json(&state.folder_id)], |
| 54 | }) |
| 55 | } |
| 56 | |
| 57 | impl<T: CsaTransport> Pins<T> { |
| 58 | pub async fn pinned_chats(&self) -> Result<PinnedChats> { |
| 59 | let url = format!("{}/conversationFolders?{FOLDER_QUERY}", self.base_url); |
| 60 | let answer = self.transport.send(Request::get(url)).await?; |
| 61 | ensure_success(&answer)?; |
| 62 | with_answer_context(parse_pinned_chats(&answer.body), &answer) |
| 63 | } |
| 64 | |
| 65 | pub async fn pin_chat(&self, chat_id: &str, index: Option<usize>) -> Result<PinnedChats> { |
| 66 | let action = FolderAction::Pin { |
| 67 | chat_id: chat_id.to_owned(), |
| 68 | index, |
| 69 | }; |
| 70 | self.write_folder(action).await |
| 71 | } |
| 72 | |
| 73 | pub async fn unpin_chat(&self, chat_id: &str) -> Result<PinnedChats> { |
| 74 | let action = FolderAction::Unpin { |
| 75 | chat_id: chat_id.to_owned(), |
| 76 | }; |
| 77 | self.write_folder(action).await |
| 78 | } |
| 79 | |
| 80 | pub async fn reorder_chats(&self, chat_ids: &[String]) -> Result<PinnedChats> { |
| 81 | let action = FolderAction::Reorder { |
| 82 | chat_ids: chat_ids.to_vec(), |
| 83 | }; |
| 84 | self.write_folder(action).await |
| 85 | } |
| 86 | |
| 87 | async fn write_folder(&self, action: FolderAction) -> Result<PinnedChats> { |
| 88 | let mut state = self.pinned_chats().await?; |
| 89 | for attempt in 0..2 { |
| 90 | let url = format!("{}/conversationFolders?{FOLDER_QUERY}", self.base_url); |
| 91 | let request = Request::with_body(Method::Post, url, write_body(&action, &state)); |
| 92 | let answer = self.transport.send(request).await?; |
| 93 | match answer.status { |
| 94 | 200..=299 => return parse_pinned_chats(&answer.body), |
| 95 | 412 if attempt == 0 => { |
| 96 | state = match parse_pinned_chats(&answer.body) { |
| 97 | Ok(current) => current, |
| 98 | Err(_) => self.pinned_chats().await?, |
| 99 | }; |
| 100 | } |
| 101 | 412 => return Err(Error::VersionConflict), |
| 102 | 400 if error_code(&answer.body).is_some_and(|code| NO_OP_CODES.contains(&code)) => { |
| 103 | return self.pinned_chats().await; |
| 104 | } |
| 105 | _ => return Err(api_error(&answer)), |
| 106 | } |
| 107 | } |
| 108 | Err(Error::VersionConflict) |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | pub(super) fn ensure_success(answer: &ApiResponse) -> Result<()> { |
| 113 | if (200..300).contains(&answer.status) { |
| 114 | Ok(()) |
| 115 | } else { |
| 116 | Err(api_error(answer)) |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | pub(super) fn describe_answer(answer: &ApiResponse) -> String { |
| 121 | let shape = match &answer.body { |
| 122 | Value::Object(fields) => { |
| 123 | let mut keys: Vec<&str> = fields.keys().map(String::as_str).collect(); |
| 124 | keys.sort_unstable(); |
| 125 | format!("object with keys [{}]", keys.join(", ")) |
| 126 | } |
| 127 | Value::Array(items) => format!("array of {} items", items.len()), |
| 128 | Value::String(text) => format!("string of {} characters", text.chars().count()), |
| 129 | Value::Null => "null".to_owned(), |
| 130 | Value::Bool(_) => "boolean".to_owned(), |
| 131 | Value::Number(_) => "number".to_owned(), |
| 132 | }; |
| 133 | format!("HTTP {}, {shape}", answer.status) |
| 134 | } |
| 135 | |
| 136 | pub(super) fn with_answer_context<T>(parsed: Result<T>, answer: &ApiResponse) -> Result<T> { |
| 137 | parsed.map_err(|error| match error { |
| 138 | Error::UnexpectedAnswer(reason) => { |
| 139 | Error::UnexpectedAnswer(format!("{reason} ({})", describe_answer(answer))) |
| 140 | } |
| 141 | other => other, |
| 142 | }) |
| 143 | } |
| 144 | |
| 145 | pub(super) fn api_error(answer: &ApiResponse) -> Error { |
| 146 | Error::Session(session::Error::api( |
| 147 | answer.status, |
| 148 | "csa", |
| 149 | answer.body.clone(), |
| 150 | )) |
| 151 | } |
| 152 | |
| 153 | #[cfg(test)] |
| 154 | mod tests { |
| 155 | use super::*; |
| 156 | |
| 157 | fn answer(status: u16, body: Value) -> ApiResponse { |
| 158 | ApiResponse { |
| 159 | status, |
| 160 | body, |
| 161 | retry_after: None, |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | #[test] |
| 166 | fn describes_an_object_by_status_and_key_names_only() { |
| 167 | let described = describe_answer(&answer(200, json!({"secret": "value", "other": 1}))); |
| 168 | assert_eq!(described, "HTTP 200, object with keys [other, secret]"); |
| 169 | assert!(!described.contains("value")); |
| 170 | } |
| 171 | |
| 172 | #[test] |
| 173 | fn describes_other_bodies_by_type_and_length() { |
| 174 | assert_eq!( |
| 175 | describe_answer(&answer(200, json!([1, 2, 3]))), |
| 176 | "HTTP 200, array of 3 items" |
| 177 | ); |
| 178 | assert_eq!( |
| 179 | describe_answer(&answer(200, json!("abcd"))), |
| 180 | "HTTP 200, string of 4 characters" |
| 181 | ); |
| 182 | assert_eq!(describe_answer(&answer(204, Value::Null)), "HTTP 204, null"); |
| 183 | } |
| 184 | |
| 185 | #[test] |
| 186 | fn a_parse_failure_carries_the_answer_description() { |
| 187 | let response = answer(200, json!({"conversationFolders": []})); |
| 188 | let error = with_answer_context(parse_pinned_chats(&response.body), &response) |
| 189 | .unwrap_err() |
| 190 | .to_string(); |
| 191 | assert!(error.contains("folderHierarchyVersion missing")); |
| 192 | assert!(error.contains("HTTP 200, object with keys [conversationFolders]")); |
| 193 | } |
| 194 | |
| 195 | #[test] |
| 196 | fn redirects_are_not_a_success() { |
| 197 | assert!(ensure_success(&answer(200, Value::Null)).is_ok()); |
| 198 | assert!(ensure_success(&answer(204, Value::Null)).is_ok()); |
| 199 | assert!(ensure_success(&answer(302, Value::Null)).is_err()); |
| 200 | } |
| 201 | } |