Skip to content

Open source CapCut alternative.

TypeScript

feat(ios): the phone mirrors a delete made at the desk

David Leebf4b4f9144d
diff --git a/apps/ios/Donkey/Controllers/CutCloudClient.swift b/apps/ios/Donkey/Controllers/CutCloudClient.swift
index e154a01e..b06ef7a5 100644
--- a/apps/ios/Donkey/Controllers/CutCloudClient.swift
+++ b/apps/ios/Donkey/Controllers/CutCloudClient.swift
@@ -19,10 +19,12 @@ final class CutCloudClient: NSObject {
private func request(
_ method: String,
_ path: String,
+ query: [URLQueryItem] = [],
body: [String: Any]? = nil
) throws -> URLRequest {
guard let token else { throw CloudSyncError.unauthorized }
- var request = URLRequest(url: base.appending(path: path))
+ let url = base.appending(path: path)
+ var request = URLRequest(url: query.isEmpty ? url : url.appending(queryItems: query))
request.httpMethod = method
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.setValue("ios", forHTTPHeaderField: "x-donkey-cut-client")
@@ -212,6 +214,29 @@ extension CutCloudClient: CloudSyncServicing {
_ = try await send(try request("DELETE", "/api/cut-cloud/library/\(id)"))
}
+ func fetchLibrary() async throws -> RemoteLibrary {
+ struct LibraryResponse: Decodable {
+ struct Asset: Decodable { var id: String }
+ var assets: [Asset]
+ var deletedAssetIds: [String]?
+ }
+ // `deleted=1` asks for the tombstoned ids: the phone mirrors the
+ // shelf onto the Camera Roll, so a delete made on the desktop has to
+ // reach it. No other client wants them.
+ let data = try await send(
+ try request(
+ "GET",
+ "/api/cut-cloud/library",
+ query: [URLQueryItem(name: "deleted", value: "1")]
+ )
+ )
+ let response = try decode(LibraryResponse.self, from: data)
+ return RemoteLibrary(
+ assetIds: Set(response.assets.map(\.id)),
+ deletedIds: Set(response.deletedAssetIds ?? [])
+ )
+ }
+
func importInspirationLink(_ url: URL) async throws -> String {
struct QueuedJob: Decodable { var jobId: String }
let data = try await send(
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swift
index abe83525..170c647d 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swift
@@ -67,6 +67,19 @@ nonisolated public struct LibraryUpload: Sendable {
}
}
+/// The cloud shelf as the phone needs to see it: the ids it holds, and the
+/// ids someone deleted. An id in neither left by some other hand — the storage
+/// sweep reclaiming a lapsed account — which is not a delete the phone mirrors.
+nonisolated public struct RemoteLibrary: Equatable, Sendable {
+ public var assetIds: Set<String>
+ public var deletedIds: Set<String>
+
+ public init(assetIds: Set<String>, deletedIds: Set<String>) {
+ self.assetIds = assetIds
+ self.deletedIds = deletedIds
+ }
+}
+
nonisolated public struct RemoteAsset: Equatable, Sendable {
public var id: String
public var fileName: String
@@ -185,6 +198,9 @@ public protocol CloudSyncServicing: AnyObject {
progress: @escaping @Sendable (Double) -> Void
) async throws -> RemoteAsset
func deleteLibraryAsset(id: String) async throws
+ /// The shelf's asset ids and its tombstones, for the pass that mirrors
+ /// deletes made at the desk back onto this phone.
+ func fetchLibrary() async throws -> RemoteLibrary
/// Queue a cloud-side import of an inspiration link (the render worker
/// fetches the media into the Inspiration folder). Returns the job id the
/// phone follows to bring the media down.
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift
index 9c22d368..e32599ed 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift
@@ -450,11 +450,44 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring, SyncJournalStori
return true
}
+ /// The cloud copy is gone with no tombstone behind it, so the item keeps
+ /// its files and stops counting as synced.
+ public func clearInspirationRemote(_ id: UUID) throws {
+ let descriptor = FetchDescriptor<InspirationRecord>(predicate: #Predicate { $0.id == id })
+ guard let record = try context.fetch(descriptor).first else { return }
+ record.remoteAssetId = nil
+ try context.save()
+ }
+
+ /// Drop an item the cloud deleted. The twin of deleteInspiration without
+ /// the tombstone: the delete came down, so nothing goes back up.
+ public func removeInspirationFromCloudDelete(id: UUID) throws {
+ let descriptor = FetchDescriptor<InspirationRecord>(predicate: #Predicate { $0.id == id })
+ guard let record = try context.fetch(descriptor).first else { return }
+ for fileName in [record.mediaFileName, record.fetchedFileName].compactMap({ $0 }) {
+ try? FileManager.default.removeItem(at: mediaDirectory.appending(path: fileName))
+ }
+ context.delete(record)
+ try context.save()
+ }
+
public func inspirationRemoteAssetId(_ id: UUID) throws -> String? {
let descriptor = FetchDescriptor<InspirationRecord>(predicate: #Predicate { $0.id == id })
return try context.fetch(descriptor).first?.remoteAssetId
}
+ /// Drop a recording the cloud deleted. The twin of deleteRecording without
+ /// the tombstone: the delete came down, so nothing goes back up.
+ public func removeRecordingFromCloudDelete(id: UUID) throws {
+ let descriptor = FetchDescriptor<RecordingRecord>(predicate: #Predicate { $0.id == id })
+ guard let record = try context.fetch(descriptor).first else { return }
+ for fileName in [record.fileName, record.thumbnailFileName].compactMap({ $0 }) {
+ try? FileManager.default.removeItem(at: recordingsDirectory.appending(path: fileName))
+ }
+ context.delete(record)
+ try context.save()
+ }
+
public func isInspirationLinkSynced(_ id: UUID) throws -> Bool {
let descriptor = FetchDescriptor<InspirationRecord>(predicate: #Predicate { $0.id == id })
return try context.fetch(descriptor).first?.linkSyncedAt != nil
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/MediaModel.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/MediaModel.swift
index 098469bd..bfd65282 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/MediaModel.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/MediaModel.swift
@@ -44,6 +44,12 @@ public final class MediaModel {
public init(store: any RecordingStoring) {
self.store = store
+ reloadFromStore()
+ }
+
+ /// Re-read what the store holds — how a delete that came down from the
+ /// cloud lands on screen.
+ public func reloadFromStore() {
recordings = (try? store.loadRecordings()) ?? []
}
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swift
index a66fba7e..70ab15b3 100644
--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swift
+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swift
@@ -65,9 +65,17 @@ public protocol SyncJournalStoring: AnyObject {
/// fresh cloud copy down with it.
@discardableResult
func setRecordingRemote(_ id: UUID, assetId: String?, claimedFileName: String?) throws -> Bool
+ /// Remove a recording the cloud deleted, movie and thumbnail with it. No
+ /// tombstone: the delete came down.
+ func removeRecordingFromCloudDelete(id: UUID) throws
// Inspiration
func inspirationRemoteAssetId(_ id: UUID) throws -> String?
+ /// Remove an inspiration item the cloud deleted, its files with it.
+ func removeInspirationFromCloudDelete(id: UUID) throws
+ /// Forget an item's cloud copy: the asset left without a tombstone, so the
+ /// item goes back to being unsynced.
+ func clearInspirationRemote(_ id: UUID) throws
func isInspirationLinkSynced(_ id: UUID) throws -> Bool
func markInspirationMediaSynced(_ id: UUID, remoteAssetId: String) throws
/// A link handed to the cloud worker: the job that is fetching it.
@@ -219,6 +227,7 @@ public final class SyncEngine {
// Link imports are small payloads, so they queue ahead of the media.
await syncInspirationLinks()
guard online else { return }
+ await syncLibrary()
await refreshStorage()
guard !storageFull else { return }
await uploadPendingRecordings()
@@ -295,6 +304,58 @@ public final class SyncEngine {
}
}
+ // MARK: The cloud shelf, mirrored down
+
+ /// The other half of a delete: what left the shelf at the desk leaves this
+ /// phone too. The listing carries every asset the shelf holds and every one
+ /// someone deleted, so a synced clip named among the tombstones goes here,
+ /// files and all.
+ ///
+ /// An id in neither set left by some other hand — the storage sweep
+ /// reclaiming a lapsed account. Nothing is deleted for that: the phone
+ /// forgets the cloud copy instead, so the clip reads as on-device again and
+ /// goes back up once there is room.
+ private func syncLibrary() async {
+ // The local side is read before the listing is asked for, so a clip
+ // that finishes uploading meanwhile is never judged by a listing that
+ // predates it.
+ let recordings: [(id: UUID, assetId: String)] = (media?.recordings ?? []).compactMap {
+ recording in
+ ((try? journal.recordingRemote(recording.id))?.assetId)
+ .map { (recording.id, $0) }
+ }
+ let inspiration: [(id: UUID, assetId: String)] = (ideas?.inspiration ?? []).compactMap {
+ item in
+ ((try? journal.inspirationRemoteAssetId(item.id)) ?? nil)
+ .map { (item.id, $0) }
+ }
+ guard !recordings.isEmpty || !inspiration.isEmpty else { return }
+ guard let shelf = try? await service.fetchLibrary() else { return }
+ var recordingsChanged = false
+ for (id, assetId) in recordings where !shelf.assetIds.contains(assetId) {
+ uploadStates[id] = nil
+ syncedIds.remove(id)
+ checkedIds.remove(id)
+ if shelf.deletedIds.contains(assetId) {
+ try? journal.removeRecordingFromCloudDelete(id: id)
+ recordingsChanged = true
+ } else {
+ _ = try? journal.setRecordingRemote(id, assetId: nil, claimedFileName: nil)
+ }
+ }
+ var inspirationChanged = false
+ for (id, assetId) in inspiration where !shelf.assetIds.contains(assetId) {
+ if shelf.deletedIds.contains(assetId) {
+ try? journal.removeInspirationFromCloudDelete(id: id)
+ } else {
+ try? journal.clearInspirationRemote(id)
+ }
+ inspirationChanged = true
+ }
+ if recordingsChanged { media?.reloadFromStore() }
+ if inspirationChanged { ideas?.reloadFromStore() }
+ }
+
// MARK: Notes (two-way, last writer wins)
private func syncNotes() async {
diff --git a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift
index e6cdcd67..c3cfba2f 100644
--- a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift
+++ b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift
@@ -131,6 +131,10 @@ import Testing
var notes: [UUID: RemoteNote] = [:]
var uploads: [String] = []
var deletedAssets: [String] = []
+ /// The shelf itself: what an upload or an import put there, and the
+ /// tombstones deletes leave — the same two lists the API answers with.
+ var libraryAssets: Set<String> = []
+ var deletedLibraryIds: Set<String> = []
var deletedNotes: [UUID] = []
var links: [URL] = []
var polled: [String] = []
@@ -156,10 +160,21 @@ import Testing
) async throws -> RemoteAsset {
uploads.append(upload.fileName)
onUpload?()
- return try uploadResult.get()
+ let asset = try uploadResult.get()
+ libraryAssets.insert(asset.id)
+ deletedLibraryIds.remove(asset.id)
+ return asset
}
- func deleteLibraryAsset(id: String) async throws { deletedAssets.append(id) }
+ func deleteLibraryAsset(id: String) async throws {
+ deletedAssets.append(id)
+ libraryAssets.remove(id)
+ deletedLibraryIds.insert(id)
+ }
+
+ func fetchLibrary() async throws -> RemoteLibrary {
+ RemoteLibrary(assetIds: libraryAssets, deletedIds: deletedLibraryIds)
+ }
func importInspirationLink(_ url: URL) async throws -> String {
links.append(url)
@@ -168,6 +183,7 @@ import Testing
func importedLink(jobId: String) async throws -> JobOutcome<ImportedLink> {
polled.append(jobId)
+ if case .done(let link) = imported { libraryAssets.insert(link.assetId) }
return imported
}
@@ -312,6 +328,47 @@ import Testing
#expect(try rig.store.tombstones().isEmpty)
}
+ @Test func cloudDeleteTakesTheClipOffThePhone() async throws {
+ let rig = try makeRig()
+ let recording = try ingestClip(rig)
+ let movie = rig.media.movieURL(for: recording)
+ await rig.engine.run()
+ // Deleted at the desk: the shelf tombstones the asset.
+ try await rig.cloud.deleteLibraryAsset(id: "asset-1")
+ rig.cloud.deletedAssets.removeAll()
+ await rig.engine.run()
+ #expect(rig.media.recordings.isEmpty)
+ #expect(!FileManager.default.fileExists(atPath: movie.localPath))
+ // The delete came down, so nothing goes back up for it.
+ #expect(try rig.store.tombstones().isEmpty)
+ #expect(rig.cloud.deletedAssets.isEmpty)
+ #expect(rig.cloud.uploads.count == 1)
+ }
+
+ @Test func anAssetThatVanishedGoesBackUpInsteadOfLeaving() async throws {
+ let rig = try makeRig()
+ let recording = try ingestClip(rig)
+ await rig.engine.run()
+ // The storage sweep collected it: gone from the shelf with no
+ // tombstone, which is not a delete anyone made.
+ rig.cloud.libraryAssets.removeAll()
+ await rig.engine.run()
+ #expect(rig.media.recordings.map(\.id) == [recording.id])
+ // The same pass that noticed puts the clip back on the shelf.
+ #expect(rig.cloud.uploads.count == 2)
+ #expect(rig.engine.state(for: recording) == .synced)
+ }
+
+ @Test func cloudDeleteTakesTheInspirationItemToo() async throws {
+ let rig = try makeRig()
+ rig.ideas.addInspiration(mediaData: Data(repeating: 3, count: 64), isVideo: false)
+ await rig.engine.run()
+ try await rig.cloud.deleteLibraryAsset(id: "asset-1")
+ await rig.engine.run()
+ #expect(rig.ideas.inspiration.isEmpty)
+ #expect(try rig.store.tombstones().isEmpty)
+ }
+
@Test func localNotePushesAndRemoteNewerWins() async throws {
let rig = try makeRig()
rig.ideas.openEditor()
diff --git a/docs/guides/ios-app.md b/docs/guides/ios-app.md
index 5be573dd..648b27c1 100644
--- a/docs/guides/ios-app.md
+++ b/docs/guides/ios-app.md
@@ -32,8 +32,15 @@ with tombstones so a delete made offline on either side still lands on the
other. The folders notes file into travel with them, under ids whichever
device made them chose; a folder carries no tombstone, so a folder the cloud
listing no longer names was deleted elsewhere and its notes come back to the
-top level. Deleting a synced recording on the phone deletes the cloud copy
-too.
+top level.
+
+Deletes on the shelf run both ways. A synced recording deleted on the phone
+takes the cloud copy with it, and a clip deleted at the desk — from the Camera
+Roll or the Library — leaves a tombstone the phone reads on its next pass and
+deletes the local movie for. What the shelf simply stops listing is a different
+thing: an asset the storage sweep reclaimed carries no tombstone, so the phone
+keeps the clip it shot, forgets the cloud copy, and sends it back up once there
+is room.
Notes are written at the desk as well as here, so the phone pulls on a clock
of its own while it is on screen, and pull to refresh runs the same pass at