Add nync to protobuf

This commit is contained in:
Leon Böttger authored and Leon Böttger committed 2026-03-14 08:26:00 +01:00
1 parent d63665136b
commit 216e2cf851
4 files changed
+226 -109

No files matched your search

@@ -30,6 +30,7 @@ class InboundNearbyConnection: NearbyConnection {
private var bytesToBeTransferred: Int64 = 0
private var isAuthenticated = false
private var peerCertificate: Sharing_Nearby_PublicCertificate? = nil
private var mirroredNotificationMetadata: Sharing_Nearby_MirroredNotificationMetadata?
var isPlainTextTransfer = false
private var isMirroredNotificationTransfer = false
@@ -260,20 +261,6 @@ class InboundNearbyConnection: NearbyConnection {
override func processBytesPayload(payload: Data, id: Int64) throws -> Bool {
if id == textPayloadID {
#if os(macOS)
if isMirroredNotificationTransfer {
if let payloadString = String(data: payload, encoding: .utf8) {
log("[InboundNearbyConnection \(self.id)] Received mirrored notification payload (\(payload.count) bytes)")
MirroredNotificationPresenter.shared.present(rawPayload: payloadString, senderDeviceName: remoteDeviceInfo?.name)
} else {
log("[InboundNearbyConnection \(self.id)] Failed to decode mirrored notification payload as UTF-8")
}
try sendDisconnectionAndDisconnect()
return true
}
#endif
if let urlStr = String(data: payload, encoding: .utf8) {
if isPlainTextTransfer {
@@ -591,39 +578,42 @@ class InboundNearbyConnection: NearbyConnection {
}
let metadata = TransferMetadata(files: filesToBeReceived.map { $0.value.meta }, id: id, pinCode: pinCode, allowsToBeAddedAsTrustedDevice: self.peerCertificate != nil)
checkIfCanProceed(metadata: metadata)
return
}
else if let textMetadata = frame.v1.introduction.textMetadata.first {
let isURL = textMetadata.type == .url
textPayloadID = textMetadata.payloadID
#if os(macOS)
if textMetadata.type == .text && textMetadata.textTitle == MirroredNotificationProtocol.introductionTitle {
isMirroredNotificationTransfer = true
shouldSuppressAppDelegates = true
#if os(macOS)
if frame.v1.introduction.hasMirroredNotificationMetadata {
isMirroredNotificationTransfer = true
mirroredNotificationMetadata = frame.v1.introduction.mirroredNotificationMetadata
shouldSuppressAppDelegates = true
if !isAuthenticated {
guard let device = self.remoteDeviceInfo else {
self.rejectTransfer(with: .reject)
return
}
let metadata = TransferMetadata(
files: [],
id: id,
pinCode: pinCode,
transferType: .notificationSync,
allowsToBeAddedAsTrustedDevice: true
)
DispatchQueue.main.async {
self.delegate?.obtainUserConsent(transfer: metadata, device: device, connection: self)
}
if !isAuthenticated {
guard let device = self.remoteDeviceInfo else {
self.rejectTransfer(with: .reject)
return
}
let metadata = TransferMetadata(
files: [],
id: id,
pinCode: pinCode,
transferType: .notificationSync,
allowsToBeAddedAsTrustedDevice: true
)
submitUserConsent(accepted: true, trustDevice: false)
DispatchQueue.main.async {
self.delegate?.obtainUserConsent(transfer: metadata, device: device, connection: self)
}
return
}
#endif
submitUserConsent(accepted: true, trustDevice: false)
return
}
#endif
if let textMetadata = frame.v1.introduction.textMetadata.first {
let isURL = textMetadata.type == .url
textPayloadID = textMetadata.payloadID
let metadata = TransferMetadata(files: [], id: id, pinCode: pinCode, textDescription: textMetadata.textTitle, transferType: isURL ? .url : .text, allowsToBeAddedAsTrustedDevice: self.peerCertificate != nil)
@@ -732,6 +722,11 @@ class InboundNearbyConnection: NearbyConnection {
currentState = .receivingFiles
isTransferring = true
try sendTransferSetupFrame(frame)
if let mirroredNotificationMetadata {
MirroredNotificationPresenter.shared.present(metadata: mirroredNotificationMetadata, senderDeviceName: remoteDeviceInfo?.name)
try sendDisconnectionAndDisconnect()
}
} catch {
lastError = error
protocolError()
@@ -8,50 +8,29 @@ import CryptoKit
import UserNotifications
import LUI
enum MirroredNotificationProtocol {
static let introductionTitle = "__quickdrop_mirror_notification_v1__"
}
final class MirroredNotificationPresenter {
static let shared = MirroredNotificationPresenter()
private let center = UNUserNotificationCenter.current()
private let queue = DispatchQueue(label: "MirroredNotificationPresenter")
private var pendingNotifications: [(MirroredNotificationEnvelope, String?)] = []
private var pendingNotifications: [(Sharing_Nearby_MirroredNotificationMetadata, String?)] = []
private var authorizationRequestInFlight = false
private init() {}
func present(rawPayload: String, senderDeviceName: String?) {
guard let envelope = decodeEnvelope(from: rawPayload) else {
log("[MirroredNotificationPresenter] Failed to decode mirrored notification payload")
return
}
func present(metadata: Sharing_Nearby_MirroredNotificationMetadata, senderDeviceName: String?) {
queue.async {
self.postNotificationIfAuthorized(envelope: envelope, senderDeviceName: senderDeviceName)
self.postNotificationIfAuthorized(metadata: metadata, senderDeviceName: senderDeviceName)
}
}
private func decodeEnvelope(from rawPayload: String) -> MirroredNotificationEnvelope? {
guard let data = rawPayload.data(using: .utf8) else {
return nil
}
do {
return try JSONDecoder().decode(MirroredNotificationEnvelope.self, from: data)
} catch {
log("[MirroredNotificationPresenter] Failed to decode envelope JSON: \(error.localizedDescription)")
return nil
}
}
private func postNotificationIfAuthorized(envelope: MirroredNotificationEnvelope, senderDeviceName: String?) {
private func postNotificationIfAuthorized(metadata: Sharing_Nearby_MirroredNotificationMetadata, senderDeviceName: String?) {
center.getNotificationSettings { settings in
self.queue.async {
self.handleAuthorizationStatus(
settings.authorizationStatus,
envelope: envelope,
metadata: metadata,
senderDeviceName: senderDeviceName
)
}
@@ -60,14 +39,14 @@ final class MirroredNotificationPresenter {
private func handleAuthorizationStatus(
_ status: UNAuthorizationStatus,
envelope: MirroredNotificationEnvelope,
metadata: Sharing_Nearby_MirroredNotificationMetadata,
senderDeviceName: String?
) {
switch status {
case .authorized, .provisional, .ephemeral:
post(envelope: envelope, senderDeviceName: senderDeviceName)
post(metadata: metadata, senderDeviceName: senderDeviceName)
case .notDetermined:
pendingNotifications.append((envelope, senderDeviceName))
pendingNotifications.append((metadata, senderDeviceName))
requestAuthorizationIfNeeded()
case .denied:
log("[MirroredNotificationPresenter] Notifications are denied in system settings; cannot mirror.")
@@ -100,22 +79,23 @@ final class MirroredNotificationPresenter {
let queued = self.pendingNotifications
self.pendingNotifications.removeAll()
for (queuedEnvelope, queuedSender) in queued {
self.post(envelope: queuedEnvelope, senderDeviceName: queuedSender)
for (queuedMetadata, queuedSender) in queued {
self.post(metadata: queuedMetadata, senderDeviceName: queuedSender)
}
}
}
}
}
private func post(envelope: MirroredNotificationEnvelope, senderDeviceName: String?) {
private func post(metadata: Sharing_Nearby_MirroredNotificationMetadata, senderDeviceName: String?) {
let senderName = senderDeviceName?.trimmingCharacters(in: .whitespacesAndNewlines)
let hasSenderName = senderName?.isEmpty == false
let displaySender = hasSenderName ? senderName! : "NotificationSyncFallbackSenderAndroid".localized()
let identifierSender = hasSenderName ? senderName! : "android"
let cleanAppName = envelope.appName.trimmingCharacters(in: .whitespacesAndNewlines)
let cleanTitle = envelope.title.trimmingCharacters(in: .whitespacesAndNewlines)
let cleanBody = envelope.body.trimmingCharacters(in: .whitespacesAndNewlines)
let cleanAppName = metadata.appName.trimmingCharacters(in: .whitespacesAndNewlines)
let cleanTitle = metadata.title.trimmingCharacters(in: .whitespacesAndNewlines)
let cleanBody = metadata.body.trimmingCharacters(in: .whitespacesAndNewlines)
let notificationKey = metadata.notificationKey.trimmingCharacters(in: .whitespacesAndNewlines)
let content = UNMutableNotificationContent()
content.title = cleanTitle.isEmpty ? (cleanAppName.isEmpty ? "NotificationSyncFallbackTitle".localized() : cleanAppName) : cleanTitle
@@ -124,7 +104,7 @@ final class MirroredNotificationPresenter {
content.sound = .default
content.threadIdentifier = "quickdrop-mirror-\(sanitizeIdentifierComponent(identifierSender))"
let identifier = makeIdentifier(sender: identifierSender, notificationKey: envelope.notificationKey)
let identifier = makeIdentifier(sender: identifierSender, notificationKey: notificationKey)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: nil)
center.add(request) { error in
@@ -154,34 +134,3 @@ final class MirroredNotificationPresenter {
return sanitized.isEmpty ? "android" : sanitized
}
}
private struct MirroredNotificationEnvelope: Codable {
let version: Int
let notificationKey: String
let packageName: String
let appName: String
let title: String
let body: String
let postedAtEpochMs: Int64
enum CodingKeys: String, CodingKey {
case version
case notificationKey
case packageName
case appName
case title
case body
case postedAtEpochMs
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
version = try container.decodeIfPresent(Int.self, forKey: .version) ?? 1
notificationKey = try container.decode(String.self, forKey: .notificationKey)
packageName = try container.decode(String.self, forKey: .packageName)
appName = try container.decode(String.self, forKey: .appName)
title = try container.decode(String.self, forKey: .title)
body = try container.decode(String.self, forKey: .body)
postedAtEpochMs = try container.decode(Int64.self, forKey: .postedAtEpochMs)
}
}