BlueGit

ict rusty-teams

Files

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

sidebar.rs

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