BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / pins / chats.rs

chats.rs

Initial commit
metis Daniel Däschle · pushed by metis · 7 weeks ago
06e0ae51 History
chats.rs 4.1 KiB Download Raw
1use serde_json::{Value, json};
2use session::{ApiResponse, Method, Request};
3
4use super::Pins;
5use super::state::{PinnedChats, error_code, parse_pinned_chats};
6use super::transport::CsaTransport;
7use crate::error::{Error, Result};
8
9pub(super) const FOLDER_QUERY: &str =
10 "supportsAdditionalSystemGeneratedFolders=true&supportsSliceItems=true";
11pub(super) const NO_OP_CODES: [&str; 2] = ["ConversationAlreadyLinkedWithFolder", "ItemNotFound"];
12
13#[derive(Debug, Clone, PartialEq)]
14pub(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
27impl 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
48pub(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
57impl<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 parse_pinned_chats(&answer.body)
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
112pub(super) fn ensure_success(answer: &ApiResponse) -> Result<()> {
113 if answer.is_success() {
114 Ok(())
115 } else {
116 Err(api_error(answer))
117 }
118}
119
120pub(super) fn api_error(answer: &ApiResponse) -> Error {
121 Error::Session(session::Error::api(
122 answer.status,
123 "csa",
124 answer.body.clone(),
125 ))
126}