rs_plugin_common_interfaces/request/
mod.rs

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 [domain, httpOnly, path, secure, expiration, name, value ] = line.split(';');
29        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        //return [domain, domain.startsWith('.') ? 'TRUE' : 'FALSE', path, secure ? 'TRUE' : 'FALSE', expiration.split('.')[0], name, value].join('\t')
66        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    /// If true this request can be saved for later use and will remain valid
104    /// If Permanent is true but status is intermediate the process will go through request plugins to try to get a permanant link
105    #[serde(default)]
106    pub permanent: bool,
107    /// If true can be played/downloaded instantly (streamable link, no need to add to service first)
108    #[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    /// some downloader like YTDL require detailed cookies. You can create Header equivalent  with `headers` fn on the vector
120    #[serde(skip_serializing_if = "Option::is_none")]
121    pub cookies: Option<Vec<RsCookie>>,
122    /// If must choose between multiple files. Recall plugin with a `selected_file` containing one of the name in this list to get link
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub files: Option<Vec<RsRequestFiles>>,
125    /// one of the `files` selected for download
126    #[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    // Download-specific fields
161    #[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    // Lookup fields (text to search in database, NOT IDs)
171    #[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); // Decodes the URL
206                    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    /// No plugin yet processed this request
257    #[default]
258	Unprocessed,
259    /// All plugin processed but with no result
260    Processed,
261    ///if remain in this state after all plugin it will go through YtDl to try to extract medias
262    NeedParsing,
263    /// Link can be processed but first need to be added to the service and downloaded
264    ///   -First call this plugin again with `add` method
265    ///   -Check status and once ready call `process` again
266    RequireAdd,
267    /// Modified but need a second pass of plugins
268    Intermediate,
269    /// Multiple files found, current plugin need to be recalled with a `selected_file``
270    NeedFileSelection,
271    /// `url` is ready but should be proxied by the server as it contains sensitive informations (like token)
272    FinalPrivate,
273    /// `url` is ready and can be directly sent to _any_ user directly (using redirect)
274    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    // Lookup fields (text to search in database, NOT IDs)
327    #[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/// Groups multiple download requests together, optionally combining them into a single media item
371#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
372#[serde(rename_all = "camelCase")]
373pub struct RsGroupDownload {
374    /// If true, all requests will be grouped into a single media item (album)
375    #[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/// Status of a processing task added via request_add
387#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, strum_macros::Display, EnumString, Default)]
388#[serde(rename_all = "camelCase")]
389#[strum(serialize_all = "camelCase")]
390pub enum RsProcessingStatus {
391    #[default]
392    Pending,
393    Processing,
394    Finished,
395    Error,
396    Paused,
397}
398
399/// Response from request_add plugin method
400#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
401#[serde(rename_all = "camelCase")]
402pub struct RsRequestAddResponse {
403    /// Processing ID returned by the plugin service
404    pub processing_id: String,
405    /// Initial status
406    #[serde(default)]
407    pub status: RsProcessingStatus,
408    /// UTC timestamp (milliseconds) for estimated completion
409    #[serde(skip_serializing_if = "Option::is_none")]
410    pub eta: Option<i64>,
411}
412
413/// Response from get_progress plugin method
414#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
415#[serde(rename_all = "camelCase")]
416pub struct RsProcessingProgress {
417    /// Processing ID
418    pub processing_id: String,
419    /// Progress percentage (0-100)
420    pub progress: u32,
421    /// Current status
422    pub status: RsProcessingStatus,
423    /// Error message if status is Error
424    #[serde(skip_serializing_if = "Option::is_none")]
425    pub error: Option<String>,
426    /// UTC timestamp (milliseconds) for estimated completion - can be updated
427    #[serde(skip_serializing_if = "Option::is_none")]
428    pub eta: Option<i64>,
429    /// Updated request with final URL when finished
430    #[serde(skip_serializing_if = "Option::is_none")]
431    pub request: Option<Box<RsRequest>>,
432}
433
434/// Request for pause/remove/get_progress plugin methods
435#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
436#[serde(rename_all = "camelCase")]
437pub struct RsProcessingActionRequest {
438    /// Processing ID to act on
439    pub processing_id: String,
440    /// Credential for the plugin
441    pub credential: Option<PluginCredential>,
442    /// Optional params
443    pub params: Option<HashMap<String, String>>,
444}
445
446#[cfg(test)]
447mod tests {
448
449    use self::error::RequestError;
450
451    use super::*;
452
453    #[test]
454    fn test_cookie_parsing() -> Result<(), RequestError> {
455        let parsed = RsCookie::from_str(".twitter.com;false;/;true;1722364794.437907;kdt;w1j")?;
456        assert!(parsed.domain == ".twitter.com".to_owned());
457        assert!(parsed.http_only == false);
458        assert!(parsed.path == "/".to_owned());
459        assert!(parsed.secure == true);
460        assert!(parsed.expiration == Some(1722364794.437907));
461        assert!(parsed.name == "kdt".to_owned());
462        assert!(parsed.value == "w1j".to_owned());
463        Ok(())
464    }
465    
466    #[test]
467    fn test_cookie_parsing_no_expi() -> Result<(), RequestError> {
468        let parsed = RsCookie::from_str(".twitter.com;false;/;true;;kdt;w1j")?;
469        assert!(parsed.domain == ".twitter.com".to_owned());
470        assert!(parsed.http_only == false);
471        assert!(parsed.path == "/".to_owned());
472        assert!(parsed.secure == true);
473        assert!(parsed.expiration == None);
474        assert!(parsed.name == "kdt".to_owned());
475        assert!(parsed.value == "w1j".to_owned());
476        Ok(())
477    }
478
479    #[test]
480    fn test_netscape() -> Result<(), RequestError> {
481        let parsed = RsCookie::from_str(".twitter.com;false;/;true;1722364794.437907;kdt;w1j")?;
482        assert!(parsed.netscape() == ".twitter.com\tTRUE\t/\tTRUE\t1722364794\tkdt\tw1j");
483        Ok(())
484    }
485    #[test]
486    fn test_netscape_doublequote() -> Result<(), RequestError> {
487        let parsed = RsCookie::from_str(".twitter.com;true;/;true;1726506480.700665;ads_prefs;\"HBESAAA=\"")?;
488        assert!(parsed.netscape() == ".twitter.com\tTRUE\t/\tTRUE\t1726506480\tads_prefs\t\"HBESAAA=\"");
489        Ok(())
490    }
491
492    #[test]
493    fn test_parse_filename() -> Result<(), RequestError> {
494        let req = RsRequest {url: "http://www.test.com/filename.mp4?toto=3".to_string(), filename: Some("test.mkv".to_owned()), ..Default::default()};
495        assert_eq!(req.filename_or_extract_from_url(), Some("test.mkv".to_string()));
496        let req = RsRequest {url: "http://www.test.com/filename.mp4?toto=3".to_string(), ..Default::default()};
497        assert_eq!(req.filename_or_extract_from_url(), Some("filename.mp4".to_string()), "We are expecting a filename from the url");
498        let req = RsRequest {url: "http://www.test.com/notfilename?toto=3".to_string(), ..Default::default()};
499        assert_eq!(req.filename_or_extract_from_url(), None, "Should return none as there is no filename with extensiopn in url");
500        let req = RsRequest {url: "http://www.test.com/notfilename.toolong?toto=3".to_string(), ..Default::default()};
501        assert_eq!(req.filename_or_extract_from_url(), None, "Should return none as too long after dot is not an extension");
502        let req = RsRequest {url: "http://www.test.com/filename%20test.mp4?toto=3".to_string(), ..Default::default()};
503        assert_eq!(req.filename_or_extract_from_url(), Some("filename test.mp4".to_string()), "Should decode URL-encoded filename");
504        Ok(())
505    }
506
507
508    #[test]
509    fn test_header() -> Result<(), RequestError> {
510        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")?];
511        println!("header: {}", parsed.header_value());
512        assert!(parsed.header_value() == "ads_prefs=\"HBESAAA=\"; kdt=w1j");
513        Ok(())
514    }
515
516    #[test]
517    fn test_parse() -> Result<(), RequestError> {
518        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()};
519        req.parse_filename();
520        assert_eq!(req.season.unwrap(), 1);
521        assert_eq!(req.episode.unwrap(), 1);
522        assert_eq!(req.resolution.unwrap(), RsResolution::FullHD);
523        assert_eq!(req.videocodec.unwrap(), RsVideoCodec::H264);
524        assert_eq!(req.video_format.unwrap(), RsVideoFormat::Mkv);
525        assert_eq!(req.audio.unwrap().len(), 1);
526        Ok(())
527    }
528
529    #[test]
530    fn test_parse2() -> Result<(), RequestError> {
531        let mut req = RsRequest { filename: Some("Shogun.2024.S01E05.MULTi.HDR.DV.2160p.WEB.H265-FW".to_owned()), ..Default::default()};
532        req.parse_filename();
533        assert_eq!(req.season.expect("a season"), 1);
534        assert_eq!(req.episode.expect("an episode"), 5);
535        assert_eq!(req.resolution.expect("a resolution"), RsResolution::UHD);
536        assert_eq!(req.videocodec.expect("a videocodec"), RsVideoCodec::H265);
537
538        Ok(())
539    }
540}
541