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
use crate::{
  upload, download,
  UploadOptions,
  DownloadOptions, MetadataOptions, Metadata,
  SkynetResult,
  util::DEFAULT_PORTAL_URL,
};
use std::{collections::HashMap, path::Path};
use hyper::{client::HttpConnector, Client};
use hyper_tls::HttpsConnector;
use mime::Mime;

#[derive(Debug)]
pub struct SkynetClientOptions {
  pub api_key: Option<String>,
  pub custom_user_agent: Option<String>,
}

impl Default for SkynetClientOptions {
  fn default() -> Self {
    Self {
      api_key: None,
      custom_user_agent: None,
    }
  }
}

#[derive(Debug)]
pub struct SkynetClient {
  portal_url: String,
  options: SkynetClientOptions,
  pub http: Client<HttpsConnector<HttpConnector>>,
}

impl SkynetClient {
  pub fn new(portal_url: &str, opt: SkynetClientOptions) -> Self {
    let https = HttpsConnector::new();
    let http = Client::builder().build::<_, hyper::Body>(https);

    Self {
      portal_url: portal_url.to_string(),
      options: opt,
      http,
    }
  }

  pub fn get_portal_url(&self) -> &str {
    self.portal_url.as_str()
  }

  pub async fn upload_data(
    &self,
    data: HashMap<String, (Mime, Vec<u8>)>,
    opt: UploadOptions,
  ) -> SkynetResult<String> {
    upload::upload_data(self, data, opt).await
  }

  pub async fn upload_file<P: AsRef<Path>>(
    &self,
    path: P,
    opt: UploadOptions,
  ) -> SkynetResult<String> {
    upload::upload_file(self, path.as_ref(), opt).await
  }

  pub async fn upload_directory<P: AsRef<Path>>(
    &self,
    path: P,
    opt: UploadOptions,
  ) -> SkynetResult<String> {
    upload::upload_directory(self, path.as_ref(), opt).await
  }

  pub async fn download_data(
    &self,
    skylink: &str,
    opt: DownloadOptions,
  ) -> SkynetResult<Vec<u8>> {
    download::download_data(self, skylink, opt).await
  }

  pub async fn download_file<P: AsRef<Path>>(
    &self,
    path: P,
    skylink: &str,
    opt: DownloadOptions,
  ) -> SkynetResult<()> {
    download::download_file(self, path, skylink, opt).await
  }

  pub async fn get_metadata(
    &self,
    skylink: &str,
    opt: MetadataOptions,
  ) -> SkynetResult<Metadata> {
    download::get_metadata(self, skylink, opt).await
  }
}

impl Default for SkynetClient {
  fn default() -> Self {
    Self::new(DEFAULT_PORTAL_URL, SkynetClientOptions::default())
  }
}