mkpm_sl/
book.rs

1use crate::{List, ReadJson, Retrieve, Search};
2use serde_derive::{Deserialize, Serialize};
3use serde_json::from_str;
4use std::io;
5use std::io::{Cursor, Error};
6
7#[derive(Debug, Clone, Deserialize, Serialize)]
8pub struct Book {
9    pub title: String,
10    pub short: String,
11}
12
13impl List for Book{
14    fn list(item: &Vec<Self>) where Self: Sized {
15        println!("//// AVAILABLE BOOKS");
16        for i in item{
17            println!("// {}", i.title);
18        }
19    }
20}
21
22impl ReadJson for Book {
23    fn read_json(path: &str) -> Result<Vec<Self>, Error>
24    where
25        Self: Sized,
26    {
27        let s = std::fs::read_to_string(path)?;
28        let v: Vec<Self> = from_str(&s).unwrap();
29        return Ok(v);
30    }
31}
32
33impl Search for Book {
34    fn search(to_check: &str, object: &Vec<Self>) -> Result<Self, String>
35    where
36        Self: Sized,
37    {
38        for i in object {
39            if to_check == i.title {
40                return Ok(i.to_owned());
41            }
42        }
43        let msg = format!("Couldn't find book of title: {}", to_check);
44        return Err(msg);
45    }
46}
47
48impl Book {
49    pub async fn get(&self) -> Retrieve<()> {
50        let link = format!("http://mkproj.com/download/{}", &self.short);
51        let resp = reqwest::get(&link).await?;
52        let filename = format!("{}.zip", &self.short);
53        let mut file = std::fs::File::create(&filename)?;
54        let mut content = Cursor::new(resp.bytes().await?);
55        io::copy(&mut content, &mut file)?;
56        return Ok(());
57    }
58}