-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathReaderPostParser.swift
More file actions
199 lines (172 loc) · 7.19 KB
/
Copy pathReaderPostParser.swift
File metadata and controls
199 lines (172 loc) · 7.19 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
import Foundation
import SwiftSoup
public enum ReaderPostParser {
public enum InteractiveElement: Sendable {
case gallery(Gallery)
case mention(Mention)
}
public struct Mention: Sendable {
public let handle: String
public let url: URL
}
public struct Gallery: Sendable {
public let images: [GalleryImage]
}
public struct GalleryImage: Sendable {
/// URL from the `src` attribute (displayed, possibly resized).
public let src: URL
/// Full-resolution URL from `data-orig-file`.
public let originalFileURL: URL?
/// Original dimensions from `data-orig-size` (e.g. "4032,3024").
public let originalSize: CGSize?
/// All srcset variants with their width descriptors.
public let srcset: [SrcsetEntry]
/// From `data-image-description`.
public let description: String?
/// From `data-image-caption`.
public let caption: String?
/// Returns the srcset URL that best fills a square of `maxDimension` pixels.
///
/// Uses `originalSize` to account for aspect ratio: for a landscape image
/// the width already matches the larger side, but for a portrait image the
/// required width is scaled up so the *height* fills `maxDimension`.
/// Falls back to the largest available entry if nothing is big enough.
///
/// - Parameter maxDimension: The target size of the larger side, in **pixels**.
/// - Returns: The best matching URL, or `nil` when `srcset` is empty.
public func bestURL(maxDimension: Int) -> URL? {
guard !srcset.isEmpty else { return nil }
// Compute the width needed so the larger side >= maxDimension.
var requiredWidth = maxDimension
if let originalSize, originalSize.height > originalSize.width {
// Portrait: we need a wider image so height fills maxDimension.
requiredWidth = Int(ceil(Double(maxDimension) * originalSize.width / originalSize.height))
}
let sorted = srcset.sorted { $0.width < $1.width }
return (sorted.first { $0.width >= requiredWidth } ?? sorted.last)?.url
}
}
public struct SrcsetEntry: Sendable {
public let url: URL
public let width: Int
}
/// Parses post HTML and returns interactive elements.
public static func parse(_ html: String) -> [InteractiveElement] {
guard let document = try? SwiftSoup.parse(html) else {
return []
}
var elements: [InteractiveElement] = []
if let anchors = try? document.select("a[data-type=fragment-mention][data-username][href]") {
elements.append(contentsOf: anchors.compactMap(parseMention(from:)).map(InteractiveElement.mention))
}
// Supported gallery selectors (order matters for specificity)
let selectors = [
"figure.wp-block-gallery",
"div.wp-block-gallery",
"figure.wp-block-jetpack-tiled-gallery",
"div.wp-block-jetpack-tiled-gallery",
"div.tiled-gallery",
"div.gallery"
]
for selector in selectors {
guard let containers = try? document.select(selector) else { continue }
for container in containers {
let images = parseImages(from: container)
if !images.isEmpty {
elements.append(.gallery(Gallery(images: images)))
}
// Remove the container so nested galleries aren't matched again
try? container.remove()
}
}
return elements
}
private static func parseMention(from anchor: Element) -> Mention? {
guard let handle = try? anchor.attr("data-username").trimmingCharacters(in: .whitespacesAndNewlines),
!handle.isEmpty,
let href = try? anchor.attr("href"),
!href.isEmpty,
let url = URL(string: href),
let scheme = url.scheme?.lowercased(),
scheme == "http" || scheme == "https"
else {
return nil
}
return Mention(handle: handle, url: url)
}
private static func parseImages(from container: Element) -> [GalleryImage] {
guard let imgElements = try? container.select("img") else {
return []
}
return imgElements.compactMap { parseImage(from: $0) }
}
private static func parseImage(from img: Element) -> GalleryImage? {
guard let srcString = try? img.attr("src"),
!srcString.isEmpty,
let src = URL(string: srcString)
else {
return nil
}
let originalFileURL: URL? = {
guard let value = try? img.attr("data-orig-file"), !value.isEmpty else { return nil }
return URL(string: value)
}()
let originalSize: CGSize? = {
guard let value = try? img.attr("data-orig-size"), !value.isEmpty else { return nil }
return parseSize(value)
}()
let srcset: [SrcsetEntry] = {
guard let value = try? img.attr("srcset"), !value.isEmpty else { return [] }
return parseSrcset(value)
}()
let description: String? = {
guard let value = try? img.attr("data-image-description"), !value.isEmpty else { return nil }
// Strip HTML tags from description
return try? SwiftSoup.clean(value, Whitelist.none())
}()
let caption: String? = {
guard let value = try? img.attr("data-image-caption"), !value.isEmpty else { return nil }
// Strip HTML tags from caption
return try? SwiftSoup.clean(value, Whitelist.none())
}()
return GalleryImage(
src: src,
originalFileURL: originalFileURL,
originalSize: originalSize,
srcset: srcset,
description: description,
caption: caption
)
}
/// Parses "W,H" format (e.g. "4032,3024") into CGSize.
private static func parseSize(_ value: String) -> CGSize? {
let parts = value.split(separator: ",")
guard parts.count == 2,
let width = Double(parts[0].trimmingCharacters(in: .whitespaces)),
let height = Double(parts[1].trimmingCharacters(in: .whitespaces))
else {
return nil
}
return CGSize(width: width, height: height)
}
/// Parses srcset string (e.g. "url1 300w, url2 600w") into entries.
private static func parseSrcset(_ value: String) -> [SrcsetEntry] {
value.split(separator: ",")
.compactMap { entry in
let parts = entry.trimmingCharacters(in: .whitespaces).split(separator: " ")
guard parts.count == 2,
let url = URL(string: String(parts[0])),
let widthStr = parts[1].dropLast().description.nilIfEmpty,
let width = Int(widthStr)
else {
return nil
}
return SrcsetEntry(url: url, width: width)
}
}
}
private extension String {
var nilIfEmpty: String? {
isEmpty ? nil : self
}
}