oximedia-clips 0.1.8

Professional clip management and logging system for OxiMedia
Documentation
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! Main clip manager that integrates all functionality.

use crate::clip::{Clip, ClipId};
use crate::database::ClipDatabase;
use crate::error::{ClipError, ClipResult};
use crate::export::{ClipListExporter, EdlExporter};
use crate::group::{Bin, BinId, Collection, CollectionId, Folder, FolderId, SmartCollection};
use crate::import::{BatchImporter, MediaScanner};
use crate::marker::{Marker, MarkerId, MarkerManager};
use crate::proxy::{ProxyLink, ProxyManager};
use crate::search::{ClipFilter, SearchEngine};
use crate::take::{Take, TakeManager};
use oximedia_core::types::Rational;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Main clip management system.
pub struct ClipManager {
    database: ClipDatabase,
    marker_manager: MarkerManager,
    take_manager: TakeManager,
    proxy_manager: ProxyManager,
    #[allow(dead_code)]
    search_engine: SearchEngine,
    bins: HashMap<BinId, Bin>,
    folders: HashMap<FolderId, Folder>,
    collections: HashMap<CollectionId, Collection>,
    smart_collections: Vec<SmartCollection>,
}

impl ClipManager {
    /// Creates a new clip manager.
    ///
    /// # Errors
    ///
    /// Returns an error if the database cannot be initialized.
    pub async fn new(database_url: impl AsRef<str>) -> ClipResult<Self> {
        let database = ClipDatabase::new(database_url).await?;

        Ok(Self {
            database,
            marker_manager: MarkerManager::new(),
            take_manager: TakeManager::new(),
            proxy_manager: ProxyManager::new(),
            search_engine: SearchEngine::new(),
            bins: HashMap::new(),
            folders: HashMap::new(),
            collections: HashMap::new(),
            smart_collections: Vec::new(),
        })
    }

    // Clip operations

    /// Adds a clip to the database.
    ///
    /// # Errors
    ///
    /// Returns an error if the clip cannot be saved.
    pub async fn add_clip(&self, clip: Clip) -> ClipResult<ClipId> {
        let clip_id = clip.id;
        self.database.save_clip(&clip).await?;
        Ok(clip_id)
    }

    /// Gets a clip by ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the clip is not found.
    pub async fn get_clip(&self, clip_id: &ClipId) -> ClipResult<Clip> {
        self.database.get_clip(clip_id).await
    }

    /// Updates a clip.
    ///
    /// # Errors
    ///
    /// Returns an error if the clip cannot be updated.
    pub async fn update_clip(&self, clip: Clip) -> ClipResult<()> {
        self.database.save_clip(&clip).await
    }

    /// Deletes a clip.
    ///
    /// # Errors
    ///
    /// Returns an error if the clip cannot be deleted.
    pub async fn delete_clip(&self, clip_id: &ClipId) -> ClipResult<()> {
        self.database.delete_clip(clip_id).await
    }

    /// Gets all clips.
    ///
    /// # Errors
    ///
    /// Returns an error if clips cannot be loaded.
    pub async fn get_all_clips(&self) -> ClipResult<Vec<Clip>> {
        self.database.get_all_clips().await
    }

    /// Returns the number of clips.
    ///
    /// # Errors
    ///
    /// Returns an error if the count fails.
    pub async fn clip_count(&self) -> ClipResult<i64> {
        self.database.count_clips().await
    }

    /// Adds multiple clips in a single database transaction (bulk import).
    ///
    /// Significantly more efficient than calling `add_clip()` in a loop.
    ///
    /// # Errors
    ///
    /// Returns an error if the transaction or any individual save fails.
    pub async fn add_clips(&self, clips: Vec<Clip>) -> ClipResult<Vec<ClipId>> {
        let ids: Vec<ClipId> = clips.iter().map(|c| c.id).collect();
        self.database.batch_save_clips(&clips).await?;
        Ok(ids)
    }

