src/anilist.rs
138 lines · 3545 bytes
1use reqwest::{header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE}, Error};
2use serde::{Serialize, Deserialize};
3
4#[derive(Serialize)]
5struct Query {
6 query: String,
7 variables: Variables,
8}
9
10#[derive(Serialize)]
11struct Variables {
12 search: String,
13}
14
15#[derive(Deserialize, Debug)]
16struct Media {
17 id: i32,
18 title: Title,
19}
20
21#[derive(Deserialize, Debug)]
22struct Title {
23 romaji: String,
24 english: Option<String>,
25 native: String,
26}
27
28#[derive(Deserialize, Debug)]
29struct Page {
30 media: Vec<Media>,
31}
32
33#[derive(Deserialize, Debug)]
34struct ResponseData {
35 Page: Page,
36}
37
38#[derive(Deserialize, Debug)]
39pub struct ApiResponse {
40 pub data: ResponseData,
41}
42
43pub struct AnimeApi {
44 pub token: String,
45}
46
47impl AnimeApi {
48 // Public constructor for the struct
49 pub fn new(token: String) -> Self {
50 AnimeApi { token }
51 }
52
53 pub fn search_anime_anilist(&self, query: &str) -> Result<ApiResponse, reqwest::Error> {
54 let url = "https://graphql.anilist.co";
55
56 let query_string = r#"
57 query ($search: String) {
58 Page(page: 1, perPage: 10) {
59 media(search: $search, type: ANIME) {
60 id
61 title {
62 romaji
63 english
64 native
65 }
66 }
67 }
68 }
69 "#;
70
71 let variables = Variables {
72 search: query.to_string(),
73 };
74
75 let request_body = Query {
76 query: query_string.to_string(),
77 variables,
78 };
79
80 let mut headers = HeaderMap::new();
81 headers.insert(AUTHORIZATION, HeaderValue::from_str(&format!("Bearer {}", self.token)).unwrap());
82 headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
83
84 // Send the request
85 let client = reqwest::blocking::Client::new();
86 let response = client
87 .post(url)
88 .headers(headers)
89 .json(&request_body)
90 .send()?;
91
92 // Check if the response is successful
93 if response.status().is_success() {
94 let api_response: ApiResponse = response.json()?;
95 Ok(api_response)
96 } else {
97 Ok(ApiResponse{
98 data: ResponseData{
99 Page: Page {
100 media: vec![
101 Media{
102 id: 0,
103 title: Title {
104 romaji: String::from("None"),
105 english: Some(String::from("None")),
106 native: String::from("None"),
107 }
108 }
109 ]
110 }
111 }
112 })
113 }
114
115 }
116}
117
118
119
120// pub fn parse_search_anime_anilist(response_text: &String) -> Result<Vec<SkipTime>, Box<dyn Error>>{
121// // Deserialize the JSON into AniskipResponse
122// let parsed_data: AniskipResponse = serde_json::from_str(response_text)?;
123
124// // If no skips are found, return an empty vector
125// if !parsed_data.found {
126// return Ok(Vec::new());
127// }
128// // Convert the parsed results into SkipTime structs
129// let skip_times: Vec<SkipTime> = parsed_data.results.into_iter().map(|result| {
130// SkipTime::new(
131// result.kind,
132// result.interval.start as i32,
133// result.interval.end as i32,
134// )
135// }).collect();
136
137// Ok(skip_times)
138// }