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