root/src/booru/safe.rs

// safe.rs
//
// Copyright 2020 nee <nee-git@hidamari.blue>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-or-later

//#[path = "../booru.rs"] mod booru;
use crate::booru::Booru;
use crate::booru::Boorus;
use crate::booru::Post;
use crate::booru::Posts;
use crate::booru::http::http_client;
use anyhow::Result;
use serde::Deserialize;

#[allow(dead_code)]
#[derive(Deserialize, Debug, Clone)]
pub struct SafebooruPost {
    directory: i32,
    hash: String,
    height: u32,
    id: u64,
    image: String,
    // change: u64,
    // owner: String,
    // parent_id: u64,
    // rating: String,
    sample: bool,
    sample_height: u32,
    sample_width: u32,
    // score: u32,
    tags: String,
    width: u32,
    #[serde(skip_deserializing)]
    domain: String,
}

impl Post for SafebooruPost {
    fn id(&self) -> u64 {
        self.id
    }
    fn sort_id(&self) -> u64 {
        self.id
    }
    fn width(&self) -> u32 {
        self.width
    }
    fn height(&self) -> u32 {
        self.height
    }
    fn sample_url(&self) -> String {
        if self.sample {
            format!(
                "https://{}/samples/{}/sample_{}.jpg",
                self.domain, self.directory, self.sample
            )
        } else {
            self.full_url()
        }
    }
    fn thumb_url(&self) -> String {
        let dot_pos = &self.image.find('.').unwrap_or(self.image.len());
        let mut filename = self.image.clone();
        filename.replace_range(dot_pos.., ".jpg");
        format!(
            "https://{}/thumbnails/{}/thumbnail_{}",
            self.domain, self.directory, filename
        )
    }
    fn full_url(&self) -> String {
        format!(
            "https://{}/images/{}/{}",
            self.domain, self.directory, self.image
        )
    }
    fn filename(&self) -> String {
        self.image.to_owned()
    }
    fn tags(&self) -> Vec<&str> {
        self.tags.split(' ').collect()
    }
    fn web_url(&self) -> String {
        format!(
            "https://{}/index.php?page=post&s=view&id={}",
            self.domain(),
            self.id()
        )
    }
    fn domain(&self) -> &String {
        &self.domain
    }
    fn clone_post(&self) -> Box<dyn Post> {
        std::boxed::Box::new(self.clone())
    }

    fn imp(&self) -> Posts {
        Posts::Safebooru(self.clone())
    }
}

#[derive(Deserialize, Debug, Clone)]
pub struct Safebooru {
    domain: String,
}
impl Booru for Safebooru {
    fn next_page(&self, current_page: u32, _last_result_count: u32) -> u32 {
        current_page + 1
    }
    fn clone_booru(&self) -> Box<dyn Booru> {
        Box::new(self.clone())
    }
    fn check_api_by_domain(&self, hash: u64, _domain: &str) -> bool {
        hash == 8429333541781048592
    }
    fn get_domain(&self) -> &String {
        &self.domain
    }
    fn imp(&self) -> Boorus {
        Boorus::Safebooru(self.clone())
    }
}

impl Safebooru {
    pub fn new(domain: String) -> Safebooru {
        Safebooru { domain }
    }

    pub async fn fetch_index(
        &self,
        search: &str,
        pid: u32,
    ) -> Result<std::vec::Vec<Box<dyn Post>>> {
        let url = format!(
            "https://{}/index.php?page=dapi&s=post&q=index&json=1&pid={pid}&tags={search}",
            self.domain
        );
        println!("fetching {}", url);
        let posts = http_client()
            .get(&url)
            .send()
            .await?
            .json::<Vec<Box<SafebooruPost>>>()
            .await?;
        Ok(posts
            .into_iter()
            .map(|mut p| {
                p.domain = self.domain.clone();
                p
            })
            .map(|p| Box::<dyn Post>::from(p))
            .collect())
    }
}