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