BlueGit

ict rusty-teams

Files

rusty-teams / crates / store / src / sidebar.rs

sidebar.rs

sidebar.rs 10.9 KiB Download Raw
1use std::cmp::Ordering;
2use std::collections::HashMap;
3
4use rusqlite::params;
5
6use crate::error::Result;
7use crate::models::{
8 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, ChannelTabRecord, Sidebar,
9 SidebarTeam, TeamLayoutRecord, TeamRecord,
10};
11use crate::store::Store;
12use crate::teams::channel_from_row;
13
14const GENERAL_FALLBACK_NAME: &str = "General";
15
16struct TeamRow {
17 team: TeamRecord,
18 position: Option<i64>,
19 hidden: bool,
20}
21
22struct ChannelRow {
23 channel: ChannelRecord,
24 general: bool,
25 hidden: bool,
26 notifications: ChannelNotifications,
27}
28
29impl Store {
30 pub fn sidebar(&self) -> Result<Sidebar> {
31 let chats = self.recent_chats(usize::MAX >> 1)?;
32 let connection = self.lock()?;
33 let mut team_rows: Vec<TeamRow> = connection
34 .prepare_cached(
35 "SELECT teams.id, teams.name, team_layout.position, COALESCE(team_layout.hidden, 0)
36 FROM teams LEFT JOIN team_layout ON team_layout.team_id = teams.id",
37 )?
38 .query_map([], |row| {
39 Ok(TeamRow {
40 team: TeamRecord {
41 id: row.get(0)?,
42 name: row.get(1)?,
43 },
44 position: row.get(2)?,
45 hidden: row.get(3)?,
46 })
47 })?
48 .collect::<rusqlite::Result<_>>()?;
49 team_rows.sort_by(|left, right| {
50 match (left.position, right.position) {
51 (Some(left), Some(right)) => left.cmp(&right),
52 (Some(_), None) => Ordering::Less,
53 (None, Some(_)) => Ordering::Greater,
54 (None, None) => Ordering::Equal,
55 }
56 .then_with(|| compare_names(&left.team.name, &right.team.name))
57 .then_with(|| left.team.id.cmp(&right.team.id))
58 });
59 let mut channel_rows: Vec<ChannelRow> = connection
60 .prepare_cached(
61 "SELECT id, team_id, name, membership_type, last_message_at, unread,
62 COALESCE(channel_layout.general, name = ?1), COALESCE(channel_layout.hidden, 0),
63 COALESCE(channel_layout.notification_level, 'feed'),
64 COALESCE(channel_layout.include_replies, 0)
65 FROM channels LEFT JOIN channel_layout ON channel_layout.channel_id = channels.id",
66 )?
67 .query_map(params![GENERAL_FALLBACK_NAME], |row| {
68 Ok(ChannelRow {
69 channel: channel_from_row(row)?,
70 general: row.get(6)?,
71 hidden: row.get(7)?,
72 notifications: ChannelNotifications {
73 level: ChannelNotificationLevel::from_key(&row.get::<_, String>(8)?),
74 include_replies: row.get(9)?,
75 },
76 })
77 })?
78 .collect::<rusqlite::Result<_>>()?;
79 channel_rows.sort_by(|left, right| {
80 right
81 .general
82 .cmp(&left.general)
83 .then_with(|| compare_names(&left.channel.name, &right.channel.name))
84 .then_with(|| left.channel.id.cmp(&right.channel.id))
85 });
86 let mut teams: Vec<SidebarTeam> = team_rows
87 .into_iter()
88 .map(|row| SidebarTeam {
89 team: row.team,
90 channels: Vec::new(),
91 hidden: row.hidden,
92 hidden_channel_ids: Vec::new(),
93 notifications: HashMap::new(),
94 })
95 .collect();
96 for row in channel_rows {
97 if let Some(team) = teams
98 .iter_mut()
99 .find(|team| team.team.id == row.channel.team_id)
100 {
101 if row.hidden {
102 team.hidden_channel_ids.push(row.channel.id.clone());
103 }
104 if row.notifications != ChannelNotifications::default() {
105 team.notifications
106 .insert(row.channel.id.clone(), row.notifications);
107 }
108 team.channels.push(row.channel);
109 }
110 }
111 Ok(Sidebar { chats, teams })
112 }
113
114 pub fn replace_team_layout(&self, layout: &[TeamLayoutRecord]) -> Result<()> {
115 let mut connection = self.lock()?;
116 let transaction = connection.transaction()?;
117 transaction.execute("DELETE FROM team_layout", [])?;
118 transaction.execute("DELETE FROM channel_layout", [])?;
119 transaction.execute("DELETE FROM channel_tabs", [])?;
120 {
121 let mut team_insert = transaction.prepare_cached(
122 "INSERT OR REPLACE INTO team_layout (team_id, position, hidden) VALUES (?1, ?2, ?3)",
123 )?;
124 let mut channel_insert = transaction.prepare_cached(
125 "INSERT OR REPLACE INTO channel_layout
126 (channel_id, general, hidden, notification_level, include_replies)
127 VALUES (?1, ?2, ?3, ?4, ?5)",
128 )?;
129 let mut tab_insert = transaction.prepare_cached(
130 "INSERT OR REPLACE INTO channel_tabs (channel_id, position, tab_id, name, definition_id, open_url)
131 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
132 )?;
133 for (position, team) in layout.iter().enumerate() {
134 team_insert.execute(params![team.team_id, position as i64, team.hidden])?;
135 for channel in &team.channels {
136 channel_insert.execute(params![
137 channel.channel_id,
138 channel.general,
139 channel.hidden,
140 channel.notifications.level.key(),
141 channel.notifications.include_replies
142 ])?;
143 for (tab_position, tab) in channel.tabs.iter().enumerate() {
144 tab_insert.execute(params![
145 channel.channel_id,
146 tab_position as i64,
147 tab.tab_id,
148 tab.name,
149 tab.definition_id,
150 tab.open_url
151 ])?;
152 }
153 }
154 }
155 }
156 Ok(transaction.commit()?)
157 }
158
159 pub fn set_channel_notifications(
160 &self,
161 channel_id: &str,
162 notifications: ChannelNotifications,
163 ) -> Result<()> {
164 self.lock()?.execute(
165 "INSERT INTO channel_layout (channel_id, general, notification_level, include_replies)
166 SELECT id, name = ?2, ?3, ?4 FROM channels WHERE id = ?1
167 ON CONFLICT (channel_id) DO UPDATE SET
168 notification_level = excluded.notification_level,
169 include_replies = excluded.include_replies",
170 params![
171 channel_id,
172 GENERAL_FALLBACK_NAME,
173 notifications.level.key(),
174 notifications.include_replies
175 ],
176 )?;
177 Ok(())
178 }
179}
180
181impl Store {
182 pub fn channel_tabs(&self, channel_id: &str) -> Result<Vec<ChannelTabRecord>> {
183 let connection = self.lock()?;
184 let tabs = connection
185 .prepare_cached(
186 "SELECT tab_id, name, definition_id, open_url FROM channel_tabs
187 WHERE channel_id = ?1 ORDER BY position",
188 )?
189 .query_map(params![channel_id], |row| {
190 Ok(ChannelTabRecord {
191 tab_id: row.get(0)?,
192 name: row.get(1)?,
193 definition_id: row.get(2)?,
194 open_url: row.get(3)?,
195 })
196 })?
197 .collect::<rusqlite::Result<_>>()?;
198 Ok(tabs)
199 }
200}
201
202fn compare_names(left: &str, right: &str) -> Ordering {
203 sort_key(left).cmp(&sort_key(right))
204}
205
206const PUNCTUATION_ORDER: &str = "_-,;:!?.'\"()[]{}@*/\\&#%`^+<=>|~$";
207
208const LETTER_FOLDS: &[(&str, &str)] = &[
209 ("àáâãäåāăą", "a"),
210 ("æ", "ae"),
211 ("çćĉċč", "c"),
212 ("ďđ", "d"),
213 ("èéêëēĕėęě", "e"),
214 ("ĝğġģ", "g"),
215 ("ĥħ", "h"),
216 ("ìíîïĩīĭįıǐ", "i"),
217 ("ĵ", "j"),
218 ("ķ", "k"),
219 ("ĺļľŀł", "l"),
220 ("ñńņňʼn", "n"),
221 ("òóôõöøōŏőǒ", "o"),
222 ("œ", "oe"),
223 ("ŕŗř", "r"),
224 ("śŝşš", "s"),
225 ("ß", "ss"),
226 ("ţťŧ", "t"),
227 ("ùúûüũūŭůűųǔ", "u"),
228 ("ŵ", "w"),
229 ("ýÿŷ", "y"),
230 ("źżž", "z"),
231];
232
233fn primary_weights(character: char) -> Vec<(u8, u32)> {
234 if character.is_whitespace() {
235 return vec![(0, 0)];
236 }
237 if let Some(position) = PUNCTUATION_ORDER.find(character) {
238 return vec![(1, position as u32)];
239 }
240 if character.is_ascii_digit() || character.is_alphabetic() {
241 let class = if character.is_numeric() { 2 } else { 3 };
242 if let Some((_, base)) = LETTER_FOLDS
243 .iter()
244 .find(|(variants, _)| variants.contains(character))
245 {
246 return base.chars().map(|letter| (class, letter as u32)).collect();
247 }
248 return vec![(class, character as u32)];
249 }
250 vec![(1, PUNCTUATION_ORDER.len() as u32 + character as u32)]
251}
252
253fn sort_key(name: &str) -> (Vec<(u8, u32)>, String) {
254 let lowered: String = name
255 .trim_start()
256 .chars()
257 .flat_map(char::to_lowercase)
258 .collect();
259 let primary = lowered.chars().flat_map(primary_weights).collect();
260 (primary, lowered)
261}
262
263#[cfg(test)]
264mod tests {
265 use super::compare_names;
266 use std::cmp::Ordering;
267
268 #[test]
269 fn names_compare_like_a_person_reads_them() {
270 assert_eq!(compare_names("alpha", "Beta"), Ordering::Less);
271 assert_eq!(compare_names("Übergabe", "Zoll"), Ordering::Less);
272 assert_eq!(compare_names("Übergabe", "Tests"), Ordering::Greater);
273 assert_eq!(compare_names("🚩 Rollout", "Alpha"), Ordering::Less);
274 }
275
276 #[test]
277 fn tie_breaks_follow_locale_compare() {
278 let ordered = ["x y", "x_y", "x-y", "xy"];
279 for pair in ordered.windows(2) {
280 assert_eq!(compare_names(pair[0], pair[1]), Ordering::Less);
281 }
282 assert_eq!(compare_names("_a", "-a"), Ordering::Less);
283 assert_eq!(compare_names("-a", "(a"), Ordering::Less);
284 assert_eq!(compare_names("(a", "#a"), Ordering::Less);
285 assert_eq!(compare_names("#a", "🚩a"), Ordering::Less);
286 assert_eq!(compare_names("10 x", "2 x"), Ordering::Less);
287 assert_eq!(compare_names("9", "a"), Ordering::Less);
288 assert_eq!(compare_names("e", "é"), Ordering::Less);
289 assert_eq!(compare_names("ss", "ß"), Ordering::Less);
290 assert_eq!(compare_names("a", "ä"), Ordering::Less);
291 assert_eq!(compare_names("ä", "ae"), Ordering::Less);
292 assert_eq!(compare_names("ø", "p"), Ordering::Less);
293 assert_eq!(compare_names("o", "ø"), Ordering::Less);
294 assert_eq!(compare_names("ł", "m"), Ordering::Less);
295 assert_eq!(compare_names("ı", "j"), Ordering::Less);
296 }
297}