AirPlayPromptWatcher.swift 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. import AirAcceptCore
  2. import AppKit
  3. import ApplicationServices
  4. import Foundation
  5. @MainActor
  6. final class AirPlayPromptWatcher {
  7. private let configStore: ConfigStore
  8. private let logger: AirAcceptLogger
  9. private var timer: Timer?
  10. private var handledFingerprints: [String: Date] = [:]
  11. private var enabled = true
  12. private var lastTrustedState: Bool?
  13. init(configStore: ConfigStore, logger: AirAcceptLogger) {
  14. self.configStore = configStore
  15. self.logger = logger
  16. }
  17. var isEnabled: Bool {
  18. enabled
  19. }
  20. func setEnabled(_ enabled: Bool) {
  21. self.enabled = enabled
  22. if enabled {
  23. start()
  24. } else {
  25. stop()
  26. }
  27. }
  28. func start() {
  29. guard enabled else {
  30. return
  31. }
  32. if updateTrustedState(prompt: true) {
  33. scanOnce()
  34. } else {
  35. logger.info("Accessibility permission is not granted yet")
  36. }
  37. let interval = currentPollInterval()
  38. scheduleTimer(interval: interval)
  39. logger.info("watcher started with poll interval \(interval)s")
  40. }
  41. func stop() {
  42. timer?.invalidate()
  43. timer = nil
  44. logger.info("watcher stopped")
  45. }
  46. func scanOnce() {
  47. guard enabled, updateTrustedState(prompt: false) else {
  48. return
  49. }
  50. guard let result = AccessibilityReader.notificationCenterCandidate() else {
  51. pruneHandledFingerprints()
  52. return
  53. }
  54. handle(result: result)
  55. pruneHandledFingerprints()
  56. }
  57. private func scheduleTimer(interval: TimeInterval) {
  58. timer?.invalidate()
  59. timer = Timer.scheduledTimer(withTimeInterval: max(interval, 0.25), repeats: true) { [weak self] _ in
  60. Task { @MainActor in
  61. self?.scanOnce()
  62. }
  63. }
  64. }
  65. private func currentPollInterval() -> TimeInterval {
  66. let config = (try? configStore.loadOrCreate()) ?? AirAcceptConfig()
  67. return TimeInterval(max(config.pollIntervalMilliseconds, 250)) / 1_000.0
  68. }
  69. private func updateTrustedState(prompt: Bool) -> Bool {
  70. let trusted = AccessibilityReader.isTrusted(prompt: prompt)
  71. if lastTrustedState != trusted {
  72. lastTrustedState = trusted
  73. logger.info("Accessibility permission is \(trusted ? "granted" : "not granted")")
  74. }
  75. return trusted
  76. }
  77. private func handle(result: PromptCandidateWithButton) {
  78. let fingerprint = "\(result.match.summary)|\(result.match.deviceName ?? "unknown")"
  79. guard handledFingerprints[fingerprint] == nil else {
  80. return
  81. }
  82. let axError = AccessibilityReader.press(result.acceptButton, actionName: result.acceptActionName)
  83. if axError == .success {
  84. handledFingerprints[fingerprint] = Date()
  85. logger.event(AirAcceptEvent(
  86. hostProcess: result.candidate.hostProcess,
  87. summary: result.match.summary,
  88. deviceName: result.match.deviceName,
  89. action: "accept",
  90. reason: "accepted matched AirPlay request"
  91. ))
  92. } else {
  93. logger.event(AirAcceptEvent(
  94. hostProcess: result.candidate.hostProcess,
  95. summary: result.match.summary,
  96. deviceName: result.match.deviceName,
  97. action: "error",
  98. reason: "failed to press Accept: \(axError.rawValue)"
  99. ))
  100. }
  101. }
  102. private func pruneHandledFingerprints() {
  103. let cutoff = Date().addingTimeInterval(-30)
  104. handledFingerprints = handledFingerprints.filter { $0.value > cutoff }
  105. }
  106. }