BlueGit

ict rusty-teams

Files

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

state.rs

Initial commit
metis Daniel Däschle · pushed by metis · 7 weeks ago
06e0ae51 History
state.rs 4.8 KiB Download Raw
1use serde_json::Value;
2
3use crate::error::{Error, Result};
4
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub struct PinnedChats {
7 pub folder_id: String,
8 pub hierarchy_version: i64,
9 pub chat_ids: Vec<String>,
10}
11
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct PinnedChannels {
14 pub order_version: String,
15 pub channel_ids: Vec<String>,
16}
17
18pub fn parse_pinned_chats(body: &Value) -> Result<PinnedChats> {
19 let hierarchy_version = body
20 .get("folderHierarchyVersion")
21 .and_then(Value::as_i64)
22 .ok_or_else(|| Error::UnexpectedAnswer("folderHierarchyVersion missing".into()))?;
23 let folders = body
24 .get("conversationFolders")
25 .and_then(Value::as_array)
26 .ok_or_else(|| Error::UnexpectedAnswer("conversationFolders missing".into()))?;
27 let favorites = folders
28 .iter()
29 .find(|folder| {
30 folder.get("folderType").and_then(Value::as_str) == Some("Favorites")
31 && folder.get("isDeleted").and_then(Value::as_bool) != Some(true)
32 })
33 .ok_or(Error::NoFavoritesFolder)?;
34 let folder_id = favorites
35 .get("id")
36 .and_then(Value::as_str)
37 .ok_or_else(|| Error::UnexpectedAnswer("Favorites folder has no id".into()))?
38 .to_owned();
39 let chat_ids = favorites
40 .get("conversationFolderItems")
41 .and_then(Value::as_array)
42 .map(|items| {
43 items
44 .iter()
45 .filter_map(|item| item.get("conversationId").and_then(Value::as_str))
46 .map(str::to_owned)
47 .collect()
48 })
49 .unwrap_or_default();
50 Ok(PinnedChats {
51 folder_id,
52 hierarchy_version,
53 chat_ids,
54 })
55}
56
57pub fn parse_pinned_channels(body: &Value) -> Result<PinnedChannels> {
58 let order_version = match body.get("orderVersion") {
59 Some(Value::String(text)) => text.clone(),
60 Some(Value::Number(number)) => number.to_string(),
61 _ => return Err(Error::UnexpectedAnswer("orderVersion missing".into())),
62 };
63 let channel_ids = body
64 .get("pinChannelOrder")
65 .and_then(Value::as_array)
66 .map(|items| {
67 items
68 .iter()
69 .filter_map(Value::as_str)
70 .map(str::to_owned)
71 .collect()
72 })
73 .unwrap_or_default();
74 Ok(PinnedChannels {
75 order_version,
76 channel_ids,
77 })
78}
79
80pub fn error_code(body: &Value) -> Option<&str> {
81 body.pointer("/error/errorCode")
82 .or_else(|| body.pointer("/error/code"))
83 .and_then(Value::as_str)
84}
85
86pub fn error_text(body: &Value) -> String {
87 match body {
88 Value::String(text) => text.clone(),
89 other => other.to_string(),
90 }
91}
92
93#[cfg(test)]
94mod tests {
95 use serde_json::json;
96
97 use super::*;
98
99 fn folders_body() -> Value {
100 json!({
101 "folderHierarchyVersion": 1791368146075i64,
102 "conversationFolderOrder": ["t~u~Favorites"],
103 "conversationFolders": [
104 {"id": "t~u~RecentChats", "folderType": "RecentChats", "conversationFolderItems": []},
105 {"id": "t~u~Old", "folderType": "Favorites", "isDeleted": true, "conversationFolderItems": []},
106 {"id": "t~u~Favorites", "name": "Team", "folderType": "Favorites", "conversationFolderItems": [
107 {"conversationId": "19:a@thread.v2", "createdTime": 1},
108 {"conversationId": "48:notes"},
109 {"threadType": "chat"}
110 ]}
111 ]
112 })
113 }
114
115 #[test]
116 fn picks_favorites_by_type_not_name() {
117 let pinned = parse_pinned_chats(&folders_body()).unwrap();
118 assert_eq!(pinned.folder_id, "t~u~Favorites");
119 assert_eq!(pinned.hierarchy_version, 1791368146075);
120 assert_eq!(pinned.chat_ids, ["19:a@thread.v2", "48:notes"]);
121 }
122
123 #[test]
124 fn missing_favorites_folder_is_typed() {
125 let body = json!({"folderHierarchyVersion": 1, "conversationFolders": []});
126 assert!(matches!(
127 parse_pinned_chats(&body),
128 Err(Error::NoFavoritesFolder)
129 ));
130 }
131
132 #[test]
133 fn missing_version_is_unexpected() {
134 assert!(matches!(
135 parse_pinned_chats(&json!({"conversationFolders": []})),
136 Err(Error::UnexpectedAnswer(_))
137 ));
138 }
139
140 #[test]
141 fn channel_state_accepts_numeric_and_text_versions() {
142 let numeric = parse_pinned_channels(
143 &json!({"orderVersion": 42, "pinChannelOrder": ["19:c@thread.tacv2"]}),
144 )
145 .unwrap();
146 assert_eq!(numeric.order_version, "42");
147 assert_eq!(numeric.channel_ids, ["19:c@thread.tacv2"]);
148 let text = parse_pinned_channels(&json!({"orderVersion": "v7"})).unwrap();
149 assert_eq!(text.order_version, "v7");
150 assert!(text.channel_ids.is_empty());
151 }
152}