Skip to main content

pinterest_url_normalizer/
lib.rs

1//! Parse, classify, and normalize supported Pinterest URLs without network requests.
2//!
3//! Full Pinterest URLs are normalized to `www.pinterest.com`. Short `pin.it`
4//! links retain their host because resolving them requires a network request.
5
6use serde::Serialize;
7use std::error::Error;
8use std::fmt;
9use url::Url;
10
11const COUNTRY_HOSTS: &[&str] = &[
12    "pinterest.at",
13    "pinterest.be",
14    "pinterest.ca",
15    "pinterest.ch",
16    "pinterest.cl",
17    "pinterest.co",
18    "pinterest.co.kr",
19    "pinterest.co.nz",
20    "pinterest.co.uk",
21    "pinterest.com.au",
22    "pinterest.com.br",
23    "pinterest.com.mx",
24    "pinterest.com.pe",
25    "pinterest.com.tr",
26    "pinterest.cz",
27    "pinterest.de",
28    "pinterest.dk",
29    "pinterest.es",
30    "pinterest.fi",
31    "pinterest.fr",
32    "pinterest.gr",
33    "pinterest.hu",
34    "pinterest.id",
35    "pinterest.ie",
36    "pinterest.it",
37    "pinterest.jp",
38    "pinterest.nl",
39    "pinterest.no",
40    "pinterest.ph",
41    "pinterest.pl",
42    "pinterest.pt",
43    "pinterest.ro",
44    "pinterest.se",
45    "pinterest.sk",
46];
47
48const REGIONAL_SUBDOMAINS: &[&str] = &[
49    "at", "au", "be", "br", "ca", "ch", "cl", "co", "cz", "de", "dk", "es", "fi", "fr", "gr", "hu",
50    "id", "ie", "it", "jp", "kr", "mx", "nl", "no", "nz", "pe", "ph", "pl", "pt", "ro", "se", "sk",
51    "tr", "uk",
52];
53
54const RESERVED_FIRST_SEGMENTS: &[&str] = &[
55    "business",
56    "categories",
57    "explore",
58    "help",
59    "ideas",
60    "login",
61    "logout",
62    "oauth",
63    "pin",
64    "pin-builder",
65    "resource",
66    "search",
67    "settings",
68    "signup",
69    "today",
70    "topics",
71];
72
73const CANONICAL_HOST: &str = "www.pinterest.com";
74const SHORT_HOST: &str = "pin.it";
75
76/// The supported Pinterest URL classes.
77#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
78#[serde(rename_all = "lowercase")]
79pub enum PinterestUrlKind {
80    Pin,
81    Short,
82    Profile,
83    Board,
84    Ideas,
85}
86
87/// A parsed Pinterest URL and its canonical representation.
88#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
89pub struct ParsedPinterestUrl {
90    pub kind: PinterestUrlKind,
91    pub original_url: String,
92    pub normalized_url: String,
93    pub host: String,
94    #[serde(skip_serializing_if = "Option::is_none")]
95    pub pin_id: Option<String>,
96    #[serde(skip_serializing_if = "Option::is_none")]
97    pub shortcode: Option<String>,
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub username: Option<String>,
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub board_slug: Option<String>,
102    #[serde(skip_serializing_if = "Option::is_none")]
103    pub idea_slug: Option<String>,
104    #[serde(skip_serializing_if = "Option::is_none")]
105    pub idea_id: Option<String>,
106}
107
108impl ParsedPinterestUrl {
109    fn new(kind: PinterestUrlKind, original_url: &str, normalized_url: String) -> Self {
110        let host = match kind {
111            PinterestUrlKind::Short => SHORT_HOST,
112            _ => CANONICAL_HOST,
113        };
114
115        Self {
116            kind,
117            original_url: original_url.to_owned(),
118            normalized_url,
119            host: host.to_owned(),
120            pin_id: None,
121            shortcode: None,
122            username: None,
123            board_slug: None,
124            idea_slug: None,
125            idea_id: None,
126        }
127    }
128}
129
130/// Machine-readable error categories returned by this crate.
131#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
132#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
133pub enum PinterestUrlErrorCode {
134    InvalidUrl,
135    UnsupportedUrl,
136}
137
138impl fmt::Display for PinterestUrlErrorCode {
139    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
140        match self {
141            Self::InvalidUrl => formatter.write_str("INVALID_URL"),
142            Self::UnsupportedUrl => formatter.write_str("UNSUPPORTED_URL"),
143        }
144    }
145}
146
147/// An error returned when an input is invalid or uses an unsupported Pinterest path.
148#[derive(Clone, Debug, Eq, PartialEq)]
149pub struct PinterestUrlError {
150    pub code: PinterestUrlErrorCode,
151    message: &'static str,
152}
153
154impl PinterestUrlError {
155    fn new(code: PinterestUrlErrorCode, message: &'static str) -> Self {
156        Self { code, message }
157    }
158}
159
160impl fmt::Display for PinterestUrlError {
161    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
162        formatter.write_str(self.message)
163    }
164}
165
166impl Error for PinterestUrlError {}
167
168/// Returns `true` when `host` is an exact Pinterest host supported by this crate.
169pub fn is_pinterest_host(host: &str) -> bool {
170    let host = host.to_ascii_lowercase();
171    if matches!(
172        host.as_str(),
173        "pinterest.com" | "www.pinterest.com" | "m.pinterest.com"
174    ) {
175        return true;
176    }
177    if COUNTRY_HOSTS.contains(&host.as_str()) {
178        return true;
179    }
180    if let Some(root) = host.strip_prefix("www.") {
181        if COUNTRY_HOSTS.contains(&root) {
182            return true;
183        }
184    }
185    host.strip_suffix(".pinterest.com")
186        .is_some_and(|region| REGIONAL_SUBDOMAINS.contains(&region))
187}
188
189/// Parses a supported Pinterest URL and returns its normalized fields.
190pub fn parse_pinterest_url(input: &str) -> Result<ParsedPinterestUrl, PinterestUrlError> {
191    let original_url = input.trim();
192    if original_url.is_empty() || original_url.len() > 2048 {
193        return Err(invalid("URL is empty or too long"));
194    }
195
196    let parsed = Url::parse(original_url).map_err(|_| invalid("URL could not be parsed"))?;
197    if parsed.scheme() != "https" {
198        return Err(invalid("Only HTTPS URLs are supported"));
199    }
200    if !parsed.username().is_empty() || parsed.password().is_some() {
201        return Err(invalid("Credentials are not supported"));
202    }
203    if parsed.port().is_some_and(|port| port != 443) {
204        return Err(invalid("Non-standard ports are not supported"));
205    }
206
207    let host = parsed
208        .host_str()
209        .ok_or_else(|| invalid("URL does not contain a host"))?
210        .to_ascii_lowercase();
211    let segments: Vec<&str> = parsed
212        .path_segments()
213        .map(|values| values.filter(|value| !value.is_empty()).collect())
214        .unwrap_or_default();
215
216    if host == SHORT_HOST {
217        return parse_short_url(original_url, &segments);
218    }
219    if !is_pinterest_host(&host) {
220        return Err(invalid("Host is not an allowed Pinterest domain"));
221    }
222
223    if let Some(parsed_pin) = parse_pin_url(original_url, &segments) {
224        return Ok(parsed_pin);
225    }
226    if let Some(parsed_ideas) = parse_ideas_url(original_url, &segments) {
227        return Ok(parsed_ideas);
228    }
229    parse_profile_or_board(original_url, &segments)
230}
231
232/// Returns the canonical URL for a supported Pinterest URL.
233pub fn normalize_pinterest_url(input: &str) -> Result<String, PinterestUrlError> {
234    parse_pinterest_url(input).map(|parsed| parsed.normalized_url)
235}
236
237/// Returns `true` when `input` is a supported Pinterest URL.
238pub fn is_pinterest_url(input: &str) -> bool {
239    parse_pinterest_url(input).is_ok()
240}
241
242fn parse_short_url(
243    original_url: &str,
244    segments: &[&str],
245) -> Result<ParsedPinterestUrl, PinterestUrlError> {
246    if segments.len() != 1 || !is_ascii_alphanumeric(segments[0]) || segments[0].len() < 2 {
247        return Err(unsupported("Unsupported pin.it path"));
248    }
249
250    let shortcode = segments[0];
251    let mut result = ParsedPinterestUrl::new(
252        PinterestUrlKind::Short,
253        original_url,
254        format!("https://{SHORT_HOST}/{shortcode}/"),
255    );
256    result.shortcode = Some(shortcode.to_owned());
257    Ok(result)
258}
259
260fn parse_pin_url(original_url: &str, segments: &[&str]) -> Option<ParsedPinterestUrl> {
261    if !(segments.len() == 2 || segments.len() == 3) || segments.first()? != &"pin" {
262        return None;
263    }
264
265    let pin_segment = segments[1];
266    let pin_id = if is_numeric_id(pin_segment) {
267        pin_segment
268    } else {
269        let (_, candidate) = pin_segment.rsplit_once("--")?;
270        if !is_slug(pin_segment) || !is_numeric_id(candidate) {
271            return None;
272        }
273        candidate
274    };
275    if segments.len() == 3 && !is_slug(segments[2]) {
276        return None;
277    }
278
279    let mut result = ParsedPinterestUrl::new(
280        PinterestUrlKind::Pin,
281        original_url,
282        format!("https://{CANONICAL_HOST}/pin/{pin_id}/"),
283    );
284    result.pin_id = Some(pin_id.to_owned());
285    Some(result)
286}
287
288fn parse_ideas_url(original_url: &str, segments: &[&str]) -> Option<ParsedPinterestUrl> {
289    if segments.len() != 3
290        || segments[0] != "ideas"
291        || !is_slug(segments[1])
292        || !is_numeric_id(segments[2])
293    {
294        return None;
295    }
296
297    let idea_slug = segments[1];
298    let idea_id = segments[2];
299    let mut result = ParsedPinterestUrl::new(
300        PinterestUrlKind::Ideas,
301        original_url,
302        format!("https://{CANONICAL_HOST}/ideas/{idea_slug}/{idea_id}/"),
303    );
304    result.idea_slug = Some(idea_slug.to_owned());
305    result.idea_id = Some(idea_id.to_owned());
306    Some(result)
307}
308
309fn parse_profile_or_board(
310    original_url: &str,
311    segments: &[&str],
312) -> Result<ParsedPinterestUrl, PinterestUrlError> {
313    let Some(username) = segments.first().copied() else {
314        return Err(unsupported("Unsupported Pinterest path"));
315    };
316    if RESERVED_FIRST_SEGMENTS.contains(&username.to_ascii_lowercase().as_str()) {
317        return Err(unsupported("Unsupported Pinterest path"));
318    }
319
320    if segments.len() == 1 && is_username(username) {
321        let mut result = ParsedPinterestUrl::new(
322            PinterestUrlKind::Profile,
323            original_url,
324            format!("https://{CANONICAL_HOST}/{username}/"),
325        );
326        result.username = Some(username.to_owned());
327        return Ok(result);
328    }
329
330    if segments.len() == 2 && is_username(username) && is_slug(segments[1]) {
331        let board_slug = segments[1];
332        let mut result = ParsedPinterestUrl::new(
333            PinterestUrlKind::Board,
334            original_url,
335            format!("https://{CANONICAL_HOST}/{username}/{board_slug}/"),
336        );
337        result.username = Some(username.to_owned());
338        result.board_slug = Some(board_slug.to_owned());
339        return Ok(result);
340    }
341
342    Err(unsupported("Unsupported Pinterest path"))
343}
344
345fn is_numeric_id(value: &str) -> bool {
346    !value.is_empty() && value.len() <= 20 && value.bytes().all(|byte| byte.is_ascii_digit())
347}
348
349fn is_ascii_alphanumeric(value: &str) -> bool {
350    value.bytes().all(|byte| byte.is_ascii_alphanumeric())
351}
352
353fn is_slug(value: &str) -> bool {
354    value
355        .bytes()
356        .next()
357        .is_some_and(|byte| byte.is_ascii_alphanumeric())
358        && value
359            .bytes()
360            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
361}
362
363fn is_username(value: &str) -> bool {
364    value
365        .bytes()
366        .next()
367        .is_some_and(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
368        && value
369            .bytes()
370            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-'))
371}
372
373fn invalid(message: &'static str) -> PinterestUrlError {
374    PinterestUrlError::new(PinterestUrlErrorCode::InvalidUrl, message)
375}
376
377fn unsupported(message: &'static str) -> PinterestUrlError {
378    PinterestUrlError::new(PinterestUrlErrorCode::UnsupportedUrl, message)
379}
380
381#[cfg(test)]
382mod tests {
383    use super::*;
384
385    #[test]
386    fn parses_and_normalizes_pin_urls() {
387        let parsed =
388            parse_pinterest_url("https://de.pinterest.com/pin/987654321/?utm_source=test").unwrap();
389
390        assert_eq!(parsed.kind, PinterestUrlKind::Pin);
391        assert_eq!(parsed.pin_id.as_deref(), Some("987654321"));
392        assert_eq!(
393            parsed.normalized_url,
394            "https://www.pinterest.com/pin/987654321/"
395        );
396    }
397
398    #[test]
399    fn extracts_numeric_id_from_slugged_pin_urls() {
400        let parsed = parse_pinterest_url(
401            "https://www.pinterest.com/pin/roasted-pineapple-chicken--68746366275/",
402        )
403        .unwrap();
404        assert_eq!(parsed.pin_id.as_deref(), Some("68746366275"));
405    }
406
407    #[test]
408    fn recognizes_short_urls_without_resolving_them() {
409        let parsed = parse_pinterest_url("https://pin.it/AbC123?source=share").unwrap();
410        assert_eq!(parsed.kind, PinterestUrlKind::Short);
411        assert_eq!(parsed.shortcode.as_deref(), Some("AbC123"));
412        assert_eq!(parsed.normalized_url, "https://pin.it/AbC123/");
413    }
414
415    #[test]
416    fn classifies_profiles_boards_and_ideas() {
417        assert_eq!(
418            parse_pinterest_url("https://pinterest.com/savepinner/")
419                .unwrap()
420                .kind,
421            PinterestUrlKind::Profile
422        );
423        assert_eq!(
424            parse_pinterest_url("https://www.pinterest.com/savepinner/media-tools/")
425                .unwrap()
426                .kind,
427            PinterestUrlKind::Board
428        );
429        assert_eq!(
430            parse_pinterest_url("https://www.pinterest.com/ideas/space-wallpaper-4k/926295399832/")
431                .unwrap()
432                .kind,
433            PinterestUrlKind::Ideas
434        );
435    }
436
437    #[test]
438    fn rejects_unsafe_and_unsupported_urls() {
439        for value in [
440            "https://www.pinterest.com.evil.example/pin/123/",
441            "http://www.pinterest.com/pin/123/",
442            "https://user:pass@www.pinterest.com/pin/123/",
443            "https://www.pinterest.com:8443/pin/123/",
444            "https://www.pinterest.com/search/pins/?q=cats",
445        ] {
446            assert!(!is_pinterest_url(value), "{value}");
447            assert!(parse_pinterest_url(value).is_err(), "{value}");
448        }
449    }
450
451    #[test]
452    fn exposes_normalization_and_exact_host_helpers() {
453        assert_eq!(
454            normalize_pinterest_url("https://pinterest.co.uk/pin/123/?foo=bar").unwrap(),
455            "https://www.pinterest.com/pin/123/"
456        );
457        assert!(is_pinterest_host("PINTEREST.CO.UK"));
458        assert!(!is_pinterest_host("pinterest.co.uk.evil.example"));
459    }
460}