capsule_library/library/
init.rs1use std::fs;
2use std::path::Path;
3
4use capsule_core::sidecar::LibraryConfigCbor;
5use capsule_core::sidecar::library_version::{CURRENT_LIBRARY_VERSION, LibraryVersionCbor};
6
7use crate::db::DatabaseDriver;
8use crate::library::error::LibraryError;
9use crate::library::library::Library;
10use crate::library::lock;
11use crate::sidecar_io::{write_library_config, write_library_version};
12
13const SKELETON_DIRS: &[&str] = &[
15 "media",
16 "index",
17 "index/thumbnails",
18 "index/thumbnails/xs",
19 "index/thumbnails/s",
20 "index/thumbnails/m",
21 "index/thumbnails/l",
22 "index/thumbnails/xl",
23 "index/thumbnails/o",
24 "index/meta",
25 "index/transcodes",
26 "index/transcodes/h264",
27 "index/transcodes/live",
28 ".library",
29 ".library/migrations",
30 ".library/trash",
31];
32
33pub fn init_library(root: &Path, name: &str) -> Result<Library, LibraryError> {
39 let root_existed = root.exists();
40 if root_existed {
41 let has_entries = fs::read_dir(root)
42 .map_err(LibraryError::Io)?
43 .next()
44 .is_some();
45 if has_entries {
46 return Err(LibraryError::DirectoryNotEmpty);
47 }
48 }
49
50 let result = init_inner(root, name);
51 if let Err(ref _e) = result
52 && !root_existed
53 {
54 let _ = fs::remove_dir_all(root);
55 }
56 result
57}
58
59fn init_inner(root: &Path, name: &str) -> Result<Library, LibraryError> {
60 for dir in SKELETON_DIRS {
61 fs::create_dir_all(root.join(dir)).map_err(LibraryError::Io)?;
62 }
63
64 let now = now_secs();
65
66 let db_path = root.join("index/library.sqlite");
68 let db = DatabaseDriver::open(&db_path).map_err(LibraryError::Db)?;
69
70 let version_path = root.join(".library/version.cbor");
72 write_library_version(
73 &version_path,
74 &LibraryVersionCbor {
75 version: CURRENT_LIBRARY_VERSION,
76 },
77 )
78 .map_err(|e| LibraryError::Cbor(e.to_string()))?;
79
80 let config = LibraryConfigCbor {
82 schema_version: 1,
83 library_name: name.to_string(),
84 last_opened_at: now,
85 last_scrubbed_at: None,
86 };
87 let config_path = root.join(".library/config.cbor");
88 write_library_config(&config_path, &config).map_err(|e| LibraryError::Cbor(e.to_string()))?;
89
90 lock::try_acquire(root)?;
92
93 Ok(Library::new(root.to_path_buf(), db, config))
94}
95
96fn now_secs() -> i64 {
97 std::time::SystemTime::now()
98 .duration_since(std::time::UNIX_EPOCH)
99 .unwrap_or_default()
100 .as_secs() as i64
101}
102
103#[cfg(test)]
104mod tests;