iOS Share Extension: pick the destination inside the share sheet
SwiftUI folder picker in the extension (WebDAV PROPFIND), account shared via a Keychain group, upload on a background session that outlives the extension and is finished by the app. The inbox + notification hand-off remains as the fallback (no account / 'choose later'). Shared code moves to ios/Shared. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
525504bc47
commit
afc9b90963
@@ -30,7 +30,7 @@ import UserNotifications
|
||||
handleEventsForBackgroundURLSession identifier: String,
|
||||
completionHandler: @escaping () -> Void
|
||||
) {
|
||||
if identifier == TransferManager.sessionIdentifier {
|
||||
if identifier == TransferManager.sessionIdentifier || identifier == ShareUpload.sessionIdentifier {
|
||||
TransferManager.shared.backgroundCompletionHandler = completionHandler
|
||||
} else {
|
||||
super.application(
|
||||
|
||||
@@ -57,6 +57,8 @@
|
||||
<true/>
|
||||
<key>LSSupportsOpeningDocumentsInPlace</key>
|
||||
<true/>
|
||||
<key>NooKeychainAccessGroup</key>
|
||||
<string>$(AppIdentifierPrefix)dev.ayushya.noo.shared</string>
|
||||
<key>NSFaceIDUsageDescription</key>
|
||||
<string>Noo uses Face ID to unlock the app and to protect hidden files.</string>
|
||||
<key>NSPhotoLibraryUsageDescription</key>
|
||||
|
||||
@@ -75,6 +75,35 @@ enum NativeServices {
|
||||
}
|
||||
TransferManager.shared.reconnect()
|
||||
registerShare(messenger: messenger)
|
||||
registerShareAccount(messenger: messenger)
|
||||
}
|
||||
|
||||
// MARK: - Account for the Share Extension
|
||||
|
||||
/// `share_account`: Dart tells native which account is active so the Share
|
||||
/// Extension - a separate process with no Flutter engine - can list folders
|
||||
/// and upload as it. Stored in the shared Keychain group.
|
||||
private static func registerShareAccount(messenger: FlutterBinaryMessenger) {
|
||||
FlutterMethodChannel(name: "dev.ayushya.noo/share_account", binaryMessenger: messenger)
|
||||
.setMethodCallHandler { call, result in
|
||||
switch call.method {
|
||||
case "setAccount":
|
||||
handle(call, result) { args in
|
||||
try SharedAccountStore.save(
|
||||
SharedAccount(
|
||||
serverUrl: try string(args, "serverUrl"),
|
||||
username: try string(args, "username"),
|
||||
authHeader: try string(args, "authHeader"),
|
||||
displayName: (args["displayName"] as? String) ?? ""
|
||||
))
|
||||
}
|
||||
case "clearAccount":
|
||||
SharedAccountStore.clear()
|
||||
result(nil)
|
||||
default:
|
||||
result(FlutterMethodNotImplemented)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Share Extension inbox
|
||||
|
||||
@@ -1,43 +1,11 @@
|
||||
import Foundation
|
||||
import UserNotifications
|
||||
|
||||
/// What a background upload/download task is, stored in the task's
|
||||
/// `taskDescription` so it's still known if the app was relaunched by the
|
||||
/// system to deliver the result.
|
||||
struct TransferTaskInfo: Codable {
|
||||
enum Kind: String, Codable { case upload, download }
|
||||
|
||||
let kind: Kind
|
||||
let batch: String
|
||||
let name: String
|
||||
let remoteFolder: String?
|
||||
let stagedPath: String?
|
||||
}
|
||||
|
||||
/// Running totals for one "upload these 3 files" / "download these 2 files"
|
||||
/// request, persisted so the one summary notification (and the Dart-side
|
||||
/// "folder changed" event) fires exactly once, on the last file, even across
|
||||
/// an app relaunch.
|
||||
struct TransferBatch: Codable {
|
||||
let kind: TransferTaskInfo.Kind
|
||||
let remoteFolder: String?
|
||||
let total: Int
|
||||
var succeeded: Int
|
||||
var failed: Int
|
||||
|
||||
var finished: Int { succeeded + failed }
|
||||
}
|
||||
|
||||
struct UploadFile {
|
||||
let uri: String
|
||||
let name: String
|
||||
}
|
||||
|
||||
struct TransferError: LocalizedError {
|
||||
let message: String
|
||||
var errorDescription: String? { message }
|
||||
}
|
||||
|
||||
/// Uploads and downloads on a background `URLSession`, so a transfer keeps
|
||||
/// going - and finishes - after the app is suspended or closed. The iOS
|
||||
/// counterpart of Android's `ShareUploadService`/`DownloadService`
|
||||
@@ -61,9 +29,6 @@ final class TransferManager: NSObject {
|
||||
/// session has delivered every pending event.
|
||||
var backgroundCompletionHandler: (() -> Void)?
|
||||
|
||||
private let defaults = UserDefaults.standard
|
||||
private let lock = NSLock()
|
||||
|
||||
private lazy var session: URLSession = {
|
||||
let config = URLSessionConfiguration.background(withIdentifier: Self.sessionIdentifier)
|
||||
config.sessionSendsLaunchEvents = true
|
||||
@@ -72,10 +37,17 @@ final class TransferManager: NSObject {
|
||||
return URLSession(configuration: config, delegate: self, delegateQueue: nil)
|
||||
}()
|
||||
|
||||
/// Touch the session at launch so a system relaunch for finished
|
||||
/// The session the Share Extension's uploads run on (see `ShareUpload`).
|
||||
/// The extension is gone by the time they finish, so the app recreates it -
|
||||
/// same identifier and shared container - to receive the results.
|
||||
private lazy var shareSession = URLSession(
|
||||
configuration: ShareUpload.configuration(), delegate: self, delegateQueue: nil)
|
||||
|
||||
/// Touch both sessions at launch so a system relaunch for finished
|
||||
/// background transfers reconnects to them.
|
||||
func reconnect() {
|
||||
_ = session
|
||||
_ = shareSession
|
||||
}
|
||||
|
||||
// MARK: - Starting transfers
|
||||
@@ -130,7 +102,7 @@ final class TransferManager: NSObject {
|
||||
)
|
||||
tasks.append(task)
|
||||
}
|
||||
saveBatch(
|
||||
TransferBatchStore.save(
|
||||
TransferBatch(kind: .upload, remoteFolder: remoteFolder, total: tasks.count, succeeded: 0, failed: 0),
|
||||
id: batch
|
||||
)
|
||||
@@ -158,7 +130,7 @@ final class TransferManager: NSObject {
|
||||
)
|
||||
tasks.append(task)
|
||||
}
|
||||
saveBatch(
|
||||
TransferBatchStore.save(
|
||||
TransferBatch(kind: .download, remoteFolder: nil, total: tasks.count, succeeded: 0, failed: 0),
|
||||
id: batch
|
||||
)
|
||||
@@ -195,30 +167,9 @@ final class TransferManager: NSObject {
|
||||
.flatMap { try? JSONDecoder().decode(TransferTaskInfo.self, from: $0) }
|
||||
}
|
||||
|
||||
private func key(_ id: String) -> String { "transfer.batch.\(id)" }
|
||||
|
||||
private func saveBatch(_ batch: TransferBatch, id: String) {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
if let data = try? JSONEncoder().encode(batch) { defaults.set(data, forKey: key(id)) }
|
||||
}
|
||||
|
||||
/// Counts one file's outcome; fires the batch summary when it was the last.
|
||||
private func record(_ info: TransferTaskInfo, success: Bool) {
|
||||
lock.lock()
|
||||
let storageKey = key(info.batch)
|
||||
var batch =
|
||||
(defaults.data(forKey: storageKey).flatMap { try? JSONDecoder().decode(TransferBatch.self, from: $0) })
|
||||
?? TransferBatch(kind: info.kind, remoteFolder: info.remoteFolder, total: 1, succeeded: 0, failed: 0)
|
||||
if success { batch.succeeded += 1 } else { batch.failed += 1 }
|
||||
let done = batch.finished >= batch.total
|
||||
if done {
|
||||
defaults.removeObject(forKey: storageKey)
|
||||
} else if let data = try? JSONEncoder().encode(batch) {
|
||||
defaults.set(data, forKey: storageKey)
|
||||
}
|
||||
lock.unlock()
|
||||
if done { finish(batch) }
|
||||
if let batch = TransferBatchStore.record(info, success: success) { finish(batch) }
|
||||
}
|
||||
|
||||
private func finish(_ batch: TransferBatch) {
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
/// URL building for a Nextcloud account's WebDAV files root. Pure functions
|
||||
/// (no networking), so they're unit-tested in `RunnerTests`.
|
||||
enum WebDAV {
|
||||
/// `urlPathAllowed` minus "/", so a file name containing a slash-like
|
||||
/// character can't introduce an extra path segment.
|
||||
private static let segmentAllowed: CharacterSet = {
|
||||
var set = CharacterSet.urlPathAllowed
|
||||
set.remove(charactersIn: "/")
|
||||
return set
|
||||
}()
|
||||
|
||||
static func encodeSegment(_ segment: String) -> String {
|
||||
segment.addingPercentEncoding(withAllowedCharacters: segmentAllowed) ?? segment
|
||||
}
|
||||
|
||||
/// `<server>/remote.php/dav/files/<user>/<remotePath>` - [remotePath] is
|
||||
/// relative to the user's root, with or without a leading slash. A server
|
||||
/// installed under a sub-path (`https://host/nextcloud`) keeps it.
|
||||
static func fileURL(serverUrl: String, username: String, remotePath: String) -> URL? {
|
||||
var base = serverUrl
|
||||
while base.hasSuffix("/") { base.removeLast() }
|
||||
let segments = remotePath.split(separator: "/").map { encodeSegment(String($0)) }
|
||||
var url = base + "/remote.php/dav/files/" + encodeSegment(username)
|
||||
if !segments.isEmpty { url += "/" + segments.joined(separator: "/") }
|
||||
return URL(string: url)
|
||||
}
|
||||
|
||||
/// `folder` + `name` with exactly one slash between them.
|
||||
static func join(_ folder: String, _ name: String) -> String {
|
||||
folder.hasSuffix("/") ? folder + name : folder + "/" + name
|
||||
}
|
||||
}
|
||||
|
||||
enum LocalFiles {
|
||||
/// A URL in [directory] for [name] that doesn't exist yet: "a.txt", then
|
||||
/// "a (1).txt", "a (2).txt"... - so a second download of the same file
|
||||
/// never overwrites the first.
|
||||
static func uniqueURL(in directory: URL, name: String, fileManager: FileManager = .default) -> URL {
|
||||
let candidate = directory.appendingPathComponent(name)
|
||||
if !fileManager.fileExists(atPath: candidate.path) { return candidate }
|
||||
let ext = (name as NSString).pathExtension
|
||||
let stem = (name as NSString).deletingPathExtension
|
||||
var index = 1
|
||||
while true {
|
||||
let numbered = ext.isEmpty ? "\(stem) (\(index))" : "\(stem) (\(index)).\(ext)"
|
||||
let url = directory.appendingPathComponent(numbered)
|
||||
if !fileManager.fileExists(atPath: url.path) { return url }
|
||||
index += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,5 +6,9 @@
|
||||
<array>
|
||||
<string>group.dev.ayushya.noo</string>
|
||||
</array>
|
||||
<key>keychain-access-groups</key>
|
||||
<array>
|
||||
<string>$(AppIdentifierPrefix)dev.ayushya.noo.shared</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
Reference in New Issue
Block a user