Skip to content

armgit / ente

Public Imported from GitHub
0

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

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.swift
index 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 time
if 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 = true
pollingStartTime = 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 key
let payload = try await decryptPayload(
@@ -172,7 +166,6 @@ class RealCastPairingService {
privateKey: device.privateKey
)
- print("βœ… Successfully decrypted cast payload!")
hasDeliveredPayload = true
stopPolling()
@@ -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 = nil
isPolling = false
pollingStartTime = nil
- print("⏹️ Stopped polling production server")
}
func resetForNewSession() {
- print("πŸ”„ Resetting pairing service for new session")
stopPolling()
hasDeliveredPayload = false
hasLoggedIntervalSwitch = false
diff --git a/mobile/native/apple/apps/cast/Cast/Services/FileCache.swift b/mobile/native/apple/apps/cast/Cast/Services/FileCache.swift
index 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 metadata
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) {
@@ -85,7 +85,7 @@ actor ThreadSafeFileCache {
// Save updated metadata
saveCacheMetadata()
- 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 metadata
try? 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 eviction
saveCacheMetadata()
- print("πŸ“¦ Cache GC complete: now \(cache.count) files, \(totalBytes) bytes")
+ print("Cache GC complete: now \(cache.count) files, \(totalBytes) bytes")
}
private func loadCacheFromDisk() {
// Load metadata
guard 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 bytes
var loadedBytes = 0
@@ -165,7 +164,7 @@ actor ThreadSafeFileCache {
cacheOrder = validFileIDs
totalBytes = 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 entries
if 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.swift
index 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 = true
isDisabled = 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 = nil
UIApplication.shared.isIdleTimerDisabled = false
isDisabled = false
- print("βœ… Screen saver prevention disabled")
}
// Cleanup method for app termination
diff --git a/mobile/native/apple/apps/cast/Cast/ViewModels/CastViewModel.swift b/mobile/native/apple/apps/cast/Cast/ViewModels/CastViewModel.swift
index 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 Properties
private var cancellables = Set<AnyCancellable>()
private let pairingService: RealCastPairingService
private let castSession: CastSession
-
- // MARK: - Public Properties
+
+ // MARK: - Public Properties
public let slideshowService: RealSlideshowService
-
+
enum CurrentView {
case pairing
case connecting
@@ -29,30 +29,24 @@ class CastViewModel: ObservableObject {
case error
case 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 changes
castSession.$state
.receive(on: DispatchQueue.main)
.sink { [weak self] state in
self?.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] _ in
self?.handleAuthenticationExpired()
}
.store(in: &cancellables)
-
- // Listen for slideshow restarted notifications
+
NotificationCenter.default.publisher(for: .slideshowRestarted)
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.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 { _ in
ScreenSaverManager.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 = .connecting
isLoading = true
statusMessage = "Registering device..."
-
+
Task {
do {
- // Register device with the server
let device = try await pairingService.registerDevice()
-
+
await MainActor.run {
deviceCode = device.deviceCode
castSession.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 reset
ScreenSaverManager.allowScreenSaver()
-
+
currentView = .connecting
deviceCode = ""
currentImageData = nil
@@ -191,43 +177,35 @@ class CastViewModel: ObservableObject {
statusMessage = ""
isLoading = false
errorMessage = 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, skip
if 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 = .connecting
statusMessage = ""
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 = .connecting
statusMessage = "Registering device..."
isLoading = true
-
+
case .waitingForPairing(let code):
deviceCode = code
currentView = .pairing
statusMessage = "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 state
return
}
-
+
if isEmptyStateError {
currentView = .empty
statusMessage = ""
@@ -318,41 +294,33 @@ class CastViewModel: ObservableObject {
handleError(error)
}
}
-
-
+
private func handleError(_ message: String) {
- print("❌ Cast Error: \(message)")
+ print("Cast Error: \(message)")
currentView = .error
errorMessage = message
isLoading = false
statusMessage = ""
castSession.setState(.error(message))
}
-
+
private func handleNetworkError(_ error: Error) {
- // Show error immediately
handleError("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 registration
startCastSession()
}
}
}
-
+
private func handleAuthenticationExpired() {
- print("πŸ” Authentication expired notification received - clearing all state and restarting")
Task {
await resetSession()
- // Clear all in-memory token state in slideshow service
await slideshowService.clearExpiredTokenState()
- // Reset pairing service to allow fresh polling
pairingService.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 flicker
currentView = .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 arrives
statusMessage = ""
isLoading = false
errorMessage = 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.swift
index 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 index
if 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 accordingly
if currentFileWasDeleted {
- print("⏭️ Handling deleted current file")
currentFileWasDeleted = false
// Current index already adjusted in processDiffBatch
if currentFileIndex >= allFiles.count {
@@ -160,7 +158,6 @@ class RealSlideshowService: ObservableObject {
// MARK: - Main Entry Points
func start(castPayload: CastPayload) async {
- print("🎬 Starting slideshow with payload:")
// Enable screen saver prevention for slideshow
ScreenSaverManager.preventScreenSaver()
@@ -175,7 +172,6 @@ class RealSlideshowService: ObservableObject {
}
do {
- print("πŸ“‘ Fetching files from Ente museum server...")
// Initialize file list and fetch all files with pagination
await 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 collection
let 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 image
if 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 slideshow
ScreenSaverManager.allowScreenSaver()
@@ -254,8 +248,7 @@ class RealSlideshowService: ObservableObject {
// Print final cache statistics
let 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 session
await 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 state
ScreenSaverManager.allowScreenSaver()
@@ -296,12 +288,11 @@ class RealSlideshowService: ObservableObject {
private func initializeFileList(castPayload: CastPayload) async {
// Check if we've already completed the initial fetch
if 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 = 0
currentFileIndex = 0
@@ -315,11 +306,10 @@ class RealSlideshowService: ObservableObject {
// Shuffle order to randomize slideshow similar to web experience
if !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 attempt
self.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 MainActor
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
}
}
@@ -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 completes
await MainActor.run {
@@ -390,7 +380,6 @@ class RealSlideshowService: ObservableObject {
// Parse the diff response
guard 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 exists
if 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 one
if originalCurrentFile?.id == id {
currentFileWasDeleted = true
- print(" ⚠️ Currently playing file was deleted - will handle gracefully")
// Immediately move to next slide if current was deleted
Task {
@@ -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 exists
if 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 so
if 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 transitions
if allFiles.isEmpty {
// Transition to empty state
- print("πŸ“­ All files removed - showing empty state")
slideTimer?.invalidate()
slideTimer = nil
isPlaying = 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 = 0
currentSlideIndex = 0
totalSlides = allFiles.count
// Restart slideshow if we have a stored payload
if 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 network
do {
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 data
prefetchCache[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 slideshow
await MainActor.run {
@@ -637,19 +622,17 @@ class RealSlideshowService: ObservableObject {
// For live photos, only set the image component for display
if 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 playback
if 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 image
currentImageData = data
currentVideoData = nil
@@ -690,7 +673,7 @@ class RealSlideshowService: ObservableObject {
currentVideoData = nil // release raw data memory
prepareVideoPlayer(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 UI
if 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 playing
if 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.count
retryCount += 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] _ in
Task {
@@ -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 updationTime
await 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 handling
guard !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 transitions
ScreenSaverManager.allowScreenSaver()
@@ -1003,7 +981,7 @@ class RealSlideshowService: ObservableObject {
guard httpResponse.statusCode == 200 else {
// Condensed error log
let 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 first
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)") }
+ if verboseFileLogging { print("Downloading and decrypting file \(file.id): \(file.title)") }
// Step 1: Download encrypted file
let 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 key
let 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 IDs
let 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 -> LivePhotoComponent
if 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 noise
if 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 -> LivePhotoComponent
if let guessImage = contents.first(where: { $0.pathExtension.isEmpty }) { // pick first extension-less file as possible image
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()) }) {
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.swift
index 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 render
let mainUIImage = preDecodedImage
let previousUIImage = previousDecodedImage
@@ -133,7 +133,6 @@ struct SlideshowView: View {
actionFeedbackOverlay
controlsOverlay
toastOverlay
-// 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 animation
Task {
diff --git a/mobile/native/apple/apps/cast/Cast/Views/VideoPlayerView.swift b/mobile/native/apple/apps/cast/Cast/Views/VideoPlayerView.swift
index 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 extension
self.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 state
self.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 in
switch 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 in
self.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 in
if 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 format
if 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"
}