moosicbox_files 0.2.0

MoosicBox files package
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
//! Artist cover image fetching and caching.
//!
//! Provides functionality for retrieving artist cover artwork from local files or remote URLs,
//! with database integration for tracking cover locations and automatic fallback between sources.

#![allow(clippy::module_name_repetitions)]

use std::{
    path::{Path, PathBuf},
    str::FromStr,
};

use bytes::BytesMut;
use futures::{StreamExt, TryStreamExt};
use moosicbox_music_api::{
    MusicApi,
    models::{ImageCoverSize, ImageCoverSource},
};
use moosicbox_music_models::{Artist, id::Id};
use moosicbox_stream_utils::stalled_monitor::StalledReadMonitor;
use switchy_database::{DatabaseError, profiles::LibraryDatabase, query::FilterableQuery};
use thiserror::Error;
use tokio_util::codec::{BytesCodec, FramedRead};

use crate::{
    CoverBytes, FetchCoverError, get_or_fetch_cover_bytes_from_remote_url,
    get_or_fetch_cover_from_remote_url, sanitize_filename, search_for_cover,
};

fn get_artist_cover_path(size: &str, source: &str, artist_id: &str, artist_name: &str) -> PathBuf {
    let path = moosicbox_config::get_cache_dir_path()
        .expect("Failed to get cache directory")
        .join(source)
        .join(sanitize_filename(artist_name));

    let filename = format!("artist_{artist_id}_{size}.jpg");

    path.join(filename)
}

fn get_artist_directory(artist: &Artist) -> Option<String> {
    artist
        .cover
        .as_ref()
        .and_then(|x| PathBuf::from_str(x.as_str()).ok())
        .and_then(|x| x.parent().and_then(|x| x.to_str()).map(ToString::to_string))
}

