caesura 0.31.0

An all-in-one command line tool to transcode FLAC audio files and upload to gazelle based indexers/trackers
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
use crate::testing_prelude::*;
use di::{Ref as DiRef, singleton_as_self};

/// Test that `UploadCommand` succeeds with a valid transcoded source.
#[tokio::test]

async fn upload_command_succeeds_with_valid_source() -> Result<(), TestError> {
    // Arrange
    init_logger();
    let transcode = TranscodeProvider::get(SampleFormat::default(), TargetFormat::_320).await;
    let test_dir = TestDirectory::new();
    let host = build_upload_test_host(&transcode, &test_dir).await;
    let (source, command) = get_source_and_command(&host).await;

    // Act
    let result = command.execute(&source).await;
    let status = UploadStatus::new(result);

    // Assert
    assert!(status.success, "upload should succeed");
    assert!(status.formats.is_some(), "should have format statuses");
    let formats = status.formats.as_ref().expect("checked above");
    assert!(!formats.is_empty(), "should have at least one format");

    Ok(())
}

/// Test that `UploadCommand` with `dry_run=true` does not call the API.
#[tokio::test]
async fn upload_command_dry_run_skips_api_call() -> Result<(), TestError> {
    // Arrange
    init_logger();
    let transcode = TranscodeProvider::get(SampleFormat::default(), TargetFormat::_320).await;
    let test_dir = TestDirectory::new();
    let host = HostBuilder::new()
        .with_mock_api(transcode.album.clone())
        .with_test_options(&test_dir)
        .await
        .with_options(SharedOptions {
            content: vec![SAMPLE_SOURCES_DIR.clone()],
            output: SAMPLE_TRANSCODES_DIR.clone(),
            ..SharedOptions::mock()
        })
        .with_options(TargetOptions {
            target: vec![transcode.target],
            ..TargetOptions::default()
        })
        .with_options(UploadOptions {
            dry_run: true,
            ..UploadOptions::default()
        })
        .expect_build();
    let (source, command) = get_source_and_command(&host).await;

    // Act
    let result = command.execute(&source).await;
    let status = UploadStatus::new(result);

    // Assert
    assert!(status.success, "dry run should succeed");
    assert!(
        status.formats.unwrap_or_default().is_empty(),
        "dry run should not record formats"
    );
    assert!(status.errors.is_none(), "dry run should have no errors");

    Ok(())
}

/// Test that torrent client injection succeeds with mock client.
#[tokio::test]
async fn upload_command_torrent_client_injection_succeeds() -> Result<(), TestError> {
    // Arrange
    init_logger();
    let transcode = TranscodeProvider::get(SampleFormat::default(), TargetFormat::_320).await;
    let test_dir = TestDirectory::new();
    let mut builder = HostBuilder::new();
    let _ = builder
        .with_mock_api(transcode.album.clone())
        .with_test_options(&test_dir)
        .await
        .with_options(SharedOptions {
            content: vec![SAMPLE_SOURCES_DIR.clone()],
            output: SAMPLE_TRANSCODES_DIR.clone(),
            ..SharedOptions::mock()
        })
        .with_options(TargetOptions {
            target: vec![transcode.target],
            ..TargetOptions::default()
        })
        .with_options(QbitOptions::mock())
        .with_options(QbitUploadOptions::mock())
        .with_mock_torrent_client(MockQBittorrentClient::default());
    let host = builder.expect_build();
    let (source, command) = get_source_and_command(&host).await;

    // Act
    let result = command.execute(&source).await;
    let status = UploadStatus::new(result);

    // Assert
    assert!(status.success, "upload should succeed");
    assert!(
        status.errors.is_none(),
        "injection should succeed with mock client"
    );

    Ok(())
}

/// Test that torrent injection is skipped when `qbit_url` is not set.
#[tokio::test]
async fn upload_command_skips_injection_when_not_configured() -> Result<(), TestError> {
    // Arrange
    init_logger();
    let transcode = TranscodeProvider::get(SampleFormat::default(), TargetFormat::_320).await;
    let test_dir = TestDirectory::new();
    let host = build_upload_test_host(&transcode, &test_dir).await;
    let (source, command) = get_source_and_command(&host).await;

    // Act
    let result = command.execute(&source).await;
    let status = UploadStatus::new(result);

    // Assert
    assert!(status.success, "upload should succeed");
    assert!(
        status.errors.is_none(),
        "no warnings when injection not configured"
    );

    Ok(())
}

