1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
use std::{str::FromStr, fmt::Display};

use percent_encoding::{percent_decode_str, utf8_percent_encode};
use pest::Parser;
use pest_derive::Parser;
use url::Url;

use crate::cjk_slug;

#[derive(Debug, Parser)]
#[grammar = "permalink.pest"]
struct PathnameParser;

#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub enum PermalinkError {
    #[error("invalid url")]
    InvalidUrl(Box<url::ParseError>),
    #[error("invalid permalink")]
    InvalidPermalink(Box<pest::error::Error<Rule>>),
    #[error("unknown country code `{0}`")]
    UnknownCountry(String),
}

impl From<url::ParseError> for PermalinkError {
    fn from(err: url::ParseError) -> Self {
        Self::InvalidUrl(Box::new(err))
    }
}

impl From<pest::error::Error<Rule>> for PermalinkError {
    fn from(err: pest::error::Error<Rule>) -> Self {
        Self::InvalidPermalink(Box::new(err))
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Permalink {
    pub country: WellKnownCountry,
    pub default_language: String,
    pub service_type: String,
    pub title: Option<String>,
    pub id: String,
    pub data: Option<String>,
}

impl Permalink {
    pub fn parse_str(url_like: &str) -> Result<Self, PermalinkError> {
        let url = Url::parse(url_like)?;
        Self::parse_url(url)
    }

    pub fn parse_url(url: Url) -> Result<Self, PermalinkError> {
        let pathname = PathnameParser::parse(Rule::pathname, url.path())?.next().unwrap();

        let mut permalink = Permalink::default();

        let mut pathname_rules = pathname.into_inner();

        let country = pathname_rules
            .next()
            .unwrap()
            .as_str();
        if let Some(country) = well_known_country_from_origin(url.origin().ascii_serialization()) {
            permalink.country = country;
        } else {
            permalink.country = WellKnownCountry::from_str(country)?;
        }

        permalink.default_language = language_from_well_known_country(permalink.country);

        let service_type = pathname_rules
            .next()
            .unwrap()
            .as_str();
        permalink.service_type = service_type.to_string();

        let slug_rules = pathname_rules
            .next()
            .unwrap()
            .into_inner();
        for rule in slug_rules {
            match rule.as_rule() {
                Rule::title => {
                    let mut chars = rule.as_str().chars();
                    chars.next_back();
                    permalink.title = Some(
                        percent_decode_str(chars.as_str())
                            .decode_utf8()
                            .unwrap()
                            .to_string()
                    );
                },
                Rule::id => {
                    permalink.id = rule.as_str().to_string();
                },
                _ => {},
            }
        }

        permalink.data = pathname_rules.next()
            .map(|rule| rule.as_str().to_string());

        Ok(permalink)
    }

    pub fn normalize(&self) -> String {
        format!(
            "{}/{}/{}/{}/",
            "https://www.karrotmarket.com",
            self.country,
            self.service_type,
            self.id,
        )
    }

    pub fn canonicalize(&self, title: &str) -> String {
        const NON_URL_SAFE: &percent_encoding::AsciiSet = &percent_encoding::CONTROLS
            .add(b' ')
            .add(b'!')
            .add(b'"')
            .add(b'#')
            .add(b'$')
            .add(b'%')
            .add(b'&')
            .add(b'\'')
            .add(b'(')
            .add(b')')
            .add(b'*')
            .add(b'+')
            .add(b',')
            .add(b'.')
            .add(b'/')
            .add(b':')
            .add(b';')
            .add(b'<')
            .add(b'=')
            .add(b'>')
            .add(b'?')
            .add(b'@')
            .add(b'[')
            .add(b'\\')
            .add(b']')
            .add(b'^')
            .add(b'`')
            .add(b'{')
            .add(b'|')
            .add(b'}')
            .add(b'~');

        let origin = well_known_origin_from_country(self.country);
        format!(
            "{}/{}/{}/{}/",
            origin,
            self.country,
            self.service_type,
            utf8_percent_encode(
                cjk_slug::slugify(format!("{}-{}", title, self.id).as_str()).as_str(),
                NON_URL_SAFE,
            ),
        )
    }
}

impl Default for Permalink {
    fn default() -> Self {
        Self {
            country: WellKnownCountry::KR,
            default_language: "ko".to_string(),
            service_type: "about".to_string(),
            title: None,
            id: "blank".to_string(),
            data: None,
        }
    }
}

impl Display for Permalink {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(fmt, "permalink")?;
        writeln!(fmt, "\tcountry: {}", self.country)?;
        writeln!(fmt, "\tdefault_language: {}", self.default_language)?;
        writeln!(fmt, "\tservice_type: {}", self.service_type)?;
        writeln!(fmt, "\ttitle: {:?}", self.title)?;
        writeln!(fmt, "\tid: {}", self.id)?;
        writeln!(fmt, "\tdata: {:?}", self.data)
    }
}

impl FromStr for Permalink {
    type Err = PermalinkError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Permalink::parse_str(value)
    }
}

