Files
duooomi-ios-sdk/Sources/DuooomiBleSDK/Services/AniConverter.swift
2026-04-10 16:15:53 +08:00

79 lines
2.6 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Foundation
struct AniConverterError: LocalizedError {
let message: String
var errorDescription: String? { message }
}
/// / ANI
final class AniConverter {
private let config: DuooomiBleConfig
private var endpoint: URL {
config.apiHost.appendingPathComponent("api/auth/loomart/file/convert-to-ani")
}
private let session: URLSession = {
let cfg = URLSessionConfiguration.default
cfg.timeoutIntervalForRequest = 120
cfg.timeoutIntervalForResource = 180
cfg.waitsForConnectivity = true
return URLSession(configuration: cfg)
}()
init(config: DuooomiBleConfig) {
self.config = config
}
/// ANI ani CDN URL
func convert(fileUrl: String) async throws -> String {
do {
return try await performConvert(fileUrl: fileUrl)
} catch let error as NSError where error.code == NSURLErrorNetworkConnectionLost {
return try await performConvert(fileUrl: fileUrl)
}
}
private func performConvert(fileUrl: String) async throws -> String {
var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "content-type")
request.setValue(config.apiKey, forHTTPHeaderField: "x-api-key")
request.timeoutInterval = 120
let body: [String: Any] = [
"videoUrl": fileUrl,
"width": 360,
"height": 360,
"fps": "24",
]
request.httpBody = try JSONSerialization.data(withJSONObject: body)
let (data, response) = try await session.data(for: request)
if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) {
throw AniConverterError(message: "HTTP \(http.statusCode)")
}
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
throw AniConverterError(message: "Invalid JSON response")
}
guard (json["success"] as? Bool) == true,
let outer = json["data"] as? [String: Any] else {
throw AniConverterError(message: "ANI API reported failure")
}
if (outer["status"] as? Bool) != true {
let msg = (outer["msg"] as? String) ?? "ANI conversion failed"
throw AniConverterError(message: msg)
}
guard let aniUrl = outer["data"] as? String, !aniUrl.isEmpty else {
throw AniConverterError(message: "Missing ani url in response")
}
return aniUrl
}
}