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