import Cocoa @main class AppDelegate: NSObject, NSApplicationDelegate { var monitor: DispatchSourceFileSystemObject? let downloadsPath = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Downloads") func applicationDidFinishLaunching(_ aNotification: Notification) { print("πŸš€ App started β€” AppDelegate is running") startWatchingDownloadsFolder() } func startWatchingDownloadsFolder() { let fileDescriptor = open(downloadsPath.path, O_EVTONLY) guard fileDescriptor != -1 else { print("❌ Impossible d'ouvrir le dossier Downloads.") return } monitor = DispatchSource.makeFileSystemObjectSource( fileDescriptor: fileDescriptor, eventMask: .write, queue: DispatchQueue.global() ) monitor?.setEventHandler { [weak self] in self?.handleNewFile() } monitor?.setCancelHandler { close(fileDescriptor) } monitor?.resume() print("πŸ‘€ Watching folder") } func handleNewFile() { do { let fileURLs = try FileManager.default.contentsOfDirectory( at: downloadsPath, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles] ) var latestFileURL: URL? var latestCreationDate: Date? let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" for fileURL in fileURLs { if let attributes = try? FileManager.default.attributesOfItem(atPath: fileURL.path), let creationDate = attributes[.creationDate] as? Date { if latestCreationDate == nil || creationDate > latestCreationDate! { latestCreationDate = creationDate latestFileURL = fileURL } } } if let latestFileURL = latestFileURL { print("πŸ“Œ Nouveau fichier dΓ©tectΓ© : \\(latestFileURL.lastPathComponent)") let process = Process() process.executableURL = URL(fileURLWithPath: "/usr/bin/shortcuts") process.arguments = ["run", "lastDownloadToDropzone", "--input-path", latestFileURL.path] do { print("⚑ Running shortcut...") try process.run() process.waitUntilExit() } catch { print("❌ Erreur lors du lancement du raccourci : \\(error)") } } } catch { print("❌ Erreur lors de la lecture du dossier : \\(error)") } } }