cloudreve-api 0.8.4

A Rust library for interacting with Cloudreve API
Documentation
//! File-related API endpoints for Cloudreve API v3

use crate::Error;
use crate::api::v3::ApiV3Client;
use crate::api::v3::models::*;

impl ApiV3Client {
    /// Search for files by keyword, scoped to `path`.
    ///
    /// Pass "/" as `path` to search the entire drive. The response reuses the
    /// directory listing shape, so the matches arrive in `objects`.
    pub async fn search_files(&self, keyword: &str, path: &str) -> Result<DirectoryList, Error> {
        let scope = if path.is_empty() { "/" } else { path };
        let endpoint = format!(
            "/file/search/keywords/{}?path={}",
            urlencoding::encode(keyword),
            urlencoding::encode(scope)
        );
        let response: ApiResponse<DirectoryList> = self.get(&endpoint).await?;
        match response.data {
            Some(list) => Ok(list),
            None => Err(Error::Api {
                code: response.code,
                message: response.msg,
            }),
        }
    }

    pub async fn upload_file(
        &self,
        request: &UploadFileRequest<'_>,
    ) -> Result<UploadSession, Error> {
        let response: ApiResponse<UploadSession> = self.put("/file/upload", request).await?;
        match response.data {
            Some(session) => Ok(session),
            None => Err(Error::Api {
                code: response.code,
                message: response.msg,
            }),
        }
    }

    pub async fn complete_upload(&self, session_id: &str) -> Result<(), Error> {
        let response: ApiResponse<()> = self
            .post(
                &format!("/callback/onedrive/finish/{}", session_id),
                &serde_json::json!({}),
            )
            .await?;
        if response.code == 0 {
            Ok(())
        } else {
            Err(Error::Api {
                code: response.code,
                message: response.msg,
            })
        }
    }

    /// Upload one chunk of an open session (`POST /file/upload/{sessionId}/{index}`).
    ///
    /// The index has to reach the server: V3 derives the append offset from it
    /// (`AppendStart = chunkSize * index`) and rejects out-of-order chunks, so
    /// pinning the URL to chunk 0 made every multi-chunk upload either fail or
    /// overwrite the first chunk.
    ///
    /// V3 answers 200 even for failures and carries the real outcome in the
    /// body's `code`, so the status alone must not be read as success.
    pub async fn upload_chunk(
        &self,
        session_id: &str,
        chunk_index: u32,
        data: Vec<u8>,
    ) -> Result<(), Error> {
        let url = self.get_url(&format!("/file/upload/{}/{}", session_id, chunk_index));
        let mut request = self.http_client.post(&url).body(data);

        if let Some(cookie) = &self.session_cookie {
            request = request.header("Cookie", format!("cloudreve-session={}", cookie));
        }

        let response = request.send().await?;
        let status = response.status();
        let raw_text = response.text().await.unwrap_or_default();

        if let Ok(api_response) = serde_json::from_str::<ApiResponse<serde_json::Value>>(&raw_text)
        {
            return match api_response.code {
                0 => Ok(()),
                code => Err(Error::Api {
                    code,
                    message: api_response.msg,
                }),
            };
        }

        if status.is_success() {
            Ok(())
        } else {
            Err(Error::Api {
                code: status.as_u16() as i32,
                message: format!("Upload failed with status: {}", status),
            })
        }
    }

    /// 原地覆盖一个已存在文件的内容(`PUT /file/update/{id}`)。
    ///
    /// V3 的上传会话没有 overwrite 语义:同名文件已存在时,建会话会被
    /// GenericAfterUpload 挡回 40004 Object existed。网页端的文本编辑器保存走的
    /// 就是这个接口,服务端以 fsctx.Overwrite 模式写回原文件,id 和路径都不变。
    ///
    /// 服务端从 Content-Length 取长度,所以这里显式带上;响应仍是 HTTP 200 +
    /// body 里的 code。
    pub async fn update_file_content(&self, id: &str, content: Vec<u8>) -> Result<(), Error> {
        let url = self.get_url(&format!("/file/update/{}", urlencoding::encode(id)));
        let mut request = self
            .http_client
            .put(&url)
            .header("Content-Type", "application/octet-stream")
            .header("Content-Length", content.len().to_string())
            .body(content);

        if let Some(cookie) = &self.session_cookie {
            request = request.header("Cookie", format!("cloudreve-session={}", cookie));
        }

        let response = request.send().await?;
        let status = response.status();
        let raw_text = response.text().await.unwrap_or_default();

        if let Ok(api_response) = serde_json::from_str::<ApiResponse<serde_json::Value>>(&raw_text)
        {
            return match api_response.code {
                0 => Ok(()),
                code => Err(Error::Api {
                    code,
                    message: api_response.msg,
                }),
            };
        }

        Err(Error::Api {
            code: status.as_u16() as i32,
            message: raw_text.trim().to_string(),
        })
    }

