From 9653b8ac5334c2130f6622de891a73b0a4e45cab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leon=20Gr=C3=BCnewald?= Date: Wed, 3 Jan 2024 15:35:58 +0100 Subject: [PATCH] Add function for singular post --- src/client.rs | 35 +++++++++++++++++++++++++++++++++-- src/post.rs | 16 ++++++++++++++-- 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/src/client.rs b/src/client.rs index 9a07ba0..ba7c8c3 100644 --- a/src/client.rs +++ b/src/client.rs @@ -1,5 +1,5 @@ use std::io::Write; -use crate::post::{Post, Posts}; +use crate::post::{Id, Post, RawPost, RawPosts}; use anyhow::Result; use base64::{engine::GeneralPurpose, Engine}; use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, USER_AGENT}; @@ -89,7 +89,38 @@ impl Client { debug_file.write_all(text.as_bytes())?; } - Ok(serde_json::from_str::(text.as_str())?.into()) + Ok(serde_json::from_str::(text.as_str())?.into()) + } + + /// Get a specific post + /// + /// ``` + ///use r621::prelude::*; + ///use std::error::Error; + /// + ///#[tokio::main] + ///async fn main() -> Result<(), Box> { + /// let user_agent = "MyProject/1.0 (by username on e621)"; + /// let auth = Authentication::Authorized { + /// username: "hexerade", + /// apikey: "1nHrmzmsvJf26EhU1F7CjnjC" + /// }; + /// let mut esix_client = Client::new(auth, user_agent); + /// let post = esix_client.get_post(1337).await?; + ///} + /// ``` + async fn get_post(&mut self, post_id: Id) -> Result { + self.request_limiter().await; + let res = self.get_post_raw(post_id).await?; + let text = res.text().await?; + + Ok(serde_json::from_str::(text.as_str())?.into()) + } + + pub async fn get_post_raw(&mut self, post_id: Id) -> Result { + let url = url::Url::parse(format!("{}/posts/{}.json", self.host, post_id).as_str())?; + self.request_counter = self.request_counter+1; + Ok(self.http_client.get(url.as_str()).send().await?) } async fn request_limiter(&mut self) { diff --git a/src/post.rs b/src/post.rs index 602f91e..63178e0 100644 --- a/src/post.rs +++ b/src/post.rs @@ -3,12 +3,24 @@ pub type FileSize = u64; pub type ImageDimension = u64; #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] -pub struct Posts { +pub struct RawPost { + #[serde(alias = "post")] + inner: Post, +} + +impl Into for RawPost { + fn into(self) -> Post { + self.inner + } +} + +#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] +pub struct RawPosts { #[serde(alias = "posts")] inner: Vec, } -impl Into> for Posts { +impl Into> for RawPosts { fn into(self) -> Vec { self.inner }