BlueGit

ict rusty-teams

Files

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

sidebar.rs

sidebar.rs 16.1 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, TeamRights,
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 rights: TeamRights,
21}
22
23struct ChannelRow {
24 channel: ChannelRecord,
25 general: bool,
26 hidden: bool,
27 notifications: ChannelNotifications,
28}
29
30impl Store {
31 pub fn sidebar(&self) -> Result<Sidebar> {
32 let chats = self.recent_chats(usize::MAX >> 1)?;
33 let connection = self.lock()?;
34 let mut team_rows: Vec<TeamRow> = connection
35 .prepare_cached(
36 "SELECT teams.id, teams.name, team_layout.position, COALESCE(team_layout.hidden, 0),
37 COALESCE(team_layout.owner, 0), COALESCE(team_layout.add_channel, 0),
38 COALESCE(team_layout.add_private_channel, 0),
39 COALESCE(team_layout.edit_channel, 0), COALESCE(team_layout.delete_channel, 0)
40 FROM teams LEFT JOIN team_layout ON team_layout.team_id = teams.id",
41 )?
42 .query_map([], |row| {
43 Ok(TeamRow {
44 team: TeamRecord {
45 id: row.get(0)?,
46 name: row.get(1)?,
47 },
48 position: row.get(2)?,
49 hidden: row.get(3)?,
50 rights: TeamRights {
51 owner: row.get(4)?,
52 add_channel: row.get(5)?,
53 add_private_channel: row.get(6)?,
54 edit_channel: row.get(7)?,
55 delete_channel: row.get(8)?,
56 },
57 })
58 })?
59 .collect::<rusqlite::Result<_>>()?;
60 team_rows.sort_by(|left, right| {
61 match (left.position, right.position) {
62 (Some(left), Some(right)) => left.cmp(&right),
63 (Some(_), None) => Ordering::Less,
64 (None, Some(_)) => Ordering::Greater,
65 (None, None) => Ordering::Equal,
66 }
67 .then_with(|| compare_names(&left.team.name, &right.team.name))
68 .then_with(|| left.team.id.cmp(&right.team.id))
69 });
70 let mut channel_rows: Vec<ChannelRow> = connection
71 .prepare_cached(
72 "SELECT id, team_id, name, membership_type, last_message_at, unread,
73 COALESCE(channel_layout.general, name = ?1), COALESCE(channel_layout.hidden, 0),
74 COALESCE(channel_layout.notification_level, 'feed'),
75 COALESCE(channel_layout.include_replies, 0)
76 FROM channels LEFT JOIN channel_layout ON channel_layout.channel_id = channels.id",
77 )?
78 .query_map(params![GENERAL_FALLBACK_NAME], |row| {
79 Ok(ChannelRow {
80 channel: channel_from_row(row)?,
81 general: row.get(6)?,
82 hidden: row.get(7)?,
83 notifications: ChannelNotifications {
84 level: ChannelNotificationLevel::from_key(&row.get::<_, String>(8)?),
85 include_replies: row.get(9)?,
86 },
87 })
88 })?
89 .collect::<rusqlite::Result<_>>()?;
90 channel_rows.sort_by(|left, right| {
91 right
92 .general
93 .cmp(&left.general)
94 .then_with(|| compare_names(&left.channel.name, &right.channel.name))
95 .then_with(|| left.channel.id.cmp(&right.channel.id))
96 });
97 let mut mentions: HashMap<String, ChannelMentions> = connection
98 .prepare_cached("SELECT channel_id, personal, channel, team FROM channel_mentions")?
99 .query_map([], |row| {
100 Ok((
101 row.get::<_, String>(0)?,
102 ChannelMentions {
103 personal: row.get(1)?,
104 channel: row.get(2)?,
105 team: row.get(3)?,
106 },
107 ))
108 })?
109 .collect::<rusqlite::Result<_>>()?;
110 let mut teams: Vec<SidebarTeam> = team_rows
111 .into_iter()
112 .map(|row| SidebarTeam {
113 team: row.team,
114 channels: Vec::new(),
115 hidden: row.hidden,
116 rights: row.rights,
117 hidden_channel_ids: Vec::new(),
118 notifications: HashMap::new(),
119 mentions: HashMap::new(),
120 })
121 .collect();
122 for row in channel_rows {
123 if let Some(team) = teams
124 .iter_mut()
125 .find(|team| team.team.id == row.channel.team_id)
126 {
127 if row.hidden {
128 team.hidden_channel_ids.push(row.channel.id.clone());
129 }
130 if row.notifications != ChannelNotifications::default() {
131 team.notifications
132 .insert(row.channel.id.clone(), row.notifications);
133 }
134 if let Some(found) = mentions.remove(&row.channel.id) {
135 team.mentions.insert(row.channel.id.clone(), found);
136 }
137 team.channels.push(row.channel);
138 }
139 }
140 Ok(Sidebar { chats, teams })
141 }
142
143 pub fn replace_team_layout(&self, layout: &[TeamLayoutRecord]) -> Result<()> {
144 let mut connection = self.lock()?;
145 let transaction = connection.transaction()?;
146 transaction.execute("DELETE FROM team_layout", [])?;
147 transaction.execute("DELETE FROM channel_layout", [])?;
148 transaction.execute("DELETE FROM channel_tabs", [])?;
149 {
150 let mut team_insert = transaction.prepare_cached(
151 "INSERT OR REPLACE INTO team_layout
152 (team_id, position, hidden, owner, add_channel, add_private_channel, edit_channel, delete_channel)
153 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
154 )?;
155 let mut channel_insert = transaction.prepare_cached(
156 "INSERT OR REPLACE INTO channel_layout
157 (channel_id, general, hidden, notification_level, include_replies, substrate_group_id)
158 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
159 )?;
160 let mut tab_insert = transaction.prepare_cached(
161 "INSERT OR REPLACE INTO channel_tabs (channel_id, position, tab_id, name, definition_id, open_url)
162 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
163 )?;
164 for (position, team) in layout.iter().enumerate() {
165 team_insert.execute(params![
166 team.team_id,
167 position as i64,
168 team.hidden,
169 team.rights.owner,
170 team.rights.add_channel,
171 team.rights.add_private_channel,
172 team.rights.edit_channel,
173 team.rights.delete_channel
174 ])?;
175 for channel in &team.channels {
176 channel_insert.execute(params![
177 channel.channel_id,
178 channel.general,
179 channel.hidden,
180 channel.notifications.level.key(),
181 channel.notifications.include_replies,
182 channel.substrate_group_id
183 ])?;
184 for (tab_position, tab) in channel.tabs.iter().enumerate() {
185 tab_insert.execute(params![
186 channel.channel_id,
187 tab_position as i64,
188 tab.tab_id,
189 tab.name,
190 tab.definition_id,
191 tab.open_url
192 ])?;
193 }
194 }
195 }
196 }
197 Ok(transaction.commit()?)
198 }
199
200 /// Replaces every stored mention count; channels left out have none.
201 pub fn replace_channel_mentions(&self, mentions: &[(String, ChannelMentions)]) -> Result<()> {
202 let mut connection = self.lock()?;
203 let transaction = connection.transaction()?;
204 transaction.execute("DELETE FROM channel_mentions", [])?;
205 {
206 let mut insert = transaction.prepare_cached(
207 "INSERT OR REPLACE INTO channel_mentions (channel_id, personal, channel, team)
208 VALUES (?1, ?2, ?3, ?4)",
209 )?;
210 for (channel_id, counts) in mentions.iter().filter(|(_, counts)| !counts.is_empty()) {
211 insert.execute(params![channel_id, counts.personal, counts.channel, counts.team])?;
212 }
213 }
214 Ok(transaction.commit()?)
215 }
216
217 pub fn clear_channel_mentions(&self, channel_id: &str) -> Result<()> {
218 self.lock()?.execute(
219 "DELETE FROM channel_mentions WHERE channel_id = ?1",
220 [channel_id],
221 )?;
222 Ok(())
223 }
224
225 pub fn channel_substrate_group_id(&self, channel_id: &str) -> Result<Option<String>> {
226 let connection = self.lock()?;
227 Ok(connection
228 .prepare_cached("SELECT substrate_group_id FROM channel_layout WHERE channel_id = ?1")?
229 .query_map([channel_id], |row| row.get::<_, Option<String>>(0))?
230 .next()
231 .transpose()?
232 .flatten())
233 }
234
235 pub fn rename_channel(&self, channel_id: &str, name: &str) -> Result<()> {
236 self.lock()?.execute(
237 "UPDATE channels SET name = ?2 WHERE id = ?1",
238 params![channel_id, name],
239 )?;
240 Ok(())
241 }
242
243 pub fn remove_channel(&self, channel_id: &str) -> Result<()> {
244 self.lock()?
245 .execute("DELETE FROM channels WHERE id = ?1", [channel_id])?;
246 Ok(())
247 }
248
249 /// The team's own thread id, which Teams' CSA routes take: the id of its General channel.
250 pub fn team_thread_id(&self, team_id: &str) -> Result<Option<String>> {
251 let connection = self.lock()?;
252 Ok(connection
253 .prepare_cached(
254 "SELECT channels.id FROM channels
255 LEFT JOIN channel_layout ON channel_layout.channel_id = channels.id
256 WHERE channels.team_id = ?1
257 AND COALESCE(channel_layout.general, channels.name = ?2)
258 ORDER BY channels.id LIMIT 1",
259 )?
260 .query_map(params![team_id, GENERAL_FALLBACK_NAME], |row| row.get(0))?
261 .next()
262 .transpose()?)
263 }
264
265 pub fn set_channel_notifications(
266 &self,
267 channel_id: &str,
268 notifications: ChannelNotifications,
269 ) -> Result<()> {
270 self.lock()?.execute(
271 "INSERT INTO channel_layout (channel_id, general, notification_level, include_replies)
272 SELECT id, name = ?2, ?3, ?4 FROM channels WHERE id = ?1
273 ON CONFLICT (channel_id) DO UPDATE SET
274 notification_level = excluded.notification_level,
275 include_replies = excluded.include_replies",
276 params![
277 channel_id,
278 GENERAL_FALLBACK_NAME,
279 notifications.level.key(),
280 notifications.include_replies
281 ],
282 )?;
283 Ok(())
284 }
285
286 pub fn set_channel_hidden(&self, channel_id: &str, hidden: bool) -> Result<()> {
287 self.lock()?.execute(
288 "INSERT INTO channel_layout (channel_id, general, hidden)
289 SELECT id, name = ?2, ?3 FROM channels WHERE id = ?1
290 ON CONFLICT (channel_id) DO UPDATE SET hidden = excluded.hidden",
291 params![channel_id, GENERAL_FALLBACK_NAME, hidden],
292 )?;
293 Ok(())
294 }
295
296 pub fn set_team_hidden(&self, team_id: &str, hidden: bool) -> Result<()> {
297 self.lock()?.execute(
298 "INSERT INTO team_layout (team_id, position, hidden)
299 SELECT ?1, COALESCE(MAX(position) + 1, 0), ?2 FROM team_layout WHERE true
300 ON CONFLICT (team_id) DO UPDATE SET hidden = excluded.hidden",
301 params![team_id, hidden],
302 )?;
303 Ok(())
304 }
305}
306
307impl Store {
308 pub fn channel_tabs(&self, channel_id: &str) -> Result<Vec<ChannelTabRecord>> {
309 let connection = self.lock()?;
310 let tabs = connection
311 .prepare_cached(
312 "SELECT tab_id, name, definition_id, open_url FROM channel_tabs
313 WHERE channel_id = ?1 ORDER BY position",
314 )?
315 .query_map(params![channel_id], |row| {
316 Ok(ChannelTabRecord {
317 tab_id: row.get(0)?,
318 name: row.get(1)?,
319 definition_id: row.get(2)?,
320 open_url: row.get(3)?,
321 })
322 })?
323 .collect::<rusqlite::Result<_>>()?;
324 Ok(tabs)
325 }
326}
327
328fn compare_names(left: &str, right: &str) -> Ordering {
329 sort_key(left).cmp(&sort_key(right))
330}
331
332const PUNCTUATION_ORDER: &str = "_-,;:!?.'\"()[]{}@*/\\&#%`^+<=>|~$";
333
334const LETTER_FOLDS: &[(&str, &str)] = &[
335 ("àáâãäåāăą", "a"),
336 ("æ", "ae"),
337 ("çćĉċč", "c"),
338 ("ďđ", "d"),
339 ("èéêëēĕėęě", "e"),
340 ("ĝğġģ", "g"),
341 ("ĥħ", "h"),
342 ("ìíîïĩīĭįıǐ", "i"),
343 ("ĵ", "j"),
344 ("ķ", "k"),
345 ("ĺļľŀł", "l"),
346 ("ñńņňʼn", "n"),
347 ("òóôõöøōŏőǒ", "o"),
348 ("œ", "oe"),
349 ("ŕŗř", "r"),
350 ("śŝşš", "s"),
351 ("ß", "ss"),
352 ("ţťŧ", "t"),
353 ("ùúûüũūŭůűųǔ", "u"),
354 ("ŵ", "w"),
355 ("ýÿŷ", "y"),
356 ("źżž", "z"),
357];
358
359fn primary_weights(character: char) -> Vec<(u8, u32)> {
360 if character.is_whitespace() {
361 return vec![(0, 0)];
362 }
363 if let Some(position) = PUNCTUATION_ORDER.find(character) {
364 return vec![(1, position as u32)];
365 }
366 if character.is_ascii_digit() || character.is_alphabetic() {
367 let class = if character.is_numeric() { 2 } else { 3 };
368 if let Some((_, base)) = LETTER_FOLDS
369 .iter()
370 .find(|(variants, _)| variants.contains(character))
371 {
372 return base.chars().map(|letter| (class, letter as u32)).collect();
373 }
374 return vec![(class, character as u32)];
375 }
376 vec![(1, PUNCTUATION_ORDER.len() as u32 + character as u32)]
377}
378
379fn sort_key(name: &str) -> (Vec<(u8, u32)>, String) {
380 let lowered: String = name
381 .trim_start()
382 .chars()
383 .flat_map(char::to_lowercase)
384 .collect();
385 let primary = lowered.chars().flat_map(primary_weights).collect();
386 (primary, lowered)
387}
388
389#[cfg(test)]
390mod tests {
391 use super::compare_names;
392 use std::cmp::Ordering;
393
394 #[test]
395 fn names_compare_like_a_person_reads_them() {
396 assert_eq!(compare_names("alpha", "Beta"), Ordering::Less);
397 assert_eq!(compare_names("Übergabe", "Zoll"), Ordering::Less);
398 assert_eq!(compare_names("Übergabe", "Tests"), Ordering::Greater);
399 assert_eq!(compare_names("🚩 Rollout", "Alpha"), Ordering::Less);
400 }
401
402 #[test]
403 fn tie_breaks_follow_locale_compare() {
404 let ordered = ["x y", "x_y", "x-y", "xy"];
405 for pair in ordered.windows(2) {
406 assert_eq!(compare_names(pair[0], pair[1]), Ordering::Less);
407 }
408 assert_eq!(compare_names("_a", "-a"), Ordering::Less);
409 assert_eq!(compare_names("-a", "(a"), Ordering::Less);
410 assert_eq!(compare_names("(a", "#a"), Ordering::Less);
411 assert_eq!(compare_names("#a", "🚩a"), Ordering::Less);
412 assert_eq!(compare_names("10 x", "2 x"), Ordering::Less);
413 assert_eq!(compare_names("9", "a"), Ordering::Less);
414 assert_eq!(compare_names("e", "é"), Ordering::Less);
415 assert_eq!(compare_names("ss", "ß"), Ordering::Less);
416 assert_eq!(compare_names("a", "ä"), Ordering::Less);
417 assert_eq!(compare_names("ä", "ae"), Ordering::Less);
418 assert_eq!(compare_names("ø", "p"), Ordering::Less);
419 assert_eq!(compare_names("o", "ø"), Ordering::Less);
420 assert_eq!(compare_names("ł", "m"), Ordering::Less);
421 assert_eq!(compare_names("ı", "j"), Ordering::Less);
422 }
423}