    /// Delete one upload session by id (`DELETE /file/upload/{sessionId}`).
    ///
    /// Opening a session makes V3 insert a placeholder file row that keeps the
    /// name taken. If the upload never finishes, every later `upload_file` for
    /// the same path fails with 40054 "Upload session existed" until the
    /// server-side GC runs (`upload_session_timeout`, 24h by default). Deleting
    /// the session drops that placeholder and is the only way a client can clear
    /// the conflict itself.
    ///
    /// A session the server no longer knows returns `CodeUploadSessionExpired`;
    /// callers that are only cleaning up can treat that as already done.
    pub async fn delete_upload_session(&self, session_id: &str) -> Result<(), Error> {
        let response: ApiResponse<()> = self
            .delete(&format!("/file/upload/{}", urlencoding::encode(session_id)))
            .await?;
        match response.code {
            0 => Ok(()),
            code => Err(Error::Api {
                code,
                message: response.msg,
            }),
        }
    }

    /// Delete every upload placeholder the current user owns
    /// (`DELETE /file/upload`).
    ///
    /// This is the recovery path for orphan sessions whose ids the client lost
    /// (killed mid-upload, local store wiped, session created but the response
    /// never arrived). It is account-wide, so any upload still in flight loses
    /// its placeholder too — only call it when nothing else is uploading.
    pub async fn delete_all_upload_sessions(&self) -> Result<(), Error> {
        let response: ApiResponse<()> = self.delete("/file/upload").await?;
        match response.code {
            0 => Ok(()),
            code => Err(Error::Api {
                code,
                message: response.msg,
            }),
        }
    }

    pub async fn download_file(&self, id: &str) -> Result<DownloadUrl, Error> {
        // V3 returns ApiResponse with data as string (download URL path)
        let response: ApiResponse<String> = self
            .put(&format!("/file/download/{}", id), &serde_json::json!({}))
            .await?;
        match response.data {
            Some(url_path) => Ok(DownloadUrl { url: url_path }),
            None => Err(Error::Api {
                code: response.code,
                message: response.msg,
            }),
        }
    }

    pub async fn get_file_source(
        &self,
        request: &FileSourceRequest,
    ) -> Result<Vec<FileSource>, Error> {
        let response: ApiResponse<Vec<FileSource>> = self.post("/file/source", request).await?;
        match response.data {
            Some(sources) => Ok(sources),
            None => Err(Error::Api {
                code: response.code,
                message: response.msg,
            }),
        }
    }

    pub async fn preview_file(&self, id: &str) -> Result<DirectoryList, Error> {
        let response: ApiResponse<DirectoryList> =
            self.get(&format!("/file/preview/{}", id)).await?;
        match response.data {
            Some(list) => Ok(list),
            None => Err(Error::Api {
                code: response.code,
                message: response.msg,
            }),
        }
    }

    pub async fn get_thumbnail(&self, id: &str) -> Result<DirectoryList, Error> {
        let response: ApiResponse<DirectoryList> = self.get(&format!("/file/thumb/{}", id)).await?;
        match response.data {
            Some(list) => Ok(list),
            None => Err(Error::Api {
                code: response.code,
                message: response.msg,
            }),
        }
    }

    pub async fn create_file(&self, request: &CreateFileRequest<'_>) -> Result<(), Error> {
        let response: ApiResponse<()> = self.post("/file/create", request).await?;
        if response.code == 0 {
            Ok(())
        } else {
            Err(Error::Api {
                code: response.code,
                message: response.msg,
            })
        }
    }
}