Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

15.2 KB
Raw Blame
//! TODO: We should investigate generating this with OpenAPI.
//! This will come part of the EffectTS rewrite work.

use serde::{Deserialize, Serialize};
use serde_json::json;
use specta::Type;
use std::collections::HashMap;
use tauri::AppHandle;
use tracing::{instrument, trace};

use crate::web_api::{AuthedApiError, ManagerExt};

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MultipartUploadInitiateResponse {
    pub upload_id: String,
    pub provider: Option<String>,
}

#[instrument(skip(app))]
pub async fn upload_multipart_initiate(
    app: &AppHandle,
    video_id: &str,
    replace_existing: bool,
) -> Result<MultipartUploadInitiateResponse, AuthedApiError> {
    let resp = app
        .authed_api_request("/api/upload/multipart/initiate", |c, url| {
            c.post(url)
                .header("Content-Type", "application/json")
                .json(&serde_json::json!({
                    "videoId": video_id,
                    "contentType": "video/mp4",
                    "replaceExisting": replace_existing
                }))
        })
        .await
        .map_err(|err| format!("api/upload_multipart_initiate/request: {err}"))?;

    if !resp.status().is_success() {
        let status = resp.status().as_u16();
        let error_body = resp
            .text()
            .await
            .unwrap_or_else(|_| "<no response body>".to_string());
        return Err(format!("api/upload_multipart_initiate/{status}: {error_body}").into());
    }

    resp.json::<MultipartUploadInitiateResponse>()
        .await
        .map_err(|err| format!("api/upload_multipart_initiate/response: {err}").into())
}

#[instrument(skip(app, upload_id))]
pub async fn upload_multipart_presign_part(
    app: &AppHandle,
    video_id: &str,
    upload_id: &str,
    part_number: u32,
    md5_sum: Option<&str>,
) -> Result<String, AuthedApiError> {
    #[derive(Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct Response {
        presigned_url: String,
    }

    let mut body = serde_json::Map::from_iter([
        ("videoId".to_string(), json!(video_id)),
        ("uploadId".to_string(), json!(upload_id)),
        ("partNumber".to_string(), json!(part_number)),
    ]);

    if let Some(md5_sum) = md5_sum {
        body.insert("md5Sum".to_string(), json!(md5_sum));
    }

    let resp = app
        .authed_api_request("/api/upload/multipart/presign-part", |c, url| {
            c.post(url)
                .header("Content-Type", "application/json")
                .json(&serde_json::json!(body))
        })
        .await
        .map_err(|err| format!("api/upload_multipart_presign_part/request: {err}"))?;

    if !resp.status().is_success() {
        let status = resp.status().as_u16();
        let error_body = resp
            .text()
            .await
            .unwrap_or_else(|_| "<no response body>".to_string());
        return Err(format!("api/upload_multipart_presign_part/{status}: {error_body}").into());
    }

    crate::upload::lifecycle::cancellable(resp.json::<Response>())
        .await?
        .map_err(|err| format!("api/upload_multipart_presign_part/response: {err}").into())
        .map(|data| data.presigned_url)
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UploadedPart {
    pub part_number: u32,
    pub etag: String,
    pub size: usize,
    #[serde(skip)]
    pub total_size: u64,
    #[serde(skip)]
    pub object_identity: Option<String>,
}

#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct S3VideoMeta {
    #[serde(rename = "durationInSecs")]
    pub duration_in_secs: f64,
    pub width: u32,
    pub height: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fps: Option<f32>,
}

#[derive(Debug, PartialEq, Eq)]
pub(crate) enum MultipartCompletion {
    Completed(Option<String>),
    ReplacementRestartRequired,
}

fn replacement_restart_required(status: u16, body: &str, replace_existing: bool) -> bool {
    #[derive(Deserialize)]
    struct ErrorBody {
        code: String,
    }

    replace_existing
        && status == 409
        && serde_json::from_str::<ErrorBody>(body)
            .is_ok_and(|body| body.code == "REPLACEMENT_RESTART_REQUIRED")
}

#[instrument(skip_all)]
pub async fn upload_multipart_complete(
    app: &AppHandle,
    video_id: &str,
    upload_id: &str,
    parts: &[UploadedPart],
    meta: Option<S3VideoMeta>,
    replace_existing: bool,
) -> Result<Option<String>, AuthedApiError> {
    match upload_multipart_complete_outcome(app, video_id, upload_id, parts, meta, replace_existing)
        .await?
    {
        MultipartCompletion::Completed(identity) => Ok(identity),
        MultipartCompletion::ReplacementRestartRequired => {
            Err("Replacement upload must be restarted; local files retained".into())
        }
    }
}

