Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Enable Swift 6 for Cast and format its sources

Neeraj Gupta131e5a7ee53a
diff --git a/apple/apps/cast/Cast.xcodeproj/project.pbxproj b/apple/apps/cast/Cast.xcodeproj/project.pbxproj
index 866791175d..6b05845e64 100644
--- a/apple/apps/cast/Cast.xcodeproj/project.pbxproj
+++ b/apple/apps/cast/Cast.xcodeproj/project.pbxproj
@@ -456,7 +456,7 @@
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_EMIT_LOC_STRINGS = YES;
- SWIFT_VERSION = 5.0;
+ SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = 3;
};
name = Debug;
@@ -494,7 +494,7 @@
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "$(APP_STORE_PROFILE_SPECIFIER)";
SWIFT_EMIT_LOC_STRINGS = YES;
- SWIFT_VERSION = 5.0;
+ SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = 3;
};
name = Release;
@@ -511,7 +511,7 @@
PRODUCT_BUNDLE_IDENTIFIER = io.ente.photos.tv.castTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
- SWIFT_VERSION = 5.0;
+ SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = 3;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Cast.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Cast";
TVOS_DEPLOYMENT_TARGET = 18.4;
@@ -530,7 +530,7 @@
PRODUCT_BUNDLE_IDENTIFIER = io.ente.photos.tv.castTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
- SWIFT_VERSION = 5.0;
+ SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = 3;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Cast.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Cast";
TVOS_DEPLOYMENT_TARGET = 18.4;
@@ -548,7 +548,7 @@
PRODUCT_BUNDLE_IDENTIFIER = io.ente.photos.tv.castUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
- SWIFT_VERSION = 5.0;
+ SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = 3;
TEST_TARGET_NAME = Cast;
};
@@ -565,7 +565,7 @@
PRODUCT_BUNDLE_IDENTIFIER = io.ente.photos.tv.castUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
- SWIFT_VERSION = 5.0;
+ SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = 3;
TEST_TARGET_NAME = Cast;
};
diff --git a/apple/apps/cast/Cast/CastApp.swift b/apple/apps/cast/Cast/CastApp.swift
index 61536d7aa9..ca5e6261c3 100644
--- a/apple/apps/cast/Cast/CastApp.swift
+++ b/apple/apps/cast/Cast/CastApp.swift
@@ -15,11 +15,10 @@ struct CastApp: App {
private final class CastRustLogSink: RustLogSink, @unchecked Sendable {
func log(level: RustLogLevel, target: String, message: String) {
- let levelName: String
- switch level {
- case .error: levelName = "error"
- case .warn: levelName = "warn"
- case .info: levelName = "info"
+ let levelName = switch level {
+ case .error: "error"
+ case .warn: "warn"
+ case .info: "info"
}
print("[\(levelName)][rust][\(target)] \(message)")
}
diff --git a/apple/apps/cast/Cast/ContentView.swift b/apple/apps/cast/Cast/ContentView.swift
index 917c4e227f..7f91e29eaf 100644
--- a/apple/apps/cast/Cast/ContentView.swift
+++ b/apple/apps/cast/Cast/ContentView.swift
@@ -4,7 +4,7 @@ struct ContentView: View {
@StateObject private var viewModel = CastViewModel()
@State private var tapCount = 0
@State private var isConfiguringEndpoint = false
-
+
var body: some View {
ZStack {
switch viewModel.currentView {
@@ -12,32 +12,32 @@ struct ContentView: View {
StatusView(
status: .loading(viewModel.statusMessage),
onRetry: nil,
- debugLogs: nil
+ debugLogs: nil,
)
-
+
case .pairing:
PairingView(deviceCode: viewModel.deviceCode)
-
+
case .slideshow:
SlideshowView(
imageData: viewModel.currentImageData,
videoData: viewModel.currentVideoData,
isVideo: viewModel.currentFile?.isVideo ?? false,
- slideshowService: viewModel.slideshowService
+ slideshowService: viewModel.slideshowService,
)
-
+
case .error:
StatusView(
status: .error(viewModel.errorMessage ?? "Unknown error"),
onRetry: viewModel.retryOperation,
- debugLogs: nil
+ debugLogs: nil,
)
-
+
case .empty:
StatusView(
status: .empty("No photos were found in this album"),
onRetry: nil,
- debugLogs: nil
+ debugLogs: nil,
)
}
}
diff --git a/apple/apps/cast/Cast/Models/CastModels.swift b/apple/apps/cast/Cast/Models/CastModels.swift
index 1164c2dd12..180395f633 100644
--- a/apple/apps/cast/Cast/Models/CastModels.swift
+++ b/apple/apps/cast/Cast/Models/CastModels.swift
@@ -1,5 +1,5 @@
-import Foundation
import AVKit
+import Foundation
extension Notification.Name {
static let authenticationExpired = Notification.Name("authenticationExpired")
@@ -14,12 +14,12 @@ struct SlideConfiguration {
let maxImageSize: Int64
let maxVideoSize: Int64
let includeVideos: Bool
-
+
let prefetchCount: Int
let maxCacheSize: Int
let prefetchDelay: TimeInterval
let enablePrefetching: Bool
-
+
init(
imageDuration: TimeInterval = 12.0,
videoDuration: TimeInterval = 30.0,
@@ -31,7 +31,7 @@ struct SlideConfiguration {
prefetchCount: Int = 3,
maxCacheSize: Int = 5,
prefetchDelay: TimeInterval = 0.5,
- enablePrefetching: Bool = true
+ enablePrefetching: Bool = true,
) {
self.imageDuration = imageDuration
self.videoDuration = videoDuration
@@ -45,13 +45,13 @@ struct SlideConfiguration {
self.prefetchDelay = prefetchDelay
self.enablePrefetching = enablePrefetching
}
-
+
func duration(for file: CastFile) -> TimeInterval {
- return file.isVideo ? videoDuration : imageDuration
+ file.isVideo ? videoDuration : imageDuration
}
-
+
static let `default` = SlideConfiguration()
-
+
static let tvOptimized = SlideConfiguration(
imageDuration: 8.0,
videoDuration: 25.0,
@@ -63,7 +63,7 @@ struct SlideConfiguration {
prefetchCount: 3,
maxCacheSize: 5,
prefetchDelay: 0.5,
- enablePrefetching: true
+ enablePrefetching: true,
)
}
@@ -75,21 +75,31 @@ struct CastFile: Codable, Equatable {
let encryptedKey: String
let keyDecryptionNonce: String
let fileDecryptionHeader: String
- let hash: String? // BLAKE2b hash for file content verification
-
- var isImage: Bool { !isVideo && !isLivePhoto }
+ let hash: String? // BLAKE2b hash for file content verification
+
+ var isImage: Bool {
+ !isVideo && !isLivePhoto
+ }
}
struct FileMetadata {
- let fileType: Int // 0 = image, 1 = video, 2 = livePhoto
- let title: String // filename with extension
+ let fileType: Int // 0 = image, 1 = video, 2 = livePhoto
+ let title: String // filename with extension
let creationTime: Int64 // microseconds since epoch
let modificationTime: Int64
- let hash: String? // BLAKE2b hash for file content verification
-
- var isImage: Bool { fileType == 0 }
- var isVideo: Bool { fileType == 1 }
- var isLivePhoto: Bool { fileType == 2 }
+ let hash: String? // BLAKE2b hash for file content verification
+
+ var isImage: Bool {
+ fileType == 0
+ }
+
+ var isVideo: Bool {
+ fileType == 1
+ }
+
+ var isLivePhoto: Bool {
+ fileType == 2
+ }
}
enum CastSessionState: Equatable {
@@ -117,15 +127,15 @@ enum CastError: Error, LocalizedError {
case networkError(String)
case serverError(Int, String?)
case decryptionError(String)
-
+
var errorDescription: String? {
switch self {
- case .networkError(let message):
- return "Network error: \(message)"
- case .serverError(let code, let message):
- return "Server error \(code): \(message ?? "Unknown error")"
- case .decryptionError(let message):
- return "Decryption error: \(message)"
+ case let .networkError(message):
+ "Network error: \(message)"
+ case let .serverError(code, message):
+ "Server error \(code): \(message ?? "Unknown error")"
+ case let .decryptionError(message):
+ "Decryption error: \(message)"
}
}
}
diff --git a/apple/apps/cast/Cast/Services/APIEndpoint.swift b/apple/apps/cast/Cast/Services/APIEndpoint.swift
index fefb1f37aa..98dd5dfa84 100644
--- a/apple/apps/cast/Cast/Services/APIEndpoint.swift
+++ b/apple/apps/cast/Cast/Services/APIEndpoint.swift
@@ -3,11 +3,17 @@ import Foundation
enum APIEndpoint {
static let production = URL(string: "https://api.ente.com")!
- static var current: URL { UserDefaults.standard.url(forKey: "endpoint") ?? production }
+ static var current: URL {
+ UserDefaults.standard.url(forKey: "endpoint") ?? production
+ }
- static var isProduction: Bool { current == production }
+ static var isProduction: Bool {
+ current == production
+ }
- static func reset() { UserDefaults.standard.removeObject(forKey: "endpoint") }
+ static func reset() {
+ UserDefaults.standard.removeObject(forKey: "endpoint")
+ }
static func update(_ value: String) async throws {
let value = value.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -38,6 +44,8 @@ enum APIEndpoint {
private enum EndpointError: String, LocalizedError {
case invalidURL = "Enter a valid HTTPS API URL"
case invalidServer = "The URL is not an Ente API server"
- var errorDescription: String? { rawValue }
+ var errorDescription: String? {
+ rawValue
+ }
}
}
diff --git a/apple/apps/cast/Cast/Services/CastPairingService.swift b/apple/apps/cast/Cast/Services/CastPairingService.swift
index bd09a3b9f8..c04d1cfd67 100644
--- a/apple/apps/cast/Cast/Services/CastPairingService.swift
+++ b/apple/apps/cast/Cast/Services/CastPairingService.swift
@@ -1,31 +1,31 @@
-import SwiftUI
import Foundation
+import SwiftUI
@MainActor
class CastSession: ObservableObject {
@Published var state: CastSessionState = .idle
@Published var isActive: Bool = false
-
+
var deviceCode: String? {
- if case .waitingForPairing(let code) = state {
+ if case let .waitingForPairing(code) = state {
return code
}
return nil
}
-
+
var payload: CastPayload? {
- if case .connected(let payload) = state {
+ if case let .connected(payload) = state {
return payload
}
return nil
}
-
+
func setState(_ newState: CastSessionState) {
guard state != newState else { return }
state = newState
isActive = !isIdle
}
-
+
private var isIdle: Bool {
if case .idle = state {
return true
@@ -34,6 +34,7 @@ class CastSession: ObservableObject {
}
}
+@MainActor
class RealCastPairingService {
private let baseURL = APIEndpoint.current.absoluteString
private var pollingTimer: Timer?
@@ -45,130 +46,159 @@ class RealCastPairingService {
private let extendedPollingInterval: TimeInterval = 5.0
private let pollingIntervalSwitchTime: TimeInterval = 60.0
private var hasLoggedIntervalSwitch: Bool = false
-
+
private func getCurrentPollingInterval() -> TimeInterval {
guard let startTime = pollingStartTime else { return initialPollingInterval }
let elapsed = Date().timeIntervalSince(startTime)
- let newInterval = elapsed >= pollingIntervalSwitchTime ? extendedPollingInterval : initialPollingInterval
-
- if elapsed >= pollingIntervalSwitchTime && newInterval == extendedPollingInterval && !hasLoggedIntervalSwitch {
- print("Switched to extended polling interval (\(extendedPollingInterval)s) after \(Int(elapsed))s")
+ let newInterval = elapsed >= pollingIntervalSwitchTime ? extendedPollingInterval :
+ initialPollingInterval
+
+ if elapsed >= pollingIntervalSwitchTime, newInterval == extendedPollingInterval,
+ !hasLoggedIntervalSwitch
+ {
+ print(
+ "Switched to extended polling interval (\(extendedPollingInterval)s) after \(Int(elapsed))s",
+ )
hasLoggedIntervalSwitch = true
}
-
+
return newInterval
}
-
+
func registerDevice() async throws -> CastDevice {
let receiver = CastReceiver()
-
+
print("POST \(baseURL)/cast/device-info")
-
+
let url = URL(string: "\(baseURL)/cast/device-info")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
-
+
let requestBody = [
"publicKey": receiver.publicKey(),
"pqPublicKey": receiver.pqPublicKey(),
]
request.httpBody = try JSONSerialization.data(withJSONObject: requestBody)
-
+
let (data, response) = try await URLSession.shared.data(for: request)
-
+
guard let httpResponse = response as? HTTPURLResponse else {
throw CastError.networkError("Invalid response")
}
-
+
guard httpResponse.statusCode == 200 else {
- throw CastError.serverError(httpResponse.statusCode, String(data: data, encoding: .utf8))
+ throw CastError.serverError(
+ httpResponse.statusCode,
+ String(data: data, encoding: .utf8),
+ )
}
-
+
let deviceResponse = try JSONDecoder().decode(DeviceRegistrationResponse.self, from: data)
-
+
print("Device registered! Code from server: \(deviceResponse.deviceCode)")
-
+
return CastDevice(
deviceCode: deviceResponse.deviceCode,
- receiver: receiver
+ receiver: receiver,
)
}
-
- func startPolling(device: CastDevice, onPayloadReceived: @escaping (CastPayload) -> Void, onError: @escaping (Error) -> Void) {
+
+ func startPolling(
+ device: CastDevice,
+ onPayloadReceived: @escaping @MainActor (CastPayload) -> Void,
+ onError: @escaping @MainActor (Error) -> Void,
+ ) {
guard !hasDeliveredPayload else { return }
guard !isPolling else { return }
pollingTimer?.invalidate()
isPolling = true
pollingStartTime = Date()
hasLoggedIntervalSwitch = false
-
+
scheduleNextPoll(device: device, onPayloadReceived: onPayloadReceived, onError: onError)
}
-
- private func scheduleNextPoll(device: CastDevice, onPayloadReceived: @escaping (CastPayload) -> Void, onError: @escaping (Error) -> Void) {
- guard isPolling && !hasDeliveredPayload else { return }
-
+
+ private func scheduleNextPoll(
+ device: CastDevice,
+ onPayloadReceived: @escaping @MainActor (CastPayload) -> Void,
+ onError: @escaping @MainActor (Error) -> Void,
+ ) {
+ guard isPolling, !hasDeliveredPayload else { return }
+
let currentInterval = getCurrentPollingInterval()
- pollingTimer = Timer.scheduledTimer(withTimeInterval: currentInterval, repeats: false) { [weak self] _ in
- Task {
- await self?.checkForPayload(device: device, onPayloadReceived: onPayloadReceived, onError: onError)
- // Poll again only after this request finishes.
- await MainActor.run {
- self?.scheduleNextPoll(device: device, onPayloadReceived: onPayloadReceived, onError: onError)
+ pollingTimer = Timer
+ .scheduledTimer(withTimeInterval: currentInterval, repeats: false) { [weak self] _ in
+ Task { @MainActor in
+ await self?.checkForPayload(
+ device: device,
+ onPayloadReceived: onPayloadReceived,
+ onError: onError,
+ )
+ // Poll again only after this request finishes.
+ self?.scheduleNextPoll(
+ device: device,
+ onPayloadReceived: onPayloadReceived,
+ onError: onError,
+ )
}
}
- }
}
-
- private func checkForPayload(device: CastDevice, onPayloadReceived: @escaping (CastPayload) -> Void, onError: @escaping (Error) -> Void) async {
- if hasDeliveredPayload { return }
- if isFetchingPayload { return }
+
+ private func checkForPayload(
+ device: CastDevice,
+ onPayloadReceived: @escaping @MainActor (CastPayload) -> Void,
+ onError: @escaping @MainActor (Error) -> Void,
+ ) async {
+ if hasDeliveredPayload {
+ return
+ }
+ if isFetchingPayload {
+ return
+ }
isFetchingPayload = true
defer { isFetchingPayload = false }
do {
let url = URL(string: "\(baseURL)/cast/cast-data/\(device.deviceCode)")!
print("GET \(url.absoluteString)")
-
+
let (data, response) = try await URLSession.shared.data(from: url)
-
+
guard let httpResponse = response as? HTTPURLResponse else {
throw CastError.networkError("Invalid response")
}
-
+
if httpResponse.statusCode == 404 {
// 404 means no cast payload is available yet.
return
}
-
+
guard httpResponse.statusCode == 200 else {
- throw CastError.serverError(httpResponse.statusCode, String(data: data, encoding: .utf8))
+ throw CastError.serverError(
+ httpResponse.statusCode,
+ String(data: data, encoding: .utf8),
+ )
}
-
+
let castDataResponse = try JSONDecoder().decode(CastDataResponse.self, from: data)
-
+
guard let encryptedData = castDataResponse.encCastData else {
return
}
-
-
+
let payload = try device.receiver.openPayload(encryptedPayload: encryptedData)
-
+
hasDeliveredPayload = true
stopPolling()
-
- await MainActor.run {
- onPayloadReceived(payload)
- }
-
+
+ onPayloadReceived(payload)
+
} catch {
print("Polling error: \(error)")
- await MainActor.run {
- onError(error)
- }
+ onError(error)
}
}
-
+
func stopPolling() {
guard isPolling else { return }
pollingTimer?.invalidate()
@@ -176,5 +206,4 @@ class RealCastPairingService {
isPolling = false
pollingStartTime = nil
}
-
}
diff --git a/apple/apps/cast/Cast/Services/FileCache.swift b/apple/apps/cast/Cast/Services/FileCache.swift
index ae89faba53..42be579cb9 100644
--- a/apple/apps/cast/Cast/Services/FileCache.swift
+++ b/apple/apps/cast/Cast/Services/FileCache.swift
@@ -8,25 +8,62 @@ actor ThreadSafeFileCache {
private let shrinkTargetBytes: Int
private let cacheDirectory: URL
private let metadataURL: URL
-
+
init(maxBytes: Int, shrinkTargetBytes: Int) {
self.maxBytes = maxBytes
self.shrinkTargetBytes = shrinkTargetBytes
-
- let documentsPath = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
- self.cacheDirectory = documentsPath.appendingPathComponent("EnteFileCache")
- self.metadataURL = cacheDirectory.appendingPathComponent("cache_metadata.json")
-
- try? FileManager.default.createDirectory(at: cacheDirectory, withIntermediateDirectories: true)
-
- loadCacheFromDisk()
+
+ let documentsPath = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
+ .first!
+ cacheDirectory = documentsPath.appendingPathComponent("EnteFileCache")
+ metadataURL = cacheDirectory.appendingPathComponent("cache_metadata.json")
+
+ try? FileManager.default.createDirectory(
+ at: cacheDirectory,
+ withIntermediateDirectories: true,
+ )
+
+ guard let metadataData = try? Data(contentsOf: metadataURL),
+ let metadata = try? JSONDecoder().decode(CacheMetadata.self, from: metadataData)
+ else {
+ return
+ }
+
+ print("Loading existing cache from disk - \(metadata.fileIDs.count) files")
+
+ var loadedBytes = 0
+ var validFileIDs: [Int] = []
+
+ for fileID in metadata.fileIDs {
+ let fileURL = cacheDirectory.appendingPathComponent("\(fileID).cache")
+ if FileManager.default.fileExists(atPath: fileURL.path) {
+ if let attributes = try? FileManager.default.attributesOfItem(atPath: fileURL.path),
+ let fileSize = attributes[.size] as? Int
+ {
+ loadedBytes += fileSize
+ validFileIDs.append(fileID)
+ }
+ }
+ }
+
+ cacheOrder = validFileIDs
+ totalBytes = loadedBytes
+
+ print("Loaded \(validFileIDs.count) cached files (\(loadedBytes) bytes) from disk")
+
+ if validFileIDs.count != metadata.fileIDs.count {
+ let metadata = CacheMetadata(fileIDs: cacheOrder, totalBytes: totalBytes)
+ if let data = try? JSONEncoder().encode(metadata) {
+ try? data.write(to: metadataURL)
+ }
+ }
}
-
+
func get(_ fileID: Int) -> Data? {
if let data = cache[fileID] {
return data
}
-
+
let fileURL = cacheDirectory.appendingPathComponent("\(fileID).cache")
if let data = try? Data(contentsOf: fileURL) {
cache[fileID] = data
@@ -36,120 +73,93 @@ actor ThreadSafeFileCache {
totalBytes += data.count
return data
}
-
+
return nil
}
-
+
func set(_ fileID: Int, data: Data) {
if let existingData = cache[fileID] {
totalBytes -= existingData.count
cacheOrder.removeAll { $0 == fileID }
}
-
+
cache[fileID] = data
cacheOrder.append(fileID)
totalBytes += data.count
-
+
let fileURL = cacheDirectory.appendingPathComponent("\(fileID).cache")
try? data.write(to: fileURL)
-
+
enforceLimits()
-
+
saveCacheMetadata()
-
- print("Cached file \(fileID) content (\(data.count) bytes) - Cache size: \(cache.count) files")
+
+ print(
+ "Cached file \(fileID) content (\(data.count) bytes) - Cache size: \(cache.count) files",
+ )
}
-
+
func remove(_ fileID: Int) {
if let removedData = cache.removeValue(forKey: fileID) {
totalBytes -= removedData.count
cacheOrder.removeAll { $0 == fileID }
-
+
let fileURL = cacheDirectory.appendingPathComponent("\(fileID).cache")
try? FileManager.default.removeItem(at: fileURL)
-
+
saveCacheMetadata()
-
+
print("Removed cached content for file \(fileID) (\(removedData.count) bytes)")
}
}
-
+
func clear() {
let clearedCount = cache.count
cache.removeAll()
cacheOrder.removeAll()
totalBytes = 0
-
+
try? FileManager.default.removeItem(at: cacheDirectory)
- try? FileManager.default.createDirectory(at: cacheDirectory, withIntermediateDirectories: true)
-
+ try? FileManager.default.createDirectory(
+ at: cacheDirectory,
+ withIntermediateDirectories: true,
+ )
+
try? FileManager.default.removeItem(at: metadataURL)
-
+
print("Cleared file content cache (\(clearedCount) files)")
}
-
+
func getStats() -> (count: Int, totalSize: Int) {
- return (count: cache.count, totalSize: totalBytes)
+ (count: cache.count, totalSize: totalBytes)
}
-
+
func getCachedFileIDs() -> [Int] {
- return Array(cache.keys) + cacheOrder.filter { !cache.keys.contains($0) }
+ Array(cache.keys) + cacheOrder.filter { !cache.keys.contains($0) }
}
-
+
private func enforceLimits() {
guard totalBytes > maxBytes else { return }
-
+
var removedBytes = 0
while totalBytes - removedBytes > shrinkTargetBytes, let oldest = cacheOrder.first {
cacheOrder.removeFirst()
if let data = cache.removeValue(forKey: oldest) {
removedBytes += data.count
-
+
let fileURL = cacheDirectory.appendingPathComponent("\(oldest).cache")
try? FileManager.default.removeItem(at: fileURL)
-
+
print("Evicted file \(oldest) (\(data.count) bytes) to control cache size")
}
}
totalBytes -= removedBytes
-
+
saveCacheMetadata()
-
+
print("Cache GC complete: now \(cache.count) files, \(totalBytes) bytes")
}
-
- private func loadCacheFromDisk() {
- guard let metadataData = try? Data(contentsOf: metadataURL),
- let metadata = try? JSONDecoder().decode(CacheMetadata.self, from: metadataData) else {
- return
- }
-
- print("Loading existing cache from disk - \(metadata.fileIDs.count) files")
-
- var loadedBytes = 0
- var validFileIDs: [Int] = []
-
- for fileID in metadata.fileIDs {
- let fileURL = cacheDirectory.appendingPathComponent("\(fileID).cache")
- if FileManager.default.fileExists(atPath: fileURL.path) {
- if let attributes = try? FileManager.default.attributesOfItem(atPath: fileURL.path),
- let fileSize = attributes[.size] as? Int {
- loadedBytes += fileSize
- validFileIDs.append(fileID)
- }
- }
- }
-
- cacheOrder = validFileIDs
- totalBytes = loadedBytes
-
- print("Loaded \(validFileIDs.count) cached files (\(loadedBytes) bytes) from disk")
-
- if validFileIDs.count != metadata.fileIDs.count {
- saveCacheMetadata()
- }
- }
-
+
private func saveCacheMetadata() {
let metadata = CacheMetadata(fileIDs: cacheOrder, totalBytes: totalBytes)
if let data = try? JSONEncoder().encode(metadata) {
diff --git a/apple/apps/cast/Cast/Utils/FontUtils.swift b/apple/apps/cast/Cast/Utils/FontUtils.swift
index 6a9eec04d1..d00a7ec591 100644
--- a/apple/apps/cast/Cast/Utils/FontUtils.swift
+++ b/apple/apps/cast/Cast/Utils/FontUtils.swift
@@ -1,37 +1,40 @@
import SwiftUI
import UIKit
-struct FontUtils {
-
+enum FontUtils {
private static func safeFont(name: String, size: CGFloat, fallback: Font) -> Font {
if UIFont(name: name, size: size) != nil {
- return .custom(name, size: size)
+ .custom(name, size: size)
} else {
- return fallback
+ fallback
}
}
static func montserratBold(size: CGFloat) -> Font {
- return safeFont(name: "Montserrat-Bold", size: size, fallback: .system(size: size, weight: .bold))
+ safeFont(name: "Montserrat-Bold", size: size, fallback: .system(size: size, weight: .bold))
}
-
+
static func montserratExtraBold(size: CGFloat) -> Font {
- return safeFont(name: "Montserrat-Bold", size: size, fallback: .system(size: size, weight: .heavy))
+ safeFont(name: "Montserrat-Bold", size: size, fallback: .system(size: size, weight: .heavy))
}
-
+
static func interRegular(size: CGFloat) -> Font {
- return safeFont(name: "Inter-Regular", size: size, fallback: .system(size: size, weight: .regular))
+ safeFont(name: "Inter-Regular", size: size, fallback: .system(size: size, weight: .regular))
}
-
+
static func interMedium(size: CGFloat) -> Font {
- return safeFont(name: "Inter-Medium", size: size, fallback: .system(size: size, weight: .medium))
+ safeFont(name: "Inter-Medium", size: size, fallback: .system(size: size, weight: .medium))
}
-
+
static func interSemiBold(size: CGFloat) -> Font {
- return safeFont(name: "Inter-SemiBold", size: size, fallback: .system(size: size, weight: .semibold))
+ safeFont(
+ name: "Inter-SemiBold",
+ size: size,
+ fallback: .system(size: size, weight: .semibold),
+ )
}
-
+
static func interBold(size: CGFloat) -> Font {
- return safeFont(name: "Inter-Bold", size: size, fallback: .system(size: size, weight: .bold))
+ safeFont(name: "Inter-Bold", size: size, fallback: .system(size: size, weight: .bold))
}
}
diff --git a/apple/apps/cast/Cast/Utils/ScreenSaverManager.swift b/apple/apps/cast/Cast/Utils/ScreenSaverManager.swift
index 669d6822a3..9bb9f18802 100644
--- a/apple/apps/cast/Cast/Utils/ScreenSaverManager.swift
+++ b/apple/apps/cast/Cast/Utils/ScreenSaverManager.swift
@@ -25,8 +25,10 @@ class ScreenSaverManager: ObservableObject {
// Refresh because this setting is unreliable on some tvOS versions.
refreshTimer = Timer.scheduledTimer(withTimeInterval: 30.0, repeats: true) { _ in
- UIApplication.shared.isIdleTimerDisabled = false
- UIApplication.shared.isIdleTimerDisabled = true
+ MainActor.assumeIsolated {
+ UIApplication.shared.isIdleTimerDisabled = false
+ UIApplication.shared.isIdleTimerDisabled = true
+ }
}
}
diff --git a/apple/apps/cast/Cast/ViewModels/CastViewModel.swift b/apple/apps/cast/Cast/ViewModels/CastViewModel.swift
index 52966e3b93..8707d46e56 100644
--- a/apple/apps/cast/Cast/ViewModels/CastViewModel.swift
+++ b/apple/apps/cast/Cast/ViewModels/CastViewModel.swift
@@ -1,5 +1,5 @@
-import SwiftUI
import Combine
+import SwiftUI
import UIKit
@MainActor
@@ -17,7 +17,7 @@ class CastViewModel: ObservableObject {
private let castSession: CastSession
private var sessionID = UUID()
- public let slideshowService: RealSlideshowService
+ let slideshowService: RealSlideshowService
enum CurrentView {
case pairing
@@ -28,8 +28,8 @@ class CastViewModel: ObservableObject {
}
init() {
- self.castSession = CastSession()
- self.slideshowService = RealSlideshowService()
+ castSession = CastSession()
+ slideshowService = RealSlideshowService()
setupBindings()
startCastSession()
@@ -50,11 +50,11 @@ class CastViewModel: ObservableObject {
slideshowService.$currentImageData
.receive(on: DispatchQueue.main)
.sink { [weak self] data in
- guard let self = self else { return }
- if data != nil && (self.currentView == .connecting || self.currentView == .empty) {
- self.currentView = .slideshow
- self.statusMessage = ""
- self.errorMessage = nil
+ guard let self else { return }
+ if data != nil, currentView == .connecting || currentView == .empty {
+ currentView = .slideshow
+ statusMessage = ""
+ errorMessage = nil
}
}
.store(in: &cancellables)
@@ -66,11 +66,11 @@ class CastViewModel: ObservableObject {
slideshowService.$currentVideoData
.receive(on: DispatchQueue.main)
.sink { [weak self] data in
- guard let self = self else { return }
- if data != nil && (self.currentView == .connecting || self.currentView == .empty) {
- self.currentView = .slideshow
- self.statusMessage = ""
- self.errorMessage = nil
+ guard let self else { return }
+ if data != nil, currentView == .connecting || currentView == .empty {
+ currentView = .slideshow
+ statusMessage = ""
+ errorMessage = nil
}
}
.store(in: &cancellables)
@@ -82,7 +82,7 @@ class CastViewModel: ObservableObject {
slideshowService.$error
.receive(on: DispatchQueue.main)
- .compactMap { $0 }
+ .compactMap(\.self)
.sink { [weak self] error in
self?.handleSlideshowError(error)
}
@@ -155,7 +155,7 @@ class CastViewModel: ObservableObject {
guard let self, sessionID == self.sessionID else { return }
self.handleNetworkError(error)
}
- }
+ },
)
} catch {
@@ -193,7 +193,7 @@ class CastViewModel: ObservableObject {
}
private func handlePayloadReceived(_ payload: CastPayload) {
- if case .connected(let existing) = castSession.state, existing == payload {
+ if case let .connected(existing) = castSession.state, existing == payload {
return
}
@@ -260,15 +260,15 @@ class CastViewModel: ObservableObject {
deviceCode = ""
currentView = .pairing
- case .waitingForPairing(let code):
+ case let .waitingForPairing(code):
deviceCode = code
currentView = .pairing
statusMessage = "Waiting for connection..."
- case .connected(let payload):
+ case let .connected(payload):
handlePayloadReceived(payload)
- case .error(let message):
+ case let .error(message):
handleError(message)
}
}
@@ -281,7 +281,7 @@ class CastViewModel: ObservableObject {
error.contains("available in this collection") ||
error.contains("Empty file list")
- if (currentView == .pairing || currentView == .connecting) && !isEmptyStateError {
+ if currentView == .pairing || currentView == .connecting, !isEmptyStateError {
return
}
diff --git a/apple/apps/cast/Cast/ViewModels/SlideshowService.swift b/apple/apps/cast/Cast/ViewModels/SlideshowService.swift
index bb140eb2f7..a25bbbcceb 100644
--- a/apple/apps/cast/Cast/ViewModels/SlideshowService.swift
+++ b/apple/apps/cast/Cast/ViewModels/SlideshowService.swift
@@ -1,8 +1,8 @@
-import SwiftUI
import AVKit
import Foundation
-import ZIPFoundation
+import SwiftUI
import UIKit
+import ZIPFoundation
@MainActor
class RealSlideshowService: ObservableObject {
@@ -16,26 +16,26 @@ class RealSlideshowService: ObservableObject {
@Published var videoDuration: Double = 0
@Published var currentFile: CastFile?
@Published var error: String?
-
+
@Published var isPlaying: Bool = false
@Published var isPaused: Bool = false
@Published var slideLoadingProgress: Double = 0.0
@Published var currentSlideIndex: Int = 0
@Published var totalSlides: Int = 0
-
+
private var allFiles: [CastFile] = []
private var currentFileIndex: Int = 0
private var lastUpdateTime: Int64 = 0
private var isLoadingMore: Bool = false
private var hasCompletedInitialFetch: Bool = false
private var storedCastPayload: CastPayload?
-
+
private var diffPollingTimer: Timer?
private let diffPollingInterval: TimeInterval = 5.0
private var isPeriodicPollingEnabled: Bool = true
private var currentFileWasDeleted: Bool = false
private var isStopping: Bool = false
-
+
private var slideTimer: Timer?
private var prefetchCache: [Int: Data] = [:]
private var videoTempFiles: [Int: URL] = [:]
@@ -43,28 +43,28 @@ class RealSlideshowService: ObservableObject {
private var slideTimeRemaining: TimeInterval = 0
private var slidePauseTime: Date?
private var slideStartTime: Date?
-
+
private let fileCache = ThreadSafeFileCache(
maxBytes: 4096 * 1024 * 1024,
- shrinkTargetBytes: 2048 * 1024 * 1024
+ shrinkTargetBytes: 2048 * 1024 * 1024,
)
-
+
private var didDisplayFirstFile: Bool = false
-
+
private var baseURL = APIEndpoint.current.absoluteString
private let castDownloadURL = "https://cast-albums.ente.com/download"
-
+
private let verboseFileLogging = false
private let verboseDecryptionLogging = false
-
+
private var isHandlingAuthExpiry: Bool = false
-
+
func pause() {
slideTimer?.invalidate()
slideTimer = nil
isPlaying = false
isPaused = true
-
+
if let startTime = slideStartTime {
let elapsed = Date().timeIntervalSince(startTime)
let totalDuration = currentFile.map { slideshowConfiguration.duration(for: $0) } ?? 0
@@ -72,20 +72,20 @@ class RealSlideshowService: ObservableObject {
}
slidePauseTime = Date()
}
-
+
func resume() {
guard !allFiles.isEmpty else { return }
isPaused = false
isPlaying = true
slidePauseTime = nil
-
+
if slideTimeRemaining > 0 {
startSlideTimer(withDuration: slideTimeRemaining)
} else {
startSlideTimer()
}
}
-
+
func togglePlayPause() {
if isPaused || !isPlaying {
resume()
@@ -93,7 +93,7 @@ class RealSlideshowService: ObservableObject {
pause()
}
}
-
+
func nextSlide() async {
// Ignore timer callbacks after the session has been reset.
guard storedCastPayload != nil else { return }
@@ -103,9 +103,9 @@ class RealSlideshowService: ObservableObject {
}
return
}
-
+
if allFiles.count == 1 {
- if isPlaying && !isPaused {
+ if isPlaying, !isPaused {
startSlideTimer()
}
return
@@ -120,60 +120,60 @@ class RealSlideshowService: ObservableObject {
} else {
currentFileIndex = (currentFileIndex + 1) % allFiles.count
}
-
+
await displaySlideAtCurrentIndex()
- if isPlaying && !isPaused {
+ if isPlaying, !isPaused {
startSlideTimer()
}
}
-
+
func previousSlide() async {
guard !allFiles.isEmpty else { return }
currentFileIndex = currentFileIndex > 0 ? currentFileIndex - 1 : allFiles.count - 1
await displaySlideAtCurrentIndex()
- if isPlaying && !isPaused {
+ if isPlaying, !isPaused {
startSlideTimer()
}
}
-
+
func start(castPayload: CastPayload) async {
-
ScreenSaverManager.preventScreenSaver()
-
+
await clearExpiredTokenState()
baseURL = APIEndpoint.current.absoluteString
storedCastPayload = castPayload
- if error != nil { error = nil }
-
+ if error != nil {
+ error = nil
+ }
+
do {
-
await initializeFileList(castPayload: castPayload)
guard storedCastPayload == castPayload else { return }
-
+
let fileCount = await MainActor.run { allFiles.count }
if fileCount == 0 {
error = "No media files available in this album"
return
}
-
+
print("Found \(fileCount) files total")
-
- let validFileIDs = Set(await MainActor.run { allFiles.map { $0.id } })
+
+ let validFileIDs = await Set(MainActor.run { allFiles.map(\.id) })
await cleanupExpiredCache(validFileIDs: validFileIDs, castPayload: castPayload)
guard storedCastPayload == castPayload else { return }
-
+
totalSlides = fileCount
currentFileIndex = 0
currentSlideIndex = 0
isPlaying = true
isPaused = false
-
+
await displaySlideAtCurrentIndex()
guard storedCastPayload == castPayload else { return }
-
+
startSlideTimer()
print("Enhanced slideshow started with \(fileCount) slide(s)")
-
+
} catch {
print("Failed to start slideshow: \(error)")
await MainActor.run {
@@ -181,16 +181,15 @@ class RealSlideshowService: ObservableObject {
}
}
}
-
+
func stop() async {
-
ScreenSaverManager.allowScreenSaver()
-
+
await MainActor.run {
isStopping = true
stopPeriodicDiffPolling()
}
-
+
// A late timer callback would surface a false empty state.
slideTimer?.invalidate()
slideTimer = nil
@@ -203,20 +202,18 @@ class RealSlideshowService: ObservableObject {
livePhotoVideoData = nil
error = nil
}
-
-
+
let stats = await getCacheStats()
print("Final cache stats: \(stats.count) files, \(stats.totalSize) bytes")
-
+
await MainActor.run {
isStopping = false
}
}
-
+
func clearExpiredTokenState() async {
-
ScreenSaverManager.allowScreenSaver()
-
+
await MainActor.run {
// A late timer callback would surface a false empty state.
slideTimer?.invalidate()
@@ -235,19 +232,19 @@ class RealSlideshowService: ObservableObject {
}
// Preserve the cache across sessions.
}
-
+
@MainActor
private func initializeFileList(castPayload: CastPayload) async {
- if hasCompletedInitialFetch && !allFiles.isEmpty {
+ if hasCompletedInitialFetch, !allFiles.isEmpty {
print("Using cached file list with \(allFiles.count) files")
return
}
-
+
allFiles.removeAll()
lastUpdateTime = 0
currentFileIndex = 0
hasCompletedInitialFetch = false
-
+
do {
try await fetchAllFiles(castPayload: castPayload)
guard storedCastPayload == castPayload else { return }
@@ -263,139 +260,158 @@ class RealSlideshowService: ObservableObject {
self.error = "Failed to load files: \(error.localizedDescription)"
}
}
-
+
private func fetchAllFiles(castPayload: CastPayload) async throws {
var hasMore = true
var sinceTime = await MainActor.run { lastUpdateTime }
-
+
while hasMore {
- if verboseFileLogging { print("Fetching files since time: \(sinceTime)") }
+ if verboseFileLogging {
+ print("Fetching files since time: \(sinceTime)")
+ }
let result = try await fetchFilesBatch(castPayload: castPayload, sinceTime: sinceTime)
guard storedCastPayload == castPayload else { return }
-
+
await processDiffBatch(result.files, castPayload: castPayload)
guard storedCastPayload == castPayload else { return }
-
+
await MainActor.run {
if result.latestUpdateTime > self.lastUpdateTime {
- print("Initial fetch updating lastUpdateTime: \(self.lastUpdateTime) β†’ \(result.latestUpdateTime)")
+ print(
+ "Initial fetch updating lastUpdateTime: \(self.lastUpdateTime) β†’ \(result.latestUpdateTime)",
+ )
self.lastUpdateTime = result.latestUpdateTime
}
}
-
+
hasMore = result.hasMore
sinceTime = result.latestUpdateTime
-
}
-
+
guard storedCastPayload == castPayload else { return }
- print("Initial diff fetch complete - total files cached: \(await MainActor.run { allFiles.count })")
+ await print(
+ "Initial diff fetch complete - total files cached: \(MainActor.run { allFiles.count })",
+ )
startPeriodicDiffPolling()
}
-
- private func fetchFilesBatch(castPayload: CastPayload, sinceTime: Int64) async throws -> (files: [[String: Any]], hasMore: Bool, latestUpdateTime: Int64) {
+
+ private func fetchFilesBatch(castPayload: CastPayload,
+ sinceTime: Int64) async throws
+ -> (files: [[String: Any]], hasMore: Bool, latestUpdateTime: Int64)
+ {
guard storedCastPayload == castPayload else { throw CancellationError() }
let url = URL(string: "\(baseURL)/cast/diff?sinceTime=\(sinceTime)")!
-
-
+
var request = URLRequest(url: url)
request.setValue(castPayload.castToken, forHTTPHeaderField: "X-Cast-Access-Token")
-
+
let (data, response) = try await URLSession.shared.data(for: request)
guard storedCastPayload == castPayload else { throw CancellationError() }
-
+
guard let httpResponse = response as? HTTPURLResponse else {
throw CastError.networkError("Invalid response")
}
-
-
+
guard httpResponse.statusCode == 200 else {
if httpResponse.statusCode == 401 {
await handleUnauthorizedError()
- throw CastError.serverError(401, "Authentication expired - resetting to pairing mode")
+ throw CastError.serverError(
+ 401,
+ "Authentication expired - resetting to pairing mode",
+ )
}
- throw CastError.serverError(httpResponse.statusCode, String(data: data, encoding: .utf8))
+ throw CastError.serverError(
+ httpResponse.statusCode,
+ String(data: data, encoding: .utf8),
+ )
}
-
+
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
- let diff = json["diff"] as? [[String: Any]] else {
+ let diff = json["diff"] as? [[String: Any]]
+ else {
throw CastError.networkError("Invalid JSON response")
}
-
+
let hasMore = json["hasMore"] as? Bool ?? false
-
+
var latestUpdateTime = sinceTime
for item in diff {
if let updateTime = item["updationTime"] as? Int64 {
latestUpdateTime = max(latestUpdateTime, updateTime)
}
}
-
-
-
+
return (files: diff, hasMore: hasMore, latestUpdateTime: latestUpdateTime)
}
-
+
@MainActor
private func processDiffBatch(_ items: [[String: Any]], castPayload: CastPayload) async {
let wasEmpty = allFiles.isEmpty
var currentFileChanged = false
- let originalCurrentFile = currentFileIndex < allFiles.count ? allFiles[currentFileIndex] : nil
-
+ let originalCurrentFile = currentFileIndex < allFiles
+ .count ? allFiles[currentFileIndex] : nil
+
for item in items {
guard storedCastPayload == castPayload else { return }
guard let id = item["id"] as? Int else {
continue
}
-
+
let isDeleted = item["isDeleted"] as? Bool ?? false
-
+
if isDeleted {
if let index = allFiles.firstIndex(where: { $0.id == id }) {
let removedFile = allFiles.remove(at: index)
print("Removed deleted file: \(removedFile.title) (ID: \(id))")
-
+
if originalCurrentFile?.id == id {
currentFileWasDeleted = true
-
+
Task {
guard self.storedCastPayload == castPayload else { return }
await self.nextSlide()
}
}
-
- if index < currentFileIndex && currentFileIndex > 0 {
+
+ if index < currentFileIndex, currentFileIndex > 0 {
currentFileIndex -= 1
- } else if index == currentFileIndex && currentFileIndex >= allFiles.count && !allFiles.isEmpty {
+ } else if index == currentFileIndex, currentFileIndex >= allFiles.count,
+ !allFiles.isEmpty
+ {
currentFileIndex = 0
}
-
+
prefetchCache.removeValue(forKey: id)
await removeCachedFileContent(fileID: id)
-
+
} else {
print("Skipping deleted file \(id) (not in list)")
}
} else {
do {
- if let file = try await decryptFileMetadata(item: item, collectionKey: castPayload.collectionKey) {
+ if let file = try await decryptFileMetadata(
+ item: item,
+ collectionKey: castPayload.collectionKey,
+ ) {
guard storedCastPayload == castPayload else { return }
// Cast images and Live Photos, not standalone videos.
- if file.isVideo && !file.isLivePhoto {
- if verboseFileLogging { print("Skipping video file: \(file.title) (ID: \(id))") }
+ if file.isVideo, !file.isLivePhoto {
+ if verboseFileLogging {
+ print("Skipping video file: \(file.title) (ID: \(id))")
+ }
continue
}
if let existingIndex = allFiles.firstIndex(where: { $0.id == id }) {
let oldFile = allFiles[existingIndex]
allFiles[existingIndex] = file
print("Updated file: \(file.title) (ID: \(id))")
-
- if oldFile.hash != file.hash && file.hash != nil {
+
+ if oldFile.hash != file.hash, file.hash != nil {
print("Hash changed for file \(id) - clearing cache")
prefetchCache.removeValue(forKey: id)
await removeCachedFileContent(fileID: id)
}
-
+
if existingIndex == currentFileIndex {
currentFileChanged = true
}
@@ -410,9 +426,9 @@ class RealSlideshowService: ObservableObject {
}
}
guard storedCastPayload == castPayload else { return }
-
+
print("File list now contains \(allFiles.count) files")
-
+
if allFiles.isEmpty {
slideTimer?.invalidate()
slideTimer = nil
@@ -430,12 +446,12 @@ class RealSlideshowService: ObservableObject {
currentFileIndex = 0
currentSlideIndex = 0
totalSlides = allFiles.count
-
+
if storedCastPayload != nil {
print("Restarting slideshow with \(allFiles.count) files")
// Clear before loading to avoid an empty-state flash.
error = nil
-
+
Task {
guard storedCastPayload == castPayload else { return }
await displaySlideAtCurrentIndex()
@@ -450,12 +466,12 @@ class RealSlideshowService: ObservableObject {
}
} else {
totalSlides = allFiles.count
-
+
if currentFileIndex >= allFiles.count {
currentFileIndex = 0
}
-
- if currentFileChanged && !allFiles.isEmpty {
+
+ if currentFileChanged, !allFiles.isEmpty {
Task {
guard storedCastPayload == castPayload else { return }
await displaySlideAtCurrentIndex()
@@ -463,56 +479,60 @@ class RealSlideshowService: ObservableObject {
}
}
- let currentValidFileIDs = Set(allFiles.map { $0.id })
+ let currentValidFileIDs = Set(allFiles.map(\.id))
Task {
await cleanupExpiredCache(validFileIDs: currentValidFileIDs, castPayload: castPayload)
}
}
-
+
private func displaySlideAtCurrentIndex() async {
guard currentFileIndex >= 0, currentFileIndex < allFiles.count,
let payload = storedCastPayload else { return }
-
+
await MainActor.run {
currentSlideIndex = currentFileIndex
slideLoadingProgress = 0.0
}
-
+
if let cachedData = prefetchCache[currentFileIndex] {
await updateCurrentSlide(with: cachedData, file: allFiles[currentFileIndex])
await MainActor.run { slideLoadingProgress = 1.0 }
return
}
-
+
do {
let file = allFiles[currentFileIndex]
print("Loading file \(file.id): \(file.title) at index \(currentFileIndex)")
await MainActor.run { slideLoadingProgress = 0.5 }
-
+
let decryptedData = try await downloadAndDecryptFileContent(
castPayload: payload,
- file: file
+ file: file,
)
guard storedCastPayload == payload else { return }
-
- print("Successfully loaded file \(file.id): \(file.title) (\(decryptedData.count) bytes)")
-
+
+ print(
+ "Successfully loaded file \(file.id): \(file.title) (\(decryptedData.count) bytes)",
+ )
+
prefetchCache[currentFileIndex] = decryptedData
-
+
await updateCurrentSlide(with: decryptedData, file: file)
await MainActor.run { slideLoadingProgress = 1.0 }
-
+
startPrefetching()
-
+
} catch {
guard storedCastPayload == payload else { return }
let file = allFiles[currentFileIndex]
- print("Failed to load file \(file.id): \(file.title) at index \(currentFileIndex) - \(error)")
-
+ print(
+ "Failed to load file \(file.id): \(file.title) at index \(currentFileIndex) - \(error)",
+ )
+
await MainActor.run {
slideLoadingProgress = 0.0
}
-
+
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
Task {
guard self.storedCastPayload == payload else { return }
@@ -521,37 +541,37 @@ class RealSlideshowService: ObservableObject {
}
}
}
-
+
@MainActor
private func updateCurrentSlide(with data: Data, file: CastFile) {
// Keep the old image until its replacement is ready.
let wasEmpty = error == "No media files available in this album"
error = nil
currentFile = file
-
+
if file.isLivePhoto {
do {
let components = try extractLivePhotoComponents(from: data)
-
+
if let imageData = components.imageData {
currentImageData = imageData
print("Live photo image component loaded: \(imageData.count) bytes")
} else {
currentImageData = data
}
-
+
if let videoData = components.videoData {
livePhotoVideoData = videoData
print("Live photo video component stored: \(videoData.count) bytes")
} else {
livePhotoVideoData = nil
}
-
+
currentVideoData = nil
currentVideoURL = nil
-
+
startSlideTimer()
-
+
} catch {
print("Failed to extract live photo components: \(error)")
currentImageData = data
@@ -570,8 +590,12 @@ class RealSlideshowService: ObservableObject {
if let existing = videoTempFiles[file.id] {
url = existing
} else {
- let fileExtension = file.title.components(separatedBy: ".").last?.lowercased() ?? "mp4"
- let tmpURL = FileManager.default.temporaryDirectory.appendingPathComponent("cast_video_\(file.id)_\(UUID().uuidString).\(fileExtension)")
+ let fileExtension = file.title.components(separatedBy: ".").last?
+ .lowercased() ?? "mp4"
+ let tmpURL = FileManager.default.temporaryDirectory
+ .appendingPathComponent(
+ "cast_video_\(file.id)_\(UUID().uuidString).\(fileExtension)",
+ )
try data.write(to: tmpURL, options: .atomic)
videoTempFiles[file.id] = tmpURL
url = tmpURL
@@ -592,74 +616,77 @@ class RealSlideshowService: ObservableObject {
startSlideTimer()
}
error = nil
-
+
if wasEmpty {
NotificationCenter.default.post(name: .slideshowRestarted, object: nil)
}
}
-
+
private func startSlideTimer(withDuration customDuration: TimeInterval? = nil) {
- guard let currentFile = currentFile else { return }
+ guard let currentFile else { return }
// Video playback advances the slideshow when it ends.
- if currentFile.isVideo {
+ if currentFile.isVideo {
slideTimeRemaining = 0
slideStartTime = nil
- return
+ return
}
-
+
slideTimer?.invalidate()
let duration = customDuration ?? slideshowConfiguration.duration(for: currentFile)
slideStartTime = Date()
slideTimeRemaining = duration
-
- slideTimer = Timer.scheduledTimer(withTimeInterval: duration, repeats: false) { [weak self] _ in
- Task { @MainActor in
- guard let self = self, self.isPlaying, !self.isPaused else { return }
- self.slideTimeRemaining = 0
- self.slideStartTime = nil
-
- await self.nextSlide()
+
+ slideTimer = Timer
+ .scheduledTimer(withTimeInterval: duration, repeats: false) { [weak self] _ in
+ Task { @MainActor in
+ guard let self, self.isPlaying, !self.isPaused else { return }
+ self.slideTimeRemaining = 0
+ self.slideStartTime = nil
+
+ await self.nextSlide()
+ }
}
- }
}
-
+
private func skipToNextSlide() async {
guard !allFiles.isEmpty, let payload = storedCastPayload else { return }
-
+
currentFileIndex = (currentFileIndex + 1) % allFiles.count
-
+
let maxRetries = allFiles.count
var retryCount = 0
-
+
while retryCount < maxRetries {
do {
let file = allFiles[currentFileIndex]
-
- print("Attempting to load file \(file.id): \(file.title) at index \(currentFileIndex)")
-
+
+ print(
+ "Attempting to load file \(file.id): \(file.title) at index \(currentFileIndex)",
+ )
+
let decryptedData = try await downloadAndDecryptFileContent(
castPayload: payload,
- file: file
+ file: file,
)
guard storedCastPayload == payload else { return }
-
+
prefetchCache[currentFileIndex] = decryptedData
await updateCurrentSlide(with: decryptedData, file: file)
-
+
await MainActor.run {
currentSlideIndex = currentFileIndex
slideLoadingProgress = 1.0
}
-
+
print("Successfully loaded file \(file.id): \(file.title)")
-
- if isPlaying && !isPaused {
+
+ if isPlaying, !isPaused {
startSlideTimer()
}
-
+
startPrefetching()
return
-
+
} catch {
guard storedCastPayload == payload else { return }
let file = allFiles[currentFileIndex]
@@ -668,53 +695,60 @@ class RealSlideshowService: ObservableObject {
retryCount += 1
}
}
-
+
await MainActor.run {
self.error = "Unable to load any slides. All files may be corrupted or have decryption issues."
}
}
-
+
private func startPrefetching() {
guard let payload = storedCastPayload else { return }
Task {
let prefetchCount = min(3, allFiles.count)
- for i in 1...prefetchCount {
+ for i in 1 ... prefetchCount {
guard storedCastPayload == payload else { return }
let prefetchIndex = (currentFileIndex + i) % allFiles.count
-
- if prefetchCache[prefetchIndex] != nil { continue }
-
+
+ if prefetchCache[prefetchIndex] != nil {
+ continue
+ }
+
do {
let file = allFiles[prefetchIndex]
let data = try await downloadAndDecryptFileContent(
castPayload: payload,
- file: file
+ file: file,
)
guard storedCastPayload == payload else { return }
prefetchCache[prefetchIndex] = data
-
+
if prefetchCache.count > 5 {
- let oldKeys = Array(prefetchCache.keys.sorted().prefix(prefetchCache.count - 5))
+ let oldKeys = Array(prefetchCache.keys.sorted()
+ .prefix(prefetchCache.count - 5))
for key in oldKeys {
prefetchCache.removeValue(forKey: key)
}
}
-
+
} catch {
guard storedCastPayload == payload else { return }
// Silently skip problematic files during prefetching
print("Prefetch failed for file \(prefetchIndex), will try on-demand")
continue
}
-
+
try? await Task.sleep(nanoseconds: 500_000_000)
}
}
}
-
+
private func prepareVideoPlayer(url: URL) {
let playerItem = AVPlayerItem(url: url)
- NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: playerItem, queue: .main) { [weak self] _ in
+ NotificationCenter.default.addObserver(
+ forName: .AVPlayerItemDidPlayToEndTime,
+ object: playerItem,
+ queue: .main,
+ ) { [weak self] _ in
Task { @MainActor in
self?.videoDidFinish()
}
@@ -732,26 +766,31 @@ class RealSlideshowService: ObservableObject {
playVideo()
startVideoProgressUpdates()
}
-
+
private func startVideoProgressUpdates() {
- videoPlayer?.addPeriodicTimeObserver(forInterval: CMTime(seconds: 0.5, preferredTimescale: 600), queue: .main) { [weak self] time in
+ videoPlayer?.addPeriodicTimeObserver(
+ forInterval: CMTime(seconds: 0.5, preferredTimescale: 600),
+ queue: .main,
+ ) { [weak self] time in
Task { @MainActor in
- guard let self = self else { return }
+ guard let self else { return }
self.videoCurrentTime = CMTimeGetSeconds(time)
- if let duration = self.videoPlayer?.currentItem?.duration.seconds, duration.isFinite {
- self.videoDuration = duration
+ if let duration = self.videoPlayer?.currentItem?.duration.seconds,
+ duration.isFinite
+ {
+ self.videoDuration = duration
}
}
}
}
-
+
func playVideo() {
guard let player = videoPlayer else { return }
player.play()
isVideoPlaying = true
slideTimer?.invalidate()
}
-
+
@MainActor
private func videoDidFinish() {
isVideoPlaying = false
@@ -760,45 +799,48 @@ class RealSlideshowService: ObservableObject {
await self.nextSlide()
}
}
-
+
@MainActor
private func startPeriodicDiffPolling() {
- guard isPeriodicPollingEnabled && storedCastPayload != nil else { return }
-
+ guard isPeriodicPollingEnabled, storedCastPayload != nil else { return }
+
stopPeriodicDiffPolling()
-
+
print("Starting periodic diff polling (every \(diffPollingInterval)s)")
-
- diffPollingTimer = Timer.scheduledTimer(withTimeInterval: diffPollingInterval, repeats: true) { [weak self] _ in
+
+ diffPollingTimer = Timer.scheduledTimer(
+ withTimeInterval: diffPollingInterval,
+ repeats: true,
+ ) { [weak self] _ in
Task {
await self?.performPeriodicDiffCheck()
}
}
}
-
+
@MainActor
private func stopPeriodicDiffPolling() {
diffPollingTimer?.invalidate()
diffPollingTimer = nil
}
-
+
private func performPeriodicDiffCheck() async {
let payload = await MainActor.run { storedCastPayload }
let isEnabled = await MainActor.run { isPeriodicPollingEnabled }
-
- guard let payload = payload, isEnabled else { return }
-
+
+ guard let payload, isEnabled else { return }
+
do {
let currentTime = await MainActor.run { lastUpdateTime }
let result = try await fetchFilesBatch(castPayload: payload, sinceTime: currentTime)
guard storedCastPayload == payload else { return }
-
+
if !result.files.isEmpty {
print("Periodic poll found \(result.files.count) changes")
-
+
await processDiffBatch(result.files, castPayload: payload)
guard storedCastPayload == payload else { return }
-
+
if result.latestUpdateTime > lastUpdateTime {
print("Updating lastUpdateTime: \(lastUpdateTime) β†’ \(result.latestUpdateTime)")
lastUpdateTime = result.latestUpdateTime
@@ -806,32 +848,33 @@ class RealSlideshowService: ObservableObject {
} else {
print("Periodic poll found no changes since \(currentTime)")
}
-
+
} catch {
if let castError = error as? CastError,
- case .serverError(401, _) = castError {
+ case .serverError(401, _) = castError
+ {
// fetchFilesBatch already handled this error.
} else {
print("Periodic diff check failed: \(error)")
}
}
}
-
+
@MainActor
private func handleUnauthorizedError() {
guard !isHandlingAuthExpiry else {
return
}
-
+
isHandlingAuthExpiry = true
-
+
ScreenSaverManager.allowScreenSaver()
-
+
isPeriodicPollingEnabled = false
stopPeriodicDiffPolling()
-
+
NotificationCenter.default.post(name: .authenticationExpired, object: nil)
-
+
// Keep the guard set while the session resets.
Task {
try? await Task.sleep(nanoseconds: 2_000_000_000)
@@ -840,83 +883,109 @@ class RealSlideshowService: ObservableObject {
}
}
}
-
+
private func downloadEncryptedFile(castPayload: CastPayload, fileID: Int) async throws -> Data {
guard storedCastPayload == castPayload else { throw CancellationError() }
let isProduction = baseURL == APIEndpoint.production.absoluteString
let url = isProduction
? URL(string: "\(castDownloadURL)/?fileID=\(fileID)")!
: URL(string: baseURL)!.appendingPathComponent("cast/files/download/v3/\(fileID)")
-
+
var request = URLRequest(url: url)
request.setValue(castPayload.castToken, forHTTPHeaderField: "X-Cast-Access-Token")
let data = try await download(request, castPayload: castPayload, fileID: fileID)
guard !isProduction else { return data }
let fileURL = try JSONDecoder().decode(FileURL.self, from: data).url
- return try await download(URLRequest(url: fileURL), castPayload: castPayload, fileID: fileID)
+ return try await download(
+ URLRequest(url: fileURL),
+ castPayload: castPayload,
+ fileID: fileID,
+ )
}
- private func download(_ request: URLRequest, castPayload: CastPayload, fileID: Int) async throws -> Data {
+ private func download(_ request: URLRequest, castPayload: CastPayload,
+ fileID: Int) async throws -> Data
+ {
let (data, response) = try await URLSession.shared.data(for: request)
guard storedCastPayload == castPayload else { throw CancellationError() }
-
+
guard let httpResponse = response as? HTTPURLResponse else {
throw CastError.networkError("Invalid response")
}
-
+
guard httpResponse.statusCode == 200 else {
let snippet = (String(data: data, encoding: .utf8) ?? "").prefix(160)
print("Download error [\(httpResponse.statusCode)] fileID=\(fileID): \(snippet)")
if httpResponse.statusCode == 401,
- request.value(forHTTPHeaderField: "X-Cast-Access-Token") != nil {
+ request.value(forHTTPHeaderField: "X-Cast-Access-Token") != nil
+ {
await handleUnauthorizedError()
- throw CastError.serverError(401, "Authentication expired - resetting to pairing mode")
+ throw CastError.serverError(
+ 401,
+ "Authentication expired - resetting to pairing mode",
+ )
} else {
throw CastError.serverError(httpResponse.statusCode, String(snippet))
}
}
- if verboseFileLogging { print("Successfully downloaded \(data.count) bytes for file \(fileID)") }
+ if verboseFileLogging {
+ print("Successfully downloaded \(data.count) bytes for file \(fileID)")
+ }
return data
}
private struct FileURL: Decodable { let url: URL }
-
- private func downloadAndDecryptFileContent(castPayload: CastPayload, file: CastFile) async throws -> Data {
+
+ private func downloadAndDecryptFileContent(castPayload: CastPayload,
+ file: CastFile) async throws -> Data
+ {
let stopping = await MainActor.run { isStopping }
if stopping {
throw CastError.networkError("Service is stopping")
}
-
+
if let cachedData = await getCachedFileContent(fileID: file.id) {
- if verboseFileLogging { print("Using cached content for file \(file.id): \(file.title) (\(cachedData.count) bytes)") }
+ if verboseFileLogging {
+ print(
+ "Using cached content for file \(file.id): \(file.title) (\(cachedData.count) bytes)",
+ )
+ }
return cachedData
}
-
- if verboseFileLogging { print("Downloading and decrypting file \(file.id): \(file.title)") }
-
- let encryptedData = try await downloadEncryptedFile(castPayload: castPayload, fileID: file.id)
- if verboseFileLogging { print("Downloaded \(encryptedData.count) bytes") }
-
+
+ if verboseFileLogging {
+ print("Downloading and decrypting file \(file.id): \(file.title)")
+ }
+
+ let encryptedData = try await downloadEncryptedFile(
+ castPayload: castPayload,
+ fileID: file.id,
+ )
+ if verboseFileLogging {
+ print("Downloaded \(encryptedData.count) bytes")
+ }
+
let fileKey = try decryptFileKey(
encryptedKey: file.encryptedKey,
nonce: file.keyDecryptionNonce,
- collectionKey: castPayload.collectionKey
+ collectionKey: castPayload.collectionKey,
)
-
-
+
let decryptedData = try decryptFileContent(
encryptedData: encryptedData,
fileKey: fileKey,
- decryptionHeader: file.fileDecryptionHeader
+ decryptionHeader: file.fileDecryptionHeader,
)
guard storedCastPayload == castPayload else { throw CancellationError() }
await cacheFileContent(fileID: file.id, data: decryptedData)
-
+
return decryptedData
}
-
- private func decryptFileMetadata(item: [String: Any], collectionKey: String) async throws -> CastFile? {
+
+ private func decryptFileMetadata(item: [String: Any],
+ collectionKey: String) async throws -> CastFile?
+ {
guard let id = item["id"] as? Int,
let encryptedKey = item["encryptedKey"] as? String,
let keyDecryptionNonce = item["keyDecryptionNonce"] as? String,
@@ -924,129 +993,156 @@ class RealSlideshowService: ObservableObject {
let encryptedMetadata = metadataDict["encryptedData"] as? String,
let metadataHeader = metadataDict["decryptionHeader"] as? String,
let fileDict = item["file"] as? [String: Any],
- let fileDecryptionHeader = fileDict["decryptionHeader"] as? String else {
+ let fileDecryptionHeader = fileDict["decryptionHeader"] as? String
+ else {
print("Missing required fields for file \(item["id"] ?? "unknown")")
return nil
}
-
+
do {
let fileKey = try decryptFileKey(
encryptedKey: encryptedKey,
nonce: keyDecryptionNonce,
- collectionKey: collectionKey
+ collectionKey: collectionKey,
)
- if verboseDecryptionLogging { print("File key decrypted successfully") }
-
+ if verboseDecryptionLogging {
+ print("File key decrypted successfully")
+ }
+
let metadata = try decryptMetadata(
encryptedData: encryptedMetadata,
decryptionHeader: metadataHeader,
- fileKey: fileKey
+ fileKey: fileKey,
)
-
-
+
let fileMetadata = try parseFileMetadata(data: metadata)
-
-
+
let isVideo = fileMetadata.fileType == 1
let isLivePhoto = fileMetadata.fileType == 2
return CastFile(
- id: id,
- title: fileMetadata.title,
+ id: id,
+ title: fileMetadata.title,
isVideo: isVideo,
isLivePhoto: isLivePhoto,
encryptedKey: encryptedKey,
keyDecryptionNonce: keyDecryptionNonce,
fileDecryptionHeader: fileDecryptionHeader,
- hash: fileMetadata.hash
+ hash: fileMetadata.hash,
)
-
+
} catch {
print("Decryption failed: \(error)")
throw error
}
}
-
- private func decryptFileKey(encryptedKey: String, nonce: String, collectionKey: String) throws -> Data {
+
+ private func decryptFileKey(encryptedKey: String, nonce: String,
+ collectionKey: String) throws -> Data
+ {
guard let encryptedKeyData = Data(base64Encoded: encryptedKey),
let nonceData = Data(base64Encoded: nonce),
- let collectionKeyData = Data(base64Encoded: collectionKey) else {
+ let collectionKeyData = Data(base64Encoded: collectionKey)
+ else {
throw CastError.decryptionError("Invalid base64 in file key decryption")
}
-
+
do {
- let decryptedFileKey = try openSecretBox(ciphertext: encryptedKeyData, nonce: nonceData, key: collectionKeyData)
- return decryptedFileKey
+ return try openSecretBox(
+ ciphertext: encryptedKeyData,
+ nonce: nonceData,
+ key: collectionKeyData,
+ )
} catch {
throw CastError.decryptionError("SecretBox decryption failed for file key: \(error)")
}
}
-
- private func decryptMetadata(encryptedData: String, decryptionHeader: String, fileKey: Data) throws -> Data {
+
+ private func decryptMetadata(encryptedData: String, decryptionHeader: String,
+ fileKey: Data) throws -> Data
+ {
guard let encryptedBytes = Data(base64Encoded: encryptedData),
- let headerBytes = Data(base64Encoded: decryptionHeader) else {
+ let headerBytes = Data(base64Encoded: decryptionHeader)
+ else {
throw CastError.decryptionError("Invalid base64 in metadata decryption")
}
-
- print("XChaCha20: encrypted=\(encryptedBytes.count)b, header=\(headerBytes.count)b, key=\(fileKey.count)b")
-
+
+ print(
+ "XChaCha20: encrypted=\(encryptedBytes.count)b, header=\(headerBytes.count)b, key=\(fileKey.count)b",
+ )
+
do {
- let decryptedData = try decryptSecretStream(encryptedData: encryptedBytes, header: headerBytes, key: fileKey)
+ let decryptedData = try decryptSecretStream(
+ encryptedData: encryptedBytes,
+ header: headerBytes,
+ key: fileKey,
+ )
print("Metadata decrypted using Rust crypto: \(decryptedData.count) bytes")
return decryptedData
} catch {
- throw CastError.decryptionError("XChaCha20-Poly1305 decryption failed for metadata: \(error)")
+ throw CastError
+ .decryptionError("XChaCha20-Poly1305 decryption failed for metadata: \(error)")
}
}
-
- private func decryptFileContent(encryptedData: Data, fileKey: Data, decryptionHeader: String) throws -> Data {
+
+ private func decryptFileContent(encryptedData: Data, fileKey: Data,
+ decryptionHeader: String) throws -> Data
+ {
guard let headerBytes = Data(base64Encoded: decryptionHeader) else {
throw CastError.decryptionError("Invalid base64 in file decryption header")
}
-
- if verboseDecryptionLogging { print("File decryption: encrypted=\(encryptedData.count)b, header=\(headerBytes.count)b, key=\(fileKey.count)b") }
-
+
+ if verboseDecryptionLogging {
+ print(
+ "File decryption: encrypted=\(encryptedData.count)b, header=\(headerBytes.count)b, key=\(fileKey.count)b",
+ )
+ }
+
do {
- return try decryptSecretStream(encryptedData: encryptedData, header: headerBytes, key: fileKey)
+ return try decryptSecretStream(
+ encryptedData: encryptedData,
+ header: headerBytes,
+ key: fileKey,
+ )
} catch {
throw CastError.decryptionError("file content decryption failed: \(error)")
}
}
-
+
private func parseFileMetadata(data: Data) throws -> FileMetadata {
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
throw CastError.decryptionError("Invalid JSON in decrypted metadata")
}
-
+
let fileType = json["fileType"] as? Int ?? 0
let title = json["title"] as? String ?? "Unknown"
let creationTime = json["creationTime"] as? Int64 ?? 0
let modificationTime = json["modificationTime"] as? Int64 ?? 0
let hash = json["hash"] as? String
-
+
return FileMetadata(
fileType: fileType,
title: title,
creationTime: creationTime,
modificationTime: modificationTime,
- hash: hash
+ hash: hash,
)
}
-
+
private func getCachedFileContent(fileID: Int) async -> Data? {
- return await fileCache.get(fileID)
+ await fileCache.get(fileID)
}
-
+
private func cacheFileContent(fileID: Int, data: Data) async {
await fileCache.set(fileID, data: data)
}
-
+
private func cleanupExpiredCache(validFileIDs: Set<Int>, castPayload: CastPayload) async {
guard storedCastPayload == castPayload else { return }
let stats = await getCacheStats()
print("Starting cache cleanup - current cache has \(stats.count) files")
-
+
let cachedFileIDs = await fileCache.getCachedFileIDs()
-
+
var removedCount = 0
for cachedFileID in cachedFileIDs {
guard storedCastPayload == castPayload else { return }
@@ -1055,23 +1151,25 @@ class RealSlideshowService: ObservableObject {
removedCount += 1
}
}
-
+
if removedCount > 0 {
let newStats = await getCacheStats()
- print("Cache cleanup complete - removed \(removedCount) expired files, now \(newStats.count) files (\(newStats.totalSize) bytes)")
+ print(
+ "Cache cleanup complete - removed \(removedCount) expired files, now \(newStats.count) files (\(newStats.totalSize) bytes)",
+ )
}
}
-
+
private func removeCachedFileContent(fileID: Int) async {
await fileCache.remove(fileID)
}
-
+
func clearCache() async {
await fileCache.clear()
}
-
+
private func getCacheStats() async -> (count: Int, totalSize: Int) {
- return await fileCache.getStats()
+ await fileCache.getStats()
}
}
@@ -1086,47 +1184,55 @@ func extractZipUsingFoundation(zipURL: URL, to destinationURL: URL) throws {
func extractLivePhotoComponents(from zipData: Data) throws -> LivePhotoComponents {
let tempDirectory = FileManager.default.temporaryDirectory
let zipURL = tempDirectory.appendingPathComponent("livephoto_\(UUID().uuidString).zip")
- let extractDirectory = tempDirectory.appendingPathComponent("livephoto_extract_\(UUID().uuidString)")
-
+ let extractDirectory = tempDirectory
+ .appendingPathComponent("livephoto_extract_\(UUID().uuidString)")
+
defer {
try? FileManager.default.removeItem(at: zipURL)
try? FileManager.default.removeItem(at: extractDirectory)
}
-
+
try zipData.write(to: zipURL)
try FileManager.default.createDirectory(at: extractDirectory, withIntermediateDirectories: true)
-
+
var imageData: Data?
var videoData: Data?
var imagePath: URL?
var videoPath: URL?
-
+
do {
try extractZipUsingFoundation(zipURL: zipURL, to: extractDirectory)
-
+
// Live Photo zips may nest their assets.
let resourceKeys: [URLResourceKey] = [.isDirectoryKey]
- let enumerator = FileManager.default.enumerator(at: extractDirectory, includingPropertiesForKeys: resourceKeys)
-
+ let enumerator = FileManager.default.enumerator(
+ at: extractDirectory,
+ includingPropertiesForKeys: resourceKeys,
+ )
+
func isLikelyImage(_ url: URL) -> Bool {
let ext = url.pathExtension.lowercased()
return ["jpg", "jpeg", "png", "heic", "heif"].contains(ext)
}
-
+
func isLikelyVideo(_ url: URL) -> Bool {
let ext = url.pathExtension.lowercased()
return ["mov", "mp4", "m4v", "hevc"].contains(ext)
}
-
- while let fileURL = enumerator?.nextObject() as? URL {
- if (try? fileURL.resourceValues(forKeys: Set(resourceKeys)).isDirectory) == true { continue }
+
+ while let fileURL = enumerator?.nextObject() as? URL {
+ if (try? fileURL.resourceValues(forKeys: Set(resourceKeys)).isDirectory) ==
+ true
+ {
+ continue
+ }
let filename = fileURL.lastPathComponent
-
- if imageData == nil && isLikelyImage(fileURL) {
+
+ if imageData == nil, isLikelyImage(fileURL) {
imageData = try Data(contentsOf: fileURL)
imagePath = fileURL
print("Extracted live photo image: \(filename) (\(imageData?.count ?? 0) bytes)")
- } else if videoData == nil && isLikelyVideo(fileURL) {
+ } else if videoData == nil, isLikelyVideo(fileURL) {
videoData = try Data(contentsOf: fileURL)
videoPath = fileURL
print("Extracted live photo video: \(filename) (\(videoData?.count ?? 0) bytes)")
@@ -1136,37 +1242,51 @@ func extractLivePhotoComponents(from zipData: Data) throws -> LivePhotoComponent
}
}
}
-
+
// Some packages use extensionless or generic asset names.
if imageData == nil || videoData == nil {
- let contents = try FileManager.default.contentsOfDirectory(at: extractDirectory, includingPropertiesForKeys: nil)
+ let contents = try FileManager.default.contentsOfDirectory(
+ at: extractDirectory,
+ includingPropertiesForKeys: nil,
+ )
if imageData == nil {
if let guessImage = contents.first(where: { $0.pathExtension.isEmpty }) {
imageData = try? Data(contentsOf: guessImage)
imagePath = guessImage
- if imageData != nil { print("Heuristic image pick: \(guessImage.lastPathComponent)") }
+ if imageData !=
+ nil
+ {
+ print("Heuristic image pick: \(guessImage.lastPathComponent)")
+ }
}
}
if videoData == nil {
- if let guessVideo = contents.first(where: { ["bin", "dat"].contains($0.pathExtension.lowercased()) }) {
+ if let guessVideo = contents
+ .first(where: { ["bin", "dat"].contains($0.pathExtension.lowercased()) })
+ {
videoData = try? Data(contentsOf: guessVideo)
videoPath = guessVideo
- if videoData != nil { print("Heuristic video pick: \(guessVideo.lastPathComponent)") }
+ if videoData !=
+ nil
+ {
+ print("Heuristic video pick: \(guessVideo.lastPathComponent)")
+ }
}
}
}
-
- if imageData == nil && videoData == nil {
- throw CastError.decryptionError("No valid image or video components found in live photo zip")
+
+ if imageData == nil, videoData == nil {
+ throw CastError
+ .decryptionError("No valid image or video components found in live photo zip")
}
-
+
return LivePhotoComponents(
imageData: imageData,
videoData: videoData,
imagePath: imagePath,
- videoPath: videoPath
+ videoPath: videoPath,
)
-
+
} catch {
print("Failed to extract live photo components: \(error)")
throw CastError.decryptionError("Failed to extract live photo zip: \(error)")
diff --git a/apple/apps/cast/Cast/Views/APIEndpointView.swift b/apple/apps/cast/Cast/Views/APIEndpointView.swift
index 4de28afcd1..6257048f37 100644
--- a/apple/apps/cast/Cast/Views/APIEndpointView.swift
+++ b/apple/apps/cast/Cast/Views/APIEndpointView.swift
@@ -35,13 +35,15 @@ struct APIEndpointView: View {
onSave()
dismiss()
} label: { buttonLabel("Use Ente") }
- .disabled(isSaving)
+ .disabled(isSaving)
}
Button(role: .cancel) { dismiss() } label: { buttonLabel("Cancel") }
.disabled(isSaving)
}
- if isSaving { ProgressView() }
+ if isSaving {
+ ProgressView()
+ }
}
.frame(maxWidth: 720)
.multilineTextAlignment(.center)
@@ -49,7 +51,9 @@ struct APIEndpointView: View {
.padding(80)
}
- private func buttonLabel(_ title: String) -> some View { Text(title).frame(width: 240) }
+ private func buttonLabel(_ title: String) -> some View {
+ Text(title).frame(width: 240)
+ }
private func save() {
isSaving = true
diff --git a/apple/apps/cast/Cast/Views/EnteBranding.swift b/apple/apps/cast/Cast/Views/EnteBranding.swift
index b3bebac341..912b4dfcfc 100644
--- a/apple/apps/cast/Cast/Views/EnteBranding.swift
+++ b/apple/apps/cast/Cast/Views/EnteBranding.swift
@@ -5,9 +5,8 @@ struct EnteBranding: View {
VStack(alignment: .leading, spacing: -4) {
Text("ente")
.font(FontUtils.montserratExtraBold(size: 40))
-
.foregroundColor(.black)
-
+
Text("photos")
.font(FontUtils.montserratBold(size: 20))
.foregroundColor(.white)
@@ -15,7 +14,7 @@ struct EnteBranding: View {
.padding(.vertical, 4)
.background(
RoundedRectangle(cornerRadius: 8)
- .fill(Color(red: 0/255, green: 179/255, blue: 61/255))
+ .fill(Color(red: 0 / 255, green: 179 / 255, blue: 61 / 255)),
)
.rotationEffect(.degrees(-8))
.offset(x: 20, y: -2)
diff --git a/apple/apps/cast/Cast/Views/PairingView.swift b/apple/apps/cast/Cast/Views/PairingView.swift
index a8c2d45773..e7d91d5a23 100644
--- a/apple/apps/cast/Cast/Views/PairingView.swift
+++ b/apple/apps/cast/Cast/Views/PairingView.swift
@@ -4,41 +4,47 @@ import UIKit
struct PairingView: View {
let deviceCode: String
@State private var pulseScale: CGFloat = 1.0
-
+
var body: some View {
GeometryReader { geometry in
ZStack {
Color.white
.ignoresSafeArea()
-
+
HStack(spacing: 0) {
Spacer()
.frame(width: geometry.size.width * 0.05)
-
+
ZStack {
RoundedRectangle(cornerRadius: 36)
- .fill(Color(red: 0/255, green: 179/255, blue: 61/255))
+ .fill(Color(red: 0 / 255, green: 179 / 255, blue: 61 / 255))
.shadow(color: Color.black.opacity(0.25), radius: 4, y: 4)
-
+
VStack(spacing: 0) {
VStack(spacing: -5) {
Text("Ready to")
- .font(FontUtils.montserratExtraBold(size: geometry.size.width * 0.035))
+ .font(FontUtils
+ .montserratExtraBold(size: geometry.size.width * 0.035))
.foregroundColor(.white)
-
+
Text("Connect?")
- .font(FontUtils.montserratExtraBold(size: geometry.size.width * 0.065))
+ .font(FontUtils
+ .montserratExtraBold(size: geometry.size.width * 0.065))
.foregroundColor(.white)
}
.padding(.top, geometry.size.height * 0.06)
-
+
Spacer()
.frame(height: geometry.size.height * 0.05)
-
+
ZStack {
// Reserve six characters so the box does not resize.
Text(deviceCode.isEmpty ? "000000" : deviceCode)
- .font(.system(size: geometry.size.width * 0.09, weight: .heavy, design: .monospaced))
+ .font(.system(
+ size: geometry.size.width * 0.09,
+ weight: .heavy,
+ design: .monospaced,
+ ))
.tracking(geometry.size.width * 0.015)
.opacity(0)
@@ -49,7 +55,11 @@ struct PairingView: View {
.scaleEffect(1.8)
} else {
Text(deviceCode)
- .font(.system(size: geometry.size.width * 0.09, weight: .heavy, design: .monospaced))
+ .font(.system(
+ size: geometry.size.width * 0.09,
+ weight: .heavy,
+ design: .monospaced,
+ ))
.tracking(geometry.size.width * 0.015)
.foregroundColor(.white)
.scaleEffect(pulseScale)
@@ -59,46 +69,46 @@ struct PairingView: View {
.padding(.vertical, geometry.size.height * 0.025)
.background(
RoundedRectangle(cornerRadius: 32)
- .fill(Color(red: 0/255, green: 150/255, blue: 51/255))
+ .fill(Color(red: 0 / 255, green: 150 / 255, blue: 51 / 255)),
)
-
+
Spacer()
.frame(height: geometry.size.height * 0.08)
-
+
HStack(spacing: geometry.size.width * 0.05) {
InstructionStep(
number: "1",
text: "Open any album",
icon: "photo.on.rectangle.angled",
- geometry: geometry
+ geometry: geometry,
)
-
+
InstructionStep(
number: "2",
text: "Click Cast button",
icon: "tv",
- geometry: geometry
+ geometry: geometry,
)
-
+
InstructionStep(
number: "3",
text: "Enter the code",
icon: "keyboard",
- geometry: geometry
+ geometry: geometry,
)
}
-
+
Spacer()
.frame(height: geometry.size.height * 0.06)
-
+
Text("Visit ente.com/cast for help")
.font(FontUtils.interMedium(size: geometry.size.width * 0.012))
.foregroundColor(.white)
-
+
Spacer()
.frame(height: geometry.size.height * 0.04)
}
-
+
VStack {
Spacer()
HStack {
@@ -115,13 +125,13 @@ struct PairingView: View {
}
.frame(width: geometry.size.width * 0.8,
height: geometry.size.height * 0.85)
-
+
Spacer()
.frame(width: geometry.size.width * 0.15)
}
.padding(.top, geometry.size.height * 0.05)
.padding(.bottom, geometry.size.height * 0.05)
-
+
VStack {
HStack {
Spacer()
@@ -129,7 +139,7 @@ struct PairingView: View {
.padding(.top, 30)
.padding(.trailing, 30)
}
-
+
Spacer()
}
}
@@ -138,7 +148,7 @@ struct PairingView: View {
startAnimations()
}
}
-
+
private func startAnimations() {
withAnimation(.easeInOut(duration: 2.0).repeatForever(autoreverses: true)) {
pulseScale = 1.05
@@ -151,20 +161,20 @@ struct InstructionStep: View {
let text: String
let icon: String
let geometry: GeometryProxy
-
+
var body: some View {
VStack(spacing: geometry.size.height * 0.015) {
ZStack {
Circle()
- .fill(Color(red: 0/255, green: 150/255, blue: 51/255))
+ .fill(Color(red: 0 / 255, green: 150 / 255, blue: 51 / 255))
.frame(width: geometry.size.width * 0.035,
height: geometry.size.width * 0.035)
-
+
Image(systemName: icon)
.font(.system(size: geometry.size.width * 0.015, weight: .medium))
.foregroundColor(.white)
}
-
+
Text(text)
.font(FontUtils.interMedium(size: geometry.size.width * 0.012))
.foregroundColor(.white)
diff --git a/apple/apps/cast/Cast/Views/SlideshowView.swift b/apple/apps/cast/Cast/Views/SlideshowView.swift
index 5a0c3108ad..f6e6d677aa 100644
--- a/apple/apps/cast/Cast/Views/SlideshowView.swift
+++ b/apple/apps/cast/Cast/Views/SlideshowView.swift
@@ -10,7 +10,7 @@ struct SlideshowView: View {
private var isLivePhoto: Bool {
slideshowService.currentFile?.isLivePhoto ?? false
}
-
+
@State private var showControls = false
@State private var controlsTimer: Timer?
@State private var imageScale: CGFloat = 1.0
@@ -29,16 +29,21 @@ struct SlideshowView: View {
@State private var displayImageData: Data? = nil
@State private var preDecodedImage: UIImage? = nil
@State private var previousDecodedImage: UIImage? = nil
-
+
@FocusState private var isFocused: Bool
- init(imageData: Data? = nil, videoData: Data? = nil, isVideo: Bool = false, slideshowService: RealSlideshowService) {
+ init(
+ imageData: Data? = nil,
+ videoData: Data? = nil,
+ isVideo: Bool = false,
+ slideshowService: RealSlideshowService,
+ ) {
self.imageData = imageData
self.videoData = videoData
self.isVideo = isVideo
self.slideshowService = slideshowService
}
-
+
var body: some View {
let mainUIImage = preDecodedImage
let previousUIImage = previousDecodedImage
@@ -58,25 +63,26 @@ struct SlideshowView: View {
} else {
Color.black.ignoresSafeArea()
}
-
- if isVideo, let videoData = videoData {
+
+ if isVideo, let videoData {
VideoPlayerView(
videoData: videoData,
- suggestedFilename: slideshowService.currentFile?.title
+ suggestedFilename: slideshowService.currentFile?.title,
)
.transition(.asymmetric(
insertion: .scale(scale: 1.1).combined(with: .opacity),
- removal: .scale(scale: 0.9).combined(with: .opacity)
+ removal: .scale(scale: 0.9).combined(with: .opacity),
))
- } else if isLivePhoto && isPlayingLivePhotoVideo,
- let liveVideoData = slideshowService.livePhotoVideoData {
+ } else if isLivePhoto, isPlayingLivePhotoVideo,
+ let liveVideoData = slideshowService.livePhotoVideoData
+ {
VideoPlayerView(
videoData: liveVideoData,
- suggestedFilename: slideshowService.currentFile?.title
+ suggestedFilename: slideshowService.currentFile?.title,
)
.transition(.asymmetric(
insertion: .scale(scale: 1.1).combined(with: .opacity),
- removal: .scale(scale: 0.9).combined(with: .opacity)
+ removal: .scale(scale: 0.9).combined(with: .opacity),
))
} else if let uiImage = mainUIImage {
ZStack {
@@ -88,7 +94,7 @@ struct SlideshowView: View {
.scaleEffect(imageScale)
.opacity(previousImageOpacity)
}
-
+
Image(uiImage: uiImage)
.resizable()
.aspectRatio(contentMode: .fit)
@@ -105,19 +111,20 @@ struct SlideshowView: View {
previousImageOpacity = 0.0
isPlayingLivePhotoVideo = false
}
-
-
+
} else {
- if let error = slideshowService.error,
- (error.contains("No media files available") || error.contains("Empty file list")) {
+ if let error = slideshowService.error,
+ error.contains("No media files available") || error
+ .contains("Empty file list")
+ {
EmptyState()
- } else if slideshowService.totalSlides == 0 && !slideshowService.isPlaying {
+ } else if slideshowService.totalSlides == 0, !slideshowService.isPlaying {
LoadingState()
} else {
LoadingState()
}
}
-
+
actionFeedbackOverlay
controlsOverlay
toastOverlay
@@ -127,13 +134,13 @@ struct SlideshowView: View {
if let newData = newValue {
Task {
let decodedImage = decodedUIImage(from: newData)
-
+
await MainActor.run {
previousDecodedImage = preDecodedImage
previousImageData = displayImageData
-
+
preDecodedImage = decodedImage
-
+
if previousDecodedImage != nil {
previousImageOpacity = 1.0
imageOpacity = 0.0
@@ -141,7 +148,7 @@ struct SlideshowView: View {
imageOpacity = 1.0
previousImageOpacity = 0.0
}
-
+
displayImageData = newData
animateImageIn(bytes: newData.count, isLive: isLivePhoto)
}
@@ -154,7 +161,7 @@ struct SlideshowView: View {
.focused($isFocused)
.onMoveCommand { direction in Task { await handleDirectionalInput(direction) } }
.onPlayPauseCommand {
- if isLivePhoto && slideshowService.livePhotoVideoData != nil {
+ if isLivePhoto, slideshowService.livePhotoVideoData != nil {
handleLongPressGesture()
} else {
Task { await handlePlayPauseAction() }
@@ -165,12 +172,12 @@ struct SlideshowView: View {
startControlsTimer()
isFocused = true
ScreenSaverManager.preventScreenSaver()
-
+
// onChange does not fire when the view starts with imageData set.
- if let initialImageData = imageData, displayImageData == nil && !isVideo {
+ if let initialImageData = imageData, displayImageData == nil, !isVideo {
Task {
let decodedImage = decodedUIImage(from: initialImageData)
-
+
await MainActor.run {
preDecodedImage = decodedImage
imageOpacity = 1.0
@@ -185,7 +192,7 @@ struct SlideshowView: View {
ScreenSaverManager.allowScreenSaver()
}
}
-
+
@ViewBuilder
private var actionFeedbackOverlay: some View {
if let feedback = actionFeedback {
@@ -197,21 +204,21 @@ struct SlideshowView: View {
}
}
}
-
+
@ViewBuilder
private var controlsOverlay: some View {
if showControls {
EnhancedControlsOverlay(
isPlaying: slideshowService.isPlaying,
- isPaused: slideshowService.isPaused
+ isPaused: slideshowService.isPaused,
)
.transition(.asymmetric(
insertion: .opacity.combined(with: .move(edge: .bottom)),
- removal: .opacity
+ removal: .opacity,
))
}
}
-
+
@ViewBuilder
private var toastOverlay: some View {
if showToast {
@@ -226,15 +233,15 @@ struct SlideshowView: View {
}
}
}
-
+
private func handleLongPressGesture() {
showToast(icon: "livephoto.play", message: "Long press called")
guard isLivePhoto, slideshowService.livePhotoVideoData != nil else { return }
-
+
withAnimation(.easeInOut(duration: 0.3)) {
isPlayingLivePhotoVideo.toggle()
}
-
+
if isPlayingLivePhotoVideo {
slideshowService.pause()
showToast(icon: "livephoto.play", message: "Playing Live Photo")
@@ -242,7 +249,7 @@ struct SlideshowView: View {
slideshowService.resume()
showToast(icon: "livephoto", message: "Live Photo Paused")
}
-
+
if isPlayingLivePhotoVideo {
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
withAnimation(.easeInOut(duration: 0.3)) {
@@ -252,10 +259,10 @@ struct SlideshowView: View {
}
}
}
-
+
private func handlePlayPauseAction() async {
slideshowService.togglePlayPause()
-
+
await MainActor.run {
if slideshowService.isPaused {
showToast(icon: "pause.fill", message: "Paused")
@@ -264,7 +271,7 @@ struct SlideshowView: View {
}
}
}
-
+
private func handleDirectionalInput(_ direction: MoveCommandDirection) async {
switch direction {
case .left:
@@ -277,7 +284,7 @@ struct SlideshowView: View {
break
}
}
-
+
private func toggleControls() {
withAnimation(.easeInOut(duration: 0.4)) {
showControls.toggle()
@@ -286,32 +293,38 @@ struct SlideshowView: View {
startControlsTimer()
}
}
-
+
private func startControlsTimer() {
controlsTimer?.invalidate()
controlsTimer = Timer.scheduledTimer(withTimeInterval: 4.0, repeats: false) { _ in
- withAnimation(.easeInOut(duration: 0.4)) {
- showControls = false
+ MainActor.assumeIsolated {
+ withAnimation(.easeInOut(duration: 0.4)) {
+ showControls = false
+ }
}
}
}
-
+
private func showToast(icon: String, message: String) {
toastIcon = icon
toastMessage = message
showToast = true
-
+
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
showToast = false
}
}
-
+
private func decodedUIImage(from data: Data) -> UIImage? {
imageDecodeFailed = false
if let uiImage = UIImage(data: data) {
// Accessing cgImage forces decompression.
if let cg = uiImage.cgImage {
- return UIImage(cgImage: cg, scale: uiImage.scale, orientation: uiImage.imageOrientation)
+ return UIImage(
+ cgImage: cg,
+ scale: uiImage.scale,
+ orientation: uiImage.imageOrientation,
+ )
}
return uiImage
} else {
@@ -320,18 +333,18 @@ struct SlideshowView: View {
return nil
}
}
-
+
private func animateImageIn(bytes: Int, isLive: Bool) {
lastImageBytes = bytes
imageScale = 1.0
-
+
withAnimation(.easeInOut(duration: 0.25)) {
imageOpacity = 1.0
previousImageOpacity = 0.0
}
-
+
print("Displaying \(isLive ? "live" : "static") image (\(bytes) bytes)")
-
+
Task {
try? await Task.sleep(nanoseconds: 300_000_000)
await MainActor.run {
@@ -342,54 +355,51 @@ struct SlideshowView: View {
}
}
-
struct LoadingState: View {
@State private var animationPhase: CGFloat = 0
@State private var pulseScale: CGFloat = 1.0
-
+
var body: some View {
VStack(spacing: 40) {
ZStack {
Circle()
.stroke(Color.white.opacity(0.1), lineWidth: 6)
.frame(width: 120, height: 120)
-
+
Circle()
.trim(from: 0, to: 0.3)
.stroke(
LinearGradient(
colors: [Color.blue, Color.purple],
startPoint: .leading,
- endPoint: .trailing
+ endPoint: .trailing,
),
- style: StrokeStyle(lineWidth: 6, lineCap: .round)
+ style: StrokeStyle(lineWidth: 6, lineCap: .round),
)
.frame(width: 120, height: 120)
.rotationEffect(.degrees(animationPhase * 360))
-
+
Circle()
.fill(
RadialGradient(
colors: [
Color.blue.opacity(0.3),
- Color.clear
+ Color.clear,
],
center: .center,
startRadius: 10,
- endRadius: 40
- )
+ endRadius: 40,
+ ),
)
.frame(width: 80, height: 80)
.scaleEffect(pulseScale)
}
-
-
}
.onAppear {
withAnimation(.linear(duration: 2.0).repeatForever(autoreverses: false)) {
animationPhase = 1.0
}
-
+
withAnimation(.easeInOut(duration: 1.5).repeatForever(autoreverses: true)) {
pulseScale = 1.2
}
@@ -399,7 +409,7 @@ struct LoadingState: View {
struct EmptyState: View {
@State private var pulseScale: CGFloat = 1.0
-
+
var body: some View {
VStack(spacing: 40) {
ZStack {
@@ -408,26 +418,26 @@ struct EmptyState: View {
RadialGradient(
colors: [
Color.gray.opacity(0.2),
- Color.clear
+ Color.clear,
],
center: .center,
startRadius: 20,
- endRadius: 60
- )
+ endRadius: 60,
+ ),
)
.frame(width: 120, height: 120)
.scaleEffect(pulseScale)
-
+
Image(systemName: "photo.on.rectangle.angled")
.font(.system(size: 50, weight: .ultraLight))
.foregroundColor(.white.opacity(0.6))
}
-
+
VStack(spacing: 12) {
Text("No photos in this album")
.font(.system(size: 32, weight: .semibold))
.foregroundColor(.white)
-
+
Text("Add some photos to start your slideshow")
.font(.system(size: 20, weight: .medium))
.foregroundColor(.white.opacity(0.7))
@@ -444,37 +454,49 @@ struct EmptyState: View {
struct EnhancedControlsOverlay: View {
let isPlaying: Bool
let isPaused: Bool
-
+
var body: some View {
VStack {
Spacer()
-
+
HStack {
Spacer()
-
+
VStack(spacing: 20) {
VStack(spacing: 8) {
HStack(spacing: 8) {
Image(systemName: isPaused ? "pause.circle.fill" : "play.circle.fill")
.font(.system(size: 20, weight: .medium))
.foregroundColor(isPaused ? .yellow : .green)
-
+
Text(isPaused ? "Paused" : "Playing")
.font(.system(size: 18, weight: .semibold))
.foregroundColor(.white)
}
-
+
Text("Apple TV Remote Controls")
.font(.system(size: 16, weight: .medium))
.foregroundColor(.white.opacity(0.8))
}
-
+
HStack(spacing: 40) {
- NavigationHint(icon: "chevron.left.circle.fill", label: "Previous", direction: .leading)
- NavigationHint(icon: isPaused ? "play.circle.fill" : "pause.circle.fill", label: isPaused ? "Resume" : "Pause", direction: .center)
- NavigationHint(icon: "chevron.right.circle.fill", label: "Next", direction: .trailing)
+ NavigationHint(
+ icon: "chevron.left.circle.fill",
+ label: "Previous",
+ direction: .leading,
+ )
+ NavigationHint(
+ icon: isPaused ? "play.circle.fill" : "pause.circle.fill",
+ label: isPaused ? "Resume" : "Pause",
+ direction: .center,
+ )
+ NavigationHint(
+ icon: "chevron.right.circle.fill",
+ label: "Next",
+ direction: .trailing,
+ )
}
-
+
VStack(spacing: 6) {
Text("β€’ Touch surface: Play/Pause")
Text("β€’ Swipe left/right: Navigate slides")
@@ -491,16 +513,19 @@ struct EnhancedControlsOverlay: View {
.background(
RoundedRectangle(cornerRadius: 20).fill(
LinearGradient(
- colors: [Color.white.opacity(0.05), Color.white.opacity(0.02)],
+ colors: [
+ Color.white.opacity(0.05),
+ Color.white.opacity(0.02),
+ ],
startPoint: .topLeading,
- endPoint: .bottomTrailing
- )
- )
+ endPoint: .bottomTrailing,
+ ),
+ ),
)
-
+
RoundedRectangle(cornerRadius: 20)
.stroke(Color.white.opacity(0.15), lineWidth: 1)
- }
+ },
)
Spacer()
}
@@ -513,12 +538,12 @@ struct NavigationHint: View {
let icon: String
let label: String
let direction: HorizontalAlignment
-
+
var body: some View {
VStack(spacing: 12) {
Image(systemName: icon)
.font(.system(size: 28, weight: .medium))
-
+
Text(label)
.font(.system(size: 14, weight: .medium))
}
@@ -529,7 +554,7 @@ struct NavigationHint: View {
enum ActionFeedback {
case play, pause, next, previous
-
+
var iconName: String {
switch self {
case .play: "play.circle.fill"
@@ -538,7 +563,7 @@ enum ActionFeedback {
case .previous: "backward.circle.fill"
}
}
-
+
var title: String {
switch self {
case .play: "Play"
@@ -551,7 +576,7 @@ enum ActionFeedback {
struct ActionFeedbackView: View {
let feedback: ActionFeedback
-
+
var body: some View {
VStack(spacing: 8) {
Image(systemName: feedback.iconName)
@@ -564,7 +589,10 @@ struct ActionFeedbackView: View {
.background(
RoundedRectangle(cornerRadius: 16)
.fill(Color.black.opacity(0.7))
- .overlay(RoundedRectangle(cornerRadius: 16).stroke(Color.white.opacity(0.2), lineWidth: 1))
+ .overlay(RoundedRectangle(cornerRadius: 16).stroke(
+ Color.white.opacity(0.2),
+ lineWidth: 1,
+ )),
)
.transition(.scale.combined(with: .opacity))
}
@@ -573,13 +601,13 @@ struct ActionFeedbackView: View {
struct AppleStyleToast: View {
let icon: String
let message: String
-
+
var body: some View {
HStack(spacing: 12) {
Image(systemName: icon)
.font(.system(size: 20, weight: .medium))
.foregroundColor(.white)
-
+
Text(message)
.font(.system(size: 18, weight: .semibold))
.foregroundColor(.white)
@@ -591,37 +619,48 @@ struct AppleStyleToast: View {
.fill(Color.black.opacity(0.8))
.overlay(
RoundedRectangle(cornerRadius: 12)
- .stroke(Color.white.opacity(0.2), lineWidth: 1)
- )
+ .stroke(Color.white.opacity(0.2), lineWidth: 1),
+ ),
)
.shadow(color: Color.black.opacity(0.3), radius: 8, x: 0, y: 4)
}
}
class MockSlideshowService: ObservableObject {
- @Published var currentFile: (title: String, isLivePhoto: Bool)? = (title: "Sample Image", isLivePhoto: false)
+ @Published var currentFile: (title: String, isLivePhoto: Bool)? = (
+ title: "Sample Image",
+ isLivePhoto: false,
+ )
@Published var isPlaying: Bool = true
@Published var isPaused: Bool = false
@Published var livePhotoVideoData: Data? = nil
-
- func togglePlayPause() { isPaused.toggle() }
+
+ func togglePlayPause() {
+ isPaused.toggle()
+ }
+
func nextSlide() async {}
func previousSlide() async {}
- func pause() { isPaused = true }
- func resume() { isPaused = false }
+ func pause() {
+ isPaused = true
+ }
+
+ func resume() {
+ isPaused = false
+ }
}
#Preview {
struct PreviewWrapper: View {
@StateObject private var slideshowService = MockSlideshowService()
-
+
var body: some View {
SlideshowView(
imageData: nil,
- slideshowService: slideshowService as! RealSlideshowService
+ slideshowService: slideshowService as! RealSlideshowService,
)
}
}
-
+
return PreviewWrapper()
}
diff --git a/apple/apps/cast/Cast/Views/StatusView.swift b/apple/apps/cast/Cast/Views/StatusView.swift
index 31f5ba38f5..aacaba137c 100644
--- a/apple/apps/cast/Cast/Views/StatusView.swift
+++ b/apple/apps/cast/Cast/Views/StatusView.swift
@@ -6,31 +6,31 @@ struct StatusView: View {
let debugLogs: String?
@State private var animationPhase: CGFloat = 0
@State private var pulseScale: CGFloat = 1.0
-
+
enum StatusType {
case loading(String)
case error(String)
case success(String)
case empty(String)
}
-
+
var body: some View {
- GeometryReader { geometry in
+ GeometryReader { _ in
ZStack {
Color.white
.ignoresSafeArea()
-
+
VStack(spacing: 24) {
Spacer()
-
+
StatusIcon(status: status)
.padding(.bottom, 16)
-
+
Text(title)
.font(FontUtils.interSemiBold(size: 42))
.foregroundColor(.black)
.multilineTextAlignment(.center)
-
+
if !message.isEmpty {
Text(message)
.font(FontUtils.interRegular(size: 20))
@@ -38,12 +38,12 @@ struct StatusView: View {
.multilineTextAlignment(.center)
.padding(.horizontal, 60)
}
-
+
Spacer()
}
.frame(maxWidth: 900)
.frame(maxWidth: .infinity)
-
+
VStack {
HStack {
Spacer()
@@ -56,42 +56,42 @@ struct StatusView: View {
}
}
}
-
+
private var title: String {
switch status {
case .loading:
- return "Preparing Slideshow"
+ "Preparing Slideshow"
case .error:
- return "Something went wrong"
+ "Something went wrong"
case .success:
- return "All set!"
+ "All set!"
case .empty:
- return "No photos found"
+ "No photos found"
}
}
-
+
private var message: String {
switch status {
- case .loading(let message):
- return message
- case .error(let message):
- return message
- case .success(let message):
- return message
- case .empty(let message):
- return message
+ case let .loading(message):
+ message
+ case let .error(message):
+ message
+ case let .success(message):
+ message
+ case let .empty(message):
+ message
}
}
}
struct StatusIcon: View {
let status: StatusView.StatusType
-
+
var body: some View {
iconView
.frame(width: 400, height: 240)
}
-
+
@ViewBuilder
private var iconView: some View {
switch status {
@@ -100,20 +100,20 @@ struct StatusIcon: View {
.resizable()
.aspectRatio(contentMode: .fit)
.frame(height: 300)
-
+
case .error:
Image("ducky_tv")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(height: 300)
.opacity(0.8)
-
+
case .success:
Image("ducky_tv")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(height: 300)
-
+
case .empty:
Image("ducky_tv")
.resizable()
@@ -126,10 +126,12 @@ struct StatusIcon: View {
#Preview {
StatusView(status: .loading("Preparing your slideshow..."), onRetry: nil, debugLogs: nil)
-
}
#Preview {
- StatusView(status: .empty("This album has no photos that can be shown here"), onRetry: nil, debugLogs: nil)
-
+ StatusView(
+ status: .empty("This album has no photos that can be shown here"),
+ onRetry: nil,
+ debugLogs: nil,
+ )
}
diff --git a/apple/apps/cast/Cast/Views/VideoPlayerView.swift b/apple/apps/cast/Cast/Views/VideoPlayerView.swift
index 1c6a2c972f..d634d02ab1 100644
--- a/apple/apps/cast/Cast/Views/VideoPlayerView.swift
+++ b/apple/apps/cast/Cast/Views/VideoPlayerView.swift
@@ -1,6 +1,6 @@
-import SwiftUI
import AVFoundation
import AVKit
+import SwiftUI
import UIKit
struct VideoPlayerView: View {
@@ -12,18 +12,18 @@ struct VideoPlayerView: View {
@State private var showToast = false
@State private var toastMessage = ""
@State private var toastIcon = ""
-
+
init(videoData: Data, suggestedFilename: String? = nil) {
self.videoData = videoData
self.suggestedFilename = suggestedFilename
}
-
+
var body: some View {
ZStack {
Color.black
.ignoresSafeArea()
-
- if let player = player {
+
+ if let player {
VideoPlayer(player: player)
.ignoresSafeArea()
.onAppear {
@@ -35,9 +35,13 @@ struct VideoPlayerView: View {
} else {
VStack(spacing: 24) {
ProgressView()
- .progressViewStyle(CircularProgressViewStyle(tint: Color(red: 29/255, green: 185/255, blue: 84/255)))
+ .progressViewStyle(CircularProgressViewStyle(tint: Color(
+ red: 29 / 255,
+ green: 185 / 255,
+ blue: 84 / 255,
+ )))
.scaleEffect(2.0)
-
+
Text("Loading video...")
.font(.system(size: 24, weight: .medium))
.foregroundColor(.white.opacity(0.8))
@@ -51,34 +55,39 @@ struct VideoPlayerView: View {
cleanup()
}
}
-
+
private func setupVideoPlayer() {
Task {
do {
- let suggestedExtension = suggestedFilename?.components(separatedBy: ".").last?.lowercased()
-
- let tempURL = try await createTemporaryVideoFile(from: videoData, suggestedExtension: suggestedExtension)
-
+ let suggestedExtension = suggestedFilename?.components(separatedBy: ".").last?
+ .lowercased()
+
+ let tempURL = try await createTemporaryVideoFile(
+ from: videoData,
+ suggestedExtension: suggestedExtension,
+ )
+
await MainActor.run {
let asset = AVURLAsset(url: tempURL)
-
+
Task {
let isPlayable = try await asset.load(.isPlayable)
- let hasVideoTracks = try await !asset.loadTracks(withMediaType: .video).isEmpty
-
+ let hasVideoTracks = try await !asset.loadTracks(withMediaType: .video)
+ .isEmpty
+
await MainActor.run {
- if isPlayable && hasVideoTracks {
+ if isPlayable, hasVideoTracks {
let playerItem = AVPlayerItem(url: tempURL)
let player = AVPlayer(playerItem: playerItem)
-
- self.monitorPlayerItemStatus(playerItem)
-
+
+ monitorPlayerItemStatus(playerItem)
+
self.playerItem = playerItem
self.player = player
-
+
setupPlayer()
} else {
- self.tryVideoFallback(originalURL: tempURL)
+ tryVideoFallback(originalURL: tempURL)
}
}
}
@@ -86,25 +95,25 @@ struct VideoPlayerView: View {
} catch {
print("Failed to setup video player: \(error)")
await MainActor.run {
- self.showErrorState()
+ showErrorState()
}
}
}
}
-
+
private func tryVideoFallback(originalURL: URL) {
Task {
do {
let fallbackURL = originalURL.deletingPathExtension().appendingPathExtension("mov")
try FileManager.default.copyItem(at: originalURL, to: fallbackURL)
-
+
await MainActor.run {
let playerItem = AVPlayerItem(url: fallbackURL)
let player = AVPlayer(playerItem: playerItem)
-
+
self.playerItem = playerItem
self.player = player
-
+
setupPlayer()
}
} catch {
@@ -113,10 +122,9 @@ struct VideoPlayerView: View {
}
}
}
-
- private func showErrorState() {
- }
-
+
+ private func showErrorState() {}
+
private func monitorPlayerItemStatus(_ playerItem: AVPlayerItem) {
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in
switch playerItem.status {
@@ -129,7 +137,7 @@ struct VideoPlayerView: View {
}
timer.invalidate()
Task { @MainActor in
- self.showErrorState()
+ showErrorState()
}
case .unknown:
break
@@ -138,145 +146,174 @@ struct VideoPlayerView: View {
}
}
}
-
+
private func setupPlayer() {
- guard let player = player else { return }
-
+ guard let player else { return }
+
player.actionAtItemEnd = .none
player.automaticallyWaitsToMinimizeStalling = true
-
+
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback)
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print("Failed to set audio session: \(error)")
}
-
+
setupPlayerObservers()
-
+
player.play()
isPlaying = true
}
-
+
private func setupPlayerObservers() {
- guard let player = player, let currentItem = player.currentItem else { return }
-
+ guard let player, let currentItem = player.currentItem else { return }
+
NotificationCenter.default.addObserver(
forName: .AVPlayerItemDidPlayToEndTime,
object: currentItem,
- queue: .main
+ queue: .main,
) { _ in
player.seek(to: .zero)
player.play()
}
-
+
NotificationCenter.default.addObserver(
forName: .AVPlayerItemFailedToPlayToEndTime,
object: currentItem,
- queue: .main
+ queue: .main,
) { notification in
- if let error = notification.userInfo?[AVPlayerItemFailedToPlayToEndTimeErrorKey] as? Error {
+ if let error = notification
+ .userInfo?[AVPlayerItemFailedToPlayToEndTimeErrorKey] as? Error
+ {
print("Video playback failed: \(error)")
}
}
-
+
NotificationCenter.default.addObserver(
forName: UIApplication.willResignActiveNotification,
object: nil,
- queue: .main
+ queue: .main,
) { _ in
player.pause()
}
-
+
NotificationCenter.default.addObserver(
forName: UIApplication.didBecomeActiveNotification,
object: nil,
- queue: .main
+ queue: .main,
) { _ in
- if self.isPlaying {
- player.play()
+ MainActor.assumeIsolated {
+ if isPlaying {
+ player.play()
+ }
}
}
}
-
- private func createTemporaryVideoFile(from data: Data, suggestedExtension: String? = nil) async throws -> URL {
+
+ private func createTemporaryVideoFile(from data: Data,
+ suggestedExtension: String? = nil) async throws -> URL
+ {
let tempDirectory = FileManager.default.temporaryDirectory
let fileExtension = detectVideoExtension(from: data) ?? suggestedExtension ?? "mp4"
- let tempURL = tempDirectory.appendingPathComponent("cast_video_\(UUID().uuidString).\(fileExtension)")
-
+ let tempURL = tempDirectory
+ .appendingPathComponent("cast_video_\(UUID().uuidString).\(fileExtension)")
+
try data.write(to: tempURL)
-
+
Task {
try? await Task.sleep(nanoseconds: 60_000_000_000)
try? FileManager.default.removeItem(at: tempURL)
}
-
+
return tempURL
}
-
+
private func detectVideoExtension(from data: Data) -> String? {
let headerBytes = data.prefix(32)
-
+
if headerBytes.count >= 4 {
let signature = headerBytes.prefix(4)
-
+
// MP4/MOV formats (most compatible with AVPlayer)
if headerBytes.count >= 12 {
- let ftyp = headerBytes.subdata(in: 4..<8)
+ let ftyp = headerBytes.subdata(in: 4 ..< 8)
if ftyp == Data("ftyp".utf8) {
- let brand = headerBytes.subdata(in: 8..<12)
- if brand == Data("mp41".utf8) || brand == Data("mp42".utf8) ||
- brand == Data("isom".utf8) || brand == Data("M4V ".utf8) {
+ let brand = headerBytes.subdata(in: 8 ..< 12)
+ if brand == Data("mp41".utf8) || brand == Data("mp42".utf8) ||
+ brand == Data("isom".utf8) || brand == Data("M4V ".utf8)
+ {
return "mp4"
} else if brand == Data("qt ".utf8) {
return "mov"
}
}
}
-
+
// Check for H.264 NAL units (common in MP4)
if headerBytes.count >= 4 {
- if signature[0] == 0x00 && signature[1] == 0x00 && signature[2] == 0x00 && signature[3] == 0x01 {
+ if signature[0] == 0x00, signature[1] == 0x00, signature[2] == 0x00,
+ signature[3] == 0x01
+ {
return "mp4"
}
}
-
+
// AVI format (less compatible with tvOS)
- if signature == Data("RIFF".utf8) && headerBytes.count >= 12 {
- let aviSignature = headerBytes.subdata(in: 8..<12)
+ if signature == Data("RIFF".utf8), headerBytes.count >= 12 {
+ let aviSignature = headerBytes.subdata(in: 8 ..< 12)
if aviSignature == Data("AVI ".utf8) {
return "avi"
}
}
-
+
// WebM format (limited support on tvOS)
if signature == Data([0x1A, 0x45, 0xDF, 0xA3]) {
return "webm"
}
-
+
// MKV format
if signature == Data([0x1A, 0x45, 0xDF, 0xA3]) {
return "mkv"
}
}
-
+
return "mp4"
}
-
+
private func cleanup() {
player?.pause()
-
- NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: nil)
- NotificationCenter.default.removeObserver(self, name: .AVPlayerItemFailedToPlayToEndTime, object: nil)
- NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)
- NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
-
+
+ NotificationCenter.default.removeObserver(
+ self,
+ name: .AVPlayerItemDidPlayToEndTime,
+ object: nil,
+ )
+ NotificationCenter.default.removeObserver(
+ self,
+ name: .AVPlayerItemFailedToPlayToEndTime,
+ object: nil,
+ )
+ NotificationCenter.default.removeObserver(
+ self,
+ name: UIApplication.willResignActiveNotification,
+ object: nil,
+ )
+ NotificationCenter.default.removeObserver(
+ self,
+ name: UIApplication.didBecomeActiveNotification,
+ object: nil,
+ )
+
do {
- try AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
+ try AVAudioSession.sharedInstance().setActive(
+ false,
+ options: .notifyOthersOnDeactivation,
+ )
} catch {
print("Failed to deactivate audio session: \(error)")
}
-
+
player = nil
playerItem = nil
isPlaying = false