Files
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

126 lines
5.4 KiB
Swift

// SPDX-FileCopyrightText: Nextcloud GmbH
// SPDX-FileCopyrightText: 2020 Ivan Sein
// SPDX-License-Identifier: GPL-3.0-or-later
import UIKit
import UserNotifications
import os
import NextcloudKit
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
var request: UNNotificationRequest?
private let deliveryLock = OSAllocatedUnfairLock()
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
self.request = request
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
NextcloudKit.configureLogger(
logLevel: .verbose,
logDirectory: NCPreferences.sharedLogDirectory
)
guard let bestAttemptContent else { return }
bestAttemptContent.title = ""
bestAttemptContent.body = "Nextcloud notification"
var matchedAccount: tableAccount?
var payload: [String: AnyObject]?
do {
if let message = bestAttemptContent.userInfo["subject"] as? String {
for tableAccount in NCManageDatabase.shared.getAllTableAccount() {
guard let privateKey = NCPreferences().getPushNotificationPrivateKey(account: tableAccount.account) else {
bestAttemptContent.body = "Error retrieving private key for \(tableAccount.account)"
continue
}
let prefixData = Data(privateKey.prefix(8))
let prefixBase64 = prefixData.base64EncodedString()
nkLog(debug: "🔑 Loaded private key for \(tableAccount.account): prefix(Base64)=\(prefixBase64)")
guard let decryptedMessage = NCPushNotificationEncryption.shared().decryptPushNotification(message, withDevicePrivateKey: privateKey) else {
bestAttemptContent.body = "Error decrypting notification for \(tableAccount.account)"
continue
}
guard let data = decryptedMessage.data(using: .utf8) else {
bestAttemptContent.body = "Error decrypting UTF8 notification data for \(tableAccount.account)"
continue
}
if var json = try JSONSerialization.jsonObject(with: data) as? [String: AnyObject],
let subject = json["subject"] as? String {
bestAttemptContent.body = subject
if let pref = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup) {
json["account"] = tableAccount.account as AnyObject
pref.set(json, forKey: "NOTIFICATION_DATA")
pref.synchronize()
}
matchedAccount = tableAccount
payload = json
} else {
bestAttemptContent.body = "Error with notification JSON for \(tableAccount.account)"
}
break
}
}
} catch let error as NSError {
nkLog(error: "Failed : \(error.localizedDescription)")
}
guard let tblAccount = matchedAccount,
let nid = payload?["nid"] as? Int,
payload?["delete"] as? Bool != true,
payload?["delete-all"] as? Bool != true else {
deliver()
return
}
// NextcloudKit Session
NextcloudKit.shared.setup(groupIdentifier: NCBrandOptions.shared.capabilitiesGroup, delegate: NCNetworking.shared)
NextcloudKit.shared.appendSession(account: tblAccount.account,
urlBase: tblAccount.urlBase,
user: tblAccount.user,
userId: tblAccount.userId,
password: NCPreferences().getPassword(account: tblAccount.account),
userAgent: userAgent,
groupIdentifier: NCBrandOptions.shared.capabilitiesGroup)
Task {
let results = await NextcloudKit.shared.getNotificationsAsync(idNotification: nid,
account: tblAccount.account,
options: NKRequestOptions(timeout: 20))
if results.error == .success, let notification = results.notifications?.first {
bestAttemptContent.title = notification.message.isEmpty ? NCBrandOptions.shared.brand : notification.subject
bestAttemptContent.body = notification.message.isEmpty ? notification.subject : notification.message
}
deliver()
}
}
override func serviceExtensionTimeWillExpire() {
deliver()
}
private func deliver() {
NextcloudKit.flushLogger()
let handler = deliveryLock.withLock {
let handler = contentHandler
contentHandler = nil
return handler
}
if let handler, let bestAttemptContent {
handler(bestAttemptContent)
}
}
}