AirAcceptConfig.swift 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import Foundation
  2. public struct AirAcceptConfig: Codable, Equatable, Sendable {
  3. public static let defaultPollIntervalMilliseconds = 2_500
  4. public var pollIntervalMilliseconds: Int
  5. public init(
  6. pollIntervalMilliseconds: Int = Self.defaultPollIntervalMilliseconds
  7. ) {
  8. self.pollIntervalMilliseconds = pollIntervalMilliseconds
  9. }
  10. private enum CodingKeys: String, CodingKey {
  11. case pollIntervalMilliseconds = "poll_interval_ms"
  12. }
  13. public init(from decoder: Decoder) throws {
  14. let container = try decoder.container(keyedBy: CodingKeys.self)
  15. self.pollIntervalMilliseconds = try container.decodeIfPresent(
  16. Int.self,
  17. forKey: .pollIntervalMilliseconds
  18. ) ?? Self.defaultPollIntervalMilliseconds
  19. }
  20. }
  21. public final class ConfigStore {
  22. public let configURL: URL
  23. private let fileManager: FileManager
  24. public init(
  25. configURL: URL = ConfigStore.defaultConfigURL(),
  26. fileManager: FileManager = .default
  27. ) {
  28. self.configURL = configURL
  29. self.fileManager = fileManager
  30. }
  31. public static func defaultConfigURL() -> URL {
  32. let baseURL = FileManager.default.homeDirectoryForCurrentUser
  33. .appendingPathComponent("Library/Application Support/AirAccept", isDirectory: true)
  34. return baseURL.appendingPathComponent("config.json", isDirectory: false)
  35. }
  36. public func loadOrCreate() throws -> AirAcceptConfig {
  37. if !fileManager.fileExists(atPath: configURL.path) {
  38. let config = AirAcceptConfig()
  39. try save(config)
  40. return config
  41. }
  42. let data = try Data(contentsOf: configURL)
  43. var config = try JSONDecoder().decode(AirAcceptConfig.self, from: data)
  44. var shouldSave = false
  45. if config.pollIntervalMilliseconds == 1_000 {
  46. config.pollIntervalMilliseconds = AirAcceptConfig.defaultPollIntervalMilliseconds
  47. shouldSave = true
  48. }
  49. if
  50. let rawConfig = String(data: data, encoding: .utf8),
  51. rawConfig.contains("dry_run") || rawConfig.contains("fallback_click_visible_airplay_banner")
  52. {
  53. shouldSave = true
  54. }
  55. if shouldSave {
  56. try save(config)
  57. }
  58. return config
  59. }
  60. public func save(_ config: AirAcceptConfig) throws {
  61. try fileManager.createDirectory(
  62. at: configURL.deletingLastPathComponent(),
  63. withIntermediateDirectories: true
  64. )
  65. let encoder = JSONEncoder()
  66. encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
  67. let data = try encoder.encode(config)
  68. try data.write(to: configURL, options: [.atomic])
  69. }
  70. }