    /// Lists clips with pagination.
    ///
    /// `page` is 0-indexed; `page_size` is the number of clips per page.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub async fn list_clips(&self, page: i64, page_size: i64) -> ClipResult<Vec<Clip>> {
        self.database.get_clips_page(page, page_size).await
    }

    /// Searches clips by query string with pagination.
    ///
    /// # Errors
    ///
    /// Returns an error if the search fails.
    pub async fn search_paged(
        &self,
        query: &str,
        page: i64,
        page_size: i64,
    ) -> ClipResult<Vec<Clip>> {
        self.database
            .search_clips_page(query, page, page_size)
            .await
    }

    // Search operations

    /// Searches clips by query string.
    ///
    /// # Errors
    ///
    /// Returns an error if the search fails.
    pub async fn search(&self, query: &str) -> ClipResult<Vec<Clip>> {
        self.database.search_clips(query).await
    }

    /// Filters clips using advanced criteria.
    ///
    /// # Errors
    ///
    /// Returns an error if the filter operation fails.
    pub async fn filter(&self, filter: &ClipFilter) -> ClipResult<Vec<Clip>> {
        let clips = self.database.get_all_clips().await?;
        Ok(filter.apply(&clips).into_iter().cloned().collect())
    }

    // Bin operations

    /// Creates a new bin.
    pub fn create_bin(&mut self, name: impl Into<String>) -> BinId {
        let bin = Bin::new(name);
        let bin_id = bin.id;
        self.bins.insert(bin_id, bin);
        bin_id
    }

    /// Gets a bin by ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the bin is not found.
    pub fn get_bin(&self, bin_id: &BinId) -> ClipResult<&Bin> {
        self.bins
            .get(bin_id)
            .ok_or_else(|| ClipError::BinNotFound(bin_id.to_string()))
    }

    /// Gets a mutable bin by ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the bin is not found.
    pub fn get_bin_mut(&mut self, bin_id: &BinId) -> ClipResult<&mut Bin> {
        self.bins
            .get_mut(bin_id)
            .ok_or_else(|| ClipError::BinNotFound(bin_id.to_string()))
    }

    /// Adds a clip to a bin.
    ///
    /// # Errors
    ///
    /// Returns an error if the bin is not found.
    pub fn add_clip_to_bin(&mut self, bin_id: &BinId, clip_id: ClipId) -> ClipResult<()> {
        let bin = self.get_bin_mut(bin_id)?;
        bin.add_clip(clip_id);
        Ok(())
    }

    /// Lists all bins.
    #[must_use]
    pub fn list_bins(&self) -> Vec<&Bin> {
        self.bins.values().collect()
    }

    // Folder operations

    /// Creates a new folder.
    pub fn create_folder(&mut self, name: impl Into<String>) -> FolderId {
        let folder = Folder::new(name);
        let folder_id = folder.id;
        self.folders.insert(folder_id, folder);
        folder_id
    }

    /// Creates a child folder.
    pub fn create_child_folder(
        &mut self,
        name: impl Into<String>,
        parent_id: FolderId,
    ) -> FolderId {
        let folder = Folder::new_child(name, parent_id);
        let folder_id = folder.id;
        self.folders.insert(folder_id, folder);
        folder_id
    }

    /// Gets a folder by ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the folder is not found.
    pub fn get_folder(&self, folder_id: &FolderId) -> ClipResult<&Folder> {
        self.folders
            .get(folder_id)
            .ok_or_else(|| ClipError::FolderNotFound(folder_id.to_string()))
    }

    // Collection operations

    /// Creates a new collection.
    pub fn create_collection(&mut self, name: impl Into<String>) -> CollectionId {
        let collection = Collection::new(name);
        let collection_id = collection.id;
        self.collections.insert(collection_id, collection);
        collection_id
    }

    /// Gets a collection by ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the collection is not found.
    pub fn get_collection(&self, collection_id: &CollectionId) -> ClipResult<&Collection> {
        self.collections
            .get(collection_id)
            .ok_or_else(|| ClipError::CollectionNotFound(collection_id.to_string()))
    }

    /// Adds a clip to a collection.
    ///
    /// # Errors
    ///
    /// Returns an error if the collection is not found.
    pub fn add_clip_to_collection(
        &mut self,
        collection_id: &CollectionId,
        clip_id: ClipId,
    ) -> ClipResult<()> {
        let collection = self
            .collections
            .get_mut(collection_id)
            .ok_or_else(|| ClipError::CollectionNotFound(collection_id.to_string()))?;
        collection.add_clip(clip_id);
        Ok(())
    }

    // Smart collection operations

    /// Creates a new smart collection.
    pub fn create_smart_collection(&mut self, smart_collection: SmartCollection) {
        self.smart_collections.push(smart_collection);
    }

    /// Updates all smart collections.
    ///
    /// # Errors
    ///
    /// Returns an error if clips cannot be loaded.
    pub async fn update_smart_collections(&mut self) -> ClipResult<()> {
        let clips = self.database.get_all_clips().await?;

        for smart_collection in &mut self.smart_collections {
            smart_collection.update(&clips);
        }

        Ok(())
    }

    // Marker operations

    /// Adds a marker to a clip.
    pub fn add_marker(&mut self, clip_id: ClipId, marker: Marker) {
        self.marker_manager.add_marker(clip_id, marker);
    }

    /// Gets markers for a clip.
    #[must_use]
    pub fn get_markers(&self, clip_id: &ClipId) -> Vec<&Marker> {
        self.marker_manager.get_markers(clip_id)
    }

    /// Removes a marker.
    ///
    /// # Errors
    ///
    /// Returns an error if the marker is not found.
    pub fn remove_marker(&mut self, clip_id: &ClipId, marker_id: &MarkerId) -> ClipResult<()> {
        self.marker_manager.remove_marker(clip_id, marker_id)
    }

    // Take operations

    /// Adds a take.
    pub fn add_take(&mut self, take: Take) {
        self.take_manager.add_take(take);
    }

    /// Gets takes for a scene.
    #[must_use]
    pub fn get_scene_takes(&self, scene: &str) -> Vec<&Take> {
        self.take_manager.get_scene_takes(scene)
    }

    /// Gets takes for a clip.
    #[must_use]
    pub fn get_clip_takes(&self, clip_id: &ClipId) -> Vec<&Take> {
        self.take_manager.get_clip_takes(clip_id)
    }

    // Proxy operations

    /// Adds a proxy link.
    pub fn add_proxy(&mut self, link: ProxyLink) {
        self.proxy_manager.add_link(link);
    }

    /// Gets proxy links for a clip.
    #[must_use]
    pub fn get_proxies(&self, clip_id: &ClipId) -> Vec<&ProxyLink> {
        self.proxy_manager.get_links(clip_id)
    }

    /// Gets the best proxy for a clip.
    #[must_use]
    pub fn get_best_proxy(&self, clip_id: &ClipId) -> Option<&ProxyLink> {
        self.proxy_manager.get_best_proxy(clip_id)
    }

    // Import operations

    /// Scans a directory for media files.
    ///
    /// # Errors
    ///
    /// Returns an error if the scan fails.
    pub async fn scan_directory(&self, path: impl AsRef<Path>) -> ClipResult<Vec<Clip>> {
        let scanner = MediaScanner::new();
        scanner.scan(path).await
    }

    /// Imports clips from file paths.
    #[must_use]
    pub fn import_clips(&self, paths: Vec<PathBuf>) -> Vec<Clip> {
        let importer = BatchImporter::default();
        importer.import(paths)
    }

    // Export operations

    /// Exports clips to CSV.
    ///
    /// # Errors
    ///
    /// Returns an error if the export fails.
    pub async fn export_csv(&self, clip_ids: &[ClipId]) -> ClipResult<String> {
        let mut clips = Vec::new();
        for clip_id in clip_ids {
            clips.push(self.database.get_clip(clip_id).await?);
        }

        let exporter = ClipListExporter::new();
        exporter.to_csv(&clips)
    }

    /// Exports clips to EDL.
    ///
    /// # Errors
    ///
    /// Returns an error if the export fails.
    pub async fn export_edl(
        &self,
        clip_ids: &[ClipId],
        frame_rate: Rational,
    ) -> ClipResult<String> {
        let mut clips = Vec::new();
        for clip_id in clip_ids {
            clips.push(self.database.get_clip(clip_id).await?);
        }

        let exporter = EdlExporter::new(frame_rate);
        exporter.to_edl(&clips)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_clip_manager() {
        let manager = ClipManager::new(":memory:")
            .await
            .expect("new should succeed");
        let count = manager
            .clip_count()
            .await
            .expect("clip_count should succeed");
        assert_eq!(count, 0);
    }

    #[tokio::test]
    async fn test_add_and_get_clip() {
        let manager = ClipManager::new(":memory:")
            .await
            .expect("new should succeed");

        let clip = Clip::new(PathBuf::from("/test.mov"));
        let clip_id = manager
            .add_clip(clip.clone())
            .await
            .expect("add_clip should succeed");

        let loaded = manager
            .get_clip(&clip_id)
            .await
            .expect("get_clip should succeed");
        assert_eq!(loaded.id, clip_id);
    }

    #[tokio::test]
    async fn test_bins() {
        let mut manager = ClipManager::new(":memory:")
            .await
            .expect("new should succeed");

        let bin_id = manager.create_bin("Test Bin");
        let bin = manager.get_bin(&bin_id).expect("get_bin should succeed");
        assert_eq!(bin.name, "Test Bin");

        let clip = Clip::new(PathBuf::from("/test.mov"));
        let clip_id = manager
            .add_clip(clip)
            .await
            .expect("add_clip should succeed");

        manager
            .add_clip_to_bin(&bin_id, clip_id)
            .expect("add_clip_to_bin should succeed");
        let bin = manager.get_bin(&bin_id).expect("get_bin should succeed");
        assert_eq!(bin.count(), 1);
    }

    #[tokio::test]
    async fn test_search() {
        let manager = ClipManager::new(":memory:")
            .await
            .expect("new should succeed");

        let mut clip = Clip::new(PathBuf::from("/test.mov"));
        clip.set_name("Interview");
        manager
            .add_clip(clip)
            .await
            .expect("operation should succeed");

        let results = manager
            .search("interview")
            .await
            .expect("search should succeed");
        assert_eq!(results.len(), 1);
    }
}