aboutsummaryrefslogtreecommitdiff
path: root/src/storage.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/storage.rs')
-rw-r--r--src/storage.rs70
1 files changed, 70 insertions, 0 deletions
diff --git a/src/storage.rs b/src/storage.rs
new file mode 100644
index 0000000..0da245b
--- /dev/null
+++ b/src/storage.rs
@@ -0,0 +1,70 @@
1use std::{
2 fs::{create_dir_all, File},
3 io::{Read, Write},
4 path::Path,
5};
6
7use ipnetwork::IpNetwork;
8use mac_address::MacAddress;
9use serde::{Deserialize, Serialize};
10use serde_json::json;
11use tracing::{debug, trace, warn};
12use utoipa::ToSchema;
13
14use crate::error::Error;
15
16#[derive(Serialize, Deserialize, Clone, Debug)]
17pub struct Device {
18 pub id: String,
19 pub mac: MacAddress,
20 pub broadcast_addr: String,
21 pub ip: IpNetwork,
22 pub times: Option<Vec<i64>>,
23}
24
25impl Device {
26 const STORAGE_PATH: &'static str = "devices";
27
28 pub fn setup() -> Result<String, Error> {
29 trace!("check for storage at {}", Self::STORAGE_PATH);
30 let sp = Path::new(Self::STORAGE_PATH);
31 if !sp.exists() {
32 warn!("device storage path doesn't exist, creating it");
33 create_dir_all(Self::STORAGE_PATH)?;
34 };
35
36 debug!("device storage at '{}'", Self::STORAGE_PATH);
37
38 Ok(Self::STORAGE_PATH.to_string())
39 }
40
41 pub fn read(id: &str) -> Result<Self, Error> {
42 trace!(?id, "attempt to read file");
43 let mut file = File::open(format!("{}/{id}.json", Self::STORAGE_PATH))?;
44 let mut buf = String::new();
45 file.read_to_string(&mut buf)?;
46 trace!(?id, ?buf, "read successfully from file");
47
48 let dev = serde_json::from_str(&buf)?;
49 Ok(dev)
50 }
51
52 pub fn write(&self) -> Result<(), Error> {
53 trace!(?self.id, ?self, "attempt to write to file");
54 let mut file = File::create(format!("{}/{}.json", Self::STORAGE_PATH, self.id))?;
55 file.write_all(json!(self).to_string().as_bytes())?;
56 trace!(?self.id, "wrote successfully to file");
57
58 Ok(())
59 }
60}
61
62#[derive(ToSchema)]
63#[schema(as = Device)]
64pub struct DeviceSchema {
65 pub id: String,
66 pub mac: String,
67 pub broadcast_addr: String,
68 pub ip: String,
69 pub times: Option<Vec<i64>>,
70}