Skip to content

Open source CapCut alternative.

TypeScript

refactor(ios): sync moves on whatever connection the phone has

David Le77e3ac04f596
diff --git a/apps/ios/Donkey/Controllers/CutCloudClient.swift b/apps/ios/Donkey/Controllers/CutCloudClient.swift
index 2845b8c6..631555f7 100644
--- a/apps/ios/Donkey/Controllers/CutCloudClient.swift
+++ b/apps/ios/Donkey/Controllers/CutCloudClient.swift
@@ -6,8 +6,7 @@ import UIKit
/// The phone's HTTP client for the hosted Cut API (/api/cut-cloud/*). The
/// bearer session comes from the keychain, and every request carries the iOS
/// client header — the marker that links this account for the desktop's phone
-/// features. Media requests are stamped with the caller's cellular decision so
-/// an upload started on Wi-Fi never silently continues over cell.
+/// features.
final class CutCloudClient: NSObject {
private let base = AuthBackend.baseURL
@@ -20,16 +19,13 @@ final class CutCloudClient: NSObject {
private func request(
_ method: String,
_ path: String,
- body: [String: Any]? = nil,
- allowCellular: Bool = true
+ body: [String: Any]? = nil
) throws -> URLRequest {
guard let token else { throw CloudSyncError.unauthorized }
var request = URLRequest(url: base.appending(path: path))
request.httpMethod = method
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.setValue("ios", forHTTPHeaderField: "x-donkey-cut-client")
- request.allowsCellularAccess = allowCellular
- request.allowsExpensiveNetworkAccess = allowCellular
if let body {
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONSerialization.data(withJSONObject: body)
@@ -98,22 +94,20 @@ extension CutCloudClient: CloudSyncServicing {
func uploadLibraryMedia(
_ upload: LibraryUpload,
- allowCellular: Bool,
progress: @escaping @Sendable (Double) -> Void
) async throws -> RemoteAsset {
let presign = try await presignLibrary(
fileName: upload.fileName,
mime: upload.mime,
bytes: upload.bytes,
- resume: upload.resume,
- allowCellular: allowCellular
+ resume: upload.resume
)
if presign.done != true {
guard let url = presign.url.flatMap(URL.init(string:)) else { throw CloudSyncError.transport }
- try await putFile(upload.fileURL, to: url, mime: upload.mime, allowCellular: allowCellular, progress: progress)
+ try await putFile(upload.fileURL, to: url, mime: upload.mime, progress: progress)
}
let posterKey: String? = if let poster = upload.poster {
- try? await uploadPoster(poster, besides: presign.fileName, allowCellular: allowCellular)
+ try? await uploadPoster(poster, besides: presign.fileName)
} else {
nil
}
@@ -130,7 +124,7 @@ extension CutCloudClient: CloudSyncServicing {
var body: [String: Any] = ["key": presign.key, "meta": meta]
if let posterKey { body["posterKey"] = posterKey }
let data = try await send(
- try request("POST", "/api/cut-cloud/library/complete", body: body, allowCellular: allowCellular)
+ try request("POST", "/api/cut-cloud/library/complete", body: body)
)
let asset = try decode(AssetResponse.self, from: data)
progress(1)
@@ -141,15 +135,13 @@ extension CutCloudClient: CloudSyncServicing {
fileName: String,
mime: String,
bytes: Int64,
- resume: Bool,
- allowCellular: Bool
+ resume: Bool
) async throws -> PresignResponse {
let data = try await send(
try request(
"POST",
"/api/cut-cloud/library/presign",
- body: ["fileName": fileName, "mime": mime, "bytes": bytes, "resume": resume],
- allowCellular: allowCellular
+ body: ["fileName": fileName, "mime": mime, "bytes": bytes, "resume": resume]
)
)
return try decode(PresignResponse.self, from: data)
@@ -157,18 +149,17 @@ extension CutCloudClient: CloudSyncServicing {
/// The recording's thumbnail goes up beside the movie so the desktop card
/// paints without decoding video. Best-effort: the upload stands without it.
- private func uploadPoster(_ poster: Data, besides fileName: String, allowCellular: Bool) async throws -> String {
+ private func uploadPoster(_ poster: Data, besides fileName: String) async throws -> String {
let posterName = (fileName as NSString).deletingPathExtension + "-poster.jpg"
let presign = try await presignLibrary(
fileName: posterName,
mime: "image/jpeg",
bytes: Int64(poster.count),
- resume: true,
- allowCellular: allowCellular
+ resume: true
)
if presign.done != true {
guard let url = presign.url.flatMap(URL.init(string:)) else { throw CloudSyncError.transport }
- try await putData(poster, to: url, mime: "image/jpeg", allowCellular: allowCellular)
+ try await putData(poster, to: url, mime: "image/jpeg")
}
return presign.key
}
@@ -177,13 +168,12 @@ extension CutCloudClient: CloudSyncServicing {
_ file: URL,
to url: URL,
mime: String,
- allowCellular: Bool,
progress: @escaping @Sendable (Double) -> Void
) async throws {
let response: URLResponse
do {
(_, response) = try await URLSession.shared.upload(
- for: putRequest(url, mime: mime, allowCellular: allowCellular),
+ for: putRequest(url, mime: mime),
fromFile: file,
delegate: UploadProgressDelegate(progress)
)
@@ -195,11 +185,11 @@ extension CutCloudClient: CloudSyncServicing {
}
}
- private func putData(_ data: Data, to url: URL, mime: String, allowCellular: Bool) async throws {
+ private func putData(_ data: Data, to url: URL, mime: String) async throws {
let response: URLResponse
do {
(_, response) = try await URLSession.shared.upload(
- for: putRequest(url, mime: mime, allowCellular: allowCellular),
+ for: putRequest(url, mime: mime),
from: data
)
} catch {
@@ -210,13 +200,11 @@ extension CutCloudClient: CloudSyncServicing {
}
}
- private func putRequest(_ url: URL, mime: String, allowCellular: Bool) -> URLRequest {
+ private func putRequest(_ url: URL, mime: String) -> URLRequest {
var request = URLRequest(url: url)
request.httpMethod = "PUT"
// The presigned URL is signed over this content type.
request.setValue(mime, forHTTPHeaderField: "Content-Type")
- request.allowsCellularAccess = allowCellular
- request.allowsExpensiveNetworkAccess = allowCellular
return request
}
diff --git a/apps/ios/Donkey/DonkeyApp.swift b/apps/ios/Donkey/DonkeyApp.swift
index 6e88c6ce..14119e5d 100644
--- a/apps/ios/Donkey/DonkeyApp.swift
+++ b/apps/ios/Donkey/DonkeyApp.swift
@@ -53,7 +53,6 @@ final class AppWiring {
let sync = SyncEngine(
journal: store,
service: cloud,
- cellularAllowed: { app.syncOverCellular },
signedIn: { auth.isSignedIn },
uploadFor: { recording in
await CutCloudClient.uploadPayload(for: recording, media: media)
@@ -63,7 +62,6 @@ final class AppWiring {
sync.ideas = ideas
media.sync = sync
ideas.onLocalChange = { sync.kick() }
- app.onSyncPolicyChange = { sync.kick() }
self.app = app
self.ideas = ideas
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AppModel.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AppModel.swift
index 8bcaab19..1392f972 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AppModel.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AppModel.swift
@@ -16,20 +16,6 @@ public final class AppModel {
didSet { defaults.set(appearance.rawValue, forKey: Self.appearanceKey) }
}
- /// Media syncs over cellular data too. Off by default: large files wait
- /// for Wi-Fi until the user opts in. Small traffic (notes, links) always
- /// moves.
- public var syncOverCellular: Bool {
- didSet {
- defaults.set(syncOverCellular, forKey: Self.cellularKey)
- if syncOverCellular != oldValue { onSyncPolicyChange?() }
- }
- }
-
- /// Fires when the cellular choice flips so queued uploads re-evaluate.
- /// Wired by the app entry.
- public var onSyncPolicyChange: (() -> Void)?
-
/// A transient confirmation message ("Note saved"), cleared by the UI.
public var toast: String?
@@ -38,13 +24,11 @@ public final class AppModel {
private let defaults: UserDefaults
private static let appearanceKey = "appearancePreference"
- private static let cellularKey = "syncOverCellular"
public init(defaults: UserDefaults = .standard) {
self.defaults = defaults
appearance = defaults.string(forKey: Self.appearanceKey)
.flatMap(AppearancePreference.init(rawValue:)) ?? .system
- syncOverCellular = defaults.bool(forKey: Self.cellularKey)
}
public func show(toast message: String) {
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swift
index 5152b914..167d9532 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swift
@@ -120,11 +120,9 @@ nonisolated public enum CloudSyncError: Error, Equatable {
/// What the app target's CutCloudClient does for the sync engine.
public protocol CloudSyncServicing: AnyObject {
/// Presign → PUT the bytes to R2 → complete. Reports rough progress in
- /// 0...1. `allowCellular` is stamped on the requests so a Wi-Fi upload
- /// never silently continues over cell when the path changes mid-transfer.
+ /// 0...1.
func uploadLibraryMedia(
_ upload: LibraryUpload,
- allowCellular: Bool,
progress: @escaping @Sendable (Double) -> Void
) async throws -> RemoteAsset
func deleteLibraryAsset(id: String) async throws
@@ -197,29 +195,11 @@ public protocol CloudProjectsServicing: AnyObject, Sendable {
// MARK: - Network policy
+/// The connection the sync engine is working over. Whether cellular data may
+/// be spent is the system's call: iOS Settings carries the per-app Cellular
+/// Data switch, and a request it forbids fails on its own.
nonisolated public enum NetworkPath: Equatable, Sendable {
case wifi
case cellular
case offline
}
-
-/// How big a transfer is, as policy sees it. Small-class traffic (notes, link
-/// imports, JSON) moves on any connection; media waits for Wi-Fi unless the
-/// user allows cellular.
-nonisolated public enum TransferClass: Equatable, Sendable {
- case small
- case media
-}
-
-/// The one rule that spends the user's data.
-nonisolated public func transferAllowed(
- _ kind: TransferClass,
- on path: NetworkPath,
- cellularAllowed: Bool
-) -> Bool {
- switch path {
- case .offline: false
- case .wifi: true
- case .cellular: kind == .small || cellularAllowed
- }
-}
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swift
index ad581ae1..7598b2b6 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swift
@@ -4,8 +4,8 @@ import Foundation
// inspiration up, notes both ways, deletes replayed — against a journal the
// store persists, so nothing depends on the app staying open: whatever was
// mid-flight when the app died is picked up from the journal on the next
-// kick. Every byte moves at most once; the policy in CloudSync.swift decides
-// what may move on which network.
+// kick. Every byte moves at most once, and it moves on whatever connection
+// the phone has: iOS Settings owns the per-app cellular switch.
nonisolated public struct SyncTombstone: Equatable, Sendable, Identifiable {
nonisolated public enum Kind: String, Sendable {
@@ -84,7 +84,6 @@ public final class SyncEngine {
private let journal: any SyncJournalStoring
private let service: any CloudSyncServicing
- private let cellularAllowed: () -> Bool
private let signedIn: () -> Bool
/// Reads a recording's upload payload (bytes, dimensions, poster) off the
/// file; the app target implements it with AVFoundation.
@@ -95,13 +94,11 @@ public final class SyncEngine {
public init(
journal: any SyncJournalStoring,
service: any CloudSyncServicing,
- cellularAllowed: @escaping () -> Bool,
signedIn: @escaping () -> Bool,
uploadFor: @escaping (Recording) async -> LibraryUpload?
) {
self.journal = journal
self.service = service
- self.cellularAllowed = cellularAllowed
self.signedIn = signedIn
self.uploadFor = uploadFor
}
@@ -150,18 +147,17 @@ public final class SyncEngine {
}
await replayTombstones()
await syncNotes()
- // Link imports are small payloads: they move on any connection, so
- // they queue ahead of the media gate.
+ // Link imports are small payloads, so they queue ahead of the media.
await uploadPendingInspirationLinks()
- guard allowed(.media) else { return }
+ guard online else { return }
await refreshStorage()
guard !storageFull else { return }
await uploadPendingRecordings()
await uploadPendingInspirationMedia()
}
- private func allowed(_ kind: TransferClass) -> Bool {
- transferAllowed(kind, on: network, cellularAllowed: cellularAllowed())
+ private var online: Bool {
+ network != .offline
}
// MARK: Deletes
@@ -190,7 +186,7 @@ public final class SyncEngine {
// MARK: Notes (two-way, last writer wins)
private func syncNotes() async {
- guard allowed(.small) else { return }
+ guard online else { return }
// Push local edits first so the pull that follows can't overwrite them.
for note in (try? journal.dirtyNotes()) ?? [] {
do {
@@ -268,7 +264,7 @@ public final class SyncEngine {
private func uploadPendingRecordings() async {
for recording in media?.recordings ?? [] {
- guard allowed(.media), !storageFull else { return }
+ guard online, !storageFull else { return }
let remote = try? journal.recordingRemote(recording.id)
guard remote?.assetId == nil, !uploading.contains(recording.id) else { continue }
guard var upload = await uploadFor(recording) else { continue }
@@ -278,10 +274,7 @@ public final class SyncEngine {
uploadStates[recording.id] = .uploading(percent: 0)
defer { uploading.remove(recording.id) }
do {
- let asset = try await service.uploadLibraryMedia(
- upload,
- allowCellular: cellularAllowed()
- ) { [weak self] fraction in
+ let asset = try await service.uploadLibraryMedia(upload) { [weak self] fraction in
Task { @MainActor [weak self] in
self?.setUploadProgress(recording.id, fraction)
}
@@ -326,7 +319,7 @@ public final class SyncEngine {
private func uploadPendingInspirationLinks() async {
for item in ideas?.inspiration ?? [] {
guard case .link(let url) = item.kind else { continue }
- guard allowed(.small) else { continue }
+ guard online else { continue }
guard ((try? journal.isInspirationLinkSynced(item.id)) ?? true) == false else { continue }
do {
try await service.importInspirationLink(url)
@@ -342,7 +335,7 @@ public final class SyncEngine {
private func uploadPendingInspirationMedia() async {
for item in ideas?.inspiration ?? [] {
guard case .media(let fileName, let isVideo) = item.kind else { continue }
- guard allowed(.media), !storageFull else { continue }
+ guard online, !storageFull else { continue }
guard ((try? journal.inspirationRemoteAssetId(item.id)) ?? nil) == nil else { continue }
guard let fileURL = ideas?.mediaURL(fileName: fileName),
let bytes = fileSize(fileURL) else { continue }
@@ -358,11 +351,7 @@ public final class SyncEngine {
resume: true
)
do {
- let asset = try await service.uploadLibraryMedia(
- upload,
- allowCellular: cellularAllowed(),
- progress: { _ in }
- )
+ let asset = try await service.uploadLibraryMedia(upload, progress: { _ in })
try? journal.markInspirationMediaSynced(item.id, remoteAssetId: asset.id)
storageFull = false
} catch CloudSyncError.storageFull {
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/Components.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/Components.swift
index ae9ec27b..e6f59f6e 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/Components.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/Components.swift
@@ -39,7 +39,6 @@ struct AvatarMenu: View {
Text("Dark").tag(AppearancePreference.dark)
}
.pickerStyle(.menu)
- Toggle("Sync over Cellular", systemImage: "antenna.radiowaves.left.and.right", isOn: $app.syncOverCellular)
Divider()
Button("Log Out", systemImage: "rectangle.portrait.and.arrow.right", role: .destructive) {
Task { await auth.signOut() }
diff --git a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift
index 61fba987..f14c2231 100644
--- a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift
+++ b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift
@@ -114,25 +114,6 @@ import Testing
}
}
-@Suite struct SyncPolicyTests {
- @Test func wifiMovesEverything() {
- #expect(transferAllowed(.media, on: .wifi, cellularAllowed: false))
- #expect(transferAllowed(.small, on: .wifi, cellularAllowed: false))
- }
-
- @Test func cellularHoldsMediaUntilAllowed() {
- #expect(!transferAllowed(.media, on: .cellular, cellularAllowed: false))
- #expect(transferAllowed(.media, on: .cellular, cellularAllowed: true))
- // Notes and links are small; they always move.
- #expect(transferAllowed(.small, on: .cellular, cellularAllowed: false))
- }
-
- @Test func offlineMovesNothing() {
- #expect(!transferAllowed(.small, on: .offline, cellularAllowed: true))
- #expect(!transferAllowed(.media, on: .offline, cellularAllowed: true))
- }
-}
-
@MainActor
@Suite struct SyncEngineTests {
final class FakeCloud: CloudSyncServicing {
@@ -149,7 +130,6 @@ import Testing
func uploadLibraryMedia(
_ upload: LibraryUpload,
- allowCellular: Bool,
progress: @escaping @Sendable (Double) -> Void
) async throws -> RemoteAsset {
uploads.append(upload.fileName)
@@ -190,7 +170,6 @@ import Testing
let engine = SyncEngine(
journal: store,
service: cloud,
- cellularAllowed: { false },
signedIn: { true },
uploadFor: { recording in
LibraryUpload(
@@ -338,17 +317,31 @@ import Testing
#expect(rig.cloud.links.count == 1)
}
- @Test func cellularHoldsMediaButMovesNotes() async throws {
+ @Test func cellularMovesEverything() async throws {
+ // iOS Settings owns the cellular switch, so the engine treats a
+ // cellular path like any other connection.
let rig = try makeRig()
rig.engine.network = .cellular
- _ = try ingestClip(rig)
+ let recording = try ingestClip(rig)
rig.ideas.openEditor()
rig.ideas.draft?.body = "typed on the train"
let note = rig.ideas.saveDraft()!
await rig.engine.run()
- #expect(rig.cloud.uploads.isEmpty)
+ #expect(rig.cloud.uploads == [recording.fileName])
#expect(rig.cloud.notes[note.id] != nil)
}
+
+ @Test func offlineMovesNothing() async throws {
+ let rig = try makeRig()
+ rig.engine.network = .offline
+ _ = try ingestClip(rig)
+ rig.ideas.openEditor()
+ rig.ideas.draft?.body = "typed in a tunnel"
+ let note = rig.ideas.saveDraft()!
+ await rig.engine.run()
+ #expect(rig.cloud.uploads.isEmpty)
+ #expect(rig.cloud.notes[note.id] == nil)
+ }
}
@Suite struct DurationTests {
diff --git a/docs/guides/ios-app.md b/docs/guides/ios-app.md
index a9aa4c60..643c002c 100644
--- a/docs/guides/ios-app.md
+++ b/docs/guides/ios-app.md
@@ -14,11 +14,10 @@ kept in the app's SwiftData store, so nothing depends on the app staying open
— whatever was mid-flight when the app died is picked up on the next launch,
foreground, network change, or edit.
-**The one rule on data:** a transfer moves when the network is Wi-Fi, or the
-user turned on "Sync over Cellular" (avatar menu), or the payload is small
-(notes, link imports, JSON). Media otherwise waits for Wi-Fi, and requests are
-stamped with that decision so an upload started on Wi-Fi never quietly
-continues over cell.
+**The one rule on data:** a transfer moves whenever the phone is online. Who
+gets to spend cellular data is the system's call — iOS Settings carries the
+per-app Cellular Data switch, and a request it forbids fails on its own — so
+the app keeps no network preference of its own.
Every byte moves at most once. Uploads go straight to storage on presigned
URLs; an interrupted upload re-presigns under the name it already claimed, and