Compare commits

..
Author SHA1 Message Date
ChrisandClaude Opus 4.5 d7127ea7da chore: Bump version to 2.9.0-beta
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 10:16:35 +00:00
ChrisandClaude Opus 4.5 29b4887d0d docs: Add player selector implementation plan
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 10:04:58 +00:00
ChrisandClaude Opus 4.5 18603c34e1 Merge audit-fixes: Memory leaks, performance, and bug fixes
Phase 1 - Critical Memory Leaks & Safety:
- Fix pending API requests memory leak (max 100, cancel on reconnect)
- Fix ImageStream listener leaks in expandable player
- Add database batch operations (10x faster sync)
- Fix connection guard race condition
- Mark undersized touch targets as deprecated (WCAG)
- Extract SleepTimerProvider and ConnectionProvider skeletons

Phase 2 - UI/Widget Fixes:
- Add LRU cache eviction to MetadataService (bounded caches)
- Add staleness detection for async player state updates
- Add explicit animation controller listener cleanup

Phase 3 - Medium Priority:
- Add MediaItem equality operators (itemId + provider)
- Extract duration formatting utility (remove 3 duplicates)

Bug Fixes:
- Fix volume precision toggle not affecting player selector overlay

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 08:11:53 +00:00
ChrisandClaude Opus 4.5 5ed2bf7725 Fix volume precision toggle not affecting player selector overlay
The ExpandablePlayer was loading the volume precision setting only once
in initState(), so changes made in settings weren't reflected until app
restart. PlayerCards in the overlay were loading fresh values on each
creation.

Fix: Add didUpdateWidget to reload the precision mode setting when the
device reveal overlay becomes visible. This ensures the setting is fresh
after the user may have changed it in settings.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 07:44:13 +00:00
ChrisandClaude Opus 4.5 67a99c88a0 Phase 3: Medium priority fixes - MediaItem equality and duration formatting
MediaItem Equality (3.4):
- Add == operator based on itemId and provider
- Add hashCode using Object.hash for correct Set/Map behavior
- Enables proper comparison in collections and deduplication

Duration Formatter Utility (3.5):
- Create lib/utils/duration_formatter.dart with reusable functions
- Add DurationFormatter extension on Duration
- Add formatDurationSeconds() and formatDurationOrEmpty() functions
- Replace 3 duplicate _formatDuration implementations:
  - expandable_player.dart
  - chapters_panel.dart
  - queue_panel.dart

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 07:21:29 +00:00
ChrisandClaude Opus 4.5 ffbb41580b Phase 2: UI/Widget fixes and memory management
MetadataService Cache Eviction (2.4):
- Create LruCache<K,V> utility class with O(1) LRU operations
- Create NullableLruCache for caches storing null (failed lookups)
- Replace unbounded static maps with bounded LRU caches:
  - Description cache: 100 entries
  - Artist/album image caches: 200 entries each
  - Author image cache: 100 entries
  - Lyrics cache: 500 entries with manual eviction

Async Cancellation on Player Switch (2.2):
- Add staleness detection to _updatePlayerState()
- Capture player ID at operation start
- Check for player changes after each await
- Abort stale operations to prevent UI inconsistency

Scroll Controller Cleanup (2.3):
- Verified existing cleanup is correct
- Only tracks scroll controller has listener, properly removed

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 07:17:53 +00:00
ChrisandClaude Opus 4.5 6942b56cfb Phase 1: Critical memory leaks, safety & performance fixes
Memory Leak Fixes:
- Add max pending requests limit (100) to prevent unbounded growth
- Cancel pending requests in _reconnect() before reconnecting
- Track ImageStream listeners in expandable_player for proper cleanup
- Add cleanup in dispose() for active image stream listeners

Database Performance:
- Add batchCacheItems() method using drift batch API
- Chunk batches at 500 items to avoid SQLite limits
- Refactor sync_service to use batch inserts (~10x faster)
- Add BatchCacheItem data class for type-safe batch operations

Race Condition Fix:
- Make connection guard check-and-set atomic
- Create completer before check to close race window

WCAG Accessibility:
- Mark ButtonSizes.sm/md as @Deprecated (below 44x44 minimum)
- Add ButtonSizes.minAccessible constant (48x48)
- Add clear documentation on WCAG Level AA/AAA requirements

Provider Decomposition (partial):
- Extract SleepTimerProvider with callback pattern
- Extract ConnectionProvider skeleton for future integration
- Prepare facade pattern for backward compatibility

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 07:13:40 +00:00
ChrisandClaude Opus 4.5 14ba524ed0 refactor: Replace Play On popups with Player Selector overlay
Use the existing PlayerRevealOverlay for "Play On" actions instead of
the PlayerPickerSheet popup modal. This provides a more consistent UX
by reusing the same player selection interface throughout the app.

