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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use std::fmt::Debug;
use std::fmt::Formatter;
use std::sync::Arc;

use bytes::Buf;
use bytes::Bytes;
use http::header;
use http::Request;
use http::Response;
use http::StatusCode;
use serde::Deserialize;
use tokio::sync::RwLock;

use super::error::parse_error;
use crate::raw::*;
use crate::*;

/// Core of [seafile](https://www.seafile.com) services support.
#[derive(Clone)]
pub struct SeafileCore {
    /// The root of this core.
    pub root: String,
    /// The endpoint of this backend.
    pub endpoint: String,
    /// The username of this backend.
    pub username: String,
    /// The password id of this backend.
    pub password: String,
    /// The repo name of this backend.
    pub repo_name: String,

    /// signer of this backend.
    pub signer: Arc<RwLock<SeafileSigner>>,

    pub client: HttpClient,
}

impl Debug for SeafileCore {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Backend")
            .field("root", &self.root)
            .field("endpoint", &self.endpoint)
            .field("username", &self.username)
            .field("repo_name", &self.repo_name)
            .finish_non_exhaustive()
    }
}

impl SeafileCore {
    #[inline]
    pub async fn send(&self, req: Request<Buffer>) -> Result<Response<Buffer>> {
        self.client.send(req).await
    }

    /// get auth info
    pub async fn get_auth_info(&self) -> Result<AuthInfo> {
        {
            let signer = self.signer.read().await;

            if !signer.auth_info.token.is_empty() {
                let auth_info = signer.auth_info.clone();
                return Ok(auth_info.clone());
            }
        }

        {
            let mut signer = self.signer.write().await;
            let body = format!(
                "username={}&password={}",
                percent_encode_path(&self.username),
                percent_encode_path(&self.password)
            );
            let req = Request::post(format!("{}/api2/auth-token/", self.endpoint))
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                .body(Buffer::from(Bytes::from(body)))
                .map_err(new_request_build_error)?;

            let resp = self.client.send(req).await?;
            let status = resp.status();

            match status {
                StatusCode::OK => {
                    let resp_body = resp.into_body();
                    let auth_response: AuthTokenResponse =
                        serde_json::from_reader(resp_body.reader())
                            .map_err(new_json_deserialize_error)?;
                    signer.auth_info = AuthInfo {
                        token: auth_response.token,
                        repo_id: "".to_string(),
                    };
                }
                _ => {
                    return Err(parse_error(resp));
                }
            }

            let url = format!("{}/api2/repos", self.endpoint);

            let req = Request::get(url)
                .header(
                    header::AUTHORIZATION,
                    format!("Token {}", signer.auth_info.token),
                )
                .body(Buffer::new())
                .map_err(new_request_build_error)?;

            let resp = self.client.send(req).await?;

            let status = resp.status();

            match status {
                StatusCode::OK => {
                    let resp_body = resp.into_body();
                    let list_library_response: Vec<ListLibraryResponse> =
                        serde_json::from_reader(resp_body.reader())
                            .map_err(new_json_deserialize_error)?;

                    for library in list_library_response {
                        if library.name == self.repo_name {
                            signer.auth_info.repo_id = library.id;
                            break;
                        }
                    }

                    // repo not found
                    if signer.auth_info.repo_id.is_empty() {
                        return Err(Error::new(
                            ErrorKind::NotFound,
                            format!("repo {} not found", self.repo_name),
                        ));
                    }
                }
                _ => {
                    return Err(parse_error(resp));
                }
            }
            Ok(signer.auth_info.clone())
        }
    }
}

impl SeafileCore {
    /// get upload url
    pub async fn get_upload_url(&self) -> Result<String> {
        let auth_info = self.get_auth_info().await?;

        let req = Request::get(format!(
            "{}/api2/repos/{}/upload-link/",
            self.endpoint, auth_info.repo_id
        ));

        let req = req
            .header(header::AUTHORIZATION, format!("Token {}", auth_info.token))
            .body(Buffer::new())
            .map_err(new_request_build_error)?;

        let resp = self.send(req).await?;
        let status = resp.status();

        match status {
            StatusCode::OK => {
                let resp_body = resp.into_body();
                let upload_url = serde_json::from_reader(resp_body.reader())
                    .map_err(new_json_deserialize_error)?;
                Ok(upload_url)
            }
            _ => Err(parse_error(resp)),
        }
    }

    /// get download
    pub async fn get_download_url(&self, path: &str) -> Result<String> {
        let path = build_abs_path(&self.root, path);
        let path = percent_encode_path(&path);

        let auth_info = self.get_auth_info().await?;

        let req = Request::get(format!(
            "{}/api2/repos/{}/file/?p={}",
            self.endpoint, auth_info.repo_id, path
        ));

        let req = req
            .header(header::AUTHORIZATION, format!("Token {}", auth_info.token))
            .body(Buffer::new())
            .map_err(new_request_build_error)?;

        let resp = self.send(req).await?;
        let status = resp.status();

        match status {
            StatusCode::OK => {
                let resp_body = resp.into_body();
                let download_url = serde_json::from_reader(resp_body.reader())
                    .map_err(new_json_deserialize_error)?;

                Ok(download_url)
            }
            _ => Err(parse_error(resp)),
        }
    }

