| 1 | use std::cmp::Ordering; |
| 2 | |
| 3 | use rusqlite::params; |
| 4 | |
| 5 | use crate::error::Result; |
| 6 | use crate::models::{ChannelRecord, Sidebar, SidebarTeam, TeamLayoutRecord, TeamRecord}; |
| 7 | use crate::store::Store; |
| 8 | use crate::teams::channel_from_row; |
| 9 | |
| 10 | const GENERAL_FALLBACK_NAME: &str = "General"; |
| 11 | |
| 12 | struct TeamRow { |
| 13 | team: TeamRecord, |
| 14 | position: Option<i64>, |
| 15 | hidden: bool, |
| 16 | } |
| 17 | |
| 18 | struct ChannelRow { |
| 19 | channel: ChannelRecord, |
| 20 | general: bool, |
| 21 | hidden: bool, |
| 22 | } |
| 23 | |
| 24 | impl Store { |
| 25 | pub fn sidebar(&self) -> Result<Sidebar> { |
| 26 | let chats = self.recent_chats(usize::MAX >> 1)?; |
| 27 | let connection = self.lock()?; |
| 28 | let mut team_rows: Vec<TeamRow> = connection |
| 29 | .prepare_cached( |
| 30 | "SELECT teams.id, teams.name, team_layout.position, COALESCE(team_layout.hidden, 0) |
| 31 | FROM teams LEFT JOIN team_layout ON team_layout.team_id = teams.id", |
| 32 | )? |
| 33 | .query_map([], |row| { |
| 34 | Ok(TeamRow { |
| 35 | team: TeamRecord { |
| 36 | id: row.get(0)?, |
| 37 | name: row.get(1)?, |
| 38 | }, |
| 39 | position: row.get(2)?, |
| 40 | hidden: row.get(3)?, |
| 41 | }) |
| 42 | })? |
| 43 | .collect::<rusqlite::Result<_>>()?; |
| 44 | team_rows.sort_by(|left, right| { |
| 45 | match (left.position, right.position) { |
| 46 | (Some(left), Some(right)) => left.cmp(&right), |
| 47 | (Some(_), None) => Ordering::Less, |
| 48 | (None, Some(_)) => Ordering::Greater, |
| 49 | (None, None) => Ordering::Equal, |
| 50 | } |
| 51 | .then_with(|| compare_names(&left.team.name, &right.team.name)) |
| 52 | .then_with(|| left.team.id.cmp(&right.team.id)) |
| 53 | }); |
| 54 | let mut channel_rows: Vec<ChannelRow> = connection |
| 55 | .prepare_cached( |
| 56 | "SELECT id, team_id, name, membership_type, last_message_at, unread, |
| 57 | COALESCE(channel_layout.general, name = ?1), COALESCE(channel_layout.hidden, 0) |
| 58 | FROM channels LEFT JOIN channel_layout ON channel_layout.channel_id = channels.id", |
| 59 | )? |
| 60 | .query_map(params![GENERAL_FALLBACK_NAME], |row| { |
| 61 | Ok(ChannelRow { |
| 62 | channel: channel_from_row(row)?, |
| 63 | general: row.get(6)?, |
| 64 | hidden: row.get(7)?, |
| 65 | }) |
| 66 | })? |
| 67 | .collect::<rusqlite::Result<_>>()?; |
| 68 | channel_rows.sort_by(|left, right| { |
| 69 | right |
| 70 | .general |
| 71 | .cmp(&left.general) |
| 72 | .then_with(|| compare_names(&left.channel.name, &right.channel.name)) |
| 73 | .then_with(|| left.channel.id.cmp(&right.channel.id)) |
| 74 | }); |
| 75 | let mut teams: Vec<SidebarTeam> = team_rows |
| 76 | .into_iter() |
| 77 | .map(|row| SidebarTeam { |
| 78 | team: row.team, |
| 79 | channels: Vec::new(), |
| 80 | hidden: row.hidden, |
| 81 | hidden_channel_ids: Vec::new(), |
| 82 | }) |
| 83 | .collect(); |
| 84 | for row in channel_rows { |
| 85 | if let Some(team) = teams |
| 86 | .iter_mut() |
| 87 | .find(|team| team.team.id == row.channel.team_id) |
| 88 | { |
| 89 | if row.hidden { |
| 90 | team.hidden_channel_ids.push(row.channel.id.clone()); |
| 91 | } |
| 92 | team.channels.push(row.channel); |
| 93 | } |
| 94 | } |
| 95 | Ok(Sidebar { chats, teams }) |
| 96 | } |
| 97 | |
| 98 | pub fn replace_team_layout(&self, layout: &[TeamLayoutRecord]) -> Result<()> { |
| 99 | let mut connection = self.lock()?; |
| 100 | let transaction = connection.transaction()?; |
| 101 | transaction.execute("DELETE FROM team_layout", [])?; |
| 102 | transaction.execute("DELETE FROM channel_layout", [])?; |
| 103 | { |
| 104 | let mut team_insert = transaction.prepare_cached( |
| 105 | "INSERT OR REPLACE INTO team_layout (team_id, position, hidden) VALUES (?1, ?2, ?3)", |
| 106 | )?; |
| 107 | let mut channel_insert = transaction.prepare_cached( |
| 108 | "INSERT OR REPLACE INTO channel_layout (channel_id, general, hidden) VALUES (?1, ?2, ?3)", |
| 109 | )?; |
| 110 | for (position, team) in layout.iter().enumerate() { |
| 111 | team_insert.execute(params![team.team_id, position as i64, team.hidden])?; |
| 112 | for channel in &team.channels { |
| 113 | channel_insert.execute(params![ |
| 114 | channel.channel_id, |
| 115 | channel.general, |
| 116 | channel.hidden |
| 117 | ])?; |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | Ok(transaction.commit()?) |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | fn compare_names(left: &str, right: &str) -> Ordering { |
| 126 | sort_key(left).cmp(&sort_key(right)) |
| 127 | } |
| 128 | |
| 129 | fn sort_key(name: &str) -> (bool, String) { |
| 130 | let trimmed = name.trim_start(); |
| 131 | let starts_with_word = trimmed |
| 132 | .chars() |
| 133 | .next() |
| 134 | .is_some_and(char::is_alphanumeric); |
| 135 | let mut folded = String::with_capacity(trimmed.len()); |
| 136 | for character in trimmed.chars().flat_map(char::to_lowercase) { |
| 137 | match character { |
| 138 | 'ä' | 'á' | 'à' | 'â' => folded.push('a'), |
| 139 | 'ö' | 'ó' | 'ò' | 'ô' => folded.push('o'), |
| 140 | 'ü' | 'ú' | 'ù' | 'û' => folded.push('u'), |
| 141 | 'é' | 'è' | 'ê' | 'ë' => folded.push('e'), |
| 142 | 'ß' => folded.push_str("ss"), |
| 143 | other => folded.push(other), |
| 144 | } |
| 145 | } |
| 146 | (starts_with_word, folded) |
| 147 | } |
| 148 | |
| 149 | #[cfg(test)] |
| 150 | mod tests { |
| 151 | use super::compare_names; |
| 152 | use std::cmp::Ordering; |
| 153 | |
| 154 | #[test] |
| 155 | fn names_compare_like_a_person_reads_them() { |
| 156 | assert_eq!(compare_names("alpha", "Beta"), Ordering::Less); |
| 157 | assert_eq!(compare_names("Übergabe", "Zoll"), Ordering::Less); |
| 158 | assert_eq!(compare_names("Übergabe", "Tests"), Ordering::Greater); |
| 159 | assert_eq!(compare_names("🚩 Rollout", "Alpha"), Ordering::Less); |
| 160 | } |
| 161 | } |