Skip to content

Commit

Permalink
some updates
Browse files Browse the repository at this point in the history
- i'll redo this crate soon
  • Loading branch information
AndrielFR committed Jun 25, 2022
1 parent e68e2a0 commit 730893f
Show file tree
Hide file tree
Showing 11 changed files with 86 additions and 171 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ Copyright © 2022 [AndrielFR](https://github.com/AndrielFR)
Licensed under the [Expat/MIT license](LICENSE).
This project is also [REUSE compliant](https://reuse.software/).
See individual files for more copyright information.
a.rs
42 changes: 12 additions & 30 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,6 @@ impl Default for Client {
}

impl Client {
pub fn new() -> Self {
Client::default()
}

pub fn api_token(mut self, token: &str) -> Self {
self.api_token = Some(token.to_string());
self
Expand Down Expand Up @@ -79,22 +75,13 @@ impl Client {
Ok(person)
}

pub async fn mutate(
&self,
_media_type: &str,
_id: i64,
_variables: serde_json::Value,
) -> Result<bool> {
todo!()
}

pub async fn search_anime(
&self,
variables: serde_json::Value,
) -> Option<Vec<crate::models::Anime>> {
let result = self.request("anime", "search", variables).await.unwrap();
let mut _models = Vec::<crate::models::Anime>::new();
todo!()
unimplemented!()
}

pub(crate) async fn request(
Expand All @@ -103,37 +90,32 @@ impl Client {
action: &str,
variables: serde_json::Value,
) -> std::result::Result<serde_json::Value, reqwest::Error> {
let query = Client::get_query(media_type, action);
let query = Client::get_query(media_type, action).unwrap();
let json = serde_json::json!({"query": query, "variables": variables});
let body = reqwest::Client::new()
let mut body = reqwest::Client::new()
.post("https://graphql.anilist.co/")
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.timeout(Duration::from_secs(self.timeout))
.body(json.to_string());

let body = match &self.api_token {
Some(token) => body.bearer_auth(token),
None => body,
};
if let Some(token) = &self.api_token {
body = body.bearer_auth(token);
}

let response = body.send().await?.text().await?;
let result: serde_json::Value = serde_json::from_str(&response).unwrap();

Ok(result)
}

pub fn get_query(media_type: &str, action: &str) -> String {
pub fn get_query(media_type: &str, action: &str) -> Result<String> {
let mut graphql_query = String::new();

let media_type = media_type.to_lowercase();
match media_type.as_str() {
"anime" => {}
"manga" => {}
"character" => {}
"user" => {}
"person" => {}
"studio" => {}
_ => panic!("The media_type '{}' does not exits!", { media_type }),
let media_types = vec!["anime", "manga", "character", "user", "person", "studio"];
if !media_types.contains(&media_type.as_str()) {
panic!("The media type '{}' does not exits", { media_type });
}

let file_name = format!("{}_{}.graphql", action, media_type);
Expand All @@ -142,6 +124,6 @@ impl Client {
.and_then(|mut file| file.read_to_string(&mut graphql_query))
.unwrap();

graphql_query
Ok(graphql_query)
}
}
3 changes: 0 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// Copyright (c) 2022 Andriel Ferreira <https://github.com/AndrielFR>

// #![deny(missing_docs)]
#![allow(clippy::field_reassign_with_default)]
#![allow(clippy::let_and_return)] // TODO: Remove this
#![allow(dead_code)] // TODO: Remove this
#![allow(unused_mut)] // TODO: Remove this
Expand All @@ -12,8 +11,6 @@
pub mod models;
mod client;
mod error;
// mod page;

pub use self::client::Client;
pub use self::error::{Error, Result};
// pub use self::page::Page;
2 changes: 1 addition & 1 deletion src/models/anime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,7 @@ impl Anime {

pub async fn load_full(self) -> crate::Result<Self> {
if !self.is_full_loaded {
let mut anime = crate::Client::new()
let mut anime = crate::Client::default()
.get_anime(serde_json::json!({"id": self.id}))
.await
.unwrap();
Expand Down
187 changes: 61 additions & 126 deletions src/models/character.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::models::Image;
use crate::models::Name;
use crate::models::Person;

use crate::Result;
use crate::{Client, Result};

#[derive(Debug, Default, Clone, PartialEq)]
pub struct Character {
Expand All @@ -31,152 +31,87 @@ pub struct Character {

impl Character {
pub(crate) fn parse(data: &serde_json::Value) -> Self {
let mut character = Character::default();

character.id = data["id"].as_i64().unwrap();

if let Some(name_object) = data["name"].as_object() {
let mut name = Name::default();

name.first = name_object["first"].as_str().unwrap().to_string();

if let Some(middle) = name_object["middle"].as_str() {
name.middle = Some(middle.to_string());
}

if let Some(last) = name_object["last"].as_str() {
name.last = Some(last.to_string());
}

name.full = name_object["full"].as_str().unwrap().to_string();

if let Some(native) = name_object["native"].as_str() {
name.native = Some(native.to_string());
}

if let Some(alternative_array) = name_object["alternative"].as_array() {
let mut alternative = Vec::with_capacity(alternative_array.len());

for alternative_name in alternative_array {
alternative.push(alternative_name.as_str().unwrap().to_string());
Self {
id: data["id"].as_i64().unwrap(),
name: data["name"].as_object().map(|object| {
Name {
first: object["first"].as_str().unwrap().to_string(),
middle: object["middle"].as_str().map(String::from),
last: object["last"].as_str().map(String::from),
full: object["full"].as_str().unwrap().to_string(),
native: object["native"].as_str().map(String::from),
alternative: object["alternative"].as_array().unwrap().into_iter().map(|item| item.as_str().unwrap().to_string()).collect::<Vec<String>>(),
alternative_spoiler: object["alternativeSpoiler"].as_array().unwrap().into_iter().map(|item| item.as_str().unwrap().to_string()).collect::<Vec<String>>(),
user_preferred: object["userPreferred"].as_str().map(String::from),
}

name.alternative = alternative;
}

if let Some(alternative_spoiler_array) = name_object["alternativeSpoiler"].as_array() {
let mut alternative_spoiler = Vec::with_capacity(alternative_spoiler_array.len());

for alternative_spoiler_name in alternative_spoiler_array {
alternative_spoiler
.push(alternative_spoiler_name.as_str().unwrap().to_string());
}).unwrap(),
role: data["role"].as_str().map(|role| {
match role.to_ascii_lowercase().as_str() {
"main" => Role::Main,
"supporting" => Role::Supporting,
_ => Role::default(),
}

name.alternative_spoiler = alternative_spoiler;
}

if let Some(user_preferred) = name_object["userPreferred"].as_str() {
name.user_preferred = Some(user_preferred.to_string());
}

character.name = name;
}

if let Some(image_object) = data["image"].as_object() {
let mut image = Image::default();

if let Some(large) = image_object["large"].as_str() {
image.large = large.to_string();
}

if let Some(medium) = image_object["medium"].as_str() {
image.medium = medium.to_string();
}

character.image = image;
}

character.description = data["description"].as_str().unwrap().to_string();

if let Some(gender) = data["gender"].as_str() {
character.gender = match gender {
"Male" => Some(Gender::Male),
"Femalm" => Some(Gender::Female),
"NonBinary" => Some(Gender::NonBinary),
other => Some(Gender::Other(other.to_string())),
};
}

if let Some(date_of_birth) = data["dateOfBirth"].as_object() {
let mut date = Date::default();

if let Some(year) = date_of_birth["year"].as_i64() {
date.year = Some(year);
}

if let Some(month) = date_of_birth["month"].as_i64() {
date.month = Some(month);
}

if let Some(day) = date_of_birth["day"].as_i64() {
date.day = Some(day);
}

character.date_of_birth = Some(date);
}

if let Some(age) = data["age"].as_str() {
character.age = Some(age.to_string());
}

if let Some(blood_type) = data["bloodType"].as_str() {
character.blood_type = Some(blood_type.to_string());
}

if let Some(is_favourite) = data["isFavourite"].as_bool() {
character.is_favourite = Some(is_favourite);
}

if let Some(is_favourite_blocked) = data["isFavouriteBlocked"].as_bool() {
character.is_favourite_blocked = Some(is_favourite_blocked);
}

character.url = data["siteUrl"].as_str().unwrap().to_string();

if let Some(favourites) = data["favourites"].as_i64() {
character.favourites = Some(favourites);
}

if let Some(mod_notes) = data["modNotes"].as_str() {
character.mod_notes = Some(mod_notes.to_string());
}),
image: data["image"].as_object().map(|object| {
Image {
large: object["large"].as_str().unwrap().to_string(),
medium: object["medium"].as_str().unwrap().to_string(),
}
}).unwrap(),
description: data["description"].as_str().unwrap().to_string(),
gender: data["gender"].as_str().map(|gender| {
match gender.to_ascii_lowercase().as_str() {
"male" => Gender::Male,
"female" => Gender::Female,
"nonbinary" => Gender::NonBinary,
_ => Gender::Other(gender.to_string()),
}
}),
date_of_birth: data["dateOfBirth"].as_object().map(|object| {
Date {
year: object["year"].as_i64(), // TODO: Use u64
month: object["month"].as_i64(), // Same as above
day: object["day"].as_i64(), // Same as above
}
}),
age: data["age"].as_str().map(String::from),
blood_type: data["bloodType"].as_str().map(String::from),
is_favourite: data["isFavourite"].as_bool(),
is_favourite_blocked: data["isFavouriteBlocked"].as_bool(),
url: data["siteUrl"].as_str().unwrap().to_string(),
favourites: data["favourites"].as_i64(),
mod_notes: data["modNotes"].as_str().map(String::from),
..Default::default()
}

character
}

pub async fn load_full(self) -> crate::Result<Self> {
pub async fn load_full(self, client: &Client) -> Result<Self> {
if !self.is_full_loaded {
let mut character = crate::Client::new()
let mut character = client
.get_character(serde_json::json!({"id": self.id}))
.await
.unwrap();
.await?;
character.is_full_loaded = true;

Ok(character)
} else {
panic!("This character is already full loaded")
}
}

pub async fn get_medias<T>() -> Result<T> {
todo!()
pub async fn get_medias<T>(&self) -> Result<T> {
unimplemented!()
}

pub fn is_full_loaded(&self) -> bool {
self.is_full_loaded
}
}

#[derive(Debug, Clone, PartialEq)]
pub enum Role {
Background,
Main,
Supporting,
Background,
}

impl Default for Role {
Expand Down
2 changes: 1 addition & 1 deletion src/models/manga.rs
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ impl Manga {

pub async fn load_full(self) -> crate::Result<Self> {
if !self.is_full_loaded {
let mut manga = crate::Client::new()
let mut manga = crate::Client::default()
.get_manga(serde_json::json!({"id": self.id}))
.await
.unwrap();
Expand Down
6 changes: 3 additions & 3 deletions src/models/person.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ impl Person {

pub async fn load_full(self) -> crate::Result<Self> {
if !self.is_full_loaded {
let mut person = crate::Client::new().get_person(self.id).await.unwrap();
let mut person = crate::Client::default().get_person(self.id).await.unwrap();
person.is_full_loaded = true;
Ok(person)
} else {
Expand All @@ -211,10 +211,10 @@ impl Person {
}

pub async fn get_medias<T>() -> Result<T> {
todo!()
unimplemented!()
}

pub async fn get_character_medias<T>(_character_id: i64) -> Result<T> {
todo!()
unimplemented!()
}
}
2 changes: 1 addition & 1 deletion tests/anime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ use rust_anilist::Client;

#[tokio::test]
async fn get_anime() {
let anime = Client::new().get_anime(serde_json::json!({"id": 20})).await;
let anime = Client::default().get_anime(serde_json::json!({"id": 20})).await;
assert!(anime.is_ok())
}
Loading

0 comments on commit 730893f

Please sign in to comment.