Skip to content

armgit / ente

Public Imported from GitHub
0

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

Prune Apple comments

Manav Rathi4adae1241ea6
diff --git a/apple/apps/cast/Cast/Models/CastModels.swift b/apple/apps/cast/Cast/Models/CastModels.swift
index 2da95e5f99..1164c2dd12 100644
--- a/apple/apps/cast/Cast/Models/CastModels.swift
+++ b/apple/apps/cast/Cast/Models/CastModels.swift
@@ -1,13 +1,11 @@
import Foundation
import AVKit
-// MARK: - Notification Extensions
extension Notification.Name {
static let authenticationExpired = Notification.Name("authenticationExpired")
static let slideshowRestarted = Notification.Name("slideshowRestarted")
}
-// MARK: - Slide Configuration
struct SlideConfiguration {
let imageDuration: TimeInterval
let videoDuration: TimeInterval
@@ -17,7 +15,6 @@ struct SlideConfiguration {
let maxVideoSize: Int64
let includeVideos: Bool
- // Enhanced prefetch settings
let prefetchCount: Int
let maxCacheSize: Int
let prefetchDelay: TimeInterval
@@ -28,8 +25,8 @@ struct SlideConfiguration {
videoDuration: TimeInterval = 30.0,
useThumbnails: Bool = false,
shuffle: Bool = true,
- maxImageSize: Int64 = 100 * 1024 * 1024, // 100MB
- maxVideoSize: Int64 = 500 * 1024 * 1024, // 500MB
+ maxImageSize: Int64 = 100 * 1024 * 1024,
+ maxVideoSize: Int64 = 500 * 1024 * 1024,
includeVideos: Bool = true,
prefetchCount: Int = 3,
maxCacheSize: Int = 5,
@@ -55,23 +52,21 @@ struct SlideConfiguration {
static let `default` = SlideConfiguration()
- // TV-optimized configuration (use thumbnails for better performance)
static let tvOptimized = SlideConfiguration(
- imageDuration: 8.0, // Faster progression for TV viewing
+ imageDuration: 8.0,
videoDuration: 25.0,
- useThumbnails: true, // Better performance on Apple TV
+ useThumbnails: true,
shuffle: true,
- maxImageSize: 50 * 1024 * 1024, // 50MB for TV
- maxVideoSize: 200 * 1024 * 1024, // 200MB for TV
+ maxImageSize: 50 * 1024 * 1024,
+ maxVideoSize: 200 * 1024 * 1024,
includeVideos: true,
- prefetchCount: 3, // Prefetch next 3 slides
- maxCacheSize: 5, // Keep 5 slides in cache
- prefetchDelay: 0.5, // 500ms delay between prefetch operations
- enablePrefetching: true // Enable prefetching for smooth transitions
+ prefetchCount: 3,
+ maxCacheSize: 5,
+ prefetchDelay: 0.5,
+ enablePrefetching: true
)
}
-// MARK: - Data Models
struct CastFile: Codable, Equatable {
let id: Int
let title: String
@@ -110,7 +105,6 @@ struct CastDevice {
let receiver: CastReceiver
}
-// MARK: - Server Response Models
struct DeviceRegistrationResponse: Codable {
let deviceCode: String
}
@@ -119,7 +113,6 @@ struct CastDataResponse: Codable {
let encCastData: String?
}
-// MARK: - Errors
enum CastError: Error, LocalizedError {
case networkError(String)
case serverError(Int, String?)
@@ -137,7 +130,6 @@ enum CastError: Error, LocalizedError {
}
}
-// MARK: - Live Photo Models
struct LivePhotoComponents {
let imageData: Data?
let videoData: Data?
@@ -145,7 +137,6 @@ struct LivePhotoComponents {
let videoPath: URL?
}
-// MARK: - Cache Metadata
struct CacheMetadata: Codable {
let fileIDs: [Int]
let totalBytes: Int
diff --git a/apple/apps/cast/Cast/Services/CastPairingService.swift b/apple/apps/cast/Cast/Services/CastPairingService.swift
index 502d48a6f0..030d185a69 100644
--- a/apple/apps/cast/Cast/Services/CastPairingService.swift
+++ b/apple/apps/cast/Cast/Services/CastPairingService.swift
@@ -1,8 +1,6 @@
import SwiftUI
import Foundation
-// MARK: - Cast Session Management
-
@MainActor
class CastSession: ObservableObject {
@Published var state: CastSessionState = .idle
@@ -35,8 +33,6 @@ class CastSession: ObservableObject {
}
}
-// MARK: - Real Cast Pairing Service
-
class RealCastPairingService {
private let baseURL = "https://api.ente.com"
private var pollingTimer: Timer?
@@ -44,9 +40,9 @@ class RealCastPairingService {
private var isFetchingPayload: Bool = false
private var hasDeliveredPayload: Bool = false
private var pollingStartTime: Date?
- private let initialPollingInterval: TimeInterval = 2.0 // 2 seconds initially
- private let extendedPollingInterval: TimeInterval = 5.0 // 5 seconds after 60 seconds
- private let pollingIntervalSwitchTime: TimeInterval = 60.0 // Switch after 60 seconds
+ private let initialPollingInterval: TimeInterval = 2.0
+ private let extendedPollingInterval: TimeInterval = 5.0
+ private let pollingIntervalSwitchTime: TimeInterval = 60.0
private var hasLoggedIntervalSwitch: Bool = false
private func getCurrentPollingInterval() -> TimeInterval {
@@ -54,7 +50,6 @@ class RealCastPairingService {
let elapsed = Date().timeIntervalSince(startTime)
let newInterval = elapsed >= pollingIntervalSwitchTime ? extendedPollingInterval : initialPollingInterval
- // 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")
hasLoggedIntervalSwitch = true
@@ -114,7 +109,7 @@ class RealCastPairingService {
pollingTimer = Timer.scheduledTimer(withTimeInterval: currentInterval, repeats: false) { [weak self] _ in
Task {
await self?.checkForPayload(device: device, onPayloadReceived: onPayloadReceived, onError: onError)
- // Schedule next poll after this one completes
+ // Poll again only after this request finishes.
await MainActor.run {
self?.scheduleNextPoll(device: device, onPayloadReceived: onPayloadReceived, onError: onError)
}
@@ -138,7 +133,7 @@ class RealCastPairingService {
}
if httpResponse.statusCode == 404 {
- // No payload available yet - this is expected
+ // 404 means no cast payload is available yet.
return
}
diff --git a/apple/apps/cast/Cast/Services/FileCache.swift b/apple/apps/cast/Cast/Services/FileCache.swift
index a108fb2046..ae89faba53 100644
--- a/apple/apps/cast/Cast/Services/FileCache.swift
+++ b/apple/apps/cast/Cast/Services/FileCache.swift
@@ -1,7 +1,5 @@
import Foundation
-// MARK: - Persistent Thread-Safe File Cache
-
actor ThreadSafeFileCache {
private var cache: [Int: Data] = [:]
private var cacheOrder: [Int] = []
@@ -19,7 +17,6 @@ actor ThreadSafeFileCache {
self.cacheDirectory = documentsPath.appendingPathComponent("EnteFileCache")
self.metadataURL = cacheDirectory.appendingPathComponent("cache_metadata.json")
- // Create cache directory if it doesn't exist
try? FileManager.default.createDirectory(at: cacheDirectory, withIntermediateDirectories: true)
loadCacheFromDisk()
@@ -32,7 +29,6 @@ actor ThreadSafeFileCache {
let fileURL = cacheDirectory.appendingPathComponent("\(fileID).cache")
if let data = try? Data(contentsOf: fileURL) {
- // Load into memory cache for faster future access
cache[fileID] = data
if !cacheOrder.contains(fileID) {
cacheOrder.append(fileID)
@@ -117,7 +113,6 @@ actor ThreadSafeFileCache {
}
totalBytes -= removedBytes
- // Save updated metadata after eviction
saveCacheMetadata()
print("Cache GC complete: now \(cache.count) files, \(totalBytes) bytes")
@@ -150,7 +145,6 @@ actor ThreadSafeFileCache {
print("Loaded \(validFileIDs.count) cached files (\(loadedBytes) bytes) from disk")
- // Clean up any invalid entries
if validFileIDs.count != metadata.fileIDs.count {
saveCacheMetadata()
}
@@ -162,4 +156,4 @@ actor ThreadSafeFileCache {
try? data.write(to: metadataURL)
}
}
-}
\ No newline at end of file
+}
diff --git a/apple/apps/cast/Cast/Utils/FontUtils.swift b/apple/apps/cast/Cast/Utils/FontUtils.swift
index 552d0ef652..6a9eec04d1 100644
--- a/apple/apps/cast/Cast/Utils/FontUtils.swift
+++ b/apple/apps/cast/Cast/Utils/FontUtils.swift
@@ -2,9 +2,7 @@ import SwiftUI
import UIKit
struct FontUtils {
-
- // MARK: - Safe Font Creation
-
+
private static func safeFont(name: String, size: CGFloat, fallback: Font) -> Font {
if UIFont(name: name, size: size) != nil {
return .custom(name, size: size)
@@ -12,9 +10,7 @@ struct FontUtils {
return fallback
}
}
-
- // MARK: - Font Presets
-
+
static func montserratBold(size: CGFloat) -> Font {
return safeFont(name: "Montserrat-Bold", size: size, fallback: .system(size: size, weight: .bold))
}
diff --git a/apple/apps/cast/Cast/Utils/ScreenSaverManager.swift b/apple/apps/cast/Cast/Utils/ScreenSaverManager.swift
index 730300028f..669d6822a3 100644
--- a/apple/apps/cast/Cast/Utils/ScreenSaverManager.swift
+++ b/apple/apps/cast/Cast/Utils/ScreenSaverManager.swift
@@ -23,8 +23,7 @@ class ScreenSaverManager: ObservableObject {
UIApplication.shared.isIdleTimerDisabled = true
isDisabled = true
- // Fallback for problematic tvOS versions where isIdleTimerDisabled doesn't work reliably
- // This timer periodically refreshes the setting to ensure it stays disabled
+ // Refresh because this setting is unreliable on some tvOS versions.
refreshTimer = Timer.scheduledTimer(withTimeInterval: 30.0, repeats: true) { _ in
UIApplication.shared.isIdleTimerDisabled = false
UIApplication.shared.isIdleTimerDisabled = true
diff --git a/apple/apps/cast/Cast/ViewModels/CastViewModel.swift b/apple/apps/cast/Cast/ViewModels/CastViewModel.swift
index bd36684904..50e6559899 100644
--- a/apple/apps/cast/Cast/ViewModels/CastViewModel.swift
+++ b/apple/apps/cast/Cast/ViewModels/CastViewModel.swift
@@ -4,7 +4,6 @@ import UIKit
@MainActor
class CastViewModel: ObservableObject {
- // MARK: - Published Properties
@Published var currentView: CurrentView = .connecting
@Published var deviceCode: String = ""
@Published var currentImageData: Data?
@@ -13,12 +12,10 @@ class CastViewModel: ObservableObject {
@Published var statusMessage: String = ""
@Published var errorMessage: String?
- // MARK: - Private Properties
private var cancellables = Set<AnyCancellable>()
private let pairingService: RealCastPairingService
private let castSession: CastSession
- // MARK: - Public Properties
public let slideshowService: RealSlideshowService
enum CurrentView {
@@ -50,7 +47,6 @@ class CastViewModel: ObservableObject {
.receive(on: DispatchQueue.main)
.assign(to: \.currentImageData, on: self)
.store(in: &cancellables)
- // Auto-transition once first image arrives (covers single-image albums and empty-to-populated)
slideshowService.$currentImageData
.receive(on: DispatchQueue.main)
.sink { [weak self] data in
@@ -123,8 +119,6 @@ class CastViewModel: ObservableObject {
.store(in: &cancellables)
}
- // MARK: - Public Methods
-
func startCastSession() {
castSession.setState(.registering)
deviceCode = ""
@@ -178,7 +172,6 @@ class CastViewModel: ObservableObject {
}
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
}
@@ -188,12 +181,10 @@ class CastViewModel: ObservableObject {
statusMessage = ""
Task {
- // Add a small delay to prevent flickering from rapid state changes
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)
await MainActor.run {
@@ -220,8 +211,6 @@ class CastViewModel: ObservableObject {
}
}
- // MARK: - Slideshow Navigation
-
func nextSlide() {
guard currentView == .slideshow else { return }
@@ -238,8 +227,6 @@ class CastViewModel: ObservableObject {
}
}
- // MARK: - Private Methods
-
private func handleStateChange(_ state: CastSessionState) {
switch state {
case .idle:
@@ -263,10 +250,8 @@ class CastViewModel: ObservableObject {
}
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
- // errors once we are actually in a connected/slideshow flow.
- // Exception: Allow empty state errors even during connecting
+ // Ignore stale slideshow errors while a new connection is starting.
+ // Empty-state errors may belong to the new connection.
let isEmptyStateError = error.contains("No media files") ||
error.contains("available in this album") ||
error.contains("available in this collection") ||
@@ -310,7 +295,6 @@ class CastViewModel: ObservableObject {
pairingService.resetForNewSession()
await MainActor.run {
- // Directly set to pairing once device registration begins to avoid brief empty/error flicker
currentView = .connecting
errorMessage = nil
statusMessage = "Starting fresh session..."
diff --git a/apple/apps/cast/Cast/ViewModels/SlideshowService.swift b/apple/apps/cast/Cast/ViewModels/SlideshowService.swift
index f95428198c..36a5d6d2d8 100644
--- a/apple/apps/cast/Cast/ViewModels/SlideshowService.swift
+++ b/apple/apps/cast/Cast/ViewModels/SlideshowService.swift
@@ -6,11 +6,10 @@ import UIKit
@MainActor
class RealSlideshowService: ObservableObject {
- // MARK: - Published Properties
@Published var currentImageData: Data?
- @Published var currentVideoData: Data? // Deprecated path (kept for compatibility)
- @Published var currentVideoURL: URL? // Temp file URL for AVPlayer playback
- @Published var livePhotoVideoData: Data? // Video component for live photos
+ @Published var currentVideoData: Data?
+ @Published var currentVideoURL: URL?
+ @Published var livePhotoVideoData: Data?
@Published var videoPlayer: AVPlayer?
@Published var isVideoPlaying: Bool = false
@Published var videoCurrentTime: Double = 0
@@ -18,16 +17,12 @@ class RealSlideshowService: ObservableObject {
@Published var currentFile: CastFile?
@Published var error: String?
- // Enhanced state management
@Published var isPlaying: Bool = false
@Published var isPaused: Bool = false
@Published var slideLoadingProgress: Double = 0.0
@Published var currentSlideIndex: Int = 0
@Published var totalSlides: Int = 0
- // MARK: - Private Properties
-
- // Global file list management
private var allFiles: [CastFile] = []
private var currentFileIndex: Int = 0
private var lastUpdateTime: Int64 = 0
@@ -35,14 +30,12 @@ class RealSlideshowService: ObservableObject {
private var hasCompletedInitialFetch: Bool = false
private var storedCastPayload: CastPayload?
- // Periodic diff polling
private var diffPollingTimer: Timer?
- private let diffPollingInterval: TimeInterval = 5.0 // 5 seconds
+ private let diffPollingInterval: TimeInterval = 5.0
private var isPeriodicPollingEnabled: Bool = true
private var currentFileWasDeleted: Bool = false
- private var isStopping: Bool = false // Flag to indicate service is being stopped
+ private var isStopping: Bool = false
- // Enhanced slideshow features
private var slideTimer: Timer?
private var prefetchCache: [Int: Data] = [:]
private var videoTempFiles: [Int: URL] = [:]
@@ -51,34 +44,27 @@ class RealSlideshowService: ObservableObject {
private var slidePauseTime: Date?
private var slideStartTime: Date?
- // File content caching - prevent redundant downloads
private let fileCache = ThreadSafeFileCache(
- maxBytes: 4096 * 1024 * 1024, // 4GB
- shrinkTargetBytes: 2048 * 1024 * 1024 // 2GB
+ maxBytes: 4096 * 1024 * 1024,
+ shrinkTargetBytes: 2048 * 1024 * 1024
)
- // Simplified mode: only load first file (no slideshow navigation)
private var didDisplayFirstFile: Bool = false
private let baseURL = "https://api.ente.com"
private let castDownloadURL = "https://cast-albums.ente.com/download"
- // Configuration Flags
- private let verboseFileLogging = false // Reduces per-file spam unless true
- private let verboseDecryptionLogging = false // Detailed size/key logs
+ private let verboseFileLogging = false
+ private let verboseDecryptionLogging = false
- // 401 Error Handling
private var isHandlingAuthExpiry: Bool = false
- // MARK: - Slideshow Controls
-
func pause() {
slideTimer?.invalidate()
slideTimer = nil
isPlaying = false
isPaused = true
- // Calculate remaining time when pausing
if let startTime = slideStartTime {
let elapsed = Date().timeIntervalSince(startTime)
let totalDuration = currentFile.map { slideshowConfiguration.duration(for: $0) } ?? 0
@@ -93,7 +79,6 @@ class RealSlideshowService: ObservableObject {
isPlaying = true
slidePauseTime = nil
- // Resume with remaining time if we have it, otherwise start fresh
if slideTimeRemaining > 0 {
startSlideTimer(withDuration: slideTimeRemaining)
} else {
@@ -110,33 +95,29 @@ class RealSlideshowService: ObservableObject {
}
func nextSlide() async {
- // If we no longer have an active payload (e.g. after auth expiry reset) just ignore any stray timer fires
+ // Ignore timer callbacks after the session has been reset.
guard storedCastPayload != nil else { return }
guard !allFiles.isEmpty else {
- // Only surface empty-state error if we're in an active slideshow session (payload present)
await MainActor.run {
self.error = "No media files available in this album"
}
return
}
- // For single photo, just restart the timer without changing index
if allFiles.count == 1 {
if isPlaying && !isPaused {
startSlideTimer()
}
return
}
-
- // Check if current file was deleted and handle accordingly
+
if currentFileWasDeleted {
currentFileWasDeleted = false
- // Current index already adjusted in processDiffBatch
+ // Removing this file already exposed the next item at this index.
if currentFileIndex >= allFiles.count {
currentFileIndex = 0
}
} else {
- // Normal progression to next slide
currentFileIndex = (currentFileIndex + 1) % allFiles.count
}
@@ -155,25 +136,18 @@ class RealSlideshowService: ObservableObject {
}
}
- // MARK: - Main Entry Points
-
func start(castPayload: CastPayload) async {
- // Enable screen saver prevention for slideshow
ScreenSaverManager.preventScreenSaver()
- // Clear any expired state first, then store new payload
await clearExpiredTokenState()
storedCastPayload = castPayload
await MainActor.run {
- // Don't blindly nuke existing UI state until we actually know file list status
- // Just mark as loading; CastViewModel controls high-level view transitions.
if self.error != nil { self.error = nil }
}
do {
- // Initialize file list and fetch all files with pagination
await initializeFileList(castPayload: castPayload)
let fileCount = await MainActor.run { allFiles.count }
@@ -186,7 +160,6 @@ class RealSlideshowService: ObservableObject {
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 } })
await cleanupExpiredCache(validFileIDs: validFileIDs)
@@ -198,10 +171,8 @@ class RealSlideshowService: ObservableObject {
self.isPaused = false
}
- // Display first file and start slideshow
await displaySlideAtCurrentIndex()
- // For single photo, ensure timer is started even if it's an image
if fileCount == 1 {
startSlideTimer()
} else {
@@ -219,20 +190,17 @@ class RealSlideshowService: ObservableObject {
func stop() async {
- // Disable screen saver prevention when stopping slideshow
ScreenSaverManager.allowScreenSaver()
- // Set stopping flag to cancel ongoing operations
await MainActor.run {
isStopping = true
stopPeriodicDiffPolling()
}
- // Invalidate slide timer to avoid post-reset nextSlide() firing that could trigger false empty-state UI
- slideTimer?.invalidate()
- slideTimer = nil
+ // A late timer callback would surface a false empty state.
+ slideTimer?.invalidate()
+ slideTimer = nil
- // Clear navigation state
await MainActor.run {
currentFile = nil
currentImageData = nil
@@ -246,7 +214,6 @@ class RealSlideshowService: ObservableObject {
let stats = await getCacheStats()
print("Final cache stats: \(stats.count) files, \(stats.totalSize) bytes")
- // Reset stopping flag for next session
await MainActor.run {
isStopping = false
}
@@ -254,11 +221,10 @@ class RealSlideshowService: ObservableObject {
func clearExpiredTokenState() async {
- // Ensure screen saver prevention is disabled when clearing expired state
ScreenSaverManager.allowScreenSaver()
await MainActor.run {
- // Ensure any existing slide timer from previous session is cancelled to prevent spurious empty-state errors
+ // A late timer callback would surface a false empty state.
slideTimer?.invalidate()
slideTimer = nil
storedCastPayload = nil
@@ -266,7 +232,6 @@ class RealSlideshowService: ObservableObject {
hasCompletedInitialFetch = false
allFiles.removeAll()
prefetchCache.removeAll()
- // Clear any error state that might trigger empty view
error = nil
currentFile = nil
currentImageData = nil
@@ -274,38 +239,31 @@ class RealSlideshowService: ObservableObject {
currentVideoURL = nil
livePhotoVideoData = nil
}
- // Don't clear cache automatically - preserve across sessions
+ // Preserve the cache across sessions.
}
- // MARK: - File List Management
-
@MainActor
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")
return
}
- // Reset state for fresh fetch
allFiles.removeAll()
lastUpdateTime = 0
currentFileIndex = 0
hasCompletedInitialFetch = false
- // Fetch all pages until hasMore is false
do {
try await fetchAllFiles(castPayload: castPayload)
- // Mark as completed only after successfully fetching all pages
hasCompletedInitialFetch = true
- // Shuffle order to randomize slideshow similar to web experience
if !allFiles.isEmpty {
allFiles.shuffle()
}
print("Initial diff fetch completed - \(allFiles.count) files cached (shuffled)")
} catch {
print("Failed to fetch files: \(error)")
- hasCompletedInitialFetch = false // Ensure we retry on next attempt
+ hasCompletedInitialFetch = false
self.error = "Failed to load files: \(error.localizedDescription)"
}
}
@@ -318,10 +276,8 @@ class RealSlideshowService: ObservableObject {
if verboseFileLogging { print("Fetching files since time: \(sinceTime)") }
let result = try await fetchFilesBatch(castPayload: castPayload, sinceTime: sinceTime)
- // Process the batch on MainActor
await processDiffBatch(result.files, collectionKey: castPayload.collectionKey)
- // Update pagination state on MainActor
await MainActor.run {
if result.latestUpdateTime > self.lastUpdateTime {
print("Initial fetch updating lastUpdateTime: \(self.lastUpdateTime) β†’ \(result.latestUpdateTime)")
@@ -336,7 +292,6 @@ class RealSlideshowService: ObservableObject {
print("Initial diff fetch complete - total files cached: \(await MainActor.run { allFiles.count })")
- // Start periodic polling after initial fetch completes
await MainActor.run {
startPeriodicDiffPolling()
}
@@ -361,7 +316,6 @@ class RealSlideshowService: ObservableObject {
}
guard httpResponse.statusCode == 200 else {
- // Handle 401 specially - this means token expired, need to reset to pairing
if httpResponse.statusCode == 401 {
await handleUnauthorizedError()
throw CastError.serverError(401, "Authentication expired - resetting to pairing mode")
@@ -369,7 +323,6 @@ class RealSlideshowService: ObservableObject {
throw CastError.serverError(httpResponse.statusCode, String(data: data, encoding: .utf8))
}
- // Parse the diff response
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let diff = json["diff"] as? [[String: Any]] else {
throw CastError.networkError("Invalid JSON response")
@@ -377,7 +330,6 @@ class RealSlideshowService: ObservableObject {
let hasMore = json["hasMore"] as? Bool ?? false
- // Find the latest update time from this batch
var latestUpdateTime = sinceTime
var foundAnyUpdates = false
for item in diff {
@@ -387,7 +339,6 @@ class RealSlideshowService: ObservableObject {
}
}
- // If no items had updationTime, keep the original sinceTime
if !foundAnyUpdates {
latestUpdateTime = sinceTime
}
@@ -411,26 +362,22 @@ class RealSlideshowService: ObservableObject {
let isDeleted = item["isDeleted"] as? Bool ?? false
if isDeleted {
- // 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))")
- // Check if deleted file was the currently playing one
if originalCurrentFile?.id == id {
currentFileWasDeleted = true
- // Immediately move to next slide if current was deleted
Task {
await self.nextSlide()
}
}
- // Adjust current index if necessary
if index < currentFileIndex && currentFileIndex > 0 {
currentFileIndex -= 1
} else if index == currentFileIndex && currentFileIndex >= allFiles.count && !allFiles.isEmpty {
- currentFileIndex = 0 // Wrap around to beginning
+ currentFileIndex = 0
}
prefetchCache.removeValue(forKey: id)
@@ -440,29 +387,24 @@ class RealSlideshowService: ObservableObject {
print("Skipping deleted file \(id) (not in list)")
}
} else {
- // Add or update file
do {
- // Only decrypt metadata here, not file content
if let file = try await decryptFileMetadata(item: item, collectionKey: collectionKey) {
- // Skip pure videos (we only want images + live photos)
+ // Cast images and Live Photos, not standalone videos.
if file.isVideo && !file.isLivePhoto {
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))")
- // Check if hash changed - clear cache if so
if oldFile.hash != file.hash && file.hash != nil {
print("Hash changed for file \(id) - clearing cache")
prefetchCache.removeValue(forKey: id)
await removeCachedFileContent(fileID: id)
}
- // Track if current file was modified
if existingIndex == currentFileIndex {
currentFileChanged = true
}
@@ -479,9 +421,7 @@ class RealSlideshowService: ObservableObject {
print("File list now contains \(allFiles.count) files")
- // Handle state transitions
if allFiles.isEmpty {
- // Transition to empty state
slideTimer?.invalidate()
slideTimer = nil
isPlaying = false
@@ -495,17 +435,15 @@ class RealSlideshowService: ObservableObject {
currentFileIndex = 0
error = "No media files available in this album"
} else if wasEmpty {
- // Transition from empty to having files
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")
- error = nil // Clear error first to avoid UI flicker
+ // Clear before loading to avoid an empty-state flash.
+ error = nil
- // Display first slide and start slideshow
Task {
await displaySlideAtCurrentIndex()
await MainActor.run {
@@ -517,15 +455,12 @@ class RealSlideshowService: ObservableObject {
}
}
} else {
- // Normal update - just update count
totalSlides = allFiles.count
- // Ensure current index is valid
if currentFileIndex >= allFiles.count {
currentFileIndex = 0
}
- // If current file was modified, reload it
if currentFileChanged && !allFiles.isEmpty {
Task {
await displaySlideAtCurrentIndex()
@@ -533,15 +468,12 @@ class RealSlideshowService: ObservableObject {
}
}
- // Clean up expired cache entries after processing batch
let currentValidFileIDs = Set(allFiles.map { $0.id })
Task {
await cleanupExpiredCache(validFileIDs: currentValidFileIDs)
}
}
- // MARK: - Slide Display & Navigation
-
private func displaySlideAtCurrentIndex() async {
guard currentFileIndex >= 0, currentFileIndex < allFiles.count,
let payload = storedCastPayload else { return }
@@ -551,7 +483,6 @@ class RealSlideshowService: ObservableObject {
slideLoadingProgress = 0.0
}
- // Check cache first
if let cachedData = prefetchCache[currentFileIndex] {
await updateCurrentSlide(with: cachedData, file: allFiles[currentFileIndex])
await MainActor.run { slideLoadingProgress = 1.0 }
@@ -575,19 +506,16 @@ class RealSlideshowService: ObservableObject {
await updateCurrentSlide(with: decryptedData, file: file)
await MainActor.run { slideLoadingProgress = 1.0 }
- // Start prefetching next few slides
startPrefetching()
} catch {
let file = allFiles[currentFileIndex]
print("Failed to load file \(file.id): \(file.title) at index \(currentFileIndex) - \(error)")
- // Auto-skip problematic files and continue slideshow
await MainActor.run {
slideLoadingProgress = 0.0
}
- // Try next slide automatically after a brief delay
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
Task {
await self.skipToNextSlide()
@@ -598,17 +526,15 @@ class RealSlideshowService: ObservableObject {
@MainActor
private func updateCurrentSlide(with data: Data, file: CastFile) {
- // Seamless transition: don't nuke existing image until replacement assigned
- let wasEmpty = error == "No media files available in this album"
- error = nil
- currentFile = file
+ // Keep the old image until its replacement is ready.
+ let wasEmpty = error == "No media files available in this album"
+ error = nil
+ currentFile = file
if file.isLivePhoto {
- // Handle live photo: extract image component only, store video separately
do {
let components = try extractLivePhotoComponents(from: data)
- // 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")
@@ -616,7 +542,6 @@ class RealSlideshowService: ObservableObject {
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")
@@ -624,34 +549,29 @@ class RealSlideshowService: ObservableObject {
livePhotoVideoData = nil
}
- // Clear video properties to ensure image display
currentVideoData = nil
currentVideoURL = nil
- // Start timer for live photo (show as image)
startSlideTimer()
} catch {
print("Failed to extract live photo components: \(error)")
- // Fallback to treating as regular image
currentImageData = data
currentVideoData = nil
currentVideoURL = nil
livePhotoVideoData = nil
startSlideTimer()
}
-
+
} else if file.isVideo {
- // Switching to video: clear image state now
currentImageData = nil
livePhotoVideoData = nil
- // Write decrypted data to a temp file to preserve original color space & avoid brightness shifts
+ // A temp file preserves the color space and avoids brightness shifts.
do {
let url: URL
if let existing = videoTempFiles[file.id] {
url = existing
} else {
- // Extract proper file extension from filename
let fileExtension = file.title.components(separatedBy: ".").last?.lowercased() ?? "mp4"
let tmpURL = FileManager.default.temporaryDirectory.appendingPathComponent("cast_video_\(file.id)_\(UUID().uuidString).\(fileExtension)")
try data.write(to: tmpURL, options: .atomic)
@@ -659,24 +579,22 @@ class RealSlideshowService: ObservableObject {
url = tmpURL
}
currentVideoURL = url
- currentVideoData = nil // release raw data memory
+ currentVideoData = nil
prepareVideoPlayer(url: url)
} catch {
print("Failed to persist video temp file: \(error)")
currentVideoURL = nil
}
} else {
- // Regular image
currentVideoData = nil
currentVideoURL = nil
livePhotoVideoData = nil
- currentImageData = data // assign image last for minimal black gap
- // Start timer for image slide immediately
+ // Assign the image last to avoid a black frame.
+ currentImageData = data
startSlideTimer()
}
error = nil
- // If we just transitioned from empty to having content, notify the UI
if wasEmpty {
NotificationCenter.default.post(name: .slideshowRestarted, object: nil)
}
@@ -684,7 +602,7 @@ class RealSlideshowService: ObservableObject {
private func startSlideTimer(withDuration customDuration: TimeInterval? = nil) {
guard let currentFile = currentFile else { return }
- // For video slides we rely on actual playback end rather than a fixed timer
+ // Video playback advances the slideshow when it ends.
if currentFile.isVideo {
slideTimeRemaining = 0
slideStartTime = nil
@@ -696,14 +614,12 @@ class RealSlideshowService: ObservableObject {
slideStartTime = Date()
slideTimeRemaining = duration
- // For single photo albums, we still want the timer to fire to maintain the slideshow loop
slideTimer = Timer.scheduledTimer(withTimeInterval: duration, repeats: false) { [weak self] _ in
Task { @MainActor in
guard let self = self, self.isPlaying, !self.isPaused else { return }
self.slideTimeRemaining = 0
self.slideStartTime = nil
- // For single photos, nextSlide will just restart the timer
await self.nextSlide()
}
}
@@ -714,7 +630,6 @@ class RealSlideshowService: ObservableObject {
currentFileIndex = (currentFileIndex + 1) % allFiles.count
- // If we've gone through all files and still have errors, stop the slideshow
let maxRetries = allFiles.count
var retryCount = 0
@@ -730,7 +645,6 @@ class RealSlideshowService: ObservableObject {
file: file
)
- // Success! Update the slide
prefetchCache[currentFileIndex] = decryptedData
await updateCurrentSlide(with: decryptedData, file: file)
@@ -741,12 +655,10 @@ class RealSlideshowService: ObservableObject {
print("Successfully loaded file \(file.id): \(file.title)")
- // Restart timer if playing
if isPlaying && !isPaused {
startSlideTimer()
}
- // Start prefetching again
startPrefetching()
return
@@ -758,7 +670,6 @@ class RealSlideshowService: ObservableObject {
}
}
- // If we reach here, all files have issues
await MainActor.run {
self.error = "Unable to load any slides. All files may be corrupted or have decryption issues."
}
@@ -770,7 +681,6 @@ class RealSlideshowService: ObservableObject {
for i in 1...prefetchCount {
let prefetchIndex = (currentFileIndex + i) % allFiles.count
- // Skip if already cached
if prefetchCache[prefetchIndex] != nil { continue }
guard let payload = storedCastPayload else { continue }
@@ -783,7 +693,6 @@ class RealSlideshowService: ObservableObject {
)
prefetchCache[prefetchIndex] = data
- // Clean up old cache entries
if prefetchCache.count > 5 {
let oldKeys = Array(prefetchCache.keys.sorted().prefix(prefetchCache.count - 5))
for key in oldKeys {
@@ -797,17 +706,13 @@ class RealSlideshowService: ObservableObject {
continue
}
- // Add delay between prefetch operations
- try? await Task.sleep(nanoseconds: 500_000_000) // 0.5 seconds
+ try? await Task.sleep(nanoseconds: 500_000_000)
}
}
}
- // MARK: - Video Playback Management
-
private func prepareVideoPlayer(url: URL) {
let playerItem = AVPlayerItem(url: url)
- // Observe duration once ready
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: playerItem, queue: .main) { [weak self] _ in
Task { @MainActor in
self?.videoDidFinish()
@@ -818,13 +723,11 @@ class RealSlideshowService: ObservableObject {
videoPlayer = player
isVideoPlaying = false
videoCurrentTime = 0
- // Get duration asynchronously for iOS 16+
Task { @MainActor in
if let duration = try? await playerItem.asset.load(.duration) {
self.videoDuration = CMTimeGetSeconds(duration)
}
}
- // Auto-play
playVideo()
startVideoProgressUpdates()
}
@@ -845,7 +748,6 @@ class RealSlideshowService: ObservableObject {
guard let player = videoPlayer else { return }
player.play()
isVideoPlaying = true
- // Ensure slideshow timer paused during video playback
slideTimer?.invalidate()
}
@@ -858,13 +760,11 @@ class RealSlideshowService: ObservableObject {
}
}
- // MARK: - Periodic Diff Polling
-
@MainActor
private func startPeriodicDiffPolling() {
guard isPeriodicPollingEnabled && storedCastPayload != nil else { return }
- stopPeriodicDiffPolling() // Stop any existing timer
+ stopPeriodicDiffPolling()
print("Starting periodic diff polling (every \(diffPollingInterval)s)")
@@ -896,7 +796,6 @@ class RealSlideshowService: ObservableObject {
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)")
@@ -910,48 +809,38 @@ class RealSlideshowService: ObservableObject {
} catch {
if let castError = error as? CastError,
case .serverError(401, _) = castError {
- // handleUnauthorizedError already called in fetchFilesBatch
+ // fetchFilesBatch already handled this error.
} else {
print("Periodic diff check failed: \(error)")
- // Continue polling on other errors
}
}
}
- // MARK: - 401 Error Handling
-
@MainActor
private func handleUnauthorizedError() {
- // Prevent multiple concurrent auth expiry handling
guard !isHandlingAuthExpiry else {
return
}
isHandlingAuthExpiry = true
- // Stop screen saver prevention immediately before any UI transitions
ScreenSaverManager.allowScreenSaver()
- // Stop all ongoing operations
isPeriodicPollingEnabled = false
stopPeriodicDiffPolling()
- // Notify the view model to reset session
NotificationCenter.default.post(name: .authenticationExpired, object: nil)
- // Reset flag after a delay to allow reset to complete
+ // Keep the guard set while the session resets.
Task {
- try? await Task.sleep(nanoseconds: 2_000_000_000) // 2 seconds
+ try? await Task.sleep(nanoseconds: 2_000_000_000)
await MainActor.run {
self.isHandlingAuthExpiry = false
}
}
}
- // MARK: - Network & Download
-
private func downloadEncryptedFile(castPayload: CastPayload, fileID: Int) async throws -> Data {
- // Use the file download endpoint with cast-specific headers
let url = URL(string: "\(castDownloadURL)/?fileID=\(fileID)")!
var request = URLRequest(url: url)
@@ -965,7 +854,6 @@ 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)")
if httpResponse.statusCode == 401 {
@@ -980,13 +868,11 @@ class RealSlideshowService: ObservableObject {
}
private func downloadAndDecryptFileContent(castPayload: CastPayload, file: CastFile) async throws -> Data {
- // Check if service is stopping
let stopping = await MainActor.run { isStopping }
if stopping {
throw CastError.networkError("Service is stopping")
}
- // 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)") }
return cachedData
@@ -994,11 +880,9 @@ class RealSlideshowService: ObservableObject {
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") }
- // Step 2: Decrypt file key using collection key
let fileKey = try decryptFileKey(
encryptedKey: file.encryptedKey,
nonce: file.keyDecryptionNonce,
@@ -1006,7 +890,6 @@ class RealSlideshowService: ObservableObject {
)
- // Step 3: Decrypt file content using file key and decryption header
let decryptedData = try decryptFileContent(
encryptedData: encryptedData,
fileKey: fileKey,
@@ -1014,14 +897,11 @@ class RealSlideshowService: ObservableObject {
)
- // Step 4: Cache the decrypted content
await cacheFileContent(fileID: file.id, data: decryptedData)
return decryptedData
}
- // MARK: - File Decryption Functions
-
private func decryptFileMetadata(item: [String: Any], collectionKey: String) async throws -> CastFile? {
guard let id = item["id"] as? Int,
let encryptedKey = item["encryptedKey"] as? String,
@@ -1036,7 +916,6 @@ class RealSlideshowService: ObservableObject {
}
do {
- // Step 1: Decrypt file key using collection key (SecretBox)
let fileKey = try decryptFileKey(
encryptedKey: encryptedKey,
nonce: keyDecryptionNonce,
@@ -1044,7 +923,6 @@ class RealSlideshowService: ObservableObject {
)
if verboseDecryptionLogging { print("File key decrypted successfully") }
- // Step 2: Decrypt metadata using file key (XChaCha20-Poly1305)
let metadata = try decryptMetadata(
encryptedData: encryptedMetadata,
decryptionHeader: metadataHeader,
@@ -1052,11 +930,9 @@ class RealSlideshowService: ObservableObject {
)
- // Step 3: Parse decrypted metadata JSON
let fileMetadata = try parseFileMetadata(data: metadata)
- // Create CastFile with decrypted metadata and decryption info
let isVideo = fileMetadata.fileType == 1
let isLivePhoto = fileMetadata.fileType == 2
return CastFile(
@@ -1077,7 +953,6 @@ class RealSlideshowService: ObservableObject {
}
private func decryptFileKey(encryptedKey: String, nonce: String, collectionKey: String) throws -> Data {
- // Convert base64 inputs to data
guard let encryptedKeyData = Data(base64Encoded: encryptedKey),
let nonceData = Data(base64Encoded: nonce),
let collectionKeyData = Data(base64Encoded: collectionKey) else {
@@ -1093,7 +968,6 @@ class RealSlideshowService: ObservableObject {
}
private func decryptMetadata(encryptedData: String, decryptionHeader: String, fileKey: Data) throws -> Data {
- // Convert base64 inputs to data
guard let encryptedBytes = Data(base64Encoded: encryptedData),
let headerBytes = Data(base64Encoded: decryptionHeader) else {
throw CastError.decryptionError("Invalid base64 in metadata decryption")
@@ -1111,7 +985,6 @@ class RealSlideshowService: ObservableObject {
}
private func decryptFileContent(encryptedData: Data, fileKey: Data, decryptionHeader: String) throws -> Data {
- // Convert base64 header to data
guard let headerBytes = Data(base64Encoded: decryptionHeader) else {
throw CastError.decryptionError("Invalid base64 in file decryption header")
}
@@ -1126,7 +999,6 @@ class RealSlideshowService: ObservableObject {
}
private func parseFileMetadata(data: Data) throws -> FileMetadata {
- // Parse the decrypted JSON metadata
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
throw CastError.decryptionError("Invalid JSON in decrypted metadata")
}
@@ -1146,8 +1018,6 @@ class RealSlideshowService: ObservableObject {
)
}
- // MARK: - Cache Management Helpers
-
private func getCachedFileContent(fileID: Int) async -> Data? {
return await fileCache.get(fileID)
}
@@ -1160,10 +1030,8 @@ class RealSlideshowService: ObservableObject {
let stats = await getCacheStats()
print("Starting cache cleanup - current cache has \(stats.count) files")
- // Get all currently cached file IDs
let cachedFileIDs = await fileCache.getCachedFileIDs()
- // Remove files that are no longer valid
var removedCount = 0
for cachedFileID in cachedFileIDs {
if !validFileIDs.contains(cachedFileID) {
@@ -1191,8 +1059,6 @@ class RealSlideshowService: ObservableObject {
}
}
-// MARK: - Live Photo Utilities
-
func extractZipUsingFoundation(zipURL: URL, to destinationURL: URL) throws {
do {
try FileManager.default.unzipItem(at: zipURL, to: destinationURL)
@@ -1220,10 +1086,9 @@ func extractLivePhotoComponents(from zipData: Data) throws -> LivePhotoComponent
var videoPath: URL?
do {
- // For tvOS, we'll implement a simple zip reader using Foundation
try extractZipUsingFoundation(zipURL: zipURL, to: extractDirectory)
- // Enumerate all extracted files (including nested) because zips may contain a folder structure.
+ // Live Photo zips may nest their assets.
let resourceKeys: [URLResourceKey] = [.isDirectoryKey]
let enumerator = FileManager.default.enumerator(at: extractDirectory, includingPropertiesForKeys: resourceKeys)
@@ -1238,7 +1103,6 @@ func extractLivePhotoComponents(from zipData: Data) throws -> LivePhotoComponent
}
while let fileURL = enumerator?.nextObject() as? URL {
- // Skip directories
if (try? fileURL.resourceValues(forKeys: Set(resourceKeys)).isDirectory) == true { continue }
let filename = fileURL.lastPathComponent
@@ -1251,18 +1115,17 @@ func extractLivePhotoComponents(from zipData: Data) throws -> LivePhotoComponent
videoPath = fileURL
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)")
}
}
}
- // Fallback heuristics: Some live photo packages may store assets without extensions or with generic names.
+ // Some packages use extensionless or generic asset names.
if imageData == nil || videoData == nil {
let contents = try FileManager.default.contentsOfDirectory(at: extractDirectory, includingPropertiesForKeys: nil)
if imageData == nil {
- if let guessImage = contents.first(where: { $0.pathExtension.isEmpty }) { // pick first extension-less file as possible image
+ if let guessImage = contents.first(where: { $0.pathExtension.isEmpty }) {
imageData = try? Data(contentsOf: guessImage)
imagePath = guessImage
if imageData != nil { print("Heuristic image pick: \(guessImage.lastPathComponent)") }
diff --git a/apple/apps/cast/Cast/Views/PairingView.swift b/apple/apps/cast/Cast/Views/PairingView.swift
index 2d31e48f9c..a8c2d45773 100644
--- a/apple/apps/cast/Cast/Views/PairingView.swift
+++ b/apple/apps/cast/Cast/Views/PairingView.swift
@@ -8,26 +8,19 @@ struct PairingView: View {
var body: some View {
GeometryReader { geometry in
ZStack {
- // White background
Color.white
.ignoresSafeArea()
- // Main content - card positioned with custom padding
HStack(spacing: 0) {
- // Left padding (1x)
Spacer()
.frame(width: geometry.size.width * 0.05)
- // Green card with content
ZStack {
- // Green card background
RoundedRectangle(cornerRadius: 36)
.fill(Color(red: 0/255, green: 179/255, blue: 61/255))
.shadow(color: Color.black.opacity(0.25), radius: 4, y: 4)
- // Card content
VStack(spacing: 0) {
- // Title section
VStack(spacing: -5) {
Text("Ready to")
.font(FontUtils.montserratExtraBold(size: geometry.size.width * 0.035))
@@ -42,9 +35,8 @@ struct PairingView: View {
Spacer()
.frame(height: geometry.size.height * 0.05)
- // Pairing code box
ZStack {
- // Reserve the 6-char code footprint so the box doesn't resize when the code arrives
+ // Reserve six characters so the box does not resize.
Text(deviceCode.isEmpty ? "000000" : deviceCode)
.font(.system(size: geometry.size.width * 0.09, weight: .heavy, design: .monospaced))
.tracking(geometry.size.width * 0.015)
@@ -73,7 +65,6 @@ struct PairingView: View {
Spacer()
.frame(height: geometry.size.height * 0.08)
- // Instruction steps
HStack(spacing: geometry.size.width * 0.05) {
InstructionStep(
number: "1",
@@ -100,7 +91,6 @@ struct PairingView: View {
Spacer()
.frame(height: geometry.size.height * 0.06)
- // Help text
Text("Visit ente.com/cast for help")
.font(FontUtils.interMedium(size: geometry.size.width * 0.012))
.foregroundColor(.white)
@@ -109,7 +99,6 @@ struct PairingView: View {
.frame(height: geometry.size.height * 0.04)
}
- // Ducky positioned at bottom right of the card
VStack {
Spacer()
HStack {
@@ -127,14 +116,12 @@ struct PairingView: View {
.frame(width: geometry.size.width * 0.8,
height: geometry.size.height * 0.85)
- // Right padding (3x)
Spacer()
.frame(width: geometry.size.width * 0.15)
}
- .padding(.top, geometry.size.height * 0.05) // Top padding (1x)
- .padding(.bottom, geometry.size.height * 0.05) // Bottom padding (1x)
+ .padding(.top, geometry.size.height * 0.05)
+ .padding(.bottom, geometry.size.height * 0.05)
- // Ente logo in top right corner
VStack {
HStack {
Spacer()
@@ -167,7 +154,6 @@ struct InstructionStep: View {
var body: some View {
VStack(spacing: geometry.size.height * 0.015) {
- // Circular icon background
ZStack {
Circle()
.fill(Color(red: 0/255, green: 150/255, blue: 51/255))
@@ -179,7 +165,6 @@ struct InstructionStep: View {
.foregroundColor(.white)
}
- // Step text
Text(text)
.font(FontUtils.interMedium(size: geometry.size.width * 0.012))
.foregroundColor(.white)
diff --git a/apple/apps/cast/Cast/Views/SlideshowView.swift b/apple/apps/cast/Cast/Views/SlideshowView.swift
index d7a34e16c6..5a0c3108ad 100644
--- a/apple/apps/cast/Cast/Views/SlideshowView.swift
+++ b/apple/apps/cast/Cast/Views/SlideshowView.swift
@@ -40,13 +40,11 @@ struct SlideshowView: View {
}
var body: some View {
- // Use pre-decoded images to avoid decoding during render
let mainUIImage = preDecodedImage
let previousUIImage = previousDecodedImage
return GeometryReader { geometry in
ZStack {
- // Background layer
if let uiImage = mainUIImage {
Image(uiImage: uiImage)
.resizable()
@@ -61,7 +59,6 @@ struct SlideshowView: View {
Color.black.ignoresSafeArea()
}
- // Foreground content
if isVideo, let videoData = videoData {
VideoPlayerView(
videoData: videoData,
@@ -82,9 +79,7 @@ struct SlideshowView: View {
removal: .scale(scale: 0.9).combined(with: .opacity)
))
} else if let uiImage = mainUIImage {
- // Crossfade image transition
ZStack {
- // Previous image (fading out)
if let prevImage = previousUIImage {
Image(uiImage: prevImage)
.resizable()
@@ -94,7 +89,6 @@ struct SlideshowView: View {
.opacity(previousImageOpacity)
}
- // Current image (fading in)
Image(uiImage: uiImage)
.resizable()
.aspectRatio(contentMode: .fit)
@@ -103,7 +97,6 @@ struct SlideshowView: View {
.opacity(imageOpacity)
}
.onAppear {
- // Pass image data count for logging purposes
animateImageIn(bytes: displayImageData?.count ?? 0, isLive: isLivePhoto)
}
.onDisappear {
@@ -115,20 +108,16 @@ struct SlideshowView: View {
} else {
- // Check if we have an empty state vs loading state
if let error = slideshowService.error,
(error.contains("No media files available") || error.contains("Empty file list")) {
EmptyState()
} else if slideshowService.totalSlides == 0 && !slideshowService.isPlaying {
- // Still loading initial file list
LoadingState()
} else {
- // Files exist but current slide is loading
LoadingState()
}
}
- // Overlays
actionFeedbackOverlay
controlsOverlay
toastOverlay
@@ -137,28 +126,22 @@ struct SlideshowView: View {
.onChange(of: imageData) { newValue in
if let newData = newValue {
Task {
- // Pre-decode image off main thread
let decodedImage = decodedUIImage(from: newData)
await MainActor.run {
- // Store current decoded image as previous for crossfade
previousDecodedImage = preDecodedImage
previousImageData = displayImageData
- // Set decoded image first
preDecodedImage = decodedImage
- // Set up opacity states
if previousDecodedImage != nil {
previousImageOpacity = 1.0
imageOpacity = 0.0
} else {
- // First image - no crossfade needed
imageOpacity = 1.0
previousImageOpacity = 0.0
}
- // Then update display data to trigger view update
displayImageData = newData
animateImageIn(bytes: newData.count, isLive: isLivePhoto)
}
@@ -181,13 +164,9 @@ struct SlideshowView: View {
.onAppear {
startControlsTimer()
isFocused = true
- // Backup screen saver prevention at view level
ScreenSaverManager.preventScreenSaver()
- // Process initial image data if present and not already processed
- // This handles the case where SlideshowView is created with imageData already populated
- // (e.g., when transitioning from .connecting to .slideshow state)
- // Without this, onChange won't fire and the image won't display
+ // onChange does not fire when the view starts with imageData set.
if let initialImageData = imageData, displayImageData == nil && !isVideo {
Task {
let decodedImage = decodedUIImage(from: initialImageData)
@@ -203,13 +182,10 @@ struct SlideshowView: View {
}
}
.onDisappear {
- // Ensure screen saver prevention is disabled when view disappears
ScreenSaverManager.allowScreenSaver()
}
}
- // MARK: - Overlay Views
-
@ViewBuilder
private var actionFeedbackOverlay: some View {
if let feedback = actionFeedback {
@@ -267,7 +243,6 @@ struct SlideshowView: View {
showToast(icon: "livephoto", message: "Live Photo Paused")
}
- // Auto-return to image after video plays
if isPlayingLivePhotoVideo {
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
withAnimation(.easeInOut(duration: 0.3)) {
@@ -282,7 +257,6 @@ struct SlideshowView: View {
slideshowService.togglePlayPause()
await MainActor.run {
- // Show toast notification only
if slideshowService.isPaused {
showToast(icon: "pause.fill", message: "Paused")
} else {
@@ -295,10 +269,8 @@ struct SlideshowView: View {
switch direction {
case .left:
await slideshowService.previousSlide()
- // No center feedback for navigation
case .right:
await slideshowService.nextSlide()
- // No center feedback for navigation
case .up, .down:
toggleControls()
@unknown default:
@@ -329,18 +301,15 @@ struct SlideshowView: View {
toastMessage = message
showToast = true
- // Auto-dismiss after 2 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
showToast = false
}
}
- // MARK: - Image Decoding & Animation
-
private func decodedUIImage(from data: Data) -> UIImage? {
imageDecodeFailed = false
if let uiImage = UIImage(data: data) {
- // Force decompression by accessing cgImage
+ // Accessing cgImage forces decompression.
if let cg = uiImage.cgImage {
return UIImage(cgImage: cg, scale: uiImage.scale, orientation: uiImage.imageOrientation)
}
@@ -356,7 +325,6 @@ struct SlideshowView: View {
lastImageBytes = bytes
imageScale = 1.0
- // Opacity states are already set up in onChange, just animate the crossfade
withAnimation(.easeInOut(duration: 0.25)) {
imageOpacity = 1.0
previousImageOpacity = 0.0
@@ -364,9 +332,8 @@ struct SlideshowView: View {
print("Displaying \(isLive ? "live" : "static") image (\(bytes) bytes)")
- // Clean up previous image data after animation
Task {
- try? await Task.sleep(nanoseconds: 300_000_000) // 0.3 seconds
+ try? await Task.sleep(nanoseconds: 300_000_000)
await MainActor.run {
previousImageData = nil
previousImageOpacity = 0.0
@@ -376,8 +343,6 @@ struct SlideshowView: View {
}
-// MARK: - Supporting Views and Types
-
struct LoadingState: View {
@State private var animationPhase: CGFloat = 0
@State private var pulseScale: CGFloat = 1.0
@@ -633,8 +598,6 @@ struct AppleStyleToast: View {
}
}
-// MARK: - Preview
-
class MockSlideshowService: ObservableObject {
@Published var currentFile: (title: String, isLivePhoto: Bool)? = (title: "Sample Image", isLivePhoto: false)
@Published var isPlaying: Bool = true
diff --git a/apple/apps/cast/Cast/Views/StatusView.swift b/apple/apps/cast/Cast/Views/StatusView.swift
index d37bfb8eb1..31f5ba38f5 100644
--- a/apple/apps/cast/Cast/Views/StatusView.swift
+++ b/apple/apps/cast/Cast/Views/StatusView.swift
@@ -17,25 +17,20 @@ struct StatusView: View {
var body: some View {
GeometryReader { geometry in
ZStack {
- // White background
Color.white
.ignoresSafeArea()
- // Main content
VStack(spacing: 24) {
Spacer()
- // Status icon - clean display without backgrounds
StatusIcon(status: status)
.padding(.bottom, 16)
- // Title
Text(title)
.font(FontUtils.interSemiBold(size: 42))
.foregroundColor(.black)
.multilineTextAlignment(.center)
- // Message (if not empty)
if !message.isEmpty {
Text(message)
.font(FontUtils.interRegular(size: 20))
@@ -49,7 +44,6 @@ struct StatusView: View {
.frame(maxWidth: 900)
.frame(maxWidth: .infinity)
- // Ente branding in top right corner
VStack {
HStack {
Spacer()
@@ -94,7 +88,6 @@ struct StatusIcon: View {
let status: StatusView.StatusType
var body: some View {
- // Simple icon display without any backgrounds or effects
iconView
.frame(width: 400, height: 240)
}
diff --git a/apple/apps/cast/Cast/Views/VideoPlayerView.swift b/apple/apps/cast/Cast/Views/VideoPlayerView.swift
index b8c07cb2d3..1c6a2c972f 100644
--- a/apple/apps/cast/Cast/Views/VideoPlayerView.swift
+++ b/apple/apps/cast/Cast/Views/VideoPlayerView.swift
@@ -33,7 +33,6 @@ struct VideoPlayerView: View {
cleanup()
}
} else {
- // Clean loading state
VStack(spacing: 24) {
ProgressView()
.progressViewStyle(CircularProgressViewStyle(tint: Color(red: 29/255, green: 185/255, blue: 84/255)))
@@ -72,7 +71,6 @@ struct VideoPlayerView: View {
let playerItem = AVPlayerItem(url: tempURL)
let player = AVPlayer(playerItem: playerItem)
- // Monitor player item status using modern async/await approach
self.monitorPlayerItemStatus(playerItem)
self.playerItem = playerItem
@@ -95,7 +93,6 @@ struct VideoPlayerView: View {
}
private func tryVideoFallback(originalURL: URL) {
- // Try creating a new temp file with .mov extension as fallback
Task {
do {
let fallbackURL = originalURL.deletingPathExtension().appendingPathExtension("mov")
@@ -118,11 +115,9 @@ struct VideoPlayerView: View {
}
private func showErrorState() {
- // Could show an error message or placeholder
}
private func monitorPlayerItemStatus(_ playerItem: AVPlayerItem) {
- // Monitor status using a timer-based approach since we can't use KVO in SwiftUI structs
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in
switch playerItem.status {
case .readyToPlay:
@@ -137,7 +132,6 @@ struct VideoPlayerView: View {
self.showErrorState()
}
case .unknown:
- // Keep checking
break
@unknown default:
timer.invalidate()
@@ -148,11 +142,9 @@ struct VideoPlayerView: View {
private func setupPlayer() {
guard let player = player else { return }
- // Configure player for TV playback
player.actionAtItemEnd = .none
player.automaticallyWaitsToMinimizeStalling = true
- // Set audio session for proper audio handling
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback)
try AVAudioSession.sharedInstance().setActive(true)
@@ -169,13 +161,11 @@ struct VideoPlayerView: View {
private func setupPlayerObservers() {
guard let player = player, let currentItem = player.currentItem else { return }
- // Add observer for when video ends
NotificationCenter.default.addObserver(
forName: .AVPlayerItemDidPlayToEndTime,
object: currentItem,
queue: .main
) { _ in
- // Loop the video
player.seek(to: .zero)
player.play()
}
@@ -190,7 +180,6 @@ struct VideoPlayerView: View {
}
}
- // Add observer for app lifecycle
NotificationCenter.default.addObserver(
forName: UIApplication.willResignActiveNotification,
object: nil,
@@ -217,9 +206,8 @@ struct VideoPlayerView: View {
try data.write(to: tempURL)
- // Schedule cleanup of temp file after some time
Task {
- try? await Task.sleep(nanoseconds: 60_000_000_000) // 60 seconds
+ try? await Task.sleep(nanoseconds: 60_000_000_000)
try? FileManager.default.removeItem(at: tempURL)
}
@@ -227,7 +215,7 @@ struct VideoPlayerView: View {
}
private func detectVideoExtension(from data: Data) -> String? {
- let headerBytes = data.prefix(32) // Read more bytes for better detection
+ let headerBytes = data.prefix(32)
if headerBytes.count >= 4 {
let signature = headerBytes.prefix(4)
@@ -278,8 +266,6 @@ struct VideoPlayerView: View {
private func cleanup() {
player?.pause()
- // KVO observer removal no longer needed as we use modern async/await approach
-
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: nil)
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemFailedToPlayToEndTime, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)
diff --git a/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift b/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift
index 35f7dd027f..78fb826bc0 100644
--- a/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift
+++ b/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift
@@ -129,7 +129,6 @@ final class ChatViewModel: ObservableObject {
let knowledgeProvider = KnowledgeProvider(assetStore: assetStore)
let knowledgeStore = KnowledgeStore(datasets: config.knowledgeDatasets, provider: knowledgeProvider)
- // Chat DB + attachments.
let dbDir = baseDir.appendingPathComponent("llmchat", isDirectory: true)
try? FileManager.default.createDirectory(at: dbDir, withIntermediateDirectories: true, attributes: nil)
let attachmentsDir = dbDir.appendingPathComponent("chat_attachments", isDirectory: true)
@@ -152,7 +151,6 @@ final class ChatViewModel: ObservableObject {
fatalError("Failed to open chat DB: \(error)")
}
- // Load sessions/messages.
let loadedResult = try? chatDb.listSessions()
if let loadedResult {
Self.pruneOrphanedAttachments(
@@ -164,7 +162,6 @@ final class ChatViewModel: ObservableObject {
let loaded = loadedResult ?? []
let sessions = Self.buildSessions(from: loaded, chatDb: chatDb, summaries: summaries)
- // Stored properties.
self.provider = provider
self.knowledgeEmbedding = config.knowledgeEmbedding
self.knowledgeProvider = knowledgeProvider
diff --git a/apple/apps/ensu/Ensu/Chat/MessageInputView.swift b/apple/apps/ensu/Ensu/Chat/MessageInputView.swift
index 5d329738c8..ec51c758c9 100644
--- a/apple/apps/ensu/Ensu/Chat/MessageInputView.swift
+++ b/apple/apps/ensu/Ensu/Chat/MessageInputView.swift
@@ -53,7 +53,6 @@ struct MessageInputView: View {
let inputVerticalPadding: CGFloat = 10
let textFieldPadding: CGFloat = 6
- // Lift the bar slightly off the bottom edge.
let bottomPadding: CGFloat = EnsuSpacing.md
let inputStackSpacing: CGFloat = EnsuSpacing.sm
diff --git a/apple/apps/ensu/Ensu/Services/KeychainStore.swift b/apple/apps/ensu/Ensu/Services/KeychainStore.swift
index 969f758013..6839f3aab3 100644
--- a/apple/apps/ensu/Ensu/Services/KeychainStore.swift
+++ b/apple/apps/ensu/Ensu/Services/KeychainStore.swift
@@ -18,7 +18,6 @@ final class KeychainStore {
kSecValueData as String: data,
]
- // Try update first.
let updateStatus = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
if updateStatus == errSecSuccess {
return
@@ -27,7 +26,6 @@ final class KeychainStore {
throw KeychainStoreError.unexpectedStatus(updateStatus)
}
- // Insert.
var insertQuery = query
insertQuery[kSecValueData as String] = data
insertQuery[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly