Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add Apple CarPlay support via flutter_carplay

Nathan Poulson2568d27cc64d
diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift
index 045a2d16..8f307118 100644
--- a/ios/Runner/AppDelegate.swift
+++ b/ios/Runner/AppDelegate.swift
@@ -4,12 +4,18 @@ import AVFoundation
import MediaPlayer
import just_audio
+let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadlessExecution: true)
+
@main
-@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
+@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
+ // Start the shared Flutter engine (used by both phone scene and CarPlay scene)
+ flutterEngine.run()
+ GeneratedPluginRegistrant.register(with: flutterEngine)
+
// Register for remote control events so lock screen / Control Center
// media controls appear. The audio_service plugin activates
// MPRemoteCommandCenter but doesn't call this, which can prevent
@@ -30,6 +36,9 @@ import just_audio
// work without opening the app.
registerWidgetNotifications()
+ // Register platform channels on the shared engine
+ registerPlatformChannels()
+
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
@@ -68,13 +77,30 @@ import just_audio
}
}
- func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
- GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
+ private func registerPlatformChannels() {
+ let messenger = flutterEngine.binaryMessenger
- guard let controller = window?.rootViewController as? FlutterViewController else { return }
+ let channel = FlutterMethodChannel(name: "com.absorb.audio_output",
+ binaryMessenger: messenger)
+ channel.setMethodCallHandler { [weak self] (call, result) in
+ switch call.method {
+ case "getAudioOutputDevices":
+ result(self?.getAudioOutputDevices() ?? [])
+ case "setAudioOutputDevice":
+ if let args = call.arguments as? [String: Any], let id = args["id"] as? Int {
+ result(self?.setAudioOutputDevice(portIndex: id) ?? false)
+ } else {
+ result(false)
+ }
+ case "resetAudioOutput":
+ result(self?.resetAudioOutput() ?? false)
+ default:
+ result(FlutterMethodNotImplemented)
+ }
+ }
let storageChannel = FlutterMethodChannel(name: "com.absorb.storage",
- binaryMessenger: controller.binaryMessenger)
+ binaryMessenger: messenger)
storageChannel.setMethodCallHandler { (call, result) in
switch call.method {
case "getDeviceStorage":
@@ -91,7 +117,7 @@ import just_audio
}
let widgetChannel = FlutterMethodChannel(name: "com.absorb.widget",
- binaryMessenger: controller.binaryMessenger)
+ binaryMessenger: messenger)
widgetChannel.setMethodCallHandler { (call, result) in
switch call.method {
case "getGroupContainerPath":
@@ -106,7 +132,7 @@ import just_audio
}
let eqChannel = FlutterMethodChannel(name: "com.absorb.equalizer",
- binaryMessenger: controller.binaryMessenger)
+ binaryMessenger: messenger)
eqChannel.setMethodCallHandler { [weak self] (call, result) in
let args = call.arguments as? [String: Any]
switch call.method {
diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist
index 3b724a22..c26b36c6 100644
--- a/ios/Runner/Info.plist
+++ b/ios/Runner/Info.plist
@@ -45,6 +45,17 @@
<string>Main</string>
</dict>
</array>
+ <key>CPTemplateApplicationSceneSessionRoleApplication</key>
+ <array>
+ <dict>
+ <key>UISceneClassName</key>
+ <string>CPTemplateApplicationScene</string>
+ <key>UISceneConfigurationName</key>
+ <string>CarPlay</string>
+ <key>UISceneDelegateClassName</key>
+ <string>flutter_carplay.FlutterCarPlaySceneDelegate</string>
+ </dict>
+ </array>
</dict>
</dict>
<key>UIApplicationSupportsIndirectInputEvents</key>
diff --git a/ios/Runner/Runner.entitlements b/ios/Runner/Runner.entitlements
index 416ca0e8..2f4f646b 100644
--- a/ios/Runner/Runner.entitlements
+++ b/ios/Runner/Runner.entitlements
@@ -6,5 +6,7 @@
<array>
<string>group.com.barnabas.absorb</string>
</array>
+ <key>com.apple.developer.carplay-audio</key>
+ <true/>
</dict>
</plist>
diff --git a/ios/Runner/SceneDelegate.swift b/ios/Runner/SceneDelegate.swift
index b9ce8ea2..3913d9d5 100644
--- a/ios/Runner/SceneDelegate.swift
+++ b/ios/Runner/SceneDelegate.swift
@@ -1,6 +1,17 @@
import Flutter
import UIKit
-class SceneDelegate: FlutterSceneDelegate {
+@available(iOS 13.0, *)
+class SceneDelegate: UIResponder, UIWindowSceneDelegate {
+ var window: UIWindow?
+ func scene(_ scene: UIScene, willConnectTo session: UISceneSession,
+ options connectionOptions: UIScene.ConnectionOptions) {
+ guard let windowScene = scene as? UIWindowScene else { return }
+ window = UIWindow(windowScene: windowScene)
+ let controller = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
+ controller.loadDefaultSplashScreenView()
+ window?.rootViewController = controller
+ window?.makeKeyAndVisible()
+ }
}
diff --git a/lib/main.dart b/lib/main.dart
index c95d9214..694ac31f 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -21,6 +21,7 @@ import 'services/sleep_timer_service.dart';
import 'services/scoped_prefs.dart';
import 'services/user_account_service.dart';
import 'services/android_auto_service.dart';
+import 'services/carplay_service.dart';
import 'services/chromecast_service.dart';
import 'services/home_widget_service.dart';
import 'services/log_service.dart';
@@ -493,6 +494,10 @@ class _AuthGateState extends State<AuthGate> {
// Pre-populate Android Auto browse tree in background.
Future.microtask(() => AndroidAutoService().refresh());
}
+ if (Platform.isIOS) {
+ // Initialize CarPlay browse tree.
+ CarPlayService().init();
+ }
if (Platform.isAndroid || Platform.isIOS) {
// Initialize homescreen widget
await HomeWidgetService().init();
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dart
index 4ae2e594..c5913a55 100644
--- a/lib/providers/_lp_core.dart
+++ b/lib/providers/_lp_core.dart
@@ -142,6 +142,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
_buildOfflineSections();
notifyListeners();
AndroidAutoService().refresh(force: true);
+ CarPlayService().refreshTemplates();
if (_deviceHasConnectivity && !_manualOffline) {
_startServerPingTimer();
}
@@ -160,6 +161,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
(this as LibraryProvider).refresh();
}
AndroidAutoService().refresh(force: true);
+ CarPlayService().refreshTemplates();
}
}
diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dart
index 657e68ad..cd04b78b 100644
--- a/lib/providers/auth_provider.dart
+++ b/lib/providers/auth_provider.dart
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../services/api_service.dart';
import '../services/android_auto_service.dart';
+import '../services/carplay_service.dart';
import '../services/audio_player_service.dart';
import '../services/session_cache.dart';
import '../services/socket_service.dart';
@@ -476,8 +477,9 @@ class AuthProvider extends ChangeNotifier {
}
} catch (_) {}
- // Clear Android Auto browse tree cache so it doesn't show stale data
+ // Clear Android Auto / CarPlay browse tree cache so it doesn't show stale data
AndroidAutoService().clearCache();
+ CarPlayService().clearAndRefresh();
// Clear cached session metadata for this user (track URLs would be invalid
// on next login anyway)
@@ -528,8 +530,9 @@ class AuthProvider extends ChangeNotifier {
}
} catch (_) {}
- // Clear Android Auto browse tree cache so it refreshes for the new user
+ // Clear Android Auto / CarPlay browse tree cache so it refreshes for the new user
AndroidAutoService().clearCache();
+ CarPlayService().clearAndRefresh();
// Set the new account as active in the account service
UserAccountService().switchTo(account.serverUrl, account.username);
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 6833f36a..59560773 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -11,6 +11,7 @@ import '../services/api_service.dart';
import '../services/progress_sync_service.dart';
import '../services/download_service.dart';
import '../services/android_auto_service.dart';
+import '../services/carplay_service.dart';
import '../services/chromecast_service.dart';
import '../services/bookmark_service.dart';
import '../services/session_cache.dart';
@@ -256,6 +257,7 @@ class LibraryProvider extends ChangeNotifier
notifyListeners();
await loadPersonalizedView(force: true);
AndroidAutoService().refresh(force: true);
+ CarPlayService().refreshTemplates();
}
diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dart
index 0a8ee35b..e86de86f 100644
--- a/lib/screens/app_shell.dart
+++ b/lib/screens/app_shell.dart
@@ -15,6 +15,7 @@ import '../main.dart'
show snappyTransitionsNotifier, coverSchemeNotifier, rootNavigatorKey;
import '../l10n/app_localizations.dart';
import '../services/android_auto_service.dart';
+import '../services/carplay_service.dart';
import '../widgets/expanded_card.dart';
import 'absorbing_screen.dart';
import 'home_screen.dart';
@@ -476,8 +477,9 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
if (_lastRefresh == null || now.difference(_lastRefresh!) > _refreshCooldown) {
_lastRefresh = now;
lib.refresh();
- // Keep Android Auto browse tree in sync
+ // Keep Android Auto / CarPlay browse tree in sync
AndroidAutoService().refresh();
+ CarPlayService().refreshTemplates();
}
}
diff --git a/lib/services/android_auto_service.dart b/lib/services/android_auto_service.dart
index 98168a09..b8b7093a 100644
--- a/lib/services/android_auto_service.dart
+++ b/lib/services/android_auto_service.dart
@@ -178,6 +178,11 @@ class AndroidAutoService {
List<AutoBookEntry> _downloaded = [];
List<AutoLibraryEntry> _libraries = [];
+ /// Public read-only access to cached data (used by CarPlayService)
+ List<AutoBookEntry> get continueListening => _continueListening;
+ List<AutoBookEntry> get downloaded => _downloaded;
+ List<AutoLibraryEntry> get libraries => _libraries;
+
DateTime? _lastRefresh;
bool _isRefreshing = false;
@@ -900,6 +905,208 @@ class AndroidAutoService {
return [];
}
+ // ─── Public data fetchers (used by CarPlayService) ─────────────────
+
+ /// Build an HTTP cover URL for use on iOS (CarPlay).
+ /// Android uses content:// URIs via CoverContentProvider; iOS loads HTTP directly.
+ Future<String?> getCoverHttpUrl(String itemId) async {
+ final api = await getApi();
+ if (api == null) return null;
+ return api.getCoverUrl(itemId);
+ }
+
+ /// Fetch books for a library, returning raw entries.
+ Future<List<AutoBookEntry>> fetchLibraryBooksData(String libraryId) async {
+ final api = await getApi();
+ if (api == null) return [];
+ try {
+ const maxItems = 200;
+ final allEntries = <AutoBookEntry>[];
+ int page = 0;
+ const pageSize = 100;
+ while (allEntries.length < maxItems) {
+ final result = await api.getLibraryItems(
+ libraryId, page: page, limit: pageSize,
+ sort: 'media.metadata.title', desc: 0,
+ );
+ if (result == null) break;
+ final entries = _resultsToEntries(result, api);
+ allEntries.addAll(entries);
+ final total = (result['total'] as num?)?.toInt() ?? 0;
+ if (allEntries.length >= total || entries.length < pageSize) break;
+ page++;
+ }
+ return allEntries.length > maxItems ? allEntries.sublist(0, maxItems) : allEntries;
+ } catch (e) {
+ debugPrint('[AndroidAuto] Error fetching library books data: $e');
+ return [];
+ }
+ }
+
+ /// Fetch series list for a library, returning id/name pairs.
+ Future<List<({String id, String name})>> fetchLibrarySeriesData(String libraryId) async {
+ final api = await getApi();
+ if (api == null) return [];
+ try {
+ final allSeries = <({String id, String name})>[];
+ int page = 0;
+ const pageSize = 100;
+ while (true) {
+ final result = await api.getLibrarySeries(
+ libraryId, page: page, limit: pageSize, sort: 'name', desc: 0,
+ );
+ if (result == null) break;
+ final seriesList = result['results'] as List<dynamic>? ?? [];
+ for (final s in seriesList) {
+ final sm = s as Map<String, dynamic>;
+ final sId = sm['id'] as String? ?? '';
+ final name = sm['name'] as String? ?? 'Unknown';
+ if (sId.isNotEmpty) allSeries.add((id: sId, name: name));
+ }
+ final total = (result['total'] as num?)?.toInt() ?? 0;
+ if (allSeries.length >= total || seriesList.length < pageSize) break;
+ page++;
+ }
+ return allSeries;
+ } catch (e) {
+ debugPrint('[AndroidAuto] Error fetching series data: $e');
+ return [];
+ }
+ }
+
+ /// Fetch authors list for a library, returning id/name pairs.
+ Future<List<({String id, String name})>> fetchLibraryAuthorsData(String libraryId) async {
+ final api = await getApi();
+ if (api == null) return [];
+ try {
+ final filterData = await api.getLibraryFilterData(libraryId);
+ if (filterData != null) {
+ final authorsList = filterData['authors'] as List<dynamic>? ?? [];
+ final items = authorsList.map((a) {
+ final am = a as Map<String, dynamic>;
+ final aId = am['id'] as String? ?? '';
+ final name = am['name'] as String? ?? 'Unknown';
+ return aId.isNotEmpty ? (id: aId, name: name) : null;
+ }).whereType<({String id, String name})>().toList();
+ items.sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
+ return items;
+ }
+ } catch (e) {
+ debugPrint('[AndroidAuto] Error fetching authors data: $e');
+ }
+ return [];
+ }
+
+ /// Fetch books in a series, returning raw entries.
+ Future<List<AutoBookEntry>> fetchSeriesBooksData(String seriesId, String libraryId) async {
+ final api = await getApi();
+ if (api == null) return [];
+ try {
+ final results = await api.getBooksBySeries(libraryId, seriesId);
+ return results
+ .whereType<Map<String, dynamic>>()
+ .map((item) => _libraryItemToEntry(item, api))
+ .whereType<AutoBookEntry>()
+ .toList();
+ } catch (e) {
+ debugPrint('[AndroidAuto] Error fetching series books data: $e');
+ return [];
+ }
+ }
+
+ /// Fetch books by an author, returning raw entries.
+ Future<List<AutoBookEntry>> fetchAuthorBooksData(String authorId, String libraryId) async {
+ final api = await getApi();
+ if (api == null) return [];
+ try {
+ final results = await api.getBooksByAuthor(libraryId, authorId);
+ return results
+ .whereType<Map<String, dynamic>>()
+ .map((item) => _libraryItemToEntry(item, api))
+ .whereType<AutoBookEntry>()
+ .toList();
+ } catch (e) {
+ debugPrint('[AndroidAuto] Error fetching author books data: $e');
+ return [];
+ }
+ }
+
+ /// Fetch podcast shows in a library, returning id/title pairs with cover URLs.
+ Future<List<({String id, String title, String? coverUrl})>> fetchPodcastShowsData(String libraryId) async {
+ final api = await getApi();
+ if (api == null) return [];
+ try {
+ const maxItems = 200;
+ final allShows = <({String id, String title, String? coverUrl})>[];
+ int page = 0;
+ const pageSize = 100;
+ while (allShows.length < maxItems) {
+ final result = await api.getLibraryItems(
+ libraryId, page: page, limit: pageSize,
+ sort: 'media.metadata.title', desc: 0,
+ );
+ if (result == null) break;
+ final results = result['results'] as List<dynamic>? ?? [];
+ for (final item in results) {
+ if (item is! Map<String, dynamic>) continue;
+ final id = item['id'] as String?;
+ if (id == null) continue;
+ final media = item['media'] as Map<String, dynamic>?;
+ final metadata = media?['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? 'Unknown';
+ allShows.add((id: id, title: title, coverUrl: api.getCoverUrl(id)));
+ }
+ final total = (result['total'] as num?)?.toInt() ?? 0;
+ if (allShows.length >= total || results.length < pageSize) break;
+ page++;
+ }
+ return allShows.length > maxItems ? allShows.sublist(0, maxItems) : allShows;
+ } catch (e) {
+ debugPrint('[AndroidAuto] Error fetching podcast shows data: $e');
+ return [];
+ }
+ }
+
+ /// Fetch episodes for a podcast show, returning raw entries.
+ Future<List<AutoBookEntry>> fetchShowEpisodesData(String showId, String libraryId) async {
+ final api = await getApi();
+ if (api == null) return [];
+ try {
+ final fullItem = await api.getLibraryItem(showId);
+ if (fullItem == null) return [];
+ final media = fullItem['media'] as Map<String, dynamic>?;
+ final metadata = media?['metadata'] as Map<String, dynamic>? ?? {};
+ final showTitle = metadata['title'] as String? ?? 'Podcast';
+ final episodes = media?['episodes'] as List<dynamic>? ?? [];
+ final sorted = List<dynamic>.from(episodes);
+ sorted.sort((a, b) {
+ final aTime = (a['publishedAt'] as num?)?.toInt() ?? 0;
+ final bTime = (b['publishedAt'] as num?)?.toInt() ?? 0;
+ return bTime.compareTo(aTime);
+ });
+ final entries = <AutoBookEntry>[];
+ for (final ep in sorted) {
+ if (ep is! Map<String, dynamic>) continue;
+ final epId = ep['id'] as String?;
+ if (epId == null) continue;
+ entries.add(AutoBookEntry(
+ id: '$showId-$epId',
+ title: ep['title'] as String? ?? 'Episode',
+ author: showTitle,
+ duration: (ep['duration'] as num?)?.toDouble() ?? 0,
+ coverUrl: api.getCoverUrl(showId),
+ chapters: ep['chapters'] as List<dynamic>? ?? [],
+ episodeId: epId,
+ showId: showId,
+ ));
+ }
+ return entries;
+ } catch (e) {
+ debugPrint('[AndroidAuto] Error fetching show episodes data: $e');
+ return [];
+ }
+ }
+
// ─── Search ────────────────────────────────────────────────────────
Future<List<MediaItem>> search(String query) async {
diff --git a/lib/services/carplay_service.dart b/lib/services/carplay_service.dart
new file mode 100644
index 00000000..3a700adb
--- /dev/null
+++ b/lib/services/carplay_service.dart
@@ -0,0 +1,325 @@
+import 'dart:io';
+import 'package:flutter/foundation.dart';
+import 'package:flutter_carplay/flutter_carplay.dart';
+import 'package:audio_service/audio_service.dart';
+import 'android_auto_service.dart';
+import 'api_service.dart';
+
+/// Manages Apple CarPlay browse tree and playback integration.
+/// Mirrors the Android Auto layout: 3 tabs (Continue, Library, Downloads)
+/// with hierarchical drilling into books/series/authors and podcasts.
+class CarPlayService {
+ static final CarPlayService _instance = CarPlayService._();
+ factory CarPlayService() => _instance;
+ CarPlayService._();
+
+ final _autoService = AndroidAutoService();
+ final _flutterCarplay = FlutterCarplay();
+ bool _initialized = false;
+
+ void init() {
+ if (!Platform.isIOS || _initialized) return;
+ _initialized = true;
+ _flutterCarplay.addListenerOnConnectionChange(_onConnectionChange);
+ debugPrint('[CarPlay] Initialized');
+ }
+
+ void dispose() {
+ _flutterCarplay.removeListenerOnConnectionChange();
+ }
+
+ void _onConnectionChange(ConnectionStatusTypes status) {
+ debugPrint('[CarPlay] Connection status: $status');
+ if (status == ConnectionStatusTypes.connected) {
+ _buildRootTemplate();
+ }
+ }
+
+ /// Clear cache and rebuild templates (e.g. on account switch).
+ Future<void> clearAndRefresh() async {
+ if (!_initialized) return;
+ await _autoService.refresh(force: true);
+ _buildRootTemplate();
+ }
+
+ /// Refresh CarPlay templates (e.g. after download completes).
+ void refreshTemplates() {
+ if (!_initialized) return;
+ _buildRootTemplate();
+ }
+
+ // ─── Root template ──────────────────────────────────────────────────
+
+ Future<void> _buildRootTemplate() async {
+ // Ensure data is populated
+ await _autoService.refresh();
+
+ final continueTab = await _buildContinueTab();
+ final libraryTab = await _buildLibraryTab();
+ final downloadsTab = await _buildDownloadsTab();
+
+ FlutterCarplay.setRootTemplate(
+ rootTemplate: CPTabBarTemplate(
+ templates: [continueTab, libraryTab, downloadsTab],
+ ),
+ );
+ debugPrint('[CarPlay] Root template set');
+ }
+
+ // ─── Continue Listening tab ─────────────────────────────────────────
+
+ Future<CPListTemplate> _buildContinueTab() async {
+ final api = await _autoService.getApi();
+ final entries = _autoService.continueListening;
+ final items = entries.map((e) => _playableListItem(e, api)).toList();
+ return CPListTemplate(
+ sections: [CPListSection(items: items)],
+ title: 'Continue',
+ systemIcon: 'play.circle.fill',
+ );
+ }
+
+ // ─── Library tab ────────────────────────────────────────────────────
+
+ Future<CPListTemplate> _buildLibraryTab() async {
+ final libs = _autoService.libraries;
+
+ // Single library: skip picker, show sub-categories or shows directly
+ if (libs.length == 1) {
+ final lib = libs.first;
+ if (lib.isPodcast) {
+ return _buildPodcastShowsList(lib.id, lib.name);
+ }
+ return _buildBookSubCategories(lib.id, 'Library');
+ }
+
+ // Multiple libraries: show library picker
+ final items = libs.map((lib) {
+ return CPListItem(
+ text: lib.name,
+ accessoryType: CPListItemAccessoryTypes.disclosureIndicator,
+ onPress: (complete, self) async {
+ if (lib.isPodcast) {
+ final template = await _buildPodcastShowsList(lib.id, lib.name);
+ FlutterCarplay.push(template: template);
+ } else {
+ final template = await _buildBookSubCategories(lib.id, lib.name);
+ FlutterCarplay.push(template: template);
+ }
+ complete();
+ },
+ );
+ }).toList();
+
+ return CPListTemplate(
+ sections: [CPListSection(items: items)],
+ title: 'Library',
+ systemIcon: 'books.vertical.fill',
+ );
+ }
+
+ // ─── Downloads tab ──────────────────────────────────────────────────
+
+ Future<CPListTemplate> _buildDownloadsTab() async {
+ final api = await _autoService.getApi();
+ final entries = _autoService.downloaded;
+ final items = entries.map((e) => _playableListItem(e, api)).toList();
+ return CPListTemplate(
+ sections: [CPListSection(items: items)],
+ title: 'Downloads',
+ systemIcon: 'arrow.down.circle.fill',
+ );
+ }
+
+ // ─── Book library sub-categories ───────────────────────────────────
+
+ Future<CPListTemplate> _buildBookSubCategories(String libraryId, String title) async {
+ final items = [
+ CPListItem(
+ text: 'Books',
+ accessoryType: CPListItemAccessoryTypes.disclosureIndicator,
+ onPress: (complete, self) async {
+ final template = await _buildBooksList(libraryId);
+ FlutterCarplay.push(template: template);
+ complete();
+ },
+ ),
+ CPListItem(
+ text: 'Series',
+ accessoryType: CPListItemAccessoryTypes.disclosureIndicator,
+ onPress: (complete, self) async {
+ final template = await _buildSeriesList(libraryId);
+ FlutterCarplay.push(template: template);
+ complete();
+ },
+ ),
+ CPListItem(
+ text: 'Authors',
+ accessoryType: CPListItemAccessoryTypes.disclosureIndicator,
+ onPress: (complete, self) async {
+ final template = await _buildAuthorsList(libraryId);
+ FlutterCarplay.push(template: template);
+ complete();
+ },
+ ),
+ ];
+
+ return CPListTemplate(
+ sections: [CPListSection(items: items)],
+ title: title,
+ systemIcon: 'books.vertical',
+ );
+ }
+
+ // ─── Books list ────────────────────────────────────────────────────
+
+ Future<CPListTemplate> _buildBooksList(String libraryId) async {
+ final api = await _autoService.getApi();
+ final entries = await _autoService.fetchLibraryBooksData(libraryId);
+ final items = entries.map((e) => _playableListItem(e, api)).toList();
+ return CPListTemplate(
+ sections: [CPListSection(items: items)],
+ title: 'Books',
+ systemIcon: 'book.fill',
+ );
+ }
+
+ // ─── Series list ───────────────────────────────────────────────────
+
+ Future<CPListTemplate> _buildSeriesList(String libraryId) async {
+ final seriesData = await _autoService.fetchLibrarySeriesData(libraryId);
+ final items = seriesData.map((s) {
+ return CPListItem(
+ text: s.name,
+ accessoryType: CPListItemAccessoryTypes.disclosureIndicator,
+ onPress: (complete, self) async {
+ final template = await _buildSeriesBooks(s.id, libraryId, s.name);
+ FlutterCarplay.push(template: template);
+ complete();
+ },
+ );
+ }).toList();
+
+ return CPListTemplate(
+ sections: [CPListSection(items: items)],
+ title: 'Series',
+ systemIcon: 'rectangle.stack.fill',
+ );
+ }
+
+ Future<CPListTemplate> _buildSeriesBooks(String seriesId, String libraryId, String title) async {
+ final api = await _autoService.getApi();
+ final entries = await _autoService.fetchSeriesBooksData(seriesId, libraryId);
+ final items = entries.map((e) => _playableListItem(e, api)).toList();
+ return CPListTemplate(
+ sections: [CPListSection(items: items)],
+ title: title,
+ systemIcon: 'rectangle.stack.fill',
+ );
+ }
+
+ // ─── Authors list ──────────────────────────────────────────────────
+
+ Future<CPListTemplate> _buildAuthorsList(String libraryId) async {
+ final authorsData = await _autoService.fetchLibraryAuthorsData(libraryId);
+ final items = authorsData.map((a) {
+ return CPListItem(
+ text: a.name,
+ accessoryType: CPListItemAccessoryTypes.disclosureIndicator,
+ onPress: (complete, self) async {
+ final template = await _buildAuthorBooks(a.id, libraryId, a.name);
+ FlutterCarplay.push(template: template);
+ complete();
+ },
+ );
+ }).toList();
+
+ return CPListTemplate(
+ sections: [CPListSection(items: items)],
+ title: 'Authors',
+ systemIcon: 'person.2.fill',
+ );
+ }
+
+ Future<CPListTemplate> _buildAuthorBooks(String authorId, String libraryId, String title) async {
+ final api = await _autoService.getApi();
+ final entries = await _autoService.fetchAuthorBooksData(authorId, libraryId);
+ final items = entries.map((e) => _playableListItem(e, api)).toList();
+ return CPListTemplate(
+ sections: [CPListSection(items: items)],
+ title: title,
+ systemIcon: 'person.fill',
+ );
+ }
+
+ // ─── Podcast shows ─────────────────────────────────────────────────
+
+ Future<CPListTemplate> _buildPodcastShowsList(String libraryId, String title) async {
+ final showsData = await _autoService.fetchPodcastShowsData(libraryId);
+ final items = showsData.map((s) {
+ return CPListItem(
+ text: s.title,
+ image: s.coverUrl,
+ accessoryType: CPListItemAccessoryTypes.disclosureIndicator,
+ onPress: (complete, self) async {
+ final template = await _buildShowEpisodes(s.id, libraryId, s.title);
+ FlutterCarplay.push(template: template);
+ complete();
+ },
+ );
+ }).toList();
+
+ return CPListTemplate(
+ sections: [CPListSection(items: items)],
+ title: title,
+ systemIcon: 'mic.fill',
+ );
+ }
+
+ Future<CPListTemplate> _buildShowEpisodes(String showId, String libraryId, String title) async {
+ final api = await _autoService.getApi();
+ final entries = await _autoService.fetchShowEpisodesData(showId, libraryId);
+ final items = entries.map((e) => _playableListItem(e, api)).toList();
+ return CPListTemplate(
+ sections: [CPListSection(items: items)],
+ title: title,
+ systemIcon: 'mic.fill',
+ );
+ }
+
+ // ─── Helpers ───────────────────────────────────────────────────────
+
+ /// Build a playable CPListItem from an AutoBookEntry.
+ CPListItem _playableListItem(AutoBookEntry entry, ApiService? api) {
+ // Use HTTP cover URL for iOS (CarPlay loads images from HTTP directly)
+ final coverItemId = entry.showId ?? entry.id;
+ final coverUrl = api?.getCoverUrl(coverItemId);
+
+ // Build the media ID matching the Android Auto scheme
+ final mediaId = (entry.episodeId != null && entry.showId != null)
+ ? AutoMediaIds.itemId('${entry.showId}-${entry.episodeId}')
+ : AutoMediaIds.itemId(entry.id);
+
+ return CPListItem(
+ text: entry.title,
+ detailText: entry.author.isNotEmpty ? entry.author : null,
+ image: coverUrl,
+ playbackProgress: _playbackProgress(entry),
+ onPress: (complete, self) {
+ _playItem(mediaId);
+ complete();
+ },
+ );
+ }
+
+ double _playbackProgress(AutoBookEntry entry) {
+ if (entry.currentTime == null || entry.duration <= 0) return 0;
+ return (entry.currentTime! / entry.duration).clamp(0.0, 1.0);
+ }
+
+ void _playItem(String mediaId) {
+ debugPrint('[CarPlay] Playing: $mediaId');
+ // Delegate to the audio handler which routes through _playFromAutoMediaId
+ AudioService.playFromMediaId(mediaId);
+ }
+}
diff --git a/pubspec.lock b/pubspec.lock
index 23f5d998..3e93a674 100644
--- a/pubspec.lock
+++ b/pubspec.lock
@@ -286,6 +286,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.4.1"
+ flutter_carplay:
+ dependency: "direct main"
+ description:
+ name: flutter_carplay
+ sha256: "134d5448a648573122af9d5a9e86c326f711150309eb518333a8bfad284604af"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.2.11"
flutter_chrome_cast:
dependency: "direct main"
description:
diff --git a/pubspec.yaml b/pubspec.yaml
index f1577f64..41221142 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -42,6 +42,9 @@ dependencies:
path: packages/just_audio
audio_service: ^0.18.13
+
+ # CarPlay
+ flutter_carplay: ^1.2.11
# Permissions
permission_handler: ^12.0.1