1use crate::{2 cache,3 commands::error::{internal_error, state_lock_error, CommandError, CommandResult},4 config::{self, AppConfig, RegisteredLibrary},5 library::error::LibraryError,6 library_root::LibraryRoot,7 AppState,8};9use serde::Serialize;10use std::{11 fs,12 path::{Path, PathBuf},
13};
14use tauri::State;
15
16#[derive(Debug, Clone, Serialize)]
17pub struct LibraryRegistrySnapshot {
18 pub active_library_id: Option<String>,
19 pub libraries: Vec<RegisteredLibrary>,
20}
21
22fn canonical_path_string(path: &Path) -> String {
23 fs::canonicalize(path)
24 .unwrap_or_else(|_| path.to_path_buf())
25 .display()
26 .to_string()
27}
28
29fn load_app_config(app_data_dir: &Path) -> CommandResult<AppConfig> {
30 Ok(config::load_config(app_data_dir)
31 .map_err(internal_error)?
32 .unwrap_or_default())
33}
34
35fn persist_app_config(app_data_dir: &Path, config: &AppConfig) -> CommandResult<()> {
36 config::save_config(app_data_dir, config).map_err(internal_error)
37}
38
39fn update_library_display_name(
40 app_data_dir: &Path,
41 library_id: &str,
42 display_name: &str,
43) -> CommandResult<LibraryRegistrySnapshot> {
44 let mut config = load_app_config(app_data_dir)?;
45 let Some(library) = config
46 .libraries
47 .iter_mut()
48 .find(|entry| entry.id() == library_id)
49 else {
50 return Err(CommandError::from(LibraryError::Internal(format!(
51 "library {library_id} was not found"
52 ))));
53 };
54
55 match library {
56 RegisteredLibrary::Local {
57 display_name: name, ..
58 }
59 | RegisteredLibrary::Remote {
60 display_name: name, ..
61 } => {
62 *name = display_name.to_owned();
63 }
64 }
65
66 persist_app_config(app_data_dir, &config)?;
67
68 Ok(LibraryRegistrySnapshot {
69 active_library_id: config.active_library_id.clone(),
70 libraries: config.libraries.clone(),
71 })
72}
73
74fn delete_library_data(app_data_dir: &Path, library: &RegisteredLibrary) -> CommandResult<()> {
75 match library {
76 RegisteredLibrary::Local { root_path, .. } => {
77 if Path::new(root_path).exists() {
78 fs::remove_dir_all(root_path).map_err(|error| {
79 CommandError::from(LibraryError::Internal(format!(
80 "failed to delete {root_path}: {error}"
81 )))
82 })?;
83 }
84 }
85 RegisteredLibrary::Remote { .. } => {
86 crate::remote::delete_remote_library_root(app_data_dir, library)?;
87 if let Some(working_copy_root) = library.working_copy_root() {
88 if working_copy_root.exists() {
89 fs::remove_dir_all(&working_copy_root).map_err(|error| {
90 CommandError::from(LibraryError::Internal(format!(
91 "failed to delete {}: {error}",
92 working_copy_root.display()
93 )))
94 })?;
95 }
96 }
97 }
98 }
99
100 Ok(())
101}
102
103fn upsert_library(config: &mut AppConfig, library: RegisteredLibrary) {
104 if let Some(existing) = config
105 .libraries
106 .iter_mut()
107 .find(|entry| entry.id() == library.id())
108 {
109 *existing = library;
110 } else {
111 config.libraries.push(library);
112 }
113}
114
115fn set_active_library(config: &mut AppConfig, library_id: String) {
116 config.active_library_id = Some(library_id);
117 config.library_path = None;
118}
119
120fn store_active_library(
121 state: &State<'_, AppState>,
122 config: &mut AppConfig,
123 library: LibraryRoot,
124) -> CommandResult<()> {
125 let mut guard = state
126 .shell
127 .library
128 .lock()
129 .map_err(|_| state_lock_error("library lock was poisoned"))?;
130 *guard = Some(library);
131 config.library_path = None;
132 Ok(())
133}
134
135fn clear_library_scoped_runtime_state(state: &State<'_, AppState>) -> CommandResult<()> {
136 {
137 let mut playback = state
138 .playback
139 .playback
140 .lock()
141 .map_err(|_| state_lock_error("playback controller lock was poisoned"))?;
142 playback.clear_track();
143 }
144 {
145 let mut cdg_state = state
146 .playback
147 .cdg_state
148 .lock()
149 .map_err(|_| state_lock_error("CDG state lock was poisoned"))?;
150 *cdg_state = None;
151 }
152 {
153 let mut upload_statuses = state
154 .remote
155 .remote_upload_statuses
156 .lock()
157 .map_err(|_| state_lock_error("remote upload status lock was poisoned"))?;
158 upload_statuses.clear();
159 }
160 Ok(())
161}
162
163fn register_library(
164 state: &State<'_, AppState>,
165 app_data_dir: &Path,
166 library: RegisteredLibrary,
167 root: LibraryRoot,
168) -> CommandResult<LibraryRegistrySnapshot> {
169 let db_path = root.database_path();
170 cache::initialize_library_database(&db_path)
171 .map_err(|e| CommandError::from(LibraryError::DatabaseUnavailable(e.to_string())))?;
172
173 let mut config = load_app_config(app_data_dir)?;
174 upsert_library(&mut config, library.clone());
175 set_active_library(&mut config, library.id().to_owned());
176 persist_app_config(app_data_dir, &config)?;
177
178 store_active_library(state, &mut config, root)?;
179 {
180 let mut upload_statuses = state
181 .remote
182 .remote_upload_statuses
183 .lock()
184 .map_err(|_| state_lock_error("remote upload status lock was poisoned"))?;
185 upload_statuses.clear();
186 }
187
188 Ok(LibraryRegistrySnapshot {
189 active_library_id: config.active_library_id.clone(),
190 libraries: config.libraries.clone(),
191 })
192}
193
194fn activate_library(
195 state: &State<'_, AppState>,
196 app_data_dir: &Path,
197 library_id: &str,
198) -> CommandResult<LibraryRegistrySnapshot> {
199 let mut config = load_app_config(app_data_dir)?;
200 let library = config
201 .libraries
202 .iter()
203 .find(|entry| entry.id() == library_id)
204 .cloned()
205 .ok_or_else(|| {
206 CommandError::from(LibraryError::Internal(format!(
207 "library {library_id} was not found"
208 )))
209 })?;
210
211 let root_path = library.working_copy_root().ok_or_else(|| {
212 CommandError::from(LibraryError::Internal(
213 "remote repository is missing a cached working copy".to_string(),
214 ))
215 })?;
216 let lib = LibraryRoot::open(&root_path).map_err(internal_error)?;
217 let db_path = lib.database_path();
218 cache::initialize_library_database(&db_path)
219 .map_err(|e| CommandError::from(LibraryError::DatabaseUnavailable(e.to_string())))?;
220
221 clear_library_scoped_runtime_state(state)?;
222
223 set_active_library(&mut config, library.id().to_owned());
224 persist_app_config(app_data_dir, &config)?;
225 store_active_library(state, &mut config, lib)?;
226
227 Ok(LibraryRegistrySnapshot {
228 active_library_id: config.active_library_id.clone(),
229 libraries: config.libraries.clone(),
230 })
231}
232
233#[tauri::command]
234pub fn create_library(
235 state: State<'_, AppState>,
236 path: String,
237) -> CommandResult<LibraryRegistrySnapshot> {
238 let lib_path = PathBuf::from(&path);
239
240 let lib = LibraryRoot::create(&lib_path).map_err(internal_error)?;
241 let canonical_root = canonical_path_string(lib.root());
242 let library = RegisteredLibrary::local(
243 canonical_root.clone(),
244 config::library_display_name(&canonical_root),
245 );
246
247 register_library(&state, &state.shell.app_data_dir, library, lib)
248}
249
250#[tauri::command]
251pub fn open_library(
252 state: State<'_, AppState>,
253 path: String,
254) -> CommandResult<LibraryRegistrySnapshot> {
255 let lib_path = PathBuf::from(&path);
256
257 let lib = LibraryRoot::open(&lib_path).map_err(internal_error)?;
258 let canonical_root = canonical_path_string(lib.root());
259 let library = RegisteredLibrary::local(
260 canonical_root.clone(),
261 config::library_display_name(&canonical_root),
262 );
263
264 register_library(&state, &state.shell.app_data_dir, library, lib)
265}
266
267#[tauri::command]
268pub fn switch_library(
269 state: State<'_, AppState>,
270 library_id: String,
271) -> CommandResult<LibraryRegistrySnapshot> {
272 activate_library(&state, &state.shell.app_data_dir, &library_id)
273}
274
275#[tauri::command]
276pub fn get_library_path(state: State<'_, AppState>) -> CommandResult<Option<String>> {
277 let guard = state
278 .shell
279 .library
280 .lock()
281 .map_err(|_| state_lock_error("library lock was poisoned"))?;
282
283 Ok(guard
284 .as_ref()
285 .map(|lib: &LibraryRoot| canonical_path_string(lib.root())))
286}
287
288#[tauri::command]
289pub fn get_library_registry(state: State<'_, AppState>) -> CommandResult<LibraryRegistrySnapshot> {
290 // Use the resolved shell app-data path (respects OPENKARA_APP_DATA_DIR under
291 // automation-smoke). Tauri's path().app_data_dir() ignores that override and
292 // makes the frontend think no library is registered.
293 let config = load_app_config(&state.shell.app_data_dir)?;
294
295 Ok(LibraryRegistrySnapshot {
296 active_library_id: config.active_library_id.clone(),
297 libraries: config.libraries.clone(),
298 })
299}
300
301#[tauri::command]
302pub fn get_active_library(state: State<'_, AppState>) -> CommandResult<Option<RegisteredLibrary>> {
303 let config = load_app_config(&state.shell.app_data_dir)?;
304
305 Ok(config.active_library().cloned())
306}
307
308#[tauri::command]
309pub fn remove_library(
310 state: State<'_, AppState>,
311 library_id: String,
312) -> CommandResult<LibraryRegistrySnapshot> {
313 let app_data_dir = state.shell.app_data_dir.clone();
314 let mut config = load_app_config(&app_data_dir)?;
315 let removed_active = config.active_library_id.as_deref() == Some(library_id.as_str());
316 let removed_libraries: Vec<_> = config
317 .libraries
318 .iter()
319 .filter(|library| library.id() == library_id)
320 .cloned()
321 .collect();
322 config
323 .libraries
324 .retain(|library| library.id() != library_id);
325
326 for library in &removed_libraries {
327 crate::remote::remove_remote_library_credentials(&app_data_dir, library)?;
328 }
329
330 if removed_active {
331 config.active_library_id = config
332 .libraries
333 .first()
334 .map(|library| library.id().to_owned());
335 }
336
337 persist_app_config(&app_data_dir, &config)?;
338
339 if config.active_library_id.is_none() {
340 let mut guard = state
341 .shell
342 .library
343 .lock()
344 .map_err(|_| state_lock_error("library lock was poisoned"))?;
345 *guard = None;
346 clear_library_scoped_runtime_state(&state)?;
347 } else if removed_active {
348 activate_library(
349 &state,
350 &app_data_dir,
351 config.active_library_id.as_deref().unwrap_or_default(),
352 )?;
353 }
354
355 Ok(LibraryRegistrySnapshot {
356 active_library_id: config.active_library_id.clone(),
357 libraries: config.libraries.clone(),
358 })
359}
360
361#[tauri::command]
362pub fn rename_library(
363 state: State<'_, AppState>,
364 library_id: String,
365 display_name: String,
366) -> CommandResult<LibraryRegistrySnapshot> {
367 update_library_display_name(&state.shell.app_data_dir, &library_id, &display_name)
368}
369
370#[tauri::command]
371pub fn delete_library(
372 state: State<'_, AppState>,
373 library_id: String,
374) -> CommandResult<LibraryRegistrySnapshot> {
375 let app_data_dir = state.shell.app_data_dir.clone();
376 let config = load_app_config(&app_data_dir)?;
377 let Some(library) = config
378 .libraries
379 .iter()
380 .find(|entry| entry.id() == library_id)
381 .cloned()
382 else {
383 return Err(CommandError::from(LibraryError::Internal(format!(
384 "library {library_id} was not found"
385 ))));
386 };
387
388 delete_library_data(&app_data_dir, &library)?;
389 remove_library(state, library_id)
390}
391
392#[cfg(test)]
393mod tests {
394 use super::*;
395
396 #[test]
397 fn register_local_library_sets_active_library() {
398 let mut config = AppConfig::default();
399 let library = RegisteredLibrary::local("/tmp/library".to_owned(), "library".to_owned());
400 upsert_library(&mut config, library.clone());
401 set_active_library(&mut config, library.id().to_owned());
402 assert_eq!(config.active_library_id.as_deref(), Some(library.id()));
403 assert_eq!(config.libraries.len(), 1);
404 }
405
406 #[test]
407 fn register_library_replaces_existing_entry_with_same_id() {
408 let mut config = AppConfig::default();
409 let first = RegisteredLibrary::local("/tmp/library".to_owned(), "one".to_owned());
410 let second = RegisteredLibrary::local("/tmp/library".to_owned(), "two".to_owned());
411 upsert_library(&mut config, first);
412 upsert_library(&mut config, second.clone());
413 assert_eq!(config.libraries.len(), 1);
414 assert_eq!(config.libraries[0].display_name(), second.display_name());
415 }
416}
417