use crate::utils::encode_path;
use crate::{FileUploadPartEntity, FilesClient, Result};
use serde_json::json;
#[derive(Debug, Clone)]
pub struct FileActionHandler {
client: FilesClient,
}
impl FileActionHandler {
pub fn new(client: FilesClient) -> Self {
Self { client }
}
pub async fn begin_upload(
&self,
path: &str,
size: Option<i64>,
mkdir_parents: bool,
) -> Result<Vec<FileUploadPartEntity>> {
let mut body = json!({
"mkdir_parents": mkdir_parents,
});
if let Some(size) = size {
body["size"] = json!(size);
}
let encoded_path = encode_path(path);
let endpoint = format!("/file_actions/begin_upload{}", encoded_path);
let response = self.client.post_raw(&endpoint, body).await?;
if response.is_array() {
Ok(serde_json::from_value(response)?)
} else {
Ok(vec![serde_json::from_value(response)?])
}
}
pub async fn begin_multipart_upload(
&self,
path: &str,
size: i64,
parts: i32,
mkdir_parents: bool,
) -> Result<Vec<FileUploadPartEntity>> {
let body = json!({
"size": size,
"parts": parts,
"mkdir_parents": mkdir_parents,
});
let encoded_path = encode_path(path);
let endpoint = format!("/file_actions/begin_upload{}", encoded_path);
let response = self.client.post_raw(&endpoint, body).await?;
if response.is_array() {
Ok(serde_json::from_value(response)?)
} else {
Ok(vec![serde_json::from_value(response)?])
}
}
pub async fn copy_file(&self, path: &str, destination: &str) -> Result<()> {
let body = json!({
"destination": destination,
});
let encoded_path = encode_path(path);
let endpoint = format!("/file_actions/copy{}", encoded_path);
self.client.post_raw(&endpoint, body).await?;
Ok(())
}
pub async fn move_file(&self, path: &str, destination: &str) -> Result<()> {
let body = json!({
"destination": destination,
});
let encoded_path = encode_path(path);
let endpoint = format!("/file_actions/move{}", encoded_path);
self.client.post_raw(&endpoint, body).await?;
Ok(())
}
pub async fn get_metadata(&self, path: &str) -> Result<crate::FileEntity> {
let encoded_path = encode_path(path);
let endpoint = format!("/file_actions/metadata{}", encoded_path);
let response = self.client.post_raw(&endpoint, json!({})).await?;
Ok(serde_json::from_value(response)?)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_handler_creation() {
let client = FilesClient::builder().api_key("test-key").build().unwrap();
let _handler = FileActionHandler::new(client);
}
}