This repository has been archived by the owner on Jul 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
Publication.kt
509 lines (431 loc) · 18.8 KB
/
Publication.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
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/*
* Module: r2-shared-kotlin
* Developers: Aferdita Muriqi, Clément Baumann, Mickaël Menu
*
* Copyright (c) 2020. Readium Foundation. All rights reserved.
* Use of this source code is governed by a BSD-style license which is detailed in the
* LICENSE file present in the project repository where this source code is maintained.
*/
package org.readium.r2.shared.publication
import android.net.Uri
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.json.JSONObject
import org.readium.r2.shared.BuildConfig.DEBUG
import org.readium.r2.shared.ReadiumCSSName
import org.readium.r2.shared.extensions.HashAlgorithm
import org.readium.r2.shared.extensions.hash
import org.readium.r2.shared.extensions.removeLastComponent
import org.readium.r2.shared.extensions.toUrlOrNull
import org.readium.r2.shared.fetcher.EmptyFetcher
import org.readium.r2.shared.fetcher.Fetcher
import org.readium.r2.shared.fetcher.Resource
import org.readium.r2.shared.format.MediaType
import org.readium.r2.shared.publication.epub.listOfAudioClips
import org.readium.r2.shared.publication.epub.listOfVideoClips
import org.readium.r2.shared.publication.services.CoverService
import org.readium.r2.shared.publication.services.PositionsService
import org.readium.r2.shared.publication.services.positions
import timber.log.Timber
import java.lang.Exception
import java.net.URL
import java.net.URLEncoder
import kotlin.reflect.KClass
internal typealias ServiceFactory = (Publication.Service.Context) -> Publication.Service?
/**
* The Publication shared model is the entry-point for all the metadata and services
* related to a Readium publication.
*
* @param manifest The manifest holding the publication metadata extracted from the publication file.
* @param fetcher The underlying fetcher used to read publication resources.
* The default implementation returns Resource.Error.NotFound for all HREFs.
* @param servicesBuilder Holds the list of service factories used to create the instances of
* Publication.Service attached to this Publication.
* @param type The kind of publication it is ( EPUB, CBZ, ... )
* @param version The version of the publication, if the type needs any.
* @param positionsFactory Factory used to build lazily the [positions].
*/
class Publication(
private val manifest: Manifest,
private val fetcher: Fetcher = EmptyFetcher(),
private val servicesBuilder: ServicesBuilder = ServicesBuilder(),
@Deprecated("Provide a [ServiceFactory] for a [PositionsService] instead.", level = DeprecationLevel.ERROR)
@Suppress("DEPRECATION")
val positionsFactory: PositionListFactory? = null,
// FIXME: To refactor after specifying the User and Rendition Settings API
var userSettingsUIPreset: MutableMap<ReadiumCSSName, Boolean> = mutableMapOf(),
var cssStyle: String? = null,
@Deprecated("This will be removed in a future version. Use [Format.of] to check the format of a publication.", level = DeprecationLevel.ERROR)
var internalData: MutableMap<String, String> = mutableMapOf()
) {
private val _services: List<Service> = servicesBuilder.build(Service.Context(manifest, fetcher))
private val _manifest = manifest.copy(links = manifest.links + _services.map(Service::links).flatten())
// Shortcuts to manifest properties
val context: List<String> get() = _manifest.context
val metadata: Metadata get() = _manifest.metadata
val links: List<Link> get() = _manifest.links
/** Identifies a list of resources in reading order for the publication. */
val readingOrder: List<Link> get() = _manifest.readingOrder
/** Identifies resources that are necessary for rendering the publication. */
val resources: List<Link> get() = _manifest.resources
/** Identifies the collection that contains a table of contents. */
val tableOfContents: List<Link> get() = _manifest.tableOfContents
val subcollections: Map<String, List<PublicationCollection>> get() = _manifest.subcollections
// FIXME: To be refactored, with the TYPE and EXTENSION enums as well
var type: TYPE = when {
metadata.type == "http://schema.org/Audiobook" || readingOrder.allAreAudio -> TYPE.AUDIO
readingOrder.allAreBitmap -> TYPE.DiViNa
else -> TYPE.WEBPUB
}
@Deprecated("Version is not available any more.", level = DeprecationLevel.ERROR)
var version: Double = 0.0
/**
* Returns the RWPM JSON representation for this [Publication]'s manifest, as a string.
*/
val jsonManifest: String
get() = _manifest.toJSON().toString().replace("\\/", "/")
/**
* The URL where this publication is served, computed from the [Link] with `self` relation.
*/
val baseUrl: URL?
get() = links.firstWithRel("self")
?.let { it.href.toUrlOrNull()?.removeLastComponent() }
/**
* Finds the first [Link] with the given HREF in the publication's links.
*
* Searches through (in order) [readingOrder], [resources] and [links] recursively following
* [alternate] and [children] links.
*
* If there's no match, try again after removing any query parameter and anchor from the
* given [href].
*/
fun linkWithHref(href: String): Link? {
fun find(href: String): Link? {
return readingOrder.deepLinkWithHref(href)
?: resources.deepLinkWithHref(href)
?: links.deepLinkWithHref(href)
}
return find(href)
?: find(href.takeWhile { it !in "#?" })
}
/**
* Finds the first [Link] having the given [rel] in the publications's links.
*/
fun linkWithRel(rel: String): Link? = _manifest.linkWithRel(rel)
/**
* Finds all [Link]s having the given [rel] in the publications's links.
*/
fun linksWithRel(rel: String): List<Link> = _manifest.linksWithRel(rel)
/**
* Returns the resource targeted by the given non-templated [link].
*/
fun get(link: Link): Resource {
if (DEBUG) { require(!link.templated) { "You must expand templated links before calling [Publication.get]" } }
_services.forEach { service -> service.get(link)?.let { return it } }
return fetcher.get(link)
}
/**
* Closes any opened resource associated with the [Publication], including services.
*/
fun close() = GlobalScope.launch {
try {
fetcher.close()
} catch (e: Exception) {
Timber.e(e)
}
_services.forEach {
try {
it.close()
} catch (e: Exception) {
Timber.e(e)
}
}
}
/**
* Returns the first publication service that is an instance of [klass].
*/
fun <T: Service> findService(serviceType: KClass<T>): T? =
_services.filterIsInstance(serviceType.java).firstOrNull()
enum class TYPE {
EPUB, CBZ, FXL, WEBPUB, AUDIO, DiViNa
}
enum class EXTENSION(var value: String) {
EPUB(".epub"),
CBZ(".cbz"),
JSON(".json"),
DIVINA(".divina"),
AUDIO(".audiobook"),
LCPL(".lcpl"),
UNKNOWN("");
companion object {
fun fromString(type: String): EXTENSION? =
values().firstOrNull { it.value == type }
}
}
/**
* Sets the URL where this [Publication]'s RWPM manifest is served.
*/
fun setSelfLink(href: String) {
_manifest.links = _manifest.links.toMutableList().apply {
removeAll { it.rels.contains("self") }
add(Link(href = href, type = MediaType.READIUM_WEBPUB_MANIFEST.toString(), rels = setOf("self")))
}
}
/**
* Returns the [ContentLayout] for the default language.
*/
val contentLayout: ContentLayout get() = metadata.contentLayout
/**
* Returns the [ContentLayout] for the given [language].
*/
fun contentLayoutForLanguage(language: String?) = metadata.contentLayoutForLanguage(language)
/**
* Returns the [links] of the first child [PublicationCollection] with the given role, or an
* empty list.
*/
internal fun linksWithRole(role: String): List<Link> =
subcollections[role]?.firstOrNull()?.links ?: emptyList()
private fun List<Link>.deepLinkWithHref(href: String): Link? {
for (l in this) {
if (l.href == href)
return l
else {
l.alternates.deepLinkWithHref(href)?.let { return it }
l.children.deepLinkWithHref(href)?.let { return it }
}
}
return null
}
companion object {
/**
* Creates the base URL for a [Publication] locally served through HTTP, from the
* publication's [filename] and the HTTP server [port].
*
* Note: This is used for backward-compatibility, but ideally this should be handled by the
* Server, and set in the self [Link]. Unfortunately, the self [Link] is not available
* in the navigator at the moment without changing the code in reading apps.
*/
fun localBaseUrlOf(filename: String, port: Int): String {
val sanitizedFilename = filename
.removePrefix("/")
.hash(HashAlgorithm.MD5)
.let { URLEncoder.encode(it, "UTF-8") }
return "http://127.0.0.1:$port/$sanitizedFilename"
}
/**
* Gets the absolute URL of a resource locally served through HTTP.
*/
fun localUrlOf(filename: String, port: Int, href: String): String =
localBaseUrlOf(filename, port) + href
@Deprecated("Parse a RWPM with [Manifest::fromJSON] and then instantiate a Publication",
ReplaceWith("Manifest.fromJSON(manifestDict)?.let { Publication(it, fetcher = aFetcher) }",
"org.readium.r2.shared.publication.Publication", "org.readium.r2.shared.publication.Manifest"),
level = DeprecationLevel.ERROR)
fun fromJSON(json: JSONObject?, normalizeHref: LinkHrefNormalizer = LinkHrefNormalizerIdentity): Publication? {
throw NotImplementedError()
}
}
/**
* Base interface to be implemented by all publication services.
*/
interface Service {
/**
* Container for the context from which a service is created.
*/
class Context(
val manifest: Manifest,
val fetcher: Fetcher
)
/**
* Links which will be added to [Publication.links].
* It can be used to expose a web API for the service, through [Publication.get].
*
* To disambiguate the href with a publication's local resources, you should use the prefix
* `/~readium/`. A custom media type or rel should be used to identify the service.
*
* You can use a templated URI to accept query parameters, e.g.:
*
* ```
* Link(
* href = "/~readium/search{?text}",
* type = "application/vnd.readium.search+json",
* templated = true
* )
* ```
*/
val links: List<Link> get () = emptyList()
/**
* A service can return a Resource to:
* - respond to a request to its web API declared in links,
* - serve additional resources on behalf of the publication,
* - replace a publication resource by its own version.
*
* Called by [Publication.get] for each request.
*
* @return The [Resource] containing the response, or null if the service doesn't recognize
* this request.
*/
fun get(link: Link): Resource? = null
/**
* Closes any opened file handles, removes temporary files, etc.
*/
fun close() {}
}
/**
* Builds a list of [Publication.Service] from a collection of service factories.
*
* Provides helpers to manipulate the list of services of a [Publication].
*/
class ServicesBuilder(internal var serviceFactories: MutableMap<String, ServiceFactory>) {
@Suppress("UNCHECKED_CAST")
constructor(
positions: ServiceFactory? = null,
cover: ServiceFactory? = null
) : this(mapOf(
PositionsService::class.java.simpleName to positions,
CoverService::class.java.simpleName to cover
).filterValues { it != null }.toMutableMap() as MutableMap<String, ServiceFactory>)
/** Builds the actual list of publication services to use in a Publication. */
fun build(context: Service.Context) : List<Service> = serviceFactories.values.mapNotNull { it(context) }
/** Gets the publication service factory for the given service type. */
operator fun <T : Service> get(serviceType: KClass<T>): ServiceFactory? {
val key = requireNotNull(serviceType.simpleName)
return serviceFactories[key]
}
/** Sets the publication service factory for the given service type. */
operator fun <T : Service> set(serviceType: KClass<T>, factory: ServiceFactory?) {
val key = requireNotNull(serviceType.simpleName)
if (factory != null) {
serviceFactories[key] = factory
} else {
serviceFactories.remove(key)
}
}
/** Removes the service factory producing the given kind of service, if any. */
fun <T : Service> remove(serviceType: KClass<T>) {
val key = requireNotNull(serviceType.simpleName)
serviceFactories.remove(key)
}
/**
* Replaces the service factory associated with the given service type with the result of
* [transform].
*/
fun <T : Service> wrap(serviceType: KClass<T>, transform: ((ServiceFactory)?) -> ServiceFactory) {
val key = requireNotNull(serviceType.simpleName)
serviceFactories[key] = transform(serviceFactories[key])
}
}
/**
* Errors occurring while opening a Publication.
*/
sealed class OpeningError(cause: Throwable? = null) : Throwable(cause) {
/**
* The file format could not be recognized by any parser.
*/
object UnsupportedFormat : OpeningError()
/**
* The publication file was not found on the file system.
*/
object NotFound : OpeningError()
/**
* The publication parser failed with the given underlying exception.
*/
class ParsingFailed(cause: Throwable) : OpeningError(cause)
/**
* We're not allowed to open the publication at all, for example because it expired.
*/
class Forbidden(cause: Throwable?) : OpeningError(cause)
/**
* The publication can't be opened at the moment, for example because of a networking error.
* This error is generally temporary, so the operation may be retried or postponed.
*/
class Unavailable(cause: Throwable?) : OpeningError(cause)
/**
* The provided credentials are incorrect and we can't open the publication in a
* `restricted` state (e.g. for a password-protected ZIP).
*/
object IncorrectCredentials: OpeningError()
}
/**
* Builds a Publication from its components.
*
* A Publication's construction is distributed over the Streamer and its parsers,
* so a builder is useful to pass the parts around.
*/
class Builder(
var manifest: Manifest,
var fetcher: Fetcher,
var servicesBuilder: ServicesBuilder
) {
fun build(): Publication = Publication(
manifest = manifest,
fetcher = fetcher,
servicesBuilder = servicesBuilder
)
}
/**
* Finds the first [Link] to the publication's cover (rel = cover).
*/
@Deprecated("Use [Publication.cover] to get the cover as a [Bitmap]", ReplaceWith("cover"))
val coverLink: Link? get() = linkWithRel("cover")
/**
* Copy the [Publication] with a different [PositionListFactory].
* The provided closure will be used to build the [PositionListFactory], with this being the
* [Publication].
*/
@Suppress("DEPRECATION")
@Deprecated("Use [Publication.copy(serviceFactories)] instead", ReplaceWith("Publication.copy(serviceFactories = listOf(positionsServiceFactory)"), level = DeprecationLevel.ERROR)
fun copyWithPositionsFactory(createFactory: Publication.() -> PositionListFactory): Publication {
throw NotImplementedError()
}
@Deprecated("Renamed to [listOfAudioClips]", ReplaceWith("listOfAudioClips"))
val listOfAudioFiles: List<Link> = listOfAudioClips
@Deprecated("Renamed to [listOfVideoClips]", ReplaceWith("listOfVideoClips"))
val listOfVideos: List<Link> = listOfVideoClips
@Deprecated("Renamed to [resourceWithHref]", ReplaceWith("resourceWithHref(href)"))
fun resource(href: String): Link? = resourceWithHref(href)
@Deprecated("Refactored as a property", ReplaceWith("baseUrl"))
fun baseUrl(): URL? = baseUrl
@Deprecated("Renamed [subcollections]", ReplaceWith("subcollections"))
val otherCollections: Map<String, List<PublicationCollection>> get() = subcollections
@Deprecated("Use [setSelfLink] instead", ReplaceWith("setSelfLink"))
fun addSelfLink(endPoint: String, baseURL: URL) {
setSelfLink(Uri.parse(baseURL.toString())
.buildUpon()
.appendEncodedPath("$endPoint/manifest.json")
.build()
.toString()
)
}
/**
* Finds the first resource [Link] (asset or [readingOrder] item) at the given relative path.
*/
@Deprecated("Use [linkWithHref] instead.", ReplaceWith("linkWithHref(href)"))
fun resourceWithHref(href: String): Link? {
return readingOrder.deepLinkWithHref(href)
?: resources.deepLinkWithHref(href)
}
/**
* Creates a [Publication]'s [positions].
*
* The parsers provide an implementation of this interface for each format, but a host app
* might want to use a custom factory to implement, for example, a caching mechanism or use a
* different calculation method.
*/
@Deprecated("Use a [ServiceFactory] for a [PositionsService] instead.")
interface PositionListFactory {
fun create(): List<Locator>
}
/**
* Finds the first [Link] matching the given [predicate] in the publications's [Link]
* properties: [resources], [readingOrder] and [links].
*
* Searches through (in order) [readingOrder], [resources] and [links]
* recursively following [alternate] and [children] links.
* The search order is unspecified.
*/
@Deprecated("Use [linkWithHref()] to find a link with the given HREF", replaceWith = ReplaceWith("linkWithHref"), level = DeprecationLevel.ERROR)
fun link(predicate: (Link) -> Boolean): Link? = null
@Deprecated("Use [jsonManifest] instead", ReplaceWith("jsonManifest"))
fun toJSON() = JSONObject(jsonManifest)
}