Skip to content
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

Add iOS Request Interception #33

Draft
wants to merge 2 commits into
base: trunk
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Demo-Android/Gutenberg/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ dependencies {
implementation(libs.androidx.appcompat)
implementation(libs.material)
implementation(libs.androidx.webkit)
implementation(platform(libs.okhttp.bom))
implementation(libs.okhttp)

testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package org.wordpress.gutenberg

import android.webkit.WebResourceRequest

public interface GutenbergRequestInterceptor {
fun interceptRequest(request: WebResourceRequest): WebResourceRequest
}

class DefaultGutenbergRequestInterceptor: GutenbergRequestInterceptor {
override fun interceptRequest(request: WebResourceRequest): WebResourceRequest {
return request
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.webkit.WebViewAssetLoader
import androidx.webkit.WebViewAssetLoader.AssetsPathHandler
import okhttp3.Headers.Companion.toHeaders
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okio.IOException
import org.json.JSONObject
import java.lang.ref.WeakReference

Expand Down Expand Up @@ -48,10 +53,15 @@ class GutenbergView : WebView {
var editorDidBecomeAvailable: ((GutenbergView) -> Unit)? = null
var filePathCallback: ValueCallback<Array<Uri?>?>? = null
val pickImageRequestCode = 1

var requestInterceptor: GutenbergRequestInterceptor = DefaultGutenbergRequestInterceptor()

private var onFileChooserRequested: WeakReference<((Intent, Int) -> Unit)?>? = null
private var contentChangeListener: WeakReference<ContentChangeListener>? = null
private var editorDidBecomeAvailableListener: EditorAvailableListener? = null

private val httpClient = OkHttpClient()

fun setContentChangeListener(listener: ContentChangeListener) {
contentChangeListener = WeakReference(listener)
}
Expand Down Expand Up @@ -103,10 +113,34 @@ class GutenbergView : WebView {
hasSetEditorConfig = true
}

return if (request?.url != null) {
assetLoader.shouldInterceptRequest(request.url)
if (request?.url == null) {
return super.shouldInterceptRequest(view, request)
} else if(request.url.host?.contains("appassets.androidplatform.net") == true) {
return assetLoader.shouldInterceptRequest(request.url)
} else {
super.shouldInterceptRequest(view, request)
val modifiedRequest = requestInterceptor.interceptRequest(request)

try {
val okHttpRequest = Request.Builder()
.url(modifiedRequest.url!!.toString())
.headers(modifiedRequest.requestHeaders.toHeaders())
.build()

val response: Response = httpClient.newCall(okHttpRequest).execute()

val body = if(response.body != null) { response.body!! } else { return null }
val contentType = if(body.contentType() != null) { body.contentType() } else { return null }

return WebResourceResponse(
contentType.toString(),
response.header("content-encoding", null),
body.byteStream()
)
} catch (e: IOException) {
// We don't need to handle this ourselves, just tell the WebView that
// we weren't able to fetch the resource
return null;
}
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions Demo-Android/gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ appcompat = "1.7.0"
material = "1.12.0"
activity = "1.9.0"
constraintlayout = "2.1.4"
okhttp = "4.12.0"
webkit = "1.11.0"

[libraries]
Expand All @@ -21,6 +22,8 @@ material = { group = "com.google.android.material", name = "material", version.r
androidx-activity = { group = "androidx.activity", name = "activity", version.ref = "activity" }
androidx-constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "constraintlayout" }
androidx-webkit = { group = "androidx.webkit", name = "webkit", version.ref = "webkit" }
okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" }
okhttp-bom = { module = "com.squareup.okhttp3:okhttp-bom", version.ref = "okhttp" }

[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
Expand Down
62 changes: 61 additions & 1 deletion Sources/GutenbergKit/Sources/EditorViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ public final class EditorViewController: UIViewController, GutenbergEditorContro
}

private func setUpEditor() {
registerRequestInterceptor()

let webViewConfiguration = webView.configuration
let userContentController = webViewConfiguration.userContentController
let editorInitialConfig = getEditorConfiguration()
Expand Down Expand Up @@ -368,6 +370,64 @@ private final class GutenbergEditorController: NSObject, WKNavigationDelegate, W
}
}

private extension WKWebView {
class InterceptionProtocol: URLProtocol {
override class func canInit(with request: URLRequest) -> Bool {

// We don't want to interfere with loading the editor JS
guard request.url?.host != "localhost" else {
Comment on lines +376 to +377
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The development server can also be an IP when testing with a physical device. Maybe we can check against the GUTENBERG_EDITOR_URL environment variable as well?

debugPrint("Not intercepting \(request)")
return false
}

// We care about WordPress.com resources – let's modify those if needed
if request.url?.host?.contains("wordpress.com") == true {
Comment on lines +382 to +383
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Eventually, we should hoist this conditional into the host app, as we want to avoid such references in Gutenberg.

return request.value(forHTTPHeaderField: "Authorization") == nil // If there's no auth header, we need to intercept
}

return false
}

override class func canonicalRequest(for request: URLRequest) -> URLRequest {
var mutableRequest = request
mutableRequest.allHTTPHeaderFields?["Authorization"] = "Bearer [REDACTED]"
return mutableRequest
}

private var taskHandle: Task<Void, Error>?
private let session: URLSession = URLSession(configuration: .ephemeral)

override func startLoading() {
self.taskHandle = Task {
do {
let (data, response) = try await session.data(for: self.request)
self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .allowedInMemoryOnly)
self.client?.urlProtocol(self, didLoad: data)
self.client?.urlProtocolDidFinishLoading(self)

} catch {
self.client?.urlProtocol(self, didFailWithError: error)
}
}
}

override func stopLoading() {
self.taskHandle?.cancel()
}
}

private extension EditorViewController {

// Inject the interceptor
func registerRequestInterceptor() {
let browsingContextClass: AnyClass = NSClassFromString("WKBrowsingContextController")!
let registerSchemeSelector: Selector = NSSelectorFromString("registerSchemeForCustomProtocol:")
// let unregisterSchemeSelector: Selector = NSSelectorFromString("unregisterSchemeForCustomProtocol:")

if browsingContextClass.responds(to: registerSchemeSelector) == true {
browsingContextClass.performSelector(inBackground: registerSchemeSelector, with: "http")
browsingContextClass.performSelector(inBackground: registerSchemeSelector, with: "https")
}

URLProtocol.registerClass(InterceptionProtocol.self)
}
}