| 1 | //! Herkennen en maken van kaart-links (V1: een gewone HTML-link met leesbare ankertekst). |
| 2 | //! |
| 3 | //! Herkend worden: |
| 4 | //! - BC-webclient: `https://kvtmd365.kvt.nl/<KVTMDLive_AAD|KVTGermanyLive_AAD>/?company=…&page=<88|11333028|11333015>&filter='<No.|Contract No.>' IS '<nr>'` |
| 5 | //! - Daedalus: `https://sleutels.kvt.nl/daedalus/…?company=…&workorder=<nr>` → werkorder |
| 6 | //! - Ponos: `https://sleutels.kvt.nl/ponos/…?company=…&project=<nr>` → project |
| 7 | //! |
| 8 | //! Elk ander patroon blijft een gewone link. |
| 9 | |
| 10 | use url::Url; |
| 11 | |
| 12 | use crate::BC_WEB_HOST; |
| 13 | |
| 14 | pub const MAX_CARDS_PER_MESSAGE: usize = 3; |
| 15 | const ENVIRONMENTS: [&str; 2] = ["KVTMDLive_AAD", "KVTGermanyLive_AAD"]; |
| 16 | const SLEUTELS_HOST: &str = "sleutels.kvt.nl"; |
| 17 | |
| 18 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] |
| 19 | pub enum CardKind { |
| 20 | Project, |
| 21 | Werkorder, |
| 22 | Contract, |
| 23 | } |
| 24 | |
| 25 | impl CardKind { |
| 26 | pub const ALL: [CardKind; 3] = [CardKind::Project, CardKind::Werkorder, CardKind::Contract]; |
| 27 | |
| 28 | /// Waarde van `type` in de kaart-API. |
| 29 | pub fn api_name(self) -> &'static str { |
| 30 | match self { |
| 31 | CardKind::Project => "project", |
| 32 | CardKind::Werkorder => "werkorder", |
| 33 | CardKind::Contract => "contract", |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | pub fn from_api_name(name: &str) -> Option<CardKind> { |
| 38 | CardKind::ALL |
| 39 | .into_iter() |
| 40 | .find(|kind| kind.api_name() == name) |
| 41 | } |
| 42 | |
| 43 | /// Nederlandse naam voor de ankertekst (leesbaar in elke Teams-client). |
| 44 | pub fn label_nl(self) -> &'static str { |
| 45 | match self { |
| 46 | CardKind::Project => "Project", |
| 47 | CardKind::Werkorder => "Werkorder", |
| 48 | CardKind::Contract => "Contract", |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | pub fn bc_page(self) -> u32 { |
| 53 | match self { |
| 54 | CardKind::Project => 88, |
| 55 | CardKind::Werkorder => 11333028, |
| 56 | CardKind::Contract => 11333015, |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | pub fn bc_filter_field(self) -> &'static str { |
| 61 | match self { |
| 62 | CardKind::Contract => "Contract No.", |
| 63 | CardKind::Project | CardKind::Werkorder => "No.", |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | fn from_bc_page(page: u32) -> Option<CardKind> { |
| 68 | CardKind::ALL |
| 69 | .into_iter() |
| 70 | .find(|kind| kind.bc_page() == page) |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | /// Verwijzing naar één BC-record. Bevat alleen type, bedrijf en nummer: de |
| 75 | /// details haalt elke kijker zelf op met eigen rechten. |
| 76 | #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] |
| 77 | pub struct CardRef { |
| 78 | pub kind: CardKind, |
| 79 | pub company: String, |
| 80 | pub no: String, |
| 81 | /// Padnaam in de webclient (`KVTMDLive_AAD`), alleen bekend uit een BC-link. |
| 82 | pub environment: Option<String>, |
| 83 | } |
| 84 | |
| 85 | pub fn number_is_valid(no: &str) -> bool { |
| 86 | !no.is_empty() |
| 87 | && no.len() <= 30 |
| 88 | && no |
| 89 | .bytes() |
| 90 | .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) |
| 91 | } |
| 92 | |
| 93 | fn company_is_valid(company: &str) -> bool { |
| 94 | let count = company.chars().count(); |
| 95 | count > 0 |
| 96 | && count <= 60 |
| 97 | && company |
| 98 | .chars() |
| 99 | .all(|c| c.is_alphanumeric() || " .,&()'-".contains(c)) |
| 100 | } |
| 101 | |
| 102 | /// `'No.' IS 'WO2699001'` → (`No.`, `WO2699001`). |
| 103 | fn parse_filter(filter: &str) -> Option<(String, String)> { |
| 104 | let filter = filter.trim(); |
| 105 | let rest = filter.strip_prefix('\'')?; |
| 106 | let (field, rest) = rest.split_once('\'')?; |
| 107 | let rest = rest.trim_start(); |
| 108 | let rest = rest |
| 109 | .strip_prefix("IS") |
| 110 | .or_else(|| rest.strip_prefix("is"))? |
| 111 | .trim_start(); |
| 112 | let value = rest.strip_prefix('\'')?.strip_suffix('\'')?; |
| 113 | if value.contains('\'') { |
| 114 | return None; |
| 115 | } |
| 116 | Some((field.to_owned(), value.to_owned())) |
| 117 | } |
| 118 | |
| 119 | /// Eén link naar een kaart-verwijzing, of `None` (gewone link). |
| 120 | pub fn parse_card_link(href: &str) -> Option<CardRef> { |
| 121 | let url = Url::parse(href.trim()).ok()?; |
| 122 | if url.scheme() != "https" || !url.username().is_empty() || url.password().is_some() { |
| 123 | return None; |
| 124 | } |
| 125 | let host = url.host_str()?.to_ascii_lowercase(); |
| 126 | let query = |name: &str| { |
| 127 | url.query_pairs() |
| 128 | .find(|(key, _)| key == name) |
| 129 | .map(|(_, value)| value.into_owned()) |
| 130 | }; |
| 131 | let company = query("company")?; |
| 132 | if !company_is_valid(&company) { |
| 133 | return None; |
| 134 | } |
| 135 | |
| 136 | if host == BC_WEB_HOST { |
| 137 | let mut segments = url.path_segments()?.filter(|s| !s.is_empty()); |
| 138 | let environment = segments.next()?; |
| 139 | let environment = ENVIRONMENTS |
| 140 | .into_iter() |
| 141 | .find(|known| known.eq_ignore_ascii_case(environment))?; |
| 142 | if segments.next().is_some() { |
| 143 | return None; |
| 144 | } |
| 145 | let kind = CardKind::from_bc_page(query("page")?.parse().ok()?)?; |
| 146 | let (field, no) = parse_filter(&query("filter")?)?; |
| 147 | if field != kind.bc_filter_field() || !number_is_valid(&no) { |
| 148 | return None; |
| 149 | } |
| 150 | return Some(CardRef { |
| 151 | kind, |
| 152 | company, |
| 153 | no, |
| 154 | environment: Some(environment.to_owned()), |
| 155 | }); |
| 156 | } |
| 157 | |
| 158 | if host == SLEUTELS_HOST { |
| 159 | let app = url |
| 160 | .path_segments()? |
| 161 | .find(|s| !s.is_empty())? |
| 162 | .to_ascii_lowercase(); |
| 163 | let (kind, no) = match app.as_str() { |
| 164 | "daedalus" => (CardKind::Werkorder, query("workorder")?), |
| 165 | "ponos" => (CardKind::Project, query("project")?), |
| 166 | _ => return None, |
| 167 | }; |
| 168 | if !number_is_valid(&no) { |
| 169 | return None; |
| 170 | } |
| 171 | return Some(CardRef { |
| 172 | kind, |
| 173 | company, |
| 174 | no, |
| 175 | environment: None, |
| 176 | }); |
| 177 | } |
| 178 | |
| 179 | None |
| 180 | } |
| 181 | |
| 182 | /// Kaart-verwijzingen uit de links van één bericht: ontdubbeld, in volgorde, hooguit |
| 183 | /// [`MAX_CARDS_PER_MESSAGE`]. Daarna blijven het gewone links. |
| 184 | pub fn card_refs_in_urls<'a>(urls: impl IntoIterator<Item = &'a str>) -> Vec<CardRef> { |
| 185 | let mut refs: Vec<CardRef> = Vec::new(); |
| 186 | for url in urls { |
| 187 | let Some(card) = parse_card_link(url) else { |
| 188 | continue; |
| 189 | }; |
| 190 | if refs.iter().any(|known| { |
| 191 | known.kind == card.kind && known.company == card.company && known.no == card.no |
| 192 | }) { |
| 193 | continue; |
| 194 | } |
| 195 | refs.push(card); |
| 196 | if refs.len() == MAX_CARDS_PER_MESSAGE { |
| 197 | break; |
| 198 | } |
| 199 | } |
| 200 | refs |
| 201 | } |
| 202 | |
| 203 | /// BC-webclient-link voor een verwijzing (zelfde vorm als Kairos en Mímir). |
| 204 | pub fn bc_url(kind: CardKind, company: &str, no: &str, environment: Option<&str>) -> String { |
| 205 | let environment = environment.unwrap_or(if company == "KVT Germany" { |
| 206 | "KVTGermanyLive_AAD" |
| 207 | } else { |
| 208 | "KVTMDLive_AAD" |
| 209 | }); |
| 210 | let filter = format!( |
| 211 | "'{}' IS '{}'", |
| 212 | kind.bc_filter_field(), |
| 213 | no.replace('\'', "''") |
| 214 | ); |
| 215 | format!( |
| 216 | "https://{BC_WEB_HOST}/{}/?company={}&page={}&filter={}", |
| 217 | encode(environment), |
| 218 | encode(company), |
| 219 | kind.bc_page(), |
| 220 | encode(&filter) |
| 221 | ) |
| 222 | } |
| 223 | |
| 224 | /// Zoals PHP `rawurlencode` (Kairos, Mímir): alles behalve `A-Za-z0-9-_.~`. |
| 225 | const RAWURL: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC |
| 226 | .remove(b'-') |
| 227 | .remove(b'_') |
| 228 | .remove(b'.') |
| 229 | .remove(b'~'); |
| 230 | |
| 231 | fn encode(value: &str) -> String { |
| 232 | percent_encoding::utf8_percent_encode(value, RAWURL).to_string() |
| 233 | } |
| 234 | |
| 235 | /// Alleen links naar de BC-webclient of sleutels.kvt.nl uit een Mímir-antwoord |
| 236 | /// mogen geopend of verzonden worden. |
| 237 | pub fn is_trusted_link(href: &str) -> bool { |
| 238 | let Ok(url) = Url::parse(href.trim()) else { |
| 239 | return false; |
| 240 | }; |
| 241 | url.scheme() == "https" |
| 242 | && url.username().is_empty() |
| 243 | && url.password().is_none() |
| 244 | && url.port().is_none() |
| 245 | && matches!(url.host_str(), Some(BC_WEB_HOST) | Some(SLEUTELS_HOST)) |
| 246 | } |
| 247 | |
| 248 | /// Ankertekst: «Werkorder WO2699001 - Onderhoud 500 uur» (omschrijving optioneel). |
| 249 | pub fn anchor_text(kind: CardKind, no: &str, title: Option<&str>) -> String { |
| 250 | match title.map(str::trim).filter(|title| !title.is_empty()) { |
| 251 | Some(title) => format!("{} {no} - {title}", kind.label_nl()), |
| 252 | None => format!("{} {no}", kind.label_nl()), |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | /// Het HTML-fragment dat verzonden wordt: een gewone link, zodat de officiële Teams |
| 257 | /// een klikbare tekst toont en rusty-teams er een kaart van maakt. |
| 258 | pub fn anchor_html( |
| 259 | kind: CardKind, |
| 260 | company: &str, |
| 261 | no: &str, |
| 262 | title: Option<&str>, |
| 263 | environment: Option<&str>, |
| 264 | ) -> String { |
| 265 | format!( |
| 266 | "<a href=\"{}\">{}</a>", |
| 267 | escape_html(&bc_url(kind, company, no, environment)), |
| 268 | escape_html(&anchor_text(kind, no, title)) |
| 269 | ) |
| 270 | } |
| 271 | |
| 272 | fn escape_html(text: &str) -> String { |
| 273 | let mut out = String::with_capacity(text.len()); |
| 274 | for c in text.chars() { |
| 275 | match c { |
| 276 | '&' => out.push_str("&"), |
| 277 | '<' => out.push_str("<"), |
| 278 | '>' => out.push_str(">"), |
| 279 | '"' => out.push_str("""), |
| 280 | '\'' => out.push_str("'"), |
| 281 | _ => out.push(c), |
| 282 | } |
| 283 | } |
| 284 | out |
| 285 | } |
| 286 | |
| 287 | #[cfg(test)] |
| 288 | mod tests { |
| 289 | use super::*; |
| 290 | |
| 291 | const WO: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=11333028&filter=%27No.%27%20IS%20%27WO2699001%27"; |
| 292 | |
| 293 | #[test] |
| 294 | fn recognises_a_work_order_link() { |
| 295 | let card = parse_card_link(WO).unwrap(); |
| 296 | assert_eq!(card.kind, CardKind::Werkorder); |
| 297 | assert_eq!(card.company, "Koninklijke van Twist"); |
| 298 | assert_eq!(card.no, "WO2699001"); |
| 299 | assert_eq!(card.environment.as_deref(), Some("KVTMDLive_AAD")); |
| 300 | } |
| 301 | |
| 302 | #[test] |
| 303 | fn recognises_project_and_contract_pages() { |
| 304 | let project = parse_card_link("https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=88&filter=%27No.%27%20IS%20%27PRJ2699001%27").unwrap(); |
| 305 | assert_eq!(project.kind, CardKind::Project); |
| 306 | let contract = parse_card_link("https://kvtmd365.kvt.nl/KVTGermanyLive_AAD/?company=KVT%20Germany&page=11333015&filter=%27Contract%20No.%27%20IS%20%27CT2699001%27").unwrap(); |
| 307 | assert_eq!(contract.kind, CardKind::Contract); |
| 308 | assert_eq!(contract.environment.as_deref(), Some("KVTGermanyLive_AAD")); |
| 309 | } |
| 310 | |
| 311 | #[test] |
| 312 | fn other_patterns_stay_plain_links() { |
| 313 | for href in [ |
| 314 | "http://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=X&page=88&filter=%27No.%27%20IS%20%27P1%27", |
| 315 | "https://kvtmd365.kvt.nl.evil.example/KVTMDLive_AAD/?company=X&page=88&filter=%27No.%27%20IS%20%27P1%27", |
| 316 | "https://kvtmd365.kvt.nl/OtherEnv/?company=X&page=88&filter=%27No.%27%20IS%20%27P1%27", |
| 317 | "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=X&page=21&filter=%27No.%27%20IS%20%27C1%27", |
| 318 | "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=X&page=11333015&filter=%27No.%27%20IS%20%27CT1%27", |
| 319 | "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=X&page=88&filter=%27No.%27%20IS%20%27P1%27%27%20or%20%27x%27", |
| 320 | "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=X&page=88&filter=%27No.%27%20IS%20%27P%201%27", |
| 321 | "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?page=88&filter=%27No.%27%20IS%20%27P1%27", |
| 322 | "https://user:pw@kvtmd365.kvt.nl/KVTMDLive_AAD/?company=X&page=88&filter=%27No.%27%20IS%20%27P1%27", |
| 323 | "https://example.com/?company=X&workorder=WO1", |
| 324 | "https://sleutels.kvt.nl/asclepius/?company=X&workorder=WO1", |
| 325 | ] { |
| 326 | assert_eq!(parse_card_link(href), None, "{href}"); |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | #[test] |
| 331 | fn only_bc_and_sleutels_links_are_trusted() { |
| 332 | assert!(is_trusted_link( |
| 333 | "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?page=88" |
| 334 | )); |
| 335 | assert!(is_trusted_link( |
| 336 | "https://sleutels.kvt.nl/daedalus/index.php" |
| 337 | )); |
| 338 | assert!(!is_trusted_link("http://kvtmd365.kvt.nl/")); |
| 339 | assert!(!is_trusted_link("https://kvtmd365.kvt.nl.example.com/")); |
| 340 | assert!(!is_trusted_link("https://user@sleutels.kvt.nl/")); |
| 341 | assert!(!is_trusted_link("https://sleutels.kvt.nl:8443/")); |
| 342 | assert!(!is_trusted_link("javascript:alert(1)")); |
| 343 | } |
| 344 | |
| 345 | #[test] |
| 346 | fn recognises_sleutels_links() { |
| 347 | let daedalus = parse_card_link("https://sleutels.kvt.nl/daedalus/index.php?company=Koninklijke%20van%20Twist&person=9001&workorder=WO2699001").unwrap(); |
| 348 | assert_eq!( |
| 349 | (daedalus.kind, daedalus.no.as_str()), |
| 350 | (CardKind::Werkorder, "WO2699001") |
| 351 | ); |
| 352 | let ponos = parse_card_link("https://sleutels.kvt.nl/ponos/?company=Koninklijke%20van%20Twist&dept=X&project=PRJ2699001&task=1").unwrap(); |
| 353 | assert_eq!( |
| 354 | (ponos.kind, ponos.no.as_str()), |
| 355 | (CardKind::Project, "PRJ2699001") |
| 356 | ); |
| 357 | } |
| 358 | |
| 359 | #[test] |
| 360 | fn at_most_three_cards_and_no_duplicates() { |
| 361 | let p = |n: u32| { |
| 362 | format!( |
| 363 | "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=X&page=88&filter=%27No.%27%20IS%20%27P{n}%27" |
| 364 | ) |
| 365 | }; |
| 366 | let urls = [p(1), p(1), p(2), p(3), p(4)]; |
| 367 | let refs = card_refs_in_urls(urls.iter().map(String::as_str)); |
| 368 | assert_eq!( |
| 369 | refs.iter().map(|r| r.no.as_str()).collect::<Vec<_>>(), |
| 370 | ["P1", "P2", "P3"] |
| 371 | ); |
| 372 | } |
| 373 | |
| 374 | #[test] |
| 375 | fn built_link_round_trips_and_matches_mimir() { |
| 376 | let url = bc_url( |
| 377 | CardKind::Werkorder, |
| 378 | "Koninklijke van Twist", |
| 379 | "WO2699001", |
| 380 | None, |
| 381 | ); |
| 382 | assert_eq!(url, WO); |
| 383 | let card = parse_card_link(&url).unwrap(); |
| 384 | assert_eq!(card.no, "WO2699001"); |
| 385 | let contract = bc_url( |
| 386 | CardKind::Contract, |
| 387 | "Koninklijke van Twist", |
| 388 | "CT25000004", |
| 389 | None, |
| 390 | ); |
| 391 | assert!( |
| 392 | contract.ends_with("page=11333015&filter=%27Contract%20No.%27%20IS%20%27CT25000004%27") |
| 393 | ); |
| 394 | assert_eq!(parse_card_link(&contract).unwrap().kind, CardKind::Contract); |
| 395 | } |
| 396 | |
| 397 | #[test] |
| 398 | fn anchor_is_readable_and_escaped() { |
| 399 | assert_eq!( |
| 400 | anchor_text(CardKind::Werkorder, "WO2699001", Some("Onderhoud 500 uur")), |
| 401 | "Werkorder WO2699001 - Onderhoud 500 uur" |
| 402 | ); |
| 403 | assert_eq!(anchor_text(CardKind::Project, "PRJ1", None), "Project PRJ1"); |
| 404 | let html = anchor_html( |
| 405 | CardKind::Project, |
| 406 | "Koninklijke van Twist", |
| 407 | "PRJ1", |
| 408 | Some("<b>A & B</b>"), |
| 409 | None, |
| 410 | ); |
| 411 | assert!(html.starts_with("<a href=\"https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=88")); |
| 412 | assert!(html.ends_with(">Project PRJ1 - <b>A & B</b></a>")); |
| 413 | } |
| 414 | } |