src/global/functions/from_url.rs

58 lines · 1838 bytes

 1fn is_id_char(c: char) -> bool {
 2    c.is_alphanumeric() || matches!(c, '-' | '_')
 3}
 4
 5/// gets the channel id from it's url
 6pub fn from_channel_url(identifier: &str) -> Result<String, String> {
 7    // if it doesnt look like a url, just assume it is an identifier
 8    if identifier.chars().all(is_id_char) {
 9        return Ok(identifier.to_string())
10    }
11
12    let index = if let Some(index) = identifier.find("/channel/") {
13        index + 9
14    } else {
15        return Err(format!("Cannot find channel id from string `{identifier}`"));
16    };
17
18    Ok(identifier[index..].chars().take_while(|c| is_id_char(*c)).collect())
19}
20
21pub fn from_video_url(identifier: &str) -> Result<String, String> {
22    if identifier.chars().all(is_id_char) {
23        return Ok(identifier.to_string())
24    }
25
26    let index = if let Some(index) = identifier.find("?v=") {
27        index + 3
28            // and also "youtu.be/"
29    } else if let Some(index) = identifier.find("youtu.be/") {
30        index + 9
31    } else {
32        return Err(format!("Cannot find video id from string `{identifier}`"));
33    };
34
35    Ok(identifier[index..].chars().take_while(|c| is_id_char(*c)).collect())
36}
37
38pub fn from_playlist_url(identifier: &str) -> Result<String, String> {
39    if identifier.chars().all(is_id_char) {
40        return Ok(identifier.to_string())
41    }
42
43    // the id can come after "list=" in urls
44    let index = if let Some(index) = identifier.find("list=") {
45        if identifier.len() < index + 39 {
46            return Err(format!(
47                    "Cannot find plalyist id from string `{identifier}`"
48            ));
49        }
50        index + 5
51    } else {
52        return Err(format!(
53                "Cannot find playlist id from string `{identifier}`"
54        ));
55    };
56
57    Ok(identifier[index..].chars().take_while(|c| is_id_char(*c)).collect())
58}