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
|
/*
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 crate::{database::Database, CONF};
use anyhow::{bail, Context, Ok};
use async_recursion::async_recursion;
use jellycommon::Node;
use log::info;
use std::{ffi::OsStr, fs::File, os::unix::prelude::OsStrExt, path::PathBuf, sync::LazyLock};
use tokio::sync::Semaphore;
static IMPORT_SEM: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(1));
pub async fn import(db: &Database) -> anyhow::Result<()> {
info!("clearing node tree");
let permit = IMPORT_SEM.try_acquire()?;
{
db.node.clear()?;
info!("importing...");
import_path(CONF.library_path.clone(), db, None)
.await
.context("indexing")?;
info!("import completed");
}
drop(permit);
Ok(())
}
#[async_recursion]
pub async fn import_path(
path: PathBuf,
db: &Database,
parent: Option<String>,
) -> anyhow::Result<Vec<String>> {
if path.is_dir() {
let mpath = path.join("directory.json");
let children_paths = path.read_dir()?.map(Result::unwrap).filter_map(|e| {
if e.path().extension() == Some(&OsStr::from_bytes(b"jelly"))
|| e.metadata().unwrap().is_dir()
{
Some(e.path())
} else {
None
}
});
let identifier = path.file_name().unwrap().to_str().unwrap().to_string();
let mut children_ids = Vec::new();
for p in children_paths {
children_ids.extend(import_path(p, db, Some(identifier.clone())).await?)
}
if mpath.exists() {
let mut data: Node =
serde_json::from_reader(File::open(mpath).context("metadata missing")?)?;
data.public.children = children_ids;
data.public.parent = parent;
info!("insert {identifier}");
db.node.insert(&identifier, &data)?;
Ok(vec![identifier])
} else {
Ok(children_ids)
}
} else if path.is_file() {
info!("loading item {path:?}");
let datafile = File::open(path.clone()).context("cant load metadata")?;
let mut data: Node = serde_json::from_reader(datafile).context("invalid metadata")?;
let identifier = path
.file_name()
.unwrap()
.to_str()
.unwrap()
.strip_suffix(".jelly")
.unwrap()
.to_string();
info!("insert {identifier}");
data.public.parent = parent;
db.node.insert(&identifier, &data)?;
Ok(vec![identifier])
} else {
bail!("did somebody really put a fifo or socket in the library?!")
}
}
|