PrivacyPolicy.swift 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. import Foundation
  2. protocol PrivacyPolicyFetching: Sendable {
  3. func fetchPolicy() async throws -> String
  4. }
  5. struct PrivacyPolicyClient: PrivacyPolicyFetching {
  6. enum PolicyError: Error { case invalidURL, invalidText }
  7. let url: URL?
  8. let transport: DataTransport
  9. init(url: URL?, session: URLSession? = nil) {
  10. self.url = url
  11. transport = NetworkClient(session: session, allowedHTTPHosts: url?.scheme == "http" ? Set([url?.host].compactMap { $0 }) : [])
  12. }
  13. static func fromBundle(_ bundle: Bundle = .main) -> Self {
  14. let url = (bundle.object(forInfoDictionaryKey: "PrivacyPolicyURL") as? String).flatMap(ActivityURL.parse)
  15. return Self(url: url)
  16. }
  17. func fetchPolicy() async throws -> String {
  18. guard let url, ActivityURL.parse(url.absoluteString) != nil else { throw PolicyError.invalidURL }
  19. var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
  20. request.httpMethod = "GET"
  21. request.setValue("text/markdown, text/plain;q=0.9", forHTTPHeaderField: "Accept")
  22. let data = try await transport.execute(request)
  23. guard let text = String(data: data, encoding: .utf8) else { throw PolicyError.invalidText }
  24. return text
  25. }
  26. }