mirror of
https://github.com/leonboe1/QuickDrop.git
synced 2026-11-20 13:26:03 +00:00
Add notification sync support
This commit is contained in:
1 parent
a352e9ed1c
commit
48eb5be4a5
8 files changed
+1014
-9
No files matched your search
@@ -31,8 +31,10 @@ class InboundNearbyConnection: NearbyConnection {
|
||||
private var isAuthenticated = false
|
||||
private var peerCertificate: Sharing_Nearby_PublicCertificate? = nil
|
||||
var isPlainTextTransfer = false
|
||||
private var isMirroredNotificationTransfer = false
|
||||
|
||||
var wasUserRejected = false
|
||||
var shouldSuppressAppDelegates = false
|
||||
var delegate: InboundNearbyConnectionDelegate?
|
||||
|
||||
enum State {
|
||||
@@ -187,6 +189,20 @@ 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 {
|
||||
@@ -507,14 +523,43 @@ class InboundNearbyConnection: NearbyConnection {
|
||||
}
|
||||
else if let textMetadata = frame.v1.introduction.textMetadata.first {
|
||||
let isURL = textMetadata.type == .url
|
||||
|
||||
let metadata = TransferMetadata(files: [], id: id, pinCode: pinCode, textDescription: textMetadata.textTitle, transferType: isURL ? .url : .text, allowsToBeAddedAsTrustedDevice: self.peerCertificate != nil)
|
||||
textPayloadID = textMetadata.payloadID
|
||||
|
||||
|
||||
#if os(macOS)
|
||||
if textMetadata.type == .text && textMetadata.textTitle == MirroredNotificationProtocol.introductionTitle {
|
||||
isMirroredNotificationTransfer = true
|
||||
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: false
|
||||
)
|
||||
|
||||
DispatchQueue.main.async {
|
||||
self.delegate?.obtainUserConsent(transfer: metadata, device: device, connection: self)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
submitUserConsent(accepted: true, trustDevice: false)
|
||||
return
|
||||
}
|
||||
#endif
|
||||
|
||||
let metadata = TransferMetadata(files: [], id: id, pinCode: pinCode, textDescription: textMetadata.textTitle, transferType: isURL ? .url : .text, allowsToBeAddedAsTrustedDevice: self.peerCertificate != nil)
|
||||
|
||||
if !isURL {
|
||||
isPlainTextTransfer = true
|
||||
}
|
||||
|
||||
|
||||
checkIfCanProceed(metadata: metadata)
|
||||
}
|
||||
else if let wifiMetadata = frame.v1.introduction.wifiCredentialsMetadata.first {
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
//
|
||||
// MirroredNotificationSupport.swift
|
||||
// QuickDrop
|
||||
//
|
||||
|
||||
import Foundation
|
||||
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 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
|
||||
}
|
||||
|
||||
queue.async {
|
||||
self.postNotificationIfAuthorized(envelope: envelope, 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?) {
|
||||
center.getNotificationSettings { settings in
|
||||
self.queue.async {
|
||||
self.handleAuthorizationStatus(
|
||||
settings.authorizationStatus,
|
||||
envelope: envelope,
|
||||
senderDeviceName: senderDeviceName
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func handleAuthorizationStatus(
|
||||
_ status: UNAuthorizationStatus,
|
||||
envelope: MirroredNotificationEnvelope,
|
||||
senderDeviceName: String?
|
||||
) {
|
||||
switch status {
|
||||
case .authorized, .provisional, .ephemeral:
|
||||
post(envelope: envelope, senderDeviceName: senderDeviceName)
|
||||
case .notDetermined:
|
||||
pendingNotifications.append((envelope, senderDeviceName))
|
||||
requestAuthorizationIfNeeded()
|
||||
case .denied:
|
||||
log("[MirroredNotificationPresenter] Notifications are denied in system settings; cannot mirror.")
|
||||
@unknown default:
|
||||
log("[MirroredNotificationPresenter] Unknown notification authorization status; skipping mirrored notification.")
|
||||
}
|
||||
}
|
||||
|
||||
private func requestAuthorizationIfNeeded() {
|
||||
if authorizationRequestInFlight {
|
||||
return
|
||||
}
|
||||
|
||||
authorizationRequestInFlight = true
|
||||
|
||||
DispatchQueue.main.async {
|
||||
self.center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
|
||||
self.queue.async {
|
||||
self.authorizationRequestInFlight = false
|
||||
|
||||
if let error = error {
|
||||
log("[MirroredNotificationPresenter] Authorization request failed: \(error.localizedDescription)")
|
||||
}
|
||||
|
||||
guard granted else {
|
||||
log("[MirroredNotificationPresenter] Authorization request not granted; dropping queued mirrored notifications.")
|
||||
self.pendingNotifications.removeAll()
|
||||
return
|
||||
}
|
||||
|
||||
let queued = self.pendingNotifications
|
||||
self.pendingNotifications.removeAll()
|
||||
for (queuedEnvelope, queuedSender) in queued {
|
||||
self.post(envelope: queuedEnvelope, senderDeviceName: queuedSender)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func post(envelope: MirroredNotificationEnvelope, 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 content = UNMutableNotificationContent()
|
||||
content.title = cleanTitle.isEmpty ? (cleanAppName.isEmpty ? "NotificationSyncFallbackTitle".localized() : cleanAppName) : cleanTitle
|
||||
content.body = cleanBody
|
||||
content.subtitle = cleanAppName.isEmpty ? displaySender : "\(cleanAppName) · \(displaySender)"
|
||||
content.sound = .default
|
||||
content.threadIdentifier = "quickdrop-mirror-\(sanitizeIdentifierComponent(identifierSender))"
|
||||
|
||||
let identifier = makeIdentifier(sender: identifierSender, notificationKey: envelope.notificationKey)
|
||||
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: nil)
|
||||
|
||||
center.add(request) { error in
|
||||
if let error = error {
|
||||
log("[MirroredNotificationPresenter] Could not post notification: \(error.localizedDescription)")
|
||||
} else {
|
||||
log("[MirroredNotificationPresenter] Posted mirrored notification (\(identifier))")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func makeIdentifier(sender: String, notificationKey: String) -> String {
|
||||
let raw = "\(sender)|\(notificationKey)"
|
||||
let digest = SHA256.hash(data: Data(raw.utf8))
|
||||
let prefix = digest.prefix(12).map { String(format: "%02x", $0) }.joined()
|
||||
return "quickdrop-mirror-\(prefix)"
|
||||
}
|
||||
|
||||
private func sanitizeIdentifierComponent(_ value: String) -> String {
|
||||
let allowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-_"))
|
||||
let scalarView = value.unicodeScalars.map { allowed.contains($0) ? Character($0) : "_" }
|
||||
let sanitized = String(scalarView)
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,10 @@ public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearb
|
||||
private var securityScopeUrl: URL?
|
||||
private static let customDeviceNameKey = "com.leonboettger.quickdrop.deviceName"
|
||||
private var defaultPort: NWEndpoint.Port = 50362
|
||||
private let txtKeyEndpointInfo = "n"
|
||||
private let txtKeyNotificationSyncCapabilities = "qd_caps"
|
||||
private let txtKeyNotificationSyncKeyFingerprint = "qd_kid"
|
||||
private let notificationSyncCapabilityToken = "nsync1"
|
||||
|
||||
|
||||
// MARK: Shared Instance
|
||||
@@ -307,14 +311,29 @@ public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearb
|
||||
mdnsServices = serviceTypes.map { serviceType in
|
||||
let service = NetService(domain: "", type: serviceType, name: name, port: port)
|
||||
service.delegate = self
|
||||
service.setTXTRecord(NetService.data(fromTXTRecord: [
|
||||
"n": deviceInfo.serialize().urlSafeBase64EncodedString().data(using: .utf8)!,
|
||||
]))
|
||||
var txtRecord: [String: Data] = [
|
||||
txtKeyEndpointInfo: deviceInfo.serialize().urlSafeBase64EncodedString().data(using: .utf8)!,
|
||||
]
|
||||
#if os(macOS)
|
||||
txtRecord[txtKeyNotificationSyncCapabilities] = Data(notificationSyncCapabilityToken.utf8)
|
||||
if let keyFingerprint = notificationSyncKeyFingerprintHex() {
|
||||
txtRecord[txtKeyNotificationSyncKeyFingerprint] = Data(keyFingerprint.utf8)
|
||||
}
|
||||
#endif
|
||||
service.setTXTRecord(NetService.data(fromTXTRecord: txtRecord))
|
||||
service.publish()
|
||||
return service
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private func notificationSyncKeyFingerprintHex() -> String? {
|
||||
guard let keyID = IdentityManager.shared.getPublicKey()?.toGenericPublicKey().id() else {
|
||||
return nil
|
||||
}
|
||||
return keyID.hex.lowercased()
|
||||
}
|
||||
|
||||
|
||||
private func stopMDNS() {
|
||||
// Gracefully stop each published service
|
||||
@@ -341,7 +360,11 @@ public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearb
|
||||
|
||||
func connectionWasTerminated(connection: InboundNearbyConnection, savedFiles: [URL], error: Error?) {
|
||||
incomingConnections.removeValue(forKey: connection.id)
|
||||
|
||||
|
||||
if connection.shouldSuppressAppDelegates {
|
||||
return
|
||||
}
|
||||
|
||||
if !connection.wasUserRejected {
|
||||
inboundAppDelegates.forEach { delegate in
|
||||
delegate.connectionWasTerminated(connectionID: connection.id, from: connection.remoteDeviceInfo, savedFiles: savedFiles, wasPlainTextTransfer: connection.isPlainTextTransfer, error: error)
|
||||
@@ -513,7 +536,7 @@ public class NearbyConnectionManager: NSObject, NetServiceDelegate, InboundNearb
|
||||
var foundService = FoundServiceInfo(service: service)
|
||||
|
||||
guard case let NWBrowser.Result.Metadata.bonjour(txtRecord) = service.metadata else { return }
|
||||
guard let endpointInfoEncoded = txtRecord.dictionary["n"] else { return }
|
||||
guard let endpointInfoEncoded = txtRecord.dictionary[txtKeyEndpointInfo] else { return }
|
||||
guard let endpointInfoData = Data.dataFromUrlSafeBase64(endpointInfoEncoded) else { return }
|
||||
guard var endpointInfo = EndpointInfo(data: endpointInfoData) else { return }
|
||||
var deviceInfo: RemoteDeviceInfo?
|
||||
|
||||
@@ -269,6 +269,15 @@ class OutboundNearbyConnection: NearbyConnection {
|
||||
private func processConnectionResponse(frame: Location_Nearby_Connections_OfflineFrame) throws {
|
||||
|
||||
guard frame.version == .v1 else { throw NearbyError.protocolError("Unexpected offline frame version \(frame.version)") }
|
||||
guard frame.hasV1, frame.v1.hasType else { throw NearbyError.requiredFieldMissing("offlineFrame.v1.type") }
|
||||
|
||||
if frame.v1.type == .keepAlive {
|
||||
log("[OutboundNearbyConnection \(self.id)] Received keep-alive while waiting for connection response")
|
||||
if frame.v1.hasKeepAlive, !frame.v1.keepAlive.ack {
|
||||
sendKeepAlive(ack: true)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
guard frame.v1.type == .connectionResponse else { throw NearbyError.protocolError("Unexpected frame type \(frame.v1.type)") }
|
||||
|
||||
|
||||
Reference in new issue
Block a user