A platform for community discussion. Free, open, simple.
FEATURE: Accept shared files via the Web Share Target (#41030)
Rafael dos Santos Silva6167f3bbac14
diff --git a/app/assets/stylesheets/common/modal/_index.scss b/app/assets/stylesheets/common/modal/_index.scssindex cd4744ea891..6b8b9337887 100644--- a/app/assets/stylesheets/common/modal/_index.scss+++ b/app/assets/stylesheets/common/modal/_index.scss@@ -3,3 +3,4 @@@import "discourse-reactions-popup";@import "change-reply-to";@import "manage-reports-modal";+@import "share-target";diff --git a/app/assets/stylesheets/common/modal/share-target.scss b/app/assets/stylesheets/common/modal/share-target.scssnew file mode 100644index 00000000000..012defc2255--- /dev/null+++ b/app/assets/stylesheets/common/modal/share-target.scss@@ -0,0 +1,42 @@+.share-target-modal {+ &__intro {+ margin-top: 0;+ }++ &__preview-text {+ padding: 0.5em 0.75em;+ background: var(--primary-very-low);+ border-radius: var(--d-border-radius);+ white-space: pre-wrap;+ word-break: break-word;+ max-height: 8em;+ overflow-y: auto;+ }++ &__files {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5em;+ margin-top: 0.75em;+ }++ &__thumbnail {+ width: 80px;+ height: 80px;+ object-fit: cover;+ border-radius: var(--d-border-radius);+ border: 1px solid var(--primary-low);+ }++ &__file-name {+ padding: 0.25em 0.5em;+ background: var(--primary-very-low);+ border-radius: var(--d-border-radius);+ font-size: var(--font-down-1);+ word-break: break-all;+ }++ .d-modal__footer {+ flex-wrap: wrap;+ }+}diff --git a/app/controllers/metadata_controller.rb b/app/controllers/metadata_controller.rbindex 6a619f3afe0..0e6e491f267 100644--- a/app/controllers/metadata_controller.rb+++ b/app/controllers/metadata_controller.rb@@ -43,6 +43,20 @@ class MetadataController < ApplicationControllerprivate+ # The accepted file types for the Web Share Target, derived from the+ # `authorized_extensions` site setting so the share sheet only offers+ # Discourse for files it can actually accept. Each extension is expressed in+ # the dotted form the Web Share Target spec expects (e.g. ".jpg"). Falls back+ # to any file type when the site authorizes all extensions ("*").+ def share_target_accept+ extensions =+ SiteSetting.authorized_extensions.gsub(/[\s.]+/, "").downcase.split("|").reject(&:blank?)++ return ["*/*"] if extensions.include?("*")++ extensions.map { |extension| ".#{extension}" }.presence || ["*/*"]+ end+def default_manifestdisplay = "standalone"if request.user_agent@@ -64,13 +78,14 @@ class MetadataController < ApplicationControllertheme_color: "##{ColorScheme.hex_for_name("header_background", scheme_id)}",icons: [],share_target: {- action: "#{Discourse.base_path}/new-topic",- method: "GET",- enctype: "application/x-www-form-urlencoded",+ action: "#{Discourse.base_path}/share-target",+ method: "POST",+ enctype: "multipart/form-data",params: {- text: "body",title: "title",- url: "title",+ text: "text",+ url: "url",+ files: [{ name: "files", accept: share_target_accept }],},},shortcuts: [diff --git a/app/views/static/service-worker.js.erb b/app/views/static/service-worker.js.erbindex e982ae788b5..0a0e94126a1 100644--- a/app/views/static/service-worker.js.erb+++ b/app/views/static/service-worker.js.erb@@ -125,6 +125,76 @@ self.addEventListener('pushsubscriptionchange', function(event) {);});+// Web Share Target (Level 2). The manifest registers a multipart/form-data+// POST share target at SHARE_TARGET_PATH. Browsers can't hand a multipart body+// to a single-page app directly, so we intercept the POST here, stash the+// shared title/text/url/files in the Cache API, and redirect to the same path+// as a GET navigation. The Ember `share-target` route then reads the payload+// back out of the cache and opens the "what do you want to do?" modal.+var SHARE_TARGET_PATH = '<%= Discourse.base_path %>/share-target';+var SHARE_TARGET_CACHE = 'discourse-share-target';+var SHARE_TARGET_KEY_PREFIX = '/__discourse_share_target__/';++function stashSharedContent(request) {+ return request.formData().then(function (formData) {+ return caches.open(SHARE_TARGET_CACHE).then(function (cache) {+ var files = formData.getAll('files').filter(function (file) {+ return file && typeof file !== 'string';+ });++ var fileMeta = [];+ var puts = files.map(function (file, index) {+ var key = SHARE_TARGET_KEY_PREFIX + 'file-' + index;+ fileMeta.push({ key: key, name: file.name, type: file.type });+ return cache.put(+ new Request(key),+ new Response(file, {+ headers: {+ 'content-type': file.type || 'application/octet-stream',+ 'x-share-filename': encodeURIComponent(file.name || ('shared-file-' + index)),+ },+ })+ );+ });++ var meta = {+ title: formData.get('title') || '',+ text: formData.get('text') || '',+ url: formData.get('url') || '',+ files: fileMeta,+ };++ puts.push(+ cache.put(+ new Request(SHARE_TARGET_KEY_PREFIX + 'meta'),+ new Response(JSON.stringify(meta), {+ headers: { 'content-type': 'application/json' },+ })+ )+ );++ return Promise.all(puts);+ });+ });+}++self.addEventListener('fetch', function (event) {+ var url = new URL(event.request.url);++ if (event.request.method === 'POST' && url.pathname === SHARE_TARGET_PATH) {+ event.respondWith(+ stashSharedContent(event.request)+ .catch(function (err) {+ console.error('Failed to stash shared content', err);+ })+ .then(function () {+ // 303 forces the follow-up navigation to be a GET.+ return Response.redirect(SHARE_TARGET_PATH, 303);+ })+ );+ }+});+self.addEventListener('message', function(event) {if (event.data?.action !== "primaryTab") {return;diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex 0a394987bcf..4d6ae9e68c8 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -4196,6 +4196,13 @@ en:banner: "You are viewing a single thread from this topic."view_full_topic: "View full topic"view_parent_context: "View parent context"+ share_target:+ title: "Shared content"+ description: "What would you like to do with the shared content?"+ new_topic: "New topic"+ new_message: "New message"+ add_to_reply: "Add to a reply"+ added_to_reply: "Saved. The content will be added the next time you open a reply."topic:filter_to:one: "%{count} post in topic"diff --git a/config/routes.rb b/config/routes.rbindex 4f81f49a8ce..367b0491f26 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -1527,6 +1527,9 @@ Discourse::Application.routes.draw doget "new-topic" => "new_topic#index"get "new-message" => "new_topic#index"+ # Landing page for the PWA Web Share Target. The service worker intercepts+ # the incoming multipart POST, stashes the payload, and redirects here.+ get "share-target" => "new_topic#index"get "new-invite" => "new_invite#index"# Topic routesdiff --git a/frontend/discourse/app/components/modal/share-target.gjs b/frontend/discourse/app/components/modal/share-target.gjsnew file mode 100644index 00000000000..0389826d301--- /dev/null+++ b/frontend/discourse/app/components/modal/share-target.gjs@@ -0,0 +1,149 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import { service } from "@ember/service";+import { sharedBody } from "discourse/lib/share-target";+import DButton from "discourse/ui-kit/d-button";+import DModal from "discourse/ui-kit/d-modal";+import { i18n } from "discourse-i18n";++export default class ShareTargetModal extends Component {+ @service appEvents;+ @service composer;+ @service("shared-content") sharedContent;+ @service toasts;++ previews;++ constructor() {+ super(...arguments);++ // Build image thumbnails for any shared files. Done in the constructor+ // (not a field initializer) so `this.args` is reliably available.+ this.previews = this.files.map((file) => {+ const isImage = file.type?.startsWith("image/");+ return {+ name: file.name,+ isImage,+ url: isImage ? URL.createObjectURL(file) : null,+ };+ });+ }++ willDestroy() {+ super.willDestroy(...arguments);+ this.previews.forEach((preview) => {+ if (preview.url) {+ URL.revokeObjectURL(preview.url);+ }+ });+ }++ get title() {+ return this.args.model.title;+ }++ get files() {+ return this.args.model.files || [];+ }++ get body() {+ return sharedBody(this.args.model);+ }++ get hasText() {+ return !!this.body;+ }++ #addFilesWhenReady(files) {+ if (!files.length) {+ return;+ }++ // Capture `files` in the closure rather than reading from `this` — the+ // modal is torn down by closeModal() before the composer's uploader is+ // ready and fires this event.+ this.appEvents.one("composer:uploader-ready", () => {+ this.appEvents.trigger("composer:add-files", files);+ });+ }++ @action+ createTopic() {+ this.#addFilesWhenReady(this.files);+ this.composer.openNewTopic({ title: this.title, body: this.body });+ this.args.closeModal();+ }++ @action+ createMessage() {+ this.#addFilesWhenReady(this.files);+ this.composer.openNewMessage({ title: this.title, body: this.body });+ this.args.closeModal();+ }++ @action+ addToReply() {+ this.sharedContent.storeForReply({ body: this.body, files: this.files });+ this.toasts.success({+ data: { message: i18n("share_target.added_to_reply") },+ });+ this.args.closeModal();+ }++ <template>+ <DModal+ @title={{i18n "share_target.title"}}+ @closeModal={{@closeModal}}+ class="share-target-modal"+ >+ <:body>+ <p class="share-target-modal__intro">{{i18n+ "share_target.description"+ }}</p>++ {{#if this.hasText}}+ <div class="share-target-modal__preview-text">{{this.body}}</div>+ {{/if}}++ {{#if this.previews.length}}+ <div class="share-target-modal__files">+ {{#each this.previews as |preview|}}+ {{#if preview.isImage}}+ <img+ class="share-target-modal__thumbnail"+ src={{preview.url}}+ alt={{preview.name}}+ />+ {{else}}+ <span+ class="share-target-modal__file-name"+ >{{preview.name}}</span>+ {{/if}}+ {{/each}}+ </div>+ {{/if}}+ </:body>++ <:footer>+ <DButton+ @action={{this.createTopic}}+ @label="share_target.new_topic"+ @icon="far-pen-to-square"+ class="btn-primary share-target-modal__new-topic"+ />+ <DButton+ @action={{this.createMessage}}+ @label="share_target.new_message"+ @icon="envelope"+ class="share-target-modal__new-message"+ />+ <DButton+ @action={{this.addToReply}}+ @label="share_target.add_to_reply"+ @icon="reply"+ class="share-target-modal__add-to-reply"+ />+ </:footer>+ </DModal>+ </template>+}diff --git a/frontend/discourse/app/instance-initializers/share-target.js b/frontend/discourse/app/instance-initializers/share-target.jsnew file mode 100644index 00000000000..50228506c17--- /dev/null+++ b/frontend/discourse/app/instance-initializers/share-target.js@@ -0,0 +1,16 @@+import { REPLY } from "discourse/models/composer";++// When content was shared into Discourse and the user chose "Add to a reply",+// inject it into the next reply composer that opens.+export default {+ initialize(owner) {+ const appEvents = owner.lookup("service:app-events");+ const sharedContent = owner.lookup("service:shared-content");++ appEvents.on("composer:open", ({ model }) => {+ if (model?.action === REPLY && sharedContent.hasPending) {+ sharedContent.consumeInto(model);+ }+ });+ },+};diff --git a/frontend/discourse/app/lib/share-target.js b/frontend/discourse/app/lib/share-target.jsnew file mode 100644index 00000000000..5c875f3f803--- /dev/null+++ b/frontend/discourse/app/lib/share-target.js@@ -0,0 +1,69 @@+// Reads the Web Share Target payload that the service worker stashed in the+// Cache API before redirecting to the `share-target` route. Keep these+// constants in sync with app/views/static/service-worker.js.erb.+const SHARE_TARGET_CACHE = "discourse-share-target";+const SHARE_TARGET_KEY_PREFIX = "/__discourse_share_target__/";++export async function readSharedContent() {+ if (typeof caches === "undefined") {+ return null;+ }++ let cache;+ try {+ cache = await caches.open(SHARE_TARGET_CACHE);+ } catch {+ return null;+ }++ const metaResponse = await cache.match(+ new Request(SHARE_TARGET_KEY_PREFIX + "meta")+ );++ if (!metaResponse) {+ return null;+ }++ const meta = await metaResponse.json();++ const files = [];+ for (const fileMeta of meta.files || []) {+ const fileResponse = await cache.match(new Request(fileMeta.key));+ if (!fileResponse) {+ continue;+ }++ const blob = await fileResponse.blob();+ const name = decodeURIComponent(+ fileResponse.headers.get("x-share-filename") ||+ fileMeta.name ||+ "shared-file"+ );++ files.push(new File([blob], name, { type: fileMeta.type || blob.type }));+ }++ return {+ title: meta.title || "",+ text: meta.text || "",+ url: meta.url || "",+ files,+ };+}++export async function clearSharedContent() {+ if (typeof caches === "undefined") {+ return;+ }++ try {+ await caches.delete(SHARE_TARGET_CACHE);+ } catch {+ // nothing to clear+ }+}++// Combines the shared text and url into a single composer body.+export function sharedBody({ text, url } = {}) {+ return [text, url].filter(Boolean).join("\n\n");+}diff --git a/frontend/discourse/app/lib/uppy/composer-upload.js b/frontend/discourse/app/lib/uppy/composer-upload.jsindex 5f5bf81893f..9d2f04acd7f 100644--- a/frontend/discourse/app/lib/uppy/composer-upload.js+++ b/frontend/discourse/app/lib/uppy/composer-upload.js@@ -433,6 +433,11 @@ export default class UppyComposerUpload {this.#uploadTargetBound = true;this.#bindMobileUploadButton();++ // Signals that the uploader is bound and ready to accept files via the+ // `${composerEventPrefix}:add-files` event, e.g. for content shared into+ // the composer through the Web Share Target.+ this.appEvents.trigger(`${this.composerEventPrefix}:uploader-ready`);}@binddiff --git a/frontend/discourse/app/routes/app-route-map.js b/frontend/discourse/app/routes/app-route-map.jsindex d6146170a24..01ccd7b96c3 100644--- a/frontend/discourse/app/routes/app-route-map.js+++ b/frontend/discourse/app/routes/app-route-map.js@@ -217,6 +217,7 @@ export default function () {this.route("new-topic");this.route("new-message");this.route("new-invite");+ this.route("share-target");this.route("badges", function () {this.route("show", { path: "/:id/:slug" });diff --git a/frontend/discourse/app/routes/share-target.js b/frontend/discourse/app/routes/share-target.jsnew file mode 100644index 00000000000..f14202ca432--- /dev/null+++ b/frontend/discourse/app/routes/share-target.js@@ -0,0 +1,40 @@+import { service } from "@ember/service";+import ShareTargetModal from "discourse/components/modal/share-target";+import { defaultHomepage } from "discourse/lib/utilities";+import DiscourseRoute from "discourse/routes/discourse";++export default class extends DiscourseRoute {+ @service appEvents;+ @service currentUser;+ @service modal;+ @service router;+ @service("shared-content") sharedContent;++ async beforeModel(transition) {+ if (!this.currentUser) {+ transition.send("showLogin");+ return;+ }++ const shared = await this.sharedContent.readShared();+ await this.sharedContent.clearShared();++ if (shared && this.#hasContent(shared)) {+ // We arrive here from the service worker redirect while the app is still+ // booting, so the modal container isn't mounted yet — opening the modal+ // now would be lost. Wait for the first rendered page instead;+ // `page:changed` fires after a route has rendered.+ this.appEvents.one("page:changed", () => {+ this.modal.show(ShareTargetModal, { model: shared });+ });+ }++ // The share-target route has no UI of its own — send the user to the+ // homepage; the modal (if any) opens once that page has rendered.+ this.router.replaceWith(`discovery.${defaultHomepage()}`);+ }++ #hasContent({ title, text, url, files }) {+ return !!(title || text || url || files?.length);+ }+}diff --git a/frontend/discourse/app/services/shared-content.js b/frontend/discourse/app/services/shared-content.jsnew file mode 100644index 00000000000..74fedefce44--- /dev/null+++ b/frontend/discourse/app/services/shared-content.js@@ -0,0 +1,55 @@+import { tracked } from "@glimmer/tracking";+import Service, { service } from "@ember/service";+import {+ clearSharedContent,+ readSharedContent,+} from "discourse/lib/share-target";++// Holds content shared into Discourse via the Web Share Target when the user+// chose "Add to a reply". The app boots fresh from the OS share sheet with no+// topic open, so we keep the payload here and inject it into the next reply+// composer that opens (see instance-initializers/share-target.js).+export default class SharedContent extends Service {+ @service appEvents;++ @tracked pending = null;++ // Reads the payload the service worker stashed before redirecting to the+ // `share-target` route. Wrapped here so it can be stubbed in tests.+ readShared() {+ return readSharedContent();+ }++ clearShared() {+ return clearSharedContent();+ }++ get hasPending() {+ return !!this.pending;+ }++ storeForReply({ body, files }) {+ this.pending = { body, files };+ }++ consumeInto(model) {+ if (!this.pending) {+ return;+ }++ const { body, files } = this.pending;+ this.pending = null;++ if (body) {+ model.appendText(body, null, { new_line: true });+ }++ if (files?.length) {+ // The uploader binds its listeners when the editor element is inserted,+ // which happens after `composer:open` fires. Wait for it to be ready.+ this.appEvents.one("composer:uploader-ready", () => {+ this.appEvents.trigger("composer:add-files", files);+ });+ }+ }+}diff --git a/spec/requests/metadata_controller_spec.rb b/spec/requests/metadata_controller_spec.rbindex ce544c62aed..b6ca1a8bbbc 100644--- a/spec/requests/metadata_controller_spec.rb+++ b/spec/requests/metadata_controller_spec.rb@@ -33,10 +33,29 @@ RSpec.describe MetadataController doget "/manifest.webmanifest"expect(response.status).to eq(200)manifest = JSON.parse(response.body)- expect(manifest["share_target"]).to be_present- expect(manifest["share_target"]["params"]["title"]).to eq("title")- expect(manifest["share_target"]["params"]["text"]).to eq("body")- expect(manifest["share_target"]["params"]["url"]).to eq("title")+ share_target = manifest["share_target"]+ expect(share_target).to be_present+ expect(share_target["action"]).to end_with("/share-target")+ expect(share_target["method"]).to eq("POST")+ expect(share_target["enctype"]).to eq("multipart/form-data")+ expect(share_target["params"]["title"]).to eq("title")+ expect(share_target["params"]["text"]).to eq("text")+ expect(share_target["params"]["url"]).to eq("url")+ expect(share_target["params"]["files"].first["name"]).to eq("files")+ end++ it "derives the share target accepted files from authorized_extensions" do+ SiteSetting.authorized_extensions = "png|pdf"+ get "/manifest.webmanifest"+ accept = JSON.parse(response.body)["share_target"]["params"]["files"].first["accept"]+ expect(accept).to contain_exactly(".png", ".pdf")+ end++ it "accepts any file type when all extensions are authorized" do+ SiteSetting.authorized_extensions = "*"+ get "/manifest.webmanifest"+ accept = JSON.parse(response.body)["share_target"]["params"]["files"].first["accept"]+ expect(accept).to eq(["*/*"])endit "can guess mime types" dodiff --git a/spec/system/page_objects/modals/share_target.rb b/spec/system/page_objects/modals/share_target.rbnew file mode 100644index 00000000000..44d2ec1e43f--- /dev/null+++ b/spec/system/page_objects/modals/share_target.rb@@ -0,0 +1,19 @@+# frozen_string_literal: true++module PageObjects+ module Modals+ class ShareTarget < PageObjects::Modals::Base+ def initialize+ super(modal_selector: ".share-target-modal")+ end++ def click_new_topic+ footer.find(".share-target-modal__new-topic").click+ end++ def has_preview_text?(text)+ body.has_css?(".share-target-modal__preview-text", text: text)+ end+ end+ end+enddiff --git a/spec/system/share_target_spec.rb b/spec/system/share_target_spec.rbnew file mode 100644index 00000000000..7c9df38357c--- /dev/null+++ b/spec/system/share_target_spec.rb@@ -0,0 +1,103 @@+# frozen_string_literal: true++RSpec.describe "Share target" do+ fab!(:user)++ let(:composer) { PageObjects::Components::Composer.new }+ let(:share_target_modal) { PageObjects::Modals::ShareTarget.new }++ before { sign_in(user) }++ it "lets the user start a new topic from shared content", mobile: true do+ title = "Shared topic title"+ text = "Shared text from another app"+ url = "https://example.com/shared-link"+ expected_body = "#{text}\n\n#{url}"++ visit("/")+ seed_shared_content(title:, text:, url:, files: [shared_image_file])++ visit("/share-target")++ expect(share_target_modal).to be_open+ expect(share_target_modal).to have_preview_text(text)+ expect(share_target_modal).to have_preview_text(url)++ share_target_modal.click_new_topic++ expect(composer).to be_opened+ expect(composer).to have_input_title(title)++ wait_for(timeout: 5) { composer.composer_input.value.include?("upload://") }+ expect(composer).to have_no_in_progress_uploads++ composer_value = composer.composer_input.value+ expect(composer_value).to include(expected_body)+ expect(composer_value).to match(%r{!\[shared-image\|.*\]\(upload://.*\)})+ end++ def seed_shared_content(title:, text:, url:, files:)+ page.execute_script(<<~JS)+ window.__shareTargetCacheSeeded = false;+ window.__shareTargetCacheSeedError = "";++ (async () => {+ await caches.delete("discourse-share-target");+ const cache = await caches.open("discourse-share-target");+ const files = #{files.to_json};++ for (const [index, file] of files.entries()) {+ const binary = atob(file.base64);+ const bytes = new Uint8Array(binary.length);++ for (let byteIndex = 0; byteIndex < binary.length; byteIndex++) {+ bytes[byteIndex] = binary.charCodeAt(byteIndex);+ }++ await cache.put(+ new Request(file.key),+ new Response(+ new Blob([bytes], { type: file.type }),+ {+ headers: {+ "content-type": file.type,+ "x-share-filename": encodeURIComponent(file.name || `shared-file-${index}`),+ },+ }+ )+ );+ }++ await cache.put(+ new Request("/__discourse_share_target__/meta"),+ new Response(+ JSON.stringify({+ title: #{title.to_json},+ text: #{text.to_json},+ url: #{url.to_json},+ files: files.map(({ key, name, type }) => ({ key, name, type })),+ }),+ { headers: { "content-type": "application/json" } }+ )+ );+ window.__shareTargetCacheSeeded = true;+ })().catch((error) => {+ window.__shareTargetCacheSeedError = `${error.name}: ${error.message}`;+ });+ JS++ wait_for(timeout: 5) { page.evaluate_script("window.__shareTargetCacheSeeded === true") }++ expect(page.evaluate_script("window.__shareTargetCacheSeedError")).to eq("")+ end++ def shared_image_file+ {+ key: "/__discourse_share_target__/file-0",+ name: "shared-image.png",+ type: "image/png",+ base64:+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=",+ }+ end+end