Class: Heathrow::Sources::Whatsapp

Inherits:
Object
  • Object
show all
Defined in:
lib/heathrow/sources/whatsapp.rb

Constant Summary collapse

DEFAULT_API_URL =
'http://localhost:3000'
DEFAULT_SESSION =
'default'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source) ⇒ Whatsapp

Returns a new instance of Whatsapp.



21
22
23
24
25
26
27
# File 'lib/heathrow/sources/whatsapp.rb', line 21

def initialize(source)
  @source = source
  @config = source.config.is_a?(String) ? JSON.parse(source.config) : source.config
  @last_fetch_time = Time.now
  @session = @config['session'] || DEFAULT_SESSION
  @api_url = @config['api_url'] || DEFAULT_API_URL
end

Instance Attribute Details

#last_fetch_timeObject (readonly)

Returns the value of attribute last_fetch_time.



16
17
18
# File 'lib/heathrow/sources/whatsapp.rb', line 16

def last_fetch_time
  @last_fetch_time
end

#sourceObject (readonly)

Returns the value of attribute source.



16
17
18
# File 'lib/heathrow/sources/whatsapp.rb', line 16

def source
  @source
end

Instance Method Details

#authenticateObject



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/heathrow/sources/whatsapp.rb', line 185

def authenticate
  begin
    # Create session if it doesn't exist
    unless session_exists?
      puts "Creating WhatsApp session '#{@session}'..."
      create_session
    end

    # Start session if stopped
    status = get_session_status
    if status == 'STOPPED'
      start_session
      sleep(2)
    end

    # Get QR code and wait for scan
    authenticate_with_qr_code

  rescue => e
    puts "Authentication error: #{e.message}"
    false
  end
end

#can_reply?Boolean

Returns:

  • (Boolean)


101
102
103
# File 'lib/heathrow/sources/whatsapp.rb', line 101

def can_reply?
  authenticated?
end

#fetch_messagesObject



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
# File 'lib/heathrow/sources/whatsapp.rb', line 29

def fetch_messages
  messages = []

  begin
    unless authenticated?
      puts "WhatsApp not authenticated. Run setup first." if ENV['DEBUG']
      return messages
    end

    # Get list of chats
    chats = fetch_chats
    return messages if chats.empty?

    # Fetch recent messages from each chat
    limit = @config['fetch_limit'] || 20
    chats.each do |chat|
      chat_id = chat['id']
      chat_messages = fetch_chat_messages(chat_id, limit)

      chat_messages.each do |msg|
        message = convert_to_heathrow_message(msg, chat)
        messages << message if message
      end
    end

    @last_fetch_time = Time.now

  rescue => e
    puts "WhatsApp fetch error: #{e.message}" if ENV['DEBUG']
    puts e.backtrace.join("\n") if ENV['DEBUG']
  end

  messages
end

#post_configureObject



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/heathrow/sources/whatsapp.rb', line 209

def post_configure
  if authenticated?
    puts "WhatsApp already authenticated!"
    return true
  end

  puts "\nWhatsApp requires authentication via QR code."
  print "Would you like to authenticate now? (y/n): "
  response = gets.chomp.downcase

  if response == 'y'
    authenticate
  else
    puts "You can authenticate later by running: ruby setup_whatsapp.rb"
    true
  end
end

#send_media(to, file_path, caption = nil) ⇒ Object



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/heathrow/sources/whatsapp.rb', line 139

def send_media(to, file_path, caption = nil)
  unless can_reply?
    return { success: false, message: "WhatsApp not authenticated" }
  end

  begin
    chat_id = format_chat_id(to)
    mime_type = detect_mime_type(file_path)

    # Determine endpoint based on media type
    endpoint = case mime_type
               when /^image/ then '/api/sendImage'
               when /^video/ then '/api/sendVideo'
               when /^audio/ then '/api/sendVoice'
               else '/api/sendFile'
               end

    # Read and encode file
    file_data = Base64.strict_encode64(File.binread(file_path))

    payload = {
      session: @session,
      chatId: chat_id,
      file: {
        mimetype: mime_type,
        filename: File.basename(file_path),
        data: file_data
      }
    }
    payload[:caption] = caption if caption

    uri = URI("#{@api_url}#{endpoint}")
    response = post_json(uri, payload)

    if response.is_a?(Net::HTTPSuccess)
      { success: true, message: "Media sent to #{to}" }
    else
      error = parse_error(response)
      { success: false, message: "Failed to send media: #{error}" }
    end

  rescue => e
    { success: false, message: "Send media failed: #{e.message}" }
  end
end

#send_message(to, subject, body, in_reply_to = nil) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/heathrow/sources/whatsapp.rb', line 105

def send_message(to, subject, body, in_reply_to = nil)
  unless can_reply?
    return { success: false, message: "WhatsApp not authenticated" }
  end

  begin
    chat_id = format_chat_id(to)

    payload = {
      session: @session,
      chatId: chat_id,
      text: body
    }

    # Add reply context if replying
    payload[:reply_to] = in_reply_to if in_reply_to

    uri = URI("#{@api_url}/api/sendText")
    response = post_json(uri, payload)

    if response.is_a?(Net::HTTPSuccess)
      { success: true, message: "Message sent to #{to}" }
    else
      error = parse_error(response)
      { success: false, message: "Failed to send: #{error}" }
    end

  rescue Errno::ECONNREFUSED
    { success: false, message: "WAHA not running" }
  rescue => e
    { success: false, message: "Send failed: #{e.message}" }
  end
end

#test_connectionObject



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/heathrow/sources/whatsapp.rb', line 64

def test_connection
  begin
    # Check session status
    uri = URI("#{@api_url}/api/sessions/#{@session}")
    response = Net::HTTP.get_response(uri)

    if response.is_a?(Net::HTTPSuccess)
      data = JSON.parse(response.body)
      status = data['status']

      case status
      when 'WORKING'
        me = data.dig('me', 'id') || 'Unknown'
        phone = me.split('@').first
        { success: true, message: "Connected as +#{phone}" }
      when 'SCAN_QR_CODE'
        { success: false, message: "Session needs QR code scan. Run setup." }
      when 'STARTING'
        { success: false, message: "Session is starting..." }
      when 'STOPPED'
        { success: false, message: "Session stopped. Run setup to start." }
      else
        { success: false, message: "Session status: #{status}" }
      end
    elsif response.code == '404'
      { success: false, message: "Session '#{@session}' not found. Run setup." }
    else
      { success: false, message: "API error: #{response.code}" }
    end

  rescue Errno::ECONNREFUSED
    { success: false, message: "WAHA not running. Start with: docker run -p 3000:3000 devlikeapro/waha" }
  rescue => e
    { success: false, message: "Connection failed: #{e.message}" }
  end
end