Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Add support for downloading through Hub (#42795)

Bannon Tanner48dda2ac93dc
diff --git a/frontend/discourse/admin/services/admin-emojis.js b/frontend/discourse/admin/services/admin-emojis.js
index aea94df1239..b3d541253ec 100644
--- a/frontend/discourse/admin/services/admin-emojis.js
+++ b/frontend/discourse/admin/services/admin-emojis.js
@@ -7,7 +7,7 @@ import {
removeValueFromArray,
uniqueItemsFromArray,
} from "discourse/lib/array-tools";
-import { triggerBlobDownload } from "discourse/lib/download-blob";
+import { deliverBlobDownload } from "discourse/lib/download-blob";
import getURL from "discourse/lib/get-url";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
import Session from "discourse/models/session";
@@ -73,7 +73,7 @@ export default class AdminEmojis extends Service {
return;
}
- triggerBlobDownload(await response.blob(), {
+ await deliverBlobDownload(await response.blob(), {
fallbackFilename: "emojis.zip",
contentDisposition: response.headers.get("Content-Disposition"),
});
diff --git a/frontend/discourse/app/lib/download-blob.js b/frontend/discourse/app/lib/download-blob.js
index 9129b129847..d74ec62a290 100644
--- a/frontend/discourse/app/lib/download-blob.js
+++ b/frontend/discourse/app/lib/download-blob.js
@@ -1,4 +1,7 @@
+import { attachmentDownloadStrategy } from "discourse/lib/download-strategy";
+
const REVOKE_AFTER = 20_000;
+export const MAX_BRIDGED_DOWNLOAD_BYTES = 25 * 1024 * 1024;
function parseFilename(contentDisposition) {
if (!contentDisposition) {
@@ -18,12 +21,49 @@ function parseFilename(contentDisposition) {
return asciiMatch ? asciiMatch[1].trim() : null;
}
-// Triggers a browser download of the given Blob via a hidden `<a download>`.
-// Preferable to a plain `<a href target=_blank>` navigation for large binaries
-// in iOS PWA and embedded WebView contexts, where the new-tab navigation
-// either strands the user in a standalone window or renders the binary as
-// text.
-export function triggerBlobDownload(
+function blobAsBase64(blob) {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onerror = () =>
+ reject(reader.error ?? new Error("File read failed"));
+ reader.onload = () => {
+ const result = reader.result;
+ const comma = typeof result === "string" ? result.indexOf(",") : -1;
+ if (comma === -1) {
+ reject(new Error("File encoding failed"));
+ } else {
+ resolve(result.slice(comma + 1));
+ }
+ };
+ reader.readAsDataURL(blob);
+ });
+}
+
+export async function bridgeBlobDownload(
+ blob,
+ { fallbackFilename, contentDisposition } = {}
+) {
+ if (blob.size > MAX_BRIDGED_DOWNLOAD_BYTES) {
+ throw new Error("Download is too large for the in-app downloader");
+ }
+
+ const filename = parseFilename(contentDisposition) ?? fallbackFilename;
+ if (!filename) {
+ throw new Error("Download filename is missing");
+ }
+
+ const data = await blobAsBase64(blob);
+ window.ReactNativeWebView.postMessage(
+ JSON.stringify({
+ type: "download",
+ filename,
+ mimeType: blob.type || "application/octet-stream",
+ data,
+ })
+ );
+}
+
+function triggerBlobDownload(
blob,
{ fallbackFilename, contentDisposition } = {}
) {
@@ -41,7 +81,14 @@ export function triggerBlobDownload(
setTimeout(() => URL.revokeObjectURL(objectUrl), REVOKE_AFTER);
}
-// Fetches `url` and triggers a browser download of the response body.
+export async function deliverBlobDownload(blob, options = {}) {
+ if (attachmentDownloadStrategy() === "bridge") {
+ await bridgeBlobDownload(blob, options);
+ } else {
+ triggerBlobDownload(blob, options);
+ }
+}
+
export default async function downloadBlob(
url,
{ fallbackFilename, fetchOptions } = {}
@@ -53,7 +100,7 @@ export default async function downloadBlob(
if (!response.ok) {
throw new Error(`Download failed: ${response.status}`);
}
- triggerBlobDownload(await response.blob(), {
+ await deliverBlobDownload(await response.blob(), {
fallbackFilename,
contentDisposition: response.headers.get("Content-Disposition"),
});
diff --git a/frontend/discourse/app/lib/download-strategy.js b/frontend/discourse/app/lib/download-strategy.js
index b1c4642ce0f..fd3971513a1 100644
--- a/frontend/discourse/app/lib/download-strategy.js
+++ b/frontend/discourse/app/lib/download-strategy.js
@@ -10,7 +10,20 @@ import { capabilities } from "discourse/services/capabilities";
// "blob" — a new-tab navigation to an attachment strands the user in a
// standalone window (iOS PWA). Callers must fetch the response
// and trigger a client-side blob download instead.
+// "bridge" — Discourse Hub receives a bounded Blob over its web/native
+// bridge, writes a temporary file, and opens native save/share UI.
+// Restricted to iOS: Android's WebView already downloads via
+// the system DownloadManager (react-native-webview >=2.15), and
+// requires the Hub app to confirm it understands the bridge
+// protocol before we rely on it (see hubDownloadBridgeSupported).
export function attachmentDownloadStrategy() {
+ if (
+ capabilities.isAppWebview &&
+ capabilities.isIOS &&
+ capabilities.hubDownloadBridgeSupported
+ ) {
+ return "bridge";
+ }
if (capabilities.isPwa) {
return "blob";
}
diff --git a/frontend/discourse/app/services/capabilities.js b/frontend/discourse/app/services/capabilities.js
index 4842a9d9258..e1f2292d39b 100644
--- a/frontend/discourse/app/services/capabilities.js
+++ b/frontend/discourse/app/services/capabilities.js
@@ -95,6 +95,11 @@ class _Capabilities {
wasLaunchedFromDiscourseHub =
window.location.search.includes("discourse_app=1");
isAppWebview = window.ReactNativeWebView !== undefined;
+ // Set by the Discourse Hub app via `injectedJavaScriptBeforeContentLoaded`
+ // once it ships a WebView message handler for `{ type: "download" }`.
+ // Lets us feature-detect support instead of assuming every app webview
+ // build understands the bridge protocol (older installed builds won't).
+ hubDownloadBridgeSupported = window.__discourseHubDownloadBridge === true;
/**
* Defines the responsive viewport breakpoints and their media queries.
diff --git a/frontend/discourse/tests/unit/lib/download-blob-test.js b/frontend/discourse/tests/unit/lib/download-blob-test.js
index 55b7874043d..14d2f1c4a5a 100644
--- a/frontend/discourse/tests/unit/lib/download-blob-test.js
+++ b/frontend/discourse/tests/unit/lib/download-blob-test.js
@@ -1,7 +1,12 @@
import { setupTest } from "ember-qunit";
import { module, test } from "qunit";
import sinon from "sinon";
-import downloadBlob, { triggerBlobDownload } from "discourse/lib/download-blob";
+import downloadBlob, {
+ bridgeBlobDownload,
+ deliverBlobDownload,
+ MAX_BRIDGED_DOWNLOAD_BYTES,
+} from "discourse/lib/download-blob";
+import { capabilities } from "discourse/services/capabilities";
function captureAnchor() {
const original = document.createElement.bind(document);
@@ -25,12 +30,18 @@ module("Unit | Utility | download-blob", function (hooks) {
hooks.beforeEach(function () {
sinon.stub(URL, "createObjectURL").returns("blob:mock");
sinon.stub(URL, "revokeObjectURL");
+ sinon.stub(capabilities, "isAppWebview").value(false);
+ sinon.stub(capabilities, "isPwa").value(false);
});
- test("triggerBlobDownload uses fallbackFilename when no Content-Disposition", function (assert) {
+ hooks.afterEach(function () {
+ delete window.ReactNativeWebView;
+ });
+
+ test("deliverBlobDownload uses fallbackFilename when no Content-Disposition", function (assert) {
const { created } = captureAnchor();
- triggerBlobDownload(new Blob(["x"]), { fallbackFilename: "fallback.zip" });
+ deliverBlobDownload(new Blob(["x"]), { fallbackFilename: "fallback.zip" });
assert.strictEqual(created.length, 1);
assert.strictEqual(created[0].getAttribute("download"), "fallback.zip");
@@ -38,10 +49,10 @@ module("Unit | Utility | download-blob", function (hooks) {
assert.true(created[0].click.calledOnce);
});
- test("triggerBlobDownload prefers the filename from Content-Disposition", function (assert) {
+ test("deliverBlobDownload prefers the filename from Content-Disposition", function (assert) {
const { created } = captureAnchor();
- triggerBlobDownload(new Blob(["x"]), {
+ deliverBlobDownload(new Blob(["x"]), {
fallbackFilename: "fallback.zip",
contentDisposition: 'attachment; filename="server-name.zip"',
});
@@ -49,10 +60,10 @@ module("Unit | Utility | download-blob", function (hooks) {
assert.strictEqual(created[0].getAttribute("download"), "server-name.zip");
});
- test("triggerBlobDownload parses RFC 5987 UTF-8 filename*", function (assert) {
+ test("deliverBlobDownload parses RFC 5987 UTF-8 filename*", function (assert) {
const { created } = captureAnchor();
- triggerBlobDownload(new Blob(["x"]), {
+ deliverBlobDownload(new Blob(["x"]), {
contentDisposition:
"attachment; filename=\"ascii-fallback.zip\"; filename*=UTF-8''caf%C3%A9.zip",
});
@@ -60,10 +71,10 @@ module("Unit | Utility | download-blob", function (hooks) {
assert.strictEqual(created[0].getAttribute("download"), "café.zip");
});
- test("triggerBlobDownload falls back to ASCII match when UTF-8 form is malformed", function (assert) {
+ test("deliverBlobDownload falls back to ASCII match when UTF-8 form is malformed", function (assert) {
const { created } = captureAnchor();
- triggerBlobDownload(new Blob(["x"]), {
+ deliverBlobDownload(new Blob(["x"]), {
contentDisposition:
"attachment; filename=\"ascii-only.zip\"; filename*=UTF-8''%E0%A4%A",
});
@@ -71,14 +82,50 @@ module("Unit | Utility | download-blob", function (hooks) {
assert.strictEqual(created[0].getAttribute("download"), "ascii-only.zip");
});
- test("triggerBlobDownload omits the download attribute when no filename is available", function (assert) {
+ test("deliverBlobDownload omits the download attribute when no filename is available", function (assert) {
const { created } = captureAnchor();
- triggerBlobDownload(new Blob(["x"]));
+ deliverBlobDownload(new Blob(["x"]));
assert.false(created[0].hasAttribute("download"));
});
+ test("bridgeBlobDownload posts a download message to Hub", async function (assert) {
+ const postMessage = sinon.stub();
+ window.ReactNativeWebView = { postMessage };
+ sinon.stub(window, "FileReader").value(
+ class {
+ readAsDataURL() {
+ this.result = "data:application/zip;base64,eA==";
+ this.onload();
+ }
+ }
+ );
+
+ await bridgeBlobDownload(new Blob(["x"], { type: "application/zip" }), {
+ fallbackFilename: "theme.zip",
+ });
+
+ const message = JSON.parse(postMessage.firstCall.args[0]);
+ assert.deepEqual(message, {
+ type: "download",
+ filename: "theme.zip",
+ mimeType: "application/zip",
+ data: "eA==",
+ });
+ delete window.ReactNativeWebView;
+ });
+
+ test("bridgeBlobDownload rejects files over the bridge limit", async function (assert) {
+ await assert.rejects(
+ bridgeBlobDownload(
+ { size: MAX_BRIDGED_DOWNLOAD_BYTES + 1 },
+ { fallbackFilename: "large.zip" }
+ ),
+ /too large/
+ );
+ });
+
test("downloadBlob fetches the URL and triggers a download", async function (assert) {
const { created } = captureAnchor();
const blob = new Blob(["zip-bytes"]);
diff --git a/frontend/discourse/tests/unit/lib/download-strategy-test.js b/frontend/discourse/tests/unit/lib/download-strategy-test.js
index a69cee59fc1..d074be40de9 100644
--- a/frontend/discourse/tests/unit/lib/download-strategy-test.js
+++ b/frontend/discourse/tests/unit/lib/download-strategy-test.js
@@ -13,7 +13,35 @@ module("Unit | Utility | download-strategy", function (hooks) {
assert.strictEqual(attachmentDownloadStrategy(), "native");
});
+ test("returns 'bridge' on iOS once the Hub app confirms bridge support", function (assert) {
+ sinon.stub(capabilities, "isAppWebview").value(true);
+ sinon.stub(capabilities, "isIOS").value(true);
+ sinon.stub(capabilities, "hubDownloadBridgeSupported").value(true);
+ sinon.stub(capabilities, "isPwa").value(false);
+
+ assert.strictEqual(attachmentDownloadStrategy(), "bridge");
+ });
+
+ test("returns 'native' in an Android app webview", function (assert) {
+ sinon.stub(capabilities, "isAppWebview").value(true);
+ sinon.stub(capabilities, "isIOS").value(false);
+ sinon.stub(capabilities, "hubDownloadBridgeSupported").value(true);
+ sinon.stub(capabilities, "isPwa").value(false);
+
+ assert.strictEqual(attachmentDownloadStrategy(), "native");
+ });
+
+ test("returns 'native' on iOS when the Hub app hasn't shipped bridge support yet", function (assert) {
+ sinon.stub(capabilities, "isAppWebview").value(true);
+ sinon.stub(capabilities, "isIOS").value(true);
+ sinon.stub(capabilities, "hubDownloadBridgeSupported").value(false);
+ sinon.stub(capabilities, "isPwa").value(false);
+
+ assert.strictEqual(attachmentDownloadStrategy(), "native");
+ });
+
test("returns 'blob' in a PWA", function (assert) {
+ sinon.stub(capabilities, "isAppWebview").value(false);
sinon.stub(capabilities, "isPwa").value(true);
assert.strictEqual(attachmentDownloadStrategy(), "blob");