bibby 0.2.0

The official Rust SDK for Bytebury — typed clients, smart .env initialization, and ergonomic macros for Geo, Images, PDF, Mailer, Uploader, Cron, Forms, Webhooks, Monitors, and Vault.
Documentation
//! Client and types for **Bytebury Uploader** (`https://api.bytebury.com/uploader/v1`).
//!
//! Upload files, list and filter stored files, generate signed download URLs,
//! create share links, issue one-time unauthenticated upload links, and check
//! storage usage.

use std::time::Duration;

use serde::{Deserialize, Serialize};

use crate::client::Bibby;
use crate::error::Result;
use crate::pagination::Page;

const PRODUCT: &str = "uploader";
const UPLOAD_TIMEOUT: Duration = Duration::from_secs(15 * 60);

/// Client for **Bytebury Uploader**.
///
/// Obtained via [`Bibby::uploader`].
#[derive(Debug, Clone, Copy)]
pub struct UploaderClient<'a> {
    client: &'a Bibby,
}

impl<'a> UploaderClient<'a> {
    pub(crate) fn new(client: &'a Bibby) -> Self {
        Self { client }
    }

    /// Uploads raw binary bytes as a file.
    ///
    /// Calls `POST /uploader/v1/files`.
    pub async fn upload(
        &self,
        bytes: impl Into<Vec<u8>>,
        options: &UploadOptions,
    ) -> Result<LinkedFile> {
        let content_type = options.content_type.as_deref();
        self.client
            .post_bytes_query(
                PRODUCT,
                "files",
                options,
                bytes.into(),
                content_type,
                UPLOAD_TIMEOUT,
            )
            .await
    }

    /// Lists files in your account (newest first).
    ///
    /// Calls `GET /uploader/v1/files`.
    pub async fn list(&self, params: &ListFilesParams) -> Result<Page<UploadedFile>> {
        self.client.get_json_query(PRODUCT, "files", params).await
    }

    /// Fetches a file's metadata along with a fresh short-lived signed download URL.
    ///
    /// Calls `GET /uploader/v1/files/{id}`.
    pub async fn get(&self, id: i64, link_expires_in_minutes: Option<i64>) -> Result<LinkedFile> {
        #[derive(Serialize)]
        struct Query {
            #[serde(skip_serializing_if = "Option::is_none")]
            link_expires_in_minutes: Option<i64>,
        }
        self.client
            .get_json_query(
                PRODUCT,
                &format!("files/{id}"),
                &Query {
                    link_expires_in_minutes,
                },
            )
            .await
    }

    /// Fetches a signed URL for the file's 32×32 WebP thumbnail (images only).
    ///
    /// Calls `GET /uploader/v1/files/{id}/thumbnail`.
    pub async fn thumbnail(&self, id: i64) -> Result<ThumbnailUrl> {
        self.client
            .get_json(PRODUCT, &format!("files/{id}/thumbnail"))
            .await
    }

    /// Renames a file or toggles its public/private visibility.
    ///
    /// Calls `PATCH /uploader/v1/files/{id}`.
    pub async fn update(&self, id: i64, changes: &UpdateFileRequest) -> Result<UploadedFile> {
        self.client
            .patch_json(PRODUCT, &format!("files/{id}"), changes)
            .await
    }

    /// Permanently deletes a file and returns its metadata prior to deletion.
    ///
    /// Calls `DELETE /uploader/v1/files/{id}`.
    pub async fn delete(&self, id: i64) -> Result<UploadedFile> {
        self.client
            .delete_json(PRODUCT, &format!("files/{id}"))
            .await
    }

    /// Bulk-deletes up to 100 files in a single request.
    ///
    /// Calls `POST /uploader/v1/files/delete`.
    pub async fn bulk_delete(&self, ids: &[i64]) -> Result<BulkDeleteResult> {
        #[derive(Serialize)]
        struct Body<'a> {
            ids: &'a [i64],
        }
        self.client
            .post_json(PRODUCT, "files/delete", &Body { ids })
            .await
    }

    /// Creates a shareable link for a file.
    ///
    /// Calls `POST /uploader/v1/files/{id}/share-links`.
    pub async fn create_share_link(
        &self,
        id: i64,
        request: &CreateShareLinkRequest,
    ) -> Result<ShareLink> {
        self.client
            .post_json(PRODUCT, &format!("files/{id}/share-links"), request)
            .await
    }

    /// Revokes all active share links for a file.
    ///
    /// Calls `DELETE /uploader/v1/files/{id}/share-links`.
    pub async fn revoke_share_links(&self, id: i64) -> Result<RevokedShareLinks> {
        self.client
            .delete_json(PRODUCT, &format!("files/{id}/share-links"))
            .await
    }

    /// Creates a one-time unauthenticated upload link that browsers or external
    /// clients can `POST` or `PUT` directly to.
    ///
    /// Calls `POST /uploader/v1/upload-links`.
    pub async fn create_upload_link(
        &self,
        request: &CreateUploadLinkRequest,
    ) -> Result<UploadLink> {
        self.client
            .post_json(PRODUCT, "upload-links", request)
            .await
    }

    /// Returns total bytes and file count currently stored in your account.
    ///
    /// Calls `GET /uploader/v1/storage`.
    pub async fn storage(&self) -> Result<StorageUsage> {
        self.client.get_json(PRODUCT, "storage").await
    }
}

