Skip to main content

capsule_library/
file_metadata.rs

1use std::ops::Deref;
2use std::path::Path;
3use std::{fs, io};
4
5use jiff::Timestamp;
6use serde::{Deserialize, Serialize};
7
8use crate::utils::hash_file;
9
10#[derive(Clone, Serialize, Deserialize)]
11pub struct HashData(String);
12
13impl std::fmt::Debug for HashData {
14    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15        write!(f, "{}", self.0)
16    }
17}
18
19impl From<String> for HashData {
20    fn from(value: String) -> Self {
21        HashData(value)
22    }
23}
24
25impl Deref for HashData {
26    type Target = String;
27
28    fn deref(&self) -> &Self::Target {
29        &self.0
30    }
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct FileMetadata {
35    /// SHA-256 hash (64-char lowercase hex)
36    pub hash_sha256: HashData,
37    /// File size in bytes
38    pub size: u64,
39    // /// Media type if available
40    // pub media_type: Option<String>,
41    /// Original file name
42    pub original_filename: String,
43    /// Creation timestamp
44    pub created_timestamp: Timestamp,
45    /// Last modified timestamp
46    pub modified_timestamp: Timestamp,
47
48    /// Import timestamp
49    pub import_timestamp: Timestamp,
50    // pub size: u64,
51    // pub modified: u64,
52}
53
54impl FileMetadata {
55    /// Generate file metadata from a path
56    pub async fn from_file_path(path: &Path) -> io::Result<FileMetadata> {
57        let metadata = fs::metadata(path)?;
58
59        // Get file hash
60        let hash = hash_file(path)?.to_hex();
61
62        // Get file size
63        let size = metadata.len();
64
65        // Extract filename from path
66        let original_filename = path
67            .file_name()
68            .and_then(|name| name.to_str())
69            .unwrap_or("unknown")
70            .to_string();
71
72        // Get timestamps
73        let created_timestamp = metadata
74            .created()
75            .ok()
76            .and_then(|t| Timestamp::try_from(t).ok())
77            .unwrap_or_else(Timestamp::now);
78
79        let modified_timestamp = metadata
80            .modified()
81            .ok()
82            .and_then(|t| Timestamp::try_from(t).ok())
83            .unwrap_or_else(Timestamp::now);
84
85        let import_timestamp = Timestamp::now();
86
87        // Detect media (MIME) type
88        // let media_type = ...;
89
90        Ok(FileMetadata {
91            hash_sha256: hash.into(),
92            size,
93            // media_type,
94            original_filename,
95            created_timestamp,
96            modified_timestamp,
97            import_timestamp,
98        })
99    }
100}