Compare commits
265
Commits
+391
@@ -0,0 +1,391 @@
|
||||
# Ensemble Codebase Intensive Audit Prompt
|
||||
|
||||
## Overview
|
||||
|
||||
You are tasked with conducting an intensive, comprehensive audit of the **Ensemble** Flutter application - a Music Assistant client for Android with multi-device synchronization, local playback, and Sendspin raw audio streaming capabilities.
|
||||
|
||||
**Codebase Statistics:**
|
||||
- 90 Dart files, ~40,583 lines of code
|
||||
- 18 screens, 27 services, 6 providers
|
||||
- Architecture: Provider pattern with ChangeNotifier
|
||||
- Audio: just_audio + flutter_pcm_sound + audio_service
|
||||
- Networking: WebSocket (JSON-RPC) + HTTP + Sendspin binary protocol
|
||||
|
||||
---
|
||||
|
||||
## Audit Scope
|
||||
|
||||
Perform a thorough audit covering ALL of the following areas. For each issue found, provide:
|
||||
1. **File path and line number(s)**
|
||||
2. **Severity**: CRITICAL / HIGH / MEDIUM / LOW
|
||||
3. **Description** of the issue
|
||||
4. **Impact** if left unfixed
|
||||
5. **Recommended fix** with code example where applicable
|
||||
|
||||
---
|
||||
|
||||
## SECTION 1: SECURITY AUDIT
|
||||
|
||||
### 1.1 Credential Storage (CRITICAL PRIORITY)
|
||||
Audit `/lib/services/settings_service.dart` for:
|
||||
- [ ] Plaintext password storage in SharedPreferences (lines 209-222)
|
||||
- [ ] Auth tokens stored without encryption
|
||||
- [ ] Serialized credentials in JSON format (lines 169-190)
|
||||
|
||||
**Expected Finding:** Credentials stored insecurely. Recommend flutter_secure_storage.
|
||||
|
||||
### 1.2 Certificate Validation
|
||||
Audit `/lib/services/auth/auth_manager.dart` for:
|
||||
- [ ] HTTPS redirect handling for local IPs
|
||||
- [ ] Certificate validation disabled scenarios
|
||||
- [ ] MITM vulnerability exposure
|
||||
|
||||
### 1.3 Authentication Strategies
|
||||
Audit all files in `/lib/services/auth/`:
|
||||
- [ ] `basic_auth_strategy.dart` - Base64 encoding (not encryption)
|
||||
- [ ] `authelia_strategy.dart` - Session cookie handling, timing attack (line 159)
|
||||
- [ ] `ma_auth_strategy.dart` - Token refresh mechanism
|
||||
- [ ] `no_auth_strategy.dart` - Public server exposure
|
||||
|
||||
### 1.4 Input Validation
|
||||
Audit `/lib/services/music_assistant_api.dart`:
|
||||
- [ ] URI construction without validation (lines 1346-1360)
|
||||
- [ ] Provider/itemId injection risks
|
||||
- [ ] WebSocket message validation
|
||||
|
||||
### 1.5 Information Disclosure
|
||||
- [ ] Debug logs exposing sensitive data (check all `_logger.log()` calls)
|
||||
- [ ] Server version exposure via `server_info`
|
||||
- [ ] Error messages leaking technical details
|
||||
|
||||
---
|
||||
|
||||
## SECTION 2: MEMORY MANAGEMENT AUDIT
|
||||
|
||||
### 2.1 Static Memory Leaks
|
||||
Audit `/lib/models/player.dart`:
|
||||
- [ ] `_playerCreationTimes` static map (lines 96-144) - grows unbounded
|
||||
- [ ] Cleanup only removes 50 of 100+ entries
|
||||
|
||||
### 2.2 Unbounded Caches
|
||||
Audit `/lib/services/cache_service.dart`:
|
||||
- [ ] `_albumTracksCache` - no size limit
|
||||
- [ ] `_artistAlbumsCache` - no TTL expiration
|
||||
- [ ] `_searchCache` - never evicted
|
||||
- [ ] `_playerTrackCache` - only cleared on disconnect
|
||||
|
||||
### 2.3 Stream/Timer Cleanup
|
||||
Audit `/lib/providers/music_assistant_provider.dart`:
|
||||
- [ ] `_playerStateTimer` disposal (line 4435-4445)
|
||||
- [ ] `_notificationPositionTimer` multiple creation paths (lines 2925-2940)
|
||||
- [ ] `_localPlayerEventSubscription` cleanup
|
||||
- [ ] `_playerUpdatedEventSubscription` cleanup
|
||||
- [ ] `_playerAddedEventSubscription` cleanup
|
||||
|
||||
Audit `/lib/services/hardware_volume_service.dart`:
|
||||
- [ ] `_volumeUpController` never closed (lines 74-85)
|
||||
- [ ] `_volumeDownController` never closed
|
||||
|
||||
### 2.4 Stream Subscription Leaks
|
||||
Audit `/lib/providers/music_assistant_provider.dart`:
|
||||
- [ ] `_api!.connectionState.listen()` - subscription not stored
|
||||
- [ ] Old subscriptions not cancelled before new API instance
|
||||
|
||||
---
|
||||
|
||||
## SECTION 3: RACE CONDITION AUDIT
|
||||
|
||||
### 3.1 Player State Dual Updates
|
||||
Audit `/lib/providers/music_assistant_provider.dart`:
|
||||
- [ ] Timer polling (every 5s) vs WebSocket events racing
|
||||
- [ ] `_updatePlayerState()` called from both paths
|
||||
- [ ] No mutex/lock protection
|
||||
|
||||
### 3.2 Async Method Reentrancy
|
||||
Audit `selectPlayer()` method:
|
||||
- [ ] `async` method without guard against concurrent calls
|
||||
- [ ] `_selectedPlayer` modified before and after `await`
|
||||
- [ ] State could change during await
|
||||
|
||||
### 3.3 Fire-and-Forget Operations
|
||||
Search for `unawaited(` and `() async {` patterns:
|
||||
- [ ] `_persistPlaybackState()` - database save not awaited
|
||||
- [ ] Pause operations fire-and-forget (lines 3876-3894)
|
||||
- [ ] Preload operations (line 2707)
|
||||
|
||||
### 3.4 PCM Player State Machine
|
||||
Audit `/lib/services/pcm_audio_player.dart`:
|
||||
- [ ] 9-state machine with complex transitions (lines 32-37)
|
||||
- [ ] Auto-recovery race condition (lines 215-229)
|
||||
- [ ] Feed loop during pause transition (lines 174-179)
|
||||
|
||||
---
|
||||
|
||||
## SECTION 4: ERROR HANDLING AUDIT
|
||||
|
||||
### 4.1 Silent Exception Handlers (CRITICAL)
|
||||
Find all instances of:
|
||||
```dart
|
||||
} catch (e) {}
|
||||
} catch (_) {}
|
||||
```
|
||||
|
||||
Known locations:
|
||||
- [ ] `music_assistant_provider.dart` (multiple)
|
||||
- [ ] `player_provider.dart` (3 instances)
|
||||
- [ ] `recently_played_service.dart`
|
||||
|
||||
### 4.2 Missing Error Recovery
|
||||
- [ ] No exponential backoff on connection retry
|
||||
- [ ] No retry logic for failed API calls
|
||||
- [ ] WebSocket timeout handling (30 seconds - too long?)
|
||||
|
||||
### 4.3 Null Safety Violations
|
||||
Find all `!` (null assertion) operators:
|
||||
- [ ] `search_screen.dart` (20+ instances)
|
||||
- [ ] `models/media_item.dart`
|
||||
- [ ] `models/player.dart`
|
||||
- [ ] `item.mediaItem! as Artist` patterns
|
||||
|
||||
---
|
||||
|
||||
## SECTION 5: ARCHITECTURAL ISSUES
|
||||
|
||||
### 5.1 God Class
|
||||
Audit `/lib/providers/music_assistant_provider.dart`:
|
||||
- [ ] 4,469 lines - violates Single Responsibility
|
||||
- [ ] 386 conditional branches
|
||||
- [ ] Mixing: connection, players, library, sync, audio, position tracking
|
||||
|
||||
**Recommend splitting into:**
|
||||
- ConnectionProvider (~500 LOC)
|
||||
- PlayerManager (~800 LOC)
|
||||
- LibraryProvider (~1000 LOC)
|
||||
- LocalPlaybackManager (~600 LOC)
|
||||
|
||||
### 5.2 Oversized Widget Files
|
||||
- [ ] `expandable_player.dart` - 2,485 lines (should be <500)
|
||||
- [ ] `global_player_overlay.dart` - 737 lines
|
||||
- [ ] `new_library_screen.dart` - 2,521 lines
|
||||
|
||||
### 5.3 Global Key Anti-Pattern
|
||||
Audit `/lib/widgets/global_player_overlay.dart`:
|
||||
- [ ] `globalPlayerKey` for state access
|
||||
- [ ] `_overlayStateKey` for overlay state
|
||||
- [ ] Should use Provider/context instead
|
||||
|
||||
### 5.4 Primitive Obsession
|
||||
- [ ] View modes as strings ('grid2', 'grid3', 'list')
|
||||
- [ ] Media types as strings ('track', 'album', 'artist')
|
||||
- [ ] Should be strongly-typed enums
|
||||
|
||||
---
|
||||
|
||||
## SECTION 6: CODE QUALITY ISSUES
|
||||
|
||||
### 6.1 Testing (CRITICAL)
|
||||
- [ ] **ZERO test files exist** - confirm this
|
||||
- [ ] No unit tests, widget tests, or integration tests
|
||||
- [ ] flutter_test dependency exists but unused
|
||||
|
||||
### 6.2 Hardcoded Values
|
||||
Find and document all:
|
||||
- [ ] Color hex codes (50+ instances of `Color(0xFF...`)
|
||||
- [ ] Duration values not using `Timings` constants
|
||||
- [ ] Magic numbers (16, 4, 5, 100, 50)
|
||||
- [ ] String literals for media types
|
||||
|
||||
### 6.3 Mixed Async Patterns
|
||||
- [ ] `.then()` chains alongside async/await
|
||||
- [ ] `.whenComplete()` usage
|
||||
- [ ] Consolidate to async/await
|
||||
|
||||
### 6.4 Dead Code
|
||||
- [ ] `@Deprecated` methods still implemented
|
||||
- [ ] `animation_debugger.dart` - dev-only?
|
||||
- [ ] Unused imports
|
||||
|
||||
### 6.5 TODO Comments
|
||||
Document all actionable TODOs:
|
||||
- [ ] `queue_screen.dart:214` - queue item removal
|
||||
- [ ] `audiobook_detail_screen.dart:261,312` - progress sync
|
||||
- [ ] `music_assistant_provider.dart:793,799` - playlist modification
|
||||
|
||||
---
|
||||
|
||||
## SECTION 7: UI/UX AUDIT
|
||||
|
||||
### 7.1 Accessibility (CRITICAL)
|
||||
Audit for missing:
|
||||
- [ ] `Semantics` widgets on interactive elements
|
||||
- [ ] `Tooltip` on icon buttons
|
||||
- [ ] Screen reader support
|
||||
- [ ] Touch target sizes (minimum 48dp)
|
||||
- [ ] Color contrast validation (WCAG AA)
|
||||
|
||||
### 7.2 Performance Issues
|
||||
Audit `/lib/widgets/expandable_player.dart`:
|
||||
- [ ] No `RepaintBoundary` wrappers
|
||||
- [ ] 55+ `setState()` calls
|
||||
- [ ] 3 AnimationControllers with multiple listeners
|
||||
- [ ] Title height cache invalidation (lines 118+)
|
||||
|
||||
### 7.3 Double Opacity Bug
|
||||
Audit `/lib/widgets/player/player_controls.dart`:
|
||||
```dart
|
||||
color: (shuffle == true ? primaryColor : textColor.withOpacity(0.5))
|
||||
.withOpacity(expandedElementsOpacity),
|
||||
```
|
||||
- [ ] Double `.withOpacity()` application
|
||||
|
||||
### 7.4 Missing Features
|
||||
- [ ] No landscape orientation support
|
||||
- [ ] No tablet layout optimization
|
||||
- [ ] No loading skeleton animations
|
||||
- [ ] No haptic feedback (except one location)
|
||||
|
||||
---
|
||||
|
||||
## SECTION 8: AUDIO PLAYBACK AUDIT
|
||||
|
||||
### 8.1 Position Interpolation
|
||||
Audit `/lib/services/position_tracker.dart`:
|
||||
- [ ] No timeout on anchor updates - unbounded drift possible
|
||||
- [ ] Duration interpolation can exceed track duration
|
||||
- [ ] Stale timestamp handling (>30 seconds)
|
||||
|
||||
### 8.2 Sendspin Protocol
|
||||
Audit `/lib/services/sendspin_service.dart`:
|
||||
- [ ] Proxy auth retry without deduplication (lines 188-209)
|
||||
- [ ] WebSocket binary frame parsing
|
||||
- [ ] Clock synchronization accuracy
|
||||
|
||||
### 8.3 Audio Resource Cleanup
|
||||
Audit `/lib/services/audio/massiv_audio_handler.dart`:
|
||||
- [ ] Audio session interrupt listeners not disposed
|
||||
- [ ] Audio focus not explicitly released
|
||||
|
||||
### 8.4 Mixed Playback Modes
|
||||
- [ ] just_audio initialized but unused during Sendspin
|
||||
- [ ] Resource allocation for unused player
|
||||
- [ ] Potential audio focus conflicts
|
||||
|
||||
---
|
||||
|
||||
## SECTION 9: NETWORKING AUDIT
|
||||
|
||||
### 9.1 WebSocket Lifecycle
|
||||
Audit `/lib/services/music_assistant_api.dart`:
|
||||
- [ ] Heartbeat interval (30s) - appropriate?
|
||||
- [ ] Reconnection logic and timing
|
||||
- [ ] Pending request cleanup on disconnect
|
||||
|
||||
### 9.2 Caching Strategy
|
||||
- [ ] No incremental/delta sync (full library every 5 minutes)
|
||||
- [ ] Cache staleness not communicated to UI
|
||||
- [ ] No query result pagination (fetches up to 5000 items)
|
||||
|
||||
### 9.3 Rate Limiting
|
||||
- [ ] No client-side rate limiting
|
||||
- [ ] Search requests not throttled
|
||||
- [ ] Could overload server
|
||||
|
||||
### 9.4 Offline Support
|
||||
Audit `/lib/services/offline_action_queue.dart`:
|
||||
- [ ] Queue execution not atomic (lines 118-130)
|
||||
- [ ] Action could execute twice on crash
|
||||
- [ ] Queue stored unencrypted
|
||||
|
||||
---
|
||||
|
||||
## SECTION 10: DATABASE AUDIT
|
||||
|
||||
### 10.1 Schema Review
|
||||
Audit `/lib/database/database.dart`:
|
||||
- [ ] Table indexes for query performance
|
||||
- [ ] Foreign key constraints
|
||||
- [ ] Migration strategy
|
||||
|
||||
### 10.2 Query Patterns
|
||||
- [ ] N+1 query prevention
|
||||
- [ ] Transaction usage for atomic operations
|
||||
- [ ] Connection pooling
|
||||
|
||||
### 10.3 Data Consistency
|
||||
- [ ] Tier 1 (DB) vs Tier 2 (API sync) race conditions
|
||||
- [ ] User modifications during background sync
|
||||
- [ ] Conflict resolution strategy
|
||||
|
||||
---
|
||||
|
||||
## Deliverables
|
||||
|
||||
After completing the audit, provide:
|
||||
|
||||
### 1. Executive Summary
|
||||
- Overall code quality score (1-10)
|
||||
- Top 5 critical issues requiring immediate attention
|
||||
- Estimated technical debt in developer-hours
|
||||
|
||||
### 2. Issue Tracker
|
||||
Create a prioritized list of all issues found:
|
||||
| ID | Severity | Category | File:Line | Description | Effort |
|
||||
|----|----------|----------|-----------|-------------|--------|
|
||||
|
||||
### 3. Recommended Roadmap
|
||||
Sprint-based plan to address findings:
|
||||
- Sprint 1 (Immediate): Security fixes, silent exception handlers
|
||||
- Sprint 2-3: God class decomposition, test infrastructure
|
||||
- Sprint 4-6: Memory leak fixes, accessibility
|
||||
- Long-term: Performance optimization, monitoring
|
||||
|
||||
### 4. Code Examples
|
||||
For each CRITICAL and HIGH severity issue, provide:
|
||||
- Current problematic code
|
||||
- Recommended refactored code
|
||||
- Migration steps
|
||||
|
||||
---
|
||||
|
||||
## Files to Prioritize
|
||||
|
||||
Start your audit with these critical files:
|
||||
|
||||
1. `/lib/providers/music_assistant_provider.dart` (4,469 LOC) - God class
|
||||
2. `/lib/services/settings_service.dart` - Credential storage
|
||||
3. `/lib/services/music_assistant_api.dart` (2,929 LOC) - Networking
|
||||
4. `/lib/widgets/expandable_player.dart` (2,485 LOC) - UI complexity
|
||||
5. `/lib/services/auth/` directory - Security
|
||||
6. `/lib/models/player.dart` - Memory leaks
|
||||
7. `/lib/services/cache_service.dart` - Unbounded caches
|
||||
8. `/lib/services/position_tracker.dart` - Audio sync issues
|
||||
|
||||
---
|
||||
|
||||
## Known Critical Issues (Pre-Identified)
|
||||
|
||||
These issues have been identified and MUST be verified and documented:
|
||||
|
||||
1. **CRITICAL: Plaintext credential storage** - SharedPreferences without encryption
|
||||
2. **CRITICAL: Zero test coverage** - No unit, widget, or integration tests
|
||||
3. **CRITICAL: 4,469 line god class** - MusicAssistantProvider violates SRP
|
||||
4. **CRITICAL: Silent exception handlers** - `catch (e) {}` patterns
|
||||
5. **HIGH: Static memory leak** - `_playerCreationTimes` unbounded growth
|
||||
6. **HIGH: Race conditions** - Player state polling vs events
|
||||
7. **HIGH: No accessibility** - Missing Semantics, screen reader support
|
||||
8. **HIGH: Certificate validation disabled** - MITM vulnerability for local IPs
|
||||
9. **MEDIUM: Double opacity bug** - `.withOpacity().withOpacity()` in player controls
|
||||
10. **MEDIUM: Position tracker drift** - No timeout on anchor updates
|
||||
|
||||
---
|
||||
|
||||
## Audit Execution Notes
|
||||
|
||||
- Use `Grep` tool to search for patterns across the codebase
|
||||
- Use `Read` tool to examine specific file sections
|
||||
- Document line numbers for all findings
|
||||
- Provide code snippets for context
|
||||
- Cross-reference related issues across files
|
||||
- Verify pre-identified issues exist and document their exact locations
|
||||
|
||||
**Total estimated audit time: 4-6 hours for thorough coverage**
|
||||
+419
@@ -0,0 +1,419 @@
|
||||
# Ensemble Codebase - Comprehensive Audit Report
|
||||
|
||||
**Audit Date:** 2026-01-01
|
||||
**Codebase:** Ensemble Flutter App (Music Assistant Client)
|
||||
**Version:** 2.7.3-beta+35
|
||||
**Total Lines of Code:** ~40,583 Dart
|
||||
**Files Analyzed:** 90 Dart files
|
||||
|
||||
---
|
||||
|
||||
## Executive Summary
|
||||
|
||||
### Overall Code Quality Score: 5.5/10
|
||||
|
||||
The Ensemble codebase demonstrates **strong architectural foundations** with a well-organized service layer, effective caching strategies, and sophisticated audio handling. However, the audit revealed **critical security vulnerabilities**, **zero test coverage**, and significant **technical debt** that must be addressed before production release.
|
||||
|
||||
### Critical Statistics
|
||||
|
||||
| Metric | Value | Status |
|
||||
|--------|-------|--------|
|
||||
| Test Coverage | 0% | CRITICAL |
|
||||
| God Class Size | 4,469 LOC | CRITICAL |
|
||||
| Silent Exception Handlers | 7 | CRITICAL |
|
||||
| Plaintext Credentials | 4 locations | CRITICAL |
|
||||
| Memory Leak Locations | 6 | HIGH |
|
||||
| Race Conditions | 4 | HIGH |
|
||||
| Accessibility (Semantics) | 0 widgets | CRITICAL |
|
||||
|
||||
---
|
||||
|
||||
## Issue Summary by Severity
|
||||
|
||||
| Severity | Count | Categories |
|
||||
|----------|-------|------------|
|
||||
| **CRITICAL** | 12 | Security, Testing, Architecture, Accessibility |
|
||||
| **HIGH** | 18 | Memory, Race Conditions, Networking, Audio |
|
||||
| **MEDIUM** | 22 | Error Handling, UI, Caching, Code Quality |
|
||||
| **LOW** | 14 | Naming, Documentation, Minor Improvements |
|
||||
|
||||
---
|
||||
|
||||
## CRITICAL ISSUES (Immediate Action Required)
|
||||
|
||||
### 1. Plaintext Credential Storage
|
||||
**File:** `/lib/services/settings_service.dart`
|
||||
**Lines:** 131-143, 147-159, 169-190, 209-222
|
||||
|
||||
Passwords and auth tokens stored in SharedPreferences without encryption.
|
||||
|
||||
```dart
|
||||
// VULNERABLE CODE
|
||||
static Future<void> setPassword(String? password) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyPassword, password); // PLAINTEXT!
|
||||
}
|
||||
```
|
||||
|
||||
**Fix:** Use `flutter_secure_storage` for all sensitive data.
|
||||
|
||||
---
|
||||
|
||||
### 2. Zero Test Coverage
|
||||
**Location:** Entire codebase
|
||||
|
||||
No unit tests, widget tests, or integration tests exist. The `flutter_test` dependency is unused.
|
||||
|
||||
**Impact:** Cannot safely refactor, high regression risk, no confidence in correctness.
|
||||
|
||||
**Fix:** Establish test infrastructure immediately. Start with:
|
||||
- Unit tests for `MusicAssistantAPI`, `CacheService`, `ErrorHandler`
|
||||
- Widget tests for player controls
|
||||
- Integration tests for playback flows
|
||||
|
||||
---
|
||||
|
||||
### 3. God Class - MusicAssistantProvider
|
||||
**File:** `/lib/providers/music_assistant_provider.dart`
|
||||
**Size:** 4,469 lines, ~140 methods, 744 conditional branches
|
||||
|
||||
Single class handles: connection, players, library, cache, audio, sync, offline queue.
|
||||
|
||||
**Fix:** Split into:
|
||||
- `ConnectionManager` (~500 LOC)
|
||||
- `PlayerManager` (~800 LOC)
|
||||
- `LibraryCacheService` (~600 LOC)
|
||||
- `SendspinManager` (~400 LOC)
|
||||
- `MusicAssistantProvider` - Facade composing above (~800 LOC)
|
||||
|
||||
---
|
||||
|
||||
### 4. Zero Accessibility Support
|
||||
**Files:** `/lib/widgets/`, `/lib/screens/` (all)
|
||||
|
||||
- **0** `Semantics` widgets
|
||||
- **0** `semanticLabel` properties
|
||||
- **1** `Tooltip` (entire app)
|
||||
- Screen readers cannot navigate the app
|
||||
|
||||
**Fix:** Add Semantics to all interactive elements:
|
||||
```dart
|
||||
Semantics(
|
||||
button: true,
|
||||
label: isPlaying ? 'Pause playback' : 'Play',
|
||||
child: IconButton(...)
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5. Silent Exception Handlers
|
||||
**Locations:** 7 instances across codebase
|
||||
|
||||
| File | Line | Code |
|
||||
|------|------|------|
|
||||
| player_provider.dart | 567, 575, 584 | `catch (e) {}` |
|
||||
| music_assistant_provider.dart | 2690 | `catch (e) {}` |
|
||||
| music_assistant_api.dart | 2542 | `catch (e) {}` |
|
||||
| recently_played_service.dart | 154, 206 | `catch (_) {}` |
|
||||
|
||||
**Fix:** Add logging or use `firstWhereOrNull` instead of try/catch around `firstWhere`.
|
||||
|
||||
---
|
||||
|
||||
### 6. Audio Session Listeners Not Disposed
|
||||
**File:** `/lib/services/audio/massiv_audio_handler.dart`
|
||||
**Lines:** 45-73
|
||||
|
||||
Stream subscriptions created but never cancelled - causes memory leaks and zombie listeners.
|
||||
|
||||
**Fix:** Store subscriptions and cancel in dispose():
|
||||
```dart
|
||||
StreamSubscription? _interruptionSubscription;
|
||||
_interruptionSubscription = session.interruptionEventStream.listen(...);
|
||||
|
||||
void dispose() {
|
||||
_interruptionSubscription?.cancel();
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## HIGH SEVERITY ISSUES
|
||||
|
||||
### 7. Connection State Subscription Not Stored
|
||||
**File:** `/lib/providers/music_assistant_provider.dart:575-614`
|
||||
|
||||
The `connectionState.listen()` return value is not stored - causes listener accumulation on reconnect.
|
||||
|
||||
---
|
||||
|
||||
### 8. Player State Race Condition
|
||||
**File:** `/lib/providers/music_assistant_provider.dart`
|
||||
|
||||
Timer polling (every 5s) and WebSocket events can race to update `_selectedPlayer` and `_currentTrack` without mutex protection.
|
||||
|
||||
---
|
||||
|
||||
### 9. Async Method Reentrancy
|
||||
**File:** `/lib/providers/music_assistant_provider.dart:2713-2841`
|
||||
|
||||
`selectPlayer()` is `void async` with no guard against concurrent calls. Multiple rapid player switches can interleave.
|
||||
|
||||
---
|
||||
|
||||
### 10. Unbounded Search Cache
|
||||
**File:** `/lib/services/cache_service.dart:31-32`
|
||||
|
||||
`_searchCache` map has no size limit or proactive TTL eviction. Grows indefinitely with user searches.
|
||||
|
||||
---
|
||||
|
||||
### 11. Static Memory Leak
|
||||
**File:** `/lib/models/player.dart:96, 139-144`
|
||||
|
||||
`_playerCreationTimes` static map cleanup only removes 50 of 100+ entries, allowing unbounded growth.
|
||||
|
||||
---
|
||||
|
||||
### 12. No Database Indexes
|
||||
**File:** `/lib/database/database.dart`
|
||||
|
||||
No secondary indexes defined. Query performance degrades as database grows.
|
||||
|
||||
---
|
||||
|
||||
### 13. No Incremental Sync
|
||||
**File:** `/lib/services/sync_service.dart:150-165`
|
||||
|
||||
Full library fetch (up to 4000 items) on every sync instead of delta updates.
|
||||
|
||||
---
|
||||
|
||||
### 14. Offline Queue Not Atomic
|
||||
**File:** `/lib/services/offline_action_queue.dart:80-108`
|
||||
|
||||
Queue persistence happens after all processing - crash during processing loses successful actions.
|
||||
|
||||
---
|
||||
|
||||
### 15. Auth Retry Without Deduplication
|
||||
**File:** `/lib/services/sendspin_service.dart:189-209`
|
||||
|
||||
Multiple auth messages can be sent during rapid reconnection attempts.
|
||||
|
||||
---
|
||||
|
||||
### 16. Pending Requests Not Completed on Disconnect
|
||||
**File:** `/lib/services/music_assistant_api.dart:2911`
|
||||
|
||||
`_pendingRequests.clear()` abandons Completers without completing them with errors.
|
||||
|
||||
---
|
||||
|
||||
### 17. HTTP Fallback for Local IPs
|
||||
**File:** `/lib/services/auth/auth_manager.dart:51-58`
|
||||
|
||||
HTTPS failures silently fall back to HTTP on local networks - MITM vulnerability.
|
||||
|
||||
---
|
||||
|
||||
### 18. Certificate Validation Bypassed
|
||||
**File:** `/lib/services/auth/auth_manager.dart:210-236`
|
||||
|
||||
HTTPS redirects explicitly refused for local IPs due to expected certificate failures.
|
||||
|
||||
---
|
||||
|
||||
## MEDIUM SEVERITY ISSUES
|
||||
|
||||
### 19. Double Opacity Bug
|
||||
**File:** `/lib/widgets/player/player_controls.dart:62-63, 99-100`
|
||||
|
||||
```dart
|
||||
// BUG: .withOpacity(0.5).withOpacity(expandedElementsOpacity) compounds opacity
|
||||
color: (shuffle == true ? primaryColor : textColor.withOpacity(0.5))
|
||||
.withOpacity(expandedElementsOpacity),
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 20. Mixed Async Patterns
|
||||
**Locations:** 13 instances
|
||||
|
||||
`.then()` chains mixed with `async/await` throughout the codebase.
|
||||
|
||||
---
|
||||
|
||||
### 21. Hardcoded Colors
|
||||
**Locations:** 55 instances
|
||||
|
||||
`Color(0xFF604CEC)`, `Color(0xFF1a1a1a)` scattered across theme files and widgets.
|
||||
|
||||
---
|
||||
|
||||
### 22. View Modes as Strings
|
||||
**Locations:** 80+ instances
|
||||
|
||||
`'grid2'`, `'grid3'`, `'list'` should be enums.
|
||||
|
||||
---
|
||||
|
||||
### 23. Fire-and-Forget Pause Commands
|
||||
**File:** `/lib/providers/music_assistant_provider.dart:3875-3894`
|
||||
|
||||
Server pause command uses `unawaited()` - errors are silently lost.
|
||||
|
||||
---
|
||||
|
||||
### 24. Position Tracker Anchor Timeout Missing
|
||||
**File:** `/lib/services/position_tracker.dart:24-26`
|
||||
|
||||
No timeout on stale anchor - interpolation can drift indefinitely.
|
||||
|
||||
---
|
||||
|
||||
### 25. PCM Buffer No Overflow Protection
|
||||
**File:** `/lib/services/pcm_audio_player.dart:68, 236-247`
|
||||
|
||||
Audio buffer grows unbounded if data arrives faster than consumption.
|
||||
|
||||
---
|
||||
|
||||
### 26. No Client-Side Rate Limiting
|
||||
**Location:** App-wide
|
||||
|
||||
No throttling on API requests during rapid user interactions.
|
||||
|
||||
---
|
||||
|
||||
### 27. Portrait-Only Lock
|
||||
**File:** `/lib/main.dart:64-68`
|
||||
|
||||
No landscape orientation support.
|
||||
|
||||
---
|
||||
|
||||
### 28. Touch Targets Below 48dp
|
||||
**Files:** player_controls.dart, queue_panel.dart, player_card.dart
|
||||
|
||||
Multiple buttons at 28x28 and 44x44 instead of minimum 48x48.
|
||||
|
||||
---
|
||||
|
||||
### 29. WCAG Contrast Not Validated
|
||||
**File:** `/lib/theme/palette_helper.dart`
|
||||
|
||||
Uses 0.4 threshold instead of proper WCAG 4.5:1 contrast ratio calculation.
|
||||
|
||||
---
|
||||
|
||||
### 30. StreamControllers Not Closed
|
||||
**File:** `/lib/services/hardware_volume_service.dart:18-19, 74-85`
|
||||
|
||||
`_volumeUpController` and `_volumeDownController` never closed in dispose().
|
||||
|
||||
---
|
||||
|
||||
## LOW SEVERITY ISSUES
|
||||
|
||||
### 31-34. Naming Inconsistencies
|
||||
Mixed patterns: `_isLoading` vs `_isLoadingPlaylists`, various cache variable names.
|
||||
|
||||
### 35-38. Missing TODO Implementations
|
||||
6 actionable TODOs identified (queue removal, audiobook progress sync, playlist modification).
|
||||
|
||||
### 39-42. Dead/Unused Code
|
||||
- `@Deprecated` methods still implemented
|
||||
- `library_stats.dart` appears unused
|
||||
- `animation_debugger.dart` disabled by default
|
||||
|
||||
### 43-44. Minor Documentation Gaps
|
||||
Missing method documentation, no architecture diagram.
|
||||
|
||||
---
|
||||
|
||||
## Recommended Remediation Roadmap
|
||||
|
||||
### Sprint 1 (Week 1-2): Security & Critical Fixes
|
||||
1. Migrate credentials to `flutter_secure_storage`
|
||||
2. Add logging to all silent catch blocks
|
||||
3. Store connection state subscription
|
||||
4. Fix audio session listener disposal
|
||||
5. Add basic test infrastructure (10% coverage target)
|
||||
|
||||
### Sprint 2 (Week 3-4): Memory & Race Conditions
|
||||
6. Add mutex to player state updates
|
||||
7. Add reentrancy guard to `selectPlayer()`
|
||||
8. Implement bounded caches with LRU eviction
|
||||
9. Fix static memory leak in Player model
|
||||
10. Store and cancel all stream subscriptions
|
||||
|
||||
### Sprint 3 (Week 5-6): Architecture Refactoring
|
||||
11. Split `MusicAssistantProvider` into 5 smaller classes
|
||||
12. Split `expandable_player.dart` into component widgets
|
||||
13. Replace GlobalKey anti-patterns with Provider
|
||||
14. Convert string constants to enums
|
||||
15. Extract hardcoded colors to constants file
|
||||
|
||||
### Sprint 4 (Week 7-8): Accessibility & UI
|
||||
16. Add Semantics to all interactive elements
|
||||
17. Increase touch targets to 48dp minimum
|
||||
18. Implement WCAG contrast validation
|
||||
19. Fix double opacity bug
|
||||
20. Add landscape orientation support
|
||||
|
||||
### Sprint 5 (Week 9-10): Performance & Polish
|
||||
21. Add database indexes
|
||||
22. Implement incremental sync
|
||||
23. Add client-side rate limiting
|
||||
24. Fix atomic offline queue processing
|
||||
25. Achieve 30% test coverage target
|
||||
|
||||
---
|
||||
|
||||
## Files Requiring Most Attention
|
||||
|
||||
| File | LOC | Issues | Priority |
|
||||
|------|-----|--------|----------|
|
||||
| `music_assistant_provider.dart` | 4,469 | 12 | CRITICAL |
|
||||
| `settings_service.dart` | 811 | 4 | CRITICAL |
|
||||
| `expandable_player.dart` | 2,485 | 6 | HIGH |
|
||||
| `music_assistant_api.dart` | 2,929 | 5 | HIGH |
|
||||
| `cache_service.dart` | 370 | 4 | HIGH |
|
||||
| `massiv_audio_handler.dart` | 296 | 2 | CRITICAL |
|
||||
| `player.dart` | 422 | 2 | HIGH |
|
||||
| `auth_manager.dart` | 300 | 3 | HIGH |
|
||||
|
||||
---
|
||||
|
||||
## Estimated Technical Debt
|
||||
|
||||
| Category | Effort (Dev-Days) |
|
||||
|----------|-------------------|
|
||||
| Security Fixes | 3-5 |
|
||||
| Test Infrastructure | 10-15 |
|
||||
| Architecture Refactoring | 15-20 |
|
||||
| Memory Leak Fixes | 3-5 |
|
||||
| Accessibility | 5-8 |
|
||||
| UI/UX Polish | 3-5 |
|
||||
| Performance | 5-8 |
|
||||
| **Total** | **44-66 dev-days** |
|
||||
|
||||
---
|
||||
|
||||
## Conclusion
|
||||
|
||||
The Ensemble app has a solid foundation with well-designed patterns for caching, audio handling, and multi-device synchronization. However, **critical security vulnerabilities** (plaintext credentials), **zero test coverage**, and a **4,469-line god class** represent significant risks that must be addressed before any production deployment.
|
||||
|
||||
The most urgent priorities are:
|
||||
1. **Secure credential storage** - immediate security risk
|
||||
2. **Add test infrastructure** - enables safe refactoring
|
||||
3. **Split the god class** - enables maintainability
|
||||
4. **Add accessibility** - legal/compliance requirement
|
||||
|
||||
With focused effort over 8-10 weeks, the codebase can be brought to production-quality standards.
|
||||
|
||||
---
|
||||
|
||||
*Audit conducted using 6 parallel specialized sub-agents analyzing security, memory management, race conditions, architecture, UI/UX, and audio/networking.*
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
# Ensemble Codebase Audit Prompt
|
||||
|
||||
Run this prompt with Claude Code to perform a comprehensive audit of the Ensemble Flutter app.
|
||||
|
||||
---
|
||||
|
||||
## Prompt
|
||||
|
||||
You are performing a comprehensive code audit on the Ensemble Flutter app. This is a music/audiobook/podcast player app with 93+ Dart files.
|
||||
|
||||
**CRITICAL RULES:**
|
||||
1. DO NOT remove or break any existing functionality
|
||||
2. All changes must be on the current branch: `audit/code-quality-review`
|
||||
3. Run `flutter analyze` after each set of changes to verify no regressions
|
||||
4. Commit changes in logical, reviewable chunks
|
||||
|
||||
**AUDIT PHASES:**
|
||||
|
||||
### Phase 1: Code Quality Analysis (Read-Only)
|
||||
First, analyze the codebase without making changes. Create a report covering:
|
||||
|
||||
1. **Large File Analysis** - Review these files for refactoring opportunities:
|
||||
- `lib/screens/new_library_screen.dart` (122KB)
|
||||
- `lib/screens/search_screen.dart` (129KB)
|
||||
- `lib/widgets/expandable_player.dart` (107KB)
|
||||
- `lib/screens/album_details_screen.dart` (48KB)
|
||||
- `lib/screens/artist_details_screen.dart` (45KB)
|
||||
|
||||
2. **Pattern Inconsistencies** - Look for:
|
||||
- Inconsistent naming conventions (camelCase vs snake_case)
|
||||
- Mixed widget composition patterns
|
||||
- Inconsistent error handling approaches
|
||||
- Duplicate code across screens/widgets
|
||||
|
||||
3. **Performance Red Flags** - Identify:
|
||||
- Unnecessary rebuilds (missing const constructors)
|
||||
- Heavy computations in build methods
|
||||
- Missing list item caching (ListView.builder vs ListView)
|
||||
- Inefficient state management patterns
|
||||
|
||||
4. **Scroll Performance Issues** - Specifically audit:
|
||||
- ScrollController usage and disposal
|
||||
- Sliver implementations
|
||||
- AnimatedBuilder/AnimatedWidget usage
|
||||
- Image loading in scrollable lists
|
||||
- Any jank-inducing patterns
|
||||
|
||||
### Phase 2: Quick Wins (Low Risk, High Impact)
|
||||
Apply these fixes first:
|
||||
|
||||
1. Add missing `const` constructors throughout
|
||||
2. Fix any `flutter analyze` warnings
|
||||
3. Remove dead code and unused imports
|
||||
4. Standardize formatting with `dart format`
|
||||
|
||||
### Phase 3: Scroll Animation Optimization
|
||||
Focus on smoother scrolling:
|
||||
|
||||
1. **Image Optimization**
|
||||
- Ensure CachedNetworkImage is used consistently
|
||||
- Add appropriate cacheWidth/cacheHeight
|
||||
- Implement proper placeholder/error widgets
|
||||
|
||||
2. **List Performance**
|
||||
- Convert any ListView to ListView.builder where appropriate
|
||||
- Add itemExtent where possible for fixed-height items
|
||||
- Implement AutomaticKeepAliveClientMixin where needed
|
||||
- Consider RepaintBoundary for complex list items
|
||||
|
||||
3. **Animation Smoothing**
|
||||
- Use `Curves.easeOutCubic` or similar for scroll-linked animations
|
||||
- Ensure animations run at 60fps (avoid heavy computations during animation)
|
||||
- Review CustomScrollView/Sliver implementations
|
||||
|
||||
### Phase 4: Code Consistency Improvements
|
||||
|
||||
1. **Widget Extraction**
|
||||
- Extract repeated UI patterns into reusable widgets
|
||||
- Ensure extracted widgets follow existing naming patterns
|
||||
|
||||
2. **State Management**
|
||||
- Verify Provider usage is consistent
|
||||
- Check for proper disposal of controllers/streams
|
||||
|
||||
3. **Error Handling**
|
||||
- Standardize try/catch patterns
|
||||
- Ensure consistent loading/error state UI
|
||||
|
||||
### Phase 5: Verification
|
||||
|
||||
After all changes:
|
||||
1. Run `flutter analyze` - must pass with 0 issues
|
||||
2. Run `flutter test` if tests exist
|
||||
3. Create a summary of all changes made
|
||||
4. List any recommendations that were NOT implemented (too risky)
|
||||
|
||||
---
|
||||
|
||||
## Execution Instructions
|
||||
|
||||
```bash
|
||||
# Start the audit
|
||||
cd /home/home-server/Ensemble
|
||||
git checkout audit/code-quality-review
|
||||
|
||||
# After each phase, commit your changes
|
||||
git add -A && git commit -m "Audit Phase X: [description]"
|
||||
|
||||
# Verify no regressions
|
||||
flutter analyze
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Expected Deliverables
|
||||
|
||||
1. `AUDIT_REPORT.md` - Findings from Phase 1
|
||||
2. Multiple commits with clear messages for each phase
|
||||
3. `AUDIT_SUMMARY.md` - Final summary of all changes and remaining recommendations
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
# Ensemble Flutter App - Code Audit Report
|
||||
|
||||
**Date:** January 4, 2026
|
||||
**Branch:** `audit/code-quality-review`
|
||||
**Files Audited:** 93 Dart files
|
||||
|
||||
---
|
||||
|
||||
## Executive Summary
|
||||
|
||||
The codebase is generally well-maintained with good existing performance optimizations (RepaintBoundary, ListView.builder, cacheExtent settings). Key improvement areas identified:
|
||||
|
||||
| Category | Issues Found | Priority |
|
||||
|----------|-------------|----------|
|
||||
| Deprecated APIs | 20 instances | HIGH |
|
||||
| Missing const constructors | 100+ instances | MEDIUM |
|
||||
| Image cache parameters | 7 locations | MEDIUM |
|
||||
| Code duplication | 8 view mode functions | LOW |
|
||||
| Color constants | 3 files with duplicates | LOW |
|
||||
|
||||
---
|
||||
|
||||
## 1. CRITICAL: Deprecated API Usage
|
||||
|
||||
### `colorScheme.background` (20 instances)
|
||||
Flutter Material 3 deprecates `ColorScheme.background`. Replace with `colorScheme.surface`.
|
||||
|
||||
**Files affected:**
|
||||
- lib/main.dart:335, 336
|
||||
- lib/screens/library_artists_screen.dart:21
|
||||
- lib/screens/new_home_screen.dart:121
|
||||
- lib/screens/artist_details_screen.dart:708, 720
|
||||
- lib/screens/library_playlists_screen.dart:53
|
||||
- lib/screens/library_tracks_screen.dart:19
|
||||
- lib/screens/login_screen.dart:489
|
||||
- lib/screens/new_library_screen.dart:933, 957, 1020, 1021
|
||||
- lib/screens/album_details_screen.dart:807, 819
|
||||
- lib/screens/library_albums_screen.dart:19
|
||||
- lib/screens/search_screen.dart:427, 738, 739
|
||||
- lib/screens/settings_screen.dart:245
|
||||
|
||||
---
|
||||
|
||||
## 2. HIGH: Missing const Constructors
|
||||
|
||||
### EdgeInsets.zero (64 instances)
|
||||
High-impact optimization - used extensively in button padding.
|
||||
|
||||
**Key files:**
|
||||
- lib/screens/album_details_screen.dart (12 instances)
|
||||
- lib/screens/artist_details_screen.dart (8 instances)
|
||||
- lib/screens/audiobook_detail_screen.dart (3 instances)
|
||||
- lib/screens/audiobook_series_screen.dart (2 instances)
|
||||
- lib/screens/audiobook_author_screen.dart (2 instances)
|
||||
|
||||
### BorderRadius.circular (40+ instances)
|
||||
Cannot use `const BorderRadius.circular()` directly. Alternative: `const BorderRadius.all(Radius.circular(X))`.
|
||||
|
||||
---
|
||||
|
||||
## 3. MEDIUM: Scroll Performance - Missing Image Cache Parameters
|
||||
|
||||
### CachedNetworkImage without memCacheWidth/Height
|
||||
|
||||
**lib/screens/new_library_screen.dart:**
|
||||
- Line 1395-1402: Author image (48x48) - missing cache params
|
||||
- Line 1480-1486: Author card image - missing cache params
|
||||
- Line 1572-1580: Audiobook cover (56x56) - missing cache params
|
||||
- Line 1740-1745: Audiobook grid cover - missing cache params
|
||||
- Line 1959-1969: Playlist cover (56x56) - missing cache params
|
||||
- Line 2143-2152: Playlist grid covers - missing cache params
|
||||
- Line 2973-2981: Album cover (56x56) - missing cache params
|
||||
|
||||
**Note:** DecorationImage with CachedNetworkImageProvider cannot have cache size specified (structural Flutter limitation).
|
||||
|
||||
---
|
||||
|
||||
## 4. LOW: Code Duplication
|
||||
|
||||
### View Mode Cycling Functions (8 nearly identical functions)
|
||||
**File:** lib/screens/new_library_screen.dart
|
||||
|
||||
Functions that follow identical switch/case pattern:
|
||||
- `_cycleArtistsViewMode()` (line 184)
|
||||
- `_cycleAlbumsViewMode()` (line 200)
|
||||
- `_cyclePlaylistsViewMode()` (line 216)
|
||||
- `_cycleAuthorsViewMode()` (line 232)
|
||||
- `_cycleAudiobooksViewMode()` (line 248)
|
||||
- `_cycleSeriesViewMode()` (line 286)
|
||||
- `_cycleRadioViewMode()` (line 303)
|
||||
- `_cyclePodcastsViewMode()` (line 319)
|
||||
|
||||
**Recommendation:** Create generic utility function.
|
||||
|
||||
### Duplicated Color Constants (3 files)
|
||||
Series fallback colors defined identically in:
|
||||
- lib/widgets/series_row.dart:246-253
|
||||
- lib/screens/audiobook_series_screen.dart:466-473
|
||||
- lib/screens/new_library_screen.dart:2112-2119
|
||||
|
||||
**Recommendation:** Extract to lib/constants/colors.dart
|
||||
|
||||
---
|
||||
|
||||
## 5. POSITIVE FINDINGS (Already Optimized)
|
||||
|
||||
- **RepaintBoundary**: Properly implemented in all list item widgets
|
||||
- **ListView.builder**: Used consistently with cacheExtent: 1000
|
||||
- **ScrollController disposal**: All 8+ controllers properly disposed
|
||||
- **Animation patterns**: Proper listener cleanup in expandable_player.dart
|
||||
- **Debounced operations**: Color extraction debounced to 300ms
|
||||
|
||||
---
|
||||
|
||||
## Recommended Action Plan
|
||||
|
||||
### Phase 1: Quick Wins (Low Risk)
|
||||
1. Replace `colorScheme.background` with `colorScheme.surface` (20 locations)
|
||||
2. Add `const` to EdgeInsets.zero instances
|
||||
|
||||
### Phase 2: Image Optimization
|
||||
1. Add memCacheWidth/memCacheHeight to CachedNetworkImage instances in new_library_screen.dart
|
||||
|
||||
### Phase 3: Code Cleanup (Optional)
|
||||
1. Extract view mode cycling to utility function
|
||||
2. Centralize color constants
|
||||
|
||||
---
|
||||
|
||||
## Files by Complexity
|
||||
|
||||
| File | Lines | Status |
|
||||
|------|-------|--------|
|
||||
| lib/screens/search_screen.dart | 3,489 | Good structure, minor fixes needed |
|
||||
| lib/screens/new_library_screen.dart | 3,351 | Good performance, some duplication |
|
||||
| lib/widgets/expandable_player.dart | 2,577 | Well-optimized animations |
|
||||
@@ -0,0 +1,57 @@
|
||||
# Audit Summary
|
||||
|
||||
**Branch:** `audit/code-quality-review`
|
||||
**Date:** January 4, 2026
|
||||
|
||||
## Changes Applied
|
||||
|
||||
### Phase 1: Analysis Complete
|
||||
- Created `AUDIT_REPORT.md` with comprehensive findings
|
||||
- 4 parallel subagents analyzed const constructors, scroll performance, code duplication, and dead code
|
||||
|
||||
### Phase 2: Deprecated API Fixes (18 files)
|
||||
- Replaced all `colorScheme.background` with `colorScheme.surface` (Material 3 compliance)
|
||||
|
||||
**Files modified:**
|
||||
- lib/screens/library_artists_screen.dart
|
||||
- lib/screens/library_albums_screen.dart
|
||||
- lib/screens/library_playlists_screen.dart
|
||||
- lib/screens/library_tracks_screen.dart
|
||||
- lib/screens/artist_details_screen.dart
|
||||
- lib/screens/new_home_screen.dart
|
||||
- lib/screens/login_screen.dart
|
||||
- lib/screens/settings_screen.dart
|
||||
- lib/screens/album_details_screen.dart
|
||||
- lib/screens/search_screen.dart
|
||||
- lib/screens/new_library_screen.dart
|
||||
|
||||
### Phase 3: Scroll Performance Optimization
|
||||
- Added `memCacheWidth` and `memCacheHeight` to CachedNetworkImage instances
|
||||
|
||||
**lib/screens/new_library_screen.dart:**
|
||||
- Line 1400-1401: Author list tile image (128x128 cache)
|
||||
- Line 1487-1488: Author grid card image (256x256 cache)
|
||||
- Line 1577-1578: Audiobook list tile cover (256x256 cache)
|
||||
- Line 1749-1750: Audiobook grid cover (512x512 cache)
|
||||
- Line 1970-1971: Series list tile cover (256x256 cache)
|
||||
- Line 2986-2987: Album list tile cover (256x256 cache)
|
||||
|
||||
## Recommendations NOT Implemented (Low Priority)
|
||||
|
||||
These were identified but NOT changed to preserve functionality:
|
||||
|
||||
1. **View mode cycling refactor** - 8 similar functions could be consolidated
|
||||
2. **Color constant extraction** - Duplicated colors in 3 files
|
||||
3. **EdgeInsets.zero const** - 64 instances (build-time only, minimal impact)
|
||||
4. **BorderRadius.circular const** - 40+ instances
|
||||
|
||||
## Verification
|
||||
|
||||
Changes should be verified by:
|
||||
1. GitHub Actions build (triggered automatically)
|
||||
2. Manual UI testing of scroll smoothness
|
||||
3. Verify no visual regressions in dark/light themes
|
||||
|
||||
## Build Trigger
|
||||
|
||||
GitHub Actions workflow triggered on branch `audit/code-quality-review`
|
||||
@@ -0,0 +1,52 @@
|
||||
# Search Improvements
|
||||
|
||||
Branch: `feature/search-improvements`
|
||||
|
||||
## Completed
|
||||
|
||||
- [x] Add playlists and audiobooks to search results
|
||||
- Parse from MA API response
|
||||
- Filter chips for each type
|
||||
- Tile builders with navigation to detail screens
|
||||
|
||||
- [x] Unified Relevance-Based "All" Results
|
||||
- Scoring algorithm implemented:
|
||||
- Exact match: 100 points
|
||||
- Starts with query: 80 points
|
||||
- Contains query (word boundary): 60 points
|
||||
- Contains query (anywhere): 40 points
|
||||
- Fuzzy match: 20 points
|
||||
- Bonus for library items (albums): +10 points
|
||||
- Bonus for favorites: +5 points
|
||||
- Secondary field matching (artist name in albums/tracks)
|
||||
- Merged all results into single sorted list
|
||||
- Type indicators in subtitle (e.g., "Artist • Album")
|
||||
|
||||
- [x] Smart Cross-Referencing
|
||||
- Extracts unique artists from matched tracks/albums
|
||||
- Filters to artists whose name contains query words (min 3 chars)
|
||||
- Adds cross-referenced artists with lower relevance score (25)
|
||||
- Avoids duplicates with direct search results
|
||||
|
||||
- [x] Past Searches Row
|
||||
- Added SearchHistory table to database (schema v4)
|
||||
- Saves successful searches (deduplicated, max 10)
|
||||
- Displays as ActionChips in empty state
|
||||
- Clicking chip performs that search
|
||||
|
||||
## Remaining Ideas (Lower Priority)
|
||||
|
||||
- **Library-only toggle:** Add switch to filter search to library items only (MA API supports this)
|
||||
- **Voice search:** Add microphone button if platform supports speech recognition
|
||||
- **Search suggestions:** Typeahead from library as user types
|
||||
- **Quick actions:** Long-press result for play/queue options without navigating
|
||||
- **Clear history in settings:** Add option to clear search history
|
||||
|
||||
## Files Modified
|
||||
|
||||
| File | Changes |
|
||||
|------|---------|
|
||||
| `lib/database/database.dart` | Added SearchHistory table, schema v4 |
|
||||
| `lib/services/database_service.dart` | Added search history methods |
|
||||
| `lib/screens/search_screen.dart` | Relevance scoring, cross-refs, history UI |
|
||||
| `lib/l10n/app_en.arb` | Added localization strings |
|
||||
@@ -25,4 +25,7 @@ class HeroTags {
|
||||
|
||||
/// Audiobook author image hero tag prefix
|
||||
static const String authorImage = 'author_image_';
|
||||
|
||||
/// Podcast cover hero tag prefix
|
||||
static const String podcastCover = 'podcast_cover_';
|
||||
}
|
||||
|
||||
+128
-2
@@ -25,6 +25,8 @@ class Profiles extends Table {
|
||||
}
|
||||
|
||||
/// Recently played items - scoped by profile
|
||||
@TableIndex(name: 'idx_recently_played_profile', columns: {#profileUsername})
|
||||
@TableIndex(name: 'idx_recently_played_profile_played', columns: {#profileUsername, #playedAt})
|
||||
class RecentlyPlayed extends Table {
|
||||
/// Auto-incrementing ID
|
||||
IntColumn get id => integer().autoIncrement()();
|
||||
@@ -55,6 +57,8 @@ class RecentlyPlayed extends Table {
|
||||
}
|
||||
|
||||
/// Cached library items for fast startup
|
||||
@TableIndex(name: 'idx_library_cache_type', columns: {#itemType})
|
||||
@TableIndex(name: 'idx_library_cache_type_deleted', columns: {#itemType, #isDeleted})
|
||||
class LibraryCache extends Table {
|
||||
/// Composite key: provider + item_id
|
||||
TextColumn get cacheKey => text()();
|
||||
@@ -139,6 +143,8 @@ class CachedPlayers extends Table {
|
||||
}
|
||||
|
||||
/// Cached queue items for selected player
|
||||
@TableIndex(name: 'idx_cached_queue_player', columns: {#playerId})
|
||||
@TableIndex(name: 'idx_cached_queue_player_position', columns: {#playerId, #position})
|
||||
class CachedQueue extends Table {
|
||||
/// Auto-incrementing ID for ordering
|
||||
IntColumn get id => integer().autoIncrement()();
|
||||
@@ -153,12 +159,39 @@ class CachedQueue extends Table {
|
||||
IntColumn get position => integer()();
|
||||
}
|
||||
|
||||
@DriftDatabase(tables: [Profiles, RecentlyPlayed, LibraryCache, SyncMetadata, PlaybackState, CachedPlayers, CachedQueue])
|
||||
/// Cached home row data for instant display on startup
|
||||
class HomeRowCache extends Table {
|
||||
/// Row type: 'recent_albums', 'discover_artists', 'discover_albums'
|
||||
TextColumn get rowType => text()();
|
||||
|
||||
/// Serialized list of items as JSON array
|
||||
TextColumn get itemsJson => text()();
|
||||
|
||||
/// When this was last updated
|
||||
DateTimeColumn get lastUpdated => dateTime()();
|
||||
|
||||
@override
|
||||
Set<Column> get primaryKey => {rowType};
|
||||
}
|
||||
|
||||
/// Search history for quick access to recent searches
|
||||
class SearchHistory extends Table {
|
||||
/// Auto-incrementing ID
|
||||
IntColumn get id => integer().autoIncrement()();
|
||||
|
||||
/// The search query
|
||||
TextColumn get query => text()();
|
||||
|
||||
/// When the search was performed
|
||||
DateTimeColumn get searchedAt => dateTime()();
|
||||
}
|
||||
|
||||
@DriftDatabase(tables: [Profiles, RecentlyPlayed, LibraryCache, SyncMetadata, PlaybackState, CachedPlayers, CachedQueue, HomeRowCache, SearchHistory])
|
||||
class AppDatabase extends _$AppDatabase {
|
||||
AppDatabase([QueryExecutor? executor]) : super(executor ?? _openConnection());
|
||||
|
||||
@override
|
||||
int get schemaVersion => 2;
|
||||
int get schemaVersion => 5;
|
||||
|
||||
@override
|
||||
MigrationStrategy get migration {
|
||||
@@ -173,6 +206,26 @@ class AppDatabase extends _$AppDatabase {
|
||||
await m.createTable(cachedPlayers);
|
||||
await m.createTable(cachedQueue);
|
||||
}
|
||||
// Migration from v2 to v3: Add home row cache table
|
||||
if (from < 3) {
|
||||
await m.createTable(homeRowCache);
|
||||
}
|
||||
// Migration from v3 to v4: Add search history table
|
||||
if (from < 4) {
|
||||
await m.createTable(searchHistory);
|
||||
}
|
||||
// Migration from v4 to v5: Add indexes for query performance
|
||||
if (from < 5) {
|
||||
// RecentlyPlayed indexes
|
||||
await customStatement('CREATE INDEX IF NOT EXISTS idx_recently_played_profile ON recently_played (profile_username)');
|
||||
await customStatement('CREATE INDEX IF NOT EXISTS idx_recently_played_profile_played ON recently_played (profile_username, played_at)');
|
||||
// LibraryCache indexes
|
||||
await customStatement('CREATE INDEX IF NOT EXISTS idx_library_cache_type ON library_cache (item_type)');
|
||||
await customStatement('CREATE INDEX IF NOT EXISTS idx_library_cache_type_deleted ON library_cache (item_type, is_deleted)');
|
||||
// CachedQueue indexes
|
||||
await customStatement('CREATE INDEX IF NOT EXISTS idx_cached_queue_player ON cached_queue (player_id)');
|
||||
await customStatement('CREATE INDEX IF NOT EXISTS idx_cached_queue_player_position ON cached_queue (player_id, position)');
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -524,4 +577,77 @@ class AppDatabase extends _$AppDatabase {
|
||||
Future<void> clearAllCachedQueues() async {
|
||||
await delete(cachedQueue).go();
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Home Row Cache Operations
|
||||
// ============================================
|
||||
|
||||
/// Save home row data
|
||||
Future<void> saveHomeRowCache(String rowType, String itemsJson) async {
|
||||
await into(homeRowCache).insertOnConflictUpdate(
|
||||
HomeRowCacheCompanion(
|
||||
rowType: Value(rowType),
|
||||
itemsJson: Value(itemsJson),
|
||||
lastUpdated: Value(DateTime.now()),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Get cached home row data
|
||||
Future<HomeRowCacheData?> getHomeRowCache(String rowType) async {
|
||||
return (select(homeRowCache)..where((h) => h.rowType.equals(rowType)))
|
||||
.getSingleOrNull();
|
||||
}
|
||||
|
||||
/// Clear all home row cache
|
||||
Future<void> clearHomeRowCache() async {
|
||||
await delete(homeRowCache).go();
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Search History Operations
|
||||
// ============================================
|
||||
|
||||
/// Save a search query to history (deduplicates and limits to 10)
|
||||
Future<void> saveSearchQuery(String query) async {
|
||||
final trimmedQuery = query.trim();
|
||||
if (trimmedQuery.isEmpty) return;
|
||||
|
||||
await transaction(() async {
|
||||
// Delete existing entry with same query (case-insensitive)
|
||||
await (delete(searchHistory)
|
||||
..where((s) => s.query.lower().equals(trimmedQuery.toLowerCase())))
|
||||
.go();
|
||||
|
||||
// Insert the new search
|
||||
await into(searchHistory).insert(SearchHistoryCompanion.insert(
|
||||
query: trimmedQuery,
|
||||
searchedAt: DateTime.now(),
|
||||
));
|
||||
|
||||
// Keep only the 10 most recent searches
|
||||
final allSearches = await (select(searchHistory)
|
||||
..orderBy([(s) => OrderingTerm.desc(s.searchedAt)]))
|
||||
.get();
|
||||
|
||||
if (allSearches.length > 10) {
|
||||
final toDelete = allSearches.skip(10).map((s) => s.id).toList();
|
||||
await (delete(searchHistory)..where((s) => s.id.isIn(toDelete))).go();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Get recent search queries (up to 10, most recent first)
|
||||
Future<List<String>> getRecentSearches() async {
|
||||
final searches = await (select(searchHistory)
|
||||
..orderBy([(s) => OrderingTerm.desc(s.searchedAt)])
|
||||
..limit(10))
|
||||
.get();
|
||||
return searches.map((s) => s.query).toList();
|
||||
}
|
||||
|
||||
/// Clear all search history
|
||||
Future<void> clearSearchHistory() async {
|
||||
await delete(searchHistory).go();
|
||||
}
|
||||
}
|
||||
|
||||
+14
-1
@@ -68,6 +68,12 @@
|
||||
"tracks": "Songs",
|
||||
"playlists": "Wiedergabelisten",
|
||||
"audiobooks": "Hörbücher",
|
||||
"music": "Musik",
|
||||
"radio": "Radio",
|
||||
"stations": "Sender",
|
||||
"selectLibrary": "Bibliothek auswählen",
|
||||
"noRadioStations": "Keine Radiosender",
|
||||
"addRadioStationsHint": "Füge Radiosender in Music Assistant hinzu",
|
||||
"searchFailed": "Suche fehlgeschlagen. Bitte überprüfe deine Verbindung.",
|
||||
|
||||
"queue": "Warteschlange",
|
||||
@@ -279,7 +285,14 @@
|
||||
"playerStateUnavailable": "Nicht verfügbar",
|
||||
"playerStateOff": "Aus",
|
||||
"playerStateIdle": "Inaktiv",
|
||||
"playerStateExternalSource": "Externe Quelle",
|
||||
"playerSelected": "Ausgewählt",
|
||||
"actionQueuedForSync": "Wird synchronisiert wenn online",
|
||||
"pendingOfflineActions": "{count} ausstehende Synchronisierung"
|
||||
"pendingOfflineActions": "{count} ausstehende Synchronisierung",
|
||||
"hintsAndTips": "Tipps & Hinweise",
|
||||
"showHints": "Hinweise anzeigen",
|
||||
"showHintsDescription": "Hilfreiche Tipps zum Entdecken von Funktionen anzeigen",
|
||||
"pullToSelectPlayers": "Ziehen um Geräte auszuwählen",
|
||||
"holdToSync": "Gedrückt halten zum Sync",
|
||||
"swipeToAdjustVolume": "Wischen für Lautstärke"
|
||||
}
|
||||
|
||||
+168
-1
@@ -261,6 +261,26 @@
|
||||
"description": "Search hint text"
|
||||
},
|
||||
|
||||
"recentSearches": "Recent Searches",
|
||||
"@recentSearches": {
|
||||
"description": "Label for recent search history section"
|
||||
},
|
||||
|
||||
"clearSearchHistory": "Clear Search History",
|
||||
"@clearSearchHistory": {
|
||||
"description": "Button to clear search history"
|
||||
},
|
||||
|
||||
"searchHistoryCleared": "Search history cleared",
|
||||
"@searchHistoryCleared": {
|
||||
"description": "Confirmation message after clearing search history"
|
||||
},
|
||||
|
||||
"libraryOnly": "Library only",
|
||||
"@libraryOnly": {
|
||||
"description": "Toggle to search only in library"
|
||||
},
|
||||
|
||||
"retry": "Retry",
|
||||
"@retry": {
|
||||
"description": "Retry button label"
|
||||
@@ -296,6 +316,36 @@
|
||||
"description": "Audiobooks category"
|
||||
},
|
||||
|
||||
"music": "Music",
|
||||
"@music": {
|
||||
"description": "Music category"
|
||||
},
|
||||
|
||||
"radio": "Radio",
|
||||
"@radio": {
|
||||
"description": "Radio category"
|
||||
},
|
||||
|
||||
"stations": "Stations",
|
||||
"@stations": {
|
||||
"description": "Radio stations subcategory"
|
||||
},
|
||||
|
||||
"selectLibrary": "Select Library",
|
||||
"@selectLibrary": {
|
||||
"description": "Title for library type selection bottom sheet"
|
||||
},
|
||||
|
||||
"noRadioStations": "No radio stations",
|
||||
"@noRadioStations": {
|
||||
"description": "Empty state when no radio stations are available"
|
||||
},
|
||||
|
||||
"addRadioStationsHint": "Add radio stations in Music Assistant",
|
||||
"@addRadioStationsHint": {
|
||||
"description": "Hint for adding radio stations"
|
||||
},
|
||||
|
||||
"searchFailed": "Search failed. Please check your connection.",
|
||||
"@searchFailed": {
|
||||
"description": "Search error message"
|
||||
@@ -610,6 +660,21 @@
|
||||
"description": "Radio button label"
|
||||
},
|
||||
|
||||
"playingRadioStation": "Playing {name}",
|
||||
"@playingRadioStation": {
|
||||
"description": "Status when playing radio station",
|
||||
"placeholders": {
|
||||
"name": {
|
||||
"type": "String"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
"addedToQueue": "Added to queue",
|
||||
"@addedToQueue": {
|
||||
"description": "Confirmation when item added to queue"
|
||||
},
|
||||
|
||||
"inLibrary": "In Library",
|
||||
"@inLibrary": {
|
||||
"description": "In library section title"
|
||||
@@ -1001,6 +1066,9 @@
|
||||
"chooseHomeScreenRows": "Choose which rows to display on the home screen",
|
||||
"addedToFavorites": "Added to favorites",
|
||||
"removedFromFavorites": "Removed from favorites",
|
||||
"addedToLibrary": "Added to library",
|
||||
"removedFromLibrary": "Removed from library",
|
||||
"addToLibrary": "Add to library",
|
||||
"unknown": "Unknown",
|
||||
"noUpcomingTracks": "No upcoming tracks",
|
||||
"showAll": "Show all",
|
||||
@@ -1011,6 +1079,10 @@
|
||||
"shows": "Shows",
|
||||
"podcasts": "Podcasts",
|
||||
"podcastSupportComingSoon": "Podcast support coming soon",
|
||||
"noPodcasts": "No podcasts",
|
||||
"addPodcastsHint": "Subscribe to podcasts in Music Assistant",
|
||||
"episodes": "Episodes",
|
||||
"episode": "Episode",
|
||||
"playlist": "Playlist",
|
||||
"connectionError": "Connection Error",
|
||||
"twoColumnGrid": "2-column grid",
|
||||
@@ -1078,7 +1150,7 @@
|
||||
"description": "Hint for Last.fm API key field"
|
||||
},
|
||||
|
||||
"swipeToSwitchDevice": "Swipe to switch device",
|
||||
"swipeToSwitchDevice": "Swipe to change player",
|
||||
"@swipeToSwitchDevice": {
|
||||
"description": "Hint for device switching gesture"
|
||||
},
|
||||
@@ -1133,6 +1205,21 @@
|
||||
"description": "Singular form of audiobook"
|
||||
},
|
||||
|
||||
"albumSingular": "Album",
|
||||
"@albumSingular": {
|
||||
"description": "Singular form of album for search type indicator"
|
||||
},
|
||||
|
||||
"trackSingular": "Track",
|
||||
"@trackSingular": {
|
||||
"description": "Singular form of track for search type indicator"
|
||||
},
|
||||
|
||||
"podcastSingular": "Podcast",
|
||||
"@podcastSingular": {
|
||||
"description": "Singular form of podcast for search type indicator"
|
||||
},
|
||||
|
||||
"trackCount": "{count} {count, plural, =1{track} other{tracks}}",
|
||||
"@trackCount": {
|
||||
"description": "Track count with plural",
|
||||
@@ -1193,6 +1280,11 @@
|
||||
"description": "Player state when idle"
|
||||
},
|
||||
|
||||
"playerStateExternalSource": "External Source",
|
||||
"@playerStateExternalSource": {
|
||||
"description": "Player state when playing from external source (optical, Spotify, etc.)"
|
||||
},
|
||||
|
||||
"playerSelected": "Selected",
|
||||
"@playerSelected": {
|
||||
"description": "Label for selected player"
|
||||
@@ -1211,5 +1303,80 @@
|
||||
"type": "int"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
"hintsAndTips": "Hints & Tips",
|
||||
"@hintsAndTips": {
|
||||
"description": "Settings section title for hints"
|
||||
},
|
||||
|
||||
"showHints": "Show Hints",
|
||||
"@showHints": {
|
||||
"description": "Toggle label for showing hints"
|
||||
},
|
||||
|
||||
"showHintsDescription": "Display helpful tips for discovering features",
|
||||
"@showHintsDescription": {
|
||||
"description": "Description for show hints toggle"
|
||||
},
|
||||
|
||||
"pullToSelectPlayers": "Pull to select players",
|
||||
"@pullToSelectPlayers": {
|
||||
"description": "Hint shown when mini player bounces"
|
||||
},
|
||||
|
||||
"holdToSync": "Long-press to sync",
|
||||
"@holdToSync": {
|
||||
"description": "Hint for long-press to sync players"
|
||||
},
|
||||
|
||||
"swipeToAdjustVolume": "Swipe to adjust volume",
|
||||
"@swipeToAdjustVolume": {
|
||||
"description": "Hint for swiping left/right to adjust player volume"
|
||||
},
|
||||
|
||||
"selectPlayerHint": "Choose a player, or dismiss by swiping down",
|
||||
"@selectPlayerHint": {
|
||||
"description": "First-time hint for selecting a player in device selector"
|
||||
},
|
||||
|
||||
"welcomeToEnsemble": "Welcome to Ensemble",
|
||||
"@welcomeToEnsemble": {
|
||||
"description": "Welcome message title for onboarding"
|
||||
},
|
||||
|
||||
"welcomeMessage": "By default your phone is the selected player.\nPull the mini player down to select another player.",
|
||||
"@welcomeMessage": {
|
||||
"description": "Welcome message body explaining how to select players"
|
||||
},
|
||||
|
||||
"skip": "Skip",
|
||||
"@skip": {
|
||||
"description": "Button to skip onboarding or hints"
|
||||
},
|
||||
|
||||
"dismissPlayerHint": "Swipe down, tap outside, or press back to return",
|
||||
"@dismissPlayerHint": {
|
||||
"description": "Hint explaining how to dismiss the player selector"
|
||||
},
|
||||
|
||||
"playingAlbum": "Playing {albumName}",
|
||||
"@playingAlbum": {
|
||||
"description": "Message shown when starting to play an album",
|
||||
"placeholders": {
|
||||
"albumName": {
|
||||
"type": "String"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
"playingPlaylist": "Playing {playlistName}",
|
||||
"@playingPlaylist": {
|
||||
"description": "Message shown when starting to play a playlist",
|
||||
"placeholders": {
|
||||
"playlistName": {
|
||||
"type": "String"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+15
-2
@@ -66,6 +66,12 @@
|
||||
"tracks": "Canciones",
|
||||
"playlists": "Listas de reproducción",
|
||||
"audiobooks": "Audiolibros",
|
||||
"music": "Música",
|
||||
"radio": "Radio",
|
||||
"stations": "Emisoras",
|
||||
"selectLibrary": "Seleccionar Biblioteca",
|
||||
"noRadioStations": "No hay emisoras de radio",
|
||||
"addRadioStationsHint": "Añade emisoras de radio en Music Assistant",
|
||||
"searchFailed": "Búsqueda fallida. Por favor, verifica tu conexión.",
|
||||
"queue": "Cola",
|
||||
"playerQueue": "Cola de {playerName}",
|
||||
@@ -434,7 +440,7 @@
|
||||
"metadataApisDescription": "Las imágenes de artistas se obtienen automáticamente de Deezer. Añade claves API a continuación para biografías de artistas y descripciones de álbumes.",
|
||||
"lastFmApiKey": "Clave API de Last.fm",
|
||||
"lastFmApiKeyHint": "Obtén una clave gratuita en last.fm/api",
|
||||
"swipeToSwitchDevice": "Desliza para cambiar de dispositivo",
|
||||
"swipeToSwitchDevice": "Desliza para cambiar dispositivo",
|
||||
"chapterNumber": "Capítulo {number}",
|
||||
"@chapterNumber": {
|
||||
"placeholders": {
|
||||
@@ -475,7 +481,14 @@
|
||||
"playerStateUnavailable": "No disponible",
|
||||
"playerStateOff": "Apagado",
|
||||
"playerStateIdle": "Inactivo",
|
||||
"playerStateExternalSource": "Fuente Externa",
|
||||
"playerSelected": "Seleccionado",
|
||||
"actionQueuedForSync": "Se sincronizará cuando esté en línea",
|
||||
"pendingOfflineActions": "{count} sincronización pendiente"
|
||||
"pendingOfflineActions": "{count} sincronización pendiente",
|
||||
"hintsAndTips": "Consejos y Sugerencias",
|
||||
"showHints": "Mostrar Sugerencias",
|
||||
"showHintsDescription": "Mostrar consejos útiles para descubrir funciones",
|
||||
"pullToSelectPlayers": "Desliza para seleccionar dispositivos",
|
||||
"holdToSync": "Mantén presionado para sync",
|
||||
"swipeToAdjustVolume": "Desliza para ajustar volumen"
|
||||
}
|
||||
|
||||
+68
-8
@@ -40,6 +40,10 @@ Future<void> main() async {
|
||||
// Migrate existing ownerName to profile (one-time for existing users)
|
||||
await ProfileService.instance.migrateFromOwnerName();
|
||||
|
||||
// Migrate credentials to secure storage (one-time for existing users)
|
||||
await SettingsService.migrateToSecureStorage();
|
||||
_logger.log('🔐 Secure storage migration complete');
|
||||
|
||||
// Load library from cache for instant startup
|
||||
await SyncService.instance.loadFromCache();
|
||||
_logger.log('📦 Library cache loaded');
|
||||
@@ -225,10 +229,17 @@ class _MusicAssistantAppState extends State<MusicAssistantApp> with WidgetsBindi
|
||||
ColorScheme? darkColorScheme;
|
||||
|
||||
if (themeProvider.useMaterialTheme && snapshot.hasData && snapshot.data != null) {
|
||||
// Use system color schemes
|
||||
// Use system color schemes, but override background to match app design
|
||||
// Material You doesn't set background consistently, causing black screen issues
|
||||
final (light, dark) = snapshot.data!;
|
||||
lightColorScheme = light;
|
||||
darkColorScheme = dark;
|
||||
lightColorScheme = light.copyWith(
|
||||
surface: light.surface,
|
||||
background: const Color(0xFFFAFAFA), // App's preferred light background
|
||||
);
|
||||
darkColorScheme = dark.copyWith(
|
||||
surface: const Color(0xFF2a2a2a), // App's preferred dark surface
|
||||
background: const Color(0xFF1a1a1a), // App's preferred dark background
|
||||
);
|
||||
} else {
|
||||
// Use custom color from theme provider
|
||||
lightColorScheme = generateLightColorScheme(themeProvider.customColor);
|
||||
@@ -348,7 +359,16 @@ class _SystemUIWrapperState extends State<SystemUIWrapper> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Startup widget that checks if user is logged in and auto-connects
|
||||
/// Startup widget that checks if user is logged in and auto-connects.
|
||||
///
|
||||
/// CRITICAL: This widget is the single source of truth for the startup transition.
|
||||
/// It loads settings FIRST (before connection), then waits for the appropriate
|
||||
/// conditions before showing HomeScreen. This eliminates the race condition between
|
||||
/// AppStartup and GlobalPlayerOverlay that caused the home screen flash.
|
||||
///
|
||||
/// For first-time users: Holds dark screen until connected + player selected,
|
||||
/// so the welcome overlay can appear seamlessly.
|
||||
/// For returning users: Transitions as soon as connection is established.
|
||||
class AppStartup extends StatefulWidget {
|
||||
const AppStartup({super.key});
|
||||
|
||||
@@ -361,9 +381,32 @@ class _AppStartupState extends State<AppStartup> {
|
||||
String? _savedServerUrl;
|
||||
bool _connectionAttempted = false;
|
||||
|
||||
// Welcome system state - loaded FIRST before connection check
|
||||
bool _settingsLoaded = false;
|
||||
bool _hasCompletedOnboarding = true; // Default to true (no welcome needed)
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadSettingsFirst();
|
||||
}
|
||||
|
||||
/// Load settings BEFORE checking connection.
|
||||
/// This ensures we know if this is a first-time user before transitioning.
|
||||
Future<void> _loadSettingsFirst() async {
|
||||
// Load onboarding state first - this is critical for determining
|
||||
// when to transition to HomeScreen
|
||||
_hasCompletedOnboarding = await SettingsService.getHasCompletedOnboarding();
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
setState(() {
|
||||
_settingsLoaded = true;
|
||||
});
|
||||
|
||||
_logger.log('🚀 AppStartup: Settings loaded, hasCompletedOnboarding=$_hasCompletedOnboarding');
|
||||
|
||||
// Now check connection
|
||||
_checkAndConnect();
|
||||
}
|
||||
|
||||
@@ -388,14 +431,30 @@ class _AppStartupState extends State<AppStartup> {
|
||||
// Just wait for it to complete or timeout
|
||||
_logger.log('🚀 AppStartup: Waiting for provider auto-connection to $serverUrl');
|
||||
|
||||
// For first-time users, we need to wait for both connection AND player selection
|
||||
// so the welcome overlay can appear immediately without home screen flash.
|
||||
// For returning users, just wait for connection.
|
||||
final needsWelcome = !_hasCompletedOnboarding;
|
||||
|
||||
// Give the provider time to connect (it restores credentials and connects in _initialize)
|
||||
// Check connection state periodically
|
||||
for (var i = 0; i < 20; i++) {
|
||||
await Future.delayed(const Duration(milliseconds: 250));
|
||||
if (provider.isConnected) {
|
||||
_logger.log('🚀 AppStartup: Connection established');
|
||||
break;
|
||||
|
||||
if (needsWelcome) {
|
||||
// First-time user: wait for connection + player selection
|
||||
if (provider.isConnected && provider.selectedPlayer != null) {
|
||||
_logger.log('🚀 AppStartup: First-time user ready (connected + player selected)');
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// Returning user: just wait for connection
|
||||
if (provider.isConnected) {
|
||||
_logger.log('🚀 AppStartup: Connection established');
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (provider.connectionState == MAConnectionState.error) {
|
||||
_logger.log('🚀 AppStartup: Connection failed with error');
|
||||
break;
|
||||
@@ -422,7 +481,8 @@ class _AppStartupState extends State<AppStartup> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Show loading while checking settings or connecting
|
||||
if (!_connectionAttempted || _isConnecting) {
|
||||
// CRITICAL: Don't transition until settings are loaded - this prevents the race
|
||||
if (!_settingsLoaded || !_connectionAttempted || _isConnecting) {
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFF1a1a1a),
|
||||
body: Center(
|
||||
|
||||
+98
-7
@@ -14,6 +14,9 @@ class Player {
|
||||
final double? elapsedTimeLastUpdated; // Unix timestamp when elapsed_time was last updated
|
||||
final List<String>? groupMembers; // List of player IDs in sync group (includes self)
|
||||
final String? syncedTo; // Player ID this player is synced to (null if leader or not synced)
|
||||
final String? activeSource; // The currently active source for this player
|
||||
final bool isExternalSource; // True when an external source (optical, Spotify, etc.) is active
|
||||
final String? appId; // The app_id from MA - 'music_assistant' when MA is playing, else external source
|
||||
|
||||
Player({
|
||||
required this.playerId,
|
||||
@@ -29,6 +32,9 @@ class Player {
|
||||
this.elapsedTimeLastUpdated,
|
||||
this.groupMembers,
|
||||
this.syncedTo,
|
||||
this.activeSource,
|
||||
this.isExternalSource = false,
|
||||
this.appId,
|
||||
});
|
||||
|
||||
/// Create a copy of this Player with some fields replaced
|
||||
@@ -46,6 +52,9 @@ class Player {
|
||||
double? elapsedTimeLastUpdated,
|
||||
List<String>? groupMembers,
|
||||
String? syncedTo,
|
||||
String? activeSource,
|
||||
bool? isExternalSource,
|
||||
String? appId,
|
||||
}) {
|
||||
return Player(
|
||||
playerId: playerId ?? this.playerId,
|
||||
@@ -61,6 +70,9 @@ class Player {
|
||||
elapsedTimeLastUpdated: elapsedTimeLastUpdated ?? this.elapsedTimeLastUpdated,
|
||||
groupMembers: groupMembers ?? this.groupMembers,
|
||||
syncedTo: syncedTo ?? this.syncedTo,
|
||||
activeSource: activeSource ?? this.activeSource,
|
||||
isExternalSource: isExternalSource ?? this.isExternalSource,
|
||||
appId: appId ?? this.appId,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -75,8 +87,31 @@ class Player {
|
||||
bool get isGroupLeader => groupMembers != null && groupMembers!.length > 1 && syncedTo == null;
|
||||
bool get isGroupChild => syncedTo != null;
|
||||
|
||||
// A player is manually synced if it's synced TO another player (child of a sync group)
|
||||
// This excludes pre-configured MA speaker groups which have groupMembers but no syncedTo
|
||||
// Used for yellow border highlight - only shows for players the user manually synced
|
||||
bool get isManuallySynced => syncedTo != null;
|
||||
|
||||
// Track when this Player object was created (for local interpolation fallback)
|
||||
static final Map<String, double> _playerCreationTimes = {};
|
||||
static const int _maxCreationTimesEntries = 50;
|
||||
|
||||
/// Clean up old creation time entries using LRU eviction
|
||||
static void _cleanupCreationTimes() {
|
||||
if (_playerCreationTimes.length <= _maxCreationTimesEntries) return;
|
||||
|
||||
// Sort by timestamp value (oldest first) for true LRU eviction
|
||||
final sortedEntries = _playerCreationTimes.entries.toList()
|
||||
..sort((a, b) => a.value.compareTo(b.value));
|
||||
|
||||
// Remove oldest entries until we're at target size
|
||||
final entriesToRemove = sortedEntries.take(
|
||||
_playerCreationTimes.length - _maxCreationTimesEntries,
|
||||
);
|
||||
for (final entry in entriesToRemove) {
|
||||
_playerCreationTimes.remove(entry.key);
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate current elapsed time (interpolated if playing)
|
||||
double get currentElapsedTime {
|
||||
@@ -118,13 +153,8 @@ class Player {
|
||||
if (!_playerCreationTimes.containsKey(creationKey)) {
|
||||
// First time seeing this elapsed_time - record when we saw it
|
||||
_playerCreationTimes[creationKey] = now;
|
||||
// Clean up old entries to prevent memory leak
|
||||
if (_playerCreationTimes.length > 100) {
|
||||
final keysToRemove = _playerCreationTimes.keys.take(50).toList();
|
||||
for (final key in keysToRemove) {
|
||||
_playerCreationTimes.remove(key);
|
||||
}
|
||||
}
|
||||
// Clean up old entries to prevent memory leak (LRU eviction)
|
||||
_cleanupCreationTimes();
|
||||
}
|
||||
|
||||
final creationTime = _playerCreationTimes[creationKey]!;
|
||||
@@ -185,6 +215,61 @@ class Player {
|
||||
// Parse synced_to - the player ID this player is synced to
|
||||
final syncedTo = json['synced_to'] as String?;
|
||||
|
||||
// Parse active_source - the currently active source for this player
|
||||
final activeSource = json['active_source'] as String?;
|
||||
|
||||
// Detect external source (optical, Spotify, AirPlay, etc.)
|
||||
// Primary indicator: app_id - if not 'music_assistant', it's an external source
|
||||
// Secondary indicators: URI patterns and media_type
|
||||
bool isExternalSource = false;
|
||||
|
||||
// Check app_id first - this is the most reliable indicator for DLNA players
|
||||
// When MA is playing: app_id = 'music_assistant'
|
||||
// When external source: app_id = 'http', 'spotify', etc.
|
||||
final appId = json['app_id'] as String?;
|
||||
if (appId != null && appId.isNotEmpty && appId != 'music_assistant') {
|
||||
// app_id is set but not 'music_assistant' - external source is active
|
||||
isExternalSource = true;
|
||||
}
|
||||
|
||||
// Also check current_media for additional external source indicators
|
||||
if (!isExternalSource && json.containsKey('current_media')) {
|
||||
final currentMedia = json['current_media'] as Map<String, dynamic>?;
|
||||
if (currentMedia != null) {
|
||||
final uri = currentMedia['uri'] as String?;
|
||||
final mediaType = currentMedia['media_type'] as String?;
|
||||
|
||||
// External source indicators:
|
||||
// 1. URI is a simple identifier like 'optical', 'line_in', 'bluetooth', 'hdmi'
|
||||
// 2. URI starts with external protocols: 'spotify://', 'airplay://', etc.
|
||||
// 3. Media type is 'unknown' (MA doesn't recognize the source)
|
||||
if (uri != null) {
|
||||
final uriLower = uri.toLowerCase();
|
||||
// Simple external source identifiers (no :// or /)
|
||||
final isSimpleExternalId = !uri.contains('://') && !uri.contains('/') &&
|
||||
(uriLower == 'optical' || uriLower == 'line_in' || uriLower == 'bluetooth' ||
|
||||
uriLower == 'hdmi' || uriLower == 'tv' || uriLower == 'aux' ||
|
||||
uriLower == 'coaxial' || uriLower == 'toslink');
|
||||
// External streaming protocols
|
||||
final isExternalProtocol = uriLower.startsWith('spotify://') ||
|
||||
uriLower.startsWith('airplay://') ||
|
||||
uriLower.startsWith('cast://') ||
|
||||
uriLower.startsWith('bluetooth://');
|
||||
|
||||
isExternalSource = isSimpleExternalId || isExternalProtocol;
|
||||
}
|
||||
|
||||
// Also check media_type - 'unknown' often indicates external source
|
||||
if (!isExternalSource && mediaType == 'unknown') {
|
||||
// If media_type is unknown and URI doesn't look like MA content, it's external
|
||||
final uri = currentMedia['uri'] as String?;
|
||||
if (uri != null && !uri.startsWith('library://') && !uri.contains('://track/')) {
|
||||
isExternalSource = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Player(
|
||||
playerId: json['player_id'] as String,
|
||||
name: json['name'] as String,
|
||||
@@ -199,6 +284,9 @@ class Player {
|
||||
elapsedTimeLastUpdated: elapsedTimeLastUpdated,
|
||||
groupMembers: groupMembers,
|
||||
syncedTo: syncedTo,
|
||||
activeSource: activeSource,
|
||||
isExternalSource: isExternalSource,
|
||||
appId: appId,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -217,6 +305,9 @@ class Player {
|
||||
if (elapsedTimeLastUpdated != null) 'elapsed_time_last_updated': elapsedTimeLastUpdated,
|
||||
if (groupMembers != null) 'group_members': groupMembers,
|
||||
if (syncedTo != null) 'synced_to': syncedTo,
|
||||
if (activeSource != null) 'active_source': activeSource,
|
||||
'is_external_source': isExternalSource,
|
||||
if (appId != null) 'app_id': appId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import '../services/music_assistant_api.dart';
|
||||
import '../services/debug_logger.dart';
|
||||
import '../services/error_handler.dart';
|
||||
import '../services/cache_service.dart';
|
||||
import '../services/settings_service.dart';
|
||||
import '../constants/timings.dart';
|
||||
|
||||
/// Provider for managing library data (artists, albums, tracks, playlists)
|
||||
@@ -138,8 +139,12 @@ class LibraryProvider with ChangeNotifier {
|
||||
_error = null;
|
||||
notifyListeners();
|
||||
|
||||
// Read artist filter setting - when ON, only fetch artists that have albums
|
||||
final showOnlyArtistsWithAlbums = await SettingsService.getShowOnlyArtistsWithAlbums();
|
||||
_logger.log('🎨 loadLibrary using albumArtistsOnly: $showOnlyArtistsWithAlbums');
|
||||
|
||||
final results = await Future.wait([
|
||||
_api!.getArtists(limit: LibraryConstants.maxLibraryItems),
|
||||
_api!.getArtists(limit: LibraryConstants.maxLibraryItems, albumArtistsOnly: showOnlyArtistsWithAlbums),
|
||||
_api!.getAlbums(limit: LibraryConstants.maxLibraryItems),
|
||||
_api!.getTracks(limit: LibraryConstants.maxLibraryItems),
|
||||
]);
|
||||
@@ -166,10 +171,14 @@ class LibraryProvider with ChangeNotifier {
|
||||
_error = null;
|
||||
notifyListeners();
|
||||
|
||||
// Read artist filter setting - when ON, only fetch artists that have albums
|
||||
final showOnlyArtistsWithAlbums = await SettingsService.getShowOnlyArtistsWithAlbums();
|
||||
|
||||
_artists = await _api!.getArtists(
|
||||
limit: limit ?? LibraryConstants.maxLibraryItems,
|
||||
offset: offset,
|
||||
search: search,
|
||||
albumArtistsOnly: showOnlyArtistsWithAlbums,
|
||||
);
|
||||
|
||||
_isLoading = false;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -559,28 +559,28 @@ class PlayerProvider with ChangeNotifier {
|
||||
if (playerToSelect == null) {
|
||||
final lastSelectedPlayerId = await SettingsService.getLastSelectedPlayerId();
|
||||
|
||||
// Priority 1: Last selected player
|
||||
if (lastSelectedPlayerId != null) {
|
||||
try {
|
||||
playerToSelect = _availablePlayers.firstWhere(
|
||||
(p) => p.playerId == lastSelectedPlayerId && p.available,
|
||||
);
|
||||
} catch (e) {}
|
||||
playerToSelect = _availablePlayers.cast<Player?>().firstWhere(
|
||||
(p) => p!.playerId == lastSelectedPlayerId && p.available,
|
||||
orElse: () => null,
|
||||
);
|
||||
}
|
||||
|
||||
// Priority 2: Built-in (local) player
|
||||
if (playerToSelect == null && builtinPlayerId != null) {
|
||||
try {
|
||||
playerToSelect = _availablePlayers.firstWhere(
|
||||
(p) => p.playerId == builtinPlayerId && p.available,
|
||||
);
|
||||
} catch (e) {}
|
||||
playerToSelect = _availablePlayers.cast<Player?>().firstWhere(
|
||||
(p) => p!.playerId == builtinPlayerId && p.available,
|
||||
orElse: () => null,
|
||||
);
|
||||
}
|
||||
|
||||
// Priority 3: Currently playing player (exclude external sources - not playing MA content)
|
||||
if (playerToSelect == null) {
|
||||
try {
|
||||
playerToSelect = _availablePlayers.firstWhere(
|
||||
(p) => p.state == 'playing' && p.available,
|
||||
);
|
||||
} catch (e) {}
|
||||
playerToSelect = _availablePlayers.cast<Player?>().firstWhere(
|
||||
(p) => p!.state == 'playing' && p.available && !p.isExternalSource,
|
||||
orElse: () => null,
|
||||
);
|
||||
}
|
||||
|
||||
if (playerToSelect == null) {
|
||||
@@ -906,10 +906,10 @@ class PlayerProvider with ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> toggleShuffle(String queueId) async {
|
||||
Future<void> toggleShuffle(String queueId, bool shuffleEnabled) async {
|
||||
if (_api == null) return;
|
||||
try {
|
||||
await _api!.toggleShuffle(queueId);
|
||||
await _api!.toggleShuffle(queueId, shuffleEnabled);
|
||||
} catch (e) {
|
||||
ErrorHandler.logError('Toggle shuffle', e);
|
||||
rethrow;
|
||||
|
||||
@@ -10,6 +10,7 @@ import '../services/metadata_service.dart';
|
||||
import '../services/debug_logger.dart';
|
||||
import '../services/recently_played_service.dart';
|
||||
import '../widgets/global_player_overlay.dart';
|
||||
import '../widgets/player_picker_sheet.dart';
|
||||
import '../l10n/app_localizations.dart';
|
||||
import 'artist_details_screen.dart';
|
||||
|
||||
@@ -35,6 +36,7 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
||||
List<Track> _tracks = [];
|
||||
bool _isLoading = true;
|
||||
bool _isFavorite = false;
|
||||
bool _isInLibrary = false;
|
||||
ColorScheme? _lightColorScheme;
|
||||
ColorScheme? _darkColorScheme;
|
||||
int? _expandedTrackIndex;
|
||||
@@ -51,6 +53,7 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
||||
void initState() {
|
||||
super.initState();
|
||||
_isFavorite = widget.album.favorite ?? false;
|
||||
_isInLibrary = widget.album.inLibrary;
|
||||
_loadTracks();
|
||||
_loadAlbumDescription();
|
||||
|
||||
@@ -139,7 +142,8 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
||||
orElse: () => widget.album.providerMappings!.first,
|
||||
),
|
||||
);
|
||||
actualProvider = mapping.providerInstance;
|
||||
// Use providerDomain (e.g., "spotify") not providerInstance (e.g., "spotify--xyz")
|
||||
actualProvider = mapping.providerDomain;
|
||||
actualItemId = mapping.itemId;
|
||||
}
|
||||
|
||||
@@ -170,7 +174,6 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
||||
throw Exception('Could not determine library ID for this album');
|
||||
}
|
||||
|
||||
_logger.log('Removing from favorites: libraryItemId=$libraryItemId');
|
||||
success = await maProvider.removeFromFavorites(
|
||||
mediaType: 'album',
|
||||
libraryItemId: libraryItemId,
|
||||
@@ -213,6 +216,104 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggle library status
|
||||
Future<void> _toggleLibrary() async {
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
|
||||
try {
|
||||
final newState = !_isInLibrary;
|
||||
bool success;
|
||||
|
||||
if (newState) {
|
||||
// Add to library - MUST use non-library provider
|
||||
String? actualProvider;
|
||||
String? actualItemId;
|
||||
|
||||
if (widget.album.providerMappings != null && widget.album.providerMappings!.isNotEmpty) {
|
||||
// For adding to library, we MUST use a non-library provider
|
||||
final nonLibraryMapping = widget.album.providerMappings!.where(
|
||||
(m) => m.providerInstance != 'library' && m.providerDomain != 'library',
|
||||
).firstOrNull;
|
||||
|
||||
if (nonLibraryMapping != null) {
|
||||
actualProvider = nonLibraryMapping.providerDomain;
|
||||
actualItemId = nonLibraryMapping.itemId;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to item's own provider if no non-library mapping found
|
||||
if (actualProvider == null || actualItemId == null) {
|
||||
if (widget.album.provider != 'library') {
|
||||
actualProvider = widget.album.provider;
|
||||
actualItemId = widget.album.itemId;
|
||||
} else {
|
||||
// Item is library-only, can't add
|
||||
_logger.log('Cannot add to library: album is library-only');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
_logger.log('Adding album to library: provider=$actualProvider, itemId=$actualItemId');
|
||||
success = await maProvider.addToLibrary(
|
||||
mediaType: 'album',
|
||||
provider: actualProvider,
|
||||
itemId: actualItemId,
|
||||
);
|
||||
} else {
|
||||
// Remove from library
|
||||
int? libraryItemId;
|
||||
if (widget.album.provider == 'library') {
|
||||
libraryItemId = int.tryParse(widget.album.itemId);
|
||||
} else if (widget.album.providerMappings != null) {
|
||||
final libraryMapping = widget.album.providerMappings!.firstWhere(
|
||||
(m) => m.providerInstance == 'library',
|
||||
orElse: () => widget.album.providerMappings!.first,
|
||||
);
|
||||
if (libraryMapping.providerInstance == 'library') {
|
||||
libraryItemId = int.tryParse(libraryMapping.itemId);
|
||||
}
|
||||
}
|
||||
|
||||
if (libraryItemId == null) {
|
||||
_logger.log('Cannot remove from library: no library ID found');
|
||||
return;
|
||||
}
|
||||
|
||||
success = await maProvider.removeFromLibrary(
|
||||
mediaType: 'album',
|
||||
libraryItemId: libraryItemId,
|
||||
);
|
||||
}
|
||||
|
||||
if (success) {
|
||||
setState(() {
|
||||
_isInLibrary = newState;
|
||||
});
|
||||
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
_isInLibrary ? S.of(context)!.addedToLibrary : S.of(context)!.removedFromLibrary,
|
||||
),
|
||||
duration: const Duration(seconds: 1),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.log('Error toggling album library: $e');
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Failed to update library: $e'),
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _toggleTrackFavorite(int trackIndex) async {
|
||||
if (trackIndex < 0 || trackIndex >= _tracks.length) return;
|
||||
|
||||
@@ -259,7 +360,8 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
||||
orElse: () => track.providerMappings!.first,
|
||||
),
|
||||
);
|
||||
actualProvider = mapping.providerInstance;
|
||||
// Use providerDomain (e.g., "spotify") not providerInstance (e.g., "spotify--xyz")
|
||||
actualProvider = mapping.providerDomain;
|
||||
actualItemId = mapping.itemId;
|
||||
}
|
||||
|
||||
@@ -558,7 +660,7 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
SizedBox(height: MediaQuery.of(context).padding.bottom + 16),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -703,10 +805,16 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
||||
},
|
||||
child: Scaffold(
|
||||
backgroundColor: colorScheme.background,
|
||||
body: CustomScrollView(
|
||||
body: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
// Responsive cover size: 70% of screen width, clamped between 200-320
|
||||
final coverSize = (constraints.maxWidth * 0.7).clamp(200.0, 320.0);
|
||||
final expandedHeight = coverSize + 70;
|
||||
|
||||
return CustomScrollView(
|
||||
slivers: [
|
||||
SliverAppBar(
|
||||
expandedHeight: 350, // Increased height for bigger art
|
||||
expandedHeight: expandedHeight,
|
||||
pinned: true,
|
||||
backgroundColor: colorScheme.background,
|
||||
leading: IconButton(
|
||||
@@ -724,35 +832,50 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
||||
const SizedBox(height: 60),
|
||||
GestureDetector(
|
||||
onTap: () => _showFullscreenArt(imageUrl),
|
||||
child: Hero(
|
||||
tag: HeroTags.albumCover + (widget.album.uri ?? widget.album.itemId) + _heroTagSuffix,
|
||||
child: Container(
|
||||
width: 280, // Increased size
|
||||
height: 280,
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceVariant,
|
||||
borderRadius: BorderRadius.circular(16), // Slightly more rounded
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.3),
|
||||
blurRadius: 20,
|
||||
offset: const Offset(0, 10),
|
||||
),
|
||||
],
|
||||
image: imageUrl != null
|
||||
? DecorationImage(
|
||||
image: CachedNetworkImageProvider(imageUrl),
|
||||
fit: BoxFit.cover,
|
||||
)
|
||||
: null,
|
||||
// Shadow container (outside Hero for correct clipping)
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.3),
|
||||
blurRadius: 20,
|
||||
offset: const Offset(0, 10),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Hero(
|
||||
tag: HeroTags.albumCover + (widget.album.uri ?? widget.album.itemId) + _heroTagSuffix,
|
||||
// FIXED: Match source structure - ClipRRect(12) → Container → CachedNetworkImage
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: Container(
|
||||
width: coverSize,
|
||||
height: coverSize,
|
||||
color: colorScheme.surfaceVariant,
|
||||
child: imageUrl != null
|
||||
? CachedNetworkImage(
|
||||
imageUrl: imageUrl,
|
||||
fit: BoxFit.cover,
|
||||
// Match source memCacheWidth for smooth Hero
|
||||
memCacheWidth: 256,
|
||||
memCacheHeight: 256,
|
||||
fadeInDuration: Duration.zero,
|
||||
fadeOutDuration: Duration.zero,
|
||||
placeholder: (_, __) => const SizedBox(),
|
||||
errorWidget: (_, __, ___) => Icon(
|
||||
Icons.album_rounded,
|
||||
size: coverSize * 0.43,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
)
|
||||
: Icon(
|
||||
Icons.album_rounded,
|
||||
size: coverSize * 0.43,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
child: imageUrl == null
|
||||
? Icon(
|
||||
Icons.album_rounded,
|
||||
size: 120,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -762,7 +885,7 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
||||
),
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24.0),
|
||||
padding: const EdgeInsets.fromLTRB(24.0, 24.0, 24.0, 12.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
@@ -903,17 +1026,32 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(width: 12),
|
||||
|
||||
// Library Button
|
||||
SizedBox(
|
||||
height: 50,
|
||||
width: 50,
|
||||
child: FilledButton.tonal(
|
||||
onPressed: _toggleLibrary,
|
||||
style: FilledButton.styleFrom(
|
||||
padding: EdgeInsets.zero,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: Icon(
|
||||
_isInLibrary ? Icons.library_add_check : Icons.library_add,
|
||||
color: _isInLibrary
|
||||
? colorScheme.primary
|
||||
: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Text(
|
||||
S.of(context)!.tracks,
|
||||
style: textTheme.titleLarge?.copyWith(
|
||||
color: colorScheme.onBackground,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -1080,118 +1218,71 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
||||
),
|
||||
const SliverToBoxAdapter(child: SizedBox(height: 164)), // Space for bottom nav + mini player
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _showPlayAlbumFromHereMenu(BuildContext context, int startIndex) {
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
final players = maProvider.availablePlayers;
|
||||
|
||||
_showPlayOnSheet(
|
||||
context,
|
||||
players,
|
||||
onPlayerSelected: (player) {
|
||||
GlobalPlayerOverlay.hidePlayer();
|
||||
|
||||
showPlayerPickerSheet(
|
||||
context: context,
|
||||
title: S.of(context)!.playOn,
|
||||
players: maProvider.availablePlayers,
|
||||
selectedPlayer: maProvider.selectedPlayer,
|
||||
onPlayerSelected: (player) async {
|
||||
maProvider.selectPlayer(player);
|
||||
maProvider.playTracks(
|
||||
await maProvider.playTracks(
|
||||
player.playerId,
|
||||
_tracks,
|
||||
startIndex: startIndex,
|
||||
);
|
||||
},
|
||||
);
|
||||
).whenComplete(() {
|
||||
GlobalPlayerOverlay.showPlayer();
|
||||
});
|
||||
}
|
||||
|
||||
void _showPlayRadioMenu(BuildContext context, int trackIndex) {
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
final players = maProvider.availablePlayers;
|
||||
final track = _tracks[trackIndex];
|
||||
|
||||
_showPlayOnSheet(
|
||||
context,
|
||||
players,
|
||||
onPlayerSelected: (player) {
|
||||
GlobalPlayerOverlay.hidePlayer();
|
||||
|
||||
showPlayerPickerSheet(
|
||||
context: context,
|
||||
title: S.of(context)!.playOn,
|
||||
players: maProvider.availablePlayers,
|
||||
selectedPlayer: maProvider.selectedPlayer,
|
||||
onPlayerSelected: (player) async {
|
||||
maProvider.selectPlayer(player);
|
||||
maProvider.playRadio(player.playerId, track);
|
||||
await maProvider.playRadio(player.playerId, track);
|
||||
},
|
||||
);
|
||||
).whenComplete(() {
|
||||
GlobalPlayerOverlay.showPlayer();
|
||||
});
|
||||
}
|
||||
|
||||
void _showPlayOnMenu(BuildContext context) {
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
final players = maProvider.availablePlayers;
|
||||
|
||||
_showPlayOnSheet(
|
||||
context,
|
||||
players,
|
||||
onPlayerSelected: (player) {
|
||||
maProvider.selectPlayer(player);
|
||||
maProvider.playTracks(player.playerId, _tracks);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Shared "Play on..." bottom sheet with fixed height and scrollable list
|
||||
void _showPlayOnSheet(
|
||||
BuildContext context,
|
||||
List players, {
|
||||
required void Function(dynamic player) onPlayerSelected,
|
||||
}) {
|
||||
// Slide mini player down out of the way
|
||||
GlobalPlayerOverlay.hidePlayer();
|
||||
|
||||
final screenHeight = MediaQuery.of(context).size.height;
|
||||
final bottomPadding = MediaQuery.of(context).padding.bottom;
|
||||
final sheetHeight = (screenHeight * 0.45) + bottomPadding; // Fixed 45% + safe area
|
||||
|
||||
showModalBottomSheet(
|
||||
showPlayerPickerSheet(
|
||||
context: context,
|
||||
backgroundColor: Colors.transparent,
|
||||
isScrollControlled: true,
|
||||
builder: (context) => Container(
|
||||
height: sheetHeight,
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
S.of(context)!.playOn,
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Expanded(
|
||||
child: players.isEmpty
|
||||
? Center(
|
||||
child: Text(S.of(context)!.noPlayersAvailable),
|
||||
)
|
||||
: ListView.builder(
|
||||
padding: EdgeInsets.only(bottom: bottomPadding + 16),
|
||||
itemCount: players.length,
|
||||
itemBuilder: (context, index) {
|
||||
final player = players[index];
|
||||
return ListTile(
|
||||
leading: Icon(
|
||||
Icons.speaker,
|
||||
color: Theme.of(context).colorScheme.onSurface,
|
||||
),
|
||||
title: Text(player.name),
|
||||
onTap: () {
|
||||
Navigator.pop(context);
|
||||
onPlayerSelected(player);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
title: S.of(context)!.playOn,
|
||||
players: maProvider.availablePlayers,
|
||||
selectedPlayer: maProvider.selectedPlayer,
|
||||
onPlayerSelected: (player) async {
|
||||
maProvider.selectPlayer(player);
|
||||
await maProvider.playTracks(player.playerId, _tracks);
|
||||
},
|
||||
).whenComplete(() {
|
||||
// Slide mini player back up when sheet is dismissed
|
||||
GlobalPlayerOverlay.showPlayer();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -36,11 +36,13 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
||||
List<Album> _providerAlbums = [];
|
||||
bool _isLoading = true;
|
||||
bool _isFavorite = false;
|
||||
bool _isInLibrary = false;
|
||||
ColorScheme? _lightColorScheme;
|
||||
ColorScheme? _darkColorScheme;
|
||||
bool _isDescriptionExpanded = false;
|
||||
String? _artistDescription;
|
||||
String? _artistImageUrl;
|
||||
MusicAssistantProvider? _maProvider;
|
||||
|
||||
// View preferences
|
||||
String _sortOrder = 'alpha'; // 'alpha' or 'year'
|
||||
@@ -52,6 +54,7 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
||||
void initState() {
|
||||
super.initState();
|
||||
_isFavorite = widget.artist.favorite ?? false;
|
||||
_isInLibrary = _checkIfInLibrary(widget.artist);
|
||||
// Use initial image URL immediately for smooth hero animation
|
||||
_artistImageUrl = widget.initialImageUrl;
|
||||
_loadViewPreferences();
|
||||
@@ -66,11 +69,60 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
||||
if (mounted) {
|
||||
_loadArtistImage();
|
||||
// Note: _extractColors is called by _loadArtistImage after image loads
|
||||
|
||||
// CRITICAL FIX: Delay adding provider listener until AFTER Hero animation
|
||||
// Adding it immediately causes rebuilds during animation (jank)
|
||||
_maProvider = context.read<MusicAssistantProvider>();
|
||||
_maProvider?.addListener(_onProviderChanged);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
void _onProviderChanged() {
|
||||
if (!mounted) return;
|
||||
// Re-check library status when provider data changes
|
||||
final newIsInLibrary = _checkIfInLibraryFromProvider();
|
||||
if (newIsInLibrary != _isInLibrary) {
|
||||
setState(() {
|
||||
_isInLibrary = newIsInLibrary;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if artist is in library using provider's artists list
|
||||
bool _checkIfInLibraryFromProvider() {
|
||||
if (_maProvider == null) return _checkIfInLibrary(widget.artist);
|
||||
|
||||
final artistName = widget.artist.name.toLowerCase();
|
||||
final artistUri = widget.artist.uri;
|
||||
|
||||
// Check if this artist exists in the provider's library
|
||||
return _maProvider!.artists.any((a) {
|
||||
// Match by URI if available
|
||||
if (artistUri != null && a.uri == artistUri) return true;
|
||||
// Match by name as fallback
|
||||
if (a.name.toLowerCase() == artistName) return true;
|
||||
// Check provider mappings for matching URIs
|
||||
if (widget.artist.providerMappings != null) {
|
||||
for (final mapping in widget.artist.providerMappings!) {
|
||||
if (a.providerMappings?.any((m) =>
|
||||
m.providerInstance == mapping.providerInstance &&
|
||||
m.itemId == mapping.itemId) == true) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_maProvider?.removeListener(_onProviderChanged);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _loadViewPreferences() async {
|
||||
final sortOrder = await SettingsService.getArtistAlbumsSortOrder();
|
||||
final viewMode = await SettingsService.getArtistAlbumsViewMode();
|
||||
@@ -172,7 +224,8 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
||||
orElse: () => widget.artist.providerMappings!.first,
|
||||
),
|
||||
);
|
||||
actualProvider = mapping.providerInstance;
|
||||
// Use providerDomain (e.g., "spotify") not providerInstance (e.g., "spotify--xyz")
|
||||
actualProvider = mapping.providerDomain;
|
||||
actualItemId = mapping.itemId;
|
||||
}
|
||||
|
||||
@@ -202,7 +255,6 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
||||
throw Exception('Could not determine library ID for this artist');
|
||||
}
|
||||
|
||||
_logger.log('Removing artist from favorites: libraryItemId=$libraryItemId');
|
||||
success = await maProvider.removeFromFavorites(
|
||||
mediaType: 'artist',
|
||||
libraryItemId: libraryItemId,
|
||||
@@ -243,57 +295,129 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _startArtistRadio() async {
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
final selectedPlayer = maProvider.selectedPlayer;
|
||||
/// Check if artist is in library
|
||||
bool _checkIfInLibrary(Artist artist) {
|
||||
if (artist.provider == 'library') return true;
|
||||
return artist.providerMappings?.any((m) => m.providerInstance == 'library') ?? false;
|
||||
}
|
||||
|
||||
if (selectedPlayer == null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(S.of(context)!.noPlayerSelected)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
/// Toggle library status
|
||||
Future<void> _toggleLibrary() async {
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
|
||||
try {
|
||||
await maProvider.playArtistRadio(selectedPlayer.playerId, widget.artist);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(S.of(context)!.startingRadio(widget.artist.name)),
|
||||
duration: const Duration(seconds: 1),
|
||||
),
|
||||
final newState = !_isInLibrary;
|
||||
bool success;
|
||||
|
||||
if (newState) {
|
||||
// Add to library - MUST use non-library provider
|
||||
String? actualProvider;
|
||||
String? actualItemId;
|
||||
|
||||
if (widget.artist.providerMappings != null && widget.artist.providerMappings!.isNotEmpty) {
|
||||
// For adding to library, we MUST use a non-library provider
|
||||
final nonLibraryMapping = widget.artist.providerMappings!.where(
|
||||
(m) => m.providerInstance != 'library' && m.providerDomain != 'library',
|
||||
).firstOrNull;
|
||||
|
||||
if (nonLibraryMapping != null) {
|
||||
actualProvider = nonLibraryMapping.providerDomain;
|
||||
actualItemId = nonLibraryMapping.itemId;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to item's own provider if no non-library mapping found
|
||||
if (actualProvider == null || actualItemId == null) {
|
||||
if (widget.artist.provider != 'library') {
|
||||
actualProvider = widget.artist.provider;
|
||||
actualItemId = widget.artist.itemId;
|
||||
} else {
|
||||
// Item is library-only, can't add
|
||||
_logger.log('Cannot add to library: artist is library-only');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
_logger.log('Adding artist to library: provider=$actualProvider, itemId=$actualItemId');
|
||||
success = await maProvider.addToLibrary(
|
||||
mediaType: 'artist',
|
||||
provider: actualProvider,
|
||||
itemId: actualItemId,
|
||||
);
|
||||
} else {
|
||||
// Remove from library
|
||||
int? libraryItemId;
|
||||
if (widget.artist.provider == 'library') {
|
||||
libraryItemId = int.tryParse(widget.artist.itemId);
|
||||
} else if (widget.artist.providerMappings != null) {
|
||||
final libraryMapping = widget.artist.providerMappings!.firstWhere(
|
||||
(m) => m.providerInstance == 'library',
|
||||
orElse: () => widget.artist.providerMappings!.first,
|
||||
);
|
||||
if (libraryMapping.providerInstance == 'library') {
|
||||
libraryItemId = int.tryParse(libraryMapping.itemId);
|
||||
}
|
||||
}
|
||||
|
||||
if (libraryItemId == null) {
|
||||
_logger.log('Cannot remove from library: no library ID found');
|
||||
return;
|
||||
}
|
||||
|
||||
success = await maProvider.removeFromLibrary(
|
||||
mediaType: 'artist',
|
||||
libraryItemId: libraryItemId,
|
||||
);
|
||||
}
|
||||
|
||||
if (success) {
|
||||
setState(() {
|
||||
_isInLibrary = newState;
|
||||
});
|
||||
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
_isInLibrary ? S.of(context)!.addedToLibrary : S.of(context)!.removedFromLibrary,
|
||||
),
|
||||
duration: const Duration(seconds: 1),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.log('Error starting artist radio: $e');
|
||||
_logger.log('Error toggling artist library: $e');
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(S.of(context)!.failedToStartRadio(e.toString())),
|
||||
backgroundColor: Colors.red,
|
||||
content: Text('Failed to update library: $e'),
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _showPlayOnMenu(BuildContext context) {
|
||||
void _showRadioMenu(BuildContext context) {
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
final players = maProvider.availablePlayers;
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
// Slide mini player down out of the way
|
||||
GlobalPlayerOverlay.hidePlayer();
|
||||
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
backgroundColor: colorScheme.surface,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
|
||||
),
|
||||
builder: (context) => Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
backgroundColor: Colors.transparent,
|
||||
builder: (context) => Container(
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
S.of(context)!.startRadioOn(widget.artist.name),
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
@@ -314,7 +438,7 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
||||
return ListTile(
|
||||
leading: Icon(
|
||||
Icons.speaker,
|
||||
color: colorScheme.onSurface,
|
||||
color: Theme.of(context).colorScheme.onSurface,
|
||||
),
|
||||
title: Text(player.name),
|
||||
onTap: () async {
|
||||
@@ -345,46 +469,103 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
SizedBox(height: MediaQuery.of(context).padding.bottom + 16),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
).whenComplete(() {
|
||||
// Slide mini player back up when sheet is dismissed
|
||||
GlobalPlayerOverlay.showPlayer();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _addArtistRadioToQueue() async {
|
||||
void _showAddToQueueMenu(BuildContext context) {
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
final selectedPlayer = maProvider.selectedPlayer;
|
||||
final players = maProvider.availablePlayers;
|
||||
|
||||
if (selectedPlayer == null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(S.of(context)!.noPlayerSelected)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Slide mini player down out of the way
|
||||
GlobalPlayerOverlay.hidePlayer();
|
||||
|
||||
try {
|
||||
// For adding to queue with radio mode, we use radio_mode but with 'add' option
|
||||
await maProvider.api?.playArtistRadioToQueue(selectedPlayer.playerId, widget.artist);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(S.of(context)!.addedRadioToQueue(widget.artist.name)),
|
||||
duration: const Duration(seconds: 1),
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.log('Error adding artist radio to queue: $e');
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(S.of(context)!.failedToAddToQueue(e.toString())),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
backgroundColor: Colors.transparent,
|
||||
builder: (context) => Container(
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
S.of(context)!.addToQueueOn,
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
if (players.isEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(32.0),
|
||||
child: Text(S.of(context)!.noPlayersAvailable),
|
||||
)
|
||||
else
|
||||
Flexible(
|
||||
child: ListView.builder(
|
||||
shrinkWrap: true,
|
||||
itemCount: players.length,
|
||||
itemBuilder: (context, index) {
|
||||
final player = players[index];
|
||||
return ListTile(
|
||||
leading: Icon(
|
||||
Icons.speaker,
|
||||
color: Theme.of(context).colorScheme.onSurface,
|
||||
),
|
||||
title: Text(player.name),
|
||||
onTap: () async {
|
||||
Navigator.pop(context);
|
||||
final api = maProvider.api;
|
||||
if (api == null) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(S.of(context)!.notConnected)),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await api.playArtistRadioToQueue(player.playerId, widget.artist);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(S.of(context)!.addedRadioToQueue(widget.artist.name)),
|
||||
duration: const Duration(seconds: 1),
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.log('Error adding artist radio to queue: $e');
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(S.of(context)!.failedToAddToQueue(e.toString())),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
SizedBox(height: MediaQuery.of(context).padding.bottom + 16),
|
||||
],
|
||||
),
|
||||
),
|
||||
).whenComplete(() {
|
||||
// Slide mini player back up when sheet is dismissed
|
||||
GlobalPlayerOverlay.showPlayer();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _loadArtistImage() async {
|
||||
@@ -526,10 +707,16 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
||||
},
|
||||
child: Scaffold(
|
||||
backgroundColor: colorScheme.background,
|
||||
body: CustomScrollView(
|
||||
body: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
// Responsive cover size: 70% of screen width, clamped between 160-280 (smaller for circular artist image)
|
||||
final coverSize = (constraints.maxWidth * 0.7).clamp(160.0, 280.0);
|
||||
final expandedHeight = coverSize + 100;
|
||||
|
||||
return CustomScrollView(
|
||||
slivers: [
|
||||
SliverAppBar(
|
||||
expandedHeight: 300,
|
||||
expandedHeight: expandedHeight,
|
||||
pinned: true,
|
||||
backgroundColor: colorScheme.background,
|
||||
leading: IconButton(
|
||||
@@ -549,24 +736,28 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
||||
tag: HeroTags.artistImage + (widget.artist.uri ?? widget.artist.itemId) + _heroTagSuffix,
|
||||
child: ClipOval(
|
||||
child: Container(
|
||||
width: 200,
|
||||
height: 200,
|
||||
width: coverSize,
|
||||
height: coverSize,
|
||||
color: colorScheme.surfaceVariant,
|
||||
child: imageUrl != null
|
||||
? CachedNetworkImage(
|
||||
imageUrl: imageUrl,
|
||||
fit: BoxFit.cover,
|
||||
// Match source memCacheWidth for smooth Hero animation
|
||||
memCacheWidth: 256,
|
||||
memCacheHeight: 256,
|
||||
fadeInDuration: Duration.zero,
|
||||
fadeOutDuration: Duration.zero,
|
||||
placeholder: (_, __) => const SizedBox(),
|
||||
errorWidget: (_, __, ___) => Icon(
|
||||
Icons.person_rounded,
|
||||
size: 100,
|
||||
size: coverSize * 0.5,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
)
|
||||
: Icon(
|
||||
Icons.person_rounded,
|
||||
size: 100,
|
||||
size: coverSize * 0.5,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
@@ -627,7 +818,7 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
||||
child: SizedBox(
|
||||
height: 50,
|
||||
child: ElevatedButton.icon(
|
||||
onPressed: _startArtistRadio,
|
||||
onPressed: () => _showRadioMenu(context),
|
||||
icon: const Icon(Icons.radio),
|
||||
label: Text(S.of(context)!.radio),
|
||||
style: ElevatedButton.styleFrom(
|
||||
@@ -640,23 +831,6 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
|
||||
// "Play on..." Button (Square)
|
||||
SizedBox(
|
||||
height: 50,
|
||||
width: 50,
|
||||
child: FilledButton.tonal(
|
||||
onPressed: () => _showPlayOnMenu(context),
|
||||
style: FilledButton.styleFrom(
|
||||
padding: EdgeInsets.zero,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: const Icon(Icons.speaker_group_outlined),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(width: 12),
|
||||
|
||||
@@ -665,7 +839,7 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
||||
height: 50,
|
||||
width: 50,
|
||||
child: FilledButton.tonal(
|
||||
onPressed: _addArtistRadioToQueue,
|
||||
onPressed: () => _showAddToQueueMenu(context),
|
||||
style: FilledButton.styleFrom(
|
||||
padding: EdgeInsets.zero,
|
||||
shape: RoundedRectangleBorder(
|
||||
@@ -698,6 +872,29 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(width: 12),
|
||||
|
||||
// Library Button
|
||||
SizedBox(
|
||||
height: 50,
|
||||
width: 50,
|
||||
child: FilledButton.tonal(
|
||||
onPressed: _toggleLibrary,
|
||||
style: FilledButton.styleFrom(
|
||||
padding: EdgeInsets.zero,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: Icon(
|
||||
_isInLibrary ? Icons.library_add_check : Icons.library_add,
|
||||
color: _isInLibrary
|
||||
? colorScheme.primary
|
||||
: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
@@ -839,6 +1036,8 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
||||
],
|
||||
],
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -5,6 +5,7 @@ import 'package:material_design_icons_flutter/material_design_icons_flutter.dart
|
||||
import '../models/media_item.dart';
|
||||
import '../providers/music_assistant_provider.dart';
|
||||
import '../widgets/global_player_overlay.dart';
|
||||
import '../widgets/player_picker_sheet.dart';
|
||||
import '../theme/palette_helper.dart';
|
||||
import '../theme/theme_provider.dart';
|
||||
import '../services/debug_logger.dart';
|
||||
@@ -139,7 +140,8 @@ class _AudiobookDetailScreenState extends State<AudiobookDetailScreen> {
|
||||
orElse: () => widget.audiobook.providerMappings!.first,
|
||||
),
|
||||
);
|
||||
actualProvider = mapping.providerInstance;
|
||||
// Use providerDomain (e.g., "spotify") not providerInstance (e.g., "spotify--xyz")
|
||||
actualProvider = mapping.providerDomain;
|
||||
actualItemId = mapping.itemId;
|
||||
}
|
||||
|
||||
@@ -168,7 +170,6 @@ class _AudiobookDetailScreenState extends State<AudiobookDetailScreen> {
|
||||
throw Exception('Could not determine library ID for this audiobook');
|
||||
}
|
||||
|
||||
_logger.log('Removing audiobook from favorites: libraryItemId=$libraryItemId');
|
||||
success = await maProvider.removeFromFavorites(
|
||||
mediaType: 'audiobook',
|
||||
libraryItemId: libraryItemId,
|
||||
@@ -209,62 +210,22 @@ class _AudiobookDetailScreenState extends State<AudiobookDetailScreen> {
|
||||
|
||||
void _showPlayOnMenu(BuildContext context) {
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
final players = maProvider.availablePlayers;
|
||||
|
||||
GlobalPlayerOverlay.hidePlayer();
|
||||
|
||||
final screenHeight = MediaQuery.of(context).size.height;
|
||||
final bottomPadding = MediaQuery.of(context).padding.bottom;
|
||||
final sheetHeight = (screenHeight * 0.45) + bottomPadding;
|
||||
|
||||
showModalBottomSheet(
|
||||
showPlayerPickerSheet(
|
||||
context: context,
|
||||
backgroundColor: Colors.transparent,
|
||||
isScrollControlled: true,
|
||||
builder: (context) => Container(
|
||||
height: sheetHeight,
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
S.of(context)!.playOn,
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Expanded(
|
||||
child: players.isEmpty
|
||||
? Center(child: Text(S.of(context)!.noPlayersAvailable))
|
||||
: ListView.builder(
|
||||
padding: EdgeInsets.only(bottom: bottomPadding + 16),
|
||||
itemCount: players.length,
|
||||
itemBuilder: (context, index) {
|
||||
final player = players[index];
|
||||
return ListTile(
|
||||
leading: Icon(
|
||||
Icons.speaker,
|
||||
color: Theme.of(context).colorScheme.onSurface,
|
||||
),
|
||||
title: Text(player.name),
|
||||
onTap: () async {
|
||||
Navigator.pop(context);
|
||||
maProvider.selectPlayer(player);
|
||||
maProvider.setCurrentAudiobook(_audiobook);
|
||||
await maProvider.api?.playAudiobook(
|
||||
player.playerId,
|
||||
widget.audiobook,
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
title: S.of(context)!.playOn,
|
||||
players: maProvider.availablePlayers,
|
||||
selectedPlayer: maProvider.selectedPlayer,
|
||||
onPlayerSelected: (player) async {
|
||||
maProvider.selectPlayer(player);
|
||||
maProvider.setCurrentAudiobook(_audiobook);
|
||||
await maProvider.api?.playAudiobook(
|
||||
player.playerId,
|
||||
widget.audiobook,
|
||||
);
|
||||
},
|
||||
).whenComplete(() {
|
||||
GlobalPlayerOverlay.showPlayer();
|
||||
});
|
||||
@@ -466,10 +427,16 @@ class _AudiobookDetailScreenState extends State<AudiobookDetailScreen> {
|
||||
},
|
||||
child: Scaffold(
|
||||
backgroundColor: colorScheme.surface,
|
||||
body: CustomScrollView(
|
||||
body: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
// Responsive cover size: 70% of screen width, clamped between 200-320
|
||||
final coverSize = (constraints.maxWidth * 0.7).clamp(200.0, 320.0);
|
||||
final expandedHeight = coverSize + 70;
|
||||
|
||||
return CustomScrollView(
|
||||
slivers: [
|
||||
SliverAppBar(
|
||||
expandedHeight: 350,
|
||||
expandedHeight: expandedHeight,
|
||||
pinned: true,
|
||||
backgroundColor: colorScheme.surface,
|
||||
leading: IconButton(
|
||||
@@ -538,26 +505,29 @@ class _AudiobookDetailScreenState extends State<AudiobookDetailScreen> {
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Container(
|
||||
width: 280,
|
||||
height: 280,
|
||||
width: coverSize,
|
||||
height: coverSize,
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
child: imageUrl != null
|
||||
? CachedNetworkImage(
|
||||
imageUrl: imageUrl,
|
||||
fit: BoxFit.cover,
|
||||
// Match source memCacheWidth for smooth Hero animation
|
||||
memCacheWidth: 256,
|
||||
memCacheHeight: 256,
|
||||
fadeInDuration: Duration.zero,
|
||||
fadeOutDuration: Duration.zero,
|
||||
placeholder: (_, __) => Center(
|
||||
child: Icon(
|
||||
MdiIcons.bookOutline,
|
||||
size: 120,
|
||||
size: coverSize * 0.43,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
errorWidget: (_, __, ___) => Center(
|
||||
child: Icon(
|
||||
MdiIcons.bookOutline,
|
||||
size: 120,
|
||||
size: coverSize * 0.43,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
@@ -565,7 +535,7 @@ class _AudiobookDetailScreenState extends State<AudiobookDetailScreen> {
|
||||
: Center(
|
||||
child: Icon(
|
||||
MdiIcons.bookOutline,
|
||||
size: 120,
|
||||
size: coverSize * 0.43,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
@@ -809,6 +779,8 @@ class _AudiobookDetailScreenState extends State<AudiobookDetailScreen> {
|
||||
|
||||
const SliverToBoxAdapter(child: SizedBox(height: 140)),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -275,11 +275,17 @@ class _AudiobookSeriesScreenState extends State<AudiobookSeriesScreen> {
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: colorScheme.surface,
|
||||
body: CustomScrollView(
|
||||
body: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
// Responsive cover size: 70% of screen width, clamped between 200-320
|
||||
final coverSize = (constraints.maxWidth * 0.7).clamp(200.0, 320.0);
|
||||
final expandedHeight = coverSize + 70;
|
||||
|
||||
return CustomScrollView(
|
||||
slivers: [
|
||||
// App bar with series cover collage (matches audiobook detail screen)
|
||||
SliverAppBar(
|
||||
expandedHeight: 350,
|
||||
expandedHeight: expandedHeight,
|
||||
pinned: true,
|
||||
backgroundColor: colorScheme.surface,
|
||||
leading: IconButton(
|
||||
@@ -292,12 +298,12 @@ class _AudiobookSeriesScreenState extends State<AudiobookSeriesScreen> {
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const SizedBox(height: 60),
|
||||
// Series cover collage - same size as audiobook detail cover
|
||||
// Series cover collage - responsive size
|
||||
Hero(
|
||||
tag: widget.heroTag ?? 'series_cover_${widget.series.id}',
|
||||
child: Container(
|
||||
width: 280,
|
||||
height: 280,
|
||||
width: coverSize,
|
||||
height: coverSize,
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
@@ -445,10 +451,12 @@ class _AudiobookSeriesScreenState extends State<AudiobookSeriesScreen> {
|
||||
_buildAudiobookSliver(maProvider),
|
||||
|
||||
// Bottom padding for mini player
|
||||
const SliverToBoxAdapter(
|
||||
SliverToBoxAdapter(
|
||||
child: SizedBox(height: BottomSpacing.withMiniPlayer),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ class LibraryAlbumsScreen extends StatelessWidget {
|
||||
|
||||
return RefreshIndicator(
|
||||
color: colorScheme.primary,
|
||||
backgroundColor: colorScheme.surface,
|
||||
backgroundColor: colorScheme.background,
|
||||
onRefresh: () async {
|
||||
await context.read<MusicAssistantProvider>().loadLibrary();
|
||||
},
|
||||
|
||||
@@ -66,7 +66,7 @@ class LibraryArtistsScreen extends StatelessWidget {
|
||||
|
||||
return RefreshIndicator(
|
||||
color: colorScheme.primary,
|
||||
backgroundColor: colorScheme.surface,
|
||||
backgroundColor: colorScheme.background,
|
||||
onRefresh: () async {
|
||||
await context.read<MusicAssistantProvider>().loadLibrary();
|
||||
},
|
||||
|
||||
@@ -30,17 +30,11 @@ class _LibraryPlaylistsScreenState extends State<LibraryPlaylistsScreen> {
|
||||
});
|
||||
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
if (maProvider.api != null) {
|
||||
final playlists = await maProvider.api!.getPlaylists(limit: 100);
|
||||
setState(() {
|
||||
_playlists = playlists;
|
||||
_isLoading = false;
|
||||
});
|
||||
} else {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
final playlists = await maProvider.getPlaylists(limit: 100);
|
||||
setState(() {
|
||||
_playlists = playlists;
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -89,7 +83,7 @@ class _LibraryPlaylistsScreenState extends State<LibraryPlaylistsScreen> {
|
||||
|
||||
return RefreshIndicator(
|
||||
color: colorScheme.primary,
|
||||
backgroundColor: colorScheme.surface,
|
||||
backgroundColor: colorScheme.background,
|
||||
onRefresh: _loadPlaylists,
|
||||
child: ListView.builder(
|
||||
itemCount: _playlists.length,
|
||||
|
||||
@@ -443,6 +443,18 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
}
|
||||
|
||||
if (provider.isConnected) {
|
||||
// For first-time users, wait for player selection so the welcome
|
||||
// overlay can appear immediately without home screen flash.
|
||||
// This matches the logic in AppStartup._checkAndConnect().
|
||||
final hasCompletedOnboarding = await SettingsService.getHasCompletedOnboarding();
|
||||
if (!hasCompletedOnboarding) {
|
||||
// First-time user: wait for connection + player selection
|
||||
for (int i = 0; i < 20; i++) {
|
||||
await Future.delayed(const Duration(milliseconds: 250));
|
||||
if (provider.selectedPlayer != null) break;
|
||||
}
|
||||
}
|
||||
|
||||
// Navigate to home screen
|
||||
if (mounted) {
|
||||
// Ensure keyboard is closed before navigating
|
||||
|
||||
@@ -194,7 +194,7 @@ class _NewHomeScreenState extends State<NewHomeScreen> with AutomaticKeepAliveCl
|
||||
RefreshIndicator(
|
||||
onRefresh: _onRefresh,
|
||||
color: colorScheme.primary,
|
||||
backgroundColor: colorScheme.surface,
|
||||
backgroundColor: colorScheme.background,
|
||||
child: _buildConnectedView(context, maProvider),
|
||||
),
|
||||
// Connecting banner overlay (doesn't affect layout)
|
||||
@@ -246,7 +246,7 @@ class _NewHomeScreenState extends State<NewHomeScreen> with AutomaticKeepAliveCl
|
||||
// Simple calculation: available height divided by 3 rows
|
||||
// Each row includes its title, artwork, and info
|
||||
final availableHeight = constraints.maxHeight - BottomSpacing.withMiniPlayer;
|
||||
final rowHeight = availableHeight / 3;
|
||||
final rowHeight = (availableHeight + 8) / 3;
|
||||
|
||||
// Use Android 12+ stretch overscroll effect
|
||||
return NotificationListener<ScrollNotification>(
|
||||
|
||||
+1346
-516
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,869 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
|
||||
import '../models/media_item.dart';
|
||||
import '../providers/music_assistant_provider.dart';
|
||||
import '../widgets/global_player_overlay.dart';
|
||||
import '../widgets/player_picker_sheet.dart';
|
||||
import '../theme/palette_helper.dart';
|
||||
import '../theme/theme_provider.dart';
|
||||
import '../services/debug_logger.dart';
|
||||
import '../constants/hero_tags.dart';
|
||||
import '../l10n/app_localizations.dart';
|
||||
|
||||
class PodcastDetailScreen extends StatefulWidget {
|
||||
final MediaItem podcast;
|
||||
final String? heroTagSuffix;
|
||||
final String? initialImageUrl;
|
||||
|
||||
const PodcastDetailScreen({
|
||||
super.key,
|
||||
required this.podcast,
|
||||
this.heroTagSuffix,
|
||||
this.initialImageUrl,
|
||||
});
|
||||
|
||||
@override
|
||||
State<PodcastDetailScreen> createState() => _PodcastDetailScreenState();
|
||||
}
|
||||
|
||||
class _PodcastDetailScreenState extends State<PodcastDetailScreen> {
|
||||
final _logger = DebugLogger();
|
||||
ColorScheme? _lightColorScheme;
|
||||
ColorScheme? _darkColorScheme;
|
||||
List<MediaItem> _episodes = [];
|
||||
bool _isLoadingEpisodes = false;
|
||||
bool _isDescriptionExpanded = false;
|
||||
bool _isInLibrary = false;
|
||||
String? _expandedEpisodeId; // Track which episode is expanded for actions
|
||||
|
||||
String get _heroTagSuffix => widget.heroTagSuffix != null ? '_${widget.heroTagSuffix}' : '';
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_isInLibrary = _checkIfInLibrary(widget.podcast);
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
Future.delayed(const Duration(milliseconds: 350), () {
|
||||
if (mounted) {
|
||||
_extractColors();
|
||||
}
|
||||
});
|
||||
_loadEpisodes();
|
||||
});
|
||||
}
|
||||
|
||||
/// Check if podcast is in library
|
||||
bool _checkIfInLibrary(MediaItem podcast) {
|
||||
if (podcast.provider == 'library') return true;
|
||||
return podcast.providerMappings?.any((m) => m.providerInstance == 'library') ?? false;
|
||||
}
|
||||
|
||||
/// Toggle library status
|
||||
Future<void> _toggleLibrary() async {
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
|
||||
try {
|
||||
final newState = !_isInLibrary;
|
||||
bool success;
|
||||
|
||||
if (newState) {
|
||||
// Add to library - MUST use non-library provider
|
||||
String? actualProvider;
|
||||
String? actualItemId;
|
||||
|
||||
if (widget.podcast.providerMappings != null && widget.podcast.providerMappings!.isNotEmpty) {
|
||||
// For adding to library, we MUST use a non-library provider
|
||||
final nonLibraryMapping = widget.podcast.providerMappings!.where(
|
||||
(m) => m.providerInstance != 'library' && m.providerDomain != 'library',
|
||||
).firstOrNull;
|
||||
|
||||
if (nonLibraryMapping != null) {
|
||||
actualProvider = nonLibraryMapping.providerDomain;
|
||||
actualItemId = nonLibraryMapping.itemId;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to item's own provider if no non-library mapping found
|
||||
if (actualProvider == null || actualItemId == null) {
|
||||
if (widget.podcast.provider != 'library') {
|
||||
actualProvider = widget.podcast.provider;
|
||||
actualItemId = widget.podcast.itemId;
|
||||
} else {
|
||||
// Item is library-only, can't add
|
||||
_logger.log('Cannot add to library: podcast is library-only');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
_logger.log('Adding podcast to library: provider=$actualProvider, itemId=$actualItemId');
|
||||
success = await maProvider.addToLibrary(
|
||||
mediaType: 'podcast',
|
||||
provider: actualProvider,
|
||||
itemId: actualItemId,
|
||||
);
|
||||
} else {
|
||||
// Remove from library
|
||||
int? libraryItemId;
|
||||
if (widget.podcast.provider == 'library') {
|
||||
libraryItemId = int.tryParse(widget.podcast.itemId);
|
||||
} else if (widget.podcast.providerMappings != null) {
|
||||
final libraryMapping = widget.podcast.providerMappings!.firstWhere(
|
||||
(m) => m.providerInstance == 'library',
|
||||
orElse: () => widget.podcast.providerMappings!.first,
|
||||
);
|
||||
if (libraryMapping.providerInstance == 'library') {
|
||||
libraryItemId = int.tryParse(libraryMapping.itemId);
|
||||
}
|
||||
}
|
||||
|
||||
if (libraryItemId == null) {
|
||||
_logger.log('Cannot remove from library: no library ID found');
|
||||
return;
|
||||
}
|
||||
|
||||
success = await maProvider.removeFromLibrary(
|
||||
mediaType: 'podcast',
|
||||
libraryItemId: libraryItemId,
|
||||
);
|
||||
}
|
||||
|
||||
if (success) {
|
||||
setState(() {
|
||||
_isInLibrary = newState;
|
||||
});
|
||||
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
_isInLibrary ? S.of(context)!.addedToLibrary : S.of(context)!.removedFromLibrary,
|
||||
),
|
||||
duration: const Duration(seconds: 1),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.log('Error toggling podcast library: $e');
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Failed to update library: $e'),
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _extractColors() async {
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
// Use initialImageUrl first for consistency with hero animation
|
||||
final imageUrl = widget.initialImageUrl ?? maProvider.getPodcastImageUrl(widget.podcast);
|
||||
|
||||
if (imageUrl != null) {
|
||||
try {
|
||||
final colorSchemes = await PaletteHelper.extractColorSchemes(
|
||||
CachedNetworkImageProvider(imageUrl),
|
||||
);
|
||||
if (mounted && colorSchemes != null) {
|
||||
setState(() {
|
||||
_lightColorScheme = colorSchemes.$1;
|
||||
_darkColorScheme = colorSchemes.$2;
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.log('🎙️ Error extracting colors: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loadEpisodes() async {
|
||||
if (_isLoadingEpisodes) return;
|
||||
|
||||
setState(() {
|
||||
_isLoadingEpisodes = true;
|
||||
});
|
||||
|
||||
try {
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
if (maProvider.api != null) {
|
||||
final episodes = await maProvider.api!.getPodcastEpisodes(
|
||||
widget.podcast.itemId,
|
||||
provider: widget.podcast.provider,
|
||||
);
|
||||
|
||||
if (mounted) {
|
||||
_logger.log('🎙️ Loaded ${episodes.length} episodes for ${widget.podcast.name}');
|
||||
// Debug: Log first episode metadata to see available fields
|
||||
if (episodes.isNotEmpty) {
|
||||
final first = episodes.first;
|
||||
_logger.log('🎙️ First episode metadata keys: ${first.metadata?.keys.toList()}');
|
||||
_logger.log('🎙️ First episode metadata: ${first.metadata}');
|
||||
}
|
||||
setState(() {
|
||||
_episodes = episodes;
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.log('🎙️ Error loading episodes: $e');
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isLoadingEpisodes = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _playEpisode(MediaItem episode) async {
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
final selectedPlayer = maProvider.selectedPlayer;
|
||||
|
||||
if (selectedPlayer != null) {
|
||||
try {
|
||||
await maProvider.api?.playPodcastEpisode(selectedPlayer.playerId, episode);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Playing: ${episode.name}'),
|
||||
duration: const Duration(seconds: 1),
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.log('🎙️ Error playing episode: $e');
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Failed to play episode: $e')),
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
_showPlayOnMenu(context, episode);
|
||||
}
|
||||
}
|
||||
|
||||
void _showPlayOnMenu(BuildContext context, MediaItem episode) {
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
|
||||
GlobalPlayerOverlay.hidePlayer();
|
||||
|
||||
showPlayerPickerSheet(
|
||||
context: context,
|
||||
title: S.of(context)!.playOn,
|
||||
players: maProvider.availablePlayers,
|
||||
selectedPlayer: maProvider.selectedPlayer,
|
||||
onPlayerSelected: (player) async {
|
||||
maProvider.selectPlayer(player);
|
||||
await maProvider.api?.playPodcastEpisode(player.playerId, episode);
|
||||
},
|
||||
).whenComplete(() {
|
||||
GlobalPlayerOverlay.showPlayer();
|
||||
});
|
||||
}
|
||||
|
||||
String _formatDuration(Duration? duration) {
|
||||
if (duration == null || duration == Duration.zero) return '';
|
||||
final hours = duration.inHours;
|
||||
final minutes = duration.inMinutes.remainder(60);
|
||||
|
||||
if (hours > 0) {
|
||||
return '${hours}h ${minutes}m';
|
||||
}
|
||||
return '${minutes} min';
|
||||
}
|
||||
|
||||
/// Format release date from episode metadata
|
||||
/// Tries various common field names for publication date
|
||||
String? _formatReleaseDate(Map<String, dynamic>? metadata) {
|
||||
if (metadata == null) return null;
|
||||
|
||||
// Try various common field names for publication date
|
||||
dynamic dateValue = metadata['published'] ??
|
||||
metadata['pub_date'] ??
|
||||
metadata['release_date'] ??
|
||||
metadata['aired'] ??
|
||||
metadata['timestamp'];
|
||||
|
||||
if (dateValue == null) return null;
|
||||
|
||||
try {
|
||||
DateTime? date;
|
||||
if (dateValue is String) {
|
||||
date = DateTime.tryParse(dateValue);
|
||||
} else if (dateValue is int) {
|
||||
// Unix timestamp
|
||||
date = DateTime.fromMillisecondsSinceEpoch(dateValue * 1000);
|
||||
}
|
||||
|
||||
if (date != null) {
|
||||
// Format as "Jan 15, 2024"
|
||||
final months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||
return '${months[date.month - 1]} ${date.day}, ${date.year}';
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.log('🎙️ Error parsing release date: $e');
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Add episode to queue on current player
|
||||
Future<void> _addToQueue(MediaItem episode) async {
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
final selectedPlayer = maProvider.selectedPlayer;
|
||||
|
||||
if (selectedPlayer == null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(S.of(context)!.noPlayerSelected)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Convert MediaItem to Track for queue addition
|
||||
final track = Track(
|
||||
itemId: episode.itemId,
|
||||
provider: episode.provider,
|
||||
name: episode.name,
|
||||
uri: episode.uri,
|
||||
duration: episode.duration,
|
||||
metadata: episode.metadata,
|
||||
);
|
||||
await maProvider.addTrackToQueue(selectedPlayer.playerId, track);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(S.of(context)!.addedToQueue),
|
||||
duration: const Duration(seconds: 1),
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.log('🎙️ Error adding episode to queue: $e');
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(S.of(context)!.failedToAddToQueue(e.toString()))),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// CRITICAL FIX: Use select() instead of watch() to prevent rebuilds during Hero animation
|
||||
// watch() rebuilds on ANY provider change (library updates, etc.) causing animation jank
|
||||
// select() only rebuilds when the specific podcast image URL changes
|
||||
final providerImageUrl = context.select<MusicAssistantProvider, String?>(
|
||||
(provider) => provider.getPodcastImageUrl(widget.podcast),
|
||||
);
|
||||
// Use initialImageUrl for seamless hero animation (same URL as source)
|
||||
final imageUrl = widget.initialImageUrl ?? providerImageUrl;
|
||||
|
||||
final adaptiveTheme = context.select<ThemeProvider, bool>(
|
||||
(provider) => provider.adaptiveTheme,
|
||||
);
|
||||
final adaptiveLightScheme = context.select<ThemeProvider, ColorScheme?>(
|
||||
(provider) => provider.adaptiveLightScheme,
|
||||
);
|
||||
final adaptiveDarkScheme = context.select<ThemeProvider, ColorScheme?>(
|
||||
(provider) => provider.adaptiveDarkScheme,
|
||||
);
|
||||
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
|
||||
ColorScheme? adaptiveScheme;
|
||||
if (adaptiveTheme) {
|
||||
adaptiveScheme = isDark
|
||||
? (_darkColorScheme ?? adaptiveDarkScheme)
|
||||
: (_lightColorScheme ?? adaptiveLightScheme);
|
||||
}
|
||||
final colorScheme = adaptiveScheme ?? Theme.of(context).colorScheme;
|
||||
final textTheme = Theme.of(context).textTheme;
|
||||
|
||||
final description = widget.podcast.metadata?['description'] as String?;
|
||||
final author = widget.podcast.metadata?['author'] as String?;
|
||||
|
||||
return PopScope(
|
||||
canPop: true,
|
||||
onPopInvokedWithResult: (didPop, result) {
|
||||
if (didPop) {
|
||||
clearAdaptiveColorsOnBack(context);
|
||||
}
|
||||
},
|
||||
child: Scaffold(
|
||||
backgroundColor: colorScheme.surface,
|
||||
body: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final coverSize = (constraints.maxWidth * 0.7).clamp(200.0, 320.0);
|
||||
final expandedHeight = coverSize + 70;
|
||||
|
||||
return CustomScrollView(
|
||||
slivers: [
|
||||
SliverAppBar(
|
||||
expandedHeight: expandedHeight,
|
||||
pinned: true,
|
||||
backgroundColor: colorScheme.surface,
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back_rounded),
|
||||
onPressed: () {
|
||||
clearAdaptiveColorsOnBack(context);
|
||||
Navigator.pop(context);
|
||||
},
|
||||
color: colorScheme.onSurface,
|
||||
),
|
||||
flexibleSpace: FlexibleSpaceBar(
|
||||
background: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const SizedBox(height: 60),
|
||||
Hero(
|
||||
tag: HeroTags.podcastCover + (widget.podcast.uri ?? widget.podcast.itemId) + _heroTagSuffix,
|
||||
// Match audiobook pattern: ClipRRect + CachedNetworkImage for smooth hero
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
child: Container(
|
||||
width: coverSize,
|
||||
height: coverSize,
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
child: imageUrl != null
|
||||
? CachedNetworkImage(
|
||||
imageUrl: imageUrl,
|
||||
fit: BoxFit.cover,
|
||||
// Match source memCacheWidth for smooth Hero animation
|
||||
memCacheWidth: 256,
|
||||
memCacheHeight: 256,
|
||||
fadeInDuration: Duration.zero,
|
||||
fadeOutDuration: Duration.zero,
|
||||
placeholder: (_, __) => Center(
|
||||
child: Icon(
|
||||
MdiIcons.podcast,
|
||||
size: coverSize * 0.43,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
errorWidget: (_, __, ___) => Center(
|
||||
child: Icon(
|
||||
MdiIcons.podcast,
|
||||
size: coverSize * 0.43,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
)
|
||||
: Center(
|
||||
child: Icon(
|
||||
MdiIcons.podcast,
|
||||
size: coverSize * 0.43,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
// Podcast title
|
||||
Text(
|
||||
widget.podcast.name,
|
||||
style: textTheme.headlineSmall?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: colorScheme.onSurface,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
if (author != null) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
author,
|
||||
style: textTheme.bodyLarge?.copyWith(
|
||||
color: colorScheme.onSurface.withOpacity(0.7),
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Action buttons row
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Row(
|
||||
children: [
|
||||
// Main Play Latest Episode Button
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: SizedBox(
|
||||
height: 50,
|
||||
child: ElevatedButton.icon(
|
||||
onPressed: _isLoadingEpisodes || _episodes.isEmpty
|
||||
? null
|
||||
: () => _playEpisode(_episodes.first),
|
||||
icon: const Icon(Icons.play_arrow_rounded),
|
||||
label: Text(S.of(context)!.play),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: colorScheme.primary,
|
||||
foregroundColor: colorScheme.onPrimary,
|
||||
disabledBackgroundColor: colorScheme.primary.withOpacity(0.38),
|
||||
disabledForegroundColor: colorScheme.onPrimary.withOpacity(0.38),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
// "Play on..." Button
|
||||
SizedBox(
|
||||
height: 50,
|
||||
width: 50,
|
||||
child: FilledButton.tonal(
|
||||
onPressed: _isLoadingEpisodes || _episodes.isEmpty
|
||||
? null
|
||||
: () => _showPlayOnMenu(context, _episodes.first),
|
||||
style: FilledButton.styleFrom(
|
||||
padding: EdgeInsets.zero,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: const Icon(Icons.speaker_group_outlined),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
// Library button
|
||||
SizedBox(
|
||||
height: 50,
|
||||
width: 50,
|
||||
child: FilledButton.tonal(
|
||||
onPressed: _toggleLibrary,
|
||||
style: FilledButton.styleFrom(
|
||||
padding: EdgeInsets.zero,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: Icon(
|
||||
_isInLibrary ? Icons.library_add_check : Icons.library_add,
|
||||
color: _isInLibrary
|
||||
? colorScheme.primary
|
||||
: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Description
|
||||
if (description != null && description.isNotEmpty) ...[
|
||||
GestureDetector(
|
||||
onTap: () {
|
||||
setState(() {
|
||||
_isDescriptionExpanded = !_isDescriptionExpanded;
|
||||
});
|
||||
},
|
||||
child: AnimatedCrossFade(
|
||||
firstChild: Text(
|
||||
description,
|
||||
maxLines: 3,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: textTheme.bodyMedium?.copyWith(
|
||||
color: colorScheme.onSurface.withOpacity(0.7),
|
||||
),
|
||||
),
|
||||
secondChild: Text(
|
||||
description,
|
||||
style: textTheme.bodyMedium?.copyWith(
|
||||
color: colorScheme.onSurface.withOpacity(0.7),
|
||||
),
|
||||
),
|
||||
crossFadeState: _isDescriptionExpanded
|
||||
? CrossFadeState.showSecond
|
||||
: CrossFadeState.showFirst,
|
||||
duration: const Duration(milliseconds: 200),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// Episodes header
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
S.of(context)!.episodes,
|
||||
style: textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
if (_episodes.isNotEmpty)
|
||||
Text(
|
||||
'(${_episodes.length})',
|
||||
style: textTheme.bodyLarge?.copyWith(
|
||||
color: colorScheme.onSurface.withOpacity(0.5),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Episodes list
|
||||
if (_isLoadingEpisodes)
|
||||
SliverToBoxAdapter(
|
||||
child: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: CircularProgressIndicator(color: colorScheme.primary),
|
||||
),
|
||||
),
|
||||
)
|
||||
else if (_episodes.isEmpty)
|
||||
SliverToBoxAdapter(
|
||||
child: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(
|
||||
children: [
|
||||
Icon(
|
||||
MdiIcons.microphoneOff,
|
||||
size: 48,
|
||||
color: colorScheme.onSurface.withOpacity(0.3),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'No episodes found',
|
||||
style: textTheme.bodyLarge?.copyWith(
|
||||
color: colorScheme.onSurface.withOpacity(0.5),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
SliverList(
|
||||
delegate: SliverChildBuilderDelegate(
|
||||
(context, index) {
|
||||
final episode = _episodes[index];
|
||||
final episodeDescription = episode.metadata?['description'] as String?;
|
||||
final duration = episode.duration;
|
||||
final episodeId = episode.uri ?? episode.itemId;
|
||||
final isExpanded = _expandedEpisodeId == episodeId;
|
||||
final episodeImageUrl = context.read<MusicAssistantProvider>().getImageUrl(episode, size: 256);
|
||||
|
||||
// Try to get release date from metadata
|
||||
final releaseDate = _formatReleaseDate(episode.metadata);
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
InkWell(
|
||||
onTap: () => _playEpisode(episode),
|
||||
onLongPress: () {
|
||||
setState(() {
|
||||
_expandedEpisodeId = isExpanded ? null : episodeId;
|
||||
});
|
||||
},
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Episode cover (bigger than before)
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Container(
|
||||
width: 72,
|
||||
height: 72,
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
child: episodeImageUrl != null
|
||||
? CachedNetworkImage(
|
||||
imageUrl: episodeImageUrl,
|
||||
fit: BoxFit.cover,
|
||||
fadeInDuration: Duration.zero,
|
||||
fadeOutDuration: Duration.zero,
|
||||
placeholder: (_, __) => Icon(
|
||||
MdiIcons.podcast,
|
||||
size: 32,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
errorWidget: (_, __, ___) => Icon(
|
||||
MdiIcons.podcast,
|
||||
size: 32,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
)
|
||||
: Icon(
|
||||
MdiIcons.podcast,
|
||||
size: 32,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
// Episode info
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
episode.name,
|
||||
style: textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
if (episodeDescription != null && episodeDescription.isNotEmpty) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
episodeDescription,
|
||||
maxLines: isExpanded ? 100 : 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.onSurface.withOpacity(0.6),
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 6),
|
||||
// Duration and release date row
|
||||
Row(
|
||||
children: [
|
||||
if (duration != null && duration > Duration.zero) ...[
|
||||
Icon(
|
||||
Icons.access_time,
|
||||
size: 14,
|
||||
color: colorScheme.onSurface.withOpacity(0.5),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
_formatDuration(duration),
|
||||
style: textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.onSurface.withOpacity(0.5),
|
||||
),
|
||||
),
|
||||
],
|
||||
if (duration != null && duration > Duration.zero && releaseDate != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
child: Text(
|
||||
'•',
|
||||
style: textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.onSurface.withOpacity(0.5),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (releaseDate != null)
|
||||
Text(
|
||||
releaseDate,
|
||||
style: textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.onSurface.withOpacity(0.5),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
// Expanded action buttons (matching album track style)
|
||||
AnimatedCrossFade(
|
||||
firstChild: const SizedBox.shrink(),
|
||||
secondChild: Padding(
|
||||
padding: const EdgeInsets.only(left: 100, right: 16, bottom: 12),
|
||||
child: Row(
|
||||
children: [
|
||||
// Play button
|
||||
SizedBox(
|
||||
height: 44,
|
||||
width: 44,
|
||||
child: FilledButton.tonal(
|
||||
onPressed: () => _playEpisode(episode),
|
||||
style: FilledButton.styleFrom(
|
||||
padding: EdgeInsets.zero,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: const Icon(Icons.play_arrow, size: 20),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
// Play on... button
|
||||
SizedBox(
|
||||
height: 44,
|
||||
width: 44,
|
||||
child: FilledButton.tonal(
|
||||
onPressed: () => _showPlayOnMenu(context, episode),
|
||||
style: FilledButton.styleFrom(
|
||||
padding: EdgeInsets.zero,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: const Icon(Icons.speaker_group_outlined, size: 20),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
// Add to queue button
|
||||
SizedBox(
|
||||
height: 44,
|
||||
width: 44,
|
||||
child: FilledButton.tonal(
|
||||
onPressed: () => _addToQueue(episode),
|
||||
style: FilledButton.styleFrom(
|
||||
padding: EdgeInsets.zero,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: const Icon(Icons.playlist_add, size: 20),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
crossFadeState: isExpanded
|
||||
? CrossFadeState.showSecond
|
||||
: CrossFadeState.showFirst,
|
||||
duration: const Duration(milliseconds: 200),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
childCount: _episodes.length,
|
||||
),
|
||||
),
|
||||
|
||||
// Bottom padding for mini player
|
||||
const SliverToBoxAdapter(
|
||||
child: SizedBox(height: 100),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+3017
-246
File diff suppressed because it is too large
Load Diff
@@ -41,6 +41,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
// Player settings
|
||||
bool _preferLocalPlayer = false;
|
||||
bool _smartSortPlayers = false;
|
||||
// Hint settings
|
||||
bool _showHints = true;
|
||||
// Library settings
|
||||
bool _showOnlyArtistsWithAlbums = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -89,6 +93,12 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
final preferLocal = await SettingsService.getPreferLocalPlayer();
|
||||
final smartSort = await SettingsService.getSmartSortPlayers();
|
||||
|
||||
// Load hint settings
|
||||
final showHints = await SettingsService.getShowHints();
|
||||
|
||||
// Load library settings
|
||||
final showOnlyArtistsWithAlbums = await SettingsService.getShowOnlyArtistsWithAlbums();
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_showRecentAlbums = showRecent;
|
||||
@@ -105,6 +115,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
_libraryEnabled = libraryEnabled;
|
||||
_preferLocalPlayer = preferLocal;
|
||||
_smartSortPlayers = smartSort;
|
||||
_showHints = showHints;
|
||||
_showOnlyArtistsWithAlbums = showOnlyArtistsWithAlbums;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -699,6 +711,89 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
|
||||
const SizedBox(height: 32),
|
||||
|
||||
// Hints & Tips section
|
||||
Text(
|
||||
S.of(context)!.hintsAndTips,
|
||||
style: textTheme.titleMedium?.copyWith(
|
||||
color: colorScheme.onBackground,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
S.of(context)!.showHintsDescription,
|
||||
style: textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.onBackground.withOpacity(0.6),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceVariant.withOpacity(0.3),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: SwitchListTile(
|
||||
title: Text(
|
||||
S.of(context)!.showHints,
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
),
|
||||
value: _showHints,
|
||||
onChanged: (value) {
|
||||
setState(() => _showHints = value);
|
||||
SettingsService.setShowHints(value);
|
||||
},
|
||||
activeColor: colorScheme.primary,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 32),
|
||||
|
||||
// Library section
|
||||
Text(
|
||||
S.of(context)!.library,
|
||||
style: textTheme.titleMedium?.copyWith(
|
||||
color: colorScheme.onBackground,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceVariant.withOpacity(0.3),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: SwitchListTile(
|
||||
title: Text(
|
||||
'Show only artists with albums',
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
),
|
||||
subtitle: Text(
|
||||
'Hide artists that have no albums in your library',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface.withOpacity(0.6),
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
value: _showOnlyArtistsWithAlbums,
|
||||
onChanged: (value) async {
|
||||
setState(() => _showOnlyArtistsWithAlbums = value);
|
||||
await SettingsService.setShowOnlyArtistsWithAlbums(value);
|
||||
// Force sync library to apply the new filter at API level
|
||||
if (mounted) {
|
||||
context.read<MusicAssistantProvider>().forceLibrarySync();
|
||||
}
|
||||
},
|
||||
activeColor: colorScheme.primary,
|
||||
contentPadding: EdgeInsets.zero,
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 32),
|
||||
|
||||
// Home Screen section
|
||||
Text(
|
||||
S.of(context)!.homeScreen,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:async';
|
||||
import 'package:audio_service/audio_service.dart';
|
||||
import 'package:audio_session/audio_session.dart';
|
||||
import 'package:just_audio/just_audio.dart';
|
||||
@@ -11,6 +12,12 @@ class MassivAudioHandler extends BaseAudioHandler with SeekHandler {
|
||||
final AuthManager authManager;
|
||||
final _logger = DebugLogger();
|
||||
|
||||
// Stream subscriptions for proper cleanup
|
||||
StreamSubscription? _interruptionSubscription;
|
||||
StreamSubscription? _becomingNoisySubscription;
|
||||
StreamSubscription? _playbackEventSubscription;
|
||||
StreamSubscription? _currentIndexSubscription;
|
||||
|
||||
// Track current metadata separately from what's in the notification
|
||||
// This allows us to update the notification when metadata arrives late
|
||||
MediaItem? _currentMediaItem;
|
||||
@@ -42,7 +49,7 @@ class MassivAudioHandler extends BaseAudioHandler with SeekHandler {
|
||||
await session.configure(const AudioSessionConfiguration.music());
|
||||
|
||||
// Handle audio interruptions
|
||||
session.interruptionEventStream.listen((event) {
|
||||
_interruptionSubscription = session.interruptionEventStream.listen((event) {
|
||||
if (event.begin) {
|
||||
switch (event.type) {
|
||||
case AudioInterruptionType.duck:
|
||||
@@ -68,15 +75,15 @@ class MassivAudioHandler extends BaseAudioHandler with SeekHandler {
|
||||
});
|
||||
|
||||
// Handle becoming noisy (headphones unplugged)
|
||||
session.becomingNoisyEventStream.listen((_) {
|
||||
_becomingNoisySubscription = session.becomingNoisyEventStream.listen((_) {
|
||||
pause();
|
||||
});
|
||||
|
||||
// Broadcast playback state changes
|
||||
_player.playbackEventStream.listen(_broadcastState);
|
||||
_playbackEventSubscription = _player.playbackEventStream.listen(_broadcastState);
|
||||
|
||||
// Broadcast current media item changes
|
||||
_player.currentIndexStream.listen((_) {
|
||||
_currentIndexSubscription = _player.currentIndexStream.listen((_) {
|
||||
if (_currentMediaItem != null) {
|
||||
mediaItem.add(_currentMediaItem);
|
||||
}
|
||||
@@ -293,4 +300,13 @@ class MassivAudioHandler extends BaseAudioHandler with SeekHandler {
|
||||
Stream<Duration?> get durationStream => _player.durationStream;
|
||||
|
||||
MediaItem? get currentMediaItem => _currentMediaItem;
|
||||
|
||||
/// Dispose of resources and cancel all subscriptions
|
||||
Future<void> dispose() async {
|
||||
await _interruptionSubscription?.cancel();
|
||||
await _becomingNoisySubscription?.cancel();
|
||||
await _playbackEventSubscription?.cancel();
|
||||
await _currentIndexSubscription?.cancel();
|
||||
await _player.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,7 +100,8 @@ class AuthManager {
|
||||
host.startsWith('172.31.') ||
|
||||
host == 'localhost' ||
|
||||
host.startsWith('127.') ||
|
||||
host.endsWith('.local');
|
||||
host.endsWith('.local') ||
|
||||
host.endsWith('.ts.net');
|
||||
}
|
||||
|
||||
/// Try to detect auth strategy for a given URL
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import 'dart:convert';
|
||||
import '../models/media_item.dart';
|
||||
import '../models/player.dart';
|
||||
import '../services/debug_logger.dart';
|
||||
import '../services/database_service.dart';
|
||||
import '../constants/timings.dart';
|
||||
|
||||
/// Centralized cache service for all app data caching
|
||||
/// This is a non-notifying service - it just stores and retrieves cached data
|
||||
class CacheService {
|
||||
final DebugLogger _logger = DebugLogger();
|
||||
bool _homeRowsLoaded = false;
|
||||
|
||||
// Cache size limits to prevent unbounded memory growth
|
||||
static const int _maxDetailCacheSize = 50; // Max albums/playlists/artists cached
|
||||
static const int _maxSearchCacheSize = 20; // Max search queries cached
|
||||
static const int _maxPlayerTrackCacheSize = 30; // Max player track associations
|
||||
|
||||
// Home screen row caching
|
||||
List<Album>? _cachedRecentAlbums;
|
||||
@@ -35,6 +43,7 @@ class CacheService {
|
||||
|
||||
// Player track cache (for smooth swipe transitions)
|
||||
final Map<String, Track?> _playerTrackCache = {};
|
||||
final Map<String, DateTime> _playerTrackCacheTime = {};
|
||||
|
||||
// ============================================================================
|
||||
// HOME SCREEN ROW CACHING
|
||||
@@ -57,6 +66,8 @@ class CacheService {
|
||||
_cachedRecentAlbums = albums;
|
||||
_recentAlbumsLastFetched = DateTime.now();
|
||||
_logger.log('✅ Cached ${albums.length} recent albums');
|
||||
// Persist to database for instant load on next launch
|
||||
_persistHomeRowToDatabase('recent_albums', albums.map((a) => a.toJson()).toList());
|
||||
}
|
||||
|
||||
/// Check if discover artists cache is valid
|
||||
@@ -76,6 +87,8 @@ class CacheService {
|
||||
_cachedDiscoverArtists = artists;
|
||||
_discoverArtistsLastFetched = DateTime.now();
|
||||
_logger.log('✅ Cached ${artists.length} discover artists');
|
||||
// Persist to database for instant load on next launch
|
||||
_persistHomeRowToDatabase('discover_artists', artists.map((a) => a.toJson()).toList());
|
||||
}
|
||||
|
||||
/// Check if discover albums cache is valid
|
||||
@@ -95,6 +108,8 @@ class CacheService {
|
||||
_cachedDiscoverAlbums = albums;
|
||||
_discoverAlbumsLastFetched = DateTime.now();
|
||||
_logger.log('✅ Cached ${albums.length} discover albums');
|
||||
// Persist to database for instant load on next launch
|
||||
_persistHomeRowToDatabase('discover_albums', albums.map((a) => a.toJson()).toList());
|
||||
}
|
||||
|
||||
/// Invalidate home screen cache (call on pull-to-refresh)
|
||||
@@ -105,6 +120,22 @@ class CacheService {
|
||||
_logger.log('🗑️ Home screen cache invalidated');
|
||||
}
|
||||
|
||||
/// Invalidate home album caches (call when albums are added/removed from library)
|
||||
void invalidateHomeAlbumCaches() {
|
||||
_cachedRecentAlbums = null;
|
||||
_recentAlbumsLastFetched = null;
|
||||
_cachedDiscoverAlbums = null;
|
||||
_discoverAlbumsLastFetched = null;
|
||||
_logger.log('🗑️ Home album caches invalidated');
|
||||
}
|
||||
|
||||
/// Invalidate home artist caches (call when artists are added/removed from library)
|
||||
void invalidateHomeArtistCaches() {
|
||||
_cachedDiscoverArtists = null;
|
||||
_discoverArtistsLastFetched = null;
|
||||
_logger.log('🗑️ Home artist caches invalidated');
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DETAIL SCREEN CACHING
|
||||
// ============================================================================
|
||||
@@ -126,15 +157,23 @@ class CacheService {
|
||||
void setCachedAlbumTracks(String cacheKey, List<Track> tracks) {
|
||||
_albumTracksCache[cacheKey] = tracks;
|
||||
_albumTracksCacheTime[cacheKey] = DateTime.now();
|
||||
_evictOldestEntries(_albumTracksCache, _albumTracksCacheTime, _maxDetailCacheSize);
|
||||
_logger.log('✅ Cached ${tracks.length} tracks for album $cacheKey');
|
||||
}
|
||||
|
||||
/// Invalidate album tracks cache
|
||||
/// Invalidate album tracks cache for a specific album
|
||||
void invalidateAlbumTracksCache(String albumId) {
|
||||
_albumTracksCache.remove(albumId);
|
||||
_albumTracksCacheTime.remove(albumId);
|
||||
}
|
||||
|
||||
/// Invalidate all album tracks caches (call when tracks are added/removed from library)
|
||||
void invalidateAllAlbumTracksCaches() {
|
||||
_albumTracksCache.clear();
|
||||
_albumTracksCacheTime.clear();
|
||||
_logger.log('🗑️ All album tracks caches invalidated');
|
||||
}
|
||||
|
||||
/// Check if playlist tracks cache is valid
|
||||
bool isPlaylistTracksCacheValid(String cacheKey, {bool forceRefresh = false}) {
|
||||
if (forceRefresh) return false;
|
||||
@@ -152,15 +191,23 @@ class CacheService {
|
||||
void setCachedPlaylistTracks(String cacheKey, List<Track> tracks) {
|
||||
_playlistTracksCache[cacheKey] = tracks;
|
||||
_playlistTracksCacheTime[cacheKey] = DateTime.now();
|
||||
_evictOldestEntries(_playlistTracksCache, _playlistTracksCacheTime, _maxDetailCacheSize);
|
||||
_logger.log('✅ Cached ${tracks.length} tracks for playlist $cacheKey');
|
||||
}
|
||||
|
||||
/// Invalidate playlist tracks cache
|
||||
/// Invalidate playlist tracks cache for a specific playlist
|
||||
void invalidatePlaylistTracksCache(String playlistId) {
|
||||
_playlistTracksCache.remove(playlistId);
|
||||
_playlistTracksCacheTime.remove(playlistId);
|
||||
}
|
||||
|
||||
/// Invalidate all playlist tracks caches (call when tracks are added/removed from library)
|
||||
void invalidateAllPlaylistTracksCaches() {
|
||||
_playlistTracksCache.clear();
|
||||
_playlistTracksCacheTime.clear();
|
||||
_logger.log('🗑️ All playlist tracks caches invalidated');
|
||||
}
|
||||
|
||||
/// Check if artist albums cache is valid
|
||||
bool isArtistAlbumsCacheValid(String cacheKey, {bool forceRefresh = false}) {
|
||||
if (forceRefresh) return false;
|
||||
@@ -178,9 +225,17 @@ class CacheService {
|
||||
void setCachedArtistAlbums(String cacheKey, List<Album> albums) {
|
||||
_artistAlbumsCache[cacheKey] = albums;
|
||||
_artistAlbumsCacheTime[cacheKey] = DateTime.now();
|
||||
_evictOldestEntries(_artistAlbumsCache, _artistAlbumsCacheTime, _maxDetailCacheSize);
|
||||
_logger.log('✅ Cached ${albums.length} albums for artist $cacheKey');
|
||||
}
|
||||
|
||||
/// Invalidate all artist albums caches (call when albums are added/removed from library)
|
||||
void invalidateArtistAlbumsCache() {
|
||||
_artistAlbumsCache.clear();
|
||||
_artistAlbumsCacheTime.clear();
|
||||
_logger.log('🗑️ Artist albums cache invalidated');
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// SEARCH CACHING
|
||||
// ============================================================================
|
||||
@@ -202,9 +257,17 @@ class CacheService {
|
||||
void setCachedSearchResults(String cacheKey, Map<String, List<MediaItem>> results) {
|
||||
_searchCache[cacheKey] = results;
|
||||
_searchCacheTime[cacheKey] = DateTime.now();
|
||||
_evictOldestEntries(_searchCache, _searchCacheTime, _maxSearchCacheSize);
|
||||
_logger.log('✅ Cached search results for "$cacheKey"');
|
||||
}
|
||||
|
||||
/// Invalidate all search cache (call when library items change)
|
||||
void invalidateSearchCache() {
|
||||
_searchCache.clear();
|
||||
_searchCacheTime.clear();
|
||||
_logger.log('🗑️ Search cache invalidated');
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// PLAYER CACHING
|
||||
// ============================================================================
|
||||
@@ -245,9 +308,20 @@ class CacheService {
|
||||
/// Get cached track for a player (used for smooth swipe transitions)
|
||||
Track? getCachedTrackForPlayer(String playerId) => _playerTrackCache[playerId];
|
||||
|
||||
/// Get all player IDs that have cached tracks
|
||||
Iterable<String> getAllCachedPlayerIds() => _playerTrackCache.keys;
|
||||
|
||||
/// Set cached track for a player
|
||||
void setCachedTrackForPlayer(String playerId, Track? track) {
|
||||
_playerTrackCache[playerId] = track;
|
||||
_playerTrackCacheTime[playerId] = DateTime.now();
|
||||
_evictOldestEntries(_playerTrackCache, _playerTrackCacheTime, _maxPlayerTrackCacheSize);
|
||||
}
|
||||
|
||||
/// Clear cached track for a player (e.g., when external source is active)
|
||||
void clearCachedTrackForPlayer(String playerId) {
|
||||
_playerTrackCache.remove(playerId);
|
||||
_playerTrackCacheTime.remove(playerId);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
@@ -265,6 +339,7 @@ class CacheService {
|
||||
_searchCache.clear();
|
||||
_searchCacheTime.clear();
|
||||
_playerTrackCache.clear();
|
||||
_playerTrackCacheTime.clear();
|
||||
_logger.log('🗑️ All detail caches cleared');
|
||||
}
|
||||
|
||||
@@ -276,4 +351,108 @@ class CacheService {
|
||||
_cachedSelectedPlayer = null;
|
||||
_playersLastFetched = null;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DATABASE PERSISTENCE FOR HOME ROWS
|
||||
// ============================================================================
|
||||
|
||||
/// Load home row data from database for instant display on startup
|
||||
Future<void> loadHomeRowsFromDatabase() async {
|
||||
if (_homeRowsLoaded) return;
|
||||
_homeRowsLoaded = true;
|
||||
|
||||
try {
|
||||
if (!DatabaseService.instance.isInitialized) return;
|
||||
|
||||
// Load recent albums
|
||||
final recentData = await DatabaseService.instance.getHomeRowCache('recent_albums');
|
||||
if (recentData != null) {
|
||||
try {
|
||||
final items = (jsonDecode(recentData.itemsJson) as List)
|
||||
.map((json) => Album.fromJson(json as Map<String, dynamic>))
|
||||
.toList();
|
||||
_cachedRecentAlbums = items;
|
||||
_recentAlbumsLastFetched = recentData.lastUpdated;
|
||||
_logger.log('📦 Loaded ${items.length} recent albums from database');
|
||||
} catch (e) {
|
||||
_logger.log('⚠️ Failed to parse recent albums: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// Load discover artists
|
||||
final artistsData = await DatabaseService.instance.getHomeRowCache('discover_artists');
|
||||
if (artistsData != null) {
|
||||
try {
|
||||
final items = (jsonDecode(artistsData.itemsJson) as List)
|
||||
.map((json) => Artist.fromJson(json as Map<String, dynamic>))
|
||||
.toList();
|
||||
_cachedDiscoverArtists = items;
|
||||
_discoverArtistsLastFetched = artistsData.lastUpdated;
|
||||
_logger.log('📦 Loaded ${items.length} discover artists from database');
|
||||
} catch (e) {
|
||||
_logger.log('⚠️ Failed to parse discover artists: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// Load discover albums
|
||||
final albumsData = await DatabaseService.instance.getHomeRowCache('discover_albums');
|
||||
if (albumsData != null) {
|
||||
try {
|
||||
final items = (jsonDecode(albumsData.itemsJson) as List)
|
||||
.map((json) => Album.fromJson(json as Map<String, dynamic>))
|
||||
.toList();
|
||||
_cachedDiscoverAlbums = items;
|
||||
_discoverAlbumsLastFetched = albumsData.lastUpdated;
|
||||
_logger.log('📦 Loaded ${items.length} discover albums from database');
|
||||
} catch (e) {
|
||||
_logger.log('⚠️ Failed to parse discover albums: $e');
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.log('⚠️ Error loading home rows from database: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Persist home row data to database (fire-and-forget)
|
||||
void _persistHomeRowToDatabase(String rowType, List<Map<String, dynamic>> items) {
|
||||
() async {
|
||||
try {
|
||||
if (!DatabaseService.instance.isInitialized) return;
|
||||
await DatabaseService.instance.saveHomeRowCache(rowType, jsonEncode(items));
|
||||
_logger.log('💾 Persisted $rowType to database');
|
||||
} catch (e) {
|
||||
_logger.log('⚠️ Failed to persist $rowType: $e');
|
||||
}
|
||||
}();
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// LRU CACHE EVICTION
|
||||
// ============================================================================
|
||||
|
||||
/// Evict oldest entries from cache maps to enforce size limit (LRU eviction)
|
||||
/// Uses the timestamp map to determine which entries are oldest
|
||||
void _evictOldestEntries<K, V>(
|
||||
Map<K, V> cache,
|
||||
Map<K, DateTime> cacheTime,
|
||||
int maxSize,
|
||||
) {
|
||||
if (cache.length <= maxSize) return;
|
||||
|
||||
// Sort keys by timestamp (oldest first)
|
||||
final sortedKeys = cacheTime.keys.toList()
|
||||
..sort((a, b) => (cacheTime[a] ?? DateTime.now())
|
||||
.compareTo(cacheTime[b] ?? DateTime.now()));
|
||||
|
||||
// Remove oldest entries until we're at maxSize
|
||||
final keysToRemove = sortedKeys.take(cache.length - maxSize);
|
||||
for (final key in keysToRemove) {
|
||||
cache.remove(key);
|
||||
cacheTime.remove(key);
|
||||
}
|
||||
|
||||
if (keysToRemove.isNotEmpty) {
|
||||
_logger.log('🗑️ LRU evicted ${keysToRemove.length} cache entries');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,6 +157,16 @@ class DatabaseService {
|
||||
/// Clear all cached data (useful for logout)
|
||||
Future<void> clearAllCache() => db.clearAllCache();
|
||||
|
||||
/// Clear cached items of a specific type (e.g., 'album', 'artist')
|
||||
/// Used before re-syncing to remove stale items
|
||||
Future<void> clearCacheForType(String itemType) => db.clearCache(itemType);
|
||||
|
||||
/// Mark a specific cached item as deleted
|
||||
/// Used when removing items from library for immediate database update
|
||||
Future<void> markCachedItemDeleted(String itemType, String itemId) {
|
||||
return db.markItemsDeleted(itemType, [itemId]);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Player Cache Convenience Methods
|
||||
// ============================================
|
||||
@@ -222,4 +232,83 @@ class DatabaseService {
|
||||
|
||||
/// Clear queue for a player
|
||||
Future<void> clearCachedQueue(String playerId) => db.clearCachedQueue(playerId);
|
||||
|
||||
// ============================================
|
||||
// Home Row Cache Convenience Methods
|
||||
// ============================================
|
||||
|
||||
/// Save home row data (recent albums, discover artists, etc.)
|
||||
Future<void> saveHomeRowCache(String rowType, String itemsJson) {
|
||||
return db.saveHomeRowCache(rowType, itemsJson);
|
||||
}
|
||||
|
||||
/// Get cached home row data
|
||||
Future<HomeRowCacheData?> getHomeRowCache(String rowType) {
|
||||
return db.getHomeRowCache(rowType);
|
||||
}
|
||||
|
||||
/// Clear all home row cache
|
||||
Future<void> clearHomeRowCache() => db.clearHomeRowCache();
|
||||
|
||||
// ============================================
|
||||
// Search History Convenience Methods
|
||||
// ============================================
|
||||
|
||||
/// Save a search query to history
|
||||
Future<void> saveSearchQuery(String query) => db.saveSearchQuery(query);
|
||||
|
||||
/// Get recent search queries (up to 10)
|
||||
Future<List<String>> getRecentSearches() => db.getRecentSearches();
|
||||
|
||||
/// Clear all search history
|
||||
Future<void> clearSearchHistory() => db.clearSearchHistory();
|
||||
|
||||
// ============================================
|
||||
// Cast-to-Sendspin Mapping Methods
|
||||
// ============================================
|
||||
|
||||
static const String _sendspinMappingType = 'cast_sendspin_mapping';
|
||||
|
||||
/// Save a Cast UUID to Sendspin ID mapping
|
||||
Future<void> saveCastToSendspinMapping(String castId, String sendspinId) {
|
||||
_logger.log('💾 Persisting Cast->Sendspin mapping: $castId -> $sendspinId');
|
||||
return db.cacheItem(
|
||||
itemType: _sendspinMappingType,
|
||||
itemId: castId,
|
||||
data: jsonEncode({'sendspinId': sendspinId}),
|
||||
);
|
||||
}
|
||||
|
||||
/// Get persisted Sendspin ID for a Cast UUID
|
||||
Future<String?> getSendspinIdForCast(String castId) async {
|
||||
final item = await db.getCachedItem(_sendspinMappingType, castId);
|
||||
if (item == null) return null;
|
||||
try {
|
||||
final data = jsonDecode(item.data) as Map<String, dynamic>;
|
||||
return data['sendspinId'] as String?;
|
||||
} catch (e) {
|
||||
_logger.log('Error decoding Sendspin mapping: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Load all persisted Cast-to-Sendspin mappings
|
||||
Future<Map<String, String>> getAllCastToSendspinMappings() async {
|
||||
final items = await db.getCachedItems(_sendspinMappingType);
|
||||
final mappings = <String, String>{};
|
||||
for (final item in items) {
|
||||
try {
|
||||
final data = jsonDecode(item.data) as Map<String, dynamic>;
|
||||
final sendspinId = data['sendspinId'] as String?;
|
||||
if (sendspinId != null) {
|
||||
// The itemId is the Cast UUID
|
||||
mappings[item.itemId] = sendspinId;
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.log('Error decoding Sendspin mapping: $e');
|
||||
}
|
||||
}
|
||||
_logger.log('📦 Loaded ${mappings.length} Cast->Sendspin mappings from database');
|
||||
return mappings;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,36 +1,99 @@
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
import 'package:device_info_plus/device_info_plus.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
import 'debug_logger.dart';
|
||||
import 'settings_service.dart';
|
||||
|
||||
/// Service to generate unique per-installation player IDs
|
||||
/// Simplified to match KMP client pattern: single storage key, lazy generation
|
||||
/// This prevents the critical bug where multiple devices of the same model
|
||||
/// would share the same player ID and trigger playback on all devices
|
||||
/// Service to generate unique per-device player IDs
|
||||
/// Uses stable device identifiers (ANDROID_ID) combined with MA username
|
||||
/// to create persistent player IDs that survive storage wipes and support
|
||||
/// multiple devices per account
|
||||
class DeviceIdService {
|
||||
static const String _keyLocalPlayerId = 'local_player_id';
|
||||
static final _logger = DebugLogger();
|
||||
static const _uuid = Uuid();
|
||||
|
||||
/// Get or generate a unique player ID for this installation
|
||||
/// ID is generated once and persisted across app restarts
|
||||
/// Format: ensemble_<uuid>
|
||||
///
|
||||
/// This matches the KMP client pattern: generate on first access, store once
|
||||
static Future<String> getOrCreateDevicePlayerId() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
// Cache stable device ID to avoid repeated platform calls
|
||||
static String? _cachedStableDeviceId;
|
||||
|
||||
// Single source of truth - no complex migration logic
|
||||
final existingId = prefs.getString(_keyLocalPlayerId);
|
||||
if (existingId != null && existingId.startsWith('ensemble_')) {
|
||||
_logger.log('Using existing player ID: $existingId');
|
||||
return existingId;
|
||||
/// Get stable device identifier that persists across storage wipes
|
||||
/// - Android: Uses ANDROID_ID (persists until factory reset)
|
||||
/// - iOS: Uses identifierForVendor (persists until app reinstall)
|
||||
static Future<String> _getStableDeviceId() async {
|
||||
if (_cachedStableDeviceId != null) {
|
||||
return _cachedStableDeviceId!;
|
||||
}
|
||||
|
||||
// Generate new ID on first access
|
||||
final playerId = 'ensemble_${_uuid.v4()}';
|
||||
await prefs.setString(_keyLocalPlayerId, playerId);
|
||||
_logger.log('Generated new player ID: $playerId');
|
||||
return playerId;
|
||||
final deviceInfo = DeviceInfoPlugin();
|
||||
|
||||
if (Platform.isAndroid) {
|
||||
final android = await deviceInfo.androidInfo;
|
||||
// ANDROID_ID is unique per device+user combo, persists across storage wipes
|
||||
// Only resets on factory reset
|
||||
_cachedStableDeviceId = android.id;
|
||||
} else if (Platform.isIOS) {
|
||||
final ios = await deviceInfo.iosInfo;
|
||||
// identifierForVendor persists across app updates but resets on reinstall
|
||||
_cachedStableDeviceId = ios.identifierForVendor ?? 'unknown_ios';
|
||||
} else {
|
||||
// Fallback for other platforms (web, desktop)
|
||||
_cachedStableDeviceId = 'unknown_platform';
|
||||
}
|
||||
|
||||
return _cachedStableDeviceId!;
|
||||
}
|
||||
|
||||
/// Detect if device is a tablet based on screen size
|
||||
/// Uses the standard 600dp threshold (shortest side >= 600 = tablet)
|
||||
static bool get isTablet {
|
||||
try {
|
||||
final view = ui.PlatformDispatcher.instance.views.first;
|
||||
final size = view.physicalSize / view.devicePixelRatio;
|
||||
return size.shortestSide >= 600;
|
||||
} catch (e) {
|
||||
_logger.log('Failed to detect device type: $e');
|
||||
return false; // Default to phone if detection fails
|
||||
}
|
||||
}
|
||||
|
||||
/// Get or generate a unique player ID for this device
|
||||
/// Format: ensemble_{username}_{deviceId} or ensemble_{deviceId}
|
||||
///
|
||||
/// Key behaviors:
|
||||
/// - Uses stable device ID that survives storage wipes
|
||||
/// - Includes MA username to support multiple devices per account
|
||||
/// - Regenerates if username changes (user logged in with different account)
|
||||
static Future<String> getOrCreateDevicePlayerId() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final stableDeviceId = await _getStableDeviceId();
|
||||
final maUsername = await SettingsService.getUsername();
|
||||
|
||||
// Generate expected ID based on current username and device
|
||||
// Use shorter device ID suffix (first 8 chars) to keep ID reasonable length
|
||||
final deviceIdSuffix = stableDeviceId.length > 8
|
||||
? stableDeviceId.substring(0, 8)
|
||||
: stableDeviceId;
|
||||
|
||||
final expectedId = maUsername != null && maUsername.isNotEmpty
|
||||
? 'ensemble_${maUsername}_$deviceIdSuffix'
|
||||
: 'ensemble_$deviceIdSuffix';
|
||||
|
||||
// Check if we already have the correct ID
|
||||
final existingId = prefs.getString(_keyLocalPlayerId);
|
||||
if (existingId == expectedId) {
|
||||
_logger.log('Using existing player ID: $expectedId');
|
||||
return expectedId;
|
||||
}
|
||||
|
||||
// ID needs to be updated (first login, username changed, or migration)
|
||||
if (existingId != null) {
|
||||
_logger.log('Updating player ID from $existingId to $expectedId');
|
||||
} else {
|
||||
_logger.log('Generated new player ID: $expectedId');
|
||||
}
|
||||
|
||||
await prefs.setString(_keyLocalPlayerId, expectedId);
|
||||
return expectedId;
|
||||
}
|
||||
|
||||
/// Adopt an existing player ID (used when claiming a ghost player)
|
||||
@@ -45,4 +108,12 @@ class DeviceIdService {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getString(_keyLocalPlayerId) == null;
|
||||
}
|
||||
|
||||
/// Force regeneration of player ID on next call
|
||||
/// Useful after login/logout to ensure ID matches current user
|
||||
static Future<void> invalidateCachedId() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove(_keyLocalPlayerId);
|
||||
_logger.log('Invalidated cached player ID');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,5 +82,9 @@ class HardwareVolumeService {
|
||||
} catch (e) {
|
||||
_logger.error('Failed to stop volume button listening', context: 'VolumeService', error: e);
|
||||
}
|
||||
|
||||
// Close StreamControllers to prevent memory leaks
|
||||
await _volumeUpController.close();
|
||||
await _volumeDownController.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -293,16 +293,10 @@ class MusicAssistantAPI {
|
||||
// Handle event
|
||||
final eventType = data['event'] as String?;
|
||||
if (eventType != null) {
|
||||
_logger.log('Event received: $eventType');
|
||||
|
||||
// Get the object_id (player_id for player events)
|
||||
final objectId = data['object_id'] as String?;
|
||||
final eventData = data['data'] as Map<String, dynamic>? ?? {};
|
||||
|
||||
// Debug: Log full data for player events
|
||||
if (eventType == 'player_added' || eventType == 'player_updated' || eventType == 'builtin_player') {
|
||||
_logger.log('Event data: ${jsonEncode(eventData)} (player_id: $objectId)');
|
||||
}
|
||||
|
||||
// Include object_id in event data so listeners can filter by player
|
||||
final enrichedData = {
|
||||
@@ -498,6 +492,227 @@ class MusicAssistantAPI {
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<MediaItem>> getRadioStations({
|
||||
int? limit,
|
||||
int? offset,
|
||||
bool? favoriteOnly,
|
||||
}) async {
|
||||
try {
|
||||
final response = await _sendCommand(
|
||||
'music/radios/library_items',
|
||||
args: {
|
||||
if (limit != null) 'limit': limit,
|
||||
if (offset != null) 'offset': offset,
|
||||
if (favoriteOnly != null) 'favorite': favoriteOnly,
|
||||
},
|
||||
);
|
||||
|
||||
final items = response['items'] as List<dynamic>? ?? response['result'] as List<dynamic>?;
|
||||
if (items == null) return [];
|
||||
|
||||
return items
|
||||
.map((item) => MediaItem.fromJson(item as Map<String, dynamic>))
|
||||
.toList();
|
||||
} catch (e) {
|
||||
_logger.log('Error getting radio stations: $e');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// Search for radio stations globally (across all providers like TuneIn)
|
||||
Future<List<MediaItem>> searchRadioStations(String query, {int limit = 25}) async {
|
||||
try {
|
||||
final response = await _sendCommand(
|
||||
'music/search',
|
||||
args: {
|
||||
'search_query': query,
|
||||
'media_types': ['radio'],
|
||||
'limit': limit,
|
||||
},
|
||||
);
|
||||
|
||||
final result = response['result'] as Map<String, dynamic>?;
|
||||
if (result == null) return [];
|
||||
|
||||
// Radio results might be under 'radios' or 'radio' key
|
||||
final radios = (result['radios'] as List<dynamic>?) ??
|
||||
(result['radio'] as List<dynamic>?) ??
|
||||
[];
|
||||
|
||||
return radios
|
||||
.map((item) => MediaItem.fromJson(item as Map<String, dynamic>))
|
||||
.toList();
|
||||
} catch (e) {
|
||||
_logger.log('Error searching radio stations: $e');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// ============ PODCASTS ============
|
||||
|
||||
/// Get all podcasts from the library
|
||||
Future<List<MediaItem>> getPodcasts({
|
||||
int? limit,
|
||||
int? offset,
|
||||
bool? favoriteOnly,
|
||||
}) async {
|
||||
try {
|
||||
final response = await _sendCommand(
|
||||
'music/podcasts/library_items',
|
||||
args: {
|
||||
if (limit != null) 'limit': limit,
|
||||
if (offset != null) 'offset': offset,
|
||||
if (favoriteOnly != null) 'favorite': favoriteOnly,
|
||||
},
|
||||
);
|
||||
|
||||
final items = response['items'] as List<dynamic>? ?? response['result'] as List<dynamic>?;
|
||||
if (items == null) return [];
|
||||
|
||||
return items
|
||||
.map((item) => MediaItem.fromJson(item as Map<String, dynamic>))
|
||||
.toList();
|
||||
} catch (e) {
|
||||
_logger.log('Error getting podcasts: $e');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// Get episodes for a specific podcast
|
||||
Future<List<MediaItem>> getPodcastEpisodes(String podcastId, {
|
||||
String? provider,
|
||||
int? limit,
|
||||
int? offset,
|
||||
}) async {
|
||||
try {
|
||||
final response = await _sendCommand(
|
||||
'music/podcasts/podcast_episodes',
|
||||
args: {
|
||||
'item_id': podcastId,
|
||||
if (provider != null) 'provider_instance_id_or_domain': provider,
|
||||
},
|
||||
);
|
||||
|
||||
final episodes = response['result'] as List<dynamic>?;
|
||||
if (episodes != null && episodes.isNotEmpty) {
|
||||
return episodes
|
||||
.map((item) => MediaItem.fromJson(item as Map<String, dynamic>))
|
||||
.toList();
|
||||
}
|
||||
|
||||
return [];
|
||||
} catch (e) {
|
||||
_logger.log('Error getting podcast episodes: $e');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// Get best available image URL for a podcast
|
||||
/// Falls back to first episode's image if podcast image is unavailable or low quality
|
||||
Future<String?> getPodcastCoverUrl(MediaItem podcast, {int size = 1024}) async {
|
||||
// First try the podcast's own image
|
||||
final podcastImage = getImageUrl(podcast, size: size);
|
||||
|
||||
// Check if podcast has images in metadata
|
||||
final images = podcast.metadata?['images'] as List<dynamic>?;
|
||||
if (images != null && images.isNotEmpty) {
|
||||
// Podcast has images, use them
|
||||
return podcastImage;
|
||||
}
|
||||
|
||||
// No podcast image, try to get first episode's image
|
||||
try {
|
||||
final episodes = await getPodcastEpisodes(
|
||||
podcast.itemId,
|
||||
provider: podcast.provider,
|
||||
);
|
||||
|
||||
if (episodes.isNotEmpty) {
|
||||
final firstEpisode = episodes.first;
|
||||
final episodeImage = getImageUrl(firstEpisode, size: size);
|
||||
if (episodeImage != null) {
|
||||
return episodeImage;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Fall through to return podcast image
|
||||
}
|
||||
|
||||
// Fall back to podcast image even if it might be low quality
|
||||
return podcastImage;
|
||||
}
|
||||
|
||||
/// Parse browse results into MediaItem episodes
|
||||
List<MediaItem> _parseBrowseEpisodes(List<dynamic> items) {
|
||||
final episodes = <MediaItem>[];
|
||||
for (final item in items) {
|
||||
if (item is Map<String, dynamic>) {
|
||||
final name = item['name'] as String? ??
|
||||
item['label'] as String? ??
|
||||
'Episode';
|
||||
final uri = item['uri'] as String? ?? item['path'] as String?;
|
||||
final itemId = item['item_id'] as String? ?? uri ?? '';
|
||||
final provider = item['provider'] as String? ?? 'library';
|
||||
|
||||
// Parse media type from string
|
||||
final mediaTypeStr = item['media_type'] as String?;
|
||||
MediaType mediaType = MediaType.track;
|
||||
if (mediaTypeStr != null) {
|
||||
mediaType = MediaType.values.firstWhere(
|
||||
(e) => e.name == mediaTypeStr || e.name == mediaTypeStr.toLowerCase(),
|
||||
orElse: () => MediaType.track,
|
||||
);
|
||||
}
|
||||
|
||||
// Get duration if available
|
||||
Duration? duration;
|
||||
final durationVal = item['duration'];
|
||||
if (durationVal is int) {
|
||||
duration = Duration(seconds: durationVal);
|
||||
} else if (durationVal is double) {
|
||||
duration = Duration(seconds: durationVal.toInt());
|
||||
}
|
||||
|
||||
episodes.add(MediaItem(
|
||||
itemId: itemId,
|
||||
provider: provider,
|
||||
name: name,
|
||||
uri: uri,
|
||||
metadata: item['metadata'] as Map<String, dynamic>?,
|
||||
mediaType: mediaType,
|
||||
duration: duration,
|
||||
));
|
||||
}
|
||||
}
|
||||
return episodes;
|
||||
}
|
||||
|
||||
/// Play a podcast episode
|
||||
Future<void> playPodcastEpisode(String playerId, MediaItem episode) async {
|
||||
try {
|
||||
// Try episode.uri first, then construct from itemId
|
||||
String uri;
|
||||
if (episode.uri != null && episode.uri!.isNotEmpty) {
|
||||
uri = episode.uri!;
|
||||
} else {
|
||||
// Construct URI based on media type
|
||||
uri = 'library://podcast_episode/${episode.itemId}';
|
||||
}
|
||||
|
||||
await _sendCommand(
|
||||
'player_queues/play_media',
|
||||
args: {
|
||||
'queue_id': playerId,
|
||||
'media': [uri],
|
||||
'option': 'replace',
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
_logger.log('Error playing podcast episode: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<Audiobook>> getAudiobooks({
|
||||
int? limit,
|
||||
int? offset,
|
||||
@@ -511,7 +726,6 @@ class MusicAssistantAPI {
|
||||
|
||||
// If specific libraries are enabled, use browse API for filtering
|
||||
if (enabledLibraries != null && enabledLibraries.isNotEmpty) {
|
||||
_logger.log('📚 Using browse API for library filtering (${enabledLibraries.length} libraries enabled)');
|
||||
return await _getAudiobooksFromBrowse(enabledLibraries, favoriteOnly: favoriteOnly);
|
||||
}
|
||||
|
||||
@@ -524,8 +738,6 @@ class MusicAssistantAPI {
|
||||
if (authorId != null) 'author_id': authorId,
|
||||
};
|
||||
|
||||
_logger.log('📚 Calling music/audiobooks/library_items with args: $args');
|
||||
|
||||
final response = await _sendCommand(
|
||||
'music/audiobooks/library_items',
|
||||
args: args,
|
||||
@@ -533,65 +745,21 @@ class MusicAssistantAPI {
|
||||
|
||||
// Check for error in response
|
||||
if (response.containsKey('error_code')) {
|
||||
_logger.log('📚 ERROR: ${response['error_code']} - ${response['details']}');
|
||||
return [];
|
||||
}
|
||||
|
||||
final items = response['result'] as List<dynamic>?;
|
||||
if (items == null) {
|
||||
_logger.log('📚 Audiobooks: result is null');
|
||||
return [];
|
||||
}
|
||||
|
||||
_logger.log('📚 Audiobooks: found ${items.length} items from API');
|
||||
|
||||
// Log first item's structure including metadata to find chapters/series
|
||||
if (items.isNotEmpty) {
|
||||
final firstItem = items.first as Map<String, dynamic>;
|
||||
_logger.log('📚 First item keys: ${firstItem.keys.toList()}');
|
||||
_logger.log('📚 First item name: ${firstItem['name']}, media_type: ${firstItem['media_type']}');
|
||||
|
||||
// Log metadata contents - this is where chapters/series info likely lives
|
||||
if (firstItem.containsKey('metadata')) {
|
||||
final metadata = firstItem['metadata'] as Map<String, dynamic>?;
|
||||
if (metadata != null) {
|
||||
_logger.log('📚 METADATA keys: ${metadata.keys.toList()}');
|
||||
for (final key in metadata.keys) {
|
||||
final value = metadata[key];
|
||||
if (value is List) {
|
||||
_logger.log('📚 metadata[$key] (List, ${value.length}): ${value.take(2)}');
|
||||
} else if (value is Map) {
|
||||
_logger.log('📚 metadata[$key] (Map): ${(value as Map).keys.toList()}');
|
||||
} else if (value != null) {
|
||||
_logger.log('📚 metadata[$key]: $value');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check for chapters at top level too
|
||||
if (firstItem.containsKey('chapters')) {
|
||||
_logger.log('📚 CHAPTERS at top level: ${firstItem['chapters']}');
|
||||
}
|
||||
}
|
||||
if (items == null) return [];
|
||||
|
||||
final audiobooks = <Audiobook>[];
|
||||
final parseErrors = <String>[];
|
||||
|
||||
for (int i = 0; i < items.length; i++) {
|
||||
try {
|
||||
final book = Audiobook.fromJson(items[i] as Map<String, dynamic>);
|
||||
audiobooks.add(book);
|
||||
} catch (e) {
|
||||
parseErrors.add('Item $i: $e');
|
||||
// Skip items that fail to parse
|
||||
}
|
||||
}
|
||||
|
||||
if (parseErrors.isNotEmpty) {
|
||||
_logger.log('📚 Parse errors (${parseErrors.length}): ${parseErrors.take(3).join(", ")}');
|
||||
}
|
||||
|
||||
_logger.log('📚 Successfully parsed ${audiobooks.length}/${items.length} audiobooks');
|
||||
return audiobooks;
|
||||
} catch (e, stack) {
|
||||
_logger.log('Error getting audiobooks: $e');
|
||||
@@ -691,6 +859,26 @@ class MusicAssistantAPI {
|
||||
}
|
||||
}
|
||||
|
||||
/// Play a radio station
|
||||
Future<void> playRadioStation(String playerId, MediaItem station) async {
|
||||
try {
|
||||
final uri = station.uri ?? 'library://radio/${station.itemId}';
|
||||
_logger.log('📻 Playing radio station: ${station.name} with URI: $uri');
|
||||
|
||||
await _sendCommand(
|
||||
'player_queues/play_media',
|
||||
args: {
|
||||
'queue_id': playerId,
|
||||
'media': [uri],
|
||||
'option': 'replace',
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
_logger.log('Error playing radio station: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// Get full audiobook details including chapters
|
||||
Future<Audiobook?> getAudiobookDetails(String provider, String itemId) async {
|
||||
try {
|
||||
@@ -1051,6 +1239,7 @@ class MusicAssistantAPI {
|
||||
);
|
||||
|
||||
final items = response['result'] as List<dynamic>?;
|
||||
_logger.log('📋 recently_played_items returned ${items?.length ?? 0} items');
|
||||
if (items == null || items.isEmpty) {
|
||||
_logger.log('⚠️ No recently played tracks found');
|
||||
return [];
|
||||
@@ -1060,6 +1249,8 @@ class MusicAssistantAPI {
|
||||
final trackUris = <String>[];
|
||||
for (final item in items) {
|
||||
final trackUri = (item as Map<String, dynamic>)['uri'] as String?;
|
||||
final name = (item as Map<String, dynamic>)['name'] as String?;
|
||||
_logger.log(' 📀 Track: $name');
|
||||
if (trackUri != null) {
|
||||
trackUris.add(trackUri);
|
||||
}
|
||||
@@ -1089,12 +1280,17 @@ class MusicAssistantAPI {
|
||||
|
||||
try {
|
||||
final fullTrack = trackResponse['result'] as Map<String, dynamic>?;
|
||||
final trackName = fullTrack?['name'] as String?;
|
||||
final albumData = fullTrack?['album'] as Map<String, dynamic>?;
|
||||
final albumUri = albumData?['uri'] as String?;
|
||||
final albumName = albumData?['name'] as String?;
|
||||
|
||||
if (albumUri != null && !seenAlbumUris.contains(albumUri)) {
|
||||
seenAlbumUris.add(albumUri);
|
||||
albumUris.add(albumUri);
|
||||
_logger.log(' 📀 Found album: $albumName from track: $trackName');
|
||||
} else if (albumUri == null) {
|
||||
_logger.log(' ⚠️ Track "$trackName" has no album');
|
||||
}
|
||||
} catch (_) {
|
||||
continue;
|
||||
@@ -1363,20 +1559,38 @@ class MusicAssistantAPI {
|
||||
/// Remove item from favorites
|
||||
/// Requires the library_item_id (the numeric ID in the MA library)
|
||||
Future<void> removeFromFavorites(String mediaType, int libraryItemId) async {
|
||||
try {
|
||||
_logger.log('Removing from favorites: mediaType=$mediaType, libraryItemId=$libraryItemId');
|
||||
await _sendCommand(
|
||||
'music/favorites/remove_item',
|
||||
args: {
|
||||
'media_type': mediaType,
|
||||
'library_item_id': libraryItemId,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
await _sendCommand(
|
||||
'music/favorites/remove_item',
|
||||
args: {
|
||||
'media_type': mediaType,
|
||||
'library_item_id': libraryItemId,
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
_logger.log('Error removing from favorites: $e');
|
||||
rethrow;
|
||||
}
|
||||
// Library
|
||||
/// Add item to library using URI format
|
||||
/// The item parameter should be a URI like "spotify://artist/4tZwfgrHOc3mvqYlEYSvVi"
|
||||
Future<void> addItemToLibrary(String mediaType, String itemId, String provider) async {
|
||||
final uri = '$provider://$mediaType/$itemId';
|
||||
await _sendCommand(
|
||||
'music/library/add_item',
|
||||
args: {
|
||||
'item': uri,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Remove item from library
|
||||
/// Requires the library_item_id (the numeric ID in the MA library)
|
||||
Future<void> removeItemFromLibrary(String mediaType, int libraryItemId) async {
|
||||
await _sendCommand(
|
||||
'music/library/remove_item',
|
||||
args: {
|
||||
'media_type': mediaType,
|
||||
'library_item_id': libraryItemId,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Search
|
||||
@@ -1399,7 +1613,7 @@ class MusicAssistantAPI {
|
||||
|
||||
final result = searchResponse['result'] as Map<String, dynamic>?;
|
||||
if (result == null) {
|
||||
return <String, List<MediaItem>>{'artists': [], 'albums': [], 'tracks': []};
|
||||
return <String, List<MediaItem>>{'artists': [], 'albums': [], 'tracks': [], 'playlists': [], 'audiobooks': [], 'radios': []};
|
||||
}
|
||||
|
||||
// Parse results from the search response
|
||||
@@ -1418,6 +1632,26 @@ class MusicAssistantAPI {
|
||||
.toList() ??
|
||||
[];
|
||||
|
||||
final playlists = (result['playlists'] as List<dynamic>?)
|
||||
?.map((item) => Playlist.fromJson(item as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
[];
|
||||
|
||||
final audiobooks = (result['audiobooks'] as List<dynamic>?)
|
||||
?.map((item) => Audiobook.fromJson(item as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
[];
|
||||
|
||||
final radios = (result['radios'] as List<dynamic>?)
|
||||
?.map((item) => MediaItem.fromJson(item as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
[];
|
||||
|
||||
final podcasts = (result['podcasts'] as List<dynamic>?)
|
||||
?.map((item) => MediaItem.fromJson(item as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
[];
|
||||
|
||||
// Deduplicate results by name
|
||||
// MA returns both library items and provider items for the same content
|
||||
// Prefer library items (provider='library') as they have all provider mappings
|
||||
@@ -1425,18 +1659,57 @@ class MusicAssistantAPI {
|
||||
'artists': _deduplicateResults(artists),
|
||||
'albums': _deduplicateResults(albums),
|
||||
'tracks': _deduplicateResults(tracks),
|
||||
'playlists': _deduplicateResults(playlists),
|
||||
'audiobooks': _deduplicateResults(audiobooks),
|
||||
'radios': _deduplicateResults(radios),
|
||||
'podcasts': _deduplicateResults(podcasts),
|
||||
};
|
||||
} catch (e) {
|
||||
_logger.log('Error searching: $e');
|
||||
return <String, List<MediaItem>>{'artists': [], 'albums': [], 'tracks': []};
|
||||
return <String, List<MediaItem>>{'artists': [], 'albums': [], 'tracks': [], 'playlists': [], 'audiobooks': [], 'radios': [], 'podcasts': []};
|
||||
}
|
||||
},
|
||||
).catchError((e) {
|
||||
_logger.log('Error searching after retries: $e');
|
||||
return <String, List<MediaItem>>{'artists': [], 'albums': [], 'tracks': []};
|
||||
return <String, List<MediaItem>>{'artists': [], 'albums': [], 'tracks': [], 'playlists': [], 'audiobooks': [], 'radios': [], 'podcasts': []};
|
||||
});
|
||||
}
|
||||
|
||||
/// Search for podcasts globally (across all providers)
|
||||
Future<List<MediaItem>> searchPodcasts(String query, {int limit = 25}) async {
|
||||
try {
|
||||
_logger.log('🎙️ Searching podcasts for: $query');
|
||||
final response = await _sendCommand(
|
||||
'music/search',
|
||||
args: {
|
||||
'search_query': query,
|
||||
'media_types': ['podcast'],
|
||||
'limit': limit,
|
||||
},
|
||||
);
|
||||
|
||||
final result = response['result'] as Map<String, dynamic>?;
|
||||
if (result == null) {
|
||||
_logger.log('🎙️ Podcast search: no result');
|
||||
return [];
|
||||
}
|
||||
|
||||
// Podcast results might be under 'podcasts' or 'podcast' key
|
||||
final podcasts = (result['podcasts'] as List<dynamic>?) ??
|
||||
(result['podcast'] as List<dynamic>?) ??
|
||||
[];
|
||||
|
||||
_logger.log('🎙️ Podcast search found ${podcasts.length} results');
|
||||
|
||||
return podcasts
|
||||
.map((item) => MediaItem.fromJson(item as Map<String, dynamic>))
|
||||
.toList();
|
||||
} catch (e) {
|
||||
_logger.log('🎙️ Error searching podcasts: $e');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// Deduplicate search results by name (case-insensitive)
|
||||
/// Prefers library items (provider='library') over provider-specific items
|
||||
/// since library items have complete provider mappings
|
||||
@@ -1516,6 +1789,7 @@ class MusicAssistantAPI {
|
||||
currentIndex = queueResult['current_index'] as int?;
|
||||
shuffleEnabled = queueResult['shuffle_enabled'] as bool?;
|
||||
repeatMode = queueResult['repeat_mode'] as String?;
|
||||
_logger.log('🔀 Queue metadata: shuffle_enabled=$shuffleEnabled, repeat_mode=$repeatMode');
|
||||
|
||||
final currentItemData = queueResult['current_item'] as Map<String, dynamic>?;
|
||||
final currentItemName = currentItemData?['name'] as String?;
|
||||
@@ -1602,6 +1876,105 @@ class MusicAssistantAPI {
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a single track to the queue without starting playback
|
||||
Future<void> addTrackToQueue(String playerId, Track track) async {
|
||||
try {
|
||||
final uri = _buildTrackUri(track);
|
||||
|
||||
await _sendCommand(
|
||||
'player_queues/play_media',
|
||||
args: {
|
||||
'queue_id': playerId,
|
||||
'media': [uri],
|
||||
'option': 'add', // Add to queue without starting
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
_logger.log('Error adding track to queue: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// Play album on player
|
||||
Future<void> playAlbum(String playerId, Album album) async {
|
||||
try {
|
||||
final uri = album.uri ?? 'library://album/${album.itemId}';
|
||||
_logger.log('💿 Playing album: ${album.name} with URI: $uri');
|
||||
|
||||
await _sendCommand(
|
||||
'player_queues/play_media',
|
||||
args: {
|
||||
'queue_id': playerId,
|
||||
'media': [uri],
|
||||
'option': 'replace',
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
_logger.log('Error playing album: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// Add album tracks to queue
|
||||
Future<void> addAlbumToQueue(String playerId, Album album) async {
|
||||
try {
|
||||
final uri = album.uri ?? 'library://album/${album.itemId}';
|
||||
_logger.log('💿 Adding album to queue: ${album.name} with URI: $uri');
|
||||
|
||||
await _sendCommand(
|
||||
'player_queues/play_media',
|
||||
args: {
|
||||
'queue_id': playerId,
|
||||
'media': [uri],
|
||||
'option': 'add',
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
_logger.log('Error adding album to queue: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// Add artist tracks to queue
|
||||
Future<void> addArtistToQueue(String playerId, Artist artist) async {
|
||||
try {
|
||||
final uri = artist.uri ?? 'library://artist/${artist.itemId}';
|
||||
_logger.log('🎤 Adding artist to queue: ${artist.name} with URI: $uri');
|
||||
|
||||
await _sendCommand(
|
||||
'player_queues/play_media',
|
||||
args: {
|
||||
'queue_id': playerId,
|
||||
'media': [uri],
|
||||
'option': 'add',
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
_logger.log('Error adding artist to queue: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// Play playlist on player
|
||||
Future<void> playPlaylist(String playerId, Playlist playlist) async {
|
||||
try {
|
||||
final uri = playlist.uri ?? 'library://playlist/${playlist.itemId}';
|
||||
_logger.log('📝 Playing playlist: ${playlist.name} with URI: $uri');
|
||||
|
||||
await _sendCommand(
|
||||
'player_queues/play_media',
|
||||
args: {
|
||||
'queue_id': playerId,
|
||||
'media': [uri],
|
||||
'option': 'replace',
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
_logger.log('Error playing playlist: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// Play multiple tracks via queue
|
||||
/// If clearQueue is true, replaces the queue (default behavior)
|
||||
/// If startIndex is provided, only tracks from that index onwards will be queued
|
||||
@@ -2036,11 +2409,11 @@ class MusicAssistantAPI {
|
||||
}
|
||||
|
||||
/// Toggle shuffle mode for queue
|
||||
Future<void> toggleShuffle(String queueId) async {
|
||||
Future<void> toggleShuffle(String queueId, bool shuffleEnabled) async {
|
||||
try {
|
||||
await _sendCommand(
|
||||
'player_queues/shuffle',
|
||||
args: {'queue_id': queueId},
|
||||
args: {'queue_id': queueId, 'shuffle_enabled': shuffleEnabled},
|
||||
);
|
||||
} catch (e) {
|
||||
_logger.log('Error toggling shuffle: $e');
|
||||
@@ -2107,6 +2480,22 @@ class MusicAssistantAPI {
|
||||
return _eventStreams['player_added']!.stream;
|
||||
}
|
||||
|
||||
/// Stream of media_item_added events (for refreshing library when items are added)
|
||||
Stream<Map<String, dynamic>> get mediaItemAddedEvents {
|
||||
if (!_eventStreams.containsKey('media_item_added')) {
|
||||
_eventStreams['media_item_added'] = StreamController<Map<String, dynamic>>.broadcast();
|
||||
}
|
||||
return _eventStreams['media_item_added']!.stream;
|
||||
}
|
||||
|
||||
/// Stream of media_item_deleted events (for refreshing library when items are removed)
|
||||
Stream<Map<String, dynamic>> get mediaItemDeletedEvents {
|
||||
if (!_eventStreams.containsKey('media_item_deleted')) {
|
||||
_eventStreams['media_item_deleted'] = StreamController<Map<String, dynamic>>.broadcast();
|
||||
}
|
||||
return _eventStreams['media_item_deleted']!.stream;
|
||||
}
|
||||
|
||||
/// Register this device as a player with retry logic
|
||||
/// CRITICAL: This creates a player config in MA's settings.json
|
||||
/// The server expects: player_id and player_name
|
||||
@@ -2508,6 +2897,7 @@ class MusicAssistantAPI {
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.log('⚠️ Error parsing stream URI "$uri": $e');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2587,6 +2977,57 @@ class MusicAssistantAPI {
|
||||
return '$baseUrl/imageproxy?provider=${Uri.encodeComponent(provider ?? "")}&size=$size&fmt=jpeg&path=${Uri.encodeComponent(imagePath)}';
|
||||
}
|
||||
|
||||
// ==================== iTunes Artwork Lookup ====================
|
||||
|
||||
/// Search iTunes for a podcast and return high-res artwork URL
|
||||
/// Returns null if not found or on error
|
||||
Future<String?> getITunesPodcastArtwork(String podcastName) async {
|
||||
try {
|
||||
final searchTerm = Uri.encodeComponent(podcastName);
|
||||
final url = 'https://itunes.apple.com/search?term=$searchTerm&entity=podcast&limit=1';
|
||||
|
||||
final client = HttpClient();
|
||||
client.connectionTimeout = const Duration(seconds: 10);
|
||||
|
||||
final request = await client.getUrl(Uri.parse(url));
|
||||
final response = await request.close();
|
||||
|
||||
if (response.statusCode != 200) {
|
||||
_logger.log('🎨 iTunes search failed for "$podcastName": ${response.statusCode}');
|
||||
return null;
|
||||
}
|
||||
|
||||
final body = await response.transform(utf8.decoder).join();
|
||||
final json = jsonDecode(body) as Map<String, dynamic>;
|
||||
|
||||
final results = json['results'] as List<dynamic>?;
|
||||
if (results == null || results.isEmpty) {
|
||||
_logger.log('🎨 No iTunes results for "$podcastName"');
|
||||
return null;
|
||||
}
|
||||
|
||||
final podcast = results.first as Map<String, dynamic>;
|
||||
var artworkUrl = podcast['artworkUrl600'] as String?;
|
||||
|
||||
if (artworkUrl == null) {
|
||||
artworkUrl = podcast['artworkUrl100'] as String?;
|
||||
}
|
||||
|
||||
if (artworkUrl != null) {
|
||||
// Use 800x800 - good quality without being excessive (was 1400x1400)
|
||||
artworkUrl = artworkUrl
|
||||
.replaceAll('600x600', '800x800')
|
||||
.replaceAll('100x100', '800x800');
|
||||
_logger.log('🎨 Found iTunes artwork for "$podcastName": $artworkUrl');
|
||||
}
|
||||
|
||||
return artworkUrl;
|
||||
} catch (e) {
|
||||
_logger.log('🎨 iTunes lookup error for "$podcastName": $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== Authentication Methods ====================
|
||||
|
||||
/// Authenticate the WebSocket session with a token
|
||||
@@ -2876,6 +3317,17 @@ class MusicAssistantAPI {
|
||||
_updateConnectionState(MAConnectionState.disconnected);
|
||||
await _channel?.sink.close();
|
||||
_channel = null;
|
||||
// Complete all pending requests with an error before clearing
|
||||
_cancelPendingRequests('Connection disconnected');
|
||||
}
|
||||
|
||||
/// Cancel all pending requests with an error message
|
||||
void _cancelPendingRequests(String reason) {
|
||||
for (final entry in _pendingRequests.entries) {
|
||||
if (!entry.value.isCompleted) {
|
||||
entry.value.completeError(Exception(reason));
|
||||
}
|
||||
}
|
||||
_pendingRequests.clear();
|
||||
}
|
||||
|
||||
|
||||
@@ -83,6 +83,11 @@ class PcmAudioPlayer {
|
||||
// Reduced from 8000 to 5000 frames (~104ms vs ~166ms) for faster response
|
||||
static const int _feedThreshold = 5000;
|
||||
|
||||
// Maximum buffer size to prevent memory overflow (~10 seconds of audio)
|
||||
// At 48kHz stereo 16-bit: 192KB/sec, so ~2MB for 10 seconds
|
||||
// Each chunk is ~4KB, so max ~500 chunks
|
||||
static const int _maxBufferChunks = 500;
|
||||
|
||||
// Stats
|
||||
int _framesPlayed = 0;
|
||||
int _bytesPlayed = 0;
|
||||
@@ -201,6 +206,16 @@ class PcmAudioPlayer {
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Safely add audio data to buffer with overflow protection
|
||||
void _addToBuffer(Uint8List audioData) {
|
||||
// If buffer is full, drop oldest chunks to make room
|
||||
while (_audioBuffer.length >= _maxBufferChunks) {
|
||||
_audioBuffer.removeAt(0);
|
||||
_logger.log('⚠️ PcmAudioPlayer: Buffer overflow - dropping oldest chunk');
|
||||
}
|
||||
_audioBuffer.add(audioData);
|
||||
}
|
||||
|
||||
/// Handle incoming audio data from the stream
|
||||
void _onAudioData(Uint8List audioData) {
|
||||
// Ignore data if in error state
|
||||
@@ -215,7 +230,7 @@ class PcmAudioPlayer {
|
||||
if (_state == PcmPlayerState.paused && !_isAutoRecovering) {
|
||||
_logger.log('PcmAudioPlayer: Audio arriving while paused - initiating auto-recovery');
|
||||
_isAutoRecovering = true;
|
||||
_audioBuffer.add(audioData);
|
||||
_addToBuffer(audioData);
|
||||
|
||||
// Trigger async recovery
|
||||
_autoRecoverFromPause();
|
||||
@@ -224,7 +239,7 @@ class PcmAudioPlayer {
|
||||
|
||||
// If already recovering or in transitional state, buffer the data
|
||||
if (_isAutoRecovering) {
|
||||
_audioBuffer.add(audioData);
|
||||
_addToBuffer(audioData);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -232,8 +247,8 @@ class PcmAudioPlayer {
|
||||
return;
|
||||
}
|
||||
|
||||
// Add to buffer
|
||||
_audioBuffer.add(audioData);
|
||||
// Add to buffer with overflow protection
|
||||
_addToBuffer(audioData);
|
||||
|
||||
// Start playback if not already started
|
||||
if (!_isStarted && _state == PcmPlayerState.ready) {
|
||||
|
||||
@@ -24,6 +24,10 @@ class PositionTracker {
|
||||
double _anchorPosition = 0.0; // Position in seconds at anchor time
|
||||
DateTime _anchorTime = DateTime.now(); // When we set the anchor
|
||||
|
||||
// Maximum time to interpolate from a stale anchor before capping
|
||||
// After this, we stop adding time to prevent indefinite drift
|
||||
static const Duration _maxAnchorAge = Duration(seconds: 30);
|
||||
|
||||
// Interpolation timer
|
||||
Timer? _interpolationTimer;
|
||||
|
||||
@@ -43,7 +47,13 @@ class PositionTracker {
|
||||
}
|
||||
|
||||
final now = DateTime.now();
|
||||
final elapsed = now.difference(_anchorTime).inMilliseconds / 1000.0;
|
||||
final anchorAge = now.difference(_anchorTime);
|
||||
|
||||
// Cap interpolation at max anchor age to prevent indefinite drift
|
||||
// If anchor is stale, return last known position (anchor + max age)
|
||||
final elapsed = anchorAge > _maxAnchorAge
|
||||
? _maxAnchorAge.inMilliseconds / 1000.0
|
||||
: anchorAge.inMilliseconds / 1000.0;
|
||||
final interpolated = _anchorPosition + elapsed;
|
||||
|
||||
// Cap at duration to prevent overflow
|
||||
@@ -61,7 +71,12 @@ class PositionTracker {
|
||||
}
|
||||
|
||||
final now = DateTime.now();
|
||||
final elapsed = now.difference(_anchorTime).inMilliseconds / 1000.0;
|
||||
final anchorAge = now.difference(_anchorTime);
|
||||
|
||||
// Cap interpolation at max anchor age to prevent indefinite drift
|
||||
final elapsed = anchorAge > _maxAnchorAge
|
||||
? _maxAnchorAge.inMilliseconds / 1000.0
|
||||
: anchorAge.inMilliseconds / 1000.0;
|
||||
final interpolated = _anchorPosition + elapsed;
|
||||
|
||||
// Cap at duration
|
||||
|
||||
@@ -151,7 +151,10 @@ class RecentlyPlayedService {
|
||||
if (item.metadata != null) {
|
||||
try {
|
||||
metadata = jsonDecode(item.metadata!) as Map<String, dynamic>;
|
||||
} catch (_) {}
|
||||
} catch (e) {
|
||||
// Corrupted metadata JSON - log and continue with null metadata
|
||||
_logger.log('⚠️ Error parsing album metadata for ${item.mediaId}: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// Build metadata with images if available (for instant artwork display)
|
||||
@@ -203,7 +206,10 @@ class RecentlyPlayedService {
|
||||
if (item.metadata != null) {
|
||||
try {
|
||||
metadata = jsonDecode(item.metadata!) as Map<String, dynamic>;
|
||||
} catch (_) {}
|
||||
} catch (e) {
|
||||
// Corrupted metadata JSON - log and continue with null metadata
|
||||
_logger.log('⚠️ Error parsing audiobook metadata for ${item.mediaId}: $e');
|
||||
}
|
||||
}
|
||||
|
||||
audiobooks.add(Audiobook(
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'dart:convert';
|
||||
|
||||
/// Service for securely storing sensitive data like passwords and tokens.
|
||||
/// Uses platform-specific secure storage (Keychain on iOS, EncryptedSharedPreferences on Android).
|
||||
class SecureStorageService {
|
||||
static const _storage = FlutterSecureStorage(
|
||||
aOptions: AndroidOptions(
|
||||
encryptedSharedPreferences: true,
|
||||
),
|
||||
);
|
||||
|
||||
// Keys for secure storage
|
||||
static const String _keyAuthToken = 'secure_auth_token';
|
||||
static const String _keyMaAuthToken = 'secure_ma_auth_token';
|
||||
static const String _keyAuthCredentials = 'secure_auth_credentials';
|
||||
static const String _keyPassword = 'secure_password';
|
||||
static const String _keyAbsApiToken = 'secure_abs_api_token';
|
||||
|
||||
// Auth Token (for stream requests)
|
||||
static Future<String?> getAuthToken() async {
|
||||
return await _storage.read(key: _keyAuthToken);
|
||||
}
|
||||
|
||||
static Future<void> setAuthToken(String? token) async {
|
||||
if (token == null || token.isEmpty) {
|
||||
await _storage.delete(key: _keyAuthToken);
|
||||
} else {
|
||||
await _storage.write(key: _keyAuthToken, value: token);
|
||||
}
|
||||
}
|
||||
|
||||
// Music Assistant Native Auth Token (long-lived token)
|
||||
static Future<String?> getMaAuthToken() async {
|
||||
return await _storage.read(key: _keyMaAuthToken);
|
||||
}
|
||||
|
||||
static Future<void> setMaAuthToken(String? token) async {
|
||||
if (token == null || token.isEmpty) {
|
||||
await _storage.delete(key: _keyMaAuthToken);
|
||||
} else {
|
||||
await _storage.write(key: _keyMaAuthToken, value: token);
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> clearMaAuthToken() async {
|
||||
await _storage.delete(key: _keyMaAuthToken);
|
||||
}
|
||||
|
||||
// Auth Credentials (serialized auth strategy credentials)
|
||||
static Future<Map<String, dynamic>?> getAuthCredentials() async {
|
||||
final json = await _storage.read(key: _keyAuthCredentials);
|
||||
if (json == null) return null;
|
||||
try {
|
||||
return jsonDecode(json) as Map<String, dynamic>;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> setAuthCredentials(Map<String, dynamic> credentials) async {
|
||||
await _storage.write(key: _keyAuthCredentials, value: jsonEncode(credentials));
|
||||
}
|
||||
|
||||
static Future<void> clearAuthCredentials() async {
|
||||
await _storage.delete(key: _keyAuthCredentials);
|
||||
}
|
||||
|
||||
// Password
|
||||
static Future<String?> getPassword() async {
|
||||
return await _storage.read(key: _keyPassword);
|
||||
}
|
||||
|
||||
static Future<void> setPassword(String? password) async {
|
||||
if (password == null || password.isEmpty) {
|
||||
await _storage.delete(key: _keyPassword);
|
||||
} else {
|
||||
await _storage.write(key: _keyPassword, value: password);
|
||||
}
|
||||
}
|
||||
|
||||
// Audiobookshelf API Token
|
||||
static Future<String?> getAbsApiToken() async {
|
||||
return await _storage.read(key: _keyAbsApiToken);
|
||||
}
|
||||
|
||||
static Future<void> setAbsApiToken(String? token) async {
|
||||
if (token == null || token.isEmpty) {
|
||||
await _storage.delete(key: _keyAbsApiToken);
|
||||
} else {
|
||||
await _storage.write(key: _keyAbsApiToken, value: token);
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear all secure storage (used during logout)
|
||||
static Future<void> clearAll() async {
|
||||
await _storage.deleteAll();
|
||||
}
|
||||
|
||||
/// Migrate credentials from SharedPreferences to secure storage.
|
||||
/// Call this once during app upgrade to migrate existing users.
|
||||
static Future<void> migrateFromSharedPreferences() async {
|
||||
// Import SharedPreferences for migration
|
||||
final SharedPreferences prefs = await SharedPreferences.getInstance();
|
||||
|
||||
// Migrate auth token
|
||||
final authToken = prefs.getString('auth_token');
|
||||
if (authToken != null && authToken.isNotEmpty) {
|
||||
await setAuthToken(authToken);
|
||||
await prefs.remove('auth_token');
|
||||
}
|
||||
|
||||
// Migrate MA auth token
|
||||
final maAuthToken = prefs.getString('ma_auth_token');
|
||||
if (maAuthToken != null && maAuthToken.isNotEmpty) {
|
||||
await setMaAuthToken(maAuthToken);
|
||||
await prefs.remove('ma_auth_token');
|
||||
}
|
||||
|
||||
// Migrate auth credentials
|
||||
final authCredentials = prefs.getString('auth_credentials');
|
||||
if (authCredentials != null && authCredentials.isNotEmpty) {
|
||||
try {
|
||||
final decoded = jsonDecode(authCredentials) as Map<String, dynamic>;
|
||||
await setAuthCredentials(decoded);
|
||||
await prefs.remove('auth_credentials');
|
||||
} catch (_) {
|
||||
// Invalid JSON, just remove it
|
||||
await prefs.remove('auth_credentials');
|
||||
}
|
||||
}
|
||||
|
||||
// Migrate password
|
||||
final password = prefs.getString('password');
|
||||
if (password != null && password.isNotEmpty) {
|
||||
await setPassword(password);
|
||||
await prefs.remove('password');
|
||||
}
|
||||
|
||||
// Migrate ABS API token
|
||||
final absApiToken = prefs.getString('abs_api_token');
|
||||
if (absApiToken != null && absApiToken.isNotEmpty) {
|
||||
await setAbsApiToken(absApiToken);
|
||||
await prefs.remove('abs_api_token');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,9 @@ class SendspinService {
|
||||
// Auth token for proxy authentication (MA 2.7.1+)
|
||||
String? _authToken;
|
||||
|
||||
// Connection deduplication guard - prevents multiple concurrent auth attempts
|
||||
Completer<bool>? _connectionInProgress;
|
||||
|
||||
SendspinService(this.serverUrl);
|
||||
|
||||
/// Set the MA auth token for proxy authentication
|
||||
@@ -100,6 +103,13 @@ class SendspinService {
|
||||
if (_isDisposed) return false;
|
||||
if (_state == SendspinConnectionState.connected) return true;
|
||||
|
||||
// Deduplicate concurrent connection attempts
|
||||
if (_connectionInProgress != null) {
|
||||
_logger.log('Sendspin: Connection already in progress, waiting...');
|
||||
return _connectionInProgress!.future;
|
||||
}
|
||||
_connectionInProgress = Completer<bool>();
|
||||
|
||||
_updateState(SendspinConnectionState.connecting);
|
||||
|
||||
try {
|
||||
@@ -126,13 +136,19 @@ class SendspinService {
|
||||
if (!connected) {
|
||||
_logger.log('Sendspin: External proxy connection failed');
|
||||
_updateState(SendspinConnectionState.error);
|
||||
_connectionInProgress?.complete(false);
|
||||
_connectionInProgress = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
_connectionInProgress?.complete(true);
|
||||
_connectionInProgress = null;
|
||||
return true;
|
||||
} catch (e) {
|
||||
_logger.log('Sendspin: Connection error: $e');
|
||||
_updateState(SendspinConnectionState.error);
|
||||
_connectionInProgress?.complete(false);
|
||||
_connectionInProgress = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -142,6 +158,13 @@ class SendspinService {
|
||||
if (_isDisposed) return false;
|
||||
if (_state == SendspinConnectionState.connected) return true;
|
||||
|
||||
// Deduplicate concurrent connection attempts
|
||||
if (_connectionInProgress != null) {
|
||||
_logger.log('Sendspin: Connection already in progress, waiting...');
|
||||
return _connectionInProgress!.future;
|
||||
}
|
||||
_connectionInProgress = Completer<bool>();
|
||||
|
||||
_updateState(SendspinConnectionState.connecting);
|
||||
|
||||
try {
|
||||
@@ -154,13 +177,19 @@ class SendspinService {
|
||||
|
||||
if (!connected) {
|
||||
_updateState(SendspinConnectionState.error);
|
||||
_connectionInProgress?.complete(false);
|
||||
_connectionInProgress = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
_connectionInProgress?.complete(true);
|
||||
_connectionInProgress = null;
|
||||
return true;
|
||||
} catch (e) {
|
||||
_logger.log('Sendspin: Connection error: $e');
|
||||
_updateState(SendspinConnectionState.error);
|
||||
_connectionInProgress?.complete(false);
|
||||
_connectionInProgress = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'dart:convert';
|
||||
import 'device_id_service.dart';
|
||||
import 'secure_storage_service.dart';
|
||||
|
||||
class SettingsService {
|
||||
static const String _keyServerUrl = 'server_url';
|
||||
@@ -33,6 +35,7 @@ class SettingsService {
|
||||
static const String _keyShowFavoriteAlbums = 'show_favorite_albums';
|
||||
static const String _keyShowFavoriteArtists = 'show_favorite_artists';
|
||||
static const String _keyShowFavoriteTracks = 'show_favorite_tracks';
|
||||
static const String _keyShowOnlyArtistsWithAlbums = 'show_only_artists_with_albums'; // Library artists filter
|
||||
static const String _keyHomeRowOrder = 'home_row_order'; // JSON list of row IDs
|
||||
|
||||
// Default row order
|
||||
@@ -64,6 +67,8 @@ class SettingsService {
|
||||
static const String _keyLibrarySeriesViewMode = 'library_series_view_mode'; // 'grid2', 'grid3', 'list'
|
||||
static const String _keySeriesAudiobooksSortOrder = 'series_audiobooks_sort_order'; // 'alpha' or 'year'
|
||||
static const String _keySeriesAudiobooksViewMode = 'series_audiobooks_view_mode'; // 'grid2', 'grid3', 'list'
|
||||
static const String _keyLibraryRadioViewMode = 'library_radio_view_mode'; // 'grid2', 'grid3', 'list'
|
||||
static const String _keyLibraryPodcastsViewMode = 'library_podcasts_view_mode'; // 'grid2', 'grid3', 'list'
|
||||
|
||||
// Audiobookshelf Direct Integration Settings
|
||||
static const String _keyAbsServerUrl = 'abs_server_url';
|
||||
@@ -74,6 +79,14 @@ class SettingsService {
|
||||
static const String _keyEnabledAbsLibraries = 'enabled_abs_libraries'; // JSON list of library paths
|
||||
static const String _keyDiscoveredAbsLibraries = 'discovered_abs_libraries'; // JSON list of {path, name}
|
||||
|
||||
// Hint System Settings
|
||||
static const String _keyShowHints = 'show_hints'; // Master toggle for hints
|
||||
static const String _keyHasUsedPlayerReveal = 'has_used_player_reveal'; // Track if user has pulled to reveal players
|
||||
static const String _keyHasCompletedOnboarding = 'has_completed_onboarding'; // Track if user has seen welcome screen
|
||||
|
||||
// Podcast Cover Cache (iTunes URLs for high-res artwork)
|
||||
static const String _keyPodcastCoverCache = 'podcast_cover_cache';
|
||||
|
||||
static Future<String?> getServerUrl() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getString(_keyServerUrl);
|
||||
@@ -121,66 +134,44 @@ class SettingsService {
|
||||
}
|
||||
}
|
||||
|
||||
// Get authentication token for stream requests
|
||||
// Get authentication token for stream requests (securely stored)
|
||||
static Future<String?> getAuthToken() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getString(_keyAuthToken);
|
||||
return await SecureStorageService.getAuthToken();
|
||||
}
|
||||
|
||||
// Set authentication token for stream requests
|
||||
// Set authentication token for stream requests (securely stored)
|
||||
static Future<void> setAuthToken(String? token) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
if (token == null || token.isEmpty) {
|
||||
await prefs.remove(_keyAuthToken);
|
||||
} else {
|
||||
await prefs.setString(_keyAuthToken, token);
|
||||
}
|
||||
await SecureStorageService.setAuthToken(token);
|
||||
}
|
||||
|
||||
// Get Music Assistant native auth token (long-lived token)
|
||||
// Get Music Assistant native auth token (long-lived token, securely stored)
|
||||
static Future<String?> getMaAuthToken() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getString(_keyMaAuthToken);
|
||||
return await SecureStorageService.getMaAuthToken();
|
||||
}
|
||||
|
||||
// Set Music Assistant native auth token (long-lived token)
|
||||
// Set Music Assistant native auth token (long-lived token, securely stored)
|
||||
static Future<void> setMaAuthToken(String? token) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
if (token == null || token.isEmpty) {
|
||||
await prefs.remove(_keyMaAuthToken);
|
||||
} else {
|
||||
await prefs.setString(_keyMaAuthToken, token);
|
||||
}
|
||||
await SecureStorageService.setMaAuthToken(token);
|
||||
}
|
||||
|
||||
// Clear Music Assistant native auth token
|
||||
static Future<void> clearMaAuthToken() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove(_keyMaAuthToken);
|
||||
await SecureStorageService.clearMaAuthToken();
|
||||
}
|
||||
|
||||
// Get authentication credentials (serialized auth strategy credentials)
|
||||
// Get authentication credentials (serialized auth strategy credentials, securely stored)
|
||||
static Future<Map<String, dynamic>?> getAuthCredentials() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final json = prefs.getString(_keyAuthCredentials);
|
||||
if (json == null) return null;
|
||||
try {
|
||||
return jsonDecode(json) as Map<String, dynamic>;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
return await SecureStorageService.getAuthCredentials();
|
||||
}
|
||||
|
||||
// Set authentication credentials (serialized auth strategy credentials)
|
||||
// Set authentication credentials (serialized auth strategy credentials, securely stored)
|
||||
static Future<void> setAuthCredentials(Map<String, dynamic> credentials) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyAuthCredentials, jsonEncode(credentials));
|
||||
await SecureStorageService.setAuthCredentials(credentials);
|
||||
}
|
||||
|
||||
// Clear authentication credentials
|
||||
static Future<void> clearAuthCredentials() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove(_keyAuthCredentials);
|
||||
await SecureStorageService.clearAuthCredentials();
|
||||
}
|
||||
|
||||
// Get username for authentication
|
||||
@@ -199,20 +190,14 @@ class SettingsService {
|
||||
}
|
||||
}
|
||||
|
||||
// Get password for authentication
|
||||
// Get password for authentication (securely stored)
|
||||
static Future<String?> getPassword() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getString(_keyPassword);
|
||||
return await SecureStorageService.getPassword();
|
||||
}
|
||||
|
||||
// Set password for authentication
|
||||
// Set password for authentication (securely stored)
|
||||
static Future<void> setPassword(String? password) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
if (password == null || password.isEmpty) {
|
||||
await prefs.remove(_keyPassword);
|
||||
} else {
|
||||
await prefs.setString(_keyPassword, password);
|
||||
}
|
||||
await SecureStorageService.setPassword(password);
|
||||
}
|
||||
|
||||
// Get built-in player ID (persistent UUID for this device)
|
||||
@@ -389,18 +374,27 @@ class SettingsService {
|
||||
}
|
||||
|
||||
// Helper to create player name with possessive apostrophe
|
||||
// Automatically detects Phone vs Tablet based on screen size
|
||||
static String _makePlayerName(String ownerName) {
|
||||
// Handle possessive: "Chris" -> "Chris' Phone", "Mom" -> "Mom's Phone"
|
||||
final deviceType = DeviceIdService.isTablet ? 'Tablet' : 'Phone';
|
||||
// Handle possessive: "Chris" -> "Chris' Tablet", "Mom" -> "Mom's Phone"
|
||||
if (ownerName.toLowerCase().endsWith('s')) {
|
||||
return "$ownerName' Phone";
|
||||
return "$ownerName' $deviceType";
|
||||
} else {
|
||||
return "$ownerName's Phone";
|
||||
return "$ownerName's $deviceType";
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> clearSettings() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.clear();
|
||||
await SecureStorageService.clearAll(); // Also clear secure storage
|
||||
}
|
||||
|
||||
/// Migrate credentials from old SharedPreferences storage to secure storage.
|
||||
/// Should be called once during app startup for existing users.
|
||||
static Future<void> migrateToSecureStorage() async {
|
||||
await SecureStorageService.migrateFromSharedPreferences();
|
||||
}
|
||||
|
||||
// Home Screen Row Settings (Main rows - default on)
|
||||
@@ -496,6 +490,17 @@ class SettingsService {
|
||||
await prefs.setBool(_keyShowFavoriteTracks, show);
|
||||
}
|
||||
|
||||
// Library Artists Filter - show only artists that have albums in library
|
||||
static Future<bool> getShowOnlyArtistsWithAlbums() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getBool(_keyShowOnlyArtistsWithAlbums) ?? false;
|
||||
}
|
||||
|
||||
static Future<void> setShowOnlyArtistsWithAlbums(bool show) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool(_keyShowOnlyArtistsWithAlbums, show);
|
||||
}
|
||||
|
||||
// Home Row Order
|
||||
static Future<List<String>> getHomeRowOrder() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
@@ -633,6 +638,26 @@ class SettingsService {
|
||||
await prefs.setString(_keyLibrarySeriesViewMode, mode);
|
||||
}
|
||||
|
||||
static Future<String> getLibraryRadioViewMode() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getString(_keyLibraryRadioViewMode) ?? 'list';
|
||||
}
|
||||
|
||||
static Future<void> setLibraryRadioViewMode(String mode) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyLibraryRadioViewMode, mode);
|
||||
}
|
||||
|
||||
static Future<String> getLibraryPodcastsViewMode() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getString(_keyLibraryPodcastsViewMode) ?? 'grid2';
|
||||
}
|
||||
|
||||
static Future<void> setLibraryPodcastsViewMode(String mode) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyLibraryPodcastsViewMode, mode);
|
||||
}
|
||||
|
||||
// View Mode Settings - Series Audiobooks (series detail screen)
|
||||
static Future<String> getSeriesAudiobooksSortOrder() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
@@ -666,13 +691,11 @@ class SettingsService {
|
||||
}
|
||||
|
||||
static Future<String?> getAbsApiToken() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getString(_keyAbsApiToken);
|
||||
return await SecureStorageService.getAbsApiToken();
|
||||
}
|
||||
|
||||
static Future<void> setAbsApiToken(String token) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyAbsApiToken, token);
|
||||
await SecureStorageService.setAbsApiToken(token);
|
||||
}
|
||||
|
||||
static Future<bool> getAbsEnabled() async {
|
||||
@@ -688,8 +711,8 @@ class SettingsService {
|
||||
static Future<void> clearAbsSettings() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove(_keyAbsServerUrl);
|
||||
await prefs.remove(_keyAbsApiToken);
|
||||
await prefs.remove(_keyAbsEnabled);
|
||||
await SecureStorageService.setAbsApiToken(null); // Clear from secure storage
|
||||
}
|
||||
|
||||
// Audiobookshelf Library Settings (via MA browse API)
|
||||
@@ -762,4 +785,71 @@ class SettingsService {
|
||||
|
||||
await setEnabledAbsLibraries(enabled);
|
||||
}
|
||||
|
||||
// Hint System Settings
|
||||
|
||||
/// Get whether hints are enabled (default: true)
|
||||
static Future<bool> getShowHints() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getBool(_keyShowHints) ?? true;
|
||||
}
|
||||
|
||||
/// Set whether hints are enabled
|
||||
static Future<void> setShowHints(bool show) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool(_keyShowHints, show);
|
||||
}
|
||||
|
||||
/// Check if user has ever used the player reveal gesture
|
||||
static Future<bool> getHasUsedPlayerReveal() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getBool(_keyHasUsedPlayerReveal) ?? false;
|
||||
}
|
||||
|
||||
/// Mark that user has used the player reveal gesture
|
||||
static Future<void> setHasUsedPlayerReveal(bool hasUsed) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool(_keyHasUsedPlayerReveal, hasUsed);
|
||||
}
|
||||
|
||||
/// Check if user has completed onboarding (seen welcome screen)
|
||||
static Future<bool> getHasCompletedOnboarding() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getBool(_keyHasCompletedOnboarding) ?? false;
|
||||
}
|
||||
|
||||
/// Mark that user has completed onboarding
|
||||
static Future<void> setHasCompletedOnboarding(bool completed) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool(_keyHasCompletedOnboarding, completed);
|
||||
}
|
||||
|
||||
// Podcast Cover Cache (iTunes URLs for high-res artwork)
|
||||
// Stored as JSON: {"podcastId": "itunesUrl", ...}
|
||||
|
||||
/// Get cached podcast cover URLs (iTunes high-res)
|
||||
static Future<Map<String, String>> getPodcastCoverCache() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final json = prefs.getString(_keyPodcastCoverCache);
|
||||
if (json == null) return {};
|
||||
try {
|
||||
final decoded = jsonDecode(json) as Map<String, dynamic>;
|
||||
return decoded.map((key, value) => MapEntry(key, value as String));
|
||||
} catch (_) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/// Save podcast cover cache
|
||||
static Future<void> setPodcastCoverCache(Map<String, String> cache) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyPodcastCoverCache, jsonEncode(cache));
|
||||
}
|
||||
|
||||
/// Add a single podcast cover to cache (for incremental updates)
|
||||
static Future<void> addPodcastCoverToCache(String podcastId, String url) async {
|
||||
final cache = await getPodcastCoverCache();
|
||||
cache[podcastId] = url;
|
||||
await setPodcastCoverCache(cache);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import '../models/media_item.dart';
|
||||
import 'database_service.dart';
|
||||
import 'debug_logger.dart';
|
||||
import 'music_assistant_api.dart';
|
||||
import 'settings_service.dart';
|
||||
|
||||
/// Sync status for UI indicators
|
||||
enum SyncStatus {
|
||||
@@ -150,10 +151,14 @@ class SyncService with ChangeNotifier {
|
||||
try {
|
||||
_logger.log('🔄 Starting background library sync...');
|
||||
|
||||
// Read artist filter setting - when ON, only fetch artists that have albums
|
||||
final showOnlyArtistsWithAlbums = await SettingsService.getShowOnlyArtistsWithAlbums();
|
||||
_logger.log('🎨 Sync using albumArtistsOnly: $showOnlyArtistsWithAlbums');
|
||||
|
||||
// Fetch fresh data from MA API (in parallel for speed)
|
||||
final results = await Future.wait([
|
||||
api.getAlbums(limit: 1000),
|
||||
api.getArtists(limit: 1000),
|
||||
api.getArtists(limit: 1000, albumArtistsOnly: showOnlyArtistsWithAlbums),
|
||||
api.getAudiobooks(limit: 1000),
|
||||
api.getPlaylists(limit: 1000),
|
||||
]);
|
||||
@@ -166,6 +171,12 @@ class SyncService with ChangeNotifier {
|
||||
_logger.log('📥 Fetched ${albums.length} albums, ${artists.length} artists, '
|
||||
'${audiobooks.length} audiobooks, ${playlists.length} playlists from MA');
|
||||
|
||||
// Clear old cache before saving fresh data (removes stale items)
|
||||
await _db.clearCacheForType('album');
|
||||
await _db.clearCacheForType('artist');
|
||||
await _db.clearCacheForType('audiobook');
|
||||
await _db.clearCacheForType('playlist');
|
||||
|
||||
// Save to database cache
|
||||
await _saveAlbumsToCache(albums);
|
||||
await _saveArtistsToCache(artists);
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import 'dart:math';
|
||||
|
||||
/// Fuzzy string matching using Jaro-Winkler similarity.
|
||||
///
|
||||
/// Jaro-Winkler is optimized for short strings like artist/song names
|
||||
/// and gives extra weight to matching prefixes (common typos occur mid-word).
|
||||
class FuzzyMatcher {
|
||||
/// Calculate Jaro-Winkler similarity between two strings.
|
||||
///
|
||||
/// Returns a value between 0.0 (no similarity) and 1.0 (exact match).
|
||||
///
|
||||
/// Jaro-Winkler gives bonus weight to strings that match from the beginning,
|
||||
/// which is useful for handling typos like "Beetles" vs "Beatles".
|
||||
double jaroWinklerSimilarity(String s1, String s2) {
|
||||
if (s1 == s2) return 1.0;
|
||||
if (s1.isEmpty || s2.isEmpty) return 0.0;
|
||||
|
||||
final jaro = _jaroSimilarity(s1, s2);
|
||||
|
||||
// Winkler modification: boost score for common prefix
|
||||
int prefixLength = 0;
|
||||
const maxPrefix = 4; // Standard Winkler prefix length
|
||||
final minLen = min(s1.length, s2.length);
|
||||
final prefixLimit = min(maxPrefix, minLen);
|
||||
|
||||
for (int i = 0; i < prefixLimit; i++) {
|
||||
if (s1[i] == s2[i]) {
|
||||
prefixLength++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const scalingFactor = 0.1; // Standard Winkler scaling factor
|
||||
return jaro + (prefixLength * scalingFactor * (1 - jaro));
|
||||
}
|
||||
|
||||
/// Calculate base Jaro similarity.
|
||||
double _jaroSimilarity(String s1, String s2) {
|
||||
final s1Len = s1.length;
|
||||
final s2Len = s2.length;
|
||||
|
||||
// Match window: characters within this distance can match
|
||||
final matchWindow = (max(s1Len, s2Len) / 2 - 1).floor();
|
||||
if (matchWindow < 0) return 0.0;
|
||||
|
||||
final s1Matches = List.filled(s1Len, false);
|
||||
final s2Matches = List.filled(s2Len, false);
|
||||
|
||||
int matches = 0;
|
||||
int transpositions = 0;
|
||||
|
||||
// Find matching characters
|
||||
for (int i = 0; i < s1Len; i++) {
|
||||
final start = max(0, i - matchWindow);
|
||||
final end = min(s2Len, i + matchWindow + 1);
|
||||
|
||||
for (int j = start; j < end; j++) {
|
||||
if (s2Matches[j] || s1[i] != s2[j]) continue;
|
||||
s1Matches[i] = true;
|
||||
s2Matches[j] = true;
|
||||
matches++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (matches == 0) return 0.0;
|
||||
|
||||
// Count transpositions
|
||||
int k = 0;
|
||||
for (int i = 0; i < s1Len; i++) {
|
||||
if (!s1Matches[i]) continue;
|
||||
while (!s2Matches[k]) {
|
||||
k++;
|
||||
}
|
||||
if (s1[i] != s2[k]) transpositions++;
|
||||
k++;
|
||||
}
|
||||
|
||||
// Jaro similarity formula
|
||||
return (matches / s1Len +
|
||||
matches / s2Len +
|
||||
(matches - transpositions / 2) / matches) /
|
||||
3;
|
||||
}
|
||||
|
||||
/// Find the best match score between query tokens and text tokens.
|
||||
///
|
||||
/// Useful for matching individual words when full string matching fails.
|
||||
/// Returns the highest similarity score found between any token pair.
|
||||
double bestTokenMatch(List<String> queryTokens, List<String> textTokens) {
|
||||
if (queryTokens.isEmpty || textTokens.isEmpty) return 0.0;
|
||||
|
||||
double bestScore = 0.0;
|
||||
|
||||
for (final queryToken in queryTokens) {
|
||||
for (final textToken in textTokens) {
|
||||
final score = jaroWinklerSimilarity(queryToken, textToken);
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
// Early exit if we find a perfect match
|
||||
if (score == 1.0) return 1.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return bestScore;
|
||||
}
|
||||
|
||||
/// Check if two strings are a fuzzy match within a threshold.
|
||||
bool isFuzzyMatch(String s1, String s2, {double threshold = 0.85}) {
|
||||
return jaroWinklerSimilarity(s1, s2) >= threshold;
|
||||
}
|
||||
|
||||
/// Calculate average token match score.
|
||||
///
|
||||
/// For each query token, finds the best matching text token,
|
||||
/// then averages all best matches. Useful for multi-word queries.
|
||||
double averageTokenMatch(List<String> queryTokens, List<String> textTokens) {
|
||||
if (queryTokens.isEmpty || textTokens.isEmpty) return 0.0;
|
||||
|
||||
double totalScore = 0.0;
|
||||
|
||||
for (final queryToken in queryTokens) {
|
||||
double bestForToken = 0.0;
|
||||
for (final textToken in textTokens) {
|
||||
final score = jaroWinklerSimilarity(queryToken, textToken);
|
||||
if (score > bestForToken) {
|
||||
bestForToken = score;
|
||||
}
|
||||
}
|
||||
totalScore += bestForToken;
|
||||
}
|
||||
|
||||
return totalScore / queryTokens.length;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/// N-gram based string matching for partial matches.
|
||||
///
|
||||
/// Uses character bigrams (2-grams) to find partial string matches
|
||||
/// when exact and fuzzy matching fail.
|
||||
class NgramMatcher {
|
||||
/// Generate character bigrams from text.
|
||||
///
|
||||
/// Example: "hello" -> ["he", "el", "ll", "lo"]
|
||||
///
|
||||
/// For strings shorter than 2 characters, returns the string itself.
|
||||
List<String> generateBigrams(String text) {
|
||||
if (text.length < 2) return text.isNotEmpty ? [text] : [];
|
||||
|
||||
final bigrams = <String>[];
|
||||
for (int i = 0; i < text.length - 1; i++) {
|
||||
bigrams.add(text.substring(i, i + 2));
|
||||
}
|
||||
return bigrams;
|
||||
}
|
||||
|
||||
/// Generate character trigrams from text.
|
||||
///
|
||||
/// Example: "hello" -> ["hel", "ell", "llo"]
|
||||
List<String> generateTrigrams(String text) {
|
||||
if (text.length < 3) return text.isNotEmpty ? [text] : [];
|
||||
|
||||
final trigrams = <String>[];
|
||||
for (int i = 0; i < text.length - 2; i++) {
|
||||
trigrams.add(text.substring(i, i + 3));
|
||||
}
|
||||
return trigrams;
|
||||
}
|
||||
|
||||
/// Calculate bigram similarity using Dice coefficient.
|
||||
///
|
||||
/// Dice coefficient: 2 * |intersection| / (|set1| + |set2|)
|
||||
/// Returns a value between 0.0 and 1.0.
|
||||
double bigramSimilarity(String s1, String s2) {
|
||||
final lower1 = s1.toLowerCase();
|
||||
final lower2 = s2.toLowerCase();
|
||||
|
||||
final bigrams1 = generateBigrams(lower1);
|
||||
final bigrams2 = generateBigrams(lower2);
|
||||
|
||||
if (bigrams1.isEmpty || bigrams2.isEmpty) return 0.0;
|
||||
|
||||
final set1 = bigrams1.toSet();
|
||||
final set2 = bigrams2.toSet();
|
||||
|
||||
final intersection = set1.intersection(set2).length;
|
||||
|
||||
// Dice coefficient
|
||||
return (2 * intersection) / (set1.length + set2.length);
|
||||
}
|
||||
|
||||
/// Calculate Jaccard similarity between bigram sets.
|
||||
///
|
||||
/// Jaccard: |intersection| / |union|
|
||||
/// More conservative than Dice coefficient.
|
||||
double jaccardSimilarity(String s1, String s2) {
|
||||
final lower1 = s1.toLowerCase();
|
||||
final lower2 = s2.toLowerCase();
|
||||
|
||||
final bigrams1 = generateBigrams(lower1).toSet();
|
||||
final bigrams2 = generateBigrams(lower2).toSet();
|
||||
|
||||
if (bigrams1.isEmpty || bigrams2.isEmpty) return 0.0;
|
||||
|
||||
final intersection = bigrams1.intersection(bigrams2).length;
|
||||
final union = bigrams1.union(bigrams2).length;
|
||||
|
||||
return intersection / union;
|
||||
}
|
||||
|
||||
/// Check if query partially matches text via bigrams.
|
||||
///
|
||||
/// Uses Dice coefficient with configurable threshold.
|
||||
bool hasPartialMatch(String query, String text, {double threshold = 0.5}) {
|
||||
return bigramSimilarity(query, text) >= threshold;
|
||||
}
|
||||
|
||||
/// Calculate containment coefficient.
|
||||
///
|
||||
/// Measures how many of the query's bigrams are in the text.
|
||||
/// Useful when query is expected to be shorter than text.
|
||||
/// Returns |intersection| / |query bigrams|
|
||||
double containmentScore(String query, String text) {
|
||||
final queryBigrams = generateBigrams(query.toLowerCase()).toSet();
|
||||
final textBigrams = generateBigrams(text.toLowerCase()).toSet();
|
||||
|
||||
if (queryBigrams.isEmpty) return 0.0;
|
||||
|
||||
final intersection = queryBigrams.intersection(textBigrams).length;
|
||||
return intersection / queryBigrams.length;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/// Configuration for search scoring weights and thresholds.
|
||||
///
|
||||
/// All scores are designed to work with the existing sorting system
|
||||
/// where higher scores indicate better matches.
|
||||
class ScoringConfig {
|
||||
// Base scores for match types (primary name matching)
|
||||
final double exactMatch;
|
||||
final double exactMatchNoStopwords;
|
||||
final double startsWithMatch;
|
||||
final double startsWithNoStopwords;
|
||||
final double wordBoundaryMatch;
|
||||
final double wordBoundaryNoStopwords;
|
||||
final double reverseContainsMatch;
|
||||
final double reverseContainsNoStopwords;
|
||||
final double containsMatch;
|
||||
final double containsNoStopwords;
|
||||
final double fuzzyMatchHigh;
|
||||
final double fuzzyMatchMedium;
|
||||
final double ngramMatch;
|
||||
final double baseline;
|
||||
|
||||
// Bonuses (additive)
|
||||
final double libraryBonus;
|
||||
final double favoriteBonus;
|
||||
final double artistFieldExactBonus;
|
||||
final double artistFieldPartialBonus;
|
||||
final double albumFieldBonus;
|
||||
final double authorFieldExactBonus;
|
||||
final double authorFieldPartialBonus;
|
||||
final double narratorFieldBonus;
|
||||
final double creatorFieldExactBonus;
|
||||
final double creatorFieldPartialBonus;
|
||||
final double descriptionBonus;
|
||||
|
||||
// Thresholds
|
||||
final double fuzzyHighThreshold;
|
||||
final double fuzzyMediumThreshold;
|
||||
final double ngramThreshold;
|
||||
|
||||
// Minimum lengths for matching
|
||||
final int minReverseMatchLength;
|
||||
final int minTokenLength;
|
||||
|
||||
const ScoringConfig({
|
||||
// Primary match scores
|
||||
this.exactMatch = 100,
|
||||
this.exactMatchNoStopwords = 95,
|
||||
this.startsWithMatch = 85,
|
||||
this.startsWithNoStopwords = 80,
|
||||
this.wordBoundaryMatch = 70,
|
||||
this.wordBoundaryNoStopwords = 65,
|
||||
this.reverseContainsMatch = 60,
|
||||
this.reverseContainsNoStopwords = 55,
|
||||
this.containsMatch = 50,
|
||||
this.containsNoStopwords = 45,
|
||||
this.fuzzyMatchHigh = 40,
|
||||
this.fuzzyMatchMedium = 35,
|
||||
this.ngramMatch = 25,
|
||||
this.baseline = 20,
|
||||
|
||||
// Bonuses
|
||||
this.libraryBonus = 10,
|
||||
this.favoriteBonus = 5,
|
||||
this.artistFieldExactBonus = 15,
|
||||
this.artistFieldPartialBonus = 8,
|
||||
this.albumFieldBonus = 5,
|
||||
this.authorFieldExactBonus = 15,
|
||||
this.authorFieldPartialBonus = 8,
|
||||
this.narratorFieldBonus = 5,
|
||||
this.creatorFieldExactBonus = 15,
|
||||
this.creatorFieldPartialBonus = 8,
|
||||
this.descriptionBonus = 5,
|
||||
|
||||
// Thresholds
|
||||
this.fuzzyHighThreshold = 0.90,
|
||||
this.fuzzyMediumThreshold = 0.85,
|
||||
this.ngramThreshold = 0.5,
|
||||
|
||||
// Minimum lengths
|
||||
this.minReverseMatchLength = 3,
|
||||
this.minTokenLength = 3,
|
||||
});
|
||||
|
||||
/// Default configuration
|
||||
static const ScoringConfig defaults = ScoringConfig();
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
/// Search scoring system for ranking search results.
|
||||
///
|
||||
/// Provides advanced text matching including:
|
||||
/// - Stopword removal ("the Ramones" finds "Ramones")
|
||||
/// - Fuzzy matching (typo tolerance)
|
||||
/// - N-gram matching (partial matches)
|
||||
/// - Reverse matching (query contains result)
|
||||
library;
|
||||
|
||||
export 'scoring_config.dart';
|
||||
export 'text_normalizer.dart';
|
||||
export 'fuzzy_matcher.dart';
|
||||
export 'ngram_matcher.dart';
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
import '../../models/media_item.dart';
|
||||
import 'scoring_config.dart';
|
||||
import 'text_normalizer.dart';
|
||||
import 'fuzzy_matcher.dart';
|
||||
import 'ngram_matcher.dart';
|
||||
|
||||
/// Main search scorer that combines all matching strategies.
|
||||
///
|
||||
/// Usage:
|
||||
/// ```dart
|
||||
/// final scorer = SearchScorer();
|
||||
/// final score = scorer.scoreItem(mediaItem, query);
|
||||
/// ```
|
||||
class SearchScorer {
|
||||
final TextNormalizer _normalizer;
|
||||
final FuzzyMatcher _fuzzyMatcher;
|
||||
final NgramMatcher _ngramMatcher;
|
||||
final ScoringConfig _config;
|
||||
|
||||
// Cache for normalized query (reused across items in same search)
|
||||
String? _cachedQueryString;
|
||||
NormalizedQuery? _cachedQuery;
|
||||
|
||||
SearchScorer({ScoringConfig? config})
|
||||
: _normalizer = TextNormalizer(),
|
||||
_fuzzyMatcher = FuzzyMatcher(),
|
||||
_ngramMatcher = NgramMatcher(),
|
||||
_config = config ?? ScoringConfig.defaults;
|
||||
|
||||
/// Access to the normalizer for external use
|
||||
TextNormalizer get normalizer => _normalizer;
|
||||
|
||||
/// Clear the query cache (call when starting a new search)
|
||||
void clearCache() {
|
||||
_cachedQueryString = null;
|
||||
_cachedQuery = null;
|
||||
}
|
||||
|
||||
/// Score a media item against a search query.
|
||||
///
|
||||
/// Returns a score where higher values indicate better matches.
|
||||
/// Score components:
|
||||
/// - Primary name matching (0-100)
|
||||
/// - Secondary field bonuses (0-20)
|
||||
/// - Library/favorite bonuses (0-15)
|
||||
double scoreItem(MediaItem item, String query) {
|
||||
// Use cached normalized query if available
|
||||
if (_cachedQueryString != query) {
|
||||
_cachedQueryString = query;
|
||||
_cachedQuery = _normalizer.normalizeQuery(query);
|
||||
}
|
||||
|
||||
final nq = _cachedQuery!;
|
||||
if (nq.isEmpty) return 0;
|
||||
|
||||
final nameLower = item.name.toLowerCase();
|
||||
final nameNoStopwords = _normalizer.normalizeTextNoStopwords(item.name);
|
||||
|
||||
// Calculate primary score based on name matching
|
||||
double score = _calculatePrimaryScore(nameLower, nameNoStopwords, nq);
|
||||
|
||||
// Add secondary field bonuses based on media type
|
||||
score += _calculateSecondaryScore(item, nq);
|
||||
|
||||
// Add library/favorite bonuses
|
||||
score += _calculateBonuses(item);
|
||||
|
||||
return score;
|
||||
}
|
||||
|
||||
/// Calculate primary score based on name matching.
|
||||
double _calculatePrimaryScore(
|
||||
String nameLower,
|
||||
String nameNoStopwords,
|
||||
NormalizedQuery nq,
|
||||
) {
|
||||
// Tier 1: Exact match (highest priority)
|
||||
if (nameLower == nq.normalized) {
|
||||
return _config.exactMatch;
|
||||
}
|
||||
if (nameNoStopwords == nq.withoutStopwords) {
|
||||
return _config.exactMatchNoStopwords;
|
||||
}
|
||||
|
||||
// Tier 2: Starts with
|
||||
if (nameLower.startsWith(nq.normalized)) {
|
||||
return _config.startsWithMatch;
|
||||
}
|
||||
if (nameNoStopwords.startsWith(nq.withoutStopwords)) {
|
||||
return _config.startsWithNoStopwords;
|
||||
}
|
||||
|
||||
// Tier 3: Word boundary match
|
||||
if (_matchesWordBoundary(nameLower, nq.normalized)) {
|
||||
return _config.wordBoundaryMatch;
|
||||
}
|
||||
if (_matchesWordBoundary(nameNoStopwords, nq.withoutStopwords)) {
|
||||
return _config.wordBoundaryNoStopwords;
|
||||
}
|
||||
|
||||
// Tier 4: Reverse contains (result name IN query)
|
||||
// This solves "the ramones" finding "Ramones"
|
||||
if (_reverseContains(nq.normalized, nameLower)) {
|
||||
return _config.reverseContainsMatch;
|
||||
}
|
||||
if (_reverseContains(nq.withoutStopwords, nameNoStopwords)) {
|
||||
return _config.reverseContainsNoStopwords;
|
||||
}
|
||||
|
||||
// Tier 5: Contains anywhere
|
||||
if (nameLower.contains(nq.normalized)) {
|
||||
return _config.containsMatch;
|
||||
}
|
||||
if (nameNoStopwords.contains(nq.withoutStopwords)) {
|
||||
return _config.containsNoStopwords;
|
||||
}
|
||||
|
||||
// Tier 6: Fuzzy matching (typo tolerance)
|
||||
final fuzzyScore = _fuzzyMatcher.jaroWinklerSimilarity(
|
||||
nq.withoutStopwords,
|
||||
nameNoStopwords,
|
||||
);
|
||||
if (fuzzyScore >= _config.fuzzyHighThreshold) {
|
||||
// Scale score based on similarity (0.90-1.0 -> 40-45)
|
||||
return _config.fuzzyMatchHigh +
|
||||
((fuzzyScore - _config.fuzzyHighThreshold) * 50);
|
||||
}
|
||||
if (fuzzyScore >= _config.fuzzyMediumThreshold) {
|
||||
return _config.fuzzyMatchMedium;
|
||||
}
|
||||
|
||||
// Tier 7: Token-level fuzzy (individual words)
|
||||
final tokenFuzzy = _fuzzyMatcher.bestTokenMatch(
|
||||
nq.tokensNoStop,
|
||||
_normalizer.tokenize(nameNoStopwords),
|
||||
);
|
||||
if (tokenFuzzy >= _config.fuzzyHighThreshold) {
|
||||
return _config.fuzzyMatchMedium;
|
||||
}
|
||||
|
||||
// Tier 8: N-gram partial matching
|
||||
final ngramScore = _ngramMatcher.bigramSimilarity(
|
||||
nq.withoutStopwords,
|
||||
nameNoStopwords,
|
||||
);
|
||||
if (ngramScore >= _config.ngramThreshold) {
|
||||
// Scale: 0.5-1.0 -> 25-35
|
||||
return _config.ngramMatch + (ngramScore * 10);
|
||||
}
|
||||
|
||||
// Baseline: Music Assistant API returned it, so some relevance
|
||||
return _config.baseline;
|
||||
}
|
||||
|
||||
/// Check if query matches at word boundary in text.
|
||||
bool _matchesWordBoundary(String text, String query) {
|
||||
if (query.contains(' ')) {
|
||||
// Multi-word query: check if at start or after space
|
||||
if (text.startsWith(query)) return true;
|
||||
if (text.contains(' $query')) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Single-word query: check if any word starts with query
|
||||
final words = text.split(RegExp(r'\s+'));
|
||||
for (final word in words) {
|
||||
if (word.startsWith(query)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Check if text is contained within query (reverse matching).
|
||||
///
|
||||
/// Solves: "the ramones" query finding "Ramones" artist
|
||||
bool _reverseContains(String query, String text) {
|
||||
if (text.length < _config.minReverseMatchLength) return false;
|
||||
|
||||
// Direct containment
|
||||
if (query.contains(text)) return true;
|
||||
|
||||
// Token-level: any query token equals text
|
||||
final queryTokens = query.split(RegExp(r'\s+'));
|
||||
for (final token in queryTokens) {
|
||||
if (token.length >= _config.minReverseMatchLength && text == token) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Calculate secondary field bonuses based on media type.
|
||||
double _calculateSecondaryScore(MediaItem item, NormalizedQuery nq) {
|
||||
double bonus = 0;
|
||||
|
||||
if (item is Album) {
|
||||
bonus += _scoreArtistField(item.artistsString, nq);
|
||||
} else if (item is Track) {
|
||||
bonus += _scoreArtistField(item.artistsString, nq);
|
||||
// Also check album name
|
||||
if (item.album?.name != null) {
|
||||
final albumLower = item.album!.name.toLowerCase();
|
||||
if (albumLower.contains(nq.withoutStopwords)) {
|
||||
bonus += _config.albumFieldBonus;
|
||||
}
|
||||
}
|
||||
} else if (item is Audiobook) {
|
||||
// Check authors
|
||||
final authorLower = item.authorsString.toLowerCase();
|
||||
if (authorLower == nq.withoutStopwords) {
|
||||
bonus += _config.authorFieldExactBonus;
|
||||
} else if (authorLower.contains(nq.withoutStopwords)) {
|
||||
bonus += _config.authorFieldPartialBonus;
|
||||
}
|
||||
// Check narrators
|
||||
final narratorLower = item.narratorsString.toLowerCase();
|
||||
if (narratorLower.contains(nq.withoutStopwords)) {
|
||||
bonus += _config.narratorFieldBonus;
|
||||
}
|
||||
} else if (item.mediaType == MediaType.podcast || item.mediaType == MediaType.podcastEpisode) {
|
||||
bonus += _scorePodcastFields(item, nq);
|
||||
}
|
||||
|
||||
return bonus;
|
||||
}
|
||||
|
||||
/// Score artist field for albums and tracks.
|
||||
double _scoreArtistField(String artistsString, NormalizedQuery nq) {
|
||||
final artistLower = artistsString.toLowerCase();
|
||||
if (artistLower == nq.withoutStopwords) {
|
||||
return _config.artistFieldExactBonus;
|
||||
}
|
||||
if (artistLower.contains(nq.withoutStopwords)) {
|
||||
return _config.artistFieldPartialBonus;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// Score podcast-specific fields (creator, description).
|
||||
double _scorePodcastFields(MediaItem item, NormalizedQuery nq) {
|
||||
double bonus = 0;
|
||||
final metadata = item.metadata;
|
||||
|
||||
if (metadata != null) {
|
||||
// Check creator fields
|
||||
final creatorFields = [
|
||||
metadata['author'] as String?,
|
||||
metadata['publisher'] as String?,
|
||||
metadata['owner'] as String?,
|
||||
metadata['creator'] as String?,
|
||||
].where((s) => s != null && s.isNotEmpty).map((s) => s!.toLowerCase());
|
||||
|
||||
bool foundExact = false;
|
||||
bool foundContains = false;
|
||||
for (final field in creatorFields) {
|
||||
if (field == nq.withoutStopwords) {
|
||||
foundExact = true;
|
||||
break;
|
||||
} else if (field.contains(nq.withoutStopwords)) {
|
||||
foundContains = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (foundExact) {
|
||||
bonus += _config.creatorFieldExactBonus;
|
||||
} else if (foundContains) {
|
||||
bonus += _config.creatorFieldPartialBonus;
|
||||
}
|
||||
|
||||
// Check description
|
||||
final description =
|
||||
(metadata['description'] as String? ?? '').toLowerCase();
|
||||
if (description.contains(nq.withoutStopwords)) {
|
||||
bonus += _config.descriptionBonus;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: podcast name prominence check
|
||||
if (bonus == 0) {
|
||||
final nameLower = item.name.toLowerCase();
|
||||
if (nameLower.contains(nq.withoutStopwords)) {
|
||||
if (nq.withoutStopwords.contains(' ')) {
|
||||
// Multi-word query prominence
|
||||
final prominence = nq.withoutStopwords.length / nameLower.length;
|
||||
if (prominence >= 0.5) {
|
||||
bonus += _config.creatorFieldExactBonus;
|
||||
} else if (prominence >= 0.3) {
|
||||
bonus += _config.creatorFieldPartialBonus + 4;
|
||||
} else {
|
||||
bonus += _config.creatorFieldPartialBonus;
|
||||
}
|
||||
} else {
|
||||
bonus += _config.descriptionBonus;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return bonus;
|
||||
}
|
||||
|
||||
/// Calculate library and favorite bonuses.
|
||||
double _calculateBonuses(MediaItem item) {
|
||||
double bonus = 0;
|
||||
|
||||
// Library bonus (Album has inLibrary property)
|
||||
if (item is Album && item.inLibrary) {
|
||||
bonus += _config.libraryBonus;
|
||||
}
|
||||
|
||||
// Favorite bonus
|
||||
if (item.favorite == true) {
|
||||
bonus += _config.favoriteBonus;
|
||||
}
|
||||
|
||||
return bonus;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
/// Text normalization utilities for search scoring.
|
||||
///
|
||||
/// Handles query normalization, stopword removal, and tokenization.
|
||||
|
||||
/// Represents a normalized search query with various forms for matching.
|
||||
class NormalizedQuery {
|
||||
/// Original query as entered by user
|
||||
final String original;
|
||||
|
||||
/// Lowercased and trimmed query
|
||||
final String normalized;
|
||||
|
||||
/// Query with stopwords removed
|
||||
final String withoutStopwords;
|
||||
|
||||
/// Individual tokens from normalized query
|
||||
final List<String> tokens;
|
||||
|
||||
/// Tokens with stopwords removed
|
||||
final List<String> tokensNoStop;
|
||||
|
||||
const NormalizedQuery({
|
||||
required this.original,
|
||||
required this.normalized,
|
||||
required this.withoutStopwords,
|
||||
required this.tokens,
|
||||
required this.tokensNoStop,
|
||||
});
|
||||
|
||||
/// Whether the query is empty after normalization
|
||||
bool get isEmpty => normalized.isEmpty;
|
||||
|
||||
/// Whether stopword removal changed the query
|
||||
bool get hasStopwordsRemoved => normalized != withoutStopwords;
|
||||
}
|
||||
|
||||
/// Normalizes text and queries for search matching.
|
||||
class TextNormalizer {
|
||||
/// Common English stopwords relevant to music/media searches.
|
||||
///
|
||||
/// Intentionally minimal to avoid over-filtering:
|
||||
/// - Articles that commonly prefix artist/album names
|
||||
/// - Common prepositions that add noise
|
||||
static const Set<String> _stopwords = {
|
||||
// Articles
|
||||
'the',
|
||||
'a',
|
||||
'an',
|
||||
// Common prepositions in music/media context
|
||||
'of',
|
||||
'and',
|
||||
'in',
|
||||
'on',
|
||||
'at',
|
||||
'to',
|
||||
'for',
|
||||
'with',
|
||||
'by',
|
||||
// Common noise words
|
||||
'is',
|
||||
'are',
|
||||
'was',
|
||||
'be',
|
||||
};
|
||||
|
||||
/// Normalize a search query into multiple forms for matching.
|
||||
///
|
||||
/// Returns a [NormalizedQuery] containing:
|
||||
/// - Original query
|
||||
/// - Lowercased/trimmed version
|
||||
/// - Version with stopwords removed
|
||||
/// - Tokenized versions
|
||||
NormalizedQuery normalizeQuery(String query) {
|
||||
final normalized = query.toLowerCase().trim();
|
||||
final tokens = tokenize(normalized);
|
||||
final tokensNoStop = tokens.where((t) => !_stopwords.contains(t)).toList();
|
||||
|
||||
// If all tokens were stopwords, preserve original tokens
|
||||
// e.g., "The The" (band name) shouldn't become empty
|
||||
final effectiveTokensNoStop =
|
||||
tokensNoStop.isEmpty ? tokens : tokensNoStop;
|
||||
final withoutStopwords = effectiveTokensNoStop.join(' ');
|
||||
|
||||
return NormalizedQuery(
|
||||
original: query,
|
||||
normalized: normalized,
|
||||
withoutStopwords: withoutStopwords,
|
||||
tokens: tokens,
|
||||
tokensNoStop: effectiveTokensNoStop,
|
||||
);
|
||||
}
|
||||
|
||||
/// Normalize text for comparison (lowercase, trim).
|
||||
String normalizeText(String text) {
|
||||
return text.toLowerCase().trim();
|
||||
}
|
||||
|
||||
/// Normalize text with stopwords removed.
|
||||
String normalizeTextNoStopwords(String text) {
|
||||
final tokens = tokenize(text.toLowerCase().trim());
|
||||
final filtered = tokens.where((t) => !_stopwords.contains(t)).toList();
|
||||
return filtered.isEmpty ? text.toLowerCase().trim() : filtered.join(' ');
|
||||
}
|
||||
|
||||
/// Split text into tokens on whitespace.
|
||||
List<String> tokenize(String text) {
|
||||
return text.split(RegExp(r'\s+')).where((t) => t.isNotEmpty).toList();
|
||||
}
|
||||
|
||||
/// Check if a word is a stopword.
|
||||
bool isStopword(String word) {
|
||||
return _stopwords.contains(word.toLowerCase());
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
@@ -13,12 +14,16 @@ class AlbumCard extends StatefulWidget {
|
||||
final Album album;
|
||||
final VoidCallback? onTap;
|
||||
final String? heroTagSuffix;
|
||||
/// Image decode size in pixels. Defaults to 256.
|
||||
/// Use smaller values (e.g., 128) for list views, larger for grids.
|
||||
final int? imageCacheSize;
|
||||
|
||||
const AlbumCard({
|
||||
super.key,
|
||||
required this.album,
|
||||
this.onTap,
|
||||
this.heroTagSuffix,
|
||||
this.imageCacheSize,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -30,6 +35,10 @@ class _AlbumCardState extends State<AlbumCard> {
|
||||
bool _triedFallback = false;
|
||||
bool _maImageFailed = false;
|
||||
String? _cachedMaImageUrl;
|
||||
Timer? _fallbackTimer;
|
||||
|
||||
/// Delay before fetching fallback images to avoid requests during fast scroll
|
||||
static const _fallbackDelay = Duration(milliseconds: 200);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -37,6 +46,12 @@ class _AlbumCardState extends State<AlbumCard> {
|
||||
_initFallbackImage();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_fallbackTimer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _initFallbackImage() {
|
||||
// Check if MA has an image after first build, then fetch fallback if needed
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
@@ -47,6 +62,16 @@ class _AlbumCardState extends State<AlbumCard> {
|
||||
|
||||
if (maImageUrl == null && !_triedFallback) {
|
||||
_triedFallback = true;
|
||||
_scheduleFallbackFetch();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Schedule fallback fetch with delay to avoid requests during fast scroll
|
||||
void _scheduleFallbackFetch() {
|
||||
_fallbackTimer?.cancel();
|
||||
_fallbackTimer = Timer(_fallbackDelay, () {
|
||||
if (mounted) {
|
||||
_fetchFallbackImage();
|
||||
}
|
||||
});
|
||||
@@ -69,7 +94,7 @@ class _AlbumCardState extends State<AlbumCard> {
|
||||
if (!_triedFallback && !_maImageFailed) {
|
||||
_maImageFailed = true;
|
||||
_triedFallback = true;
|
||||
_fetchFallbackImage();
|
||||
_scheduleFallbackFetch();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,6 +111,9 @@ class _AlbumCardState extends State<AlbumCard> {
|
||||
// Use fallback if MA image failed or wasn't available
|
||||
final imageUrl = (_maImageFailed || maImageUrl == null) ? _fallbackImageUrl : maImageUrl;
|
||||
|
||||
// PERF: Use appropriate cache size based on display size
|
||||
final cacheSize = widget.imageCacheSize ?? 256;
|
||||
|
||||
return RepaintBoundary(
|
||||
child: GestureDetector(
|
||||
onTap: widget.onTap ?? () {
|
||||
@@ -118,8 +146,8 @@ class _AlbumCardState extends State<AlbumCard> {
|
||||
? CachedNetworkImage(
|
||||
imageUrl: imageUrl,
|
||||
fit: BoxFit.cover,
|
||||
memCacheWidth: 256,
|
||||
memCacheHeight: 256,
|
||||
memCacheWidth: cacheSize,
|
||||
memCacheHeight: cacheSize,
|
||||
fadeInDuration: Duration.zero,
|
||||
fadeOutDuration: Duration.zero,
|
||||
placeholder: (context, url) => const SizedBox(),
|
||||
|
||||
@@ -126,6 +126,7 @@ class _AlbumRowState extends State<AlbumRow> with AutomaticKeepAliveClientMixin
|
||||
return ScrollConfiguration(
|
||||
behavior: const _StretchScrollBehavior(),
|
||||
child: ListView.builder(
|
||||
clipBehavior: Clip.none,
|
||||
scrollDirection: Axis.horizontal,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12.0),
|
||||
itemCount: _albums.length,
|
||||
@@ -135,13 +136,16 @@ class _AlbumRowState extends State<AlbumRow> with AutomaticKeepAliveClientMixin
|
||||
addRepaintBoundaries: false, // Cards already have RepaintBoundary
|
||||
itemBuilder: (context, index) {
|
||||
final album = _albums[index];
|
||||
return Container(
|
||||
key: ValueKey(album.uri ?? album.itemId),
|
||||
width: cardWidth,
|
||||
margin: const EdgeInsets.symmetric(horizontal: 6.0),
|
||||
child: AlbumCard(
|
||||
album: album,
|
||||
heroTagSuffix: widget.heroTagSuffix,
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 4.0),
|
||||
child: Container(
|
||||
key: ValueKey(album.uri ?? album.itemId),
|
||||
width: cardWidth,
|
||||
margin: const EdgeInsets.symmetric(horizontal: 6.0),
|
||||
child: AlbumCard(
|
||||
album: album,
|
||||
heroTagSuffix: widget.heroTagSuffix,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
@@ -32,6 +33,10 @@ class _ArtistAvatarState extends State<ArtistAvatar> {
|
||||
String? _fallbackImageUrl;
|
||||
bool _triedFallback = false;
|
||||
bool _maImageFailed = false;
|
||||
Timer? _fallbackTimer;
|
||||
|
||||
/// Delay before fetching fallback images to avoid requests during fast scroll
|
||||
static const _fallbackDelay = Duration(milliseconds: 200);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -39,6 +44,12 @@ class _ArtistAvatarState extends State<ArtistAvatar> {
|
||||
_loadImage();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_fallbackTimer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _loadImage() async {
|
||||
final provider = context.read<MusicAssistantProvider>();
|
||||
|
||||
@@ -56,14 +67,23 @@ class _ArtistAvatarState extends State<ArtistAvatar> {
|
||||
return;
|
||||
}
|
||||
|
||||
// Fallback to external sources (MA returned null)
|
||||
_fetchFallbackImage();
|
||||
// Fallback to external sources (MA returned null) - with delay
|
||||
_scheduleFallbackFetch();
|
||||
}
|
||||
|
||||
/// Schedule fallback fetch with delay to avoid requests during fast scroll
|
||||
void _scheduleFallbackFetch() {
|
||||
if (_triedFallback) return;
|
||||
_triedFallback = true;
|
||||
_fallbackTimer?.cancel();
|
||||
_fallbackTimer = Timer(_fallbackDelay, () {
|
||||
if (mounted) {
|
||||
_fetchFallbackImage();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _fetchFallbackImage() async {
|
||||
if (_triedFallback) return;
|
||||
_triedFallback = true;
|
||||
|
||||
final fallbackUrl = await MetadataService.getArtistImageUrl(widget.artist.name);
|
||||
_fallbackImageUrl = fallbackUrl;
|
||||
|
||||
@@ -79,7 +99,7 @@ class _ArtistAvatarState extends State<ArtistAvatar> {
|
||||
// When MA image fails to load, try Deezer fallback
|
||||
if (!_maImageFailed) {
|
||||
_maImageFailed = true;
|
||||
_fetchFallbackImage();
|
||||
_scheduleFallbackFetch();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,6 +120,9 @@ class _ArtistAvatarState extends State<ArtistAvatar> {
|
||||
width: widget.radius * 2,
|
||||
height: widget.radius * 2,
|
||||
fit: BoxFit.cover,
|
||||
// PERF: Use imageSize for memory cache to reduce decode overhead
|
||||
memCacheWidth: widget.imageSize,
|
||||
memCacheHeight: widget.imageSize,
|
||||
fadeInDuration: Duration.zero,
|
||||
fadeOutDuration: Duration.zero,
|
||||
placeholder: (context, url) => Container(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
@@ -14,14 +15,16 @@ class ArtistCard extends StatefulWidget {
|
||||
final Artist artist;
|
||||
final VoidCallback? onTap;
|
||||
final String? heroTagSuffix;
|
||||
final double? imageSize;
|
||||
/// Image decode size in pixels. Defaults to 256.
|
||||
/// Use smaller values (e.g., 128) for list views, larger for grids.
|
||||
final int? imageCacheSize;
|
||||
|
||||
const ArtistCard({
|
||||
super.key,
|
||||
required this.artist,
|
||||
this.onTap,
|
||||
this.heroTagSuffix,
|
||||
this.imageSize,
|
||||
this.imageCacheSize,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -34,6 +37,10 @@ class _ArtistCardState extends State<ArtistCard> {
|
||||
bool _triedFallback = false;
|
||||
bool _maImageFailed = false;
|
||||
String? _cachedMaImageUrl;
|
||||
Timer? _fallbackTimer;
|
||||
|
||||
/// Delay before fetching fallback images to avoid requests during fast scroll
|
||||
static const _fallbackDelay = Duration(milliseconds: 200);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -42,6 +49,12 @@ class _ArtistCardState extends State<ArtistCard> {
|
||||
_initFallbackImage();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_fallbackTimer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _initFallbackImage() {
|
||||
// We'll check if MA has an image after first build, then fetch fallback if needed
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
@@ -52,7 +65,17 @@ class _ArtistCardState extends State<ArtistCard> {
|
||||
|
||||
if (maImageUrl == null && !_triedFallback) {
|
||||
_triedFallback = true;
|
||||
_logger.debug('No MA image for "${widget.artist.name}", trying fallback', context: 'ArtistCard');
|
||||
_logger.debug('No MA image for "${widget.artist.name}", scheduling fallback', context: 'ArtistCard');
|
||||
_scheduleFallbackFetch();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Schedule fallback fetch with delay to avoid requests during fast scroll
|
||||
void _scheduleFallbackFetch() {
|
||||
_fallbackTimer?.cancel();
|
||||
_fallbackTimer = Timer(_fallbackDelay, () {
|
||||
if (mounted) {
|
||||
_fetchFallbackImage();
|
||||
}
|
||||
});
|
||||
@@ -63,8 +86,8 @@ class _ArtistCardState extends State<ArtistCard> {
|
||||
if (!_triedFallback && !_maImageFailed) {
|
||||
_maImageFailed = true;
|
||||
_triedFallback = true;
|
||||
_logger.debug('MA image failed for "${widget.artist.name}", trying fallback', context: 'ArtistCard');
|
||||
_fetchFallbackImage();
|
||||
_logger.debug('MA image failed for "${widget.artist.name}", scheduling fallback', context: 'ArtistCard');
|
||||
_scheduleFallbackFetch();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,6 +104,9 @@ class _ArtistCardState extends State<ArtistCard> {
|
||||
// Use fallback if MA image failed or wasn't available
|
||||
final imageUrl = (_maImageFailed || maImageUrl == null) ? _fallbackImageUrl : maImageUrl;
|
||||
|
||||
// PERF: Use appropriate cache size based on display size
|
||||
final cacheSize = widget.imageCacheSize ?? 256;
|
||||
|
||||
return RepaintBoundary(
|
||||
child: GestureDetector(
|
||||
onTap: widget.onTap ?? () {
|
||||
@@ -115,8 +141,8 @@ class _ArtistCardState extends State<ArtistCard> {
|
||||
? CachedNetworkImage(
|
||||
imageUrl: imageUrl,
|
||||
fit: BoxFit.cover,
|
||||
memCacheWidth: 256,
|
||||
memCacheHeight: 256,
|
||||
memCacheWidth: cacheSize,
|
||||
memCacheHeight: cacheSize,
|
||||
fadeInDuration: Duration.zero,
|
||||
fadeOutDuration: Duration.zero,
|
||||
placeholder: (context, url) => const SizedBox(),
|
||||
@@ -163,6 +189,7 @@ class _ArtistCardState extends State<ArtistCard> {
|
||||
style: textTheme.titleSmall?.copyWith(
|
||||
color: colorScheme.onSurface,
|
||||
fontWeight: FontWeight.w500,
|
||||
height: 1.15,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -31,6 +31,7 @@ class _AudiobookRowState extends State<AudiobookRow> with AutomaticKeepAliveClie
|
||||
late Future<List<Audiobook>> _audiobooksFuture;
|
||||
List<Audiobook>? _cachedAudiobooks;
|
||||
bool _hasLoaded = false;
|
||||
bool _hasPrecachedAudiobooks = false;
|
||||
|
||||
@override
|
||||
bool get wantKeepAlive => true;
|
||||
@@ -45,12 +46,38 @@ class _AudiobookRowState extends State<AudiobookRow> with AutomaticKeepAliveClie
|
||||
if (!_hasLoaded) {
|
||||
_audiobooksFuture = widget.loadAudiobooks().then((audiobooks) {
|
||||
_cachedAudiobooks = audiobooks;
|
||||
// Pre-cache images for smooth Hero animations
|
||||
_precacheAudiobookImages(audiobooks);
|
||||
return audiobooks;
|
||||
});
|
||||
_hasLoaded = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Pre-cache audiobook images so Hero animations are smooth on first tap
|
||||
void _precacheAudiobookImages(List<Audiobook> audiobooks) {
|
||||
if (!mounted || _hasPrecachedAudiobooks) return;
|
||||
_hasPrecachedAudiobooks = true;
|
||||
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
|
||||
// Only precache first ~10 visible items
|
||||
final audiobooksToCache = audiobooks.take(10);
|
||||
|
||||
for (final audiobook in audiobooksToCache) {
|
||||
final imageUrl = maProvider.api?.getImageUrl(audiobook, size: 256);
|
||||
if (imageUrl != null) {
|
||||
precacheImage(
|
||||
CachedNetworkImageProvider(imageUrl),
|
||||
context,
|
||||
).catchError((_) {
|
||||
// Silently ignore precache errors
|
||||
return false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static final _logger = DebugLogger();
|
||||
|
||||
@override
|
||||
|
||||
@@ -36,12 +36,17 @@ class ExpandablePlayer extends StatefulWidget {
|
||||
/// When true, shows player name instead of track name in collapsed state
|
||||
final bool isDeviceRevealVisible;
|
||||
|
||||
/// Whether the hint text should be shown
|
||||
/// When true, shows "Pull to select players" instead of track info
|
||||
final bool isHintVisible;
|
||||
|
||||
const ExpandablePlayer({
|
||||
super.key,
|
||||
this.slideOffset = 0.0,
|
||||
this.bounceOffset = 0.0,
|
||||
this.onRevealPlayers,
|
||||
this.isDeviceRevealVisible = false,
|
||||
this.isHintVisible = false,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -72,10 +77,10 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
final ValueNotifier<double?> _seekPositionNotifier = ValueNotifier<double?>(null);
|
||||
|
||||
// Dimensions
|
||||
static const double _collapsedHeight = 64.0;
|
||||
static double get _collapsedHeight => MiniPlayerLayout.height;
|
||||
static const double _collapsedMargin = 12.0; // Increased from 8 to 12 (4px more gap above nav bar)
|
||||
static const double _collapsedBorderRadius = 16.0;
|
||||
static const double _collapsedArtSize = 64.0;
|
||||
static double get _collapsedArtSize => MiniPlayerLayout.artSize;
|
||||
static const double _bottomNavHeight = 56.0;
|
||||
static const double _edgeDeadZone = 40.0; // Dead zone for Android back gesture
|
||||
|
||||
@@ -99,6 +104,12 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
// When true, we hide main content and show peek content at center
|
||||
bool _inTransition = false;
|
||||
|
||||
// Volume swipe state (only active when device reveal is visible)
|
||||
bool _isDraggingVolume = false;
|
||||
double _dragVolumeLevel = 0.0;
|
||||
int _lastVolumeUpdateTime = 0;
|
||||
static const int _volumeThrottleMs = 150; // Only send volume updates every 150ms
|
||||
|
||||
// Track favorite state for current track
|
||||
bool _isCurrentTrackFavorite = false;
|
||||
String? _lastTrackUri; // Track which track we last checked favorite status for
|
||||
@@ -340,14 +351,17 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
}
|
||||
|
||||
// 1. Show cached queue immediately (if available)
|
||||
final cachedQueue = await maProvider.getCachedQueue(player.playerId);
|
||||
if (cachedQueue != null && cachedQueue.items.isNotEmpty && mounted) {
|
||||
setState(() {
|
||||
_queue = cachedQueue;
|
||||
_isLoadingQueue = false;
|
||||
});
|
||||
} else {
|
||||
setState(() => _isLoadingQueue = true);
|
||||
// Only load from cache if we don't already have a queue (preserves optimistic updates)
|
||||
if (_queue == null) {
|
||||
final cachedQueue = await maProvider.getCachedQueue(player.playerId);
|
||||
if (cachedQueue != null && cachedQueue.items.isNotEmpty && mounted) {
|
||||
setState(() {
|
||||
_queue = cachedQueue;
|
||||
_isLoadingQueue = false;
|
||||
});
|
||||
} else {
|
||||
setState(() => _isLoadingQueue = true);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Fetch fresh queue in background
|
||||
@@ -355,11 +369,28 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
try {
|
||||
final freshQueue = await maProvider.getQueue(player.playerId);
|
||||
if (mounted && freshQueue != null) {
|
||||
// Only update if queue changed
|
||||
debugPrint('🔀 Queue loaded: shuffle=${freshQueue.shuffle}, shuffleEnabled=${freshQueue.shuffleEnabled}');
|
||||
// Check if queue items were reordered by comparing first few item IDs
|
||||
bool itemsReordered = false;
|
||||
if (_queue != null && _queue!.items.isNotEmpty && freshQueue.items.isNotEmpty) {
|
||||
// Compare first 3 items to detect reordering (shuffle changes item order)
|
||||
final maxCheck = (_queue!.items.length < 3 ? _queue!.items.length : 3).clamp(1, freshQueue.items.length);
|
||||
for (int i = 0; i < maxCheck; i++) {
|
||||
if (_queue!.items[i].queueItemId != freshQueue.items[i].queueItemId) {
|
||||
itemsReordered = true;
|
||||
debugPrint('🔀 Queue items reordered detected at position $i');
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Update if queue metadata or item order changed
|
||||
final queueChanged = _queue == null ||
|
||||
_queue!.items.length != freshQueue.items.length ||
|
||||
_queue!.currentIndex != freshQueue.currentIndex;
|
||||
_queue!.currentIndex != freshQueue.currentIndex ||
|
||||
_queue!.shuffle != freshQueue.shuffle ||
|
||||
itemsReordered;
|
||||
if (queueChanged) {
|
||||
debugPrint('🔀 Queue changed, updating UI (reordered=$itemsReordered)');
|
||||
setState(() {
|
||||
_queue = freshQueue;
|
||||
_isLoadingQueue = false;
|
||||
@@ -401,16 +432,69 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
}
|
||||
|
||||
Future<void> _toggleShuffle() async {
|
||||
if (_queue == null) return;
|
||||
debugPrint('🔀 Shuffle button pressed');
|
||||
if (_queue == null) {
|
||||
debugPrint('🔀 Shuffle: _queue is null, returning');
|
||||
return;
|
||||
}
|
||||
final newShuffleState = !_queue!.shuffle;
|
||||
debugPrint('🔀 Shuffle: current=${_queue!.shuffle}, toggling to $newShuffleState');
|
||||
|
||||
// Optimistically update local state for immediate visual feedback
|
||||
setState(() {
|
||||
_queue = PlayerQueue(
|
||||
playerId: _queue!.playerId,
|
||||
items: _queue!.items,
|
||||
currentIndex: _queue!.currentIndex,
|
||||
shuffleEnabled: newShuffleState,
|
||||
repeatMode: _queue!.repeatMode,
|
||||
);
|
||||
});
|
||||
debugPrint('🔀 Shuffle: optimistic update applied, shuffleEnabled=$newShuffleState');
|
||||
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
await maProvider.toggleShuffle(_queue!.playerId);
|
||||
// Toggle: if currently shuffled, disable; if not shuffled, enable
|
||||
await maProvider.toggleShuffle(_queue!.playerId, newShuffleState);
|
||||
debugPrint('🔀 Shuffle: command sent, waiting for server to reorder queue');
|
||||
// Small delay to allow server to finish reordering queue items
|
||||
await Future.delayed(const Duration(milliseconds: 150));
|
||||
debugPrint('🔀 Shuffle: reloading queue');
|
||||
await _loadQueue();
|
||||
}
|
||||
|
||||
Future<void> _cycleRepeat() async {
|
||||
if (_queue == null) return;
|
||||
|
||||
// Calculate next repeat mode: off -> all -> one -> off
|
||||
String nextMode;
|
||||
switch (_queue!.repeatMode) {
|
||||
case 'off':
|
||||
case null:
|
||||
nextMode = 'all';
|
||||
break;
|
||||
case 'all':
|
||||
nextMode = 'one';
|
||||
break;
|
||||
case 'one':
|
||||
nextMode = 'off';
|
||||
break;
|
||||
default:
|
||||
nextMode = 'off';
|
||||
}
|
||||
|
||||
// Optimistically update local state for immediate visual feedback
|
||||
setState(() {
|
||||
_queue = PlayerQueue(
|
||||
playerId: _queue!.playerId,
|
||||
items: _queue!.items,
|
||||
currentIndex: _queue!.currentIndex,
|
||||
shuffleEnabled: _queue!.shuffleEnabled,
|
||||
repeatMode: nextMode,
|
||||
);
|
||||
});
|
||||
|
||||
final maProvider = context.read<MusicAssistantProvider>();
|
||||
await maProvider.cycleRepeatMode(_queue!.playerId, _queue!.repeatMode);
|
||||
await maProvider.setRepeatMode(_queue!.playerId, nextMode);
|
||||
await _loadQueue();
|
||||
}
|
||||
|
||||
@@ -499,9 +583,10 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
final mappings = currentTrack.providerMappings as List<dynamic>?;
|
||||
if (mappings != null && mappings.isNotEmpty) {
|
||||
// Find a non-library provider mapping
|
||||
// Use providerDomain (e.g., "spotify") not providerInstance (e.g., "spotify--xyz")
|
||||
for (final mapping in mappings) {
|
||||
if (mapping.available == true && mapping.providerInstance != 'library') {
|
||||
actualProvider = mapping.providerInstance;
|
||||
actualProvider = mapping.providerDomain;
|
||||
actualItemId = mapping.itemId;
|
||||
break;
|
||||
}
|
||||
@@ -510,7 +595,7 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
if (actualProvider == 'library') {
|
||||
for (final mapping in mappings) {
|
||||
if (mapping.available == true) {
|
||||
actualProvider = mapping.providerInstance;
|
||||
actualProvider = mapping.providerDomain;
|
||||
actualItemId = mapping.itemId;
|
||||
break;
|
||||
}
|
||||
@@ -984,7 +1069,8 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
ThemeProvider themeProvider,
|
||||
) {
|
||||
final screenSize = MediaQuery.of(context).size;
|
||||
final bottomPadding = MediaQuery.of(context).padding.bottom;
|
||||
// Use viewPadding to match BottomNavigationBar's height calculation
|
||||
final bottomPadding = MediaQuery.of(context).viewPadding.bottom;
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
|
||||
@@ -1017,6 +1103,8 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
right: _collapsedMargin,
|
||||
bottom: adjustedBottomOffset,
|
||||
child: GestureDetector(
|
||||
// Tap to dismiss player reveal (matching _buildMorphingPlayer behavior)
|
||||
onTap: widget.isDeviceRevealVisible ? GlobalPlayerOverlay.dismissPlayerReveal : null,
|
||||
onVerticalDragUpdate: (details) {
|
||||
if (details.primaryDelta! > 5 && widget.onRevealPlayers != null) {
|
||||
widget.onRevealPlayers!();
|
||||
@@ -1057,6 +1145,7 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
|
||||
_handleHorizontalDragEnd(details, maProvider);
|
||||
},
|
||||
onPowerToggle: () => maProvider.togglePower(selectedPlayer.playerId),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -1071,7 +1160,9 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
ThemeProvider themeProvider,
|
||||
) {
|
||||
final screenSize = MediaQuery.of(context).size;
|
||||
final bottomPadding = MediaQuery.of(context).padding.bottom;
|
||||
// Use viewPadding (not padding) to match BottomNavigationBar's height calculation
|
||||
// viewPadding represents permanent system UI, padding can change (e.g., keyboard)
|
||||
final bottomPadding = MediaQuery.of(context).viewPadding.bottom;
|
||||
final topPadding = MediaQuery.of(context).padding.top;
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
@@ -1110,10 +1201,11 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
final primaryColor = adaptiveScheme?.primary ?? Colors.white;
|
||||
|
||||
// Always position above bottom nav bar
|
||||
// Overlap by 2px when expanded to eliminate any subpixel rendering gaps
|
||||
final bottomNavSpace = _bottomNavHeight + bottomPadding;
|
||||
final collapsedBottomOffset = bottomNavSpace + _collapsedMargin;
|
||||
final expandedBottomOffset = bottomNavSpace;
|
||||
final expandedHeight = screenSize.height - bottomNavSpace;
|
||||
final expandedBottomOffset = bottomNavSpace - 2;
|
||||
final expandedHeight = screenSize.height - bottomNavSpace + 2;
|
||||
|
||||
// Apply slide offset to hide mini player (slides down off-screen)
|
||||
// Apply bounce offset for reveal animation (small downward movement)
|
||||
@@ -1158,7 +1250,7 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
final expandedArtLeft = (screenSize.width - expandedArtSize) / 2;
|
||||
final artLeft = _lerpDouble(collapsedArtLeft, expandedArtLeft, t);
|
||||
|
||||
final collapsedArtTop = 0.0;
|
||||
final collapsedArtTop = (_collapsedHeight - _collapsedArtSize) / 2; // Center vertically
|
||||
final expandedArtTop = topPadding + headerHeight + 16;
|
||||
final artTop = _lerpDouble(collapsedArtTop, expandedArtTop, t);
|
||||
|
||||
@@ -1215,7 +1307,8 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
// - Progress bar + times: ~70px
|
||||
// Total from bottom edge: ~48 + 40 + 70 + 64 = 222, plus safe area padding
|
||||
// Position progress bar so controls section is anchored at bottom
|
||||
final bottomSafeArea = MediaQuery.of(context).padding.bottom;
|
||||
// Use viewPadding for consistency with player height calculation
|
||||
final bottomSafeArea = MediaQuery.of(context).viewPadding.bottom;
|
||||
final controlsSectionHeight = 222.0; // Total height of progress + controls + volume
|
||||
final playButtonHalfHeight = 36.0; // Half of the 72px play button container
|
||||
final expandedProgressTop = screenSize.height - bottomSafeArea - controlsSectionHeight - 24 - playButtonHalfHeight;
|
||||
@@ -1234,6 +1327,9 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
final expandedArtistTop = expandedTitleTop + expandedTitleHeight + titleToArtistGap;
|
||||
final artistTop = _lerpDouble(collapsedArtistTop, expandedArtistTop, t);
|
||||
|
||||
// Player name - only visible when collapsed (third line)
|
||||
final playerNameTop = MiniPlayerLayout.tertiaryTop;
|
||||
|
||||
// Album - subtle, below artist
|
||||
final expandedAlbumTop = expandedArtistTop + artistHeight + artistToAlbumGap;
|
||||
|
||||
@@ -1272,8 +1368,8 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
child: GestureDetector(
|
||||
// Use translucent to allow child widgets (like buttons) to receive taps
|
||||
behavior: HitTestBehavior.translucent,
|
||||
// Only handle tap when collapsed - when expanded, let children handle their own taps
|
||||
onTap: isExpanded ? null : expand,
|
||||
// Handle tap: when device list is visible, dismiss it; when collapsed, expand
|
||||
onTap: isExpanded ? null : (widget.isDeviceRevealVisible ? GlobalPlayerOverlay.dismissPlayerReveal : expand),
|
||||
onVerticalDragStart: (details) {
|
||||
// For expanded player or queue panel: start tracking immediately
|
||||
// For collapsed player: defer decision until we know swipe direction
|
||||
@@ -1317,9 +1413,39 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
},
|
||||
onHorizontalDragStart: (details) {
|
||||
_horizontalDragStartX = details.globalPosition.dx;
|
||||
// Start volume drag if device reveal is visible
|
||||
if (widget.isDeviceRevealVisible && !isExpanded) {
|
||||
final currentVolume = (selectedPlayer.volumeLevel ?? 0).toDouble() / 100.0;
|
||||
setState(() {
|
||||
_isDraggingVolume = true;
|
||||
_dragVolumeLevel = currentVolume;
|
||||
});
|
||||
HapticFeedback.lightImpact();
|
||||
}
|
||||
},
|
||||
onHorizontalDragUpdate: (details) {
|
||||
// Only handle in collapsed mode with multiple players
|
||||
// Volume swipe when device reveal is visible
|
||||
if (widget.isDeviceRevealVisible && _isDraggingVolume && !isExpanded) {
|
||||
// Directional volume: drag right = increase, drag left = decrease
|
||||
// Multiple swipes accumulate - each starts from current volume
|
||||
final dragDelta = details.delta.dx;
|
||||
final volumeDelta = dragDelta / collapsedWidth;
|
||||
final newVolume = (_dragVolumeLevel + volumeDelta).clamp(0.0, 1.0);
|
||||
if ((newVolume - _dragVolumeLevel).abs() > 0.001) {
|
||||
setState(() {
|
||||
_dragVolumeLevel = newVolume;
|
||||
});
|
||||
// Throttle API calls to prevent flooding
|
||||
final now = DateTime.now().millisecondsSinceEpoch;
|
||||
if (now - _lastVolumeUpdateTime >= _volumeThrottleMs) {
|
||||
_lastVolumeUpdateTime = now;
|
||||
maProvider.setVolume(selectedPlayer.playerId, (newVolume * 100).round());
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Only handle player swipe in collapsed mode with multiple players
|
||||
if (isExpanded || !hasMultiplePlayers) return;
|
||||
|
||||
// Ignore drags that started in the edge dead zone
|
||||
@@ -1332,6 +1458,18 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
_handleHorizontalDragUpdate(details, maProvider, collapsedWidth);
|
||||
},
|
||||
onHorizontalDragEnd: (details) {
|
||||
// End volume drag
|
||||
if (_isDraggingVolume) {
|
||||
// Send final volume on release
|
||||
maProvider.setVolume(selectedPlayer.playerId, (_dragVolumeLevel * 100).round());
|
||||
setState(() {
|
||||
_isDraggingVolume = false;
|
||||
});
|
||||
HapticFeedback.lightImpact();
|
||||
_horizontalDragStartX = null;
|
||||
return;
|
||||
}
|
||||
|
||||
// Ignore swipes that started near the edges (Android back gesture zone)
|
||||
final screenWidth = MediaQuery.of(context).size.width;
|
||||
final startedInDeadZone = _horizontalDragStartX != null &&
|
||||
@@ -1356,18 +1494,22 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
}
|
||||
},
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(borderRadius),
|
||||
border: selectedPlayer.isGrouped && t < 0.5
|
||||
? Border.all(color: _groupBorderColor, width: 1.5)
|
||||
: null,
|
||||
),
|
||||
// Use foregroundDecoration for border so it renders ON TOP of content
|
||||
// This prevents the album art from clipping the yellow synced border
|
||||
foregroundDecoration: maProvider.isPlayerManuallySynced(selectedPlayer.playerId) && t < 0.5
|
||||
? BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(borderRadius),
|
||||
border: Border.all(color: _groupBorderColor, width: 1.5),
|
||||
)
|
||||
: null,
|
||||
child: Material(
|
||||
color: backgroundColor,
|
||||
borderRadius: BorderRadius.circular(borderRadius),
|
||||
elevation: _lerpDouble(4, 0, t),
|
||||
shadowColor: Colors.black.withOpacity(0.3),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
// Use hardEdge when fully expanded (no border radius) to avoid anti-alias artifacts
|
||||
// Use antiAlias when collapsed/animating to smooth rounded corners
|
||||
clipBehavior: borderRadius > 0.5 ? Clip.antiAlias : Clip.hardEdge,
|
||||
child: SizedBox(
|
||||
width: width,
|
||||
height: height,
|
||||
@@ -1483,21 +1625,55 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
),
|
||||
|
||||
// Track title - with slide animation when collapsed
|
||||
// When hint is visible, show lightbulb icon + "Pull to select players"
|
||||
// When device reveal is visible, show player name instead of track name
|
||||
// Hidden during transition to prevent flash
|
||||
// FALLBACK: Show if transition active but no peek content available
|
||||
// GPU PERF: Use conditional instead of Opacity to avoid saveLayer
|
||||
if (!(_inTransition && t < 0.1 && _peekPlayer != null))
|
||||
// Hint text - vertically centered in mini player
|
||||
if (widget.isHintVisible && t < 0.5 && !(_inTransition && t < 0.1 && _peekPlayer != null))
|
||||
Positioned(
|
||||
left: titleLeft + miniPlayerSlideOffset,
|
||||
// Center vertically: (64 - ~20) / 2 = 22
|
||||
top: (MiniPlayerLayout.height - 20) / 2,
|
||||
child: SizedBox(
|
||||
width: titleWidth,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.lightbulb_outline,
|
||||
size: 16,
|
||||
color: textColor,
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Flexible(
|
||||
child: Text(
|
||||
S.of(context)!.pullToSelectPlayers,
|
||||
style: TextStyle(
|
||||
color: textColor,
|
||||
fontSize: titleFontSize,
|
||||
fontWeight: MiniPlayerLayout.primaryFontWeight,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Track title - with slide animation when collapsed
|
||||
// Hidden when hint is visible
|
||||
if (!(widget.isHintVisible && t < 0.5) && !(_inTransition && t < 0.1 && _peekPlayer != null))
|
||||
Positioned(
|
||||
left: titleLeft + miniPlayerSlideOffset,
|
||||
top: titleTop,
|
||||
child: SizedBox(
|
||||
width: titleWidth,
|
||||
child: Text(
|
||||
// Show player name when device reveal visible and collapsed
|
||||
(widget.isDeviceRevealVisible && t < 0.5)
|
||||
? selectedPlayer.name
|
||||
: currentTrack.name,
|
||||
currentTrack.name,
|
||||
style: TextStyle(
|
||||
color: textColor,
|
||||
fontSize: titleFontSize,
|
||||
@@ -1514,23 +1690,24 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
),
|
||||
|
||||
// Artist/Author name - with slide animation when collapsed
|
||||
// When hint is visible, show blank line
|
||||
// When device reveal is visible, show "Now Playing" hint
|
||||
// For audiobooks: show author from audiobook context
|
||||
// Hidden during transition to prevent flash
|
||||
// FALLBACK: Show if transition active but no peek content available
|
||||
// GPU PERF: Use conditional instead of Opacity to avoid saveLayer
|
||||
if (!(_inTransition && t < 0.1 && _peekPlayer != null))
|
||||
if (!(_inTransition && t < 0.1 && _peekPlayer != null) && !(widget.isHintVisible && t < 0.5))
|
||||
Positioned(
|
||||
left: titleLeft + miniPlayerSlideOffset,
|
||||
top: artistTop,
|
||||
child: SizedBox(
|
||||
width: titleWidth,
|
||||
child: Text(
|
||||
// Show "Now Playing" when device reveal visible and collapsed
|
||||
(widget.isDeviceRevealVisible && t < 0.5)
|
||||
? S.of(context)!.nowPlaying
|
||||
: maProvider.isPlayingAudiobook
|
||||
? (maProvider.currentAudiobook?.authorsString ?? S.of(context)!.unknownAuthor)
|
||||
// Always show artist/author/podcast name (was showing "Now Playing" when device reveal visible)
|
||||
maProvider.isPlayingAudiobook
|
||||
? (maProvider.currentAudiobook?.authorsString ?? S.of(context)!.unknownAuthor)
|
||||
: maProvider.isPlayingPodcast
|
||||
? (maProvider.currentPodcastName ?? S.of(context)!.podcasts)
|
||||
: currentTrack.artistsString,
|
||||
style: TextStyle(
|
||||
color: textColor.withOpacity(t > 0.5 ? 0.7 : MiniPlayerLayout.secondaryTextOpacity),
|
||||
@@ -1545,10 +1722,31 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
),
|
||||
),
|
||||
|
||||
// Player name - third line, only visible when collapsed
|
||||
// Same size as artist, same color as track
|
||||
if (t < 0.5 && !(_inTransition && t < 0.1 && _peekPlayer != null) && !(widget.isHintVisible && t < 0.5))
|
||||
Positioned(
|
||||
left: titleLeft + miniPlayerSlideOffset,
|
||||
top: playerNameTop,
|
||||
child: SizedBox(
|
||||
width: titleWidth,
|
||||
child: Text(
|
||||
selectedPlayer.name,
|
||||
style: TextStyle(
|
||||
color: textColor.withOpacity(1.0 - t * 2), // Fade out as expanding
|
||||
fontSize: MiniPlayerLayout.tertiaryFontSize,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Album name OR Chapter name (expanded only)
|
||||
// GPU PERF: Use color alpha instead of Opacity widget
|
||||
// For audiobooks: show current chapter; for music: show album
|
||||
if (t > 0.3 && (currentTrack.album != null || maProvider.isPlayingAudiobook))
|
||||
// For podcasts: hide album line since podcast name is already shown in artist position
|
||||
if (t > 0.3 && (currentTrack.album != null || maProvider.isPlayingAudiobook) && !maProvider.isPlayingPodcast)
|
||||
Positioned(
|
||||
left: contentPadding,
|
||||
right: contentPadding,
|
||||
@@ -1574,7 +1772,7 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
Positioned(
|
||||
left: contentPadding,
|
||||
right: contentPadding,
|
||||
top: expandedAlbumTop + (currentTrack.album != null ? 24 : 0),
|
||||
top: expandedAlbumTop + (maProvider.isPlayingAudiobook ? 24 : (currentTrack.album != null ? 24 : 0)),
|
||||
child: FadeTransition(
|
||||
opacity: _expandAnimation.drive(
|
||||
Tween(begin: 0.0, end: 1.0).chain(
|
||||
@@ -1697,24 +1895,130 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
),
|
||||
|
||||
// Playback controls - with slide animation when collapsed
|
||||
// Use skip 30s controls for audiobooks and podcasts
|
||||
Positioned(
|
||||
left: t > 0.5 ? 0 : null,
|
||||
right: t > 0.5 ? 0 : collapsedControlsRight - miniPlayerSlideOffset,
|
||||
top: controlsTop,
|
||||
child: maProvider.isPlayingAudiobook
|
||||
? _buildAudiobookControls(
|
||||
maProvider: maProvider,
|
||||
selectedPlayer: selectedPlayer,
|
||||
textColor: textColor,
|
||||
primaryColor: primaryColor,
|
||||
backgroundColor: backgroundColor,
|
||||
skipButtonSize: skipButtonSize,
|
||||
playButtonSize: playButtonSize,
|
||||
playButtonContainerSize: playButtonContainerSize,
|
||||
t: t,
|
||||
expandedElementsOpacity: expandedElementsOpacity,
|
||||
)
|
||||
: Row(
|
||||
child: (maProvider.isPlayingAudiobook || maProvider.isPlayingPodcast)
|
||||
// When device reveal is visible (player list shown), use compact controls
|
||||
// for audiobooks/podcasts: Play, Forward 30, Power
|
||||
? widget.isDeviceRevealVisible && t < 0.5
|
||||
? Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
// Play/Pause - compact like PlayerCard
|
||||
Transform.translate(
|
||||
offset: const Offset(3, 0),
|
||||
child: SizedBox(
|
||||
width: 44,
|
||||
height: 44,
|
||||
child: IconButton(
|
||||
icon: Icon(
|
||||
selectedPlayer.isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded,
|
||||
color: textColor,
|
||||
size: 28,
|
||||
),
|
||||
onPressed: () => maProvider.playPauseSelectedPlayer(),
|
||||
padding: EdgeInsets.zero,
|
||||
),
|
||||
),
|
||||
),
|
||||
// Forward 30 seconds
|
||||
Transform.translate(
|
||||
offset: const Offset(6, 0),
|
||||
child: IconButton(
|
||||
icon: Icon(
|
||||
Icons.forward_30_rounded,
|
||||
color: textColor,
|
||||
size: 28,
|
||||
),
|
||||
onPressed: () => maProvider.seekRelative(selectedPlayer.playerId, 30),
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(),
|
||||
),
|
||||
),
|
||||
// Power button
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
Icons.power_settings_new_rounded,
|
||||
color: selectedPlayer.powered ? textColor : textColor.withOpacity(0.5),
|
||||
size: 20,
|
||||
),
|
||||
onPressed: () => maProvider.togglePower(selectedPlayer.playerId),
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
)
|
||||
: _buildAudiobookControls(
|
||||
maProvider: maProvider,
|
||||
selectedPlayer: selectedPlayer,
|
||||
textColor: textColor,
|
||||
primaryColor: primaryColor,
|
||||
backgroundColor: backgroundColor,
|
||||
skipButtonSize: skipButtonSize,
|
||||
playButtonSize: playButtonSize,
|
||||
playButtonContainerSize: playButtonContainerSize,
|
||||
t: t,
|
||||
expandedElementsOpacity: expandedElementsOpacity,
|
||||
)
|
||||
// When device reveal is visible (player list shown), use compact controls
|
||||
// like PlayerCard: Play, Next, Power - matching other players in the list
|
||||
: widget.isDeviceRevealVisible && t < 0.5
|
||||
? Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
// Play/Pause - compact like PlayerCard
|
||||
// Touch target increased to 44dp for accessibility
|
||||
Transform.translate(
|
||||
offset: const Offset(3, 0),
|
||||
child: SizedBox(
|
||||
width: 44,
|
||||
height: 44,
|
||||
child: IconButton(
|
||||
icon: Icon(
|
||||
selectedPlayer.isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded,
|
||||
color: textColor,
|
||||
size: 28,
|
||||
),
|
||||
onPressed: () => maProvider.playPauseSelectedPlayer(),
|
||||
padding: EdgeInsets.zero,
|
||||
),
|
||||
),
|
||||
),
|
||||
// Skip next - nudged right like PlayerCard
|
||||
Transform.translate(
|
||||
offset: const Offset(6, 0),
|
||||
child: IconButton(
|
||||
icon: Icon(
|
||||
Icons.skip_next_rounded,
|
||||
color: textColor,
|
||||
size: 28,
|
||||
),
|
||||
onPressed: () => maProvider.nextTrackSelectedPlayer(),
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(),
|
||||
),
|
||||
),
|
||||
// Power button - smallest, like PlayerCard
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
Icons.power_settings_new_rounded,
|
||||
color: selectedPlayer.powered ? textColor : textColor.withOpacity(0.5),
|
||||
size: 20,
|
||||
),
|
||||
onPressed: () => maProvider.togglePower(selectedPlayer.playerId),
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
)
|
||||
: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
mainAxisAlignment: t > 0.5 ? MainAxisAlignment.center : MainAxisAlignment.end,
|
||||
children: [
|
||||
@@ -1905,6 +2209,32 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Volume swipe overlay (covers entire mini player when dragging volume)
|
||||
// Only visible when device reveal is open and user is dragging
|
||||
// Positioned last in Stack so it renders ON TOP of all content
|
||||
if (_isDraggingVolume && t < 0.5)
|
||||
Positioned.fill(
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(borderRadius),
|
||||
child: Stack(
|
||||
children: [
|
||||
// Unfilled (darker) background
|
||||
Container(color: collapsedBgUnplayed),
|
||||
// Filled (lighter) portion based on volume
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: FractionallySizedBox(
|
||||
widthFactor: _dragVolumeLevel.clamp(0.0, 1.0),
|
||||
heightFactor: 1.0,
|
||||
child: Container(color: collapsedBg),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -1942,12 +2272,15 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
final hasTrack = _peekTrack != null && peekImageUrl != null;
|
||||
final peekTrackName = hasTrack ? _peekTrack!.name : (peekPlayer?.name ?? S.of(context)!.unknown);
|
||||
final peekArtistName = hasTrack ? (_peekTrack!.artistsString ?? '') : S.of(context)!.swipeToSwitchDevice;
|
||||
// Show player name as third line only when playing
|
||||
final peekPlayerName = hasTrack ? (peekPlayer?.name ?? '') : null;
|
||||
|
||||
return Transform.translate(
|
||||
offset: Offset(peekBaseOffset, 0),
|
||||
child: MiniPlayerContent(
|
||||
primaryText: peekTrackName,
|
||||
secondaryText: peekArtistName,
|
||||
tertiaryText: peekPlayerName,
|
||||
imageUrl: hasTrack ? peekImageUrl : null,
|
||||
playerName: peekPlayer?.name ?? '',
|
||||
backgroundColor: backgroundColor,
|
||||
@@ -2062,7 +2395,8 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
}
|
||||
|
||||
/// Build audiobook-specific playback controls
|
||||
/// Layout: [Prev Chapter] [-30s] [Play/Pause] [+30s] [Next Chapter]
|
||||
/// Collapsed: [-30s] [Play/Pause] [+30s]
|
||||
/// Expanded: [Prev Chapter] [-30s] [-10s] [Play/Pause] [+10s] [+30s] [Next Chapter]
|
||||
Widget _buildAudiobookControls({
|
||||
required MusicAssistantProvider maProvider,
|
||||
required dynamic selectedPlayer,
|
||||
@@ -2076,19 +2410,20 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
required double expandedElementsOpacity,
|
||||
}) {
|
||||
final hasChapters = maProvider.currentAudiobook?.chapters?.isNotEmpty ?? false;
|
||||
final isExpanded = t > 0.5;
|
||||
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
mainAxisAlignment: t > 0.5 ? MainAxisAlignment.center : MainAxisAlignment.end,
|
||||
mainAxisAlignment: isExpanded ? MainAxisAlignment.center : MainAxisAlignment.end,
|
||||
children: [
|
||||
// Previous Chapter (expanded only, if chapters available)
|
||||
if (t > 0.5 && expandedElementsOpacity > 0.1 && hasChapters)
|
||||
if (isExpanded && expandedElementsOpacity > 0.1 && hasChapters)
|
||||
_buildSecondaryButton(
|
||||
icon: Icons.skip_previous_rounded,
|
||||
color: textColor.withOpacity(expandedElementsOpacity),
|
||||
onPressed: () => maProvider.seekToPreviousChapter(selectedPlayer.playerId),
|
||||
),
|
||||
if (t > 0.5 && hasChapters) SizedBox(width: _lerpDouble(0, 12, t)),
|
||||
if (isExpanded && hasChapters) SizedBox(width: _lerpDouble(0, 12, t)),
|
||||
|
||||
// Rewind 30 seconds
|
||||
_buildControlButton(
|
||||
@@ -2096,9 +2431,21 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
color: textColor,
|
||||
size: skipButtonSize,
|
||||
onPressed: () => maProvider.seekRelative(selectedPlayer.playerId, -30),
|
||||
useAnimation: t > 0.5,
|
||||
useAnimation: isExpanded,
|
||||
),
|
||||
SizedBox(width: _lerpDouble(0, 20, t)),
|
||||
|
||||
// Rewind 10 seconds (expanded only, same size as 30s)
|
||||
if (isExpanded) ...[
|
||||
SizedBox(width: _lerpDouble(0, 8, t)),
|
||||
_buildControlButton(
|
||||
icon: Icons.replay_10_rounded,
|
||||
color: textColor,
|
||||
size: skipButtonSize,
|
||||
onPressed: () => maProvider.seekRelative(selectedPlayer.playerId, -10),
|
||||
useAnimation: true,
|
||||
),
|
||||
],
|
||||
SizedBox(width: _lerpDouble(0, 12, t)),
|
||||
|
||||
// Play/Pause
|
||||
_buildPlayButton(
|
||||
@@ -2112,7 +2459,19 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
onPressed: () => maProvider.playPauseSelectedPlayer(),
|
||||
onLongPress: () => maProvider.stopPlayer(selectedPlayer.playerId),
|
||||
),
|
||||
SizedBox(width: _lerpDouble(0, 20, t)),
|
||||
SizedBox(width: _lerpDouble(0, 12, t)),
|
||||
|
||||
// Forward 10 seconds (expanded only, same size as 30s)
|
||||
if (isExpanded) ...[
|
||||
_buildControlButton(
|
||||
icon: Icons.forward_10_rounded,
|
||||
color: textColor,
|
||||
size: skipButtonSize,
|
||||
onPressed: () => maProvider.seekRelative(selectedPlayer.playerId, 10),
|
||||
useAnimation: true,
|
||||
),
|
||||
SizedBox(width: _lerpDouble(0, 8, t)),
|
||||
],
|
||||
|
||||
// Forward 30 seconds
|
||||
_buildControlButton(
|
||||
@@ -2120,12 +2479,12 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
color: textColor,
|
||||
size: skipButtonSize,
|
||||
onPressed: () => maProvider.seekRelative(selectedPlayer.playerId, 30),
|
||||
useAnimation: t > 0.5,
|
||||
useAnimation: isExpanded,
|
||||
),
|
||||
|
||||
// Next Chapter (expanded only, if chapters available)
|
||||
if (t > 0.5 && hasChapters) SizedBox(width: _lerpDouble(0, 12, t)),
|
||||
if (t > 0.5 && expandedElementsOpacity > 0.1 && hasChapters)
|
||||
if (isExpanded && hasChapters) SizedBox(width: _lerpDouble(0, 12, t)),
|
||||
if (isExpanded && expandedElementsOpacity > 0.1 && hasChapters)
|
||||
_buildSecondaryButton(
|
||||
icon: Icons.skip_next_rounded,
|
||||
color: textColor.withOpacity(expandedElementsOpacity),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:async';
|
||||
import 'dart:ui';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
@@ -5,8 +6,10 @@ import 'package:provider/provider.dart';
|
||||
import '../l10n/app_localizations.dart';
|
||||
import '../providers/music_assistant_provider.dart';
|
||||
import '../providers/navigation_provider.dart';
|
||||
import '../services/settings_service.dart';
|
||||
import '../theme/theme_provider.dart';
|
||||
import 'expandable_player.dart';
|
||||
import 'player/mini_player_content.dart' show MiniPlayerLayout;
|
||||
import 'player/player_reveal_overlay.dart';
|
||||
|
||||
/// Cached color with contrast adjustment
|
||||
@@ -54,14 +57,14 @@ class BottomSpacing {
|
||||
/// Height of the bottom navigation bar
|
||||
static const double navBarHeight = 56.0;
|
||||
|
||||
/// Height of mini player when visible (64px height + 12px margin)
|
||||
static const double miniPlayerHeight = 76.0;
|
||||
/// Height of mini player when visible (height + 12px margin)
|
||||
static double get miniPlayerHeight => MiniPlayerLayout.height + 12.0;
|
||||
|
||||
/// Space needed when only nav bar is visible (with some extra padding)
|
||||
static const double navBarOnly = navBarHeight + 16.0;
|
||||
|
||||
/// Space needed when mini player is also visible
|
||||
static const double withMiniPlayer = navBarHeight + miniPlayerHeight + 22.0;
|
||||
static double get withMiniPlayer => navBarHeight + miniPlayerHeight + 22.0;
|
||||
}
|
||||
|
||||
/// ValueNotifier for player expansion progress (0.0 to 1.0) and background color
|
||||
@@ -130,7 +133,7 @@ class GlobalPlayerOverlay extends StatefulWidget {
|
||||
_overlayStateKey.currentState?._dismissPlayerReveal();
|
||||
}
|
||||
|
||||
/// Trigger the bounce animation on mini player (called when overlay dismiss starts)
|
||||
/// Trigger single bounce on mini player (called when device selector collapses)
|
||||
static void triggerBounce() {
|
||||
_overlayStateKey.currentState?._triggerBounce();
|
||||
}
|
||||
@@ -145,17 +148,40 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
|
||||
late AnimationController _slideController;
|
||||
late Animation<double> _slideAnimation;
|
||||
|
||||
// Controller for player reveal animation with bounce
|
||||
late AnimationController _bounceController;
|
||||
late Animation<double> _bounceAnimation;
|
||||
// Single bounce controller for device selector expand/collapse
|
||||
late AnimationController _singleBounceController;
|
||||
|
||||
// Double bounce controller for hint
|
||||
late AnimationController _doubleBounceController;
|
||||
|
||||
// State for player reveal overlay
|
||||
bool _isRevealVisible = false;
|
||||
|
||||
// Use ValueNotifier instead of setState for bounce offset
|
||||
// This prevents full widget tree rebuilds during animation
|
||||
// State for interactive hint mode (blur backdrop + wait for user action)
|
||||
bool _isHintModeActive = false;
|
||||
Timer? _hintBounceTimer;
|
||||
|
||||
// Track if player reveal was triggered from onboarding (for showing extra hints)
|
||||
bool _isOnboardingReveal = false;
|
||||
|
||||
// Bounce offset for mini player (used by both single and double bounce)
|
||||
final _bounceOffsetNotifier = ValueNotifier<double>(0.0);
|
||||
|
||||
// Hint system state
|
||||
// NOTE: AppStartup now handles the settings loading gate. It waits for:
|
||||
// - First-time users: connected + player selected before showing HomeScreen
|
||||
// - Returning users: connected before showing HomeScreen
|
||||
// This eliminates the race condition that caused home screen flash.
|
||||
bool _showHints = true;
|
||||
bool _hasCompletedOnboarding = false; // First-use welcome screen
|
||||
bool _hintTriggered = false; // Prevent multiple triggers per session
|
||||
bool _settingsLoaded = false; // True once settings have been loaded from storage
|
||||
bool _miniPlayerHintsReady = false; // True once connected with player (can show hints)
|
||||
final _hintOpacityNotifier = ValueNotifier<double>(0.0);
|
||||
|
||||
// Welcome content fade-in animation
|
||||
late AnimationController _welcomeFadeController;
|
||||
|
||||
// Key for the reveal overlay
|
||||
final _revealKey = GlobalKey<PlayerRevealOverlayState>();
|
||||
|
||||
@@ -172,30 +198,134 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
|
||||
reverseCurve: Curves.easeInCubic,
|
||||
);
|
||||
|
||||
// Bounce animation - quick dip down then back up
|
||||
_bounceController = AnimationController(
|
||||
duration: const Duration(milliseconds: 200),
|
||||
// Single bounce for device selector expand/collapse
|
||||
_singleBounceController = AnimationController(
|
||||
duration: const Duration(milliseconds: 400),
|
||||
vsync: this,
|
||||
);
|
||||
_bounceAnimation = CurvedAnimation(
|
||||
parent: _bounceController,
|
||||
curve: Curves.easeOut,
|
||||
_singleBounceController.addListener(() {
|
||||
final t = Curves.easeOut.transform(_singleBounceController.value);
|
||||
// Single bounce: up to 10px then back to 0
|
||||
if (t < 0.5) {
|
||||
_bounceOffsetNotifier.value = 10.0 * (t * 2); // 0 -> 10
|
||||
} else {
|
||||
_bounceOffsetNotifier.value = 10.0 * ((1.0 - t) * 2); // 10 -> 0
|
||||
}
|
||||
});
|
||||
|
||||
// Hint bounce - single gentle bounce to draw attention
|
||||
_doubleBounceController = AnimationController(
|
||||
duration: const Duration(milliseconds: 600),
|
||||
vsync: this,
|
||||
);
|
||||
_doubleBounceController.addListener(() {
|
||||
final t = Curves.easeOut.transform(_doubleBounceController.value);
|
||||
// Single bounce: up 20px then back down
|
||||
if (t < 0.5) {
|
||||
_bounceOffsetNotifier.value = 20.0 * (t * 2); // 0 -> 20
|
||||
} else {
|
||||
_bounceOffsetNotifier.value = 20.0 * ((1.0 - t) * 2); // 20 -> 0
|
||||
}
|
||||
});
|
||||
|
||||
// Welcome content fade-in
|
||||
_welcomeFadeController = AnimationController(
|
||||
duration: const Duration(milliseconds: 800),
|
||||
vsync: this,
|
||||
);
|
||||
|
||||
// Use ValueNotifier instead of setState to avoid full widget rebuilds
|
||||
// This isolates the rebuild to only the widgets that depend on bounce offset
|
||||
_bounceController.addListener(() {
|
||||
final t = _bounceAnimation.value;
|
||||
// Sine curve: 0 -> 1 -> 0 as t goes 0 -> 0.5 -> 1
|
||||
_bounceOffsetNotifier.value = 10.0 * (t < 0.5 ? t * 2 : (1.0 - t) * 2);
|
||||
// Load hint settings and start welcome immediately if needed
|
||||
_loadHintSettings();
|
||||
}
|
||||
|
||||
Future<void> _loadHintSettings() async {
|
||||
_showHints = await SettingsService.getShowHints();
|
||||
_hasCompletedOnboarding = await SettingsService.getHasCompletedOnboarding();
|
||||
if (!mounted) return;
|
||||
|
||||
setState(() {
|
||||
_settingsLoaded = true;
|
||||
});
|
||||
|
||||
// If first-time user and already connected (AppStartup waited for us),
|
||||
// start welcome screen immediately - no race condition possible
|
||||
if (!_hasCompletedOnboarding && !_hintTriggered) {
|
||||
final provider = context.read<MusicAssistantProvider>();
|
||||
if (provider.isConnected && provider.selectedPlayer != null) {
|
||||
_miniPlayerHintsReady = true;
|
||||
_startWelcomeScreen();
|
||||
_startMiniPlayerBounce();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
// Check if we should enable mini player hints now that we have connection
|
||||
_checkConnectionForMiniPlayerHints();
|
||||
}
|
||||
|
||||
/// Check connection state and start welcome screen if appropriate.
|
||||
/// This is called from multiple places:
|
||||
/// 1. didChangeDependencies() - when widget first builds
|
||||
/// 2. _loadHintSettings() - when settings finish loading
|
||||
/// 3. build() - when provider state changes (via post-frame callback)
|
||||
void _checkConnectionForMiniPlayerHints() {
|
||||
if (_hintTriggered || !mounted || !_settingsLoaded) return;
|
||||
if (_hasCompletedOnboarding) return; // Not first-time user
|
||||
|
||||
final provider = context.read<MusicAssistantProvider>();
|
||||
if (provider.isConnected && provider.selectedPlayer != null) {
|
||||
// Connected with a player - start welcome screen now
|
||||
_miniPlayerHintsReady = true;
|
||||
_startWelcomeScreen();
|
||||
// Start the bounce animation now that mini player is visible
|
||||
_startMiniPlayerBounce();
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the bounce animation for mini player hints
|
||||
void _startMiniPlayerBounce() {
|
||||
if (!_isHintModeActive || !mounted) return;
|
||||
_doubleBounceController.reset();
|
||||
_doubleBounceController.forward();
|
||||
|
||||
// Repeat bounce every 2 seconds
|
||||
_hintBounceTimer?.cancel();
|
||||
_hintBounceTimer = Timer.periodic(const Duration(seconds: 2), (_) {
|
||||
if (_isHintModeActive && mounted) {
|
||||
_doubleBounceController.reset();
|
||||
_doubleBounceController.forward();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Start the welcome screen with fade-in animation
|
||||
void _startWelcomeScreen() {
|
||||
if (_hintTriggered) return;
|
||||
_hintTriggered = true;
|
||||
|
||||
// Activate hint mode immediately (blur backdrop visible)
|
||||
setState(() {
|
||||
_isHintModeActive = true;
|
||||
});
|
||||
|
||||
// Fade in welcome content (logo + title)
|
||||
_welcomeFadeController.forward();
|
||||
|
||||
// Mini player bounce is started separately once connected via _startMiniPlayerBounce()
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_hintBounceTimer?.cancel();
|
||||
_slideController.dispose();
|
||||
_bounceController.dispose();
|
||||
_singleBounceController.dispose();
|
||||
_doubleBounceController.dispose();
|
||||
_welcomeFadeController.dispose();
|
||||
_bounceOffsetNotifier.dispose();
|
||||
_hintOpacityNotifier.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -213,11 +343,29 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
|
||||
GlobalPlayerOverlay.collapsePlayer();
|
||||
}
|
||||
HapticFeedback.mediumImpact();
|
||||
_bounceController.reset();
|
||||
|
||||
// Track if coming from hint mode (for onboarding hints in player selector)
|
||||
final wasInHintMode = _isHintModeActive;
|
||||
|
||||
// End hint mode if active (user learned the gesture!)
|
||||
_hintBounceTimer?.cancel();
|
||||
_hintBounceTimer = null;
|
||||
_hintOpacityNotifier.value = 0.0;
|
||||
_isHintModeActive = false;
|
||||
|
||||
// Mark onboarding as completed if coming from welcome screen
|
||||
if (wasInHintMode) {
|
||||
SettingsService.setHasCompletedOnboarding(true);
|
||||
}
|
||||
|
||||
// Trigger single bounce on expand
|
||||
_singleBounceController.reset();
|
||||
_singleBounceController.forward();
|
||||
|
||||
setState(() {
|
||||
_isRevealVisible = true;
|
||||
_isOnboardingReveal = wasInHintMode;
|
||||
});
|
||||
_bounceController.forward();
|
||||
}
|
||||
|
||||
void _hidePlayerReveal() {
|
||||
@@ -225,6 +373,7 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
|
||||
_bounceOffsetNotifier.value = 0;
|
||||
setState(() {
|
||||
_isRevealVisible = false;
|
||||
_isOnboardingReveal = false;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -232,14 +381,27 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
|
||||
void _dismissPlayerReveal() {
|
||||
if (!_isRevealVisible) return;
|
||||
// Call the overlay's dismiss method which has the slide animation
|
||||
// Note: dismiss() triggers the bounce animation internally
|
||||
_revealKey.currentState?.dismiss();
|
||||
}
|
||||
|
||||
/// Trigger bounce animation on mini player
|
||||
/// Trigger single bounce on mini player (called when device selector collapses)
|
||||
void _triggerBounce() {
|
||||
_bounceController.reset();
|
||||
_bounceController.forward();
|
||||
_singleBounceController.reset();
|
||||
_singleBounceController.forward();
|
||||
}
|
||||
|
||||
/// End hint mode (called when user taps skip button)
|
||||
void _endHintMode() {
|
||||
if (!_isHintModeActive) return;
|
||||
_hintBounceTimer?.cancel();
|
||||
_hintBounceTimer = null;
|
||||
_hintOpacityNotifier.value = 0.0;
|
||||
_bounceOffsetNotifier.value = 0.0;
|
||||
// Mark onboarding as completed (first use only)
|
||||
SettingsService.setHasCompletedOnboarding(true);
|
||||
setState(() {
|
||||
_isHintModeActive = false;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -247,12 +409,46 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
|
||||
final theme = Theme.of(context);
|
||||
final colorScheme = theme.colorScheme;
|
||||
|
||||
// Handle back gesture at top level - dismiss device list if visible
|
||||
// Watch provider to trigger rebuilds when connection state changes
|
||||
final provider = context.watch<MusicAssistantProvider>();
|
||||
|
||||
// Compute whether this is a first-time user ready for welcome screen.
|
||||
// This is SYNCHRONOUS - no setState needed - so it works in the same frame.
|
||||
final isFirstTimeUserReady = _settingsLoaded &&
|
||||
!_hasCompletedOnboarding &&
|
||||
provider.isConnected &&
|
||||
provider.selectedPlayer != null;
|
||||
|
||||
// Show welcome backdrop if:
|
||||
// 1. Already in hint mode (_isHintModeActive), OR
|
||||
// 2. First-time user ready but hint mode not started yet (!_hintTriggered)
|
||||
// This ensures backdrop appears IMMEDIATELY when HomeScreen renders,
|
||||
// preventing the flash. Welcome content fades in after via animation.
|
||||
final shouldShowWelcomeBackdrop = _isHintModeActive ||
|
||||
(isFirstTimeUserReady && !_hintTriggered);
|
||||
|
||||
// Trigger hint mode if conditions are met (for animations, bounce, etc)
|
||||
if (isFirstTimeUserReady && !_hintTriggered) {
|
||||
// Schedule for post-frame to avoid setState during build
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted && !_hintTriggered) {
|
||||
_miniPlayerHintsReady = true;
|
||||
_startWelcomeScreen();
|
||||
_startMiniPlayerBounce();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Handle back gesture at top level - dismiss hint mode or device list if visible
|
||||
return PopScope(
|
||||
canPop: !_isRevealVisible,
|
||||
canPop: !_isRevealVisible && !_isHintModeActive,
|
||||
onPopInvokedWithResult: (didPop, result) {
|
||||
if (!didPop && _isRevealVisible) {
|
||||
_dismissPlayerReveal();
|
||||
if (!didPop) {
|
||||
if (_isHintModeActive) {
|
||||
_endHintMode();
|
||||
} else if (_isRevealVisible) {
|
||||
_dismissPlayerReveal();
|
||||
}
|
||||
}
|
||||
},
|
||||
child: Stack(
|
||||
@@ -264,14 +460,18 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
|
||||
child: widget.child,
|
||||
),
|
||||
// Global persistent bottom navigation bar - positioned at bottom
|
||||
Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
child: ListenableBuilder(
|
||||
listenable: navigationProvider,
|
||||
builder: (context, _) {
|
||||
return Consumer<ThemeProvider>(
|
||||
// Hide when: not connected, no player selected, OR showing welcome screen
|
||||
// For first-time users, selectedPlayer becomes non-null at the same time
|
||||
// as shouldShowWelcomeBackdrop becomes true, preventing any gap.
|
||||
if (provider.isConnected && provider.selectedPlayer != null && !shouldShowWelcomeBackdrop)
|
||||
Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
child: ListenableBuilder(
|
||||
listenable: navigationProvider,
|
||||
builder: (context, _) {
|
||||
return Consumer<ThemeProvider>(
|
||||
builder: (context, themeProvider, _) {
|
||||
// Use adaptive primary color for bottom nav when adaptive theme is enabled
|
||||
final sourceColor = themeProvider.adaptiveTheme
|
||||
@@ -360,57 +560,171 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
// Blur backdrop when device selector is open
|
||||
if (_isRevealVisible)
|
||||
// Blur backdrop for device selector (reveal mode) - static, no animation
|
||||
if (_isRevealVisible && !_isHintModeActive)
|
||||
Positioned.fill(
|
||||
child: IgnorePointer(
|
||||
child: GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: _dismissPlayerReveal,
|
||||
child: BackdropFilter(
|
||||
filter: ImageFilter.blur(sigmaX: 8.0, sigmaY: 8.0),
|
||||
child: Container(
|
||||
color: Colors.black.withOpacity(0.1),
|
||||
color: colorScheme.surface.withOpacity(0.5),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Welcome/hint backdrop - shows IMMEDIATELY when first-time user is ready.
|
||||
// Uses computed `shouldShowWelcomeBackdrop` which is true BEFORE _isHintModeActive,
|
||||
// preventing the 1-frame gap where home screen would be visible.
|
||||
if (shouldShowWelcomeBackdrop)
|
||||
Positioned.fill(
|
||||
child: TweenAnimationBuilder<double>(
|
||||
// Hold solid for 2s, then fade to 0.5 over 1s
|
||||
tween: Tween<double>(begin: 1.0, end: 0.5),
|
||||
duration: const Duration(seconds: 3),
|
||||
curve: const Interval(0.67, 1.0, curve: Curves.easeOut),
|
||||
builder: (context, opacity, child) {
|
||||
return BackdropFilter(
|
||||
filter: ImageFilter.blur(sigmaX: 8.0, sigmaY: 8.0),
|
||||
child: Container(
|
||||
// Use same dark color as connection screen for seamless transition
|
||||
color: const Color(0xFF1a1a1a).withOpacity(opacity),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
|
||||
// Welcome message during hint mode - two positioned sections with fade-in
|
||||
// Top section: Logo and Welcome title (stays fixed at top area)
|
||||
if (_isHintModeActive)
|
||||
Positioned(
|
||||
left: 24,
|
||||
right: 24,
|
||||
// Position logo section high up - about 1/3 from top
|
||||
top: MediaQuery.of(context).size.height * 0.15,
|
||||
child: FadeTransition(
|
||||
opacity: CurvedAnimation(
|
||||
parent: _welcomeFadeController,
|
||||
curve: Curves.easeOut,
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Ensemble logo - same as settings screen
|
||||
Image.asset(
|
||||
'assets/images/ensemble_icon_transparent.png',
|
||||
width: MediaQuery.of(context).size.width * 0.5,
|
||||
fit: BoxFit.contain,
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
// Welcome title
|
||||
Text(
|
||||
S.of(context)!.welcomeToEnsemble,
|
||||
style: theme.textTheme.headlineSmall?.copyWith(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Bottom section: Hint text and Skip button (only show once mini player is visible)
|
||||
if (_isHintModeActive && _miniPlayerHintsReady)
|
||||
Positioned(
|
||||
left: 24,
|
||||
right: 24,
|
||||
// Position so skip button is ~32px above mini player, matching skip-to-miniplayer gap
|
||||
// Use viewPadding to match BottomNavigationBar's height calculation
|
||||
bottom: BottomSpacing.navBarHeight + BottomSpacing.miniPlayerHeight + MediaQuery.of(context).viewPadding.bottom + 32,
|
||||
child: FadeTransition(
|
||||
opacity: CurvedAnimation(
|
||||
parent: _welcomeFadeController,
|
||||
curve: Curves.easeOut,
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Hint text
|
||||
Text(
|
||||
S.of(context)!.welcomeMessage,
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
color: Colors.white,
|
||||
fontSize: 16,
|
||||
height: 1.4,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
// Skip button - same gap above as below to mini player
|
||||
TextButton(
|
||||
onPressed: _endHintMode,
|
||||
child: Text(
|
||||
S.of(context)!.skip,
|
||||
style: TextStyle(
|
||||
color: Colors.white.withOpacity(0.7),
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Player reveal overlay - renders BELOW mini player so cards slide behind it
|
||||
if (_isRevealVisible)
|
||||
PlayerRevealOverlay(
|
||||
key: _revealKey,
|
||||
onDismiss: _hidePlayerReveal,
|
||||
miniPlayerBottom: BottomSpacing.navBarHeight + MediaQuery.of(context).padding.bottom + 12,
|
||||
// Use viewPadding to match BottomNavigationBar's height calculation
|
||||
miniPlayerBottom: BottomSpacing.navBarHeight + MediaQuery.of(context).viewPadding.bottom + 12,
|
||||
miniPlayerHeight: 64,
|
||||
showOnboardingHints: _isOnboardingReveal,
|
||||
),
|
||||
|
||||
// Global player overlay - renders ON TOP so cards slide behind it
|
||||
// Use Selector instead of Consumer to avoid rebuilds during animation
|
||||
Selector<MusicAssistantProvider, ({bool isConnected, bool hasPlayer})>(
|
||||
Selector<MusicAssistantProvider, ({bool isConnected, bool hasPlayer, bool hasTrack})>(
|
||||
selector: (_, provider) => (
|
||||
isConnected: provider.isConnected,
|
||||
hasPlayer: provider.selectedPlayer != null,
|
||||
hasTrack: provider.currentTrack != null,
|
||||
),
|
||||
builder: (context, state, child) {
|
||||
// Only show player if connected and has a selected player
|
||||
if (!state.isConnected || !state.hasPlayer) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
// Combine slide and bounce animations with ValueListenableBuilder
|
||||
|
||||
// Combine slide, bounce, and hint animations with ValueListenableBuilders
|
||||
// This prevents full widget tree rebuilds - only ExpandablePlayer updates
|
||||
return ValueListenableBuilder<double>(
|
||||
valueListenable: _bounceOffsetNotifier,
|
||||
builder: (context, bounceOffset, _) {
|
||||
return AnimatedBuilder(
|
||||
animation: _slideAnimation,
|
||||
builder: (context, _) {
|
||||
return ExpandablePlayer(
|
||||
key: globalPlayerKey,
|
||||
slideOffset: _slideAnimation.value,
|
||||
bounceOffset: bounceOffset,
|
||||
onRevealPlayers: _showPlayerReveal,
|
||||
isDeviceRevealVisible: _isRevealVisible,
|
||||
return ValueListenableBuilder<double>(
|
||||
valueListenable: _hintOpacityNotifier,
|
||||
builder: (context, hintOpacity, _) {
|
||||
return AnimatedBuilder(
|
||||
animation: _slideAnimation,
|
||||
builder: (context, _) {
|
||||
return ExpandablePlayer(
|
||||
key: globalPlayerKey,
|
||||
slideOffset: _slideAnimation.value,
|
||||
bounceOffset: bounceOffset,
|
||||
onRevealPlayers: _showPlayerReveal,
|
||||
isDeviceRevealVisible: _isRevealVisible,
|
||||
isHintVisible: hintOpacity > 0,
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// A scrollbar that shows a letter popup when dragging, for fast navigation
|
||||
/// through alphabetically sorted lists.
|
||||
class LetterScrollbar extends StatefulWidget {
|
||||
/// The scrollable child widget (ListView, GridView, etc.)
|
||||
final Widget child;
|
||||
|
||||
/// The scroll controller for the child
|
||||
final ScrollController controller;
|
||||
|
||||
/// List of items to extract letters from (must be sorted alphabetically)
|
||||
/// Each item's first character is used to determine the letter
|
||||
final List<String> items;
|
||||
|
||||
/// Callback when user taps/drags to a specific index
|
||||
final void Function(int index)? onScrollToIndex;
|
||||
|
||||
/// Callback when drag state changes (for disabling scroll-to-hide)
|
||||
final void Function(bool isDragging)? onDragStateChanged;
|
||||
|
||||
const LetterScrollbar({
|
||||
super.key,
|
||||
required this.child,
|
||||
required this.controller,
|
||||
required this.items,
|
||||
this.onScrollToIndex,
|
||||
this.onDragStateChanged,
|
||||
});
|
||||
|
||||
@override
|
||||
State<LetterScrollbar> createState() => _LetterScrollbarState();
|
||||
}
|
||||
|
||||
class _LetterScrollbarState extends State<LetterScrollbar> {
|
||||
bool _isDragging = false;
|
||||
String _currentLetter = '';
|
||||
double _dragPosition = 0;
|
||||
double _scrollFraction = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
widget.controller.addListener(_onScrollChanged);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
widget.controller.removeListener(_onScrollChanged);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onScrollChanged() {
|
||||
if (!_isDragging && widget.controller.hasClients) {
|
||||
final position = widget.controller.position;
|
||||
if (position.maxScrollExtent > 0) {
|
||||
final newFraction = (position.pixels / position.maxScrollExtent).clamp(0.0, 1.0);
|
||||
// PERF: Only rebuild if fraction changed by more than 1% to reduce rebuilds
|
||||
if ((newFraction - _scrollFraction).abs() > 0.01) {
|
||||
setState(() {
|
||||
_scrollFraction = newFraction;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build a map of letter -> first index for that letter
|
||||
Map<String, int> get _letterIndexMap {
|
||||
final map = <String, int>{};
|
||||
for (int i = 0; i < widget.items.length; i++) {
|
||||
final item = widget.items[i];
|
||||
if (item.isNotEmpty) {
|
||||
final letter = item[0].toUpperCase();
|
||||
if (!map.containsKey(letter)) {
|
||||
map[letter] = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
String _getLetterAtPosition(double position, double maxHeight) {
|
||||
if (widget.items.isEmpty || maxHeight <= 0) return '';
|
||||
|
||||
// Calculate which item index corresponds to this position
|
||||
final fraction = (position / maxHeight).clamp(0.0, 1.0);
|
||||
final index = (fraction * (widget.items.length - 1)).round();
|
||||
|
||||
if (index >= 0 && index < widget.items.length) {
|
||||
final item = widget.items[index];
|
||||
if (item.isNotEmpty) {
|
||||
return item[0].toUpperCase();
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
void _scrollToLetter(String letter) {
|
||||
final letterMap = _letterIndexMap;
|
||||
if (letterMap.containsKey(letter)) {
|
||||
final index = letterMap[letter]!;
|
||||
if (widget.onScrollToIndex != null) {
|
||||
widget.onScrollToIndex!(index);
|
||||
} else {
|
||||
// Estimate scroll position based on index
|
||||
// This is approximate - works better with fixed height items
|
||||
final scrollController = widget.controller;
|
||||
if (scrollController.hasClients) {
|
||||
final maxScroll = scrollController.position.maxScrollExtent;
|
||||
final fraction = index / widget.items.length;
|
||||
final targetScroll = (fraction * maxScroll).clamp(0.0, maxScroll);
|
||||
|
||||
// Update scroll fraction immediately for smooth thumb tracking
|
||||
setState(() {
|
||||
_scrollFraction = fraction;
|
||||
});
|
||||
|
||||
scrollController.jumpTo(targetScroll);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _handleDragStart(DragStartDetails details) {
|
||||
setState(() {
|
||||
_isDragging = true;
|
||||
_dragPosition = details.localPosition.dy;
|
||||
});
|
||||
widget.onDragStateChanged?.call(true);
|
||||
_updateLetterAndScroll(details.localPosition.dy);
|
||||
}
|
||||
|
||||
void _handleDragUpdate(DragUpdateDetails details) {
|
||||
setState(() {
|
||||
_dragPosition = details.localPosition.dy;
|
||||
});
|
||||
_updateLetterAndScroll(details.localPosition.dy);
|
||||
}
|
||||
|
||||
void _handleDragEnd(DragEndDetails details) {
|
||||
setState(() {
|
||||
_isDragging = false;
|
||||
});
|
||||
widget.onDragStateChanged?.call(false);
|
||||
}
|
||||
|
||||
void _updateLetterAndScroll(double position) {
|
||||
final renderBox = context.findRenderObject() as RenderBox?;
|
||||
if (renderBox != null) {
|
||||
final height = renderBox.size.height;
|
||||
final letter = _getLetterAtPosition(position, height);
|
||||
if (letter.isNotEmpty && letter != _currentLetter) {
|
||||
setState(() {
|
||||
_currentLetter = letter;
|
||||
});
|
||||
_scrollToLetter(letter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return Stack(
|
||||
children: [
|
||||
// The scrollable content
|
||||
widget.child,
|
||||
|
||||
// The draggable scrollbar area (right edge) - wider grab area
|
||||
Positioned(
|
||||
right: 0,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
width: 32, // Wider grab area
|
||||
child: GestureDetector(
|
||||
onVerticalDragStart: _handleDragStart,
|
||||
onVerticalDragUpdate: _handleDragUpdate,
|
||||
onVerticalDragEnd: _handleDragEnd,
|
||||
onTapDown: (details) {
|
||||
_handleDragStart(DragStartDetails(
|
||||
localPosition: details.localPosition,
|
||||
globalPosition: details.globalPosition,
|
||||
));
|
||||
},
|
||||
onTapUp: (_) {
|
||||
setState(() {
|
||||
_isDragging = false;
|
||||
});
|
||||
widget.onDragStateChanged?.call(false);
|
||||
},
|
||||
behavior: HitTestBehavior.translucent,
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final trackHeight = constraints.maxHeight;
|
||||
final thumbHeight = _isDragging ? 60.0 : 40.0;
|
||||
final availableTrack = trackHeight - thumbHeight;
|
||||
final thumbTop = availableTrack * _scrollFraction;
|
||||
|
||||
return Stack(
|
||||
children: [
|
||||
// Thumb that tracks scroll position - use AnimatedPositioned for smooth motion
|
||||
AnimatedPositioned(
|
||||
duration: const Duration(milliseconds: 50),
|
||||
curve: Curves.linear,
|
||||
top: thumbTop,
|
||||
right: 4,
|
||||
child: AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 100),
|
||||
width: _isDragging ? 6 : 4,
|
||||
height: thumbHeight,
|
||||
decoration: BoxDecoration(
|
||||
color: _isDragging
|
||||
? colorScheme.primary
|
||||
: colorScheme.onSurface.withOpacity(0.3),
|
||||
borderRadius: BorderRadius.circular(3),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// The letter popup bubble
|
||||
if (_isDragging && _currentLetter.isNotEmpty)
|
||||
Positioned(
|
||||
right: 48,
|
||||
top: _dragPosition - 28,
|
||||
child: Material(
|
||||
elevation: 4,
|
||||
color: colorScheme.primaryContainer,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Container(
|
||||
width: 56,
|
||||
height: 56,
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
_currentLetter,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onPrimaryContainer,
|
||||
fontSize: 28,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ class DeviceSelectorBar extends StatelessWidget {
|
||||
final GestureDragStartCallback? onHorizontalDragStart;
|
||||
final GestureDragUpdateCallback? onHorizontalDragUpdate;
|
||||
final GestureDragEndCallback? onHorizontalDragEnd;
|
||||
final VoidCallback? onPowerToggle;
|
||||
|
||||
const DeviceSelectorBar({
|
||||
super.key,
|
||||
@@ -31,6 +32,7 @@ class DeviceSelectorBar extends StatelessWidget {
|
||||
this.onHorizontalDragStart,
|
||||
this.onHorizontalDragUpdate,
|
||||
this.onHorizontalDragEnd,
|
||||
this.onPowerToggle,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -67,6 +69,9 @@ class DeviceSelectorBar extends StatelessWidget {
|
||||
textColor: textColor,
|
||||
width: width,
|
||||
slideOffset: slideOffset,
|
||||
isHint: swipeHint != null,
|
||||
onPowerToggle: onPowerToggle,
|
||||
isPoweredOn: selectedPlayer.powered,
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -97,6 +102,7 @@ class DeviceSelectorBar extends StatelessWidget {
|
||||
textColor: textColor,
|
||||
width: width,
|
||||
slideOffset: 0, // No additional slide - Transform handles positioning
|
||||
isHint: swipeHint != null,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,18 +3,27 @@ import 'package:cached_network_image/cached_network_image.dart';
|
||||
|
||||
/// Shared constants for mini player layout
|
||||
class MiniPlayerLayout {
|
||||
static const double height = 64.0;
|
||||
static const double artSize = 64.0;
|
||||
static const double height = 72.0;
|
||||
static const double artSize = 72.0;
|
||||
static const double textLeftOffset = 10.0; // Gap between art and text
|
||||
static const double textLeft = artSize + textLeftOffset; // 74px
|
||||
static const double primaryTop = 13.0;
|
||||
static const double secondaryTop = 33.0;
|
||||
static const double textLeft = artSize + textLeftOffset; // 82px
|
||||
// 3-line layout: track, artist, player
|
||||
static const double primaryTop = 5.0; // raised slightly from 7
|
||||
static const double secondaryTop = 26.0; // raised by 1
|
||||
static const double tertiaryTop = 46.0;
|
||||
// 2-line layout (evenly spaced): player name, hint
|
||||
// Height 72 / 3 = 24px spacing. Line 1 center at 24, Line 2 center at 48
|
||||
static const double primaryTop2Line = 14.0; // 24 - (18/2) = 15, adjusted to 14
|
||||
static const double secondaryTop2Line = 40.0; // raised slightly from 42
|
||||
static const double textRightPadding = 12.0;
|
||||
static const double powerButtonSize = 40.0; // Power button tap area
|
||||
static const double iconSize = 28.0;
|
||||
static const double iconOpacity = 0.4;
|
||||
static const double secondaryTextOpacity = 0.6;
|
||||
static const double primaryFontSize = 16.0;
|
||||
static const double primaryFontSize = 16.0; // 3-line playing mode
|
||||
static const double primaryFontSize2Line = 18.0; // larger for 2-line off mode
|
||||
static const double secondaryFontSize = 14.0;
|
||||
static const double tertiaryFontSize = 14.0;
|
||||
static const FontWeight primaryFontWeight = FontWeight.w500;
|
||||
}
|
||||
|
||||
@@ -30,6 +39,10 @@ class MiniPlayerContent extends StatelessWidget {
|
||||
/// If null, primary text will be vertically centered
|
||||
final String? secondaryText;
|
||||
|
||||
/// Tertiary text line (player name when playing)
|
||||
/// If provided, uses 3-line layout; if null, uses centered 2-line layout
|
||||
final String? tertiaryText;
|
||||
|
||||
/// Album art URL - if null, shows device icon
|
||||
final String? imageUrl;
|
||||
|
||||
@@ -48,37 +61,64 @@ class MiniPlayerContent extends StatelessWidget {
|
||||
/// Horizontal slide offset for swipe animation (-1 to 1)
|
||||
final double slideOffset;
|
||||
|
||||
/// Whether secondary text is a hint (shows lightbulb icon)
|
||||
final bool isHint;
|
||||
|
||||
/// Whether to show the progress bar overlay (for playing state)
|
||||
final bool showProgress;
|
||||
|
||||
/// Progress value 0.0 to 1.0 (only used if showProgress is true)
|
||||
final double progress;
|
||||
|
||||
/// Callback for power button tap (only shown in 2-line mode when provided)
|
||||
final VoidCallback? onPowerToggle;
|
||||
|
||||
/// Whether the player is currently powered on
|
||||
final bool isPoweredOn;
|
||||
|
||||
const MiniPlayerContent({
|
||||
super.key,
|
||||
required this.primaryText,
|
||||
this.secondaryText,
|
||||
this.tertiaryText,
|
||||
this.imageUrl,
|
||||
required this.playerName,
|
||||
required this.backgroundColor,
|
||||
required this.textColor,
|
||||
required this.width,
|
||||
this.slideOffset = 0.0,
|
||||
this.isHint = false,
|
||||
this.showProgress = false,
|
||||
this.progress = 0.0,
|
||||
this.onPowerToggle,
|
||||
this.isPoweredOn = true,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final hasSecondaryLine = secondaryText != null && secondaryText!.isNotEmpty;
|
||||
final hasTertiaryLine = tertiaryText != null && tertiaryText!.isNotEmpty;
|
||||
final is2LineMode = !hasTertiaryLine;
|
||||
final showPowerButton = is2LineMode && onPowerToggle != null;
|
||||
final slidePixels = slideOffset * width;
|
||||
|
||||
// Calculate text width (leaves room for right padding)
|
||||
final textWidth = width - MiniPlayerLayout.textLeft - MiniPlayerLayout.textRightPadding;
|
||||
// Use 3-line layout when tertiary exists, 2-line centered otherwise
|
||||
final primaryTop = hasTertiaryLine ? MiniPlayerLayout.primaryTop : MiniPlayerLayout.primaryTop2Line;
|
||||
final secondaryTop = hasTertiaryLine ? MiniPlayerLayout.secondaryTop : MiniPlayerLayout.secondaryTop2Line;
|
||||
|
||||
// Calculate right padding (extra space for power button in 2-line mode)
|
||||
final rightPadding = showPowerButton
|
||||
? MiniPlayerLayout.powerButtonSize + 8.0
|
||||
: MiniPlayerLayout.textRightPadding;
|
||||
|
||||
// Darkened background for icon area (matches DeviceSelectorBar)
|
||||
final iconAreaBackground = Color.lerp(backgroundColor, Colors.black, 0.15)!;
|
||||
|
||||
// Font size for primary text (larger in 2-line mode)
|
||||
final primaryFontSize = is2LineMode
|
||||
? MiniPlayerLayout.primaryFontSize2Line
|
||||
: MiniPlayerLayout.primaryFontSize;
|
||||
|
||||
return SizedBox(
|
||||
width: width,
|
||||
height: MiniPlayerLayout.height,
|
||||
@@ -95,10 +135,10 @@ class MiniPlayerContent extends StatelessWidget {
|
||||
child: Container(color: backgroundColor),
|
||||
),
|
||||
|
||||
// Art / Icon area
|
||||
// Art / Icon area - centered vertically
|
||||
Positioned(
|
||||
left: slidePixels,
|
||||
top: 0,
|
||||
top: (MiniPlayerLayout.height - MiniPlayerLayout.artSize) / 2,
|
||||
child: SizedBox(
|
||||
width: MiniPlayerLayout.artSize,
|
||||
height: MiniPlayerLayout.artSize,
|
||||
@@ -121,14 +161,14 @@ class MiniPlayerContent extends StatelessWidget {
|
||||
Positioned(
|
||||
left: MiniPlayerLayout.textLeft + slidePixels,
|
||||
top: hasSecondaryLine
|
||||
? MiniPlayerLayout.primaryTop
|
||||
: (MiniPlayerLayout.height - MiniPlayerLayout.primaryFontSize) / 2,
|
||||
right: MiniPlayerLayout.textRightPadding - slidePixels,
|
||||
? primaryTop
|
||||
: (MiniPlayerLayout.height - primaryFontSize) / 2,
|
||||
right: rightPadding - slidePixels,
|
||||
child: Text(
|
||||
primaryText,
|
||||
style: TextStyle(
|
||||
color: textColor,
|
||||
fontSize: MiniPlayerLayout.primaryFontSize,
|
||||
fontSize: primaryFontSize,
|
||||
fontWeight: MiniPlayerLayout.primaryFontWeight,
|
||||
),
|
||||
maxLines: 1,
|
||||
@@ -136,22 +176,83 @@ class MiniPlayerContent extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
|
||||
// Secondary text line
|
||||
// Secondary text line (with optional hint icon)
|
||||
if (hasSecondaryLine)
|
||||
Positioned(
|
||||
left: MiniPlayerLayout.textLeft + slidePixels,
|
||||
top: MiniPlayerLayout.secondaryTop,
|
||||
top: secondaryTop,
|
||||
right: rightPadding - slidePixels,
|
||||
child: isHint
|
||||
? Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.lightbulb_outline,
|
||||
size: 14,
|
||||
color: textColor.withOpacity(MiniPlayerLayout.secondaryTextOpacity),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Flexible(
|
||||
child: Text(
|
||||
secondaryText!,
|
||||
style: TextStyle(
|
||||
color: textColor.withOpacity(MiniPlayerLayout.secondaryTextOpacity),
|
||||
fontSize: MiniPlayerLayout.secondaryFontSize,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: Text(
|
||||
secondaryText!,
|
||||
style: TextStyle(
|
||||
color: textColor.withOpacity(MiniPlayerLayout.secondaryTextOpacity),
|
||||
fontSize: MiniPlayerLayout.secondaryFontSize,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
|
||||
// Tertiary text line (player name, only for 3-line layout)
|
||||
if (hasTertiaryLine)
|
||||
Positioned(
|
||||
left: MiniPlayerLayout.textLeft + slidePixels,
|
||||
top: MiniPlayerLayout.tertiaryTop,
|
||||
right: MiniPlayerLayout.textRightPadding - slidePixels,
|
||||
child: Text(
|
||||
secondaryText!,
|
||||
tertiaryText!,
|
||||
style: TextStyle(
|
||||
color: textColor.withOpacity(MiniPlayerLayout.secondaryTextOpacity),
|
||||
fontSize: MiniPlayerLayout.secondaryFontSize,
|
||||
color: textColor,
|
||||
fontSize: MiniPlayerLayout.tertiaryFontSize,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
|
||||
// Power button (only for 2-line mode when callback provided)
|
||||
// Matches PlayerCard power button style
|
||||
if (showPowerButton)
|
||||
Positioned(
|
||||
right: 8.0 - slidePixels,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
child: Center(
|
||||
child: IconButton(
|
||||
onPressed: onPowerToggle,
|
||||
icon: Icon(
|
||||
Icons.power_settings_new_rounded,
|
||||
color: isPoweredOn ? textColor : textColor.withOpacity(0.5),
|
||||
size: 20,
|
||||
),
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
+273
-139
@@ -1,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import '../../providers/music_assistant_provider.dart';
|
||||
import '../../theme/design_tokens.dart';
|
||||
@@ -6,7 +7,8 @@ import '../../l10n/app_localizations.dart';
|
||||
|
||||
/// A player card that matches the mini player's visual style.
|
||||
/// Used in the player reveal overlay when swiping down or tapping the device button.
|
||||
class PlayerCard extends StatelessWidget {
|
||||
/// Supports horizontal swipe to adjust volume with a two-tone overlay.
|
||||
class PlayerCard extends StatefulWidget {
|
||||
final dynamic player;
|
||||
final dynamic trackInfo;
|
||||
final String? albumArtUrl;
|
||||
@@ -20,6 +22,7 @@ class PlayerCard extends StatelessWidget {
|
||||
final VoidCallback? onPlayPause;
|
||||
final VoidCallback? onSkipNext;
|
||||
final VoidCallback? onPower;
|
||||
final ValueChanged<double>? onVolumeChange;
|
||||
|
||||
// Pastel yellow for grouped players
|
||||
static const Color groupBorderColor = Color(0xFFFFF59D);
|
||||
@@ -39,174 +42,305 @@ class PlayerCard extends StatelessWidget {
|
||||
this.onPlayPause,
|
||||
this.onSkipNext,
|
||||
this.onPower,
|
||||
this.onVolumeChange,
|
||||
});
|
||||
|
||||
@override
|
||||
State<PlayerCard> createState() => _PlayerCardState();
|
||||
}
|
||||
|
||||
class _PlayerCardState extends State<PlayerCard> {
|
||||
bool _isDraggingVolume = false;
|
||||
double _dragVolumeLevel = 0.0;
|
||||
double _cardWidth = 0.0;
|
||||
int _lastVolumeUpdateTime = 0;
|
||||
static const int _volumeThrottleMs = 150; // Only send volume updates every 150ms
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Match mini player dimensions
|
||||
const double cardHeight = Dimensions.miniPlayerHeight; // 64px
|
||||
const double cardHeight = Dimensions.miniPlayerHeight;
|
||||
const double artSize = cardHeight;
|
||||
const double borderRadius = Radii.xl; // 16px - same as mini player
|
||||
|
||||
return GestureDetector(
|
||||
onTap: onTap,
|
||||
onLongPress: onLongPress,
|
||||
child: Container(
|
||||
height: cardHeight,
|
||||
decoration: BoxDecoration(
|
||||
color: backgroundColor,
|
||||
borderRadius: BorderRadius.circular(borderRadius),
|
||||
border: isGrouped
|
||||
? Border.all(color: groupBorderColor, width: 1.5)
|
||||
: null,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.2),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: Row(
|
||||
children: [
|
||||
// Album art or speaker icon - same size for consistent text alignment
|
||||
SizedBox(
|
||||
width: artSize,
|
||||
height: artSize,
|
||||
child: albumArtUrl != null
|
||||
? CachedNetworkImage(
|
||||
imageUrl: albumArtUrl!,
|
||||
fit: BoxFit.cover,
|
||||
memCacheWidth: 128,
|
||||
memCacheHeight: 128,
|
||||
fadeInDuration: Duration.zero,
|
||||
fadeOutDuration: Duration.zero,
|
||||
placeholder: (_, __) => _buildSpeakerIcon(),
|
||||
errorWidget: (_, __, ___) => _buildSpeakerIcon(),
|
||||
)
|
||||
: _buildSpeakerIcon(),
|
||||
),
|
||||
// Colors for volume overlay (same as mini player progress bar)
|
||||
final filledColor = widget.backgroundColor;
|
||||
final unfilledColor = Color.lerp(widget.backgroundColor, Colors.black, 0.3)!;
|
||||
|
||||
// Player info
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Player name
|
||||
Row(
|
||||
children: [
|
||||
// Status indicator
|
||||
Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
margin: const EdgeInsets.only(right: 8),
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: _getStatusColor(),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
player.name,
|
||||
style: TextStyle(
|
||||
color: textColor,
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w500,
|
||||
fontFamily: 'Roboto',
|
||||
decoration: TextDecoration.none,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
// Track name or status
|
||||
Text(
|
||||
_getSubtitle(context),
|
||||
style: TextStyle(
|
||||
color: textColor.withOpacity(0.6),
|
||||
fontSize: 14,
|
||||
fontFamily: 'Roboto',
|
||||
decoration: TextDecoration.none,
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
_cardWidth = constraints.maxWidth;
|
||||
|
||||
return GestureDetector(
|
||||
onTap: _isDraggingVolume ? null : widget.onTap,
|
||||
onLongPress: _isDraggingVolume ? null : widget.onLongPress,
|
||||
onHorizontalDragStart: _onDragStart,
|
||||
onHorizontalDragUpdate: _onDragUpdate,
|
||||
onHorizontalDragEnd: _onDragEnd,
|
||||
onHorizontalDragCancel: _onDragCancel,
|
||||
// Use Stack to render border ON TOP of content, preventing album art clipping
|
||||
child: Stack(
|
||||
children: [
|
||||
// Main card content (hidden when dragging volume)
|
||||
if (!_isDraggingVolume)
|
||||
_buildCardContent(cardHeight, artSize, borderRadius),
|
||||
|
||||
// Volume overlay (shown when dragging)
|
||||
if (_isDraggingVolume)
|
||||
Container(
|
||||
height: cardHeight,
|
||||
decoration: BoxDecoration(
|
||||
color: unfilledColor,
|
||||
borderRadius: BorderRadius.circular(borderRadius),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.2),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: FractionallySizedBox(
|
||||
widthFactor: _dragVolumeLevel.clamp(0.0, 1.0),
|
||||
heightFactor: 1.0,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: filledColor,
|
||||
borderRadius: BorderRadius.only(
|
||||
topLeft: Radius.circular(borderRadius),
|
||||
bottomLeft: Radius.circular(borderRadius),
|
||||
),
|
||||
),
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Transport controls - compact sizing to align with mini player
|
||||
// Play/Pause and Next only shown when powered with content
|
||||
if (player.available && player.powered && trackInfo != null) ...[
|
||||
// Play/Pause - slight nudge right
|
||||
Transform.translate(
|
||||
offset: const Offset(3, 0),
|
||||
child: SizedBox(
|
||||
width: 28,
|
||||
height: 28,
|
||||
child: IconButton(
|
||||
icon: Icon(
|
||||
isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded,
|
||||
color: textColor,
|
||||
size: 28,
|
||||
),
|
||||
onPressed: onPlayPause,
|
||||
padding: EdgeInsets.zero,
|
||||
),
|
||||
),
|
||||
|
||||
// Border overlay - renders ON TOP to prevent clipping by album art
|
||||
if (widget.isGrouped)
|
||||
Positioned.fill(
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(borderRadius),
|
||||
border: Border.all(color: PlayerCard.groupBorderColor, width: 1.5),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCardContent(double cardHeight, double artSize, double borderRadius) {
|
||||
return Container(
|
||||
height: cardHeight,
|
||||
decoration: BoxDecoration(
|
||||
color: widget.backgroundColor,
|
||||
borderRadius: BorderRadius.circular(borderRadius),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.2),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: Row(
|
||||
children: [
|
||||
// Album art or speaker icon - same size for consistent text alignment
|
||||
SizedBox(
|
||||
width: artSize,
|
||||
height: artSize,
|
||||
child: widget.albumArtUrl != null
|
||||
? CachedNetworkImage(
|
||||
imageUrl: widget.albumArtUrl!,
|
||||
fit: BoxFit.cover,
|
||||
memCacheWidth: 128,
|
||||
memCacheHeight: 128,
|
||||
fadeInDuration: Duration.zero,
|
||||
fadeOutDuration: Duration.zero,
|
||||
placeholder: (_, __) => _buildSpeakerIcon(),
|
||||
errorWidget: (_, __, ___) => _buildSpeakerIcon(),
|
||||
)
|
||||
: _buildSpeakerIcon(),
|
||||
),
|
||||
|
||||
// Player info
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Player name
|
||||
Row(
|
||||
children: [
|
||||
// Status indicator
|
||||
Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
margin: const EdgeInsets.only(right: 8),
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: _getStatusColor(),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
widget.player.name,
|
||||
style: TextStyle(
|
||||
color: widget.textColor,
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w500,
|
||||
fontFamily: 'Roboto',
|
||||
decoration: TextDecoration.none,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
// Track name or status
|
||||
Text(
|
||||
_getSubtitle(context),
|
||||
style: TextStyle(
|
||||
color: widget.textColor.withOpacity(0.6),
|
||||
fontSize: 14,
|
||||
fontFamily: 'Roboto',
|
||||
decoration: TextDecoration.none,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
// Skip next - nudged right to close gap with power
|
||||
Transform.translate(
|
||||
offset: const Offset(6, 0),
|
||||
),
|
||||
),
|
||||
|
||||
// Transport controls - compact sizing to align with mini player
|
||||
// Play/Pause and Next only shown when powered with content
|
||||
if (widget.player.available && widget.player.powered && widget.trackInfo != null) ...[
|
||||
// Play/Pause - slight nudge right
|
||||
// Touch target increased to 44dp for accessibility (icon remains 28)
|
||||
Transform.translate(
|
||||
offset: const Offset(3, 0),
|
||||
child: SizedBox(
|
||||
width: 44,
|
||||
height: 44,
|
||||
child: IconButton(
|
||||
icon: Icon(
|
||||
Icons.skip_next_rounded,
|
||||
color: textColor,
|
||||
widget.isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded,
|
||||
color: widget.textColor,
|
||||
size: 28,
|
||||
),
|
||||
onPressed: onSkipNext,
|
||||
onPressed: widget.onPlayPause,
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(),
|
||||
),
|
||||
),
|
||||
],
|
||||
// Power button - smallest
|
||||
if (player.available)
|
||||
IconButton(
|
||||
),
|
||||
// Skip next - nudged right to close gap with power
|
||||
Transform.translate(
|
||||
offset: const Offset(6, 0),
|
||||
child: IconButton(
|
||||
icon: Icon(
|
||||
Icons.power_settings_new_rounded,
|
||||
color: player.powered ? textColor : textColor.withOpacity(0.5),
|
||||
size: 20,
|
||||
Icons.skip_next_rounded,
|
||||
color: widget.textColor,
|
||||
size: 28,
|
||||
),
|
||||
onPressed: onPower,
|
||||
onPressed: widget.onSkipNext,
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(),
|
||||
),
|
||||
|
||||
const SizedBox(width: 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
// Power button - smallest
|
||||
if (widget.player.available)
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
Icons.power_settings_new_rounded,
|
||||
color: widget.player.powered ? widget.textColor : widget.textColor.withOpacity(0.5),
|
||||
size: 20,
|
||||
),
|
||||
onPressed: widget.onPower,
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(),
|
||||
),
|
||||
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _onDragStart(DragStartDetails details) {
|
||||
// Get current volume from player
|
||||
final currentVolume = (widget.player.volumeLevel ?? 0).toDouble() / 100.0;
|
||||
setState(() {
|
||||
_isDraggingVolume = true;
|
||||
_dragVolumeLevel = currentVolume;
|
||||
});
|
||||
HapticFeedback.lightImpact();
|
||||
}
|
||||
|
||||
void _onDragUpdate(DragUpdateDetails details) {
|
||||
if (!_isDraggingVolume || _cardWidth <= 0) return;
|
||||
|
||||
// Directional volume: drag right = increase, drag left = decrease
|
||||
// Distance determines amount of change (full card width = 100%)
|
||||
// Multiple swipes accumulate - each starts from current volume
|
||||
final dragDelta = details.delta.dx;
|
||||
final volumeDelta = dragDelta / _cardWidth;
|
||||
|
||||
final newVolume = (_dragVolumeLevel + volumeDelta).clamp(0.0, 1.0);
|
||||
|
||||
// Always update visual
|
||||
if ((newVolume - _dragVolumeLevel).abs() > 0.001) {
|
||||
setState(() {
|
||||
_dragVolumeLevel = newVolume;
|
||||
});
|
||||
|
||||
// Throttle API calls to prevent flooding
|
||||
final now = DateTime.now().millisecondsSinceEpoch;
|
||||
if (now - _lastVolumeUpdateTime >= _volumeThrottleMs) {
|
||||
_lastVolumeUpdateTime = now;
|
||||
widget.onVolumeChange?.call(newVolume);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _onDragEnd(DragEndDetails details) {
|
||||
// Send final volume on release
|
||||
widget.onVolumeChange?.call(_dragVolumeLevel);
|
||||
setState(() {
|
||||
_isDraggingVolume = false;
|
||||
});
|
||||
HapticFeedback.lightImpact();
|
||||
}
|
||||
|
||||
void _onDragCancel() {
|
||||
setState(() {
|
||||
_isDraggingVolume = false;
|
||||
});
|
||||
}
|
||||
|
||||
Widget _buildSpeakerIcon() {
|
||||
// Darker shade of the card background to match album art square
|
||||
final iconBgColor = Color.lerp(backgroundColor, Colors.black, 0.15)!;
|
||||
final iconBgColor = Color.lerp(widget.backgroundColor, Colors.black, 0.15)!;
|
||||
return Container(
|
||||
color: iconBgColor,
|
||||
child: Center(
|
||||
child: Icon(
|
||||
Icons.speaker_rounded,
|
||||
color: textColor.withOpacity(0.4),
|
||||
color: widget.textColor.withOpacity(0.4),
|
||||
size: 28,
|
||||
),
|
||||
),
|
||||
@@ -214,30 +348,30 @@ class PlayerCard extends StatelessWidget {
|
||||
}
|
||||
|
||||
Color _getStatusColor() {
|
||||
if (!player.available) {
|
||||
if (!widget.player.available) {
|
||||
return Colors.grey.withOpacity(0.5);
|
||||
}
|
||||
if (!player.powered) {
|
||||
if (!widget.player.powered) {
|
||||
return Colors.grey;
|
||||
}
|
||||
if (isPlaying) {
|
||||
if (widget.isPlaying) {
|
||||
return Colors.green;
|
||||
}
|
||||
if (trackInfo != null) {
|
||||
if (widget.trackInfo != null) {
|
||||
return Colors.orange; // Has content but paused
|
||||
}
|
||||
return Colors.grey.shade400; // Idle
|
||||
}
|
||||
|
||||
String _getSubtitle(BuildContext context) {
|
||||
if (!player.available) {
|
||||
if (!widget.player.available) {
|
||||
return S.of(context)!.playerStateUnavailable;
|
||||
}
|
||||
if (!player.powered) {
|
||||
if (!widget.player.powered) {
|
||||
return S.of(context)!.playerStateOff;
|
||||
}
|
||||
if (trackInfo != null) {
|
||||
return trackInfo.name ?? S.of(context)!.playerStateIdle;
|
||||
if (widget.trackInfo != null) {
|
||||
return widget.trackInfo.name ?? S.of(context)!.playerStateIdle;
|
||||
}
|
||||
return S.of(context)!.playerStateIdle;
|
||||
}
|
||||
|
||||
@@ -59,19 +59,25 @@ class PlayerControls extends StatelessWidget {
|
||||
if (isExpanded && expandedElementsOpacity > 0.1)
|
||||
_buildSecondaryButton(
|
||||
icon: Icons.shuffle_rounded,
|
||||
color: (shuffle == true ? primaryColor : textColor.withOpacity(0.5))
|
||||
.withOpacity(expandedElementsOpacity),
|
||||
// Fix: compute final opacity once to avoid multiplicative opacity bug
|
||||
color: shuffle == true
|
||||
? primaryColor.withOpacity(expandedElementsOpacity)
|
||||
: textColor.withOpacity(0.5 * expandedElementsOpacity),
|
||||
onPressed: isLoadingQueue ? null : onToggleShuffle,
|
||||
),
|
||||
if (isExpanded) SizedBox(width: _lerpDouble(0, 20, t)),
|
||||
|
||||
// Previous
|
||||
_buildControlButton(
|
||||
icon: Icons.skip_previous_rounded,
|
||||
color: textColor,
|
||||
size: skipButtonSize,
|
||||
onPressed: onPrevious,
|
||||
useAnimation: isExpanded,
|
||||
Semantics(
|
||||
button: true,
|
||||
label: 'Previous track',
|
||||
child: _buildControlButton(
|
||||
icon: Icons.skip_previous_rounded,
|
||||
color: textColor,
|
||||
size: skipButtonSize,
|
||||
onPressed: onPrevious,
|
||||
useAnimation: isExpanded,
|
||||
),
|
||||
),
|
||||
SizedBox(width: _lerpDouble(0, 20, t)),
|
||||
|
||||
@@ -80,12 +86,16 @@ class PlayerControls extends StatelessWidget {
|
||||
SizedBox(width: _lerpDouble(0, 20, t)),
|
||||
|
||||
// Next
|
||||
_buildControlButton(
|
||||
icon: Icons.skip_next_rounded,
|
||||
color: textColor,
|
||||
size: skipButtonSize,
|
||||
onPressed: onNext,
|
||||
useAnimation: isExpanded,
|
||||
Semantics(
|
||||
button: true,
|
||||
label: 'Next track',
|
||||
child: _buildControlButton(
|
||||
icon: Icons.skip_next_rounded,
|
||||
color: textColor,
|
||||
size: skipButtonSize,
|
||||
onPressed: onNext,
|
||||
useAnimation: isExpanded,
|
||||
),
|
||||
),
|
||||
|
||||
// Repeat (expanded only)
|
||||
@@ -94,10 +104,10 @@ class PlayerControls extends StatelessWidget {
|
||||
if (isExpanded && expandedElementsOpacity > 0.1)
|
||||
_buildSecondaryButton(
|
||||
icon: repeatMode == 'one' ? Icons.repeat_one_rounded : Icons.repeat_rounded,
|
||||
color: (repeatMode != null && repeatMode != 'off'
|
||||
? primaryColor
|
||||
: textColor.withOpacity(0.5))
|
||||
.withOpacity(expandedElementsOpacity),
|
||||
// Fix: compute final opacity once to avoid multiplicative opacity bug
|
||||
color: (repeatMode != null && repeatMode != 'off')
|
||||
? primaryColor.withOpacity(expandedElementsOpacity)
|
||||
: textColor.withOpacity(0.5 * expandedElementsOpacity),
|
||||
onPressed: isLoadingQueue ? null : onCycleRepeat,
|
||||
),
|
||||
],
|
||||
@@ -151,21 +161,26 @@ class PlayerControls extends StatelessWidget {
|
||||
final bgColor = Color.lerp(Colors.transparent, primaryColor, progress);
|
||||
final iconColor = Color.lerp(textColor, backgroundColor, progress);
|
||||
|
||||
return GestureDetector(
|
||||
onLongPress: onStop,
|
||||
child: Container(
|
||||
width: playButtonContainerSize,
|
||||
height: playButtonContainerSize,
|
||||
decoration: BoxDecoration(
|
||||
color: bgColor,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: IconButton(
|
||||
icon: Icon(isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded),
|
||||
color: iconColor,
|
||||
iconSize: playButtonSize,
|
||||
onPressed: onPlayPause,
|
||||
padding: EdgeInsets.zero,
|
||||
return Semantics(
|
||||
button: true,
|
||||
label: isPlaying ? 'Pause' : 'Play',
|
||||
hint: 'Long press to stop',
|
||||
child: GestureDetector(
|
||||
onLongPress: onStop,
|
||||
child: Container(
|
||||
width: playButtonContainerSize,
|
||||
height: playButtonContainerSize,
|
||||
decoration: BoxDecoration(
|
||||
color: bgColor,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: IconButton(
|
||||
icon: Icon(isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded),
|
||||
color: iconColor,
|
||||
iconSize: playButtonSize,
|
||||
onPressed: onPlayPause,
|
||||
padding: EdgeInsets.zero,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -2,7 +2,9 @@ import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../../l10n/app_localizations.dart';
|
||||
import '../../providers/music_assistant_provider.dart';
|
||||
import '../../services/settings_service.dart';
|
||||
import '../../theme/design_tokens.dart';
|
||||
import '../../theme/theme_provider.dart';
|
||||
import '../../theme/palette_helper.dart';
|
||||
@@ -16,12 +18,14 @@ class PlayerRevealOverlay extends StatefulWidget {
|
||||
final VoidCallback onDismiss;
|
||||
final double miniPlayerBottom; // Bottom position of mini player
|
||||
final double miniPlayerHeight;
|
||||
final bool showOnboardingHints; // Show additional hints for first-time users
|
||||
|
||||
const PlayerRevealOverlay({
|
||||
super.key,
|
||||
required this.onDismiss,
|
||||
required this.miniPlayerBottom,
|
||||
required this.miniPlayerHeight,
|
||||
this.showOnboardingHints = false,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -40,13 +44,25 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
||||
double _dragOffset = 0;
|
||||
bool _isDragging = false;
|
||||
|
||||
// Scroll controller for when player list overflows
|
||||
final ScrollController _scrollController = ScrollController();
|
||||
bool _isScrollable = false;
|
||||
|
||||
// Cache extracted colors per player for per-device accent colors
|
||||
final Map<String, ColorScheme?> _playerColors = {};
|
||||
|
||||
// Hint system
|
||||
bool _showHints = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
// Load hint settings
|
||||
SettingsService.getShowHints().then((value) {
|
||||
if (mounted) setState(() => _showHints = value);
|
||||
});
|
||||
|
||||
_revealController = AnimationController(
|
||||
vsync: this,
|
||||
);
|
||||
@@ -116,6 +132,7 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
||||
void dispose() {
|
||||
_revealController.dispose();
|
||||
_refreshTimer?.cancel();
|
||||
_scrollController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -127,7 +144,7 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
||||
|
||||
/// Animate dismissal and call callback when done
|
||||
void dismiss() {
|
||||
// Trigger settle bounce on mini player when cards are ~70% collapsed
|
||||
// Trigger single bounce on mini player when cards are ~70% collapsed
|
||||
// This creates the effect of cards "landing" on the mini player
|
||||
bool bounceFired = false;
|
||||
void checkBounce() {
|
||||
@@ -145,19 +162,51 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
||||
});
|
||||
}
|
||||
|
||||
/// Check if scroll is at top (or not scrollable)
|
||||
bool get _isAtTop {
|
||||
if (!_isScrollable) return true;
|
||||
if (!_scrollController.hasClients) return true;
|
||||
return _scrollController.offset <= 0;
|
||||
}
|
||||
|
||||
void _handleVerticalDragUpdate(DragUpdateDetails details) {
|
||||
final delta = details.primaryDelta ?? 0;
|
||||
|
||||
// If scrollable and not at top, let scroll handle it
|
||||
if (_isScrollable && !_isAtTop) {
|
||||
// Scroll the list
|
||||
if (_scrollController.hasClients) {
|
||||
final newOffset = _scrollController.offset - delta;
|
||||
_scrollController.jumpTo(newOffset.clamp(0.0, _scrollController.position.maxScrollExtent));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// At top: check if trying to scroll down (view more) or dismiss
|
||||
if (_isScrollable && delta < 0 && _scrollController.hasClients) {
|
||||
// Swiping up (delta negative) = scroll down to see more players
|
||||
final newOffset = _scrollController.offset - delta;
|
||||
_scrollController.jumpTo(newOffset.clamp(0.0, _scrollController.position.maxScrollExtent));
|
||||
return;
|
||||
}
|
||||
|
||||
// Only process dismiss gesture when swiping DOWN (positive delta = finger moving down)
|
||||
// Ignore swipe up when not scrollable - cards should stay fixed
|
||||
if (delta <= 0) return;
|
||||
|
||||
// Swiping down = dismiss gesture
|
||||
setState(() {
|
||||
_isDragging = true;
|
||||
// Negate delta so swipe down = cards move down (toward dismissal)
|
||||
_dragOffset -= details.primaryDelta ?? 0;
|
||||
// Clamp: allow moving down (positive) freely, limit moving up to 20px
|
||||
_dragOffset = _dragOffset.clamp(-20.0, double.infinity);
|
||||
_dragOffset += delta;
|
||||
});
|
||||
}
|
||||
|
||||
void _handleVerticalDragEnd(DragEndDetails details) {
|
||||
final velocity = details.primaryVelocity ?? 0;
|
||||
|
||||
// If not dragging (was scrolling), don't dismiss
|
||||
if (!_isDragging) return;
|
||||
|
||||
// Dismiss if dragged down enough or with enough velocity
|
||||
if (_dragOffset > 100 || velocity > 500) {
|
||||
HapticFeedback.lightImpact();
|
||||
@@ -203,6 +252,21 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
||||
const cardSpacing = 12.0;
|
||||
final totalStackHeight = players.length * cardHeight + (players.length - 1) * cardSpacing;
|
||||
|
||||
// Calculate max available height (80% of screen minus mini player area)
|
||||
final screenHeight = MediaQuery.of(context).size.height;
|
||||
final statusBarHeight = MediaQuery.of(context).padding.top;
|
||||
final bottomPadding = widget.miniPlayerBottom + widget.miniPlayerHeight + 20;
|
||||
final maxListHeight = (screenHeight - statusBarHeight - bottomPadding) * 0.8;
|
||||
|
||||
// Determine if scrolling is needed
|
||||
final needsScroll = totalStackHeight > maxListHeight;
|
||||
// Update scrollable state (used by gesture handlers)
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (_isScrollable != needsScroll) {
|
||||
_isScrollable = needsScroll;
|
||||
}
|
||||
});
|
||||
|
||||
return AnimatedBuilder(
|
||||
animation: _revealAnimation,
|
||||
builder: (context, child) {
|
||||
@@ -210,13 +274,12 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
||||
|
||||
return Stack(
|
||||
children: [
|
||||
// Backdrop - tap to dismiss
|
||||
// Backdrop - tap to dismiss (darkness handled by GlobalPlayerOverlay)
|
||||
Positioned.fill(
|
||||
child: GestureDetector(
|
||||
onTap: dismiss,
|
||||
child: Container(
|
||||
color: Colors.black.withOpacity(0.6 * _backdropAnimation.value),
|
||||
),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
child: const SizedBox.expand(),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -231,7 +294,134 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Build player cards - all slide from behind mini player
|
||||
// Hint above player list - different for onboarding vs regular use
|
||||
// Onboarding: show first-time hint (how to select)
|
||||
// Regular: show sync hint (tap and hold to sync)
|
||||
if (players.isNotEmpty && (_showHints || widget.showOnboardingHints))
|
||||
Builder(
|
||||
builder: (context) {
|
||||
// Calculate slide offset to match the topmost card
|
||||
const baseOffset = 80.0;
|
||||
final hintDistanceToTravel = baseOffset + (players.length * (cardHeight + cardSpacing));
|
||||
final hintSlideOffset = hintDistanceToTravel * (1.0 - t);
|
||||
|
||||
// Show different hint for onboarding vs regular use
|
||||
final isOnboarding = widget.showOnboardingHints;
|
||||
|
||||
Widget buildHintRow(IconData icon, String text) {
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
icon,
|
||||
size: 18,
|
||||
color: colorScheme.onSurface.withOpacity(0.7),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
text,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface.withOpacity(0.7),
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
return Transform.translate(
|
||||
offset: Offset(0, hintSlideOffset),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: Material(
|
||||
type: MaterialType.transparency,
|
||||
child: isOnboarding
|
||||
? buildHintRow(Icons.touch_app_outlined, S.of(context)!.selectPlayerHint)
|
||||
: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
buildHintRow(Icons.lightbulb_outline, S.of(context)!.holdToSync),
|
||||
const SizedBox(height: 4),
|
||||
buildHintRow(Icons.lightbulb_outline, S.of(context)!.swipeToAdjustVolume),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
// Build player cards - scrollable when overflow, otherwise static
|
||||
// Using ListView.builder for many players: only builds visible items
|
||||
// This significantly improves animation performance with 10+ players
|
||||
if (needsScroll)
|
||||
ConstrainedBox(
|
||||
constraints: BoxConstraints(maxHeight: maxListHeight),
|
||||
child: ListView.builder(
|
||||
controller: _scrollController,
|
||||
physics: const ClampingScrollPhysics(),
|
||||
itemCount: players.length,
|
||||
// Fixed height per item for optimal scroll performance
|
||||
itemExtent: cardHeight + cardSpacing,
|
||||
itemBuilder: (context, index) {
|
||||
final player = players[index];
|
||||
final isPlaying = player.state == 'playing';
|
||||
final playerTrack = maProvider.getCachedTrackForPlayer(player.playerId);
|
||||
String? albumArtUrl;
|
||||
if (playerTrack != null && player.available && player.powered) {
|
||||
albumArtUrl = maProvider.getImageUrl(playerTrack, size: 128);
|
||||
}
|
||||
final playerColorScheme = _playerColors[player.playerId];
|
||||
final cardBgColor = playerColorScheme?.primaryContainer ?? defaultBgColor;
|
||||
final cardTextColor = playerColorScheme?.onPrimaryContainer ?? defaultTextColor;
|
||||
|
||||
// Animation: slide from behind mini player
|
||||
// Only calculate for items that will be built (visible ones)
|
||||
const baseOffset = 80.0;
|
||||
final reverseIndex = players.length - 1 - index;
|
||||
final distanceToTravel = baseOffset + (reverseIndex * (cardHeight + cardSpacing));
|
||||
final slideOffset = distanceToTravel * (1.0 - t);
|
||||
|
||||
return Transform.translate(
|
||||
offset: Offset(0, slideOffset),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(bottom: cardSpacing),
|
||||
child: PlayerCard(
|
||||
player: player,
|
||||
trackInfo: playerTrack,
|
||||
albumArtUrl: albumArtUrl,
|
||||
isSelected: false,
|
||||
isPlaying: isPlaying,
|
||||
isGrouped: maProvider.isPlayerManuallySynced(player.playerId),
|
||||
backgroundColor: cardBgColor,
|
||||
textColor: cardTextColor,
|
||||
onTap: () {
|
||||
HapticFeedback.mediumImpact();
|
||||
maProvider.selectPlayer(player);
|
||||
dismiss();
|
||||
},
|
||||
onLongPress: () {
|
||||
HapticFeedback.mediumImpact();
|
||||
maProvider.togglePlayerSync(player.playerId);
|
||||
},
|
||||
onPlayPause: () {
|
||||
if (isPlaying) {
|
||||
maProvider.pausePlayer(player.playerId);
|
||||
} else {
|
||||
maProvider.resumePlayer(player.playerId);
|
||||
}
|
||||
},
|
||||
onSkipNext: () => maProvider.nextTrack(player.playerId),
|
||||
onPower: () => maProvider.togglePower(player.playerId),
|
||||
onVolumeChange: (volume) => maProvider.setVolume(player.playerId, (volume * 100).round()),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
)
|
||||
else
|
||||
// Non-scrollable list for when players fit
|
||||
...List.generate(players.length, (index) {
|
||||
final player = players[index];
|
||||
final isPlaying = player.state == 'playing';
|
||||
@@ -269,7 +459,7 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
||||
albumArtUrl: albumArtUrl,
|
||||
isSelected: false,
|
||||
isPlaying: isPlaying,
|
||||
isGrouped: player.isGrouped,
|
||||
isGrouped: maProvider.isPlayerManuallySynced(player.playerId),
|
||||
backgroundColor: cardBgColor,
|
||||
textColor: cardTextColor,
|
||||
onTap: () {
|
||||
@@ -277,7 +467,7 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
||||
maProvider.selectPlayer(player);
|
||||
dismiss();
|
||||
},
|
||||
onLongPress: player.available ? () {
|
||||
onLongPress: () {
|
||||
HapticFeedback.mediumImpact();
|
||||
debugPrint('🔗 Long-press on ${player.name} (${player.playerId})');
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
@@ -287,7 +477,7 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
||||
),
|
||||
);
|
||||
maProvider.togglePlayerSync(player.playerId);
|
||||
} : null,
|
||||
},
|
||||
onPlayPause: () {
|
||||
if (isPlaying) {
|
||||
maProvider.pausePlayer(player.playerId);
|
||||
@@ -301,6 +491,7 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
||||
onPower: () {
|
||||
maProvider.togglePower(player.playerId);
|
||||
},
|
||||
onVolumeChange: (volume) => maProvider.setVolume(player.playerId, (volume * 100).round()),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../models/player.dart';
|
||||
import '../l10n/app_localizations.dart';
|
||||
|
||||
/// A themed bottom sheet for selecting a player.
|
||||
///
|
||||
/// Supports adaptive theming - pass [adaptiveColorScheme] to use colors
|
||||
/// extracted from album art, matching the detail screen backgrounds.
|
||||
class PlayerPickerSheet extends StatelessWidget {
|
||||
final String title;
|
||||
final List<Player> players;
|
||||
final Player? selectedPlayer;
|
||||
final ColorScheme? adaptiveColorScheme;
|
||||
final Future<void> Function(Player player) onPlayerSelected;
|
||||
|
||||
const PlayerPickerSheet({
|
||||
super.key,
|
||||
required this.title,
|
||||
required this.players,
|
||||
this.selectedPlayer,
|
||||
this.adaptiveColorScheme,
|
||||
required this.onPlayerSelected,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final themeColorScheme = Theme.of(context).colorScheme;
|
||||
final colorScheme = adaptiveColorScheme ?? themeColorScheme;
|
||||
|
||||
// Use surface container for slightly elevated look, or adaptive surface
|
||||
final backgroundColor = adaptiveColorScheme?.surface ?? themeColorScheme.surfaceContainerHigh;
|
||||
final onBackgroundColor = adaptiveColorScheme?.onSurface ?? themeColorScheme.onSurface;
|
||||
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
color: backgroundColor,
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Drag handle
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 12, bottom: 8),
|
||||
child: Container(
|
||||
width: 32,
|
||||
height: 4,
|
||||
decoration: BoxDecoration(
|
||||
color: onBackgroundColor.withOpacity(0.3),
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Title
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8),
|
||||
child: Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
color: onBackgroundColor,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 8),
|
||||
|
||||
// Player list
|
||||
if (players.isEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(32.0),
|
||||
child: Text(
|
||||
S.of(context)!.noPlayersAvailable,
|
||||
style: TextStyle(color: onBackgroundColor.withOpacity(0.6)),
|
||||
),
|
||||
)
|
||||
else
|
||||
Flexible(
|
||||
child: ListView.builder(
|
||||
shrinkWrap: true,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
itemCount: players.length,
|
||||
itemBuilder: (context, index) {
|
||||
final player = players[index];
|
||||
final isSelected = selectedPlayer?.playerId == player.playerId;
|
||||
|
||||
return _PlayerTile(
|
||||
player: player,
|
||||
isSelected: isSelected,
|
||||
colorScheme: colorScheme,
|
||||
onBackgroundColor: onBackgroundColor,
|
||||
onTap: () => onPlayerSelected(player),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
|
||||
SizedBox(height: MediaQuery.of(context).padding.bottom + 70),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _PlayerTile extends StatelessWidget {
|
||||
final Player player;
|
||||
final bool isSelected;
|
||||
final ColorScheme colorScheme;
|
||||
final Color onBackgroundColor;
|
||||
final VoidCallback onTap;
|
||||
|
||||
const _PlayerTile({
|
||||
required this.player,
|
||||
required this.isSelected,
|
||||
required this.colorScheme,
|
||||
required this.onBackgroundColor,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Status color based on player state
|
||||
Color statusColor;
|
||||
if (!player.available) {
|
||||
statusColor = Colors.grey.withOpacity(0.5);
|
||||
} else if (!player.powered) {
|
||||
statusColor = Colors.grey;
|
||||
} else if (player.state == 'playing') {
|
||||
statusColor = Colors.green;
|
||||
} else {
|
||||
statusColor = Colors.orange; // Idle/paused but powered
|
||||
}
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 2),
|
||||
child: Material(
|
||||
color: isSelected
|
||||
? colorScheme.primaryContainer.withOpacity(0.3)
|
||||
: Colors.transparent,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: InkWell(
|
||||
onTap: onTap,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
child: Row(
|
||||
children: [
|
||||
// Status indicator
|
||||
Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: statusColor,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
|
||||
// Speaker icon
|
||||
Icon(
|
||||
Icons.speaker_rounded,
|
||||
color: isSelected
|
||||
? colorScheme.primary
|
||||
: onBackgroundColor.withOpacity(0.7),
|
||||
size: 24,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
|
||||
// Player name
|
||||
Expanded(
|
||||
child: Text(
|
||||
player.name,
|
||||
style: TextStyle(
|
||||
color: isSelected
|
||||
? colorScheme.primary
|
||||
: onBackgroundColor,
|
||||
fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
|
||||
fontSize: 16,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Selected checkmark
|
||||
if (isSelected)
|
||||
Icon(
|
||||
Icons.check_circle_rounded,
|
||||
color: colorScheme.primary,
|
||||
size: 20,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the player picker bottom sheet with adaptive theming.
|
||||
///
|
||||
/// Returns the selected player, or null if dismissed.
|
||||
Future<void> showPlayerPickerSheet({
|
||||
required BuildContext context,
|
||||
required String title,
|
||||
required List<Player> players,
|
||||
Player? selectedPlayer,
|
||||
ColorScheme? adaptiveColorScheme,
|
||||
required Future<void> Function(Player player) onPlayerSelected,
|
||||
}) {
|
||||
return showModalBottomSheet(
|
||||
context: context,
|
||||
backgroundColor: Colors.transparent,
|
||||
isScrollControlled: true,
|
||||
builder: (context) => PlayerPickerSheet(
|
||||
title: title,
|
||||
players: players,
|
||||
selectedPlayer: selectedPlayer,
|
||||
adaptiveColorScheme: adaptiveColorScheme,
|
||||
onPlayerSelected: (player) async {
|
||||
Navigator.pop(context);
|
||||
await onPlayerSelected(player);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -19,11 +19,12 @@ class PlayerSelector extends StatelessWidget {
|
||||
final availablePlayers = maProvider.availablePlayers;
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
// Count players that are currently playing (excluding selected player)
|
||||
// Count players that are currently playing MA content (excluding selected player)
|
||||
// User already sees if selected player is playing, badge shows "other" activity
|
||||
// Exclude external sources (Spotify Connect, TV optical, etc.) - they're not playing MA content
|
||||
final selectedPlayerId = selectedPlayer?.playerId;
|
||||
final playingCount = availablePlayers
|
||||
.where((p) => p.state == 'playing' && p.playerId != selectedPlayerId)
|
||||
.where((p) => p.state == 'playing' && p.playerId != selectedPlayerId && !p.isExternalSource)
|
||||
.length;
|
||||
|
||||
return Padding(
|
||||
@@ -202,25 +203,31 @@ class _PlayerSelectorSheetState extends State<_PlayerSelectorSheet> {
|
||||
// but still have track info - treat as "has content" for display
|
||||
final isIdle = player.state == 'idle';
|
||||
|
||||
// Check for external source (optical, Spotify, etc.)
|
||||
final isExternalSource = player.isExternalSource;
|
||||
|
||||
// Get track info - use current track for selected player, cache for others
|
||||
final playerTrack = isSelected
|
||||
? currentTrack
|
||||
: maProvider.getCachedTrackForPlayer(player.playerId);
|
||||
// Skip track info for external sources
|
||||
final playerTrack = isExternalSource
|
||||
? null
|
||||
: (isSelected
|
||||
? currentTrack
|
||||
: maProvider.getCachedTrackForPlayer(player.playerId));
|
||||
|
||||
// Player has content if playing, paused, or idle with cached track
|
||||
final hasContent = isPlaying || isPaused || (isIdle && playerTrack != null);
|
||||
// Player has content if playing, paused, or idle with cached track (but not external source)
|
||||
final hasContent = !isExternalSource && (isPlaying || isPaused || (isIdle && playerTrack != null));
|
||||
|
||||
// Get album art for any player with content
|
||||
// Get album art for any player with content (skip for external source)
|
||||
String? albumArtUrl;
|
||||
if (playerTrack != null && isOn && hasContent) {
|
||||
if (!isExternalSource && playerTrack != null && isOn && hasContent) {
|
||||
albumArtUrl = maProvider.getImageUrl(
|
||||
playerTrack.album ?? playerTrack,
|
||||
size: 128,
|
||||
);
|
||||
}
|
||||
|
||||
// Check if this player is part of a sync group
|
||||
final isGrouped = player.isGrouped;
|
||||
// Check if this player is manually synced (not a pre-configured group)
|
||||
final isGrouped = maProvider.isPlayerManuallySynced(player.playerId);
|
||||
// Pastel yellow for grouped players
|
||||
const groupBorderColor = Color(0xFFFFF59D);
|
||||
|
||||
@@ -231,25 +238,23 @@ class _PlayerSelectorSheetState extends State<_PlayerSelectorSheet> {
|
||||
maProvider.selectPlayer(player);
|
||||
Navigator.pop(context);
|
||||
},
|
||||
onLongPress: player.available
|
||||
? () {
|
||||
// Haptic feedback for sync action
|
||||
HapticFeedback.mediumImpact();
|
||||
onLongPress: () {
|
||||
// Haptic feedback for sync action
|
||||
HapticFeedback.mediumImpact();
|
||||
|
||||
// Show snackbar for visual feedback
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Syncing ${player.name}...'),
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
// Show snackbar for visual feedback
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Syncing ${player.name}...'),
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
|
||||
// Long-press to sync/unsync player
|
||||
debugPrint('🔗 Long-press on ${player.name} (${player.playerId})');
|
||||
debugPrint('🔗 Player isGrouped: ${player.isGrouped}, groupMembers: ${player.groupMembers}');
|
||||
maProvider.togglePlayerSync(player.playerId);
|
||||
}
|
||||
: null,
|
||||
// Long-press to sync/unsync player
|
||||
debugPrint('🔗 Long-press on ${player.name} (${player.playerId})');
|
||||
debugPrint('🔗 Player isGrouped: ${player.isGrouped}, groupMembers: ${player.groupMembers}');
|
||||
maProvider.togglePlayerSync(player.playerId);
|
||||
},
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
child: Container(
|
||||
height: 72,
|
||||
@@ -323,11 +328,13 @@ class _PlayerSelectorSheetState extends State<_PlayerSelectorSheet> {
|
||||
? colorScheme.onSurface.withOpacity(0.24)
|
||||
: !isOn
|
||||
? colorScheme.onSurface.withOpacity(0.3)
|
||||
: isPlaying
|
||||
? Colors.green
|
||||
: hasContent
|
||||
? Colors.orange // paused or idle with content
|
||||
: colorScheme.onSurfaceVariant.withOpacity(0.5),
|
||||
: isExternalSource
|
||||
? Colors.cyan // external source (optical, Spotify, etc.)
|
||||
: isPlaying
|
||||
? Colors.green
|
||||
: hasContent
|
||||
? Colors.orange // paused or idle with content
|
||||
: colorScheme.onSurfaceVariant.withOpacity(0.5),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
@@ -337,9 +344,11 @@ class _PlayerSelectorSheetState extends State<_PlayerSelectorSheet> {
|
||||
? S.of(context)!.playerStateUnavailable
|
||||
: !isOn
|
||||
? S.of(context)!.playerStateOff
|
||||
: hasContent && playerTrack != null
|
||||
? playerTrack.name
|
||||
: S.of(context)!.playerStateIdle,
|
||||
: isExternalSource
|
||||
? S.of(context)!.playerStateExternalSource
|
||||
: hasContent && playerTrack != null
|
||||
? playerTrack.name
|
||||
: S.of(context)!.playerStateIdle,
|
||||
style: TextStyle(
|
||||
color: player.available
|
||||
? colorScheme.onSurfaceVariant
|
||||
@@ -402,8 +411,8 @@ class _PlayerSelectorSheetState extends State<_PlayerSelectorSheet> {
|
||||
],
|
||||
),
|
||||
),
|
||||
// Play/Pause button
|
||||
if (player.available && isOn)
|
||||
// Play/Pause button (hidden for external sources - controls don't work)
|
||||
if (player.available && isOn && !isExternalSource)
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded,
|
||||
|
||||
+2
-1
@@ -1,7 +1,7 @@
|
||||
name: ensemble
|
||||
description: A minimalistic Music Assistant client built with Flutter
|
||||
publish_to: 'none'
|
||||
version: 2.5.0-beta+27
|
||||
version: 2.8.4-beta+42
|
||||
|
||||
environment:
|
||||
sdk: '>=3.0.0 <4.0.0'
|
||||
@@ -28,6 +28,7 @@ dependencies:
|
||||
|
||||
# Storage
|
||||
shared_preferences: ^2.2.2
|
||||
flutter_secure_storage: ^9.2.2
|
||||
drift: ^2.22.0
|
||||
drift_flutter: 0.2.0
|
||||
path_provider: ^2.1.5
|
||||
|
||||
Reference in New Issue
Block a user