/// Query options for [`UploaderClient::upload`].
#[derive(Debug, Clone, Serialize)]
pub struct UploadOptions {
    /// Filename including extension (max 255 characters).
    pub name: String,
    /// Optional MIME media type (`type/subtype`). Guessed from `name` if omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,
    /// Optional TTL in minutes (`1..=525600`); omitted keeps the file until deleted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_in_minutes: Option<i64>,
    /// Whether the file should have a permanent public URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub public: Option<bool>,
}

impl UploadOptions {
    /// Creates upload options with the required filename.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            content_type: None,
            expires_in_minutes: None,
            public: None,
        }
    }

    /// Sets the file's MIME content type.
    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
        self.content_type = Some(content_type.into());
        self
    }

    /// Sets a temporary expiration TTL in minutes (`1..=525600`).
    pub fn expires_in_minutes(mut self, minutes: i64) -> Self {
        self.expires_in_minutes = Some(minutes);
        self
    }

    /// Marks the uploaded file as public or private.
    pub fn public(mut self, public: bool) -> Self {
        self.public = Some(public);
        self
    }
}

/// File kind filter for [`ListFilesParams`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FileKind {
    /// Image files.
    Image,
    /// Video files.
    Video,
    /// Audio files.
    Audio,
    /// PDF documents.
    Pdf,
    /// Text files.
    Text,
}

/// Query parameters for [`UploaderClient::list`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ListFilesParams {
    /// Case-insensitive filename substring filter.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub q: Option<String>,
    /// Filter by broad file kind.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<FileKind>,
    /// Filter by public (`true`) or private (`false`) visibility.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub public: Option<bool>,
    /// 1-based page number.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<i64>,
    /// Items per page (`1..=100`, default `10`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_size: Option<i64>,
}

/// Request body for [`UploaderClient::update`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateFileRequest {
    /// New filename.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Toggle public visibility (`false` revokes the existing `public_url`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub public: Option<bool>,
}

/// Request body for [`UploaderClient::create_share_link`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateShareLinkRequest {
    /// Optional expiration in minutes (`1..=525600`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_in_minutes: Option<i64>,
}

/// Request body for [`UploaderClient::create_upload_link`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateUploadLinkRequest {
    /// Filename (required for raw `PUT`/`POST` uploads; optional for multipart).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Whether the uploaded file should be public.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub public: Option<bool>,
    /// Expected MIME type (`type/subtype`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,
    /// Optional uploaded-file TTL in minutes (`1..=525600`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_in_minutes: Option<i64>,
    /// Optional redirect URL after browser form upload.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redirect_url: Option<String>,
    /// Upload link expiration in minutes (`1..=1440`, default `15`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub link_expires_in_minutes: Option<i64>,
}

/// Metadata for a stored file in Bytebury Uploader.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UploadedFile {
    /// File ID.
    pub id: i64,
    /// Filename.
    pub name: String,
    /// MIME content type.
    pub content_type: String,
    /// Size in bytes.
    pub size_bytes: i64,
    /// Permanent public URL when public, or `None` when private.
    pub public_url: Option<String>,
    /// RFC 3339 expiration timestamp, or `None` if permanent.
    pub expires_at: Option<String>,
    /// RFC 3339 creation timestamp.
    pub created_at: String,
    /// RFC 3339 last-update timestamp.
    pub updated_at: String,
    /// Whether a 32×32 WebP thumbnail is available.
    #[serde(default)]
    pub has_thumbnail: bool,
}

/// File metadata paired with a fresh short-lived signed download URL.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LinkedFile {
    /// Core file metadata.
    #[serde(flatten)]
    pub file: UploadedFile,
    /// Short-lived signed bucket URL.
    pub url: String,
    /// RFC 3339 expiration timestamp for [`Self::url`].
    pub url_expires_at: String,
}

/// Signed thumbnail URL returned by [`UploaderClient::thumbnail`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ThumbnailUrl {
    /// Signed URL to the 32×32 WebP thumbnail.
    pub url: String,
}

/// Response from [`UploaderClient::bulk_delete`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BulkDeleteResult {
    /// Files that were deleted.
    #[serde(default)]
    pub deleted: Vec<UploadedFile>,
    /// IDs that did not exist in the account.
    #[serde(default)]
    pub not_found: Vec<i64>,
}

/// Share link created by [`UploaderClient::create_share_link`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShareLink {
    /// Public share URL (`https://api.bytebury.com/uploader/shared/bb_sh_...`).
    pub url: String,
    /// Underlying file ID.
    pub file_id: i64,
    /// Filename.
    pub name: String,
    /// Optional RFC 3339 expiration timestamp.
    pub expires_at: Option<String>,
}

/// Response from [`UploaderClient::revoke_share_links`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RevokedShareLinks {
    /// File ID whose links were stopped.
    pub file_id: i64,
    /// Number of active share links revoked.
    pub stopped: i64,
}

/// One-time upload link returned by [`UploaderClient::create_upload_link`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UploadLink {
    /// One-time upload URL (`https://api.bytebury.com/uploader/uploads/bb_up_...`).
    pub upload_url: String,
    /// Allowed HTTP methods (`["POST", "PUT"]`).
    pub methods: Vec<String>,
    /// RFC 3339 expiration timestamp for the upload link.
    pub expires_at: String,
    /// Optional redirect URL after upload.
    pub redirect_url: Option<String>,
}

/// Account storage usage returned by [`UploaderClient::storage`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct StorageUsage {
    /// Total bytes stored.
    pub bytes: i64,
    /// Total number of files stored.
    pub files: i64,
}