jmserver/src/ipfs/mod.rs

85 lines
1.9 KiB
Rust
Raw Normal View History

2022-01-05 23:46:19 +01:00
use std::time::Duration;
use axum::body::Bytes;
2022-01-05 23:46:19 +01:00
use reqwest::{
multipart::{Form, Part},
2022-01-16 22:43:45 +01:00
Response,
2022-01-05 23:46:19 +01:00
};
2021-12-18 20:04:34 +01:00
use serde::{Deserialize, Serialize};
2022-01-17 21:58:33 +01:00
use crate::{error::ServiceError, JMServiceInner};
2022-01-05 23:46:19 +01:00
2021-12-18 20:04:34 +01:00
#[derive(Deserialize)]
2022-01-05 23:46:19 +01:00
pub struct IPFSFile {
2021-12-18 20:04:34 +01:00
#[serde(rename = "Hash")]
pub hash: String,
#[serde(rename = "Name")]
pub name: String,
#[serde(rename = "Size")]
pub size: String,
}
#[derive(Serialize)]
pub struct CatQuery {
pub arg: String,
}
2022-01-05 23:46:19 +01:00
#[derive(Serialize)]
pub struct AddQuery {
pub pin: bool,
}
#[derive(Serialize)]
pub struct PinQuery {
pub arg: String,
}
2022-01-16 22:43:45 +01:00
impl JMServiceInner {
2022-07-19 21:11:13 +02:00
pub async fn ipfs_cat(&self, cid: String) -> Result<Response, ServiceError> {
2022-01-05 23:46:19 +01:00
let request = self
.client
2022-01-16 22:43:45 +01:00
.post(self.ipfs_url.join("/api/v0/cat")?)
2022-01-05 23:46:19 +01:00
.query(&CatQuery::new(cid));
Ok(request.send().await?)
2021-12-18 20:04:34 +01:00
}
2022-07-19 21:11:13 +02:00
pub async fn ipfs_add(&self, file: Bytes, filename: String) -> Result<IPFSFile, ServiceError> {
2022-01-05 23:46:19 +01:00
let request = self
.client
2022-01-16 22:43:45 +01:00
.post(self.ipfs_url.join("/api/v0/add")?)
2022-01-05 23:46:19 +01:00
.query(&AddQuery::new(false))
.multipart(Form::new().part("file", Part::stream(file).file_name(filename)));
let response = request.send().await?;
let res: IPFSFile = response.json().await?;
Ok(res)
2021-12-18 20:04:34 +01:00
}
2022-07-19 21:11:13 +02:00
pub async fn ipfs_pin(&self, cid: String) -> Result<(), ServiceError> {
2022-01-05 23:46:19 +01:00
let request = self
.client
2022-01-16 22:43:45 +01:00
.post(self.ipfs_url.join("/api/v0/pin/add")?)
2022-01-05 23:46:19 +01:00
.query(&PinQuery::new(cid))
.timeout(Duration::from_secs(60));
request.send().await?;
2022-01-05 23:46:19 +01:00
Ok(())
2021-12-18 20:04:34 +01:00
}
}
impl CatQuery {
pub fn new(cid: String) -> Self {
2022-01-05 23:46:19 +01:00
Self { arg: cid }
2021-12-18 20:04:34 +01:00
}
2022-01-05 23:46:19 +01:00
}
2021-12-18 20:04:34 +01:00
2022-01-05 23:46:19 +01:00
impl AddQuery {
pub fn new(pin: bool) -> Self {
Self { pin }
}
2021-12-18 20:04:34 +01:00
}
2022-01-05 23:46:19 +01:00
impl PinQuery {
pub fn new(cid: String) -> Self {
Self { arg: cid }
}
}