/// Errors that can occur when retrieving artist cover artwork.
#[derive(Debug, Error)]
pub enum ArtistCoverError {
    /// Artist cover not found for the specified artist ID
    #[error("Artist cover not found for artist: {0} ({1})")]
    NotFound(Id, String),
    /// Music API error
    #[error(transparent)]
    MusicApi(#[from] moosicbox_music_api::Error),
    /// Error fetching cover from remote source
    #[error(transparent)]
    FetchCover(#[from] FetchCoverError),
    /// Error fetching local artist cover file
    #[error(transparent)]
    FetchLocalArtistCover(#[from] FetchLocalArtistCoverError),
    /// IO error reading or writing cover file
    #[error(transparent)]
    IO(#[from] tokio::io::Error),
    /// Database error
    #[error(transparent)]
    Database(#[from] DatabaseError),
    /// Failed to read cover file at the specified path
    #[error("Failed to read file with path: {0} ({1})")]
    File(String, String),
    /// Invalid or unsupported API source
    #[error("Invalid source")]
    InvalidSource,
}

/// Retrieves the local file path to an artist cover image.
///
/// First checks for a local file, then falls back to fetching from remote sources if available.
/// Updates the database with the located cover path.
///
/// # Errors
///
/// * `ArtistCoverError::NotFound` - If the artist cover was not found
/// * `ArtistCoverError::MusicApi` - If failed to get the artist info
/// * `ArtistCoverError::IO` - If an IO error occurs
/// * `ArtistCoverError::Database` - If a database error occurs
/// * `ArtistCoverError::InvalidSource` - If the `ApiSource` is invalid
pub async fn get_local_artist_cover(
    api: &dyn MusicApi,
    db: &LibraryDatabase,
    artist: &Artist,
    size: ImageCoverSize,
) -> Result<String, ArtistCoverError> {
    log::debug!(
        "get_local_artist_cover: api_source={} artist={artist:?} size={size}",
        api.source()
    );
    let source = api
        .artist_cover_source(artist, size)
        .await?
        .ok_or_else(|| {
            log::debug!("get_local_artist_cover: artist cover source not found");
            ArtistCoverError::NotFound(
                artist.id.clone(),
                "Artist cover source not found".to_owned(),
            )
        })?;

    let directory = get_artist_directory(artist);
    if let Ok(cover) =
        fetch_local_artist_cover(db, artist, source.clone(), directory.as_ref()).await
    {
        return Ok(cover);
    }

    if let Ok(cover) = get_remote_artist_cover(artist, source, size).await {
        log::debug!("Found {} artist cover", api.source());
        return copy_streaming_cover_to_local(db, artist, cover).await;
    }

    Err(ArtistCoverError::NotFound(
        artist.id.clone(),
        "Artist cover remote image not found".to_owned(),
    ))
}

/// Retrieves an artist cover image as a stream of bytes.
///
/// First checks for a local file, then falls back to fetching from remote sources if available.
/// Returns a byte stream suitable for streaming to clients.
///
/// # Errors
///
/// * `ArtistCoverError::NotFound` - If the artist cover was not found
/// * `ArtistCoverError::MusicApi` - If failed to get the artist info
/// * `ArtistCoverError::IO` - If an IO error occurs
/// * `ArtistCoverError::Database` - If a database error occurs
/// * `ArtistCoverError::InvalidSource` - If the `ApiSource` is invalid
pub async fn get_local_artist_cover_bytes(
    api: &dyn MusicApi,
    db: &LibraryDatabase,
    artist: &Artist,
    size: ImageCoverSize,
    try_to_get_stream_size: bool,
) -> Result<CoverBytes, ArtistCoverError> {
    let source = api
        .artist_cover_source(artist, size)
        .await?
        .ok_or_else(|| {
            ArtistCoverError::NotFound(
                artist.id.clone(),
                "Artist cover source not found".to_owned(),
            )
        })?;

    let directory = get_artist_directory(artist);
    if let Ok(cover) = fetch_local_artist_cover_bytes(db, artist, directory.as_ref()).await {
        return Ok(cover);
    }

    if let Ok(cover) =
        get_remote_artist_cover_bytes(artist, source, size, try_to_get_stream_size).await
    {
        return Ok(cover);
    }

    Err(ArtistCoverError::NotFound(
        artist.id.clone(),
        "Artist cover remote image not found".to_owned(),
    ))
}

/// Errors that can occur when fetching local artist cover files.
#[derive(Debug, Error)]
pub enum FetchLocalArtistCoverError {
    /// IO error reading cover file
    #[error(transparent)]
    IO(#[from] std::io::Error),
    /// Database error
    #[error(transparent)]
    Database(#[from] DatabaseError),
    /// No artist cover available
    #[error("No Artist Cover")]
    NoArtistCover,
    /// Invalid or unsupported source type
    #[error("Invalid source")]
    InvalidSource,
}

async fn fetch_local_artist_cover(
    db: &LibraryDatabase,
    artist: &Artist,
    source: ImageCoverSource,
    directory: Option<&String>,
) -> Result<String, FetchLocalArtistCoverError> {
    match source {
        ImageCoverSource::LocalFilePath(cover) => {
            let cover_path = std::path::PathBuf::from(&cover);

            if Path::is_file(&cover_path) {
                return Ok(cover_path.to_str().unwrap().to_string());
            }

            let directory = directory.ok_or(FetchLocalArtistCoverError::NoArtistCover)?;
            let directory_path = std::path::PathBuf::from(directory);

            if let Some(path) = search_for_cover(directory_path, "cover", None, None).await? {
                let new_cover = path.to_str().unwrap().to_string();

                log::debug!(
                    "Updating Artist {} cover file from '{cover}' to '{new_cover}'",
                    &artist.id
                );

                db.update("artists")
                    .where_eq("id", &artist.id)
                    .value("cover", new_cover)
                    .execute(&**db)
                    .await?;

                return Ok(path.to_str().unwrap().to_string());
            }

            Err(FetchLocalArtistCoverError::NoArtistCover)
        }
        ImageCoverSource::RemoteUrl { .. } => Err(FetchLocalArtistCoverError::InvalidSource),
    }
}

async fn fetch_local_artist_cover_bytes(
    db: &LibraryDatabase,
    artist: &Artist,
    directory: Option<&String>,
) -> Result<CoverBytes, FetchLocalArtistCoverError> {
    let cover = artist
        .cover
        .as_ref()
        .ok_or(FetchLocalArtistCoverError::NoArtistCover)?;

    let cover_path = std::path::PathBuf::from(&cover);

    if Path::is_file(&cover_path) {
        let file = tokio::fs::File::open(cover_path.clone()).await?;

        let size = (file.metadata().await).map_or(None, |metadata| Some(metadata.len()));

        return Ok(CoverBytes {
            stream: StalledReadMonitor::new(
                FramedRead::new(file, BytesCodec::new())
                    .map_ok(BytesMut::freeze)
                    .boxed(),
            ),
            size,
        });
    }

    let directory = directory.ok_or(FetchLocalArtistCoverError::NoArtistCover)?;
    let directory_path = std::path::PathBuf::from(directory);

    if let Some(path) = search_for_cover(directory_path, "cover", None, None).await? {
        let new_cover = path.to_str().unwrap().to_string();

        log::debug!(
            "Updating Artist {} cover file from '{cover}' to '{new_cover}'",
            &artist.id
        );

        db.update("artists")
            .where_eq("id", &artist.id)
            .value("cover", new_cover)
            .execute(&**db)
            .await?;

        let file = tokio::fs::File::open(path).await?;

        let size = (file.metadata().await).map_or(None, |metadata| Some(metadata.len()));

        return Ok(CoverBytes {
            stream: StalledReadMonitor::new(
                FramedRead::new(file, BytesCodec::new())
                    .map_ok(BytesMut::freeze)
                    .boxed(),
            ),
            size,
        });
    }

    Err(FetchLocalArtistCoverError::NoArtistCover)
}

async fn copy_streaming_cover_to_local(
    db: &LibraryDatabase,
    artist: &Artist,
    cover: String,
) -> Result<String, ArtistCoverError> {
    log::debug!("Updating Artist {} cover file to '{cover}'", artist.id);

    db.update("artists")
        .where_eq("id", &artist.id)
        .value("cover", cover.clone())
        .execute(&**db)
        .await?;

    Ok(cover)
}

/// Retrieves the file path to an artist cover image at the specified size.
///
/// This is the main public API for getting artist covers. It delegates to `get_local_artist_cover`
/// to handle local and remote sources.
///
/// # Errors
///
/// * `ArtistCoverError::NotFound` - If the artist cover was not found
/// * `ArtistCoverError::MusicApi` - If failed to get the artist info
/// * `ArtistCoverError::IO` - If an IO error occurs
/// * `ArtistCoverError::Database` - If a database error occurs
/// * `ArtistCoverError::InvalidSource` - If the `ApiSource` is invalid
pub async fn get_artist_cover(
    api: &dyn MusicApi,
    db: &LibraryDatabase,
    artist: &Artist,
    size: ImageCoverSize,
) -> Result<String, ArtistCoverError> {
    get_local_artist_cover(api, db, artist, size).await
}

/// Retrieves an artist cover image as a stream of bytes at the specified size.
///
/// This is the main public API for getting artist cover byte streams. It delegates to
/// `get_local_artist_cover_bytes` to handle local and remote sources.
///
/// # Errors
///
/// * `ArtistCoverError::NotFound` - If the artist cover was not found
/// * `ArtistCoverError::MusicApi` - If failed to get the artist info
/// * `ArtistCoverError::IO` - If an IO error occurs
/// * `ArtistCoverError::Database` - If a database error occurs
/// * `ArtistCoverError::InvalidSource` - If the `ApiSource` is invalid
pub async fn get_artist_cover_bytes(
    api: &dyn MusicApi,
    db: &LibraryDatabase,
    artist: &Artist,
    size: ImageCoverSize,
    try_to_get_stream_size: bool,
) -> Result<CoverBytes, ArtistCoverError> {
    get_local_artist_cover_bytes(api, db, artist, size, try_to_get_stream_size).await
}

fn get_remote_artist_cover_request(
    artist: &Artist,
    source: ImageCoverSource,
    size: ImageCoverSize,
) -> Result<ArtistCoverRequest, ArtistCoverError> {
    match source {
        ImageCoverSource::LocalFilePath(_) => Err(ArtistCoverError::InvalidSource),
        ImageCoverSource::RemoteUrl { url, headers } => {
            let file_path = get_artist_cover_path(
                &size.to_string(),
                artist.api_source.as_ref(),
                &artist.id.to_string(),
                &artist.title,
            );

            Ok(ArtistCoverRequest {
                url,
                file_path,
                headers,
            })
        }
    }
}

async fn get_remote_artist_cover(
    artist: &Artist,
    source: ImageCoverSource,
    size: ImageCoverSize,
) -> Result<String, ArtistCoverError> {
    let request = get_remote_artist_cover_request(artist, source, size)?;

    Ok(get_or_fetch_cover_from_remote_url(
        &request.url,
        request.headers.as_deref(),
        &request.file_path,
    )
    .await?)
}

async fn get_remote_artist_cover_bytes(
    artist: &Artist,
    source: ImageCoverSource,
    size: ImageCoverSize,
    try_to_get_stream_size: bool,
) -> Result<CoverBytes, ArtistCoverError> {
    let request = get_remote_artist_cover_request(artist, source, size)?;

    Ok(get_or_fetch_cover_bytes_from_remote_url(
        &request.url,
        request.headers.as_deref(),
        &request.file_path,
        try_to_get_stream_size,
    )
    .await?)
}

struct ArtistCoverRequest {
    url: String,
    file_path: PathBuf,
    headers: Option<Vec<(String, String)>>,
}