pakem/core/backup/
manager.rs1use crate::core::backup::exporter::DatabaseExporter;
2use chrono::Local;
3use std::fs::{self, File};
4use std::io::{Read, Write};
5use std::path::Path;
6use zip::write::FileOptions;
7
8pub struct BackupManager {
9 backup_path: String,
10}
11
12impl BackupManager {
13 pub fn new() -> Self {
14 let backup_path = "storage/backups".to_string();
15 if !Path::new(&backup_path).exists() {
16 fs::create_dir_all(&backup_path).unwrap();
17 }
18 Self { backup_path }
19 }
20
21 pub async fn run_full_backup(&self, connection: &str, db_url: &str) -> Result<String, String> {
23 let timestamp = Local::now().format("%Y%m%d_%H%M%S").to_string();
24 let folder_name = format!("backup_{}", timestamp);
25 let target_dir = format!("{}/{}", self.backup_path, folder_name);
26
27 fs::create_dir_all(&target_dir).map_err(|e| e.to_string())?;
28
29 let db_file = format!("{}/database.sql", target_dir);
31 DatabaseExporter::export(connection, db_url, &db_file)?;
32
33 let storage_zip = format!("{}/storage.zip", target_dir);
35 self.archive_directory("storage/app/public", &storage_zip)?;
36
37 let final_zip = format!("{}/{}.zip", self.backup_path, folder_name);
39 self.archive_directory(&target_dir, &final_zip)?;
40
41 let _ = fs::remove_dir_all(&target_dir);
43
44 Ok(final_zip)
45 }
46
47 fn archive_directory(&self, src_dir: &str, dst_file: &str) -> Result<(), String> {
48 if !Path::new(src_dir).exists() {
49 return Ok(()); }
51
52 let file = File::create(dst_file).map_err(|e| e.to_string())?;
53 let mut zip = zip::ZipWriter::new(file);
54 let options = FileOptions::<()>::default()
55 .compression_method(zip::CompressionMethod::Deflated)
56 .unix_permissions(0o755);
57
58 let walkdir = walkdir::WalkDir::new(src_dir);
59 let it = walkdir.into_iter();
60
61 for entry in it.filter_map(|e| e.ok()) {
62 let path = entry.path();
63 let name = path.strip_prefix(Path::new(src_dir)).unwrap();
64
65 if path.is_file() {
66 zip.start_file(name.to_string_lossy(), options)
67 .map_err(|e| e.to_string())?;
68 let mut f = File::open(path).map_err(|e| e.to_string())?;
69 let mut buffer = Vec::new();
70 f.read_to_end(&mut buffer).map_err(|e| e.to_string())?;
71 zip.write_all(&buffer).map_err(|e| e.to_string())?;
72 } else if !name.as_os_str().is_empty() {
73 zip.add_directory(name.to_string_lossy(), options)
74 .map_err(|e| e.to_string())?;
75 }
76 }
77
78 zip.finish().map_err(|e| e.to_string())?;
79 Ok(())
80 }
81}