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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use crate::api_core::access_management::{
    ApiVersion, ApiVersionResponse, GetServices, GetServicesResponse, SessionKey,
    SessionKeyResponse, VerifyAccessKey, VerifyAccessKeyResponse,
};
use crate::api_core::adding_files::{
    AddFile, AddFileRequest, AddFileResponse, ArchiveFiles, ArchiveFilesRequest, DeleteFiles,
    DeleteFilesRequest, UnarchiveFiles, UnarchiveFilesRequest, UndeleteFiles, UndeleteFilesRequest,
};
use crate::api_core::adding_tags::{AddTags, AddTagsRequest, CleanTags, CleanTagsResponse};
use crate::api_core::adding_urls::{
    AddUrl, AddUrlRequest, AddUrlResponse, AssociateUrl, AssociateUrlRequest, GetUrlFiles,
    GetUrlFilesResponse, GetUrlInfo, GetUrlInfoResponse,
};
use crate::api_core::common::{FileIdentifier, FileMetadataInfo, FileRecord, OptionalStringNumber};
use crate::api_core::managing_cookies_and_http_headers::{
    GetCookies, GetCookiesResponse, SetCookies, SetCookiesRequest, SetUserAgent,
    SetUserAgentRequest,
};
use crate::api_core::managing_pages::{
    AddFiles, AddFilesRequest, FocusPage, FocusPageRequest, GetPageInfo, GetPageInfoResponse,
    GetPages, GetPagesResponse,
};
use crate::api_core::searching_and_fetching_files::{
    FileMetadata, FileMetadataResponse, GetFile, SearchFiles, SearchFilesResponse,
};
use crate::api_core::Endpoint;
use crate::error::{Error, Result};
use crate::utils::{number_list_to_json_array, string_list_to_json_array};
use reqwest::Response;
use serde::de::DeserializeOwned;
use serde::Serialize;

static ACCESS_KEY_HEADER: &str = "Hydrus-Client-API-Access-Key";

#[derive(Clone)]
/// A low level Client for the hydrus API. It provides basic abstraction
/// over the REST api.
#[derive(Debug)]
pub struct Client {
    inner: reqwest::Client,
    base_url: String,
    access_key: String,
}

impl Client {
    /// Creates a new client to start requests against the hydrus api.
    pub fn new<S: AsRef<str>>(url: S, access_key: S) -> Self {
        Self {
            inner: reqwest::Client::new(),
            access_key: access_key.as_ref().to_string(),
            base_url: url.as_ref().to_string(),
        }
    }

    /// Starts a get request to the path
    async fn get<E: Endpoint, Q: Serialize + ?Sized>(&self, query: &Q) -> Result<Response> {
        log::debug!("GET request to {}", E::path());
        let response = self
            .inner
            .get(format!("{}/{}", self.base_url, E::path()))
            .header(ACCESS_KEY_HEADER, &self.access_key)
            .query(query)
            .send()
            .await?;

        Self::extract_error(response).await
    }

    /// Starts a get request to the path associated with the Endpoint Type
    async fn get_and_parse<E: Endpoint, Q: Serialize + ?Sized>(
        &self,
        query: &Q,
    ) -> Result<E::Response> {
        let response = self.get::<E, Q>(query).await?;

        Self::extract_content(response).await
    }

    /// Stats a post request to the path associated with the Endpoint Type
    async fn post<E: Endpoint>(&self, body: E::Request) -> Result<Response> {
        log::debug!("POST request to {}", E::path());
        let response = self
            .inner
            .post(format!("{}/{}", self.base_url, E::path()))
            .json(&body)
            .header(ACCESS_KEY_HEADER, &self.access_key)
            .send()
            .await?;
        let response = Self::extract_error(response).await?;
        Ok(response)
    }

    /// Stats a post request and parses the body as json
    async fn post_and_parse<E: Endpoint>(&self, body: E::Request) -> Result<E::Response> {
        let response = self.post::<E>(body).await?;

        Self::extract_content(response).await
    }

    /// Stats a post request to the path associated with the return type
    async fn post_binary<E: Endpoint>(&self, data: Vec<u8>) -> Result<E::Response> {
        log::debug!("Binary POST request to {}", E::path());
        let response = self
            .inner
            .post(format!("{}/{}", self.base_url, E::path()))
            .body(data)
            .header(ACCESS_KEY_HEADER, &self.access_key)
            .header("Content-Type", "application/octet-stream")
            .send()
            .await?;
        let response = Self::extract_error(response).await?;

        Self::extract_content(response).await
    }

    /// Returns an error with the response text content if the status doesn't indicate success
    async fn extract_error(response: Response) -> Result<Response> {
        if !response.status().is_success() {
            let msg = response.text().await?;
            log::error!("API returned error '{}'", msg);
            Err(Error::Hydrus(msg))
        } else {
            Ok(response)
        }
    }

    /// Parses the response as JSOn
    async fn extract_content<T: DeserializeOwned>(response: Response) -> Result<T> {
        response.json::<T>().await.map_err(Error::from)
    }

