A platform for community discussion. Free, open, simple.
FEATURE: force refresh translations (#34904)
Keegan George768eb01c6b9d
diff --git a/app/assets/javascripts/discourse/app/components/post/menu/buttons/add-translation.gjs b/app/assets/javascripts/discourse/app/components/post/menu/buttons/add-translation.gjsindex 16bfe0ce135..683087d2f32 100644--- a/app/assets/javascripts/discourse/app/components/post/menu/buttons/add-translation.gjs+++ b/app/assets/javascripts/discourse/app/components/post/menu/buttons/add-translation.gjs@@ -6,6 +6,8 @@ import DButton from "discourse/components/d-button";import DEditorOriginalTranslationPreview from "discourse/components/d-editor-original-translation-preview";import DropdownMenu from "discourse/components/dropdown-menu";import PostTranslationsModal from "discourse/components/modal/post-translations";+import PluginOutlet from "discourse/components/plugin-outlet";+import lazyHash from "discourse/helpers/lazy-hash";import { ajax } from "discourse/lib/ajax";import Composer from "discourse/models/composer";import { i18n } from "discourse-i18n";@@ -98,22 +100,27 @@ export default class PostMenuAddTranslationButton extends Component {><:content><DropdownMenu as |dropdown|>- <dropdown.item class="update-translations-menu__view">- <DButton- class="post-action-menu__view-translation"- @translatedLabel={{this.viewTranslationLabel}}- @icon="eye"- @action={{this.viewTranslations}}- />- </dropdown.item>- <dropdown.item class="update-translations-menu__add">- <DButton- class="post-action-menu__add-translation"- @label="post.localizations.add"- @icon="plus"- @action={{this.addTranslation}}- />- </dropdown.item>+ <PluginOutlet+ @name="post-menu-translations-dropdown"+ @outletArgs={{lazyHash dropdown=dropdown post=@post}}+ >+ <dropdown.item class="update-translations-menu__view">+ <DButton+ class="post-action-menu__view-translation"+ @translatedLabel={{this.viewTranslationLabel}}+ @icon="eye"+ @action={{this.viewTranslations}}+ />+ </dropdown.item>+ <dropdown.item class="update-translations-menu__add">+ <DButton+ class="post-action-menu__add-translation"+ @label="post.localizations.add"+ @icon="plus"+ @action={{this.addTranslation}}+ />+ </dropdown.item>+ </PluginOutlet></DropdownMenu></:content></DMenu>diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/translation/translation_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/translation/translation_controller.rbnew file mode 100644index 00000000000..8a64887a76b--- /dev/null+++ b/plugins/discourse-ai/app/controllers/discourse_ai/translation/translation_controller.rb@@ -0,0 +1,46 @@+# frozen_string_literal: true++module DiscourseAi+ module Translation+ class TranslationController < ::ApplicationController+ requires_plugin DiscourseAi::PLUGIN_NAME++ before_action :ensure_logged_in+ before_action :check_permissions+ before_action :rate_limit!++ def translate+ post = Post.find_by(id: params[:post_id])+ raise ActiveRecord::RecordNotFound unless post++ if DiscourseAi::Translation.enabled?+ Jobs.enqueue(:detect_translate_post, post_id: post.id, force: true)+ else+ return(+ render json:+ failed_json.merge(error: I18n.t("discourse_ai.translation.errors.disabled")),+ status: 400+ )+ end++ render json: success_json+ end++ private++ def check_permissions+ if !current_user&.in_any_groups?(SiteSetting.content_localization_allowed_groups_map)+ raise Discourse::InvalidAccess+ end+ end++ def rate_limit!+ begin+ RateLimiter.new(current_user, "ai_translate_post", 3, 5.minutes).performed!+ rescue RateLimiter::LimitExceeded+ render_json_error(I18n.t("rate_limiter.slow_down"))+ end+ end+ end+ end+enddiff --git a/plugins/discourse-ai/app/jobs/regular/detect_translate_post.rb b/plugins/discourse-ai/app/jobs/regular/detect_translate_post.rbindex bde9f63c9df..bee6fbcffa8 100644--- a/plugins/discourse-ai/app/jobs/regular/detect_translate_post.rb+++ b/plugins/discourse-ai/app/jobs/regular/detect_translate_post.rb@@ -15,7 +15,11 @@ module Jobstopic = post.topicreturn if topic.blank?- if SiteSetting.ai_translation_backfill_limit_to_public_content+ force = args[:force] || false++ if force+ # no restrictions+ elsif SiteSetting.ai_translation_backfill_limit_to_public_contentreturn if topic.category&.read_restricted? || topic.archetype == Archetype.private_messageelseif topic.archetype == Archetype.private_message &&diff --git a/plugins/discourse-ai/assets/javascripts/discourse/connectors/post-menu-translations-dropdown/ai-post-menu-translation-extras.gjs b/plugins/discourse-ai/assets/javascripts/discourse/connectors/post-menu-translations-dropdown/ai-post-menu-translation-extras.gjsnew file mode 100644index 00000000000..9e61c262d0c--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/connectors/post-menu-translations-dropdown/ai-post-menu-translation-extras.gjs@@ -0,0 +1,70 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import { service } from "@ember/service";+import DButton from "discourse/components/d-button";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { i18n } from "discourse-i18n";++export default class AiPostMenuTranslationExtras extends Component {+ static shouldRender(args, { siteSettings, currentUser }) {+ return (+ siteSettings.discourse_ai_enabled &&+ siteSettings.ai_translation_enabled &&+ currentUser.can_localize_content+ );+ }++ @service dialog;+ @service toasts;++ async #translate() {+ try {+ await ajax(`/discourse-ai/translate/posts/${this.args.post.id}`, {+ type: "POST",+ });+ } catch (error) {+ popupAjaxError(error);+ }+ }++ @action+ translate() {+ const confirmMessage = i18n(+ "discourse_ai.translations.translations_menu.translate.confirm"+ );++ return this.dialog.yesNoConfirm({+ message: confirmMessage,+ didConfirm: async () => {+ try {+ await this.#translate();++ this.toasts.success({+ duration: "short",+ data: {+ message: i18n(+ "discourse_ai.translations.translations_menu.translate.success"+ ),+ },+ });+ } catch (e) {+ popupAjaxError(e);+ }+ },+ });+ }++ <template>+ <@dropdown.item class="update-translations-menu__translate">+ <DButton+ class="post-action-menu__translate-translation"+ @label="discourse_ai.translations.translations_menu.translate.label"+ @icon="arrows-rotate"+ @action={{this.translate}}+ @title="discourse_ai.translations.translations_menu.translate.title"+ />+ </@dropdown.item>+ {{yield}}+ </template>+}diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.ymlindex 239137e7c7a..6d71ff70cf8 100644--- a/plugins/discourse-ai/config/locales/client.en.yml+++ b/plugins/discourse-ai/config/locales/client.en.yml@@ -346,6 +346,12 @@ en:bar_done:one: "%{count} post"other: "%{count} posts"+ translations_menu:+ translate:+ label: "Translate post"+ title: "Translates this post to all supported languages"+ confirm: "This will update any existing translations on this post. Are you sure?"+ success: "Translations are been successfully refreshed"spam:short_title: "Spam"diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex 5023cb85970..0a3139af664 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -640,6 +640,10 @@ en:set: "set"removed: "removed"+ translation:+ errors:+ disabled: "The AI translation feature is not fully configured."+errors:quota_exceeded: "You have exceeded the quota for this model. Please try again in %{relative_time}."quota_required: "You must specify maximum tokens or usages for this model"diff --git a/plugins/discourse-ai/config/routes.rb b/plugins/discourse-ai/config/routes.rbindex 5c8409b4d59..31d5554ac0b 100644--- a/plugins/discourse-ai/config/routes.rb+++ b/plugins/discourse-ai/config/routes.rb@@ -62,6 +62,10 @@ DiscourseAi::Engine.routes.draw doscope module: :sentiment, path: "/sentiment", defaults: { format: :json } doget "/posts" => "sentiment#posts", :constraints => StaffConstraint.newend++ scope module: :translation, path: "/translate", defaults: { format: :json } do+ post "/posts/:post_id" => "translation#translate"+ endendDiscourse::Application.routes.draw dodiff --git a/plugins/discourse-ai/spec/jobs/regular/detect_translate_post_spec.rb b/plugins/discourse-ai/spec/jobs/regular/detect_translate_post_spec.rbindex 55737a0ebcc..6d4dc8cfc80 100644--- a/plugins/discourse-ai/spec/jobs/regular/detect_translate_post_spec.rb+++ b/plugins/discourse-ai/spec/jobs/regular/detect_translate_post_spec.rb@@ -176,6 +176,26 @@ describe Jobs::DetectTranslatePost do.neverjob.execute({ post_id: personal_pm_post.id })end++ describe "force arg" do+ it "processes private content when force is true" do+ DiscourseAi::Translation::PostLocaleDetector+ .expects(:detect_locale)+ .with(group_pm_post)+ .once++ job.execute({ post_id: group_pm_post.id, force: true })+ end++ it "processes PM content when force is true" do+ DiscourseAi::Translation::PostLocaleDetector+ .expects(:detect_locale)+ .with(personal_pm_post)+ .once++ job.execute({ post_id: personal_pm_post.id, force: true })+ end+ endendendenddiff --git a/plugins/discourse-ai/spec/requests/translation/translation_controller_spec.rb b/plugins/discourse-ai/spec/requests/translation/translation_controller_spec.rbnew file mode 100644index 00000000000..9c1ab61eb4a--- /dev/null+++ b/plugins/discourse-ai/spec/requests/translation/translation_controller_spec.rb@@ -0,0 +1,71 @@+# frozen_string_literal: true++describe DiscourseAi::Translation::TranslationController do+ fab!(:user)+ fab!(:admin)+ fab!(:test_post) { Fabricate(:post) }+ fab!(:group)++ before do+ enable_current_plugin+ assign_fake_provider_to(:ai_default_llm_model)+ SiteSetting.discourse_ai_enabled = true+ SiteSetting.ai_translation_enabled = true+ SiteSetting.content_localization_supported_locales = "en"+ SiteSetting.content_localization_allowed_groups = "#{Group::AUTO_GROUPS[:staff]}|#{group.id}"+ end++ describe "#translate" do+ context "when not logged in" do+ it "returns a 403 response" do+ post "/discourse-ai/translate/posts/#{test_post.id}"+ expect(response.status).to eq(403)+ end+ end++ context "when logged in but not in allowed groups" do+ it "returns a 403 response" do+ sign_in(user)+ post "/discourse-ai/translate/posts/#{test_post.id}"+ expect(response.status).to eq(403)+ end+ end++ context "when logged in and in allowed groups" do+ before do+ group.add(user)+ SiteSetting.content_localization_allowed_groups = group.id.to_s+ sign_in(user)+ end++ it "returns a 404 for non-existent post" do+ post "/discourse-ai/translate/posts/999999"+ expect(response.status).to eq(404)+ end++ it "successfully enqueues translation job when user can edit" do+ admin_post = Fabricate(:post, user: admin)++ expect_enqueued_with(+ job: Jobs::DetectTranslatePost,+ args: {+ post_id: admin_post.id,+ force: true,+ },+ ) { post "/discourse-ai/translate/posts/#{admin_post.id}" }++ expect(response.status).to eq(200)+ end+ end++ context "when required settings are unconfigured" do+ it "returns a 400 response" do+ sign_in(admin)+ SiteSetting.ai_translation_enabled = false++ post "/discourse-ai/translate/posts/#{test_post.id}"+ expect(response.status).to eq(400)+ end+ end+ end+end