Skip to content

armgit / clipy

Public Imported from GitHub
0

The AI-native screen recorder. Record your screen and talk; the people you share it with and your AI agents both get it.

11.5 KB
Raw Blame
//! Getting a local recording out of its app-data folder as one file a person
//! can send: the video under a readable name, or the whole recording (AREC,
//! screenshots, transcript) as one ZIP.
//!
//! Why this exists: a Local recording lives in a hidden,
//! UUID-named folder and every video is called `recording.mp4`, so someone
//! who is not technical cannot find it or tell takes apart. Saving to a
//! folder they pick (Desktop, a OneDrive or Dropbox sync folder) reaches
//! Teams, email, Drive and S3 without any upload code in Clipy.
//!
//! Pure std plus the `zip` crate, so it is tested without Tauri.

use anyhow::{bail, Context, Result};
use std::fs::File;
use std::io::{BufReader, BufWriter, Write};
use std::path::{Path, PathBuf};

/// Longest file stem we suggest. Windows paths stop at 260 characters, and
/// the folder the user picks takes its share.
const MAX_STEM_CHARS: usize = 80;

/// Files that only mean something to Clipy on this machine: markers for
/// retention and who started the take. Leaving them out keeps an imported
/// copy from inheriting "kept" or "agent take" by accident.
const INTERNAL_FILES: [&str; 4] = ["keep", super::AGENT_TAKE, super::TALK_TAKE, ".DS_Store"];

/// Turns a suggested name (a title and a date from the page) into a stem
/// that is safe on macOS and Windows: no path separators, no characters
/// Windows refuses, no trailing dots or spaces, not a reserved device name.
pub fn file_stem(requested: &str, fallback: &str) -> String {
    let mut out = String::new();
    let mut last_space = true;
    for c in requested.chars() {
        let c = match c {
            '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '-',
            c if c.is_control() => ' ',
            c => c,
        };
        if c.is_whitespace() {
            if !last_space {
                out.push(' ');
            }
            last_space = true;
        } else {
            out.push(c);
            last_space = false;
        }
        if out.chars().count() >= MAX_STEM_CHARS {
            break;
        }
    }
    let trimmed = out.trim_matches(|c: char| c == ' ' || c == '.').to_string();
    let upper = trimmed.to_ascii_uppercase();
    let reserved = matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL")
        || ((upper.starts_with("COM") || upper.starts_with("LPT"))
            && upper.len() == 4
            && upper.as_bytes()[3].is_ascii_digit());
    if trimmed.is_empty() || reserved {
        fallback.to_string()
    } else {
        trimmed
    }
}

/// The chosen path with the expected extension. A save dialog normally adds
/// it, but a name typed without one must still open in a video player.
pub fn with_extension(path: PathBuf, extension: &str) -> PathBuf {
    let matches = path
        .extension()
        .and_then(|e| e.to_str())
        .is_some_and(|e| e.eq_ignore_ascii_case(extension));
    if matches {
        path
    } else {
        let mut name = path
            .file_name()
            .map(|n| n.to_os_string())
            .unwrap_or_default();
        name.push(".");
        name.push(extension);
        path.with_file_name(name)
    }
}

/// Written beside the destination, then renamed over it, so a crash or a
/// full disk never leaves a half-written file under the name the user chose
/// (and a sync client never uploads one).
fn partial_path(dest: &Path) -> PathBuf {
    let mut name = dest
        .file_name()
        .map(|n| n.to_os_string())
        .unwrap_or_default();
    name.push(".clipy-partial");
    dest.with_file_name(name)
}

fn finish(partial: &Path, dest: &Path) -> Result<()> {
    // Windows' rename replaces an existing file too (MoveFileEx with
    // REPLACE_EXISTING); the save dialog already asked before replacing.
    std::fs::rename(partial, dest).with_context(|| format!("save {}", dest.display()))
}

