BlueGit

ict rusty-teams

Files

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

sidebar.rs

sidebar.rs 16.2 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.read()?;
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![
212 channel_id,
213 counts.personal,
214 counts.channel,
215 counts.team
216 ])?;
217 }
218 }
219 Ok(transaction.commit()?)
220 }
221
222 pub fn clear_channel_mentions(&self, channel_id: &str) -> Result<()> {
223 self.lock()?.execute(
224 "DELETE FROM channel_mentions WHERE channel_id = ?1",
225 [channel_id],
226 )?;
227 Ok(())
228 }
229
230 pub fn channel_substrate_group_id(&self, channel_id: &str) -> Result<Option<String>> {
231 let connection = self.read()?;
232 Ok(connection
233 .prepare_cached("SELECT substrate_group_id FROM channel_layout WHERE channel_id = ?1")?
234 .query_map([channel_id], |row| row.get::<_, Option<String>>(0))?
235 .next()
236 .transpose()?
237 .flatten())
238 }
239
240 pub fn rename_channel(&self, channel_id: &str, name: &str) -> Result<()> {
241 self.lock()?.execute(
242 "UPDATE channels SET name = ?2 WHERE id = ?1",
243 params![channel_id, name],
244 )?;
245 Ok(())
246 }
247
248 pub fn remove_channel(&self, channel_id: &str) -> Result<()> {
249 self.lock()?
250 .execute("DELETE FROM channels WHERE id = ?1", [channel_id])?;
251 Ok(())
252 }
253
254 /// The team's own thread id, which Teams' CSA routes take: the id of its General channel.
255 pub fn team_thread_id(&self, team_id: &str) -> Result<Option<String>> {
256 let connection = self.read()?;
257 Ok(connection
258 .prepare_cached(
259 "SELECT channels.id FROM channels
260 LEFT JOIN channel_layout ON channel_layout.channel_id = channels.id
261 WHERE channels.team_id = ?1
262 AND COALESCE(channel_layout.general, channels.name = ?2)
263 ORDER BY channels.id LIMIT 1",
264 )?
265 .query_map(params![team_id, GENERAL_FALLBACK_NAME], |row| row.get(0))?
266 .next()
267 .transpose()?)
268 }
269
270 pub fn set_channel_notifications(
271 &self,
272 channel_id: &str,
273 notifications: ChannelNotifications,
274 ) -> Result<()> {
275 self.lock()?.execute(
276 "INSERT INTO channel_layout (channel_id, general, notification_level, include_replies)
277 SELECT id, name = ?2, ?3, ?4 FROM channels WHERE id = ?1
278 ON CONFLICT (channel_id) DO UPDATE SET
279 notification_level = excluded.notification_level,
280 include_replies = excluded.include_replies",
281 params![
282 channel_id,
283 GENERAL_FALLBACK_NAME,
284 notifications.level.key(),
285 notifications.include_replies
286 ],
287 )?;
288 Ok(())
289 }
290
291 pub fn set_channel_hidden(&self, channel_id: &str, hidden: bool) -> Result<()> {
292 self.lock()?.execute(
293 "INSERT INTO channel_layout (channel_id, general, hidden)
294 SELECT id, name = ?2, ?3 FROM channels WHERE id = ?1
295 ON CONFLICT (channel_id) DO UPDATE SET hidden = excluded.hidden",
296 params![channel_id, GENERAL_FALLBACK_NAME, hidden],
297 )?;
298 Ok(())
299 }
300
301 pub fn set_team_hidden(&self, team_id: &str, hidden: bool) -> Result<()> {
302 self.lock()?.execute(
303 "INSERT INTO team_layout (team_id, position, hidden)
304 SELECT ?1, COALESCE(MAX(position) + 1, 0), ?2 FROM team_layout WHERE true
305 ON CONFLICT (team_id) DO UPDATE SET hidden = excluded.hidden",
306 params![team_id, hidden],
307 )?;
308 Ok(())
309 }
310}
311
312impl Store {
313 pub fn channel_tabs(&self, channel_id: &str) -> Result<Vec<ChannelTabRecord>> {
314 let connection = self.read()?;
315 let tabs = connection
316 .prepare_cached(
317 "SELECT tab_id, name, definition_id, open_url FROM channel_tabs
318 WHERE channel_id = ?1 ORDER BY position",
319 )?
320 .query_map(params![channel_id], |row| {
321 Ok(ChannelTabRecord {
322 tab_id: row.get(0)?,
323 name: row.get(1)?,
324 definition_id: row.get(2)?,
325 open_url: row.get(3)?,
326 })
327 })?
328 .collect::<rusqlite::Result<_>>()?;
329 Ok(tabs)
330 }
331}
332
333fn compare_names(left: &str, right: &str) -> Ordering {
334 sort_key(left).cmp(&sort_key(right))
335}
336
337const PUNCTUATION_ORDER: &str = "_-,;:!?.'\"()[]{}@*/\\&#%`^+<=>|~$";
338
339const LETTER_FOLDS: &[(&str, &str)] = &[
340 ("àáâãäåāăą", "a"),
341 ("æ", "ae"),
342 ("çćĉċč", "c"),
343 ("ďđ", "d"),
344 ("èéêëēĕėęě", "e"),
345 ("ĝğġģ", "g"),
346 ("ĥħ", "h"),
347 ("ìíîïĩīĭįıǐ", "i"),
348 ("ĵ", "j"),
349 ("ķ", "k"),
350 ("ĺļľŀł", "l"),
351 ("ñńņňʼn", "n"),
352 ("òóôõöøōŏőǒ", "o"),
353 ("œ", "oe"),
354 ("ŕŗř", "r"),
355 ("śŝşš", "s"),
356 ("ß", "ss"),
357 ("ţťŧ", "t"),
358 ("ùúûüũūŭůűųǔ", "u"),
359 ("ŵ", "w"),
360 ("ýÿŷ", "y"),
361 ("źżž", "z"),
362];
363
364fn primary_weights(character: char) -> Vec<(u8, u32)> {
365 if character.is_whitespace() {
366 return vec![(0, 0)];
367 }
368 if let Some(position) = PUNCTUATION_ORDER.find(character) {
369 return vec![(1, position as u32)];
370 }
371 if character.is_ascii_digit() || character.is_alphabetic() {
372 let class = if character.is_numeric() { 2 } else { 3 };
373 if let Some((_, base)) = LETTER_FOLDS
374 .iter()
375 .find(|(variants, _)| variants.contains(character))
376 {
377 return base.chars().map(|letter| (class, letter as u32)).collect();
378 }
379 return vec![(class, character as u32)];
380 }
381 vec![(1, PUNCTUATION_ORDER.len() as u32 + character as u32)]
382}
383
384fn sort_key(name: &str) -> (Vec<(u8, u32)>, String) {
385 let lowered: String = name
386 .trim_start()
387 .chars()
388 .flat_map(char::to_lowercase)
389 .collect();
390 let primary = lowered.chars().flat_map(primary_weights).collect();
391 (primary, lowered)
392}
393
394#[cfg(test)]
395mod tests {
396 use super::compare_names;
397 use std::cmp::Ordering;
398
399 #[test]
400 fn names_compare_like_a_person_reads_them() {
401 assert_eq!(compare_names("alpha", "Beta"), Ordering::Less);
402 assert_eq!(compare_names("Übergabe", "Zoll"), Ordering::Less);
403 assert_eq!(compare_names("Übergabe", "Tests"), Ordering::Greater);
404 assert_eq!(compare_names("🚩 Rollout", "Alpha"), Ordering::Less);
405 }
406
407 #[test]
408 fn tie_breaks_follow_locale_compare() {
409 let ordered = ["x y", "x_y", "x-y", "xy"];
410 for pair in ordered.windows(2) {
411 assert_eq!(compare_names(pair[0], pair[1]), Ordering::Less);
412 }
413 assert_eq!(compare_names("_a", "-a"), Ordering::Less);
414 assert_eq!(compare_names("-a", "(a"), Ordering::Less);
415 assert_eq!(compare_names("(a", "#a"), Ordering::Less);
416 assert_eq!(compare_names("#a", "🚩a"), Ordering::Less);
417 assert_eq!(compare_names("10 x", "2 x"), Ordering::Less);
418 assert_eq!(compare_names("9", "a"), Ordering::Less);
419 assert_eq!(compare_names("e", "é"), Ordering::Less);
420 assert_eq!(compare_names("ss", "ß"), Ordering::Less);
421 assert_eq!(compare_names("a", "ä"), Ordering::Less);
422 assert_eq!(compare_names("ä", "ae"), Ordering::Less);
423 assert_eq!(compare_names("ø", "p"), Ordering::Less);
424 assert_eq!(compare_names("o", "ø"), Ordering::Less);
425 assert_eq!(compare_names("ł", "m"), Ordering::Less);
426 assert_eq!(compare_names("ı", "j"), Ordering::Less);
427 }
428}