/// Test that `UploadCommand` fails when torrent file is missing (no transcodes).
#[tokio::test]
async fn upload_command_missing_transcode_returns_error() -> Result<(), TestError> {
    // Arrange
    init_logger();
    let album = AlbumProvider::get(SampleFormat::default()).await;
    let test_dir = TestDirectory::new();

    let host = HostBuilder::new()
        .with_mock_api(album)
        .with_test_options(&test_dir)
        .await
        .with_options(UploadOptions {
            copy_torrent_to: Some(PathBuf::from("/nonexistent/path")),
            ..UploadOptions::default()
        })
        .with_options(SourceArg {
            source: AlbumConfig::TORRENT_ID.to_string(),
        })
        .expect_build();

    let command = host.services.get_required::<UploadCommand>();

    // Act
    let result = command.execute_cli().await;

    // Assert - now returns Err since missing torrent is a failure
    assert!(result.is_err());

    Ok(())
}

/// Test that `UploadCommand` fails when the torrent file is missing.
#[tokio::test]

async fn upload_command_missing_torrent_fails() -> Result<(), TestError> {
    // Arrange
    init_logger();
    let album = AlbumProvider::get(SampleFormat::default()).await;
    let test_dir = TestDirectory::new();

    let host = HostBuilder::new()
        .with_mock_api(album)
        .with_test_options(&test_dir)
        .await
        .expect_build();

    let provider = host.services.get_required::<SourceProvider>();
    let transcoder = host.services.get_required::<TranscodeCommand>();
    let source = provider
        .get(AlbumConfig::TORRENT_ID)
        .await
        .expect("should not fail")
        .expect("should find source");

    transcoder
        .execute(&source)
        .await
        .expect("transcode should succeed");

    // Delete torrent files
    let output_dir = test_dir.output();
    delete_torrent_files(&output_dir);

    let command = host.services.get_required::<UploadCommand>();

    // Act
    let result = command.execute(&source).await;
    let status = UploadStatus::new(result);

    // Assert
    assert!(!status.success, "upload should fail with missing torrent");
    assert!(status.errors.is_some(), "should have error messages");

    Ok(())
}

fn delete_torrent_files(dir: &PathBuf) {
    if let Ok(entries) = read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().is_some_and(|ext| ext == "torrent") {
                let _ = remove_file(&path);
            }
            if path.is_dir() {
                delete_torrent_files(&path);
            }
        }
    }
}

/// Test that `UploadCommand` copies transcode to content directory when enabled.
#[tokio::test]

async fn upload_command_copies_to_content_dir() -> Result<(), TestError> {
    // Arrange
    init_logger();
    let transcode = TranscodeProvider::get(SampleFormat::default(), TargetFormat::_320).await;
    let test_dir = TestDirectory::new();
    let copy_target = TempDirectory::create("content_copy_target");
    let host = HostBuilder::new()
        .with_mock_api(transcode.album.clone())
        .with_test_options(&test_dir)
        .await
        .with_options(SharedOptions {
            // First content dir is for copy destination, second is where source files are found
            content: vec![copy_target.to_path_buf(), SAMPLE_SOURCES_DIR.clone()],
            output: SAMPLE_TRANSCODES_DIR.clone(),
            ..SharedOptions::mock()
        })
        .with_options(TargetOptions {
            target: vec![transcode.target],
            allow_existing: true, // Allow existing since we're using pre-generated transcodes
            ..TargetOptions::default()
        })
        .with_options(UploadOptions {
            copy_transcode_to_content_dir: true,
            ..UploadOptions::default()
        })
        .expect_build();
    let (source, command) = get_source_and_command(&host).await;

    // Act
    let result = command.execute(&source).await;
    let status = UploadStatus::new(result);

    // Assert
    assert!(status.success, "upload should succeed");
    let entries: Vec<_> = read_dir(&copy_target).expect("read dir").collect();
    assert!(!entries.is_empty(), "should have copied transcodes");

    Ok(())
}

/// Test that `UploadCommand` copies transcode to custom directory.
#[tokio::test]

