aboutsummaryrefslogtreecommitdiff
path: root/src/storage.rs
blob: 52c2e60a6a76900f6074172f13f7f60742e95ffc (plain) (blame)
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
use std::{
    fs::{create_dir_all, File},
    io::{Read, Write},
    path::Path,
};

use ipnetwork::IpNetwork;
use mac_address::MacAddress;
use serde::{Deserialize, Serialize};
use serde_json::json;
use tracing::{debug, trace, warn};
use utoipa::ToSchema;

use crate::error::Error;

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Device {
    pub id: String,
    pub mac: MacAddress,
    pub broadcast_addr: String,
    pub ip: Option<IpNetwork>,
    pub times: Option<Vec<i64>>,
}

impl Device {
    const STORAGE_PATH: &'static str = "devices";

    pub fn setup() -> Result<String, Error> {
        trace!("check for storage at {}", Self::STORAGE_PATH);
        let sp = Path::new(Self::STORAGE_PATH);
        if !sp.exists() {
            warn!("device storage path doesn't exist, creating it");
            create_dir_all(Self::STORAGE_PATH)?;
        };

        debug!("device storage at '{}'", Self::STORAGE_PATH);

        Ok(Self::STORAGE_PATH.to_string())
    }

    pub fn read(id: &str) -> Result<Self, Error> {
        trace!(?id, "attempt to read file");
        let mut file = File::open(format!("{}/{id}.json", Self::STORAGE_PATH))?;
        let mut buf = String::new();
        file.read_to_string(&mut buf)?;
        trace!(?id, ?buf, "read successfully from file");

        let dev = serde_json::from_str(&buf)?;
        Ok(dev)
    }

    pub fn write(&self) -> Result<(), Error> {
        trace!(?self.id, ?self, "attempt to write to file");
        let mut file = File::create(format!("{}/{}.json", Self::STORAGE_PATH, self.id))?;
        file.write_all(json!(self).to_string().as_bytes())?;
        trace!(?self.id, "wrote successfully to file");

        Ok(())
    }
}

#[derive(ToSchema)]
#[schema(as = Device)]
pub struct DeviceSchema {
    pub id: String,
    pub mac: String,
    pub broadcast_addr: String,
    pub ip: String,
    pub times: Option<Vec<i64>>,
}