@@ -24,19 +24,53 @@ def self.cache_key
2424 "#{ key_prefix } #{ access_token_key } "
2525 end
2626
27- def self . translate ( post )
27+ def self . translate ( topic_or_post )
28+ return if text_for_translation ( topic_or_post ) . blank?
29+ detected_lang = detect ( topic_or_post )
30+
31+ return detected_lang , get_text ( topic_or_post ) if ( detected_lang &.to_s . eql? I18n . locale . to_s )
32+ unless translate_supported? ( detected_lang , I18n . locale )
33+ raise TranslatorError . new (
34+ I18n . t (
35+ "translator.failed" ,
36+ source_locale : detected_lang ,
37+ target_locale : I18n . locale ,
38+ ) ,
39+ )
40+ end
41+
42+ translated_text = translate! ( topic_or_post )
43+
44+ [ detected_lang , translated_text ]
45+ end
46+
47+ def self . translate! ( post )
2848 raise "Not Implemented"
2949 end
3050
31- def self . detect ( post )
51+ # Returns the stored detected locale of a post or topic.
52+ # If the locale does not exist yet, it will be detected first via the API then stored.
53+ # @param topic_or_post [Post|Topic]
54+ def self . detect ( topic_or_post )
55+ return if text_for_detection ( topic_or_post ) . blank?
56+ get_detected_locale ( topic_or_post ) || detect! ( topic_or_post )
57+ end
58+
59+ def self . detect! ( post )
3260 raise "Not Implemented"
3361 end
3462
3563 def self . access_token
3664 raise "Not Implemented"
3765 end
3866
39- def self . from_custom_fields ( topic_or_post )
67+ def self . get_translation ( topic_or_post )
68+ translated_custom_field =
69+ topic_or_post . custom_fields [ DiscourseTranslator ::TRANSLATED_CUSTOM_FIELD ] || { }
70+ translated_custom_field [ I18n . locale ]
71+ end
72+
73+ def self . save_translation ( topic_or_post )
4074 translated_custom_field =
4175 topic_or_post . custom_fields [ DiscourseTranslator ::TRANSLATED_CUSTOM_FIELD ] || { }
4276 translated_text = translated_custom_field [ I18n . locale ]
@@ -54,6 +88,22 @@ def self.from_custom_fields(topic_or_post)
5488 translated_text
5589 end
5690
91+ def self . get_detected_locale ( topic_or_post )
92+ topic_or_post . custom_fields [ DiscourseTranslator ::DETECTED_LANG_CUSTOM_FIELD ]
93+ end
94+
95+ def self . save_detected_locale ( topic_or_post )
96+ detected_locale = yield
97+ topic_or_post . custom_fields [ DiscourseTranslator ::DETECTED_LANG_CUSTOM_FIELD ] = detected_locale
98+
99+ if !topic_or_post . custom_fields_clean?
100+ topic_or_post . save_custom_fields
101+ topic_or_post . publish_change_to_clients! ( :revised ) if topic_or_post . class . name == "Post"
102+ end
103+
104+ detected_locale
105+ end
106+
57107 def self . get_text ( topic_or_post )
58108 case topic_or_post . class . name
59109 when "Post"
@@ -70,6 +120,10 @@ def self.language_supported?(detected_lang)
70120 detected_lang != supported_lang [ I18n . locale ]
71121 end
72122
123+ def self . translate_supported? ( detected_lang , target_lang )
124+ true
125+ end
126+
73127 private
74128
75129 def self . strip_tags_for_detection ( detection_text )
0 commit comments