π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Strip emoji debug logging from the cast app
Manav Rathi2f67b0d44122
diff --git a/mobile/native/apple/apps/cast/Cast/Services/CastPairingService.swift b/mobile/native/apple/apps/cast/Cast/Services/CastPairingService.swiftindex 8874225b5b..9c6a76dc0d 100644--- a/mobile/native/apple/apps/cast/Cast/Services/CastPairingService.swift+++ b/mobile/native/apple/apps/cast/Cast/Services/CastPairingService.swift@@ -56,7 +56,7 @@ class RealCastPairingService {// Log when switching to extended interval for the first timeif elapsed >= pollingIntervalSwitchTime && newInterval == extendedPollingInterval && !hasLoggedIntervalSwitch {- print("π Switched to extended polling interval (\(extendedPollingInterval)s) after \(Int(elapsed))s")+ print("Switched to extended polling interval (\(extendedPollingInterval)s) after \(Int(elapsed))s")hasLoggedIntervalSwitch = true}@@ -68,12 +68,10 @@ class RealCastPairingService {}func registerDevice() async throws -> CastDevice {- print("π Generating real X25519 keypair...")let keys = try generateKeyPair()let publicKeyBase64 = keys.publicKey.base64EncodedString()- print("π‘ Registering device with Ente production server...")- print("π POST \(baseURL)/cast/device-info")+ print("POST \(baseURL)/cast/device-info")let url = URL(string: "\(baseURL)/cast/device-info")!var request = URLRequest(url: url)@@ -95,7 +93,7 @@ class RealCastPairingService {let deviceResponse = try JSONDecoder().decode(DeviceRegistrationResponse.self, from: data)- print("β Device registered! Code from server: \(deviceResponse.deviceCode)")+ print("Device registered! Code from server: \(deviceResponse.deviceCode)")return CastDevice(deviceCode: deviceResponse.deviceCode,@@ -107,7 +105,6 @@ class RealCastPairingService {func startPolling(device: CastDevice, onPayloadReceived: @escaping (CastPayload) -> Void, onError: @escaping (Error) -> Void) {guard !hasDeliveredPayload else { return }guard !isPolling else { return }- print("π Starting real polling of Ente production server...")pollingTimer?.invalidate()isPolling = truepollingStartTime = Date()@@ -138,7 +135,7 @@ class RealCastPairingService {defer { isFetchingPayload = false }do {let url = URL(string: "\(baseURL)/cast/cast-data/\(device.deviceCode)")!- print("π‘ GET \(url.absoluteString)")+ print("GET \(url.absoluteString)")let (data, response) = try await URLSession.shared.data(from: url)@@ -148,7 +145,6 @@ class RealCastPairingService {if httpResponse.statusCode == 404 {// No payload available yet - this is expected- print("β³ No encrypted payload available yet")return}@@ -159,11 +155,9 @@ class RealCastPairingService {let castDataResponse = try JSONDecoder().decode(CastDataResponse.self, from: data)guard let encryptedData = castDataResponse.encCastData else {- print("β³ No encrypted payload in response yet")return}- print("π Received encrypted payload! Decrypting...")// Decrypt the payload using our private keylet payload = try await decryptPayload(@@ -172,7 +166,6 @@ class RealCastPairingService {privateKey: device.privateKey)- print("β Successfully decrypted cast payload!")hasDeliveredPayload = truestopPolling()@@ -181,7 +174,7 @@ class RealCastPairingService {}} catch {- print("β Polling error: \(error)")+ print("Polling error: \(error)")await MainActor.run {onError(error)}@@ -224,11 +217,9 @@ class RealCastPairingService {pollingTimer = nilisPolling = falsepollingStartTime = nil- print("βΉοΈ Stopped polling production server")}func resetForNewSession() {- print("π Resetting pairing service for new session")stopPolling()hasDeliveredPayload = falsehasLoggedIntervalSwitch = falsediff --git a/mobile/native/apple/apps/cast/Cast/Services/FileCache.swift b/mobile/native/apple/apps/cast/Cast/Services/FileCache.swiftindex 516c3f3242..98f52a0d65 100644--- a/mobile/native/apple/apps/cast/Cast/Services/FileCache.swift+++ b/mobile/native/apple/apps/cast/Cast/Services/FileCache.swift@@ -70,7 +70,7 @@ actor ThreadSafeFileCache {// Save metadatasaveCacheMetadata()- 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) {@@ -85,7 +85,7 @@ actor ThreadSafeFileCache {// Save updated metadatasaveCacheMetadata()- print("ποΈ Removed cached content for file \(fileID) (\(removedData.count) bytes)")+ print("Removed cached content for file \(fileID) (\(removedData.count) bytes)")}}@@ -102,7 +102,7 @@ actor ThreadSafeFileCache {// Clear metadatatry? FileManager.default.removeItem(at: metadataURL)- print("ποΈ Cleared file content cache (\(clearedCount) files)")+ print("Cleared file content cache (\(clearedCount) files)")}func getStats() -> (count: Int, totalSize: Int) {@@ -126,7 +126,7 @@ 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")+ print("Evicted file \(oldest) (\(data.count) bytes) to control cache size")}}totalBytes -= removedBytes@@ -134,18 +134,17 @@ actor ThreadSafeFileCache {// Save updated metadata after evictionsaveCacheMetadata()- print("π¦ Cache GC complete: now \(cache.count) files, \(totalBytes) bytes")+ print("Cache GC complete: now \(cache.count) files, \(totalBytes) bytes")}private func loadCacheFromDisk() {// Load metadataguard let metadataData = try? Data(contentsOf: metadataURL),let metadata = try? JSONDecoder().decode(CacheMetadata.self, from: metadataData) else {- print("π No existing cache metadata found - starting fresh")return}- print("π Loading existing cache from disk - \(metadata.fileIDs.count) files")+ print("Loading existing cache from disk - \(metadata.fileIDs.count) files")// Load cache order and calculate total bytesvar loadedBytes = 0@@ -165,7 +164,7 @@ actor ThreadSafeFileCache {cacheOrder = validFileIDstotalBytes = loadedBytes- print("π Loaded \(validFileIDs.count) cached files (\(loadedBytes) bytes) from disk")+ print("Loaded \(validFileIDs.count) cached files (\(loadedBytes) bytes) from disk")// Clean up any invalid entriesif validFileIDs.count != metadata.fileIDs.count {diff --git a/mobile/native/apple/apps/cast/Cast/Utils/ScreenSaverManager.swift b/mobile/native/apple/apps/cast/Cast/Utils/ScreenSaverManager.swiftindex b948e7c8b7..b58e6102ec 100644--- a/mobile/native/apple/apps/cast/Cast/Utils/ScreenSaverManager.swift+++ b/mobile/native/apple/apps/cast/Cast/Utils/ScreenSaverManager.swift@@ -17,13 +17,11 @@ class ScreenSaverManager: ObservableObject {private func startPrevention() {guard !isDisabled else {- print("π« Screen saver prevention already enabled")return}UIApplication.shared.isIdleTimerDisabled = trueisDisabled = true- print("π« Screen saver prevention enabled")// Fallback for problematic tvOS versions where isIdleTimerDisabled doesn't work reliably// This timer periodically refreshes the setting to ensure it stays disabled@@ -35,7 +33,6 @@ class ScreenSaverManager: ObservableObject {private func stopPrevention() {guard isDisabled else {- print("β Screen saver prevention already disabled")return}@@ -43,7 +40,6 @@ class ScreenSaverManager: ObservableObject {refreshTimer = nilUIApplication.shared.isIdleTimerDisabled = falseisDisabled = false- print("β Screen saver prevention disabled")}// Cleanup method for app terminationdiff --git a/mobile/native/apple/apps/cast/Cast/ViewModels/CastViewModel.swift b/mobile/native/apple/apps/cast/Cast/ViewModels/CastViewModel.swiftindex 9b77abb410..fd30b437ad 100644--- a/mobile/native/apple/apps/cast/Cast/ViewModels/CastViewModel.swift+++ b/mobile/native/apple/apps/cast/Cast/ViewModels/CastViewModel.swift@@ -13,15 +13,15 @@ class CastViewModel: ObservableObject {@Published var statusMessage: String = ""@Published var isLoading: Bool = false@Published var errorMessage: String?-+// MARK: - Private Propertiesprivate var cancellables = Set<AnyCancellable>()private let pairingService: RealCastPairingServiceprivate let castSession: CastSession-- // MARK: - Public Properties++ // MARK: - Public Propertiespublic let slideshowService: RealSlideshowService-+enum CurrentView {case pairingcase connecting@@ -29,30 +29,24 @@ class CastViewModel: ObservableObject {case errorcase empty}-+init() {- print("π Initializing with REAL Ente production server calls!")-self.castSession = CastSession()self.pairingService = RealCastPairingService()self.slideshowService = RealSlideshowService()-+setupBindings()-- // Auto-start cast session on app launch (like web implementation)startCastSession()}-+private func setupBindings() {- // Bind to cast session state changescastSession.$state.receive(on: DispatchQueue.main).sink { [weak self] state inself?.handleStateChange(state)}.store(in: &cancellables)-- // Bind to slideshow service updates+slideshowService.$currentImageData.receive(on: DispatchQueue.main).assign(to: \.currentImageData, on: self)@@ -70,7 +64,7 @@ class CastViewModel: ObservableObject {}}.store(in: &cancellables)-+slideshowService.$currentVideoData.receive(on: DispatchQueue.main).assign(to: \.currentVideoData, on: self)@@ -87,12 +81,12 @@ class CastViewModel: ObservableObject {}}.store(in: &cancellables)-+slideshowService.$currentFile.receive(on: DispatchQueue.main).assign(to: \.currentFile, on: self).store(in: &cancellables)-+slideshowService.$error.receive(on: DispatchQueue.main).compactMap { $0 }@@ -100,31 +94,28 @@ class CastViewModel: ObservableObject {self?.handleSlideshowError(error)}.store(in: &cancellables)-- // Listen for authentication expired notifications+NotificationCenter.default.publisher(for: .authenticationExpired).receive(on: DispatchQueue.main).sink { [weak self] _ inself?.handleAuthenticationExpired()}.store(in: &cancellables)-- // Listen for slideshow restarted notifications+NotificationCenter.default.publisher(for: .slideshowRestarted).receive(on: DispatchQueue.main).sink { [weak self] _ inself?.handleSlideshowRestarted()}.store(in: &cancellables)-- // Listen for app lifecycle events to manage screen saver prevention+NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification).receive(on: DispatchQueue.main).sink { _ inScreenSaverManager.allowScreenSaver()}.store(in: &cancellables)-+NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification).receive(on: DispatchQueue.main).sink { [weak self] _ in@@ -134,20 +125,19 @@ class CastViewModel: ObservableObject {}.store(in: &cancellables)}-+// MARK: - Public Methods-+func startCastSession() {castSession.setState(.registering)currentView = .connectingisLoading = truestatusMessage = "Registering device..."-+Task {do {- // Register device with the serverlet device = try await pairingService.registerDevice()-+await MainActor.run {deviceCode = device.deviceCodecastSession.setState(.waitingForPairing(deviceCode: device.deviceCode))@@ -155,8 +145,7 @@ class CastViewModel: ObservableObject {statusMessage = "Waiting for connection..."isLoading = false}-- // Start polling for payload+pairingService.startPolling(device: device,onPayloadReceived: { [weak self] payload in@@ -170,19 +159,16 @@ class CastViewModel: ObservableObject {}})-+} catch {handleNetworkError(error)}}}-+func resetSession() async {- print("π Resetting cast session...")-- // Ensure screen saver prevention is disabled during resetScreenSaverManager.allowScreenSaver()-+currentView = .connectingdeviceCode = ""currentImageData = nil@@ -191,43 +177,35 @@ class CastViewModel: ObservableObject {statusMessage = ""isLoading = falseerrorMessage = nil-- // Clean up services+pairingService.stopPolling()await slideshowService.stop()castSession.setState(.idle)- print("β Cast session reset complete")}-+private func handlePayloadReceived(_ payload: CastPayload) {// Idempotency: if we're already connected with same payload, skipif case .connected(let existing) = castSession.state, existing == payload {return}- print("π Cast payload received successfully!")-- // Update cast session with the payload+castSession.setState(.connected(payload))currentView = .connectingstatusMessage = ""isLoading = true-- // Stop polling once we receive payload- // pairingService.stopPolling() // redundant; pairing service already stops itself when delivering payload-- // Start the slideshow with the full payload+Task {// Add a small delay to prevent flickering from rapid state changes- try? await Task.sleep(nanoseconds: 500_000_000) // 0.5 seconds-+ try? await Task.sleep(nanoseconds: 500_000_000)+await slideshowService.start(castPayload: payload)-+// Additional delay to ensure slideshow is properly loaded- try? await Task.sleep(nanoseconds: 1_000_000_000) // 1 second-+ try? await Task.sleep(nanoseconds: 1_000_000_000)+await MainActor.run {let hasError = slideshowService.error != nil && !slideshowService.error!.isEmpty-+if hasError {handleSlideshowError(slideshowService.error!)} else {@@ -238,10 +216,10 @@ class CastViewModel: ObservableObject {}}}-+func retryOperation() {errorMessage = nil-+switch currentView {case .error:startCastSession()@@ -249,52 +227,51 @@ class CastViewModel: ObservableObject {break}}-+// MARK: - Slideshow Navigation-+func nextSlide() {guard currentView == .slideshow else { return }-+Task {await slideshowService.nextSlide()}}-+func previousSlide() {guard currentView == .slideshow else { return }-+Task {await slideshowService.previousSlide()}}-+// MARK: - Private Methods-+private func handleStateChange(_ state: CastSessionState) {switch state {case .idle:currentView = .connecting-+case .registering:currentView = .connectingstatusMessage = "Registering device..."isLoading = true-+case .waitingForPairing(let code):deviceCode = codecurrentView = .pairingstatusMessage = "Waiting for connection..."isLoading = false-+case .connected(let payload):handlePayloadReceived(payload)-+case .error(let message):handleError(message)}}--+private func handleSlideshowError(_ error: String) {// Prevent stale slideshow errors from a previous (expired) session// from overriding the fresh pairing code UI. Only react to slideshow@@ -304,12 +281,11 @@ class CastViewModel: ObservableObject {error.contains("available in this album") ||error.contains("available in this collection") ||error.contains("Empty file list")-+if (currentView == .pairing || currentView == .connecting) && !isEmptyStateError {- // Ignore slideshow-originating errors during pairing / reconnection, except empty statereturn}-+if isEmptyStateError {currentView = .emptystatusMessage = ""@@ -318,41 +294,33 @@ class CastViewModel: ObservableObject {handleError(error)}}--+private func handleError(_ message: String) {- print("β Cast Error: \(message)")+ print("Cast Error: \(message)")currentView = .errorerrorMessage = messageisLoading = falsestatusMessage = ""castSession.setState(.error(message))}-+private func handleNetworkError(_ error: Error) {- // Show error immediatelyhandleError("An error occurred: \(error.localizedDescription)")-- // Wait 5 seconds then reset state for new device registration+Task {- try? await Task.sleep(nanoseconds: 5_000_000_000) // 5 seconds+ try? await Task.sleep(nanoseconds: 5_000_000_000)await MainActor.run {- // Reset to start new device registrationstartCastSession()}}}-+private func handleAuthenticationExpired() {- print("π Authentication expired notification received - clearing all state and restarting")Task {await resetSession()- // Clear all in-memory token state in slideshow serviceawait slideshowService.clearExpiredTokenState()- // Reset pairing service to allow fresh pollingpairingService.resetForNewSession()-- // Ensure we're in a clean state before starting new session+await MainActor.run {// Directly set to pairing once device registration begins to avoid brief empty/error flickercurrentView = .connecting@@ -360,27 +328,18 @@ class CastViewModel: ObservableObject {statusMessage = "Starting fresh session..."isLoading = true}-- // Generate fresh device code for new pairing+startCastSession()}}-+private func handleSlideshowRestarted() {- print("π¬ Slideshow restarted notification received")- // Wait for image data to be available before transitioning- // The binding will handle the transition when data arrivesstatusMessage = ""isLoading = falseerrorMessage = nil-- // Only transition if we already have image data+if slideshowService.currentImageData != nil || slideshowService.currentVideoData != nil {- print("π¬ Image/video data available - transitioning to slideshow view")currentView = .slideshow- } else {- print("β³ Waiting for image data before transitioning to slideshow view")}}-}diff --git a/mobile/native/apple/apps/cast/Cast/ViewModels/SlideshowService.swift b/mobile/native/apple/apps/cast/Cast/ViewModels/SlideshowService.swiftindex 1fbb2ecc2f..6e258ca0ab 100644--- a/mobile/native/apple/apps/cast/Cast/ViewModels/SlideshowService.swift+++ b/mobile/native/apple/apps/cast/Cast/ViewModels/SlideshowService.swift@@ -122,7 +122,6 @@ class RealSlideshowService: ObservableObject {// For single photo, just restart the timer without changing indexif allFiles.count == 1 {- print("πΈ Single photo in album - restarting timer")if isPlaying && !isPaused {startSlideTimer()}@@ -131,7 +130,6 @@ class RealSlideshowService: ObservableObject {// Check if current file was deleted and handle accordinglyif currentFileWasDeleted {- print("βοΈ Handling deleted current file")currentFileWasDeleted = false// Current index already adjusted in processDiffBatchif currentFileIndex >= allFiles.count {@@ -160,7 +158,6 @@ class RealSlideshowService: ObservableObject {// MARK: - Main Entry Pointsfunc start(castPayload: CastPayload) async {- print("π¬ Starting slideshow with payload:")// Enable screen saver prevention for slideshowScreenSaverManager.preventScreenSaver()@@ -175,7 +172,6 @@ class RealSlideshowService: ObservableObject {}do {- print("π‘ Fetching files from Ente museum server...")// Initialize file list and fetch all files with paginationawait initializeFileList(castPayload: castPayload)@@ -188,7 +184,7 @@ class RealSlideshowService: ObservableObject {return}- print("π Found \(fileCount) files total")+ print("Found \(fileCount) files total")// Clean up cache for files no longer in the collectionlet validFileIDs = Set(await MainActor.run { allFiles.map { $0.id } })@@ -208,15 +204,14 @@ class RealSlideshowService: ObservableObject {// For single photo, ensure timer is started even if it's an imageif fileCount == 1 {- print("πΈ Starting slideshow with single photo")startSlideTimer()} else {startSlideTimer()}- print("β Enhanced slideshow started with \(fileCount) slide(s)")+ print("Enhanced slideshow started with \(fileCount) slide(s)")} catch {- print("β Failed to start slideshow: \(error)")+ print("Failed to start slideshow: \(error)")await MainActor.run {self.error = "Failed to load slideshow: \(error.localizedDescription)"}@@ -224,7 +219,6 @@ class RealSlideshowService: ObservableObject {}func stop() async {- print("βΉοΈ Stopping real slideshow service...")// Disable screen saver prevention when stopping slideshowScreenSaverManager.allowScreenSaver()@@ -254,8 +248,7 @@ class RealSlideshowService: ObservableObject {// Print final cache statisticslet stats = await getCacheStats()- print("π Final cache stats: \(stats.count) files, \(stats.totalSize) bytes")- print("β Real slideshow service stopped")+ print("Final cache stats: \(stats.count) files, \(stats.totalSize) bytes")// Reset stopping flag for next sessionawait MainActor.run {@@ -264,7 +257,6 @@ class RealSlideshowService: ObservableObject {}func clearExpiredTokenState() async {- print("π§Ή Clearing expired token state from slideshow service")// Ensure screen saver prevention is disabled when clearing expired stateScreenSaverManager.allowScreenSaver()@@ -296,12 +288,11 @@ class RealSlideshowService: ObservableObject {private func initializeFileList(castPayload: CastPayload) async {// Check if we've already completed the initial fetchif hasCompletedInitialFetch && !allFiles.isEmpty {- print("π Using cached file list with \(allFiles.count) files")+ print("Using cached file list with \(allFiles.count) files")return}// Reset state for fresh fetch- print("π‘ Performing initial diff fetch...")allFiles.removeAll()lastUpdateTime = 0currentFileIndex = 0@@ -315,11 +306,10 @@ class RealSlideshowService: ObservableObject {// Shuffle order to randomize slideshow similar to web experienceif !allFiles.isEmpty {allFiles.shuffle()- print("π Shuffled file order for slideshow")}- print("β Initial diff fetch completed - \(allFiles.count) files cached (shuffled)")+ print("Initial diff fetch completed - \(allFiles.count) files cached (shuffled)")} catch {- print("β Failed to fetch files: \(error)")+ print("Failed to fetch files: \(error)")hasCompletedInitialFetch = false // Ensure we retry on next attemptself.error = "Failed to load files: \(error.localizedDescription)"}@@ -330,7 +320,7 @@ class RealSlideshowService: ObservableObject {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)// Process the batch on MainActor@@ -339,7 +329,7 @@ class RealSlideshowService: ObservableObject {// Update pagination state on MainActorawait 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}}@@ -349,7 +339,7 @@ class RealSlideshowService: ObservableObject {}- print("π Initial diff fetch complete - total files cached: \(await MainActor.run { allFiles.count })")+ print("Initial diff fetch complete - total files cached: \(await MainActor.run { allFiles.count })")// Start periodic polling after initial fetch completesawait MainActor.run {@@ -390,7 +380,6 @@ class RealSlideshowService: ObservableObject {// Parse the diff responseguard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],let diff = json["diff"] as? [[String: Any]] else {- print("β Failed to parse JSON response")throw CastError.networkError("Invalid JSON response")}@@ -424,7 +413,6 @@ class RealSlideshowService: ObservableObject {for item in items {guard let id = item["id"] as? Int else {- print(" β No ID found in item")continue}@@ -434,12 +422,11 @@ class RealSlideshowService: ObservableObject {// Remove file from list if it existsif let index = allFiles.firstIndex(where: { $0.id == id }) {let removedFile = allFiles.remove(at: index)- print(" ποΈ Removed deleted file: \(removedFile.title) (ID: \(id))")+ print("Removed deleted file: \(removedFile.title) (ID: \(id))")// Check if deleted file was the currently playing oneif originalCurrentFile?.id == id {currentFileWasDeleted = true- print(" β οΈ Currently playing file was deleted - will handle gracefully")// Immediately move to next slide if current was deletedTask {@@ -459,7 +446,7 @@ class RealSlideshowService: ObservableObject {await removeCachedFileContent(fileID: id)} else {- print(" βοΈ Skipping deleted file \(id) (not in list)")+ print("Skipping deleted file \(id) (not in list)")}} else {// Add or update file@@ -468,18 +455,18 @@ class RealSlideshowService: ObservableObject {if let file = try await decryptFileMetadata(item: item, collectionKey: collectionKey) {// Skip pure videos (we only want images + live photos)if file.isVideo && !file.isLivePhoto {- if verboseFileLogging { print(" π« Skipping video file: \(file.title) (ID: \(id))") }+ if verboseFileLogging { print("Skipping video file: \(file.title) (ID: \(id))") }continue}// Check if file already existsif let existingIndex = allFiles.firstIndex(where: { $0.id == id }) {let oldFile = allFiles[existingIndex]allFiles[existingIndex] = file- print(" π Updated file: \(file.title) (ID: \(id))")+ print("Updated file: \(file.title) (ID: \(id))")// Check if hash changed - clear cache if soif oldFile.hash != file.hash && file.hash != nil {- print(" π§Ή Hash changed for file \(id) - clearing cache")+ print("Hash changed for file \(id) - clearing cache")prefetchCache.removeValue(forKey: id)await removeCachedFileContent(fileID: id)}@@ -490,21 +477,20 @@ class RealSlideshowService: ObservableObject {}} else {allFiles.append(file)- print(" β Added file: \(file.title) (ID: \(id))")+ print("Added file: \(file.title) (ID: \(id))")}}} catch {- print(" β Error processing file \(id): \(error)")+ print("Error processing file \(id): \(error)")}}}- print("π File list now contains \(allFiles.count) files")+ print("File list now contains \(allFiles.count) files")// Handle state transitionsif allFiles.isEmpty {// Transition to empty state- print("π All files removed - showing empty state")slideTimer?.invalidate()slideTimer = nilisPlaying = false@@ -519,14 +505,13 @@ class RealSlideshowService: ObservableObject {error = "No media files available in this album"} else if wasEmpty {// Transition from empty to having files- print("π· Files added to empty album - starting slideshow")currentFileIndex = 0currentSlideIndex = 0totalSlides = allFiles.count// Restart slideshow if we have a stored payloadif let payload = storedCastPayload {- print("π Restarting slideshow with \(allFiles.count) files")+ print("Restarting slideshow with \(allFiles.count) files")error = nil // Clear error first to avoid UI flicker// Display first slide and start slideshow@@ -585,7 +570,7 @@ class RealSlideshowService: ObservableObject {// Load from networkdo {let file = allFiles[currentFileIndex]- print("π Loading file \(file.id): \(file.title) at index \(currentFileIndex)")+ print("Loading file \(file.id): \(file.title) at index \(currentFileIndex)")await MainActor.run { slideLoadingProgress = 0.5 }let decryptedData = try await downloadAndDecryptFileContent(@@ -593,7 +578,7 @@ class RealSlideshowService: ObservableObject {file: file)- print("β Successfully loaded file \(file.id): \(file.title) (\(decryptedData.count) bytes)")+ print("Successfully loaded file \(file.id): \(file.title) (\(decryptedData.count) bytes)")// Cache the dataprefetchCache[currentFileIndex] = decryptedData@@ -606,7 +591,7 @@ class RealSlideshowService: ObservableObject {} catch {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)")// Auto-skip problematic files and continue slideshowawait MainActor.run {@@ -637,19 +622,17 @@ class RealSlideshowService: ObservableObject {// For live photos, only set the image component for displayif let imageData = components.imageData {currentImageData = imageData- print("πΈ Live photo image component loaded: \(imageData.count) bytes")+ print("Live photo image component loaded: \(imageData.count) bytes")} else {- print("β οΈ Live photo missing image component - using original data as fallback")currentImageData = data}// Store video component separately for long-press playbackif let videoData = components.videoData {livePhotoVideoData = videoData- print("π₯ Live photo video component stored: \(videoData.count) bytes")+ print("Live photo video component stored: \(videoData.count) bytes")} else {livePhotoVideoData = nil- print("β οΈ Live photo missing video component")}// Clear video properties to ensure image display@@ -660,7 +643,7 @@ class RealSlideshowService: ObservableObject {startSlideTimer()} catch {- print("β Failed to extract live photo components: \(error)")+ print("Failed to extract live photo components: \(error)")// Fallback to treating as regular imagecurrentImageData = datacurrentVideoData = nil@@ -690,7 +673,7 @@ class RealSlideshowService: ObservableObject {currentVideoData = nil // release raw data memoryprepareVideoPlayer(url: url)} catch {- print("β Failed to persist video temp file: \(error)")+ print("Failed to persist video temp file: \(error)")currentVideoURL = nil}} else {@@ -706,7 +689,6 @@ class RealSlideshowService: ObservableObject {// If we just transitioned from empty to having content, notify the UIif wasEmpty {- print("π· Slideshow restarted with image data - notifying UI")NotificationCenter.default.post(name: .slideshowRestarted, object: nil)}}@@ -753,7 +735,7 @@ class RealSlideshowService: ObservableObject {guard let payload = storedCastPayload else { return }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,@@ -769,7 +751,7 @@ class RealSlideshowService: ObservableObject {slideLoadingProgress = 1.0}- print("β Successfully loaded file \(file.id): \(file.title)")+ print("Successfully loaded file \(file.id): \(file.title)")// Restart timer if playingif isPlaying && !isPaused {@@ -782,7 +764,7 @@ class RealSlideshowService: ObservableObject {} catch {let file = allFiles[currentFileIndex]- print("β Failed to load file \(file.id): \(file.title) - \(error)")+ print("Failed to load file \(file.id): \(file.title) - \(error)")currentFileIndex = (currentFileIndex + 1) % allFiles.countretryCount += 1}@@ -823,7 +805,7 @@ class RealSlideshowService: ObservableObject {} catch {// Silently skip problematic files during prefetching- print("β οΈ Prefetch failed for file \(prefetchIndex), will try on-demand")+ print("Prefetch failed for file \(prefetchIndex), will try on-demand")continue}@@ -896,7 +878,7 @@ class RealSlideshowService: ObservableObject {stopPeriodicDiffPolling() // Stop any existing timer- print("π Starting periodic diff polling (every \(diffPollingInterval)s)")+ print("Starting periodic diff polling (every \(diffPollingInterval)s)")diffPollingTimer = Timer.scheduledTimer(withTimeInterval: diffPollingInterval, repeats: true) { [weak self] _ inTask {@@ -909,7 +891,6 @@ class RealSlideshowService: ObservableObject {private func stopPeriodicDiffPolling() {diffPollingTimer?.invalidate()diffPollingTimer = nil- print("βΉοΈ Stopped periodic diff polling")}private func performPeriodicDiffCheck() async {@@ -923,28 +904,27 @@ class RealSlideshowService: ObservableObject {let result = try await fetchFilesBatch(castPayload: payload, sinceTime: currentTime)if !result.files.isEmpty {- print("π Periodic poll found \(result.files.count) changes")+ print("Periodic poll found \(result.files.count) changes")await processDiffBatch(result.files, collectionKey: payload.collectionKey)// Only update lastUpdateTime if we actually found items with valid updationTimeawait MainActor.run {if result.latestUpdateTime > self.lastUpdateTime {- print("π Updating lastUpdateTime: \(self.lastUpdateTime) β \(result.latestUpdateTime)")+ print("Updating lastUpdateTime: \(self.lastUpdateTime) β \(result.latestUpdateTime)")self.lastUpdateTime = result.latestUpdateTime}}} else {- print("π Periodic poll found no changes since \(currentTime)")+ print("Periodic poll found no changes since \(currentTime)")}} catch {if let castError = error as? CastError,case .serverError(401, _) = castError {- print("π 401 error during periodic polling - authentication expired")// handleUnauthorizedError already called in fetchFilesBatch} else {- print("β οΈ Periodic diff check failed: \(error)")+ print("Periodic diff check failed: \(error)")// Continue polling on other errors}}@@ -956,12 +936,10 @@ class RealSlideshowService: ObservableObject {private func handleUnauthorizedError() {// Prevent multiple concurrent auth expiry handlingguard !isHandlingAuthExpiry else {- print("π Auth expiry already being handled - ignoring duplicate")return}isHandlingAuthExpiry = true- print("π¨ Authentication expired - resetting to pairing mode")// CRITICAL: Stop screen saver prevention immediately before any UI transitionsScreenSaverManager.allowScreenSaver()@@ -1003,7 +981,7 @@ class RealSlideshowService: ObservableObject {guard httpResponse.statusCode == 200 else {// Condensed error loglet snippet = (String(data: data, encoding: .utf8) ?? "").prefix(160)- print("β Download error [\(httpResponse.statusCode)] fileID=\(fileID): \(snippet)")+ print("Download error [\(httpResponse.statusCode)] fileID=\(fileID): \(snippet)")if httpResponse.statusCode == 401 {await handleUnauthorizedError()throw CastError.serverError(401, "Authentication expired - resetting to pairing mode")@@ -1011,7 +989,7 @@ class RealSlideshowService: ObservableObject {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}@@ -1024,15 +1002,15 @@ class RealSlideshowService: ObservableObject {// Check cache firstif 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)") }+ if verboseFileLogging { print("Downloading and decrypting file \(file.id): \(file.title)") }// Step 1: Download encrypted filelet encryptedData = try await downloadEncryptedFile(castPayload: castPayload, fileID: file.id)- if verboseFileLogging { print(" π₯ Downloaded \(encryptedData.count) bytes") }+ if verboseFileLogging { print("Downloaded \(encryptedData.count) bytes") }// Step 2: Decrypt file key using collection keylet fileKey = try decryptFileKey(@@ -1067,7 +1045,7 @@ class RealSlideshowService: ObservableObject {let metadataHeader = metadataDict["decryptionHeader"] as? String,let fileDict = item["file"] as? [String: Any],let fileDecryptionHeader = fileDict["decryptionHeader"] as? String else {- print(" β Missing required fields for file \(item["id"] ?? "unknown")")+ print("Missing required fields for file \(item["id"] ?? "unknown")")return nil}@@ -1078,7 +1056,7 @@ class RealSlideshowService: ObservableObject {nonce: keyDecryptionNonce,collectionKey: collectionKey)- if verboseDecryptionLogging { print(" π File key decrypted successfully") }+ if verboseDecryptionLogging { print("File key decrypted successfully") }// Step 2: Decrypt metadata using file key (XChaCha20-Poly1305)let metadata = try decryptMetadata(@@ -1107,7 +1085,7 @@ class RealSlideshowService: ObservableObject {)} catch {- print(" β Decryption failed: \(error)")+ print("Decryption failed: \(error)")throw error}}@@ -1135,11 +1113,11 @@ 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")+ print("XChaCha20: encrypted=\(encryptedBytes.count)b, header=\(headerBytes.count)b, key=\(fileKey.count)b")do {let decryptedData = try Crypto.decryptSecretStream(encryptedData: encryptedBytes, key: fileKey, header: headerBytes)- print(" β Metadata decrypted using Rust crypto: \(decryptedData.count) bytes")+ print("Metadata decrypted using Rust crypto: \(decryptedData.count) bytes")return decryptedData} catch {throw CastError.decryptionError("XChaCha20-Poly1305 decryption failed for metadata: \(error)")@@ -1152,7 +1130,7 @@ 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") }+ if verboseDecryptionLogging { print("File decryption: encrypted=\(encryptedData.count)b, header=\(headerBytes.count)b, key=\(fileKey.count)b") }do {return try Crypto.decryptSecretStream(encryptedData: encryptedData, key: fileKey, header: headerBytes)@@ -1194,7 +1172,7 @@ class RealSlideshowService: ObservableObject {private func cleanupExpiredCache(validFileIDs: Set<Int>) async {let stats = await getCacheStats()- print("π§Ή Starting cache cleanup - current cache has \(stats.count) files")+ print("Starting cache cleanup - current cache has \(stats.count) files")// Get all currently cached file IDslet cachedFileIDs = await fileCache.getCachedFileIDs()@@ -1210,9 +1188,7 @@ class RealSlideshowService: ObservableObject {if removedCount > 0 {let newStats = await getCacheStats()- print("π§Ή Cache cleanup complete - removed \(removedCount) expired files, now \(newStats.count) files (\(newStats.totalSize) bytes)")- } else {- print("π§Ή Cache cleanup complete - no expired files found")+ print("Cache cleanup complete - removed \(removedCount) expired files, now \(newStats.count) files (\(newStats.totalSize) bytes)")}}@@ -1234,7 +1210,6 @@ class RealSlideshowService: ObservableObject {func extractZipUsingFoundation(zipURL: URL, to destinationURL: URL) throws {do {try FileManager.default.unzipItem(at: zipURL, to: destinationURL)- print("β Successfully extracted zip using ZipFoundation")} catch {throw CastError.decryptionError("ZipFoundation extraction failed: \(error)")}@@ -1284,15 +1259,15 @@ func extractLivePhotoComponents(from zipData: Data) throws -> LivePhotoComponentif imageData == nil && isLikelyImage(fileURL) {imageData = try Data(contentsOf: fileURL)imagePath = fileURL- print("πΈ Extracted live photo image: \(filename) (\(imageData?.count ?? 0) bytes)")+ 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)")+ print("Extracted live photo video: \(filename) (\(videoData?.count ?? 0) bytes)")} else {// Only log unexpected files once both components missing to avoid noiseif imageData == nil || videoData == nil {- print("βΉοΈ Ignoring non-component file in live photo zip: \(filename)")+ print("Ignoring non-component file in live photo zip: \(filename)")}}}@@ -1304,14 +1279,14 @@ func extractLivePhotoComponents(from zipData: Data) throws -> LivePhotoComponentif let guessImage = contents.first(where: { $0.pathExtension.isEmpty }) { // pick first extension-less file as possible imageimageData = 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()) }) {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)") }}}}@@ -1328,7 +1303,7 @@ func extractLivePhotoComponents(from zipData: Data) throws -> LivePhotoComponent)} catch {- print("β Failed to extract live photo components: \(error)")+ print("Failed to extract live photo components: \(error)")throw CastError.decryptionError("Failed to extract live photo zip: \(error)")}}diff --git a/mobile/native/apple/apps/cast/Cast/Views/SlideshowView.swift b/mobile/native/apple/apps/cast/Cast/Views/SlideshowView.swiftindex ce46634370..493ed6bd03 100644--- a/mobile/native/apple/apps/cast/Cast/Views/SlideshowView.swift+++ b/mobile/native/apple/apps/cast/Cast/Views/SlideshowView.swift@@ -41,7 +41,7 @@ struct SlideshowView: View {}var body: some View {- // β OPTIMIZATION: Use pre-decoded images to avoid decoding during render+ // Use pre-decoded images to avoid decoding during renderlet mainUIImage = preDecodedImagelet previousUIImage = previousDecodedImage@@ -133,7 +133,6 @@ struct SlideshowView: View {actionFeedbackOverlaycontrolsOverlaytoastOverlay-// ambientLightOverlay}}.onChange(of: imageData) { newValue in@@ -349,7 +348,7 @@ struct SlideshowView: View {return uiImage} else {imageDecodeFailed = true- print("β UIImage decode failed (bytes: \(data.count))")+ print("UIImage decode failed (bytes: \(data.count))")return nil}}@@ -364,7 +363,7 @@ struct SlideshowView: View {previousImageOpacity = 0.0}- print("πΌοΈ Displaying \(isLive ? "live" : "static") image (\(bytes) bytes)")+ print("Displaying \(isLive ? "live" : "static") image (\(bytes) bytes)")// Clean up previous image data after animationTask {diff --git a/mobile/native/apple/apps/cast/Cast/Views/VideoPlayerView.swift b/mobile/native/apple/apps/cast/Cast/Views/VideoPlayerView.swiftindex 4484ce99d8..5bb4561250 100644--- a/mobile/native/apple/apps/cast/Cast/Views/VideoPlayerView.swift+++ b/mobile/native/apple/apps/cast/Cast/Views/VideoPlayerView.swift@@ -84,7 +84,6 @@ struct VideoPlayerView: View {setupPlayer()} else {- print("β Video asset is not playable or has no video tracks")// Try fallback with different extensionself.tryVideoFallback(originalURL: tempURL)}@@ -92,7 +91,7 @@ struct VideoPlayerView: View {}}} catch {- print("β Failed to setup video player: \(error)")+ print("Failed to setup video player: \(error)")await MainActor.run {// Show error stateself.showErrorState()@@ -118,7 +117,7 @@ struct VideoPlayerView: View {setupPlayer()}} catch {- print("β Video fallback also failed: \(error)")+ print("Video fallback also failed: \(error)")showErrorState()}}@@ -126,7 +125,6 @@ struct VideoPlayerView: View {private func showErrorState() {// Could show an error message or placeholder- print("β Unable to play video - showing error state")}private func monitorPlayerItemStatus(_ playerItem: AVPlayerItem) {@@ -134,20 +132,19 @@ struct VideoPlayerView: View {Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer inswitch playerItem.status {case .readyToPlay:- print("β Video player ready to play")timer.invalidate()case .failed:if let error = playerItem.error {- print("β Video player failed with error: \(error)")- print("β Error details: \(error.localizedDescription)")+ print("Video player failed with error: \(error)")+ print("Error details: \(error.localizedDescription)")}timer.invalidate()Task { @MainActor inself.showErrorState()}case .unknown:- print("β³ Video player status unknown")// Keep checking+ break@unknown default:timer.invalidate()}@@ -198,7 +195,7 @@ struct VideoPlayerView: View {queue: .main) { notification inif let error = notification.userInfo?[AVPlayerItemFailedToPlayToEndTimeErrorKey] as? Error {- print("β Video playback failed: \(error)")+ print("Video playback failed: \(error)")}}@@ -251,10 +248,8 @@ struct VideoPlayerView: View {let brand = headerBytes.subdata(in: 8..<12)if brand == Data("mp41".utf8) || brand == Data("mp42".utf8) ||brand == Data("isom".utf8) || brand == Data("M4V ".utf8) {- print("π₯ Detected MP4 video format")return "mp4"} else if brand == Data("qt ".utf8) {- print("π₯ Detected MOV video format")return "mov"}}@@ -263,7 +258,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 {- print("π₯ Detected H.264 stream, using MP4 container")return "mp4"}}@@ -272,25 +266,21 @@ struct VideoPlayerView: View {if signature == Data("RIFF".utf8) && headerBytes.count >= 12 {let aviSignature = headerBytes.subdata(in: 8..<12)if aviSignature == Data("AVI ".utf8) {- print("β οΈ Detected AVI format - may have compatibility issues")return "avi"}}// WebM format (limited support on tvOS)if signature == Data([0x1A, 0x45, 0xDF, 0xA3]) {- print("β οΈ Detected WebM format - may have compatibility issues")return "webm"}// MKV formatif signature == Data([0x1A, 0x45, 0xDF, 0xA3]) {- print("β οΈ Detected MKV format - may have compatibility issues")return "mkv"}}- print("π₯ Unknown video format, defaulting to MP4")return "mp4"}