lastfm_edit/trait.rs
1use crate::iterator::AsyncPaginatedIterator;
2use crate::types::{
3 Album, Artist, ArtistPage, ClientEvent, ClientEventReceiver, EditResponse, ExactScrobbleEdit,
4 LastFmEditSession, 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 tracks directly using the paginated endpoint.
177 ///
178 /// This alternative approach uses
179 /// `/user/{username}/library/music/{artist}/+tracks` directly with
180 /// pagination, which is more efficient than the album-based approach since
181 /// it doesn't need to iterate through albums first. The downside of this
182 /// approach is that the tracks will not come with album information, which
183 /// will need to get looked up eventually in the process of making edits.
184 fn artist_tracks_direct(&self, artist: &str) -> Box<dyn AsyncPaginatedIterator<Track>>;
185
186 /// Create an iterator for browsing an artist's albums from the user's library.
187 fn artist_albums(&self, artist: &str) -> Box<dyn AsyncPaginatedIterator<Album>>;
188
189 /// Create an iterator for browsing tracks from a specific album.
190 fn album_tracks(
191 &self,
192 album_name: &str,
193 artist_name: &str,
194 ) -> Box<dyn AsyncPaginatedIterator<Track>>;
195
196 /// Create an iterator for browsing the user's recent tracks/scrobbles.
197 fn recent_tracks(&self) -> Box<dyn AsyncPaginatedIterator<Track>>;
198
199 /// Create an iterator for browsing the user's recent tracks starting from a specific page.
200 fn recent_tracks_from_page(&self, starting_page: u32)
201 -> Box<dyn AsyncPaginatedIterator<Track>>;
202
203 /// Create an iterator for searching tracks in the user's library.
204 ///
205 /// This returns an iterator that uses Last.fm's library search functionality
206 /// to find tracks matching the provided query string. The iterator handles
207 /// pagination automatically.
208 ///
209 /// # Arguments
210 ///
211 /// * `query` - The search query (e.g., "remaster", "live", artist name, etc.)
212 ///
213 /// # Returns
214 ///
215 /// Returns a `SearchTracksIterator` for streaming search results.
216 fn search_tracks(&self, query: &str) -> Box<dyn AsyncPaginatedIterator<Track>>;
217
218 /// Create an iterator for searching albums in the user's library.
219 ///
220 /// This returns an iterator that uses Last.fm's library search functionality
221 /// to find albums matching the provided query string. The iterator handles
222 /// pagination automatically.
223 ///
224 /// # Arguments
225 ///
226 /// * `query` - The search query (e.g., "remaster", "deluxe", artist name, etc.)
227 ///
228 /// # Returns
229 ///
230 /// Returns a `SearchAlbumsIterator` for streaming search results.
231 fn search_albums(&self, query: &str) -> Box<dyn AsyncPaginatedIterator<Album>>;
232
233 /// Create an iterator for searching artists in the user's library.
234 ///
235 /// This returns an iterator that uses Last.fm's library search functionality
236 /// to find artists matching the provided query string. The iterator handles
237 /// pagination automatically.
238 ///
239 /// # Arguments
240 ///
241 /// * `query` - The search query (e.g., artist name, partial match, etc.)
242 ///
243 /// # Returns
244 ///
245 /// Returns a `SearchArtistsIterator` for streaming search results.
246 fn search_artists(&self, query: &str) -> Box<dyn AsyncPaginatedIterator<Artist>>;
247
248 // =============================================================================
249 // SEARCH METHODS - Library search functionality
250 // =============================================================================
251
252 /// Get a single page of track search results from the user's library.
253 ///
254 /// This performs a search using Last.fm's library search functionality,
255 /// returning one page of tracks that match the provided query string.
256 /// For iterator-based access, use [`search_tracks`](Self::search_tracks) instead.
257 ///
258 /// # Arguments
259 ///
260 /// * `query` - The search query (e.g., "remaster", "live", artist name, etc.)
261 /// * `page` - The page number to retrieve (1-based)
262 ///
263 /// # Returns
264 ///
265 /// Returns a `TrackPage` containing the search results with pagination information.
266 async fn search_tracks_page(&self, query: &str, page: u32) -> Result<crate::TrackPage>;
267
268 /// Get a single page of album search results from the user's library.
269 ///
270 /// This performs a search using Last.fm's library search functionality,
271 /// returning one page of albums that match the provided query string.
272 /// For iterator-based access, use [`search_albums`](Self::search_albums) instead.
273 ///
274 /// # Arguments
275 ///
276 /// * `query` - The search query (e.g., "remaster", "deluxe", artist name, etc.)
277 /// * `page` - The page number to retrieve (1-based)
278 ///
279 /// # Returns
280 ///
281 /// Returns an `AlbumPage` containing the search results with pagination information.
282 async fn search_albums_page(&self, query: &str, page: u32) -> Result<crate::AlbumPage>;
283
284 /// Get a single page of artist search results from the user's library.
285 ///
286 /// This performs a search using Last.fm's library search functionality,
287 /// returning one page of artists that match the provided query string.
288 /// For iterator-based access, use [`search_artists`](Self::search_artists) instead.
289 ///
290 /// # Arguments
291 ///
292 /// * `query` - The search query (e.g., artist name, partial match, etc.)
293 /// * `page` - The page number to retrieve (1-based)
294 ///
295 /// # Returns
296 ///
297 /// Returns an `ArtistPage` containing the search results with pagination information.
298 async fn search_artists_page(&self, query: &str, page: u32) -> Result<crate::ArtistPage>;
299
300 // =============================================================================
301 // CORE DATA METHODS - Essential data access
302 // =============================================================================
303
304 /// Get the currently authenticated username.
305 fn username(&self) -> String;
306
307 /// Find the most recent scrobble for a specific track.
308 async fn find_recent_scrobble_for_track(
309 &self,
310 track_name: &str,
311 artist_name: &str,
312 max_pages: u32,
313 ) -> Result<Option<Track>>;
314
315 /// Get a page of artists from the user's library.
316 async fn get_artists_page(&self, page: u32) -> Result<ArtistPage>;
317
318 /// Get a page of tracks from the user's library for the specified artist.
319 async fn get_artist_tracks_page(&self, artist: &str, page: u32) -> Result<crate::TrackPage>;
320
321 /// Get a page of albums from the user's library for the specified artist.
322 async fn get_artist_albums_page(&self, artist: &str, page: u32) -> Result<crate::AlbumPage>;
323
324 /// Get a page of tracks from a specific album in the user's library.
325 async fn get_album_tracks_page(
326 &self,
327 album_name: &str,
328 artist_name: &str,
329 page: u32,
330 ) -> Result<crate::TrackPage>;
331
332 /// Get a page of tracks from the user's recent listening history.
333 async fn get_recent_tracks_page(&self, page: u32) -> Result<crate::TrackPage>;
334
335 // =============================================================================
336 // CONVENIENCE METHODS - Higher-level helpers and shortcuts
337 // =============================================================================
338
339 /// Discover all scrobble edit variations based on the provided ScrobbleEdit template.
340 ///
341 /// This method analyzes what fields are specified in the input ScrobbleEdit and discovers
342 /// all relevant scrobble instances that match the criteria:
343 /// - If track_name_original is specified: discovers all album variations of that track
344 /// - If only album_name_original is specified: discovers all tracks in that album
345 /// - If neither is specified: discovers all tracks by that artist
346 ///
347 /// Returns fully-specified ExactScrobbleEdit instances with all metadata populated
348 /// from the user's library, ready for editing operations.
349 async fn discover_scrobble_edit_variations(
350 &self,
351 edit: &ScrobbleEdit,
352 ) -> Result<Vec<ExactScrobbleEdit>> {
353 // Use the incremental iterator and collect all results
354 let mut discovery_iterator = self.discover_scrobbles(edit.clone());
355 discovery_iterator.collect_all().await
356 }
357
358 /// Edit album metadata by updating scrobbles with new album name.
359 async fn edit_album(
360 &self,
361 old_album_name: &str,
362 new_album_name: &str,
363 artist_name: &str,
364 ) -> Result<EditResponse> {
365 log::debug!("Editing album '{old_album_name}' -> '{new_album_name}' by '{artist_name}'");
366
367 let edit = ScrobbleEdit::for_album(old_album_name, artist_name, artist_name)
368 .with_album_name(new_album_name);
369
370 self.edit_scrobble(&edit).await
371 }
372
373 /// Edit artist metadata by updating scrobbles with new artist name.
374 ///
375 /// This edits ALL tracks from the artist that are found in recent scrobbles.
376 async fn edit_artist(
377 &self,
378 old_artist_name: &str,
379 new_artist_name: &str,
380 ) -> Result<EditResponse> {
381 log::debug!("Editing artist '{old_artist_name}' -> '{new_artist_name}'");
382
383 let edit = ScrobbleEdit::for_artist(old_artist_name, new_artist_name);
384
385 self.edit_scrobble(&edit).await
386 }
387
388 /// Edit artist metadata for a specific track only.
389 ///
390 /// This edits only the specified track if found in recent scrobbles.
391 async fn edit_artist_for_track(
392 &self,
393 track_name: &str,
394 old_artist_name: &str,
395 new_artist_name: &str,
396 ) -> Result<EditResponse> {
397 log::debug!("Editing artist for track '{track_name}' from '{old_artist_name}' -> '{new_artist_name}'");
398
399 let edit = ScrobbleEdit::from_track_and_artist(track_name, old_artist_name)
400 .with_artist_name(new_artist_name);
401
402 self.edit_scrobble(&edit).await
403 }
404
405 /// Edit artist metadata for all tracks in a specific album.
406 ///
407 /// This edits ALL tracks from the specified album that are found in recent scrobbles.
408 async fn edit_artist_for_album(
409 &self,
410 album_name: &str,
411 old_artist_name: &str,
412 new_artist_name: &str,
413 ) -> Result<EditResponse> {
414 log::debug!("Editing artist for album '{album_name}' from '{old_artist_name}' -> '{new_artist_name}'");
415
416 let edit = ScrobbleEdit::for_album(album_name, old_artist_name, old_artist_name)
417 .with_artist_name(new_artist_name);
418
419 self.edit_scrobble(&edit).await
420 }
421
422 // =============================================================================
423 // SESSION & EVENT MANAGEMENT - Authentication and monitoring
424 // =============================================================================
425
426 /// Extract the current session state for persistence.
427 ///
428 /// This allows you to save the authentication state and restore it later
429 /// without requiring the user to log in again.
430 ///
431 /// # Returns
432 ///
433 /// Returns a [`LastFmEditSession`] that can be serialized and saved.
434 fn get_session(&self) -> LastFmEditSession;
435
436 /// Subscribe to internal client events.
437 ///
438 /// Returns a broadcast receiver that can be used to listen to events like rate limiting.
439 /// Multiple subscribers can listen simultaneously.
440 ///
441 /// # Example
442 /// ```rust,no_run
443 /// use lastfm_edit::{LastFmEditClientImpl, LastFmEditSession, ClientEvent};
444 ///
445 /// let http_client = http_client::native::NativeClient::new();
446 /// let test_session = LastFmEditSession::new("test".to_string(), vec!["sessionid=.test123".to_string()], Some("csrf".to_string()), "https://www.last.fm".to_string());
447 /// let client = LastFmEditClientImpl::from_session(Box::new(http_client), test_session);
448 /// let mut events = client.subscribe();
449 ///
450 /// // Listen for events in a background task
451 /// tokio::spawn(async move {
452 /// while let Ok(event) = events.recv().await {
453 /// match event {
454 /// ClientEvent::RequestStarted { request } => {
455 /// println!("Request started: {}", request.short_description());
456 /// }
457 /// ClientEvent::RequestCompleted { request, status_code, duration_ms } => {
458 /// println!("Request completed: {} - {} ({} ms)", request.short_description(), status_code, duration_ms);
459 /// }
460 /// ClientEvent::RateLimited { delay_seconds, .. } => {
461 /// println!("Rate limited! Waiting {} seconds", delay_seconds);
462 /// }
463 /// ClientEvent::RateLimitEnded { total_rate_limit_duration_seconds, .. } => {
464 /// println!("Rate limiting ended after {} seconds", total_rate_limit_duration_seconds);
465 /// }
466 /// ClientEvent::EditAttempted { edit, success, .. } => {
467 /// println!("Edit attempt: '{}' -> '{}' - {}",
468 /// edit.track_name_original, edit.track_name,
469 /// if success { "Success" } else { "Failed" });
470 /// }
471 /// }
472 /// }
473 /// });
474 /// ```
475 fn subscribe(&self) -> ClientEventReceiver;
476
477 /// Get the latest client event without subscribing to future events.
478 ///
479 /// This returns the most recent event that occurred, or `None` if no events have occurred yet.
480 /// Unlike `subscribe()`, this provides instant access to the current state without waiting.
481 ///
482 /// # Example
483 /// ```rust,no_run
484 /// use lastfm_edit::{LastFmEditClientImpl, LastFmEditSession, ClientEvent};
485 ///
486 /// let http_client = http_client::native::NativeClient::new();
487 /// let test_session = LastFmEditSession::new("test".to_string(), vec!["sessionid=.test123".to_string()], Some("csrf".to_string()), "https://www.last.fm".to_string());
488 /// let client = LastFmEditClientImpl::from_session(Box::new(http_client), test_session);
489 ///
490 /// if let Some(ClientEvent::RateLimited { delay_seconds, .. }) = client.latest_event() {
491 /// println!("Currently rate limited for {} seconds", delay_seconds);
492 /// }
493 /// ```
494 fn latest_event(&self) -> Option<ClientEvent>;
495
496 /// Validate if the current session is still working.
497 ///
498 /// This method makes a test request to a protected Last.fm settings page to verify
499 /// that the current session is still valid. If the session has expired or become
500 /// invalid, Last.fm will redirect to the login page.
501 ///
502 /// This is useful for checking session validity before attempting operations that
503 /// require authentication, especially after loading a previously saved session.
504 ///
505 /// # Returns
506 ///
507 /// Returns `true` if the session is valid and can be used for authenticated operations,
508 /// `false` if the session is invalid or expired.
509 async fn validate_session(&self) -> bool;
510}