Compare commits
88
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.*
|
||||
@@ -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()();
|
||||
@@ -185,7 +191,7 @@ class AppDatabase extends _$AppDatabase {
|
||||
AppDatabase([QueryExecutor? executor]) : super(executor ?? _openConnection());
|
||||
|
||||
@override
|
||||
int get schemaVersion => 4;
|
||||
int get schemaVersion => 5;
|
||||
|
||||
@override
|
||||
MigrationStrategy get migration {
|
||||
@@ -208,6 +214,18 @@ class AppDatabase extends _$AppDatabase {
|
||||
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)');
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
+2
-1
@@ -287,5 +287,6 @@
|
||||
"showHints": "Hinweise anzeigen",
|
||||
"showHintsDescription": "Hilfreiche Tipps zum Entdecken von Funktionen anzeigen",
|
||||
"pullToSelectPlayers": "Ziehen um Geräte auszuwählen",
|
||||
"holdToSync": "Gerät gedrückt halten zum Synchronisieren"
|
||||
"holdToSync": "Gedrückt halten zum Sync",
|
||||
"swipeToAdjustVolume": "Wischen für Lautstärke"
|
||||
}
|
||||
|
||||
+6
-1
@@ -1273,11 +1273,16 @@
|
||||
"description": "Hint shown when mini player bounces"
|
||||
},
|
||||
|
||||
"holdToSync": "Tap and hold a player to sync",
|
||||
"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"
|
||||
|
||||
+2
-1
@@ -483,5 +483,6 @@
|
||||
"showHints": "Mostrar Sugerencias",
|
||||
"showHintsDescription": "Mostrar consejos útiles para descubrir funciones",
|
||||
"pullToSelectPlayers": "Desliza para seleccionar dispositivos",
|
||||
"holdToSync": "Mantén presionado un dispositivo para sincronizar"
|
||||
"holdToSync": "Mantén presionado para sync",
|
||||
"swipeToAdjustVolume": "Desliza para ajustar volumen"
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
|
||||
+45
-9
@@ -16,6 +16,7 @@ class Player {
|
||||
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,
|
||||
@@ -33,6 +34,7 @@ class Player {
|
||||
this.syncedTo,
|
||||
this.activeSource,
|
||||
this.isExternalSource = false,
|
||||
this.appId,
|
||||
});
|
||||
|
||||
/// Create a copy of this Player with some fields replaced
|
||||
@@ -52,6 +54,7 @@ class Player {
|
||||
String? syncedTo,
|
||||
String? activeSource,
|
||||
bool? isExternalSource,
|
||||
String? appId,
|
||||
}) {
|
||||
return Player(
|
||||
playerId: playerId ?? this.playerId,
|
||||
@@ -69,6 +72,7 @@ class Player {
|
||||
syncedTo: syncedTo ?? this.syncedTo,
|
||||
activeSource: activeSource ?? this.activeSource,
|
||||
isExternalSource: isExternalSource ?? this.isExternalSource,
|
||||
appId: appId ?? this.appId,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -83,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 {
|
||||
@@ -126,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]!;
|
||||
@@ -197,9 +219,21 @@ class Player {
|
||||
final activeSource = json['active_source'] as String?;
|
||||
|
||||
// Detect external source (optical, Spotify, AirPlay, etc.)
|
||||
// External sources have non-MA URIs and often media_type='unknown'
|
||||
// Primary indicator: app_id - if not 'music_assistant', it's an external source
|
||||
// Secondary indicators: URI patterns and media_type
|
||||
bool isExternalSource = false;
|
||||
if (json.containsKey('current_media')) {
|
||||
|
||||
// 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?;
|
||||
@@ -252,6 +286,7 @@ class Player {
|
||||
syncedTo: syncedTo,
|
||||
activeSource: activeSource,
|
||||
isExternalSource: isExternalSource,
|
||||
appId: appId,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -272,6 +307,7 @@ class Player {
|
||||
if (syncedTo != null) 'synced_to': syncedTo,
|
||||
if (activeSource != null) 'active_source': activeSource,
|
||||
'is_external_source': isExternalSource,
|
||||
if (appId != null) 'app_id': appId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,6 +57,7 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
// Player state
|
||||
Player? _selectedPlayer;
|
||||
List<Player> _availablePlayers = [];
|
||||
bool _selectPlayerInProgress = false; // Reentrancy guard for selectPlayer()
|
||||
Map<String, String> _castToSendspinIdMap = {}; // Maps regular Cast IDs to Sendspin IDs for grouping
|
||||
Track? _currentTrack;
|
||||
Audiobook? _currentAudiobook; // Currently playing audiobook context (with chapters)
|
||||
@@ -67,6 +68,7 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
bool _isLocalPlayerPowered = true;
|
||||
int _localPlayerVolume = 100; // Tracked MA volume for builtin player (0-100)
|
||||
bool _builtinPlayerAvailable = true; // False on MA 2.7.0b20+ (uses Sendspin instead)
|
||||
StreamSubscription? _connectionStateSubscription;
|
||||
StreamSubscription? _localPlayerEventSubscription;
|
||||
StreamSubscription? _playerUpdatedEventSubscription;
|
||||
StreamSubscription? _playerAddedEventSubscription;
|
||||
@@ -131,6 +133,69 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
return _availablePlayers;
|
||||
}
|
||||
|
||||
/// Check if a player should show the "manually synced" indicator (yellow border)
|
||||
/// Returns true for BOTH the leader AND children of a manually created sync group
|
||||
/// Excludes pre-configured MA speaker groups (provider = 'player_group')
|
||||
bool isPlayerManuallySynced(String playerId) {
|
||||
final player = _availablePlayers.where((p) => p.playerId == playerId).firstOrNull;
|
||||
if (player == null) return false;
|
||||
|
||||
// Group players (like "All Speakers") should NEVER have yellow border
|
||||
// They are pre-configured containers, not manually synced players
|
||||
// Check this FIRST before any other logic to prevent edge cases
|
||||
if (player.provider == 'player_group') return false;
|
||||
|
||||
// Case 1: Player is a child synced to another player
|
||||
if (player.syncedTo != null) {
|
||||
// Look up sync target - also check translated IDs for Cast+Sendspin players
|
||||
// The syncedTo might contain a Cast ID but the player list has the Sendspin version
|
||||
Player? syncTarget = _availablePlayers.where((p) => p.playerId == player.syncedTo).firstOrNull;
|
||||
|
||||
// If not found, try looking up by translated Sendspin ID
|
||||
if (syncTarget == null) {
|
||||
final translatedId = _castToSendspinIdMap[player.syncedTo];
|
||||
if (translatedId != null) {
|
||||
syncTarget = _availablePlayers.where((p) => p.playerId == translatedId).firstOrNull;
|
||||
}
|
||||
}
|
||||
|
||||
// Also check reverse: syncedTo might be Sendspin ID, look for Cast player
|
||||
if (syncTarget == null) {
|
||||
// Build reverse map on demand
|
||||
for (final entry in _castToSendspinIdMap.entries) {
|
||||
if (entry.value == player.syncedTo) {
|
||||
syncTarget = _availablePlayers.where((p) => p.playerId == entry.key).firstOrNull;
|
||||
if (syncTarget != null) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (syncTarget == null) return false;
|
||||
|
||||
// If synced to a group player, it's part of a pre-configured group
|
||||
if (syncTarget.provider == 'player_group') return false;
|
||||
|
||||
// Synced to a regular player - this is a manual sync child
|
||||
return true;
|
||||
}
|
||||
|
||||
// Case 2: Player is a leader with group members
|
||||
if (player.groupMembers != null && player.groupMembers!.length > 1) {
|
||||
// Key distinction: In a MANUAL sync, the leader's own ID is in groupMembers
|
||||
// In a PRE-CONFIGURED group (UGP), the group player's ID is NOT in groupMembers
|
||||
// (the members are the child players, not including the group itself)
|
||||
final isInOwnGroup = player.groupMembers!.contains(player.playerId);
|
||||
if (!isInOwnGroup) {
|
||||
// This is a pre-configured group player (like "All Speakers")
|
||||
return false;
|
||||
}
|
||||
// Leader's ID is in groupMembers = manual sync
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
Track? get currentTrack => _currentTrack;
|
||||
|
||||
/// Whether we have cached players available (for instant UI display on app resume)
|
||||
@@ -174,6 +239,7 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
|
||||
/// Get cached track for a player (used for smooth swipe transitions)
|
||||
/// For grouped child players, returns the leader's track
|
||||
/// Also checks translated Cast<->Sendspin IDs (both from map and computed dynamically)
|
||||
Track? getCachedTrackForPlayer(String playerId) {
|
||||
// If player is a group child, get the leader's track instead
|
||||
final player = _availablePlayers.firstWhere(
|
||||
@@ -191,7 +257,72 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
? player.syncedTo!
|
||||
: playerId;
|
||||
|
||||
return _cacheService.getCachedTrackForPlayer(effectivePlayerId);
|
||||
// Try direct lookup first
|
||||
var track = _cacheService.getCachedTrackForPlayer(effectivePlayerId);
|
||||
|
||||
// If not found, try translated Cast<->Sendspin ID
|
||||
if (track == null) {
|
||||
// Check Cast -> Sendspin (from map)
|
||||
final sendspinId = _castToSendspinIdMap[effectivePlayerId];
|
||||
if (sendspinId != null) {
|
||||
track = _cacheService.getCachedTrackForPlayer(sendspinId);
|
||||
}
|
||||
|
||||
// Check Sendspin -> Cast (reverse lookup from map)
|
||||
if (track == null) {
|
||||
for (final entry in _castToSendspinIdMap.entries) {
|
||||
if (entry.value == effectivePlayerId) {
|
||||
track = _cacheService.getCachedTrackForPlayer(entry.key);
|
||||
if (track != null) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Dynamic ID computation for chromecast players
|
||||
// This handles cases where the map doesn't have the entry yet
|
||||
if (track == null) {
|
||||
// If effectivePlayerId looks like a Sendspin ID (cast-{8chars}), compute Cast ID
|
||||
if (effectivePlayerId.startsWith('cast-') && effectivePlayerId.length >= 13) {
|
||||
// Sendspin ID: cast-7df484e3 -> need to find Cast ID that starts with 7df484e3
|
||||
final prefix = effectivePlayerId.substring(5); // Remove "cast-"
|
||||
// Search through available players for a chromecast player with matching UUID prefix
|
||||
for (final p in _availablePlayers) {
|
||||
if (p.provider == 'chromecast' && p.playerId.startsWith(prefix)) {
|
||||
track = _cacheService.getCachedTrackForPlayer(p.playerId);
|
||||
if (track != null) {
|
||||
_logger.log('🔍 Found track via computed Cast ID: ${p.playerId}');
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Also try direct cache lookup with the prefix as partial ID
|
||||
if (track == null) {
|
||||
// Try common UUID patterns - the cache might have the full Cast UUID
|
||||
final possibleCastIds = _cacheService.getAllCachedPlayerIds()
|
||||
.where((id) => id.startsWith(prefix))
|
||||
.toList();
|
||||
for (final castId in possibleCastIds) {
|
||||
track = _cacheService.getCachedTrackForPlayer(castId);
|
||||
if (track != null) {
|
||||
_logger.log('🔍 Found track via cache scan for prefix $prefix: $castId');
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If effectivePlayerId looks like a Cast UUID, compute Sendspin ID
|
||||
if (track == null && effectivePlayerId.length >= 8 && effectivePlayerId.contains('-')) {
|
||||
final computedSendspinId = 'cast-${effectivePlayerId.substring(0, 8)}';
|
||||
track = _cacheService.getCachedTrackForPlayer(computedSendspinId);
|
||||
if (track != null) {
|
||||
_logger.log('🔍 Found track via computed Sendspin ID: $computedSendspinId');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return track;
|
||||
}
|
||||
|
||||
/// Get artwork URL for a player from cache
|
||||
@@ -443,7 +574,8 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
|
||||
_api = MusicAssistantAPI(serverUrl, _authManager);
|
||||
|
||||
_api!.connectionState.listen(
|
||||
_connectionStateSubscription?.cancel();
|
||||
_connectionStateSubscription = _api!.connectionState.listen(
|
||||
(state) async {
|
||||
_connectionState = state;
|
||||
notifyListeners();
|
||||
@@ -1587,8 +1719,16 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
final playerId = event['player_id'] as String?;
|
||||
if (playerId == null) return;
|
||||
|
||||
if (_selectedPlayer != null && playerId == _selectedPlayer!.playerId) {
|
||||
_updatePlayerState();
|
||||
// Check if this event is for the selected player - also check translated Cast<->Sendspin IDs
|
||||
// Events may come with Cast ID but selected player uses Sendspin ID (or vice versa)
|
||||
if (_selectedPlayer != null) {
|
||||
final selectedId = _selectedPlayer!.playerId;
|
||||
final isMatch = playerId == selectedId ||
|
||||
_castToSendspinIdMap[playerId] == selectedId ||
|
||||
_castToSendspinIdMap[selectedId] == playerId;
|
||||
if (isMatch) {
|
||||
_updatePlayerState();
|
||||
}
|
||||
}
|
||||
|
||||
final currentMedia = event['current_media'] as Map<String, dynamic>?;
|
||||
@@ -1703,6 +1843,18 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
if (!keepExisting) {
|
||||
_cacheService.setCachedTrackForPlayer(playerId, trackFromEvent);
|
||||
_logger.log('📋 Cached track for $playerName from player_updated: ${trackFromEvent.name}');
|
||||
|
||||
// Dual-cache for Cast<->Sendspin players so track is findable by either ID
|
||||
final sendspinId = _castToSendspinIdMap[playerId];
|
||||
if (sendspinId != null) {
|
||||
_cacheService.setCachedTrackForPlayer(sendspinId, trackFromEvent);
|
||||
_logger.log('📋 Also cached under Sendspin ID: $sendspinId');
|
||||
} else if (playerId.length >= 8 && playerId.contains('-')) {
|
||||
// Compute Sendspin ID for chromecast players not yet in map
|
||||
final computedSendspinId = 'cast-${playerId.substring(0, 8)}';
|
||||
_cacheService.setCachedTrackForPlayer(computedSendspinId, trackFromEvent);
|
||||
_logger.log('📋 Also cached under computed Sendspin ID: $computedSendspinId');
|
||||
}
|
||||
} else {
|
||||
_logger.log('📋 Skipped caching for $playerName - already have better data (artist: $existingHasProperArtist, image: $existingHasImage)');
|
||||
}
|
||||
@@ -2196,12 +2348,28 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
|
||||
Future<void> _loadAndSelectPlayers({bool forceRefresh = false, bool coldStart = false}) async {
|
||||
try {
|
||||
// Don't skip on coldStart - we need to apply full auto-selection priority logic
|
||||
if (!forceRefresh &&
|
||||
!coldStart &&
|
||||
_cacheService.isPlayersCacheValid() &&
|
||||
_availablePlayers.isNotEmpty) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Load persisted Cast-to-Sendspin mappings from database
|
||||
// This ensures we remember mappings even when Sendspin players are unavailable
|
||||
if (_castToSendspinIdMap.isEmpty) {
|
||||
try {
|
||||
final persistedMappings = await DatabaseService.instance.getAllCastToSendspinMappings();
|
||||
_castToSendspinIdMap.addAll(persistedMappings);
|
||||
if (persistedMappings.isNotEmpty) {
|
||||
_logger.log('🔗 Loaded ${persistedMappings.length} Cast->Sendspin mappings from database');
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.log('⚠️ Failed to load Cast->Sendspin mappings: $e');
|
||||
}
|
||||
}
|
||||
|
||||
final allPlayers = await getPlayers();
|
||||
final builtinPlayerId = await SettingsService.getBuiltinPlayerId();
|
||||
|
||||
@@ -2256,9 +2424,19 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
// - When ungrouped: show original Cast, hide Sendspin version
|
||||
// This gives power control and proper queue behavior when not syncing
|
||||
final sendspinSuffix = ' (Sendspin)';
|
||||
final sendspinPlayers = _availablePlayers
|
||||
.where((p) => p.name.endsWith(sendspinSuffix))
|
||||
.toList();
|
||||
|
||||
// Detect Sendspin players by:
|
||||
// 1. Name ends with " (Sendspin)" (e.g., "Kitchen speaker (Sendspin)")
|
||||
// 2. ID starts with "cast-" and name equals ID (e.g., ID="cast-7df484e3", name="cast-7df484e3")
|
||||
// This handles Cast devices where MA registers Sendspin player with raw ID as name
|
||||
bool isSendspinPlayer(Player p) {
|
||||
if (p.name.endsWith(sendspinSuffix)) return true;
|
||||
// Check for Sendspin players named with their raw ID (cast-{uuid-prefix})
|
||||
if (p.playerId.startsWith('cast-') && p.name == p.playerId) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
final sendspinPlayers = _availablePlayers.where(isSendspinPlayer).toList();
|
||||
|
||||
// NOTE: Don't clear _castToSendspinIdMap - we want to remember mappings
|
||||
// even when the Sendspin player is temporarily unavailable (e.g., device off)
|
||||
@@ -2268,18 +2446,47 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
// Build maps for Sendspin players and their grouped status
|
||||
final sendspinByBaseName = <String, Player>{};
|
||||
final groupedSendspinBaseNames = <String>{};
|
||||
// Track Sendspin players that have raw ID as name (need renaming)
|
||||
final rawIdSendspinPlayers = <String, Player>{};
|
||||
|
||||
for (final player in sendspinPlayers) {
|
||||
final baseName = player.name.substring(0, player.name.length - sendspinSuffix.length);
|
||||
String baseName;
|
||||
Player? regularCastPlayer;
|
||||
|
||||
if (player.name.endsWith(sendspinSuffix)) {
|
||||
// Standard "(Sendspin)" suffix naming
|
||||
baseName = player.name.substring(0, player.name.length - sendspinSuffix.length);
|
||||
regularCastPlayer = _availablePlayers.where(
|
||||
(p) => p.name == baseName && !isSendspinPlayer(p)
|
||||
).firstOrNull;
|
||||
} else if (player.playerId.startsWith('cast-') && player.name == player.playerId) {
|
||||
// Raw ID naming (e.g., "cast-7df484e3") - find matching Cast player by UUID prefix
|
||||
// Sendspin ID format: cast-{first 8 chars of Cast UUID}
|
||||
// Cast ID format: {uuid} e.g., 7df484e3-d2ee-c897-f746-2dffc29595ff
|
||||
final sendspinPrefix = player.playerId.substring(5); // Remove "cast-" prefix
|
||||
regularCastPlayer = _availablePlayers.where(
|
||||
(p) => p.playerId.startsWith(sendspinPrefix) && !isSendspinPlayer(p)
|
||||
).firstOrNull;
|
||||
baseName = regularCastPlayer?.name ?? player.name;
|
||||
if (regularCastPlayer != null) {
|
||||
rawIdSendspinPlayers[player.playerId] = player;
|
||||
_logger.log('🔍 Found raw-ID Sendspin player: ${player.playerId} matches Cast player "${regularCastPlayer.name}"');
|
||||
}
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
sendspinByBaseName[baseName] = player;
|
||||
|
||||
// Find the corresponding regular Cast player and store the ID mapping
|
||||
final regularCastPlayer = _availablePlayers.where(
|
||||
(p) => p.name == baseName && !p.name.endsWith(sendspinSuffix)
|
||||
).firstOrNull;
|
||||
// Store the ID mapping and persist to database
|
||||
if (regularCastPlayer != null) {
|
||||
_castToSendspinIdMap[regularCastPlayer.playerId] = player.playerId;
|
||||
_logger.log('🔗 Mapped Cast ID ${regularCastPlayer.playerId} -> Sendspin ID ${player.playerId}');
|
||||
// Persist mapping so it survives when Sendspin player is unavailable
|
||||
DatabaseService.instance.saveCastToSendspinMapping(
|
||||
regularCastPlayer.playerId,
|
||||
player.playerId,
|
||||
);
|
||||
}
|
||||
|
||||
if (player.isGrouped) {
|
||||
@@ -2292,10 +2499,23 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
|
||||
// Filter players based on grouped status
|
||||
_availablePlayers = _availablePlayers.where((player) {
|
||||
final isSendspin = player.name.endsWith(sendspinSuffix);
|
||||
final isSendspin = isSendspinPlayer(player);
|
||||
|
||||
if (isSendspin) {
|
||||
final baseName = player.name.substring(0, player.name.length - sendspinSuffix.length);
|
||||
// Get base name for this Sendspin player
|
||||
String baseName;
|
||||
if (player.name.endsWith(sendspinSuffix)) {
|
||||
baseName = player.name.substring(0, player.name.length - sendspinSuffix.length);
|
||||
} else if (rawIdSendspinPlayers.containsKey(player.playerId)) {
|
||||
// For raw ID players, find the base name from our earlier mapping
|
||||
baseName = sendspinByBaseName.entries
|
||||
.firstWhere((e) => e.value.playerId == player.playerId,
|
||||
orElse: () => MapEntry(player.name, player))
|
||||
.key;
|
||||
} else {
|
||||
baseName = player.name;
|
||||
}
|
||||
|
||||
// Keep Sendspin only if grouped
|
||||
if (player.isGrouped) {
|
||||
return true;
|
||||
@@ -2315,13 +2535,24 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
}
|
||||
}).toList();
|
||||
|
||||
// Rename remaining Sendspin players to remove the suffix
|
||||
// Rename remaining Sendspin players to remove the suffix or give proper name
|
||||
_availablePlayers = _availablePlayers.map((player) {
|
||||
if (player.name.endsWith(sendspinSuffix)) {
|
||||
final cleanName = player.name.substring(0, player.name.length - sendspinSuffix.length);
|
||||
_logger.log('✨ Renaming "${player.name}" to "$cleanName"');
|
||||
return player.copyWith(name: cleanName);
|
||||
}
|
||||
// Rename raw ID Sendspin players to their proper name
|
||||
if (rawIdSendspinPlayers.containsKey(player.playerId)) {
|
||||
final properName = sendspinByBaseName.entries
|
||||
.firstWhere((e) => e.value.playerId == player.playerId,
|
||||
orElse: () => MapEntry(player.name, player))
|
||||
.key;
|
||||
if (properName != player.name) {
|
||||
_logger.log('✨ Renaming raw ID Sendspin "${player.name}" to "$properName"');
|
||||
return player.copyWith(name: properName);
|
||||
}
|
||||
}
|
||||
return player;
|
||||
}).toList();
|
||||
}
|
||||
@@ -2360,18 +2591,37 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
// But allow switching to a playing player when preferLocalPlayer is OFF
|
||||
// On coldStart, skip this block and apply full priority logic (playing > local > last selected)
|
||||
if (playerToSelect == null && _selectedPlayer != null && !coldStart) {
|
||||
// Check if selected player is still available - also check translated Cast/Sendspin IDs
|
||||
// When Cast player gets replaced by Sendspin version (or vice versa), we should keep selection
|
||||
final selectedId = _selectedPlayer!.playerId;
|
||||
final translatedId = _castToSendspinIdMap[selectedId];
|
||||
String? reverseTranslatedId;
|
||||
for (final entry in _castToSendspinIdMap.entries) {
|
||||
if (entry.value == selectedId) {
|
||||
reverseTranslatedId = entry.key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
final stillAvailable = _availablePlayers.any(
|
||||
(p) => p.playerId == _selectedPlayer!.playerId && p.available,
|
||||
(p) => p.available && (p.playerId == selectedId ||
|
||||
(translatedId != null && p.playerId == translatedId) ||
|
||||
(reverseTranslatedId != null && p.playerId == reverseTranslatedId)),
|
||||
);
|
||||
if (stillAvailable) {
|
||||
// Find the actual player in the list (might be Cast or Sendspin version)
|
||||
final currentPlayer = _availablePlayers.firstWhere(
|
||||
(p) => p.playerId == selectedId ||
|
||||
(translatedId != null && p.playerId == translatedId) ||
|
||||
(reverseTranslatedId != null && p.playerId == reverseTranslatedId),
|
||||
);
|
||||
|
||||
// If preferLocalPlayer is OFF, check if we should switch to a playing player
|
||||
if (!preferLocalPlayer) {
|
||||
final currentPlayerState = _availablePlayers
|
||||
.firstWhere((p) => p.playerId == _selectedPlayer!.playerId)
|
||||
.state;
|
||||
final currentIsPlaying = currentPlayerState == 'playing';
|
||||
final currentIsPlaying = currentPlayer.state == 'playing';
|
||||
// Exclude external sources - they're not playing MA content
|
||||
final playingPlayers = _availablePlayers.where(
|
||||
(p) => p.state == 'playing' && p.available,
|
||||
(p) => p.state == 'playing' && p.available && !p.isExternalSource,
|
||||
).toList();
|
||||
|
||||
// Switch to playing player only if current isn't playing and exactly one other is
|
||||
@@ -2383,9 +2633,10 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
|
||||
// Keep current selection if no switch happened
|
||||
if (playerToSelect == null) {
|
||||
playerToSelect = _availablePlayers.firstWhere(
|
||||
(p) => p.playerId == _selectedPlayer!.playerId,
|
||||
);
|
||||
playerToSelect = currentPlayer;
|
||||
if (currentPlayer.playerId != selectedId) {
|
||||
_logger.log('🔄 Selected player ID changed (Cast<->Sendspin): $selectedId -> ${currentPlayer.playerId}');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2400,8 +2651,9 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
|
||||
if (!preferLocalPlayer) {
|
||||
// Priority 1 (normal): Single playing player (skip if multiple are playing)
|
||||
// Exclude external sources - they're not playing MA content
|
||||
final playingPlayers = _availablePlayers.where(
|
||||
(p) => p.state == 'playing' && p.available,
|
||||
(p) => p.state == 'playing' && p.available && !p.isExternalSource,
|
||||
).toList();
|
||||
if (playingPlayers.length == 1) {
|
||||
playerToSelect = playingPlayers.first;
|
||||
@@ -2415,18 +2667,31 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
(p) => p.playerId == builtinPlayerId && p.available,
|
||||
);
|
||||
_logger.log('📱 Auto-selected local player: ${playerToSelect?.name}');
|
||||
} catch (e) {}
|
||||
} catch (e) {
|
||||
// Local player not found or not available - check why
|
||||
final localPlayer = _availablePlayers
|
||||
.where((p) => p.playerId == builtinPlayerId)
|
||||
.toList();
|
||||
if (localPlayer.isEmpty) {
|
||||
_logger.log('⚠️ Priority 2 skipped: local player ($builtinPlayerId) not in available players list');
|
||||
} else {
|
||||
_logger.log('⚠️ Priority 2 skipped: local player found but available=${localPlayer.first.available}');
|
||||
}
|
||||
}
|
||||
} else if (playerToSelect == null && builtinPlayerId == null) {
|
||||
_logger.log('⚠️ Priority 2 skipped: builtinPlayerId is null');
|
||||
}
|
||||
}
|
||||
|
||||
// Priority 3: Last manually selected player
|
||||
if (playerToSelect == null && lastSelectedPlayerId != null) {
|
||||
try {
|
||||
playerToSelect = _availablePlayers.firstWhere(
|
||||
(p) => p.playerId == lastSelectedPlayerId && p.available,
|
||||
);
|
||||
playerToSelect = _availablePlayers.cast<Player?>().firstWhere(
|
||||
(p) => p!.playerId == lastSelectedPlayerId && p.available,
|
||||
orElse: () => null,
|
||||
);
|
||||
if (playerToSelect != null) {
|
||||
_logger.log('🔄 Auto-selected last used player: ${playerToSelect?.name}');
|
||||
} catch (e) {}
|
||||
}
|
||||
}
|
||||
|
||||
// Priority 4: First available player
|
||||
@@ -2450,7 +2715,15 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
}
|
||||
|
||||
void selectPlayer(Player player, {bool skipNotify = false}) async {
|
||||
_selectedPlayer = player;
|
||||
// Reentrancy guard - prevent concurrent selection which can cause race conditions
|
||||
if (_selectPlayerInProgress) {
|
||||
_logger.log('⚠️ selectPlayer already in progress, skipping for ${player.name}');
|
||||
return;
|
||||
}
|
||||
_selectPlayerInProgress = true;
|
||||
|
||||
try {
|
||||
_selectedPlayer = player;
|
||||
|
||||
// Cache for instant display on app resume
|
||||
_cacheService.setCachedSelectedPlayer(player);
|
||||
@@ -2462,17 +2735,24 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
// IMPORTANT: Always set from cache, even if null - this prevents showing
|
||||
// stale track info when switching to a non-playing player.
|
||||
// For grouped child players, this returns the leader's track
|
||||
_currentTrack = getCachedTrackForPlayer(player.playerId);
|
||||
// IMPORTANT: Clear track for external sources - they're playing non-MA content
|
||||
if (player.isExternalSource) {
|
||||
_currentTrack = null;
|
||||
} else {
|
||||
_currentTrack = getCachedTrackForPlayer(player.playerId);
|
||||
}
|
||||
|
||||
// Initialize position tracker for this player
|
||||
// Initialize position tracker for this player (skip for external sources)
|
||||
_positionTracker.onPlayerSelected(player.playerId);
|
||||
_positionTracker.updateFromServer(
|
||||
playerId: player.playerId,
|
||||
position: player.elapsedTime ?? 0.0,
|
||||
isPlaying: player.state == 'playing',
|
||||
duration: _currentTrack?.duration,
|
||||
serverTimestamp: player.elapsedTimeLastUpdated,
|
||||
);
|
||||
if (!player.isExternalSource) {
|
||||
_positionTracker.updateFromServer(
|
||||
playerId: player.playerId,
|
||||
position: player.elapsedTime ?? 0.0,
|
||||
isPlaying: player.state == 'playing',
|
||||
duration: _currentTrack?.duration,
|
||||
serverTimestamp: player.elapsedTimeLastUpdated,
|
||||
);
|
||||
}
|
||||
|
||||
// Switch audio handler mode based on player type
|
||||
final builtinPlayerId = await SettingsService.getBuiltinPlayerId();
|
||||
@@ -2571,6 +2851,9 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
if (!skipNotify) {
|
||||
notifyListeners();
|
||||
}
|
||||
} finally {
|
||||
_selectPlayerInProgress = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Cycle to the next active player (for notification switch button)
|
||||
@@ -2756,7 +3039,19 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
if (_api == null) return;
|
||||
|
||||
try {
|
||||
_logger.log('🔍 Preload ${player.name}: state=${player.state}, available=${player.available}');
|
||||
// Log app_id for playing players to help diagnose external source detection
|
||||
if (player.state == 'playing') {
|
||||
_logger.log('🔍 Preload ${player.name}: state=${player.state}, app_id=${player.appId}, isExternalSource=${player.isExternalSource}');
|
||||
} else {
|
||||
_logger.log('🔍 Preload ${player.name}: state=${player.state}, available=${player.available}');
|
||||
}
|
||||
|
||||
// Skip external sources - they're not playing MA content
|
||||
if (player.isExternalSource) {
|
||||
_logger.log('🔍 Preload ${player.name}: SKIPPED - external source (app_id=${player.appId})');
|
||||
_cacheService.setCachedTrackForPlayer(player.playerId, null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!player.available || !player.powered) {
|
||||
_logger.log('🔍 Preload ${player.name}: SKIPPED - not available or powered');
|
||||
@@ -2780,6 +3075,15 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
_cacheService.setCachedTrackForPlayer(player.playerId, track);
|
||||
_logger.log('🔍 Preload ${player.name}: CACHED track "${track.name}"');
|
||||
|
||||
// Dual-cache for Cast<->Sendspin players
|
||||
final sendspinId = _castToSendspinIdMap[player.playerId];
|
||||
if (sendspinId != null) {
|
||||
_cacheService.setCachedTrackForPlayer(sendspinId, track);
|
||||
} else if (player.provider == 'chromecast' && player.playerId.length >= 8) {
|
||||
final computedSendspinId = 'cast-${player.playerId.substring(0, 8)}';
|
||||
_cacheService.setCachedTrackForPlayer(computedSendspinId, track);
|
||||
}
|
||||
|
||||
// Also precache the image so it's ready for swipe preview
|
||||
final imageUrl = getImageUrl(track, size: 512);
|
||||
if (imageUrl != null) {
|
||||
@@ -2879,15 +3183,78 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
try {
|
||||
bool stateChanged = false;
|
||||
|
||||
// Get fresh player data - but look up from _availablePlayers which has
|
||||
// the processed names (Sendspin suffix removed) and correct filtering
|
||||
// Also check translated Cast<->Sendspin IDs
|
||||
final selectedId = _selectedPlayer!.playerId;
|
||||
final translatedSendspinId = _castToSendspinIdMap[selectedId];
|
||||
String? translatedCastId;
|
||||
for (final entry in _castToSendspinIdMap.entries) {
|
||||
if (entry.value == selectedId) {
|
||||
translatedCastId = entry.key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Try to refresh from API first for latest state
|
||||
final allPlayers = await getPlayers();
|
||||
final updatedPlayer = allPlayers.firstWhere(
|
||||
(p) => p.playerId == _selectedPlayer!.playerId,
|
||||
Player? rawPlayer = allPlayers.firstWhere(
|
||||
(p) => p.playerId == selectedId ||
|
||||
(translatedSendspinId != null && p.playerId == translatedSendspinId) ||
|
||||
(translatedCastId != null && p.playerId == translatedCastId),
|
||||
orElse: () => _selectedPlayer!,
|
||||
);
|
||||
|
||||
// Now get the processed version from _availablePlayers to preserve renamed name
|
||||
// But update with latest state (volume, playing state, etc.) from rawPlayer
|
||||
final processedPlayer = _availablePlayers.firstWhere(
|
||||
(p) => p.playerId == selectedId ||
|
||||
(translatedSendspinId != null && p.playerId == translatedSendspinId) ||
|
||||
(translatedCastId != null && p.playerId == translatedCastId),
|
||||
orElse: () => rawPlayer,
|
||||
);
|
||||
|
||||
// Use the processed player's name but raw player's state
|
||||
final updatedPlayer = processedPlayer.copyWith(
|
||||
state: rawPlayer.state,
|
||||
volumeLevel: rawPlayer.volumeLevel,
|
||||
volumeMuted: rawPlayer.volumeMuted,
|
||||
elapsedTime: rawPlayer.elapsedTime,
|
||||
elapsedTimeLastUpdated: rawPlayer.elapsedTimeLastUpdated,
|
||||
powered: rawPlayer.powered,
|
||||
available: rawPlayer.available,
|
||||
groupMembers: rawPlayer.groupMembers,
|
||||
syncedTo: rawPlayer.syncedTo,
|
||||
currentItemId: rawPlayer.currentItemId,
|
||||
isExternalSource: rawPlayer.isExternalSource,
|
||||
appId: rawPlayer.appId,
|
||||
);
|
||||
|
||||
_selectedPlayer = updatedPlayer;
|
||||
stateChanged = true;
|
||||
|
||||
// Handle external sources (Spotify Connect, TV optical, etc.)
|
||||
// These players are "playing" from MA's perspective but not MA content
|
||||
if (updatedPlayer.isExternalSource) {
|
||||
if (_currentTrack != null) {
|
||||
_currentTrack = null;
|
||||
_cacheService.setCachedTrackForPlayer(updatedPlayer.playerId, null);
|
||||
stateChanged = true;
|
||||
_persistPlaybackState();
|
||||
}
|
||||
if (_currentAudiobook != null) {
|
||||
_logger.log('📚 External source active, clearing audiobook context');
|
||||
_currentAudiobook = null;
|
||||
stateChanged = true;
|
||||
}
|
||||
// Clear notification for external source
|
||||
audioHandler.clearRemotePlaybackState();
|
||||
if (stateChanged) {
|
||||
notifyListeners();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Feed position tracker with server data
|
||||
// Log raw values to debug position issues
|
||||
final rawElapsedTime = updatedPlayer.elapsedTime;
|
||||
@@ -2980,6 +3347,15 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
// Update cache if queue track has good metadata
|
||||
if (queueHasImage || queueHasProperArtist) {
|
||||
_cacheService.setCachedTrackForPlayer(_selectedPlayer!.playerId, queueTrack);
|
||||
|
||||
// Dual-cache for Cast<->Sendspin players
|
||||
final sendspinId = _castToSendspinIdMap[_selectedPlayer!.playerId];
|
||||
if (sendspinId != null) {
|
||||
_cacheService.setCachedTrackForPlayer(sendspinId, queueTrack);
|
||||
} else if (_selectedPlayer!.provider == 'chromecast' && _selectedPlayer!.playerId.length >= 8) {
|
||||
final computedSendspinId = 'cast-${_selectedPlayer!.playerId.substring(0, 8)}';
|
||||
_cacheService.setCachedTrackForPlayer(computedSendspinId, queueTrack);
|
||||
}
|
||||
}
|
||||
}
|
||||
stateChanged = true;
|
||||
@@ -3352,6 +3728,31 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
effectivePlayerId = player.syncedTo!;
|
||||
}
|
||||
|
||||
// Translate Sendspin ID to Cast UUID for queue fetch
|
||||
// MA stores queues under the Cast UUID, not the Sendspin ID
|
||||
if (effectivePlayerId.startsWith('cast-') && effectivePlayerId.length >= 13) {
|
||||
// Sendspin ID format: cast-7df484e3 -> need Cast UUID starting with 7df484e3
|
||||
final prefix = effectivePlayerId.substring(5); // Remove "cast-"
|
||||
// Reverse lookup in the map
|
||||
for (final entry in _castToSendspinIdMap.entries) {
|
||||
if (entry.value == effectivePlayerId) {
|
||||
_logger.log('🔗 Translated Sendspin ID $effectivePlayerId to Cast UUID ${entry.key} for queue fetch');
|
||||
effectivePlayerId = entry.key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// If not in map, try to find in available players
|
||||
if (effectivePlayerId.startsWith('cast-')) {
|
||||
for (final p in _availablePlayers) {
|
||||
if (p.provider == 'chromecast' && p.playerId.startsWith(prefix)) {
|
||||
_logger.log('🔗 Found Cast UUID ${p.playerId} for Sendspin ID $effectivePlayerId via player lookup');
|
||||
effectivePlayerId = p.playerId;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final queue = await _api?.getQueue(effectivePlayerId);
|
||||
|
||||
// Persist queue to database for instant display on app resume
|
||||
@@ -3487,8 +3888,10 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
_logger.log('⏸️ Non-blocking local pause for builtin player');
|
||||
|
||||
// CRITICAL: Don't await these - they can block the UI thread
|
||||
// Use unawaited to make them fire-and-forget
|
||||
unawaited(_pcmAudioPlayer?.pause() ?? Future.value());
|
||||
// Use unawaited to make them fire-and-forget, but log errors
|
||||
unawaited((_pcmAudioPlayer?.pause() ?? Future.value()).catchError(
|
||||
(e) => _logger.log('⚠️ PCM pause error (non-blocking): $e'),
|
||||
));
|
||||
|
||||
// Don't pause just_audio for Sendspin mode - it's not being used for audio output
|
||||
// and calling pause() on it can cause blocking issues
|
||||
@@ -3504,8 +3907,10 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
// Send command to MA for proper state sync - don't await
|
||||
unawaited(_api?.pausePlayer(playerId) ?? Future.value());
|
||||
// Send command to MA for proper state sync - don't await, but log errors
|
||||
unawaited((_api?.pausePlayer(playerId) ?? Future.value()).catchError(
|
||||
(e) => _logger.log('⚠️ MA pause command error (non-blocking): $e'),
|
||||
));
|
||||
} catch (e) {
|
||||
ErrorHandler.logError('Pause player', e);
|
||||
// Don't rethrow - we want pause to be resilient
|
||||
@@ -3583,8 +3988,10 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
final builtinPlayerId = await SettingsService.getBuiltinPlayerId();
|
||||
if (builtinPlayerId != null && playerId == builtinPlayerId && _sendspinConnected) {
|
||||
_logger.log('⏭️ Non-blocking local stop for skip on builtin player');
|
||||
// Stop current audio immediately - fire and forget
|
||||
unawaited(_pcmAudioPlayer?.pause() ?? Future.value());
|
||||
// Stop current audio immediately - fire and forget, but log errors
|
||||
unawaited((_pcmAudioPlayer?.pause() ?? Future.value()).catchError(
|
||||
(e) => _logger.log('⚠️ PCM pause error on next (non-blocking): $e'),
|
||||
));
|
||||
// Don't stop just_audio - not used for Sendspin audio output
|
||||
}
|
||||
await _api?.nextTrack(playerId);
|
||||
@@ -3600,8 +4007,10 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
final builtinPlayerId = await SettingsService.getBuiltinPlayerId();
|
||||
if (builtinPlayerId != null && playerId == builtinPlayerId && _sendspinConnected) {
|
||||
_logger.log('⏮️ Non-blocking local stop for previous on builtin player');
|
||||
// Stop current audio immediately - fire and forget
|
||||
unawaited(_pcmAudioPlayer?.pause() ?? Future.value());
|
||||
// Stop current audio immediately - fire and forget, but log errors
|
||||
unawaited((_pcmAudioPlayer?.pause() ?? Future.value()).catchError(
|
||||
(e) => _logger.log('⚠️ PCM pause error on previous (non-blocking): $e'),
|
||||
));
|
||||
// Don't stop just_audio - not used for Sendspin audio output
|
||||
}
|
||||
await _api?.previousTrack(playerId);
|
||||
@@ -3642,15 +4051,43 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
return;
|
||||
}
|
||||
|
||||
// Translate Cast player ID to Sendspin ID if available
|
||||
// This is needed because regular Cast players can't sync with Sendspin players
|
||||
final actualTargetId = _castToSendspinIdMap[targetPlayerId] ?? targetPlayerId;
|
||||
if (actualTargetId != targetPlayerId) {
|
||||
_logger.log('🔗 Translated Cast ID to Sendspin ID: $targetPlayerId -> $actualTargetId');
|
||||
// Translate Cast player IDs to Sendspin IDs for group commands
|
||||
// Cast players don't support group commands - only their Sendspin counterparts do
|
||||
// We need to translate BOTH target and leader IDs
|
||||
//
|
||||
// The mapping comes from _castToSendspinIdMap which contains:
|
||||
// 1. Currently discovered mappings (from available Sendspin players)
|
||||
// 2. Persisted mappings from database (survives when Sendspin player is unavailable)
|
||||
String translateToSendspinId(String playerId, Player? player) {
|
||||
if (_castToSendspinIdMap.containsKey(playerId)) {
|
||||
_logger.log('🔗 Found Sendspin mapping: $playerId -> ${_castToSendspinIdMap[playerId]}');
|
||||
return _castToSendspinIdMap[playerId]!;
|
||||
}
|
||||
// No Sendspin counterpart known - use original ID
|
||||
return playerId;
|
||||
}
|
||||
|
||||
_logger.log('🔗 Calling API syncPlayerToLeader($actualTargetId, ${leaderPlayer.playerId})');
|
||||
await _api!.syncPlayerToLeader(actualTargetId, leaderPlayer.playerId);
|
||||
// Find target player to check its provider
|
||||
final targetPlayer = _availablePlayers.where((p) => p.playerId == targetPlayerId).firstOrNull;
|
||||
|
||||
// Translate BOTH target AND leader to Sendspin IDs
|
||||
// Only Sendspin players support the SET_MEMBERS feature required for grouping
|
||||
// Cast players will return "Player X does not support group commands"
|
||||
final actualTargetId = translateToSendspinId(targetPlayerId, targetPlayer);
|
||||
String actualLeaderId = leaderPlayer.playerId;
|
||||
|
||||
// If leader is a Cast player, translate to its Sendspin counterpart
|
||||
if (_castToSendspinIdMap.containsKey(leaderPlayer.playerId)) {
|
||||
actualLeaderId = _castToSendspinIdMap[leaderPlayer.playerId]!;
|
||||
_logger.log('🔗 Translated leader Cast ID to Sendspin ID: ${leaderPlayer.playerId} -> $actualLeaderId');
|
||||
}
|
||||
|
||||
if (actualTargetId != targetPlayerId) {
|
||||
_logger.log('🔗 Translated target Cast ID to Sendspin ID: $targetPlayerId -> $actualTargetId');
|
||||
}
|
||||
|
||||
_logger.log('🔗 Calling API syncPlayerToLeader($actualTargetId, $actualLeaderId)');
|
||||
await _api!.syncPlayerToLeader(actualTargetId, actualLeaderId);
|
||||
_logger.log('✅ API sync call completed');
|
||||
|
||||
// Refresh players to get updated group state
|
||||
@@ -3668,7 +4105,51 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
Future<void> unsyncPlayer(String playerId) async {
|
||||
try {
|
||||
_logger.log('🔓 Unsyncing player: $playerId');
|
||||
await _api?.unsyncPlayer(playerId);
|
||||
|
||||
// Find the player to check if it's a child
|
||||
final player = _availablePlayers.firstWhere(
|
||||
(p) => p.playerId == playerId,
|
||||
orElse: () => Player(
|
||||
playerId: playerId,
|
||||
name: '',
|
||||
available: false,
|
||||
powered: false,
|
||||
state: 'idle',
|
||||
),
|
||||
);
|
||||
|
||||
// Determine the effective player ID to unsync
|
||||
// For children, we unsync the child directly (not the leader!)
|
||||
// Unsyncing the leader would dissolve the entire group
|
||||
String effectivePlayerId = playerId;
|
||||
String? leaderId = player.syncedTo;
|
||||
|
||||
if (leaderId != null) {
|
||||
_logger.log('🔓 Player is a child synced to $leaderId, unsyncing child directly');
|
||||
}
|
||||
|
||||
// Try to unsync the player directly
|
||||
try {
|
||||
await _api?.unsyncPlayer(effectivePlayerId);
|
||||
} catch (e) {
|
||||
// Some players (like pure Sendspin CLI players) don't support set_members
|
||||
// In this case, we need to unsync via the leader instead
|
||||
if (e.toString().contains('set_members') && leaderId != null) {
|
||||
_logger.log('🔓 Child unsync failed (set_members not supported), unsyncing via leader');
|
||||
|
||||
// Try to find the Sendspin ID for the leader if it's a Cast UUID
|
||||
String leaderToUnsync = leaderId;
|
||||
if (_castToSendspinIdMap.containsKey(leaderId)) {
|
||||
leaderToUnsync = _castToSendspinIdMap[leaderId]!;
|
||||
_logger.log('🔓 Translated leader to Sendspin ID: $leaderToUnsync');
|
||||
}
|
||||
|
||||
await _api?.unsyncPlayer(leaderToUnsync);
|
||||
_logger.log('⚠️ Dissolved entire group (pure Sendspin player limitation)');
|
||||
} else {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh players to get updated group state
|
||||
await refreshPlayers();
|
||||
@@ -3933,10 +4414,13 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> toggleShuffle(String queueId) async {
|
||||
Future<void> toggleShuffle(String queueId, bool shuffleEnabled) async {
|
||||
_logger.log('🔀 toggleShuffle called: queueId=$queueId, shuffleEnabled=$shuffleEnabled');
|
||||
try {
|
||||
await _api?.toggleShuffle(queueId);
|
||||
await _api?.toggleShuffle(queueId, shuffleEnabled);
|
||||
_logger.log('🔀 toggleShuffle: API call completed');
|
||||
} catch (e) {
|
||||
_logger.log('🔀 toggleShuffle ERROR: $e');
|
||||
ErrorHandler.logError('Toggle shuffle', e);
|
||||
rethrow;
|
||||
}
|
||||
@@ -3975,6 +4459,7 @@ class MusicAssistantProvider with ChangeNotifier {
|
||||
_playerStateTimer?.cancel();
|
||||
_notificationPositionTimer?.cancel();
|
||||
_localPlayerStateReportTimer?.cancel();
|
||||
_connectionStateSubscription?.cancel();
|
||||
_localPlayerEventSubscription?.cancel();
|
||||
_playerUpdatedEventSubscription?.cancel();
|
||||
_playerAddedEventSubscription?.cancel();
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -558,7 +559,7 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
SizedBox(height: MediaQuery.of(context).padding.bottom + 16),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -703,10 +704,16 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
||||
},
|
||||
child: Scaffold(
|
||||
backgroundColor: colorScheme.background,
|
||||
body: CustomScrollView(
|
||||
body: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
// Responsive cover size: 50% of screen width, clamped between 200-320
|
||||
final coverSize = (constraints.maxWidth * 0.5).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(
|
||||
@@ -727,11 +734,11 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
||||
child: Hero(
|
||||
tag: HeroTags.albumCover + (widget.album.uri ?? widget.album.itemId) + _heroTagSuffix,
|
||||
child: Container(
|
||||
width: 280, // Increased size
|
||||
height: 280,
|
||||
width: coverSize,
|
||||
height: coverSize,
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceVariant,
|
||||
borderRadius: BorderRadius.circular(16), // Slightly more rounded
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.3),
|
||||
@@ -749,7 +756,7 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
||||
child: imageUrl == null
|
||||
? Icon(
|
||||
Icons.album_rounded,
|
||||
size: 120,
|
||||
size: coverSize * 0.43,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
)
|
||||
: null,
|
||||
@@ -906,14 +913,6 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
||||
],
|
||||
),
|
||||
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 +1079,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();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -243,57 +243,25 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _startArtistRadio() 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 {
|
||||
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),
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.log('Error starting artist radio: $e');
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(S.of(context)!.failedToStartRadio(e.toString())),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 +282,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,54 +313,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();
|
||||
|
||||
final api = maProvider.api;
|
||||
if (api == null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(S.of(context)!.notConnected)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// For adding to queue with radio mode, we use radio_mode but with 'add' option
|
||||
await 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 {
|
||||
@@ -534,10 +551,16 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
||||
},
|
||||
child: Scaffold(
|
||||
backgroundColor: colorScheme.background,
|
||||
body: CustomScrollView(
|
||||
body: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
// Responsive cover size: 40% of screen width, clamped between 160-280 (smaller for circular artist image)
|
||||
final coverSize = (constraints.maxWidth * 0.4).clamp(160.0, 280.0);
|
||||
final expandedHeight = coverSize + 100;
|
||||
|
||||
return CustomScrollView(
|
||||
slivers: [
|
||||
SliverAppBar(
|
||||
expandedHeight: 300,
|
||||
expandedHeight: expandedHeight,
|
||||
pinned: true,
|
||||
backgroundColor: colorScheme.background,
|
||||
leading: IconButton(
|
||||
@@ -557,8 +580,8 @@ 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(
|
||||
@@ -568,13 +591,13 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
||||
fadeOutDuration: Duration.zero,
|
||||
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,
|
||||
),
|
||||
),
|
||||
@@ -635,7 +658,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(
|
||||
@@ -648,23 +671,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),
|
||||
|
||||
@@ -673,7 +679,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(
|
||||
@@ -847,6 +853,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';
|
||||
@@ -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: 50% of screen width, clamped between 200-320
|
||||
final coverSize = (constraints.maxWidth * 0.5).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,8 +505,8 @@ 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(
|
||||
@@ -550,14 +517,14 @@ class _AudiobookDetailScreenState extends State<AudiobookDetailScreen> {
|
||||
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 +532,7 @@ class _AudiobookDetailScreenState extends State<AudiobookDetailScreen> {
|
||||
: Center(
|
||||
child: Icon(
|
||||
MdiIcons.bookOutline,
|
||||
size: 120,
|
||||
size: coverSize * 0.43,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
@@ -809,6 +776,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: 50% of screen width, clamped between 200-320
|
||||
final coverSize = (constraints.maxWidth * 0.5).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),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
+592
-367
File diff suppressed because it is too large
Load Diff
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,11 @@ 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;
|
||||
List<Artist>? _cachedDiscoverArtists;
|
||||
@@ -38,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
|
||||
@@ -135,6 +141,7 @@ 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');
|
||||
}
|
||||
|
||||
@@ -161,6 +168,7 @@ 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');
|
||||
}
|
||||
|
||||
@@ -187,6 +195,7 @@ 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');
|
||||
}
|
||||
|
||||
@@ -211,6 +220,7 @@ 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"');
|
||||
}
|
||||
|
||||
@@ -254,14 +264,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);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
@@ -279,6 +295,7 @@ class CacheService {
|
||||
_searchCache.clear();
|
||||
_searchCacheTime.clear();
|
||||
_playerTrackCache.clear();
|
||||
_playerTrackCacheTime.clear();
|
||||
_logger.log('🗑️ All detail caches cleared');
|
||||
}
|
||||
|
||||
@@ -364,4 +381,34 @@ class CacheService {
|
||||
}
|
||||
}();
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 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');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,4 +252,53 @@ class DatabaseService {
|
||||
|
||||
/// 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1528,6 +1528,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?;
|
||||
@@ -2067,11 +2068,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');
|
||||
@@ -2539,6 +2540,7 @@ class MusicAssistantAPI {
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.log('⚠️ Error parsing stream URI "$uri": $e');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2907,6 +2909,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';
|
||||
@@ -126,66 +128,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
|
||||
@@ -204,20 +184,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)
|
||||
@@ -394,18 +368,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)
|
||||
@@ -671,13 +654,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 {
|
||||
@@ -693,8 +674,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)
|
||||
|
||||
@@ -77,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
|
||||
|
||||
@@ -104,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
|
||||
@@ -345,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
|
||||
@@ -360,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;
|
||||
@@ -406,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();
|
||||
}
|
||||
|
||||
@@ -1022,6 +1101,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!();
|
||||
@@ -1163,7 +1244,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);
|
||||
|
||||
@@ -1239,6 +1320,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;
|
||||
|
||||
@@ -1277,8 +1361,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
|
||||
@@ -1322,9 +1406,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
|
||||
@@ -1337,6 +1451,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 &&
|
||||
@@ -1361,12 +1487,14 @@ 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),
|
||||
@@ -1536,10 +1664,7 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
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,
|
||||
@@ -1586,6 +1711,26 @@ 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
|
||||
@@ -1755,7 +1900,60 @@ class ExpandablePlayerState extends State<ExpandablePlayer>
|
||||
t: t,
|
||||
expandedElementsOpacity: expandedElementsOpacity,
|
||||
)
|
||||
: Row(
|
||||
// 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: [
|
||||
@@ -1946,6 +2144,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),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -1983,12 +2207,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,
|
||||
|
||||
@@ -9,6 +9,7 @@ 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
|
||||
@@ -56,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
|
||||
|
||||
@@ -3,18 +3,24 @@ 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 = 7.0;
|
||||
static const double secondaryTop = 27.0;
|
||||
static const double tertiaryTop = 46.0;
|
||||
// 2-line layout (centered): player name, hint
|
||||
static const double primaryTop2Line = 16.0;
|
||||
static const double secondaryTop2Line = 36.0;
|
||||
static const double textRightPadding = 12.0;
|
||||
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 secondaryFontSize = 14.0;
|
||||
static const double tertiaryFontSize = 14.0;
|
||||
static const FontWeight primaryFontWeight = FontWeight.w500;
|
||||
}
|
||||
|
||||
@@ -30,6 +36,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;
|
||||
|
||||
@@ -61,6 +71,7 @@ class MiniPlayerContent extends StatelessWidget {
|
||||
super.key,
|
||||
required this.primaryText,
|
||||
this.secondaryText,
|
||||
this.tertiaryText,
|
||||
this.imageUrl,
|
||||
required this.playerName,
|
||||
required this.backgroundColor,
|
||||
@@ -75,8 +86,13 @@ class MiniPlayerContent extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final hasSecondaryLine = secondaryText != null && secondaryText!.isNotEmpty;
|
||||
final hasTertiaryLine = tertiaryText != null && tertiaryText!.isNotEmpty;
|
||||
final slidePixels = slideOffset * width;
|
||||
|
||||
// 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 text width (leaves room for right padding)
|
||||
final textWidth = width - MiniPlayerLayout.textLeft - MiniPlayerLayout.textRightPadding;
|
||||
|
||||
@@ -99,10 +115,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,
|
||||
@@ -125,7 +141,7 @@ class MiniPlayerContent extends StatelessWidget {
|
||||
Positioned(
|
||||
left: MiniPlayerLayout.textLeft + slidePixels,
|
||||
top: hasSecondaryLine
|
||||
? MiniPlayerLayout.primaryTop
|
||||
? primaryTop
|
||||
: (MiniPlayerLayout.height - MiniPlayerLayout.primaryFontSize) / 2,
|
||||
right: MiniPlayerLayout.textRightPadding - slidePixels,
|
||||
child: Text(
|
||||
@@ -144,7 +160,7 @@ class MiniPlayerContent extends StatelessWidget {
|
||||
if (hasSecondaryLine)
|
||||
Positioned(
|
||||
left: MiniPlayerLayout.textLeft + slidePixels,
|
||||
top: MiniPlayerLayout.secondaryTop,
|
||||
top: secondaryTop,
|
||||
right: MiniPlayerLayout.textRightPadding - slidePixels,
|
||||
child: isHint
|
||||
? Row(
|
||||
@@ -179,6 +195,23 @@ class MiniPlayerContent extends StatelessWidget {
|
||||
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(
|
||||
tertiaryText!,
|
||||
style: TextStyle(
|
||||
color: textColor,
|
||||
fontSize: MiniPlayerLayout.tertiaryFontSize,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
+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,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -44,6 +44,10 @@ 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 = {};
|
||||
|
||||
@@ -128,6 +132,7 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
||||
void dispose() {
|
||||
_revealController.dispose();
|
||||
_refreshTimer?.cancel();
|
||||
_scrollController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -157,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();
|
||||
@@ -215,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) {
|
||||
@@ -255,9 +307,28 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
||||
|
||||
// Show different hint for onboarding vs regular use
|
||||
final isOnboarding = widget.showOnboardingHints;
|
||||
final hintText = isOnboarding
|
||||
? S.of(context)!.selectPlayerHint
|
||||
: S.of(context)!.holdToSync;
|
||||
|
||||
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),
|
||||
@@ -265,31 +336,92 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: Material(
|
||||
type: MaterialType.transparency,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
isOnboarding ? Icons.touch_app_outlined : Icons.lightbulb_outline,
|
||||
size: 18,
|
||||
color: colorScheme.onSurface.withOpacity(0.7),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
hintText,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface.withOpacity(0.7),
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w500,
|
||||
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 - all slide from behind mini player
|
||||
// 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';
|
||||
@@ -327,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: () {
|
||||
@@ -359,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(
|
||||
@@ -225,8 +226,8 @@ class _PlayerSelectorSheetState extends State<_PlayerSelectorSheet> {
|
||||
);
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
||||
|
||||
+2
-1
@@ -1,7 +1,7 @@
|
||||
name: ensemble
|
||||
description: A minimalistic Music Assistant client built with Flutter
|
||||
publish_to: 'none'
|
||||
version: 2.7.0-beta+30
|
||||
version: 2.7.4-beta+36
|
||||
|
||||
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