Files
ios/Action Assistant/ActionViewController.swift
Marino Faggiana 72fd5b2f8a feat: harden experimental PhotoKit background uploads (#4343)
* fix: stop background uploads on database schema mismatch

Validate the Realm schema version before opening the database and fail background upload jobs when the database is unavailable.

Signed-off-by: Marino Faggiana <[email protected]>

* fix: require manual retry for background upload auth failures

Avoid falling back to the Camera Roll when selected albums are unavailable and document the background upload extension workflow.

Signed-off-by: Marino Faggiana <[email protected]>

* fix: suspend background uploads after repeated failures

Limit each upload to three attempts and pause an account after consecutive asset failures. Resume suspended queues through explicit user actions and surface the blocking error in Auto Upload status.

Signed-off-by: Marino Faggiana <[email protected]>

* perf: bound auto-upload asset discovery memory

Lazily merge sorted PhotoKit results and scope duplicate checks to active or relevant uploads.

Signed-off-by: Marino Faggiana <[email protected]>

* feat: add experimental background upload opt-in

Limit the PhotoKit extension to Debug and TestFlight builds on Nextcloud 35 or later.

Signed-off-by: Marino Faggiana <[email protected]>

* fix: clarify PhotoKit HEIC upload behavior

Signed-off-by: Marino Faggiana <[email protected]>

* fix: improve background upload diagnostics

Log processing stages and detailed errors, and promote extension diagnostics to notice level.

Signed-off-by: Marino Faggiana <[email protected]>

* fix: mark background PhotoKit uploads

Add the X-NC-PhotoKit-Upload header to background upload requests.

Signed-off-by: Marino Faggiana <[email protected]>

* Clean up background upload metadata when PhotoKit assets are missing

Signed-off-by: Marino Faggiana <[email protected]>

* Log

Signed-off-by: Marino Faggiana <[email protected]>

* Log

Signed-off-by: Marino Faggiana <[email protected]>

* feat: add log file browser to advanced settings

List, preview, and share active and rotated log files.
Limit upload diagnostics to failures and redact sensitive response headers.
Update NextcloudKit and Realm dependencies.

Signed-off-by: Marino Faggiana <[email protected]>

* feat: document Apache setup for PhotoKit uploads

Mark the background upload extension as experimental and show the required Apache rewrite rules.

Update NextcloudKit and bump the project build number.

Signed-off-by: Marino Faggiana <[email protected]>

---------

Signed-off-by: Marino Faggiana <[email protected]>
2026-09-29 08:18:02 +02:00

160 lines
6.2 KiB
Swift

// SPDX-FileCopyrightText: Nextcloud GmbH
// SPDX-FileCopyrightText: 2026 Marino Faggiana
// SPDX-License-Identifier: GPL-3.0-or-later
import UIKit
import NextcloudKit
import UniformTypeIdentifiers
final class ActionViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let groupIdentifier = NCBrandOptions.shared.capabilitiesGroup
let storedLogLevel = UserDefaults(suiteName: groupIdentifier)?
.object(forKey: "Preferences_logLevel") as? Int
let logLevel = storedLogLevel.flatMap(NKLogLevel.init(rawValue:)) ?? .normal
let logDirectory = FileManager.default
.containerURL(forSecurityApplicationGroupIdentifier: groupIdentifier)?
.appendingPathComponent("Logs", isDirectory: true)
NextcloudKit.configureLogger(
logLevel: NCBrandOptions.shared.disable_log ? .disabled : logLevel,
logDirectory: logDirectory
)
view.isHidden = true
view.alpha = 0
view.backgroundColor = .clear
preferredContentSize = .zero
Task {
await handleAction()
}
}
private func handleAction() async {
guard let text = await loadText() else {
extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
return
}
NCAssistantSharedTextStore.save(text)
openMainAppForAssistantSharedText()
}
private func loadText() async -> String? {
guard let extensionItems = extensionContext?.inputItems as? [NSExtensionItem] else {
return nil
}
for extensionItem in extensionItems {
guard let attachments = extensionItem.attachments else {
continue
}
for provider in attachments {
if provider.hasItemConformingToTypeIdentifier(UTType.plainText.identifier) {
return await loadText(from: provider, typeIdentifier: UTType.plainText.identifier)
}
if provider.hasItemConformingToTypeIdentifier(UTType.utf8PlainText.identifier) {
return await loadText(from: provider, typeIdentifier: UTType.utf8PlainText.identifier)
}
if provider.hasItemConformingToTypeIdentifier(UTType.text.identifier) {
return await loadText(from: provider, typeIdentifier: UTType.text.identifier)
}
}
}
return nil
}
private func loadText(from provider: NSItemProvider, typeIdentifier: String) async -> String? {
await withCheckedContinuation { continuation in
provider.loadItem(forTypeIdentifier: typeIdentifier, options: nil) { item, _ in
let text: String?
if let string = item as? String {
text = string
} else if let attributedString = item as? NSAttributedString {
text = attributedString.string
} else if let data = item as? Data {
text = String(data: data, encoding: .utf8)
} else if let url = item as? URL {
text = try? String(contentsOf: url, encoding: .utf8)
} else {
text = nil
}
guard let text, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
continuation.resume(returning: nil)
return
}
continuation.resume(returning: text)
}
}
}
private func openMainAppForAssistantSharedText() {
guard let url = URL(string: "nextcloud://assistant/shared-text") else {
extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
return
}
openAssistantSharedTextURLThroughResponderChain(url)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
self?.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
}
}
/// Opens the Assistant shared-text deep link from the Share extension.
///
/// Share extensions cannot use `UIApplication.shared` directly because it is not
/// extension-safe. This method walks the responder chain until it finds the hidden
/// `UIApplication` responder and invokes the modern `open(_:options:completionHandler:)`
/// Objective-C selector dynamically.
///
/// This is intentionally isolated because it relies on Objective-C runtime dispatch.
///
/// - Parameter url: Deep link URL to open in the containing application.
private func openAssistantSharedTextURLThroughResponderChain(_ url: URL) {
let selector = NSSelectorFromString("openURL:options:completionHandler:")
let applicationClass: AnyClass? = NSClassFromString("UIApplication")
var responder: UIResponder? = self
while let currentResponder = responder {
guard let applicationClass,
currentResponder.isKind(of: applicationClass),
currentResponder.responds(to: selector),
let implementation = currentResponder.method(for: selector) else {
responder = currentResponder.next
continue
}
typealias CompletionBlock = @convention(block) (Bool) -> Void
typealias OpenURLFunction = @convention(c) (AnyObject, Selector, NSURL, NSDictionary, CompletionBlock?) -> Void
let openURL = unsafeBitCast(implementation, to: OpenURLFunction.self)
let completion: CompletionBlock = { success in
if success {
nkLog(debug: "Assistant shared text deep link performed through modern responder chain")
} else {
nkLog(error: "Assistant shared text deep link modern responder chain returned false")
}
NextcloudKit.flushLogger()
}
openURL(currentResponder, selector, url as NSURL, NSDictionary(), completion)
return
}
nkLog(error: "Assistant shared text deep link failed because no UIApplication responder can open URL")
NextcloudKit.flushLogger()
}
}