Skip to content

Commit

Permalink
feat: migrate to ES5 compatible loader
Browse files Browse the repository at this point in the history
  • Loading branch information
CAMOBAP committed Feb 29, 2024
1 parent 8bc3cf6 commit 9b897b9
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 31 deletions.
18 changes: 12 additions & 6 deletions sdk/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ plugins {
}

ext {
hcaptchaLoaderVersion = "1.1.3"
hcaptchaLoaderVersion = "1.2.3"
}

android {
Expand Down Expand Up @@ -126,14 +126,20 @@ project.afterEvaluate {
}
}

long MAX_AAR_SIZE_KB = 200
long MAX_AAR_SIZE_KB = 250

tasks.register('downloadHCaptchaLoaderJs', Download) {
src "https://www.unpkg.com/@hcaptcha/loader@${hcaptchaLoaderVersion}/dist/index.mjs"
dest layout.buildDirectory.file("generated/assets/hcaptcha/loader.mjs")
tasks.register('downloadPolyfillsJs', Download) {
src "https://www.unpkg.com/@hcaptcha/loader@${hcaptchaLoaderVersion}/dist/polyfills.js"
dest layout.buildDirectory.file("generated/assets/hcaptcha/polyfills.js")
onlyIfModified true
}

tasks.register('downloadHCaptchaLoaderJs', Download) {
src "https://www.unpkg.com/@hcaptcha/loader@${hcaptchaLoaderVersion}/dist/index.es5.js"
dest layout.buildDirectory.file("generated/assets/hcaptcha/loader.js")
onlyIfModified true
}.get().dependsOn('downloadPolyfillsJs')

android.sourceSets.main.assets.srcDirs += [layout.buildDirectory.file("generated/assets")]

android.libraryVariants.all { variant ->
Expand All @@ -159,7 +165,7 @@ android.libraryVariants.all { variant ->
var aarFile = variant.packageLibraryProvider.get().archiveFile.get().getAsFile()
long aarSizeKb = aarFile.length() / 1024
if (aarSizeKb > MAX_AAR_SIZE_KB) {
throw new GradleException("${aarPath} size exceeded! ${aarSizeKb}Kbyte > ${MAX_AAR_SIZE_KB}Kbyte")
throw new GradleException("${aarFile} size exceeded! ${aarSizeKb}Kbyte > ${MAX_AAR_SIZE_KB}Kbyte")
}
}
})
Expand Down
33 changes: 16 additions & 17 deletions sdk/src/main/html/hcaptcha.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@
window.sysDebug = JSON.parse(window.JSDI.getSysDebug());
}
</script>
<script type="module">
import { hCaptchaLoader } from 'https://www.unpkg.com/@hcaptcha/loader@@LOADER_VERSION@/dist/index.mjs';