impl TryFrom<String> for Permalink {
    type Error = PermalinkError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Permalink::parse_str(value.as_str())
    }
}

impl TryFrom<Url> for Permalink {
    type Error = PermalinkError;

    fn try_from(value: Url) -> Result<Self, Self::Error> {
        Self::parse_url(value)
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum WellKnownCountry {
    CA,
    JP,
    KR,
    UK,
    US,
}

impl FromStr for WellKnownCountry {
    type Err = PermalinkError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "ca" | "CA" | "cA" | "Ca" => Ok(Self::CA),
            "jp" | "JP" | "jP" | "Jp" => Ok(Self::JP),
            "kr" | "KR" | "kR" | "Kr"  => Ok(Self::KR),
            "uk" | "UK" | "uK" | "Uk" => Ok(Self::UK),
            "us" | "US" | "uS" | "Us" => Ok(Self::US),
            _ => Err(Self::Err::UnknownCountry(value.to_string())),
        }
    }
}

impl Display for WellKnownCountry {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fmt.write_str(match self {
            Self::CA => "ca",
            Self::JP => "jp",
            Self::KR => "kr",
            Self::UK => "uk",
            Self::US => "us",
        })
    }
}

fn well_known_country_from_origin(origin: String) -> Option<WellKnownCountry> {
    match normalize_origin(origin).as_str() {
        "https://www.daangn.com" => Some(WellKnownCountry::KR),
        "https://www.karrotmarket.com" => None,
        "https://ca.karrotmarket.com" => Some(WellKnownCountry::CA),
        "https://jp.karrotmarket.com" => Some(WellKnownCountry::JP),
        "https://uk.karrotmarket.com" => Some(WellKnownCountry::UK),
        "https://us.karrotmarket.com" => Some(WellKnownCountry::US),
        "https://kr.karrotmarket.com" => Some(WellKnownCountry::KR),
        _ => None,
    }
}

fn well_known_origin_from_country(country: WellKnownCountry) -> String {
    match country {
        WellKnownCountry::CA => "https://ca.karrotmarket.com".to_string(),
        WellKnownCountry::JP => "https://jp.karrotmarket.com".to_string(),
        WellKnownCountry::KR => "https://www.daangn.com".to_string(),
        WellKnownCountry::UK => "https://uk.karrotmarket.com".to_string(),
        WellKnownCountry::US => "https://us.karrotmarket.com".to_string(),
    }
}

fn language_from_well_known_country(country: WellKnownCountry) -> String {
    match country {
        WellKnownCountry::CA => "en".to_string(),
        WellKnownCountry::JP => "ja".to_string(),
        WellKnownCountry::KR => "ko".to_string(),
        WellKnownCountry::UK => "en".to_string(),
        WellKnownCountry::US => "en".to_string(),
    }
}