async fn upload_command_copies_to_custom_dir() -> Result<(), TestError> {
    // Arrange
    init_logger();
    let transcode = TranscodeProvider::get(SampleFormat::default(), TargetFormat::_320).await;
    let test_dir = TestDirectory::new();
    let copy_target = TempDirectory::create("custom_copy_target");
    let host = HostBuilder::new()
        .with_mock_api(transcode.album.clone())
        .with_test_options(&test_dir)
        .await
        .with_options(SharedOptions {
            content: vec![SAMPLE_SOURCES_DIR.clone()],
            output: SAMPLE_TRANSCODES_DIR.clone(),
            ..SharedOptions::mock()
        })
        .with_options(TargetOptions {
            target: vec![transcode.target],
            ..TargetOptions::default()
        })
        .with_options(UploadOptions {
            copy_transcode_to: Some(copy_target.to_path_buf()),
            ..UploadOptions::default()
        })
        .expect_build();
    let (source, command) = get_source_and_command(&host).await;

    // Act
    let result = command.execute(&source).await;
    let status = UploadStatus::new(result);

    // Assert
    assert!(status.success, "upload should succeed");
    let entries: Vec<_> = read_dir(&copy_target).expect("read dir").collect();
    assert!(!entries.is_empty(), "should have copied transcodes");

    Ok(())
}

/// Test that `UploadCommand` copies torrent file to specified directory.
#[tokio::test]

async fn upload_command_copies_torrent_file() -> Result<(), TestError> {
    // Arrange
    init_logger();
    let transcode = TranscodeProvider::get(SampleFormat::default(), TargetFormat::_320).await;
    let test_dir = TestDirectory::new();
    let torrent_target = TempDirectory::create("torrent_copy_target");
    let host = HostBuilder::new()
        .with_mock_api(transcode.album.clone())
        .with_test_options(&test_dir)
        .await
        .with_options(SharedOptions {
            content: vec![SAMPLE_SOURCES_DIR.clone()],
            output: SAMPLE_TRANSCODES_DIR.clone(),
            ..SharedOptions::mock()
        })
        .with_options(TargetOptions {
            target: vec![transcode.target],
            ..TargetOptions::default()
        })
        .with_options(UploadOptions {
            copy_torrent_to: Some(torrent_target.to_path_buf()),
            ..UploadOptions::default()
        })
        .expect_build();
    let (source, command) = get_source_and_command(&host).await;

    // Act
    let result = command.execute(&source).await;
    let status = UploadStatus::new(result);

    // Assert
    assert!(status.success, "upload should succeed");
    let torrent_files: Vec<_> = read_dir(&*torrent_target)
        .expect("read dir")
        .filter_map(Result::ok)
        .filter(|e| e.path().extension().is_some_and(|ext| ext == "torrent"))
        .collect();
    assert!(!torrent_files.is_empty(), "should have copied torrents");

    Ok(())
}

/// Test that `UploadCommand` handles API failure gracefully.
#[tokio::test]

