-
Notifications
You must be signed in to change notification settings - Fork 133
fix: styles and scripts not injected into epub navigator #749
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
m-abs
wants to merge
15
commits into
readium:develop
Choose a base branch
from
m-abs:fix/718
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
8815d6c
fix: styles and scripts not injected into epub navigator
m-abs a207963
Merge branch 'develop' into fix/718
m-abs 4156dae
Serve packaged content and assets from dedicated hostnames and stream…
m-abs 94a913a
Cleaner handling of hrefs for streamed resources
m-abs 278d7f8
Merge branch 'develop' into fix/718
m-abs c317268
chor: document publicationLinkFromHref(href: Url)
m-abs 8d4e30b
Use ASSETS_HOSTNAME instead of assetsBaseHref.host
m-abs 80d8810
Use ASSETS_HOSTNAME instead of assetsBaseHref.host
m-abs a902f67
chor: reuse HttpRange
m-abs d233a4a
Add serveErrorResponse() for unknown resources
m-abs 4c6e796
Remove AbsoluteUrl constraint, as a packaged publication can have rem…
m-abs e2b74bf
Only inject html for EPUB profile
m-abs d7fbb71
Merge branch 'fix/718' of github.com:m-abs/kotlin-toolkit into fix/718
m-abs 723f56a
Go back to requiring baseUrl to be AbsoluteUrl
m-abs 772d7ad
Merge branch 'fix/718' of github.com:m-abs/kotlin-toolkit into fix/718
m-abs File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,6 +10,7 @@ package org.readium.r2.navigator.epub | |
|
|
||
| import android.app.Application | ||
| import android.os.PatternMatcher | ||
| import android.webkit.MimeTypeMap | ||
| import android.webkit.WebResourceRequest | ||
| import android.webkit.WebResourceResponse | ||
| import androidx.webkit.WebViewAssetLoader | ||
|
|
@@ -28,9 +29,11 @@ import org.readium.r2.shared.util.data.ReadError | |
| import org.readium.r2.shared.util.data.asInputStream | ||
| import org.readium.r2.shared.util.http.HttpHeaders | ||
| import org.readium.r2.shared.util.http.HttpRange | ||
| import org.readium.r2.shared.util.mediatype.MediaType | ||
| import org.readium.r2.shared.util.resource.Resource | ||
| import org.readium.r2.shared.util.resource.StringResource | ||
| import org.readium.r2.shared.util.resource.fallback | ||
| import org.readium.r2.shared.util.toUrl | ||
|
|
||
| /** | ||
| * Serves the publication resources and application assets in the EPUB navigator web views. | ||
|
|
@@ -44,8 +47,11 @@ internal class WebViewServer( | |
| private val onResourceLoadFailed: (Url, ReadError) -> Unit, | ||
| ) { | ||
| companion object { | ||
| val publicationBaseHref = AbsoluteUrl("https://readium/publication/")!! | ||
| val assetsBaseHref = AbsoluteUrl("https://readium/assets/")!! | ||
| const val READIUM_PACKAGE_HOSTNAME = "readium_package" | ||
| const val ASSETS_HOSTNAME = "readium_assets" | ||
|
|
||
| val publicationBaseHref = AbsoluteUrl("https://$READIUM_PACKAGE_HOSTNAME/")!! | ||
| val assetsBaseHref = AbsoluteUrl("https://$ASSETS_HOSTNAME/")!! | ||
|
|
||
| fun assetUrl(path: String): Url? = | ||
| Url.fromDecodedPath(path)?.let { assetsBaseHref.resolve(it) } | ||
|
|
@@ -54,28 +60,64 @@ internal class WebViewServer( | |
| /** | ||
| * Serves the requests of the navigator web views. | ||
| * | ||
| * https://readium/publication/ serves the publication resources through its fetcher. | ||
| * https://readium/assets/ serves the application assets. | ||
| * https://readium_package/ serves the publication resources through its fetcher. | ||
| * https://readium_assets/ serves the application assets. | ||
| */ | ||
| fun shouldInterceptRequest(request: WebResourceRequest, css: ReadiumCss): WebResourceResponse? { | ||
| if (request.url.host != "readium") return null | ||
| val path = request.url.path ?: return null | ||
| val hostname = request.url.host ?: return null | ||
| val requestUrl = request.url.toUrl() ?: return null | ||
| val range = HttpHeaders(request.requestHeaders).range | ||
|
|
||
| return when { | ||
| path.startsWith("/publication/") -> { | ||
| val href = Url.fromDecodedPath(path.removePrefix("/publication/")) | ||
| ?: return null | ||
| return when (hostname) { | ||
| READIUM_PACKAGE_HOSTNAME -> { | ||
| // Request is for a packaged resource. | ||
| val href = Url.fromDecodedPath(path.removePrefix("/")) | ||
| ?: return serveErrorResponse() | ||
|
|
||
| servePublicationResource( | ||
| href = href, | ||
| range = HttpHeaders(request.requestHeaders).range, | ||
| range = range, | ||
| css = css | ||
| ) | ||
| } | ||
| path.startsWith("/assets/") && isServedAsset(path.removePrefix("/assets/")) -> { | ||
|
|
||
| ASSETS_HOSTNAME if isServedAsset(path.removePrefix("/")) -> { | ||
| // Request is for a known asset. | ||
| assetsLoader.shouldInterceptRequest(request.url) | ||
| } | ||
| else -> null | ||
|
|
||
| ASSETS_HOSTNAME -> { | ||
| val error = ReadError.Decoding( | ||
| "Attempted to load an unknown asset from $requestUrl" | ||
| ) | ||
| onResourceLoadFailed(requestUrl, error) | ||
| serveErrorResponse() // Request is for an unknown asset. | ||
| } | ||
|
|
||
| else -> { | ||
| // Request is for streaming a resource, if the baseUrl an AbsoluteUrl and hostname | ||
| // is not ASSETS_HOSTNAME or READIUM_PACKAGE_HOSTNAME | ||
| val baseUrl = publication.baseUrl as? AbsoluteUrl ?: run { | ||
| val error = ReadError.Decoding( | ||
| "baseUrl is not an AbsoluteUrl, cannot load remote resource from $requestUrl" | ||
| ) | ||
| onResourceLoadFailed(requestUrl, error) | ||
| return serveErrorResponse() | ||
| } | ||
|
|
||
| val href = | ||
| // Look up the link in the publication to make sure we have the right resource. | ||
| publicationLinkFromHref(baseUrl.resolve(requestUrl))?.href?.resolve() | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why do you resolve |
||
| ?: publicationLinkFromHref(baseUrl.relativize(requestUrl))?.href?.resolve() | ||
| ?: requestUrl | ||
|
|
||
| servePublicationResource( | ||
| href = href, | ||
| range = range, | ||
| css = css | ||
| ) | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -84,15 +126,17 @@ internal class WebViewServer( | |
| * | ||
| * If the [Resource] is an HTML document, injects the required JavaScript and CSS files. | ||
| */ | ||
| private fun servePublicationResource(href: Url, range: HttpRange?, css: ReadiumCss): WebResourceResponse { | ||
| val link = publication.linkWithHref(href) | ||
| // Query parameters must be kept as they might be relevant for the fetcher. | ||
| ?.copy(href = Href(href)) | ||
| ?: Link(href = href) | ||
| private fun servePublicationResource( | ||
| href: Url, | ||
| range: HttpRange?, | ||
| css: ReadiumCss | ||
| ): WebResourceResponse { | ||
| val link = publicationLinkFromHref(href) | ||
| // Link not found, create a Link from the href and guess the MediaType | ||
| ?: Link(href = href, mediaType = mediaTypeFromUrl(href)) | ||
|
|
||
| // Drop anchor because it is meant to be interpreted by the client. | ||
| val urlWithoutAnchor = href.removeFragment() | ||
|
|
||
| var resource = publication | ||
| .get(urlWithoutAnchor) | ||
| ?.fallback { | ||
|
|
@@ -106,41 +150,52 @@ internal class WebViewServer( | |
| errorResource() | ||
| } | ||
|
|
||
| link.mediaType | ||
| ?.takeIf { it.isHtml } | ||
| ?.let { | ||
| resource = resource.injectHtml( | ||
| publication, | ||
| mediaType = it, | ||
| css, | ||
| baseHref = assetsBaseHref, | ||
| disableSelectionWhenProtected = disableSelectionWhenProtected | ||
| ) | ||
| } | ||
| // Only inject html when the profile is EPUB | ||
| if (publication.conformsTo(Publication.Profile.EPUB)) { | ||
| link.mediaType | ||
| ?.takeIf { it.isHtml } | ||
| ?.let { | ||
| resource = resource.injectHtml( | ||
| publication, | ||
| mediaType = it, | ||
| css, | ||
| baseHref = assetsBaseHref, | ||
| disableSelectionWhenProtected = disableSelectionWhenProtected | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| return serveResource(resource, range, link.mediaType) | ||
| } | ||
|
|
||
| private fun serveResource( | ||
| resource: Resource, | ||
| range: HttpRange?, | ||
| mediaType: MediaType?, | ||
| ): WebResourceResponse { | ||
| val headers = mutableMapOf( | ||
| "Accept-Ranges" to "bytes" | ||
| ) | ||
|
|
||
| val stream = resource.asInputStream() | ||
| if (range == null) { | ||
| return WebResourceResponse( | ||
| link.mediaType?.toString(), | ||
| mediaType?.toString(), | ||
| null, | ||
| 200, | ||
| "OK", | ||
| headers, | ||
| resource.asInputStream() | ||
| stream | ||
| ) | ||
| } else { // Byte range request | ||
| val stream = resource.asInputStream() | ||
| val length = stream.available() | ||
| val longRange = range.toLongRange(length.toLong()) | ||
| headers["Content-Range"] = "bytes ${longRange.first}-${longRange.last}/$length" | ||
| // Content-Length will automatically be filled by the WebView using the Content-Range header. | ||
| // headers["Content-Length"] = (longRange.last - longRange.first + 1).toString() | ||
| // Weirdly, the WebView will call itself stream.skip to skip to the requested range. | ||
| return WebResourceResponse( | ||
| link.mediaType?.toString(), | ||
| mediaType?.toString(), | ||
| null, | ||
| 206, | ||
| "Partial Content", | ||
|
|
@@ -149,6 +204,26 @@ internal class WebViewServer( | |
| ) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Resolve the [MediaType] from an [Url]. | ||
| */ | ||
| private fun mediaTypeFromUrl(href: Url): MediaType? { | ||
| val ext = MimeTypeMap.getFileExtensionFromUrl(href.normalize().toString()) ?: return null | ||
| val mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext) ?: return null | ||
|
|
||
| return MediaType.invoke(mimetype) | ||
| } | ||
|
|
||
| /** | ||
| * Get link in publication from a [Url] and replace href to preserve request query parameters. | ||
| */ | ||
| private fun publicationLinkFromHref(href: Url): Link? { | ||
| return publication.linkWithHref(href) | ||
| // Query parameters must be kept as they might be relevant for the fetcher. | ||
| ?.copy(href = Href(href)) | ||
| } | ||
|
|
||
| private fun errorResource(): Resource = | ||
| StringResource { | ||
| withContext(Dispatchers.IO) { | ||
|
|
@@ -161,6 +236,10 @@ internal class WebViewServer( | |
| } | ||
| } | ||
|
|
||
| private fun serveErrorResponse(): WebResourceResponse { | ||
| return serveResource(errorResource(), null, MediaType.XHTML) | ||
| } | ||
|
|
||
| private fun isServedAsset(path: String): Boolean = | ||
| servedAssetPatterns.any { it.match(path) } | ||
|
|
||
|
|
@@ -169,7 +248,7 @@ internal class WebViewServer( | |
|
|
||
| private val assetsLoader = | ||
| WebViewAssetLoader.Builder() | ||
| .setDomain("readium") | ||
| .addPathHandler("/assets/", WebViewAssetLoader.AssetsPathHandler(application)) | ||
| .setDomain(ASSETS_HOSTNAME) | ||
| .addPathHandler("/", WebViewAssetLoader.AssetsPathHandler(application)) | ||
| .build() | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We don't need
baseUrlif href is absolute. It could be safer to keep going in that case.