aboutsummaryrefslogtreecommitdiff
path: root/src/library.rs
blob: ea0b9ed03f580e12ab9c1de491bb93a8b38d5344 (plain)
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
use crate::metadata::{DirectoryInfo, ItemInfo};
use anyhow::{anyhow, bail, Context, Ok};
use std::{ffi::OsStr, fs::File, path::PathBuf, sync::Arc};

pub struct Library {
    root: Arc<Node>,
}

#[derive(Debug, Clone)]
pub enum Node {
    Directory(Arc<Directory>),
    Item(Arc<Item>),
}

#[derive(Debug, Clone)]
pub struct Directory {
    pub identifier: String,
    pub data: DirectoryInfo,
    pub children: Vec<Arc<Node>>,
}

#[derive(Debug, Clone)]
pub struct Item {
    pub identifier: String,
    pub data: ItemInfo,
}

impl Library {
    pub fn open(path: &str) -> anyhow::Result<Self> {
        Ok(Self {
            root: Node::from_path(path.into()).context("indexing root")?,
        })
    }
    pub fn nested(&self, path: &str) -> anyhow::Result<Arc<Node>> {
        let mut n = self.root.clone();
        if path == "" {
            return Ok(n);
        }
        for seg in path.split("/") {
            n = n
                .get_directory()?
                .child_by_ident(seg)
                .ok_or(anyhow!("does not exist"))?;
        }
        Ok(n)
    }
}

impl Node {
    pub fn get_directory(&self) -> anyhow::Result<&Directory> {
        match self {
            Node::Directory(d) => Ok(d),
            Node::Item(_) => bail!("not a directory"),
        }
    }
    pub fn title(&self) -> &str {
        match self {
            Node::Directory(d) => &d.data.name,
            Node::Item(i) => &i.data.title,
        }
    }
    pub fn identifier(&self) -> &str {
        match self {
            Node::Directory(d) => &d.identifier,
            Node::Item(i) => &i.identifier,
        }
    }
    pub fn from_path(path: PathBuf) -> anyhow::Result<Arc<Node>> {
        if path.is_dir() {
            let mpath = path.join("directory.json");
            let data: DirectoryInfo =
                serde_json::from_reader(File::open(mpath).context("metadata missing")?)?;
            let children = path
                .read_dir()?
                .map(|e| e.unwrap().path())
                .filter(|e| e.extension() != Some(OsStr::new("json")))
                .map(|e| Node::from_path(e.clone()).context(format!("loading {e:?}")))
                .into_iter()
                .collect::<anyhow::Result<Vec<_>>>()?;

            Ok(Node::Directory(Arc::new(Directory {
                children,
                data,
                identifier: path.file_name().unwrap().to_str().unwrap().to_string(),
            }))
            .into())
        } else if path.is_file() {
            let mpath = path.clone().with_extension("metadata.json");
            let datafile = File::open(mpath.clone())
                .context(format!("metadata missing, tried path {mpath:?}"))?;
            let data: ItemInfo = serde_json::from_reader(datafile).context("invalid metadata")?;
            Ok(Node::Item(Arc::new(Item {
                data,
                identifier: path
                    .with_extension("")
                    .file_name()
                    .unwrap()
                    .to_str()
                    .unwrap()
                    .to_string(),
            }))
            .into())
        } else {
            bail!("did somebody really put a fifo or socket in the library?!")
        }
    }
}

impl Directory {
    pub fn child_by_ident(&self, i: &str) -> Option<Arc<Node>> {
        self.children
            .iter()
            .find(|e| e.identifier() == i)
            .map(|e| e.to_owned())
    }
}