lastfm_edit/
trait.rs

1use crate::iterator::AsyncPaginatedIterator;
2use crate::types::{
3    Album, Artist, ArtistPage, ClientEvent, ClientEventReceiver, EditResponse, ExactScrobbleEdit,
4    LastFmEditSession, LastFmError, ScrobbleEdit, Track,
5};
6use crate::Result;
7use async_trait::async_trait;
8
9/// Trait for Last.fm client operations that can be mocked for testing.
10///
11/// This trait abstracts the core functionality needed for Last.fm scrobble editing
12/// to enable easy mocking and testing. All methods that perform network operations or
13/// state changes are included to support comprehensive test coverage.
14///
15/// # Mocking Support
16///
17/// When the `mock` feature is enabled, this crate provides `MockLastFmEditClient`
18/// that implements this trait using the `mockall` library.
19///
20#[cfg_attr(feature = "mock", mockall::automock)]
21#[async_trait(?Send)]
22pub trait LastFmEditClient {
23    // =============================================================================
24    // CORE EDITING METHODS - Most important functionality
25    // =============================================================================
26
27    /// Edit scrobbles by discovering and updating all matching instances.
28    ///
29    /// This is the main editing method that automatically discovers all scrobble instances
30    /// that match the provided criteria and applies the specified changes to each one.
31    ///
32    /// # How it works
33    ///
34    /// 1. **Discovery**: Analyzes the `ScrobbleEdit` to determine what to search for:
35    ///    - If `track_name_original` is specified: finds all album variations of that track
36    ///    - If only `album_name_original` is specified: finds all tracks in that album
37    ///    - If neither is specified: finds all tracks by that artist
38    ///
39    /// 2. **Enrichment**: For each discovered scrobble, extracts complete metadata
40    ///    including album artist information from the user's library
41    ///
42    /// 3. **Editing**: Applies the requested changes to each discovered instance
43    ///
44    /// # Arguments
45    ///
46    /// * `edit` - A `ScrobbleEdit` specifying what to find and how to change it
47    ///
48    /// # Returns
49    ///
50    /// Returns an `EditResponse` containing results for all edited scrobbles, including:
51    /// - Overall success status
52    /// - Individual results for each scrobble instance
53    /// - Detailed error messages if any edits fail
54    ///
55    /// # Errors
56    ///
57    /// Returns `LastFmError::Parse` if no matching scrobbles are found, or other errors
58    /// for network/authentication issues.
59    ///
60    /// # Example
61    ///
62    /// ```rust,no_run
63    /// # use lastfm_edit::{LastFmEditClient, ScrobbleEdit, Result};
64    /// # async fn example(client: &dyn LastFmEditClient) -> Result<()> {
65    /// // Change track name for all instances of a track
66    /// let edit = ScrobbleEdit::from_track_and_artist("Old Track Name", "Artist")
67    ///     .with_track_name("New Track Name");
68    ///
69    /// let response = client.edit_scrobble(&edit).await?;
70    /// if response.success() {
71    ///     println!("Successfully edited {} scrobbles", response.total_edits());
72    /// }
73    /// # Ok(())
74    /// # }
75    /// ```
76    async fn edit_scrobble(&self, edit: &ScrobbleEdit) -> Result<EditResponse>;
77
78    /// Edit a single scrobble with complete information and retry logic.
79    ///
80    /// This method performs a single edit operation on a fully-specified scrobble.
81    /// Unlike [`edit_scrobble`], this method does not perform discovery, enrichment,
82    /// or multiple edits - it edits exactly one scrobble instance.
83    ///
84    /// # Key Differences from `edit_scrobble`
85    ///
86    /// - **No discovery**: Requires a fully-specified `ExactScrobbleEdit`
87    /// - **Single edit**: Only edits one scrobble instance
88    /// - **No enrichment**: All fields must be provided upfront
89    /// - **Retry logic**: Automatically retries on rate limiting
90    ///
91    /// # Arguments
92    ///
93    /// * `exact_edit` - A fully-specified edit with all required fields populated,
94    ///   including original metadata and timestamps
95    /// * `max_retries` - Maximum number of retry attempts for rate limiting.
96    ///   The method will wait with exponential backoff between retries.
97    ///
98    /// # Returns
99    ///
100    /// Returns an `EditResponse` with a single result indicating success or failure.
101    /// If max retries are exceeded due to rate limiting, returns a failed response
102    /// rather than an error.
103    ///
104    /// # Example
105    ///
106    /// ```rust,no_run
107    /// # use lastfm_edit::{LastFmEditClient, ExactScrobbleEdit, Result};
108    /// # async fn example(client: &dyn LastFmEditClient) -> Result<()> {
109    /// let exact_edit = ExactScrobbleEdit::new(
110    ///     "Original Track".to_string(),
111    ///     "Original Album".to_string(),
112    ///     "Artist".to_string(),
113    ///     "Artist".to_string(),
114    ///     "New Track Name".to_string(),
115    ///     "Original Album".to_string(),
116    ///     "Artist".to_string(),
117    ///     "Artist".to_string(),
118    ///     1640995200, // timestamp
119    ///     false
120    /// );
121    ///
122    /// let response = client.edit_scrobble_single(&exact_edit, 3).await?;
123    /// # Ok(())
124    /// # }
125    /// ```
126    async fn edit_scrobble_single(
127        &self,
128        exact_edit: &ExactScrobbleEdit,
129        max_retries: u32,
130    ) -> Result<EditResponse>;
131
132    /// Delete a scrobble by its identifying information.
133    ///
134    /// This method deletes a specific scrobble from the user's library using the
135    /// artist name, track name, and timestamp to uniquely identify it.
136    ///
137    /// # Arguments
138    ///
139    /// * `artist_name` - The artist name of the scrobble to delete
140    /// * `track_name` - The track name of the scrobble to delete
141    /// * `timestamp` - The unix timestamp of the scrobble to delete
142    ///
143    /// # Returns
144    ///
145    /// Returns `true` if the deletion was successful, `false` otherwise.
146    async fn delete_scrobble(
147        &self,
148        artist_name: &str,
149        track_name: &str,
150        timestamp: u64,
151    ) -> Result<bool>;
152
153    /// Create an incremental discovery iterator for scrobble editing.
154    ///
155    /// This returns the appropriate discovery iterator based on what fields are specified
156    /// in the ScrobbleEdit. The iterator yields `ExactScrobbleEdit` results incrementally,
157    /// which helps avoid rate limiting issues when discovering many scrobbles.
158    ///
159    /// Returns a `Box<dyn AsyncDiscoveryIterator<ExactScrobbleEdit>>` to handle the different
160    /// discovery strategies uniformly.
161    fn discover_scrobbles(
162        &self,
163        edit: ScrobbleEdit,
164    ) -> Box<dyn crate::AsyncDiscoveryIterator<crate::ExactScrobbleEdit>>;
165
166    // =============================================================================
167    // ITERATOR METHODS - Core library browsing functionality
168    // =============================================================================
169
170    /// Create an iterator for browsing all artists in the user's library.
171    fn artists(&self) -> Box<dyn AsyncPaginatedIterator<Artist>>;
172
173    /// Create an iterator for browsing an artist's tracks from the user's library.
174    fn artist_tracks(&self, artist: &str) -> Box<dyn AsyncPaginatedIterator<Track>>;
175
176    /// Create an iterator for browsing an artist's albums from the user's library.
177    fn artist_albums(&self, artist: &str) -> Box<dyn AsyncPaginatedIterator<Album>>;
178
179    /// Create an iterator for browsing tracks from a specific album.
180    fn album_tracks(
181        &self,
182        album_name: &str,
183        artist_name: &str,
184    ) -> Box<dyn AsyncPaginatedIterator<Track>>;
185
186    /// Create an iterator for browsing the user's recent tracks/scrobbles.
187    fn recent_tracks(&self) -> Box<dyn AsyncPaginatedIterator<Track>>;
188
189    /// Create an iterator for browsing the user's recent tracks starting from a specific page.
190    fn recent_tracks_from_page(&self, starting_page: u32)
191        -> Box<dyn AsyncPaginatedIterator<Track>>;
192
193    /// Create an iterator for searching tracks in the user's library.
194    ///
195    /// This returns an iterator that uses Last.fm's library search functionality
196    /// to find tracks matching the provided query string. The iterator handles
197    /// pagination automatically.
198    ///
199    /// # Arguments
200    ///
201    /// * `query` - The search query (e.g., "remaster", "live", artist name, etc.)
202    ///
203    /// # Returns
204    ///
205    /// Returns a `SearchTracksIterator` for streaming search results.
206    fn search_tracks(&self, query: &str) -> Box<dyn AsyncPaginatedIterator<Track>>;
207
208    /// Create an iterator for searching albums in the user's library.
209    ///
210    /// This returns an iterator that uses Last.fm's library search functionality
211    /// to find albums matching the provided query string. The iterator handles
212    /// pagination automatically.
213    ///
214    /// # Arguments
215    ///
216    /// * `query` - The search query (e.g., "remaster", "deluxe", artist name, etc.)
217    ///
218    /// # Returns
219    ///
220    /// Returns a `SearchAlbumsIterator` for streaming search results.
221    fn search_albums(&self, query: &str) -> Box<dyn AsyncPaginatedIterator<Album>>;
222
223    // =============================================================================
224    // SEARCH METHODS - Library search functionality
225    // =============================================================================
226
227    /// Get a single page of track search results from the user's library.
228    ///
229    /// This performs a search using Last.fm's library search functionality,
230    /// returning one page of tracks that match the provided query string.
231    /// For iterator-based access, use [`search_tracks`](Self::search_tracks) instead.
232    ///
233    /// # Arguments
234    ///
235    /// * `query` - The search query (e.g., "remaster", "live", artist name, etc.)
236    /// * `page` - The page number to retrieve (1-based)
237    ///
238    /// # Returns
239    ///
240    /// Returns a `TrackPage` containing the search results with pagination information.
241    async fn search_tracks_page(&self, query: &str, page: u32) -> Result<crate::TrackPage>;
242
243    /// Get a single page of album search results from the user's library.
244    ///
245    /// This performs a search using Last.fm's library search functionality,
246    /// returning one page of albums that match the provided query string.
247    /// For iterator-based access, use [`search_albums`](Self::search_albums) instead.
248    ///
249    /// # Arguments
250    ///
251    /// * `query` - The search query (e.g., "remaster", "deluxe", artist name, etc.)
252    /// * `page` - The page number to retrieve (1-based)
253    ///
254    /// # Returns
255    ///
256    /// Returns an `AlbumPage` containing the search results with pagination information.
257    async fn search_albums_page(&self, query: &str, page: u32) -> Result<crate::AlbumPage>;
258
259    // =============================================================================
260    // CORE DATA METHODS - Essential data access
261    // =============================================================================
262
263    /// Get the currently authenticated username.
264    fn username(&self) -> String;
265
266    /// Fetch recent scrobbles from the user's listening history.
267    async fn get_recent_scrobbles(&self, page: u32) -> Result<Vec<Track>>;
268
269    /// Find the most recent scrobble for a specific track.
270    async fn find_recent_scrobble_for_track(
271        &self,
272        track_name: &str,
273        artist_name: &str,
274        max_pages: u32,
275    ) -> Result<Option<Track>>;
276
277    /// Get a page of artists from the user's library.
278    async fn get_artists_page(&self, page: u32) -> Result<ArtistPage>;
279
280    /// Get a page of tracks from the user's library for the specified artist.
281    async fn get_artist_tracks_page(&self, artist: &str, page: u32) -> Result<crate::TrackPage>;
282
283    /// Get a page of albums from the user's library for the specified artist.
284    async fn get_artist_albums_page(&self, artist: &str, page: u32) -> Result<crate::AlbumPage>;
285
286    /// Get a page of tracks from a specific album in the user's library.
287    async fn get_album_tracks_page(
288        &self,
289        album_name: &str,
290        artist_name: &str,
291        page: u32,
292    ) -> Result<crate::TrackPage>;
293
294    /// Get a page of tracks from the user's recent listening history.
295    async fn get_recent_tracks_page(&self, page: u32) -> Result<crate::TrackPage> {
296        let tracks = self.get_recent_scrobbles(page).await?;
297        let has_next_page = !tracks.is_empty();
298        Ok(crate::TrackPage {
299            tracks,
300            page_number: page,
301            has_next_page,
302            total_pages: None,
303        })
304    }
305
306    // =============================================================================
307    // CONVENIENCE METHODS - Higher-level helpers and shortcuts
308    // =============================================================================
309
310    /// Discover all scrobble edit variations based on the provided ScrobbleEdit template.
311    ///
312    /// This method analyzes what fields are specified in the input ScrobbleEdit and discovers
313    /// all relevant scrobble instances that match the criteria:
314    /// - If track_name_original is specified: discovers all album variations of that track
315    /// - If only album_name_original is specified: discovers all tracks in that album
316    /// - If neither is specified: discovers all tracks by that artist
317    ///
318    /// Returns fully-specified ExactScrobbleEdit instances with all metadata populated
319    /// from the user's library, ready for editing operations.
320    async fn discover_scrobble_edit_variations(
321        &self,
322        edit: &ScrobbleEdit,
323    ) -> Result<Vec<ExactScrobbleEdit>> {
324        // Use the incremental iterator and collect all results
325        let mut discovery_iterator = self.discover_scrobbles(edit.clone());
326        discovery_iterator.collect_all().await
327    }
328
329    /// Get tracks from a specific album page.
330    async fn get_album_tracks(&self, album_name: &str, artist_name: &str) -> Result<Vec<Track>> {
331        let mut tracks_iterator = self.album_tracks(album_name, artist_name);
332        tracks_iterator.collect_all().await
333    }
334
335    /// Find a scrobble by its timestamp in recent scrobbles.
336    async fn find_scrobble_by_timestamp(&self, timestamp: u64) -> Result<Track> {
337        log::debug!("Searching for scrobble with timestamp {timestamp}");
338
339        // Search through recent scrobbles to find the one with matching timestamp
340        for page in 1..=10 {
341            // Search up to 10 pages of recent scrobbles
342            let scrobbles = self.get_recent_scrobbles(page).await?;
343
344            for scrobble in scrobbles {
345                if let Some(scrobble_timestamp) = scrobble.timestamp {
346                    if scrobble_timestamp == timestamp {
347                        log::debug!(
348                            "Found scrobble: '{}' by '{}' with album: '{:?}', album_artist: '{:?}'",
349                            scrobble.name,
350                            scrobble.artist,
351                            scrobble.album,
352                            scrobble.album_artist
353                        );
354                        return Ok(scrobble);
355                    }
356                }
357            }
358        }
359
360        Err(LastFmError::Parse(format!(
361            "Could not find scrobble with timestamp {timestamp}"
362        )))
363    }
364
365    /// Edit album metadata by updating scrobbles with new album name.
366    async fn edit_album(
367        &self,
368        old_album_name: &str,
369        new_album_name: &str,
370        artist_name: &str,
371    ) -> Result<EditResponse> {
372        log::debug!("Editing album '{old_album_name}' -> '{new_album_name}' by '{artist_name}'");
373
374        let edit = ScrobbleEdit::for_album(old_album_name, artist_name, artist_name)
375            .with_album_name(new_album_name);
376
377        self.edit_scrobble(&edit).await
378    }
379
380    /// Edit artist metadata by updating scrobbles with new artist name.
381    ///
382    /// This edits ALL tracks from the artist that are found in recent scrobbles.
383    async fn edit_artist(
384        &self,
385        old_artist_name: &str,
386        new_artist_name: &str,
387    ) -> Result<EditResponse> {
388        log::debug!("Editing artist '{old_artist_name}' -> '{new_artist_name}'");
389
390        let edit = ScrobbleEdit::for_artist(old_artist_name, new_artist_name);
391
392        self.edit_scrobble(&edit).await
393    }
394
395    /// Edit artist metadata for a specific track only.
396    ///
397    /// This edits only the specified track if found in recent scrobbles.
398    async fn edit_artist_for_track(
399        &self,
400        track_name: &str,
401        old_artist_name: &str,
402        new_artist_name: &str,
403    ) -> Result<EditResponse> {
404        log::debug!("Editing artist for track '{track_name}' from '{old_artist_name}' -> '{new_artist_name}'");
405
406        let edit = ScrobbleEdit::from_track_and_artist(track_name, old_artist_name)
407            .with_artist_name(new_artist_name);
408
409        self.edit_scrobble(&edit).await
410    }
411
412    /// Edit artist metadata for all tracks in a specific album.
413    ///
414    /// This edits ALL tracks from the specified album that are found in recent scrobbles.
415    async fn edit_artist_for_album(
416        &self,
417        album_name: &str,
418        old_artist_name: &str,
419        new_artist_name: &str,
420    ) -> Result<EditResponse> {
421        log::debug!("Editing artist for album '{album_name}' from '{old_artist_name}' -> '{new_artist_name}'");
422
423        let edit = ScrobbleEdit::for_album(album_name, old_artist_name, old_artist_name)
424            .with_artist_name(new_artist_name);
425
426        self.edit_scrobble(&edit).await
427    }
428
429    // =============================================================================
430    // SESSION & EVENT MANAGEMENT - Authentication and monitoring
431    // =============================================================================
432
433    /// Extract the current session state for persistence.
434    ///
435    /// This allows you to save the authentication state and restore it later
436    /// without requiring the user to log in again.
437    ///
438    /// # Returns
439    ///
440    /// Returns a [`LastFmEditSession`] that can be serialized and saved.
441    fn get_session(&self) -> LastFmEditSession;
442
443    /// Restore session state from a previously saved session.
444    ///
445    /// This allows you to restore authentication state without logging in again.
446    ///
447    /// # Arguments
448    ///
449    /// * `session` - Previously saved session state
450    fn restore_session(&self, session: LastFmEditSession);
451
452    /// Subscribe to internal client events.
453    ///
454    /// Returns a broadcast receiver that can be used to listen to events like rate limiting.
455    /// Multiple subscribers can listen simultaneously.
456    ///
457    /// # Example
458    /// ```rust,no_run
459    /// use lastfm_edit::{LastFmEditClientImpl, LastFmEditSession, ClientEvent};
460    ///
461    /// let http_client = http_client::native::NativeClient::new();
462    /// let test_session = LastFmEditSession::new("test".to_string(), vec!["sessionid=.test123".to_string()], Some("csrf".to_string()), "https://www.last.fm".to_string());
463    /// let client = LastFmEditClientImpl::from_session(Box::new(http_client), test_session);
464    /// let mut events = client.subscribe();
465    ///
466    /// // Listen for events in a background task
467    /// tokio::spawn(async move {
468    ///     while let Ok(event) = events.recv().await {
469    ///         match event {
470    ///             ClientEvent::RequestStarted { request } => {
471    ///                 println!("Request started: {}", request.short_description());
472    ///             }
473    ///             ClientEvent::RequestCompleted { request, status_code, duration_ms } => {
474    ///                 println!("Request completed: {} - {} ({} ms)", request.short_description(), status_code, duration_ms);
475    ///             }
476    ///             ClientEvent::RateLimited { delay_seconds, .. } => {
477    ///                 println!("Rate limited! Waiting {} seconds", delay_seconds);
478    ///             }
479    ///             ClientEvent::RateLimitEnded { total_rate_limit_duration_seconds, .. } => {
480    ///                 println!("Rate limiting ended after {} seconds", total_rate_limit_duration_seconds);
481    ///             }
482    ///             ClientEvent::EditAttempted { edit, success, .. } => {
483    ///                 println!("Edit attempt: '{}' -> '{}' - {}",
484    ///                          edit.track_name_original, edit.track_name,
485    ///                          if success { "Success" } else { "Failed" });
486    ///             }
487    ///         }
488    ///     }
489    /// });
490    /// ```
491    fn subscribe(&self) -> ClientEventReceiver;
492
493    /// Get the latest client event without subscribing to future events.
494    ///
495    /// This returns the most recent event that occurred, or `None` if no events have occurred yet.
496    /// Unlike `subscribe()`, this provides instant access to the current state without waiting.
497    ///
498    /// # Example
499    /// ```rust,no_run
500    /// use lastfm_edit::{LastFmEditClientImpl, LastFmEditSession, ClientEvent};
501    ///
502    /// let http_client = http_client::native::NativeClient::new();
503    /// let test_session = LastFmEditSession::new("test".to_string(), vec!["sessionid=.test123".to_string()], Some("csrf".to_string()), "https://www.last.fm".to_string());
504    /// let client = LastFmEditClientImpl::from_session(Box::new(http_client), test_session);
505    ///
506    /// if let Some(ClientEvent::RateLimited { delay_seconds, .. }) = client.latest_event() {
507    ///     println!("Currently rate limited for {} seconds", delay_seconds);
508    /// }
509    /// ```
510    fn latest_event(&self) -> Option<ClientEvent>;
511
512    /// Validate if the current session is still working.
513    ///
514    /// This method makes a test request to a protected Last.fm settings page to verify
515    /// that the current session is still valid. If the session has expired or become
516    /// invalid, Last.fm will redirect to the login page.
517    ///
518    /// This is useful for checking session validity before attempting operations that
519    /// require authentication, especially after loading a previously saved session.
520    ///
521    /// # Returns
522    ///
523    /// Returns `true` if the session is valid and can be used for authenticated operations,
524    /// `false` if the session is invalid or expired.
525    async fn validate_session(&self) -> bool;
526}