async fn upload_command_api_failure_sets_error() -> Result<(), TestError> {
    // Arrange
    init_logger();
    let transcode = TranscodeProvider::get(SampleFormat::default(), TargetFormat::_320).await;
    let test_dir = TestDirectory::new();

    // Create a mock client that fails on upload
    let torrent_path = SAMPLE_SOURCES_DIR.join(transcode.album.torrent_filename());
    let torrent_bytes = read(torrent_path).expect("torrent file should exist");

    let mock = MockGazelleClient::new()
        .with_get_torrent(Ok(TorrentResponse {
            group: Group {
                id: 123,
                name: transcode.album.album.to_owned(),
                year: transcode.album.year,
                category_name: "Music".to_owned(),
                music_info: Some(Credits {
                    artists: vec![Credit {
                        id: 1,
                        name: transcode.album.artist.to_owned(),
                    }],
                    ..Credits::default()
                }),
                ..Group::default()
            },
            torrent: Torrent {
                id: AlbumConfig::TORRENT_ID,
                format: Format::FLAC,
                encoding: Quality::Lossless,
                media: Media::WEB,
                file_path: transcode.album.dir_name(),
                ..Torrent::default()
            },
        }))
        .with_get_torrent_group(Ok(GroupResponse {
            group: Group {
                id: 123,
                name: transcode.album.album.to_owned(),
                year: transcode.album.year,
                category_name: "Music".to_owned(),
                ..Group::default()
            },
            torrents: vec![Torrent {
                id: AlbumConfig::TORRENT_ID,
                format: Format::FLAC,
                encoding: Quality::Lossless,
                media: Media::WEB,
                file_path: transcode.album.dir_name(),
                ..Torrent::default()
            }],
        }))
        .with_download_torrent(Ok(torrent_bytes))
        .with_upload_torrent(Err(GazelleError {
            operation: GazelleOperation::ReadFile,
            source: ErrorSource::Io(IoError::new(ErrorKind::NotFound, "Upload failed")),
        }));

    let mut builder = HostBuilder::new();

    #[allow(clippy::as_conversions)]
    let client: DiRef<GazelleClient> = DiRef::new(Box::new(mock) as GazelleClient);
    builder
        .services
        .add(singleton_as_self().from(move |_| client.clone()));

    let _ = builder
        .with_test_options(&test_dir)
        .await
        .with_options(SharedOptions {
            content: vec![SAMPLE_SOURCES_DIR.clone()],
            output: SAMPLE_TRANSCODES_DIR.clone(),
            ..SharedOptions::mock()
        })
        .with_options(TargetOptions {
            target: vec![transcode.target],
            ..TargetOptions::default()
        });
    let host = builder.expect_build();
    let (source, command) = get_source_and_command(&host).await;

    // Act
    let result = command.execute(&source).await;
    let status = UploadStatus::new(result);

    // Assert
    assert!(!status.success, "upload should fail on API error");
    assert!(status.errors.is_some(), "should have errors");

    Ok(())
}

/// Test that `UploadCommand` captures torrent ID from API response.
#[tokio::test]

async fn upload_command_captures_response_ids() -> Result<(), TestError> {
    // Arrange
    init_logger();
    let transcode = TranscodeProvider::get(SampleFormat::default(), TargetFormat::_320).await;
    let test_dir = TestDirectory::new();
    let host = build_upload_test_host(&transcode, &test_dir).await;
    let (source, command) = get_source_and_command(&host).await;

    // Act
    let result = command.execute(&source).await;
    let status = UploadStatus::new(result);

    // Assert
    assert!(status.success, "upload should succeed");
    assert!(status.formats.is_some(), "should have format statuses");
    for format_status in status.formats.as_ref().expect("checked") {
        assert!(format_status.id > 0, "should have valid ID");
    }

    Ok(())
}

/// Test that upload succeeds when copy target already exists.
#[tokio::test]

async fn upload_command_skip_existing_copy_succeeds() -> Result<(), TestError> {
    // Arrange
    init_logger();
    let transcode = TranscodeProvider::get(SampleFormat::default(), TargetFormat::_320).await;
    let test_dir = TestDirectory::new();
    let host = build_upload_test_host(&transcode, &test_dir).await;
    let (source, command) = get_source_and_command(&host).await;

    // Act - run twice
    let result1 = command.execute(&source).await;
    let status1 = UploadStatus::new(result1);
    assert!(status1.success, "first upload should succeed");

    let result2 = command.execute(&source).await;
    let status2 = UploadStatus::new(result2);

    // Assert
    assert!(status2.success, "second upload should succeed");

    Ok(())
}

/// Helper to build a host configured for upload tests with pre-generated transcodes.
async fn build_upload_test_host(transcode: &TranscodeConfig, test_dir: &TestDirectory) -> Host {
    HostBuilder::new()
        .with_mock_api(transcode.album.clone())
        .with_test_options(test_dir)
        .await
        .with_options(SharedOptions {
            content: vec![SAMPLE_SOURCES_DIR.clone()],
            output: SAMPLE_TRANSCODES_DIR.clone(),
            ..SharedOptions::mock()
        })
        .with_options(TargetOptions {
            target: vec![transcode.target],
            ..TargetOptions::default()
        })
        .expect_build()
}

/// Helper to get source and upload command from a host.
async fn get_source_and_command(host: &Host) -> (Source, DiRef<UploadCommand>) {
    let provider = host.services.get_required::<SourceProvider>();
    let source = provider
        .get(AlbumConfig::TORRENT_ID)
        .await
        .expect("should not fail")
        .expect("should find source");
    let command = host.services.get_required::<UploadCommand>();
    (source, command)
}