# frozen_string_literal: true require 'json' require 'net/http' require 'net/https' require 'uri' class CdrDeltachatApi def initialize(api_url, token) @token = token @last_update = 0 @api_url = ENV.fetch('BRIDGE_DELTACHAT_URL', api_url || 'http://bridge-deltachat:5001') end def get(api) url = "#{@api_url}/api/bots/#{@token}/#{api}" response = Faraday.get(url, nil, { 'Accept' => 'application/json' }) return {} unless response.success? JSON.parse(response.body) rescue JSON::ParserError, Faraday::Error => e Rails.logger.error "CdrDeltachatApi: GET #{api} failed: #{e.message}" {} end def post(api, params = {}) url = "#{@api_url}/api/bots/#{@token}/#{api}" response = Faraday.post(url, params.to_json, { 'Content-Type' => 'application/json', 'Accept' => 'application/json' }) unless response.success? Rails.logger.error "CdrDeltachatApi: POST #{api} failed: #{response.status} #{response.body}" raise "Failed to call DeltaChat API: #{response.status}" end JSON.parse(response.body) rescue JSON::ParserError => e Rails.logger.error "CdrDeltachatApi: Failed to parse response: #{e.message}" {} rescue Faraday::Error => e Rails.logger.error "CdrDeltachatApi: POST #{api} failed: #{e.message}" raise "Failed to call DeltaChat API: #{e.message}" end def fetch_self get('') end def send_message(recipient, text, options = {}) params = { email: recipient.to_s, message: text } if options[:attachments].present? params[:attachments] = options[:attachments].map do |att| { data: att[:data], filename: att[:filename], mime_type: att[:mime_type] } end end result = post('send', params) { 'result' => { 'to' => result.dig('result', 'recipient') || recipient, 'from' => result.dig('result', 'source') || @token, 'timestamp' => result.dig('result', 'timestamp') || Time.current.iso8601 } } end end