A platform for community discussion. Free, open, simple.
FIX: Export Theme - PWA fix (#42454)
Bannon Tanner9fbd8d9d8a6a
diff --git a/frontend/discourse/admin/components/admin-config-areas/components.gjs b/frontend/discourse/admin/components/admin-config-areas/components.gjsindex 685e5368537..88c28fedf4e 100644--- a/frontend/discourse/admin/components/admin-config-areas/components.gjs+++ b/frontend/discourse/admin/components/admin-config-areas/components.gjs@@ -15,6 +15,8 @@ import lazyHash from "discourse/helpers/lazy-hash";import { ajax } from "discourse/lib/ajax";import { extractErrorInfo } from "discourse/lib/ajax-error";import discourseDebounce from "discourse/lib/debounce";+import downloadBlob from "discourse/lib/download-blob";+import { attachmentDownloadStrategy } from "discourse/lib/download-strategy";import { INPUT_DELAY } from "discourse/lib/environment";import getURL from "discourse/lib/get-url";import { descriptionForRemoteUrl } from "discourse/lib/popular-themes";@@ -454,6 +456,21 @@ class ComponentRow extends Component {}}+ get exportAction() {+ return attachmentDownloadStrategy() === "native" ? undefined : this.export;+ }++ @action+ async export() {+ try {+ await downloadBlob(+ getURL(`/admin/customize/themes/${this.args.component.id}/export`)+ );+ } catch {+ this.dialog.alert(i18n("generic_error"));+ }+ }+@actiondelete() {return this.dialog.deleteConfirm({@@ -636,8 +653,6 @@ class ComponentRow extends Component {<dropdown.item><DButtonclass="btn-transparent admin-config-components__export"- target="_blank"- rel="noopener noreferrer"@label="admin.config_areas.themes_and_components.components.export"@icon="download"@href={{getURL@@ -645,6 +660,7 @@ class ComponentRow extends Component {"/admin/customize/themes/" @component.id "/export")}}+ @action={{this.exportAction}}/></dropdown.item><dropdown.item>diff --git a/frontend/discourse/admin/controllers/admin-customize-themes/show/index.js b/frontend/discourse/admin/controllers/admin-customize-themes/show/index.jsindex 55ca2e7eec4..8e0bbb66ab2 100644--- a/frontend/discourse/admin/controllers/admin-customize-themes/show/index.js+++ b/frontend/discourse/admin/controllers/admin-customize-themes/show/index.js@@ -10,6 +10,8 @@ import ThemeSettings from "discourse/admin/models/theme-settings";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";import { removeValueFromArray } from "discourse/lib/array-tools";+import downloadBlob from "discourse/lib/download-blob";+import { attachmentDownloadStrategy } from "discourse/lib/download-strategy";import getURL from "discourse/lib/get-url";import { makeArray } from "discourse/lib/helpers";import { i18n } from "discourse-i18n";@@ -358,6 +360,21 @@ export default class AdminCustomizeThemesShowIndexController extends Controllerreturn this.model?.user?.id > 0 && !this.model?.default;}+ get exportAction() {+ return attachmentDownloadStrategy() === "native"+ ? undefined+ : this.exportTheme;+ }++ @action+ async exportTheme() {+ try {+ await downloadBlob(this.downloadUrl);+ } catch {+ this.dialog.alert(i18n("generic_error"));+ }+ }+@actionrefreshModel() {this.send("routeRefreshModel");diff --git a/frontend/discourse/admin/controllers/admin-watched-words/action.js b/frontend/discourse/admin/controllers/admin-watched-words/action.jsindex e9195328020..61a9a8bdc31 100644--- a/frontend/discourse/admin/controllers/admin-watched-words/action.js+++ b/frontend/discourse/admin/controllers/admin-watched-words/action.js@@ -6,6 +6,8 @@ import { schedule } from "@ember/runloop";import { service } from "@ember/service";import WatchedWordTestingModal from "discourse/admin/components/modal/watched-word-testing";import { ajax } from "discourse/lib/ajax";+import downloadBlob from "discourse/lib/download-blob";+import { attachmentDownloadStrategy } from "discourse/lib/download-strategy";import { i18n } from "discourse-i18n";export default class AdminWatchedWordsActionController extends Controller {@@ -119,6 +121,21 @@ export default class AdminWatchedWordsActionController extends Controller {return this.adminWatchedWords.updateAllWords();}+ get downloadAction() {+ return attachmentDownloadStrategy() === "native"+ ? undefined+ : this.download;+ }++ @action+ async download() {+ try {+ await downloadBlob(this.downloadLink);+ } catch {+ this.dialog.alert(i18n("generic_error"));+ }+ }+@actionasync test() {await this.adminWatchedWords.updateAllWords();diff --git a/frontend/discourse/admin/services/admin-emojis.js b/frontend/discourse/admin/services/admin-emojis.jsindex a23878f8e11..aea94df1239 100644--- a/frontend/discourse/admin/services/admin-emojis.js+++ b/frontend/discourse/admin/services/admin-emojis.js@@ -7,6 +7,7 @@ import {removeValueFromArray,uniqueItemsFromArray,} from "discourse/lib/array-tools";+import { triggerBlobDownload } 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";@@ -72,15 +73,10 @@ export default class AdminEmojis extends Service {return;}- const blob = await response.blob();- const objectUrl = URL.createObjectURL(blob);- const a = document.createElement("a");- a.href = objectUrl;- a.download = "emojis.zip";- document.body.appendChild(a);- a.click();- document.body.removeChild(a);- setTimeout(() => URL.revokeObjectURL(objectUrl), 20_000);+ triggerBlobDownload(await response.blob(), {+ fallbackFilename: "emojis.zip",+ contentDisposition: response.headers.get("Content-Disposition"),+ });} catch {this.dialog.alert(i18n("admin.emoji.export_failed"));} finally {diff --git a/frontend/discourse/admin/templates/admin-customize-themes/show/index.gjs b/frontend/discourse/admin/templates/admin-customize-themes/show/index.gjsindex bbf73a7f4f4..404588d46f3 100644--- a/frontend/discourse/admin/templates/admin-customize-themes/show/index.gjs+++ b/frontend/discourse/admin/templates/admin-customize-themes/show/index.gjs@@ -483,12 +483,13 @@ export default <template>class="btn btn-default">{{dIcon "desktop"}}{{i18n "admin.customize.theme.preview"}}</a>{{#unless @controller.model.system}}- <a- class="btn btn-default export"- rel="noopener noreferrer"- target="_blank"- href={{@controller.downloadUrl}}- >{{dIcon "download"}} {{i18n "admin.export_json.button_text"}}</a>+ <DButton+ class="btn-default export"+ @href={{@controller.downloadUrl}}+ @action={{@controller.exportAction}}+ @icon="download"+ @label="admin.export_json.button_text"+ />{{/unless}}{{#if @controller.showConvert}}diff --git a/frontend/discourse/admin/templates/admin-watched-words/action.gjs b/frontend/discourse/admin/templates/admin-watched-words/action.gjsindex 729a1726e8c..869268a1881 100644--- a/frontend/discourse/admin/templates/admin-watched-words/action.gjs+++ b/frontend/discourse/admin/templates/admin-watched-words/action.gjs@@ -25,6 +25,7 @@ export default <template><div class="watched-word-controls"><DButton@href={{@controller.downloadLink}}+ @action={{@controller.downloadAction}}@icon="download"@label="admin.watched_words.download"class="btn-default download-link"diff --git a/frontend/discourse/app/lib/download-blob.js b/frontend/discourse/app/lib/download-blob.jsnew file mode 100644index 00000000000..9129b129847--- /dev/null+++ b/frontend/discourse/app/lib/download-blob.js@@ -0,0 +1,60 @@+const REVOKE_AFTER = 20_000;++function parseFilename(contentDisposition) {+ if (!contentDisposition) {+ return null;+ }+ const utf8Match = contentDisposition.match(+ /filename\*\s*=\s*UTF-8''([^;]+)/i+ );+ if (utf8Match) {+ try {+ return decodeURIComponent(utf8Match[1].trim().replace(/^"|"$/g, ""));+ } catch {+ // fall through to ascii match+ }+ }+ const asciiMatch = contentDisposition.match(/filename\s*=\s*"?([^";]+)"?/i);+ 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(+ blob,+ { fallbackFilename, contentDisposition } = {}+) {+ const objectUrl = URL.createObjectURL(blob);+ const filename = parseFilename(contentDisposition) ?? fallbackFilename;+ const a = document.createElement("a");+ a.href = objectUrl;+ if (filename) {+ a.download = filename;+ }+ a.rel = "noopener";+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ setTimeout(() => URL.revokeObjectURL(objectUrl), REVOKE_AFTER);+}++// Fetches `url` and triggers a browser download of the response body.+export default async function downloadBlob(+ url,+ { fallbackFilename, fetchOptions } = {}+) {+ const response = await fetch(url, {+ credentials: "same-origin",+ ...fetchOptions,+ });+ if (!response.ok) {+ throw new Error(`Download failed: ${response.status}`);+ }+ triggerBlobDownload(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.jsnew file mode 100644index 00000000000..b1c4642ce0f--- /dev/null+++ b/frontend/discourse/app/lib/download-strategy.js@@ -0,0 +1,18 @@+import { capabilities } from "discourse/services/capabilities";++// Reports how the current runtime handles server-generated attachment+// downloads (responses with `Content-Disposition: attachment`).+//+// "native" — a plain <a href> triggers a proper download: the browser+// streams to disk, uses its own header parser to pick the+// filename, and shows its native progress UI. This is the case+// for desktop and mobile browsers.+// "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.+export function attachmentDownloadStrategy() {+ if (capabilities.isPwa) {+ return "blob";+ }+ return "native";+}diff --git a/frontend/discourse/app/lib/url.js b/frontend/discourse/app/lib/url.jsindex 847a6048f5f..37e1a78bd64 100644--- a/frontend/discourse/app/lib/url.js+++ b/frontend/discourse/app/lib/url.js@@ -33,6 +33,7 @@ const SERVER_SIDE_ONLY = [/\.json$/,/^\/logs($|\/)/,/^\/admin\/customize\/watched_words\/action\/[^\/]+\/download$/,+ /^\/admin\/customize\/themes\/\d+\/export$/,/^\/pub\//,/^\/invites\//,/^\/styleguide/,diff --git a/frontend/discourse/tests/unit/lib/download-blob-test.js b/frontend/discourse/tests/unit/lib/download-blob-test.jsnew file mode 100644index 00000000000..55b7874043d--- /dev/null+++ b/frontend/discourse/tests/unit/lib/download-blob-test.js@@ -0,0 +1,110 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import sinon from "sinon";+import downloadBlob, { triggerBlobDownload } from "discourse/lib/download-blob";++function captureAnchor() {+ const original = document.createElement.bind(document);+ const created = [];+ const stub = sinon+ .stub(document, "createElement")+ .callsFake(function (tagName) {+ const el = original(tagName);+ if (tagName === "a") {+ created.push(el);+ sinon.stub(el, "click");+ }+ return el;+ });+ return { created, stub };+}++module("Unit | Utility | download-blob", function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ sinon.stub(URL, "createObjectURL").returns("blob:mock");+ sinon.stub(URL, "revokeObjectURL");+ });++ test("triggerBlobDownload uses fallbackFilename when no Content-Disposition", function (assert) {+ const { created } = captureAnchor();++ triggerBlobDownload(new Blob(["x"]), { fallbackFilename: "fallback.zip" });++ assert.strictEqual(created.length, 1);+ assert.strictEqual(created[0].getAttribute("download"), "fallback.zip");+ assert.strictEqual(created[0].getAttribute("href"), "blob:mock");+ assert.true(created[0].click.calledOnce);+ });++ test("triggerBlobDownload prefers the filename from Content-Disposition", function (assert) {+ const { created } = captureAnchor();++ triggerBlobDownload(new Blob(["x"]), {+ fallbackFilename: "fallback.zip",+ contentDisposition: 'attachment; filename="server-name.zip"',+ });++ assert.strictEqual(created[0].getAttribute("download"), "server-name.zip");+ });++ test("triggerBlobDownload parses RFC 5987 UTF-8 filename*", function (assert) {+ const { created } = captureAnchor();++ triggerBlobDownload(new Blob(["x"]), {+ contentDisposition:+ "attachment; filename=\"ascii-fallback.zip\"; filename*=UTF-8''caf%C3%A9.zip",+ });++ assert.strictEqual(created[0].getAttribute("download"), "café.zip");+ });++ test("triggerBlobDownload falls back to ASCII match when UTF-8 form is malformed", function (assert) {+ const { created } = captureAnchor();++ triggerBlobDownload(new Blob(["x"]), {+ contentDisposition:+ "attachment; filename=\"ascii-only.zip\"; filename*=UTF-8''%E0%A4%A",+ });++ assert.strictEqual(created[0].getAttribute("download"), "ascii-only.zip");+ });++ test("triggerBlobDownload omits the download attribute when no filename is available", function (assert) {+ const { created } = captureAnchor();++ triggerBlobDownload(new Blob(["x"]));++ assert.false(created[0].hasAttribute("download"));+ });++ test("downloadBlob fetches the URL and triggers a download", async function (assert) {+ const { created } = captureAnchor();+ const blob = new Blob(["zip-bytes"]);+ const fetchStub = sinon.stub(window, "fetch").resolves(+ new Response(blob, {+ status: 200,+ headers: { "Content-Disposition": 'attachment; filename="theme.zip"' },+ })+ );++ await downloadBlob("/some/export");++ assert.true(+ fetchStub.calledWith(+ "/some/export",+ sinon.match({ credentials: "same-origin" })+ )+ );+ assert.strictEqual(created[0].getAttribute("download"), "theme.zip");+ });++ test("downloadBlob throws on non-2xx responses without triggering a download", async function (assert) {+ const { created } = captureAnchor();+ sinon.stub(window, "fetch").resolves(new Response("nope", { status: 500 }));++ await assert.rejects(downloadBlob("/some/export"), /Download failed: 500/);+ assert.strictEqual(created.length, 0);+ });+});diff --git a/frontend/discourse/tests/unit/lib/download-strategy-test.js b/frontend/discourse/tests/unit/lib/download-strategy-test.jsnew file mode 100644index 00000000000..a69cee59fc1--- /dev/null+++ b/frontend/discourse/tests/unit/lib/download-strategy-test.js@@ -0,0 +1,21 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import sinon from "sinon";+import { attachmentDownloadStrategy } from "discourse/lib/download-strategy";+import { capabilities } from "discourse/services/capabilities";++module("Unit | Utility | download-strategy", function (hooks) {+ setupTest(hooks);++ test("returns 'native' by default", function (assert) {+ sinon.stub(capabilities, "isPwa").value(false);++ assert.strictEqual(attachmentDownloadStrategy(), "native");+ });++ test("returns 'blob' in a PWA", function (assert) {+ sinon.stub(capabilities, "isPwa").value(true);++ assert.strictEqual(attachmentDownloadStrategy(), "blob");+ });+});