2022-09-24 06:00:12 +09:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class TranslateStatusService < BaseService
|
|
|
|
CACHE_TTL = 1.day.freeze
|
|
|
|
|
2022-09-28 08:02:01 +09:00
|
|
|
include FormattingHelper
|
|
|
|
|
2022-09-24 06:00:12 +09:00
|
|
|
def call(status, target_language)
|
|
|
|
@status = status
|
2022-09-28 08:02:01 +09:00
|
|
|
@content = status_content_format(@status)
|
2022-09-24 06:00:12 +09:00
|
|
|
@target_language = target_language
|
|
|
|
|
2023-03-16 19:07:24 +09:00
|
|
|
raise Mastodon::NotPermittedError unless permitted?
|
|
|
|
|
2022-09-28 08:02:01 +09:00
|
|
|
Rails.cache.fetch("translations/#{@status.language}/#{@target_language}/#{content_hash}", expires_in: CACHE_TTL) { translation_backend.translate(@content, @status.language, @target_language) }
|
2022-09-24 06:00:12 +09:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def translation_backend
|
2023-03-16 19:07:24 +09:00
|
|
|
@translation_backend ||= TranslationService.configured
|
|
|
|
end
|
|
|
|
|
|
|
|
def permitted?
|
|
|
|
return false unless @status.distributable? && @status.content.present? && TranslationService.configured?
|
|
|
|
|
|
|
|
languages[@status.language]&.include?(@target_language)
|
|
|
|
end
|
|
|
|
|
|
|
|
def languages
|
|
|
|
Rails.cache.fetch('translation_service/languages', expires_in: 7.days, race_condition_ttl: 1.hour) { TranslationService.configured.languages }
|
2022-09-24 06:00:12 +09:00
|
|
|
end
|
|
|
|
|
|
|
|
def content_hash
|
2022-09-28 08:02:01 +09:00
|
|
|
Digest::SHA256.base64digest(@content)
|
2022-09-24 06:00:12 +09:00
|
|
|
end
|
|
|
|
end
|