From b18f19dd4a53bc4b26b2676857d33377c8277ee0 Mon Sep 17 00:00:00 2001
From: Mark Raynsford <code@io7m.com>
Date: Mon, 8 Apr 2024 20:26:18 +0000
Subject: [PATCH] Work around broken DRM systems that cannot accept fragments

Fix: https://ebce-lyrasis.atlassian.net/browse/PP-1117
---
 .../r2/vanilla/internal/SR2Controller.kt         | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)

diff --git a/org.librarysimplified.r2.vanilla/src/main/java/org/librarysimplified/r2/vanilla/internal/SR2Controller.kt b/org.librarysimplified.r2.vanilla/src/main/java/org/librarysimplified/r2/vanilla/internal/SR2Controller.kt
index d0e881a..c5d66ca 100644
--- a/org.librarysimplified.r2.vanilla/src/main/java/org/librarysimplified/r2/vanilla/internal/SR2Controller.kt
+++ b/org.librarysimplified.r2.vanilla/src/main/java/org/librarysimplified/r2/vanilla/internal/SR2Controller.kt
@@ -62,6 +62,7 @@ import org.readium.r2.streamer.parser.DefaultPublicationParser
 import org.slf4j.LoggerFactory
 import java.io.ByteArrayInputStream
 import java.io.IOException
+import java.net.URI
 import java.util.concurrent.CompletableFuture
 import java.util.concurrent.ExecutionException
 import java.util.concurrent.Executors
@@ -653,9 +654,18 @@ internal class SR2Controller private constructor(
       val connection =
         this.waitForWebViewAvailability()
       val chapterURL =
-        this.currentNavigationIntent.chapterHref
+        this.currentNavigationIntent.chapterHref.toString()
+
+      /*
+       * If we pass a URL with a fragment into the web view, this will result in
+       * a URL with a fragment going into the underlying DRM engine, and this causes
+       * Adobe DRM to go insane and fail to decrypt.
+       */
+
+      val chapterURLWithoutFragment =
+        chapterURL.substringBefore('#')
       val resolvedURL =
-        chapterURL.resolve(Url(PREFIX_PUBLICATION))
+        URI(PREFIX_PUBLICATION).resolve(chapterURLWithoutFragment)
 
       val future =
         connection.openURL(resolvedURL.toString())
@@ -685,7 +695,7 @@ internal class SR2Controller private constructor(
        * If there's a fragment, attempt to scroll to it.
        */
 
-      when (val fragment = chapterURL.toString().substringAfter('#', "")) {
+      when (val fragment = chapterURL.substringAfter('#', "")) {
         "" -> future
 
         else ->