5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
# File 'lib/polylingo_chat/translate_job.rb', line 5
def perform(message_id)
message = ::Message.find_by(id: message_id)
return unless message
conversation = message.conversation
return unless conversation
recipients = conversation.users.where.not(id: message.sender_id)
translation_enabled = PolylingoChat.config.api_key.present?
recipients.each do |recipient|
if translation_enabled
target_lang = recipient.preferred_language || PolylingoChat.config.default_language
source_lang = PolylingoChat::Translator.detect_language(message.body)
context = conversation.messages.order(created_at: :asc).last(20).pluck(:body).join("") rescue nil
translated = PolylingoChat::Translator.translate(text: message.body, from: source_lang, to: target_lang, context: context)
translated = translated.value if translated.respond_to?(:value)
else
translated = message.body
end
begin
ActionCable.server.broadcast("polylingo_chat_recipient_#{recipient.id}", {
message: translated,
original: message.body,
message_id: message.id,
sender_id: message.sender_id,
sender_name: message.sender.name,
translated: translation_enabled
})
ActionCable.server.broadcast("conversation_#{conversation.id}", {
message: translated,
original: message.body,
message_id: message.id,
sender_id: message.sender_id,
sender_name: message.sender.name,
translated: translation_enabled,
recipient_id: recipient.id
})
rescue StandardError => e
Rails.logger.error("PolylingoChat: Broadcast failed - #{e.message}")
end
end
message.update(translated: translation_enabled)
rescue StandardError => e
Rails.logger.error("PolylingoChat: Failed to update message translation status - #{e.message}")
end
|