Skip to main content

basemapper_core/
attribution.rs

1//! The attribution text styles ask maps to show.
2//!
3//! As MapLibre's attribution control: every source a style's layers draw
4//! from contributes its `attribution`, read from the style, else from the
5//! source's TileJSON (Esri's service JSON names it `copyrightText`) or
6//! PMTiles metadata. HTML is reduced to plain text, duplicates are dropped
7//! and the rest is joined with `" | "`.
8
9use crate::style::StyleInput;
10use crate::BasemapError;
11use serde_json::Value;
12
13/// Plain text from an attribution's HTML: tags dropped, entities decoded,
14/// whitespace collapsed.
15pub fn plain_text(html: &str) -> String {
16    // Inline tags (<a>, <span>) vanish; line and block breaks become spaces.
17    let mut text = String::with_capacity(html.len());
18    let mut tag: Option<String> = None;
19    for c in html.chars() {
20        match (&mut tag, c) {
21            (None, '<') => tag = Some(String::new()),
22            (Some(t), '>') => {
23                let name: String =
24                    t.trim_start_matches('/').chars().take_while(|c| c.is_ascii_alphanumeric()).collect();
25                if matches!(name.to_ascii_lowercase().as_str(), "br" | "p" | "div" | "li" | "tr") {
26                    text.push(' ');
27                }
28                tag = None;
29            }
30            (Some(t), c) => t.push(c),
31            (None, c) => text.push(c),
32        }
33    }
34    let mut out = String::with_capacity(text.len());
35    let mut rest = text.as_str();
36    while let Some(i) = rest.find('&') {
37        out.push_str(&rest[..i]);
38        rest = &rest[i..];
39        let end = rest.find(';').filter(|&e| e <= 10);
40        let decoded = end.and_then(|e| {
41            let name = &rest[1..e];
42            let c = match name {
43                "copy" => Some('©'),
44                "reg" => Some('®'),
45                "amp" => Some('&'),
46                "lt" => Some('<'),
47                "gt" => Some('>'),
48                "quot" => Some('"'),
49                "apos" => Some('\''),
50                "nbsp" => Some(' '),
51                "mdash" => Some('—'),
52                "ndash" => Some('–'),
53                _ => name
54                    .strip_prefix("#x")
55                    .and_then(|h| u32::from_str_radix(h, 16).ok())
56                    .or_else(|| name.strip_prefix('#').and_then(|d| d.parse().ok()))
57                    .and_then(char::from_u32),
58            };
59            c.map(|c| (c, e))
60        });
61        match decoded {
62            Some((c, e)) => {
63                out.push(c);
64                rest = &rest[e + 1..];
65            }
66            None => {
67                out.push('&');
68                rest = &rest[1..];
69            }
70        }
71    }
72    out.push_str(rest);
73    out.split_whitespace().collect::<Vec<_>>().join(" ")
74}
75
76/// A source's attribution: its own, else its TileJSON's or archive's.
77async fn source_attribution(
78    source: &Value,
79    base: Option<&str>,
80    client: &reqwest::Client,
81    auth_token: Option<&str>,
82) -> Option<String> {
83    if let Some(a) = source["attribution"].as_str() {
84        return Some(a.to_owned());
85    }
86    let url = source["url"].as_str()?;
87    if let Some(archive) = url.strip_prefix("pmtiles://") {
88        let reader = crate::open_pmtiles(&crate::resolve_url(archive, base), client).await.ok()?;
89        let meta: Value = serde_json::from_str(&reader.get_metadata().await.ok()?).ok()?;
90        return meta["attribution"].as_str().map(str::to_owned);
91    }
92    let url = crate::resolve_url(url, base);
93    let mut req = client.get(&url);
94    if let Some(token) = auth_token {
95        req = req.header("Authorization", format!("Bearer {token}"));
96    }
97    let tilejson: Value = req.send().await.ok()?.error_for_status().ok()?.json().await.ok()?;
98    tilejson["attribution"].as_str().or_else(|| tilejson["copyrightText"].as_str()).map(str::to_owned)
99}
100
101/// The attribution of `styles` (stacked styles, as [`crate::render`]
102/// takes them), as plain text joined with `" | "`; empty when none is given.
103pub(crate) async fn attribution(
104    styles: &[String],
105    client: &reqwest::Client,
106    auth_token: Option<&str>,
107) -> Result<String, BasemapError> {
108    let mut parts: Vec<String> = Vec::new();
109    // A stacked basemap's name (UGRC.Lite) credits its catalogue entry, not
110    // its services' own metadata (UGRC's hillshade credits "me"), plus the
111    // catalogue basemaps in it (Esri's imagery under UGRC.Hybrid).
112    let mut read: Vec<String> = Vec::new();
113    let mut fixed: Vec<(usize, &'static str)> = Vec::new();
114    for s in styles {
115        match crate::providers::stack_provider(s) {
116            Some(p) => {
117                for part in p.stack.iter().filter(|part| crate::providers::find_provider(part).is_some()) {
118                    read.push(crate::providers::stack_part(part));
119                }
120                fixed.push((read.len(), p.attribution));
121            }
122            None => read.push(s.clone()),
123        }
124    }
125    let mut next_fixed = 0;
126    for (k, s) in read.iter().enumerate() {
127        while next_fixed < fixed.len() && fixed[next_fixed].0 == k {
128            add_credit(&mut parts, fixed[next_fixed].1.to_owned());
129            next_fixed += 1;
130        }
131        let input = StyleInput::detect(s);
132        let json = input.resolve(client, auth_token).await?;
133        let base = match &input {
134            StyleInput::Url(u) if u.starts_with("http") || u.starts_with("file://") => Some(u.as_str()),
135            _ => None,
136        };
137        let style: Value = serde_json::from_str(&json).map_err(|e| BasemapError::StyleParseError(e.to_string()))?;
138        let mut used: Vec<&str> = Vec::new();
139        for layer in style["layers"].as_array().map(Vec::as_slice).unwrap_or(&[]) {
140            if let Some(id) = layer["source"].as_str() {
141                if !used.contains(&id) {
142                    used.push(id);
143                }
144            }
145        }
146        for id in used {
147            if let Some(a) = source_attribution(&style["sources"][id], base, client, auth_token).await {
148                add_credit(&mut parts, plain_text(&a));
149            }
150        }
151    }
152    for (_, credit) in &fixed[next_fixed..] {
153        add_credit(&mut parts, credit.to_string());
154    }
155    Ok(parts.join(" | "))
156}
157
158/// Add a credit, unless another one already includes it (and drop those
159/// it includes).
160fn add_credit(parts: &mut Vec<String>, a: String) {
161    if !a.is_empty() && !parts.iter().any(|p| p.contains(&a)) {
162        parts.retain(|p| !a.contains(p.as_str()));
163        parts.push(a);
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170
171    #[test]
172    fn html_becomes_plain_text() {
173        let ofm = r#"<a href="https://openfreemap.org" target="_blank">OpenFreeMap</a> <a href="https://www.openmaptiles.org/" target="_blank">&copy; OpenMapTiles</a> Data from <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a>"#;
174        assert_eq!(plain_text(ofm), "OpenFreeMap © OpenMapTiles Data from OpenStreetMap");
175        assert_eq!(plain_text("&copy;&#169;&#xA9; A &amp; B &unknown; R&D"), "©©© A & B &unknown; R&D");
176        assert_eq!(plain_text("  Tiles \n © Esri "), "Tiles © Esri");
177        assert_eq!(
178            plain_text("ESA WorldCover 2021 (<a href='x'>CC BY 4.0</a>)<br/>Next"),
179            "ESA WorldCover 2021 (CC BY 4.0) Next"
180        );
181    }
182}