forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebLoader.swift
More file actions
239 lines (212 loc) · 7.71 KB
/
WebLoader.swift
File metadata and controls
239 lines (212 loc) · 7.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import Foundation
import Logger
import SwiftSoup
import WebKit
/// Load the body of a web page.
public struct WebLoader: DocumentLoader {
enum MetadataKeys {
static let title = "title"
static let url = "url"
static let date = "date"
}
var downloadHTML: (_ url: URL, _ strategy: LoadWebPageMainContentStrategy) async throws
-> (url: URL, html: String, strategy: LoadWebPageMainContentStrategy) = { url, strategy in
let html = try await WebScrapper(strategy: strategy).fetch(url: url)
return (url, html, strategy)
}
public var urls: [URL]
public init(urls: [URL]) {
self.urls = urls
}
public init(url: URL) {
urls = [url]
}
public func load() async throws -> [Document] {
try await withThrowingTaskGroup(of: (
url: URL,
html: String,
strategy: LoadWebPageMainContentStrategy
).self) { group in
for url in urls {
let strategy: LoadWebPageMainContentStrategy = {
switch url {
case let url
where url.absoluteString.contains("developer.apple.com/documentation"):
return Developer_Apple_Documentation_LoadContentStrategy()
default:
return DefaultLoadContentStrategy()
}
}()
group.addTask {
try await downloadHTML(url, strategy)
}
}
var documents: [Document] = []
for try await result in group {
do {
let parsed = try SwiftSoup.parse(result.html, result.url.path)
let title = (try? parsed.title()) ?? "Untitled"
let parsedDocuments = try result.strategy.load(
parsed,
metadata: [
MetadataKeys.title: .string(title),
MetadataKeys.url: .string(result.url.absoluteString),
MetadataKeys.date: .number(Date().timeIntervalSince1970),
]
)
documents.append(contentsOf: parsedDocuments)
} catch let Exception.Error(_, message) {
Logger.langchain.error(message)
} catch {
Logger.langchain.error(error.localizedDescription)
}
}
return documents
}
}
}
// MARK: - WebScrapper
@MainActor
public final class WebScrapper: NSObject, WKNavigationDelegate {
public var webView: WKWebView
let strategy: LoadWebPageMainContentStrategy
let retryLimit: Int
var webViewDidFinishLoading = false
var navigationError: (any Error)?
enum WebScrapperError: Error {
case retry
}
init(
retryLimit: Int = 10,
strategy: LoadWebPageMainContentStrategy
) {
self.retryLimit = retryLimit
self.strategy = strategy
let configuration = WKWebViewConfiguration()
configuration.defaultWebpagePreferences.preferredContentMode = .desktop
configuration.defaultWebpagePreferences.allowsContentJavaScript = true
configuration
.applicationNameForUserAgent =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Safari/605.1.15"
// The web page need the web view to have a size to load correctly.
let webView = WKWebView(
frame: .init(x: 0, y: 0, width: 500, height: 500),
configuration: configuration
)
self.webView = webView
super.init()
webView.navigationDelegate = self
}
func fetch(url: URL) async throws -> String {
webViewDidFinishLoading = false
navigationError = nil
var retryCount = 0
_ = webView.load(.init(url: url))
while !webViewDidFinishLoading {
try await Task.sleep(nanoseconds: 10_000_000)
}
if let navigationError { throw navigationError }
while retryCount < retryLimit {
if let html = try? await getHTML(), !html.isEmpty,
let document = try? SwiftSoup.parse(html, url.path),
strategy.validate(document)
{
return html
}
retryCount += 1
try await Task.sleep(nanoseconds: 100_000_000)
}
throw CancellationError()
}
public nonisolated func webView(_: WKWebView, didFinish _: WKNavigation!) {
Task { @MainActor in
self.webViewDidFinishLoading = true
}
}
public nonisolated func webView(
_: WKWebView,
didFail _: WKNavigation!,
withError error: Error
) {
Task { @MainActor in
self.navigationError = error
self.webViewDidFinishLoading = true
}
}
func getHTML() async throws -> String {
do {
let isReady = try await webView.evaluateJavaScript(checkIfReady) as? Bool ?? false
if !isReady { throw WebScrapperError.retry }
return try await webView.evaluateJavaScript(getHTMLText) as? String ?? ""
} catch {
throw WebScrapperError.retry
}
}
}
private let getHTMLText = """
document.documentElement.outerHTML;
"""
private let checkIfReady = """
document.readyState === "ready" || document.readyState === "complete";
"""
// MARK: - LoadWebPageMainContentStrategy
protocol LoadWebPageMainContentStrategy {
/// Load the web content into several documents.
func load(_ document: SwiftSoup.Document, metadata: Document.Metadata) throws -> [Document]
/// Validate if the web page is fully loaded.
func validate(_ document: SwiftSoup.Document) -> Bool
}
extension LoadWebPageMainContentStrategy {
func text(inFirstTag tagName: String, from document: SwiftSoup.Document) -> String? {
if let tag = try? document.getElementsByTag(tagName).first(),
let text = try? tag.text()
{
return text
}
return nil
}
}
extension WebLoader {
struct DefaultLoadContentStrategy: LoadWebPageMainContentStrategy {
func load(
_ document: SwiftSoup.Document,
metadata: Document.Metadata
) throws -> [Document] {
if let mainContent = try? {
if let article = text(inFirstTag: "article", from: document) { return article }
if let main = text(inFirstTag: "main", from: document) { return main }
let body = try document.body()?.text()
return body
}() {
return [.init(pageContent: mainContent, metadata: metadata)]
}
return []
}
func validate(_: SwiftSoup.Document) -> Bool {
return true
}
}
/// https://developer.apple.com/documentation
struct Developer_Apple_Documentation_LoadContentStrategy: LoadWebPageMainContentStrategy {
func load(
_ document: SwiftSoup.Document,
metadata: Document.Metadata
) throws -> [Document] {
if let mainContent = try? {
if let main = text(inFirstTag: "main", from: document) { return main }
let body = try document.body()?.text()
return body
}() {
return [.init(pageContent: mainContent, metadata: metadata)]
}
return []
}
func validate(_ document: SwiftSoup.Document) -> Bool {
do {
return !(try document.getElementsByTag("main").isEmpty())
} catch {
return false
}
}
}
}