π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Clean up Cast logging and comments
Manav Rathic6bf778b7a19
diff --git a/apple/apps/cast/Cast/CastApp.swift b/apple/apps/cast/Cast/CastApp.swiftindex 81dee513b5..0b79b3fc1e 100644--- a/apple/apps/cast/Cast/CastApp.swift+++ b/apple/apps/cast/Cast/CastApp.swift@@ -1,3 +1,4 @@+import OSLogimport SwiftUI@main@@ -14,13 +15,16 @@ struct CastApp: App {}private final class CastRustLogSink: RustLogSink, @unchecked Sendable {+ private let logger = Logger(subsystem: "io.ente.cast", category: "Rust")+func log(level: RustLogLevel, target: String, message: String) {- let levelName =- switch level {- case .error: "error"- case .warn: "warn"- case .info: "info"- }- print("[\(levelName)][rust][\(target)] \(message)")+ switch level {+ case .error:+ logger.error("[\(target)] \(message)")+ case .warn:+ logger.warning("[\(target)] \(message)")+ case .info:+ logger.info("[\(target)] \(message)")+ }}}diff --git a/apple/apps/cast/Cast/Models/CastModels.swift b/apple/apps/cast/Cast/Models/CastModels.swiftindex ea0859cdf7..df364b1412 100644--- a/apple/apps/cast/Cast/Models/CastModels.swift+++ b/apple/apps/cast/Cast/Models/CastModels.swift@@ -75,7 +75,7 @@ struct CastFile: Codable, Equatable {let encryptedKey: Stringlet keyDecryptionNonce: Stringlet fileDecryptionHeader: String- let hash: String? // BLAKE2b hash for file content verification+ let hash: String?var isImage: Bool {!isVideo && !isLivePhoto@@ -87,7 +87,7 @@ struct FileMetadata {let title: String // filename with extensionlet creationTime: Int64 // microseconds since epochlet modificationTime: Int64- let hash: String? // BLAKE2b hash for file content verification+ let hash: String?var isImage: Bool {fileType == 0diff --git a/apple/apps/cast/Cast/Services/CastPairingService.swift b/apple/apps/cast/Cast/Services/CastPairingService.swiftindex e02bae7a64..c45e7b2eb7 100644--- a/apple/apps/cast/Cast/Services/CastPairingService.swift+++ b/apple/apps/cast/Cast/Services/CastPairingService.swift@@ -1,6 +1,9 @@import Foundation+import OSLogimport SwiftUI+private let logger = Logger(subsystem: "io.ente.cast", category: "Pairing")+@MainActorclass CastSession: ObservableObject {@Published var state: CastSessionState = .idle@@ -45,31 +48,17 @@ class RealCastPairingService {private let initialPollingInterval: TimeInterval = 2.0private let extendedPollingInterval: TimeInterval = 5.0private let pollingIntervalSwitchTime: TimeInterval = 60.0- private var hasLoggedIntervalSwitch: Bool = falseprivate 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",- )- hasLoggedIntervalSwitch = true- }-- return newInterval+ return elapsed >= pollingIntervalSwitchTime+ ? extendedPollingInterval : initialPollingInterval}func registerDevice() async throws -> CastDevice {let receiver = CastReceiver()- print("POST \(baseURL)/cast/device-info")-let url = baseURL.appendingPathComponent("cast/device-info")var request = URLRequest(url: url)request.httpMethod = "POST"@@ -96,7 +85,7 @@ class RealCastPairingService {let deviceResponse = try JSONDecoder().decode(DeviceRegistrationResponse.self, from: data)- print("Device registered! Code from server: \(deviceResponse.deviceCode)")+ logger.info("Device registered")return CastDevice(deviceCode: deviceResponse.deviceCode,@@ -114,7 +103,6 @@ class RealCastPairingService {pollingTimer?.invalidate()isPolling = truepollingStartTime = Date()- hasLoggedIntervalSwitch = falsescheduleNextPoll(device: device, onPayloadReceived: onPayloadReceived, onError: onError)}@@ -161,7 +149,6 @@ class RealCastPairingService {defer { isFetchingPayload = false }do {let url = baseURL.appendingPathComponent("cast/cast-data/\(device.deviceCode)")- print("GET \(url.absoluteString)")let (data, response) = try await URLSession.shared.data(from: url)@@ -195,7 +182,6 @@ class RealCastPairingService {onPayloadReceived(payload)} catch {- print("Polling error: \(error)")onError(error)}}diff --git a/apple/apps/cast/Cast/Services/FileCache.swift b/apple/apps/cast/Cast/Services/FileCache.swiftindex 2d446d33d7..1b6b08e1d3 100644--- a/apple/apps/cast/Cast/Services/FileCache.swift+++ b/apple/apps/cast/Cast/Services/FileCache.swift@@ -27,8 +27,6 @@ actor ThreadSafeFileCache {return}- print("Loading existing cache from disk - \(metadata.fileIDs.count) files")-var loadedBytes = 0var validFileIDs: [Int] = []@@ -47,8 +45,6 @@ actor ThreadSafeFileCache {cacheOrder = validFileIDstotalBytes = 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) {@@ -91,10 +87,6 @@ actor ThreadSafeFileCache {enforceLimits()saveCacheMetadata()-- print(- "Cached file \(fileID) content (\(data.count) bytes) - Cache size: \(cache.count) files",- )}func remove(_ fileID: Int) {@@ -106,13 +98,10 @@ actor ThreadSafeFileCache {try? FileManager.default.removeItem(at: fileURL)saveCacheMetadata()-- print("Removed cached content for file \(fileID) (\(removedData.count) bytes)")}}func clear() {- let clearedCount = cache.countcache.removeAll()cacheOrder.removeAll()totalBytes = 0@@ -124,12 +113,6 @@ actor ThreadSafeFileCache {)try? FileManager.default.removeItem(at: metadataURL)-- print("Cleared file content cache (\(clearedCount) files)")- }-- func getStats() -> (count: Int, totalSize: Int) {- (count: cache.count, totalSize: totalBytes)}func getCachedFileIDs() -> [Int] {@@ -147,15 +130,11 @@ actor ThreadSafeFileCache {let fileURL = cacheDirectory.appendingPathComponent("\(oldest).cache")try? FileManager.default.removeItem(at: fileURL)-- print("Evicted file \(oldest) (\(data.count) bytes) to control cache size")}}totalBytes -= removedBytessaveCacheMetadata()-- print("Cache GC complete: now \(cache.count) files, \(totalBytes) bytes")}private func saveCacheMetadata() {diff --git a/apple/apps/cast/Cast/ViewModels/CastViewModel.swift b/apple/apps/cast/Cast/ViewModels/CastViewModel.swiftindex 7ad2f2e237..1b669ca2ad 100644--- a/apple/apps/cast/Cast/ViewModels/CastViewModel.swift+++ b/apple/apps/cast/Cast/ViewModels/CastViewModel.swift@@ -1,7 +1,10 @@import Combine+import OSLogimport SwiftUIimport UIKit+private let logger = Logger(subsystem: "io.ente.cast", category: "Session")+@MainActorclass CastViewModel: ObservableObject {@Published var currentView: CurrentView = .connecting@@ -291,7 +294,7 @@ class CastViewModel: ObservableObject {}private func handleError(_ message: String) {- print("Cast Error: \(message)")+ logger.error("Cast session failed: \(message)")currentView = .errorerrorMessage = messagestatusMessage = ""diff --git a/apple/apps/cast/Cast/ViewModels/SlideshowService.swift b/apple/apps/cast/Cast/ViewModels/SlideshowService.swiftindex 40976fc08a..f7f44686d0 100644--- a/apple/apps/cast/Cast/ViewModels/SlideshowService.swift+++ b/apple/apps/cast/Cast/ViewModels/SlideshowService.swift@@ -1,9 +1,12 @@import AVKitimport Foundation+import OSLogimport SwiftUIimport UIKitimport ZIPFoundation+private let logger = Logger(subsystem: "io.ente.cast", category: "Slideshow")+@MainActorclass RealSlideshowService: ObservableObject {@Published var currentImageData: Data?@@ -57,9 +60,6 @@ class RealSlideshowService: ObservableObject {// swift-format-ignore: NeverForceUnwrapprivate let castDownloadURL = URL(string: "https://cast-albums.ente.com/download/")!- private let verboseFileLogging = false- private let verboseDecryptionLogging = false-private var isHandlingAuthExpiry: Bool = falsefunc pause() {@@ -159,8 +159,6 @@ class RealSlideshowService: ObservableObject {return}- print("Found \(fileCount) files total")-let validFileIDs = await Set(MainActor.run { allFiles.map(\.id) })await cleanupExpiredCache(validFileIDs: validFileIDs, castPayload: castPayload)guard storedCastPayload == castPayload else { return }@@ -175,10 +173,10 @@ class RealSlideshowService: ObservableObject {guard storedCastPayload == castPayload else { return }startSlideTimer()- print("Enhanced slideshow started with \(fileCount) slide(s)")+ logger.info("Slideshow started with \(fileCount) slides")} catch {- print("Failed to start slideshow: \(error)")+ logger.error("Failed to start slideshow: \(error.localizedDescription)")await MainActor.run {self.error = "Failed to load slideshow: \(error.localizedDescription)"}@@ -194,7 +192,6 @@ class RealSlideshowService: ObservableObject {stopPeriodicDiffPolling()}- // A late timer callback would surface a false empty state.slideTimer?.invalidate()slideTimer = nil@@ -207,8 +204,7 @@ class RealSlideshowService: ObservableObject {error = nil}- let stats = await getCacheStats()- print("Final cache stats: \(stats.count) files, \(stats.totalSize) bytes")+ logger.info("Slideshow stopped")await MainActor.run {isStopping = false@@ -220,7 +216,6 @@ class RealSlideshowService: ObservableObject {removeVideoEndObserver()await MainActor.run {- // A late timer callback would surface a false empty state.slideTimer?.invalidate()slideTimer = nilstoredCastPayload = nil@@ -241,7 +236,6 @@ class RealSlideshowService: ObservableObject {@MainActorprivate func initializeFileList(castPayload: CastPayload) async {if hasCompletedInitialFetch, !allFiles.isEmpty {- print("Using cached file list with \(allFiles.count) files")return}@@ -257,10 +251,9 @@ class RealSlideshowService: ObservableObject {if !allFiles.isEmpty {allFiles.shuffle()}- print("Initial diff fetch completed - \(allFiles.count) files cached (shuffled)")} catch {guard storedCastPayload == castPayload else { return }- print("Failed to fetch files: \(error)")+ logger.error("Failed to fetch files: \(error.localizedDescription)")hasCompletedInitialFetch = falseself.error = "Failed to load files: \(error.localizedDescription)"}@@ -271,9 +264,6 @@ class RealSlideshowService: ObservableObject {var sinceTime = await MainActor.run { lastUpdateTime }while hasMore {- if verboseFileLogging {- print("Fetching files since time: \(sinceTime)")- }let result = try await fetchFilesBatch(castPayload: castPayload, sinceTime: sinceTime)guard storedCastPayload == castPayload else { return }@@ -282,9 +272,6 @@ class RealSlideshowService: ObservableObject {await MainActor.run {if result.latestUpdateTime > self.lastUpdateTime {- print(- "Initial fetch updating lastUpdateTime: \(self.lastUpdateTime) β \(result.latestUpdateTime)",- )self.lastUpdateTime = result.latestUpdateTime}}@@ -294,9 +281,6 @@ class RealSlideshowService: ObservableObject {}guard storedCastPayload == castPayload else { return }- await print(- "Initial diff fetch complete - total files cached: \(MainActor.run { allFiles.count })",- )startPeriodicDiffPolling()}@@ -372,8 +356,7 @@ class RealSlideshowService: ObservableObject {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))")+ allFiles.remove(at: index)if originalCurrentFile?.id == id {currentFileWasDeleted = true@@ -394,9 +377,6 @@ class RealSlideshowService: ObservableObject {prefetchCache.removeValue(forKey: id)await removeCachedFileContent(fileID: id)-- } else {- print("Skipping deleted file \(id) (not in list)")}} else {do {@@ -407,18 +387,13 @@ class RealSlideshowService: ObservableObject {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))")- }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 {- print("Hash changed for file \(id) - clearing cache")prefetchCache.removeValue(forKey: id)await removeCachedFileContent(fileID: id)}@@ -428,18 +403,15 @@ class RealSlideshowService: ObservableObject {}} else {allFiles.append(file)- print("Added file: \(file.title) (ID: \(id))")}}} catch {- print("Error processing file \(id): \(error)")+ logger.error("Failed to process file metadata: \(error.localizedDescription)")}}}guard storedCastPayload == castPayload else { return }- print("File list now contains \(allFiles.count) files")-if allFiles.isEmpty {slideTimer?.invalidate()slideTimer = nil@@ -459,7 +431,7 @@ class RealSlideshowService: ObservableObject {totalSlides = allFiles.countif storedCastPayload != nil {- print("Restarting slideshow with \(allFiles.count) files")+ logger.info("Restarting slideshow with \(self.allFiles.count) files")// Clear before loading to avoid an empty-state flash.error = nil@@ -514,7 +486,6 @@ class RealSlideshowService: ObservableObject {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(@@ -523,10 +494,6 @@ class RealSlideshowService: ObservableObject {)guard storedCastPayload == payload else { return }- print(- "Successfully loaded file \(file.id): \(file.title) (\(decryptedData.count) bytes)",- )-prefetchCache[currentFileIndex] = decryptedDataawait updateCurrentSlide(with: decryptedData, file: file)@@ -536,10 +503,7 @@ class RealSlideshowService: ObservableObject {} catch {guard storedCastPayload == payload else { return }- let file = allFiles[currentFileIndex]- print(- "Failed to load file \(file.id): \(file.title) at index \(currentFileIndex) - \(error)",- )+ logger.error("Failed to load slideshow item: \(error.localizedDescription)")await MainActor.run {slideLoadingProgress = 0.0@@ -556,7 +520,6 @@ class RealSlideshowService: ObservableObject {@MainActorprivate 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 = nilcurrentFile = file@@ -567,14 +530,12 @@ class RealSlideshowService: ObservableObject {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}@@ -585,7 +546,8 @@ class RealSlideshowService: ObservableObject {startSlideTimer()} catch {- print("Failed to extract live photo components: \(error)")+ logger.error(+ "Failed to extract Live Photo components: \(error.localizedDescription)")currentImageData = datacurrentVideoData = nilcurrentVideoURL = nil@@ -596,7 +558,6 @@ class RealSlideshowService: ObservableObject {} else if file.isVideo {currentImageData = nillivePhotoVideoData = nil- // A temp file preserves the color space and avoids brightness shifts.do {let url: URLif let existing = videoTempFiles[file.id] {@@ -617,7 +578,7 @@ class RealSlideshowService: ObservableObject {currentVideoData = nilprepareVideoPlayer(url: url)} catch {- print("Failed to persist video temp file: \(error)")+ logger.error("Failed to save temporary video file: \(error.localizedDescription)")currentVideoURL = nil}} else {@@ -674,10 +635,6 @@ class RealSlideshowService: ObservableObject {do {let file = allFiles[currentFileIndex]- print(- "Attempting to load file \(file.id): \(file.title) at index \(currentFileIndex)",- )-let decryptedData = try await downloadAndDecryptFileContent(castPayload: payload,file: file,@@ -692,8 +649,6 @@ class RealSlideshowService: ObservableObject {slideLoadingProgress = 1.0}- print("Successfully loaded file \(file.id): \(file.title)")-if isPlaying, !isPaused {startSlideTimer()}@@ -703,8 +658,7 @@ class RealSlideshowService: ObservableObject {} catch {guard storedCastPayload == payload else { return }- let file = allFiles[currentFileIndex]- print("Failed to load file \(file.id): \(file.title) - \(error)")+ logger.error("Failed to load next slideshow item: \(error.localizedDescription)")currentFileIndex = (currentFileIndex + 1) % allFiles.countretryCount += 1}@@ -748,8 +702,6 @@ class RealSlideshowService: ObservableObject {} catch {guard storedCastPayload == payload else { return }- // Silently skip problematic files during prefetching- print("Prefetch failed for file \(prefetchIndex), will try on-demand")continue}@@ -830,8 +782,6 @@ class RealSlideshowService: ObservableObject {stopPeriodicDiffPolling()- print("Starting periodic diff polling (every \(diffPollingInterval)s)")-diffPollingTimer = Timer.scheduledTimer(withTimeInterval: diffPollingInterval,repeats: true,@@ -860,17 +810,12 @@ class RealSlideshowService: ObservableObject {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}- } else {- print("Periodic poll found no changes since \(currentTime)")}} catch {@@ -879,7 +824,7 @@ class RealSlideshowService: ObservableObject {{// fetchFilesBatch already handled this error.} else {- print("Periodic diff check failed: \(error)")+ logger.error("Periodic diff check failed: \(error.localizedDescription)")}}}@@ -921,19 +866,17 @@ class RealSlideshowService: ObservableObject {var request = URLRequest(url: url)request.setValue(castPayload.castToken, forHTTPHeaderField: "X-Cast-Access-Token")- let data = try await download(request, castPayload: castPayload, fileID: fileID)+ let data = try await download(request, castPayload: castPayload)guard !isProduction else { return data }let fileURL = try JSONDecoder().decode(FileURL.self, from: data).urlreturn try await download(URLRequest(url: fileURL),castPayload: castPayload,- fileID: fileID,)}private func download(- _ request: URLRequest, castPayload: CastPayload,- fileID: Int+ _ request: URLRequest, castPayload: CastPayload) async throws -> Data {let (data, response) = try await URLSession.shared.data(for: request)guard storedCastPayload == castPayload else { throw CancellationError() }@@ -944,7 +887,6 @@ class RealSlideshowService: ObservableObject {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{@@ -957,9 +899,6 @@ class RealSlideshowService: ObservableObject {throw CastError.serverError(httpResponse.statusCode, String(snippet))}}- if verboseFileLogging {- print("Successfully downloaded \(data.count) bytes for file \(fileID)")- }return data}@@ -975,25 +914,13 @@ class RealSlideshowService: ObservableObject {}if let cachedData = await getCachedFileContent(fileID: file.id) {- 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")- }let fileKey = try decryptFileKey(encryptedKey: file.encryptedKey,@@ -1025,45 +952,36 @@ class RealSlideshowService: ObservableObject {let fileDict = item["file"] as? [String: Any],let fileDecryptionHeader = fileDict["decryptionHeader"] as? Stringelse {- print("Missing required fields for file \(item["id"] ?? "unknown")")+ logger.warning("Skipping file with incomplete metadata")return nil}- do {- let fileKey = try decryptFileKey(- encryptedKey: encryptedKey,- nonce: keyDecryptionNonce,- collectionKey: collectionKey,- )- if verboseDecryptionLogging {- print("File key decrypted successfully")- }-- let metadata = try decryptMetadata(- encryptedData: encryptedMetadata,- decryptionHeader: metadataHeader,- fileKey: fileKey,- )+ let fileKey = try decryptFileKey(+ encryptedKey: encryptedKey,+ nonce: keyDecryptionNonce,+ collectionKey: collectionKey,+ )- let fileMetadata = try parseFileMetadata(data: metadata)-- let isVideo = fileMetadata.fileType == 1- let isLivePhoto = fileMetadata.fileType == 2- return CastFile(- id: id,- title: fileMetadata.title,- isVideo: isVideo,- isLivePhoto: isLivePhoto,- encryptedKey: encryptedKey,- keyDecryptionNonce: keyDecryptionNonce,- fileDecryptionHeader: fileDecryptionHeader,- hash: fileMetadata.hash,- )+ let metadata = try decryptMetadata(+ encryptedData: encryptedMetadata,+ decryptionHeader: metadataHeader,+ fileKey: fileKey,+ )- } catch {- print("Decryption failed: \(error)")- throw error- }+ let fileMetadata = try parseFileMetadata(data: metadata)++ let isVideo = fileMetadata.fileType == 1+ let isLivePhoto = fileMetadata.fileType == 2+ return CastFile(+ id: id,+ title: fileMetadata.title,+ isVideo: isVideo,+ isLivePhoto: isLivePhoto,+ encryptedKey: encryptedKey,+ keyDecryptionNonce: keyDecryptionNonce,+ fileDecryptionHeader: fileDecryptionHeader,+ hash: fileMetadata.hash,+ )}private func decryptFileKey(@@ -1098,18 +1016,12 @@ class RealSlideshowService: ObservableObject {throw CastError.decryptionError("Invalid base64 in metadata decryption")}- print(- "XChaCha20: encrypted=\(encryptedBytes.count)b, header=\(headerBytes.count)b, key=\(fileKey.count)b",- )-do {- let decryptedData = try decryptSecretStream(+ return try decryptSecretStream(encryptedData: encryptedBytes,header: headerBytes,key: fileKey,)- print("Metadata decrypted using Rust crypto: \(decryptedData.count) bytes")- return decryptedData} catch {throwCastError@@ -1125,12 +1037,6 @@ class RealSlideshowService: ObservableObject {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",- )- }-do {return try decryptSecretStream(encryptedData: encryptedData,@@ -1172,26 +1078,15 @@ class RealSlideshowService: ObservableObject {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 = 0for cachedFileID in cachedFileIDs {guard storedCastPayload == castPayload else { return }if !validFileIDs.contains(cachedFileID) {await removeCachedFileContent(fileID: cachedFileID)- removedCount += 1}}-- if removedCount > 0 {- let newStats = await getCacheStats()- print(- "Cache cleanup complete - removed \(removedCount) expired files, now \(newStats.count) files (\(newStats.totalSize) bytes)",- )- }}private func removeCachedFileContent(fileID: Int) async {@@ -1201,10 +1096,6 @@ class RealSlideshowService: ObservableObject {func clearCache() async {await fileCache.clear()}-- private func getCacheStats() async -> (count: Int, totalSize: Int) {- await fileCache.getStats()- }}func extractZipUsingFoundation(zipURL: URL, to destinationURL: URL) throws {@@ -1259,20 +1150,12 @@ func extractLivePhotoComponents(from zipData: Data) throws -> LivePhotoComponentif (try? fileURL.resourceValues(forKeys: Set(resourceKeys)).isDirectory) == true {continue}- let filename = fileURL.lastPathComponent-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) {videoData = try Data(contentsOf: fileURL)videoPath = fileURL- print("Extracted live photo video: \(filename) (\(videoData?.count ?? 0) bytes)")- } else {- if imageData == nil || videoData == nil {- print("Ignoring non-component file in live photo zip: \(filename)")- }}}@@ -1286,9 +1169,6 @@ func extractLivePhotoComponents(from zipData: Data) throws -> LivePhotoComponentif 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 videoData == nil {@@ -1298,9 +1178,6 @@ func extractLivePhotoComponents(from zipData: Data) throws -> LivePhotoComponent{videoData = try? Data(contentsOf: guessVideo)videoPath = guessVideo- if videoData != nil {- print("Heuristic video pick: \(guessVideo.lastPathComponent)")- }}}}@@ -1319,7 +1196,6 @@ func extractLivePhotoComponents(from zipData: Data) throws -> LivePhotoComponent)} 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/SlideshowView.swift b/apple/apps/cast/Cast/Views/SlideshowView.swiftindex 79b5efb8b4..0c93522086 100644--- a/apple/apps/cast/Cast/Views/SlideshowView.swift+++ b/apple/apps/cast/Cast/Views/SlideshowView.swift@@ -1,6 +1,9 @@+import OSLogimport SwiftUIimport UIKit+private let logger = Logger(subsystem: "io.ente.cast", category: "SlideshowView")+struct SlideshowView: View {let imageData: Data?let videoData: Data?@@ -105,7 +108,7 @@ struct SlideshowView: View {.opacity(imageOpacity)}.onAppear {- animateImageIn(bytes: displayImageData?.count ?? 0, isLive: isLivePhoto)+ animateImageIn(bytes: displayImageData?.count ?? 0)}.onDisappear {imageScale = 1.0@@ -153,7 +156,7 @@ struct SlideshowView: View {}displayImageData = newData- animateImageIn(bytes: newData.count, isLive: isLivePhoto)+ animateImageIn(bytes: newData.count)}}}@@ -186,7 +189,7 @@ struct SlideshowView: View {imageOpacity = 1.0previousImageOpacity = 0.0displayImageData = initialImageData- animateImageIn(bytes: initialImageData.count, isLive: isLivePhoto)+ animateImageIn(bytes: initialImageData.count)}}}@@ -322,7 +325,6 @@ struct SlideshowView: View {private func decodedUIImage(from data: Data) -> UIImage? {imageDecodeFailed = falseif let uiImage = UIImage(data: data) {- // Accessing cgImage forces decompression.if let cg = uiImage.cgImage {return UIImage(cgImage: cg,@@ -333,12 +335,12 @@ struct SlideshowView: View {return uiImage} else {imageDecodeFailed = true- print("UIImage decode failed (bytes: \(data.count))")+ logger.error("Image decoding failed (\(data.count) bytes)")return nil}}- private func animateImageIn(bytes: Int, isLive: Bool) {+ private func animateImageIn(bytes: Int) {lastImageBytes = bytesimageScale = 1.0@@ -347,8 +349,6 @@ struct SlideshowView: View {previousImageOpacity = 0.0}- print("Displaying \(isLive ? "live" : "static") image (\(bytes) bytes)")-Task {try? await Task.sleep(nanoseconds: 300_000_000)await MainActor.run {diff --git a/apple/apps/cast/Cast/Views/VideoPlayerView.swift b/apple/apps/cast/Cast/Views/VideoPlayerView.swiftindex 00002f8569..e38fa37717 100644--- a/apple/apps/cast/Cast/Views/VideoPlayerView.swift+++ b/apple/apps/cast/Cast/Views/VideoPlayerView.swift@@ -1,8 +1,11 @@import AVFoundationimport AVKit+import OSLogimport SwiftUIimport UIKit+private let logger = Logger(subsystem: "io.ente.cast", category: "VideoPlayer")+struct VideoPlayerView: View {let videoData: Datalet suggestedFilename: String?@@ -89,7 +92,7 @@ struct VideoPlayerView: View {tryVideoFallback(originalURL: tempURL)}} catch {- print("Failed to setup video player: \(error)")+ logger.error("Failed to set up video player: \(error.localizedDescription)")await MainActor.run {showErrorState()}@@ -113,7 +116,7 @@ struct VideoPlayerView: View {setupPlayer()}} catch {- print("Video fallback also failed: \(error)")+ logger.error("Video fallback failed: \(error.localizedDescription)")showErrorState()}}@@ -128,8 +131,7 @@ struct VideoPlayerView: View {timer.invalidate()case .failed:if let error = playerItem.error {- print("Video player failed with error: \(error)")- print("Error details: \(error.localizedDescription)")+ logger.error("Video player failed: \(error.localizedDescription)")}timer.invalidate()Task { @MainActor in@@ -153,7 +155,7 @@ struct VideoPlayerView: View {try AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback)try AVAudioSession.sharedInstance().setActive(true)} catch {- print("Failed to set audio session: \(error)")+ logger.error("Failed to set up audio session: \(error.localizedDescription)")}setupPlayerObservers()@@ -183,7 +185,7 @@ struct VideoPlayerView: View {if let error = notification.userInfo?[AVPlayerItemFailedToPlayToEndTimeErrorKey] as? Error{- print("Video playback failed: \(error)")+ logger.error("Video playback failed: \(error.localizedDescription)")}}@@ -235,7 +237,6 @@ struct VideoPlayerView: View {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)if ftyp == Data("ftyp".utf8) {@@ -250,7 +251,6 @@ struct VideoPlayerView: View {}}- // 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@@ -259,7 +259,6 @@ struct VideoPlayerView: View {}}- // AVI format (less compatible with tvOS)if signature == Data("RIFF".utf8), headerBytes.count >= 12 {let aviSignature = headerBytes.subdata(in: 8..<12)if aviSignature == Data("AVI ".utf8) {@@ -267,12 +266,10 @@ struct VideoPlayerView: View {}}- // WebM format (limited support on tvOS)if signature == Data([0x1A, 0x45, 0xDF, 0xA3]) {return "webm"}- // MKV formatif signature == Data([0x1A, 0x45, 0xDF, 0xA3]) {return "mkv"}@@ -298,7 +295,7 @@ struct VideoPlayerView: View {options: .notifyOthersOnDeactivation,)} catch {- print("Failed to deactivate audio session: \(error)")+ logger.error("Failed to deactivate audio session: \(error.localizedDescription)")}player = nil