shared.rs 9.05 KB
Newer Older
Sophie Herold's avatar
Sophie Herold committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
use crate::borg;
use chrono::prelude::*;
use gio::prelude::*;
use std::collections::{BTreeMap, BTreeSet};
use std::path;
use zeroize::Zeroizing;

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct BackupConfig {
    pub id: String,
    pub repo: BackupRepo,
    pub encrypted: bool,
    pub include: BTreeSet<path::PathBuf>,
    pub exclude: BTreeSet<path::PathBuf>,
    pub last_run: Option<RunInfo>,
}

impl BackupConfig {
    pub fn include_dirs(&self) -> Vec<path::PathBuf> {
        let mut dirs = Vec::new();

        for dir in &self.include {
            dirs.push(absolute(dir));
        }

        dirs
    }

    pub fn exclude_dirs_internal(&self) -> Vec<path::PathBuf> {
        let mut dirs = Vec::new();

        for dir in &self.exclude {
            dirs.push(absolute(dir));
        }

        dirs.push(absolute(path::Path::new(crate::REPO_MOUNT_DIR)));

        dirs
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct RunInfo {
    pub end: DateTime<Local>,
    pub result: Result<borg::Stats, String>,
}

impl RunInfo {
    pub fn new(result: Result<borg::Stats, String>) -> Self {
        Self {
            end: Local::now(),
            result,
        }
    }
}

pub type Password = Zeroizing<Vec<u8>>;

impl BackupConfig {
    pub fn new_from_uri(uri: String) -> Self {
        Self::new_from_repo(BackupRepo::Remote { uri })
    }

    pub fn new_from_path(repo: &path::Path) -> Self {
        let repo_file = gio::File::new_for_path(&repo);
        let none: Option<&gio::Cancellable> = None;
        let mount = repo_file.find_enclosing_mount(none).ok();
        let drive = mount.as_ref().and_then(gio::Mount::get_drive);

        let volume_uuid = mount.as_ref().and_then(get_mount_uuid);

        let icon = drive
            .as_ref()
            .and_then(gio::Drive::get_icon)
            .as_ref()
            .and_then(gio::IconExt::to_string)
            .as_ref()
            .map(std::string::ToString::to_string);

        Self::new_from_repo(BackupRepo::Local {
            path: repo.to_path_buf(),
            icon,
            label: mount
                .as_ref()
                .and_then(gio::Mount::get_name)
                .map(Into::into),
            device: drive
                .as_ref()
                .and_then(gio::Drive::get_name)
                .map(Into::into),
            removable: drive.as_ref().map_or(false, gio::Drive::is_removable),
            volume_uuid,
        })
    }

    pub fn new_from_repo(repo: BackupRepo) -> Self {
        let mut include = std::collections::BTreeSet::new();
        // TODO: Adds Home dir, good idea?
        include.insert(std::path::PathBuf::new());

        Self {
            id: glib::uuid_string_random().unwrap().to_string(),
            repo,
            encrypted: false,
            include,
            exclude: Default::default(),
            last_run: None,
        }
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(tag = "type")]
pub enum BackupRepo {
    Local {
        path: path::PathBuf,
        label: Option<String>,
        device: Option<String>,
        removable: bool,
        volume_uuid: Option<String>,
        icon: Option<String>,
    },
    Remote {
        uri: String,
    },
}

impl BackupRepo {
    pub fn icon(&self) -> Option<String> {
        match self {
            Self::Local { icon, .. } => icon.clone(),
            Self::Remote { .. } => None,
        }
    }
}

impl std::fmt::Display for BackupRepo {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let repo = match self {
            Self::Local { path, .. } => path.to_string_lossy().to_string(),
            Self::Remote { uri, .. } => uri.to_string(),
        };
        write!(f, "{}", repo)
    }
}

#[derive(Serialize, Deserialize, Debug, Default, Clone)]
#[serde(default)]
pub struct Settings {
    pub backups: BTreeMap<String, BackupConfig>,
}

pub fn get_home_dir() -> path::PathBuf {
    crate::globals::HOME_DIR.to_path_buf()
}

pub fn absolute(path: &path::Path) -> path::PathBuf {
    get_home_dir().join(path)
}

pub fn get_mount_uuid(mount: &gio::Mount) -> Option<String> {
    let volume = mount.get_volume();

    volume
        .as_ref()
        .and_then(gio::Volume::get_uuid)
        .or_else(|| volume.as_ref().and_then(|v| v.get_identifier("uuid")))
        .as_ref()
        .map(std::string::ToString::to_string)
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(tag = "type")]
//#[serde(rename_all = "snake_case")]
pub enum Progress {
    #[serde(rename = "archive_progress")]
    Archive {
        original_size: u64,
        compressed_size: u64,
        deduplicated_size: u64,
        nfiles: u64,
        path: String,
    },
    #[serde(rename = "progress_message")]
    Message {
        operation: u64,
        msgid: Option<String>,
        finished: bool,
        message: Option<String>,
    },
    #[serde(rename = "progress_percent")]
    Percent {
        operation: u64,
        msgid: Option<String>,
        finished: bool,
        message: Option<String>,
        current: Option<u64>,
        total: Option<u64>,
    },
}

#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
pub enum LogLevel {
    DEBUG,
    INFO,
    WARNING,
    ERROR,
    CRITICAL,
}

#[allow(non_camel_case_types)]
#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
pub enum MsgId {
    ConnectionClosed,
    ConnectionClosedWithHint,
    PassphraseWrong,
    #[serde(rename = "Repository.DoesNotExist")]
    RepositoryDoesNotExist,
    Other(String),
    #[serde(other)]
    Undefined,
}

impl Default for MsgId {
    fn default() -> Self {
        Self::Undefined
    }
}

#[derive(Deserialize)]
pub struct MsgIdHelper {
    pub msgid: String,
}

#[derive(Clone, Debug)]
pub enum LogMessageEnum {
    ParsedErr(LogMessage),
    UnparsableErr(String),
}

impl LogMessageEnum {
    pub fn message(&self) -> String {
        match &self {
            Self::ParsedErr(LogMessage { ref message, .. }) => message.to_string(),
            Self::UnparsableErr(ref message) => message.to_string(),
        }
    }
}

#[derive(Clone, Debug)]
pub struct LogMessageCollection {
    pub messages: Vec<LogMessageEnum>,
}

impl LogMessageCollection {
    pub fn new(messages: Vec<LogMessageEnum>) -> Self {
        Self { messages }
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub struct LogMessage {
    pub levelname: LogLevel,
    pub name: String,
    pub message: String,
    #[serde(default)]
    pub msgid: MsgId,
}

impl std::fmt::Display for LogMessage {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl std::error::Error for LogMessage {}

#[derive(Debug)]
pub struct BorgUnparsableErr {
    pub stderr: String,
}

impl std::fmt::Display for BorgUnparsableErr {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "STDERR({})", self.stderr)
    }
}

impl std::fmt::Display for LogMessageEnum {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::ParsedErr(e) => write!(f, "{}", e),
            Self::UnparsableErr(s) => write!(f, "{}", s),
        }
    }
}

impl std::fmt::Display for LogMessageCollection {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "{}",
            self.messages
                .iter()
                .map(|m| format!("{}", &m))
                .collect::<Vec<String>>()
                .join("\n")
        )
    }
}

