1use std::str::FromStr;
2
3use regex::Regex;
4use serde_json::Value;
5use urlencoding::decode;
6use crate::{PluginCredential, RsVideoFormat};
7use crate::{RsAudio, RsResolution, RsVideoCodec};
8use serde::{Deserialize, Serialize};
9use strum_macros::EnumString;
10
11pub mod error;
12
13#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
14#[serde(rename_all = "camelCase")]
15pub struct RsCookie {
16 pub domain: String,
17 pub http_only: bool,
18 pub path: String,
19 pub secure: bool,
20 pub expiration: Option<f64>,
21 pub name: String,
22 pub value: String,
23}
24
25impl FromStr for RsCookie {
26 type Err = error::RequestError;
27 fn from_str(line: &str) -> Result<Self, Self::Err> {
28 let mut splitted = line.split(';');
30 Ok(RsCookie {
31 domain: splitted.next().ok_or(error::RequestError::UnableToParseCookieString("domain".to_owned(), line.to_owned()))?.to_owned(),
32 http_only: "true" == splitted.next().ok_or(error::RequestError::UnableToParseCookieString("http_only".to_owned(), line.to_owned()))?,
33 path: splitted.next().ok_or(error::RequestError::UnableToParseCookieString("path".to_owned(), line.to_owned()))?.to_owned(),
34 secure: "true" == splitted.next().ok_or(error::RequestError::UnableToParseCookieString("secure".to_owned(), line.to_owned()))?,
35 expiration: {
36 let t = splitted.next().ok_or(error::RequestError::UnableToParseCookieString("expiration".to_owned(), line.to_owned()))?.to_owned();
37 if t.is_empty() {
38 None
39 } else {
40 Some(t.parse().map_err(|_| error::RequestError::UnableToParseCookieString("expiration parsing".to_owned(), line.to_owned()))?)
41 }
42 },
43 name: splitted.next().ok_or(error::RequestError::UnableToParseCookieString("name".to_owned(), line.to_owned()))?.to_owned(),
44 value: splitted.next().ok_or(error::RequestError::UnableToParseCookieString("value".to_owned(), line.to_owned()))?.to_owned() })
45 }
46}
47
48impl RsCookie {
49 pub fn netscape(&self) -> String {
50 let second = if self.domain.starts_with('.') {
51 "TRUE"
52 } else {
53 "FALSE"
54 };
55 let secure = if self.secure {
56 "TRUE"
57 } else {
58 "FALSE"
59 };
60 let expiration = if let Some(expiration) = self.expiration {
61 (expiration as u32).to_string()
62 } else {
63 "".to_owned()
64 };
65 format!("{}\t{}\t{}\t{}\t{}\t{}\t{}", self.domain, second, self.path, secure, expiration, self.name, self.value)
67 }
68
69 pub fn header(&self) -> String {
70 format!("{}={}", self.name, self.value)
71 }
72}
73
74pub trait RsCookies {
75 fn header_value(&self) -> String;
76 fn headers(&self) -> (String, String);
77}
78
79impl RsCookies for Vec<RsCookie> {
80 fn header_value(&self) -> String {
81 self.iter().map(|t| t.header()).collect::<Vec<String>>().join("; ")
82 }
83
84 fn headers(&self) -> (String, String) {
85 ("cookie".to_owned(), self.iter().map(|t| t.header()).collect::<Vec<String>>().join("; "))
86 }
87}
88
89#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
90#[serde(rename_all = "camelCase")]
91pub struct RsRequest {
92 pub upload_id: Option<String>,
93 pub url: String,
94 #[serde(skip_serializing_if = "Option::is_none")]
95 pub mime: Option<String>,
96 #[serde(skip_serializing_if = "Option::is_none")]
97 pub size: Option<u64>,
98 #[serde(skip_serializing_if = "Option::is_none")]
99 pub filename: Option<String>,
100 #[serde(default)]
101 pub status: RsRequestStatus,
102
103 #[serde(default)]
106 pub permanent: bool,
107
108 pub json_body: Option<Value>,
109 #[serde(default)]
110 pub method: RsRequestMethod,
111
112 #[serde(skip_serializing_if = "Option::is_none")]
113 pub referer: Option<String>,
114 #[serde(skip_serializing_if = "Option::is_none")]
115 pub headers: Option<Vec<(String, String)>>,
116 #[serde(skip_serializing_if = "Option::is_none")]
118 pub cookies: Option<Vec<RsCookie>>,
119 #[serde(skip_serializing_if = "Option::is_none")]
121 pub files: Option<Vec<RsRequestFiles>>,
122 #[serde(skip_serializing_if = "Option::is_none")]
124 pub selected_file: Option<String>,
125
126
127 #[serde(skip_serializing_if = "Option::is_none")]
128 pub description: Option<String>,
129 #[serde(skip_serializing_if = "Option::is_none")]
130 pub tags: Option<Vec<String>>,
131 #[serde(skip_serializing_if = "Option::is_none")]
132 pub people: Option<Vec<String>>,
133 #[serde(skip_serializing_if = "Option::is_none")]
134 pub albums: Option<Vec<String>>,
135 #[serde(skip_serializing_if = "Option::is_none")]
136 pub season: Option<u32>,
137 #[serde(skip_serializing_if = "Option::is_none")]
138 pub episode: Option<u32>,
139 #[serde(skip_serializing_if = "Option::is_none")]
140 pub language: Option<String>,
141 #[serde(skip_serializing_if = "Option::is_none")]
142 pub resolution: Option<RsResolution>,
143 #[serde(skip_serializing_if = "Option::is_none")]
144 pub video_format: Option<RsVideoFormat>,
145 #[serde(skip_serializing_if = "Option::is_none")]
146 pub videocodec: Option<RsVideoCodec>,
147 #[serde(skip_serializing_if = "Option::is_none")]
148 pub audio: Option<Vec<RsAudio>>,
149 #[serde(skip_serializing_if = "Option::is_none")]
150 pub quality: Option<u64>,
151
152 #[serde(default)]
153 pub ignore_origin_duplicate: bool,
154}
155
156impl RsRequest {
157 pub fn set_cookies(&mut self, cookies: Vec<RsCookie>) {
158 let mut existing = if let Some(headers) = &self.headers {
159 headers.to_owned()
160 } else{
161 vec![]
162 };
163 existing.push(cookies.headers());
164 self.headers = Some(existing);
165 }
166
167 pub fn filename_or_extract_from_url(&self) -> Option<String> {
168 if self.filename.is_some() {
169 self.filename.clone()
170 } else {
171 self.url.split('/')
172 .last()
173 .and_then(|segment| {
174 segment.split('?')
175 .next()
176 .filter(|s| !s.is_empty())
177 .map(|s| s.to_string())
178 })
179 .and_then(|potential| {
180 let extension = potential.split('.').map(|t| t.to_string()).collect::<Vec<String>>();
181 if extension.len() > 1 && extension.last().unwrap_or(&"".to_string()).len() > 2 && extension.last().unwrap_or(&"".to_string()).len() < 5{
182 let decoded = decode(&potential).map(|x| x.into_owned()).unwrap_or(potential); Some(decoded)
184 } else {
185 None
186 }
187 })
188 }
189
190 }
191
192 pub fn parse_filename(&mut self) {
193 if let Some(filename) = &self.filename {
194 let resolution = RsResolution::from_filename(filename);
195 if resolution != RsResolution::Unknown {
196 self.resolution = Some(resolution);
197 }
198 let video_format = RsVideoFormat::from_filename(filename);
199 if video_format != RsVideoFormat::Other {
200 self.video_format = Some(video_format);
201 }
202 let videocodec = RsVideoCodec::from_filename(filename);
203 if videocodec != RsVideoCodec::Unknown {
204 self.videocodec = Some(videocodec);
205 }
206 let audio = RsAudio::list_from_filename(filename);
207 if !audio.is_empty() {
208 self.audio = Some(audio);
209 }
210
211 let re = Regex::new(r"(?i)s(\d+)e(\d+)").unwrap();
212 if let Some(caps) = re.captures(filename) {
213 self.season = caps[1].parse::<u32>().ok();
214 self.episode = caps[2].parse::<u32>().ok();
215 }
216 }
217
218 }
219
220 pub fn parse_subfilenames(&mut self) {
221 if let Some(ref mut files) = self.files {
222 for file in files {
223 file.parse_filename();
224 }
225 }
226 }
227}
228
229#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, strum_macros::Display,EnumString, Default)]
230#[serde(rename_all = "camelCase")]
231#[strum(serialize_all = "camelCase")]
232pub enum RsRequestStatus {
233 #[default]
235 Unprocessed,
236 Processed,
238 NeedParsing,
240 RequireAdd,
244 Intermediate,
246 NeedFileSelection,
248 FinalPrivate,
250 FinalPublic
252}
253
254
255#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, strum_macros::Display,EnumString, Default)]
256#[serde(rename_all = "camelCase")]
257#[strum(serialize_all = "camelCase")]
258pub enum RsRequestMethod {
259
260 #[default]
261 Get,
262 Post,
263 Patch,
264 Delete,
265 Head,
266
267}
268
269
270
271#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
272#[serde(rename_all = "camelCase")]
273pub struct RsRequestFiles {
274 pub name: String,
275 pub size: u64,
276
277 pub mime: Option<String>,
278 #[serde(skip_serializing_if = "Option::is_none")]
279 pub description: Option<String>,
280 #[serde(skip_serializing_if = "Option::is_none")]
281 pub tags: Option<Vec<String>>,
282 #[serde(skip_serializing_if = "Option::is_none")]
283 pub people: Option<Vec<String>>,
284 #[serde(skip_serializing_if = "Option::is_none")]
285 pub albums: Option<Vec<String>>,
286 #[serde(skip_serializing_if = "Option::is_none")]
287 pub season: Option<u32>,
288 #[serde(skip_serializing_if = "Option::is_none")]
289 pub episode: Option<u32>,
290 #[serde(skip_serializing_if = "Option::is_none")]
291 pub language: Option<String>,
292 #[serde(skip_serializing_if = "Option::is_none")]
293 pub resolution: Option<RsResolution>,
294 #[serde(skip_serializing_if = "Option::is_none")]
295 pub video_format: Option<RsVideoFormat>,
296 #[serde(skip_serializing_if = "Option::is_none")]
297 pub videocodec: Option<RsVideoCodec>,
298 #[serde(skip_serializing_if = "Option::is_none")]
299 pub audio: Option<Vec<RsAudio>>,
300 #[serde(skip_serializing_if = "Option::is_none")]
301 pub quality: Option<u64>,
302}
303
304impl RsRequestFiles {
305 pub fn parse_filename(&mut self) {
306 let resolution = RsResolution::from_filename(&self.name);
307 if resolution != RsResolution::Unknown {
308 self.resolution = Some(resolution);
309 }
310 let video_format = RsVideoFormat::from_filename(&self.name);
311 if video_format != RsVideoFormat::Other {
312 self.video_format = Some(video_format);
313 }
314 let videocodec = RsVideoCodec::from_filename(&self.name);
315 if videocodec != RsVideoCodec::Unknown {
316 self.videocodec = Some(videocodec);
317 }
318 let audio = RsAudio::list_from_filename(&self.name);
319 if !audio.is_empty() {
320 self.audio = Some(audio);
321 }
322
323 let re = Regex::new(r"(?i)s(\d+)e(\d+)").unwrap();
324 if let Some(caps) = re.captures(&self.name) {
325 self.season = caps[1].parse::<u32>().ok();
326 self.episode = caps[2].parse::<u32>().ok();
327 }
328 }
329}
330
331#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
332#[serde(rename_all = "camelCase")]
333pub struct RsRequestPluginRequest {
334 pub request: RsRequest,
335 pub credential: Option<PluginCredential>,
336}
337
338
339
340#[cfg(test)]
341mod tests {
342
343 use self::error::RequestError;
344
345 use super::*;
346
347 #[test]
348 fn test_cookie_parsing() -> Result<(), RequestError> {
349 let parsed = RsCookie::from_str(".twitter.com;false;/;true;1722364794.437907;kdt;w1j")?;
350 assert!(parsed.domain == ".twitter.com".to_owned());
351 assert!(parsed.http_only == false);
352 assert!(parsed.path == "/".to_owned());
353 assert!(parsed.secure == true);
354 assert!(parsed.expiration == Some(1722364794.437907));
355 assert!(parsed.name == "kdt".to_owned());
356 assert!(parsed.value == "w1j".to_owned());
357 Ok(())
358 }
359
360 #[test]
361 fn test_cookie_parsing_no_expi() -> Result<(), RequestError> {
362 let parsed = RsCookie::from_str(".twitter.com;false;/;true;;kdt;w1j")?;
363 assert!(parsed.domain == ".twitter.com".to_owned());
364 assert!(parsed.http_only == false);
365 assert!(parsed.path == "/".to_owned());
366 assert!(parsed.secure == true);
367 assert!(parsed.expiration == None);
368 assert!(parsed.name == "kdt".to_owned());
369 assert!(parsed.value == "w1j".to_owned());
370 Ok(())
371 }
372
373 #[test]
374 fn test_netscape() -> Result<(), RequestError> {
375 let parsed = RsCookie::from_str(".twitter.com;false;/;true;1722364794.437907;kdt;w1j")?;
376 assert!(parsed.netscape() == ".twitter.com\tTRUE\t/\tTRUE\t1722364794\tkdt\tw1j");
377 Ok(())
378 }
379 #[test]
380 fn test_netscape_doublequote() -> Result<(), RequestError> {
381 let parsed = RsCookie::from_str(".twitter.com;true;/;true;1726506480.700665;ads_prefs;\"HBESAAA=\"")?;
382 assert!(parsed.netscape() == ".twitter.com\tTRUE\t/\tTRUE\t1726506480\tads_prefs\t\"HBESAAA=\"");
383 Ok(())
384 }
385
386 #[test]
387 fn test_parse_filename() -> Result<(), RequestError> {
388 let req = RsRequest {url: "http://www.test.com/filename.mp4?toto=3".to_string(), filename: Some("test.mkv".to_owned()), ..Default::default()};
389 assert_eq!(req.filename_or_extract_from_url(), Some("test.mkv".to_string()));
390 let req = RsRequest {url: "http://www.test.com/filename.mp4?toto=3".to_string(), ..Default::default()};
391 assert_eq!(req.filename_or_extract_from_url(), Some("filename.mp4".to_string()), "We are expecting a filename from the url");
392 let req = RsRequest {url: "http://www.test.com/notfilename?toto=3".to_string(), ..Default::default()};
393 assert_eq!(req.filename_or_extract_from_url(), None, "Should return none as there is no filename with extensiopn in url");
394 let req = RsRequest {url: "http://www.test.com/notfilename.toolong?toto=3".to_string(), ..Default::default()};
395 assert_eq!(req.filename_or_extract_from_url(), None, "Should return none as too long after dot is not an extension");
396 let req = RsRequest {url: "http://www.test.com/filename%20test.mp4?toto=3".to_string(), filename: Some("test.mkv".to_owned()), ..Default::default()};
397 assert_eq!(req.filename_or_extract_from_url(), Some("filename test.mp4".to_string()));
398 Ok(())
399 }
400
401
402 #[test]
403 fn test_header() -> Result<(), RequestError> {
404 let parsed = vec![RsCookie::from_str(".twitter.com;true;/;true;1726506480.700665;ads_prefs;\"HBESAAA=\"")?, RsCookie::from_str(".twitter.com;false;/;true;1722364794.437907;kdt;w1j")?];
405 println!("header: {}", parsed.header_value());
406 assert!(parsed.header_value() == "ads_prefs=\"HBESAAA=\"; kdt=w1j");
407 Ok(())
408 }
409
410 #[test]
411 fn test_parse() -> Result<(), RequestError> {
412 let mut req = RsRequest { filename: Some("Shogun.2024.S01E01.Anjin.1080p.VOSTFR.DSNP.WEB-DL.DDP5.1.H.264-NTb.mkv".to_owned()), ..Default::default()};
413 req.parse_filename();
414 assert_eq!(req.season.unwrap(), 1);
415 assert_eq!(req.episode.unwrap(), 1);
416 assert_eq!(req.resolution.unwrap(), RsResolution::FullHD);
417 assert_eq!(req.videocodec.unwrap(), RsVideoCodec::H264);
418 assert_eq!(req.video_format.unwrap(), RsVideoFormat::Mkv);
419 assert_eq!(req.audio.unwrap().len(), 1);
420 Ok(())
421 }
422
423 #[test]
424 fn test_parse2() -> Result<(), RequestError> {
425 let mut req = RsRequest { filename: Some("Shogun.2024.S01E05.MULTi.HDR.DV.2160p.WEB.H265-FW".to_owned()), ..Default::default()};
426 req.parse_filename();
427 assert_eq!(req.season.expect("a season"), 1);
428 assert_eq!(req.episode.expect("an episode"), 5);
429 assert_eq!(req.resolution.expect("a resolution"), RsResolution::UHD);
430 assert_eq!(req.videocodec.expect("a videocodec"), RsVideoCodec::H265);
431
432 Ok(())
433 }
434}
435