src/global/functions/from_url.rs
67 lines · 1910 bytes
4 symbols in this file
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..]
19 .chars()
20 .take_while(|c| is_id_char(*c))
21 .collect())
22}
23
24pub fn from_video_url(identifier: &str) -> Result<String, String> {
25 if identifier.chars().all(is_id_char) {
26 return Ok(identifier.to_string());
27 }
28
29 let index = if let Some(index) = identifier.find("?v=") {
30 index + 3
31 // and also "youtu.be/"
32 } else if let Some(index) = identifier.find("youtu.be/") {
33 index + 9
34 } else {
35 return Err(format!("Cannot find video id from string `{identifier}`"));
36 };
37
38 Ok(identifier[index..]
39 .chars()
40 .take_while(|c| is_id_char(*c))
41 .collect())
42}
43
44pub fn from_playlist_url(identifier: &str) -> Result<String, String> {
45 if identifier.chars().all(is_id_char) {
46 return Ok(identifier.to_string());
47 }
48
49 // the id can come after "list=" in urls
50 let index = if let Some(index) = identifier.find("list=") {
51 if identifier.len() < index + 39 {
52 return Err(format!(
53 "Cannot find plalyist id from string `{identifier}`"
54 ));
55 }
56 index + 5
57 } else {
58 return Err(format!(
59 "Cannot find playlist id from string `{identifier}`"
60 ));
61 };
62
63 Ok(identifier[index..]
64 .chars()
65 .take_while(|c| is_id_char(*c))
66 .collect())
67}