fix(tvos): top shelf sync

This commit is contained in:
edde746
2026-06-09 08:06:42 +02:00
parent e02daa89b8
commit 726281ed44
4 changed files with 173 additions and 76 deletions
+25
View File
@@ -148,6 +148,8 @@ class _DiscoverScreenState extends State<DiscoverScreen>
LibrariesProvider? _librariesProvider;
Set<String> _lastSeenHiddenKeys = {};
List<String> _lastSeenLibraryOrderKeys = const [];
Future<void>? _systemShelfSyncFuture;
List<MediaItem>? _pendingSystemShelfItems;
// WatchStateAware: watch on-deck items and their parent shows/seasons
@override
@@ -548,6 +550,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
WidgetsBinding.instance.removeObserver(this);
_autoScrollTimer?.cancel();
_indicatorTimer?.cancel();
_pendingSystemShelfItems = null;
_indicatorProgress.dispose();
_heroController.dispose();
_scrollController.dispose();
@@ -902,6 +905,24 @@ class _DiscoverScreenState extends State<DiscoverScreen>
/// Sync Continue Watching items to the platform launcher shelf.
Future<void> _syncSystemShelf(List<MediaItem> onDeck) async {
_pendingSystemShelfItems = List<MediaItem>.unmodifiable(onDeck);
if (_systemShelfSyncFuture != null) {
await _systemShelfSyncFuture;
return;
}
final syncFuture = _drainSystemShelfSyncQueue();
_systemShelfSyncFuture = syncFuture;
await syncFuture;
}
Future<void> _drainSystemShelfSyncQueue() async {
try {
while (_pendingSystemShelfItems != null) {
final onDeck = _pendingSystemShelfItems!;
_pendingSystemShelfItems = null;
if (!mounted) return;
try {
await SystemShelfService().syncFromContinueWatching(
onDeck,
@@ -912,6 +933,10 @@ class _DiscoverScreenState extends State<DiscoverScreen>
appLogger.w('Failed to sync system shelf', error: e);
}
}
} finally {
_systemShelfSyncFuture = null;
}
}
// Public method to refresh content (for normal navigation)
@override
+34 -5
View File
@@ -18,6 +18,7 @@ import 'settings_service.dart' show EpisodePosterMode;
class SystemShelfService {
static const MethodChannel _androidChannel = MethodChannel('com.plezy/watch_next');
static const MethodChannel _tvosChannel = MethodChannel('com.plezy/system_shelf');
static const bool _tvosBuild = bool.fromEnvironment('TVOS_BUILD');
static final SystemShelfService _instance = SystemShelfService._internal();
factory SystemShelfService() => _instance;
@@ -32,7 +33,7 @@ class SystemShelfService {
MethodChannel? get _channel {
if (Platform.isAndroid) return _androidChannel;
if (Platform.isIOS && PlatformDetector.isAppleTV()) return _tvosChannel;
if (Platform.isIOS && (_tvosBuild || PlatformDetector.isAppleTV())) return _tvosChannel;
return null;
}
@@ -52,6 +53,9 @@ class SystemShelfService {
if (channel == null) return null;
try {
return await channel.invokeMethod<String>('getInitialDeepLink');
} on MissingPluginException catch (e) {
appLogger.w('System shelf initial deep link failed: native channel missing', error: e);
return null;
} catch (e) {
appLogger.w('Failed to get system shelf initial deep link', error: e);
return null;
@@ -64,7 +68,14 @@ class SystemShelfService {
if (channel == null) return false;
try {
return await channel.invokeMethod<bool>('isSupported') ?? false;
} catch (_) {
} on MissingPluginException catch (e) {
appLogger.w('System shelf unsupported: native channel missing', error: e);
return false;
} on PlatformException catch (e) {
appLogger.w('System shelf unsupported: native platform error', error: e);
return false;
} catch (e) {
appLogger.w('System shelf unsupported: native support check failed', error: e);
return false;
}
}
@@ -79,14 +90,20 @@ class SystemShelfService {
if (channel == null) return false;
try {
final supported = await isSupported();
if (!supported) return false;
final items = continueWatchingItems.map((item) {
return _convertToShelfItem(item, getClientForServerId, hideSpoilers: hideSpoilers);
}).toList();
final supported = await isSupported();
if (!supported) return false;
return await channel.invokeMethod<bool>('sync', {'items': items}) ?? false;
} on MissingPluginException catch (e) {
appLogger.e('Failed to sync system shelf: native channel missing', error: e);
return false;
} on PlatformException catch (e) {
appLogger.e('Failed to sync system shelf: native platform error', error: e);
return false;
} catch (e) {
appLogger.e('Failed to sync system shelf', error: e);
return false;
@@ -99,6 +116,12 @@ class SystemShelfService {
if (channel == null) return false;
try {
return await channel.invokeMethod<bool>('clear') ?? false;
} on MissingPluginException catch (e) {
appLogger.e('Failed to clear system shelf: native channel missing', error: e);
return false;
} on PlatformException catch (e) {
appLogger.e('Failed to clear system shelf: native platform error', error: e);
return false;
} catch (e) {
appLogger.e('Failed to clear system shelf', error: e);
return false;
@@ -112,6 +135,12 @@ class SystemShelfService {
try {
final contentId = _buildContentId(serverId, ratingKey);
return await channel.invokeMethod<bool>('remove', {'contentId': contentId}) ?? false;
} on MissingPluginException catch (e) {
appLogger.e('Failed to remove system shelf item: native channel missing', error: e);
return false;
} on PlatformException catch (e) {
appLogger.e('Failed to remove system shelf item: native platform error', error: e);
return false;
} catch (e) {
appLogger.e('Failed to remove system shelf item', error: e);
return false;
+57 -44
View File
@@ -7,7 +7,7 @@ import TVServices
final class SystemShelfPlugin: NSObject, FlutterPlugin {
private static let channelName = "com.plezy/system_shelf"
private static let appGroupIdentifier = "group.com.edde746.plezy"
private static let cacheFileName = "PlezySystemShelfCache.json"
private static let cacheDataKey = "PlezySystemShelfCacheData"
private static var pendingDeepLink: String?
private static var methodChannel: FlutterMethodChannel?
@@ -36,11 +36,7 @@ import TVServices
func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "isSupported":
let supported = Self.cacheURL != nil
if !supported {
Self.log("App Group container unavailable")
}
result(supported)
result(Self.sharedDefaults != nil)
case "sync":
guard let args = call.arguments as? [String: Any], let rawItems = args["items"] as? [[String: Any]] else {
result(FlutterError(code: "INVALID_ARGS", message: "Missing items", details: nil))
@@ -64,16 +60,8 @@ import TVServices
}
}
private static var appGroupContainerURL: URL? {
FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier)
}
private static var cacheURL: URL? {
appGroupContainerURL?.appendingPathComponent(cacheFileName, isDirectory: false)
}
private static func log(_ message: String) {
NSLog("PlezySystemShelf: %@", message)
private static var sharedDefaults: UserDefaults? {
UserDefaults(suiteName: appGroupIdentifier)
}
private static func normalizedItem(_ item: [String: Any]) -> [String: Any] {
@@ -99,61 +87,84 @@ import TVServices
}
private static func writePayload(_ payload: [String: Any]) -> Bool {
guard let url = cacheURL else {
log("Cannot write cache because App Group container is unavailable")
guard let defaults = sharedDefaults else {
return false
}
guard JSONSerialization.isValidJSONObject(payload),
let data = try? JSONSerialization.data(withJSONObject: payload)
else {
log("Cannot write cache because payload is not valid JSON")
let sanitizedPayload = sanitizedJSONObject(payload)
guard JSONSerialization.isValidJSONObject(sanitizedPayload) else {
return false
}
do {
try data.write(to: url, options: [.atomic])
let data = try JSONSerialization.data(withJSONObject: sanitizedPayload)
defaults.set(data, forKey: cacheDataKey)
defaults.synchronize()
} catch {
log("Failed to write cache: \(error)")
return false
}
let itemCount =
(payload["sections"] as? [[String: Any]])?.reduce(0) { count, section in
count + ((section["items"] as? [[String: Any]])?.count ?? 0)
} ?? 0
log("Wrote cache with \(itemCount) items")
TVTopShelfContentProvider.topShelfContentDidChange()
return true
}
private static func sanitizedJSONObject(_ object: [String: Any]) -> [String: Any] {
object.reduce(into: [String: Any]()) { result, entry in
if let value = sanitizedJSONValue(entry.value) {
result[entry.key] = value
}
}
}
private static func sanitizedJSONValue(_ value: Any) -> Any? {
if value is NSNull { return nil }
if let value = value as? String { return value }
if let value = value as? NSNumber {
if CFGetTypeID(value) == CFBooleanGetTypeID() { return value.boolValue }
return value.doubleValue.isFinite ? value : nil
}
if let value = value as? Bool { return value }
if let value = value as? Int { return value }
if let value = value as? Int64 { return value }
if let value = value as? Double { return value.isFinite ? value : nil }
if let value = value as? Float { return value.isFinite ? Double(value) : nil }
if let value = value as? [String: Any] {
return value.reduce(into: [String: Any]()) { result, entry in
if let nestedValue = sanitizedJSONValue(entry.value) {
result[entry.key] = nestedValue
}
}
}
if let value = value as? [Any] {
return value.compactMap { nestedValue in
sanitizedJSONValue(nestedValue)
}
}
return nil
}
private static func clearCache() -> Bool {
guard let url = cacheURL else {
log("Cannot clear cache because App Group container is unavailable")
guard let defaults = sharedDefaults else {
return false
}
do {
if FileManager.default.fileExists(atPath: url.path) {
try FileManager.default.removeItem(at: url)
}
} catch {
log("Failed to clear cache: \(error)")
return false
}
defaults.removeObject(forKey: cacheDataKey)
defaults.synchronize()
log("Cleared cache")
TVTopShelfContentProvider.topShelfContentDidChange()
return true
}
private static func removeItem(contentId: String) -> Bool {
guard let url = cacheURL,
let data = try? Data(contentsOf: url),
guard let defaults = sharedDefaults,
let data = defaults.data(forKey: cacheDataKey),
var payload = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let sections = payload["sections"] as? [[String: Any]]
else {
log("Cannot remove cache item because cache is unavailable or invalid")
return false
}
@@ -168,7 +179,9 @@ import TVServices
return nextSection
}
if !removed { return false }
if !removed {
return false
}
payload["updatedAt"] = Date().timeIntervalSince1970
payload["sections"] = filteredSections
return writePayload(payload)
+54 -24
View File
@@ -3,16 +3,10 @@ import TVServices
private enum TopShelfShared {
static let appGroupIdentifier = "group.com.edde746.plezy"
static let cacheFileName = "PlezySystemShelfCache.json"
static let cacheDataKey = "PlezySystemShelfCacheData"
static var cacheURL: URL? {
FileManager.default
.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier)?
.appendingPathComponent(cacheFileName, isDirectory: false)
}
static func log(_ message: String) {
NSLog("PlezyTopShelf: %@", message)
static var sharedDefaults: UserDefaults? {
UserDefaults(suiteName: appGroupIdentifier)
}
}
@@ -34,33 +28,72 @@ private struct TopShelfCachePayload: Decodable {
let lastPlaybackPosition: Double?
let seasonNumber: Int?
let episodeNumber: Int?
private enum CodingKeys: String, CodingKey {
case contentId
case title
case episodeTitle
case description
case posterUri
case type
case duration
case lastPlaybackPosition
case seasonNumber
case episodeNumber
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
contentId = try container.decode(String.self, forKey: .contentId)
title = try container.decode(String.self, forKey: .title)
episodeTitle = try container.decodeIfPresent(String.self, forKey: .episodeTitle)
description = try container.decodeIfPresent(String.self, forKey: .description)
posterUri = try container.decodeIfPresent(String.self, forKey: .posterUri)
type = try container.decodeIfPresent(String.self, forKey: .type)
duration = container.decodeFlexibleDoubleIfPresent(.duration)
lastPlaybackPosition = container.decodeFlexibleDoubleIfPresent(.lastPlaybackPosition)
seasonNumber = container.decodeFlexibleIntIfPresent(.seasonNumber)
episodeNumber = container.decodeFlexibleIntIfPresent(.episodeNumber)
}
}
let sections: [Section]
}
final class TopShelfProvider: TVTopShelfContentProvider {
override func loadTopShelfContent() async -> (any TVTopShelfContent)? {
buildContent()
}
private func buildContent() -> TVTopShelfContent? {
guard let url = TopShelfShared.cacheURL else {
TopShelfShared.log("App Group container unavailable")
private extension KeyedDecodingContainer {
func decodeFlexibleDoubleIfPresent(_ key: Key) -> Double? {
if let value = try? decodeIfPresent(Double.self, forKey: key) { return value }
if let value = try? decodeIfPresent(Int.self, forKey: key) { return Double(value) }
if let value = try? decodeIfPresent(String.self, forKey: key) { return Double(value) }
return nil
}
guard FileManager.default.fileExists(atPath: url.path) else {
TopShelfShared.log("Cache file missing")
func decodeFlexibleIntIfPresent(_ key: Key) -> Int? {
if let value = try? decodeIfPresent(Int.self, forKey: key) { return value }
if let value = try? decodeIfPresent(Double.self, forKey: key) { return Int(value) }
if let value = try? decodeIfPresent(String.self, forKey: key) { return Int(value) }
return nil
}
}
final class TopShelfProvider: TVTopShelfContentProvider {
override func loadTopShelfContent() async -> (any TVTopShelfContent)? {
return buildContent()
}
private func buildContent() -> TVTopShelfContent? {
guard let defaults = TopShelfShared.sharedDefaults else {
return nil
}
guard let data = defaults.data(forKey: TopShelfShared.cacheDataKey) else {
return nil
}
let payload: TopShelfCachePayload
do {
let data = try Data(contentsOf: url)
payload = try JSONDecoder().decode(TopShelfCachePayload.self, from: data)
} catch {
TopShelfShared.log("Failed to read cache: \(error)")
return nil
}
@@ -74,12 +107,9 @@ final class TopShelfProvider: TVTopShelfContentProvider {
}
guard !sections.isEmpty else {
TopShelfShared.log("Cache has no displayable items")
return nil
}
let itemCount = sections.reduce(0) { $0 + $1.items.count }
TopShelfShared.log("Loaded \(itemCount) items")
return TVTopShelfSectionedContent(sections: sections)
}