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