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