π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Allow configuring Cast API endpoint
Neeraj Guptad3491ec47af3
diff --git a/apple/apps/cast/Cast/ContentView.swift b/apple/apps/cast/Cast/ContentView.swiftindex c55fcc1e41..917c4e227f 100644--- a/apple/apps/cast/Cast/ContentView.swift+++ b/apple/apps/cast/Cast/ContentView.swift@@ -2,6 +2,8 @@ import SwiftUIstruct ContentView: View {@StateObject private var viewModel = CastViewModel()+ @State private var tapCount = 0+ @State private var isConfiguringEndpoint = falsevar body: some View {ZStack {@@ -40,6 +42,17 @@ struct ContentView: View {}}.animation(.easeInOut(duration: 0.6), value: viewModel.currentView)+ .focusable(viewModel.currentView != .slideshow)+ .onTapGesture {+ guard viewModel.currentView != .slideshow else { return }+ tapCount += 1+ guard tapCount == 7 else { return }+ tapCount = 0+ isConfiguringEndpoint = true+ }+ .sheet(isPresented: $isConfiguringEndpoint) {+ APIEndpointView(onSave: viewModel.endpointChanged)+ }}}diff --git a/apple/apps/cast/Cast/Info.plist b/apple/apps/cast/Cast/Info.plistindex 1853b470de..cadb856ad7 100644--- a/apple/apps/cast/Cast/Info.plist+++ b/apple/apps/cast/Cast/Info.plist@@ -2,6 +2,11 @@<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>+ <key>NSAppTransportSecurity</key>+ <dict>+ <key>NSAllowsLocalNetworking</key>+ <true/>+ </dict><key>UIAppFonts</key><array><string>Montserrat-Bold.ttf</string>diff --git a/apple/apps/cast/Cast/Services/APIEndpoint.swift b/apple/apps/cast/Cast/Services/APIEndpoint.swiftnew file mode 100644index 0000000000..ab6dfdc946--- /dev/null+++ b/apple/apps/cast/Cast/Services/APIEndpoint.swift@@ -0,0 +1,44 @@+import Foundation++enum APIEndpoint {+ static let production = URL(string: "https://api.ente.com")!++ static var current: URL { UserDefaults.standard.url(forKey: "endpoint") ?? production }++ static var isProduction: Bool { current == production }++ static func reset() { UserDefaults.standard.removeObject(forKey: "endpoint") }++ static func update(_ value: String) async throws {+ let value = value.trimmingCharacters(in: .whitespacesAndNewlines)+ guard var components = URLComponents(string: value),+ let scheme = components.scheme,+ ["http", "https"].contains(scheme.lowercased()),+ components.host != nil,+ components.user == nil,+ components.query == nil,+ components.fragment == nil,+ components.path.isEmpty || components.path == "/"+ else { throw EndpointError.invalidURL }+ components.scheme = scheme.lowercased()+ components.path = ""+ guard let url = components.url else { throw EndpointError.invalidURL }++ var request = URLRequest(url: url.appendingPathComponent("ping"))+ request.timeoutInterval = 10+ let (data, response) = try await URLSession.shared.data(for: request)+ guard (response as? HTTPURLResponse)?.statusCode == 200,+ (try? JSONDecoder().decode(Ping.self, from: data).message) == "pong"+ else { throw EndpointError.invalidServer }++ url == production ? reset() : UserDefaults.standard.set(url, forKey: "endpoint")+ }++ private struct Ping: Decodable { let message: String }++ private enum EndpointError: String, LocalizedError {+ case invalidURL = "Enter a valid HTTP or HTTPS API URL"+ case invalidServer = "The URL is not an Ente API server"+ var errorDescription: String? { rawValue }+ }+}diff --git a/apple/apps/cast/Cast/Services/CastPairingService.swift b/apple/apps/cast/Cast/Services/CastPairingService.swiftindex d9883e5afa..bd09a3b9f8 100644--- a/apple/apps/cast/Cast/Services/CastPairingService.swift+++ b/apple/apps/cast/Cast/Services/CastPairingService.swift@@ -21,6 +21,7 @@ class CastSession: ObservableObject {}func setState(_ newState: CastSessionState) {+ guard state != newState else { return }state = newStateisActive = !isIdle}@@ -34,7 +35,7 @@ class CastSession: ObservableObject {}class RealCastPairingService {- private let baseURL = "https://api.ente.com"+ private let baseURL = APIEndpoint.current.absoluteStringprivate var pollingTimer: Timer?private var isPolling: Bool = falseprivate var isFetchingPayload: Bool = false@@ -176,9 +177,4 @@ class RealCastPairingService {pollingStartTime = nil}- func resetForNewSession() {- stopPolling()- hasDeliveredPayload = false- hasLoggedIntervalSwitch = false- }}diff --git a/apple/apps/cast/Cast/ViewModels/CastViewModel.swift b/apple/apps/cast/Cast/ViewModels/CastViewModel.swiftindex 50e6559899..52966e3b93 100644--- a/apple/apps/cast/Cast/ViewModels/CastViewModel.swift+++ b/apple/apps/cast/Cast/ViewModels/CastViewModel.swift@@ -13,8 +13,9 @@ class CastViewModel: ObservableObject {@Published var errorMessage: String?private var cancellables = Set<AnyCancellable>()- private let pairingService: RealCastPairingService+ private var pairingService = RealCastPairingService()private let castSession: CastSession+ private var sessionID = UUID()public let slideshowService: RealSlideshowService@@ -28,7 +29,6 @@ class CastViewModel: ObservableObject {init() {self.castSession = CastSession()- self.pairingService = RealCastPairingService()self.slideshowService = RealSlideshowService()setupBindings()@@ -120,6 +120,12 @@ class CastViewModel: ObservableObject {}func startCastSession() {+ sessionID = UUID()+ pairingService.stopPolling()+ pairingService = RealCastPairingService()+ let sessionID = sessionID+ let pairingService = pairingService+castSession.setState(.registering)deviceCode = ""currentView = .pairing@@ -127,6 +133,7 @@ class CastViewModel: ObservableObject {Task {do {let device = try await pairingService.registerDevice()+ guard sessionID == self.sessionID else { return }await MainActor.run {deviceCode = device.deviceCode@@ -139,22 +146,36 @@ class CastViewModel: ObservableObject {device: device,onPayloadReceived: { [weak self] payload inTask { @MainActor in- self?.handlePayloadReceived(payload)+ guard let self, sessionID == self.sessionID else { return }+ self.handlePayloadReceived(payload)}},onError: { [weak self] error inTask { @MainActor in- self?.handleNetworkError(error)+ guard let self, sessionID == self.sessionID else { return }+ self.handleNetworkError(error)}})} catch {+ guard sessionID == self.sessionID else { return }handleNetworkError(error)}}}+ func endpointChanged() {+ sessionID = UUID()+ errorMessage = nil+ Task {+ await resetSession()+ await slideshowService.clearExpiredTokenState()+ await slideshowService.clearCache()+ startCastSession()+ }+ }+func resetSession() async {ScreenSaverManager.allowScreenSaver()@@ -180,14 +201,17 @@ class CastViewModel: ObservableObject {currentView = .connectingstatusMessage = ""+ let sessionID = sessionIDTask {try? await Task.sleep(nanoseconds: 500_000_000)+ guard sessionID == self.sessionID else { return }await slideshowService.start(castPayload: payload)try? await Task.sleep(nanoseconds: 1_000_000_000)await MainActor.run {+ guard sessionID == self.sessionID else { return }let hasError = slideshowService.error != nil && !slideshowService.error!.isEmptyif hasError {@@ -280,9 +304,11 @@ class CastViewModel: ObservableObject {private func handleNetworkError(_ error: Error) {handleError("An error occurred: \(error.localizedDescription)")+ let sessionID = sessionIDTask {try? await Task.sleep(nanoseconds: 5_000_000_000)await MainActor.run {+ guard sessionID == self.sessionID else { return }startCastSession()}}@@ -292,7 +318,6 @@ class CastViewModel: ObservableObject {Task {await resetSession()await slideshowService.clearExpiredTokenState()- pairingService.resetForNewSession()await MainActor.run {currentView = .connectingdiff --git a/apple/apps/cast/Cast/ViewModels/SlideshowService.swift b/apple/apps/cast/Cast/ViewModels/SlideshowService.swiftindex 36a5d6d2d8..d62b536c5f 100644--- a/apple/apps/cast/Cast/ViewModels/SlideshowService.swift+++ b/apple/apps/cast/Cast/ViewModels/SlideshowService.swift@@ -51,7 +51,7 @@ class RealSlideshowService: ObservableObject {private var didDisplayFirstFile: Bool = false- private let baseURL = "https://api.ente.com"+ private var baseURL = APIEndpoint.current.absoluteStringprivate let castDownloadURL = "https://cast-albums.ente.com/download"private let verboseFileLogging = false@@ -141,43 +141,37 @@ class RealSlideshowService: ObservableObject {ScreenSaverManager.preventScreenSaver()await clearExpiredTokenState()+ baseURL = APIEndpoint.current.absoluteStringstoredCastPayload = castPayload- await MainActor.run {- if self.error != nil { self.error = nil }- }+ if error != nil { error = nil }do {await initializeFileList(castPayload: castPayload)+ guard storedCastPayload == castPayload else { return }let fileCount = await MainActor.run { allFiles.count }if fileCount == 0 {- await MainActor.run {- self.error = "No media files available in this album"- }+ error = "No media files available in this album"return}print("Found \(fileCount) files total")let validFileIDs = Set(await MainActor.run { allFiles.map { $0.id } })- await cleanupExpiredCache(validFileIDs: validFileIDs)+ await cleanupExpiredCache(validFileIDs: validFileIDs, castPayload: castPayload)+ guard storedCastPayload == castPayload else { return }- await MainActor.run {- self.totalSlides = fileCount- self.currentFileIndex = 0- self.currentSlideIndex = 0- self.isPlaying = true- self.isPaused = false- }+ totalSlides = fileCount+ currentFileIndex = 0+ currentSlideIndex = 0+ isPlaying = true+ isPaused = falseawait displaySlideAtCurrentIndex()+ guard storedCastPayload == castPayload else { return }- if fileCount == 1 {- startSlideTimer()- } else {- startSlideTimer()- }+ startSlideTimer()print("Enhanced slideshow started with \(fileCount) slide(s)")} catch {@@ -256,12 +250,14 @@ class RealSlideshowService: ObservableObject {do {try await fetchAllFiles(castPayload: castPayload)+ guard storedCastPayload == castPayload else { return }hasCompletedInitialFetch = trueif !allFiles.isEmpty {allFiles.shuffle()}print("Initial diff fetch completed - \(allFiles.count) files cached (shuffled)")} catch {+ guard storedCastPayload == castPayload else { return }print("Failed to fetch files: \(error)")hasCompletedInitialFetch = falseself.error = "Failed to load files: \(error.localizedDescription)"@@ -275,8 +271,10 @@ class RealSlideshowService: ObservableObject {while hasMore {if verboseFileLogging { print("Fetching files since time: \(sinceTime)") }let result = try await fetchFilesBatch(castPayload: castPayload, sinceTime: sinceTime)+ guard storedCastPayload == castPayload else { return }- await processDiffBatch(result.files, collectionKey: castPayload.collectionKey)+ await processDiffBatch(result.files, castPayload: castPayload)+ guard storedCastPayload == castPayload else { return }await MainActor.run {if result.latestUpdateTime > self.lastUpdateTime {@@ -290,14 +288,13 @@ class RealSlideshowService: ObservableObject {}+ guard storedCastPayload == castPayload else { return }print("Initial diff fetch complete - total files cached: \(await MainActor.run { allFiles.count })")-- await MainActor.run {- startPeriodicDiffPolling()- }+ startPeriodicDiffPolling()}private func fetchFilesBatch(castPayload: CastPayload, sinceTime: Int64) async throws -> (files: [[String: Any]], hasMore: Bool, latestUpdateTime: Int64) {+ guard storedCastPayload == castPayload else { throw CancellationError() }let url = URL(string: "\(baseURL)/cast/diff?sinceTime=\(sinceTime)")!@@ -305,16 +302,13 @@ class RealSlideshowService: ObservableObject {request.setValue(castPayload.castToken, forHTTPHeaderField: "X-Cast-Access-Token")let (data, response) = try await URLSession.shared.data(for: request)+ guard storedCastPayload == castPayload else { throw CancellationError() }guard let httpResponse = response as? HTTPURLResponse else {throw CastError.networkError("Invalid response")}- if let responseString = String(data: data, encoding: .utf8) {-- }-guard httpResponse.statusCode == 200 else {if httpResponse.statusCode == 401 {await handleUnauthorizedError()@@ -331,30 +325,25 @@ class RealSlideshowService: ObservableObject {let hasMore = json["hasMore"] as? Bool ?? falsevar latestUpdateTime = sinceTime- var foundAnyUpdates = falsefor item in diff {if let updateTime = item["updationTime"] as? Int64 {latestUpdateTime = max(latestUpdateTime, updateTime)- foundAnyUpdates = true}}- if !foundAnyUpdates {- latestUpdateTime = sinceTime- }-return (files: diff, hasMore: hasMore, latestUpdateTime: latestUpdateTime)}@MainActor- private func processDiffBatch(_ items: [[String: Any]], collectionKey: String) async {+ private func processDiffBatch(_ items: [[String: Any]], castPayload: CastPayload) async {let wasEmpty = allFiles.isEmptyvar currentFileChanged = falselet originalCurrentFile = currentFileIndex < allFiles.count ? allFiles[currentFileIndex] : nilfor item in items {+ guard storedCastPayload == castPayload else { return }guard let id = item["id"] as? Int else {continue}@@ -370,6 +359,7 @@ class RealSlideshowService: ObservableObject {currentFileWasDeleted = trueTask {+ guard self.storedCastPayload == castPayload else { return }await self.nextSlide()}}@@ -388,7 +378,8 @@ class RealSlideshowService: ObservableObject {}} else {do {- if let file = try await decryptFileMetadata(item: item, collectionKey: collectionKey) {+ if let file = try await decryptFileMetadata(item: item, collectionKey: castPayload.collectionKey) {+ guard storedCastPayload == castPayload else { return }// Cast images and Live Photos, not standalone videos.if file.isVideo && !file.isLivePhoto {if verboseFileLogging { print("Skipping video file: \(file.title) (ID: \(id))") }@@ -418,6 +409,7 @@ class RealSlideshowService: ObservableObject {}}}+ guard storedCastPayload == castPayload else { return }print("File list now contains \(allFiles.count) files")@@ -439,13 +431,15 @@ class RealSlideshowService: ObservableObject {currentSlideIndex = 0totalSlides = allFiles.count- if let payload = storedCastPayload {+ if storedCastPayload != nil {print("Restarting slideshow with \(allFiles.count) files")// Clear before loading to avoid an empty-state flash.error = nilTask {+ guard storedCastPayload == castPayload else { return }await displaySlideAtCurrentIndex()+ guard storedCastPayload == castPayload else { return }await MainActor.run {self.isPlaying = trueself.isPaused = false@@ -463,14 +457,15 @@ class RealSlideshowService: ObservableObject {if currentFileChanged && !allFiles.isEmpty {Task {+ guard storedCastPayload == castPayload else { return }await displaySlideAtCurrentIndex()}}}-+let currentValidFileIDs = Set(allFiles.map { $0.id })Task {- await cleanupExpiredCache(validFileIDs: currentValidFileIDs)+ await cleanupExpiredCache(validFileIDs: currentValidFileIDs, castPayload: castPayload)}}@@ -498,6 +493,7 @@ class RealSlideshowService: ObservableObject {castPayload: payload,file: file)+ guard storedCastPayload == payload else { return }print("Successfully loaded file \(file.id): \(file.title) (\(decryptedData.count) bytes)")@@ -509,6 +505,7 @@ class RealSlideshowService: ObservableObject {startPrefetching()} catch {+ guard storedCastPayload == payload else { return }let file = allFiles[currentFileIndex]print("Failed to load file \(file.id): \(file.title) at index \(currentFileIndex) - \(error)")@@ -518,6 +515,7 @@ class RealSlideshowService: ObservableObject {DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {Task {+ guard self.storedCastPayload == payload else { return }await self.skipToNextSlide()}}@@ -626,7 +624,7 @@ class RealSlideshowService: ObservableObject {}private func skipToNextSlide() async {- guard !allFiles.isEmpty else { return }+ guard !allFiles.isEmpty, let payload = storedCastPayload else { return }currentFileIndex = (currentFileIndex + 1) % allFiles.count@@ -635,7 +633,6 @@ class RealSlideshowService: ObservableObject {while retryCount < maxRetries {do {- guard let payload = storedCastPayload else { return }let file = allFiles[currentFileIndex]print("Attempting to load file \(file.id): \(file.title) at index \(currentFileIndex)")@@ -644,6 +641,7 @@ class RealSlideshowService: ObservableObject {castPayload: payload,file: file)+ guard storedCastPayload == payload else { return }prefetchCache[currentFileIndex] = decryptedDataawait updateCurrentSlide(with: decryptedData, file: file)@@ -663,6 +661,7 @@ class RealSlideshowService: ObservableObject {return} catch {+ guard storedCastPayload == payload else { return }let file = allFiles[currentFileIndex]print("Failed to load file \(file.id): \(file.title) - \(error)")currentFileIndex = (currentFileIndex + 1) % allFiles.count@@ -676,21 +675,22 @@ class RealSlideshowService: ObservableObject {}private func startPrefetching() {+ guard let payload = storedCastPayload else { return }Task {let prefetchCount = min(3, allFiles.count)for i in 1...prefetchCount {+ guard storedCastPayload == payload else { return }let prefetchIndex = (currentFileIndex + i) % allFiles.countif prefetchCache[prefetchIndex] != nil { continue }- guard let payload = storedCastPayload else { continue }-do {let file = allFiles[prefetchIndex]let data = try await downloadAndDecryptFileContent(castPayload: payload,file: file)+ guard storedCastPayload == payload else { return }prefetchCache[prefetchIndex] = dataif prefetchCache.count > 5 {@@ -701,6 +701,7 @@ class RealSlideshowService: ObservableObject {}} catch {+ guard storedCastPayload == payload else { return }// Silently skip problematic files during prefetchingprint("Prefetch failed for file \(prefetchIndex), will try on-demand")continue@@ -790,17 +791,17 @@ class RealSlideshowService: ObservableObject {do {let currentTime = await MainActor.run { lastUpdateTime }let result = try await fetchFilesBatch(castPayload: payload, sinceTime: currentTime)+ guard storedCastPayload == payload else { return }if !result.files.isEmpty {print("Periodic poll found \(result.files.count) changes")- await processDiffBatch(result.files, collectionKey: payload.collectionKey)+ await processDiffBatch(result.files, castPayload: payload)+ guard storedCastPayload == payload else { return }- await MainActor.run {- if result.latestUpdateTime > self.lastUpdateTime {- print("Updating lastUpdateTime: \(self.lastUpdateTime) β \(result.latestUpdateTime)")- self.lastUpdateTime = result.latestUpdateTime- }+ if result.latestUpdateTime > lastUpdateTime {+ print("Updating lastUpdateTime: \(lastUpdateTime) β \(result.latestUpdateTime)")+ lastUpdateTime = result.latestUpdateTime}} else {print("Periodic poll found no changes since \(currentTime)")@@ -841,13 +842,17 @@ class RealSlideshowService: ObservableObject {}private func downloadEncryptedFile(castPayload: CastPayload, fileID: Int) async throws -> Data {- let url = URL(string: "\(castDownloadURL)/?fileID=\(fileID)")!+ guard storedCastPayload == castPayload else { throw CancellationError() }+ let url = baseURL == APIEndpoint.production.absoluteString+ ? URL(string: "\(castDownloadURL)/?fileID=\(fileID)")!+ : URL(string: baseURL)!.appendingPathComponent("cast/files/download/\(fileID)")var request = URLRequest(url: url)request.setValue(castPayload.castToken, forHTTPHeaderField: "X-Cast-Access-Token")let (data, response) = try await URLSession.shared.data(for: request)+ guard storedCastPayload == castPayload else { throw CancellationError() }guard let httpResponse = response as? HTTPURLResponse else {throw CastError.networkError("Invalid response")@@ -895,8 +900,7 @@ class RealSlideshowService: ObservableObject {fileKey: fileKey,decryptionHeader: file.fileDecryptionHeader)--+ guard storedCastPayload == castPayload else { throw CancellationError() }await cacheFileContent(fileID: file.id, data: decryptedData)return decryptedData@@ -1026,7 +1030,8 @@ class RealSlideshowService: ObservableObject {await fileCache.set(fileID, data: data)}- private func cleanupExpiredCache(validFileIDs: Set<Int>) async {+ private func cleanupExpiredCache(validFileIDs: Set<Int>, castPayload: CastPayload) async {+ guard storedCastPayload == castPayload else { return }let stats = await getCacheStats()print("Starting cache cleanup - current cache has \(stats.count) files")@@ -1034,6 +1039,7 @@ class RealSlideshowService: ObservableObject {var removedCount = 0for cachedFileID in cachedFileIDs {+ guard storedCastPayload == castPayload else { return }if !validFileIDs.contains(cachedFileID) {await removeCachedFileContent(fileID: cachedFileID)removedCount += 1@@ -1050,7 +1056,7 @@ class RealSlideshowService: ObservableObject {await fileCache.remove(fileID)}- private func clearCache() async {+ func clearCache() async {await fileCache.clear()}diff --git a/apple/apps/cast/Cast/Views/APIEndpointView.swift b/apple/apps/cast/Cast/Views/APIEndpointView.swiftnew file mode 100644index 0000000000..4de28afcd1--- /dev/null+++ b/apple/apps/cast/Cast/Views/APIEndpointView.swift@@ -0,0 +1,68 @@+import SwiftUI++struct APIEndpointView: View {+ let onSave: () -> Void++ @Environment(\.dismiss) private var dismiss+ @State private var endpoint = APIEndpoint.current.absoluteString+ @State private var error: String?+ @State private var isSaving = false++ var body: some View {+ VStack(spacing: 32) {+ Text("API server")+ .font(.title2.bold())++ Text("Enter your self-hosted API URL.")+ .foregroundStyle(.secondary)++ TextField("https://api.example.com", text: $endpoint)+ .keyboardType(.URL)+ .disableAutocorrection(true)++ if let error {+ Text(error)+ .font(.footnote)+ .foregroundStyle(.red)+ }++ VStack(spacing: 16) {+ Button(action: save) { buttonLabel("Save") }+ .disabled(isSaving)+ if !APIEndpoint.isProduction {+ Button {+ APIEndpoint.reset()+ onSave()+ dismiss()+ } label: { buttonLabel("Use Ente") }+ .disabled(isSaving)+ }+ Button(role: .cancel) { dismiss() } label: { buttonLabel("Cancel") }+ .disabled(isSaving)+ }++ if isSaving { ProgressView() }+ }+ .frame(maxWidth: 720)+ .multilineTextAlignment(.center)+ .interactiveDismissDisabled(isSaving)+ .padding(80)+ }++ private func buttonLabel(_ title: String) -> some View { Text(title).frame(width: 240) }++ private func save() {+ isSaving = true+ error = nil+ Task {+ do {+ try await APIEndpoint.update(endpoint)+ onSave()+ dismiss()+ } catch {+ self.error = error.localizedDescription+ isSaving = false+ }+ }+ }+}