#[instrument(skip_all)]
pub(crate) async fn upload_multipart_complete_outcome(
    app: &AppHandle,
    video_id: &str,
    upload_id: &str,
    parts: &[UploadedPart],
    meta: Option<S3VideoMeta>,
    replace_existing: bool,
) -> Result<MultipartCompletion, AuthedApiError> {
    #[derive(Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct MultipartCompleteRequest<'a> {
        video_id: &'a str,
        upload_id: &'a str,
        parts: &'a [UploadedPart],
        #[serde(flatten)]
        meta: Option<S3VideoMeta>,
        replace_existing: bool,
    }

    #[derive(Deserialize)]
    pub struct Response {
        #[serde(rename = "objectIdentity")]
        object_identity: Option<String>,
    }

    trace!("Completing multipart upload");

    let resp = app
        .authed_api_request("/api/upload/multipart/complete", |c, url| {
            c.post(url)
                .header("Content-Type", "application/json")
                .json(&MultipartCompleteRequest {
                    video_id,
                    upload_id,
                    parts,
                    meta,
                    replace_existing,
                })
        })
        .await
        .map_err(|err| format!("api/upload_multipart_complete/request: {err}"))?;

    if !resp.status().is_success() {
        let status = resp.status().as_u16();
        let error_body = crate::upload::lifecycle::cancellable(resp.text())
            .await?
            .unwrap_or_else(|_| "<no response body>".to_string());
        if replacement_restart_required(status, &error_body, replace_existing) {
            return Ok(MultipartCompletion::ReplacementRestartRequired);
        }
        return Err(format!("api/upload_multipart_complete/{status}: {error_body}").into());
    }

    crate::upload::lifecycle::cancellable(resp.json::<Response>())
        .await?
        .map_err(|err| format!("api/upload_multipart_complete/response: {err}").into())
        .map(|data| MultipartCompletion::Completed(data.object_identity))
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum PresignedS3PutRequestMethod {
    #[allow(unused)]
    Post,
    Put,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PresignedS3PutRequest {
    pub video_id: String,
    pub subpath: String,
    pub method: PresignedS3PutRequestMethod,
    #[serde(flatten)]
    pub meta: Option<S3VideoMeta>,
}

#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SignedUploadTarget {
    pub url: String,
    #[serde(default)]
    pub headers: HashMap<String, String>,
}

#[instrument(skip(app))]
pub async fn upload_signed(
    app: &AppHandle,
    body: PresignedS3PutRequest,
) -> Result<SignedUploadTarget, AuthedApiError> {
    #[derive(Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct Response {
        presigned_put_data: SignedUploadTarget,
    }

    let resp = app
        .authed_api_request("/api/upload/signed", |client, url| {
            client.post(url).json(&body)
        })
        .await
        .map_err(|err| format!("api/upload_signed/request: {err}"))?;

    if !resp.status().is_success() {
        let status = resp.status().as_u16();
        let error_body = resp
            .text()
            .await
            .unwrap_or_else(|_| "<no response body>".to_string());
        return Err(format!("api/upload_signed/{status}: {error_body}").into());
    }

    crate::upload::lifecycle::cancellable(resp.json::<Response>())
        .await?
        .map_err(|err| format!("api/upload_signed/response: {err}").into())
        .map(|data| data.presigned_put_data)
}

#[instrument(skip(app))]
pub async fn upload_signed_batch(
    app: &AppHandle,
    video_id: &str,
    subpaths: &[String],
) -> Result<std::collections::HashMap<String, String>, AuthedApiError> {
    #[derive(Deserialize)]
    struct Response {
        urls: std::collections::HashMap<String, String>,
    }

    let resp = app
        .authed_api_request("/api/upload/signed/batch", |client, url| {
            client.post(url).json(&serde_json::json!({
                "videoId": video_id,
                "subpaths": subpaths,
            }))
        })
        .await
        .map_err(|err| format!("api/upload_signed_batch/request: {err}"))?;

    if !resp.status().is_success() {
        let status = resp.status().as_u16();
        let error_body = resp
            .text()
            .await
            .unwrap_or_else(|_| "<no response body>".to_string());
        return Err(format!("api/upload_signed_batch/{status}: {error_body}").into());
    }

    crate::upload::lifecycle::cancellable(resp.json::<Response>())
        .await?
        .map_err(|err| format!("api/upload_signed_batch/response: {err}").into())
        .map(|data| data.urls)
}

#[instrument(skip(app))]
pub async fn desktop_video_progress(
    app: &AppHandle,
    video_id: &str,
    uploaded: u64,
    total: u64,
) -> Result<(), AuthedApiError> {
    let resp = app
        .authed_api_request("/api/desktop/video/progress", |client, url| {
            client.post(url).json(&json!({
                "videoId": video_id,
                "uploaded": uploaded,
                "total": total,
                "updatedAt": chrono::Utc::now().to_rfc3339()
            }))
        })
        .await
        .map_err(|err| format!("api/desktop_video_progress/request: {err}"))?;

    if !resp.status().is_success() {
        let status = resp.status().as_u16();
        let error_body = resp
            .text()
            .await
            .unwrap_or_else(|_| "<no response body>".to_string());
        return Err(format!("api/desktop_video_progress/{status}: {error_body}").into());
    }

    Ok(())
}

