Gemini/GeminiIntents/MakeRequestIntentHandler.swift

78 lines
3.3 KiB
Swift

//
// MakeRequestIntentHandler.swift
// GeminiIntents
//
// Created by Shadowfacts on 9/30/21.
//
import Intents
import GeminiProtocol
import BrowserCore
class MakeRequestIntentHandler: NSObject, MakeRequestIntentHandling {
private var task: GeminiDataTask?
func resolveUrl(for intent: MakeRequestIntent, with completion: @escaping (INURLResolutionResult) -> Void) {
guard let url = intent.url,
url.scheme?.lowercased() == "gemini" else {
completion(.unsupported())
return
}
completion(.success(with: url))
}
func handle(intent: MakeRequestIntent, completion: @escaping (MakeRequestIntentResponse) -> Void) {
guard let url = intent.url else {
completion(MakeRequestIntentResponse(code: .failure, userActivity: nil))
return
}
makeRequest(for: url, followRedirects: intent.followRedirects?.boolValue ?? true, completion: completion)
}
private func makeRequest(for url: URL, followRedirects: Bool, completion: @escaping (MakeRequestIntentResponse) -> Void) {
guard let request = try? GeminiRequest(url: url) else {
completion(MakeRequestIntentResponse(code: .failure, userActivity: nil))
return
}
// foo(bar(baz))
// a
task = GeminiDataTask(request: request) { [unowned self] (result) in
switch result {
case let .success(response):
if response.status.isRedirect && followRedirects {
if let newURL = URL(string: response.meta, relativeTo: url) {
self.makeRequest(for: newURL, followRedirects: followRedirects, completion: completion)
} else {
completion(MakeRequestIntentResponse(code: .failure, userActivity: nil))
}
} else {
let intentResp = MakeRequestIntentResponse(code: .success, userActivity: nil)
let displayStr = "\(response.status), \(BrowserHelper.urlForDisplay(url)), '\(response.meta)'"
intentResp.response = Response(identifier: url.absoluteString, display: displayStr)
intentResp.response!.url = url
intentResp.response!.body = response.bodyText
intentResp.response!.status = ResponseStatus(rawValue: response.status.rawValue)!
intentResp.response!.meta = response.meta
// intentResp.status = ResponseStatus(rawValue: response.status.rawValue)!
// intentResp.status = NSNumber(integerLiteral: response.status.rawValue)
// intentResp.statusCategory = ResponseStatusCategory(rawValue: response.status.rawValue / 10)!
// intentResp.meta = response.meta
// intentResp.mimeType = response.mimeType
// intentResp.body = response.bodyText
completion(intentResp)
}
case .failure(_):
completion(MakeRequestIntentResponse(code: .failure, userActivity: nil))
}
}
if #available(iOS 15.0, *) {
task!.attribution = .user
}
task!.resume()
}
}