    /// Returns the current API version. It's being incremented every time the API changes.
    pub async fn api_version(&self) -> Result<ApiVersionResponse> {
        log::trace!("Getting api version");
        self.get_and_parse::<ApiVersion, ()>(&()).await
    }

    /// Creates a new session key
    pub async fn session_key(&self) -> Result<SessionKeyResponse> {
        log::trace!("Getting session key");
        self.get_and_parse::<SessionKey, ()>(&()).await
    }

    /// Verifies if the access key is valid and returns some information about its permissions
    pub async fn verify_access_key(&self) -> Result<VerifyAccessKeyResponse> {
        log::trace!("Verifying access key");
        self.get_and_parse::<VerifyAccessKey, ()>(&()).await
    }

    /// Returns the list of tag and file services of the client
    pub async fn get_services(&self) -> Result<GetServicesResponse> {
        log::trace!("Getting services");
        self.get_and_parse::<GetServices, ()>(&()).await
    }

    /// Adds a file to hydrus
    pub async fn add_file<S: ToString>(&self, path: S) -> Result<AddFileResponse> {
        let path = path.to_string();
        log::trace!("Adding file {}", path);
        self.post_and_parse::<AddFile>(AddFileRequest { path })
            .await
    }

    /// Adds a file from binary data to hydrus
    pub async fn add_binary_file(&self, data: Vec<u8>) -> Result<AddFileResponse> {
        log::trace!("Adding binary file");
        self.post_binary::<AddFile>(data).await
    }

    /// Moves files with matching hashes to the trash
    pub async fn delete_files(&self, hashes: Vec<String>) -> Result<()> {
        log::trace!("Deleting files {:?}", hashes);
        self.post::<DeleteFiles>(DeleteFilesRequest { hashes })
            .await?;

        Ok(())
    }

    /// Pulls files out of the trash by hash
    pub async fn undelete_files(&self, hashes: Vec<String>) -> Result<()> {
        log::trace!("Undeleting files {:?}", hashes);
        self.post::<UndeleteFiles>(UndeleteFilesRequest { hashes })
            .await?;

        Ok(())
    }

    /// Moves files from the inbox into the archive
    pub async fn archive_files(&self, hashes: Vec<String>) -> Result<()> {
        log::trace!("Archiving files {:?}", hashes);
        self.post::<ArchiveFiles>(ArchiveFilesRequest { hashes })
            .await?;

        Ok(())
    }

    /// Moves files from the archive into the inbox
    pub async fn unarchive_files(&self, hashes: Vec<String>) -> Result<()> {
        log::trace!("Unarchiving files {:?}", hashes);
        self.post::<UnarchiveFiles>(UnarchiveFilesRequest { hashes })
            .await?;

        Ok(())
    }

    /// Returns the list of tags as the client would see them in a human friendly order
    pub async fn clean_tags(&self, tags: Vec<String>) -> Result<CleanTagsResponse> {
        log::trace!("Cleaning tags {:?}", tags);
        self.get_and_parse::<CleanTags, [(&str, String)]>(&[(
            "tags",
            string_list_to_json_array(tags),
        )])
        .await
    }

    /// Adds tags to files with the given hashes
    pub async fn add_tags(&self, request: AddTagsRequest) -> Result<()> {
        log::trace!("Adding tags {:?}", request);
        self.post::<AddTags>(request).await?;

        Ok(())
    }

    /// Searches for files in the inbox, the archive or both
    pub async fn search_files(&self, tags: Vec<String>) -> Result<SearchFilesResponse> {
        log::trace!("Searching for files with tags {:?}", tags);
        self.get_and_parse::<SearchFiles, [(&str, String)]>(&[(
            "tags",
            string_list_to_json_array(tags),
        )])
        .await
    }

    /// Returns the metadata for a given list of file_ids or hashes
    pub async fn get_file_metadata(
        &self,
        file_ids: Vec<u64>,
        hashes: Vec<String>,
    ) -> Result<FileMetadataResponse> {
        log::trace!(
            "Getting file info for ids {:?} or hashes {:?}",
            file_ids,
            hashes
        );
        let query = if file_ids.len() > 0 {
            ("file_ids", number_list_to_json_array(file_ids))
        } else {
            ("hashes", string_list_to_json_array(hashes))
        };
        self.get_and_parse::<FileMetadata, [(&str, String)]>(&[query])
            .await
    }

    /// Returns the metadata for a single file identifier
    pub async fn get_file_metadata_by_identifier(
        &self,
        id: FileIdentifier,
    ) -> Result<FileMetadataInfo> {
        log::trace!("Getting file metadata {:?}", id);
        let mut response = match id.clone() {
            FileIdentifier::ID(id) => self.get_file_metadata(vec![id], vec![]).await?,
            FileIdentifier::Hash(hash) => self.get_file_metadata(vec![], vec![hash]).await?,
        };

        response
            .metadata
            .pop()
            .ok_or_else(|| Error::FileNotFound(id))
    }

