mirror of
https://github.com/leonboe1/QuickDrop.git
synced 2026-11-21 05:46:03 +00:00
Refactoring
This commit is contained in:
1 parent
af5ff5e4fe
commit
a311aa01b0
18 files changed
+50
-18
No files matched your search
@@ -0,0 +1,41 @@
|
||||
//
|
||||
// ConnectionFailureTracker.swift
|
||||
// QuickDrop
|
||||
//
|
||||
// Created by Leon Böttger on 15.05.25.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
class ConnectionFailureTracker {
|
||||
static let shared = ConnectionFailureTracker()
|
||||
|
||||
private var failureTimestamps: [Date] = []
|
||||
private var lastAlertShownAt: Date?
|
||||
|
||||
private let queue = DispatchQueue(label: "ConnectionFailureTrackerQueue")
|
||||
|
||||
private init() {}
|
||||
|
||||
func recordFailure(onTrigger: @escaping () -> Void) {
|
||||
queue.async {
|
||||
let now = Date()
|
||||
|
||||
// Remove old timestamps older than 10 seconds
|
||||
self.failureTimestamps = self.failureTimestamps.filter { now.timeIntervalSince($0) < 10 }
|
||||
self.failureTimestamps.append(now)
|
||||
|
||||
// Check if alert can be shown
|
||||
let canShowAlert = self.failureTimestamps.count >= 2 &&
|
||||
(self.lastAlertShownAt == nil || now.timeIntervalSince(self.lastAlertShownAt!) >= 60)
|
||||
|
||||
if canShowAlert {
|
||||
self.lastAlertShownAt = now
|
||||
self.failureTimestamps.removeAll()
|
||||
DispatchQueue.main.async {
|
||||
onTrigger()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//
|
||||
// Helpers.swift
|
||||
// QuickDrop
|
||||
//
|
||||
// Created by Leon Böttger on 04.04.25.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
extension Data {
|
||||
func urlSafeBase64EncodedString() -> String {
|
||||
return String(base64EncodedString().replacingOccurrences(of: "=", with: "").map {
|
||||
if $0 == "/" {
|
||||
return "_"
|
||||
} else if $0 == "+" {
|
||||
return "-"
|
||||
} else {
|
||||
return $0
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
static func randomData(length: Int) -> Data {
|
||||
var data = Data(count: length)
|
||||
data.withUnsafeMutableBytes {
|
||||
guard SecRandomCopyBytes(kSecRandomDefault, length, $0.baseAddress!) == 0 else { fatalError() }
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
|
||||
static func dataFromUrlSafeBase64(_ str: String) -> Data? {
|
||||
var regularB64 = String(str.map {
|
||||
if $0 == "_" {
|
||||
return "/"
|
||||
} else if $0 == "-" {
|
||||
return "+"
|
||||
} else {
|
||||
return $0
|
||||
}
|
||||
})
|
||||
while (regularB64.count % 4) != 0 {
|
||||
regularB64 = regularB64 + "="
|
||||
}
|
||||
return Data(base64Encoded: regularB64, options: .ignoreUnknownCharacters)
|
||||
}
|
||||
|
||||
|
||||
var hex: String {
|
||||
return map { String(format: "%02hhx", $0) }.joined()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension String {
|
||||
var dataFromHex: Data {
|
||||
var data = Data(capacity: count / 2)
|
||||
var index = startIndex
|
||||
while index < endIndex {
|
||||
let nextIndex = self.index(index, offsetBy: 2)
|
||||
if nextIndex <= endIndex,
|
||||
let byte = UInt8(self[index ..< nextIndex], radix: 16)
|
||||
{
|
||||
data.append(byte)
|
||||
} else {
|
||||
break // or handle invalid hex gracefully
|
||||
}
|
||||
index = nextIndex
|
||||
}
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public enum UserDefaultsKeys: String, CaseIterable {
|
||||
case isEligibleForIap = "isEligibleForIap"
|
||||
case appLaunchedBefore = "ShowedWelcomeScreen"
|
||||
case plusVersion = "isPlusVersion"
|
||||
case transmissionCount = "reviewRequestCountKey"
|
||||
case automaticallyAcceptFiles = "automaticallyAcceptFiles"
|
||||
case saveFolderBookmark = "saveFolderBookmark"
|
||||
case openFinderAfterReceiving = "openFinderAfterReceiving"
|
||||
case endpointID = "endpointID"
|
||||
}
|
||||
|
||||
|
||||
public func isPlusVersion() -> Bool {
|
||||
return UserDefaults.standard.bool(forKey: UserDefaultsKeys.plusVersion.rawValue)
|
||||
}
|
||||
|
||||
|
||||
public func isFileTransferRestricted() -> Bool {
|
||||
(!isPlusVersion() && transmissionCount() > 1)
|
||||
}
|
||||
|
||||
|
||||
public func transmissionCount() -> Int {
|
||||
return UserDefaults.standard.integer(forKey: UserDefaultsKeys.transmissionCount.rawValue)
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
//
|
||||
// Logger.swift
|
||||
// QuickDrop
|
||||
//
|
||||
// Created by Leon Böttger on 26.02.25.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import os
|
||||
|
||||
fileprivate let loggerQueue = DispatchQueue(label: "loggerQueue", qos: .utility)
|
||||
|
||||
/// Manages logging functionality
|
||||
final class LogManager {
|
||||
|
||||
/// The URL of the log file
|
||||
let logFileURL: URL?
|
||||
|
||||
/// Shared instance
|
||||
public static let sharedInstance = LogManager()
|
||||
|
||||
@Published var loggingEnabled = true
|
||||
|
||||
|
||||
/// Private initializer
|
||||
private init() {
|
||||
// Use the App Group container
|
||||
let directory = getAppGroupDirectory()
|
||||
|
||||
// Create file name from date
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "dd-MM-yyyy"
|
||||
let dateString = formatter.string(from: Date())
|
||||
let fileName = "\(dateString).log"
|
||||
|
||||
// Full path in app group container
|
||||
self.logFileURL = directory?.appendingPathComponent(fileName)
|
||||
}
|
||||
|
||||
|
||||
/// Writes a specified string to the log file.
|
||||
func writeToFile(string: String) {
|
||||
guard let logFileURL = logFileURL else { return }
|
||||
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "HH:mm:ss"
|
||||
let timestamp = formatter.string(from: Date())
|
||||
guard let data = (timestamp + " - " + string + "\n").data(using: .utf8) else { return }
|
||||
|
||||
loggerQueue.async {
|
||||
let fileManager = FileManager.default
|
||||
|
||||
if !fileManager.fileExists(atPath: logFileURL.path) {
|
||||
// Clean up older logs
|
||||
self.deleteLogs()
|
||||
// Create file atomically
|
||||
try? data.write(to: logFileURL, options: .atomicWrite)
|
||||
return
|
||||
}
|
||||
|
||||
// Atomic append with file locking using FileHandle
|
||||
do {
|
||||
let fileHandle = try FileHandle(forWritingTo: logFileURL)
|
||||
defer { try? fileHandle.close() }
|
||||
|
||||
// Locking is handled by the serial dispatch queue
|
||||
try fileHandle.seekToEnd()
|
||||
try fileHandle.write(contentsOf: data)
|
||||
} catch {
|
||||
print("[Logger] Failed to write to log file: \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Gets the contents of the log file.
|
||||
func getLogString() -> String {
|
||||
guard let logFileURL = logFileURL else { return "" }
|
||||
do {
|
||||
return try String(contentsOf: logFileURL, encoding: .utf8)
|
||||
} catch {
|
||||
log("[LUI] Error reading file: \(error.localizedDescription)")
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Deletes all log files in the shared container.
|
||||
func deleteLogs() {
|
||||
log("[LUI] Deleting all logs...")
|
||||
|
||||
guard let directory = getAppGroupDirectory() else { return }
|
||||
let fileManager = FileManager.default
|
||||
|
||||
guard let allFiles = try? fileManager.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) else {
|
||||
return
|
||||
}
|
||||
|
||||
let logFiles = allFiles.filter { $0.pathExtension == "log" }
|
||||
for file in logFiles {
|
||||
do {
|
||||
log("[LUI] Removing \(file.lastPathComponent)")
|
||||
try fileManager.removeItem(at: file)
|
||||
} catch {
|
||||
print("[Logger] Failed to delete file: \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Logs a specified string
|
||||
public func log(_ text: String) {
|
||||
let logger = LogManager.sharedInstance
|
||||
|
||||
if logger.loggingEnabled {
|
||||
loggerQueue.async {
|
||||
print(text)
|
||||
#if !os(tvOS)
|
||||
let isAppExtension = Bundle.main.bundlePath.hasSuffix(".appex")
|
||||
let prefix = isAppExtension ? "[EXT]" : "[APP]"
|
||||
logger.writeToFile(string: "\(prefix) \(text)")
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Returns the shared App Group directory
|
||||
fileprivate func getAppGroupDirectory() -> URL? {
|
||||
let groupIdentifier = "group.com.leonboettger.neardrop"
|
||||
return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: groupIdentifier)
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
//
|
||||
// SaveFilesManager.swift
|
||||
// QuickDrop
|
||||
//
|
||||
// Created by Leon Böttger on 26.07.25.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import AppKit
|
||||
import ImageIO
|
||||
|
||||
public class SaveFilesManager {
|
||||
|
||||
private init() {
|
||||
// remove old temp directory
|
||||
|
||||
let tempPath = FileManager.default.temporaryDirectory
|
||||
let fileManager = FileManager.default
|
||||
|
||||
do {
|
||||
let contents = try fileManager.contentsOfDirectory(at: tempPath, includingPropertiesForKeys: nil)
|
||||
|
||||
var didSomething = false
|
||||
|
||||
for item in contents {
|
||||
didSomething = true
|
||||
try fileManager.removeItem(at: item)
|
||||
}
|
||||
|
||||
if didSomething {
|
||||
log("Temporary directory cleared.")
|
||||
}
|
||||
} catch {
|
||||
log("Failed to list contents of temp directory: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
public static let shared = SaveFilesManager()
|
||||
|
||||
let tempDirectory: URL = FileManager.default.temporaryDirectory.appendingPathComponent("Pending")
|
||||
private var securityScopeUrl: URL?
|
||||
|
||||
private var filesFinishedDownloading = [URL]()
|
||||
private var filesFinishedDownloadingSinceLastRun = [URL]()
|
||||
|
||||
|
||||
public func registerFileFinishedDownloading(_ fileURL: URL) {
|
||||
filesFinishedDownloading.append(fileURL)
|
||||
filesFinishedDownloadingSinceLastRun.append(fileURL)
|
||||
|
||||
// read out EXIF timestamp and manually set file creation date to it
|
||||
applyEXIFTimestamps(at: fileURL)
|
||||
}
|
||||
|
||||
|
||||
public func movePendingFilesToTarget() {
|
||||
|
||||
if isPlusVersion() {
|
||||
do {
|
||||
let fileManager = FileManager.default
|
||||
let files = try fileManager.contentsOfDirectory(at: tempDirectory, includingPropertiesForKeys: nil)
|
||||
|
||||
let target = getSaveDirectory()
|
||||
var loggedExecution = false
|
||||
|
||||
for file in files {
|
||||
|
||||
if !loggedExecution {
|
||||
log("Moving pending files to target directory")
|
||||
loggedExecution = true
|
||||
}
|
||||
|
||||
let fileName = file.lastPathComponent
|
||||
let destinationURL = target.appendingPathComponent(fileName)
|
||||
|
||||
if !filesFinishedDownloading.contains(destinationURL) {
|
||||
log("File \(file) not finished downloading, skipping")
|
||||
continue
|
||||
}
|
||||
|
||||
log("Moving file: \(file.lastPathComponent) to \(destinationURL.lastPathComponent)")
|
||||
|
||||
do {
|
||||
try fileManager.copyItem(at: file, to: destinationURL)
|
||||
|
||||
let progress = Progress()
|
||||
progress.fileURL = destinationURL
|
||||
progress.totalUnitCount = 10
|
||||
progress.kind = .file
|
||||
progress.isPausable = false
|
||||
progress.publish()
|
||||
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
|
||||
progress.completedUnitCount = 10
|
||||
progress.unpublish()
|
||||
}
|
||||
|
||||
try fileManager.removeItem(at: file)
|
||||
}
|
||||
catch {
|
||||
log("Error moving file: \(error)")
|
||||
}
|
||||
}
|
||||
log("Moved all pending files to target directory")
|
||||
}
|
||||
catch {
|
||||
// Pending directory doesn't exist or is empty
|
||||
}
|
||||
}
|
||||
|
||||
if !filesFinishedDownloadingSinceLastRun.isEmpty && !isFileTransferRestricted() {
|
||||
|
||||
if UserDefaults.standard.bool(forKey: UserDefaultsKeys.openFinderAfterReceiving.rawValue) {
|
||||
log("Opening \(filesFinishedDownloadingSinceLastRun.count) file(s) in Finder.")
|
||||
NSWorkspace.shared.activateFileViewerSelecting(filesFinishedDownloadingSinceLastRun)
|
||||
}
|
||||
|
||||
// Clear the list of finished files
|
||||
filesFinishedDownloadingSinceLastRun.removeAll()
|
||||
}
|
||||
|
||||
stopAccessingSecurityScopedResource()
|
||||
}
|
||||
|
||||
|
||||
public func stopAccessingSecurityScopedResource() {
|
||||
guard let url = securityScopeUrl else {
|
||||
return
|
||||
}
|
||||
|
||||
log("Stopping access to security scoped resource: \(url)")
|
||||
url.stopAccessingSecurityScopedResource()
|
||||
securityScopeUrl = nil
|
||||
}
|
||||
|
||||
|
||||
public func getSaveDirectory() -> URL {
|
||||
if let securityScopeUrl = securityScopeUrl {
|
||||
log("Using existing security scope URL: \(securityScopeUrl)")
|
||||
return securityScopeUrl
|
||||
}
|
||||
|
||||
if let bookmarkData = UserDefaults.standard.data(forKey: UserDefaultsKeys.saveFolderBookmark.rawValue) {
|
||||
var isStale = false
|
||||
|
||||
do {
|
||||
let url = try URL(resolvingBookmarkData: bookmarkData, options: .withSecurityScope, relativeTo: nil, bookmarkDataIsStale: &isStale)
|
||||
|
||||
if !isStale {
|
||||
if url.startAccessingSecurityScopedResource() {
|
||||
log("Successfully accessed security scoped resource: \(url)")
|
||||
|
||||
securityScopeUrl = url
|
||||
return url
|
||||
}
|
||||
} else {
|
||||
log("Bookmark is stale, using default downloads folder.")
|
||||
}
|
||||
|
||||
} catch {
|
||||
log("Failed to resolve bookmark: \(error), using default downloads folder.")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
return try FileManager.default.url(for: .downloadsDirectory, in: .userDomainMask, appropriateFor: nil, create: true).resolvingSymlinksInPath()
|
||||
} catch {
|
||||
fatalError("Failed to get downloads directory: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Returns the EXIF original date of an image file, adjusted to the current time zone.
|
||||
private func exifOriginalDate(from url: URL) -> Date? {
|
||||
guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, nil),
|
||||
let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? [CFString: Any],
|
||||
let exif = properties[kCGImagePropertyExifDictionary] as? [CFString: Any],
|
||||
let dateString = exif[kCGImagePropertyExifDateTimeOriginal] as? String
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "yyyy:MM:dd HH:mm:ss"
|
||||
formatter.timeZone = TimeZone.current // Use the current device time zone
|
||||
return formatter.date(from: dateString)
|
||||
}
|
||||
|
||||
|
||||
/// Applies EXIF timestamps to a given file or directory.
|
||||
private func applyEXIFTimestamps(at url: URL) {
|
||||
let fm = FileManager.default
|
||||
var isDir: ObjCBool = false
|
||||
guard fm.fileExists(atPath: url.path, isDirectory: &isDir) else { return }
|
||||
|
||||
if isDir.boolValue {
|
||||
// It's a directory — enumerate files
|
||||
if let enumerator = fm.enumerator(at: url, includingPropertiesForKeys: [.isRegularFileKey]) {
|
||||
for case let fileURL as URL in enumerator {
|
||||
guard (try? fileURL.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile == true else { continue }
|
||||
applyEXIFTimestamp(to: fileURL)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// It's a single file
|
||||
applyEXIFTimestamp(to: url)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Applies EXIF timestamp (if available) to a single file
|
||||
private func applyEXIFTimestamp(to fileURL: URL) {
|
||||
guard let exifDate = exifOriginalDate(from: fileURL) else {
|
||||
return
|
||||
}
|
||||
|
||||
// Set the "creation date"
|
||||
try? FileManager.default.setAttributes([.creationDate: exifDate], ofItemAtPath: fileURL.path)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//
|
||||
// SleepManager.swift
|
||||
// QuickDrop
|
||||
//
|
||||
// Created by Leon Böttger on 03.05.25.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import IOKit
|
||||
import IOKit.pwr_mgt
|
||||
|
||||
class SleepManager {
|
||||
public static let shared = SleepManager()
|
||||
private var assertionID: IOPMAssertionID = 0
|
||||
private var timer: Timer?
|
||||
|
||||
private init() {
|
||||
// Start periodic check
|
||||
timer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { [weak self] _ in
|
||||
self?.updateSleepState()
|
||||
}
|
||||
|
||||
RunLoop.main.add(timer!, forMode: .common)
|
||||
}
|
||||
|
||||
private func disableSleep() {
|
||||
if assertionID != 0 {
|
||||
return
|
||||
}
|
||||
|
||||
log("[SleepManager] Enabling Wakelock")
|
||||
|
||||
IOPMAssertionCreateWithName(
|
||||
kIOPMAssertionTypePreventUserIdleDisplaySleep as CFString,
|
||||
IOPMAssertionLevel(kIOPMAssertionLevelOn),
|
||||
"QuickDrop Data Transfer" as CFString,
|
||||
&assertionID
|
||||
)
|
||||
}
|
||||
|
||||
private func enableSleep() {
|
||||
if assertionID == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
log("[SleepManager] Disabling Wakelock")
|
||||
IOPMAssertionRelease(assertionID)
|
||||
assertionID = 0
|
||||
}
|
||||
|
||||
private func updateSleepState() {
|
||||
let activeConnections = NearbyConnectionManager.shared.getActiveConnectionsCount()
|
||||
if activeConnections > 0 {
|
||||
disableSleep()
|
||||
} else {
|
||||
enableSleep()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user