/// Copies one file to `dest` through a partial file.
pub fn copy_file(src: &Path, dest: &Path) -> Result<u64> {
    if !src.is_file() {
        bail!("The video is no longer in this recording's folder");
    }
    if same_file(src, dest) {
        bail!("Pick a folder outside Clipy's own recordings folder");
    }
    let partial = partial_path(dest);
    let result = (|| -> Result<u64> {
        let bytes = std::fs::copy(src, &partial).context("copy the video")?;
        File::open(&partial)?.sync_all().ok();
        finish(&partial, dest)?;
        Ok(bytes)
    })();
    if result.is_err() {
        let _ = std::fs::remove_file(&partial);
    }
    result
}

fn same_file(a: &Path, b: &Path) -> bool {
    match (a.canonicalize(), b.canonicalize()) {
        (Ok(a), Ok(b)) => a == b,
        _ => false,
    }
}

/// Every file the ZIP holds: (file on disk, path inside the archive), in a
/// stable order. Symlinks are skipped, never followed, so the archive can
/// only ever hold what is inside the recording's own folder.
pub fn entries(dir: &Path) -> Result<Vec<(PathBuf, String)>> {
    let mut out = Vec::new();
    collect(dir, dir, &mut out)?;
    out.sort_by(|a, b| a.1.cmp(&b.1));
    Ok(out)
}

fn collect(root: &Path, dir: &Path, out: &mut Vec<(PathBuf, String)>) -> Result<()> {
    for entry in std::fs::read_dir(dir).with_context(|| format!("read {}", dir.display()))? {
        let entry = entry?;
        let kind = entry.file_type()?;
        let path = entry.path();
        let name = entry.file_name().to_string_lossy().into_owned();
        if kind.is_symlink() || skip(&name) {
            continue;
        }
        if kind.is_dir() {
            collect(root, &path, out)?;
        } else if kind.is_file() {
            let relative = path
                .strip_prefix(root)
                .context("entry outside the recording")?
                .components()
                .map(|c| c.as_os_str().to_string_lossy().into_owned())
                .collect::<Vec<_>>()
                .join("/");
            out.push((path, relative));
        }
    }
    Ok(())
}

fn skip(name: &str) -> bool {
    INTERNAL_FILES.contains(&name)
        || name.ends_with(".tmp")
        || name.ends_with(".partial")
        || name.ends_with(".clipy-partial")
}

