src/aniskip.rs

179 lines · 4933 bytes

  1use reqwest::{blocking, Response};
  2use serde::{Deserialize, Serialize};
  3use std::{error::Error};
  4use serde_json;
  5
  6// Define the enum for SkipType
  7#[derive(Debug, Deserialize, PartialEq)]
  8pub enum SkipType {
  9    #[serde(rename = "op")]
 10    Op,
 11    #[serde(rename = "ed")]
 12    Ed,
 13}
 14
 15// Define the struct for the interval part
 16#[derive(Debug, Deserialize)]
 17pub struct Interval {
 18    #[serde(rename = "start_time")]
 19    pub start: f64,
 20    #[serde(rename = "end_time")]
 21    pub end: f64,
 22}
 23
 24// Define the struct for the response result
 25#[derive(Debug, Deserialize)]
 26pub struct SkipResult {
 27    pub interval: Interval,
 28    #[serde(rename = "skip_type")]
 29    pub kind: SkipType,
 30    #[serde(rename = "episode_length")]
 31    pub episode_length: f64,
 32}
 33
 34// Define the struct for the entire response
 35#[derive(Debug, Deserialize)]
 36pub struct AniskipResponse {
 37    pub found: bool,
 38    pub results: Vec<SkipResult>,
 39}
 40
 41// Struct to represent the simplified skip time
 42#[derive(Debug)]
 43pub struct SkipTime {
 44    pub kind: SkipType,
 45    pub intervals: SkipInterval,
 46}
 47
 48// Interval struct for simplified handling
 49#[derive(Debug)]
 50pub struct SkipInterval {
 51    pub start: i32,
 52    pub end: i32,
 53}
 54
 55impl SkipTime {
 56    // Constructor for SkipTime
 57    pub fn new(kind: SkipType, start: i32, end: i32) -> Self {
 58        SkipTime {
 59            kind,
 60            intervals: SkipInterval { start, end },
 61        }
 62    }
 63}
 64
 65// Function to get aniskip data
 66pub fn get_aniskip_data(anime_id: i32, episode_number: i32) -> Result<String, Box<dyn Error>> {
 67    let base_url = "https://api.aniskip.com/v1/skip-times";
 68    let url = format!("{base_url}/{anime_id}/{episode_number}?types=op&types=ed"); 
 69
 70    let response = blocking::get(url)?;
 71    // Check if the request was successful
 72    if response.status().is_success() {
 73        // Return the response body
 74        let body = response.text()?;
 75        Ok(body)
 76    } else {
 77        Err(format!("Failed to retrieve the page. Status: {}", response.status()).into())
 78    }
 79}
 80
 81// Function to parse the Aniskip response and return SkipTime structs
 82pub fn parse_aniskip_response(response_text: &String) -> Result<Vec<SkipTime>, Box<dyn Error>> {
 83    // Deserialize the JSON into AniskipResponse
 84    let parsed_data: AniskipResponse = serde_json::from_str(response_text)?;
 85
 86    // If no skips are found, return an empty vector
 87    if !parsed_data.found {
 88        return Ok(Vec::new());
 89    }
 90
 91    // Convert the parsed results into SkipTime structs
 92    let skip_times: Vec<SkipTime> = parsed_data.results.into_iter().map(|result| {
 93        SkipTime::new(
 94            result.kind,
 95            result.interval.start as i32,
 96            result.interval.end as i32,
 97        )
 98    }).collect();
 99
100    Ok(skip_times)
101}
102
103pub fn get_skip_times(anime_id: i32, episode_number: i32) -> Result<Vec<SkipTime>, Box<dyn Error>> {
104
105    let mut response_text = get_aniskip_data(anime_id, episode_number);
106
107    match response_text{
108        Ok(response_text) => {
109            let skip_times = parse_aniskip_response(&response_text);
110            // println!("{:?}", skip_times);
111            skip_times
112            
113        },
114        Err(e) => {
115            // eprintln!("Error fetching Aniskip data: {}", e);
116            Err(e)
117        }
118    }
119}
120
121// Unit tests
122#[cfg(test)]
123mod tests {
124    use super::*; // Import the functions and types from the current module
125
126    #[test]
127    fn test_skip_time_creation() {
128        let skip = SkipTime::new(SkipType::Op, 10, 30);
129
130        match skip.kind {
131            SkipType::Op => assert_eq!(skip.intervals.start, 10),
132            _ => panic!("Expected SkipType::Op"),
133        }
134    }
135
136    #[test]
137    fn test_skip_time_ed_creation() {
138        let skip = SkipTime::new(SkipType::Ed, 1100, 1130);
139
140        match skip.kind {
141            SkipType::Ed => {
142                assert_eq!(skip.intervals.start, 1100);
143                assert_eq!(skip.intervals.end, 1130);
144            }
145            _ => panic!("Expected SkipType::Ed"),
146        }
147    }
148
149    #[test]
150    fn test_parse_aniskip_response(){
151        let anime_id = 21;
152        let episode_no = 2;
153    
154        let response_text = get_aniskip_data(anime_id, episode_no);
155    
156        match response_text{
157            Ok(response_text) => {
158                let skip_times = parse_aniskip_response(&response_text);
159                // println!("{:?}", skip_times);
160                match skip_times{
161                    Ok(skip_times) => {
162                        for skip in skip_times {
163                            println!("{:?} skips from {} to {}", skip.kind, skip.intervals.start, skip.intervals.end);
164                        }
165                    }
166                    Err(e) => {
167                        eprintln!("Error: {e}")
168                    }
169                }
170            },
171            Err(e) => {
172                eprintln!("Error fetching Aniskip data, Are you connected to internet?: {}", e);
173            }
174        }
175    }
176
177}
178
179