# newMusic Application - Developer Guide ## Overview This document provides comprehensive documentation for the newMusic application, a sophisticated music download manager with Spotify integration. The application enables users to search, download, and organize music from the Soulseek network while providing advanced Spotify matching capabilities for metadata enhancement and folder organization. ## Architecture The application follows a modular architecture with clear separation of concerns: - **Core Module**: Business logic and external service integrations - **UI Module**: Qt-based user interface components - **Services Module**: High-level service orchestration - **Main Module**: Application entry point and global management ## Key Components ### Core Components #### SoulseekClient (`/core/soulseek_client.py`) Primary interface for Soulseek P2P network operations. **Key Functions:** - `search()` - Performs comprehensive search with real-time progress tracking - `download()` - Initiates file downloads from network peers - `search_and_download_best()` - Automated search and download of highest quality matches - `get_all_downloads()` - Retrieves status of all active downloads - `cancel_download()` - Cancels specific downloads by ID - `clear_all_completed_downloads()` - Batch cleanup of completed downloads #### SpotifyClient (`/core/spotify_client.py`) OAuth-authenticated Spotify Web API integration. **Key Functions:** - `get_user_playlists()` - Retrieves all user playlists with full track metadata - `search_tracks()` - Searches Spotify catalog for tracks (critical for artist matching) - `get_track_features()` - Retrieves audio features for advanced matching - `is_authenticated()` - Validates current authentication status #### MusicMatchingEngine (`/core/matching_engine.py`) Sophisticated matching algorithm for correlating tracks across services. **Key Functions:** - `calculate_match_confidence()` - Computes similarity scores between tracks - `find_best_match()` - Identifies highest confidence matches from candidates - `match_playlist_tracks()` - Batch matching for entire playlists - `normalize_string()` - Text normalization for consistent matching - `create_search_queries()` - Generates multiple query variations for improved results #### PlexClient (`/core/plex_client.py`) Integration with Plex Media Server for library management. **Key Functions:** - `get_all_tracks()` - Retrieves complete music library metadata - `update_track_metadata()` - Modifies track information in Plex database - `_find_track()` - Locates specific tracks using flexible search criteria ### UI Components #### DownloadsPage (`/ui/pages/downloads.py`) Central hub for search, download, and queue management. **Key Functions:** - `perform_search()` - Initiates search operations with progress tracking - `create_search_result_item()` - Generates UI widgets for search results - `on_search_results_partial()` - Handles real-time result updates - `clear_search_results()` - Resets search interface state #### DownloadQueue (`/ui/pages/downloads.py`) Visual queue management for download operations. **Key Functions:** - `add_download_item()` - Adds new items to download queue with progress tracking - `clear_completed_downloads()` - Removes completed items and updates UI - `move_to_finished()` - Transitions downloads through status states #### MediaPlayer (`/ui/sidebar.py`) Integrated media player with playback controls. **Key Functions:** - `set_track_info()` - Updates player with current track metadata - `toggle_expansion()` - Switches between collapsed and expanded views - Playback control functions for audio streaming ### Service Layer #### PlaylistSyncService (`/services/sync_service.py`) High-level orchestration of playlist synchronization operations. **Key Functions:** - `sync_playlist()` - Complete playlist synchronization workflow - `get_sync_preview()` - Generates preview of sync operations for user confirmation - Progress tracking and error handling for complex operations ## Data Models ### Track Model ```python @dataclass class Track: id: str title: str artist: str album: str duration: int spotify_id: Optional[str] = None ``` ### Search Result Models ```python @dataclass class TrackResult: filename: str user: str size: int bit_rate: int sample_rate: int duration: int format: str # Auto-parsed metadata title: str artist: str album: str track_number: Optional[int] ``` ### Download Status Model ```python @dataclass class DownloadStatus: id: str filename: str user: str state: str # "Queued", "InProgress", "Completed", "Cancelled" progress: float transferred_bytes: int total_bytes: int start_time: Optional[datetime] end_time: Optional[datetime] ``` ## Download System Architecture *Reference: [download-details.md](download-details.md)* The newMusic application implements a sophisticated download management system handling music downloads from the Soulseek P2P network. The download system provides the foundation for all file acquisition operations and serves as the base for the Spotify matching functionality. ### Download Flow Overview The download system follows a well-defined flow from user interaction to file completion: 1. **Button Interaction**: Download buttons on tracks/albums trigger request signals 2. **Queue Management**: Downloads are added to active queue with progress tracking 3. **Thread Execution**: Background threads handle actual file downloads 4. **Status Monitoring**: Real-time progress updates via API polling 5. **Queue Transitions**: Completed downloads move to finished queue 6. **Cleanup Operations**: Clear completed functionality removes finished items ### Key Integration Points The current download system provides several extension points for Spotify matching: - **`start_download()`** at `downloads.py:5065` - Primary download initiation - **`add_download_item()`** at `downloads.py:3006` - Queue item creation - **Download completion handling** at `downloads.py:5860` - Post-download processing - **Clear operations** at `downloads.py:5976` - Cleanup and organization ## Spotify Matching System Implementation *Reference: [spotify_matching_spec.md](spotify_matching_spec.md)* ### Core Matching Flow The Spotify matching system provides intelligent artist matching and metadata enhancement: 1. **Artist Matching Modal**: Elegant interface with auto-suggestions and manual search 2. **Confidence Scoring**: Percentage-based matching using multiple criteria 3. **Metadata Enhancement**: Spotify API data for accurate tagging 4. **Folder Organization**: Automatic structure creation based on album detection ### Key Implementation Areas #### Modal Interface Components - **Auto-matching Section**: Top 5 likely artists with confidence percentages - **Manual Search Section**: User-driven artist search with similar result display - **Artist Selection**: Click-to-select functionality triggering download process #### Matching Algorithm Enhancement ```python # Core matching function for artist suggestions def generate_artist_suggestions(track_query: str, limit: int = 5) -> List[ArtistMatch]: """ Generate top artist matches for a given track query Returns list of ArtistMatch objects with confidence scores """ # Implementation leverages existing MusicMatchingEngine functions # - normalize_string() for query processing # - similarity_score() for confidence calculation # - SpotifyClient.search_tracks() for candidate retrieval ``` #### Folder Structure Management The system implements intelligent folder organization: **Single Track Structure:** ``` Transfer/  ARTIST_NAME/   ARTIST_NAME - SINGLE_NAME/    SINGLE_NAME.flac    cover.jpg ``` **Album Track Structure:** ``` Transfer/  ARTIST_NAME/   ARTIST_NAME - ALBUM_NAME/    01 TRACK_NAME.flac    02 TRACK_NAME.flac    cover.jpg ``` ### Integration Points #### Existing Function Utilization - **`SpotifyClient.search_tracks()`**: Powers both auto-matching and manual search - **`MusicMatchingEngine.calculate_match_confidence()`**: Generates confidence percentages - **`SoulseekClient.download()`**: Handles actual file downloads post-matching - **`DownloadQueue.add_download_item()`**: Integrates matched downloads into queue system #### New Function Requirements - **`create_spotify_matching_modal()`**: Modal interface creation - **`generate_artist_suggestions()`**: Auto-matching algorithm - **`apply_spotify_metadata()`**: Metadata enhancement from Spotify API - **`create_transfer_folder_structure()`**: Folder organization implementation ## Development Guidelines ### Code Organization - Follow existing patterns in UI component creation - Maintain separation between core logic and UI presentation - Use dataclasses for structured data models - Implement proper error handling and user feedback ### API Integration Best Practices - **Spotify API**: Respect rate limits, cache responses, handle authentication refresh - **Soulseek Network**: Implement proper timeout handling, manage connection state - **Plex Integration**: Validate server connectivity, handle library updates gracefully ### Testing Approach - Unit tests for core matching algorithms - Integration tests for service interactions - UI tests for critical user workflows - Mock external services for reliable testing ### Performance Considerations - Implement caching for frequently accessed data - Use background threads for long-running operations - Optimize search result processing for large datasets - Manage memory usage in large playlist operations ## Configuration ### Environment Variables - `SPOTIFY_CLIENT_ID`: Spotify application client ID - `SPOTIFY_CLIENT_SECRET`: Spotify application client secret - `SLSKD_HOST`: Soulseek daemon host address - `SLSKD_PORT`: Soulseek daemon port - `PLEX_URL`: Plex server URL - `PLEX_TOKEN`: Plex authentication token ### Application Settings Settings are managed through JSON configuration files with support for: - Service connection parameters - UI preferences and layout - Download directory paths - Matching algorithm parameters ## Error Handling ### Service Connectivity - Automatic retry mechanisms for transient failures - Graceful degradation when services are unavailable - User notification for critical service issues ### Download Management - Automatic cleanup of failed downloads - Progress tracking with error state handling - Queue management with cancellation support ## Future Enhancements ### Advanced Matching Features - Machine learning-based confidence scoring - Audio fingerprinting for improved accuracy - Cross-platform playlist format support ### UI/UX Improvements - Drag-and-drop playlist import - Advanced search filters and sorting - Customizable download organization templates ### Service Integrations - Additional music service support (Apple Music, YouTube Music) - Cloud storage integration for downloads - Social features for playlist sharing ## Contributing When contributing to the newMusic application: 1. **Review existing patterns** in similar components before implementing new features 2. **Update this documentation** when adding new functions or changing existing behavior 3. **Test integration points** thoroughly, especially service interactions 4. **Follow the established code style** and architectural patterns 5. **Consider performance implications** of new features on large music libraries ## Function Reference Quick Guide ### Most Frequently Used Functions - `SoulseekClient.search()` - Core search functionality - `SpotifyClient.search_tracks()` - Artist/track lookup - `MusicMatchingEngine.calculate_match_confidence()` - Matching logic - `DownloadQueue.add_download_item()` - Queue management - `DownloadsPage.perform_search()` - UI search initiation ### Critical Integration Points - `PlaylistSyncService.sync_playlist()` - High-level sync orchestration - `ServiceStatusThread.run()` - Service health monitoring - `MainWindow.update_service_status()` - UI status updates This documentation serves as a comprehensive guide for understanding and extending the newMusic application. For specific implementation details of the Spotify matching system, refer to the detailed specification in `spotify_matching_spec.md`.