12 KiB
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 trackingdownload()- Initiates file downloads from network peerssearch_and_download_best()- Automated search and download of highest quality matchesget_all_downloads()- Retrieves status of all active downloadscancel_download()- Cancels specific downloads by IDclear_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 metadatasearch_tracks()- Searches Spotify catalog for tracks (critical for artist matching)get_track_features()- Retrieves audio features for advanced matchingis_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 tracksfind_best_match()- Identifies highest confidence matches from candidatesmatch_playlist_tracks()- Batch matching for entire playlistsnormalize_string()- Text normalization for consistent matchingcreate_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 metadataupdate_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 trackingcreate_search_result_item()- Generates UI widgets for search resultson_search_results_partial()- Handles real-time result updatesclear_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 trackingclear_completed_downloads()- Removes completed items and updates UImove_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 metadatatoggle_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 workflowget_sync_preview()- Generates preview of sync operations for user confirmation- Progress tracking and error handling for complex operations
Data Models
Track Model
@dataclass
class Track:
id: str
title: str
artist: str
album: str
duration: int
spotify_id: Optional[str] = None
Search Result Models
@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
@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
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:
- Button Interaction: Download buttons on tracks/albums trigger request signals
- Queue Management: Downloads are added to active queue with progress tracking
- Thread Execution: Background threads handle actual file downloads
- Status Monitoring: Real-time progress updates via API polling
- Queue Transitions: Completed downloads move to finished queue
- Cleanup Operations: Clear completed functionality removes finished items
Key Integration Points
The current download system provides several extension points for Spotify matching:
start_download()atdownloads.py:5065- Primary download initiationadd_download_item()atdownloads.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
Core Matching Flow
The Spotify matching system provides intelligent artist matching and metadata enhancement:
- Artist Matching Modal: Elegant interface with auto-suggestions and manual search
- Confidence Scoring: Percentage-based matching using multiple criteria
- Metadata Enhancement: Spotify API data for accurate tagging
- 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
# 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 searchMusicMatchingEngine.calculate_match_confidence(): Generates confidence percentagesSoulseekClient.download(): Handles actual file downloads post-matchingDownloadQueue.add_download_item(): Integrates matched downloads into queue system
New Function Requirements
create_spotify_matching_modal(): Modal interface creationgenerate_artist_suggestions(): Auto-matching algorithmapply_spotify_metadata(): Metadata enhancement from Spotify APIcreate_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 IDSPOTIFY_CLIENT_SECRET: Spotify application client secretSLSKD_HOST: Soulseek daemon host addressSLSKD_PORT: Soulseek daemon portPLEX_URL: Plex server URLPLEX_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:
- Review existing patterns in similar components before implementing new features
- Update this documentation when adding new functions or changing existing behavior
- Test integration points thoroughly, especially service interactions
- Follow the established code style and architectural patterns
- Consider performance implications of new features on large music libraries
Function Reference Quick Guide
Most Frequently Used Functions
SoulseekClient.search()- Core search functionalitySpotifyClient.search_tracks()- Artist/track lookupMusicMatchingEngine.calculate_match_confidence()- Matching logicDownloadQueue.add_download_item()- Queue managementDownloadsPage.perform_search()- UI search initiation
Critical Integration Points
PlaylistSyncService.sync_playlist()- High-level sync orchestrationServiceStatusThread.run()- Service health monitoringMainWindow.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.