impl std::error::Error for LogMessageCollection {}

#[derive(Debug)]
pub struct ReturnCodeErr {
    pub code: Option<i32>,
}

impl ReturnCodeErr {
    pub fn new(code: Option<i32>) -> Self {
        Self { code }
    }
}

impl std::fmt::Display for ReturnCodeErr {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "Return code err: {:?}", self.code)
    }
}

impl std::error::Error for ReturnCodeErr {}

quick_error! {
    #[derive(Debug)]
    pub enum BorgErr {
        Io(err: std::io::Error) { from() }
        Json(err: serde_json::error::Error) { from () }
        Unix(err: nix::Error) { from() }
        Borg(err: LogMessageCollection) {
            from()
            display("{}", err)
        }
        BorgCode(err: ReturnCodeErr) { from() }
        PasswordMissing { from(secret_service::SsError) }
        UserAborted {}
        Other(err: String) { from() }
    }
}

impl LogMessageEnum {
    pub fn has_borg_msgid(&self, msgid_needle: &MsgId) -> bool {
        if let Self::ParsedErr(x) = self {
            if x.msgid == *msgid_needle {
                return true;
            }
        }

        false
    }
}

impl BorgErr {
    pub fn has_borg_msgid(&self, msgid_needle: &MsgId) -> bool {
        match self {
            Self::Borg(LogMessageCollection { messages }) => {
                for message in messages {
                    if message.has_borg_msgid(msgid_needle) {
                        return true;
                    }
                }
                false
            }
            _ => false,
        }
    }
}