-
Notifications
You must be signed in to change notification settings - Fork 117
/
OPDS1Parser.swift
483 lines (430 loc) · 17.8 KB
/
OPDS1Parser.swift
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//
// Copyright 2024 Readium Foundation. All rights reserved.
// Use of this source code is governed by the BSD-style license
// available in the top-level LICENSE file of the project.
//
import Foundation
import ReadiumFuzi
import ReadiumShared
public enum OPDS1ParserError: Error {
// The title is missing from the feed.
case missingTitle
// Root is not found
case rootNotFound
}
public enum OPDSParserOpenSearchHelperError: Error {
// Search link not found in feed
case searchLinkNotFound
// OpenSearch document is invalid
case searchDocumentIsInvalid
}
struct MimeTypeParameters {
var type: String
var parameters = [String: String]()
}
public class OPDS1Parser: Loggable {
static var feedURL: URL?
/// Parse an OPDS feed or publication.
/// Feed can only be v1 (XML).
/// - parameter url: The feed URL
public static func parseURL(url: URL, completion: @escaping (ParseData?, Error?) -> Void) {
feedURL = url
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, let response = response else {
completion(nil, error ?? OPDSParserError.documentNotFound)
return
}
do {
let parseData = try self.parse(xmlData: data, url: url, response: response)
completion(parseData, nil)
} catch {
completion(nil, error)
}
}.resume()
}
/// Parse an OPDS feed or publication.
/// Feed can only be v1 (XML).
/// - parameter xmlData: The xml raw data
/// - parameter url: The feed URL
/// - parameter response: The response payload
/// - Returns: The intermediate structure of type ParseData
public static func parse(xmlData: Data, url: URL, response: URLResponse) throws -> ParseData {
feedURL = url
var parseData = ParseData(url: url, response: response, version: .OPDS1)
let xmlDocument = try XMLDocument(data: xmlData)
if xmlDocument.root?.tag == "feed" {
// Feed
parseData.feed = try? parse(document: xmlDocument)
} else if xmlDocument.root?.tag == "entry" {
// Publication only
do {
parseData.publication = try parseEntry(document: xmlDocument)
} catch {
log(.warning, "Failed to parse Publication at \(url)")
}
} else {
throw OPDS1ParserError.rootNotFound
}
return parseData
}
/// Parse an OPDS feed.
/// Feed can only be v1 (XML).
/// - parameter document: The XMLDocument data
/// - Returns: The resulting Feed
public static func parse(document: ReadiumFuzi.XMLDocument) throws -> Feed {
document.definePrefix("thr", forNamespace: "http://purl.org/syndication/thread/1.0")
document.definePrefix("dcterms", forNamespace: "http://purl.org/dc/terms/")
document.definePrefix("opds", forNamespace: "http://opds-spec.org/2010/catalog")
guard let root = document.root else {
throw OPDS1ParserError.rootNotFound
}
guard let title = root.firstChild(tag: "title")?.stringValue else {
throw OPDS1ParserError.missingTitle
}
let feed = Feed(title: title)
if let tmpDate = root.firstChild(tag: "updated")?.stringValue,
let date = tmpDate.dateFromISO8601
{
feed.metadata.modified = date
}
if let totalResults = root.firstChild(tag: "TotalResults")?.stringValue {
feed.metadata.numberOfItem = Int(totalResults)
}
if let itemsPerPage = root.firstChild(tag: "ItemsPerPage")?.stringValue {
feed.metadata.itemsPerPage = Int(itemsPerPage)
}
for entry in root.children(tag: "entry") {
var isNavigation = true
var collectionLink: Link?
for link in entry.children(tag: "link") {
if let rel = link.attributes["rel"] {
// Check is navigation or acquisition.
if rel.range(of: "http://opds-spec.org/acquisition") != nil {
isNavigation = false
}
// Check if there is a collection.
if rel == "collection" || rel == "http://opds-spec.org/group",
let href = link.attributes["href"],
let absoluteHref = URLHelper.getAbsolute(href: href, base: feedURL)
{
collectionLink = Link(
href: absoluteHref,
title: link.attributes["title"],
rel: .collection
)
}
}
}
if !isNavigation {
if let publication = parseEntry(entry: entry) {
// Checking if this publication need to go into a group or in publications.
if let collectionLink = collectionLink {
addPublicationInGroup(feed, publication, collectionLink)
} else {
feed.publications.append(publication)
}
}
} else if let link = entry.firstChild(tag: "link"),
let href = link.attr("href"),
let absoluteHref = URLHelper.getAbsolute(href: href, base: feedURL)
{
var properties: [String: Any] = [:]
if let facetElementCount = link.attr("count").map(Int.init) {
properties["numberOfItems"] = facetElementCount
}
let newLink = Link(
href: absoluteHref,
mediaType: link.attr("type").flatMap { MediaType($0) },
title: entry.firstChild(tag: "title")?.stringValue,
rel: link.attr("rel").map { LinkRelation($0) },
properties: .init(properties)
)
// Check collection link
if let collectionLink = collectionLink {
addNavigationInGroup(feed, newLink, collectionLink)
} else {
feed.navigation.append(newLink)
}
}
}
for link in root.children(tag: "link") {
guard let href = link.attributes["href"], let absoluteHref = URLHelper.getAbsolute(href: href, base: feedURL) else {
continue
}
var rels: [LinkRelation] = []
if let rel = link.attributes["rel"], !rel.isEmpty {
rels.append(.init(rel))
}
var properties: [String: Any] = [:]
let isFacet = rels.contains(.opdsFacet)
if isFacet {
// Active Facet Check
if link.attr("activeFacet")?.lowercased() == "true" {
rels.append(.self)
}
if let facetElementCount = link.attr("count").map(Int.init) {
properties["numberOfItems"] = facetElementCount
}
}
let newLink = Link(
href: absoluteHref,
mediaType: link.attributes["type"].flatMap { MediaType($0) },
title: link.attributes["title"],
rels: rels,
properties: .init(properties)
)
if isFacet {
if let facetGroupName = link.attributes["facetGroup"] {
addFacet(feed: feed, to: newLink, named: facetGroupName)
}
} else {
feed.links.append(newLink)
}
}
return feed
}
/// Parse an OPDS publication.
/// Publication can only be v1 (XML).
/// - parameter document: The XMLDocument data
/// - Returns: The resulting Publication
public static func parseEntry(document: ReadiumFuzi.XMLDocument) throws -> Publication? {
guard let root = document.root else {
throw OPDS1ParserError.rootNotFound
}
return parseEntry(entry: root)
}
/// Fetch an Open Search template from an OPDS feed.
/// - parameter feed: The OPDS feed
public static func fetchOpenSearchTemplate(feed: Feed, completion: @escaping (String?, Error?) -> Void) {
guard let openSearchHref = feed.links.firstWithRel(.search)?.href,
let openSearchURL = URL(string: openSearchHref)
else {
completion(nil, OPDSParserOpenSearchHelperError.searchLinkNotFound)
return
}
URLSession.shared.dataTask(with: openSearchURL) { data, _, error in
guard let data = data else {
completion(nil, error ?? OPDSParserOpenSearchHelperError.searchDocumentIsInvalid)
return
}
guard let document = try? XMLDocument(data: data) else {
completion(nil, OPDSParserOpenSearchHelperError.searchDocumentIsInvalid)
return
}
guard let urls = document.root?.children(tag: "Url") else {
completion(nil, OPDSParserOpenSearchHelperError.searchDocumentIsInvalid)
return
}
if urls.count == 0 {
completion(nil, OPDSParserOpenSearchHelperError.searchDocumentIsInvalid)
return
}
// The OpenSearch document may contain multiple Urls, and we need to find the closest matching one.
// We match by mimetype and profile; if that fails, by mimetype; and if that fails, the first url is returned
var typeAndProfileMatch: ReadiumFuzi.XMLElement? = nil
var typeMatch: ReadiumFuzi.XMLElement? = nil
if let selfMimeType = feed.links.firstWithRel(.self)?.mediaType {
let selfMimeParams = parseMimeType(mimeTypeString: selfMimeType.string)
for url in urls {
guard let urlMimeType = url.attributes["type"] else {
continue
}
let otherMimeParams = parseMimeType(mimeTypeString: urlMimeType)
if selfMimeParams.type == otherMimeParams.type {
if typeMatch == nil {
typeMatch = url
}
if selfMimeParams.parameters["profile"] == otherMimeParams.parameters["profile"] {
typeAndProfileMatch = url
break
}
}
}
}
let match = typeAndProfileMatch ?? (typeMatch ?? urls[0])
guard let template = match.attributes["template"] else {
completion(nil, OPDSParserOpenSearchHelperError.searchDocumentIsInvalid)
return
}
completion(template, nil)
}.resume()
}
static func parseMimeType(mimeTypeString: String) -> MimeTypeParameters {
let substrings = mimeTypeString.split(separator: ";")
let type = String(substrings[0]).trimmingCharacters(in: .whitespaces)
var params = [String: String]()
for defn in substrings.dropFirst() {
let halves = defn.split(separator: "=")
let paramName = String(halves[0]).trimmingCharacters(in: .whitespaces)
let paramValue = String(halves[1]).trimmingCharacters(in: .whitespaces)
params[paramName] = paramValue
}
return MimeTypeParameters(type: type, parameters: params)
}
static func parseEntry(entry: ReadiumFuzi.XMLElement) -> Publication? {
// Shortcuts to get tag(s)' string value.
func tag(_ name: String) -> String? {
entry.firstChild(tag: name)?.stringValue
}
func tags(_ name: String) -> [String] {
entry.children(tag: name).map(\.stringValue)
}
guard let title = tag("title") else {
return nil
}
let authors: [Contributor] = entry.children(tag: "author").compactMap { author in
guard let name = author.firstChild(tag: "name")?.stringValue else {
return nil
}
return Contributor(
name: name,
identifier: author.firstChild(tag: "uri")?.stringValue
)
}
let subjects: [Subject] = entry.children(tag: "category").compactMap { category in
guard let name = category.attributes["label"] else {
return nil
}
return Subject(
name: name,
scheme: category.attributes["scheme"],
code: category.attributes["term"]
)
}
let metadata = Metadata(
identifier: tag("identifier") ?? tag("id"),
title: title,
modified: tag("updated")?.dateFromISO8601,
published: tag("published")?.dateFromISO8601,
languages: tags("language"),
subjects: subjects,
authors: authors,
publishers: tags("publisher").map { Contributor(name: $0) },
description: tag("content") ?? tag("summary"),
otherMetadata: [
"rights": tags("rights").joined(separator: " "),
]
)
// Links.
var images: [Link] = []
var links: [Link] = []
for linkElement in entry.children(tag: "link") {
guard let href = linkElement.attributes["href"], let absoluteHref = URLHelper.getAbsolute(href: href, base: feedURL) else {
continue
}
var properties: [String: Any] = [:]
if let price = parsePrice(link: linkElement)?.json, !price.isEmpty {
properties["price"] = price
}
let indirectAcquisition = parseIndirectAcquisition(children: linkElement.children(tag: "indirectAcquisition")).json
if !indirectAcquisition.isEmpty {
properties["indirectAcquisition"] = indirectAcquisition
}
let link = Link(
href: absoluteHref,
mediaType: linkElement.attributes["type"].flatMap { MediaType($0) },
title: linkElement.attributes["title"],
rel: linkElement.attributes["rel"].map { LinkRelation($0) },
properties: .init(properties)
)
let rels = link.rels
if rels.contains("collection") || rels.contains("http://opds-spec.org/group") {
// no-op
} else if rels.contains("http://opds-spec.org/image") || rels.contains("http://opds-spec.org/image-thumbnail") {
images.append(link)
} else {
links.append(link)
}
}
return Publication(
manifest: Manifest(
metadata: metadata,
links: links,
subcollections: [
"images": [PublicationCollection(links: images)],
]
)
)
}
static func addFacet(feed: Feed, to link: Link, named title: String) {
for facet in feed.facets {
if facet.metadata.title == title {
facet.links.append(link)
return
}
}
let newFacet = Facet(title: title)
newFacet.links.append(link)
feed.facets.append(newFacet)
}
static func addPublicationInGroup(_ feed: Feed,
_ publication: Publication,
_ collectionLink: Link)
{
for group in feed.groups {
for l in group.links {
if l.href == collectionLink.href {
group.publications.append(publication)
return
}
}
}
if let title = collectionLink.title {
let newGroup = Group(title: title)
let selfLink = Link(
href: collectionLink.href,
title: collectionLink.title,
rel: .self
)
newGroup.links.append(selfLink)
newGroup.publications.append(publication)
feed.groups.append(newGroup)
}
}
static func addNavigationInGroup(_ feed: Feed,
_ link: Link,
_ collectionLink: Link)
{
for group in feed.groups {
for l in group.links {
if l.href == collectionLink.href {
group.navigation.append(link)
return
}
}
}
if let title = collectionLink.title {
let newGroup = Group(title: title)
let selfLink = Link(
href: collectionLink.href,
title: collectionLink.title,
rel: .self
)
newGroup.links.append(selfLink)
newGroup.navigation.append(link)
feed.groups.append(newGroup)
}
}
static func parseIndirectAcquisition(children: [ReadiumFuzi.XMLElement]) -> [OPDSAcquisition] {
children.compactMap { child in
guard let type = child.attributes["type"] else {
return nil
}
var acquisition = OPDSAcquisition(type: type)
let grandChildren = child.children(tag: "indirectAcquisition")
if grandChildren.count > 0 {
acquisition.children = parseIndirectAcquisition(children: grandChildren)
}
return acquisition
}
}
static func parsePrice(link: ReadiumFuzi.XMLElement) -> OPDSPrice? {
guard let price = link.firstChild(tag: "price")?.stringValue,
let value = Double(price),
let currency = link.firstChild(tag: "price")?.attr("currencycode")
else {
return nil
}
return OPDSPrice(currency: currency, value: value)
}
}