1use std::{collections::HashMap, str::FromStr};
2
3use regex::Regex;
4use serde_json::Value;
5use urlencoding::decode;
6use crate::{PluginCredential, RsFileType, 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 #[serde(skip_serializing_if = "Option::is_none")]
109 pub instant: Option<bool>,
110
111 pub json_body: Option<Value>,
112 #[serde(default)]
113 pub method: RsRequestMethod,
114
115 #[serde(skip_serializing_if = "Option::is_none")]
116 pub referer: Option<String>,
117 #[serde(skip_serializing_if = "Option::is_none")]
118 pub headers: Option<Vec<(String, String)>>,
119 #[serde(skip_serializing_if = "Option::is_none")]
121 pub cookies: Option<Vec<RsCookie>>,
122 #[serde(skip_serializing_if = "Option::is_none")]
124 pub files: Option<Vec<RsRequestFiles>>,
125 #[serde(skip_serializing_if = "Option::is_none")]
127 pub selected_file: Option<String>,
128
129
130 #[serde(skip_serializing_if = "Option::is_none")]
131 pub description: Option<String>,
132 #[serde(skip_serializing_if = "Option::is_none")]
133 pub tags: Option<Vec<String>>,
134 #[serde(skip_serializing_if = "Option::is_none")]
135 pub people: Option<Vec<String>>,
136 #[serde(skip_serializing_if = "Option::is_none")]
137 pub albums: Option<Vec<String>>,
138 #[serde(skip_serializing_if = "Option::is_none")]
139 pub season: Option<u32>,
140 #[serde(skip_serializing_if = "Option::is_none")]
141 pub episode: Option<u32>,
142 #[serde(skip_serializing_if = "Option::is_none")]
143 pub movie: Option<String>,
144 #[serde(skip_serializing_if = "Option::is_none")]
145 pub language: Option<String>,
146 #[serde(skip_serializing_if = "Option::is_none")]
147 pub resolution: Option<RsResolution>,
148 #[serde(skip_serializing_if = "Option::is_none")]
149 pub video_format: Option<RsVideoFormat>,
150 #[serde(skip_serializing_if = "Option::is_none")]
151 pub videocodec: Option<RsVideoCodec>,
152 #[serde(skip_serializing_if = "Option::is_none")]
153 pub audio: Option<Vec<RsAudio>>,
154 #[serde(skip_serializing_if = "Option::is_none")]
155 pub quality: Option<u64>,
156
157 #[serde(default)]
158 pub ignore_origin_duplicate: bool,
159
160 #[serde(skip_serializing_if = "Option::is_none")]
162 pub thumbnail_url: Option<String>,
163 #[serde(skip_serializing_if = "Option::is_none")]
164 pub origin_url: Option<String>,
165 #[serde(skip_serializing_if = "Option::is_none")]
166 pub title: Option<String>,
167 #[serde(skip_serializing_if = "Option::is_none")]
168 pub kind: Option<RsFileType>,
169
170 #[serde(skip_serializing_if = "Option::is_none")]
172 pub tags_lookup: Option<Vec<String>>,
173 #[serde(skip_serializing_if = "Option::is_none")]
174 pub people_lookup: Option<Vec<String>>,
175 #[serde(skip_serializing_if = "Option::is_none")]
176 pub albums_lookup: Option<Vec<String>>,
177}
178
179impl RsRequest {
180 pub fn set_cookies(&mut self, cookies: Vec<RsCookie>) {
181 let mut existing = if let Some(headers) = &self.headers {
182 headers.to_owned()
183 } else{
184 vec![]
185 };
186 existing.push(cookies.headers());
187 self.headers = Some(existing);
188 }
189
190 pub fn filename_or_extract_from_url(&self) -> Option<String> {
191 if self.filename.is_some() {
192 self.filename.clone()
193 } else {
194 self.url.split('/')
195 .last()
196 .and_then(|segment| {
197 segment.split('?')
198 .next()
199 .filter(|s| !s.is_empty())
200 .map(|s| s.to_string())
201 })
202 .and_then(|potential| {
203 let extension = potential.split('.').map(|t| t.to_string()).collect::<Vec<String>>();
204 if extension.len() > 1 && extension.last().unwrap_or(&"".to_string()).len() > 2 && extension.last().unwrap_or(&"".to_string()).len() < 5{
205 let decoded = decode(&potential).map(|x| x.into_owned()).unwrap_or(potential); Some(decoded)
207 } else {
208 None
209 }
210 })
211 }
212
213 }
214
215 pub fn parse_filename(&mut self) {
216 if let Some(filename) = &self.filename {
217 let resolution = RsResolution::from_filename(filename);
218 if resolution != RsResolution::Unknown {
219 self.resolution = Some(resolution);
220 }
221 let video_format = RsVideoFormat::from_filename(filename);
222 if video_format != RsVideoFormat::Other {
223 self.video_format = Some(video_format);
224 }
225 let videocodec = RsVideoCodec::from_filename(filename);
226 if videocodec != RsVideoCodec::Unknown {
227 self.videocodec = Some(videocodec);
228 }
229 let audio = RsAudio::list_from_filename(filename);
230 if !audio.is_empty() {
231 self.audio = Some(audio);
232 }
233
234 let re = Regex::new(r"(?i)s(\d+)e(\d+)").unwrap();
235 if let Some(caps) = re.captures(filename) {
236 self.season = caps[1].parse::<u32>().ok();
237 self.episode = caps[2].parse::<u32>().ok();
238 }
239 }
240
241 }
242
243 pub fn parse_subfilenames(&mut self) {
244 if let Some(ref mut files) = self.files {
245 for file in files {
246 file.parse_filename();
247 }
248 }
249 }
250}
251
252#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, strum_macros::Display,EnumString, Default)]
253#[serde(rename_all = "camelCase")]
254#[strum(serialize_all = "camelCase")]
255pub enum RsRequestStatus {
256 #[default]
258 Unprocessed,
259 Processed,
261 NeedParsing,
263 RequireAdd,
267 Intermediate,
269 NeedFileSelection,
271 FinalPrivate,
273 FinalPublic
275}
276
277
278#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, strum_macros::Display,EnumString, Default)]
279#[serde(rename_all = "camelCase")]
280#[strum(serialize_all = "camelCase")]
281pub enum RsRequestMethod {
282
283 #[default]
284 Get,
285 Post,
286 Patch,
287 Delete,
288 Head,
289
290}
291
292
293
294#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
295#[serde(rename_all = "camelCase")]
296pub struct RsRequestFiles {
297 pub name: String,
298 pub size: u64,
299
300 pub mime: Option<String>,
301 #[serde(skip_serializing_if = "Option::is_none")]
302 pub description: Option<String>,
303 #[serde(skip_serializing_if = "Option::is_none")]
304 pub tags: Option<Vec<String>>,
305 #[serde(skip_serializing_if = "Option::is_none")]
306 pub people: Option<Vec<String>>,
307 #[serde(skip_serializing_if = "Option::is_none")]
308 pub albums: Option<Vec<String>>,
309 #[serde(skip_serializing_if = "Option::is_none")]
310 pub season: Option<u32>,
311 #[serde(skip_serializing_if = "Option::is_none")]
312 pub episode: Option<u32>,
313 #[serde(skip_serializing_if = "Option::is_none")]
314 pub language: Option<String>,
315 #[serde(skip_serializing_if = "Option::is_none")]
316 pub resolution: Option<RsResolution>,
317 #[serde(skip_serializing_if = "Option::is_none")]
318 pub video_format: Option<RsVideoFormat>,
319 #[serde(skip_serializing_if = "Option::is_none")]
320 pub videocodec: Option<RsVideoCodec>,
321 #[serde(skip_serializing_if = "Option::is_none")]
322 pub audio: Option<Vec<RsAudio>>,
323 #[serde(skip_serializing_if = "Option::is_none")]
324 pub quality: Option<u64>,
325
326 #[serde(skip_serializing_if = "Option::is_none")]
328 pub tags_lookup: Option<Vec<String>>,
329 #[serde(skip_serializing_if = "Option::is_none")]
330 pub people_lookup: Option<Vec<String>>,
331 #[serde(skip_serializing_if = "Option::is_none")]
332 pub albums_lookup: Option<Vec<String>>,
333}
334
335impl RsRequestFiles {
336 pub fn parse_filename(&mut self) {
337 let resolution = RsResolution::from_filename(&self.name);
338 if resolution != RsResolution::Unknown {
339 self.resolution = Some(resolution);
340 }
341 let video_format = RsVideoFormat::from_filename(&self.name);
342 if video_format != RsVideoFormat::Other {
343 self.video_format = Some(video_format);
344 }
345 let videocodec = RsVideoCodec::from_filename(&self.name);
346 if videocodec != RsVideoCodec::Unknown {
347 self.videocodec = Some(videocodec);
348 }
349 let audio = RsAudio::list_from_filename(&self.name);
350 if !audio.is_empty() {
351 self.audio = Some(audio);
352 }
353
354 let re = Regex::new(r"(?i)s(\d+)e(\d+)").unwrap();
355 if let Some(caps) = re.captures(&self.name) {
356 self.season = caps[1].parse::<u32>().ok();
357 self.episode = caps[2].parse::<u32>().ok();
358 }
359 }
360}
361
362#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
363#[serde(rename_all = "camelCase")]
364pub struct RsRequestPluginRequest {
365 pub request: RsRequest,
366 pub credential: Option<PluginCredential>,
367 pub params: Option<HashMap<String, String>>,
368}
369
370#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
372#[serde(rename_all = "camelCase")]
373pub struct RsGroupDownload {
374 #[serde(default)]
376 pub group: bool,
377 #[serde(skip_serializing_if = "Option::is_none")]
378 pub group_thumbnail_url: Option<String>,
379 #[serde(skip_serializing_if = "Option::is_none")]
380 pub group_filename: Option<String>,
381 #[serde(skip_serializing_if = "Option::is_none")]
382 pub group_mime: Option<String>,
383 pub requests: Vec<RsRequest>,
384}
385
386
387
388#[cfg(test)]
389mod tests {
390
391 use self::error::RequestError;
392
393 use super::*;
394
395 #[test]
396 fn test_cookie_parsing() -> Result<(), RequestError> {
397 let parsed = RsCookie::from_str(".twitter.com;false;/;true;1722364794.437907;kdt;w1j")?;
398 assert!(parsed.domain == ".twitter.com".to_owned());
399 assert!(parsed.http_only == false);
400 assert!(parsed.path == "/".to_owned());
401 assert!(parsed.secure == true);
402 assert!(parsed.expiration == Some(1722364794.437907));
403 assert!(parsed.name == "kdt".to_owned());
404 assert!(parsed.value == "w1j".to_owned());
405 Ok(())
406 }
407
408 #[test]
409 fn test_cookie_parsing_no_expi() -> Result<(), RequestError> {
410 let parsed = RsCookie::from_str(".twitter.com;false;/;true;;kdt;w1j")?;
411 assert!(parsed.domain == ".twitter.com".to_owned());
412 assert!(parsed.http_only == false);
413 assert!(parsed.path == "/".to_owned());
414 assert!(parsed.secure == true);
415 assert!(parsed.expiration == None);
416 assert!(parsed.name == "kdt".to_owned());
417 assert!(parsed.value == "w1j".to_owned());
418 Ok(())
419 }
420
421 #[test]
422 fn test_netscape() -> Result<(), RequestError> {
423 let parsed = RsCookie::from_str(".twitter.com;false;/;true;1722364794.437907;kdt;w1j")?;
424 assert!(parsed.netscape() == ".twitter.com\tTRUE\t/\tTRUE\t1722364794\tkdt\tw1j");
425 Ok(())
426 }
427 #[test]
428 fn test_netscape_doublequote() -> Result<(), RequestError> {
429 let parsed = RsCookie::from_str(".twitter.com;true;/;true;1726506480.700665;ads_prefs;\"HBESAAA=\"")?;
430 assert!(parsed.netscape() == ".twitter.com\tTRUE\t/\tTRUE\t1726506480\tads_prefs\t\"HBESAAA=\"");
431 Ok(())
432 }
433
434 #[test]
435 fn test_parse_filename() -> Result<(), RequestError> {
436 let req = RsRequest {url: "http://www.test.com/filename.mp4?toto=3".to_string(), filename: Some("test.mkv".to_owned()), ..Default::default()};
437 assert_eq!(req.filename_or_extract_from_url(), Some("test.mkv".to_string()));
438 let req = RsRequest {url: "http://www.test.com/filename.mp4?toto=3".to_string(), ..Default::default()};
439 assert_eq!(req.filename_or_extract_from_url(), Some("filename.mp4".to_string()), "We are expecting a filename from the url");
440 let req = RsRequest {url: "http://www.test.com/notfilename?toto=3".to_string(), ..Default::default()};
441 assert_eq!(req.filename_or_extract_from_url(), None, "Should return none as there is no filename with extensiopn in url");
442 let req = RsRequest {url: "http://www.test.com/notfilename.toolong?toto=3".to_string(), ..Default::default()};
443 assert_eq!(req.filename_or_extract_from_url(), None, "Should return none as too long after dot is not an extension");
444 let req = RsRequest {url: "http://www.test.com/filename%20test.mp4?toto=3".to_string(), ..Default::default()};
445 assert_eq!(req.filename_or_extract_from_url(), Some("filename test.mp4".to_string()), "Should decode URL-encoded filename");
446 Ok(())
447 }
448
449
450 #[test]
451 fn test_header() -> Result<(), RequestError> {
452 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")?];
453 println!("header: {}", parsed.header_value());
454 assert!(parsed.header_value() == "ads_prefs=\"HBESAAA=\"; kdt=w1j");
455 Ok(())
456 }
457
458 #[test]
459 fn test_parse() -> Result<(), RequestError> {
460 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()};
461 req.parse_filename();
462 assert_eq!(req.season.unwrap(), 1);
463 assert_eq!(req.episode.unwrap(), 1);
464 assert_eq!(req.resolution.unwrap(), RsResolution::FullHD);
465 assert_eq!(req.videocodec.unwrap(), RsVideoCodec::H264);
466 assert_eq!(req.video_format.unwrap(), RsVideoFormat::Mkv);
467 assert_eq!(req.audio.unwrap().len(), 1);
468 Ok(())
469 }
470
471 #[test]
472 fn test_parse2() -> Result<(), RequestError> {
473 let mut req = RsRequest { filename: Some("Shogun.2024.S01E05.MULTi.HDR.DV.2160p.WEB.H265-FW".to_owned()), ..Default::default()};
474 req.parse_filename();
475 assert_eq!(req.season.expect("a season"), 1);
476 assert_eq!(req.episode.expect("an episode"), 5);
477 assert_eq!(req.resolution.expect("a resolution"), RsResolution::UHD);
478 assert_eq!(req.videocodec.expect("a videocodec"), RsVideoCodec::H265);
479
480 Ok(())
481 }
482}
483