1use bytes::Bytes;
10use color_eyre::Result;
11use serde::Deserialize;
12use sn_client::protocol::storage::ChunkAddress;
13use std::{ffi::OsString, path::Path};
14use tracing::{error, warn};
15
16pub const UPLOADED_FILES: &str = "uploaded_files";
18
19#[derive(Clone, Debug, Deserialize)]
22pub struct UploadedFile {
23 pub filename: OsString,
24 pub data_map: Option<Bytes>,
25}
26
27impl UploadedFile {
28 pub fn write(&self, root_dir: &Path, head_chunk_address: &ChunkAddress) -> Result<()> {
31 let uploaded_files = root_dir.join(UPLOADED_FILES);
32
33 if !uploaded_files.exists() {
34 if let Err(error) = std::fs::create_dir_all(&uploaded_files) {
35 error!("Failed to create {uploaded_files:?} because {error:?}");
36 }
37 }
38
39 let uploaded_file_path = uploaded_files.join(head_chunk_address.to_hex());
40
41 if self.data_map.is_none() {
42 warn!(
43 "No data-map being written for {:?} as it is empty",
44 self.filename
45 );
46 }
47 let serialized =
48 rmp_serde::to_vec(&(&self.filename, &self.data_map)).inspect_err(|_err| {
49 error!("Failed to serialize UploadedFile");
50 })?;
51
52 std::fs::write(&uploaded_file_path, serialized).inspect_err(|_err| {
53 error!(
54 "Could not write UploadedFile of {:?} to {uploaded_file_path:?}",
55 self.filename
56 );
57 })?;
58
59 Ok(())
60 }
61
62 pub fn read(path: &Path) -> Result<Self> {
63 let bytes = std::fs::read(path).inspect_err(|_err| {
64 error!("Error while reading the UploadedFile from {path:?}");
65 })?;
66 let metadata = rmp_serde::from_slice(&bytes).inspect_err(|_err| {
67 error!("Error while deserializing UploadedFile for {path:?}");
68 })?;
69 Ok(metadata)
70 }
71}