cyberdrop-client 0.4.6

Rust API client for Cyberdrop, with async support and typed models. Also works for bunkr.cr
Documentation
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
use std::collections::HashMap;

use reqwest::Url;
use serde::{Deserialize, Serialize};
use serde::de::{self, Visitor};
use std::fmt;

use crate::CyberdropError;

/// Authentication token returned by [`crate::CyberdropClient::login`] and
/// [`crate::CyberdropClient::register`].
///
/// This type is `#[serde(transparent)]` and typically deserializes from a JSON string.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(transparent)]
pub struct AuthToken {
    pub(crate) token: String,
}

impl AuthToken {
    /// Construct a new token wrapper.
    pub fn new(token: impl Into<String>) -> Self {
        Self {
            token: token.into(),
        }
    }

    /// Borrow the underlying token string.
    pub fn as_str(&self) -> &str {
        &self.token
    }

    /// Consume this value and return the underlying token string.
    pub fn into_string(self) -> String {
        self.token
    }
}

/// Permission flags associated with a user/token verification response.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct Permissions {
    /// Whether the account has "user" privileges.
    pub user: bool,
    /// Whether the account has "poweruser" privileges.
    pub poweruser: bool,
    /// Whether the account has "moderator" privileges.
    pub moderator: bool,
    /// Whether the account has "admin" privileges.
    pub admin: bool,
    /// Whether the account has "superadmin" privileges.
    pub superadmin: bool,
}

/// Result of verifying a token via [`crate::CyberdropClient::verify_token`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TokenVerification {
    /// Whether the token verification succeeded.
    pub success: bool,
    /// Username associated with the token.
    pub username: String,
    /// Permission flags associated with the token.
    pub permissions: Permissions,
}

/// Album metadata as returned by the Cyberdrop API.
///
/// Field semantics (timestamps/flags) are intentionally documented minimally: values are exposed
/// as returned by the service without additional interpretation.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Album {
    /// Album numeric ID.
    pub id: u64,
    /// Display name.
    pub name: String,
    /// Service-provided timestamp value.
    #[serde(default)]
    pub timestamp: u64,
    /// Service-provided identifier string.
    pub identifier: String,
    /// Service-provided "edited at" timestamp value.
    #[serde(default)]
    pub edited_at: u64,
    /// Service-provided download flag.
    #[serde(default)]
    pub download: bool,
    /// Service-provided public flag.
    #[serde(default)]
    pub public: bool,
    /// Album description (may be empty).
    #[serde(default)]
    pub description: String,
    /// Number of files in the album.
    #[serde(default)]
    pub files: u64,
}

/// Album listing for the authenticated user.
///
/// Values produced by this crate always have `success == true`; failures are returned as
/// [`CyberdropError`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AlbumsList {
    /// Whether the API request was successful.
    pub success: bool,
    /// Albums returned by the service.
    pub albums: Vec<Album>,
    /// Optional home domain returned by the service, parsed as a URL.
    pub home_domain: Option<Url>,
}

/// File metadata as returned by the album listing endpoint.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct AlbumFile {
    pub id: u64,
    pub name: String,
    #[serde(rename = "userid", deserialize_with = "de_string_or_number")]
    pub user_id: String,
    #[serde(deserialize_with = "de_u64_or_string")]
    pub size: u64,
    pub timestamp: u64,
    #[serde(rename = "last_visited_at")]
    pub last_visited_at: Option<String>,
    pub slug: String,
    /// Base domain for file media (for example, `https://sun-i.cyberdrop.cr`).
    pub image: String,
    /// Nullable expiry date as returned by the service.
    pub expirydate: Option<String>,
    #[serde(rename = "albumid", deserialize_with = "de_string_or_number")]
    pub album_id: String,
    pub extname: String,
    /// Thumbnail path relative to `image` (for example, `thumbs/<...>.png`).
    pub thumb: String,
}

fn de_string_or_number<'de, D>(deserializer: D) -> Result<String, D::Error>
where
    D: serde::Deserializer<'de>,
{
    struct StringOrNumber;

    impl<'de> Visitor<'de> for StringOrNumber {
        type Value = String;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a string or number")
        }

        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(v.to_string())
        }

        fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(v)
        }

        fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(v.to_string())
        }

        fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(v.to_string())
        }
    }

    deserializer.deserialize_any(StringOrNumber)
}

fn de_u64_or_string<'de, D>(deserializer: D) -> Result<u64, D::Error>
where
    D: serde::Deserializer<'de>,
{
    struct U64OrString;

    impl<'de> Visitor<'de> for U64OrString {
        type Value = u64;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a u64 or numeric string")
        }

        fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(v)
        }

        fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            if v < 0 {
                return Err(E::custom("negative value not allowed"));
            }
            Ok(v as u64)
        }

        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            v.parse::<u64>().map_err(E::custom)
        }

        fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            v.parse::<u64>().map_err(E::custom)
        }
    }

    deserializer.deserialize_any(U64OrString)
}

