Class: PolylingoChat::TranslateJob

Inherits:
ApplicationJob
  • Object
show all
Defined in:
lib/polylingo_chat/translate_job.rb

Instance Method Summary collapse

Instance Method Details

#perform(message_id) ⇒ Object



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)
  # Host app must implement Message model with associations matching spec
  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)

  # Check if translation is enabled (API key present)
  translation_enabled = PolylingoChat.config.api_key.present?

  recipients.each do |recipient|
    if translation_enabled
      # Translation enabled - translate message
      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)
      # If translator returns a Future-like, wait
      translated = translated.value if translated.respond_to?(:value)
    else
      # No API key - just use original message (chat-only mode)
      translated = message.body
    end

    # Broadcast to recipient using ActionCable
    begin
      # Broadcast to user-specific channel
      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
      })

      # Also broadcast to conversation channel for demo/group chat
      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