fn normalize_origin(origin: String) -> String {
    match origin.as_str() {
        "https://daangn.com" => "https://www.daangn.com".to_string(),
        "https://karrotmarket.com" => "https://www.karrotmarket.com".to_string(),
        _ => origin,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_valid_permalink() {
        let permalink = Permalink::parse_str("https://www.daangn.com/kr/app/당근마켓-대한민국-1등-동네-앱-id1018769995/").unwrap();
        assert_eq!(permalink.country, WellKnownCountry::KR);
        assert_eq!(permalink.default_language, "ko".to_string());
        assert_eq!(permalink.service_type, "app".to_string());
        assert_eq!(permalink.title, Some("당근마켓-대한민국-1등-동네-앱".to_string()));
        assert_eq!(permalink.id, "id1018769995".to_string());
    }

    #[test]
    fn test_parse_valid_permalink_without_trailing_slash() {
        let permalink = Permalink::parse_str("https://www.daangn.com/kr/app/당근마켓-대한민국-1등-동네-앱-id1018769995").unwrap();
        assert_eq!(permalink.country, WellKnownCountry::KR);
        assert_eq!(permalink.default_language, "ko".to_string());
        assert_eq!(permalink.service_type, "app".to_string());
        assert_eq!(permalink.title, Some("당근마켓-대한민국-1등-동네-앱".to_string()));
        assert_eq!(permalink.id, "id1018769995".to_string());
    }

    #[test]
    fn test_parse_valid_permalink_without_title() {
        let permalink = Permalink::parse_str("https://www.daangn.com/kr/app/id1018769995/").unwrap();
        assert_eq!(permalink.country, WellKnownCountry::KR);
        assert_eq!(permalink.default_language, "ko".to_string());
        assert_eq!(permalink.service_type, "app".to_string());
        assert_eq!(permalink.title, None);
        assert_eq!(permalink.id, "id1018769995".to_string());
    }

    #[test]
    fn test_parse_invalid_url() {
        let result = Permalink::parse_str("invalid/kr/app/id1018769995/");
        assert!(matches!(result, Err(PermalinkError::InvalidUrl(_))));
    }

    #[test]
    fn test_parse_invalid_permalink() {
        let result = Permalink::parse_str("https://apps.apple.com/kr/app/%EB%8B%B9%EA%B7%BC%EB%A7%88%EC%BC%93/id1018769995");
        assert!(matches!(result, Err(PermalinkError::InvalidPermalink(_))));
    }

    #[test]
    fn test_parse_well_known_host() {
        let permalink = Permalink::parse_str("https://www.daangn.com/ca/app/id1018769995/").unwrap();
        assert_eq!(permalink.country, WellKnownCountry::KR);
        assert_eq!(permalink.default_language, "ko".to_string());
        assert_eq!(permalink.service_type, "app".to_string());
        assert_eq!(permalink.title, None);
        assert_eq!(permalink.id, "id1018769995".to_string());
    }

    #[test]
    fn test_parse_country_case_insensitive() {
        let permalink = Permalink::parse_str("https://www.daangn.com/KR/app/id1018769995/").unwrap();
        assert_eq!(permalink.country, WellKnownCountry::KR);
        assert_eq!(permalink.default_language, "ko".to_string());
        assert_eq!(permalink.service_type, "app".to_string());
        assert_eq!(permalink.title, None);
        assert_eq!(permalink.id, "id1018769995".to_string());
    }

    #[test]
    fn test_parse_unknown_country() {
        let result = Permalink::parse_str("http://localhost/xx/app/id1018769995/");
        assert_eq!(result, Err(PermalinkError::UnknownCountry("xx".to_string())));
    }

    #[test]
    fn test_normalize() {
        let permalink = Permalink::parse_str("https://www.daangn.com/kr/app/당근마켓-대한민국-1등-동네-앱-id1018769995/").unwrap();
        assert_eq!(
            permalink.normalize(),
            "https://www.karrotmarket.com/kr/app/id1018769995/".to_string(),
        );
    }

    #[test]
    fn test_canonicalize() {
        let permalink = Permalink::parse_str("https://www.daangn.com/kr/app/id1018769995/").unwrap();
        assert_eq!(
            permalink.canonicalize("당근마켓-대한민국-1등-동네-앱"),
            "https://www.daangn.com/kr/app/%EB%8B%B9%EA%B7%BC%EB%A7%88%EC%BC%93-%EB%8C%80%ED%95%9C%EB%AF%BC%EA%B5%AD-1%EB%93%B1-%EB%8F%99%EB%84%A4-%EC%95%B1-id1018769995/".to_string(),
        );
    }
}