1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
use crate::Bytes;
use crate::{
    models::api::MissingParams, models::features::*, models::images::*, HttpError,
    HttpResult, MsgResp, ENDPOINT,
};
use reqwest::{Client, RequestBuilder};
use std::sync::Arc;

fn image_endpoint(pr: String) -> String {
    format!("{}/image/{}/", ENDPOINT, pr)
}

async fn make_request_image(c: RequestBuilder) -> HttpResult<ImageResponse, String> {
    let response = c.send().await?;
    println!("{}", response.status());
    return match response.status().as_u16() {
        429u16 => {
            let l = response
                .headers()
                .get("X-Ratelimit-Limit")
                .unwrap()
                .to_str()
                .unwrap()
                .parse::<i32>()
                .unwrap();
            let u = response
                .headers()
                .get("X-Ratelimit-Left")
                .unwrap()
                .to_str()
                .unwrap()
                .parse::<i32>()
                .unwrap();
            Err(HttpError::RateLimited(l, u))
        }

        413u16 => Err(HttpError::FileTooLarge),
        404u16 => Err(HttpError::NotFound),
        422u16 => {
            let err: MissingParams = response.json::<MissingParams>().await?;
            Err(HttpError::ParameterError(err))
        }
        400 => {
            let err: MsgResp = response.json::<MsgResp>().await?;
            Err(HttpError::BadRequest(err.message))
        }

        c if c >= 500u16 => Err(HttpError::InternalServerError),
        200u16 => {
            let headers = response.headers();
            let size = response.content_length().unwrap();
            let process_time: f32 = headers
                .get("x-process-time")
                .unwrap()
                .to_str()
                .unwrap()
                .to_string()[..7]
                .parse()
                .unwrap();

            let format = match headers
                .get("Content-Type")
                .unwrap()
                .to_str()
                .unwrap()
                .to_string()
                .replace("image/", "")
                .as_str()
            {
                "png" => ImageType::Png,
                "gif" => ImageType::Gif,
                _ => ImageType::Unkown,
            };
            let bytes: Bytes = response.bytes().await?;
            Ok(Ok(ImageResponse {
                bytes,
                format,
                size,
                process_time,
            }))
        }
        _ => {
            let err = response.json::<MsgResp>().await?;
            Ok(Err(err.message))
        }
    };
}

/// Image Manipulation Functions for async client.
pub struct Image {
    http: Arc<Client>,
}

impl Image {
    pub fn new(http: Arc<Client>) -> Self {
        Image { http }
    }
    /// Sample Image Processing
    /// This example processes a URL and saves a format aware Image
    /// # Example
    /// ```rust
    /// use dagpirs::{Client, Bytes};
    /// // Only here the std fs is used, in prod for async use the tokio::fs;
    /// use std::fs;
    /// use std::io::Write;
    /// use tokio;
    /// #[tokio::main]
    /// async fn main() {
    ///     let token = std::env::var("DAGPI_TOKEN").unwrap();
    ///     let c = Client::new(&token).unwrap();
    ///     if let Ok(i) = c.image.image_process("https://dagpi.xyz/dagpi.png".to_string(), dagpirs::models::ImageManipulation::Wanted).await {
    ///         match i {
    ///             Ok(im) => {
    ///                 let buff: Bytes = im.bytes;
    ///                 let mut f = fs::File::create(format!("wanted.{}", im.format)).unwrap();
    ///                 f.write_all(buff.to_vec().as_slice()).unwrap();
    ///         },
    ///             Err(e) => panic!("{}", e)    
    ///         }
    ///     }
    ///}
    pub async fn image_process(
        &self,
        url: String,
        manipulation: ImageManipulation,
    ) -> HttpResult<ImageResponse, String> {
        let req = self
            .http
            .clone()
            .get(&image_endpoint(manipulation.to_string().to_lowercase()))
            .query(&[("url", &url)]);
        make_request_image(req).await
    }

    /// Process an image with text
    pub async fn image_process_text(
        &self,
        url: String,
        text: String,
        manipulation: ImageManipulationText,
    ) -> HttpResult<ImageResponse, String> {
        let req = self
            .http
            .clone()
            .get(&image_endpoint(manipulation.to_string().to_lowercase()))
            .query(&[("url", &url)])
            .query(&[("text", &text)]);
        make_request_image(req).await
    }

    /// Process and Image with both top and bottom text
    pub async fn image_process_top_bottom(
        &self,
        url: String,
        top_text: String,
        bottom_text: String,
        manipulation: ImageManipulationTopBottom,
    ) -> HttpResult<ImageResponse, String> {
        let req = self
            .http
            .clone()
            .get(&image_endpoint(manipulation.to_string().to_lowercase()))
            .query(&[("url", &url)])
            .query(&[("top_text", &top_text)])
            .query(&[("bottom_text", &bottom_text)]);
        make_request_image(req).await
    }

    /// Generate a realistic fake tweet
    pub async fn tweet(
        &self,
        url: String,
        username: String,
        text: String,
    ) -> HttpResult<ImageResponse, String> {
        let req = self
            .http
            .clone()
            .get(&image_endpoint("tweet".to_string()))
            .query(&[("url", &url)])
            .query(&[("username", username)])
            .query(&[("text", text)]);
        make_request_image(req).await
    }

    /// Generate a realistic fake youtube comment
    pub async fn yt(
        &self,
        url: String,
        username: String,
        text: String,
        dark: bool,
    ) -> HttpResult<ImageResponse, String> {
        let req = self
            .http
            .clone()
            .get(&image_endpoint("yt".to_string()))
            .query(&[("url", &url)])
            .query(&[("username", username)])
            .query(&[("text", text)])
            .query(&[("dark", dark)]);
        make_request_image(req).await
    }

    /// Generate a realistic fake discord message
    pub async fn discord_message(
        &self,
        url: String,
        username: String,
        text: String,
        dark: bool,
    ) -> HttpResult<ImageResponse, String> {
        let req = self
            .http
            .clone()
            .get(&image_endpoint("discord".to_string()))
            .query(&[("url", &url)])
            .query(&[("username", username)])
            .query(&[("text", text)])
            .query(&[("dark", dark)]);
        make_request_image(req).await
    }

    /// Put a pride flag overlay over an image from a selection of pride flags
    pub async fn pride(
        &self,
        url: String,
        flag: Pride,
    ) -> HttpResult<ImageResponse, String> {
        let req = self
            .http
            .clone()
            .get(&image_endpoint("pride".to_string()))
            .query(&[("url", &url)])
            .query(&[("flag", flag.to_string().to_lowercase())]);
        make_request_image(req).await
    }
}