From 9b2c7a860232317d98165ca249212b412df6d4d8 Mon Sep 17 00:00:00 2001 From: lifegpc Date: Sun, 26 Jun 2022 08:34:52 +0000 Subject: [PATCH] fanbox api: item deserailze more data --- src/fanbox/item.rs | 41 +++++++++++++++++++++++++++++------------ src/parser/json.rs | 14 ++++++++++++++ src/parser/mod.rs | 1 + 3 files changed, 44 insertions(+), 12 deletions(-) create mode 100644 src/parser/json.rs diff --git a/src/fanbox/item.rs b/src/fanbox/item.rs index c03bf60..9b26a5c 100644 --- a/src/fanbox/item.rs +++ b/src/fanbox/item.rs @@ -1,3 +1,4 @@ +use crate::parser::json::parse_u64; use json::JsonValue; use std::fmt::Debug; @@ -8,19 +9,20 @@ pub struct FanboxItem { } impl FanboxItem { + #[inline] + pub fn creator_id(&self) -> Option<&str> { + self.data["creatorId"].as_str() + } + + #[inline] + pub fn fee_required(&self) -> Option { + self.data["feeRequired"].as_u64() + } + + #[inline] /// Returns the id of the item pub fn id(&self) -> Option { - let id = &self.data["id"]; - match id.as_u64() { - Some(id) => Some(id), - None => match id.as_str() { - Some(id) => match id.trim().parse::() { - Ok(id) => Some(id), - Err(_) => None, - }, - None => None, - }, - } + parse_u64(&self.data["id"]) } #[inline] @@ -28,19 +30,34 @@ impl FanboxItem { self.data["isLiked"].as_bool() } + #[inline] + pub fn like_count(&self) -> Option { + self.data["likeCount"].as_u64() + } + #[inline] /// Returns item's title pub fn title(&self) -> Option<&str> { self.data["title"].as_str() } + + #[inline] + /// Returns pixiv user id + pub fn user_id(&self) -> Option { + parse_u64(&self.data["user"]["userId"]) + } } impl Debug for FanboxItem { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("FanboxItem") .field("id", &self.id()) - .field("title", &self.title()) + .field("creator_id", &self.creator_id()) + .field("fee_required", &self.fee_required()) .field("is_liked", &self.is_liked()) + .field("like_count", &self.like_count()) + .field("title", &self.title()) + .field("user_id", &self.user_id()) .finish_non_exhaustive() } } diff --git a/src/parser/json.rs b/src/parser/json.rs new file mode 100644 index 0000000..da27ac8 --- /dev/null +++ b/src/parser/json.rs @@ -0,0 +1,14 @@ +use json::JsonValue; + +pub fn parse_u64(data: &JsonValue) -> Option { + match data.as_u64() { + Some(num) => Some(num), + None => match data.as_str() { + Some(num) => match num.trim().parse::() { + Ok(num) => Some(num), + Err(_) => None, + }, + None => None, + }, + } +} diff --git a/src/parser/mod.rs b/src/parser/mod.rs index e280a05..a720e33 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -1,2 +1,3 @@ pub mod description; +pub mod json; pub mod metadata;