subx_cli/lib.rs
1//! SubX: Intelligent Subtitle Processing Library
2//!
3//! SubX is a comprehensive Rust library for intelligent subtitle file processing,
4//! featuring AI-powered matching, format conversion, audio synchronization,
5//! and advanced encoding detection capabilities.
6//!
7//! # Key Features
8//!
9//! - **AI-Powered Matching**: Intelligent subtitle file matching and renaming
10//! - **Format Conversion**: Support for multiple subtitle formats (SRT, ASS, VTT, etc.)
11//! - **Audio Synchronization**: Advanced audio-subtitle timing adjustment
12//! - **Encoding Detection**: Automatic character encoding detection and conversion
13//! - **Parallel Processing**: High-performance batch operations
14//! - **Configuration Management**: Flexible multi-source configuration system
15//!
16//! # Architecture Overview
17//!
18//! The library is organized into several key modules:
19//!
20//! - [`cli`] - Command-line interface and argument parsing
21//! - [`commands`] - Implementation of all SubX commands
22//! - [`config`] - Configuration management and validation
23//! - [`core`] - Core processing engines (formats, matching, sync)
24//! - [`error`] - Comprehensive error handling system
25//! - [`services`] - External service integrations (AI, audio processing)
26//!
27//! # Quick Start
28//!
29//! ```rust,no_run
30//! use subx_cli::config::{TestConfigService, ConfigService};
31//!
32//! // Create a configuration service
33//! let config_service = TestConfigService::with_defaults();
34//! let config = config_service.config();
35//!
36//! // Use the configuration for processing...
37//! ```
38//!
39//! # Error Handling
40//!
41//! All operations return a [`Result<T>`] type that wraps [`error::SubXError`]:
42//!
43//! ```rust
44//! use subx_cli::{Result, error::SubXError};
45//!
46//! fn example_operation() -> Result<String> {
47//! // This could fail with various error types
48//! Err(SubXError::config("Missing configuration"))
49//! }
50//! ```
51//!
52//! # Configuration
53//!
54//! SubX supports dependency injection-based configuration:
55//!
56//! ```rust,no_run
57//! use subx_cli::config::{TestConfigService, Config};
58//!
59//! // Create configuration service with AI settings
60//! let config_service = TestConfigService::with_ai_settings("openai", "gpt-4.1");
61//! let config = config_service.config();
62//!
63//! // Access configuration values
64//! println!("AI Provider: {}", config.ai.provider);
65//! println!("AI Model: {}", config.ai.model);
66//! ```
67//!
68//! # Performance Considerations
69//!
70//! - Use [`core::parallel`] for batch operations on large file sets
71//! - Configure appropriate cache settings for repeated operations
72//! - Consider memory usage when processing large audio files
73//!
74//! # Thread Safety
75//!
76//! The library is designed to be thread-safe where appropriate:
77//! - Configuration manager uses `Arc<RwLock<T>>` for shared state
78//! - File operations include rollback capabilities for atomicity
79//! - Parallel processing uses safe concurrency patterns
80//!
81//! # Feature Flags
82//!
83//! SubX supports several optional features:
84//! ```text
85//! - ai - AI service integrations (default)
86//! - audio - Audio processing capabilities (default)
87//! - parallel - Parallel processing support (default)
88//! ```
89
90#![allow(
91 clippy::new_without_default,
92 clippy::manual_clamp,
93 clippy::useless_vec,
94 clippy::items_after_test_module,
95 clippy::needless_borrow,
96 clippy::uninlined_format_args,
97 clippy::collapsible_if
98)]
99#![warn(missing_docs)]
100#![warn(rustdoc::missing_crate_level_docs)]
101
102/// Library version string.
103///
104/// This constant provides the current version of the SubX library,
105/// automatically populated from `Cargo.toml` at compile time.
106///
107/// # Examples
108///
109/// ```rust
110/// use subx_cli::VERSION;
111///
112/// println!("SubX version: {}", VERSION);
113/// ```
114pub const VERSION: &str = env!("CARGO_PKG_VERSION");
115
116pub mod cli;
117pub mod commands;
118pub mod config;
119pub use config::Config;
120// Re-export new configuration service system
121pub use config::{
122 ConfigService, EnvironmentProvider, ProductionConfigService, SystemEnvironmentProvider,
123 TestConfigBuilder, TestConfigService, TestEnvironmentProvider,
124};
125pub mod core;
126pub mod error;
127/// Convenient type alias for `Result<T, SubXError>`.
128///
129/// This type alias simplifies error handling throughout the SubX library
130/// by providing a default error type for all fallible operations.
131pub type Result<T> = error::SubXResult<T>;
132
133pub mod services;
134
135/// Main application structure with dependency injection support.
136///
137/// The `App` struct provides a programmatic interface to SubX functionality,
138/// designed for embedding SubX in other Rust applications or for advanced
139/// use cases requiring fine-grained control over configuration and execution.
140///
141/// # Use Cases
142///
143/// - **Embedding**: Use SubX as a library component in larger applications
144/// - **Testing**: Programmatic testing of SubX functionality with custom configurations
145/// - **Automation**: Scripted execution of SubX operations without shell commands
146/// - **Custom Workflows**: Building complex workflows that combine multiple SubX operations
147///
148/// # vs CLI Interface
149///
150/// | Feature | CLI (`subx` command) | App (Library API) |
151/// |---------|---------------------|-------------------|
152/// | Usage | Command line tool | Embedded in Rust code |
153/// | Config | Files + Environment | Programmatic injection |
154/// | Output | Terminal/stdout | Programmatic control |
155/// | Error Handling | Exit codes | Result types |
156///
157/// # Examples
158///
159/// ## Basic Usage
160///
161/// ```rust,no_run
162/// use subx_cli::{App, config::ProductionConfigService};
163/// use std::sync::Arc;
164///
165/// # async fn example() -> subx_cli::Result<()> {
166/// let config_service = Arc::new(ProductionConfigService::new()?);
167/// let app = App::new(config_service);
168///
169/// // Execute operations programmatically
170/// app.match_files("/movies", true).await?; // dry run
171/// app.convert_files("/subs", "srt", Some("/output")).await?;
172/// # Ok(())
173/// # }
174/// ```
175///
176/// ## With Custom Configuration
177///
178/// ```rust,no_run
179/// use subx_cli::{App, config::{TestConfigService, Config}};
180/// use std::sync::Arc;
181///
182/// # async fn example() -> subx_cli::Result<()> {
183/// let mut config_service = TestConfigService::with_ai_settings("openai", "gpt-4");
184///
185/// let app = App::new(Arc::new(config_service));
186/// app.match_files("/path", false).await?;
187/// # Ok(())
188/// # }
189/// ```
190pub struct App {
191 config_service: std::sync::Arc<dyn config::ConfigService>,
192}
193
194impl App {
195 /// Create a new application instance with the provided configuration service.
196 ///
197 /// # Arguments
198 ///
199 /// * `config_service` - The configuration service to use
200 ///
201 /// # Examples
202 ///
203 /// ```rust,no_run
204 /// use subx_cli::{App, config::TestConfigService};
205 /// use std::sync::Arc;
206 ///
207 /// let config_service = Arc::new(TestConfigService::with_defaults());
208 /// let app = App::new(config_service);
209 /// ```
210 pub fn new(config_service: std::sync::Arc<dyn config::ConfigService>) -> Self {
211 Self { config_service }
212 }
213
214 /// Create a new application instance with the production configuration service.
215 ///
216 /// This is the default way to create an application instance for production use.
217 ///
218 /// # Examples
219 ///
220 /// ```rust,no_run
221 /// use subx_cli::App;
222 ///
223 /// # async fn example() -> subx_cli::Result<()> {
224 /// let app = App::new_with_production_config()?;
225 /// // Ready to use with production configuration
226 /// # Ok(())
227 /// # }
228 /// ```
229 ///
230 /// # Errors
231 ///
232 /// Returns an error if the production configuration service cannot be created.
233 pub fn new_with_production_config() -> Result<Self> {
234 let config_service = std::sync::Arc::new(config::ProductionConfigService::new()?);
235 Ok(Self::new(config_service))
236 }
237
238 /// Run the application with command-line argument parsing.
239 ///
240 /// This method provides a programmatic way to run SubX with CLI-style
241 /// arguments, useful for embedding SubX in other Rust applications.
242 ///
243 /// # Examples
244 ///
245 /// ```rust,no_run
246 /// use subx_cli::{App, config::ProductionConfigService};
247 /// use std::sync::Arc;
248 ///
249 /// # async fn example() -> subx_cli::Result<()> {
250 /// let config_service = Arc::new(ProductionConfigService::new()?);
251 /// let app = App::new(config_service);
252 ///
253 /// // This parses std::env::args() just like the CLI
254 /// app.run().await?;
255 /// # Ok(())
256 /// # }
257 /// ```
258 ///
259 /// # Errors
260 ///
261 /// Returns an error if command execution fails.
262 pub async fn run(&self) -> Result<()> {
263 let cli = <cli::Cli as clap::Parser>::parse();
264 self.handle_command(cli.command).await
265 }
266
267 /// Handle a specific command with the current configuration.
268 ///
269 /// This method allows programmatic execution of specific SubX commands
270 /// without parsing command-line arguments.
271 ///
272 /// # Examples
273 ///
274 /// ```rust,no_run
275 /// use subx_cli::{App, cli::{Commands, MatchArgs}, config::TestConfigService};
276 /// use std::sync::Arc;
277 ///
278 /// # async fn example() -> subx_cli::Result<()> {
279 /// let config_service = Arc::new(TestConfigService::with_defaults());
280 /// let app = App::new(config_service);
281 ///
282 /// let match_args = MatchArgs {
283 /// path: Some("/path/to/files".into()),
284 /// input_paths: vec![],
285 /// dry_run: true,
286 /// confidence: 80,
287 /// recursive: false,
288 /// backup: false,
289 /// copy: false,
290 /// move_files: false,
291 /// };
292 ///
293 /// app.handle_command(Commands::Match(match_args)).await?;
294 /// # Ok(())
295 /// # }
296 /// ```
297 ///
298 /// # Arguments
299 ///
300 /// * `command` - The command to execute
301 ///
302 /// # Errors
303 ///
304 /// Returns an error if command execution fails.
305 pub async fn handle_command(&self, command: cli::Commands) -> Result<()> {
306 // Use the centralized dispatcher to eliminate code duplication
307 crate::commands::dispatcher::dispatch_command(command, self.config_service.clone()).await
308 }
309
310 /// Execute a match operation programmatically.
311 ///
312 /// This is a convenience method for programmatic usage without
313 /// needing to construct the Commands enum manually.
314 ///
315 /// # Examples
316 ///
317 /// ```rust,no_run
318 /// use subx_cli::{App, config::TestConfigService};
319 /// use std::sync::Arc;
320 ///
321 /// # async fn example() -> subx_cli::Result<()> {
322 /// let config_service = Arc::new(TestConfigService::with_defaults());
323 /// let app = App::new(config_service);
324 ///
325 /// // Match files programmatically
326 /// app.match_files("/path/to/files", true).await?; // dry_run = true
327 /// # Ok(())
328 /// # }
329 /// ```
330 ///
331 /// # Arguments
332 ///
333 /// * `input_path` - Path to the directory or file to process
334 /// * `dry_run` - Whether to perform a dry run (no actual changes)
335 ///
336 /// # Errors
337 ///
338 /// Returns an error if the match operation fails.
339 pub async fn match_files(&self, input_path: &str, dry_run: bool) -> Result<()> {
340 let args = cli::MatchArgs {
341 path: Some(input_path.into()),
342 input_paths: vec![],
343 dry_run,
344 confidence: 80,
345 recursive: false,
346 backup: false,
347 copy: false,
348 move_files: false,
349 };
350 self.handle_command(cli::Commands::Match(args)).await
351 }
352
353 /// Convert subtitle files programmatically.
354 ///
355 /// # Examples
356 ///
357 /// ```rust,no_run
358 /// use subx_cli::{App, config::TestConfigService};
359 /// use std::sync::Arc;
360 ///
361 /// # async fn example() -> subx_cli::Result<()> {
362 /// let config_service = Arc::new(TestConfigService::with_defaults());
363 /// let app = App::new(config_service);
364 ///
365 /// // Convert to SRT format
366 /// app.convert_files("/path/to/subtitles", "srt", Some("/output/path")).await?;
367 /// # Ok(())
368 /// # }
369 /// ```
370 ///
371 /// # Arguments
372 ///
373 /// * `input_path` - Path to subtitle files to convert
374 /// * `output_format` - Target format ("srt", "ass", "vtt", etc.)
375 /// * `output_path` - Optional output directory path
376 ///
377 /// # Errors
378 ///
379 /// Returns an error if the conversion fails.
380 pub async fn convert_files(
381 &self,
382 input_path: &str,
383 output_format: &str,
384 output_path: Option<&str>,
385 ) -> Result<()> {
386 let format = match output_format.to_lowercase().as_str() {
387 "srt" => cli::OutputSubtitleFormat::Srt,
388 "ass" => cli::OutputSubtitleFormat::Ass,
389 "vtt" => cli::OutputSubtitleFormat::Vtt,
390 "sub" => cli::OutputSubtitleFormat::Sub,
391 _ => {
392 return Err(error::SubXError::CommandExecution(format!(
393 "Unsupported output format: {output_format}. Supported formats: srt, ass, vtt, sub"
394 )));
395 }
396 };
397
398 let args = cli::ConvertArgs {
399 input: Some(input_path.into()),
400 input_paths: vec![],
401 recursive: false,
402 format: Some(format),
403 output: output_path.map(Into::into),
404 keep_original: false,
405 encoding: "utf-8".to_string(),
406 };
407 self.handle_command(cli::Commands::Convert(args)).await
408 }
409
410 /// Synchronize subtitle files programmatically.
411 ///
412 /// # Examples
413 ///
414 /// ```rust,no_run
415 /// use subx_cli::{App, config::TestConfigService};
416 /// use std::sync::Arc;
417 ///
418 /// # async fn example() -> subx_cli::Result<()> {
419 /// let config_service = Arc::new(TestConfigService::with_defaults());
420 /// let app = App::new(config_service);
421 ///
422 /// // Synchronize using VAD method
423 /// app.sync_files("/path/to/video.mp4", "/path/to/subtitle.srt", "vad").await?;
424 /// # Ok(())
425 /// # }
426 /// ```
427 ///
428 /// # Arguments
429 ///
430 /// * `video_path` - Path to video file for audio analysis
431 /// * `subtitle_path` - Path to subtitle file to synchronize
432 /// * `method` - Synchronization method ("vad", "manual")
433 ///
434 /// # Errors
435 ///
436 /// Returns an error if synchronization fails.
437 pub async fn sync_files(
438 &self,
439 video_path: &str,
440 subtitle_path: &str,
441 method: &str,
442 ) -> Result<()> {
443 let sync_method = match method.to_lowercase().as_str() {
444 "vad" => Some(cli::SyncMethodArg::Vad),
445 "manual" => Some(cli::SyncMethodArg::Manual),
446 _ => {
447 return Err(error::SubXError::CommandExecution(format!(
448 "Unsupported sync method: {method}. Supported methods: vad, manual"
449 )));
450 }
451 };
452
453 let args = cli::SyncArgs {
454 positional_paths: Vec::new(),
455 video: Some(video_path.into()),
456 subtitle: Some(subtitle_path.into()),
457 input_paths: vec![],
458 recursive: false,
459 offset: None,
460 method: sync_method,
461 window: 30,
462 vad_sensitivity: None,
463 output: None,
464 verbose: false,
465 dry_run: false,
466 force: false,
467 batch: None,
468 };
469 self.handle_command(cli::Commands::Sync(args)).await
470 }
471
472 /// Synchronize subtitle files with manual offset.
473 ///
474 /// # Examples
475 ///
476 /// ```rust,no_run
477 /// use subx_cli::{App, config::TestConfigService};
478 /// use std::sync::Arc;
479 ///
480 /// # async fn example() -> subx_cli::Result<()> {
481 /// let config_service = Arc::new(TestConfigService::with_defaults());
482 /// let app = App::new(config_service);
483 ///
484 /// // Apply +2.5 second offset to subtitles
485 /// app.sync_files_with_offset("/path/to/subtitle.srt", 2.5).await?;
486 /// # Ok(())
487 /// # }
488 /// ```
489 ///
490 /// # Arguments
491 ///
492 /// * `subtitle_path` - Path to subtitle file to synchronize
493 /// * `offset` - Time offset in seconds (positive delays, negative advances)
494 ///
495 /// # Errors
496 ///
497 /// Returns an error if synchronization fails.
498 pub async fn sync_files_with_offset(&self, subtitle_path: &str, offset: f32) -> Result<()> {
499 let args = cli::SyncArgs {
500 positional_paths: Vec::new(),
501 video: None,
502 subtitle: Some(subtitle_path.into()),
503 input_paths: vec![],
504 recursive: false,
505 offset: Some(offset),
506 method: None,
507 window: 30,
508 vad_sensitivity: None,
509 output: None,
510 verbose: false,
511 dry_run: false,
512 force: false,
513 batch: None,
514 };
515 self.handle_command(cli::Commands::Sync(args)).await
516 }
517
518 /// Get a reference to the configuration service.
519 ///
520 /// This allows access to the configuration service for testing or
521 /// advanced use cases.
522 pub fn config_service(&self) -> &std::sync::Arc<dyn config::ConfigService> {
523 &self.config_service
524 }
525
526 /// Get the current configuration.
527 ///
528 /// This is a convenience method that retrieves the configuration
529 /// from the configured service.
530 ///
531 /// # Errors
532 ///
533 /// Returns an error if configuration loading fails.
534 pub fn get_config(&self) -> Result<config::Config> {
535 self.config_service.get_config()
536 }
537}