A platform for community discussion. Free, open, simple.
# frozen_string_literal: true
module Jobs
class DetectTranslatePost < ::Jobs::Base
cluster_concurrency 1
sidekiq_options retry: false
def execute(args)
return if !DiscourseAi::Translation.enabled?
return if args[:post_id].blank?
unless DiscourseAi::Translation.credits_available_for_post_detection?
Rails.logger.info(
"Translation skipped for post: insufficient credits. Will resume when credits reset.",
)
return
end
post = Post.find_by(id: args[:post_id])
return if post.blank? || post.raw.blank? || post.deleted_at.present?
force = args[:force] || false
return if post.topic.blank?
return if !force && !DiscourseAi::Translation.post_translatable?(post)
# the user may fill locale in manually
if (detected_locale = post.locale).blank?
begin
detected_locale = DiscourseAi::Translation::PostLocaleDetector.detect_locale(post)
rescue FinalDestination::SSRFDetector::LookupFailedError
# this job is non-critical
# the backfill job will handle failures
return
end
return if detected_locale.blank?
DiscourseEvent.trigger(
:post_locale_detected,
post,
{ skip_workflows: args[:skip_workflows] },
)
end
locales = DiscourseAi::Translation.locales
return if locales.blank?
existing_base_locales =
PostLocalization
.where(post_id: post.id)
.pluck(:locale)
.map { |l| l.split("_").first }
.to_set
locales.each do |locale|
next if LocaleNormalizer.is_same?(locale, detected_locale)
base_locale = locale.split("_").first
exists = existing_base_locales.include?(base_locale)
has_quota = DiscourseAi::Translation::PostLocalizer.has_relocalize_quota?(post, locale)
next if !force && exists && !has_quota
localize(post, locale)
end
MessageBus.publish(
"/topic/#{post.topic_id}",
{ type: :localized, id: post.id },
post.topic.secure_audience_publish_messages,
)
ensure
# Lets anything waiting on this post's translations stop waiting, even when
# some of them weren't produced.
if args[:post_id].present?
DiscourseEvent.trigger(:post_localizations_finished, args[:post_id].to_i)
end
end
private
def localize(post, locale)
DiscourseAi::Translation::PostLocalizer.localize(post, locale)
rescue FinalDestination::SSRFDetector::LookupFailedError
# do nothing, there are too many sporadic lookup failures
rescue => e
DiscourseAi::Translation::VerboseLogger.log(
"Failed to translate post #{post.id} to #{locale}: #{e.message}\n\n#{e.backtrace[0..3].join("\n")}",
)
end
end
end