- Add onPlayerSelected callback and contextHint to PlayerRevealOverlay
- Add showPlayerSelectorForAction helper to GlobalPlayerOverlay
- Refactor album, artist, playlist, podcast, audiobook, and search screens
- Add localization strings for context-specific hints

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 06:45:57 +00:00
ChrisandClaude Opus 4.5 49fc2a77e7 fix: Multiple notification and UI fixes
- Clear notification when switching to idle player (fixes issue #42)
- Fix notification progress bar desync after seek and with Sendspin
  - Always use position tracker instead of PCM elapsed time
  - PCM elapsed resets to 0 on stream start, causing wrong position
- Fix invisible nav bar due to stale playerExpansionNotifier
  - Reset notifier when player hidden (disconnect/no player)
  - Reset notifier after collapse() completes even if already at 0
- Fix welcome backdrop showing dark color in light theme
  - Now uses theme-appropriate surface color

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 05:26:33 +00:00
ChrisandClaude Opus 4.5 6632fa14c6 feat: Add sleep timer and fix progress bar freeze bug
Sleep Timer:
- Add sleep timer panel with preset durations (15/30/45/60 min)
- Support finish current track option
- Show countdown in queue panel header
- Auto-stop playback when timer expires

Progress Bar Fix:
- Fix anchor refresh logic when server sends stale position data
- Allow anchor refresh even with suspicious reset when anchor is stale
- Use interpolated position to prevent backward jumps from bad server data

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 04:47:31 +00:00
ChrisandClaude Opus 4.5 a0cac2174f chore: Bump version to 2.8.9-beta
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-18 09:37:44 +00:00
ChrisandClaude Opus 4.5 056d1fb854 refactor: Move audiobook libraries toggle from settings to library menu
- Remove "Show only artists with albums" option from settings (now in library menu)
- Remove "Audiobook Libraries" section from settings screen
- Add ABS library filter to Books tab options menu
- Show spinner on menu button while syncing libraries

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-18 09:33:27 +00:00
ChrisandClaude Opus 4.5 a4cc7115bf chore: Localization audit and debug cleanup
- Localize hardcoded strings in search_screen.dart (21 strings)
- Localize language names in settings_screen.dart
- Localize queue screen messages and tooltips
- Localize widget strings (queue_panel, debug_console)
- Add 15 new localization keys to app_en.arb
- Remove all debugPrint statements from widget files
  - expandable_player.dart (11 removed)
  - queue_panel.dart (8 removed)
  - player_selector.dart (2 removed)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-18 08:58:31 +00:00
ChrisandClaude Opus 4.5 1f3188fa6c feat: Add player navigation to artist/album detail screens
- Tap artist name in expanded player to navigate to artist details
- Tap album name in expanded player to navigate to album details
- Use global navigator key for overlay context navigation
- Fix album details to use fresh album data for artist display
- Fix EmptyState widgets to be scrollable for PageView swipe detection

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-18 08:36:50 +00:00
ChrisandClaude Opus 4.5 9527ba341e fix: Hide providers not synced to library from filter list
- Provider counts now only count items where inLibrary=true
  (the provider that actually added the item to library)
- Providers with 0 items are hidden from the filter list
- Fixes issue where playback-only providers appeared with
  duplicate counts matching other accounts

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-18 07:56:47 +00:00
ChrisandClaude Opus 4.5 79e9e02f53 docs: Add session documentation for optimistic updates and podcast filtering
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-17 23:10:15 +00:00
ChrisandClaude Opus 4.5 d14a4b99c6 fix: Optimistic updates for library buttons and podcast provider filtering
- Add inLibrary field to ProviderMapping for accurate ownership tracking
- Fix podcast provider filtering to use inLibrary field
- Add itunes_podcasts to provider capabilities
- Convert album/artist/podcast detail screens to use optimistic updates
  (button updates immediately, reverts on API failure)
- Remove server-side provider filtering from search
- Add client-side provider filtering for search in-library mode
- Fix episode loading fallback for non-library podcasts

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-17 23:08:11 +00:00
ChrisandClaude Opus 4.5 7e72b08f44 docs: Add detailed documentation for per-provider sync implementation
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-17 10:26:35 +00:00
ChrisandClaude Opus 4.5 801952482f feat: Add per-provider sync with source tracking for instant filtering
- Add sourceProviders column to database schema (v6) for tracking which
  provider instance each item came from
- Update SyncService to sync each enabled provider separately and tag
  items with their source provider
- Add client-side filtering methods that use source tracking to properly
  differentiate between multiple accounts of the same provider type
  (e.g., two Spotify accounts)
- Update library UI to use instant client-side filtering with background
  sync for data freshness

This enables instant UI updates when toggling provider filters, with
accurate filtering even for same-provider-type accounts.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-17 10:23:58 +00:00
ChrisandClaude Opus 4.5 bae1154bcf feat: Add server-side sorting for library items
- Add orderBy parameter to API methods (getArtists, getAlbums, getTracks,
  getPlaylists, getRadioStations, getPodcasts)
- Add orderBy parameter to provider load methods
- Migrate legacy sort values (alpha → name, alpha_desc → name_desc, etc.)
- Use MA API sort values: name, name_desc, year, year_desc, timestamp_added,
  timestamp_added_desc, last_played, play_count, artist_name, duration
- Trigger server-side reload when sort option changes
- Add options menu overlay management (closes on navigation)
- Trust server-side sorting instead of re-sorting client-side

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-17 00:50:48 +00:00
50 changed files with 7962 additions and 1623 deletions
+336
View File
@@ -0,0 +1,336 @@
# Per-Provider Sync Implementation
## Date: January 17, 2026
## Overview
This document details the implementation of per-provider sync with source tracking, enabling instant client-side filtering that properly differentiates between multiple accounts of the same provider type (e.g., two different Spotify accounts).
## Problem Statement
### The Core Issue
When a user has multiple accounts of the same provider type (e.g., two Spotify accounts: "Chris Laycock" and "Bababagoly"), the existing provider filter couldn't differentiate between them.
**Why?** Music Assistant's `provider_mappings` field on media items shows which providers **CAN PLAY** an item, not which provider **ADDED** it. When both Spotify accounts can play the same artist, both appear in `provider_mappings`, making client-side filtering impossible.
### Previous Approach (Failed)
The initial implementation tried to filter client-side using `provider_mappings`:
```dart
bool isItemAllowedByProviderFilter(MediaItem item) {
final mappings = item.providerMappings;
for (final mapping in mappings) {
if (_providerFilter.contains(mapping.providerInstance)) {
return true;
}
}
return false;
}
```
**Result:** Both Spotify accounts showed the same items because `provider_mappings` contained both account IDs for shared content.
### Race Condition Issue
Additionally, when rapidly toggling providers, a race condition occurred:
1. User toggles Provider A off
2. Sync starts for remaining providers
3. User toggles Provider B off before sync completes
4. First sync completes with wrong filter state
5. UI shows incorrect results
## Solution: Per-Provider Sync with Source Tracking
### Concept
Instead of relying on `provider_mappings`, we:
1. **Sync each provider separately** using the MA API's `provider` parameter
2. **Tag each item** with which provider instance(s) returned it
3. **Store source tracking** in the local database
4. **Filter client-side** using the source tracking data (instant)
5. **Background sync** keeps data fresh without blocking UI
### Why This Works
When we call the MA API with `provider: ["spotify--RKnr3jKx"]`, the server returns **only items from that specific account's library**. By syncing each provider separately and remembering which provider returned each item, we can accurately filter.
## Implementation Details
### 1. Database Schema Update
**File:** `lib/database/database.dart`
Added `sourceProviders` column to `LibraryCache` table:
```dart
class LibraryCache extends Table {
// ... existing columns ...
/// Provider instance IDs that provided this item (JSON array)
/// Used for client-side filtering by source provider
TextColumn get sourceProviders => text().withDefault(const Constant('[]'))();
}
```
**Schema version:** 5 → 6
**Migration:**
```dart
if (from < 6) {
await customStatement(
"ALTER TABLE library_cache ADD COLUMN source_providers TEXT NOT NULL DEFAULT '[]'"
);
}
```
### 2. Database Service Updates
**File:** `lib/services/database_service.dart`
Added `sourceProvider` parameter to `cacheItem()`:
```dart
Future<void> cacheItem<T>({
required String itemType,
required String itemId,
required Map<String, dynamic> data,
String? sourceProvider, // NEW: tracks which provider this item came from
})
```
Added new method to retrieve items with source tracking:
```dart
Future<List<(Map<String, dynamic>, List<String>)>> getCachedItemsWithProviders(String itemType)
```
Returns tuples of `(itemData, sourceProviderIds)`.
### 3. SyncService Rewrite
**File:** `lib/services/sync_service.dart`
#### New Fields
```dart
// Source provider tracking for client-side filtering
Map<String, List<String>> _albumSourceProviders = {};
Map<String, List<String>> _artistSourceProviders = {};
Map<String, List<String>> _audiobookSourceProviders = {};
Map<String, List<String>> _playlistSourceProviders = {};
```
#### Per-Provider Sync Logic
```dart
Future<void> syncFromApi(MusicAssistantAPI api, {
bool force = false,
List<String>? providerInstanceIds,
}) async {
// If specific providers are requested, sync each separately
if (providerInstanceIds != null && providerInstanceIds.isNotEmpty) {
for (final providerId in providerInstanceIds) {
// Fetch from this specific provider
final results = await Future.wait([
api.getAlbums(limit: 1000, providerInstanceIds: [providerId]),
api.getArtists(limit: 1000, providerInstanceIds: [providerId]),
// ... etc
]);
// Track source provider for each item
for (final album in albums) {
albumMap[album.itemId] = album;
_albumSourceProviders.putIfAbsent(album.itemId, () => []);
if (!_albumSourceProviders[album.itemId]!.contains(providerId)) {
_albumSourceProviders[album.itemId]!.add(providerId);
}
}
}
}
}
```
#### Client-Side Filtering Methods
```dart
/// Filter albums by source provider (instant, no network)
List<Album> getAlbumsFilteredByProviders(Set<String> enabledProviderIds) {
if (enabledProviderIds.isEmpty || _albumSourceProviders.isEmpty) {
return _cachedAlbums;
}
return _cachedAlbums.where((album) {
final sources = _albumSourceProviders[album.itemId];
if (sources == null || sources.isEmpty) return true; // No tracking = show
return sources.any((s) => enabledProviderIds.contains(s));
}).toList();
}
// Similar methods for artists, audiobooks, playlists
```
### 4. Library Screen Updates
**File:** `lib/screens/new_library_screen.dart`
#### Hybrid Provider Toggle Handler
```dart
void _handleProviderToggle(String providerId, bool enabled) {
final maProvider = context.read<MusicAssistantProvider>();
// Instant UI update via global provider toggle
maProvider.toggleProviderEnabled(providerId, enabled);
setState(() {}); // Rebuild with client-side filtering
// Background sync after 1.5s debounce
_providerFilterDebounce?.cancel();
_providerFilterDebounce = Timer(const Duration(milliseconds: 1500), () async {
if (mounted) {
await maProvider.forceLibrarySync();
if (mounted) setState(() {});
}
});
}
```
#### Updated Tab Builders
Artists tab now uses source tracking:
```dart
Widget _buildArtistsTab(BuildContext context, S l10n) {
return Selector<MusicAssistantProvider, (List<Artist>, bool, Set<String>)>(
selector: (_, provider) => (
provider.artists,
provider.isLoading,
provider.enabledProviderIds.toSet()
),
builder: (context, data, _) {
final (allArtists, isLoading, enabledProviders) = data;
// Client-side filtering using SyncService source tracking
final syncService = SyncService.instance;
final filteredArtists = syncService.hasSourceTracking && enabledProviders.isNotEmpty
? syncService.getArtistsFilteredByProviders(enabledProviders)
: allArtists;
// ... rest of build
},
);
}
```
Similar updates for albums, playlists, and audiobooks tabs.
### 5. Provider Instance Model
**File:** `lib/models/provider_instance.dart` (new file)
```dart
class ProviderInstance {
final String instanceId; // e.g., "spotify--abc123"
final String domain; // e.g., "spotify"
final String name; // e.g., "Spotify (John's Account)"
final bool available;
/// Known music provider domains
static const Set<String> musicProviderDomains = {
'spotify', 'tidal', 'qobuz', 'deezer', 'ytmusic', 'soundcloud',
'apple_music', 'amazon_music', 'plex', 'subsonic', 'opensubsonic',
'jellyfin', 'emby', 'navidrome', 'audiobookshelf', 'filesystem',
'tunein', 'radiobrowser', 'snapcast', 'fully_kiosk',
};
bool get isMusicProvider => musicProviderDomains.contains(domain);
}
```
## Data Flow
```
┌─────────────────────────────────────────────────────────────────┐
│ User Toggles Provider │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ 1. MusicAssistantProvider.toggleProviderEnabled() │
│ - Updates enabledProviderIds │
│ - Triggers setState() for instant UI update │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ 2. UI Rebuilds Immediately │
│ - Selector detects enabledProviderIds change │
│ - Calls SyncService.getArtistsFilteredByProviders() │
│ - Filters using source tracking (instant, no network) │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ 3. Background Sync (after 1.5s debounce) │
│ - forceLibrarySync() called │
│ - Syncs each enabled provider separately │
│ - Updates source tracking in database │
│ - UI refreshes with fresh data │
└─────────────────────────────────────────────────────────────────┘
```
## Files Changed
| File | Changes |
|------|---------|
| `lib/database/database.dart` | Added `sourceProviders` column, schema v6, migration |
| `lib/database/database.g.dart` | Auto-generated from schema changes |
| `lib/services/database_service.dart` | Added `sourceProvider` param, `getCachedItemsWithProviders()` |
| `lib/services/sync_service.dart` | Per-provider sync, source tracking maps, filtering methods |
| `lib/screens/new_library_screen.dart` | Hybrid toggle handler, updated tab builders |
| `lib/models/provider_instance.dart` | New model for provider instances |
## Testing Checklist
- [ ] Fresh install: First sync should populate source tracking
- [ ] Toggle single provider: UI updates instantly
- [ ] Toggle multiple providers rapidly: Debounce prevents race conditions
- [ ] Two Spotify accounts: Toggling one only shows that account's items
- [ ] Mixed providers: Toggling Spotify doesn't affect Audiobookshelf items
- [ ] Legacy cache: Items without source tracking show regardless of filter
- [ ] Pull to refresh: Refreshes source tracking data
## Known Limitations
1. **First sync required:** Source tracking only works after at least one sync with providers enabled
2. **Network cost:** Per-provider sync makes N API calls (one per provider) vs. 1 call for all providers
3. **Items in multiple accounts:** If the same item exists in both Spotify accounts, it will show when either is enabled
## Future Improvements
1. **Incremental sync:** Only sync changed items instead of full library
2. **Provider-specific cache age:** Different sync intervals per provider
3. **Offline source tracking:** Persist source tracking independently of full cache
## Branch
All changes are on the `feature/per-provider-sync` branch.
```bash
git checkout feature/per-provider-sync
```
## Commit
```
feat: Add per-provider sync with source tracking for instant filtering
- Add sourceProviders column to database schema (v6) for tracking which
provider instance each item came from
- Update SyncService to sync each enabled provider separately and tag
items with their source provider
- Add client-side filtering methods that use source tracking to properly
differentiate between multiple accounts of the same provider type
- Update library UI to use instant client-side filtering with background
sync for data freshness
```
+217
View File
@@ -0,0 +1,217 @@
# Provider Filter Implementation Notes
## Overview
This document captures the context and learnings from an attempted implementation of provider filtering in the Ensemble app. The goal was to allow users to filter their library to show only items from a specific music provider (e.g., only one Spotify account when multiple are configured).
## The Problem
Users with multiple music provider accounts (e.g., two Spotify accounts: one personal, one family) want to filter their library view to show only items from one specific account. The Music Assistant (MA) web UI successfully implements this feature.
## What Works vs What Failed
### Works: Different Provider Types
Filtering between different provider types (e.g., Spotify vs Tidal vs Plex) works correctly. Each provider type has distinct `provider_mappings` entries.
### Failed: Multiple Accounts of Same Provider
Filtering between multiple Spotify accounts (e.g., `spotify--abc123` vs `spotify--xyz789`) does NOT work correctly. The same library items appear regardless of which Spotify account is selected.
## Root Cause Analysis
### The provider_mappings Problem
MA's `provider_mappings` field on media items does NOT indicate "which account ADDED this item to the library." Instead, it indicates "which providers CAN PLAY this item."
Example: An artist "Ari Mason" that exists ONLY in User A's Spotify library will show provider_mappings containing BOTH Spotify accounts:
```json
{
"provider_mappings": [
{"provider_instance": "spotify--userA_id", "item_id": "..."},
{"provider_instance": "spotify--userB_id", "item_id": "..."}
]
}
```
This happens because:
1. MA's internal database stores that the artist exists
2. MA knows both Spotify accounts CAN play this artist (Spotify has the content)
3. MA doesn't track WHICH account originally added the item to the library
### MA Web UI Behavior
The MA web UI's provider filter works differently - it appears to use server-side filtering via the `provider` parameter on library_items API calls. When you select a single provider in MA settings, the API returns only items from that provider's library.
## API Investigation
### Server-Side Filtering Parameter
The MA server's `library_items` method accepts a `provider` parameter:
- Parameter name: `provider` (string or list of strings)
- Endpoint: `music/{type}/library_items` (e.g., `music/artists/library_items`)
- Expected behavior: Filter to only return items from the specified provider's library
### What We Tried
1. **Client-side filtering based on provider_mappings**
- Result: Failed - all Spotify accounts appear in mappings regardless of which added the item
2. **Server-side filtering with `provider` parameter**
- Result: Partially implemented but behavior was inconsistent
- The API accepts the parameter but may not filter correctly for same-provider-type accounts
3. **Using `provider_instance_id_or_domain` parameter**
- Result: This parameter is for getting specific items by ID, not for filtering library_items
## Code Locations
### Files Modified (in stash)
The implementation attempt is preserved in git stash:
```bash
git stash list # Look for "provider-filter-and-dropdown-work"
git stash show -p stash@{0} # View the changes
```
Key files that were modified:
1. **lib/providers/music_assistant_provider.dart**
- `_disabledProviders`: List of disabled provider instance IDs (local app setting)
- `selectedProviderForFilter`: Returns single enabled provider for server-side filtering
- `toggleProviderEnabled()`: Toggle provider on/off and trigger re-sync
- `loadDisabledProviders()`: Load from local settings
- `filterByProvider()`: Client-side filtering (enhanced version)
- `isItemAllowedByProviderFilter()`: Check if item should be visible
2. **lib/services/music_assistant_api.dart**
- Added `provider` parameter to: `getArtists`, `getAlbums`, `getTracks`, `getRandomArtists`, `getRandomAlbums`
- Added `MusicProvider` model parsing from `/providers` endpoint
- `musicProviders` getter: List of available music providers
3. **lib/services/sync_service.dart**
- Added `provider` parameter to `syncFromApi()` and `forceSync()`
- Pass provider filter to API calls during sync
4. **lib/services/settings_service.dart**
- `getDisabledMusicProviders()`: Get list of disabled provider IDs
- `setDisabledMusicProviders()`: Save disabled providers
- `toggleProviderEnabled()`: Toggle and persist
5. **lib/screens/settings_screen.dart**
- UI for toggling individual providers on/off
- Display provider name and instance ID
6. **lib/screens/new_library_screen.dart**
- Integration with provider filtering
7. **lib/models/music_provider.dart** (new file)
- Model for MA provider instances
- Fields: `instanceId`, `domain`, `name`, `available`
## Race Condition Issue
A race condition was identified where:
1. Initial app sync starts WITHOUT provider filter
2. User toggles provider filter
3. `clearCache()` is called
4. New sync with provider filter tries to start
5. "Sync already in progress" - new sync is skipped
6. Result: Old unfiltered data remains
Fix attempted: Reset `_isSyncing = false` in `clearCache()` to allow fresh sync.
## Potential Solutions to Explore
### 1. Investigate MA Server-Side Filtering
The MA server should support filtering by provider. Need to verify:
- Does the `provider` parameter work for filtering between same-type providers?
- Is there a different parameter or API endpoint?
- Check MA source code: https://github.com/music-assistant/server
### 2. Library Sync Per Provider
Instead of syncing all items and filtering, sync each provider's library separately:
```dart
for (final provider in enabledProviders) {
final items = await api.getAlbums(provider: provider.instanceId);
// Store with provider association
}
```
### 3. Track Item Origin
Store which provider originally added each item:
- Modify database schema to track `source_provider`
- When syncing, record which provider the item came from
- Filter based on source, not playability
### 4. Use MA's Internal Library State
MA might have internal state about which items are in which provider's library. Investigate:
- `/music/library/items` endpoint
- Provider-specific library endpoints
- MA's database schema for library associations
### 5. Check MA User Settings
The MA web UI's provider filter might be stored in user settings:
```dart
final userInfo = await api.getCurrentUserInfo();
// Check for provider_filter or similar field
```
## Testing Notes
### Log Messages to Watch
```
🔌 Selected provider for filter: spotify--xxxxx
🔍 API getArtists args: {limit: 1000, provider: spotify--xxxxx}
🔍 API getArtists returned XXX items
🔌 filterByProvider: XXX → YYY (disabled=[...])
```
### Test Scenario
1. Configure two Spotify accounts in MA
2. Add different artists to each account's library
3. In Ensemble, select only one Spotify account
4. Verify library shows ONLY that account's items
5. Switch to other account, verify different items
### Expected vs Actual
- **Expected**: Artist "Ari Mason" (only in Account A) should NOT appear when Account B is selected
- **Actual**: Artist appears regardless of which account is selected
## MA API Reference
### Get Providers
```
Command: providers
Returns: List of provider instances with type, domain, instanceId, name, available
```
### Library Items with Filter
```
Command: music/artists/library_items
Args: {
limit: int,
offset: int,
provider: string | list<string>, // Filter to specific provider(s)
album_artists_only: bool,
order_by: string
}
```
### Relevant MA Source Files
- `music_assistant/server/controllers/music.py` - Library item retrieval
- `music_assistant/server/models/provider.py` - Provider model
- `music_assistant/server/providers/` - Individual provider implementations
## Conclusion
The core challenge is that MA's `provider_mappings` indicates playability, not ownership. Server-side filtering via the `provider` parameter should work but needs further investigation to understand why it doesn't differentiate between multiple accounts of the same provider type.
The implementation is preserved in the git stash for future reference. The sorting/dropdown improvements were extracted and committed separately.
@@ -0,0 +1,271 @@
# Audiobook Provider Filtering Fix
## Date: January 17, 2026 (Continuation)
## Overview
This session focused on fixing provider filtering issues discovered after the initial provider filtering improvements:
1. Audiobooks were not responding to provider filter changes (browse API ignoring `providerInstanceIds`)
2. UI not updating instantly when toggling providers (missing `notifyListeners()` call)
3. Audiobook tabs not rebuilding on provider changes (using `context.read` instead of `Selector`)
---
## Problem Statement
After implementing capability-based provider filtering for the music library, two issues remained:
### Issue 1: Audiobooks Not Filtering During Sync
The bug report showed:
```
📊 Source tracking: 252 albums, 87 artists have provider info
📚 Total audiobooks from browse: 186
```
- Albums and artists had provider source tracking
- Audiobooks had NO provider source tracking (not listed)
- All 186 audiobooks were returned regardless of provider selection
### Issue 2: UI Not Updating Instantly
When toggling providers in the library menu:
- Music tabs weren't updating immediately
- Audiobooks required manual pull-to-refresh
- Changes only appeared after ~600ms (debounce timer)
---
## Root Cause Analysis
### Cause 1: Browse API Ignoring Provider Filter
In `lib/services/music_assistant_api.dart`, when ABS library filtering is enabled, the `getAudiobooks()` function uses the browse API but was **ignoring** the `providerInstanceIds` parameter:
```dart
// BEFORE: providerInstanceIds was ignored when using browse API
if (enabledLibraries != null && enabledLibraries.isNotEmpty) {
return await _getAudiobooksFromBrowse(enabledLibraries, favoriteOnly: favoriteOnly);
}
```
### Cause 2: `notifyListeners()` Called Too Late
In `lib/providers/music_assistant_provider.dart`, the `toggleProviderEnabled()` function only called `notifyListeners()` **inside** the 600ms debounce timer:
```dart
// BEFORE: notifyListeners only called after 600ms debounce
_providerFilterDebounceTimer = Timer(const Duration(milliseconds: 600), () {
forceLibrarySync();
notifyListeners(); // Too late! UI should update immediately
});
```
### Cause 3: Audiobook Tabs Not Listening for Changes
The audiobook tabs used `context.read<MusicAssistantProvider>()` which doesn't trigger rebuilds when the provider changes:
```dart
// BEFORE: context.read doesn't listen for changes
Widget _buildBooksAuthorsTab(BuildContext context, S l10n) {
final maProvider = context.read<MusicAssistantProvider>();
final enabledProviders = maProvider.enabledProviderIds.toSet();
// ... widget doesn't rebuild when enabledProviders changes
}
```
---
## Solutions
### Fix 1: Browse API Provider Filtering
**File:** `lib/services/music_assistant_api.dart` (lines 760-785)
Added logic to filter library paths by provider ID before browsing:
```dart
if (enabledLibraries != null && enabledLibraries.isNotEmpty) {
_logger.log('📚 getAudiobooks: enabledLibraries=$enabledLibraries, providerInstanceIds=$providerInstanceIds');
// If specific providers are requested, filter libraries to only matching providers
// Library paths start with provider ID (e.g., "audiobookshelf--abc123://lb...")
var librariesToBrowse = enabledLibraries;
if (providerInstanceIds != null && providerInstanceIds.isNotEmpty) {
librariesToBrowse = enabledLibraries.where((libPath) {
// Extract provider ID from library path (everything before "://")
final providerEnd = libPath.indexOf('://');
if (providerEnd == -1) return false;
final providerId = libPath.substring(0, providerEnd);
return providerInstanceIds.contains(providerId);
}).toList();
// If no libraries match the requested providers, return empty
if (librariesToBrowse.isEmpty) {
return [];
}
}
return await _getAudiobooksFromBrowse(librariesToBrowse, favoriteOnly: favoriteOnly);
}
```
### Fix 2: Immediate `notifyListeners()` Call
**File:** `lib/providers/music_assistant_provider.dart` (line 1149)
Moved `notifyListeners()` to fire immediately after `_enabledProviderIds` changes:
```dart
// Reload the enabled providers
final savedEnabled = await SettingsService.getEnabledMusicProviders();
_enabledProviderIds = savedEnabled ?? [];
// Notify listeners IMMEDIATELY so UI rebuilds with client-side filtering
// This enables instant UI updates using cached data with source tracking
notifyListeners();
// Cancel any pending debounce timer
_providerFilterDebounceTimer?.cancel();
// Start debounced sync - waits 600ms for user to finish toggling
// This refreshes the cache with new data from enabled providers
_providerFilterDebounceTimer = Timer(const Duration(milliseconds: 600), () {
_logger.log('🔄 Debounce complete, starting library sync...');
forceLibrarySync();
});
```
### Fix 3: Audiobook Tabs Use Selector
**File:** `lib/screens/new_library_screen.dart`
Wrapped `_buildBooksAuthorsTab` and `_buildAllBooksTab` in `Selector` to rebuild when `enabledProviderIds` changes:
```dart
Widget _buildBooksAuthorsTab(BuildContext context, S l10n) {
// Use Selector to rebuild when enabledProviderIds changes
return Selector<MusicAssistantProvider, Set<String>>(
selector: (_, provider) => provider.enabledProviderIds.toSet(),
builder: (context, enabledProviders, _) {
final syncService = SyncService.instance;
// Client-side filtering using SyncService source tracking for instant updates
var audiobooks = syncService.hasSourceTracking && enabledProviders.isNotEmpty
? syncService.getAudiobooksFilteredByProviders(enabledProviders)
: List<Audiobook>.from(_audiobooks);
// ... rest of widget
},
);
}
```
### Fix 4: Enhanced Sync Logging
**File:** `lib/services/sync_service.dart`
Added audiobook counts to logging:
```dart
// Per-provider log (line 237)
_logger.log(' 📥 Got ${albums.length} albums, ${artists.length} artists, ${audiobooks.length} audiobooks from $providerId');
// Source tracking summary (line 323)
_logger.log('📊 Source tracking: ${_albumSourceProviders.length} albums, ${_artistSourceProviders.length} artists, ${_audiobookSourceProviders.length} audiobooks have provider info');
```
---
## Data Flow After Fixes
```
┌─────────────────────────────────────────────────────────────────┐
│ User Toggles Provider │
│ │
│ 1. toggleProviderEnabled() called │
│ 2. _enabledProviderIds updated │
│ 3. notifyListeners() called IMMEDIATELY │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Selectors Detect Change │
│ │
│ Music tabs: Selector<..., (List, bool, Set<String>)> │
│ Audiobook tabs: Selector<..., Set<String>> │
│ │
│ → All tabs rebuild immediately │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Client-Side Filtering (Instant) │
│ │
│ syncService.getAlbumsFilteredByProviders(enabledProviders) │
│ syncService.getArtistsFilteredByProviders(enabledProviders) │
│ syncService.getAudiobooksFilteredByProviders(enabledProviders)│
│ │
│ → Uses EXISTING cache with source tracking │
│ → Instant UI update, no network required │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Background Sync (After 600ms Debounce) │
│ │
│ - Refreshes cache with new data from enabled providers │
│ - Updates source tracking │
│ - Only needed when ENABLING providers (to fetch new data) │
└─────────────────────────────────────────────────────────────────┘
```
---
## Files Changed
| File | Changes |
|------|---------|
| `lib/services/music_assistant_api.dart` | Added provider filtering to browse API path in `getAudiobooks()`, added debug logging |
| `lib/services/sync_service.dart` | Added audiobook counts to per-provider and summary logs |
| `lib/providers/music_assistant_provider.dart` | Moved `notifyListeners()` to fire immediately on provider toggle |
| `lib/screens/new_library_screen.dart` | Wrapped audiobook tabs in `Selector` to rebuild on provider changes |
---
## Expected Behavior After Fixes
1. **Instant UI Updates:** When you toggle a provider, the library immediately updates using client-side filtering
2. **Audiobook Source Tracking:** Audiobooks now have provider source tracking (visible in logs)
3. **Audiobook Tab Rebuilds:** Both audiobook tabs (Authors and All Books) rebuild instantly on provider toggle
4. **Music Tab Consistency:** Music tabs continue to work as before, now with immediate rebuilds
---
## Testing Checklist
- [ ] Toggle a music provider, verify instant UI update (no 600ms delay)
- [ ] Toggle between different Spotify accounts, verify correct filtering
- [ ] Sync with ABS library filtering enabled
- [ ] Verify audiobooks appear in source tracking log
- [ ] Toggle ABS provider off in library menu
- [ ] Verify audiobooks list becomes empty immediately (no pull-to-refresh needed)
- [ ] Toggle ABS provider back on
- [ ] Verify audiobooks reappear after sync completes
- [ ] Test with multiple providers (Spotify audiobooks + ABS)
---
## Related Documentation
- `docs/SESSION_2026_01_17_PROVIDER_FILTERING.md` - Initial provider filtering implementation
- `docs/PER_PROVIDER_SYNC_IMPLEMENTATION.md` - Per-provider sync architecture
---
## Known Limitations
1. **Series Tab:** The Series tab still doesn't filter by provider. Series are fetched as `AudiobookSeries` objects without per-provider tracking.
2. **Mixed Provider Scenario:** If user has both Spotify audiobooks and ABS audiobooks, and ABS library filtering is enabled, Spotify audiobooks may not be fetched because the browse API path is taken. This is a pre-existing architectural limitation.
3. **Enabling Providers:** When ENABLING a previously disabled provider, the UI updates immediately but shows empty until the background sync completes (because the cache doesn't have that provider's data yet). This is expected behavior.
@@ -0,0 +1,217 @@
# Session 2026-01-17: Optimistic Updates & Podcast Provider Filtering
## Overview
This session focused on fixing provider filtering for podcasts, resolving iTunes podcast provider issues, and implementing optimistic updates for library buttons across detail screens.
## Issues Addressed
### 1. Podcast Provider Counts Showing Incorrectly
**Problem**: All Spotify accounts showed the same podcast count instead of only counting podcasts owned by each account.
**Root Cause**: The podcast counting logic wasn't checking the `inLibrary` field on provider mappings.
**Solution**:
- Added `inLibrary` field to `ProviderMapping` model
- Updated `getProvidersWithPodcasts()` to only count mappings where `inLibrary == true`
- Updated podcast filtering in library screen to check `inLibrary` field
**Files Modified**:
- `lib/models/media_item.dart` - Added `inLibrary` field
- `lib/providers/music_assistant_provider.dart` - Updated counting logic
- `lib/screens/new_library_screen.dart` - Updated filtering logic
### 2. iTunes Podcasts Not Appearing in Library
**Problem**: Podcasts added from iTunes search weren't showing in library and iTunes provider filter showed 0 count.
**Investigation**:
- Added `itunes_podcasts` to provider capabilities and music provider domains
- Added synthetic provider instance creation for search-only providers
- Added debug logging to understand podcast loading
**Resolution**: The issue was with Music Assistant's iTunes podcast provider itself - podcasts added via iTunes weren't being properly stored in the MA library. The user removed the iTunes provider from MA and re-added podcasts via Spotify search as a workaround.
**Files Modified**:
- `lib/models/provider_instance.dart` - Added `itunes_podcasts` to capabilities
### 3. Episode Loading Failing for Non-Library Podcasts
**Problem**: When a podcast was removed from library, the old library ID became invalid and episodes wouldn't load.
**Solution**: Added fallback logic to try loading episodes via provider mappings when the primary ID fails.
**Files Modified**:
- `lib/screens/podcast_detail_screen.dart` - Added fallback episode loading
### 4. Search Filtering Rework
**Problem**: Server-side provider filtering was being applied to search results when it should only apply when the "in library" toggle is enabled.
**Solution**:
- Removed `filterSearchResults()` calls from search methods
- Added client-side `_filterByEnabledProviders()` helper
- Applied filtering only when `_libraryOnly` toggle is ON
**Files Modified**:
- `lib/providers/music_assistant_provider.dart` - Removed filterSearchResults calls
- `lib/screens/search_screen.dart` - Added client-side filtering
### 5. Library Buttons Not Updating Immediately
**Problem**: Add/remove library buttons on detail screens waited for API response before updating, causing perceived lag.
**Solution**: Implemented optimistic updates - update UI immediately, revert on failure.
**Files Modified**:
- `lib/screens/podcast_detail_screen.dart`
- `lib/screens/album_details_screen.dart`
- `lib/screens/artist_details_screen.dart`
## Code Changes
### ProviderMapping.inLibrary Field
```dart
// lib/models/media_item.dart
class ProviderMapping {
final String itemId;
final String providerDomain;
final String providerInstance;
final bool available;
final Map<String, dynamic>? audioFormat;
final bool inLibrary; // NEW: indicates ownership
factory ProviderMapping.fromJson(Map<String, dynamic> json) {
return ProviderMapping(
// ... other fields ...
inLibrary: json['in_library'] == true || json['in_library'] == 1,
);
}
}
```
### Podcast Provider Counting
```dart
// lib/providers/music_assistant_provider.dart
Map<String, int> getProvidersWithPodcasts() {
final counts = <String, int>{};
for (final item in _podcasts) {
final mappings = item.providerMappings;
if (mappings != null) {
for (final mapping in mappings) {
// Only count if this provider "owns" the item
if (mapping.inLibrary) {
final instanceId = mapping.providerInstance;
if (instanceId.isNotEmpty) {
counts[instanceId] = (counts[instanceId] ?? 0) + 1;
}
}
}
}
}
return counts;
}
```
### Optimistic Update Pattern
```dart
// Example from podcast_detail_screen.dart
Future<void> _toggleLibrary() async {
final newState = !_isInLibrary;
// OPTIMISTIC UPDATE: Update UI immediately
setState(() {
_isInLibrary = newState;
});
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(S.of(context)!.addedToLibrary)),
);
}
// Fire and forget - API call happens in background
maProvider.addToLibrary(...).catchError((e) {
// Revert on failure
if (mounted) {
setState(() {
_isInLibrary = !newState;
});
}
});
}
```
### Client-Side Search Filtering
```dart
// lib/screens/search_screen.dart
Map<String, List<MediaItem>> _filterByEnabledProviders(
Map<String, List<MediaItem>> results,
Set<String> enabledProviders,
) {
if (enabledProviders.isEmpty) return results;
bool isItemAllowed(MediaItem item) {
final mappings = item.providerMappings;
if (mappings == null || mappings.isEmpty) return true;
return mappings.any((m) => m.inLibrary && enabledProviders.contains(m.providerInstance));
}
return {
for (final entry in results.entries)
entry.key: entry.value.where(isItemAllowed).toList(),
};
}
// Applied when setting results:
if (_libraryOnly) {
final enabledProviders = provider.enabledProviderIds.toSet();
combinedResults = _filterByEnabledProviders(combinedResults, enabledProviders);
}
```
## Provider Capabilities Update
```dart
// lib/models/provider_instance.dart
static const Map<String, Set<String>> providerCapabilities = {
'spotify': {'artists', 'albums', 'tracks', 'playlists', 'audiobooks', 'podcasts'},
'ytmusic': {'artists', 'albums', 'tracks', 'playlists', 'podcasts'},
'apple_music': {'artists', 'albums', 'tracks', 'playlists', 'podcasts'},
'plex': {'artists', 'albums', 'tracks', 'playlists', 'audiobooks', 'podcasts'},
'jellyfin': {'artists', 'albums', 'tracks', 'playlists', 'audiobooks', 'podcasts'},
'emby': {'artists', 'albums', 'tracks', 'playlists', 'audiobooks', 'podcasts'},
'audiobookshelf': {'audiobooks', 'podcasts'},
'itunes_podcasts': {'podcasts'}, // NEW
'tunein': {'radio', 'podcasts'},
// ... other providers
};
```
## Summary of All Modified Files
| File | Changes |
|------|---------|
| `lib/models/media_item.dart` | Added `inLibrary` field to ProviderMapping |
| `lib/models/provider_instance.dart` | Added `itunes_podcasts`, podcasts to capabilities |
| `lib/providers/music_assistant_provider.dart` | Updated podcast counting, removed filterSearchResults |
| `lib/screens/new_library_screen.dart` | Updated podcast filtering with inLibrary check |
| `lib/screens/search_screen.dart` | Added client-side filtering for in-library mode |
| `lib/screens/podcast_detail_screen.dart` | Optimistic updates, fallback episode loading |
| `lib/screens/album_details_screen.dart` | Optimistic updates for library button |
| `lib/screens/artist_details_screen.dart` | Optimistic updates for library button |
## Key Learnings
1. **inLibrary field**: Music Assistant's provider mappings include an `in_library` field that indicates whether the user added the item from that specific provider account. This is essential for accurate per-provider filtering.
2. **iTunes podcast provider**: The MA iTunes podcast provider is for search only - it doesn't properly store items in the library. Users should add podcasts from streaming providers like Spotify instead.
3. **Optimistic updates**: For better UX, library toggle buttons should update immediately and only revert if the API call fails, rather than waiting for API response.
4. **Search vs Library filtering**: Server-side provider filtering should only apply to library views, not search results (unless the "in library" toggle is enabled).
@@ -0,0 +1,263 @@
# Provider Filtering Improvements
## Date: January 17, 2026
## Overview
This session focused on improving the provider filtering system across the app, building on the per-provider sync implementation. Key improvements include a cleaner capability-based architecture, fixing filter visibility bugs, and extending filtering to the audiobooks library.
---
## Changes Made
### 1. Provider Capability Mapping
**File:** `lib/models/provider_instance.dart`
Replaced the clunky item-count-based filtering with a static capability map that defines what content types each provider domain supports.
```dart
static const Map<String, Set<String>> providerCapabilities = {
// Music streaming services
'spotify': {'artists', 'albums', 'tracks', 'playlists', 'audiobooks'},
'tidal': {'artists', 'albums', 'tracks', 'playlists'},
'qobuz': {'artists', 'albums', 'tracks', 'playlists'},
'deezer': {'artists', 'albums', 'tracks', 'playlists'},
'ytmusic': {'artists', 'albums', 'tracks', 'playlists'},
'soundcloud': {'artists', 'albums', 'tracks', 'playlists'},
'apple_music': {'artists', 'albums', 'tracks', 'playlists'},
'amazon_music': {'artists', 'albums', 'tracks', 'playlists'},
// Self-hosted media servers (can have music and audiobooks)
'plex': {'artists', 'albums', 'tracks', 'playlists', 'audiobooks'},
'jellyfin': {'artists', 'albums', 'tracks', 'playlists', 'audiobooks'},
'emby': {'artists', 'albums', 'tracks', 'playlists', 'audiobooks'},
// Music-only servers
'subsonic': {'artists', 'albums', 'tracks', 'playlists'},
'opensubsonic': {'artists', 'albums', 'tracks', 'playlists'},
'navidrome': {'artists', 'albums', 'tracks', 'playlists'},
'filesystem': {'artists', 'albums', 'tracks', 'playlists'},
// Audiobook-only providers
'audiobookshelf': {'audiobooks'},
// Radio providers
'tunein': {'radio'},
'radiobrowser': {'radio'},
// Player/system providers (no library content)
'snapcast': <String>{},
'fully_kiosk': <String>{},
};
```
**Added helper methods:**
```dart
Set<String> get supportedContentTypes => providerCapabilities[domain] ?? <String>{};
bool supportsContentType(String category) => supportedContentTypes.contains(category);
```
**Benefits:**
- Radio providers never show in Artists tab (by design, not by count)
- Works immediately, even with empty libraries
- Disabled providers still show in menu (if they support the content type)
- Clean separation of concerns
---
### 2. Updated Provider Filtering in MusicAssistantProvider
**File:** `lib/providers/music_assistant_provider.dart`
Updated `getRelevantProvidersForCategory()` to filter by capability:
```dart
List<(ProviderInstance, int)> getRelevantProvidersForCategory(String category) {
// ... get counts ...
final result = <(ProviderInstance, int)>[];
for (final provider in _availableMusicProviders) {
// Only include providers that support this content type
if (provider.supportsContentType(category)) {
final count = counts[provider.instanceId] ?? 0;
result.add((provider, count));
}
}
// ...
}
```
---
### 3. Simplified Library Menu Provider Filter
**File:** `lib/screens/new_library_screen.dart`
Simplified the options menu overlay to show all providers that support the current category:
**Before (clunky):**
```dart
if (widget.relevantProviders.where((p) {
final hasItems = p.$2 > 0;
final isDisabledByUser = widget.enabledProviderIds.isNotEmpty &&
!widget.enabledProviderIds.contains(p.$1.instanceId);
return hasItems || isDisabledByUser;
}).length > 1) ...[
```
**After (clean):**
```dart
// relevantProviders is pre-filtered by capability
if (widget.relevantProviders.length > 1) ...[
// Show all providers that support this category
...widget.relevantProviders.map((providerData) {
```
---
### 4. Removed Provider Toggles from Settings Screen
**File:** `lib/screens/settings_screen.dart`
Removed the "Music Providers" section entirely since provider filtering is now handled in the library menu:
- Removed `_providerEnabled` state variable
- Removed provider loading code from `_loadSettings()`
- Removed the entire Music Providers UI section (~100 lines)
**Rationale:** Single source of truth - provider toggles now only appear in the library menu where they're contextually relevant.
---
### 5. Fixed Audiobooks Library Provider Filtering
**File:** `lib/screens/new_library_screen.dart`
The audiobooks tabs were not filtering by provider - they loaded data once and displayed it without responding to provider changes.
**Fixed `_buildBooksAuthorsTab()`:**
```dart
final syncService = SyncService.instance;
final enabledProviders = maProvider.enabledProviderIds.toSet();
// Client-side filtering using SyncService source tracking
var audiobooks = syncService.hasSourceTracking && enabledProviders.isNotEmpty
? syncService.getAudiobooksFilteredByProviders(enabledProviders)
: List<Audiobook>.from(_audiobooks);
// Filter by favorites if enabled
if (_showFavoritesOnly) {
audiobooks = audiobooks.where((a) => a.favorite == true).toList();
}
// Group filtered audiobooks by author (dynamic, not cached)
final groupedByAuthor = <String, List<Audiobook>>{};
for (final book in audiobooks) {
final authorName = book.authorsString;
groupedByAuthor.putIfAbsent(authorName, () => []).add(book);
}
```
**Fixed `_buildAllBooksTab()`:**
- Same provider filtering pattern
- Dynamic sorting after filtering
- Updated PageStorageKey to include provider count for proper rebuild
---
## Bug Fixes
### Provider Filter Menu Disappearing
**Problem:** When providers were deselected, the background sync would clear the cache and only fetch data for enabled providers. Disabled providers then had 0 items, and the menu required `> 1 providers WITH items` to show. The entire Providers section would disappear.
**Solution:** Changed to capability-based filtering. The menu now shows all providers that support the category, regardless of item count.
### Audiobooks Not Filtering by Provider
**Problem:** Audiobooks tabs loaded data once into `_audiobooks` and displayed it without provider filtering. Toggling providers in the menu had no effect.
**Solution:** Added inline provider filtering during build (same pattern as music tabs).
---
## Files Changed
| File | Changes |
|------|---------|
| `lib/models/provider_instance.dart` | Added `providerCapabilities` map and helper methods |
| `lib/providers/music_assistant_provider.dart` | Updated `getRelevantProvidersForCategory()` to filter by capability |
| `lib/screens/new_library_screen.dart` | Simplified menu filter logic, added audiobook provider filtering |
| `lib/screens/settings_screen.dart` | Removed Music Providers section |
---
## Architecture
```
┌─────────────────────────────────────────────────────────────────┐
│ Provider Capability Map │
│ (ProviderInstance.providerCapabilities) │
│ │
│ spotify → {artists, albums, tracks, playlists, audiobooks} │
│ audiobookshelf → {audiobooks} │
│ tunein → {radio} │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ getRelevantProvidersForCategory(category) │
│ │
│ - Filters _availableMusicProviders by capability │
│ - Returns only providers that support the category │
│ - Includes item counts for display │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Library Menu (Options) │
│ │
│ - Shows providers section if > 1 providers support category │
│ - All relevant providers shown (can toggle on/off) │
│ - Instant UI update via setState() │
│ - Background sync after 1.5s debounce │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Tab Build Methods │
│ │
│ - Get enabledProviderIds from MusicAssistantProvider │
│ - Filter data using SyncService source tracking │
│ - Display filtered results │
└─────────────────────────────────────────────────────────────────┘
```
---
## Known Limitations
1. **Series Tab:** The Series tab in audiobooks doesn't filter by provider yet. Series are fetched separately as `AudiobookSeries` objects and don't have the same source tracking as individual audiobooks.
2. **First Sync Required:** Source tracking only works after at least one sync with providers enabled.
---
## Testing Checklist
- [x] Music tabs filter by provider correctly
- [x] Provider menu shows only relevant providers per category
- [x] Radio providers don't appear in Artists/Albums tabs
- [x] Spotify appears in Audiobooks tab (has audiobooks)
- [x] Audiobooks Authors tab filters by provider
- [x] Audiobooks All Books tab filters by provider
- [ ] Audiobooks Series tab filters by provider (not implemented)
- [x] Disabled providers can be re-enabled from menu
- [x] Settings screen no longer has provider toggles
---
## Related Documentation
- `docs/PER_PROVIDER_SYNC_IMPLEMENTATION.md` - Original per-provider sync implementation
+221
View File
@@ -0,0 +1,221 @@
# Feature: Replace "Play On" Popups with Player Selector
## Overview
Replace the `PlayerPickerSheet` popup modal with the existing Player Selector (reveal overlay) when users tap "Play on" buttons throughout the app. This provides a consistent, richer player selection experience.
## Current State
### PlayerPickerSheet Popup
Used in 7+ places:
- `album_details_screen.dart` - Play Album, Play From Here, Play Radio
- `playlist_details_screen.dart` - Play Playlist, Play Radio
- `search_screen.dart` - Play album/playlist/audiobook/radio from search
- `podcast_detail_screen.dart` - Play Episode
- `audiobook_detail_screen.dart` - Play Audiobook
- `queue_screen.dart` - Transfer Queue (special case - keep popup)
### Player Selector (Reveal Overlay)
- Location: `lib/widgets/player/player_reveal_overlay.dart`
- Shows vertical list of all players with artwork, current track, sync status
- Has hints above player list: "Long-press to sync" & "Swipe to adjust volume"
- Triggered by pull-down gesture or device button tap
## Proposed Changes
### 1. Modify PlayerRevealOverlay
**File:** `lib/widgets/player/player_reveal_overlay.dart`
Add new optional parameters:
```dart
class PlayerRevealOverlay extends StatefulWidget {
final VoidCallback onDismiss;
final double miniPlayerBottom;
final double miniPlayerHeight;
final bool showOnboardingHints;
// NEW: Callback when player is selected for a pending action
final void Function(Player player)? onPlayerSelected;
// NEW: Context hint to display instead of default hints
// e.g., "Select player to play album"
final String? contextHint;
// NEW: Icon for context hint (default: speaker icon)
final IconData? contextHintIcon;
```
### 2. Modify Hint Display
**File:** `lib/widgets/player/player_reveal_overlay.dart` (around line 386-394)
```dart
// Current:
: 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),
],
),
// New:
: widget.contextHint != null
? buildHintRow(
widget.contextHintIcon ?? Icons.play_circle_outline,
widget.contextHint!,
)
: 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),
],
),
```
### 3. Modify Player Card onTap
**File:** `lib/widgets/player/player_reveal_overlay.dart` (around line 437-441 and 490-494)
```dart
// Current:
onTap: () {
HapticFeedback.mediumImpact();
maProvider.selectPlayer(data.player);
dismiss();
},
// New:
onTap: () {
HapticFeedback.mediumImpact();
if (widget.onPlayerSelected != null) {
// Execute the pending action with selected player
widget.onPlayerSelected!(data.player);
} else {
// Default behavior: just select the player
maProvider.selectPlayer(data.player);
}
dismiss();
},
```
### 4. Add Helper Method to GlobalPlayerOverlay
**File:** `lib/widgets/global_player_overlay.dart`
Add a static method to show player selector with pending action:
```dart
/// Show player selector for a "Play on" action
///
/// [contextHint] - Message shown instead of default hints
/// [onPlayerSelected] - Called when user taps a player
///
/// Example:
/// ```dart
/// GlobalPlayerOverlay.showPlayerSelectorForAction(
/// contextHint: "Select player to play album",
/// onPlayerSelected: (player) {
/// provider.playAlbum(albumId, playerId: player.playerId);
/// },
/// );
/// ```
static void showPlayerSelectorForAction({
required String contextHint,
required void Function(Player player) onPlayerSelected,
IconData? hintIcon,
}) {
// Implementation: trigger the player reveal overlay with these parameters
// May need to store pending action in state and pass to overlay
}
```
### 5. Update Calling Sites
Replace `showPlayerPickerSheet()` calls with new method:
**Example - album_details_screen.dart:**
```dart
// Current (around line 1305-1316):
showPlayerPickerSheet(
context: context,
title: 'Play Album',
onPlayerSelected: (player) async {
GlobalPlayerOverlay.hidePlayer();
await maProvider.playAlbum(albumId, playerId: player.playerId);
GlobalPlayerOverlay.showPlayer();
},
);
// New:
GlobalPlayerOverlay.showPlayerSelectorForAction(
contextHint: S.of(context)!.selectPlayerToPlayAlbum, // Add localization
onPlayerSelected: (player) async {
await maProvider.playAlbum(albumId, playerId: player.playerId);
},
);
```
### 6. Add Localizations
**File:** `lib/l10n/app_en.arb` (and other language files)
```json
"selectPlayerToPlay": "Select player to play",
"selectPlayerToPlayAlbum": "Select player to play album",
"selectPlayerToPlayPlaylist": "Select player to play playlist",
"selectPlayerToPlayRadio": "Select player to start radio",
"selectPlayerToPlayEpisode": "Select player to play episode",
"selectPlayerToPlayAudiobook": "Select player to play audiobook"
```
## Files to Modify
1. `lib/widgets/player/player_reveal_overlay.dart` - Add parameters, modify hints & onTap
2. `lib/widgets/global_player_overlay.dart` - Add helper method
3. `lib/screens/album_details_screen.dart` - Replace 3 popup calls
4. `lib/screens/playlist_details_screen.dart` - Replace 2 popup calls
5. `lib/screens/search_screen.dart` - Replace ~5 popup calls
6. `lib/screens/podcast_detail_screen.dart` - Replace 1 popup call
7. `lib/screens/audiobook_detail_screen.dart` - Replace 1 popup call
8. `lib/l10n/app_en.arb` - Add new strings
9. `lib/l10n/app_de.arb`, `app_fr.arb`, `app_es.arb` - Translations
## Exception: Queue Transfer
**Keep the popup for `queue_screen.dart`** because:
- Needs to filter out current player (can't transfer to self)
- Needs to filter out certain player types
- Different UX intent (transfer vs play)
## Implementation Order
1. Modify `PlayerRevealOverlay` to accept new parameters
2. Add helper method to `GlobalPlayerOverlay`
3. Test with one screen (album_details_screen.dart)
4. Add localizations
5. Migrate remaining screens
6. Clean up unused code from PlayerPickerSheet if no longer needed elsewhere
## Testing Checklist
- [ ] Album details: Play Album button
- [ ] Album details: Play From Here (track context menu)
- [ ] Album details: Play Radio (track context menu)
- [ ] Playlist details: Play Playlist button
- [ ] Playlist details: Play Radio (track context menu)
- [ ] Search: Play album from results
- [ ] Search: Play playlist from results
- [ ] Search: Play radio from results
- [ ] Podcast detail: Play episode
- [ ] Audiobook detail: Play audiobook
- [ ] Queue transfer still works with popup
- [ ] Long-press to sync still works in player selector
- [ ] Dismiss by tapping backdrop works
- [ ] Dismiss by swiping down works
Binary file not shown.
+3
View File
@@ -10,4 +10,7 @@ class NetworkConstants {
/// Default HTTP port
static const int defaultHttpPort = 80;
/// Maximum number of pending WebSocket requests to prevent memory leaks
static const int maxPendingRequests = 100;
}
+115 -8
View File
@@ -78,6 +78,10 @@ class LibraryCache extends Table {
/// Whether this item was deleted on the server
BoolColumn get isDeleted => boolean().withDefault(const Constant(false))();
/// Provider instance IDs that provided this item (JSON array)
/// Used for client-side filtering by source provider
TextColumn get sourceProviders => text().withDefault(const Constant('[]'))();
@override
Set<Column> get primaryKey => {cacheKey};
}
@@ -191,7 +195,7 @@ class AppDatabase extends _$AppDatabase {
AppDatabase([QueryExecutor? executor]) : super(executor ?? _openConnection());
@override
int get schemaVersion => 5;
int get schemaVersion => 6;
@override
MigrationStrategy get migration {
@@ -226,6 +230,10 @@ class AppDatabase extends _$AppDatabase {
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)');
}
// Migration from v5 to v6: Add source_providers column for client-side filtering
if (from < 6) {
await customStatement("ALTER TABLE library_cache ADD COLUMN source_providers TEXT NOT NULL DEFAULT '[]'");
}
},
);
}
@@ -368,20 +376,57 @@ class AppDatabase extends _$AppDatabase {
// ============================================
/// Cache a library item
/// [sourceProvider] - the provider instance ID that provided this item (for filtering)
Future<void> cacheItem({
required String itemType,
required String itemId,
required String data,
String? sourceProvider,
}) async {
final cacheKey = '${itemType}_$itemId';
await into(libraryCache).insertOnConflictUpdate(LibraryCacheCompanion.insert(
cacheKey: cacheKey,
itemType: itemType,
itemId: itemId,
data: data,
lastSynced: DateTime.now(),
));
// If sourceProvider is specified, we need to merge with existing providers
if (sourceProvider != null) {
final existing = await getCachedItem(itemType, itemId);
List<String> providers = [];
if (existing != null) {
try {
final existingProviders = existing.sourceProviders;
if (existingProviders.isNotEmpty && existingProviders != '[]') {
providers = List<String>.from(
(await Future.value(existingProviders))
.replaceAll('[', '')
.replaceAll(']', '')
.replaceAll('"', '')
.split(',')
.where((s) => s.trim().isNotEmpty)
.map((s) => s.trim()),
);
}
} catch (_) {}
}
if (!providers.contains(sourceProvider)) {
providers.add(sourceProvider);
}
final sourceProvidersJson = '[${providers.map((p) => '"$p"').join(',')}]';
await into(libraryCache).insertOnConflictUpdate(LibraryCacheCompanion.insert(
cacheKey: cacheKey,
itemType: itemType,
itemId: itemId,
data: data,
lastSynced: DateTime.now(),
sourceProviders: Value(sourceProvidersJson),
));
} else {
await into(libraryCache).insertOnConflictUpdate(LibraryCacheCompanion.insert(
cacheKey: cacheKey,
itemType: itemType,
itemId: itemId,
data: data,
lastSynced: DateTime.now(),
));
}
}
/// Get cached items by type
@@ -650,4 +695,66 @@ class AppDatabase extends _$AppDatabase {
Future<void> clearSearchHistory() async {
await delete(searchHistory).go();
}
// ============================================
// Batch Cache Operations
// ============================================
/// Batch size for chunked inserts to prevent SQLite limits
static const int _batchChunkSize = 500;
/// Batch cache multiple items efficiently using drift batch API
/// This is much faster than individual inserts for large datasets.
/// Items are chunked into batches of 500 to prevent SQLite variable limits.
///
/// [items] - List of items to cache, each containing:
/// - itemType: 'album', 'artist', 'track', 'playlist', 'audiobook', etc.
/// - itemId: the item's ID
/// - data: JSON string of the item
/// - sourceProviders: list of provider instance IDs
Future<void> batchCacheItems(List<BatchCacheItem> items) async {
if (items.isEmpty) return;
// Process in chunks to avoid SQLite variable limits
for (var i = 0; i < items.length; i += _batchChunkSize) {
final chunk = items.skip(i).take(_batchChunkSize).toList();
await batch((b) {
for (final item in chunk) {
final cacheKey = '${item.itemType}_${item.itemId}';
final sourceProvidersJson = item.sourceProviders.isEmpty
? '[]'
: '[${item.sourceProviders.map((p) => '"$p"').join(',')}]';
b.insert(
libraryCache,
LibraryCacheCompanion.insert(
cacheKey: cacheKey,
itemType: item.itemType,
itemId: item.itemId,
data: item.data,
lastSynced: DateTime.now(),
sourceProviders: Value(sourceProvidersJson),
),
mode: InsertMode.insertOrReplace,
);
}
});
}
}
}
/// Data class for batch cache operations
class BatchCacheItem {
final String itemType;
final String itemId;
final String data;
final List<String> sourceProviders;
const BatchCacheItem({
required this.itemType,
required this.itemId,
required this.data,
this.sourceProviders = const [],
});
}
+75 -8
View File
@@ -856,9 +856,24 @@ class $LibraryCacheTable extends LibraryCache
defaultConstraints:
GeneratedColumn.constraintIsAlways('CHECK ("is_deleted" IN (0, 1))'),
defaultValue: const Constant(false));
static const VerificationMeta _sourceProvidersMeta =
const VerificationMeta('sourceProviders');
@override
List<GeneratedColumn> get $columns =>
[cacheKey, itemType, itemId, data, lastSynced, isDeleted];
late final GeneratedColumn<String> sourceProviders = GeneratedColumn<String>(
'source_providers', aliasedName, false,
type: DriftSqlType.string,
requiredDuringInsert: false,
defaultValue: const Constant('[]'));
@override
List<GeneratedColumn> get $columns => [
cacheKey,
itemType,
itemId,
data,
lastSynced,
isDeleted,
sourceProviders
];
@override
String get aliasedName => _alias ?? actualTableName;
@override
@@ -905,6 +920,12 @@ class $LibraryCacheTable extends LibraryCache
context.handle(_isDeletedMeta,
isDeleted.isAcceptableOrUnknown(data['is_deleted']!, _isDeletedMeta));
}
if (data.containsKey('source_providers')) {
context.handle(
_sourceProvidersMeta,
sourceProviders.isAcceptableOrUnknown(
data['source_providers']!, _sourceProvidersMeta));
}
return context;
}
@@ -926,6 +947,8 @@ class $LibraryCacheTable extends LibraryCache
.read(DriftSqlType.dateTime, data['${effectivePrefix}last_synced'])!,
isDeleted: attachedDatabase.typeMapping
.read(DriftSqlType.bool, data['${effectivePrefix}is_deleted'])!,
sourceProviders: attachedDatabase.typeMapping.read(
DriftSqlType.string, data['${effectivePrefix}source_providers'])!,
);
}
@@ -954,13 +977,18 @@ class LibraryCacheData extends DataClass
/// Whether this item was deleted on the server
final bool isDeleted;
/// Provider instance IDs that provided this item (JSON array)
/// Used for client-side filtering by source provider
final String sourceProviders;
const LibraryCacheData(
{required this.cacheKey,
required this.itemType,
required this.itemId,
required this.data,
required this.lastSynced,
required this.isDeleted});
required this.isDeleted,
required this.sourceProviders});
@override
Map<String, Expression> toColumns(bool nullToAbsent) {
final map = <String, Expression>{};
@@ -970,6 +998,7 @@ class LibraryCacheData extends DataClass
map['data'] = Variable<String>(data);
map['last_synced'] = Variable<DateTime>(lastSynced);
map['is_deleted'] = Variable<bool>(isDeleted);
map['source_providers'] = Variable<String>(sourceProviders);
return map;
}
@@ -981,6 +1010,7 @@ class LibraryCacheData extends DataClass
data: Value(data),
lastSynced: Value(lastSynced),
isDeleted: Value(isDeleted),
sourceProviders: Value(sourceProviders),
);
}
@@ -994,6 +1024,7 @@ class LibraryCacheData extends DataClass
data: serializer.fromJson<String>(json['data']),
lastSynced: serializer.fromJson<DateTime>(json['lastSynced']),
isDeleted: serializer.fromJson<bool>(json['isDeleted']),
sourceProviders: serializer.fromJson<String>(json['sourceProviders']),
);
}
@override
@@ -1006,6 +1037,7 @@ class LibraryCacheData extends DataClass
'data': serializer.toJson<String>(data),
'lastSynced': serializer.toJson<DateTime>(lastSynced),
'isDeleted': serializer.toJson<bool>(isDeleted),
'sourceProviders': serializer.toJson<String>(sourceProviders),
};
}
@@ -1015,7 +1047,8 @@ class LibraryCacheData extends DataClass
String? itemId,
String? data,
DateTime? lastSynced,
bool? isDeleted}) =>
bool? isDeleted,
String? sourceProviders}) =>
LibraryCacheData(
cacheKey: cacheKey ?? this.cacheKey,
itemType: itemType ?? this.itemType,
@@ -1023,6 +1056,7 @@ class LibraryCacheData extends DataClass
data: data ?? this.data,
lastSynced: lastSynced ?? this.lastSynced,
isDeleted: isDeleted ?? this.isDeleted,
sourceProviders: sourceProviders ?? this.sourceProviders,
);
LibraryCacheData copyWithCompanion(LibraryCacheCompanion data) {
return LibraryCacheData(
@@ -1033,6 +1067,9 @@ class LibraryCacheData extends DataClass
lastSynced:
data.lastSynced.present ? data.lastSynced.value : this.lastSynced,
isDeleted: data.isDeleted.present ? data.isDeleted.value : this.isDeleted,
sourceProviders: data.sourceProviders.present
? data.sourceProviders.value
: this.sourceProviders,
);
}
@@ -1044,14 +1081,15 @@ class LibraryCacheData extends DataClass
..write('itemId: $itemId, ')
..write('data: $data, ')
..write('lastSynced: $lastSynced, ')
..write('isDeleted: $isDeleted')
..write('isDeleted: $isDeleted, ')
..write('sourceProviders: $sourceProviders')
..write(')'))
.toString();
}
@override
int get hashCode =>
Object.hash(cacheKey, itemType, itemId, data, lastSynced, isDeleted);
int get hashCode => Object.hash(
cacheKey, itemType, itemId, data, lastSynced, isDeleted, sourceProviders);
@override
bool operator ==(Object other) =>
identical(this, other) ||
@@ -1061,7 +1099,8 @@ class LibraryCacheData extends DataClass
other.itemId == this.itemId &&
other.data == this.data &&
other.lastSynced == this.lastSynced &&
other.isDeleted == this.isDeleted);
other.isDeleted == this.isDeleted &&
other.sourceProviders == this.sourceProviders);
}
class LibraryCacheCompanion extends UpdateCompanion<LibraryCacheData> {
@@ -1071,6 +1110,7 @@ class LibraryCacheCompanion extends UpdateCompanion<LibraryCacheData> {
final Value<String> data;
final Value<DateTime> lastSynced;
final Value<bool> isDeleted;
final Value<String> sourceProviders;
final Value<int> rowid;
const LibraryCacheCompanion({
this.cacheKey = const Value.absent(),
@@ -1079,6 +1119,7 @@ class LibraryCacheCompanion extends UpdateCompanion<LibraryCacheData> {
this.data = const Value.absent(),
this.lastSynced = const Value.absent(),
this.isDeleted = const Value.absent(),
this.sourceProviders = const Value.absent(),
this.rowid = const Value.absent(),
});
LibraryCacheCompanion.insert({
@@ -1088,6 +1129,7 @@ class LibraryCacheCompanion extends UpdateCompanion<LibraryCacheData> {
required String data,
required DateTime lastSynced,
this.isDeleted = const Value.absent(),
this.sourceProviders = const Value.absent(),
this.rowid = const Value.absent(),
}) : cacheKey = Value(cacheKey),
itemType = Value(itemType),
@@ -1101,6 +1143,7 @@ class LibraryCacheCompanion extends UpdateCompanion<LibraryCacheData> {
Expression<String>? data,
Expression<DateTime>? lastSynced,
Expression<bool>? isDeleted,
Expression<String>? sourceProviders,
Expression<int>? rowid,
}) {
return RawValuesInsertable({
@@ -1110,6 +1153,7 @@ class LibraryCacheCompanion extends UpdateCompanion<LibraryCacheData> {
if (data != null) 'data': data,
if (lastSynced != null) 'last_synced': lastSynced,
if (isDeleted != null) 'is_deleted': isDeleted,
if (sourceProviders != null) 'source_providers': sourceProviders,
if (rowid != null) 'rowid': rowid,
});
}
@@ -1121,6 +1165,7 @@ class LibraryCacheCompanion extends UpdateCompanion<LibraryCacheData> {
Value<String>? data,
Value<DateTime>? lastSynced,
Value<bool>? isDeleted,
Value<String>? sourceProviders,
Value<int>? rowid}) {
return LibraryCacheCompanion(
cacheKey: cacheKey ?? this.cacheKey,
@@ -1129,6 +1174,7 @@ class LibraryCacheCompanion extends UpdateCompanion<LibraryCacheData> {
data: data ?? this.data,
lastSynced: lastSynced ?? this.lastSynced,
isDeleted: isDeleted ?? this.isDeleted,
sourceProviders: sourceProviders ?? this.sourceProviders,
rowid: rowid ?? this.rowid,
);
}
@@ -1154,6 +1200,9 @@ class LibraryCacheCompanion extends UpdateCompanion<LibraryCacheData> {
if (isDeleted.present) {
map['is_deleted'] = Variable<bool>(isDeleted.value);
}
if (sourceProviders.present) {
map['source_providers'] = Variable<String>(sourceProviders.value);
}
if (rowid.present) {
map['rowid'] = Variable<int>(rowid.value);
}
@@ -1169,6 +1218,7 @@ class LibraryCacheCompanion extends UpdateCompanion<LibraryCacheData> {
..write('data: $data, ')
..write('lastSynced: $lastSynced, ')
..write('isDeleted: $isDeleted, ')
..write('sourceProviders: $sourceProviders, ')
..write('rowid: $rowid')
..write(')'))
.toString();
@@ -3507,6 +3557,7 @@ typedef $$LibraryCacheTableCreateCompanionBuilder = LibraryCacheCompanion
required String data,
required DateTime lastSynced,
Value<bool> isDeleted,
Value<String> sourceProviders,
Value<int> rowid,
});
typedef $$LibraryCacheTableUpdateCompanionBuilder = LibraryCacheCompanion
@@ -3517,6 +3568,7 @@ typedef $$LibraryCacheTableUpdateCompanionBuilder = LibraryCacheCompanion
Value<String> data,
Value<DateTime> lastSynced,
Value<bool> isDeleted,
Value<String> sourceProviders,
Value<int> rowid,
});
@@ -3546,6 +3598,10 @@ class $$LibraryCacheTableFilterComposer
ColumnFilters<bool> get isDeleted => $composableBuilder(
column: $table.isDeleted, builder: (column) => ColumnFilters(column));
ColumnFilters<String> get sourceProviders => $composableBuilder(
column: $table.sourceProviders,
builder: (column) => ColumnFilters(column));
}
class $$LibraryCacheTableOrderingComposer
@@ -3574,6 +3630,10 @@ class $$LibraryCacheTableOrderingComposer
ColumnOrderings<bool> get isDeleted => $composableBuilder(
column: $table.isDeleted, builder: (column) => ColumnOrderings(column));
ColumnOrderings<String> get sourceProviders => $composableBuilder(
column: $table.sourceProviders,
builder: (column) => ColumnOrderings(column));
}
class $$LibraryCacheTableAnnotationComposer
@@ -3602,6 +3662,9 @@ class $$LibraryCacheTableAnnotationComposer
GeneratedColumn<bool> get isDeleted =>
$composableBuilder(column: $table.isDeleted, builder: (column) => column);
GeneratedColumn<String> get sourceProviders => $composableBuilder(
column: $table.sourceProviders, builder: (column) => column);
}
class $$LibraryCacheTableTableManager extends RootTableManager<
@@ -3636,6 +3699,7 @@ class $$LibraryCacheTableTableManager extends RootTableManager<
Value<String> data = const Value.absent(),
Value<DateTime> lastSynced = const Value.absent(),
Value<bool> isDeleted = const Value.absent(),
Value<String> sourceProviders = const Value.absent(),
Value<int> rowid = const Value.absent(),
}) =>
LibraryCacheCompanion(
@@ -3645,6 +3709,7 @@ class $$LibraryCacheTableTableManager extends RootTableManager<
data: data,
lastSynced: lastSynced,
isDeleted: isDeleted,
sourceProviders: sourceProviders,
rowid: rowid,
),
createCompanionCallback: ({
@@ -3654,6 +3719,7 @@ class $$LibraryCacheTableTableManager extends RootTableManager<
required String data,
required DateTime lastSynced,
Value<bool> isDeleted = const Value.absent(),
Value<String> sourceProviders = const Value.absent(),
Value<int> rowid = const Value.absent(),
}) =>
LibraryCacheCompanion.insert(
@@ -3663,6 +3729,7 @@ class $$LibraryCacheTableTableManager extends RootTableManager<
data: data,
lastSynced: lastSynced,
isDeleted: isDeleted,
sourceProviders: sourceProviders,
rowid: rowid,
),
withReferenceMapper: (p0) => p0
+197
View File
@@ -1140,6 +1140,10 @@
"audiobookLibraries": "Audiobook Libraries",
"chooseAudiobookLibraries": "Choose which Audiobookshelf libraries to include",
"unknownLibrary": "Unknown Library",
"musicProviders": "Music Providers",
"musicProvidersDescription": "Choose which accounts to show in your library",
"libraryRefreshing": "Refreshing library...",
"cannotDisableLastProvider": "Cannot disable the last provider",
"noSeriesFound": "No Series Found",
"ensembleBugReport": "Ensemble Bug Report",
"byOwner": "By {owner}",
@@ -1431,5 +1435,198 @@
"longPressPodcastHint": "Long-press a podcast and tap the heart to add it to favorites",
"@longPressPodcastHint": {
"description": "Hint for favoriting podcasts"
},
"failedToPlayRadioStation": "Failed to play radio station: {error}",
"@failedToPlayRadioStation": {
"description": "Error when playing radio station fails",
"placeholders": {
"error": {
"type": "String"
}
}
},
"itemAlreadyInLibrary": "Item is already in library",
"@itemAlreadyInLibrary": {
"description": "Message when trying to add item already in library"
},
"failedToAddToLibrary": "Failed to add to library",
"@failedToAddToLibrary": {
"description": "Error when adding to library fails"
},
"cannotFindLibraryId": "Cannot find library ID for removal",
"@cannotFindLibraryId": {
"description": "Error when library ID not found for removal"
},
"failedToRemoveFromLibrary": "Failed to remove from library",
"@failedToRemoveFromLibrary": {
"description": "Error when removing from library fails"
},
"failedToPlayAlbum": "Failed to play album: {error}",
"@failedToPlayAlbum": {
"description": "Error when playing album fails",
"placeholders": {
"error": {
"type": "String"
}
}
},
"playingOnPlayer": "Playing {name} on {playerName}",
"@playingOnPlayer": {
"description": "Status when playing item on specific player",
"placeholders": {
"name": {
"type": "String"
},
"playerName": {
"type": "String"
}
}
},
"failedToPlayPlaylist": "Failed to play playlist: {error}",
"@failedToPlayPlaylist": {
"description": "Error when playing playlist fails",
"placeholders": {
"error": {
"type": "String"
}
}
},
"failedToPlayAudiobook": "Failed to play audiobook: {error}",
"@failedToPlayAudiobook": {
"description": "Error when playing audiobook fails",
"placeholders": {
"error": {
"type": "String"
}
}
},
"noOtherPlayersAvailable": "No other players available",
"@noOtherPlayersAvailable": {
"description": "Message when no other players available for transfer"
},
"transferQueue": "Transfer queue",
"@transferQueue": {
"description": "Tooltip for transfer queue button"
},
"clearQueue": "Clear queue",
"@clearQueue": {
"description": "Tooltip for clear queue button"
},
"syncingPlayer": "Syncing {playerName}...",
"@syncingPlayer": {
"description": "Status when syncing player",
"placeholders": {
"playerName": {
"type": "String"
}
}
},
"switchPlayer": "Switch Player",
"@switchPlayer": {
"description": "Label for switch player action"
},
"logsCopiedToClipboard": "Logs copied to clipboard",
"@logsCopiedToClipboard": {
"description": "Confirmation when logs copied"
},
"auto": "Auto",
"@auto": {
"description": "Auto option for language selection"
},
"transferQueueTo": "Transfer Queue To",
"@transferQueueTo": {
"description": "Title for transfer queue dialog"
},
"queueTransferredTo": "Queue transferred to {playerName}",
"@queueTransferredTo": {
"description": "Success message when queue transferred",
"placeholders": {
"playerName": {
"type": "String"
}
}
},
"failedToTransferQueue": "Failed to transfer queue: {error}",
"@failedToTransferQueue": {
"description": "Error when queue transfer fails",
"placeholders": {
"error": {
"type": "String"
}
}
},
"failedToLoadQueue": "Failed to load queue: {error}",
"@failedToLoadQueue": {
"description": "Error when queue loading fails",
"placeholders": {
"error": {
"type": "String"
}
}
},
"transferTo": "Transfer to...",
"@transferTo": {
"description": "Label for transfer destination selection"
},
"transferQueueToPlayer": "Transfer queue to another player",
"@transferQueueToPlayer": {
"description": "Tooltip for transfer queue button"
},
"selectPlayerToPlay": "Select a player",
"@selectPlayerToPlay": {
"description": "Generic hint for selecting a player in player selector"
},
"selectPlayerToPlayAlbum": "Select player to play album",
"@selectPlayerToPlayAlbum": {
"description": "Hint for selecting player to play album"
},
"selectPlayerToPlayPlaylist": "Select player to play playlist",
"@selectPlayerToPlayPlaylist": {
"description": "Hint for selecting player to play playlist"
},
"selectPlayerForRadio": "Select player for radio",
"@selectPlayerForRadio": {
"description": "Hint for selecting player to start radio"
},
"selectPlayerForEpisode": "Select player for episode",
"@selectPlayerForEpisode": {
"description": "Hint for selecting player to play episode"
},
"selectPlayerForAudiobook": "Select player for audiobook",
"@selectPlayerForAudiobook": {
"description": "Hint for selecting player to play audiobook"
},
"selectPlayerToAddToQueue": "Select player to add to queue",
"@selectPlayerToAddToQueue": {
"description": "Hint for selecting player to add to queue"
}
}
+198
View File
@@ -1563,6 +1563,30 @@ abstract class S {
/// **'Unknown Library'**
String get unknownLibrary;
/// No description provided for @musicProviders.
///
/// In en, this message translates to:
/// **'Music Providers'**
String get musicProviders;
/// No description provided for @musicProvidersDescription.
///
/// In en, this message translates to:
/// **'Choose which accounts to show in your library'**
String get musicProvidersDescription;
/// No description provided for @libraryRefreshing.
///
/// In en, this message translates to:
/// **'Refreshing library...'**
String get libraryRefreshing;
/// No description provided for @cannotDisableLastProvider.
///
/// In en, this message translates to:
/// **'Cannot disable the last provider'**
String get cannotDisableLastProvider;
/// No description provided for @noSeriesFound.
///
/// In en, this message translates to:
@@ -1892,6 +1916,180 @@ abstract class S {
/// In en, this message translates to:
/// **'Long-press a podcast and tap the heart to add it to favorites'**
String get longPressPodcastHint;
/// Error when playing radio station fails
///
/// In en, this message translates to:
/// **'Failed to play radio station: {error}'**
String failedToPlayRadioStation(String error);
/// Message when trying to add item already in library
///
/// In en, this message translates to:
/// **'Item is already in library'**
String get itemAlreadyInLibrary;
/// Error when adding to library fails
///
/// In en, this message translates to:
/// **'Failed to add to library'**
String get failedToAddToLibrary;
/// Error when library ID not found for removal
///
/// In en, this message translates to:
/// **'Cannot find library ID for removal'**
String get cannotFindLibraryId;
/// Error when removing from library fails
///
/// In en, this message translates to:
/// **'Failed to remove from library'**
String get failedToRemoveFromLibrary;
/// Error when playing album fails
///
/// In en, this message translates to:
/// **'Failed to play album: {error}'**
String failedToPlayAlbum(String error);
/// Status when playing item on specific player
///
/// In en, this message translates to:
/// **'Playing {name} on {playerName}'**
String playingOnPlayer(String name, String playerName);
/// Error when playing playlist fails
///
/// In en, this message translates to:
/// **'Failed to play playlist: {error}'**
String failedToPlayPlaylist(String error);
/// Error when playing audiobook fails
///
/// In en, this message translates to:
/// **'Failed to play audiobook: {error}'**
String failedToPlayAudiobook(String error);
/// Message when no other players available for transfer
///
/// In en, this message translates to:
/// **'No other players available'**
String get noOtherPlayersAvailable;
/// Tooltip for transfer queue button
///
/// In en, this message translates to:
/// **'Transfer queue'**
String get transferQueue;
/// Tooltip for clear queue button
///
/// In en, this message translates to:
/// **'Clear queue'**
String get clearQueue;
/// Status when syncing player
///
/// In en, this message translates to:
/// **'Syncing {playerName}...'**
String syncingPlayer(String playerName);
/// Label for switch player action
///
/// In en, this message translates to:
/// **'Switch Player'**
String get switchPlayer;
/// Confirmation when logs copied
///
/// In en, this message translates to:
/// **'Logs copied to clipboard'**
String get logsCopiedToClipboard;
/// Auto option for language selection
///
/// In en, this message translates to:
/// **'Auto'**
String get auto;
/// Title for transfer queue dialog
///
/// In en, this message translates to:
/// **'Transfer Queue To'**
String get transferQueueTo;
/// Success message when queue transferred
///
/// In en, this message translates to:
/// **'Queue transferred to {playerName}'**
String queueTransferredTo(String playerName);
/// Error when queue transfer fails
///
/// In en, this message translates to:
/// **'Failed to transfer queue: {error}'**
String failedToTransferQueue(String error);
/// Error when queue loading fails
///
/// In en, this message translates to:
/// **'Failed to load queue: {error}'**
String failedToLoadQueue(String error);
/// Label for transfer destination selection
///
/// In en, this message translates to:
/// **'Transfer to...'**
String get transferTo;
/// Tooltip for transfer queue button
///
/// In en, this message translates to:
/// **'Transfer queue to another player'**
String get transferQueueToPlayer;
/// Generic hint for selecting a player in player selector
///
/// In en, this message translates to:
/// **'Select a player'**
String get selectPlayerToPlay;
/// Hint for selecting player to play album
///
/// In en, this message translates to:
/// **'Select player to play album'**
String get selectPlayerToPlayAlbum;
/// Hint for selecting player to play playlist
///
/// In en, this message translates to:
/// **'Select player to play playlist'**
String get selectPlayerToPlayPlaylist;
/// Hint for selecting player to start radio
///
/// In en, this message translates to:
/// **'Select player for radio'**
String get selectPlayerForRadio;
/// Hint for selecting player to play episode
///
/// In en, this message translates to:
/// **'Select player for episode'**
String get selectPlayerForEpisode;
/// Hint for selecting player to play audiobook
///
/// In en, this message translates to:
/// **'Select player for audiobook'**
String get selectPlayerForAudiobook;
/// Hint for selecting player to add to queue
///
/// In en, this message translates to:
/// **'Select player to add to queue'**
String get selectPlayerToAddToQueue;
}
class _SDelegate extends LocalizationsDelegate<S> {
+117
View File
@@ -796,6 +796,18 @@ class SDe extends S {
@override
String get unknownLibrary => 'Unbekannte Bibliothek';
@override
String get musicProviders => 'Music Providers';
@override
String get musicProvidersDescription => 'Choose which accounts to show in your library';
@override
String get libraryRefreshing => 'Refreshing library...';
@override
String get cannotDisableLastProvider => 'Cannot disable the last provider';
@override
String get noSeriesFound => 'Keine Serien gefunden';
@@ -980,4 +992,109 @@ class SDe extends S {
@override
String get longPressPodcastHint => 'Long-press a podcast and tap the heart to add it to favorites';
@override
String failedToPlayRadioStation(String error) {
return 'Failed to play radio station: $error';
}
@override
String get itemAlreadyInLibrary => 'Item is already in library';
@override
String get failedToAddToLibrary => 'Failed to add to library';
@override
String get cannotFindLibraryId => 'Cannot find library ID for removal';
@override
String get failedToRemoveFromLibrary => 'Failed to remove from library';
@override
String failedToPlayAlbum(String error) {
return 'Failed to play album: $error';
}
@override
String playingOnPlayer(String name, String playerName) {
return 'Playing $name on $playerName';
}
@override
String failedToPlayPlaylist(String error) {
return 'Failed to play playlist: $error';
}
@override
String failedToPlayAudiobook(String error) {
return 'Failed to play audiobook: $error';
}
@override
String get noOtherPlayersAvailable => 'No other players available';
@override
String get transferQueue => 'Transfer queue';
@override
String get clearQueue => 'Clear queue';
@override
String syncingPlayer(String playerName) {
return 'Syncing $playerName...';
}
@override
String get switchPlayer => 'Switch Player';
@override
String get logsCopiedToClipboard => 'Logs copied to clipboard';
@override
String get auto => 'Auto';
@override
String get transferQueueTo => 'Transfer Queue To';
@override
String queueTransferredTo(String playerName) {
return 'Queue transferred to $playerName';
}
@override
String failedToTransferQueue(String error) {
return 'Failed to transfer queue: $error';
}
@override
String failedToLoadQueue(String error) {
return 'Failed to load queue: $error';
}
@override
String get transferTo => 'Transfer to...';
@override
String get transferQueueToPlayer => 'Transfer queue to another player';
@override
String get selectPlayerToPlay => 'Select a player';
@override
String get selectPlayerToPlayAlbum => 'Select player to play album';
@override
String get selectPlayerToPlayPlaylist => 'Select player to play playlist';
@override
String get selectPlayerForRadio => 'Select player for radio';
@override
String get selectPlayerForEpisode => 'Select player for episode';
@override
String get selectPlayerForAudiobook => 'Select player for audiobook';
@override
String get selectPlayerToAddToQueue => 'Select player to add to queue';
}
+117
View File
@@ -796,6 +796,18 @@ class SEn extends S {
@override
String get unknownLibrary => 'Unknown Library';
@override
String get musicProviders => 'Music Providers';
@override
String get musicProvidersDescription => 'Choose which accounts to show in your library';
@override
String get libraryRefreshing => 'Refreshing library...';
@override
String get cannotDisableLastProvider => 'Cannot disable the last provider';
@override
String get noSeriesFound => 'No Series Found';
@@ -980,4 +992,109 @@ class SEn extends S {
@override
String get longPressPodcastHint => 'Long-press a podcast and tap the heart to add it to favorites';
@override
String failedToPlayRadioStation(String error) {
return 'Failed to play radio station: $error';
}
@override
String get itemAlreadyInLibrary => 'Item is already in library';
@override
String get failedToAddToLibrary => 'Failed to add to library';
@override
String get cannotFindLibraryId => 'Cannot find library ID for removal';
@override
String get failedToRemoveFromLibrary => 'Failed to remove from library';
@override
String failedToPlayAlbum(String error) {
return 'Failed to play album: $error';
}
@override
String playingOnPlayer(String name, String playerName) {
return 'Playing $name on $playerName';
}
@override
String failedToPlayPlaylist(String error) {
return 'Failed to play playlist: $error';
}
@override
String failedToPlayAudiobook(String error) {
return 'Failed to play audiobook: $error';
}
@override
String get noOtherPlayersAvailable => 'No other players available';
@override
String get transferQueue => 'Transfer queue';
@override
String get clearQueue => 'Clear queue';
@override
String syncingPlayer(String playerName) {
return 'Syncing $playerName...';
}
@override
String get switchPlayer => 'Switch Player';
@override
String get logsCopiedToClipboard => 'Logs copied to clipboard';
@override
String get auto => 'Auto';
@override
String get transferQueueTo => 'Transfer Queue To';
@override
String queueTransferredTo(String playerName) {
return 'Queue transferred to $playerName';
}
@override
String failedToTransferQueue(String error) {
return 'Failed to transfer queue: $error';
}
@override
String failedToLoadQueue(String error) {
return 'Failed to load queue: $error';
}
@override
String get transferTo => 'Transfer to...';
@override
String get transferQueueToPlayer => 'Transfer queue to another player';
@override
String get selectPlayerToPlay => 'Select a player';
@override
String get selectPlayerToPlayAlbum => 'Select player to play album';
@override
String get selectPlayerToPlayPlaylist => 'Select player to play playlist';
@override
String get selectPlayerForRadio => 'Select player for radio';
@override
String get selectPlayerForEpisode => 'Select player for episode';
@override
String get selectPlayerForAudiobook => 'Select player for audiobook';
@override
String get selectPlayerToAddToQueue => 'Select player to add to queue';
}
+117
View File
@@ -796,6 +796,18 @@ class SEs extends S {
@override
String get unknownLibrary => 'Biblioteca desconocida';
@override
String get musicProviders => 'Music Providers';
@override
String get musicProvidersDescription => 'Choose which accounts to show in your library';
@override
String get libraryRefreshing => 'Refreshing library...';
@override
String get cannotDisableLastProvider => 'Cannot disable the last provider';
@override
String get noSeriesFound => 'No se encontraron series';
@@ -980,4 +992,109 @@ class SEs extends S {
@override
String get longPressPodcastHint => 'Long-press a podcast and tap the heart to add it to favorites';
@override
String failedToPlayRadioStation(String error) {
return 'Failed to play radio station: $error';
}
@override
String get itemAlreadyInLibrary => 'Item is already in library';
@override
String get failedToAddToLibrary => 'Failed to add to library';
@override
String get cannotFindLibraryId => 'Cannot find library ID for removal';
@override
String get failedToRemoveFromLibrary => 'Failed to remove from library';
@override
String failedToPlayAlbum(String error) {
return 'Failed to play album: $error';
}
@override
String playingOnPlayer(String name, String playerName) {
return 'Playing $name on $playerName';
}
@override
String failedToPlayPlaylist(String error) {
return 'Failed to play playlist: $error';
}
@override
String failedToPlayAudiobook(String error) {
return 'Failed to play audiobook: $error';
}
@override
String get noOtherPlayersAvailable => 'No other players available';
@override
String get transferQueue => 'Transfer queue';
@override
String get clearQueue => 'Clear queue';
@override
String syncingPlayer(String playerName) {
return 'Syncing $playerName...';
}
@override
String get switchPlayer => 'Switch Player';
@override
String get logsCopiedToClipboard => 'Logs copied to clipboard';
@override
String get auto => 'Auto';
@override
String get transferQueueTo => 'Transfer Queue To';
@override
String queueTransferredTo(String playerName) {
return 'Queue transferred to $playerName';
}
@override
String failedToTransferQueue(String error) {
return 'Failed to transfer queue: $error';
}
@override
String failedToLoadQueue(String error) {
return 'Failed to load queue: $error';
}
@override
String get transferTo => 'Transfer to...';
@override
String get transferQueueToPlayer => 'Transfer queue to another player';
@override
String get selectPlayerToPlay => 'Select a player';
@override
String get selectPlayerToPlayAlbum => 'Select player to play album';
@override
String get selectPlayerToPlayPlaylist => 'Select player to play playlist';
@override
String get selectPlayerForRadio => 'Select player for radio';
@override
String get selectPlayerForEpisode => 'Select player for episode';
@override
String get selectPlayerForAudiobook => 'Select player for audiobook';
@override
String get selectPlayerToAddToQueue => 'Select player to add to queue';
}
+117
View File
@@ -796,6 +796,18 @@ class SFr extends S {
@override
String get unknownLibrary => 'Bibliothèque inconnue';
@override
String get musicProviders => 'Music Providers';
@override
String get musicProvidersDescription => 'Choose which accounts to show in your library';
@override
String get libraryRefreshing => 'Refreshing library...';
@override
String get cannotDisableLastProvider => 'Cannot disable the last provider';
@override
String get noSeriesFound => 'Aucune série trouvee';
@@ -980,4 +992,109 @@ class SFr extends S {
@override
String get longPressPodcastHint => 'Long-press a podcast and tap the heart to add it to favorites';
@override
String failedToPlayRadioStation(String error) {
return 'Failed to play radio station: $error';
}
@override
String get itemAlreadyInLibrary => 'Item is already in library';
@override
String get failedToAddToLibrary => 'Failed to add to library';
@override
String get cannotFindLibraryId => 'Cannot find library ID for removal';
@override
String get failedToRemoveFromLibrary => 'Failed to remove from library';
@override
String failedToPlayAlbum(String error) {
return 'Failed to play album: $error';
}
@override
String playingOnPlayer(String name, String playerName) {
return 'Playing $name on $playerName';
}
@override
String failedToPlayPlaylist(String error) {
return 'Failed to play playlist: $error';
}
@override
String failedToPlayAudiobook(String error) {
return 'Failed to play audiobook: $error';
}
@override
String get noOtherPlayersAvailable => 'No other players available';
@override
String get transferQueue => 'Transfer queue';
@override
String get clearQueue => 'Clear queue';
@override
String syncingPlayer(String playerName) {
return 'Syncing $playerName...';
}
@override
String get switchPlayer => 'Switch Player';
@override
String get logsCopiedToClipboard => 'Logs copied to clipboard';
@override
String get auto => 'Auto';
@override
String get transferQueueTo => 'Transfer Queue To';
@override
String queueTransferredTo(String playerName) {
return 'Queue transferred to $playerName';
}
@override
String failedToTransferQueue(String error) {
return 'Failed to transfer queue: $error';
}
@override
String failedToLoadQueue(String error) {
return 'Failed to load queue: $error';
}
@override
String get transferTo => 'Transfer to...';
@override
String get transferQueueToPlayer => 'Transfer queue to another player';
@override
String get selectPlayerToPlay => 'Select a player';
@override
String get selectPlayerToPlayAlbum => 'Select player to play album';
@override
String get selectPlayerToPlayPlaylist => 'Select player to play playlist';
@override
String get selectPlayerForRadio => 'Select player for radio';
@override
String get selectPlayerForEpisode => 'Select player for episode';
@override
String get selectPlayerForAudiobook => 'Select player for audiobook';
@override
String get selectPlayerToAddToQueue => 'Select player to add to queue';
}
+2 -1
View File
@@ -223,8 +223,9 @@ class _MusicAssistantAppState extends State<MusicAssistantApp> with WidgetsBindi
}
// Then check expanded player
// No haptic - Android back gesture provides its own
if (GlobalPlayerOverlay.isPlayerExpanded) {
GlobalPlayerOverlay.collapsePlayer();
GlobalPlayerOverlay.collapsePlayer(withHaptic: false);
return true; // We handled it, don't let Navigator process it
}
+19
View File
@@ -16,6 +16,10 @@ class ProviderMapping {
final String providerInstance;
final bool available;
final Map<String, dynamic>? audioFormat;
/// Whether this item is in the library for this specific provider instance.
/// True = this provider "owns" the item (user added it from this account)
/// False = item exists but wasn't added from this provider
final bool inLibrary;
ProviderMapping({
required this.itemId,
@@ -23,6 +27,7 @@ class ProviderMapping {
required this.providerInstance,
required this.available,
this.audioFormat,
this.inLibrary = true,
});
factory ProviderMapping.fromJson(Map<String, dynamic> json) {
@@ -32,6 +37,8 @@ class ProviderMapping {
providerInstance: json['provider_instance'] as String? ?? '',
available: json['available'] as bool? ?? true,
audioFormat: json['audio_format'] as Map<String, dynamic>?,
// Parse in_library field - MA uses 1/0 or true/false
inLibrary: json['in_library'] == true || json['in_library'] == 1,
);
}
@@ -42,6 +49,7 @@ class ProviderMapping {
'provider_instance': providerInstance,
'available': available,
if (audioFormat != null) 'audio_format': audioFormat,
'in_library': inLibrary,
};
}
}
@@ -118,6 +126,17 @@ class MediaItem {
if (duration != null) 'duration': duration!.inSeconds,
};
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is MediaItem &&
runtimeType == other.runtimeType &&
itemId == other.itemId &&
provider == other.provider;
@override
int get hashCode => Object.hash(itemId, provider);
}
class Artist extends MediaItem {
+128
View File
@@ -0,0 +1,128 @@
/// Represents a music provider instance from Music Assistant.
///
/// Each provider (like Spotify, Tidal) can have multiple instances
/// (e.g., two different Spotify accounts). This class represents
/// a single provider instance with its unique ID.
class ProviderInstance {
/// Unique identifier for this provider instance (e.g., "spotify--abc123")
final String instanceId;
/// The provider domain/type (e.g., "spotify", "tidal", "qobuz")
final String domain;
/// Display name for this instance (e.g., "Spotify (John's Account)")
final String name;
/// Whether this provider is currently available/connected
final bool available;
ProviderInstance({
required this.instanceId,
required this.domain,
required this.name,
required this.available,
});
/// Provider capabilities - maps domain to supported content types
/// This determines which tabs/categories show which providers
static const Map<String, Set<String>> providerCapabilities = {
// Music streaming services (support artists, albums, tracks, playlists)
// Spotify also has audiobooks and podcasts
'spotify': {'artists', 'albums', 'tracks', 'playlists', 'audiobooks', 'podcasts'},
'tidal': {'artists', 'albums', 'tracks', 'playlists'},
'qobuz': {'artists', 'albums', 'tracks', 'playlists'},
'deezer': {'artists', 'albums', 'tracks', 'playlists'},
'ytmusic': {'artists', 'albums', 'tracks', 'playlists', 'podcasts'},
'soundcloud': {'artists', 'albums', 'tracks', 'playlists'},
'apple_music': {'artists', 'albums', 'tracks', 'playlists', 'podcasts'},
'amazon_music': {'artists', 'albums', 'tracks', 'playlists'},
// Self-hosted media servers (can have music, audiobooks, and podcasts)
'plex': {'artists', 'albums', 'tracks', 'playlists', 'audiobooks', 'podcasts'},
'jellyfin': {'artists', 'albums', 'tracks', 'playlists', 'audiobooks', 'podcasts'},
'emby': {'artists', 'albums', 'tracks', 'playlists', 'audiobooks', 'podcasts'},
// Music-only servers
'subsonic': {'artists', 'albums', 'tracks', 'playlists'},
'opensubsonic': {'artists', 'albums', 'tracks', 'playlists'},
'navidrome': {'artists', 'albums', 'tracks', 'playlists'},
'filesystem': {'artists', 'albums', 'tracks', 'playlists'},
// Audiobook and podcast providers
'audiobookshelf': {'audiobooks', 'podcasts'},
'itunes_podcasts': {'podcasts'},
// Radio providers (tunein also has podcasts)
'tunein': {'radio', 'podcasts'},
'radiobrowser': {'radio'},
// Player/system providers (no library content)
'snapcast': <String>{},
'fully_kiosk': <String>{},
};
/// Known music provider domains that provide library content
static const Set<String> musicProviderDomains = {
// Streaming services
'spotify',
'tidal',
'qobuz',
'deezer',
'ytmusic',
'soundcloud',
'apple_music',
'amazon_music',
// Self-hosted / local
'plex',
'subsonic',
'opensubsonic',
'jellyfin',
'emby',
'navidrome',
'audiobookshelf',
'filesystem',
'itunes_podcasts',
// Other
'tunein',
'radiobrowser',
'snapcast',
'fully_kiosk',
};
/// Whether this is a music provider (vs. player provider, metadata provider, etc.)
bool get isMusicProvider => musicProviderDomains.contains(domain);
/// Get supported content types for this provider
Set<String> get supportedContentTypes =>
providerCapabilities[domain] ?? <String>{};
/// Check if this provider supports a specific content type/category
bool supportsContentType(String category) =>
supportedContentTypes.contains(category);
factory ProviderInstance.fromJson(Map<String, dynamic> json) {
return ProviderInstance(
instanceId: json['instance_id'] as String? ?? '',
domain: json['domain'] as String? ?? json['type'] as String? ?? '',
name: json['name'] as String? ?? json['instance_id'] as String? ?? 'Unknown',
available: json['available'] as bool? ?? true,
);
}
Map<String, dynamic> toJson() {
return {
'instance_id': instanceId,
'domain': domain,
'name': name,
'available': available,
};
}
@override
String toString() => 'ProviderInstance($instanceId: $name)';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is ProviderInstance &&
runtimeType == other.runtimeType &&
instanceId == other.instanceId;
@override
int get hashCode => instanceId.hashCode;
}
+245
View File
@@ -0,0 +1,245 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../services/music_assistant_api.dart';
import '../services/settings_service.dart';
import '../services/debug_logger.dart';
import '../services/error_handler.dart';
import '../services/auth/auth_manager.dart';
/// Callback types for connection events
typedef OnConnected = Future<void> Function();
typedef OnAuthenticated = Future<void> Function();
typedef OnDisconnected = void Function();
/// Provider for connection state management.
///
/// Extracted from MusicAssistantProvider to handle:
/// - WebSocket connection lifecycle
/// - Authentication flow (MA token, credentials)
/// - Reconnection logic
/// - Connection state broadcasting
///
/// Note: This is a partial extraction. Full integration requires updating
/// all consumers to use this provider directly.
class ConnectionProvider with ChangeNotifier {
final DebugLogger _logger = DebugLogger();
final AuthManager _authManager = AuthManager();
MusicAssistantAPI? _api;
String? _serverUrl;
String? _error;
MAConnectionState _connectionState = MAConnectionState.disconnected;
StreamSubscription? _connectionStateSubscription;
// Callbacks for connection events - set by the facade provider
OnConnected? onConnected;
OnAuthenticated? onAuthenticated;
OnDisconnected? onDisconnected;
// User settings captured during authentication
List<String> _providerFilter = [];
List<String> _playerFilter = [];
// ============================================================================
// GETTERS
// ============================================================================
MusicAssistantAPI? get api => _api;
AuthManager get authManager => _authManager;
String? get serverUrl => _serverUrl;
String? get error => _error;
MAConnectionState get connectionState => _connectionState;
bool get isConnected =>
_connectionState == MAConnectionState.connected ||
_connectionState == MAConnectionState.authenticated;
List<String> get providerFilter => _providerFilter;
List<String> get playerFilter => _playerFilter;
// ============================================================================
// CONNECTION
// ============================================================================
/// Connect to the Music Assistant server
Future<void> connect(String serverUrl) async {
try {
_error = null;
_serverUrl = serverUrl;
await SettingsService.setServerUrl(serverUrl);
// Dispose the old API to stop any pending reconnects
_api?.dispose();
_api = MusicAssistantAPI(serverUrl, _authManager);
_connectionStateSubscription?.cancel();
_connectionStateSubscription = _api!.connectionState.listen(
(state) async {
_connectionState = state;
notifyListeners();
if (state == MAConnectionState.connected) {
_logger.log('🔗 WebSocket connected to MA server');
if (_api!.authRequired && !_api!.isAuthenticated) {
_logger.log('🔐 MA auth required, attempting authentication...');
final authenticated = await _handleAuthentication();
if (!authenticated) {
_error = 'Authentication required. Please log in again.';
notifyListeners();
return;
}
return;
}
// No auth required, trigger callback
await onConnected?.call();
} else if (state == MAConnectionState.authenticated) {
_logger.log('✅ MA authentication successful');
await onAuthenticated?.call();
} else if (state == MAConnectionState.disconnected) {
_logger.log('📡 Disconnected - keeping cached data for instant resume');
onDisconnected?.call();
}
},
onError: (error) {
_logger.log('Connection state stream error: $error');
_connectionState = MAConnectionState.error;
notifyListeners();
},
);
await _api!.connect();
notifyListeners();
} catch (e) {
final errorInfo = ErrorHandler.handleError(e, context: 'Connect to server');
_error = errorInfo.userMessage;
_connectionState = MAConnectionState.error;
_logger.log('Connection error: ${errorInfo.technicalMessage}');
notifyListeners();
rethrow;
}
}
Future<bool> _handleAuthentication() async {
if (_api == null) return false;
try {
final storedToken = await SettingsService.getMaAuthToken();
if (storedToken != null) {
_logger.log('🔐 Trying stored MA token...');
final success = await _api!.authenticateWithToken(storedToken);
if (success) {
_logger.log('✅ MA authentication with stored token successful');
await _fetchUserSettings();
return true;
}
_logger.log('⚠️ Stored MA token invalid, clearing...');
await SettingsService.clearMaAuthToken();
}
final username = await SettingsService.getUsername();
final password = await SettingsService.getPassword();
if (username != null &&
password != null &&
username.isNotEmpty &&
password.isNotEmpty) {
_logger.log('🔐 Trying stored credentials...');
final accessToken = await _api!.loginWithCredentials(username, password);
if (accessToken != null) {
_logger.log('✅ MA login with stored credentials successful');
final longLivedToken = await _api!.createLongLivedToken();
if (longLivedToken != null) {
await SettingsService.setMaAuthToken(longLivedToken);
_logger.log('✅ Saved new long-lived MA token');
} else {
await SettingsService.setMaAuthToken(accessToken);
}
await _fetchUserSettings();
return true;
}
}
_logger.log('❌ MA authentication failed - no valid token or credentials');
return false;
} catch (e) {
_logger.log('❌ MA authentication error: $e');
return false;
}
}
Future<void> _fetchUserSettings() async {
if (_api == null) return;
try {
final userInfo = await _api!.getCurrentUserInfo();
if (userInfo == null) return;
// Set profile name
final displayName = userInfo['display_name'] as String?;
final username = userInfo['username'] as String?;
final profileName =
(displayName != null && displayName.isNotEmpty) ? displayName : username;
if (profileName != null && profileName.isNotEmpty) {
await SettingsService.setOwnerName(profileName);
_logger.log('✅ Set owner name from MA profile: $profileName');
}
// Capture provider filter
final providerFilterRaw = userInfo['provider_filter'];
if (providerFilterRaw is List) {
_providerFilter = providerFilterRaw.cast<String>().toList();
if (_providerFilter.isNotEmpty) {
_logger.log(
'🔒 Provider filter active: ${_providerFilter.length} providers allowed');
}
} else {
_providerFilter = [];
}
// Capture player filter
final playerFilterRaw = userInfo['player_filter'];
if (playerFilterRaw is List) {
_playerFilter = playerFilterRaw.cast<String>().toList();
if (_playerFilter.isNotEmpty) {
_logger.log(
'🔒 Player filter active: ${_playerFilter.length} players allowed');
}
} else {
_playerFilter = [];
}
} catch (e) {
_logger.log('⚠️ Could not fetch user settings (non-fatal): $e');
}
}
/// Disconnect from the server
Future<void> disconnect() async {
_connectionStateSubscription?.cancel();
await _api?.disconnect();
_connectionState = MAConnectionState.disconnected;
notifyListeners();
}
/// Check connection and reconnect if needed
Future<void> checkAndReconnect() async {
if (_serverUrl != null && !isConnected) {
_logger.log('🔄 Attempting reconnection...');
await connect(_serverUrl!);
}
}
@override
void dispose() {
_connectionStateSubscription?.cancel();
_api?.dispose();
super.dispose();
}
}
+487 -46
View File
@@ -7,6 +7,7 @@ import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_volume_controller/flutter_volume_controller.dart';
import '../models/media_item.dart';
import '../models/player.dart';
import '../models/provider_instance.dart';
import '../services/music_assistant_api.dart';
import '../services/settings_service.dart';
import '../services/debug_logger.dart';
@@ -69,6 +70,12 @@ class MusicAssistantProvider with ChangeNotifier {
Timer? _playerStateTimer;
Timer? _notificationPositionTimer; // Updates notification position every second for remote players
// Sleep timer state
Timer? _sleepTimer;
DateTime? _sleepTimerEndTime;
int? _sleepTimerMinutes; // null = off, -1 = end of track, positive = minutes
Timer? _sleepTimerDisplayTimer; // Updates remaining time display every second
// Local player state
bool _isLocalPlayerPowered = true;
int _localPlayerVolume = 100; // Tracked MA volume for builtin player (0-100)
@@ -114,6 +121,13 @@ class MusicAssistantProvider with ChangeNotifier {
// Empty list means all players are allowed
List<String> _playerFilter = [];
// User-controlled music provider filter (local settings in Ensemble)
// Empty list means all providers are enabled (no filtering)
List<String> _enabledProviderIds = [];
// Available music providers discovered from MA
List<ProviderInstance> _availableMusicProviders = [];
// ============================================================================
// GETTERS
// ============================================================================
@@ -134,6 +148,8 @@ class MusicAssistantProvider with ChangeNotifier {
// Raw unfiltered access (for internal use only)
List<Artist> get artistsUnfiltered => _artists;
List<Album> get albumsUnfiltered => _albums;
List<MediaItem> get podcastsUnfiltered => _podcasts;
List<MediaItem> get radioStationsUnfiltered => _radioStations;
bool get isLoading => _isLoading;
bool get isLoadingRadio => _isLoadingRadio;
bool get isLoadingPodcasts => _isLoadingPodcasts;
@@ -204,6 +220,210 @@ class MusicAssistantProvider with ChangeNotifier {
return players.where(isPlayerAllowedByFilter).toList();
}
// ============================================================================
// USER-CONTROLLED MUSIC PROVIDER FILTER
// ============================================================================
/// List of available music providers from MA
List<ProviderInstance> get availableMusicProviders => _availableMusicProviders;
/// List of enabled provider instance IDs (empty = all enabled)
List<String> get enabledProviderIds => _enabledProviderIds;
/// Whether user has enabled specific providers (not all)
bool get hasUserProviderFilter => _enabledProviderIds.isNotEmpty;
/// Get provider IDs to pass to API calls
/// Returns null if all providers are enabled (no filtering needed)
/// Returns the list of enabled provider IDs otherwise
List<String>? get providerIdsForApiCalls {
if (_enabledProviderIds.isEmpty) return null; // All enabled
return _enabledProviderIds;
}
/// Check if a specific provider is enabled by the user
bool isProviderEnabled(String instanceId) {
if (_enabledProviderIds.isEmpty) return true; // All enabled by default
return _enabledProviderIds.contains(instanceId);
}
/// Get providers that have content in artists library (with item counts)
Map<String, int> getProvidersWithArtists() {
return _getProvidersWithCounts(_artists);
}
/// Get providers that have content in albums library (with item counts)
Map<String, int> getProvidersWithAlbums() {
return _getProvidersWithCounts(_albums);
}
/// Get providers that have content in tracks library (with item counts)
Map<String, int> getProvidersWithTracks() {
return _getProvidersWithCounts(_tracks);
}
/// Get providers that have content in playlists (with item counts)
Map<String, int> getProvidersWithPlaylists() {
return _getProvidersWithCounts(SyncService.instance.cachedPlaylists);
}
/// Get providers that have audiobooks (with item counts)
Map<String, int> getProvidersWithAudiobooks() {
return _getProvidersWithCounts(SyncService.instance.cachedAudiobooks);
}
/// Get providers that have radio stations (with item counts)
Map<String, int> getProvidersWithRadio() {
return _getProvidersWithCounts(_radioStations);
}
/// Get providers that have podcasts (with item counts)
/// Only counts mappings where inLibrary is true - this indicates which provider
/// the user actually added the podcast from (vs providers that can play it)
Map<String, int> getProvidersWithPodcasts() {
final counts = <String, int>{};
for (final item in _podcasts) {
final mappings = item.providerMappings;
if (mappings != null) {
for (final mapping in mappings) {
// Only count if this provider "owns" the item (user added it from this account)
if (mapping.inLibrary) {
final instanceId = mapping.providerInstance;
if (instanceId.isNotEmpty) {
counts[instanceId] = (counts[instanceId] ?? 0) + 1;
}
}
}
}
}
return counts;
}
/// Internal helper to count items per provider from a list of media items
/// Only counts mappings where inLibrary is true - this indicates which provider
/// the user actually added the item from (vs providers that can play it)
Map<String, int> _getProvidersWithCounts<T extends MediaItem>(List<T> items) {
final counts = <String, int>{};
for (final item in items) {
final mappings = item.providerMappings;
if (mappings != null) {
for (final mapping in mappings) {
// Only count if this provider "owns" the item (user added it from this account)
if (mapping.inLibrary) {
final instanceId = mapping.providerInstance;
if (instanceId.isNotEmpty) {
counts[instanceId] = (counts[instanceId] ?? 0) + 1;
}
}
}
}
}
return counts;
}
/// Get ProviderInstance objects for providers that have content in a category
/// Returns list of (ProviderInstance, itemCount) tuples, sorted by name
List<(ProviderInstance, int)> getRelevantProvidersForCategory(String category) {
final Map<String, int> counts;
switch (category) {
case 'artists':
counts = getProvidersWithArtists();
break;
case 'albums':
counts = getProvidersWithAlbums();
break;
case 'tracks':
counts = getProvidersWithTracks();
break;
case 'playlists':
counts = getProvidersWithPlaylists();
break;
case 'audiobooks':
counts = getProvidersWithAudiobooks();
break;
case 'radio':
counts = getProvidersWithRadio();
break;
case 'podcasts':
counts = getProvidersWithPodcasts();
break;
default:
counts = {};
}
// Build list of providers that support this category, with their item counts
// Only include providers that have at least 1 item (hides providers not synced to library)
final result = <(ProviderInstance, int)>[];
final addedInstanceIds = <String>{};
for (final provider in _availableMusicProviders) {
// Only include providers that support this content type AND have items
if (provider.supportsContentType(category)) {
final count = counts[provider.instanceId] ?? 0;
if (count > 0) {
result.add((provider, count));
addedInstanceIds.add(provider.instanceId);
}
}
}
// Also include providers that have items but aren't in _availableMusicProviders
// (e.g., search-only providers like iTunes)
for (final entry in counts.entries) {
if (!addedInstanceIds.contains(entry.key) && entry.value > 0) {
// Create a synthetic ProviderInstance from the instance ID
// Format is typically "domain--uniqueId" (e.g., "itunes--abc123")
final instanceId = entry.key;
final domain = instanceId.contains('--')
? instanceId.split('--').first
: instanceId;
// Only add if this domain supports the category
final capabilities = ProviderInstance.providerCapabilities[domain];
if (capabilities != null && capabilities.contains(category)) {
result.add((
ProviderInstance(
instanceId: instanceId,
domain: domain,
name: _formatProviderName(domain),
available: true,
),
entry.value,
));
}
}
}
// Sort by name
result.sort((a, b) => a.$1.name.compareTo(b.$1.name));
return result;
}
/// Format a provider domain into a readable display name
String _formatProviderName(String domain) {
const names = {
'spotify': 'Spotify',
'tidal': 'Tidal',
'qobuz': 'Qobuz',
'deezer': 'Deezer',
'ytmusic': 'YouTube Music',
'soundcloud': 'SoundCloud',
'apple_music': 'Apple Music',
'amazon_music': 'Amazon Music',
'plex': 'Plex',
'jellyfin': 'Jellyfin',
'emby': 'Emby',
'subsonic': 'Subsonic',
'opensubsonic': 'OpenSubsonic',
'navidrome': 'Navidrome',
'audiobookshelf': 'Audiobookshelf',
'filesystem': 'Filesystem',
'itunes_podcasts': 'iTunes Podcasts',
'tunein': 'TuneIn',
'radiobrowser': 'Radio Browser',
};
return names[domain] ?? domain[0].toUpperCase() + domain.substring(1);
}
/// Whether library is syncing in background
bool get isSyncing => SyncService.instance.isSyncing;
@@ -296,6 +516,15 @@ class MusicAssistantProvider with ChangeNotifier {
Track? get currentTrack => _currentTrack;
// Sleep timer getters
bool get sleepTimerActive => _sleepTimerMinutes != null;
int? get sleepTimerMinutes => _sleepTimerMinutes;
Duration? get sleepTimerRemaining {
if (_sleepTimerEndTime == null) return null;
final remaining = _sleepTimerEndTime!.difference(DateTime.now());
return remaining.isNegative ? Duration.zero : remaining;
}
/// Whether we have cached players available (for instant UI display on app resume)
bool get hasCachedPlayers => _cacheService.hasCachedPlayers;
@@ -377,7 +606,7 @@ class MusicAssistantProvider with ChangeNotifier {
}
String get lastSearchQuery => _lastSearchQuery;
Map<String, List<MediaItem>> get lastSearchResults => filterSearchResults(_lastSearchResults);
Map<String, List<MediaItem>> get lastSearchResults => _lastSearchResults;
MusicAssistantAPI? get api => _api;
AuthManager get authManager => _authManager;
@@ -950,6 +1179,83 @@ class MusicAssistantProvider with ChangeNotifier {
}
}
/// Load available music providers from MA and restore saved filter settings
Future<void> loadMusicProviders() async {
if (_api == null) return;
try {
_logger.log('🎵 Loading music providers...');
// Fetch available providers from MA
_availableMusicProviders = await _api!.getMusicProviders();
// Save discovered providers to settings
final discoveredList = _availableMusicProviders.map((p) => {
'instanceId': p.instanceId,
'domain': p.domain,
'name': p.name,
}).toList();
await SettingsService.setDiscoveredMusicProviders(discoveredList);
// Load saved enabled providers
final savedEnabled = await SettingsService.getEnabledMusicProviders();
if (savedEnabled != null) {
// Validate saved IDs against available providers
final availableIds = _availableMusicProviders.map((p) => p.instanceId).toSet();
_enabledProviderIds = savedEnabled.where((id) => availableIds.contains(id)).toList();
// If all saved providers are gone, reset to all enabled
if (_enabledProviderIds.isEmpty && savedEnabled.isNotEmpty) {
_enabledProviderIds = [];
await SettingsService.clearEnabledMusicProviders();
_logger.log('🔄 Reset provider filter - saved providers no longer available');
} else if (_enabledProviderIds.isNotEmpty) {
_logger.log('🔒 Loaded provider filter: ${_enabledProviderIds.length} providers enabled');
}
} else {
_enabledProviderIds = [];
_logger.log('🔓 No provider filter - all ${_availableMusicProviders.length} providers enabled');
}
notifyListeners();
} catch (e) {
_logger.log('⚠️ Could not load music providers (non-fatal): $e');
}
}
/// Toggle a specific music provider on/off
/// Uses debounce to allow multiple toggles before syncing
Future<bool> toggleProviderEnabled(String instanceId, bool enabled) async {
final allIds = _availableMusicProviders.map((p) => p.instanceId).toList();
// Don't allow disabling the last provider
if (!enabled && _enabledProviderIds.isNotEmpty && _enabledProviderIds.length <= 1) {
_logger.log('⚠️ Cannot disable last provider');
return false;
}
await SettingsService.toggleMusicProvider(instanceId, enabled, allIds);
// Reload the enabled providers
final savedEnabled = await SettingsService.getEnabledMusicProviders();
_enabledProviderIds = savedEnabled ?? [];
_logger.log('🔄 Provider filter updated: ${_enabledProviderIds.isEmpty ? "all enabled" : "${_enabledProviderIds.length} enabled"}');
// Clear discover caches so they get refetched with new filter
_cacheService.clearDiscoverCaches();
// Notify listeners IMMEDIATELY so UI rebuilds with client-side filtering
// This enables instant UI updates using cached data with source tracking
notifyListeners();
// NOTE: Debounced sync is handled by the UI layer (new_library_screen.dart)
// to avoid duplicate timers and ensure single point of control
// Return true to indicate UI should update
return true;
}
Future<void> _initializeAfterConnection() async {
if (_api == null) return;
@@ -962,6 +1268,9 @@ class MusicAssistantProvider with ChangeNotifier {
await _fetchUserSettings();
}
// Load available music providers and user's filter preferences
await loadMusicProviders();
await _tryAdoptGhostPlayer();
await _registerLocalPlayer();
await _loadAndSelectPlayers(coldStart: true);
@@ -2727,7 +3036,10 @@ class MusicAssistantProvider with ChangeNotifier {
try {
_logger.log('🔄 Fetching fresh discover artists...');
final artists = await _api!.getRandomArtists(limit: LibraryConstants.defaultRecentLimit);
final artists = await _api!.getRandomArtists(
limit: LibraryConstants.defaultRecentLimit,
providerInstanceIds: providerIdsForApiCalls,
);
_cacheService.setCachedDiscoverArtists(artists);
return artists;
} catch (e) {
@@ -2746,7 +3058,10 @@ class MusicAssistantProvider with ChangeNotifier {
try {
_logger.log('🔄 Fetching fresh discover albums...');
final albums = await _api!.getRandomAlbums(limit: LibraryConstants.defaultRecentLimit);
final albums = await _api!.getRandomAlbums(
limit: LibraryConstants.defaultRecentLimit,
providerInstanceIds: providerIdsForApiCalls,
);
_cacheService.setCachedDiscoverAlbums(albums);
return albums;
} catch (e) {
@@ -2770,10 +3085,14 @@ class MusicAssistantProvider with ChangeNotifier {
/// Force a full library sync (for pull-to-refresh)
Future<void> forceLibrarySync() async {
if (_api == null) return;
if (_api == null) {
_logger.log('⚠️ forceLibrarySync: API is null, skipping');
return;
}
_logger.log('🔄 Forcing full library sync...');
await SyncService.instance.forceSync(_api!);
final providerIds = providerIdsForApiCalls;
_logger.log('🔄 Forcing full library sync with providers: ${providerIds ?? "ALL"}');
await SyncService.instance.forceSync(_api!, providerInstanceIds: providerIds);
// Update local lists from sync result
_albums = SyncService.instance.cachedAlbums;
@@ -2781,7 +3100,10 @@ class MusicAssistantProvider with ChangeNotifier {
// Also refresh tracks from API
try {
_tracks = await _api!.getTracks(limit: LibraryConstants.maxLibraryItems);
_tracks = await _api!.getTracks(
limit: LibraryConstants.maxLibraryItems,
providerInstanceIds: providerIdsForApiCalls,
);
} catch (e) {
_logger.log('⚠️ Failed to refresh tracks: $e');
}
@@ -3089,12 +3411,11 @@ class MusicAssistantProvider with ChangeNotifier {
if (_cacheService.isSearchCacheValid(cacheKey, forceRefresh: forceRefresh)) {
_logger.log('📦 Using cached search results for "$query" (libraryOnly: $libraryOnly)');
return filterSearchResults(_cacheService.getCachedSearchResults(cacheKey)!);
return _cacheService.getCachedSearchResults(cacheKey)!;
}
if (_api == null) {
final cached = _cacheService.getCachedSearchResults(cacheKey) ?? {'artists': [], 'albums': [], 'tracks': [], 'playlists': [], 'audiobooks': []};
return filterSearchResults(cached);
return _cacheService.getCachedSearchResults(cacheKey) ?? {'artists': [], 'albums': [], 'tracks': [], 'playlists': [], 'audiobooks': []};
}
try {
@@ -3111,11 +3432,10 @@ class MusicAssistantProvider with ChangeNotifier {
_cacheService.setCachedSearchResults(cacheKey, cachedResults);
_logger.log('✅ Cached search results for "$query"');
return filterSearchResults(cachedResults);
return cachedResults;
} catch (e) {
_logger.log('❌ Search failed: $e');
final cached = _cacheService.getCachedSearchResults(cacheKey) ?? {'artists': [], 'albums': [], 'tracks': [], 'playlists': [], 'audiobooks': []};
return filterSearchResults(cached);
return _cacheService.getCachedSearchResults(cacheKey) ?? {'artists': [], 'albums': [], 'tracks': [], 'playlists': [], 'audiobooks': []};
}
}
@@ -3626,6 +3946,9 @@ class MusicAssistantProvider with ChangeNotifier {
item: mediaItem,
playing: player.state == 'playing',
);
} else {
// Builtin player is idle - clear notification (fixes issue #42)
audioHandler.clearRemotePlaybackState();
}
} else {
// For remote players, immediately show notification if we have cached track info
@@ -3668,6 +3991,10 @@ class MusicAssistantProvider with ChangeNotifier {
position: position,
duration: Duration.zero,
);
} else {
// Player is idle - clear the notification to prevent stale metadata
// from previous player showing (fixes issue #42)
audioHandler.clearRemotePlaybackState();
}
}
@@ -3779,40 +4106,33 @@ class MusicAssistantProvider with ChangeNotifier {
}
/// Update just the notification position (called every 500ms for remote/Sendspin players)
void _updateNotificationPosition() {
/// Set [forceUpdate] to true to update even when paused (used after seek)
void _updateNotificationPosition({bool forceUpdate = false}) {
if (_selectedPlayer == null || _currentTrack == null) {
_notificationPositionTimer?.cancel();
return;
}
// Don't update if player is not playing
if (_selectedPlayer!.state != 'playing') {
final isPlaying = _selectedPlayer!.state == 'playing';
// Don't update if player is not playing (unless forced for seek)
if (!isPlaying && !forceUpdate) {
_notificationPositionTimer?.cancel();
return;
}
final track = _currentTrack!;
Duration position;
// For Sendspin PCM, use the PCM player's elapsed time (based on bytes played)
// For remote players, use the position tracker (server-based interpolation)
if (_sendspinConnected && _pcmAudioPlayer != null && _pcmAudioPlayer!.isPlaying) {
position = _pcmAudioPlayer!.elapsedTime;
// Always use position tracker for notification position - it's the single source of truth.
// Previously used PCM elapsed time for Sendspin, but this breaks when:
// 1. Stream starts mid-track (resume from pause) - PCM elapsed resets to 0
// 2. Switching between multiple Sendspin players - PCM elapsed doesn't match
final position = _positionTracker.currentPosition;
// Check if track has ended based on PCM elapsed time
if (track.duration != null && position >= track.duration!) {
_logger.log('🔔 Sendspin: Track appears to have ended (position >= duration)');
return;
}
} else {
// Use position tracker for remote players
position = _positionTracker.currentPosition;
// Check if track has ended (position reached duration)
if (_positionTracker.hasReachedEnd) {
_logger.log('PositionTracker: Track appears to have ended (position >= duration)');
return;
}
// Check if track has ended (position reached duration)
if (_positionTracker.hasReachedEnd) {
_logger.log('PositionTracker: Track appears to have ended (position >= duration)');
return;
}
final artworkUrl = _api?.getImageUrl(track, size: 512);
@@ -3830,7 +4150,7 @@ class MusicAssistantProvider with ChangeNotifier {
audioHandler.setRemotePlaybackState(
item: mediaItem,
playing: true,
playing: isPlaying,
position: position,
duration: track.duration,
);
@@ -4015,6 +4335,10 @@ class MusicAssistantProvider with ChangeNotifier {
Future<void> _updatePlayerState() async {
if (_selectedPlayer == null || _api == null) return;
// Capture player ID at start to detect stale operations
// If player changes during async operations, we should abort
final operationPlayerId = _selectedPlayer!.playerId;
try {
bool stateChanged = false;
@@ -4033,6 +4357,13 @@ class MusicAssistantProvider with ChangeNotifier {
// Try to refresh from API first for latest state
final allPlayers = await getPlayers();
// Check for stale operation - player may have changed during async call
if (_selectedPlayer?.playerId != operationPlayerId) {
_logger.log('⚠️ _updatePlayerState: Player changed during operation, aborting');
return;
}
Player? rawPlayer = allPlayers.firstWhere(
(p) => p.playerId == selectedId ||
(translatedSendspinId != null && p.playerId == translatedSendspinId) ||
@@ -4143,6 +4474,12 @@ class MusicAssistantProvider with ChangeNotifier {
final queue = await getQueue(_selectedPlayer!.playerId);
// Check for stale operation - player may have changed during async call
if (_selectedPlayer?.playerId != operationPlayerId) {
_logger.log('⚠️ _updatePlayerState: Player changed during getQueue, aborting');
return;
}
if (queue != null && queue.currentItem != null) {
final queueTrack = queue.currentItem!.track;
final trackChanged = _currentTrack == null ||
@@ -4150,6 +4487,11 @@ class MusicAssistantProvider with ChangeNotifier {
_currentTrack!.name != queueTrack.name;
if (trackChanged) {
// Check "end of track" sleep timer - previous track just ended
if (_currentTrack != null) {
checkEndOfTrackSleepTimer();
}
// Check if cached track has better metadata (images, proper artist info)
// This prevents losing album art and artist data when resuming the app
// For grouped child players, this gets the leader's cached track
@@ -4404,7 +4746,10 @@ class MusicAssistantProvider with ChangeNotifier {
// Fetch tracks from API (not cached - too many items)
if (_api != null) {
try {
_tracks = await _api!.getTracks(limit: LibraryConstants.maxLibraryItems);
_tracks = await _api!.getTracks(
limit: LibraryConstants.maxLibraryItems,
providerInstanceIds: providerIdsForApiCalls,
);
_logger.log('📥 Fetched ${_tracks.length} tracks from MA');
} catch (e) {
_logger.log('⚠️ Failed to fetch tracks: $e');
@@ -4444,18 +4789,18 @@ class MusicAssistantProvider with ChangeNotifier {
}
syncService.addListener(onSyncComplete);
await syncService.syncFromApi(_api!);
await syncService.syncFromApi(_api!, providerInstanceIds: providerIdsForApiCalls);
}
/// Load radio stations from the library
Future<void> loadRadioStations() async {
Future<void> loadRadioStations({String? orderBy}) async {
if (!isConnected || _api == null) return;
try {
_isLoadingRadio = true;
notifyListeners();
_radioStations = await _api!.getRadioStations(limit: 100);
_radioStations = await _api!.getRadioStations(limit: 100, orderBy: orderBy);
_isLoadingRadio = false;
notifyListeners();
} catch (e) {
@@ -4465,14 +4810,14 @@ class MusicAssistantProvider with ChangeNotifier {
}
}
Future<void> loadPodcasts() async {
Future<void> loadPodcasts({String? orderBy}) async {
if (!isConnected || _api == null) return;
try {
_isLoadingPodcasts = true;
notifyListeners();
_podcasts = await _api!.getPodcasts(limit: 100);
_podcasts = await _api!.getPodcasts(limit: 100, orderBy: orderBy);
_logger.log('🎙️ Loaded ${_podcasts.length} podcasts');
_isLoadingPodcasts = false;
@@ -4515,7 +4860,7 @@ class MusicAssistantProvider with ChangeNotifier {
}
}
Future<void> loadArtists({int? limit, int? offset, String? search}) async {
Future<void> loadArtists({int? limit, int? offset, String? search, String? orderBy}) async {
if (!isConnected) return;
try {
@@ -4528,6 +4873,7 @@ class MusicAssistantProvider with ChangeNotifier {
offset: offset,
search: search,
albumArtistsOnly: false, // Show ALL library artists, not just those with albums
orderBy: orderBy,
);
_isLoading = false;
@@ -4545,6 +4891,7 @@ class MusicAssistantProvider with ChangeNotifier {
int? offset,
String? search,
String? artistId,
String? orderBy,
}) async {
if (!isConnected) return;
@@ -4558,6 +4905,7 @@ class MusicAssistantProvider with ChangeNotifier {
offset: offset,
search: search,
artistId: artistId,
orderBy: orderBy,
);
_isLoading = false;
@@ -4588,7 +4936,7 @@ class MusicAssistantProvider with ChangeNotifier {
try {
final results = await _api!.search(query, libraryOnly: libraryOnly);
return filterSearchResults(results);
return results;
} catch (e) {
ErrorHandler.logError('Search', e);
return {'artists': [], 'albums': [], 'tracks': []};
@@ -4596,10 +4944,10 @@ class MusicAssistantProvider with ChangeNotifier {
}
/// Get playlists with provider filtering applied
Future<List<Playlist>> getPlaylists({int? limit, bool? favoriteOnly}) async {
Future<List<Playlist>> getPlaylists({int? limit, bool? favoriteOnly, String? orderBy}) async {
if (_api == null) return [];
try {
final playlists = await _api!.getPlaylists(limit: limit, favoriteOnly: favoriteOnly);
final playlists = await _api!.getPlaylists(limit: limit, favoriteOnly: favoriteOnly, orderBy: orderBy);
return filterByProvider(playlists);
} catch (e) {
_logger.log('❌ Failed to fetch playlists: $e');
@@ -4982,6 +5330,94 @@ class MusicAssistantProvider with ChangeNotifier {
}
}
// ============================================================================
// SLEEP TIMER
// ============================================================================
/// Set sleep timer. Pass null to turn off, -1 for end of track, or minutes.
void setSleepTimer(int? minutes) {
// Cancel any existing timer
_cancelSleepTimerInternal();
_sleepTimerMinutes = minutes;
if (minutes == null) {
// Timer off
_logger.log('😴 Sleep timer: OFF');
notifyListeners();
return;
}
if (minutes == -1) {
// End of track - handled in player state updates
_sleepTimerEndTime = null; // No fixed end time
_logger.log('😴 Sleep timer: End of track');
notifyListeners();
return;
}
// Set timer for specified minutes
_sleepTimerEndTime = DateTime.now().add(Duration(minutes: minutes));
_logger.log('😴 Sleep timer: $minutes minutes (until $_sleepTimerEndTime)');
// Create the actual timer
_sleepTimer = Timer(Duration(minutes: minutes), _onSleepTimerExpired);
// Start display update timer (every second for countdown)
_sleepTimerDisplayTimer = Timer.periodic(const Duration(seconds: 1), (_) {
notifyListeners(); // Update UI with remaining time
});
notifyListeners();
}
/// Cancel sleep timer
void cancelSleepTimer() {
_cancelSleepTimerInternal();
_sleepTimerMinutes = null;
_sleepTimerEndTime = null;
_logger.log('😴 Sleep timer: Cancelled');
notifyListeners();
}
void _cancelSleepTimerInternal() {
_sleepTimer?.cancel();
_sleepTimer = null;
_sleepTimerDisplayTimer?.cancel();
_sleepTimerDisplayTimer = null;
}
void _onSleepTimerExpired() {
_logger.log('😴 Sleep timer expired - pausing playback');
_cancelSleepTimerInternal();
_sleepTimerMinutes = null;
_sleepTimerEndTime = null;
// Pause the current player
final playerId = _selectedPlayer?.playerId;
if (playerId != null) {
pausePlayer(playerId);
}
notifyListeners();
}
/// Called when track ends - checks if "end of track" sleep timer is active
void checkEndOfTrackSleepTimer() {
if (_sleepTimerMinutes == -1) {
_logger.log('😴 End of track sleep timer triggered');
_sleepTimerMinutes = null;
// Pause the current player
final playerId = _selectedPlayer?.playerId;
if (playerId != null) {
pausePlayer(playerId);
}
notifyListeners();
}
}
/// Sync a player to the currently selected player (temporary group)
/// The target player will play the same audio as the selected player
Future<void> syncPlayerToSelected(String targetPlayerId) async {
@@ -5252,6 +5688,9 @@ class MusicAssistantProvider with ChangeNotifier {
try {
// Immediately update position tracker for responsive UI
_positionTracker.onSeek(position.toDouble());
// Immediately update notification position to stay in sync with app
// Use forceUpdate since seek can happen while paused
_updateNotificationPosition(forceUpdate: true);
await _api?.seek(playerId, position);
} catch (e) {
ErrorHandler.logError('Seek', e);
@@ -5412,6 +5851,8 @@ class MusicAssistantProvider with ChangeNotifier {
_playerStateTimer?.cancel();
_notificationPositionTimer?.cancel();
_localPlayerStateReportTimer?.cancel();
_sleepTimer?.cancel();
_sleepTimerDisplayTimer?.cancel();
_connectionStateSubscription?.cancel();
_localPlayerEventSubscription?.cancel();
_playerUpdatedEventSubscription?.cancel();
+129
View File
@@ -0,0 +1,129 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../services/debug_logger.dart';
/// Callback type for when sleep timer expires and should pause playback
typedef OnSleepTimerExpired = void Function();
/// Provider for sleep timer functionality.
///
/// Extracted from MusicAssistantProvider to reduce complexity and improve testability.
/// This provider manages:
/// - Timed sleep (pause after X minutes)
/// - End of track sleep (pause when current track ends)
class SleepTimerProvider with ChangeNotifier {
final DebugLogger _logger = DebugLogger();
Timer? _sleepTimer;
DateTime? _sleepTimerEndTime;
int? _sleepTimerMinutes; // null = off, -1 = end of track, positive = minutes
Timer? _sleepTimerDisplayTimer;
/// Callback to pause playback when timer expires
OnSleepTimerExpired? onExpired;
// ============================================================================
// GETTERS
// ============================================================================
/// Whether a sleep timer is currently active
bool get isActive => _sleepTimerMinutes != null;
/// Current timer setting: null = off, -1 = end of track, positive = minutes
int? get minutes => _sleepTimerMinutes;
/// Time remaining until sleep timer expires (null if end-of-track mode or inactive)
Duration? get remaining {
if (_sleepTimerEndTime == null) return null;
final remaining = _sleepTimerEndTime!.difference(DateTime.now());
return remaining.isNegative ? Duration.zero : remaining;
}
// ============================================================================
// TIMER CONTROL
// ============================================================================
/// Set sleep timer. Pass null to turn off, -1 for end of track, or minutes.
void setTimer(int? minutes) {
// Cancel any existing timer
_cancelInternal();
_sleepTimerMinutes = minutes;
if (minutes == null) {
// Timer off
_logger.log('😴 Sleep timer: OFF');
notifyListeners();
return;
}
if (minutes == -1) {
// End of track - handled in player state updates
_sleepTimerEndTime = null; // No fixed end time
_logger.log('😴 Sleep timer: End of track');
notifyListeners();
return;
}
// Set timer for specified minutes
_sleepTimerEndTime = DateTime.now().add(Duration(minutes: minutes));
_logger.log('😴 Sleep timer: $minutes minutes (until $_sleepTimerEndTime)');
// Create the actual timer
_sleepTimer = Timer(Duration(minutes: minutes), _onTimerExpired);
// Start display update timer (every second for countdown)
_sleepTimerDisplayTimer = Timer.periodic(const Duration(seconds: 1), (_) {
notifyListeners(); // Update UI with remaining time
});
notifyListeners();
}
/// Cancel sleep timer
void cancel() {
_cancelInternal();
_sleepTimerMinutes = null;
_sleepTimerEndTime = null;
_logger.log('😴 Sleep timer: Cancelled');
notifyListeners();
}
void _cancelInternal() {
_sleepTimer?.cancel();
_sleepTimer = null;
_sleepTimerDisplayTimer?.cancel();
_sleepTimerDisplayTimer = null;
}
void _onTimerExpired() {
_logger.log('😴 Sleep timer expired - pausing playback');
_cancelInternal();
_sleepTimerMinutes = null;
_sleepTimerEndTime = null;
// Trigger the callback to pause playback
onExpired?.call();
notifyListeners();
}
/// Called when track ends - checks if "end of track" sleep timer is active
void checkEndOfTrack() {
if (_sleepTimerMinutes == -1) {
_logger.log('😴 End of track sleep timer triggered');
_sleepTimerMinutes = null;
// Trigger the callback to pause playback
onExpired?.call();
notifyListeners();
}
}
@override
void dispose() {
_cancelInternal();
super.dispose();
}
}
+53 -47
View File
@@ -10,7 +10,6 @@ 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 '../theme/design_tokens.dart';
import 'artist_details_screen.dart';
@@ -223,7 +222,6 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
try {
final newState = !_isInLibrary;
bool success;
if (newState) {
// Add to library - MUST use non-library provider
@@ -254,12 +252,35 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
}
}
// OPTIMISTIC UPDATE: Update UI immediately
setState(() {
_isInLibrary = newState;
});
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(S.of(context)!.addedToLibrary),
duration: const Duration(seconds: 1),
),
);
}
_logger.log('Adding album to library: provider=$actualProvider, itemId=$actualItemId');
success = await maProvider.addToLibrary(
// Fire and forget - API call happens in background
maProvider.addToLibrary(
mediaType: 'album',
provider: actualProvider,
itemId: actualItemId,
);
).catchError((e) {
_logger.log('❌ Failed to add album to library: $e');
// Revert on failure
if (mounted) {
setState(() {
_isInLibrary = !newState;
});
}
});
} else {
// Remove from library
int? libraryItemId;
@@ -280,13 +301,7 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
return;
}
success = await maProvider.removeFromLibrary(
mediaType: 'album',
libraryItemId: libraryItemId,
);
}
if (success) {
// OPTIMISTIC UPDATE: Update UI immediately
setState(() {
_isInLibrary = newState;
});
@@ -294,13 +309,25 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
_isInLibrary ? S.of(context)!.addedToLibrary : S.of(context)!.removedFromLibrary,
),
content: Text(S.of(context)!.removedFromLibrary),
duration: const Duration(seconds: 1),
),
);
}
// Fire and forget - API call happens in background
maProvider.removeFromLibrary(
mediaType: 'album',
libraryItemId: libraryItemId,
).catchError((e) {
_logger.log('❌ Failed to remove album from library: $e');
// Revert on failure
if (mounted) {
setState(() {
_isInLibrary = !newState;
});
}
});
}
} catch (e) {
_logger.log('Error toggling album library: $e');
@@ -673,8 +700,8 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
void _navigateToArtist() {
// Navigate to the first artist if available
if (widget.album.artists != null && widget.album.artists!.isNotEmpty) {
final artist = widget.album.artists!.first;
if (_displayAlbum.artists != null && _displayAlbum.artists!.isNotEmpty) {
final artist = _displayAlbum.artists!.first;
final maProvider = context.read<MusicAssistantProvider>();
final imageUrl = maProvider.getImageUrl(artist, size: 256);
Navigator.push(
@@ -914,7 +941,7 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 4.0),
child: Text(
widget.album.artistsString,
_displayAlbum.artistsString,
style: textTheme.titleMedium?.copyWith(
color: colorScheme.onBackground.withOpacity(0.7),
),
@@ -1229,13 +1256,8 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
void _showPlayAlbumFromHereMenu(BuildContext context, int startIndex) {
final maProvider = context.read<MusicAssistantProvider>();
GlobalPlayerOverlay.hidePlayer();
showPlayerPickerSheet(
context: context,
title: S.of(context)!.playOn,
players: maProvider.availablePlayers,
selectedPlayer: maProvider.selectedPlayer,
GlobalPlayerOverlay.showPlayerSelectorForAction(
contextHint: S.of(context)!.selectPlayerToPlayAlbum,
onPlayerSelected: (player) async {
maProvider.selectPlayer(player);
await maProvider.playTracks(
@@ -1244,48 +1266,32 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
startIndex: startIndex,
);
},
).whenComplete(() {
GlobalPlayerOverlay.showPlayer();
});
);
}
void _showPlayRadioMenu(BuildContext context, int trackIndex) {
final maProvider = context.read<MusicAssistantProvider>();
final track = _tracks[trackIndex];
GlobalPlayerOverlay.hidePlayer();
showPlayerPickerSheet(
context: context,
title: S.of(context)!.playOn,
players: maProvider.availablePlayers,
selectedPlayer: maProvider.selectedPlayer,
GlobalPlayerOverlay.showPlayerSelectorForAction(
contextHint: S.of(context)!.selectPlayerForRadio,
onPlayerSelected: (player) async {
maProvider.selectPlayer(player);
await maProvider.playRadio(player.playerId, track);
},
).whenComplete(() {
GlobalPlayerOverlay.showPlayer();
});
);
}
void _showPlayOnMenu(BuildContext context) {
final maProvider = context.read<MusicAssistantProvider>();
GlobalPlayerOverlay.hidePlayer();
showPlayerPickerSheet(
context: context,
title: S.of(context)!.playOn,
players: maProvider.availablePlayers,
selectedPlayer: maProvider.selectedPlayer,
GlobalPlayerOverlay.showPlayerSelectorForAction(
contextHint: S.of(context)!.selectPlayerToPlayAlbum,
onPlayerSelected: (player) async {
maProvider.selectPlayer(player);
await maProvider.playTracks(player.playerId, _tracks);
},
).whenComplete(() {
GlobalPlayerOverlay.showPlayer();
});
);
}
String _formatDuration(Duration duration) {
+100 -170
View File
@@ -308,7 +308,6 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
try {
final newState = !_isInLibrary;
bool success;
if (newState) {
// Add to library - MUST use non-library provider
@@ -339,12 +338,35 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
}
}
// OPTIMISTIC UPDATE: Update UI immediately
setState(() {
_isInLibrary = newState;
});
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(S.of(context)!.addedToLibrary),
duration: const Duration(seconds: 1),
),
);
}
_logger.log('Adding artist to library: provider=$actualProvider, itemId=$actualItemId');
success = await maProvider.addToLibrary(
// Fire and forget - API call happens in background
maProvider.addToLibrary(
mediaType: 'artist',
provider: actualProvider,
itemId: actualItemId,
);
).catchError((e) {
_logger.log('❌ Failed to add artist to library: $e');
// Revert on failure
if (mounted) {
setState(() {
_isInLibrary = !newState;
});
}
});
} else {
// Remove from library
int? libraryItemId;
@@ -365,13 +387,7 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
return;
}
success = await maProvider.removeFromLibrary(
mediaType: 'artist',
libraryItemId: libraryItemId,
);
}
if (success) {
// OPTIMISTIC UPDATE: Update UI immediately
setState(() {
_isInLibrary = newState;
});
@@ -379,13 +395,25 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
_isInLibrary ? S.of(context)!.addedToLibrary : S.of(context)!.removedFromLibrary,
),
content: Text(S.of(context)!.removedFromLibrary),
duration: const Duration(seconds: 1),
),
);
}
// Fire and forget - API call happens in background
maProvider.removeFromLibrary(
mediaType: 'artist',
libraryItemId: libraryItemId,
).catchError((e) {
_logger.log('❌ Failed to remove artist from library: $e');
// Revert on failure
if (mounted) {
setState(() {
_isInLibrary = !newState;
});
}
});
}
} catch (e) {
_logger.log('Error toggling artist library: $e');
@@ -402,171 +430,73 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
void _showRadioMenu(BuildContext context) {
final maProvider = context.read<MusicAssistantProvider>();
final players = maProvider.availablePlayers;
// Slide mini player down out of the way
GlobalPlayerOverlay.hidePlayer();
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: [
Spacing.vGap16,
Text(
S.of(context)!.startRadioOn(widget.artist.name),
style: Theme.of(context).textTheme.titleLarge,
),
Spacing.vGap16,
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);
try {
await maProvider.playArtistRadio(player.playerId, widget.artist);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(S.of(context)!.startingRadioOnPlayer(widget.artist.name, player.name)),
duration: const Duration(seconds: 1),
),
);
}
} catch (e) {
_logger.log('Error starting artist radio on player: $e');
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(S.of(context)!.failedToStartRadio(e.toString())),
backgroundColor: Colors.red,
),
);
}
}
},
);
},
),
GlobalPlayerOverlay.showPlayerSelectorForAction(
contextHint: S.of(context)!.selectPlayerForRadio,
onPlayerSelected: (player) async {
try {
await maProvider.playArtistRadio(player.playerId, widget.artist);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(S.of(context)!.startingRadioOnPlayer(widget.artist.name, player.name)),
duration: const Duration(seconds: 1),
),
SizedBox(height: MediaQuery.of(context).padding.bottom + 16),
],
),
),
).whenComplete(() {
// Slide mini player back up when sheet is dismissed
GlobalPlayerOverlay.showPlayer();
});
);
}
} catch (e) {
_logger.log('Error starting artist radio on player: $e');
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(S.of(context)!.failedToStartRadio(e.toString())),
backgroundColor: Colors.red,
),
);
}
}
},
);
}
void _showAddToQueueMenu(BuildContext context) {
final maProvider = context.read<MusicAssistantProvider>();
final players = maProvider.availablePlayers;
// Slide mini player down out of the way
GlobalPlayerOverlay.hidePlayer();
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: [
Spacing.vGap16,
Text(
S.of(context)!.addToQueueOn,
style: Theme.of(context).textTheme.titleLarge,
),
Spacing.vGap16,
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,
),
);
}
}
},
);
},
),
GlobalPlayerOverlay.showPlayerSelectorForAction(
contextHint: S.of(context)!.selectPlayerToAddToQueue,
onPlayerSelected: (player) async {
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),
),
SizedBox(height: MediaQuery.of(context).padding.bottom + 16),
],
),
),
).whenComplete(() {
// Slide mini player back up when sheet is dismissed
GlobalPlayerOverlay.showPlayer();
});
);
}
} 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,
),
);
}
}
},
);
}
Future<void> _loadArtistImage() async {
+3 -11
View File
@@ -5,7 +5,6 @@ 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';
@@ -212,13 +211,8 @@ class _AudiobookDetailScreenState extends State<AudiobookDetailScreen> {
void _showPlayOnMenu(BuildContext context) {
final maProvider = context.read<MusicAssistantProvider>();
GlobalPlayerOverlay.hidePlayer();
showPlayerPickerSheet(
context: context,
title: S.of(context)!.playOn,
players: maProvider.availablePlayers,
selectedPlayer: maProvider.selectedPlayer,
GlobalPlayerOverlay.showPlayerSelectorForAction(
contextHint: S.of(context)!.selectPlayerForAudiobook,
onPlayerSelected: (player) async {
maProvider.selectPlayer(player);
maProvider.setCurrentAudiobook(_audiobook);
@@ -227,9 +221,7 @@ class _AudiobookDetailScreenState extends State<AudiobookDetailScreen> {
widget.audiobook,
);
},
).whenComplete(() {
GlobalPlayerOverlay.showPlayer();
});
);
}
Future<void> _markAsFinished() async {
File diff suppressed because it is too large Load Diff
+6 -21
View File
@@ -9,7 +9,6 @@ import '../theme/theme_provider.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 '../theme/design_tokens.dart';
@@ -378,20 +377,13 @@ class _PlaylistDetailsScreenState extends State<PlaylistDetailsScreen> with Sing
void _showPlayOnMenu(BuildContext context) {
final maProvider = context.read<MusicAssistantProvider>();
GlobalPlayerOverlay.hidePlayer();
showPlayerPickerSheet(
context: context,
title: S.of(context)!.playOn,
players: maProvider.availablePlayers,
selectedPlayer: maProvider.selectedPlayer,
GlobalPlayerOverlay.showPlayerSelectorForAction(
contextHint: S.of(context)!.selectPlayerToPlayPlaylist,
onPlayerSelected: (player) async {
maProvider.selectPlayer(player);
await maProvider.playTracks(player.playerId, _tracks);
},
).whenComplete(() {
GlobalPlayerOverlay.showPlayer();
});
);
}
void _addPlaylistToQueue() {
@@ -552,20 +544,13 @@ class _PlaylistDetailsScreenState extends State<PlaylistDetailsScreen> with Sing
final maProvider = context.read<MusicAssistantProvider>();
final track = _tracks[trackIndex];
GlobalPlayerOverlay.hidePlayer();
showPlayerPickerSheet(
context: context,
title: S.of(context)!.playOn,
players: maProvider.availablePlayers,
selectedPlayer: maProvider.selectedPlayer,
GlobalPlayerOverlay.showPlayerSelectorForAction(
contextHint: S.of(context)!.selectPlayerForRadio,
onPlayerSelected: (player) async {
maProvider.selectPlayer(player);
await maProvider.playRadio(player.playerId, track);
},
).whenComplete(() {
GlobalPlayerOverlay.showPlayer();
});
);
}
void _showError(String message) {
+76 -28
View File
@@ -5,7 +5,6 @@ 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';
@@ -66,7 +65,6 @@ class _PodcastDetailScreenState extends State<PodcastDetailScreen> {
try {
final newState = !_isInLibrary;
bool success;
if (newState) {
// Add to library - MUST use non-library provider
@@ -97,12 +95,35 @@ class _PodcastDetailScreenState extends State<PodcastDetailScreen> {
}
}
// OPTIMISTIC UPDATE: Update UI immediately
setState(() {
_isInLibrary = newState;
});
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(S.of(context)!.addedToLibrary),
duration: const Duration(seconds: 1),
),
);
}
_logger.log('Adding podcast to library: provider=$actualProvider, itemId=$actualItemId');
success = await maProvider.addToLibrary(
// Fire and forget - API call happens in background
maProvider.addToLibrary(
mediaType: 'podcast',
provider: actualProvider,
itemId: actualItemId,
);
).catchError((e) {
_logger.log('❌ Failed to add podcast to library: $e');
// Revert on failure
if (mounted) {
setState(() {
_isInLibrary = !newState;
});
}
});
} else {
// Remove from library
int? libraryItemId;
@@ -123,13 +144,7 @@ class _PodcastDetailScreenState extends State<PodcastDetailScreen> {
return;
}
success = await maProvider.removeFromLibrary(
mediaType: 'podcast',
libraryItemId: libraryItemId,
);
}
if (success) {
// OPTIMISTIC UPDATE: Update UI immediately
setState(() {
_isInLibrary = newState;
});
@@ -137,13 +152,25 @@ class _PodcastDetailScreenState extends State<PodcastDetailScreen> {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
_isInLibrary ? S.of(context)!.addedToLibrary : S.of(context)!.removedFromLibrary,
),
content: Text(S.of(context)!.removedFromLibrary),
duration: const Duration(seconds: 1),
),
);
}
// Fire and forget - API call happens in background
maProvider.removeFromLibrary(
mediaType: 'podcast',
libraryItemId: libraryItemId,
).catchError((e) {
_logger.log('❌ Failed to remove podcast from library: $e');
// Revert on failure
if (mounted) {
setState(() {
_isInLibrary = !newState;
});
}
});
}
} catch (e) {
_logger.log('Error toggling podcast library: $e');
@@ -190,10 +217,38 @@ class _PodcastDetailScreenState extends State<PodcastDetailScreen> {
try {
final maProvider = context.read<MusicAssistantProvider>();
if (maProvider.api != null) {
final episodes = await maProvider.api!.getPodcastEpisodes(
widget.podcast.itemId,
provider: widget.podcast.provider,
);
List<MediaItem> episodes = [];
// Try loading with the podcast's own ID and provider first
try {
episodes = await maProvider.api!.getPodcastEpisodes(
widget.podcast.itemId,
provider: widget.podcast.provider,
);
} catch (e) {
_logger.log('🎙️ Primary episode load failed: $e');
}
// If that failed and we have provider mappings, try those
if (episodes.isEmpty && widget.podcast.providerMappings != null) {
for (final mapping in widget.podcast.providerMappings!) {
if (mapping.itemId.isNotEmpty && mapping.providerInstance.isNotEmpty) {
try {
_logger.log('🎙️ Trying provider mapping: ${mapping.providerInstance}');
episodes = await maProvider.api!.getPodcastEpisodes(
mapping.itemId,
provider: mapping.providerInstance,
);
if (episodes.isNotEmpty) {
_logger.log('🎙️ Loaded episodes via provider mapping');
break;
}
} catch (e) {
_logger.log('🎙️ Provider mapping failed: $e');
}
}
}
}
if (mounted) {
_logger.log('🎙️ Loaded ${episodes.length} episodes for ${widget.podcast.name}');
@@ -252,22 +307,15 @@ class _PodcastDetailScreenState extends State<PodcastDetailScreen> {
void _showPlayOnMenu(BuildContext context, MediaItem episode) {
final maProvider = context.read<MusicAssistantProvider>();
GlobalPlayerOverlay.hidePlayer();
showPlayerPickerSheet(
context: context,
title: S.of(context)!.playOn,
players: maProvider.availablePlayers,
selectedPlayer: maProvider.selectedPlayer,
GlobalPlayerOverlay.showPlayerSelectorForAction(
contextHint: S.of(context)!.selectPlayerForEpisode,
onPlayerSelected: (player) async {
maProvider.selectPlayer(player);
// Set podcast context before playing so player UI shows correct podcast name
maProvider.setCurrentPodcastName(widget.podcast.name);
await maProvider.api?.playPodcastEpisode(player.playerId, episode);
},
).whenComplete(() {
GlobalPlayerOverlay.showPlayer();
});
);
}
String _formatDuration(Duration? duration) {
+7 -7
View File
@@ -85,9 +85,9 @@ class _QueueScreenState extends State<QueueScreen> {
if (targetPlayers.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('No other players available to transfer to'),
duration: Duration(seconds: 2),
SnackBar(
content: Text(S.of(context)!.noOtherPlayersAvailable),
duration: const Duration(seconds: 2),
),
);
return;
@@ -96,7 +96,7 @@ class _QueueScreenState extends State<QueueScreen> {
// Show player picker sheet
await showPlayerPickerSheet(
context: context,
title: 'Transfer Queue To',
title: S.of(context)!.transferQueueTo,
players: targetPlayers,
onPlayerSelected: (targetPlayer) async {
try {
@@ -109,7 +109,7 @@ class _QueueScreenState extends State<QueueScreen> {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Queue transferred to ${targetPlayer.name}'),
content: Text(S.of(context)!.queueTransferredTo(targetPlayer.name)),
duration: const Duration(seconds: 2),
),
);
@@ -119,7 +119,7 @@ class _QueueScreenState extends State<QueueScreen> {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Failed to transfer queue: $e'),
content: Text(S.of(context)!.failedToTransferQueue(e.toString())),
backgroundColor: Colors.red.shade700,
duration: const Duration(seconds: 3),
),
@@ -152,7 +152,7 @@ class _QueueScreenState extends State<QueueScreen> {
actions: [
IconButton(
icon: const Icon(Icons.swap_horiz_rounded),
tooltip: 'Transfer queue',
tooltip: S.of(context)!.transferQueue,
onPressed: () => _handleTransferQueue(maProvider),
),
IconButton(
+74 -87
View File
@@ -8,7 +8,6 @@ import '../models/media_item.dart';
import '../services/debug_logger.dart';
import '../services/database_service.dart';
import '../widgets/global_player_overlay.dart';
import '../widgets/player_picker_sheet.dart';
import '../widgets/common/empty_state.dart';
import '../widgets/common/disconnected_state.dart';
import '../widgets/artist_avatar.dart';
@@ -169,6 +168,27 @@ class SearchScreenState extends State<SearchScreen> {
return filters;
}
/// Filter search results by enabled providers (only when in-library mode is on)
/// Uses the client-side provider toggles from the library screen
Map<String, List<MediaItem>> _filterByEnabledProviders(
Map<String, List<MediaItem>> results,
Set<String> enabledProviders,
) {
if (enabledProviders.isEmpty) return results; // No filter = show all
bool isItemAllowed(MediaItem item) {
final mappings = item.providerMappings;
if (mappings == null || mappings.isEmpty) return true; // No mappings = show
// Item is allowed if it has inLibrary=true for any enabled provider
return mappings.any((m) => m.inLibrary && enabledProviders.contains(m.providerInstance));
}
return {
for (final entry in results.entries)
entry.key: entry.value.where(isItemAllowed).toList(),
};
}
/// Animate to a specific filter
void _animateToFilter(String filter) {
final filters = _getAvailableFilters();
@@ -428,12 +448,21 @@ class SearchScreenState extends State<SearchScreen> {
}
if (mounted) {
// Combine all results
var combinedResults = {
...results,
'radios': allRadios.values.toList(),
'podcasts': allPodcasts.values.toList(),
};
// When "in library" mode is on, also filter by enabled providers
if (_libraryOnly) {
final enabledProviders = provider.enabledProviderIds.toSet();
combinedResults = _filterByEnabledProviders(combinedResults, enabledProviders);
}
setState(() {
_searchResults = {
...results,
'radios': allRadios.values.toList(),
'podcasts': allPodcasts.values.toList(),
};
_searchResults = combinedResults;
_isSearching = false;
_hasSearched = true;
_cachedListItems.clear(); // PERF: Clear cache on new results
@@ -2385,7 +2414,7 @@ class SearchScreenState extends State<SearchScreen> {
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to play radio station: $e')),
SnackBar(content: Text(S.of(context)!.failedToPlayRadioStation(e.toString()))),
);
}
}
@@ -2443,13 +2472,8 @@ class SearchScreenState extends State<SearchScreen> {
void _showRadioOnMenu(Track track) {
final maProvider = context.read<MusicAssistantProvider>();
GlobalPlayerOverlay.hidePlayer();
showPlayerPickerSheet(
context: context,
title: S.of(context)!.playOn,
players: maProvider.availablePlayers,
selectedPlayer: maProvider.selectedPlayer,
GlobalPlayerOverlay.showPlayerSelectorForAction(
contextHint: S.of(context)!.selectPlayerForRadio,
onPlayerSelected: (player) async {
try {
maProvider.selectPlayer(player);
@@ -2470,9 +2494,7 @@ class SearchScreenState extends State<SearchScreen> {
}
}
},
).whenComplete(() {
GlobalPlayerOverlay.showPlayer();
});
);
}
/// Add track to queue on current player (1 tap)
@@ -2582,7 +2604,7 @@ class SearchScreenState extends State<SearchScreen> {
_logger.log('Error toggling favorite: $e');
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to update favorite: $e')),
SnackBar(content: Text(S.of(context)!.failedToUpdateFavorite(e.toString()))),
);
}
}
@@ -2633,7 +2655,7 @@ class SearchScreenState extends State<SearchScreen> {
// Item is library-only, can't add
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Item is already in library')),
SnackBar(content: Text(S.of(context)!.itemAlreadyInLibrary)),
);
}
return;
@@ -2669,7 +2691,7 @@ class SearchScreenState extends State<SearchScreen> {
if (mounted) {
setState(() {});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to add to library')),
SnackBar(content: Text(S.of(context)!.failedToAddToLibrary)),
);
}
}
@@ -2696,7 +2718,7 @@ class SearchScreenState extends State<SearchScreen> {
if (libraryItemId == null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Cannot find library ID for removal')),
SnackBar(content: Text(S.of(context)!.cannotFindLibraryId)),
);
return;
}
@@ -2728,7 +2750,7 @@ class SearchScreenState extends State<SearchScreen> {
if (mounted) {
setState(() {});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to remove from library')),
SnackBar(content: Text(S.of(context)!.failedToRemoveFromLibrary)),
);
}
}
@@ -2872,7 +2894,7 @@ class SearchScreenState extends State<SearchScreen> {
_logger.log('Error toggling artist favorite: $e');
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to update favorite: $e')),
SnackBar(content: Text(S.of(context)!.failedToUpdateFavorite(e.toString()))),
);
}
}
@@ -2903,7 +2925,7 @@ class SearchScreenState extends State<SearchScreen> {
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to play album: $e')),
SnackBar(content: Text(S.of(context)!.failedToPlayAlbum(e.toString()))),
);
}
}
@@ -2913,13 +2935,8 @@ class SearchScreenState extends State<SearchScreen> {
void _showAlbumPlayOnMenu(Album album) {
final maProvider = context.read<MusicAssistantProvider>();
GlobalPlayerOverlay.hidePlayer();
showPlayerPickerSheet(
context: context,
title: S.of(context)!.playOn,
players: maProvider.availablePlayers,
selectedPlayer: maProvider.selectedPlayer,
GlobalPlayerOverlay.showPlayerSelectorForAction(
contextHint: S.of(context)!.selectPlayerToPlayAlbum,
onPlayerSelected: (player) async {
try {
maProvider.selectPlayer(player);
@@ -2927,7 +2944,7 @@ class SearchScreenState extends State<SearchScreen> {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Playing ${album.name} on ${player.name}'),
content: Text(S.of(context)!.playingOnPlayer(album.name, player.name)),
duration: const Duration(seconds: 1),
),
);
@@ -2935,14 +2952,12 @@ class SearchScreenState extends State<SearchScreen> {
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to play album: $e')),
SnackBar(content: Text(S.of(context)!.failedToPlayAlbum(e.toString()))),
);
}
}
},
).whenComplete(() {
GlobalPlayerOverlay.showPlayer();
});
);
}
/// Add album to queue
@@ -3051,7 +3066,7 @@ class SearchScreenState extends State<SearchScreen> {
_logger.log('Error toggling album favorite: $e');
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to update favorite: $e')),
SnackBar(content: Text(S.of(context)!.failedToUpdateFavorite(e.toString()))),
);
}
}
@@ -3082,7 +3097,7 @@ class SearchScreenState extends State<SearchScreen> {
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to play playlist: $e')),
SnackBar(content: Text(S.of(context)!.failedToPlayPlaylist(e.toString()))),
);
}
}
@@ -3092,13 +3107,8 @@ class SearchScreenState extends State<SearchScreen> {
void _showPlaylistPlayOnMenu(Playlist playlist) {
final maProvider = context.read<MusicAssistantProvider>();
GlobalPlayerOverlay.hidePlayer();
showPlayerPickerSheet(
context: context,
title: S.of(context)!.playOn,
players: maProvider.availablePlayers,
selectedPlayer: maProvider.selectedPlayer,
GlobalPlayerOverlay.showPlayerSelectorForAction(
contextHint: S.of(context)!.selectPlayerToPlayPlaylist,
onPlayerSelected: (player) async {
try {
maProvider.selectPlayer(player);
@@ -3106,7 +3116,7 @@ class SearchScreenState extends State<SearchScreen> {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Playing ${playlist.name} on ${player.name}'),
content: Text(S.of(context)!.playingOnPlayer(playlist.name, player.name)),
duration: const Duration(seconds: 1),
),
);
@@ -3114,14 +3124,12 @@ class SearchScreenState extends State<SearchScreen> {
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to play playlist: $e')),
SnackBar(content: Text(S.of(context)!.failedToPlayPlaylist(e.toString()))),
);
}
}
},
).whenComplete(() {
GlobalPlayerOverlay.showPlayer();
});
);
}
/// Play audiobook on current player
@@ -3141,7 +3149,7 @@ class SearchScreenState extends State<SearchScreen> {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Playing ${audiobook.name}'),
content: Text(S.of(context)!.playing(audiobook.name)),
duration: const Duration(seconds: 1),
),
);
@@ -3149,7 +3157,7 @@ class SearchScreenState extends State<SearchScreen> {
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to play audiobook: $e')),
SnackBar(content: Text(S.of(context)!.failedToPlayAudiobook(e.toString()))),
);
}
}
@@ -3159,13 +3167,8 @@ class SearchScreenState extends State<SearchScreen> {
void _showAudiobookPlayOnMenu(Audiobook audiobook) {
final maProvider = context.read<MusicAssistantProvider>();
GlobalPlayerOverlay.hidePlayer();
showPlayerPickerSheet(
context: context,
title: S.of(context)!.playOn,
players: maProvider.availablePlayers,
selectedPlayer: maProvider.selectedPlayer,
GlobalPlayerOverlay.showPlayerSelectorForAction(
contextHint: S.of(context)!.selectPlayerForAudiobook,
onPlayerSelected: (player) async {
try {
maProvider.selectPlayer(player);
@@ -3173,7 +3176,7 @@ class SearchScreenState extends State<SearchScreen> {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Playing ${audiobook.name} on ${player.name}'),
content: Text(S.of(context)!.playingOnPlayer(audiobook.name, player.name)),
duration: const Duration(seconds: 1),
),
);
@@ -3181,14 +3184,12 @@ class SearchScreenState extends State<SearchScreen> {
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to play audiobook: $e')),
SnackBar(content: Text(S.of(context)!.failedToPlayAudiobook(e.toString()))),
);
}
}
},
).whenComplete(() {
GlobalPlayerOverlay.showPlayer();
});
);
}
/// Toggle audiobook favorite status
@@ -3266,7 +3267,7 @@ class SearchScreenState extends State<SearchScreen> {
_logger.log('Error toggling audiobook favorite: $e');
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to update favorite: $e')),
SnackBar(content: Text(S.of(context)!.failedToUpdateFavorite(e.toString()))),
);
}
}
@@ -3276,13 +3277,8 @@ class SearchScreenState extends State<SearchScreen> {
void _showRadioPlayOnMenu(MediaItem radio) {
final maProvider = context.read<MusicAssistantProvider>();
GlobalPlayerOverlay.hidePlayer();
showPlayerPickerSheet(
context: context,
title: S.of(context)!.playOn,
players: maProvider.availablePlayers,
selectedPlayer: maProvider.selectedPlayer,
GlobalPlayerOverlay.showPlayerSelectorForAction(
contextHint: S.of(context)!.selectPlayerForRadio,
onPlayerSelected: (player) async {
try {
maProvider.selectPlayer(player);
@@ -3290,7 +3286,7 @@ class SearchScreenState extends State<SearchScreen> {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Playing ${radio.name} on ${player.name}'),
content: Text(S.of(context)!.playingOnPlayer(radio.name, player.name)),
duration: const Duration(seconds: 1),
),
);
@@ -3298,14 +3294,12 @@ class SearchScreenState extends State<SearchScreen> {
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to play radio station: $e')),
SnackBar(content: Text(S.of(context)!.failedToPlayRadioStation(e.toString()))),
);
}
}
},
).whenComplete(() {
GlobalPlayerOverlay.showPlayer();
});
);
}
/// Play podcast (navigate to detail screen where episodes can be played)
@@ -3333,13 +3327,8 @@ class SearchScreenState extends State<SearchScreen> {
void _showPodcastPlayOnMenu(MediaItem podcast) {
final maProvider = context.read<MusicAssistantProvider>();
GlobalPlayerOverlay.hidePlayer();
showPlayerPickerSheet(
context: context,
title: S.of(context)!.playOn,
players: maProvider.availablePlayers,
selectedPlayer: maProvider.selectedPlayer,
GlobalPlayerOverlay.showPlayerSelectorForAction(
contextHint: S.of(context)!.selectPlayerToPlay,
onPlayerSelected: (player) async {
// Select the player, then navigate to podcast detail
maProvider.selectPlayer(player);
@@ -3359,9 +3348,7 @@ class SearchScreenState extends State<SearchScreen> {
);
}
},
).whenComplete(() {
GlobalPlayerOverlay.showPlayer();
});
);
}
String _formatDuration(Duration duration) {
+5 -139
View File
@@ -38,17 +38,12 @@ class _SettingsScreenState extends State<SettingsScreen> {
bool _showDiscoverSeries = false;
// Home row order
List<String> _homeRowOrder = List.from(SettingsService.defaultHomeRowOrder);
// Audiobook libraries
List<Map<String, String>> _discoveredLibraries = [];
Map<String, bool> _libraryEnabled = {};
// Player settings
bool _preferLocalPlayer = false;
bool _smartSortPlayers = false;
bool _volumePrecisionMode = true;
// Hint settings
bool _showHints = true;
// Library settings
bool _showOnlyArtistsWithAlbums = false;
@override
void initState() {
@@ -86,16 +81,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
// Load home row order
final rowOrder = await SettingsService.getHomeRowOrder();
// Load audiobook library settings
final discovered = await SettingsService.getDiscoveredAbsLibraries() ?? [];
final enabled = await SettingsService.getEnabledAbsLibraries();
final libraryEnabled = <String, bool>{};
for (final lib in discovered) {
final path = lib['path'] ?? '';
// null means all enabled
libraryEnabled[path] = enabled == null || enabled.contains(path);
}
// Load player settings
final preferLocal = await SettingsService.getPreferLocalPlayer();
final smartSort = await SettingsService.getSmartSortPlayers();
@@ -104,9 +89,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
// Load hint settings
final showHints = await SettingsService.getShowHints();
// Load library settings
final showOnlyArtistsWithAlbums = await SettingsService.getShowOnlyArtistsWithAlbums();
if (mounted) {
setState(() {
_showRecentAlbums = showRecent;
@@ -122,13 +104,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
_showDiscoverAudiobooks = showDiscAudiobooks;
_showDiscoverSeries = showDiscSeries;
_homeRowOrder = rowOrder;
_discoveredLibraries = discovered;
_libraryEnabled = libraryEnabled;
_preferLocalPlayer = preferLocal;
_smartSortPlayers = smartSort;
_volumePrecisionMode = volumePrecision;
_showHints = showHints;
_showOnlyArtistsWithAlbums = showOnlyArtistsWithAlbums;
});
}
}
@@ -649,7 +628,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
children: [
RadioListTile<String?>(
title: Text(S.of(context)!.system),
subtitle: const Text('Auto'),
subtitle: Text(S.of(context)!.auto),
value: null,
groupValue: localeProvider.locale?.languageCode,
onChanged: (value) {
@@ -658,7 +637,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
},
),
RadioListTile<String?>(
title: const Text('English'),
title: Text(S.of(context)!.english),
value: 'en',
groupValue: localeProvider.locale?.languageCode,
onChanged: (value) {
@@ -667,7 +646,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
},
),
RadioListTile<String?>(
title: const Text('Deutsch'),
title: Text(S.of(context)!.german),
value: 'de',
groupValue: localeProvider.locale?.languageCode,
onChanged: (value) {
@@ -676,7 +655,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
},
),
RadioListTile<String?>(
title: const Text('Español'),
title: Text(S.of(context)!.spanish),
value: 'es',
groupValue: localeProvider.locale?.languageCode,
onChanged: (value) {
@@ -685,7 +664,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
},
),
RadioListTile<String?>(
title: const Text('Français'),
title: Text(S.of(context)!.french),
value: 'fr',
groupValue: localeProvider.locale?.languageCode,
onChanged: (value) {
@@ -834,49 +813,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
const SizedBox(height: 32),
// Library section
Text(
S.of(context)!.library,
style: textTheme.titleMedium?.copyWith(
color: colorScheme.onBackground,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 16),
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
decoration: BoxDecoration(
color: colorScheme.surfaceVariant.withOpacity(0.3),
borderRadius: BorderRadius.circular(12),
),
child: SwitchListTile(
title: Text(
'Show only artists with albums',
style: TextStyle(color: colorScheme.onSurface),
),
subtitle: Text(
'Hide artists that have no albums in your library',
style: TextStyle(
color: colorScheme.onSurface.withOpacity(0.6),
fontSize: 12,
),
),
value: _showOnlyArtistsWithAlbums,
onChanged: (value) async {
setState(() => _showOnlyArtistsWithAlbums = value);
await SettingsService.setShowOnlyArtistsWithAlbums(value);
// Force sync library to apply the new filter at API level
if (mounted) {
context.read<MusicAssistantProvider>().forceLibrarySync();
}
},
activeColor: colorScheme.primary,
contentPadding: EdgeInsets.zero,
),
),
const SizedBox(height: 32),
// Home Screen section
Text(
S.of(context)!.homeScreen,
@@ -1053,76 +989,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
const SizedBox(height: 32),
// Audiobook Libraries section
if (_discoveredLibraries.isNotEmpty) ...[
Text(
S.of(context)!.audiobookLibraries,
style: textTheme.titleMedium?.copyWith(
color: colorScheme.onBackground,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Text(
S.of(context)!.chooseAudiobookLibraries,
style: textTheme.bodySmall?.copyWith(
color: colorScheme.onBackground.withOpacity(0.6),
),
),
const SizedBox(height: 16),
Container(
decoration: BoxDecoration(
color: colorScheme.surfaceVariant.withOpacity(0.3),
borderRadius: BorderRadius.circular(12),
),
child: Column(
children: _discoveredLibraries.asMap().entries.map((entry) {
final index = entry.key;
final library = entry.value;
final path = library['path'] ?? '';
final name = library['name'] ?? S.of(context)!.unknownLibrary;
final isEnabled = _libraryEnabled[path] ?? true;
return Column(
children: [
SwitchListTile(
title: Text(
name,
style: TextStyle(color: colorScheme.onSurface),
),
value: isEnabled,
onChanged: (value) async {
setState(() {
_libraryEnabled[path] = value;
});
await SettingsService.toggleAbsLibrary(path, value);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(S.of(context)!.pullToRefresh),
duration: const Duration(seconds: 2),
),
);
}
},
activeColor: colorScheme.primary,
),
if (index < _discoveredLibraries.length - 1)
Divider(
height: 1,
indent: 16,
endIndent: 16,
color: colorScheme.onSurface.withOpacity(0.1),
),
],
);
}).toList(),
),
),
const SizedBox(height: 32),
],
SizedBox(
width: double.infinity,
height: 50,
+14
View File
@@ -213,6 +213,20 @@ class CacheService {
_logger.log('🗑️ Home artist caches invalidated');
}
/// Clear discover caches (call when provider filter changes)
/// This ensures discover rows are refetched with the new provider filter
void clearDiscoverCaches() {
_cachedDiscoverArtists = null;
_discoverArtistsLastFetched = null;
_cachedDiscoverAlbums = null;
_discoverAlbumsLastFetched = null;
_cachedRecentAlbums = null;
_recentAlbumsLastFetched = null;
_searchCache.clear();
_searchCacheTime.clear();
_logger.log('🗑️ Discover caches cleared for provider filter change');
}
// ============================================================================
// DETAIL SCREEN CACHING
// ============================================================================
+33
View File
@@ -107,15 +107,18 @@ class DatabaseService {
// ============================================
/// Cache an item with JSON serialization
/// [sourceProvider] - optional provider instance ID that provided this item (for client-side filtering)
Future<void> cacheItem<T>({
required String itemType,
required String itemId,
required Map<String, dynamic> data,
String? sourceProvider,
}) {
return db.cacheItem(
itemType: itemType,
itemId: itemId,
data: jsonEncode(data),
sourceProvider: sourceProvider,
);
}
@@ -132,6 +135,29 @@ class DatabaseService {
}).where((item) => item.isNotEmpty).toList();
}
/// Get cached items with source provider info for client-side filtering
/// Returns list of (data, sourceProviders) tuples
Future<List<(Map<String, dynamic>, List<String>)>> getCachedItemsWithProviders(String itemType) async {
final items = await db.getCachedItems(itemType);
return items.map((item) {
try {
final data = jsonDecode(item.data) as Map<String, dynamic>;
List<String> providers = [];
try {
if (item.sourceProviders.isNotEmpty && item.sourceProviders != '[]') {
providers = List<String>.from(
jsonDecode(item.sourceProviders) as List,
);
}
} catch (_) {}
return (data, providers);
} catch (e) {
_logger.log('Error decoding cached item: $e');
return (<String, dynamic>{}, <String>[]);
}
}).where((item) => item.$1.isNotEmpty).toList();
}
/// Get a single cached item
Future<Map<String, dynamic>?> getCachedItem(String itemType, String itemId) async {
final item = await db.getCachedItem(itemType, itemId);
@@ -167,6 +193,13 @@ class DatabaseService {
return db.markItemsDeleted(itemType, [itemId]);
}
/// Batch cache multiple items efficiently
/// Uses drift's batch API for much better performance on large datasets.
/// Items are automatically chunked into batches of 500.
Future<void> batchCacheItems(List<BatchCacheItem> items) {
return db.batchCacheItems(items);
}
// ============================================
// Player Cache Convenience Methods
// ============================================
+101 -17
View File
@@ -2,14 +2,19 @@ import 'dart:convert';
import 'package:http/http.dart' as http;
import 'debug_logger.dart';
import 'settings_service.dart';
import '../utils/lru_cache.dart';
class MetadataService {
static final _logger = DebugLogger();
// Cache to avoid repeated API calls for the same artist/album
static final Map<String, String> _cache = {};
// Cache for artist images
static final Map<String, String?> _artistImageCache = {};
// LRU caches to avoid repeated API calls and prevent unbounded memory growth
// Using NullableLruCache for caches that store null values (failed lookups)
/// Cache for artist/album descriptions (100 entries)
static final LruCache<String, String> _descriptionCache = LruCache(maxSize: 100);
/// Cache for artist images - includes null entries for failed lookups (200 entries)
static final NullableLruCache<String, String> _artistImageCache = NullableLruCache(maxSize: 200);
/// Fetches artist biography/description with fallback chain:
/// 1. Music Assistant metadata (passed in)
@@ -34,8 +39,8 @@ class MetadataService {
// Check cache
final cacheKey = 'artist:$artistName';
if (_cache.containsKey(cacheKey)) {
return _cache[cacheKey];
if (_descriptionCache.containsKey(cacheKey)) {
return _descriptionCache[cacheKey];
}
// Try Last.fm API
@@ -43,7 +48,7 @@ class MetadataService {
if (lastFmKey != null && lastFmKey.isNotEmpty) {
final lastFmDesc = await _fetchFromLastFm(artistName, null, lastFmKey);
if (lastFmDesc != null) {
_cache[cacheKey] = lastFmDesc;
_descriptionCache[cacheKey] = lastFmDesc;
return lastFmDesc;
}
}
@@ -53,7 +58,7 @@ class MetadataService {
if (audioDbKey != null && audioDbKey.isNotEmpty) {
final audioDbDesc = await _fetchFromTheAudioDb(artistName, audioDbKey);
if (audioDbDesc != null) {
_cache[cacheKey] = audioDbDesc;
_descriptionCache[cacheKey] = audioDbDesc;
return audioDbDesc;
}
}
@@ -83,8 +88,8 @@ class MetadataService {
// Check cache
final cacheKey = 'album:$artistName:$albumName';
if (_cache.containsKey(cacheKey)) {
return _cache[cacheKey];
if (_descriptionCache.containsKey(cacheKey)) {
return _descriptionCache[cacheKey];
}
// Try Last.fm API (TheAudioDB doesn't have good album info)
@@ -92,7 +97,7 @@ class MetadataService {
if (lastFmKey != null && lastFmKey.isNotEmpty) {
final lastFmDesc = await _fetchFromLastFm(artistName, albumName, lastFmKey);
if (lastFmDesc != null) {
_cache[cacheKey] = lastFmDesc;
_descriptionCache[cacheKey] = lastFmDesc;
return lastFmDesc;
}
}
@@ -251,11 +256,11 @@ class MetadataService {
return null;
}
// Cache for album images
static final Map<String, String?> _albumImageCache = {};
/// Cache for album images - includes null entries for failed lookups (200 entries)
static final NullableLruCache<String, String> _albumImageCache = NullableLruCache(maxSize: 200);
// Cache for author images (audiobooks)
static final Map<String, String?> _authorImageCache = {};
/// Cache for author images (audiobooks) - includes null entries for failed lookups (100 entries)
static final NullableLruCache<String, String> _authorImageCache = NullableLruCache(maxSize: 100);
/// Fetches album cover URL from Deezer (free, no API key required)
/// Returns the image URL if found, null otherwise
@@ -740,11 +745,90 @@ class MetadataService {
return null;
}
/// Clears the metadata cache
/// Cache for lyrics - uses bounded Map with manual size limiting (500 entries max)
/// Stores (plainLyrics, syncedLyrics) tuples or null for failed lookups
static final Map<String, (String?, String?)?> _lyricsCache = {};
static const int _lyricsCacheMaxSize = 500;
/// Fetches lyrics from LRCLIB (free, no API key required)
/// Returns a tuple of (plainLyrics, syncedLyrics) or null if not found
/// LRCLIB provides both synced (LRC format) and plain lyrics
static Future<(String?, String?)?> getTrackLyrics({
required String trackName,
required String artistName,
String? albumName,
int? durationSeconds,
}) async {
// Build cache key
final cacheKey = 'lyrics:$artistName:$trackName';
if (_lyricsCache.containsKey(cacheKey)) {
return _lyricsCache[cacheKey];
}
// Try LRCLIB API
try {
final params = <String, String>{
'track_name': trackName,
'artist_name': artistName,
};
if (albumName != null && albumName.isNotEmpty) {
params['album_name'] = albumName;
}
if (durationSeconds != null && durationSeconds > 0) {
params['duration'] = durationSeconds.toString();
}
final uri = Uri.https('lrclib.net', '/api/get', params);
_logger.log('🎤 Fetching lyrics from LRCLIB: $trackName by $artistName');
final response = await http.get(
uri,
headers: {
'User-Agent': 'Ensemble Music Player (https://github.com/ensemble-app)',
},
).timeout(const Duration(seconds: 5));
if (response.statusCode == 200) {
final data = json.decode(response.body);
final plainLyrics = data['plainLyrics'] as String?;
final syncedLyrics = data['syncedLyrics'] as String?;
if ((plainLyrics != null && plainLyrics.isNotEmpty) ||
(syncedLyrics != null && syncedLyrics.isNotEmpty)) {
_logger.log('🎤 LRCLIB found lyrics: plain=${plainLyrics?.length ?? 0} chars, synced=${syncedLyrics?.length ?? 0} chars');
final result = (plainLyrics, syncedLyrics);
_evictLyricsCacheIfNeeded();
_lyricsCache[cacheKey] = result;
return result;
}
} else if (response.statusCode == 404) {
_logger.log('🎤 LRCLIB: No lyrics found for $trackName');
} else {
_logger.log('🎤 LRCLIB error: ${response.statusCode}');
}
} catch (e) {
_logger.warning('LRCLIB API error: $e', context: 'Metadata');
}
// Cache the null result to avoid repeated failed lookups
_evictLyricsCacheIfNeeded();
_lyricsCache[cacheKey] = null;
return null;
}
/// Evict oldest entries from lyrics cache if over max size
static void _evictLyricsCacheIfNeeded() {
while (_lyricsCache.length >= _lyricsCacheMaxSize) {
_lyricsCache.remove(_lyricsCache.keys.first);
}
}
/// Clears all metadata caches
static void clearCache() {
_cache.clear();
_descriptionCache.clear();
_artistImageCache.clear();
_albumImageCache.clear();
_authorImageCache.clear();
_lyricsCache.clear();
}
}
+245 -56
View File
@@ -8,6 +8,7 @@ import '../constants/network.dart';
import '../constants/timings.dart' show Timings, LibraryConstants;
import '../models/media_item.dart';
import '../models/player.dart';
import '../models/provider_instance.dart';
import 'debug_logger.dart';
import 'settings_service.dart';
import 'device_id_service.dart';
@@ -79,13 +80,15 @@ class MusicAssistantAPI {
return;
}
// If connection is in progress, wait for it instead of starting another
// Atomic check-and-set: create new completer first, then check if one exists
// This ensures no async operations happen between check and set
final newCompleter = Completer<void>();
if (_connectionInProgress != null && !_connectionInProgress!.isCompleted) {
_logger.log('Connection already in progress, waiting...');
return _connectionInProgress!.future;
}
_connectionInProgress = Completer<void>();
// Set immediately before any async operations to close the race window
_connectionInProgress = newCompleter;
try {
_updateConnectionState(MAConnectionState.connecting);
@@ -344,6 +347,14 @@ class MusicAssistantAPI {
}
}
// Prevent memory leaks by limiting pending requests
if (_pendingRequests.length >= NetworkConstants.maxPendingRequests) {
throw Exception(
'Too many pending requests (${_pendingRequests.length}). '
'Please wait for existing requests to complete.',
);
}
final messageId = _uuid.v4();
final completer = Completer<Map<String, dynamic>>();
_pendingRequests[messageId] = completer;
@@ -376,23 +387,31 @@ class MusicAssistantAPI {
String? search,
bool? favoriteOnly,
bool albumArtistsOnly = true,
String? orderBy,
List<String>? providerInstanceIds,
}) async {
try {
final args = {
if (limit != null) 'limit': limit,
if (offset != null) 'offset': offset,
if (search != null) 'search': search,
if (favoriteOnly != null) 'favorite': favoriteOnly,
'album_artists_only': albumArtistsOnly,
if (orderBy != null) 'order_by': orderBy,
if (providerInstanceIds != null && providerInstanceIds.isNotEmpty)
'provider': providerInstanceIds,
};
_logger.log('🔍 API getArtists args: $args');
final response = await _sendCommand(
'music/artists/library_items',
args: {
if (limit != null) 'limit': limit,
if (offset != null) 'offset': offset,
if (search != null) 'search': search,
if (favoriteOnly != null) 'favorite': favoriteOnly,
'album_artists_only': albumArtistsOnly,
},
args: args,
);
final items = response['result'] as List<dynamic>?;
if (items == null) {
return [];
}
_logger.log('🔍 API getArtists returned ${items.length} items');
return items
.map((item) => Artist.fromJson(item as Map<String, dynamic>))
.toList();
@@ -402,7 +421,11 @@ class MusicAssistantAPI {
}
}
Future<List<Artist>> getRandomArtists({int limit = 10, bool albumArtistsOnly = true}) async {
Future<List<Artist>> getRandomArtists({
int limit = 10,
bool albumArtistsOnly = true,
List<String>? providerInstanceIds,
}) async {
try {
final response = await _sendCommand(
'music/artists/library_items',
@@ -410,6 +433,8 @@ class MusicAssistantAPI {
'limit': limit,
'order_by': 'random',
'album_artists_only': albumArtistsOnly,
if (providerInstanceIds != null && providerInstanceIds.isNotEmpty)
'provider': providerInstanceIds,
},
);
@@ -431,6 +456,8 @@ class MusicAssistantAPI {
String? search,
bool? favoriteOnly,
String? artistId,
String? orderBy,
List<String>? providerInstanceIds,
}) async {
try {
final args = <String, dynamic>{
@@ -439,7 +466,11 @@ class MusicAssistantAPI {
if (search != null) 'search': search,
if (favoriteOnly != null) 'favorite': favoriteOnly,
if (artistId != null) 'artist_id': artistId,
if (orderBy != null) 'order_by': orderBy,
if (providerInstanceIds != null && providerInstanceIds.isNotEmpty)
'provider': providerInstanceIds,
};
_logger.log('🔍 API getAlbums args: $args');
final response = await _sendCommand(
'music/albums/library_items',
@@ -448,6 +479,7 @@ class MusicAssistantAPI {
final items = response['result'] as List<dynamic>?;
if (items == null) return [];
_logger.log('🔍 API getAlbums returned ${items.length} items');
return items
.map((item) => Album.fromJson(item as Map<String, dynamic>))
@@ -465,6 +497,8 @@ class MusicAssistantAPI {
bool? favoriteOnly,
String? artistId,
String? albumId,
String? orderBy,
List<String>? providerInstanceIds,
}) async {
try {
final response = await _sendCommand(
@@ -476,6 +510,9 @@ class MusicAssistantAPI {
if (favoriteOnly != null) 'favorite': favoriteOnly,
if (artistId != null) 'artist': artistId,
if (albumId != null) 'album': albumId,
if (orderBy != null) 'order_by': orderBy,
if (providerInstanceIds != null && providerInstanceIds.isNotEmpty)
'provider': providerInstanceIds,
},
);
@@ -496,6 +533,7 @@ class MusicAssistantAPI {
int? limit,
int? offset,
bool? favoriteOnly,
String? orderBy,
}) async {
try {
final response = await _sendCommand(
@@ -504,6 +542,7 @@ class MusicAssistantAPI {
if (limit != null) 'limit': limit,
if (offset != null) 'offset': offset,
if (favoriteOnly != null) 'favorite': favoriteOnly,
if (orderBy != null) 'order_by': orderBy,
},
);
@@ -555,6 +594,7 @@ class MusicAssistantAPI {
int? limit,
int? offset,
bool? favoriteOnly,
String? orderBy,
}) async {
try {
final response = await _sendCommand(
@@ -563,6 +603,7 @@ class MusicAssistantAPI {
if (limit != null) 'limit': limit,
if (offset != null) 'offset': offset,
if (favoriteOnly != null) 'favorite': favoriteOnly,
if (orderBy != null) 'order_by': orderBy,
},
);
@@ -719,48 +760,113 @@ class MusicAssistantAPI {
String? search,
bool? favoriteOnly,
String? authorId,
List<String>? providerInstanceIds,
}) async {
try {
// Check if library filtering is enabled
final allAudiobooks = <Audiobook>[];
final seenIds = <String>{};
// Check if library filtering is enabled (for ABS providers)
final enabledLibraries = await SettingsService.getEnabledAbsLibraries();
// If specific libraries are enabled, use browse API for filtering
// Extract ABS provider IDs from library paths
final absProviderIds = <String>{};
if (enabledLibraries != null && enabledLibraries.isNotEmpty) {
return await _getAudiobooksFromBrowse(enabledLibraries, favoriteOnly: favoriteOnly);
}
// Otherwise use the faster MA API (returns all audiobooks)
final args = <String, dynamic>{
if (limit != null) 'limit': limit,
if (offset != null) 'offset': offset,
if (search != null) 'search': search,
if (favoriteOnly != null) 'favorite': favoriteOnly,
if (authorId != null) 'author_id': authorId,
};
final response = await _sendCommand(
'music/audiobooks/library_items',
args: args,
);
// Check for error in response
if (response.containsKey('error_code')) {
return [];
}
final items = response['result'] as List<dynamic>?;
if (items == null) return [];
final audiobooks = <Audiobook>[];
for (int i = 0; i < items.length; i++) {
try {
final book = Audiobook.fromJson(items[i] as Map<String, dynamic>);
audiobooks.add(book);
} catch (e) {
// Skip items that fail to parse
for (final libPath in enabledLibraries) {
final providerEnd = libPath.indexOf('://');
if (providerEnd != -1) {
absProviderIds.add(libPath.substring(0, providerEnd));
}
}
}
return audiobooks;
_logger.log('📚 getAudiobooks: absProviderIds=$absProviderIds, providerInstanceIds=$providerInstanceIds');
// PART 1: Fetch from ABS providers using browse API (for library filtering support)
if (enabledLibraries != null && enabledLibraries.isNotEmpty) {
// If specific providers are requested, filter libraries to only matching ABS providers
var librariesToBrowse = enabledLibraries;
if (providerInstanceIds != null && providerInstanceIds.isNotEmpty) {
librariesToBrowse = enabledLibraries.where((libPath) {
final providerEnd = libPath.indexOf('://');
if (providerEnd == -1) return false;
final providerId = libPath.substring(0, providerEnd);
return providerInstanceIds.contains(providerId);
}).toList();
}
if (librariesToBrowse.isNotEmpty) {
final browseBooks = await _getAudiobooksFromBrowse(librariesToBrowse, favoriteOnly: favoriteOnly);
for (final book in browseBooks) {
if (!seenIds.contains(book.itemId)) {
seenIds.add(book.itemId);
allAudiobooks.add(book);
}
}
_logger.log('📚 Got ${browseBooks.length} audiobooks from ABS browse API');
}
}
// PART 2: Fetch from non-ABS providers using library_items API
// This gets audiobooks from Spotify, Plex, Jellyfin, etc.
List<String>? nonAbsProviders;
if (providerInstanceIds != null && providerInstanceIds.isNotEmpty) {
// Filter to only non-ABS providers from the requested list
nonAbsProviders = providerInstanceIds.where((id) => !absProviderIds.contains(id)).toList();
} else if (absProviderIds.isNotEmpty) {
// No specific providers requested, but we have ABS - need to also fetch from non-ABS
// Pass null to get all, then we'll deduplicate
nonAbsProviders = null; // Will fetch all
}
// Only call library_items API if:
// 1. No ABS libraries configured (traditional mode), OR
// 2. We have non-ABS providers to query
final shouldFetchFromApi = enabledLibraries == null ||
enabledLibraries.isEmpty ||
(nonAbsProviders == null && absProviderIds.isNotEmpty) ||
(nonAbsProviders != null && nonAbsProviders.isNotEmpty);
if (shouldFetchFromApi) {
final args = <String, dynamic>{
if (limit != null) 'limit': limit,
if (offset != null) 'offset': offset,
if (search != null) 'search': search,
if (favoriteOnly != null) 'favorite': favoriteOnly,
if (authorId != null) 'author_id': authorId,
if (nonAbsProviders != null && nonAbsProviders.isNotEmpty)
'provider': nonAbsProviders,
};
final response = await _sendCommand(
'music/audiobooks/library_items',
args: args,
);
if (!response.containsKey('error_code')) {
final items = response['result'] as List<dynamic>?;
if (items != null) {
int addedCount = 0;
for (int i = 0; i < items.length; i++) {
try {
final book = Audiobook.fromJson(items[i] as Map<String, dynamic>);
// Deduplicate by itemId
if (!seenIds.contains(book.itemId)) {
seenIds.add(book.itemId);
allAudiobooks.add(book);
addedCount++;
}
} catch (e) {
// Skip items that fail to parse
}
}
_logger.log('📚 Got $addedCount audiobooks from library_items API');
}
}
}
_logger.log('📚 Total audiobooks: ${allAudiobooks.length}');
return allAudiobooks;
} catch (e, stack) {
_logger.log('Error getting audiobooks: $e');
_logger.log('Stack: $stack');
@@ -988,6 +1094,51 @@ class MusicAssistantAPI {
}
}
/// Get lyrics for a track
/// Returns the lyrics text if available, null otherwise
/// Uses the dedicated metadata/get_track_lyrics endpoint
Future<String?> getTrackLyrics(Map<String, dynamic> track) async {
try {
_logger.log('🎤 Getting lyrics for track: ${track['name']}');
// Use the dedicated lyrics endpoint
final response = await _sendCommand(
'metadata/get_track_lyrics',
args: {
'track': track,
},
);
if (response.containsKey('error_code')) {
_logger.log('🎤 Error getting lyrics: ${response['error_code']}');
return null;
}
// Result is a tuple: [plain_lyrics, synced_lyrics]
// We prefer synced lyrics if available, otherwise plain
final result = response['result'];
if (result is List && result.length >= 2) {
final plainLyrics = result[0] as String?;
final syncedLyrics = result[1] as String?;
if (syncedLyrics != null && syncedLyrics.isNotEmpty) {
_logger.log('🎤 Found synced lyrics: ${syncedLyrics.length} chars');
return syncedLyrics;
}
if (plainLyrics != null && plainLyrics.isNotEmpty) {
_logger.log('🎤 Found plain lyrics: ${plainLyrics.length} chars');
return plainLyrics;
}
}
_logger.log('🎤 No lyrics found in result: $result');
return null;
} catch (e) {
_logger.log('🎤 Error getting lyrics: $e');
return null;
}
}
/// Browse Music Assistant content by path
/// Returns a list of browse items (folders or media items)
Future<List<dynamic>> browse(String? path) async {
@@ -1338,13 +1489,18 @@ class MusicAssistantAPI {
}
/// Get random albums
Future<List<Album>> getRandomAlbums({int limit = 10}) async {
Future<List<Album>> getRandomAlbums({
int limit = 10,
List<String>? providerInstanceIds,
}) async {
try {
final response = await _sendCommand(
'music/albums/library_items',
args: {
'limit': limit,
'order_by': 'random',
if (providerInstanceIds != null && providerInstanceIds.isNotEmpty)
'provider': providerInstanceIds,
},
);
@@ -1460,6 +1616,8 @@ class MusicAssistantAPI {
int? offset,
String? search,
bool? favoriteOnly,
String? orderBy,
List<String>? providerInstanceIds,
}) async {
try {
final response = await _sendCommand(
@@ -1469,6 +1627,9 @@ class MusicAssistantAPI {
if (offset != null) 'offset': offset,
if (search != null) 'search': search,
if (favoriteOnly != null) 'favorite': favoriteOnly,
if (orderBy != null) 'order_by': orderBy,
if (providerInstanceIds != null && providerInstanceIds.isNotEmpty)
'provider': providerInstanceIds,
},
);
@@ -1490,7 +1651,7 @@ class MusicAssistantAPI {
final response = await _sendCommand(
'music/playlist',
args: {
'provider': provider,
'provider_instance_id_or_domain': provider,
'item_id': itemId,
},
);
@@ -3269,14 +3430,6 @@ class MusicAssistantAPI {
_logger.log('⚠️ Could not load provider manifests: $e');
}
// Fetch provider instances (active providers)
try {
await _sendCommand('providers');
_logger.log('✓ Provider instances loaded');
} catch (e) {
_logger.log('⚠️ Could not load provider instances: $e');
}
_logger.log('✅ Initial state fetch complete');
} catch (e) {
_logger.log('❌ Error fetching state: $e');
@@ -3284,6 +3437,39 @@ class MusicAssistantAPI {
}
}
/// Get all music provider instances configured in Music Assistant
/// Returns only music providers (spotify, tidal, filesystem, etc.) not player/metadata providers
Future<List<ProviderInstance>> getMusicProviders() async {
try {
final response = await _sendCommand('providers');
final result = response['result'];
if (result == null) {
_logger.log('⚠️ providers command returned no result');
return [];
}
final List<dynamic> providers = result is List ? result : [];
final musicProviders = <ProviderInstance>[];
for (final providerData in providers) {
if (providerData is Map<String, dynamic>) {
final instance = ProviderInstance.fromJson(providerData);
// Only include music providers (not player providers, metadata providers, etc.)
if (instance.isMusicProvider) {
musicProviders.add(instance);
}
}
}
_logger.log('🎵 Found ${musicProviders.length} music providers: ${musicProviders.map((p) => p.name).join(", ")}');
return musicProviders;
} catch (e) {
_logger.log('❌ Error getting music providers: $e');
return [];
}
}
/// Get current authenticated user's profile
/// Returns user info including display_name, username, groups, etc.
Future<Map<String, dynamic>?> getCurrentUserInfo() async {
@@ -3419,6 +3605,9 @@ class MusicAssistantAPI {
return;
}
// Cancel all pending requests before reconnecting to prevent memory leaks
_cancelPendingRequests('Connection lost, reconnecting');
await Future.delayed(Timings.reconnectDelay);
// Check again after delay
+36 -4
View File
@@ -100,6 +100,7 @@ class PositionTracker {
Duration? duration,
double? serverTimestamp,
}) {
_logger.log('⏱️ PositionTracker.updateFromServer: pos=${position.toStringAsFixed(1)}s, isPlaying=$isPlaying, playerId=$playerId');
final bool playerChanged = _playerId != playerId;
final bool playStateChanged = _isPlaying != isPlaying;
final bool durationChanged = duration != null && _duration != duration;
@@ -155,17 +156,34 @@ class PositionTracker {
// 3. Position jumped significantly (seek or track change) - BUT NOT if it's a suspicious reset
// AND NOT if the timestamp is stale (stale data shouldn't override interpolated position)
// 4. We're not playing (paused state should reflect server position)
// 5. Anchor is getting stale (> 20 seconds old) - prevents position freezing at _maxAnchorAge cap
//
// Key insight: When timestamp is stale, the raw position from server is likely outdated.
// Our interpolated position is probably more accurate, so don't let stale data override it.
// HOWEVER, if our anchor itself is getting old, we need to refresh it to prevent freezing.
final anchorAge = DateTime.now().difference(_anchorTime);
final anchorIsGettingStale = anchorAge.inSeconds > 20;
// When anchor is stale, always refresh it - the suspicious reset check should
// only prevent us from trusting the SERVER's position, not from refreshing
// our own interpolated anchor. The newAnchorPos logic below handles using
// interpolated position for stale anchors with suspicious server data.
final shouldUpdateAnchor = playerChanged
|| playStateChanged
|| (positionDiff > 2 && !isSuspiciousReset && !hasStaleTimestamp)
|| !isPlaying;
|| !isPlaying
|| anchorIsGettingStale;
if (shouldUpdateAnchor) {
_anchorPosition = anchorPos;
// When refreshing due to stale anchor (not player/state change), use interpolated position
// to avoid backward jumps from outdated server data
final newAnchorPos = anchorIsGettingStale && !playerChanged && !playStateChanged && isPlaying
? currentInterpolated // Keep our interpolated position, just refresh the anchor time
: anchorPos; // Use server position for other cases
_logger.log('⏱️ PositionTracker: Anchor updated ${_anchorPosition.toStringAsFixed(1)}s -> ${newAnchorPos.toStringAsFixed(1)}s (playerChanged=$playerChanged, playStateChanged=$playStateChanged, positionDiff=${positionDiff.toStringAsFixed(1)}, suspiciousReset=$isSuspiciousReset, anchorStale=$anchorIsGettingStale)');
_anchorPosition = newAnchorPos;
_anchorTime = DateTime.now();
} else if (positionDiff > 2) {
_logger.log('⏱️ PositionTracker: Anchor NOT updated (suspiciousReset=$isSuspiciousReset, staleTimestamp=$hasStaleTimestamp, interpolated=${currentInterpolated.toStringAsFixed(1)}s)');
}
_isPlaying = isPlaying;
@@ -209,6 +227,7 @@ class PositionTracker {
/// Clear tracker state (e.g., when disconnecting)
void clear() {
_logger.log('⏱️ PositionTracker.clear() called');
_stopInterpolationTimer();
_playerId = null;
_isPlaying = false;
@@ -218,9 +237,20 @@ class PositionTracker {
}
void _startInterpolationTimer() {
if (_interpolationTimer != null) return;
if (_interpolationTimer != null) {
_logger.log('⏱️ PositionTracker: Timer already running, skipping start');
return;
}
_interpolationTimer = Timer.periodic(const Duration(milliseconds: 250), (_) {
_logger.log('⏱️ PositionTracker: Starting interpolation timer (anchor=${_anchorPosition.toStringAsFixed(1)}s)');
_interpolationTimer = Timer.periodic(const Duration(milliseconds: 250), (timer) {
// Log every 4 ticks (1 second) if no emission happened
if (timer.tick % 4 == 0) {
final pos = currentPosition;
if (pos.inSeconds == _lastEmittedSeconds) {
_logger.log('⏱️ PositionTracker: Timer tick ${timer.tick}, pos=${pos.inSeconds}s unchanged');
}
}
_emitPosition();
});
@@ -229,6 +259,7 @@ class PositionTracker {
}
void _stopInterpolationTimer() {
_logger.log('⏱️ PositionTracker: Stopping interpolation timer (was ${_interpolationTimer != null ? "running" : "null"})');
_interpolationTimer?.cancel();
_interpolationTimer = null;
}
@@ -240,6 +271,7 @@ class PositionTracker {
// Only emit if second changed (reduces unnecessary updates)
if (seconds != _lastEmittedSeconds) {
_lastEmittedSeconds = seconds;
_logger.log('⏱️ PositionTracker: Emitting position ${seconds}s (anchor=${_anchorPosition.toStringAsFixed(1)}s, playing=$_isPlaying)');
_positionController.add(pos);
}
}
+79
View File
@@ -161,6 +161,10 @@ class SettingsService {
static const String _keyEnabledAbsLibraries = 'enabled_abs_libraries'; // JSON list of library paths
static const String _keyDiscoveredAbsLibraries = 'discovered_abs_libraries'; // JSON list of {path, name}
// Music Provider Filter Settings
static const String _keyEnabledMusicProviders = 'enabled_music_providers'; // JSON list of provider instance IDs
static const String _keyDiscoveredMusicProviders = 'discovered_music_providers'; // JSON list of {instanceId, domain, name}
// Hint System Settings
static const String _keyShowHints = 'show_hints'; // Master toggle for hints
static const String _keyHasUsedPlayerReveal = 'has_used_player_reveal'; // Track if user has pulled to reveal players
@@ -789,6 +793,81 @@ class SettingsService {
await setEnabledAbsLibraries(enabled);
}
// Music Provider Filter Settings
/// Get list of enabled music provider instance IDs (null = all enabled)
/// Returns null if no filter is set (all providers enabled by default)
static Future<List<String>?> getEnabledMusicProviders() async {
final prefs = await _getPrefs();
final json = prefs.getString(_keyEnabledMusicProviders);
if (json == null) return null; // null means all providers are enabled
try {
final list = jsonDecode(json) as List<dynamic>;
return list.cast<String>();
} catch (e) {
return null;
}
}
/// Set list of enabled music provider instance IDs
/// Pass null or call clearEnabledMusicProviders() to enable all providers
static Future<void> setEnabledMusicProviders(List<String> providerIds) async {
final prefs = await _getPrefs();
await prefs.setString(_keyEnabledMusicProviders, jsonEncode(providerIds));
}
/// Clear enabled providers (reverts to all enabled)
static Future<void> clearEnabledMusicProviders() async {
final prefs = await _getPrefs();
await prefs.remove(_keyEnabledMusicProviders);
}
/// Get discovered music providers [{instanceId, domain, name}]
static Future<List<Map<String, String>>?> getDiscoveredMusicProviders() async {
final prefs = await _getPrefs();
final json = prefs.getString(_keyDiscoveredMusicProviders);
if (json == null) return null;
try {
final list = jsonDecode(json) as List<dynamic>;
return list.map((e) => Map<String, String>.from(e as Map)).toList();
} catch (e) {
return null;
}
}
/// Save discovered music providers
static Future<void> setDiscoveredMusicProviders(List<Map<String, String>> providers) async {
final prefs = await _getPrefs();
await prefs.setString(_keyDiscoveredMusicProviders, jsonEncode(providers));
}
/// Check if a specific music provider is enabled
static Future<bool> isMusicProviderEnabled(String instanceId) async {
final enabled = await getEnabledMusicProviders();
if (enabled == null) return true; // All enabled by default
return enabled.contains(instanceId);
}
/// Toggle a specific music provider
/// allProviderIds should contain all available provider instance IDs
static Future<void> toggleMusicProvider(String instanceId, bool enable, List<String> allProviderIds) async {
var enabled = await getEnabledMusicProviders();
// If null (all enabled), initialize with all provider IDs
enabled ??= List.from(allProviderIds);
if (enable && !enabled.contains(instanceId)) {
enabled.add(instanceId);
} else if (!enable && enabled.contains(instanceId)) {
// Prevent disabling the last provider
if (enabled.length <= 1) {
return; // Don't allow disabling the last provider
}
enabled.remove(instanceId);
}
await setEnabledMusicProviders(enabled);
}
// Hint System Settings
/// Get whether hints are enabled (default: true)
+373 -102
View File
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import '../database/database.dart' show BatchCacheItem;
import '../models/media_item.dart';
import 'database_service.dart';
import 'debug_logger.dart';
@@ -17,6 +18,7 @@ enum SyncStatus {
/// Service for background library synchronization
/// Loads from database cache first, then syncs from MA API in background
/// Supports per-provider sync for accurate client-side filtering
class SyncService with ChangeNotifier {
static SyncService? _instance;
static final _logger = DebugLogger();
@@ -42,6 +44,13 @@ class SyncService with ChangeNotifier {
List<Audiobook> _cachedAudiobooks = [];
List<Playlist> _cachedPlaylists = [];
// Source provider tracking for client-side filtering
// Maps itemId -> list of provider instance IDs that provided the item
Map<String, List<String>> _albumSourceProviders = {};
Map<String, List<String>> _artistSourceProviders = {};
Map<String, List<String>> _audiobookSourceProviders = {};
Map<String, List<String>> _playlistSourceProviders = {};
// Getters
SyncStatus get status => _status;
String? get lastError => _lastError;
@@ -54,8 +63,15 @@ class SyncService with ChangeNotifier {
bool get hasCache => _cachedAlbums.isNotEmpty || _cachedArtists.isNotEmpty ||
_cachedAudiobooks.isNotEmpty || _cachedPlaylists.isNotEmpty;
// Source provider getters for client-side filtering
Map<String, List<String>> get albumSourceProviders => _albumSourceProviders;
Map<String, List<String>> get artistSourceProviders => _artistSourceProviders;
Map<String, List<String>> get audiobookSourceProviders => _audiobookSourceProviders;
Map<String, List<String>> get playlistSourceProviders => _playlistSourceProviders;
/// Load library data from database cache (instant)
/// Call this on app startup for immediate data
/// Also loads source provider info for client-side filtering
Future<void> loadFromCache() async {
if (!_db.isInitialized) {
_logger.log('⚠️ Database not initialized, skipping cache load');
@@ -65,52 +81,73 @@ class SyncService with ChangeNotifier {
try {
_logger.log('📦 Loading library from database cache...');
// Load albums from cache
final albumData = await _db.getCachedItems('album');
_cachedAlbums = albumData.map((data) {
// Load albums from cache with source providers
final albumDataWithProviders = await _db.getCachedItemsWithProviders('album');
_cachedAlbums = [];
_albumSourceProviders = {};
for (final (data, providers) in albumDataWithProviders) {
try {
return Album.fromJson(data);
final album = Album.fromJson(data);
_cachedAlbums.add(album);
if (providers.isNotEmpty) {
_albumSourceProviders[album.itemId] = providers;
}
} catch (e) {
_logger.log('⚠️ Failed to parse cached album: $e');
return null;
}
}).whereType<Album>().toList();
}
// Load artists from cache
final artistData = await _db.getCachedItems('artist');
_cachedArtists = artistData.map((data) {
// Load artists from cache with source providers
final artistDataWithProviders = await _db.getCachedItemsWithProviders('artist');
_cachedArtists = [];
_artistSourceProviders = {};
for (final (data, providers) in artistDataWithProviders) {
try {
return Artist.fromJson(data);
final artist = Artist.fromJson(data);
_cachedArtists.add(artist);
if (providers.isNotEmpty) {
_artistSourceProviders[artist.itemId] = providers;
}
} catch (e) {
_logger.log('⚠️ Failed to parse cached artist: $e');
return null;
}
}).whereType<Artist>().toList();
}
// Load audiobooks from cache
final audiobookData = await _db.getCachedItems('audiobook');
_cachedAudiobooks = audiobookData.map((data) {
// Load audiobooks from cache with source providers
final audiobookDataWithProviders = await _db.getCachedItemsWithProviders('audiobook');
_cachedAudiobooks = [];
_audiobookSourceProviders = {};
for (final (data, providers) in audiobookDataWithProviders) {
try {
return Audiobook.fromJson(data);
final audiobook = Audiobook.fromJson(data);
_cachedAudiobooks.add(audiobook);
if (providers.isNotEmpty) {
_audiobookSourceProviders[audiobook.itemId] = providers;
}
} catch (e) {
_logger.log('⚠️ Failed to parse cached audiobook: $e');
return null;
}
}).whereType<Audiobook>().toList();
}
// Load playlists from cache
final playlistData = await _db.getCachedItems('playlist');
_cachedPlaylists = playlistData.map((data) {
// Load playlists from cache with source providers
final playlistDataWithProviders = await _db.getCachedItemsWithProviders('playlist');
_cachedPlaylists = [];
_playlistSourceProviders = {};
for (final (data, providers) in playlistDataWithProviders) {
try {
return Playlist.fromJson(data);
final playlist = Playlist.fromJson(data);
_cachedPlaylists.add(playlist);
if (providers.isNotEmpty) {
_playlistSourceProviders[playlist.itemId] = providers;
}
} catch (e) {
_logger.log('⚠️ Failed to parse cached playlist: $e');
return null;
}
}).whereType<Playlist>().toList();
}
_logger.log('📦 Loaded ${_cachedAlbums.length} albums, ${_cachedArtists.length} artists, '
'${_cachedAudiobooks.length} audiobooks, ${_cachedPlaylists.length} playlists from cache');
_logger.log('📦 Source providers: ${_albumSourceProviders.length} albums, ${_artistSourceProviders.length} artists tracked');
notifyListeners();
} catch (e) {
_logger.log('❌ Failed to load from cache: $e');
@@ -119,7 +156,12 @@ class SyncService with ChangeNotifier {
/// Sync library data from MA API in background
/// Updates database cache and notifies listeners when complete
Future<void> syncFromApi(MusicAssistantAPI api, {bool force = false}) async {
/// [providerInstanceIds] - list of provider IDs to sync (fetches each provider separately for accurate source tracking)
Future<void> syncFromApi(
MusicAssistantAPI api, {
bool force = false,
List<String>? providerInstanceIds,
}) async {
if (_isSyncing) {
_logger.log('🔄 Sync already in progress, skipping');
return;
@@ -155,33 +197,140 @@ class SyncService with ChangeNotifier {
final showOnlyArtistsWithAlbums = await SettingsService.getShowOnlyArtistsWithAlbums();
_logger.log('🎨 Sync using albumArtistsOnly: $showOnlyArtistsWithAlbums');
// Fetch fresh data from MA API (in parallel for speed)
final results = await Future.wait([
api.getAlbums(limit: 1000),
api.getArtists(limit: 1000, albumArtistsOnly: showOnlyArtistsWithAlbums),
api.getAudiobooks(limit: 1000),
api.getPlaylists(limit: 1000),
]);
// Only clear cache for full syncs (no specific providers)
// Partial syncs preserve items from disabled providers for instant toggle-on
final isPartialSync = providerInstanceIds != null && providerInstanceIds.isNotEmpty;
if (!isPartialSync) {
await _db.clearCacheForType('album');
await _db.clearCacheForType('artist');
await _db.clearCacheForType('audiobook');
await _db.clearCacheForType('playlist');
}
final albums = results[0] as List<Album>;
final artists = results[1] as List<Artist>;
final audiobooks = results[2] as List<Audiobook>;
final playlists = results[3] as List<Playlist>;
// Build NEW source tracking maps - don't modify existing until sync is complete
// This prevents UI flicker from partial tracking during sync
final syncingProviders = providerInstanceIds?.toSet() ?? <String>{};
final newAlbumSourceProviders = <String, List<String>>{};
final newArtistSourceProviders = <String, List<String>>{};
final newAudiobookSourceProviders = <String, List<String>>{};
final newPlaylistSourceProviders = <String, List<String>>{};
_logger.log('📥 Fetched ${albums.length} albums, ${artists.length} artists, '
'${audiobooks.length} audiobooks, ${playlists.length} playlists from MA');
// For partial syncs, copy tracking from non-syncing providers
if (isPartialSync) {
for (final entry in _albumSourceProviders.entries) {
final preserved = entry.value.where((p) => !syncingProviders.contains(p)).toList();
if (preserved.isNotEmpty) newAlbumSourceProviders[entry.key] = preserved;
}
for (final entry in _artistSourceProviders.entries) {
final preserved = entry.value.where((p) => !syncingProviders.contains(p)).toList();
if (preserved.isNotEmpty) newArtistSourceProviders[entry.key] = preserved;
}
for (final entry in _audiobookSourceProviders.entries) {
final preserved = entry.value.where((p) => !syncingProviders.contains(p)).toList();
if (preserved.isNotEmpty) newAudiobookSourceProviders[entry.key] = preserved;
}
for (final entry in _playlistSourceProviders.entries) {
final preserved = entry.value.where((p) => !syncingProviders.contains(p)).toList();
if (preserved.isNotEmpty) newPlaylistSourceProviders[entry.key] = preserved;
}
}
// Clear old cache before saving fresh data (removes stale items)
await _db.clearCacheForType('album');
await _db.clearCacheForType('artist');
await _db.clearCacheForType('audiobook');
await _db.clearCacheForType('playlist');
// Collect all items (deduped by itemId, but tracking all source providers)
final albumMap = <String, Album>{};
final artistMap = <String, Artist>{};
final audiobookMap = <String, Audiobook>{};
final playlistMap = <String, Playlist>{};
// Save to database cache
await _saveAlbumsToCache(albums);
await _saveArtistsToCache(artists);
await _saveAudiobooksToCache(audiobooks);
await _savePlaylistsToCache(playlists);
// If specific providers are requested, sync each separately for accurate source tracking
if (providerInstanceIds != null && providerInstanceIds.isNotEmpty) {
_logger.log('🔒 Per-provider sync for ${providerInstanceIds.length} providers');
for (final providerId in providerInstanceIds) {
_logger.log(' 📡 Syncing provider: $providerId');
// Fetch from this specific provider
final results = await Future.wait([
api.getAlbums(limit: 1000, providerInstanceIds: [providerId]),
api.getArtists(limit: 1000, albumArtistsOnly: showOnlyArtistsWithAlbums, providerInstanceIds: [providerId]),
api.getAudiobooks(limit: 1000, providerInstanceIds: [providerId]),
api.getPlaylists(limit: 1000, providerInstanceIds: [providerId]),
]);
final albums = results[0] as List<Album>;
final artists = results[1] as List<Artist>;
final audiobooks = results[2] as List<Audiobook>;
final playlists = results[3] as List<Playlist>;
_logger.log(' 📥 Got ${albums.length} albums, ${artists.length} artists, ${audiobooks.length} audiobooks from $providerId');
// Add to maps and track source provider in NEW tracking maps
for (final album in albums) {
albumMap[album.itemId] = album;
newAlbumSourceProviders.putIfAbsent(album.itemId, () => []);
if (!newAlbumSourceProviders[album.itemId]!.contains(providerId)) {
newAlbumSourceProviders[album.itemId]!.add(providerId);
}
}
for (final artist in artists) {
artistMap[artist.itemId] = artist;
newArtistSourceProviders.putIfAbsent(artist.itemId, () => []);
if (!newArtistSourceProviders[artist.itemId]!.contains(providerId)) {
newArtistSourceProviders[artist.itemId]!.add(providerId);
}
}
for (final audiobook in audiobooks) {
audiobookMap[audiobook.itemId] = audiobook;
newAudiobookSourceProviders.putIfAbsent(audiobook.itemId, () => []);
if (!newAudiobookSourceProviders[audiobook.itemId]!.contains(providerId)) {
newAudiobookSourceProviders[audiobook.itemId]!.add(providerId);
}
}
for (final playlist in playlists) {
playlistMap[playlist.itemId] = playlist;
newPlaylistSourceProviders.putIfAbsent(playlist.itemId, () => []);
if (!newPlaylistSourceProviders[playlist.itemId]!.contains(providerId)) {
newPlaylistSourceProviders[playlist.itemId]!.add(providerId);
}
}
}
} else {
// No provider filter - fetch all at once (faster, but no source tracking)
_logger.log('📡 Fetching from all providers (no source tracking)');
final results = await Future.wait([
api.getAlbums(limit: 1000),
api.getArtists(limit: 1000, albumArtistsOnly: showOnlyArtistsWithAlbums),
api.getAudiobooks(limit: 1000),
api.getPlaylists(limit: 1000),
]);
for (final album in results[0] as List<Album>) {
albumMap[album.itemId] = album;
}
for (final artist in results[1] as List<Artist>) {
artistMap[artist.itemId] = artist;
}
for (final audiobook in results[2] as List<Audiobook>) {
audiobookMap[audiobook.itemId] = audiobook;
}
for (final playlist in results[3] as List<Playlist>) {
playlistMap[playlist.itemId] = playlist;
}
}
final albums = albumMap.values.toList();
final artists = artistMap.values.toList();
final audiobooks = audiobookMap.values.toList();
final playlists = playlistMap.values.toList();
_logger.log('📥 Total: ${albums.length} albums, ${artists.length} artists, '
'${audiobooks.length} audiobooks, ${playlists.length} playlists');
// Save to database cache with source provider info (using NEW tracking maps)
await _saveAlbumsToCache(albums, newAlbumSourceProviders);
await _saveArtistsToCache(artists, newArtistSourceProviders);
await _saveAudiobooksToCache(audiobooks, newAudiobookSourceProviders);
await _savePlaylistsToCache(playlists, newPlaylistSourceProviders);
// Update sync metadata
await _db.updateSyncMetadata('albums', albums.length);
@@ -190,14 +339,49 @@ class SyncService with ChangeNotifier {
await _db.updateSyncMetadata('playlists', playlists.length);
// Update in-memory cache
_cachedAlbums = albums;
_cachedArtists = artists;
_cachedAudiobooks = audiobooks;
_cachedPlaylists = playlists;
if (isPartialSync) {
// Partial sync: merge with existing cache to preserve items from disabled providers
final albumIds = albums.map((a) => a.itemId).toSet();
final artistIds = artists.map((a) => a.itemId).toSet();
final audiobookIds = audiobooks.map((a) => a.itemId).toSet();
final playlistIds = playlists.map((p) => p.itemId).toSet();
// Keep items not in current sync, add/update items from sync
_cachedAlbums = [
..._cachedAlbums.where((a) => !albumIds.contains(a.itemId)),
...albums,
];
_cachedArtists = [
..._cachedArtists.where((a) => !artistIds.contains(a.itemId)),
...artists,
];
_cachedAudiobooks = [
..._cachedAudiobooks.where((a) => !audiobookIds.contains(a.itemId)),
...audiobooks,
];
_cachedPlaylists = [
..._cachedPlaylists.where((p) => !playlistIds.contains(p.itemId)),
...playlists,
];
} else {
// Full sync: replace entire cache
_cachedAlbums = albums;
_cachedArtists = artists;
_cachedAudiobooks = audiobooks;
_cachedPlaylists = playlists;
}
// Atomically swap in the new source tracking maps
// This ensures filtering always sees complete data, never partial
_albumSourceProviders = newAlbumSourceProviders;
_artistSourceProviders = newArtistSourceProviders;
_audiobookSourceProviders = newAudiobookSourceProviders;
_playlistSourceProviders = newPlaylistSourceProviders;
_lastSyncTime = DateTime.now();
_status = SyncStatus.completed;
_logger.log('✅ Library sync complete');
_logger.log('📊 Source tracking: ${_albumSourceProviders.length} albums, ${_artistSourceProviders.length} artists, ${_audiobookSourceProviders.length} audiobooks have provider info');
} catch (e) {
_logger.log('❌ Library sync failed: $e');
_status = SyncStatus.error;
@@ -208,73 +392,90 @@ class SyncService with ChangeNotifier {
}
}
/// Save albums to database cache
Future<void> _saveAlbumsToCache(List<Album> albums) async {
/// Save albums to database cache with source provider tracking (batched)
Future<void> _saveAlbumsToCache(List<Album> albums, Map<String, List<String>> sourceProviders) async {
final batchItems = <BatchCacheItem>[];
for (final album in albums) {
try {
await _db.cacheItem(
itemType: 'album',
itemId: album.itemId,
data: album.toJson(),
);
} catch (e) {
_logger.log('⚠️ Failed to cache album ${album.name}: $e');
}
final providers = sourceProviders[album.itemId] ?? <String>[];
batchItems.add(BatchCacheItem(
itemType: 'album',
itemId: album.itemId,
data: jsonEncode(album.toJson()),
sourceProviders: providers,
));
}
try {
await _db.batchCacheItems(batchItems);
_logger.log('💾 Batch saved ${albums.length} albums to cache');
} catch (e) {
_logger.log('⚠️ Failed to batch cache albums: $e');
}
_logger.log('💾 Saved ${albums.length} albums to cache');
}
/// Save artists to database cache
Future<void> _saveArtistsToCache(List<Artist> artists) async {
/// Save artists to database cache with source provider tracking (batched)
Future<void> _saveArtistsToCache(List<Artist> artists, Map<String, List<String>> sourceProviders) async {
final batchItems = <BatchCacheItem>[];
for (final artist in artists) {
try {
await _db.cacheItem(
itemType: 'artist',
itemId: artist.itemId,
data: artist.toJson(),
);
} catch (e) {
_logger.log('⚠️ Failed to cache artist ${artist.name}: $e');
}
final providers = sourceProviders[artist.itemId] ?? <String>[];
batchItems.add(BatchCacheItem(
itemType: 'artist',
itemId: artist.itemId,
data: jsonEncode(artist.toJson()),
sourceProviders: providers,
));
}
try {
await _db.batchCacheItems(batchItems);
_logger.log('💾 Batch saved ${artists.length} artists to cache');
} catch (e) {
_logger.log('⚠️ Failed to batch cache artists: $e');
}
_logger.log('💾 Saved ${artists.length} artists to cache');
}
/// Save audiobooks to database cache
Future<void> _saveAudiobooksToCache(List<Audiobook> audiobooks) async {
/// Save audiobooks to database cache with source provider tracking (batched)
Future<void> _saveAudiobooksToCache(List<Audiobook> audiobooks, Map<String, List<String>> sourceProviders) async {
final batchItems = <BatchCacheItem>[];
for (final audiobook in audiobooks) {
try {
await _db.cacheItem(
itemType: 'audiobook',
itemId: audiobook.itemId,
data: audiobook.toJson(),
);
} catch (e) {
_logger.log('⚠️ Failed to cache audiobook ${audiobook.name}: $e');
}
final providers = sourceProviders[audiobook.itemId] ?? <String>[];
batchItems.add(BatchCacheItem(
itemType: 'audiobook',
itemId: audiobook.itemId,
data: jsonEncode(audiobook.toJson()),
sourceProviders: providers,
));
}
try {
await _db.batchCacheItems(batchItems);
_logger.log('💾 Batch saved ${audiobooks.length} audiobooks to cache');
} catch (e) {
_logger.log('⚠️ Failed to batch cache audiobooks: $e');
}
_logger.log('💾 Saved ${audiobooks.length} audiobooks to cache');
}
/// Save playlists to database cache
Future<void> _savePlaylistsToCache(List<Playlist> playlists) async {
/// Save playlists to database cache with source provider tracking (batched)
Future<void> _savePlaylistsToCache(List<Playlist> playlists, Map<String, List<String>> sourceProviders) async {
final batchItems = <BatchCacheItem>[];
for (final playlist in playlists) {
try {
await _db.cacheItem(
itemType: 'playlist',
itemId: playlist.itemId,
data: playlist.toJson(),
);
} catch (e) {
_logger.log('⚠️ Failed to cache playlist ${playlist.name}: $e');
}
final providers = sourceProviders[playlist.itemId] ?? <String>[];
batchItems.add(BatchCacheItem(
itemType: 'playlist',
itemId: playlist.itemId,
data: jsonEncode(playlist.toJson()),
sourceProviders: providers,
));
}
try {
await _db.batchCacheItems(batchItems);
_logger.log('💾 Batch saved ${playlists.length} playlists to cache');
} catch (e) {
_logger.log('⚠️ Failed to batch cache playlists: $e');
}
_logger.log('💾 Saved ${playlists.length} playlists to cache');
}
/// Force a fresh sync (for pull-to-refresh)
Future<void> forceSync(MusicAssistantAPI api) async {
await syncFromApi(api, force: true);
/// [providerInstanceIds] - optional list of provider IDs to filter by (null = all providers)
Future<void> forceSync(MusicAssistantAPI api, {List<String>? providerInstanceIds}) async {
await syncFromApi(api, force: true, providerInstanceIds: providerInstanceIds);
}
/// Clear all cached data
@@ -286,12 +487,82 @@ class SyncService with ChangeNotifier {
_cachedArtists = [];
_cachedAudiobooks = [];
_cachedPlaylists = [];
_albumSourceProviders = {};
_artistSourceProviders = {};
_audiobookSourceProviders = {};
_playlistSourceProviders = {};
_lastSyncTime = null;
_status = SyncStatus.idle;
notifyListeners();
_logger.log('🗑️ Library cache cleared');
}
// ============================================
// Client-side filtering methods
// ============================================
/// Filter albums by source provider (instant, no network)
/// Empty enabledProviderIds = all providers enabled, show everything
/// Items without source tracking are HIDDEN (strict mode) to ensure accurate filtering
List<Album> getAlbumsFilteredByProviders(Set<String> enabledProviderIds) {
// Empty set = all providers enabled, show everything
if (enabledProviderIds.isEmpty) {
return _cachedAlbums;
}
return _cachedAlbums.where((album) {
final sources = _albumSourceProviders[album.itemId];
// STRICT MODE: Hide items without tracking to ensure accurate filtering
if (sources == null || sources.isEmpty) return false;
return sources.any((s) => enabledProviderIds.contains(s));
}).toList();
}
/// Filter artists by source provider (instant, no network)
List<Artist> getArtistsFilteredByProviders(Set<String> enabledProviderIds) {
if (enabledProviderIds.isEmpty) {
return _cachedArtists;
}
return _cachedArtists.where((artist) {
final sources = _artistSourceProviders[artist.itemId];
// STRICT MODE: Hide items without tracking
if (sources == null || sources.isEmpty) return false;
return sources.any((s) => enabledProviderIds.contains(s));
}).toList();
}
/// Filter audiobooks by source provider (instant, no network)
List<Audiobook> getAudiobooksFilteredByProviders(Set<String> enabledProviderIds) {
if (enabledProviderIds.isEmpty) {
return _cachedAudiobooks;
}
return _cachedAudiobooks.where((audiobook) {
final sources = _audiobookSourceProviders[audiobook.itemId];
// STRICT MODE: Hide items without tracking
if (sources == null || sources.isEmpty) return false;
return sources.any((s) => enabledProviderIds.contains(s));
}).toList();
}
/// Filter playlists by source provider (instant, no network)
List<Playlist> getPlaylistsFilteredByProviders(Set<String> enabledProviderIds) {
if (enabledProviderIds.isEmpty) {
return _cachedPlaylists;
}
return _cachedPlaylists.where((playlist) {
final sources = _playlistSourceProviders[playlist.itemId];
// STRICT MODE: Hide items without tracking
if (sources == null || sources.isEmpty) return false;
return sources.any((s) => enabledProviderIds.contains(s));
}).toList();
}
/// Check if we have source provider tracking data
bool get hasSourceTracking =>
_albumSourceProviders.isNotEmpty ||
_artistSourceProviders.isNotEmpty ||
_audiobookSourceProviders.isNotEmpty ||
_playlistSourceProviders.isNotEmpty;
/// Get albums (from cache or empty if not loaded)
List<Album> getAlbums() => _cachedAlbums;
+19 -1
View File
@@ -129,13 +129,31 @@ class Durations {
class ButtonSizes {
ButtonSizes._();
// Touch target sizes (Material Design minimum: 48x48)
// Touch target sizes
// WCAG 2.1 Level AA requires minimum 44x44, Level AAA requires 48x48
// Material Design recommends 48x48 minimum
// WARNING: sm and md are below WCAG minimum - use only for non-interactive elements
/// 32x32 - NOT WCAG compliant, use only for decorative/non-interactive elements
@Deprecated('Use xl (48x48) for touch targets to meet WCAG accessibility guidelines')
static const double sm = 32.0;
/// 36x36 - NOT WCAG compliant, use only for dense layouts where space is critical
@Deprecated('Use xl (48x48) for touch targets to meet WCAG accessibility guidelines')
static const double md = 36.0;
/// 44x44 - Meets WCAG Level AA minimum
static const double lg = 44.0;
/// 48x48 - Meets WCAG Level AAA and Material Design recommended minimum
static const double xl = 48.0;
/// 56x56 - Comfortable touch target for primary actions
static const double xxl = 56.0;
/// Minimum WCAG-compliant touch target size (48x48)
static const double minAccessible = 48.0;
// Icon sizes within buttons
static const double iconSm = 16.0;
static const double iconMd = 18.0;
+46
View File
@@ -0,0 +1,46 @@
/// Extension methods for formatting Duration values.
///
/// Provides consistent duration formatting across the codebase,
/// replacing duplicate _formatDuration() implementations.
extension DurationFormatter on Duration {
/// Format duration as "H:MM:SS" or "M:SS" depending on length.
///
/// Examples:
/// - 45 seconds -> "0:45"
/// - 3 minutes, 45 seconds -> "3:45"
/// - 1 hour, 3 minutes, 45 seconds -> "1:03:45"
String toFormattedString() {
final hours = inHours;
final minutes = inMinutes % 60;
final seconds = inSeconds % 60;
if (hours > 0) {
return '$hours:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
}
return '$minutes:${seconds.toString().padLeft(2, '0')}';
}
/// Format duration as "M:SS" (no hours, minutes not padded).
///
/// Use this for shorter content like songs where hours are unlikely.
String toMinutesSeconds() {
final totalSeconds = inSeconds;
final minutes = totalSeconds ~/ 60;
final seconds = totalSeconds % 60;
return '$minutes:${seconds.toString().padLeft(2, '0')}';
}
}
/// Format an integer number of seconds as "H:MM:SS" or "M:SS".
///
/// This is a standalone function for cases where you have raw seconds
/// rather than a Duration object.
String formatDurationSeconds(int seconds) {
return Duration(seconds: seconds).toFormattedString();
}
/// Format a nullable Duration, returning empty string if null.
String formatDurationOrEmpty(Duration? duration) {
if (duration == null) return '';
return duration.toMinutesSeconds();
}
+139
View File
@@ -0,0 +1,139 @@
import 'dart:collection';
/// A simple Least Recently Used (LRU) cache implementation.
///
/// When the cache reaches its maximum size, the least recently used entries
/// are automatically evicted to make room for new entries.
///
/// Usage:
/// ```dart
/// final cache = LruCache<String, String>(maxSize: 100);
/// cache.put('key', 'value');
/// final value = cache.get('key');
/// ```
class LruCache<K, V> {
/// Maximum number of entries to store
final int maxSize;
/// Internal storage using LinkedHashMap for O(1) LRU operations
final LinkedHashMap<K, V> _cache = LinkedHashMap<K, V>();
/// Creates an LRU cache with the specified maximum size.
///
/// [maxSize] must be greater than 0.
LruCache({required this.maxSize}) : assert(maxSize > 0);
/// Returns the number of entries currently in the cache.
int get length => _cache.length;
/// Returns true if the cache is empty.
bool get isEmpty => _cache.isEmpty;
/// Returns true if the cache is not empty.
bool get isNotEmpty => _cache.isNotEmpty;
/// Returns true if the cache contains an entry for [key].
bool containsKey(K key) => _cache.containsKey(key);
/// Returns the value for [key], or null if not found.
///
/// This operation marks the entry as recently used.
V? get(K key) {
if (!_cache.containsKey(key)) {
return null;
}
// Move to end (most recently used) by removing and re-adding
final value = _cache.remove(key);
_cache[key] = value as V;
return value;
}
/// Returns the value for [key] without marking it as recently used.
///
/// Use this when you need to check a value without affecting LRU order.
V? peek(K key) => _cache[key];
/// Stores [value] for [key] in the cache.
///
/// If [key] already exists, the value is updated and marked as recently used.
/// If the cache is full, the least recently used entry is evicted.
void put(K key, V value) {
// If key exists, remove it first (will be re-added at end)
if (_cache.containsKey(key)) {
_cache.remove(key);
} else if (_cache.length >= maxSize) {
// Cache is full, remove least recently used (first entry)
_cache.remove(_cache.keys.first);
}
_cache[key] = value;
}
/// Operator access for getting values (same as [get]).
V? operator [](K key) => get(key);
/// Operator access for setting values (same as [put]).
void operator []=(K key, V value) => put(key, value);
/// Removes the entry for [key] if it exists.
///
/// Returns the removed value, or null if [key] was not in the cache.
V? remove(K key) => _cache.remove(key);
/// Removes all entries from the cache.
void clear() => _cache.clear();
/// Returns all keys currently in the cache.
Iterable<K> get keys => _cache.keys;
/// Returns all values currently in the cache.
Iterable<V> get values => _cache.values;
/// Returns all entries currently in the cache.
Iterable<MapEntry<K, V>> get entries => _cache.entries;
}
/// An LRU cache that can store null values and distinguish them from missing entries.
///
/// Regular LruCache returns null for both missing keys and keys with null values.
/// This class uses a wrapper to distinguish between the two cases.
class NullableLruCache<K, V> {
final LruCache<K, _CacheEntry<V>> _cache;
/// Creates a nullable LRU cache with the specified maximum size.
NullableLruCache({required int maxSize}) : _cache = LruCache(maxSize: maxSize);
/// Returns the number of entries currently in the cache.
int get length => _cache.length;
/// Returns true if the cache contains an entry for [key].
bool containsKey(K key) => _cache.containsKey(key);
/// Returns the value for [key], or null if not found.
///
/// Note: This will also return null if the cached value is null.
/// Use [containsKey] to distinguish between missing and null values.
V? get(K key) => _cache.get(key)?.value;
/// Stores [value] for [key] in the cache.
///
/// The value can be null.
void put(K key, V? value) => _cache.put(key, _CacheEntry(value));
/// Operator access for getting values.
V? operator [](K key) => get(key);
/// Operator access for setting values.
void operator []=(K key, V? value) => put(key, value);
/// Removes the entry for [key] if it exists.
V? remove(K key) => _cache.remove(key)?.value;
/// Removes all entries from the cache.
void clear() => _cache.clear();
}
/// Wrapper to store nullable values in the cache
class _CacheEntry<V> {
final V? value;
_CacheEntry(this.value);
}
+93 -75
View File
@@ -103,39 +103,48 @@ class EmptyState extends StatelessWidget {
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Center(
child: Padding(
padding: Spacing.paddingAll24,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
icon,
size: iconSize,
color: colorScheme.onSurface.withOpacity(0.38),
),
Spacing.vGap16,
Text(
message,
style: TextStyle(
color: colorScheme.onSurface.withOpacity(0.6),
fontSize: 16,
// Wrap in scrollable to allow PageView horizontal swipe detection
return LayoutBuilder(
builder: (context, constraints) => SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: ConstrainedBox(
constraints: BoxConstraints(minHeight: constraints.maxHeight),
child: Center(
child: Padding(
padding: Spacing.paddingAll24,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
icon,
size: iconSize,
color: colorScheme.onSurface.withOpacity(0.38),
),
Spacing.vGap16,
Text(
message,
style: TextStyle(
color: colorScheme.onSurface.withOpacity(0.6),
fontSize: 16,
),
textAlign: TextAlign.center,
),
if (actionLabel != null && onAction != null) ...[
Spacing.vGap24,
ElevatedButton.icon(
onPressed: onAction,
icon: const Icon(Icons.refresh_rounded),
label: Text(actionLabel!),
style: ElevatedButton.styleFrom(
backgroundColor: colorScheme.surfaceVariant,
foregroundColor: colorScheme.onSurfaceVariant,
),
),
],
],
),
textAlign: TextAlign.center,
),
if (actionLabel != null && onAction != null) ...[
Spacing.vGap24,
ElevatedButton.icon(
onPressed: onAction,
icon: const Icon(Icons.refresh_rounded),
label: Text(actionLabel!),
style: ElevatedButton.styleFrom(
backgroundColor: colorScheme.surfaceVariant,
foregroundColor: colorScheme.onSurfaceVariant,
),
),
],
],
),
),
),
);
@@ -162,51 +171,60 @@ class _CustomEmptyState extends EmptyState {
final colorScheme = Theme.of(context).colorScheme;
final s = S.of(context)!;
return Center(
child: Padding(
padding: Spacing.paddingAll24,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
icon,
size: iconSize,
color: colorScheme.onSurface.withOpacity(0.38),
// Wrap in scrollable to allow PageView horizontal swipe detection
return LayoutBuilder(
builder: (context, constraints) => SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: ConstrainedBox(
constraints: BoxConstraints(minHeight: constraints.maxHeight),
child: Center(
child: Padding(
padding: Spacing.paddingAll24,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
icon,
size: iconSize,
color: colorScheme.onSurface.withOpacity(0.38),
),
Spacing.vGap16,
Text(
title,
style: TextStyle(
color: colorScheme.onSurface.withOpacity(0.6),
fontSize: 16,
fontWeight: FontWeight.w500,
),
textAlign: TextAlign.center,
),
if (subtitle != null) ...[
Spacing.vGap8,
Text(
subtitle!,
style: TextStyle(
color: colorScheme.onSurface.withOpacity(0.4),
fontSize: 14,
),
textAlign: TextAlign.center,
),
],
if (onRefresh != null) ...[
Spacing.vGap24,
ElevatedButton.icon(
onPressed: onRefresh,
icon: const Icon(Icons.refresh_rounded),
label: Text(s.refresh),
style: ElevatedButton.styleFrom(
backgroundColor: colorScheme.surfaceVariant,
foregroundColor: colorScheme.onSurfaceVariant,
),
),
],
],
),
),
Spacing.vGap16,
Text(
title,
style: TextStyle(
color: colorScheme.onSurface.withOpacity(0.6),
fontSize: 16,
fontWeight: FontWeight.w500,
),
textAlign: TextAlign.center,
),
if (subtitle != null) ...[
Spacing.vGap8,
Text(
subtitle!,
style: TextStyle(
color: colorScheme.onSurface.withOpacity(0.4),
fontSize: 14,
),
textAlign: TextAlign.center,
),
],
if (onRefresh != null) ...[
Spacing.vGap24,
ElevatedButton.icon(
onPressed: onRefresh,
icon: const Icon(Icons.refresh_rounded),
label: Text(s.refresh),
style: ElevatedButton.styleFrom(
backgroundColor: colorScheme.surfaceVariant,
foregroundColor: colorScheme.onSurfaceVariant,
),
),
],
],
),
),
),
);
+10 -9
View File
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../l10n/app_localizations.dart';
import '../../services/debug_logger.dart';
import '../../theme/design_tokens.dart';
@@ -72,9 +73,9 @@ class DebugConsole extends StatelessWidget {
padding: EdgeInsets.zero,
minimumSize: const Size(40, 20),
),
child: const Text(
'Clear',
style: TextStyle(fontSize: 10, color: Colors.green),
child: Text(
S.of(context)!.clear,
style: const TextStyle(fontSize: 10, color: Colors.green),
),
),
],
@@ -86,17 +87,17 @@ class DebugConsole extends StatelessWidget {
if (logs.isNotEmpty) {
Clipboard.setData(ClipboardData(text: logs));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Logs copied to clipboard'),
SnackBar(
content: Text(S.of(context)!.logsCopied),
backgroundColor: Colors.green,
duration: Duration(seconds: 2),
duration: const Duration(seconds: 2),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('No logs to copy'),
duration: Duration(seconds: 2),
SnackBar(
content: Text(S.of(context)!.noLogsToCopy),
duration: const Duration(seconds: 2),
),
);
}
File diff suppressed because it is too large Load Diff
+132 -58
View File
@@ -93,8 +93,9 @@ class GlobalPlayerOverlay extends StatefulWidget {
State<GlobalPlayerOverlay> createState() => _GlobalPlayerOverlayState();
/// Collapse the player if it's expanded
static void collapsePlayer() {
globalPlayerKey.currentState?.collapse();
/// [withHaptic]: Set to false for Android back gesture (system provides haptic)
static void collapsePlayer({bool withHaptic = true}) {
globalPlayerKey.currentState?.collapse(withHaptic: withHaptic);
}
/// Force collapse player to mini state, instantly closing queue panel if open.
@@ -164,6 +165,21 @@ class GlobalPlayerOverlay extends StatefulWidget {
/// Check if the player reveal is currently visible
static bool get isPlayerRevealVisible =>
_overlayStateKey.currentState?._isRevealVisible ?? false;
/// Show player selector for a "Play On" action.
/// Instead of the default hints, shows a contextual hint like "Select player to play album".
/// When a player is tapped, calls onPlayerSelected instead of switching to that player.
static void showPlayerSelectorForAction({
required String contextHint,
required void Function(dynamic player) onPlayerSelected,
IconData? hintIcon,
}) {
_overlayStateKey.currentState?._showPlayerSelectorForAction(
contextHint: contextHint,
onPlayerSelected: onPlayerSelected,
hintIcon: hintIcon,
);
}
}
class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
@@ -208,6 +224,11 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
// Key for the reveal overlay
final _revealKey = GlobalKey<PlayerRevealOverlayState>();
// State for "Play On" action - stored here so it can be passed to PlayerRevealOverlay
void Function(dynamic player)? _pendingPlayerAction;
String? _pendingContextHint;
IconData? _pendingHintIcon;
@override
void initState() {
super.initState();
@@ -394,6 +415,7 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
void _hidePlayerReveal() {
if (!_isRevealVisible) return;
_bounceOffsetNotifier.value = 0;
_clearPendingAction(); // Clear pending action when overlay is dismissed
setState(() {
_isRevealVisible = false;
_isOnboardingReveal = false;
@@ -413,6 +435,29 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
_singleBounceController.forward();
}
/// Clear pending action state (called when overlay is dismissed)
void _clearPendingAction() {
_pendingPlayerAction = null;
_pendingContextHint = null;
_pendingHintIcon = null;
}
/// Show player selector for a "Play On" action.
/// Stores the pending action and shows the reveal overlay with context hint.
void _showPlayerSelectorForAction({
required String contextHint,
required void Function(dynamic player) onPlayerSelected,
IconData? hintIcon,
}) {
// Store pending action state
_pendingPlayerAction = onPlayerSelected;
_pendingContextHint = contextHint;
_pendingHintIcon = hintIcon;
// Show the reveal overlay
_showPlayerReveal();
}
/// End hint mode (called when user taps skip button)
void _endHintMode() {
if (!_isHintModeActive) return;
@@ -536,62 +581,76 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
}
final navSelectedColor = _cachedNavColor.getAdjustedColor(sourceColor, isDark);
return Container(
decoration: BoxDecoration(
color: navBgColor,
boxShadow: expansionState.progress < 0.5
? [
BoxShadow(
color: Colors.black.withOpacity(0.1),
blurRadius: 10,
offset: const Offset(0, -2),
// Fade out and slide down nav bar as player expands
// Use IgnorePointer when faded to prevent accidental taps
final navOpacity = (1.0 - expansionState.progress * 2).clamp(0.0, 1.0);
final navSlideDown = expansionState.progress * 20; // Slide down 20px as it fades
return IgnorePointer(
ignoring: navOpacity < 0.1,
child: Transform.translate(
offset: Offset(0, navSlideDown),
child: Opacity(
opacity: navOpacity,
child: Container(
decoration: BoxDecoration(
color: navBgColor,
boxShadow: expansionState.progress < 0.5
? [
BoxShadow(
color: Colors.black.withOpacity(0.1),
blurRadius: 10,
offset: const Offset(0, -2),
),
]
: null,
),
child: BottomNavigationBar(
currentIndex: navigationProvider.selectedIndex,
onTap: (index) {
if (GlobalPlayerOverlay.isPlayerExpanded) {
GlobalPlayerOverlay.collapsePlayer();
}
navigationProvider.navigatorKey.currentState?.popUntil((route) => route.isFirst);
if (index == 3) {
GlobalPlayerOverlay.hidePlayer();
} else if (navigationProvider.selectedIndex == 3) {
GlobalPlayerOverlay.showPlayer();
}
navigationProvider.setSelectedIndex(index);
},
backgroundColor: Colors.transparent,
selectedItemColor: navSelectedColor,
unselectedItemColor: colorScheme.onSurface.withOpacity(0.54),
elevation: 0,
type: BottomNavigationBarType.fixed,
selectedFontSize: 12,
unselectedFontSize: 12,
items: [
BottomNavigationBarItem(
icon: const Icon(Icons.home_outlined),
activeIcon: const Icon(Icons.home_rounded),
label: S.of(context)!.home,
),
]
: null,
),
child: BottomNavigationBar(
currentIndex: navigationProvider.selectedIndex,
onTap: (index) {
if (GlobalPlayerOverlay.isPlayerExpanded) {
GlobalPlayerOverlay.collapsePlayer();
}
navigationProvider.navigatorKey.currentState?.popUntil((route) => route.isFirst);
if (index == 3) {
GlobalPlayerOverlay.hidePlayer();
} else if (navigationProvider.selectedIndex == 3) {
GlobalPlayerOverlay.showPlayer();
}
navigationProvider.setSelectedIndex(index);
},
backgroundColor: Colors.transparent,
selectedItemColor: navSelectedColor,
unselectedItemColor: colorScheme.onSurface.withOpacity(0.54),
elevation: 0,
type: BottomNavigationBarType.fixed,
selectedFontSize: 12,
unselectedFontSize: 12,
items: [
BottomNavigationBarItem(
icon: const Icon(Icons.home_outlined),
activeIcon: const Icon(Icons.home_rounded),
label: S.of(context)!.home,
BottomNavigationBarItem(
icon: const Icon(Icons.library_music_outlined),
activeIcon: const Icon(Icons.library_music_rounded),
label: S.of(context)!.library,
),
BottomNavigationBarItem(
icon: const Icon(Icons.search_rounded),
activeIcon: const Icon(Icons.search_rounded),
label: S.of(context)!.search,
),
BottomNavigationBarItem(
icon: const Icon(Icons.settings_outlined),
activeIcon: const Icon(Icons.settings_rounded),
label: S.of(context)!.settings,
),
],
),
),
BottomNavigationBarItem(
icon: const Icon(Icons.library_music_outlined),
activeIcon: const Icon(Icons.library_music_rounded),
label: S.of(context)!.library,
),
BottomNavigationBarItem(
icon: const Icon(Icons.search_rounded),
activeIcon: const Icon(Icons.search_rounded),
label: S.of(context)!.search,
),
BottomNavigationBarItem(
icon: const Icon(Icons.settings_outlined),
activeIcon: const Icon(Icons.settings_rounded),
label: S.of(context)!.settings,
),
],
),
),
);
},
@@ -627,11 +686,15 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
duration: const Duration(seconds: 3),
curve: const Interval(0.67, 1.0, curve: Curves.easeOut),
builder: (context, opacity, child) {
// Use theme-appropriate background color for seamless transition
final isDark = Theme.of(context).brightness == Brightness.dark;
final backdropColor = isDark
? const Color(0xFF1a1a1a) // Dark theme background
: colorScheme.surface; // Light theme surface
return BackdropFilter(
filter: ImageFilter.blur(sigmaX: 8.0, sigmaY: 8.0),
child: Container(
// Use same dark color as connection screen for seamless transition
color: const Color(0xFF1a1a1a).withOpacity(opacity),
color: backdropColor.withOpacity(opacity),
),
);
},
@@ -727,6 +790,10 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
miniPlayerBottom: BottomSpacing.navBarHeight + MediaQuery.of(context).viewPadding.bottom + 12,
miniPlayerHeight: 64,
showOnboardingHints: _isOnboardingReveal,
// Pass pending action parameters for "Play On" functionality
onPlayerSelected: _pendingPlayerAction,
contextHint: _pendingContextHint,
contextHintIcon: _pendingHintIcon,
),
// Global player overlay - renders ON TOP so cards slide behind it
@@ -740,6 +807,13 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
builder: (context, state, child) {
// Only show player if connected and has a selected player
if (!state.isConnected || !state.hasPlayer) {
// Reset expansion state to prevent stale values from causing
// invisible/non-interactive nav bar when connection restores.
// This fixes a bug where expanded player state persisted after
// disconnect, making nav bar opacity=0 and ignoring taps.
if (playerExpansionNotifier.value.progress != 0.0) {
playerExpansionNotifier.value = PlayerExpansionState(0.0, null, null);
}
return const SizedBox.shrink();
}
+2 -13
View File
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import '../../providers/music_assistant_provider.dart';
import '../../models/media_item.dart' show Audiobook, Chapter;
import '../../theme/design_tokens.dart';
import '../../utils/duration_formatter.dart';
import '../common/empty_state.dart';
import '../../l10n/app_localizations.dart';
@@ -26,18 +27,6 @@ class ChaptersPanel extends StatelessWidget {
required this.onClose,
});
String _formatDuration(int seconds) {
final duration = Duration(seconds: seconds);
final hours = duration.inHours;
final minutes = duration.inMinutes % 60;
final secs = duration.inSeconds % 60;
if (hours > 0) {
return '${hours}:${minutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
}
return '${minutes}:${secs.toString().padLeft(2, '0')}';
}
@override
Widget build(BuildContext context) {
final chapters = audiobook?.chapters ?? [];
@@ -147,7 +136,7 @@ class ChaptersPanel extends StatelessWidget {
overflow: TextOverflow.ellipsis,
),
subtitle: Text(
_formatDuration(chapter.positionMs ~/ 1000),
formatDurationSeconds(chapter.positionMs ~/ 1000),
style: TextStyle(
color: textColor.withOpacity(0.5),
fontSize: 12,
+38 -12
View File
@@ -19,12 +19,25 @@ class PlayerRevealOverlay extends StatefulWidget {
final double miniPlayerHeight;
final bool showOnboardingHints; // Show additional hints for first-time users
/// Callback when player is selected for a pending action (e.g., "Play On").
/// If null, selecting a player just switches to that player.
final void Function(dynamic player)? onPlayerSelected;
/// Context hint to display instead of default hints (e.g., "Select player to play album").
final String? contextHint;
/// Icon for context hint (default: play_circle_outline).
final IconData? contextHintIcon;
const PlayerRevealOverlay({
super.key,
required this.onDismiss,
required this.miniPlayerBottom,
required this.miniPlayerHeight,
this.showOnboardingHints = false,
this.onPlayerSelected,
this.contextHint,
this.contextHintIcon,
});
@override
@@ -383,16 +396,21 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
padding: const EdgeInsets.only(bottom: 12),
child: Material(
type: MaterialType.transparency,
child: isOnboarding
? buildHintRow(Icons.touch_app_outlined, S.of(context)!.selectPlayerHint)
: Column(
mainAxisSize: MainAxisSize.min,
children: [
buildHintRow(Icons.lightbulb_outline, S.of(context)!.holdToSync),
const SizedBox(height: 4),
buildHintRow(Icons.lightbulb_outline, S.of(context)!.swipeToAdjustVolume),
],
),
child: widget.contextHint != null
? buildHintRow(
widget.contextHintIcon ?? Icons.play_circle_outline,
widget.contextHint!,
)
: 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),
],
),
),
),
);
@@ -436,7 +454,11 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
textColor: data.cardTextColor,
onTap: () {
HapticFeedback.mediumImpact();
maProvider.selectPlayer(data.player);
if (widget.onPlayerSelected != null) {
widget.onPlayerSelected!(data.player);
} else {
maProvider.selectPlayer(data.player);
}
dismiss();
},
onLongPress: () {
@@ -489,7 +511,11 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
textColor: data.cardTextColor,
onTap: () {
HapticFeedback.mediumImpact();
maProvider.selectPlayer(data.player);
if (widget.onPlayerSelected != null) {
widget.onPlayerSelected!(data.player);
} else {
maProvider.selectPlayer(data.player);
}
dismiss();
},
onLongPress: () {
+149 -42
View File
@@ -3,9 +3,11 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../l10n/app_localizations.dart';
import '../../providers/music_assistant_provider.dart';
import '../../models/player.dart';
import '../../theme/design_tokens.dart';
import '../../utils/duration_formatter.dart';
import '../common/empty_state.dart';
import '../global_player_overlay.dart';
@@ -26,8 +28,8 @@ class QueuePanel extends StatefulWidget {
final VoidCallback onRefresh;
final ValueChanged<bool>? onDraggingChanged;
final VoidCallback? onSwipeStart;
final ValueChanged<double>? onSwipeUpdate; // dx delta from start
final void Function(double velocity, double totalDx)? onSwipeEnd; // velocity and total displacement
final ValueChanged<double>? onSwipeUpdate; // dy delta from start (vertical swipe)
final void Function(double velocity, double totalDy)? onSwipeEnd; // velocity and total displacement (vertical)
const QueuePanel({
super.key,
@@ -54,6 +56,11 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
List<QueueItem> _items = [];
final GlobalKey _stackKey = GlobalKey();
// Scroll controller to track list position (for swipe-to-close only at top)
final ScrollController _scrollController = ScrollController();
bool _isAtTop = true;
bool _wasAtTopOnSwipeStart = true; // Capture at gesture start
// Transfer dropdown animation
late AnimationController _dropdownController;
bool _showingTransferDropdown = false;
@@ -99,6 +106,17 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
vsync: this,
duration: const Duration(milliseconds: 300),
);
// Track scroll position for swipe-to-close (only allowed at top)
_scrollController.addListener(_onScroll);
}
void _onScroll() {
final atTop = _scrollController.offset <= 0;
if (atTop != _isAtTop) {
setState(() {
_isAtTop = atTop;
});
}
}
@override
@@ -134,18 +152,13 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
@override
void dispose() {
_scrollController.removeListener(_onScroll);
_scrollController.dispose();
_dropdownController.dispose();
_pendingReorderTimer?.cancel();
super.dispose();
}
String _formatDuration(Duration? duration) {
if (duration == null) return '';
final totalSeconds = duration.inSeconds;
final minutes = totalSeconds ~/ 60;
final seconds = totalSeconds % 60;
return '$minutes:${seconds.toString().padLeft(2, '0')}';
}
void _handleDelete(QueueItem item, int index) async {
// Store item for potential rollback
@@ -162,9 +175,7 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
if (playerId != null) {
try {
await widget.maProvider.api?.queueCommandDeleteItem(playerId, item.queueItemId);
debugPrint('QueuePanel: Delete successful for ${item.track.name}');
} catch (e) {
debugPrint('QueuePanel: Error deleting queue item: $e');
// Rollback: re-insert the item or refresh from server
// Refresh is safer as queue may have changed
widget.onRefresh();
@@ -185,7 +196,6 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
try {
await widget.maProvider.api?.queueCommandClear(playerId);
} catch (e) {
debugPrint('QueuePanel: Error clearing queue: $e');
// Refresh to restore if failed
widget.onRefresh();
}
@@ -257,7 +267,7 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
child: Text(
'Transfer to...',
S.of(context)!.transferTo,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
@@ -271,7 +281,7 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
child: Text(
'No other players available',
S.of(context)!.noOtherPlayersAvailable,
style: TextStyle(color: menuTextColor.withOpacity(0.5), fontSize: 14),
),
)
@@ -346,7 +356,6 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
autoPlay: true,
);
debugPrint('QueuePanel: Queue transferred to ${targetPlayer.name}');
// Clear source player's track cache since its queue was transferred away
widget.maProvider.clearPlayerTrackCache(sourcePlayerId);
@@ -357,7 +366,7 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
// Switch to the target player - mini player will update to show new player
widget.maProvider.selectPlayer(targetPlayer);
} catch (e) {
debugPrint('QueuePanel: Error transferring queue: $e');
// Error transferring queue - handled silently
}
}
@@ -430,6 +439,29 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
return totalWeight > 0 ? totalVelocity / totalWeight : 0.0;
}
double _calculateAverageVelocityVertical() {
if (_velocitySamples.length < 2) return 0.0;
// Use weighted average of recent samples (more recent = higher weight)
double totalVelocity = 0.0;
double totalWeight = 0.0;
for (int i = 1; i < _velocitySamples.length; i++) {
final prev = _velocitySamples[i - 1];
final curr = _velocitySamples[i];
final dt = curr.timeMs - prev.timeMs;
if (dt > 0 && dt < 100) { // Only use samples within 100ms
final dy = curr.position.dy - prev.position.dy;
final velocity = (dy / dt) * 1000; // px/s
final weight = i.toDouble(); // Later samples get higher weight
totalVelocity += velocity * weight;
totalWeight += weight;
}
}
return totalWeight > 0 ? totalVelocity / totalWeight : 0.0;
}
void _startDrag(int index, BuildContext itemContext, Offset globalPosition) {
if (_dragIndex != null) return;
@@ -523,11 +555,9 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
final playerId = widget.queue?.playerId;
// API uses relative shift: positive = down, negative = up
final posShift = newIndex - originalIndex;
debugPrint('QueuePanel: Moving ${item.track.name} from $originalIndex to $newIndex (shift: $posShift, queueItemId: ${item.queueItemId})');
if (playerId != null) {
try {
await widget.maProvider.api?.queueCommandMoveItem(playerId, item.queueItemId, posShift);
debugPrint('QueuePanel: Move API call completed successfully');
// Allow updates again after a delay for server state to propagate
_pendingReorderTimer = Timer(const Duration(milliseconds: 2000), () {
if (mounted) {
@@ -537,7 +567,6 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
}
});
} catch (e) {
debugPrint('QueuePanel: Move API error: $e');
// Clear pending state immediately on error
if (mounted) {
setState(() {
@@ -548,7 +577,6 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
widget.onRefresh();
}
} else {
debugPrint('QueuePanel: playerId is null, cannot move');
// Clear pending state
if (mounted) {
setState(() {
@@ -595,7 +623,7 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
try {
await widget.maProvider.api?.queueCommandPlayIndex(playerId, item.queueItemId);
} catch (e) {
debugPrint('QueuePanel: Error playing index: $e');
// Error playing index - handled silently
}
// Clear optimistic state after delay - server state will take over
@@ -607,6 +635,64 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
}
}
void _handleMoveToPlayNext(QueueItem item, int index, bool isCurrentItem) async {
if (isCurrentItem) return;
final playerId = widget.queue?.playerId;
if (playerId == null) return;
// Get current index (where the currently playing track is)
final currentIndex = _optimisticCurrentIndex ?? widget.queue!.currentIndex ?? 0;
// Target position is right after the current track
final targetIndex = currentIndex + 1;
// If already at target position, nothing to do
if (index == targetIndex) {
// Haptic to confirm it's already in position
HapticFeedback.lightImpact();
return;
}
// Calculate the position shift for the API
final posShift = targetIndex - index;
// Cancel any existing timer to prevent stacking
_pendingReorderTimer?.cancel();
// Optimistic update - move item in local list
setState(() {
final movedItem = _items.removeAt(index);
_items.insert(targetIndex > index ? targetIndex - 1 : targetIndex, movedItem);
_pendingReorder = true;
});
// Haptic feedback
HapticFeedback.mediumImpact();
// Call API
try {
await widget.maProvider.api?.queueCommandMoveItem(playerId, item.queueItemId, posShift);
// Allow updates again after a delay for server state to propagate
_pendingReorderTimer = Timer(const Duration(milliseconds: 2000), () {
if (mounted) {
setState(() {
_pendingReorder = false;
});
}
});
} catch (e) {
// Clear pending state immediately on error
if (mounted) {
setState(() {
_pendingReorder = false;
});
}
// Refresh queue from server to get correct state
widget.onRefresh();
}
}
@override
Widget build(BuildContext context) {
// Use Listener for raw pointer events to bypass gesture arena
@@ -630,17 +716,19 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
_swipeLocked = false;
_velocitySamples.clear();
_addVelocitySample(event.position, _swipeLastTime!);
// Capture scroll position at gesture start - only allow close if already at top
_wasAtTopOnSwipeStart = _isAtTop;
} else if (startedInEdgeZone) {
// Clear swipe state for edge touches
_swipeStart = null;
}
},
onPointerMove: (event) {
// Ignore swipes from edge zone (let Android back gesture handle it)
// Ignore swipes while dragging a queue item
if (_swipeStart == null || _dragIndex != null) return;
final dx = event.position.dx - _swipeStart!.dx;
final dy = (event.position.dy - _swipeStart!.dy).abs();
final dx = (event.position.dx - _swipeStart!.dx).abs();
final dy = event.position.dy - _swipeStart!.dy;
final now = DateTime.now().millisecondsSinceEpoch;
// Track all move events for velocity calculation
@@ -650,31 +738,31 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
// Once direction is locked, maintain it (prevents accidental cancellation)
if (_swipeLocked && _isSwiping) {
widget.onSwipeUpdate?.call(dx.clamp(0.0, double.infinity));
widget.onSwipeUpdate?.call(dy.clamp(0.0, double.infinity));
return;
}
// Check if this is a horizontal swipe (reduced tolerance: dx > dy * 1.2)
final isHorizontal = dx.abs() > _swipeMinDistance && dx.abs() > dy * 1.2;
// Check if this is a vertical swipe (dy > dx * 1.2)
final isVertical = dy.abs() > _swipeMinDistance && dy.abs() > dx * 1.2;
if (isHorizontal && dx > 0) {
// Horizontal swipe right - close gesture
if (isVertical && dy > 0 && _wasAtTopOnSwipeStart) {
// Vertical swipe down - close gesture (only when was at top when gesture started)
if (!_isSwiping) {
_isSwiping = true;
_swipeLocked = true; // Lock direction once swipe starts
widget.onSwipeStart?.call();
}
widget.onSwipeUpdate?.call(dx);
} else if (!_swipeLocked && dx.abs() > _swipeMinDistance) {
// Direction established as vertical - don't start swipe
widget.onSwipeUpdate?.call(dy);
} else if (!_swipeLocked && dy.abs() > _swipeMinDistance) {
// Direction established as horizontal - don't start swipe
_swipeLocked = true; // Lock as non-swipe
}
},
onPointerUp: (event) {
if (_isSwiping && _swipeStart != null) {
final velocity = _calculateAverageVelocity();
final totalDx = event.position.dx - _swipeStart!.dx;
widget.onSwipeEnd?.call(velocity, totalDx);
final velocity = _calculateAverageVelocityVertical();
final totalDy = event.position.dy - _swipeStart!.dy;
widget.onSwipeEnd?.call(velocity, totalDy);
}
_resetSwipeState();
},
@@ -697,7 +785,7 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
child: Row(
children: [
IconButton(
icon: Icon(Icons.arrow_back_rounded, color: widget.textColor, size: IconSizes.md),
icon: Icon(Icons.keyboard_arrow_down_rounded, color: widget.textColor, size: IconSizes.lg),
onPressed: _showingTransferDropdown ? _closeTransferDropdown : widget.onClose,
padding: Spacing.paddingAll12,
),
@@ -720,14 +808,14 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
),
onPressed: () => _handleTransferQueue(context),
padding: Spacing.paddingAll12,
tooltip: 'Transfer queue to another player',
tooltip: S.of(context)!.transferQueueToPlayer,
),
// Clear queue button
IconButton(
icon: Icon(Icons.delete_sweep_rounded, color: widget.textColor.withOpacity(0.7), size: IconSizes.sm),
onPressed: _handleClearQueue,
padding: Spacing.paddingAll12,
tooltip: 'Clear queue',
tooltip: S.of(context)!.clearQueue,
),
],
),
@@ -834,6 +922,7 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
return ListView.builder(
key: const PageStorageKey('queue_list'),
controller: _scrollController,
padding: Spacing.paddingH8,
// Disable scrolling while dragging to prevent gesture conflict
physics: _dragIndex != null
@@ -857,8 +946,19 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
Widget _buildDismissibleItem(QueueItem item, int index, bool isCurrentItem, bool isPastItem) {
return Dismissible(
key: ValueKey(item.queueItemId),
direction: DismissDirection.endToStart,
direction: isCurrentItem ? DismissDirection.none : DismissDirection.horizontal,
// Swipe right (startToEnd) = move to play next
background: Container(
alignment: Alignment.centerLeft,
padding: const EdgeInsets.only(left: 20),
decoration: BoxDecoration(
color: widget.primaryColor,
borderRadius: BorderRadius.zero,
),
child: const Icon(Icons.skip_next_rounded, color: Colors.white, size: 28),
),
// Swipe left (endToStart) = delete
secondaryBackground: Container(
alignment: Alignment.centerRight,
padding: const EdgeInsets.only(right: 20),
decoration: BoxDecoration(
@@ -870,8 +970,15 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
confirmDismiss: (direction) async {
// Block dismissal if swipe started from screen edge (Android back gesture)
if (lastTouchWasInEdgeZone) return false;
// Don't allow dismissing the currently playing item
return !isCurrentItem;
if (direction == DismissDirection.startToEnd) {
// Swipe right = move to play next position
_handleMoveToPlayNext(item, index, isCurrentItem);
return false; // Don't dismiss - item stays in queue (just moved)
} else {
// Swipe left = delete
return true;
}
},
onDismissed: (direction) => _handleDelete(item, index),
child: _buildQueueItemWithDragHandle(item, index, isCurrentItem, isPastItem),
@@ -913,7 +1020,7 @@ class _QueuePanelState extends State<QueuePanel> with SingleTickerProviderStateM
Widget _buildQueueItemContent(QueueItem item, int index, bool isCurrentItem, bool isPastItem, {Widget? dragHandle}) {
final imageUrl = widget.maProvider.api?.getImageUrl(item.track, size: 80);
final duration = _formatDuration(item.track.duration);
final duration = formatDurationOrEmpty(item.track.duration);
return RepaintBoundary(
child: Opacity(
+1 -3
View File
@@ -245,14 +245,12 @@ class _PlayerSelectorSheetState extends State<_PlayerSelectorSheet> {
// Show snackbar for visual feedback
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Syncing ${player.name}...'),
content: Text(S.of(context)!.syncingPlayer(player.name)),
duration: const Duration(seconds: 2),
),
);
// Long-press to sync/unsync player
debugPrint('🔗 Long-press on ${player.name} (${player.playerId})');
debugPrint('🔗 Player isGrouped: ${player.isGrouped}, groupMembers: ${player.groupMembers}');
maProvider.togglePlayerSync(player.playerId);
},
borderRadius: BorderRadius.circular(16),
+1 -1
View File
@@ -1,7 +1,7 @@
name: ensemble
description: A minimalistic Music Assistant client built with Flutter
publish_to: 'none'
version: 2.8.8-beta+46
version: 2.9.0-beta+48
environment:
sdk: '>=3.0.0 <4.0.0'