-
Notifications
You must be signed in to change notification settings - Fork 1
/
WebPubParserProvider.kt
99 lines (86 loc) · 2.73 KB
/
WebPubParserProvider.kt
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
package org.librarysimplified.audiobook.manifest_parser.webpub
import one.irradia.fieldrush.api.FRParseResult
import one.irradia.fieldrush.vanilla.FRParsers
import org.librarysimplified.audiobook.manifest.api.PlayerManifest
import org.librarysimplified.audiobook.manifest_parser.api.ManifestParserProviderType
import org.librarysimplified.audiobook.manifest_parser.extension_spi.ManifestParserExtensionType
import org.librarysimplified.audiobook.parser.api.ParserType
import org.slf4j.LoggerFactory
import java.io.ByteArrayInputStream
import java.net.URI
/**
* Note: This class MUST have a no-argument public constructor in order to be used via
* java.util.ServiceLoader.
*/
class WebPubParserProvider : ManifestParserProviderType {
private val logger =
LoggerFactory.getLogger(WebPubParserProvider::class.java)
private val fieldRushParsers =
FRParsers()
private val contextTypes =
setOf(
"http://readium.org/webpub/default.jsonld",
"https://readium.org/webpub/default.jsonld",
"http://readium.org/webpub-manifest/context.jsonld",
"https://readium.org/webpub-manifest/context.jsonld",
)
private fun isRecognizedContextType(type: String): Boolean =
this.contextTypes.contains(type)
override val format: String =
WebPub.baseFormat
override fun canParse(
uri: URI,
input: ByteArray
): Boolean {
val contextParser =
this.fieldRushParsers.createParser(
uri = uri,
stream = ByteArrayInputStream(input),
rootParser = WebPubContextFinderParser()
)
return when (val parseResult = contextParser.parse()) {
is FRParseResult.FRParseSucceeded -> {
val receivedTypes = parseResult.result
for (type in receivedTypes) {
if (isRecognizedContextType(type)) {
return true
}
}
this.logger.error(
"none of the received types {} are present in {}",
receivedTypes,
this.contextTypes
)
false
}
is FRParseResult.FRParseFailed -> {
for (error in parseResult.errors) {
this.logger.error(
"parse: {}: {}:{}:{}: {}: ",
error.producer,
error.position.source,
error.position.line,
error.position.column,
error.message,
error.exception
)
}
false
}
}
}
override fun createParser(
uri: URI,
input: ByteArray,
extensions: List<ManifestParserExtensionType>,
warningsAsErrors: Boolean
): ParserType<PlayerManifest> {
return WebPubParser(
extensions = extensions,
parsers = this.fieldRushParsers,
originalBytes = input,
stream = ByteArrayInputStream(input),
uri = uri
)
}
}