common.rs (2357B)
1 use std::fs; 2 use std::io::Write; 3 use std::path::PathBuf; 4 use std::result::Result; 5 use std::sync::Arc; 6 7 use openssl::error::ErrorStack; 8 use tempfile::{NamedTempFile, PersistError}; 9 use thiserror::Error; 10 11 #[derive(Debug, Clone)] 12 pub struct FileData { 13 path: Option<PathBuf>, 14 bytes: Option<Vec<u8>>, 15 #[allow(dead_code)] 16 file_name: Option<String>, 17 } 18 19 impl FileData { 20 pub fn new( 21 path: Option<PathBuf>, 22 bytes: Option<Vec<u8>>, 23 file_name: Option<String>, 24 ) -> Arc<Self> { 25 Arc::new(FileData { 26 path, 27 bytes, 28 file_name, 29 }) 30 } 31 32 pub fn get_bytes(&self) -> Result<Vec<u8>, SimpleC2PAError> { 33 if let Some(bytes) = &self.bytes { 34 return Ok(bytes.clone()); 35 } 36 37 if let Some(path) = &self.path { 38 return Ok(fs::read(path)?); 39 } 40 41 Err(SimpleC2PAError::Failure { 42 message: "No bytes or path".to_owned(), 43 }) 44 } 45 46 pub fn get_path(&self) -> Result<PathBuf, SimpleC2PAError> { 47 if let Some(ref path) = self.path { 48 return Ok(path.clone()); 49 } 50 51 if let Some(bytes) = &self.bytes { 52 let mut file = NamedTempFile::new()?; 53 file.write_all(bytes)?; 54 return Ok(file.path().into()); 55 } 56 57 Err(SimpleC2PAError::Failure { 58 message: "No bytes or path".to_owned(), 59 }) 60 } 61 } 62 63 #[derive(Error, Debug)] 64 pub enum SimpleC2PAError { 65 #[error("Failed with message: {message}")] 66 Failure { message: String }, 67 68 #[error("unexpected id: {id}")] 69 Unexpected { id: i32 }, 70 } 71 72 impl From<std::io::Error> for SimpleC2PAError { 73 fn from(error: std::io::Error) -> Self { 74 SimpleC2PAError::Failure { 75 message: error.to_string(), 76 } 77 } 78 } 79 80 impl From<PersistError> for SimpleC2PAError { 81 fn from(error: PersistError) -> Self { 82 SimpleC2PAError::Failure { 83 message: error.to_string(), 84 } 85 } 86 } 87 88 impl From<ErrorStack> for SimpleC2PAError { 89 fn from(error: ErrorStack) -> Self { 90 SimpleC2PAError::Failure { 91 message: error.to_string(), 92 } 93 } 94 } 95 96 impl From<c2pa::Error> for SimpleC2PAError { 97 fn from(error: c2pa::Error) -> Self { 98 SimpleC2PAError::Failure { 99 message: error.to_string(), 100 } 101 } 102 }