A platform for community discussion. Free, open, simple.
FEATURE: Add bulk emoji import/export for admins (#41816)
Steven Changbd3906ce640d
diff --git a/app/assets/stylesheets/admin/admin_base.scss b/app/assets/stylesheets/admin/admin_base.scssindex 25242091e5d..0f2b1e01e2c 100644--- a/app/assets/stylesheets/admin/admin_base.scss+++ b/app/assets/stylesheets/admin/admin_base.scss@@ -1310,3 +1310,4 @@ a.inline-editable-field {@import "admin/upcoming-changes";@import "admin/discourse_id";@import "admin/admin_new_category_setup";+@import "admin/admin_emoji";diff --git a/app/assets/stylesheets/admin/admin_emoji.scss b/app/assets/stylesheets/admin/admin_emoji.scssnew file mode 100644index 00000000000..a426275e46b--- /dev/null+++ b/app/assets/stylesheets/admin/admin_emoji.scss@@ -0,0 +1,97 @@+.admin-emoji-import {+ padding: 1rem 0;++ &__summary {+ color: var(--primary-medium);+ }++ &__section {+ margin-bottom: 2rem;+ }++ &__section-heading {+ color: var(--primary-medium);+ }++ &__section-count {+ font-weight: normal;+ margin-left: 0.25em;+ }++ &__section-description {+ font-size: var(--font-down-1);+ color: var(--primary-medium);+ margin-bottom: 0.5rem;+ }++ &__section-subtitle {+ display: block;+ font-size: var(--font-down-1);+ font-weight: normal;+ color: var(--primary-medium);+ margin-top: 0.15em;+ }++ &__table {+ display: grid;+ grid-template-columns:+ 10rem minmax(15rem, 1fr) minmax(10rem, 0.5fr)+ 1fr;++ thead,+ tbody,+ tr {+ display: grid;+ grid-column: 1 / -1;+ grid-template-columns: subgrid;+ grid-template-rows: auto;+ }++ .d-table__cell.--controls {+ text-align: unset;+ }+ }++ &__existing-value {+ display: block;+ margin-top: 0.25rem;+ color: var(--primary-medium);+ }++ &__actions {+ display: flex;+ gap: 0.5rem;+ margin-top: 1.5rem;+ }++ &__error {+ margin: 0;+ font-size: var(--font-down-1);+ color: var(--danger);+ }++ &__badge {+ font-size: var(--font-down-1);+ padding: 0.2em 0.5em;+ border-radius: var(--d-border-radius);++ &.--skip {+ color: var(--primary-medium);+ }+ }++ &__conflict-resolution {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+ font-size: var(--font-down-1);+ margin-top: 1px;++ label {+ display: flex;+ align-items: center;+ gap: 0.4rem;+ cursor: pointer;+ }+ }+}diff --git a/app/controllers/admin/emoji_controller.rb b/app/controllers/admin/emoji_controller.rbindex 6631399464d..26318720b21 100644--- a/app/controllers/admin/emoji_controller.rb+++ b/app/controllers/admin/emoji_controller.rb@@ -1,6 +1,16 @@# frozen_string_literal: true+require "csv"+class Admin::EmojiController < Admin::AdminController+ skip_before_action :check_xhr, only: [:export]++ IMPORT_PREVIEW_TTL = 2.hours.to_i+ IMPORT_MAX_ENTRIES = 1000+ IMPORT_MAX_BYTES = 500.megabytes+ IMPORT_MAX_COMPRESSION_RATIO = 20+ SUPPORTED_EXTENSIONS = %w[png gif svg].freeze+def indexrender_serialized(Emoji.custom, EmojiSerializer, root: false)end@@ -49,6 +59,284 @@ class Admin::EmojiController < Admin::AdminControllerendend+ def export+ names = Array(params[:names]).map(&:to_s).reject(&:blank?)+ if names.empty?+ return(+ render json: failed_json.merge(errors: [I18n.t("emoji.export.no_selection")]),+ status: :unprocessable_entity+ )+ end++ emojis = CustomEmoji.where(name: names).includes(:upload)+ return render json: failed_json, status: :not_found if emojis.empty?++ temp_dir = Dir.mktmpdir("discourse_emoji_export_")++ begin+ csv_rows = []++ emojis.each do |emoji|+ filename = "#{emoji.name}.#{emoji.upload.extension}"+ File.binwrite(File.join(temp_dir, filename), emoji.upload.content)+ group = emoji.group.presence+ group = nil if group == "default"+ csv_rows << [emoji.name, group, filename]+ end++ CSV.open(File.join(temp_dir, "emojis.csv"), "w") do |csv|+ csv << %w[name group filename]+ csv_rows.each { |row| csv << row }+ end++ zip_path = Compression::Zip.new.compress(File.dirname(temp_dir), File.basename(temp_dir))+ send_data File.binread(zip_path),+ type: "application/zip",+ disposition: "attachment",+ filename: "emojis.zip"+ ensure+ FileUtils.rm_rf(temp_dir)+ File.delete(zip_path) if zip_path && File.exist?(zip_path)+ end+ end++ def import_preview+ zip_file = params[:file]+ if zip_file.blank?+ return(+ render json: failed_json.merge(errors: [I18n.t("emoji.import.missing_file")]),+ status: :unprocessable_entity+ )+ end++ rows = []+ upload_map = {}++ hijack do+ begin+ Compression::SafeZipReader.open(+ zip_file.tempfile.path,+ max_entries: IMPORT_MAX_ENTRIES,+ max_total_bytes: IMPORT_MAX_BYTES,+ max_compression_ratio: IMPORT_MAX_COMPRESSION_RATIO,+ ) do |reader|+ csv_data = reader.read_entry("emojis.csv", max_bytes: 1.megabyte, required: true)++ csv_rows = CSV.parse(csv_data, headers: true)++ filenames_seen = {}+ parsed_rows = []++ csv_rows.each_with_index do |row, idx|+ name = row["name"].to_s.strip+ group = row["group"].to_s.strip.downcase.presence+ group = nil if group == "default"+ filename = row["filename"].to_s.strip++ errors = validate_import_row(name, group, filename, filenames_seen)+ filenames_seen[filename] = true++ parsed_rows << {+ idx: idx,+ name: name,+ group: group,+ filename: filename,+ errors: errors,+ }+ end++ valid_names = parsed_rows.filter_map { |r| r[:name] if r[:errors].empty? }+ existing_by_name = CustomEmoji.where(name: valid_names).includes(:upload).index_by(&:name)++ parsed_rows.each do |parsed|+ idx = parsed[:idx]+ name = parsed[:name]+ group = parsed[:group]+ filename = parsed[:filename]+ errors = parsed[:errors]++ if errors.any?+ rows << {+ index: idx,+ name: name,+ group: group || "default",+ filename: filename,+ category: "invalid",+ errors: errors,+ }+ next+ end++ tmp_image = Tempfile.new(["emoji_import_", ".#{File.extname(filename).delete(".")}"])+ tmp_image.binmode++ begin+ bytes_written =+ reader.stream_entry_to_file(+ filename,+ tmp_image,+ max_bytes: SiteSetting.max_image_size_kb.kilobytes,+ required: false,+ )++ if bytes_written.nil?+ rows << {+ index: idx,+ name: name,+ group: group || "default",+ filename: filename,+ category: "invalid",+ errors: [I18n.t("emoji.import.validation.missing_filename")],+ }+ next+ end++ tmp_image.rewind++ upload =+ UploadCreator.new(tmp_image, filename, type: "custom_emoji").create_for(+ current_user.id,+ )++ unless upload.persisted?+ rows << {+ index: idx,+ name: name,+ group: group || "default",+ filename: filename,+ category: "invalid",+ errors: upload.errors.full_messages,+ }+ next+ end++ upload.update_columns(retain_hours: 3)+ upload_map[filename] = upload.id++ category, existing_url, existing_group =+ classify_import_row(name, group, upload, existing_by_name[name])++ rows << {+ index: idx,+ name: name,+ group: group || "default",+ filename: filename,+ category: category,+ incoming_url: upload.url,+ existing_url: existing_url,+ existing_group: existing_group || "default",+ }+ ensure+ tmp_image.close!+ end+ end+ end+ rescue Compression::SafeZipReader::MissingEntryError+ return(+ render json: failed_json.merge(errors: [I18n.t("emoji.import.missing_csv")]),+ status: :unprocessable_entity+ )+ rescue Compression::SafeZipReader::TooManyEntriesError+ return(+ render json: failed_json.merge(errors: [I18n.t("emoji.import.too_many_entries")]),+ status: :unprocessable_entity+ )+ rescue Compression::SafeZipReader::EntryTooLargeError+ return(+ render json: failed_json.merge(errors: [I18n.t("emoji.import.file_too_large")]),+ status: :unprocessable_entity+ )+ end++ token = SecureRandom.hex+ manifest = { rows: rows, upload_map: upload_map }+ Discourse.redis.setex(import_preview_key(token), IMPORT_PREVIEW_TTL, manifest.to_json)++ render json: { token: token, rows: rows }+ end+ end++ def import_confirm+ token = params.require(:token)+ resolutions = params[:resolutions] || {}++ manifest_json = Discourse.redis.get(import_preview_key(token))+ if manifest_json.blank?+ return(+ render json: failed_json.merge(errors: [I18n.t("emoji.import.session_expired")]),+ status: :unprocessable_entity+ )+ end++ manifest = JSON.parse(manifest_json, symbolize_names: true)+ rows = manifest[:rows]+ upload_map = manifest[:upload_map]++ created = 0+ updated = 0+ skipped = 0++ actionable_names =+ rows+ .map { |r| r.transform_keys(&:to_s) }+ .reject { |r| %w[invalid identical].include?(r["category"]) }+ .filter_map { |r| r["name"] if (resolutions[r["name"].to_s] || "incoming") != "keep" }+ existing_by_name = CustomEmoji.where(name: actionable_names).index_by(&:name)++ ActiveRecord::Base.transaction do+ rows.each do |row|+ row = row.transform_keys(&:to_s)+ name = row["name"]+ group = row["group"].presence+ filename = row["filename"]+ category = row["category"]++ next if category == "invalid"++ if category == "identical"+ skipped += 1+ next+ end++ resolution = resolutions[name.to_s] || "incoming"+ next if resolution == "keep"++ upload_id = upload_map[filename.to_sym] || upload_map[filename.to_s]+ upload = Upload.find_by(id: upload_id)+ next if upload.nil?++ existing = existing_by_name[name]++ if existing+ existing.update!(upload: upload, group: group)+ else+ custom_emoji =+ CustomEmoji.new(name: name, upload: upload, group: group, user: current_user)+ custom_emoji.save!+ StaffActionLogger.new(current_user).log_custom_emoji_create(name, group: group)+ created += 1+ end++ if existing &&+ (+ category == "conflict_group" || category == "conflict_image" ||+ category == "conflict_both"+ )+ StaffActionLogger.new(current_user).log_custom_emoji_create(name, group: group)+ updated += 1+ end+ end++ Emoji.clear_cache+ end++ Discourse.redis.del(import_preview_key(token))++ render json: { created: created, updated: updated, skipped: skipped }+ rescue ActiveRecord::RecordInvalid => e+ render json: failed_json.merge(errors: [e.message]), status: :unprocessable_entity+ end+def destroyname = params.require(:id)@@ -66,4 +354,60 @@ class Admin::EmojiController < Admin::AdminControllerrender json: success_jsonend++ private++ def import_preview_key(token)+ "emoji_import_preview:#{current_user.id}:#{token}"+ end++ def validate_import_row(name, group, filename, filenames_seen)+ errors = []+ errors << I18n.t("emoji.import.validation.missing_name") if name.blank?+ errors << I18n.t("emoji.import.validation.missing_filename") if filename.blank?++ if name.present?+ sanitized = Emoji.sanitize_emoji_name(name)+ errors << I18n.t("emoji.import.validation.invalid_name") if sanitized.blank?+ end++ if group.present? && group.length > 20+ errors << I18n.t("emoji.import.validation.group_too_long")+ end++ if filename.present?+ ext = File.extname(filename).delete(".").downcase+ if SUPPORTED_EXTENSIONS.exclude?(ext)+ errors << I18n.t("emoji.import.validation.unsupported_extension", ext: ext)+ end+ errors << I18n.t("emoji.import.validation.duplicate_filename") if filenames_seen[filename]+ end++ errors+ end++ def classify_import_row(name, group, upload, existing = nil)+ existing ||= CustomEmoji.find_by(name: name)+ return "new", nil unless existing++ existing_url = existing.upload&.url+ existing_group = existing.group.presence+ existing_group = nil if existing_group == "default"+ group_changed = existing_group != group+ display_existing_group = existing_group || "default"+ image_changed = existing.upload&.sha1 != upload.sha1++ category =+ if group_changed && image_changed+ "conflict_both"+ elsif image_changed+ "conflict_image"+ elsif group_changed+ "conflict_group"+ else+ "identical"+ end++ [category, existing_url, display_existing_group]+ endenddiff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex 6ae9d3841ce..ea6993c850f 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -9886,6 +9886,31 @@ en:alt: "custom emoji preview"delete_confirm: "Are you sure you want to delete the :%{name}: emoji?"settings: "Settings"+ export: "Export"+ export_count: "Export (%{count} selected)"+ export_failed: "Export failed. Please try again."+ select_to_export: "Select to export"+ import: "Import"+ import_heading: "Import emojis"+ import_description: "Upload a ZIP file containing an emojis.csv manifest and image files."+ import_download_sample: "Download an example template."+ import_preview_heading: "Review import"+ import_summary: "%{new} new · %{conflicts} conflicts · %{unchanged} unchanged · %{invalid} errors"+ import_confirm: "Confirm import"+ import_unchanged_count: "%{count} unchanged"+ import_will_skip: "Unchanged — will skip"+ import_excluded: "Excluded from import"+ import_incoming_alt: "Incoming: %{name}"+ import_existing_alt: "Existing: %{name}"+ import_existing_group_alt: "Existing group"+ import_use_incoming: "Use new"+ import_keep_existing: "Keep existing"+ import_category:+ new: "New"+ conflict: "Conflicts"+ invalid: "Errors"+ select_all: "Select all emojis"+ select: "Select %{name}"embedding:get_started: "If you'd like to embed Discourse on another website, begin by adding its host."diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 0bbd7516697..d99ef1b2677 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -6359,6 +6359,23 @@ en:unsafe_description: "has an unsafe HTML description"invalid_tag_group: "has invalid tag group: %{tag_group_name}"+ emoji:+ export:+ no_selection: "Select at least one emoji to export."+ import:+ missing_file: "No ZIP file provided."+ missing_csv: "The ZIP must contain an emojis.csv file."+ too_many_entries: "The ZIP contains too many entries (maximum 1000)."+ file_too_large: "One or more files in the ZIP are too large."+ session_expired: "Import session has expired. Please start the import again."+ validation:+ missing_name: "Name is required."+ missing_filename: "Filename is required."+ invalid_name: "Name contains invalid characters."+ group_too_long: "Group name must be 20 characters or fewer."+ unsupported_extension: "File extension .%{ext} is not supported (use png, gif, or svg)."+ duplicate_filename: "Filename appears more than once in the CSV."+discourse_id:already_registered: "This site is already registered with Discourse ID"errors:diff --git a/config/routes.rb b/config/routes.rbindex 71492e4859f..56a64513d2d 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -509,9 +509,16 @@ Discourse::Application.routes.draw doget "user_fields/:id" => "user_fields#show"get "user_fields/:id/edit" => "user_fields#edit"- resources :emoji, only: %i[index create destroy], constraints: AdminConstraint.new+ resources :emoji, only: %i[index create destroy], constraints: AdminConstraint.new do+ collection do+ post :export+ post :import_preview+ post :import_confirm+ end+ endget "emoji/new" => "emoji#index"get "emoji/settings" => "emoji#index"+ get "emoji/import" => "emoji#index"resources :permalinks, only: %i[index new create show destroy]enddiff --git a/frontend/discourse/admin/components/admin-config-areas/emojis-import.gjs b/frontend/discourse/admin/components/admin-config-areas/emojis-import.gjsnew file mode 100644index 00000000000..a0cc43bbb41--- /dev/null+++ b/frontend/discourse/admin/components/admin-config-areas/emojis-import.gjs@@ -0,0 +1,337 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { concat, fn, get } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import { service } from "@ember/service";+import BackButton from "discourse/components/back-button";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import getURL from "discourse/lib/get-url";+import { eq, or } from "discourse/truth-helpers";+import DButton from "discourse/ui-kit/d-button";+import { i18n } from "discourse-i18n";++const CONFLICT_CATEGORIES = [+ "conflict_both",+ "conflict_image",+ "conflict_group",+];++const ImportRowControls = <template>+ {{#if (eq @category "invalid")}}+ {{#if @row.errors}}+ <p class="admin-emoji-import__error">{{get @row.errors 0}}</p>+ {{/if}}+ {{else if (eq @row.category "identical")}}+ <span class="admin-emoji-import__badge --skip">+ {{i18n "admin.emoji.import_will_skip"}}+ </span>+ {{else if (eq @category "conflict")}}+ <div class="admin-emoji-import__conflict-resolution">+ <label>+ <input+ type="radio"+ name={{concat "resolution-" @row.name}}+ value="incoming"+ checked={{eq (or (get @resolutions @row.name) "incoming") "incoming"}}+ {{on "change" (fn @onSetResolution @row.name "incoming")}}+ />+ {{i18n "admin.emoji.import_use_incoming"}}+ </label>+ <label>+ <input+ type="radio"+ name={{concat "resolution-" @row.name}}+ value="keep"+ checked={{eq (get @resolutions @row.name) "keep"}}+ {{on "change" (fn @onSetResolution @row.name "keep")}}+ />+ {{i18n "admin.emoji.import_keep_existing"}}+ </label>+ </div>+ {{/if}}+</template>;++const ImportSection = <template>+ <div class="admin-emoji-import__section">+ <h3 class="admin-emoji-import__section-heading">+ {{#if (eq @category "no_action")}}+ {{i18n "admin.emoji.import_category.new"}}+ <span class="admin-emoji-import__section-count">({{@newCount}})</span>+ {{#if @identicalCount}}+ <small class="admin-emoji-import__section-subtitle">+ {{i18n "admin.emoji.import_unchanged_count" count=@identicalCount}}+ </small>+ {{/if}}+ {{else}}+ {{i18n (concat "admin.emoji.import_category." @category)}}+ <span+ class="admin-emoji-import__section-count"+ >({{@rows.length}})</span>+ {{/if}}+ </h3>+ {{#if (eq @category "invalid")}}+ <p class="admin-emoji-import__section-description">+ {{i18n "admin.emoji.import_excluded"}}+ </p>+ {{/if}}+ <table class="d-table admin-emoji-import__table">+ <thead class="d-table__header">+ <tr class="d-table__row">+ <th class="d-table__header-cell">{{i18n "admin.emoji.image"}}</th>+ <th class="d-table__header-cell">{{i18n "admin.emoji.name"}}</th>+ <th class="d-table__header-cell">{{i18n "admin.emoji.group"}}</th>+ <th class="d-table__header-cell"></th>+ </tr>+ </thead>+ <tbody class="d-table__body">+ {{#each @rows as |row|}}+ <tr class="d-table__row">+ <td class="d-table__cell --overview">+ {{#if row.incoming_url}}+ <img+ class="emoji emoji-custom"+ src={{row.incoming_url}}+ alt={{i18n "admin.emoji.import_incoming_alt" name=row.name}}+ />+ {{/if}}+ {{#if (eq @category "conflict")}}+ {{#if row.existing_url}}+ <span+ class="admin-emoji-import__existing-value"+ aria-label={{i18n+ "admin.emoji.import_existing_alt"+ name=row.name+ }}+ >+ <img+ class="emoji emoji-custom"+ src={{row.existing_url}}+ alt=""+ aria-hidden="true"+ />+ </span>+ {{/if}}+ {{/if}}+ </td>+ <td class="d-table__cell --detail">+ :{{row.name}}:+ {{#if (eq @category "conflict")}}+ <span class="admin-emoji-import__existing-value">+ :{{row.name}}:+ </span>+ {{/if}}+ </td>+ <td class="d-table__cell --detail">+ {{row.group}}+ {{#if (eq @category "conflict")}}+ <span+ class="admin-emoji-import__existing-value"+ aria-label={{i18n "admin.emoji.import_existing_group_alt"}}+ >+ {{row.existing_group}}+ </span>+ {{/if}}+ </td>+ <td class="d-table__cell --controls">+ <ImportRowControls+ @category={{@category}}+ @row={{row}}+ @resolutions={{@resolutions}}+ @onSetResolution={{@onSetResolution}}+ />+ </td>+ </tr>+ {{/each}}+ </tbody>+ </table>+ </div>+</template>;++export default class AdminConfigAreasEmojisImport extends Component {+ @service router;+ @service adminEmojis;++ @tracked previewToken = null;+ @tracked previewRows = null;+ @tracked resolutions = {};+ @tracked isUploading = false;+ @tracked isConfirming = false;++ get isPreviewPhase() {+ return this.previewRows !== null;+ }++ get rowsByCategory() {+ if (!this.previewRows) {+ return {};+ }+ const grouped = {};+ grouped["invalid"] = this.previewRows.filter(+ (r) => r.category === "invalid"+ );+ grouped["conflict"] = this.previewRows.filter((r) =>+ CONFLICT_CATEGORIES.includes(r.category)+ );+ grouped["no_action"] = this.previewRows.filter(+ (r) => r.category === "new" || r.category === "identical"+ );+ return grouped;+ }++ get summaryCounts() {+ if (!this.previewRows) {+ return null;+ }+ return {+ no_action: this.rowsByCategory["no_action"].length,+ newCount: this.previewRows.filter((r) => r.category === "new").length,+ identicalCount: this.previewRows.filter((r) => r.category === "identical")+ .length,+ conflicts: this.rowsByCategory["conflict"].length,+ invalid: this.rowsByCategory["invalid"].length,+ };+ }++ @action+ async uploadZip(event) {+ const file = event.target.files[0];+ if (!file) {+ return;+ }++ this.isUploading = true;++ const formData = new FormData();+ formData.append("file", file);++ try {+ const data = await ajax("/admin/config/emoji/import_preview", {+ type: "POST",+ data: formData,+ processData: false,+ contentType: false,+ });++ this.previewToken = data.token;+ this.previewRows = data.rows;+ this.resolutions = {};+ } catch (err) {+ popupAjaxError(err);+ } finally {+ this.isUploading = false;+ event.target.value = null;+ }+ }++ @action+ setResolution(name, value) {+ this.resolutions = { ...this.resolutions, [name]: value };+ }++ @action+ async confirm() {+ this.isConfirming = true;++ try {+ await ajax("/admin/config/emoji/import_confirm", {+ type: "POST",+ data: { token: this.previewToken, resolutions: this.resolutions },+ });++ await this.adminEmojis.refresh();++ this.router.transitionTo("adminEmojis.index");+ } catch (err) {+ popupAjaxError(err);+ } finally {+ this.isConfirming = false;+ }+ }++ @action+ cancel() {+ this.previewRows = null;+ this.previewToken = null;+ this.resolutions = {};+ }++ <template>+ <BackButton @route="adminEmojis.index" @label="admin.emoji.back" />+ <div class="admin-emoji-import">++ {{#if this.isPreviewPhase}}+ <h2 class="admin-emoji-import__heading">{{i18n+ "admin.emoji.import_preview_heading"+ }}</h2>+ {{#if this.summaryCounts}}+ <p class="admin-emoji-import__summary">+ {{i18n+ "admin.emoji.import_summary"+ new=this.summaryCounts.newCount+ conflicts=this.summaryCounts.conflicts+ unchanged=this.summaryCounts.identicalCount+ invalid=this.summaryCounts.invalid+ }}+ </p>+ {{/if}}++ {{#each-in this.rowsByCategory as |category rows|}}+ {{#if rows.length}}+ <ImportSection+ @category={{category}}+ @rows={{rows}}+ @resolutions={{this.resolutions}}+ @onSetResolution={{this.setResolution}}+ @newCount={{this.summaryCounts.newCount}}+ @identicalCount={{this.summaryCounts.identicalCount}}+ />+ {{/if}}+ {{/each-in}}++ <div class="admin-emoji-import__actions">+ <DButton+ @action={{this.confirm}}+ @label="admin.emoji.import_confirm"+ @disabled={{this.isConfirming}}+ @isLoading={{this.isConfirming}}+ class="btn-primary"+ />+ <DButton+ @action={{this.cancel}}+ @label="cancel"+ class="btn-default"+ />+ </div>++ {{else}}+ <h2 class="admin-emoji-import__heading">{{i18n+ "admin.emoji.import_heading"+ }}</h2>+ <p class="admin-emoji-import__description">+ {{i18n "admin.emoji.import_description"}}+ <br />+ <a+ href={{getURL "/emoji-import-sample.zip"}}+ target="_blank"+ rel="noopener noreferrer"+ >{{i18n "admin.emoji.import_download_sample"}}</a>+ </p>+ <div class="inputs">+ <input+ type="file"+ accept=".zip"+ class="admin-emoji-import__file-input"+ disabled={{this.isUploading}}+ {{on "change" this.uploadZip}}+ />+ {{#if this.isUploading}}+ <span>{{i18n "admin.emoji.uploading"}}</span>+ {{/if}}+ </div>+ {{/if}}++ </div>+ </template>+}diff --git a/frontend/discourse/admin/components/admin-config-areas/emojis-list.gjs b/frontend/discourse/admin/components/admin-config-areas/emojis-list.gjsindex 22b6af6f593..a276116233f 100644--- a/frontend/discourse/admin/components/admin-config-areas/emojis-list.gjs+++ b/frontend/discourse/admin/components/admin-config-areas/emojis-list.gjs@@ -1,5 +1,6 @@import Component from "@glimmer/component";import { fn } from "@ember/helper";+import { on } from "@ember/modifier";import { service } from "@ember/service";import AdminConfigAreaEmptyList from "discourse/admin/components/admin-config-area-empty-list";import ComboBox from "discourse/select-kit/components/combo-box";@@ -9,6 +10,10 @@ import { i18n } from "discourse-i18n";export default class AdminConfigAreasEmojisList extends Component {@service adminEmojis;+ isEmojiSelected = (name) => {+ return this.adminEmojis.selectedEmojis.has(name);+ };+get emojis() {return this.adminEmojis.emojis;}@@ -22,7 +27,7 @@ export default class AdminConfigAreasEmojisList extends Component {}<template>- <div class="form-horizontal">+ <div class="admin-emoji-list__controls"><div class="inline-form"><ComboBox@value={{this.adminEmojis.filter}}@@ -30,13 +35,48 @@ export default class AdminConfigAreasEmojisList extends Component {@nameProperty={{null}}@valueProperty={{null}}/>++ {{#if this.adminEmojis.isSelecting}}+ <DButton+ @action={{this.adminEmojis.exportSelected}}+ @translatedLabel={{this.adminEmojis.exportLabel}}+ @icon="download"+ @disabled={{this.adminEmojis.exportDisabled}}+ @isLoading={{this.adminEmojis.isExporting}}+ class="btn-primary admin-emoji-list__export-btn"+ />+ <DButton+ @action={{this.adminEmojis.cancelSelecting}}+ @label="cancel"+ class="btn-default admin-emoji-list__cancel-btn"+ />+ {{else}}+ <DButton+ @action={{this.adminEmojis.startSelecting}}+ @label="admin.emoji.select_to_export"+ @icon="download"+ class="btn-default admin-emoji-list__select-to-export"+ />+ {{/if}}</div></div>{{#if this.emojis}}- <table id="custom_emoji" class="d-table">+ <table id="custom_emoji" class="d-table admin-emoji-list"><thead class="d-table__header"><tr class="d-table__row">+ {{#if this.adminEmojis.isSelecting}}+ <th class="d-table__header-cell admin-emoji-list__select-col">+ <input+ type="checkbox"+ class="admin-emoji-list__select-all"+ aria-label={{i18n "admin.emoji.select_all"}}+ checked={{this.adminEmojis.allVisibleSelected}}+ indeterminate={{this.adminEmojis.someVisibleSelected}}+ {{on "change" this.adminEmojis.toggleAllVisible}}+ />+ </th>+ {{/if}}<th class="d-table__header-cell">{{i18n "admin.emoji.image"}}</th><th class="d-table__header-cell">{{i18n "admin.emoji.name"}}</th><th class="d-table__header-cell">{{i18n "admin.emoji.group"}}</th>@@ -49,6 +89,20 @@ export default class AdminConfigAreasEmojisList extends Component {<tbody class="d-table__body">{{#each this.sortedEmojis as |emoji|}}<tr class="d-table__row">+ {{#if this.adminEmojis.isSelecting}}+ <td class="d-table__cell admin-emoji-list__select-col">+ <input+ type="checkbox"+ class="admin-emoji-list__select"+ aria-label={{i18n "admin.emoji.select" name=emoji.name}}+ checked={{this.isEmojiSelected emoji.name}}+ {{on+ "change"+ (fn this.adminEmojis.toggleEmojiSelected emoji)+ }}+ />+ </td>+ {{/if}}<td class="d-table__cell --overview"><imgclass="emoji emoji-custom"@@ -75,13 +129,15 @@ export default class AdminConfigAreasEmojisList extends Component {</div>{{emoji.created_by}}</td>- <td class="d-table__cell --controls action">- <DButton- @action={{fn this.adminEmojis.destroyEmoji emoji}}- @label="admin.emoji.delete"- class="btn-default btn-small d-table__cell-action-delete"- />- </td>+ {{#unless this.adminEmojis.isSelecting}}+ <td class="d-table__cell --controls action">+ <DButton+ @action={{fn this.adminEmojis.destroyEmoji emoji}}+ @label="admin.emoji.delete"+ class="btn-default btn-small d-table__cell-action-delete"+ />+ </td>+ {{/unless}}</tr>{{/each}}</tbody>diff --git a/frontend/discourse/admin/controllers/admin-emojis.js b/frontend/discourse/admin/controllers/admin-emojis.jsindex 5aec351060f..96e22697c0c 100644--- a/frontend/discourse/admin/controllers/admin-emojis.js+++ b/frontend/discourse/admin/controllers/admin-emojis.js@@ -5,6 +5,8 @@ export default class AdminEmojisController extends Controller {@service router;get hideTabs() {- return ["adminEmojis.new"].includes(this.router.currentRouteName);+ return ["adminEmojis.new", "adminEmojis.import"].includes(+ this.router.currentRouteName+ );}}diff --git a/frontend/discourse/admin/routes/admin-emojis/import.js b/frontend/discourse/admin/routes/admin-emojis/import.jsnew file mode 100644index 00000000000..6f7c9de03d4--- /dev/null+++ b/frontend/discourse/admin/routes/admin-emojis/import.js@@ -0,0 +1,8 @@+import DiscourseRoute from "discourse/routes/discourse";+import { i18n } from "discourse-i18n";++export default class AdminEmojisImportRoute extends DiscourseRoute {+ titleToken() {+ return i18n("admin.emoji.import");+ }+}diff --git a/frontend/discourse/admin/routes/admin-emojis/index.js b/frontend/discourse/admin/routes/admin-emojis/index.jsnew file mode 100644index 00000000000..678b9d2d708--- /dev/null+++ b/frontend/discourse/admin/routes/admin-emojis/index.js@@ -0,0 +1,10 @@+import { service } from "@ember/service";+import DiscourseRoute from "discourse/routes/discourse";++export default class AdminEmojisIndexRoute extends DiscourseRoute {+ @service adminEmojis;++ deactivate() {+ this.adminEmojis.cancelSelecting();+ }+}diff --git a/frontend/discourse/admin/routes/admin-route-map.js b/frontend/discourse/admin/routes/admin-route-map.jsindex 6f5c0ebc8d8..212655a6a5f 100644--- a/frontend/discourse/admin/routes/admin-route-map.js+++ b/frontend/discourse/admin/routes/admin-route-map.js@@ -383,6 +383,7 @@ export default function () {{ path: "/emoji", resetNamespace: true },function () {this.route("new");+ this.route("import");this.route("index", { path: "/" });this.route("settings");}diff --git a/frontend/discourse/admin/services/admin-emojis.js b/frontend/discourse/admin/services/admin-emojis.jsindex 52497fd8430..3784d45b9ef 100644--- a/frontend/discourse/admin/services/admin-emojis.js+++ b/frontend/discourse/admin/services/admin-emojis.js@@ -7,7 +7,9 @@ import {removeValueFromArray,uniqueItemsFromArray,} from "discourse/lib/array-tools";+import getURL from "discourse/lib/get-url";import { autoTrackedArray } from "discourse/lib/tracked-tools";+import Session from "discourse/models/session";import { i18n } from "discourse-i18n";const ALL_FILTER = "all";@@ -18,11 +20,13 @@ export default class AdminEmojis extends Service {@tracked filter = ALL_FILTER;@tracked sorting = ["group", "name"];+ @tracked selectedEmojis = new Set();+ @tracked isSelecting = false;+ @tracked isExporting = false;@autoTrackedArray emojis = [];constructor() {super(...arguments);-this.#fetchEmojis();}@@ -48,15 +52,111 @@ export default class AdminEmojis extends Service {return [ALL_FILTER].concat(this.emojiGroups);}- async #fetchEmojis() {+ get allVisibleSelected() {+ const visible = this.sortedEmojis;+ return (+ visible.length > 0 &&+ visible.every((e) => this.selectedEmojis.has(e.get("name")))+ );+ }++ get someVisibleSelected() {+ return (+ !this.allVisibleSelected &&+ this.sortedEmojis.some((e) => this.selectedEmojis.has(e.get("name")))+ );+ }++ get exportDisabled() {+ return this.selectedEmojis.size === 0;+ }++ get exportLabel() {+ const count = this.selectedEmojis.size;+ if (count === 0) {+ return i18n("admin.export_json.button_text");+ }+ return i18n("admin.emoji.export_count", { count });+ }++ @action+ async exportSelected() {+ if (this.exportDisabled || this.isExporting) {+ return;+ }++ this.isExporting = true;+try {- const data = await ajax("/admin/config/emoji.json");- this.emojis = data.map((emoji) => EmberObject.create(emoji));- } catch (err) {- popupAjaxError(err);+ const response = await fetch(getURL("/admin/config/emoji/export"), {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "X-CSRF-Token": Session.currentProp("csrfToken"),+ },+ body: JSON.stringify({ names: [...this.selectedEmojis] }),+ });++ if (!response.ok) {+ const data = await response.json().catch(() => ({}));+ this.dialog.alert(+ data.errors?.[0] || i18n("admin.emoji.export_failed")+ );+ 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);+ } catch {+ this.dialog.alert(i18n("admin.emoji.export_failed"));+ } finally {+ this.isExporting = false;}}+ @action+ startSelecting() {+ this.isSelecting = true;+ this.selectedEmojis = new Set();+ }++ @action+ cancelSelecting() {+ this.isSelecting = false;+ this.selectedEmojis = new Set();+ }++ @action+ toggleEmojiSelected(emoji) {+ const name = emoji.get("name");+ const next = new Set(this.selectedEmojis);+ if (next.has(name)) {+ next.delete(name);+ } else {+ next.add(name);+ }+ this.selectedEmojis = next;+ }++ @action+ toggleAllVisible() {+ const emojis = this.sortedEmojis;+ const next = new Set(this.selectedEmojis);+ if (this.allVisibleSelected) {+ emojis.forEach((e) => next.delete(e.get("name")));+ } else {+ emojis.forEach((e) => next.add(e.get("name")));+ }+ this.selectedEmojis = next;+ }+@actiondestroyEmoji(emoji) {this.dialog.deleteConfirm({@@ -67,12 +167,28 @@ export default class AdminEmojis extends Service {});}+ async refresh() {+ await this.#fetchEmojis();+ }++ async #fetchEmojis() {+ try {+ const data = await ajax("/admin/config/emoji.json");+ this.emojis = data.map((emoji) => EmberObject.create(emoji));+ } catch (err) {+ popupAjaxError(err);+ }+ }+async #destroyEmoji(emoji) {try {await ajax("/admin/config/emoji/" + emoji.get("name"), {type: "DELETE",});removeValueFromArray(this.emojis, emoji);+ const next = new Set(this.selectedEmojis);+ next.delete(emoji.get("name"));+ this.selectedEmojis = next;} catch (err) {popupAjaxError(err);}diff --git a/frontend/discourse/admin/templates/admin-emojis.gjs b/frontend/discourse/admin/templates/admin-emojis.gjsindex ee43d313d79..9b84eb81021 100644--- a/frontend/discourse/admin/templates/admin-emojis.gjs+++ b/frontend/discourse/admin/templates/admin-emojis.gjs@@ -1,14 +1,16 @@+import { not } from "discourse/truth-helpers";import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";import DNavItem from "discourse/ui-kit/d-nav-item";import DPageHeader from "discourse/ui-kit/d-page-header";import { i18n } from "discourse-i18n";-export default <template>+const AdminEmojisTemplate = <template><div class="admin-emoji admin-config-page"><DPageHeader@titleLabel={{i18n "admin.config.emoji.title"}}@descriptionLabel={{i18n "admin.config.emoji.header_description"}}@hideTabs={{@controller.hideTabs}}+ @shouldDisplay={{not @controller.hideTabs}}><:breadcrumbs><DBreadcrumbsItem @path="/admin" @label={{i18n "admin_title"}} />@@ -19,6 +21,11 @@ export default <template></:breadcrumbs><:actions as |actions|><actions.Primary @route="adminEmojis.new" @label="admin.emoji.add" />+ <actions.Default+ @route="adminEmojis.import"+ @label="admin.emoji.import"+ class="admin-emoji__import"+ /></:actions><:tabs><DNavItem@@ -38,4 +45,6 @@ export default <template>{{outlet}}</div></div>-</template>+</template>;++export default AdminEmojisTemplate;diff --git a/frontend/discourse/admin/templates/admin-emojis/import.gjs b/frontend/discourse/admin/templates/admin-emojis/import.gjsnew file mode 100644index 00000000000..235cca8c971--- /dev/null+++ b/frontend/discourse/admin/templates/admin-emojis/import.gjs@@ -0,0 +1,3 @@+import EmojisImport from "discourse/admin/components/admin-config-areas/emojis-import";++export default <template><EmojisImport /></template>diff --git a/frontend/discourse/tests/acceptance/admin-emoji-test.gjs b/frontend/discourse/tests/acceptance/admin-emoji-test.gjsnew file mode 100644index 00000000000..34ffe2adb4e--- /dev/null+++ b/frontend/discourse/tests/acceptance/admin-emoji-test.gjs@@ -0,0 +1,383 @@+import { click, currentURL, triggerEvent, visit } from "@ember/test-helpers";+import { test } from "qunit";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import { acceptance, createFile } from "discourse/tests/helpers/qunit-helpers";++const emojiList = [+ {+ name: "partyblob",+ url: "/images/emoji/twitter/partyblob.png",+ group: "fun",+ created_by: "admin",+ },+ {+ name: "wave",+ url: "/images/emoji/twitter/wave.png",+ group: "default",+ created_by: "admin",+ },+];++const previewResponse = {+ token: "abc123",+ rows: [+ {+ index: 0,+ name: "new-emoji",+ group: "default",+ filename: "new-emoji.png",+ category: "new",+ incoming_url: "/images/emoji/twitter/new-emoji.png",+ existing_url: null,+ },+ {+ index: 1,+ name: "partyblob",+ group: "fun",+ filename: "partyblob.png",+ category: "identical",+ incoming_url: "/images/emoji/twitter/partyblob.png",+ existing_url: "/images/emoji/twitter/partyblob.png",+ },+ {+ index: 2,+ name: "wave",+ group: "reactions",+ filename: "wave.png",+ category: "conflict_group",+ incoming_url: "/images/emoji/twitter/wave.png",+ existing_url: "/images/emoji/twitter/wave.png",+ },+ {+ index: 3,+ name: "bad-emoji",+ group: "default",+ filename: "bad-emoji.bmp",+ category: "invalid",+ errors: ["File extension .bmp is not supported"],+ },+ ],+};++acceptance("Admin - Emoji", function (needs) {+ needs.user();++ needs.pretender((server, helper) => {+ server.get("/admin/config/emoji.json", () => helper.response(emojiList));+ server.get("/admin/config/emoji/settings", () => helper.response({}));+ server.delete("/admin/config/emoji/:name", () => helper.response({}));+ server.post("/admin/config/emoji/import_preview", () =>+ helper.response(previewResponse)+ );+ server.post("/admin/config/emoji/import_confirm", () =>+ helper.response({ created: 1, updated: 1, skipped: 1 })+ );+ });++ // ─── List ──────────────────────────────────────────────────────────────────++ test("lists custom emojis with a delete button per row and a select-to-export button", async function (assert) {+ await visit("/admin/config/emoji");++ assert+ .dom(".admin-emoji-list tbody .d-table__row")+ .exists({ count: 2 }, "renders one row per emoji");++ assert+ .dom(".admin-emoji-list__select-to-export")+ .exists("select-to-export button is shown");++ assert+ .dom(".admin-emoji-list tbody .d-table__cell-action-delete")+ .exists({ count: 2 }, "each row has a delete button");++ assert+ .dom(".admin-emoji-list__select")+ .doesNotExist("checkboxes not shown before selecting mode");+ });++ // ─── Select to export flow ─────────────────────────────────────────────────++ test("clicking select-to-export enters selecting mode and shows checkboxes", async function (assert) {+ await visit("/admin/config/emoji");++ await click(".admin-emoji-list__select-to-export");++ assert+ .dom(".admin-emoji-list__select")+ .exists({ count: 2 }, "per-row checkboxes shown in selecting mode");++ assert+ .dom(".admin-emoji-list__select-all")+ .exists("select-all checkbox shown in selecting mode");++ assert+ .dom(".admin-emoji-list__export-btn")+ .exists("export button shown in selecting mode");++ assert+ .dom(".admin-emoji-list__cancel-btn")+ .exists("cancel button shown in selecting mode");++ assert+ .dom(".admin-emoji-list__select-to-export")+ .doesNotExist("select-to-export button hidden in selecting mode");+ });++ test("navigating away from the emoji list clears selecting mode", async function (assert) {+ await visit("/admin/config/emoji");++ await click(".admin-emoji-list__select-to-export");+ assert+ .dom(".admin-emoji-list__select")+ .exists("checkboxes shown in selecting mode");++ await click(".admin-emoji__import");++ await visit("/admin/config/emoji");+ assert+ .dom(".admin-emoji-list__select")+ .doesNotExist("selecting mode cleared after navigating away and back");++ assert+ .dom(".admin-emoji-list__select-to-export")+ .exists("select-to-export button visible again");+ });++ test("cancel exits selecting mode and hides checkboxes", async function (assert) {+ await visit("/admin/config/emoji");++ await click(".admin-emoji-list__select-to-export");+ await click(".admin-emoji-list__cancel-btn");++ assert+ .dom(".admin-emoji-list__select")+ .doesNotExist("checkboxes hidden after cancel");++ assert+ .dom(".admin-emoji-list__select-to-export")+ .exists("select-to-export button visible again after cancel");+ });++ test("select-all checks all rows and deselect-all unchecks them", async function (assert) {+ await visit("/admin/config/emoji");++ await click(".admin-emoji-list__select-to-export");++ await click(".admin-emoji-list__select-all");+ assert+ .dom(".admin-emoji-list__select:checked")+ .exists({ count: 2 }, "all rows selected after select-all");++ await click(".admin-emoji-list__select-all");+ assert+ .dom(".admin-emoji-list__select:checked")+ .doesNotExist("all rows deselected after clicking select-all again");+ });++ test("selecting a row makes header select-all indeterminate", async function (assert) {+ await visit("/admin/config/emoji");++ await click(".admin-emoji-list__select-to-export");++ await click(+ ".admin-emoji-list tbody .d-table__row:first-child .admin-emoji-list__select"+ );++ assert+ .dom(".admin-emoji-list__select-all")+ .hasProperty("indeterminate", true, "header checkbox is indeterminate");+ });++ test("export button is present in page header", async function (assert) {+ await visit("/admin/config/emoji");++ assert.dom(".admin-emoji__import").exists("import button is present");+ });++ // ─── Import navigation ─────────────────────────────────────────────────────++ test("import button navigates to the import route", async function (assert) {+ await visit("/admin/config/emoji");++ await click(".admin-emoji__import");++ assert+ .dom(".admin-emoji-import__file-input")+ .exists("navigates to import page");+ });++ test("import page shows file picker initially", async function (assert) {+ await visit("/admin/config/emoji/import");++ assert+ .dom(".admin-emoji-import__file-input")+ .exists("file input is shown on import page");+ });++ // ─── Import preview ────────────────────────────────────────────────────────++ test("uploading a ZIP shows the confirmation view with categorised rows", async function (assert) {+ await visit("/admin/config/emoji/import");++ const file = createFile("emojis.zip", "application/zip");+ await triggerEvent(".admin-emoji-import__file-input", "change", {+ files: [file],+ });++ assert+ .dom(".admin-emoji-import__summary")+ .exists("summary bar is shown after upload");++ assert+ .dom(".admin-emoji-import__actions .btn-primary")+ .exists("confirm import button is shown");++ assert+ .dom(".admin-emoji-import__actions .btn-default")+ .exists("cancel button is shown");+ });++ test("summary bar shows correct counts", async function (assert) {+ await visit("/admin/config/emoji/import");++ const file = createFile("emojis.zip", "application/zip");+ await triggerEvent(".admin-emoji-import__file-input", "change", {+ files: [file],+ });++ assert+ .dom(".admin-emoji-import__summary")+ .hasText(+ "1 new · 1 conflicts · 1 unchanged · 1 errors",+ "summary shows correct counts"+ );+ });++ test("invalid rows count appears in summary", async function (assert) {+ await visit("/admin/config/emoji/import");++ const file = createFile("emojis.zip", "application/zip");+ await triggerEvent(".admin-emoji-import__file-input", "change", {+ files: [file],+ });++ assert+ .dom(".admin-emoji-import__summary")+ .containsText("1 errors", "invalid count shown in summary");+ });++ test("confirming the import navigates back to the emoji list", async function (assert) {+ let confirmCalled = false;+ pretender.post("/admin/config/emoji/import_confirm", () => {+ confirmCalled = true;+ return response({});+ });++ await visit("/admin/config/emoji/import");++ const file = createFile("emojis.zip", "application/zip");+ await triggerEvent(".admin-emoji-import__file-input", "change", {+ files: [file],+ });++ await click(".admin-emoji-import__actions .btn-primary");++ assert.true(confirmCalled, "confirm endpoint was called");++ assert.strictEqual(+ currentURL(),+ "/admin/config/emoji",+ "navigates back to emoji list after confirm"+ );+ });++ test("cancel from confirmation view returns to file picker", async function (assert) {+ await visit("/admin/config/emoji/import");++ const file = createFile("emojis.zip", "application/zip");+ await triggerEvent(".admin-emoji-import__file-input", "change", {+ files: [file],+ });++ await click(".admin-emoji-import__actions .btn-default");++ assert+ .dom(".admin-emoji-import__file-input")+ .exists("back to file picker after cancel");+ });++ test("preview renders a section for each category with rows", async function (assert) {+ await visit("/admin/config/emoji/import");++ const file = createFile("emojis.zip", "application/zip");+ await triggerEvent(".admin-emoji-import__file-input", "change", {+ files: [file],+ });++ assert+ .dom(".admin-emoji-import__section")+ .exists(+ { count: 3 },+ "three sections rendered (new/identical, conflict, invalid)"+ );++ assert+ .dom(".admin-emoji-import__table")+ .exists({ count: 3 }, "each section has a table");++ assert+ .dom(".admin-emoji-import__table .d-table__row")+ .exists("at least one row is rendered in the tables");+ });++ test("new emoji section shows incoming image", async function (assert) {+ await visit("/admin/config/emoji/import");++ const file = createFile("emojis.zip", "application/zip");+ await triggerEvent(".admin-emoji-import__file-input", "change", {+ files: [file],+ });++ assert+ .dom(".admin-emoji-import__table img.emoji-custom")+ .exists("incoming emoji images are shown in the preview tables");+ });++ test("conflict section shows resolution radio buttons", async function (assert) {+ await visit("/admin/config/emoji/import");++ const file = createFile("emojis.zip", "application/zip");+ await triggerEvent(".admin-emoji-import__file-input", "change", {+ files: [file],+ });++ assert+ .dom(".admin-emoji-import__conflict-resolution")+ .exists("conflict resolution controls are shown");++ assert+ .dom(".admin-emoji-import__conflict-resolution input[type='radio']")+ .exists({ count: 2 }, "two radio options (incoming / keep existing)");+ });++ test("invalid section shows error message", async function (assert) {+ await visit("/admin/config/emoji/import");++ const file = createFile("emojis.zip", "application/zip");+ await triggerEvent(".admin-emoji-import__file-input", "change", {+ files: [file],+ });++ assert+ .dom(".admin-emoji-import__error")+ .exists("error message shown for invalid row");++ assert+ .dom(".admin-emoji-import__error")+ .hasText(+ "File extension .bmp is not supported",+ "error text matches the validation message"+ );+ });+});diff --git a/public/emoji-import-sample.zip b/public/emoji-import-sample.zipnew file mode 100644index 00000000000..ced356e4559Binary files /dev/null and b/public/emoji-import-sample.zip differdiff --git a/spec/requests/admin/emojis_controller_spec.rb b/spec/requests/admin/emojis_controller_spec.rbindex e2670319c56..c7aef6558c9 100644--- a/spec/requests/admin/emojis_controller_spec.rb+++ b/spec/requests/admin/emojis_controller_spec.rb@@ -1,5 +1,8 @@# frozen_string_literal: true+require "zip"+require "csv"+RSpec.describe Admin::EmojiController dofab!(:admin)fab!(:moderator)@@ -237,6 +240,344 @@ RSpec.describe Admin::EmojiController doendend+ describe "#export" do+ fab!(:png_upload) do+ UploadCreator.new(+ file_from_fixtures("logo.png"),+ "logo.png",+ type: "custom_emoji",+ ).create_for(Discourse.system_user.id)+ end++ fab!(:emoji_a) { CustomEmoji.create!(name: "emoji-a", upload: png_upload, user: admin) }+ fab!(:emoji_b) do+ CustomEmoji.create!(name: "emoji-b", upload: png_upload, group: "fun", user: admin)+ end++ context "when logged in as an admin" do+ before { sign_in(admin) }++ it "streams a ZIP containing emojis.csv and image files" do+ post "/admin/config/emoji/export", params: { names: %w[emoji-a emoji-b] }, as: :json++ expect(response.status).to eq(200)+ expect(response.headers["Content-Type"]).to include("application/zip")++ Tempfile.create(%w[export_test_ .zip]) do |f|+ f.binmode+ f.write(response.body)+ f.rewind++ Zip::File.open(f.path) do |zip|+ entries = zip.entries.map(&:name)+ expect(entries).to include("emojis.csv")+ expect(entries).to include("emoji-a.png")+ expect(entries).to include("emoji-b.png")++ csv = zip.read("emojis.csv")+ rows = CSV.parse(csv, headers: true)+ expect(rows.map { |r| r["name"] }).to contain_exactly("emoji-a", "emoji-b")+ emoji_b_row = rows.find { |r| r["name"] == "emoji-b" }+ expect(emoji_b_row["group"]).to eq("fun")+ end+ end+ end++ it "returns 422 when no names are provided" do+ post "/admin/config/emoji/export", as: :json+ expect(response.status).to eq(422)+ end+ end++ shared_examples "export not allowed" do+ it "denies access with a 404 response" do+ post "/admin/config/emoji/export", params: { names: ["emoji-a"] }, as: :json+ expect(response.status).to eq(404)+ end+ end++ context "when logged in as a moderator" do+ before { sign_in(moderator) }+ include_examples "export not allowed"+ end++ context "when logged in as a non-staff user" do+ before { sign_in(user) }+ include_examples "export not allowed"+ end+ end++ describe "#import_preview" do+ let(:image_path) { Rails.root.join("spec/fixtures/images/logo.png") }++ def build_emoji_zip(csv_content, images = {})+ tmp = Tempfile.new(%w[emoji_import_ .zip])+ tmp.close++ Zip::File.open(tmp.path, create: true) do |zip|+ zip.get_output_stream("emojis.csv") { |f| f.write(csv_content) }+ images.each { |filename, path| zip.add(filename, path) }+ end++ Rack::Test::UploadedFile.new(tmp.path, "application/zip")+ end++ context "when logged in as an admin" do+ before { sign_in(admin) }++ it "returns a preview with new emojis correctly categorised" do+ zip =+ build_emoji_zip(+ "name,group,filename\npreview-emoji,,preview-emoji.png\n",+ { "preview-emoji.png" => image_path },+ )++ post "/admin/config/emoji/import_preview.json", params: { file: zip }++ expect(response.status).to eq(200)+ body = response.parsed_body+ expect(body["token"]).to be_present+ expect(body["rows"].length).to eq(1)+ expect(body["rows"][0]["category"]).to eq("new")+ expect(body["rows"][0]["name"]).to eq("preview-emoji")+ end++ it "categorises existing emoji with a group change as conflict_group" do+ existing_upload =+ UploadCreator.new(+ file_from_fixtures("logo.png"),+ "logo.png",+ type: "custom_emoji",+ ).create_for(admin.id)+ CustomEmoji.create!(+ name: "existing-emoji",+ upload: existing_upload,+ group: "old-group",+ user: admin,+ )++ zip =+ build_emoji_zip(+ "name,group,filename\nexisting-emoji,new-group,existing-emoji.png\n",+ { "existing-emoji.png" => image_path },+ )++ post "/admin/config/emoji/import_preview.json", params: { file: zip }++ expect(response.status).to eq(200)+ row = response.parsed_body["rows"][0]+ expect(row["category"]).to eq("conflict_group")+ end++ it "flags missing image file in ZIP as invalid" do+ zip = build_emoji_zip("name,group,filename\nmissing-img,,missing-img.png\n")++ post "/admin/config/emoji/import_preview.json", params: { file: zip }++ expect(response.status).to eq(200)+ row = response.parsed_body["rows"][0]+ expect(row["category"]).to eq("invalid")+ end++ it "flags unsupported extension as invalid" do+ zip = build_emoji_zip("name,group,filename\nbad-ext,,bad-ext.bmp\n")++ post "/admin/config/emoji/import_preview.json", params: { file: zip }++ row = response.parsed_body["rows"][0]+ expect(row["category"]).to eq("invalid")+ expect(row["errors"].join).to include("bmp")+ end++ it "returns 422 when no file is provided" do+ post "/admin/config/emoji/import_preview.json"+ expect(response.status).to eq(422)+ end++ it "returns 422 when ZIP has no emojis.csv" do+ tmp = Tempfile.new(%w[no_csv_ .zip])+ tmp.close+ Zip::File.open(tmp.path, create: true) do |z|+ z.get_output_stream("readme.txt") { |f| f.write("hi") }+ end+ zip = Rack::Test::UploadedFile.new(tmp.path, "application/zip")++ post "/admin/config/emoji/import_preview.json", params: { file: zip }+ expect(response.status).to eq(422)+ end++ it "stores a manifest in Redis" do+ zip =+ build_emoji_zip(+ "name,group,filename\nredis-test,,redis-test.png\n",+ { "redis-test.png" => image_path },+ )++ post "/admin/config/emoji/import_preview.json", params: { file: zip }++ token = response.parsed_body["token"]+ redis_key = "emoji_import_preview:#{admin.id}:#{token}"+ expect(Discourse.redis.exists?(redis_key)).to eq(true)+ end+ end++ shared_examples "import preview not allowed" do+ it "denies access with a 404 response" do+ post "/admin/config/emoji/import_preview.json"+ expect(response.status).to eq(404)+ end+ end++ context "when logged in as a moderator" do+ before { sign_in(moderator) }+ include_examples "import preview not allowed"+ end++ context "when logged in as a non-staff user" do+ before { sign_in(user) }+ include_examples "import preview not allowed"+ end+ end++ describe "#import_confirm" do+ let(:image_path) { Rails.root.join("spec/fixtures/images/logo.png") }++ def store_manifest(user, token, rows, upload_map)+ key = "emoji_import_preview:#{user.id}:#{token}"+ Discourse.redis.setex(key, 2.hours.to_i, { rows: rows, upload_map: upload_map }.to_json)+ end++ context "when logged in as an admin" do+ before { sign_in(admin) }++ it "creates new emojis and clears the Redis manifest" do+ staged_upload =+ UploadCreator.new(+ file_from_fixtures("logo.png"),+ "logo.png",+ type: "custom_emoji",+ ).create_for(admin.id)+ token = SecureRandom.hex+ store_manifest(+ admin,+ token,+ [{ name: "confirm-new", group: "default", filename: "confirm-new.png", category: "new" }],+ { "confirm-new.png" => staged_upload.id },+ )++ expect do+ post "/admin/config/emoji/import_confirm.json", params: { token: token }+ end.to change { CustomEmoji.exists?(name: "confirm-new") }.from(false).to(true)++ expect(response.status).to eq(200)+ expect(response.parsed_body["created"]).to eq(1)+ expect(Discourse.redis.exists?("emoji_import_preview:#{admin.id}:#{token}")).to eq(false)+ end++ it "rolls back all changes on failure" do+ staged_upload =+ UploadCreator.new(+ file_from_fixtures("logo.png"),+ "logo.png",+ type: "custom_emoji",+ ).create_for(admin.id)+ token = SecureRandom.hex+ store_manifest(+ admin,+ token,+ [+ { name: "rollback-ok", group: "default", filename: "rollback-ok.png", category: "new" },+ { name: "", group: "default", filename: "bad.png", category: "new" },+ ],+ { "rollback-ok.png" => staged_upload.id, "bad.png" => staged_upload.id },+ )++ post "/admin/config/emoji/import_confirm.json", params: { token: token }++ expect(CustomEmoji.exists?(name: "rollback-ok")).to eq(false)+ end++ it "skips identical rows without creating records" do+ existing = CustomEmoji.create!(name: "same-emoji", upload: upload, user: admin)+ token = SecureRandom.hex+ store_manifest(+ admin,+ token,+ [+ {+ name: "same-emoji",+ group: "default",+ filename: "same-emoji.png",+ category: "identical",+ },+ ],+ {},+ )++ post "/admin/config/emoji/import_confirm.json", params: { token: token }++ expect(response.parsed_body["skipped"]).to eq(1)+ expect(existing.reload.upload_id).to eq(existing.upload_id)+ end++ it "respects keep resolution for conflict rows" do+ staged_upload =+ UploadCreator.new(+ file_from_fixtures("logo.png"),+ "logo.png",+ type: "custom_emoji",+ ).create_for(admin.id)+ existing = CustomEmoji.create!(name: "keep-me", upload: upload, group: "old", user: admin)+ token = SecureRandom.hex+ store_manifest(+ admin,+ token,+ [+ {+ name: "keep-me",+ group: "new-group",+ filename: "keep-me.png",+ category: "conflict_group",+ },+ ],+ { "keep-me.png" => staged_upload.id },+ )++ post "/admin/config/emoji/import_confirm.json",+ params: {+ token: token,+ resolutions: {+ "keep-me" => "keep",+ },+ }++ expect(existing.reload.group).to eq("old")+ end++ it "returns 422 when the session token is missing or expired" do+ post "/admin/config/emoji/import_confirm.json", params: { token: "nonexistent-token" }+ expect(response.status).to eq(422)+ end+ end++ shared_examples "import confirm not allowed" do+ it "denies access with a 404 response" do+ post "/admin/config/emoji/import_confirm.json", params: { token: "x" }+ expect(response.status).to eq(404)+ end+ end++ context "when logged in as a moderator" do+ before { sign_in(moderator) }+ include_examples "import confirm not allowed"+ end++ context "when logged in as a non-staff user" do+ before { sign_in(user) }+ include_examples "import confirm not allowed"+ end+ end+describe "#destroy" docontext "when logged in as an admin" dobefore { sign_in(admin) }diff --git a/spec/system/admin_customize_emojis_import_spec.rb b/spec/system/admin_customize_emojis_import_spec.rbnew file mode 100644index 00000000000..169c9676980--- /dev/null+++ b/spec/system/admin_customize_emojis_import_spec.rb@@ -0,0 +1,41 @@+# frozen_string_literal: true++describe "Admin Emoji Bulk Import" do+ fab!(:current_user, :admin)++ let(:emojis_page) { PageObjects::Pages::AdminEmojis.new }+ let(:dialog) { PageObjects::Components::Dialog.new }++ let(:sample_zip) { Rails.public_path.join("emoji-import-sample.zip") }++ before { sign_in(current_user) }++ it "imports emojis from the sample ZIP and shows them in the list" do+ emojis_page.visit_import_page++ emojis_page.upload_zip(sample_zip)++ expect(emojis_page).to have_import_preview++ emojis_page.confirm_import++ expect(page).to have_current_path("/admin/config/emoji")+ expect(emojis_page).to have_emoji_listed("discourse")+ end++ it "can re-import without error when emoji already exists (conflict resolution)" do+ emojis_page.visit_import_page+ emojis_page.upload_zip(sample_zip)+ emojis_page.confirm_import++ emojis_page.visit_import_page+ emojis_page.upload_zip(sample_zip)++ expect(emojis_page).to have_import_preview++ emojis_page.confirm_import++ expect(page).to have_current_path("/admin/config/emoji")+ expect(emojis_page).to have_emoji_listed("discourse")+ end+enddiff --git a/spec/system/page_objects/pages/admin_emojis.rb b/spec/system/page_objects/pages/admin_emojis.rbindex 66a93fecfca..1acfb90979f 100644--- a/spec/system/page_objects/pages/admin_emojis.rb+++ b/spec/system/page_objects/pages/admin_emojis.rb@@ -8,6 +8,11 @@ module PageObjectsselfend+ def visit_import_page+ page.visit "/admin/config/emoji/import"+ self+ end+def has_emoji_listed?(name)page.has_css?(emoji_table_selector, text: name)end@@ -20,6 +25,25 @@ module PageObjectsfind(".d-table__row", text: name).find(delete_button_selector).clickend+ def upload_zip(path)+ attach_file(path, class: "admin-emoji-import__file-input", make_visible: true)+ self+ end++ def has_import_preview?+ page.has_css?(".admin-emoji-import__summary")+ end++ def confirm_import+ find(".admin-emoji-import__actions .btn-primary").click+ self+ end++ def click_tab(tab_name)+ find(".admin-emoji-tabs__#{tab_name}").click+ self+ end+privatedef emoji_table_selector