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
//! 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,
})
}
}
}