    /// download file
    pub async fn download_file(&self, path: &str, range: BytesRange) -> Result<Response<HttpBody>> {
        let download_url = self.get_download_url(path).await?;

        let req = Request::get(download_url);

        let req = req
            .header(header::RANGE, range.to_header())
            .body(Buffer::new())
            .map_err(new_request_build_error)?;

        self.client.fetch(req).await
    }

    /// file detail
    pub async fn file_detail(&self, path: &str) -> Result<FileDetail> {
        let path = build_abs_path(&self.root, path);
        let path = percent_encode_path(&path);

        let auth_info = self.get_auth_info().await?;

        let req = Request::get(format!(
            "{}/api2/repos/{}/file/detail/?p={}",
            self.endpoint, auth_info.repo_id, path
        ));

        let req = req
            .header(header::AUTHORIZATION, format!("Token {}", auth_info.token))
            .body(Buffer::new())
            .map_err(new_request_build_error)?;

        let resp = self.send(req).await?;
        let status = resp.status();

        match status {
            StatusCode::OK => {
                let resp_body = resp.into_body();
                let file_detail: FileDetail = serde_json::from_reader(resp_body.reader())
                    .map_err(new_json_deserialize_error)?;
                Ok(file_detail)
            }
            _ => Err(parse_error(resp)),
        }
    }

    /// dir detail
    pub async fn dir_detail(&self, path: &str) -> Result<DirDetail> {
        let path = build_abs_path(&self.root, path);
        let path = percent_encode_path(&path);

        let auth_info = self.get_auth_info().await?;

        let req = Request::get(format!(
            "{}/api/v2.1/repos/{}/dir/detail/?path={}",
            self.endpoint, auth_info.repo_id, path
        ));

        let req = req
            .header(header::AUTHORIZATION, format!("Token {}", auth_info.token))
            .body(Buffer::new())
            .map_err(new_request_build_error)?;

        let resp = self.send(req).await?;
        let status = resp.status();

        match status {
            StatusCode::OK => {
                let resp_body = resp.into_body();
                let dir_detail: DirDetail = serde_json::from_reader(resp_body.reader())
                    .map_err(new_json_deserialize_error)?;
                Ok(dir_detail)
            }
            _ => Err(parse_error(resp)),
        }
    }

    /// delete file or dir
    pub async fn delete(&self, path: &str) -> Result<()> {
        let path = build_abs_path(&self.root, path);
        let path = percent_encode_path(&path);

        let auth_info = self.get_auth_info().await?;

        let url = if path.ends_with('/') {
            format!(
                "{}/api2/repos/{}/dir/?p={}",
                self.endpoint, auth_info.repo_id, path
            )
        } else {
            format!(
                "{}/api2/repos/{}/file/?p={}",
                self.endpoint, auth_info.repo_id, path
            )
        };

        let req = Request::delete(url);

        let req = req
            .header(header::AUTHORIZATION, format!("Token {}", auth_info.token))
            .body(Buffer::new())
            .map_err(new_request_build_error)?;

        let resp = self.send(req).await?;

        let status = resp.status();

        match status {
            StatusCode::OK => Ok(()),
            _ => Err(parse_error(resp)),
        }
    }
}

#[derive(Deserialize)]
pub struct AuthTokenResponse {
    pub token: String,
}

#[derive(Deserialize)]
pub struct FileDetail {
    pub last_modified: String,
    pub size: u64,
}

#[derive(Debug, Deserialize)]
pub struct DirDetail {
    mtime: String,
}

pub fn parse_dir_detail(dir_detail: DirDetail) -> Result<Metadata> {
    let mut md = Metadata::new(EntryMode::DIR);

    md.set_last_modified(parse_datetime_from_rfc3339(&dir_detail.mtime)?);

    Ok(md)
}

pub fn parse_file_detail(file_detail: FileDetail) -> Result<Metadata> {
    let mut md = Metadata::new(EntryMode::FILE);

    md.set_content_length(file_detail.size);
    md.set_last_modified(parse_datetime_from_rfc3339(&file_detail.last_modified)?);

    Ok(md)
}

#[derive(Clone, Default)]
pub struct SeafileSigner {
    pub auth_info: AuthInfo,
}

#[derive(Clone, Default)]
pub struct AuthInfo {
    /// The repo id of this auth info.
    pub repo_id: String,
    /// The token of this auth info,
    pub token: String,
}

#[derive(Deserialize)]
pub struct ListLibraryResponse {
    pub name: String,
    pub id: String,
}