IceCubesApp/Packages/Network/Sources/Network/DeepLClient.swift

75 lines
2.3 KiB
Swift
Raw Normal View History

2023-01-21 08:58:38 +00:00
import Foundation
import Models
2023-01-21 08:58:38 +00:00
2024-01-26 12:01:23 +00:00
public struct DeepLClient: Sendable {
public enum DeepLError: Error {
case notFound
}
2023-02-12 15:29:41 +00:00
2023-03-14 17:50:19 +00:00
private var deeplUserAPIKey: String?
private var deeplUserAPIFree: Bool
private var endpoint: String {
"https://api\(deeplUserAPIFree && (deeplUserAPIKey != nil) ? "-free" : "").deepl.com/v2/translate"
}
2023-01-22 05:38:30 +00:00
2023-01-21 08:58:38 +00:00
private var APIKey: String {
2023-03-14 17:50:19 +00:00
if let deeplUserAPIKey {
return deeplUserAPIKey
}
2023-01-21 08:58:38 +00:00
if let path = Bundle.main.path(forResource: "Secret", ofType: "plist") {
let secret = NSDictionary(contentsOfFile: path)
return secret?["DEEPL_SECRET"] as? String ?? ""
}
return ""
}
2023-01-22 05:38:30 +00:00
2023-01-21 08:58:38 +00:00
private var authorizationHeaderValue: String {
"DeepL-Auth-Key \(APIKey)"
}
2023-01-22 05:38:30 +00:00
2023-01-21 08:58:38 +00:00
public struct Response: Decodable {
public struct Translation: Decodable {
public let detectedSourceLanguage: String
public let text: String
}
2023-01-22 05:38:30 +00:00
2023-01-21 08:58:38 +00:00
public let translations: [Translation]
}
2023-01-22 05:38:30 +00:00
2023-01-21 08:58:38 +00:00
private var decoder: JSONDecoder {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return decoder
}
2023-01-22 05:38:30 +00:00
2023-03-14 17:50:19 +00:00
public init(userAPIKey: String?, userAPIFree: Bool) {
deeplUserAPIKey = userAPIKey
deeplUserAPIFree = userAPIFree
}
2023-01-22 05:38:30 +00:00
public func request(target: String, text: String) async throws -> Translation {
2023-01-21 08:58:38 +00:00
do {
var components = URLComponents(string: endpoint)!
var queryItems: [URLQueryItem] = []
queryItems.append(.init(name: "text", value: text))
queryItems.append(.init(name: "target_lang", value: target.uppercased()))
components.queryItems = queryItems
var request = URLRequest(url: components.url!)
request.httpMethod = "POST"
request.setValue(authorizationHeaderValue, forHTTPHeaderField: "Authorization")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let (result, _) = try await URLSession.shared.data(for: request)
let response = try decoder.decode(Response.self, from: result)
if let translation = response.translations.first {
return .init(content: translation.text.removingPercentEncoding ?? "",
detectedSourceLanguage: translation.detectedSourceLanguage,
provider: "DeepL.com")
}
throw DeepLError.notFound
2023-01-21 08:58:38 +00:00
} catch {
throw error
}
}
}