/// Packs the recording folder into `dest`, every file under `root_name/` so
/// unzipping gives one folder whose AREC still finds its screenshots.
/// Stored, not deflated: the video and screenshots are compressed already,
/// so deflate would cost minutes of CPU on a long take to save almost
/// nothing. Returns the archive's size.
pub fn write_zip(dir: &Path, dest: &Path, root_name: &str) -> Result<u64> {
    let files = entries(dir)?;
    if files.is_empty() {
        bail!("This recording's folder is empty");
    }
    if dest.starts_with(dir) {
        bail!("Pick a folder outside the recording itself");
    }
    let partial = partial_path(dest);
    let result = (|| -> Result<u64> {
        let file =
            File::create(&partial).with_context(|| format!("create {}", partial.display()))?;
        let mut zip = zip::ZipWriter::new(BufWriter::new(file));
        for (path, relative) in &files {
            let size = std::fs::metadata(path)?.len();
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored)
                .large_file(size >= u32::MAX as u64);
            zip.start_file(format!("{root_name}/{relative}"), options)?;
            let mut reader =
                BufReader::new(File::open(path).with_context(|| format!("read {relative}"))?);
            std::io::copy(&mut reader, &mut zip).with_context(|| format!("pack {relative}"))?;
        }
        let mut writer = zip.finish()?;
        writer.flush()?;
        let file = writer.into_inner().map_err(|e| e.into_error())?;
        file.sync_all().ok();
        drop(file);
        let bytes = std::fs::metadata(&partial)?.len();
        finish(&partial, dest)?;
        Ok(bytes)
    })();
    if result.is_err() {
        let _ = std::fs::remove_file(&partial);
    }
    result
}

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

    #[test]
    fn stems_are_safe_on_every_platform() {
        assert_eq!(file_stem("Login bug: step 2/3", "x"), "Login bug- step 2-3");
        assert_eq!(file_stem("  a \n\t b  ", "x"), "a b");
        assert_eq!(file_stem("ends with dots...", "x"), "ends with dots");
        assert_eq!(file_stem("CON", "fallback"), "fallback");
        assert_eq!(file_stem("com1", "fallback"), "fallback");
        assert_eq!(file_stem("Common", "fallback"), "Common");
        assert_eq!(file_stem("..", "fallback"), "fallback");
        assert_eq!(
            file_stem(&"a".repeat(300), "x").chars().count(),
            MAX_STEM_CHARS
        );
    }

    #[test]
    fn a_missing_extension_is_added() {
        assert_eq!(
            with_extension("/tmp/a".into(), "mp4"),
            PathBuf::from("/tmp/a.mp4")
        );
        assert_eq!(
            with_extension("/tmp/a.MP4".into(), "mp4"),
            PathBuf::from("/tmp/a.MP4")
        );
        assert_eq!(
            with_extension("/tmp/a.b".into(), "zip"),
            PathBuf::from("/tmp/a.b.zip")
        );
    }

    fn sample() -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        let take = dir.path().join("take");
        std::fs::create_dir_all(take.join("frames")).unwrap();
        std::fs::write(take.join("recording.arec"), b"# AREC").unwrap();
        std::fs::write(take.join("recording.mp4"), vec![7u8; 4096]).unwrap();
        std::fs::write(take.join("frames/frame-001.jpg"), b"jpg").unwrap();
        std::fs::write(take.join("keep"), b"keep").unwrap();
        std::fs::write(take.join("status.json.tmp"), b"{}").unwrap();
        dir
    }

    #[test]
    fn the_zip_holds_the_recording_and_not_clipys_markers() {
        let dir = sample();
        let take = dir.path().join("take");
        let names: Vec<String> = entries(&take).unwrap().into_iter().map(|e| e.1).collect();
        assert_eq!(
            names,
            ["frames/frame-001.jpg", "recording.arec", "recording.mp4"]
        );

        let dest = dir.path().join("out.zip");
        let bytes = write_zip(&take, &dest, "Login bug").unwrap();
        assert_eq!(bytes, std::fs::metadata(&dest).unwrap().len());
        assert!(!partial_path(&dest).exists());
        let mut archive = zip::ZipArchive::new(File::open(&dest).unwrap()).unwrap();
        let mut inside: Vec<String> = (0..archive.len())
            .map(|i| archive.by_index(i).unwrap().name().to_string())
            .collect();
        inside.sort();
        assert_eq!(
            inside,
            [
                "Login bug/frames/frame-001.jpg",
                "Login bug/recording.arec",
                "Login bug/recording.mp4"
            ]
        );
        let mut video = Vec::new();
        std::io::Read::read_to_end(
            &mut archive.by_name("Login bug/recording.mp4").unwrap(),
            &mut video,
        )
        .unwrap();
        assert_eq!(video, vec![7u8; 4096]);
    }

    #[test]
    fn a_zip_is_never_written_inside_the_recording() {
        let dir = sample();
        let take = dir.path().join("take");
        assert!(write_zip(&take, &take.join("self.zip"), "x").is_err());
    }

    #[test]
    fn the_video_is_copied_whole_and_never_onto_itself() {
        let dir = sample();
        let take = dir.path().join("take");
        let dest = dir.path().join("Login bug.mp4");
        assert_eq!(copy_file(&take.join("recording.mp4"), &dest).unwrap(), 4096);
        assert_eq!(std::fs::read(&dest).unwrap(), vec![7u8; 4096]);
        assert!(copy_file(&take.join("recording.mp4"), &take.join("recording.mp4")).is_err());
        assert!(copy_file(&take.join("missing.mp4"), &dest).is_err());
    }
}