<script type="text/javascript" src="https://unpkg.com/@hcaptcha/loader@@LOADER_VERSION@/dist/polyfills.js"></script>
<script type="text/javascript" src="https://unpkg.com/@hcaptcha/loader@@LOADER_VERSION@/dist/index.es5.js"></script>
<script>
// Android will inject this bridge object as `JSInterface`
// Browser is missing it, so we mock it
var BridgeObject = window.JSInterface || {
Expand Down Expand Up @@ -75,9 +75,9 @@
/**
* Called programmatically from HCaptchaWebViewHelper.
*/
async function resetAndExecute() {
function resetAndExecute() {
hcaptcha.reset();
await execute();
execute();
}
window.resetAndExecute = resetAndExecute;
function reset() {
Expand Down Expand Up @@ -175,17 +175,16 @@
BridgeObject.onError(30);
}
});
async function execute() {
try {
var { response } = await hcaptcha.execute(getScriptParams(bridgeConfig));
function execute() {
hcaptcha.execute(getScriptParams(bridgeConfig)).then(function(result) {
var response = result.response;
BridgeObject.onPass(response);
} catch (error) {
}).catch(function(error) {
errorCallback(error);
}
});
}
async function loadApi(config) {
try {
window.hcaptcha = await hCaptchaLoader(getLoaderParams(config));
function loadApi(config) {
hCaptchaLoader(getLoaderParams(config)).then(function(hcaptcha) {
var renderConfig = getRenderConfig(config);
hcaptcha.render("hcaptcha-container", renderConfig);
BridgeObject.onLoaded();
Expand All @@ -197,12 +196,12 @@
// We want to auto execute in case of `invisible` checkbox.
// But not in case of `hideDialog` since verification process
// might be desired to happen at a later time.
await execute();
execute();
}
} catch (e) {
console.error("loadApi error", e);
}).catch(function(error) {
console.error("loadApi error", error);
BridgeObject.onError(29);
}
});
}
loadApi(bridgeConfig);
</script>
Expand Down
17 changes: 11 additions & 6 deletions sdk/src/main/java/com/hcaptcha/sdk/HCaptchaWebViewHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

final class HCaptchaWebViewHelper {
Expand Down Expand Up @@ -130,9 +132,7 @@ public boolean shouldRetry(HCaptchaException exception) {

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private class HCaptchaWebClient extends WebViewClient {
private final Uri loaderUri = Uri.parse(
"https://www.unpkg.com/@hcaptcha/loader@" + BuildConfig.LOADER_VERSION + "/dist/index.mjs"
);
private final Map<Uri, String> assetsCache = new HashMap<>();

@NonNull
private final Handler handler;
Expand All @@ -143,6 +143,10 @@ private class HCaptchaWebClient extends WebViewClient {
HCaptchaWebClient(@NonNull Handler handler, @NonNull HCaptchaStateListener listener) {
this.handler = handler;
this.listener = listener;

final String baseUrl = "https://unpkg.com/@hcaptcha/loader@" + BuildConfig.LOADER_VERSION + "/dist";
assetsCache.put(Uri.parse(baseUrl + "/index.es5.js"), "hcaptcha/loader.js");
assetsCache.put(Uri.parse(baseUrl + "/polyfills.js"), "hcaptcha/polyfills.js");
}

private String stripUrl(String url) {
Expand All @@ -152,7 +156,8 @@ private String stripUrl(String url) {
@Override
public WebResourceResponse shouldInterceptRequest (final WebView view, final WebResourceRequest request) {
final Uri requestUri = request.getUrl();
if (loaderUri.equals(requestUri)) {
final String assetPath = assetsCache.get(requestUri);
if (assetPath != null) {
try {
return new WebResourceResponse(
"application/javascript",
Expand All @@ -161,10 +166,10 @@ public WebResourceResponse shouldInterceptRequest (final WebView view, final Web
"OK",
Collections.singletonMap("Access-Control-Allow-Origin",
Objects.toString(config.getHost(), "null")),
view.getContext().getAssets().open("hcaptcha/loader.mjs")
view.getContext().getAssets().open(assetPath)
);
} catch (IOException e) {
HCaptchaLog.w("WebViewHelper wasn't able to load loader.mjs from assets");
HCaptchaLog.w("WebViewHelper wasn't able to load " + assetPath + " from assets");
}
} else if (requestUri != null && requestUri.getScheme() != null && requestUri.getScheme().equals("http")) {
handler.post(() -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
import static org.mockito.Mockito.mock;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Handler;
import android.os.Looper;

import androidx.test.core.app.ActivityScenario;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import androidx.test.platform.app.InstrumentationRegistry;

Expand All @@ -21,6 +23,7 @@
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

Expand Down Expand Up @@ -76,7 +79,19 @@ void onFailure(HCaptchaException e) {

@Test
public void testLoaderJsAssetPresence() throws IOException {
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertNotNull(appContext.getAssets().open("hcaptcha/loader.mjs"));
AssetManager assets = InstrumentationRegistry
.getInstrumentation()
.getTargetContext()
.getAssets();
assertNotNull(assets.open("hcaptcha/loader.js"));
}

@Test
public void testPolyfillsJsAssetPresence() throws IOException {
AssetManager assets = InstrumentationRegistry
.getInstrumentation()
.getTargetContext()
.getAssets();
assertNotNull(assets.open("hcaptcha/polyfills.js"));
}
}

0 comments on commit 9b897b9

Please sign in to comment.