#[derive(Serialize, Deserialize, Type, Debug, Clone, Default)]
#[serde(rename_all = "camelCase")]
pub struct OrganizationBrandColors {
    pub primary: Option<String>,
    pub secondary: Option<String>,
    pub accent: Option<String>,
    pub background: Option<String>,
}

fn default_organization_role() -> String {
    "member".to_string()
}

#[derive(Serialize, Deserialize, Type, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Organization {
    pub id: String,
    pub name: String,
    pub owner_id: String,
    #[serde(default = "default_organization_role")]
    pub role: String,
    #[serde(default)]
    pub can_edit_brand: bool,
    #[serde(default)]
    pub icon_url: Option<String>,
    #[serde(default)]
    pub brand_colors: OrganizationBrandColors,
}

pub(crate) async fn prepare_recording_segments(
    app: &AppHandle,
    video_id: &str,
    segments: &[crate::upload::preparation::Segment],
) -> Result<Option<Vec<crate::upload::preparation::Segment>>, AuthedApiError> {
    #[derive(Deserialize)]
    struct Response {
        version: u32,
        prepared: Vec<crate::upload::preparation::Segment>,
    }

    let response = app
        .authed_api_request("/api/recording/prepare", |client, url| {
            client
                .post(url)
                .timeout(std::time::Duration::from_secs(20))
                .json(&serde_json::json!({ "videoId": video_id, "segments": segments }))
        })
        .await?;
    if matches!(response.status().as_u16(), 404 | 405) {
        return Ok(None);
    }
    if !response.status().is_success() {
        return Err(format!(
            "Optional recording preparation unavailable ({})",
            response.status()
        )
        .into());
    }
    let response: Response = crate::upload::lifecycle::cancellable(response.json()).await??;
    if response.version != 1 || response.prepared.len() > 32 {
        return Ok(None);
    }
    Ok(Some(response.prepared))
}

pub async fn verify_recording_complete(
    app: &AppHandle,
    video_id: &str,
    verification: &cap_recording::upload_verification::UploadVerification,
) -> Result<Option<cap_recording::upload_verification::VerifiedUploadReceipt>, AuthedApiError> {
    let response = app
        .authed_api_request("/api/upload/recording-complete", |client, url| {
            client
                .post(url)
                .timeout(std::time::Duration::from_secs(45))
                .json(&serde_json::json!({
                    "videoId": video_id,
                    "verification": verification,
                }))
        })
        .await?;
    let status = response.status();
    let response: serde_json::Value =
        crate::upload::lifecycle::cancellable(response.json()).await??;
    if status == reqwest::StatusCode::CONFLICT
        && response.get("status").and_then(serde_json::Value::as_str) == Some("reupload-required")
    {
        return Err(AuthedApiError::ReuploadRequired);
    }
    if !status.is_success() {
        return Err(format!(
            "Recording verification is unavailable ({status}); local recording retained"
        )
        .into());
    }
    verification
        .verified_receipt(video_id, &response)
        .map_err(AuthedApiError::from)
}

pub async fn fetch_organizations(app: &AppHandle) -> Result<Vec<Organization>, AuthedApiError> {
    let resp = app
        .authed_api_request("/api/desktop/organizations", |client, url| client.get(url))
        .await
        .map_err(|err| format!("api/fetch_organizations/request: {err}"))?;

    if !resp.status().is_success() {
        let status = resp.status().as_u16();
        let error_body = resp
            .text()
            .await
            .unwrap_or_else(|_| "<no response body>".to_string());
        return Err(format!("api/fetch_organizations/{status}: {error_body}").into());
    }

    resp.json()
        .await
        .map_err(|err| format!("api/fetch_organizations/response: {err}").into())
}

#[cfg(test)]
mod replacement_completion_tests {
    use super::*;

    #[test]
    fn restart_requires_replacement_conflict_and_exact_structured_code() {
        let restart = r#"{"code":"REPLACEMENT_RESTART_REQUIRED","error":"Restart upload"}"#;
        assert!(replacement_restart_required(409, restart, true));
        assert!(!replacement_restart_required(409, restart, false));
        for status in [200, 400, 401, 403, 404, 500, 503] {
            assert!(!replacement_restart_required(status, restart, true));
        }
        for body in [
            "REPLACEMENT_RESTART_REQUIRED",
            r#"{"error":"REPLACEMENT_RESTART_REQUIRED"}"#,
            r#"{"code":"OTHER_CONFLICT"}"#,
            r#"{"code":"replacement_restart_required"}"#,
            r#"{"code":null}"#,
            r#"{"code":1}"#,
            "{}",
            "invalid JSON",
        ] {
            assert!(!replacement_restart_required(409, body, true));
        }
    }
}