diff --git a/NearbyShare/InboundNearbyConnection.swift b/NearbyShare/InboundNearbyConnection.swift index d53a805..e69856d 100644 --- a/NearbyShare/InboundNearbyConnection.swift +++ b/NearbyShare/InboundNearbyConnection.swift @@ -22,6 +22,9 @@ class InboundNearbyConnection: NearbyConnection { private var textPayloadID: Int64 = 0 private var isPlainTextTransfer = false + + private var inactivityTimer: DispatchSourceTimer? + private let timeoutInterval: TimeInterval = 7 enum State { case initial, receivedConnectionRequest, sentUkeyServerInit, receivedUkeyClientFinish, sentConnectionResponse, sentPairedKeyResult, receivedPairedKeyResult, waitingForUserConsent, receivingFiles, disconnected @@ -34,7 +37,6 @@ class InboundNearbyConnection: NearbyConnection { override func handleConnectionClosure() { super.handleConnectionClosure() currentState = .disconnected - deletePartiallyReceivedFiles() DispatchQueue.main.async { self.delegate?.connectionWasTerminated(connection: self, error: self.lastError) @@ -475,18 +477,6 @@ class InboundNearbyConnection: NearbyConnection { protocolError() } } - - private func deletePartiallyReceivedFiles() { - for (_, file) in transferredFiles { - guard file.created else { continue } - do { - try FileManager.default.removeItem(at: file.destinationURL) - } - catch { - // if it fails, we don't care. Could be because file was not created yet - } - } - } } protocol InboundNearbyConnectionDelegate { diff --git a/NearbyShare/NearbyConnection.swift b/NearbyShare/NearbyConnection.swift index 935bfed..6aafe4a 100644 --- a/NearbyShare/NearbyConnection.swift +++ b/NearbyShare/NearbyConnection.swift @@ -27,6 +27,9 @@ class NearbyConnection { var lastError: Error? private var connectionClosed: Bool = false + private var inactivityTimer: DispatchSourceTimer? + private let timeoutInterval: TimeInterval = 7 + // UKEY2-related state var publicKey: ECPublicKey? var privateKey: ECPrivateKey? @@ -96,7 +99,7 @@ class NearbyConnection { self.lastError = NearbyError.protocolError("Error.NetworkDown".localized()) } - self.handleConnectionClosure() + self.disconnect() } } @@ -104,6 +107,7 @@ class NearbyConnection { func handleConnectionClosure() { log("Connection closed") + deletePartiallyReceivedFiles() } func protocolError() { @@ -139,7 +143,7 @@ class NearbyConnection { if isComplete { log("Connection closed by peer during receiveFrameAsync") self.lastError = NearbyError.protocolError("Error.ClosedByPeer".localized()) - self.handleConnectionClosure() + self.disconnect() return } if !(error == nil) { @@ -157,6 +161,8 @@ class NearbyConnection { self.protocolError() return } + + self.startInactivityTimer() self.receiveFrameAsync(length: frameLength) } } @@ -169,13 +175,15 @@ class NearbyConnection { if isComplete { log("Connection closed by peer during receiveFrameAsync") self.lastError = NearbyError.protocolError("Error.ClosedByPeer".localized()) - self.handleConnectionClosure() + self.disconnect() return } guard let content = content else { self.protocolError() return } + + self.startInactivityTimer() self.processReceivedFrame(frameData: content) self.receiveFrameAsync() } @@ -446,6 +454,8 @@ class NearbyConnection { log("Disconnecting from connection.") connection.stateUpdateHandler = nil + inactivityTimer?.cancel() + inactivityTimer = nil connectionClosed = true self.handleConnectionClosure() @@ -498,6 +508,33 @@ class NearbyConnection { log("Error sending KEEP_ALIVE: \(error)") } } + + func startInactivityTimer() { + inactivityTimer?.cancel() // Cancel previous timer if any + inactivityTimer = DispatchSource.makeTimerSource(queue: NearbyConnection.dispatchQueue) + inactivityTimer?.schedule(deadline: .now() + timeoutInterval) + inactivityTimer?.setEventHandler { [weak self] in + guard let self = self else { return } + if !self.connectionClosed { + log("Connection timeout: No message received in \(self.timeoutInterval) seconds") + self.lastError = NearbyError.canceled(reason: .timedOut) + self.disconnect() + } + } + inactivityTimer?.resume() + } + + private func deletePartiallyReceivedFiles() { + for (_, file) in transferredFiles { + guard file.created else { continue } + do { + try FileManager.default.removeItem(at: file.destinationURL) + } + catch { + // if it fails, we don't care. Could be because file was not created yet + } + } + } } struct InternalFileInfo { diff --git a/NearbyShare/NearbyConnectionManager.swift b/NearbyShare/NearbyConnectionManager.swift index 64ba5b6..7ad08fc 100644 --- a/NearbyShare/NearbyConnectionManager.swift +++ b/NearbyShare/NearbyConnectionManager.swift @@ -58,6 +58,21 @@ public enum NearbyError: Error { public enum CancellationReason { case userRejected, userCanceled, notEnoughSpace, unsupportedType, timedOut + + public func localizedDescription() -> String { + switch self { + case .userRejected: + "TransferDeclined".localized() + case .userCanceled: + "TransferCanceled".localized() + case .notEnoughSpace: + "NotEnoughSpace".localized() + case .unsupportedType: + "UnsupportedType".localized() + case .timedOut: + "TransferTimedOut".localized() + } + } } } diff --git a/NearbyShare/OutboundNearbyConnection.swift b/NearbyShare/OutboundNearbyConnection.swift index db4df49..64b009e 100644 --- a/NearbyShare/OutboundNearbyConnection.swift +++ b/NearbyShare/OutboundNearbyConnection.swift @@ -56,6 +56,16 @@ class OutboundNearbyConnection: NearbyConnection { } } } + + override func handleConnectionClosure() { + super.handleConnectionClosure() + + if let error = lastError { + DispatchQueue.main.async { + self.delegate?.outboundConnection(connection: self, failedWithError: error) + } + } + } public func cancel() { cancelled = true @@ -422,6 +432,7 @@ class OutboundNearbyConnection: NearbyConnection { }) totalBytesSent += Int64(fileBuffer.count) log("sent file chunk \(totalBytesSent)") + startInactivityTimer() delegate?.outboundConnection(connection: self, transferProgress: Double(totalBytesSent) / Double(totalBytesToSend)) if currentTransfer!.currentOffset == currentTransfer!.totalBytes { diff --git a/QuickDrop.xcodeproj/project.pbxproj b/QuickDrop.xcodeproj/project.pbxproj index 1560cfa..077fac6 100644 --- a/QuickDrop.xcodeproj/project.pbxproj +++ b/QuickDrop.xcodeproj/project.pbxproj @@ -54,6 +54,8 @@ EB96ED8F2D7F8105004B3FF1 /* Localized.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB96ED8E2D7F8103004B3FF1 /* Localized.swift */; }; EB96ED902D7F8114004B3FF1 /* Localized.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB96ED8E2D7F8103004B3FF1 /* Localized.swift */; }; EBC05C592E32C22200EECC18 /* Localized.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB96ED8E2D7F8103004B3FF1 /* Localized.swift */; }; + EBC05C5B2E33937200EECC18 /* ErrorAlertHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = EBC05C5A2E33936C00EECC18 /* ErrorAlertHandler.swift */; }; + EBC05C5C2E3394EF00EECC18 /* ErrorAlertHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = EBC05C5A2E33936C00EECC18 /* ErrorAlertHandler.swift */; }; EBCC27F92D80C9F90079C478 /* Zip.swift in Sources */ = {isa = PBXBuildFile; fileRef = EBCC27F82D80C9F70079C478 /* Zip.swift */; }; EBD2A2172D2860C100BCB8E2 /* WelcomeScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = EBD2A2162D2860BE00BCB8E2 /* WelcomeScreen.swift */; }; /* End PBXBuildFile section */ @@ -223,14 +225,36 @@ EB9237C32D7CDE4100CA3A42 /* th */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = th; path = th.lproj/ShareViewController.strings; sourceTree = ""; }; EB96ED8A2D7F7CF4004B3FF1 /* SmallSheetView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SmallSheetView.swift; sourceTree = ""; }; EB96ED8E2D7F8103004B3FF1 /* Localized.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Localized.swift; sourceTree = ""; }; + EBC05C5A2E33936C00EECC18 /* ErrorAlertHandler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ErrorAlertHandler.swift; sourceTree = ""; }; EBCC27F82D80C9F70079C478 /* Zip.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Zip.swift; sourceTree = ""; }; EBD2A2162D2860BE00BCB8E2 /* WelcomeScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WelcomeScreen.swift; sourceTree = ""; }; EBD2A2182D28619200BCB8E2 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = ""; }; /* End PBXFileReference section */ +/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */ + EBC05C632E3396CF00EECC18 /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = { + isa = PBXFileSystemSynchronizedBuildFileExceptionSet; + membershipExceptions = ( + ApIsolationIssueView.swift, + FirewallIssueView.swift, + IssueView.swift, + NetworkFilterIssueView.swift, + ); + target = 699DEBA02AB0573200115D22 /* QuickDropShareExtension */; + }; + EBC05C672E3396F300EECC18 /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = { + isa = PBXFileSystemSynchronizedBuildFileExceptionSet; + membershipExceptions = ( + ActiveNetworkInterface.swift, + ApIsolationTester.swift, + ); + target = 699DEBA02AB0573200115D22 /* QuickDropShareExtension */; + }; +/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */ + /* Begin PBXFileSystemSynchronizedRootGroup section */ - EB1A7E422DD4D8BD00A6D5A3 /* SelfTest */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = SelfTest; sourceTree = ""; }; - EB6E743F2DD5CBFB00331466 /* IssueViews */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = IssueViews; sourceTree = ""; }; + EB1A7E422DD4D8BD00A6D5A3 /* SelfTest */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (EBC05C672E3396F300EECC18 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = SelfTest; sourceTree = ""; }; + EB6E743F2DD5CBFB00331466 /* IssueViews */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (EBC05C632E3396CF00EECC18 /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = IssueViews; sourceTree = ""; }; EB7CD13B2D6F8B6500CB0CB5 /* Plus */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = Plus; sourceTree = ""; }; EBC05C582E32A21000EECC18 /* Resources */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = Resources; sourceTree = ""; }; /* End PBXFileSystemSynchronizedRootGroup section */ @@ -317,6 +341,7 @@ EBD2A2182D28619200BCB8E2 /* Info.plist */, 69DA9A1129E0BF5100A442DA /* AppDelegate.swift */, EBD2A2162D2860BE00BCB8E2 /* WelcomeScreen.swift */, + EBC05C5A2E33936C00EECC18 /* ErrorAlertHandler.swift */, EB7F54112D78E95C00989564 /* TutorialView.swift */, EB1A7E422DD4D8BD00A6D5A3 /* SelfTest */, EB7F54132D78E9E400989564 /* LicenseWindow.swift */, @@ -562,6 +587,7 @@ EB96ED8B2D7F7CF7004B3FF1 /* SmallSheetView.swift in Sources */, EBCC27F92D80C9F90079C478 /* Zip.swift in Sources */, EB7CD1462D6FB0E800CB0CB5 /* Logger.swift in Sources */, + EBC05C5C2E3394EF00EECC18 /* ErrorAlertHandler.swift in Sources */, 691F53BB2ABB70840089FD92 /* DeviceListCell.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -573,6 +599,7 @@ EBD2A2172D2860C100BCB8E2 /* WelcomeScreen.swift in Sources */, EB3643602D73A2A2009CDFF8 /* AudioManager.swift in Sources */, EB91F0EB2DEDC741006C1867 /* CableConnectionView.swift in Sources */, + EBC05C5B2E33937200EECC18 /* ErrorAlertHandler.swift in Sources */, EB96ED8C2D7F7E7B004B3FF1 /* SmallSheetView.swift in Sources */, EB7F54142D78E9E700989564 /* LicenseWindow.swift in Sources */, 69DA9A1229E0BF5100A442DA /* AppDelegate.swift in Sources */, diff --git a/QuickDrop/AppDelegate.swift b/QuickDrop/AppDelegate.swift index 531115c..fe71494 100644 --- a/QuickDrop/AppDelegate.swift +++ b/QuickDrop/AppDelegate.swift @@ -23,13 +23,10 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele var welcomeWindow: NSWindow? var plusWindow: NSWindow? - private var isAlertShown = false private var sheetView: NSPanel? = nil private var sheetAttachedWindow: NSWindow? = nil - - var firewallAlertWindow: NSWindow? - var apIsolationAlertWindow: NSWindow? - var networkFilterAlertWindow: NSWindow? + private var errorAlertHandler = ErrorAlertHandler.shared + private var iapManager: IAPManager? var showsFirewallAlert = false @@ -275,52 +272,9 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele // MARK: - Alerts and Notifications - - enum AlertType: String { - case ApIsolation - case NetworkFilter - case Firewall - } - - func openAlert(type: AlertType) { - log("Opening Alert for \(type)") - - DispatchQueue.main.async { [self] in - // Create an NSWindow to host the SwiftUI view - let alertWindow = NSWindow( - contentRect: NSRect(x: 0, y: 0, width: issueViewWidth, height: issueViewHeight), - styleMask: [.titled, .closable], - backing: .buffered, - defer: false - ) - - switch type { - case .ApIsolation: - apIsolationAlertWindow = alertWindow - alertWindow.contentView = NSHostingView(rootView: ApIsolationIssueView(closeView: { self.apIsolationAlertWindow?.close() })) - case .NetworkFilter: - networkFilterAlertWindow = alertWindow - alertWindow.contentView = NSHostingView(rootView: NetworkFilterIssueView()) - case .Firewall: - firewallAlertWindow = alertWindow - alertWindow.contentView = NSHostingView(rootView: FirewallIssueView()) - } - - alertWindow.title = "QuickDrop" - alertWindow.center() - alertWindow.isReleasedWhenClosed = false - alertWindow.setFrameAutosaveName(type.rawValue) - - NSApp.activate(ignoringOtherApps: true) - alertWindow.makeKeyAndOrderFront(nil) - alertWindow.level = .normal - } - } - - func showFirewallAlert() { - openAlert(type: .Firewall) + ErrorAlertHandler.shared.openAlert(type: .Firewall) } @@ -457,60 +411,13 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele guard let transfer = activeIncomingTransfers[id] else { return } if let error = error { - NSApp.activate(ignoringOtherApps: true) - - var description = "" - - if let ne = (error as? NearbyError) { - switch ne { - case .inputOutput: - description = "I/O Error" - case .protocolError(errorMessage: let errorMessage): - description = "Error.Protocol".localized() + ": \(errorMessage)" - case .packetFilterError: - openAlert(type: .NetworkFilter) - plusWindow?.close() - return - case .requiredFieldMissing(errorMessage: let errorMessage): - description = "Error.Protocol".localized() + ": \(errorMessage)" - case .ukey2: - description = "Error.Crypto".localized() + ": \(ne.localizedDescription)" - case .canceled(reason: let reason): - description = "Error.Protocol".localized() + ": \(reason)" - } - } else { - description = error.localizedDescription - } - - let alert = NSAlert() - alert.alertStyle = .critical - alert.messageText = String(format: "TransferError".localized(), arguments: [transfer.device.name]) - alert.informativeText = description - alert.addButton(withTitle: "InformDeveloper".localized()) - alert.addButton(withTitle: "CloseAlert".localized()) - + if let plusWindow = plusWindow { log("Closing plus screen because of error") plusWindow.close() } - // Prevent multiple alerts at the same time - if self.isAlertShown { - log("Skipping alert for error \(error.localizedDescription) because one is already shown") - return - } - else { - self.isAlertShown = true - log("Showing alert with message: \"\(alert.messageText)\" and description: \"\(alert.informativeText)\"") - log("Already successful transmissions: \(transmissionCount())") - - let result = alert.runModal() - self.isAlertShown = false - - if result == .alertFirstButtonReturn { - sendLoggingString() - } - } + ErrorAlertHandler.shared.showErrorAlert(for: transfer.device.name, error: error) } else { let currentCount = transmissionCount() if currentCount % 20 == 0 { @@ -534,10 +441,10 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele scanner.scan { allowed in if allowed { log("✅ Device-to-device likely allowed (peer responded on LAN).") - self.apIsolationAlertWindow?.close() + ErrorAlertHandler.shared.closeApIsolationAlert() } else { log("❌ Device-to-device check failed. Informing user...") - self.openAlert(type: .ApIsolation) + ErrorAlertHandler.shared.openAlert(type: .ApIsolation) } } } diff --git a/QuickDrop/ErrorAlertHandler.swift b/QuickDrop/ErrorAlertHandler.swift new file mode 100644 index 0000000..1e7adba --- /dev/null +++ b/QuickDrop/ErrorAlertHandler.swift @@ -0,0 +1,177 @@ +// +// ErrorAlertHandler.swift +// QuickDrop +// +// Created by Leon Böttger on 25.07.25. +// + +import AudioToolbox +import BezelNotification +import Cocoa +import NearbyShare +import Network +import StoreKit +import SwiftUI +import UserNotifications + +class ErrorAlertHandler { + + private init() {} + static let shared = ErrorAlertHandler() + + private var isAlertShown = false + private var firewallAlertWindow: NSWindow? + private var apIsolationAlertWindow: NSWindow? + private var networkFilterAlertWindow: NSWindow? + + func showErrorAlert(for deviceName: String, error: Error) { + NSApp.activate(ignoringOtherApps: true) + + var description = "" + + if let ne = (error as? NearbyError) { + switch ne { + case .inputOutput: + description = "I/O Error" + case .protocolError(errorMessage: let errorMessage): + description = "Error.Protocol".localized() + ": \(errorMessage)" + case .packetFilterError: + openAlert(type: .NetworkFilter) + return + case .requiredFieldMissing(errorMessage: let errorMessage): + description = "Error.Protocol".localized() + ": \(errorMessage)" + case .ukey2: + description = "Error.Crypto".localized() + ": \(ne.localizedDescription)" + case .canceled(reason: let reason): + description = "Error.Protocol".localized() + ": \(reason.localizedDescription())" + } + } else { + description = error.localizedDescription + } + + let alert = NSAlert() + alert.alertStyle = .critical + alert.messageText = String(format: "TransferError".localized(), arguments: [deviceName]) + alert.informativeText = description + alert.addButton(withTitle: "InformDeveloper".localized()) + alert.addButton(withTitle: "CloseAlert".localized()) + + // Prevent multiple alerts at the same time + if self.isAlertShown { + log("Skipping alert for error \(error.localizedDescription) because one is already shown") + return + } + else { + self.isAlertShown = true + log("Showing alert with message: \"\(alert.messageText)\" and description: \"\(alert.informativeText)\"") + log("Unsuccessful transmission. Already successful transmissions: \(transmissionCount())") + + let result = alert.runModal() + self.isAlertShown = false + + if result == .alertFirstButtonReturn { + sendLoggingString() + } + } + } + + + func openAlert(type: AlertType) { + log("Opening Alert for \(type)") + + DispatchQueue.main.async { [self] in + // Create an NSWindow to host the SwiftUI view + let alertWindow = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: issueViewWidth, height: issueViewHeight), + styleMask: [.titled, .closable], + backing: .buffered, + defer: false + ) + + switch type { + case .ApIsolation: + apIsolationAlertWindow = alertWindow + alertWindow.contentView = NSHostingView(rootView: ApIsolationIssueView(closeView: { self.apIsolationAlertWindow?.close() })) + case .NetworkFilter: + networkFilterAlertWindow = alertWindow + alertWindow.contentView = NSHostingView(rootView: NetworkFilterIssueView()) + case .Firewall: + firewallAlertWindow = alertWindow + alertWindow.contentView = NSHostingView(rootView: FirewallIssueView()) + } + + alertWindow.title = "QuickDrop" + alertWindow.center() + alertWindow.isReleasedWhenClosed = false + alertWindow.setFrameAutosaveName(type.rawValue) + + NSApp.activate(ignoringOtherApps: true) + alertWindow.makeKeyAndOrderFront(nil) + alertWindow.level = .normal + } + } + + + func closeApIsolationAlert() { + log("Closing AP Isolation Alert") + DispatchQueue.main.async { + self.apIsolationAlertWindow?.close() + self.apIsolationAlertWindow = nil + } + } +} + + +func sendLoggingString() { + + if let url = LogManager.sharedInstance.logFileURL { + + let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "Unknown" + + sendEmailWithAttachment(fileURL: url, recipients: ["quickdrop@leonboettger.com"], subject: "QuickDrop \(appVersion) - \(getDeviceAndSystem())") + } +} + + +fileprivate func getDeviceAndSystem() -> String { + // Get Mac model identifier + var size: Int = 0 + sysctlbyname("hw.model", nil, &size, nil, 0) + + var modelBuffer = [CChar](repeating: 0, count: size) + sysctlbyname("hw.model", &modelBuffer, &size, nil, 0) + + let model = String(cString: modelBuffer) + + // Get macOS version + let version = ProcessInfo.processInfo.operatingSystemVersion + let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + + return "\(model) - \(versionString)" +} + + +func sendEmailWithAttachment(fileURL: URL, recipients: [String], subject: String) { + guard let emailService = NSSharingService(named: .composeEmail) else { + log("No email service available") + return + } + + emailService.recipients = recipients + emailService.subject = subject + emailService.perform(withItems: [fileURL]) +} + + +func copyToClipboard(_ text: String) { + let pasteboard = NSPasteboard.general + pasteboard.clearContents() + pasteboard.setString(text, forType: .string) +} + + +enum AlertType: String { + case ApIsolation + case NetworkFilter + case Firewall +} diff --git a/QuickDrop/TutorialView.swift b/QuickDrop/TutorialView.swift index bf2ea05..f3c2ba5 100644 --- a/QuickDrop/TutorialView.swift +++ b/QuickDrop/TutorialView.swift @@ -120,53 +120,6 @@ struct LargeAppIconView: View { } } -func sendLoggingString() { - - if let url = LogManager.sharedInstance.logFileURL { - - let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "Unknown" - - sendEmailWithAttachment(fileURL: url, recipients: ["quickdrop@leonboettger.com"], subject: "QuickDrop \(appVersion) - \(getDeviceAndSystem())") - } -} - - -fileprivate func getDeviceAndSystem() -> String { - // Get Mac model identifier - var size: Int = 0 - sysctlbyname("hw.model", nil, &size, nil, 0) - - var modelBuffer = [CChar](repeating: 0, count: size) - sysctlbyname("hw.model", &modelBuffer, &size, nil, 0) - - let model = String(cString: modelBuffer) - - // Get macOS version - let version = ProcessInfo.processInfo.operatingSystemVersion - let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" - - return "\(model) - \(versionString)" -} - - -func sendEmailWithAttachment(fileURL: URL, recipients: [String], subject: String) { - guard let emailService = NSSharingService(named: .composeEmail) else { - log("No email service available") - return - } - - emailService.recipients = recipients - emailService.subject = subject - emailService.perform(withItems: [fileURL]) -} - - -func copyToClipboard(_ text: String) { - let pasteboard = NSPasteboard.general - pasteboard.clearContents() - pasteboard.setString(text, forType: .string) -} - #Preview { WelcomeScreen(openPlusScreen: {}, openAppAdvertisementView: {}, openCableTransmissionView: {}, checkForNetworkIssues: {}) diff --git a/ShareExtension/ShareViewController.swift b/ShareExtension/ShareViewController.swift index 7ea6ecf..8b2a805 100644 --- a/ShareExtension/ShareViewController.swift +++ b/ShareExtension/ShareViewController.swift @@ -16,6 +16,7 @@ class ShareViewController: NSViewController, ShareExtensionDelegate { private var foundDevices: [RemoteDeviceInfo] = [] private var chosenDevice: RemoteDeviceInfo? private var lastError: Error? + private var errorAlertHandler = ErrorAlertHandler.shared private var connectionEstablished = false private var timeoutDispatchWorkItem: DispatchWorkItem? = nil @@ -282,26 +283,13 @@ class ShareViewController: NSViewController, ShareExtensionDelegate { lastError = error if let ne = (error as? NearbyError), case let .canceled(reason) = ne { - switch reason { - case .userRejected: - progressState?.stringValue = "TransferDeclined".localized() - case .userCanceled: - progressState?.stringValue = "TransferCanceled".localized() - case .notEnoughSpace: - progressState?.stringValue = "NotEnoughSpace".localized() - case .unsupportedType: - progressState?.stringValue = "UnsupportedType".localized() - case .timedOut: - progressState?.stringValue = "TransferTimedOut".localized() - } + progressState?.stringValue = reason.localizedDescription() progressDeviceSecondaryIcon?.isHidden = false dismissDelayed() - } else { - let alert = NSAlert(error: error) - - alert.beginSheetModal(for: view.window!) { _ in - self.extensionContext!.cancelRequest(withError: error) - } + } + else { + ErrorAlertHandler.shared.showErrorAlert(for: chosenDevice?.name ?? "", error: error) + self.extensionContext!.cancelRequest(withError: error) } }