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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
//! Template system for dynamic file naming and configuration
pub mod engine;
pub mod functions;
pub mod variables;
use crate::error::Result;
use engine::TemplateEngine;
use std::collections::HashMap;
use std::path::Path;
/// Template context with variables
#[derive(Debug, Clone)]
pub struct TemplateContext {
variables: HashMap<String, String>,
}
impl TemplateContext {
/// Create a new template context
#[must_use]
pub fn new() -> Self {
Self {
variables: HashMap::new(),
}
}
/// Set a variable
pub fn set(&mut self, key: String, value: String) {
self.variables.insert(key, value);
}
/// Get a variable
#[must_use]
pub fn get(&self, key: &str) -> Option<&String> {
self.variables.get(key)
}
/// Load variables from a file
///
/// # Arguments
///
/// * `path` - Path to the file
///
/// # Errors
///
/// Returns an error if loading fails
pub fn from_file(&mut self, path: &Path) -> Result<()> {
// Extract file properties
if let Some(filename) = path.file_name() {
self.set(
"filename".to_string(),
filename.to_string_lossy().to_string(),
);
}
if let Some(stem) = path.file_stem() {
self.set("stem".to_string(), stem.to_string_lossy().to_string());
}
if let Some(extension) = path.extension() {
self.set(
"extension".to_string(),
extension.to_string_lossy().to_string(),
);
}
if let Some(parent) = path.parent() {
self.set(
"directory".to_string(),
parent.to_string_lossy().to_string(),
);
}
// File metadata
if let Ok(metadata) = std::fs::metadata(path) {
self.set("size".to_string(), metadata.len().to_string());
if let Ok(modified) = metadata.modified() {
if let Ok(datetime) = modified.duration_since(std::time::UNIX_EPOCH) {
self.set("modified".to_string(), datetime.as_secs().to_string());
}
}
}
Ok(())
}
/// Load media properties from a file using `oximedia-metadata`.
///
/// Reads the file at `path` and populates template variables using
/// [`oximedia_metadata::media_metadata::ID3Parser`] for audio files and
/// [`oximedia_metadata::media_metadata::XmpParser`] for sidecar XMP, plus
/// high-level fields from [`oximedia_metadata::media_metadata::MediaMetadata`].
///
/// The following variables are set unconditionally (falling back to
/// sensible defaults when the format does not carry the field):
///
/// | Variable | Source |
/// |-------------|--------------------------------------|
/// | `title` | `MediaMetadata::title` |
/// | `creator` | `MediaMetadata::creator` |
/// | `created` | `MediaMetadata::created_at` |
/// | `duration` | `MediaMetadata::duration` (seconds) |
/// | `tags` | `MediaMetadata::tags` (comma-joined) |
///
/// The `width`, `height`, `codec`, `bitrate`, and `framerate` fields are
/// populated from the file's stream properties when they are available in
/// the embedded XMP sidecar; otherwise their values remain unset.
///
/// # Errors
///
/// Returns an error if the path cannot be read.
pub fn from_media(&mut self, path: &Path) -> Result<()> {
use oximedia_metadata::media_metadata::{ID3Parser, MediaMetadata, XmpParser};
// Read the raw file bytes. If reading fails we fall back to an empty
// metadata object rather than propagating an I/O error — the caller
// may be probing a path that does not yet exist.
let raw_bytes = std::fs::read(path).unwrap_or_default();
// Choose parser based on extension.
let ext = path
.extension()
.map(|e| e.to_string_lossy().to_lowercase())
.unwrap_or_default();
let mut media_meta = MediaMetadata::new();
match ext.as_str() {
"mp3" => {
media_meta = ID3Parser::read(&raw_bytes);
}
"xmp" => {
if let Ok(xml) = std::str::from_utf8(&raw_bytes) {
media_meta = XmpParser::parse(xml);
}
}
_ => {
// For video/other formats, attempt to read a sidecar XMP file.
let mut sidecar = path.to_path_buf();
sidecar.set_extension("xmp");
if let Ok(xmp_bytes) = std::fs::read(&sidecar) {
if let Ok(xml) = std::str::from_utf8(&xmp_bytes) {
media_meta = XmpParser::parse(xml);
}
}
}
}
// Populate template variables from the metadata.
if let Some(title) = &media_meta.title {
self.set("title".to_string(), title.clone());
}
if let Some(creator) = &media_meta.creator {
self.set("creator".to_string(), creator.clone());
}
if let Some(created_at) = &media_meta.created_at {
self.set("created".to_string(), created_at.clone());
}
if let Some(duration) = media_meta.duration {
self.set("duration".to_string(), format!("{duration:.3}"));
}
if !media_meta.tags.is_empty() {
self.set("tags".to_string(), media_meta.tags.join(","));
}
for (k, v) in &media_meta.extra {
self.set(k.clone(), v.clone());
}
// Populate video stream properties from `extra` keys when present,
// or fall back to neutral sentinel values so callers can always rely
// on these keys being set regardless of whether the file exists or
// carries embedded stream metadata.
if self.get("width").is_none() {
let width = media_meta
.extra
.get("width")
.cloned()
.unwrap_or_else(|| "0".to_string());
self.set("width".to_string(), width);
}
if self.get("height").is_none() {
let height = media_meta
.extra
.get("height")
.cloned()
.unwrap_or_else(|| "0".to_string());
self.set("height".to_string(), height);
}
if self.get("codec").is_none() {
let codec = media_meta
.extra
.get("codec")
.cloned()
.unwrap_or_else(|| "unknown".to_string());
self.set("codec".to_string(), codec);
}
Ok(())
}
}
impl Default for TemplateContext {
fn default() -> Self {
Self::new()
}
}
/// Template processor
pub struct TemplateProcessor {
engine: TemplateEngine,
}
impl TemplateProcessor {
/// Create a new template processor
#[must_use]
pub fn new() -> Self {
Self {
engine: TemplateEngine::new(),
}
}
/// Process a template with context
///
/// # Arguments
///
/// * `template` - Template string
/// * `context` - Template context
///
/// # Errors
///
/// Returns an error if processing fails
pub fn process(&self, template: &str, context: &TemplateContext) -> Result<String> {
self.engine.render(template, context)
}
/// Process a file path template
///
/// # Arguments
///
/// * `template` - Template string
/// * `input_path` - Input file path
///
/// # Errors
///
/// Returns an error if processing fails
pub fn process_file_path(&self, template: &str, input_path: &Path) -> Result<String> {
let mut context = TemplateContext::new();
context.from_file(input_path)?;
self.process(template, &context)
}
}
impl Default for TemplateProcessor {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_template_context_creation() {
let context = TemplateContext::new();
assert!(context.variables.is_empty());
}
#[test]
fn test_set_and_get_variable() {
let mut context = TemplateContext::new();
context.set("key".to_string(), "value".to_string());
assert_eq!(context.get("key"), Some(&"value".to_string()));
}
#[test]
fn test_context_from_file() {
let mut context = TemplateContext::new();
let path = std::env::temp_dir().join("test.mp4");
context.from_file(&path).ok();
assert_eq!(context.get("filename"), Some(&"test.mp4".to_string()));
assert_eq!(context.get("stem"), Some(&"test".to_string()));
assert_eq!(context.get("extension"), Some(&"mp4".to_string()));
}
#[test]
fn test_context_from_media() {
let mut context = TemplateContext::new();
let path = std::env::temp_dir().join("test.mp4");
context.from_media(&path).ok();
assert!(context.get("width").is_some());
assert!(context.get("height").is_some());
assert!(context.get("codec").is_some());
}
#[test]
fn test_template_processor_creation() {
let processor = TemplateProcessor::new();
let _ = processor; // processor created successfully
}
}