src/global/functions/from_url.rs

72 lines · 2783 bytes

 1/// gets the channel id from it's url
 2pub fn from_channel_url(identifier: &str) -> Result<String, String> {
 3    // a youtube channel id is exactly 24 characters long, so if the identifier to 24 chars
 4    // long, then just assume its the channel id
 5    if identifier.len() == 24 {
 6        Ok(identifier.to_string())
 7    } else {
 8        // the channel id comes after `/channel/` in an url
 9        let index = if let Some(index) = identifier.find("/channel/") {
10            // if there isnt 24 characters after `/channel/`, that url must not have
11            // contained a channel id
12            if identifier.len() < index + 33 {
13                return Err(format!("Cannot find channel id from string `{identifier}`"));
14            }
15            index + 9
16        } else {
17            return Err(format!("Cannot find channel id from string `{identifier}`"));
18        };
19
20        Ok(identifier[index..index + 24].to_string())
21    }
22}
23
24pub fn from_video_url(identifier: &str) -> Result<String, String> {
25    // a youtube video id is exactly 11 characters long, so if the identifier to 11 chars
26    // long, then just assume its the video id
27    if identifier.len() == 11 {
28        Ok(identifier.to_string())
29    } else {
30        // the id can come after "?v=" in an url
31        let index = if let Some(index) = identifier.find("?v=") {
32            if identifier.len() < index + 14 {
33                return Err(format!("Cannot find video id from string `{identifier}`"));
34            }
35            index + 3
36        // and also "youtu.be/"
37        } else if let Some(index) = identifier.find("youtu.be/") {
38            if identifier.len() < index + 20 {
39                return Err(format!("Cannot find video id from string `{identifier}`"));
40            }
41            index + 9
42        } else {
43            return Err(format!("Cannot find video id from string `{identifier}`"));
44        };
45
46        Ok(identifier[index..index + 11].to_string())
47    }
48}
49
50pub fn from_playlist_url(identifier: &str) -> Result<String, String> {
51    // a youtube playlist id is exactly 34 characters long, so if the identifier to 34 chars
52    // long, then just assume its the playlist id
53    if identifier.len() == 34 {
54        Ok(identifier.to_string())
55    } else {
56        // the id can come after "list=" in urls
57        let index = if let Some(index) = identifier.find("list=") {
58            if identifier.len() < index + 39 {
59                return Err(format!(
60                    "Cannot find plalyist id from string `{identifier}`"
61                ));
62            }
63            index + 5
64        } else {
65            return Err(format!(
66                "Cannot find playlist id from string `{identifier}`"
67            ));
68        };
69
70        Ok(identifier[index..index + 34].to_string())
71    }
72}