    /// Returns the bytes of a file from hydrus
    pub async fn get_file(&self, id: FileIdentifier) -> Result<FileRecord> {
        log::trace!("Getting file {:?}", id);
        let response = match id {
            FileIdentifier::ID(id) => {
                self.get::<GetFile, [(&str, u64)]>(&[("file_id", id)])
                    .await?
            }
            FileIdentifier::Hash(hash) => {
                self.get::<GetFile, [(&str, String)]>(&[("hash", hash)])
                    .await?
            }
        };
        let mime_type = response
            .headers()
            .get("mime-type")
            .cloned()
            .map(|h| h.to_str().unwrap().to_string())
            .unwrap_or("image/jpeg".into());

        let bytes = response.bytes().await?.to_vec();

        Ok(FileRecord { bytes, mime_type })
    }

    /// Returns all files associated with the given url
    pub async fn get_url_files<S: AsRef<str>>(&self, url: S) -> Result<GetUrlFilesResponse> {
        log::trace!("Getting files for url {}", url.as_ref());
        self.get_and_parse::<GetUrlFiles, [(&str, &str)]>(&[("url", url.as_ref())])
            .await
    }

    /// Returns information about the given url
    pub async fn get_url_info<S: AsRef<str>>(&self, url: S) -> Result<GetUrlInfoResponse> {
        log::trace!("Getting info for url {}", url.as_ref());
        self.get_and_parse::<GetUrlInfo, [(&str, &str)]>(&[("url", url.as_ref())])
            .await
    }

    /// Adds an url to hydrus, optionally with additional tags and a destination page
    pub async fn add_url(&self, request: AddUrlRequest) -> Result<AddUrlResponse> {
        log::trace!("Adding url {:?}", request);
        self.post_and_parse::<AddUrl>(request).await
    }

    /// Associates urls with the given file hashes
    pub async fn associate_urls(&self, urls: Vec<String>, hashes: Vec<String>) -> Result<()> {
        log::trace!("Associating urls {:?} with hashes {:?}", urls, hashes);
        self.post::<AssociateUrl>(AssociateUrlRequest {
            hashes,
            urls_to_add: urls,
            urls_to_delete: vec![],
        })
        .await?;

        Ok(())
    }

    /// Disassociates urls with the given file hashes
    pub async fn disassociate_urls(&self, urls: Vec<String>, hashes: Vec<String>) -> Result<()> {
        log::trace!("Disassociating urls {:?} with hashes {:?}", urls, hashes);
        self.post::<AssociateUrl>(AssociateUrlRequest {
            hashes,
            urls_to_add: vec![],
            urls_to_delete: urls,
        })
        .await?;

        Ok(())
    }

    /// Returns all pages of the client
    pub async fn get_pages(&self) -> Result<GetPagesResponse> {
        log::trace!("Getting pages");
        self.get_and_parse::<GetPages, ()>(&()).await
    }

    /// Returns information about a single page
    pub async fn get_page_info<S: AsRef<str>>(&self, page_key: S) -> Result<GetPageInfoResponse> {
        log::trace!("Getting information for page {}", page_key.as_ref());
        self.get_and_parse::<GetPageInfo, [(&str, &str)]>(&[("page_key", page_key.as_ref())])
            .await
    }

    /// Focuses a page in the client
    pub async fn focus_page<S: ToString>(&self, page_key: S) -> Result<()> {
        let page_key = page_key.to_string();
        log::trace!("Focussing page {}", page_key);
        self.post::<FocusPage>(FocusPageRequest { page_key })
            .await?;

        Ok(())
    }

    /// Adds files to a page
    pub async fn add_files_to_page<S: ToString>(
        &self,
        page_key: S,
        file_ids: Vec<u64>,
        hashes: Vec<String>,
    ) -> Result<()> {
        let page_key = page_key.to_string();
        log::trace!(
            "Adding files with ids {:?} or hashes {:?} to page {}",
            file_ids,
            hashes,
            page_key
        );
        self.post::<AddFiles>(AddFilesRequest {
            page_key,
            file_ids,
            hashes,
        })
        .await?;

        Ok(())
    }

    /// Returns all cookies for the given domain
    pub async fn get_cookies<S: AsRef<str>>(&self, domain: S) -> Result<GetCookiesResponse> {
        log::trace!("Getting cookies");
        self.get_and_parse::<GetCookies, [(&str, &str)]>(&[("domain", domain.as_ref())])
            .await
    }

    /// Sets some cookies for some websites.
    /// Each entry needs to be in the format `[<name>, <value>, <domain>, <path>, <expires>]`
    /// with the types `[String, String, String, String, u64]`
    pub async fn set_cookies(&self, cookies: Vec<[OptionalStringNumber; 5]>) -> Result<()> {
        log::trace!("Setting cookies {:?}", cookies);
        self.post::<SetCookies>(SetCookiesRequest { cookies })
            .await?;

        Ok(())
    }

    /// Sets the user agent that is being used for every request hydrus starts
    pub async fn set_user_agent<S: ToString>(&self, user_agent: S) -> Result<()> {
        let user_agent = user_agent.to_string();
        log::trace!("Setting user agent to {}", user_agent);
        self.post::<SetUserAgent>(SetUserAgentRequest { user_agent })
            .await?;

        Ok(())
    }
}