Add web search and page retrieval to Toolbox
This commit is contained in:
+100
-16
@@ -112,27 +112,20 @@ enum WebClipCapture {
|
||||
}
|
||||
|
||||
static func text(from address: String) async throws -> String {
|
||||
let session = URLSession(configuration: .ephemeral)
|
||||
defer { session.invalidateAndCancel() }
|
||||
var request = URLRequest(url: try url(address), timeoutInterval: 20)
|
||||
request.setValue("text/html, text/plain", forHTTPHeaderField: "Accept")
|
||||
let (bytes, response) = try await session.bytes(for: request)
|
||||
guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode),
|
||||
let type = response.mimeType, ["text/html", "text/plain", "application/xhtml+xml"].contains(type) else {
|
||||
throw StudioError("The server did not return a supported text page.")
|
||||
}
|
||||
var data = Data()
|
||||
for try await byte in bytes {
|
||||
try Task.checkCancellation()
|
||||
guard data.count < 1_048_576 else { throw StudioError("The page exceeds the 1 MB capture limit.") }
|
||||
data.append(byte)
|
||||
}
|
||||
try await page(from: address).text
|
||||
}
|
||||
|
||||
static func page(from address: String) async throws -> WebPage {
|
||||
let types = ["text/html", "text/plain", "application/xhtml+xml"]
|
||||
let resource = try await WebFetch.load(try url(address), types: types)
|
||||
let data = resource.data
|
||||
let type = resource.type
|
||||
guard let raw = String(data: data, encoding: .utf8) else { throw StudioError("The page is not UTF-8.") }
|
||||
let content = type == "text/plain" ? raw : plainText(raw)
|
||||
guard !content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||
throw StudioError("The page contains no readable text.")
|
||||
}
|
||||
return String(content.prefix(12_000))
|
||||
return WebPage(url: resource.url, text: String(content.prefix(12_000)))
|
||||
}
|
||||
|
||||
static func plainText(_ html: String) -> String {
|
||||
@@ -152,3 +145,94 @@ enum WebClipCapture {
|
||||
.filter { !$0.isEmpty }.joined(separator: "\n")
|
||||
}
|
||||
}
|
||||
|
||||
struct WebPage {
|
||||
let url: URL
|
||||
let text: String
|
||||
var reference: String { "Source: \(url.absoluteString)\n\n\(text)" }
|
||||
}
|
||||
|
||||
enum WebFetch {
|
||||
static func load(_ url: URL, types: [String]) async throws -> (url: URL, type: String, data: Data) {
|
||||
let config = URLSessionConfiguration.ephemeral
|
||||
config.httpShouldSetCookies = false
|
||||
config.timeoutIntervalForResource = 35
|
||||
let session = URLSession(configuration: config)
|
||||
defer { session.invalidateAndCancel() }
|
||||
var request = URLRequest(url: url, timeoutInterval: 20)
|
||||
request.setValue(types.joined(separator: ", "), forHTTPHeaderField: "Accept")
|
||||
let (bytes, response) = try await session.bytes(for: request)
|
||||
guard let response = response as? HTTPURLResponse, let final = response.url else {
|
||||
throw StudioError("The server did not return an HTTP response.")
|
||||
}
|
||||
_ = try WebClipCapture.url(final.absoluteString)
|
||||
guard (200..<300).contains(response.statusCode) else {
|
||||
throw StudioError("The server returned HTTP \(response.statusCode).")
|
||||
}
|
||||
guard let type = response.mimeType, types.contains(type) else {
|
||||
throw StudioError("The server did not return the expected content type.")
|
||||
}
|
||||
var data = Data()
|
||||
for try await byte in bytes {
|
||||
try Task.checkCancellation()
|
||||
guard data.count < 1_048_576 else { throw StudioError("The response exceeds 1 MB.") }
|
||||
data.append(byte)
|
||||
}
|
||||
return (final, type, data)
|
||||
}
|
||||
}
|
||||
|
||||
struct WebSearchResult: Identifiable, Equatable {
|
||||
let url: URL
|
||||
let title: String
|
||||
let snippet: String
|
||||
var id: URL { url }
|
||||
|
||||
var reference: String { "\(title)\nSource: \(url.absoluteString)\n\(snippet)" }
|
||||
}
|
||||
|
||||
enum WebSearch {
|
||||
static func requestURL(endpoint: String, query: String) throws -> URL {
|
||||
let query = query.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !query.isEmpty, query.count <= 500 else {
|
||||
throw StudioError("Enter a search query of up to 500 characters.")
|
||||
}
|
||||
let base = try WebClipCapture.url(endpoint)
|
||||
guard var parts = URLComponents(url: base, resolvingAgainstBaseURL: false),
|
||||
parts.fragment == nil else { throw StudioError("Enter the SearXNG search URL without a fragment.") }
|
||||
var items = (parts.queryItems ?? []).filter { $0.name != "q" && $0.name != "format" }
|
||||
items += [.init(name: "q", value: query), .init(name: "format", value: "json")]
|
||||
parts.queryItems = items
|
||||
guard let url = parts.url else { throw StudioError("Could not prepare the search URL.") }
|
||||
return url
|
||||
}
|
||||
|
||||
static func results(endpoint: String, query: String) async throws -> [WebSearchResult] {
|
||||
let resource = try await WebFetch.load(try requestURL(endpoint: endpoint, query: query),
|
||||
types: ["application/json"])
|
||||
return try decode(resource.data)
|
||||
}
|
||||
|
||||
static func decode(_ data: Data) throws -> [WebSearchResult] {
|
||||
struct Response: Decodable {
|
||||
struct Item: Decodable {
|
||||
let url: String?
|
||||
let title: String?
|
||||
let content: String?
|
||||
}
|
||||
let results: [Item]
|
||||
}
|
||||
let response = try JSONDecoder().decode(Response.self, from: data)
|
||||
var seen: Set<URL> = []
|
||||
var output: [WebSearchResult] = []
|
||||
for item in response.results {
|
||||
guard let address = item.url, let url = try? WebClipCapture.url(address), seen.insert(url).inserted else { continue }
|
||||
let title = WebClipCapture.plainText(item.title ?? "")
|
||||
let snippet = WebClipCapture.plainText(item.content ?? "")
|
||||
output.append(WebSearchResult(url: url, title: title.isEmpty ? (url.host ?? "Web result") : String(title.prefix(180)),
|
||||
snippet: String(snippet.prefix(500))))
|
||||
if output.count == 10 { break }
|
||||
}
|
||||
return output
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user