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 the user's recent listening history.
209 async fn get_recent_tracks_page(&self, page: u32) -> Result<crate::TrackPage> {
210 let tracks = self.get_recent_scrobbles(page).await?;
211 let has_next_page = !tracks.is_empty();
212 Ok(crate::TrackPage {
213 tracks,
214 page_number: page,
215 has_next_page,
216 total_pages: None,
217 })
218 }
219
220 // =============================================================================
221 // CONVENIENCE METHODS - Higher-level helpers and shortcuts
222 // =============================================================================
223
224 /// Discover all scrobble edit variations based on the provided ScrobbleEdit template.
225 ///
226 /// This method analyzes what fields are specified in the input ScrobbleEdit and discovers
227 /// all relevant scrobble instances that match the criteria:
228 /// - If track_name_original is specified: discovers all album variations of that track
229 /// - If only album_name_original is specified: discovers all tracks in that album
230 /// - If neither is specified: discovers all tracks by that artist
231 ///
232 /// Returns fully-specified ExactScrobbleEdit instances with all metadata populated
233 /// from the user's library, ready for editing operations.
234 async fn discover_scrobble_edit_variations(
235 &self,
236 edit: &ScrobbleEdit,
237 ) -> Result<Vec<ExactScrobbleEdit>> {
238 // Use the incremental iterator and collect all results
239 let mut discovery_iterator = self.discover_scrobbles(edit.clone());
240 discovery_iterator.collect_all().await
241 }
242
243 /// Get tracks from a specific album page.
244 async fn get_album_tracks(&self, album_name: &str, artist_name: &str) -> Result<Vec<Track>> {
245 let mut tracks_iterator = self.album_tracks(album_name, artist_name);
246 tracks_iterator.collect_all().await
247 }
248
249 /// Find a scrobble by its timestamp in recent scrobbles.
250 async fn find_scrobble_by_timestamp(&self, timestamp: u64) -> Result<Track> {
251 log::debug!("Searching for scrobble with timestamp {timestamp}");
252
253 // Search through recent scrobbles to find the one with matching timestamp
254 for page in 1..=10 {
255 // Search up to 10 pages of recent scrobbles
256 let scrobbles = self.get_recent_scrobbles(page).await?;
257
258 for scrobble in scrobbles {
259 if let Some(scrobble_timestamp) = scrobble.timestamp {
260 if scrobble_timestamp == timestamp {
261 log::debug!(
262 "Found scrobble: '{}' by '{}' with album: '{:?}', album_artist: '{:?}'",
263 scrobble.name,
264 scrobble.artist,
265 scrobble.album,
266 scrobble.album_artist
267 );
268 return Ok(scrobble);
269 }
270 }
271 }
272 }
273
274 Err(LastFmError::Parse(format!(
275 "Could not find scrobble with timestamp {timestamp}"
276 )))
277 }
278
279 /// Edit album metadata by updating scrobbles with new album name.
280 async fn edit_album(
281 &self,
282 old_album_name: &str,
283 new_album_name: &str,
284 artist_name: &str,
285 ) -> Result<EditResponse> {
286 log::debug!("Editing album '{old_album_name}' -> '{new_album_name}' by '{artist_name}'");
287
288 let edit = ScrobbleEdit::for_album(old_album_name, artist_name, artist_name)
289 .with_album_name(new_album_name);
290
291 self.edit_scrobble(&edit).await
292 }
293
294 /// Edit artist metadata by updating scrobbles with new artist name.
295 ///
296 /// This edits ALL tracks from the artist that are found in recent scrobbles.
297 async fn edit_artist(
298 &self,
299 old_artist_name: &str,
300 new_artist_name: &str,
301 ) -> Result<EditResponse> {
302 log::debug!("Editing artist '{old_artist_name}' -> '{new_artist_name}'");
303
304 let edit = ScrobbleEdit::for_artist(old_artist_name, new_artist_name);
305
306 self.edit_scrobble(&edit).await
307 }
308
309 /// Edit artist metadata for a specific track only.
310 ///
311 /// This edits only the specified track if found in recent scrobbles.
312 async fn edit_artist_for_track(
313 &self,
314 track_name: &str,
315 old_artist_name: &str,
316 new_artist_name: &str,
317 ) -> Result<EditResponse> {
318 log::debug!("Editing artist for track '{track_name}' from '{old_artist_name}' -> '{new_artist_name}'");
319
320 let edit = ScrobbleEdit::from_track_and_artist(track_name, old_artist_name)
321 .with_artist_name(new_artist_name);
322
323 self.edit_scrobble(&edit).await
324 }
325
326 /// Edit artist metadata for all tracks in a specific album.
327 ///
328 /// This edits ALL tracks from the specified album that are found in recent scrobbles.
329 async fn edit_artist_for_album(
330 &self,
331 album_name: &str,
332 old_artist_name: &str,
333 new_artist_name: &str,
334 ) -> Result<EditResponse> {
335 log::debug!("Editing artist for album '{album_name}' from '{old_artist_name}' -> '{new_artist_name}'");
336
337 let edit = ScrobbleEdit::for_album(album_name, old_artist_name, old_artist_name)
338 .with_artist_name(new_artist_name);
339
340 self.edit_scrobble(&edit).await
341 }
342
343 // =============================================================================
344 // SESSION & EVENT MANAGEMENT - Authentication and monitoring
345 // =============================================================================
346
347 /// Extract the current session state for persistence.
348 ///
349 /// This allows you to save the authentication state and restore it later
350 /// without requiring the user to log in again.
351 ///
352 /// # Returns
353 ///
354 /// Returns a [`LastFmEditSession`] that can be serialized and saved.
355 fn get_session(&self) -> LastFmEditSession;
356
357 /// Restore session state from a previously saved session.
358 ///
359 /// This allows you to restore authentication state without logging in again.
360 ///
361 /// # Arguments
362 ///
363 /// * `session` - Previously saved session state
364 fn restore_session(&self, session: LastFmEditSession);
365
366 /// Subscribe to internal client events.
367 ///
368 /// Returns a broadcast receiver that can be used to listen to events like rate limiting.
369 /// Multiple subscribers can listen simultaneously.
370 ///
371 /// # Example
372 /// ```rust,no_run
373 /// use lastfm_edit::{LastFmEditClientImpl, LastFmEditSession, ClientEvent};
374 ///
375 /// let http_client = http_client::native::NativeClient::new();
376 /// let test_session = LastFmEditSession::new("test".to_string(), vec!["sessionid=.test123".to_string()], Some("csrf".to_string()), "https://www.last.fm".to_string());
377 /// let client = LastFmEditClientImpl::from_session(Box::new(http_client), test_session);
378 /// let mut events = client.subscribe();
379 ///
380 /// // Listen for events in a background task
381 /// tokio::spawn(async move {
382 /// while let Ok(event) = events.recv().await {
383 /// match event {
384 /// ClientEvent::RequestStarted { request } => {
385 /// println!("Request started: {}", request.short_description());
386 /// }
387 /// ClientEvent::RequestCompleted { request, status_code, duration_ms } => {
388 /// println!("Request completed: {} - {} ({} ms)", request.short_description(), status_code, duration_ms);
389 /// }
390 /// ClientEvent::RateLimited { delay_seconds, .. } => {
391 /// println!("Rate limited! Waiting {} seconds", delay_seconds);
392 /// }
393 /// ClientEvent::EditAttempted { edit, success, .. } => {
394 /// println!("Edit attempt: '{}' -> '{}' - {}",
395 /// edit.track_name_original, edit.track_name,
396 /// if success { "Success" } else { "Failed" });
397 /// }
398 /// }
399 /// }
400 /// });
401 /// ```
402 fn subscribe(&self) -> ClientEventReceiver;
403
404 /// Get the latest client event without subscribing to future events.
405 ///
406 /// This returns the most recent event that occurred, or `None` if no events have occurred yet.
407 /// Unlike `subscribe()`, this provides instant access to the current state without waiting.
408 ///
409 /// # Example
410 /// ```rust,no_run
411 /// use lastfm_edit::{LastFmEditClientImpl, LastFmEditSession, ClientEvent};
412 ///
413 /// let http_client = http_client::native::NativeClient::new();
414 /// let test_session = LastFmEditSession::new("test".to_string(), vec!["sessionid=.test123".to_string()], Some("csrf".to_string()), "https://www.last.fm".to_string());
415 /// let client = LastFmEditClientImpl::from_session(Box::new(http_client), test_session);
416 ///
417 /// if let Some(ClientEvent::RateLimited { delay_seconds, .. }) = client.latest_event() {
418 /// println!("Currently rate limited for {} seconds", delay_seconds);
419 /// }
420 /// ```
421 fn latest_event(&self) -> Option<ClientEvent>;
422
423 /// Validate if the current session is still working.
424 ///
425 /// This method makes a test request to a protected Last.fm settings page to verify
426 /// that the current session is still valid. If the session has expired or become
427 /// invalid, Last.fm will redirect to the login page.
428 ///
429 /// This is useful for checking session validity before attempting operations that
430 /// require authentication, especially after loading a previously saved session.
431 ///
432 /// # Returns
433 ///
434 /// Returns `true` if the session is valid and can be used for authenticated operations,
435 /// `false` if the session is invalid or expired.
436 async fn validate_session(&self) -> bool;
437}