BlueGit

ict rusty-teams

Files

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

sidebar.rs

sidebar.rs 13.4 KiB Download Raw
1use std::cmp::Ordering;
2use std::collections::HashMap;
3
4use rusqlite::params;
5
6use crate::error::Result;
7use crate::models::{
8 ChannelMentions, ChannelNotificationLevel, ChannelNotifications, ChannelRecord,
9 ChannelTabRecord, Sidebar, 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 mentions: HashMap<String, ChannelMentions> = connection
87 .prepare_cached("SELECT channel_id, personal, channel, team FROM channel_mentions")?
88 .query_map([], |row| {
89 Ok((
90 row.get::<_, String>(0)?,
91 ChannelMentions {
92 personal: row.get(1)?,
93 channel: row.get(2)?,
94 team: row.get(3)?,
95 },
96 ))
97 })?
98 .collect::<rusqlite::Result<_>>()?;
99 let mut teams: Vec<SidebarTeam> = team_rows
100 .into_iter()
101 .map(|row| SidebarTeam {
102 team: row.team,
103 channels: Vec::new(),
104 hidden: row.hidden,
105 hidden_channel_ids: Vec::new(),
106 notifications: HashMap::new(),
107 mentions: HashMap::new(),
108 })
109 .collect();
110 for row in channel_rows {
111 if let Some(team) = teams
112 .iter_mut()
113 .find(|team| team.team.id == row.channel.team_id)
114 {
115 if row.hidden {
116 team.hidden_channel_ids.push(row.channel.id.clone());
117 }
118 if row.notifications != ChannelNotifications::default() {
119 team.notifications
120 .insert(row.channel.id.clone(), row.notifications);
121 }
122 if let Some(found) = mentions.remove(&row.channel.id) {
123 team.mentions.insert(row.channel.id.clone(), found);
124 }
125 team.channels.push(row.channel);
126 }
127 }
128 Ok(Sidebar { chats, teams })
129 }
130
131 pub fn replace_team_layout(&self, layout: &[TeamLayoutRecord]) -> Result<()> {
132 let mut connection = self.lock()?;
133 let transaction = connection.transaction()?;
134 transaction.execute("DELETE FROM team_layout", [])?;
135 transaction.execute("DELETE FROM channel_layout", [])?;
136 transaction.execute("DELETE FROM channel_tabs", [])?;
137 {
138 let mut team_insert = transaction.prepare_cached(
139 "INSERT OR REPLACE INTO team_layout (team_id, position, hidden) VALUES (?1, ?2, ?3)",
140 )?;
141 let mut channel_insert = transaction.prepare_cached(
142 "INSERT OR REPLACE INTO channel_layout
143 (channel_id, general, hidden, notification_level, include_replies)
144 VALUES (?1, ?2, ?3, ?4, ?5)",
145 )?;
146 let mut tab_insert = transaction.prepare_cached(
147 "INSERT OR REPLACE INTO channel_tabs (channel_id, position, tab_id, name, definition_id, open_url)
148 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
149 )?;
150 for (position, team) in layout.iter().enumerate() {
151 team_insert.execute(params![team.team_id, position as i64, team.hidden])?;
152 for channel in &team.channels {
153 channel_insert.execute(params![
154 channel.channel_id,
155 channel.general,
156 channel.hidden,
157 channel.notifications.level.key(),
158 channel.notifications.include_replies
159 ])?;
160 for (tab_position, tab) in channel.tabs.iter().enumerate() {
161 tab_insert.execute(params![
162 channel.channel_id,
163 tab_position as i64,
164 tab.tab_id,
165 tab.name,
166 tab.definition_id,
167 tab.open_url
168 ])?;
169 }
170 }
171 }
172 }
173 Ok(transaction.commit()?)
174 }
175
176 /// Replaces every stored mention count; channels left out have none.
177 pub fn replace_channel_mentions(&self, mentions: &[(String, ChannelMentions)]) -> Result<()> {
178 let mut connection = self.lock()?;
179 let transaction = connection.transaction()?;
180 transaction.execute("DELETE FROM channel_mentions", [])?;
181 {
182 let mut insert = transaction.prepare_cached(
183 "INSERT OR REPLACE INTO channel_mentions (channel_id, personal, channel, team)
184 VALUES (?1, ?2, ?3, ?4)",
185 )?;
186 for (channel_id, counts) in mentions.iter().filter(|(_, counts)| !counts.is_empty()) {
187 insert.execute(params![channel_id, counts.personal, counts.channel, counts.team])?;
188 }
189 }
190 Ok(transaction.commit()?)
191 }
192
193 pub fn clear_channel_mentions(&self, channel_id: &str) -> Result<()> {
194 self.lock()?.execute(
195 "DELETE FROM channel_mentions WHERE channel_id = ?1",
196 [channel_id],
197 )?;
198 Ok(())
199 }
200
201 /// The team's own thread id, which Teams' CSA routes take: the id of its General channel.
202 pub fn team_thread_id(&self, team_id: &str) -> Result<Option<String>> {
203 let connection = self.lock()?;
204 Ok(connection
205 .prepare_cached(
206 "SELECT channels.id FROM channels
207 LEFT JOIN channel_layout ON channel_layout.channel_id = channels.id
208 WHERE channels.team_id = ?1
209 AND COALESCE(channel_layout.general, channels.name = ?2)
210 ORDER BY channels.id LIMIT 1",
211 )?
212 .query_map(params![team_id, GENERAL_FALLBACK_NAME], |row| row.get(0))?
213 .next()
214 .transpose()?)
215 }
216
217 pub fn set_channel_notifications(
218 &self,
219 channel_id: &str,
220 notifications: ChannelNotifications,
221 ) -> Result<()> {
222 self.lock()?.execute(
223 "INSERT INTO channel_layout (channel_id, general, notification_level, include_replies)
224 SELECT id, name = ?2, ?3, ?4 FROM channels WHERE id = ?1
225 ON CONFLICT (channel_id) DO UPDATE SET
226 notification_level = excluded.notification_level,
227 include_replies = excluded.include_replies",
228 params![
229 channel_id,
230 GENERAL_FALLBACK_NAME,
231 notifications.level.key(),
232 notifications.include_replies
233 ],
234 )?;
235 Ok(())
236 }
237}
238
239impl Store {
240 pub fn channel_tabs(&self, channel_id: &str) -> Result<Vec<ChannelTabRecord>> {
241 let connection = self.lock()?;
242 let tabs = connection
243 .prepare_cached(
244 "SELECT tab_id, name, definition_id, open_url FROM channel_tabs
245 WHERE channel_id = ?1 ORDER BY position",
246 )?
247 .query_map(params![channel_id], |row| {
248 Ok(ChannelTabRecord {
249 tab_id: row.get(0)?,
250 name: row.get(1)?,
251 definition_id: row.get(2)?,
252 open_url: row.get(3)?,
253 })
254 })?
255 .collect::<rusqlite::Result<_>>()?;
256 Ok(tabs)
257 }
258}
259
260fn compare_names(left: &str, right: &str) -> Ordering {
261 sort_key(left).cmp(&sort_key(right))
262}
263
264const PUNCTUATION_ORDER: &str = "_-,;:!?.'\"()[]{}@*/\\&#%`^+<=>|~$";
265
266const LETTER_FOLDS: &[(&str, &str)] = &[
267 ("àáâãäåāăą", "a"),
268 ("æ", "ae"),
269 ("çćĉċč", "c"),
270 ("ďđ", "d"),
271 ("èéêëēĕėęě", "e"),
272 ("ĝğġģ", "g"),
273 ("ĥħ", "h"),
274 ("ìíîïĩīĭįıǐ", "i"),
275 ("ĵ", "j"),
276 ("ķ", "k"),
277 ("ĺļľŀł", "l"),
278 ("ñńņňʼn", "n"),
279 ("òóôõöøōŏőǒ", "o"),
280 ("œ", "oe"),
281 ("ŕŗř", "r"),
282 ("śŝşš", "s"),
283 ("ß", "ss"),
284 ("ţťŧ", "t"),
285 ("ùúûüũūŭůűųǔ", "u"),
286 ("ŵ", "w"),
287 ("ýÿŷ", "y"),
288 ("źżž", "z"),
289];
290
291fn primary_weights(character: char) -> Vec<(u8, u32)> {
292 if character.is_whitespace() {
293 return vec![(0, 0)];
294 }
295 if let Some(position) = PUNCTUATION_ORDER.find(character) {
296 return vec![(1, position as u32)];
297 }
298 if character.is_ascii_digit() || character.is_alphabetic() {
299 let class = if character.is_numeric() { 2 } else { 3 };
300 if let Some((_, base)) = LETTER_FOLDS
301 .iter()
302 .find(|(variants, _)| variants.contains(character))
303 {
304 return base.chars().map(|letter| (class, letter as u32)).collect();
305 }
306 return vec![(class, character as u32)];
307 }
308 vec![(1, PUNCTUATION_ORDER.len() as u32 + character as u32)]
309}
310
311fn sort_key(name: &str) -> (Vec<(u8, u32)>, String) {
312 let lowered: String = name
313 .trim_start()
314 .chars()
315 .flat_map(char::to_lowercase)
316 .collect();
317 let primary = lowered.chars().flat_map(primary_weights).collect();
318 (primary, lowered)
319}
320
321#[cfg(test)]
322mod tests {
323 use super::compare_names;
324 use std::cmp::Ordering;
325
326 #[test]
327 fn names_compare_like_a_person_reads_them() {
328 assert_eq!(compare_names("alpha", "Beta"), Ordering::Less);
329 assert_eq!(compare_names("Übergabe", "Zoll"), Ordering::Less);
330 assert_eq!(compare_names("Übergabe", "Tests"), Ordering::Greater);
331 assert_eq!(compare_names("🚩 Rollout", "Alpha"), Ordering::Less);
332 }
333
334 #[test]
335 fn tie_breaks_follow_locale_compare() {
336 let ordered = ["x y", "x_y", "x-y", "xy"];
337 for pair in ordered.windows(2) {
338 assert_eq!(compare_names(pair[0], pair[1]), Ordering::Less);
339 }
340 assert_eq!(compare_names("_a", "-a"), Ordering::Less);
341 assert_eq!(compare_names("-a", "(a"), Ordering::Less);
342 assert_eq!(compare_names("(a", "#a"), Ordering::Less);
343 assert_eq!(compare_names("#a", "🚩a"), Ordering::Less);
344 assert_eq!(compare_names("10 x", "2 x"), Ordering::Less);
345 assert_eq!(compare_names("9", "a"), Ordering::Less);
346 assert_eq!(compare_names("e", "é"), Ordering::Less);
347 assert_eq!(compare_names("ss", "ß"), Ordering::Less);
348 assert_eq!(compare_names("a", "ä"), Ordering::Less);
349 assert_eq!(compare_names("ä", "ae"), Ordering::Less);
350 assert_eq!(compare_names("ø", "p"), Ordering::Less);
351 assert_eq!(compare_names("o", "ø"), Ordering::Less);
352 assert_eq!(compare_names("ł", "m"), Ordering::Less);
353 assert_eq!(compare_names("ı", "j"), Ordering::Less);
354 }
355}