/// Page of files returned by the album listing endpoint.
///
/// This type represents a single response page; the API currently returns at most 25 files per
/// request and provides a total `count` for pagination.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AlbumFilesPage {
    /// Whether the API request was successful.
    pub success: bool,
    /// Files returned for the requested page.
    pub files: Vec<AlbumFile>,
    /// Total number of files in the album (across all pages).
    pub count: u64,
    /// Album mapping returned by the service (keyed by album id as a string).
    pub albums: HashMap<String, String>,
    /// Base domain returned by the service (parsed as a URL).
    ///
    /// Note: the API omits this field for empty albums, so it can be `None`.
    pub base_domain: Option<Url>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateAlbumRequest {
    pub name: String,
    pub description: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct CreateAlbumResponse {
    pub success: Option<bool>,
    pub id: Option<u64>,
    pub message: Option<String>,
    pub description: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct UploadResponse {
    pub success: Option<bool>,
    pub description: Option<String>,
    pub files: Option<Vec<UploadedFile>>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct EditAlbumRequest {
    pub(crate) id: u64,
    pub(crate) name: String,
    pub(crate) description: String,
    pub(crate) download: bool,
    pub(crate) public: bool,
    #[serde(rename = "requestLink")]
    pub(crate) request_link: bool,
}

#[derive(Debug, Deserialize)]
pub(crate) struct EditAlbumResponse {
    pub(crate) success: Option<bool>,
    pub(crate) name: Option<String>,
    pub(crate) identifier: Option<String>,
    pub(crate) message: Option<String>,
    pub(crate) description: Option<String>,
}

/// Result of editing an album via [`crate::CyberdropClient::edit_album`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EditAlbumResult {
    /// Updated name if the API returned it.
    pub name: Option<String>,
    /// New identifier if `request_new_link` was set and the API returned it.
    pub identifier: Option<String>,
}

/// Uploaded file metadata returned by [`crate::CyberdropClient::upload_file`].
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct UploadedFile {
    /// Name of the uploaded file.
    pub name: String,
    /// URL of the uploaded file (stringified URL).
    pub url: String,
}

/// Upload progress information emitted during file uploads.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UploadProgress {
    pub file_name: String,
    pub bytes_sent: u64,
    pub total_bytes: u64,
}

#[derive(Debug, Serialize)]
pub(crate) struct LoginRequest {
    pub(crate) username: String,
    pub(crate) password: String,
}

#[derive(Debug, Deserialize)]
pub(crate) struct LoginResponse {
    pub(crate) token: Option<AuthToken>,
}

#[derive(Debug, Serialize)]
pub(crate) struct RegisterRequest {
    pub(crate) username: String,
    pub(crate) password: String,
}

#[derive(Debug, Deserialize)]
pub(crate) struct RegisterResponse {
    pub(crate) success: Option<bool>,
    pub(crate) token: Option<AuthToken>,
    pub(crate) message: Option<String>,
    pub(crate) description: Option<String>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct NodeResponse {
    pub(crate) success: Option<bool>,
    pub(crate) url: Option<String>,
    pub(crate) message: Option<String>,
    pub(crate) description: Option<String>,
}

#[derive(Debug, Serialize)]
pub(crate) struct VerifyTokenRequest {
    pub(crate) token: String,
}

#[derive(Debug, Deserialize)]
pub(crate) struct VerifyTokenResponse {
    pub(crate) success: Option<bool>,
    pub(crate) username: Option<String>,
    pub(crate) permissions: Option<Permissions>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct AlbumsResponse {
    pub(crate) success: Option<bool>,
    pub(crate) albums: Option<Vec<Album>>,
    pub(crate) home_domain: Option<String>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct AlbumFilesResponse {
    pub(crate) success: Option<bool>,
    pub(crate) files: Option<Vec<AlbumFile>>,
    pub(crate) count: Option<u64>,
    pub(crate) albums: Option<HashMap<String, String>>,
    pub(crate) basedomain: Option<String>,
    pub(crate) message: Option<String>,
    pub(crate) description: Option<String>,
}

impl TryFrom<LoginResponse> for AuthToken {
    type Error = CyberdropError;

    fn try_from(response: LoginResponse) -> Result<Self, Self::Error> {
        response.token.ok_or(CyberdropError::MissingToken)
    }
}

impl TryFrom<RegisterResponse> for AuthToken {
    type Error = CyberdropError;

    fn try_from(body: RegisterResponse) -> Result<Self, Self::Error> {
        if body.success.unwrap_or(false) {
            return body.token.ok_or(CyberdropError::MissingToken);
        }

        let msg = body
            .description
            .or(body.message)
            .unwrap_or_else(|| "registration failed".to_string());

        Err(CyberdropError::Api(msg))
    }
}

impl TryFrom<VerifyTokenResponse> for TokenVerification {
    type Error = CyberdropError;

    fn try_from(body: VerifyTokenResponse) -> Result<Self, Self::Error> {
        let success = body.success.ok_or(CyberdropError::MissingField(
            "verification response missing success",
        ))?;
        let username = body.username.ok_or(CyberdropError::MissingField(
            "verification response missing username",
        ))?;
        let permissions = body.permissions.ok_or(CyberdropError::MissingField(
            "verification response missing permissions",
        ))?;

        Ok(TokenVerification {
            success,
            username,
            permissions,
        })
    }
}

impl TryFrom<AlbumsResponse> for AlbumsList {
    type Error = CyberdropError;

    fn try_from(body: AlbumsResponse) -> Result<Self, Self::Error> {
        if !body.success.unwrap_or(false) {
            return Err(CyberdropError::Api("failed to fetch albums".into()));
        }

        let albums = body.albums.ok_or(CyberdropError::MissingField(
            "albums response missing albums",
        ))?;

        let home_domain = match body.home_domain {
            Some(url) => Some(Url::parse(&url)?),
            None => None,
        };

        Ok(AlbumsList {
            success: true,
            albums,
            home_domain,
        })
    }
}

impl TryFrom<AlbumFilesResponse> for AlbumFilesPage {
    type Error = CyberdropError;

    fn try_from(body: AlbumFilesResponse) -> Result<Self, Self::Error> {
        if !body.success.unwrap_or(false) {
            let msg = body
                .description
                .or(body.message)
                .unwrap_or_else(|| "failed to fetch album files".to_string());
            return Err(CyberdropError::Api(msg));
        }

        let files = body.files.ok_or(CyberdropError::MissingField(
            "album files response missing files",
        ))?;

        let count = body.count.ok_or(CyberdropError::MissingField(
            "album files response missing count",
        ))?;

        let base_domain = if files.is_empty() {
            match body.basedomain {
                Some(url) => Some(Url::parse(&url)?),
                None => None,
            }
        } else {
            let url = body.basedomain.ok_or(CyberdropError::MissingField(
                "album files response missing basedomain",
            ))?;
            Some(Url::parse(&url)?)
        };

        Ok(AlbumFilesPage {
            success: true,
            files,
            count,
            albums: body.albums.unwrap_or_default(),
            base_domain,
        })
    }
}

impl TryFrom<CreateAlbumResponse> for u64 {
    type Error = CyberdropError;

    fn try_from(body: CreateAlbumResponse) -> Result<Self, Self::Error> {
        if body.success.unwrap_or(false) {
            return body.id.ok_or(CyberdropError::MissingField(
                "create album response missing id",
            ));
        }

        let msg = body
            .description
            .or(body.message)
            .unwrap_or_else(|| "create album failed".to_string());

        if msg.to_lowercase().contains("already an album") {
            Err(CyberdropError::AlbumAlreadyExists(msg))
        } else {
            Err(CyberdropError::Api(msg))
        }
    }
}

impl TryFrom<UploadResponse> for UploadedFile {
    type Error = CyberdropError;

    fn try_from(body: UploadResponse) -> Result<Self, Self::Error> {
        if body.success.unwrap_or(false) {
            let first = body.files.and_then(|mut files| files.pop()).ok_or(
                CyberdropError::MissingField("upload response missing files"),
            )?;
            let url = Url::parse(&first.url)?;
            Ok(UploadedFile {
                name: first.name,
                url: url.to_string(),
            })
        } else {
            let msg = body
                .description
                .unwrap_or_else(|| "upload failed".to_string());
            Err(CyberdropError::Api(msg))
        }
    }
}

impl TryFrom<EditAlbumResponse> for EditAlbumResult {
    type Error = CyberdropError;

    fn try_from(body: EditAlbumResponse) -> Result<Self, Self::Error> {
        if !body.success.unwrap_or(false) {
            let msg = body
                .description
                .or(body.message)
                .unwrap_or_else(|| "edit album failed".to_string());
            return Err(CyberdropError::Api(msg));
        }

        if body.name.is_none() && body.identifier.is_none() {
            return Err(CyberdropError::MissingField(
                "edit album response missing name/identifier",
            ));
        }

        Ok(EditAlbumResult {
            name: body.name,
            identifier: body.identifier,
        })
    }
}