aboutsummaryrefslogtreecommitdiff
path: root/server/src/library.rs
blob: 258569e36e91678878ad1a59434350e43df166f7 (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
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
/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2023 metamuffin <metamuffin.org>
*/
use anyhow::{anyhow, bail, Context, Ok};
use jellycommon::{DirectoryInfo, ItemInfo};
use log::info;
use std::{
    fs::File,
    path::{Path, PathBuf},
    sync::Arc,
};

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

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

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

#[derive(Debug, Clone)]
pub struct Item {
    pub fs_path: PathBuf,
    pub lib_path: PathBuf,
    pub identifier: String,
    pub info: ItemInfo,
}

impl Library {
    pub fn open(path: &Path) -> anyhow::Result<Self> {
        Ok(Self {
            root: Node::from_path(path.to_path_buf(), PathBuf::new(), true)
                .context("indexing root")?
                .ok_or(anyhow!("root need directory.json"))?,
        })
    }
    pub fn nested_path(&self, path: &Path) -> anyhow::Result<Arc<Node>> {
        self.nested(path.to_str().unwrap())
    }
    pub fn nested(&self, path: &str) -> anyhow::Result<Arc<Node>> {
        let mut n = self.root.clone();
        if path.is_empty() {
            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<Arc<Directory>> {
        match self {
            Node::Directory(d) => Ok(d.clone()),
            Node::Item(_) => bail!("not a directory"),
        }
    }
    pub fn get_item(&self) -> anyhow::Result<Arc<Item>> {
        match self {
            Node::Item(i) => Ok(i.clone()),
            Node::Directory(_) => bail!("not an item"),
        }
    }
    pub fn title(&self) -> &str {
        match self {
            Node::Directory(d) => &d.data.name,
            Node::Item(i) => &i.info.title,
        }
    }
    pub fn identifier(&self) -> &str {
        match self {
            Node::Directory(d) => &d.identifier,
            Node::Item(i) => &i.identifier,
        }
    }
    pub fn from_path(
        path: PathBuf,
        mut lib_path: PathBuf,
        root: bool,
    ) -> anyhow::Result<Option<Arc<Node>>> {
        if path.is_dir() {
            let mpath = path.join("directory.json");
            if !mpath.exists() {
                return Ok(None);
            }
            let data: DirectoryInfo =
                serde_json::from_reader(File::open(mpath).context("metadata missing")?)?;

            let identifier = path.file_name().unwrap().to_str().unwrap().to_string();
            if !root {
                lib_path = lib_path.join(identifier.clone());
            }

            let children = path
                .read_dir()?
                .filter_map(|e| {
                    let e = e.unwrap();
                    if (e.path().extension().is_none() || e.metadata().unwrap().is_dir())
                        && !e.path().ends_with("directory.json")
                    {
                        Some(e.path())
                    } else {
                        None
                    }
                })
                .filter_map(|e| {
                    Node::from_path(e.clone(), lib_path.clone(), false)
                        .context(format!("loading {e:?}"))
                        .transpose()
                })
                .collect::<anyhow::Result<Vec<_>>>()?;

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

impl Item {
    pub fn path(&self) -> String {
        self.lib_path.to_str().unwrap().to_string()
    }
}

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