Module: Brainiac::Plugins::Zoho::MailApi

Defined in:
lib/brainiac/plugins/zoho/mail_api.rb

Constant Summary collapse

ZOHO_TOKEN_URL =
"https://accounts.zoho.com/oauth/v2/token"
ZOHO_MAIL_API_BASE =
"https://mail.zoho.com/api/accounts"

Class Method Summary collapse

Class Method Details

.access_tokenObject



45
46
47
48
49
# File 'lib/brainiac/plugins/zoho/mail_api.rb', line 45

def access_token
  return @access_token if @access_token && Time.now < @token_expires_at

  refresh_access_token!
end

.configured?Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/brainiac/plugins/zoho/mail_api.rb', line 16

def configured?
  Config.api_configured?
end

.fetch_email_content(message_id) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/brainiac/plugins/zoho/mail_api.rb', line 57

def fetch_email_content(message_id)
  return nil unless configured?

  token = access_token
  return nil unless token

   = Config.api_section["account_id"]
  uri = URI("#{ZOHO_MAIL_API_BASE}/#{}/messages/#{message_id}/originalmessage")

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  req = Net::HTTP::Get.new(uri)
  req["Authorization"] = "Zoho-oauthtoken #{token}"
  req["Accept"] = "application/json"

  res = http.request(req)
  data = JSON.parse(res.body)

  if data.dig("status", "code") == 200
    raw_mime = data.dig("data", "content").to_s
    text = extract_text_from_mime(raw_mime)
    LOG.info "[Zoho:API] Fetched content for message #{message_id} (#{text.length} chars)"
    text
  else
    LOG.warn "[Zoho:API] Failed to fetch content: #{data.dig("status", "description")}"
    nil
  end
rescue StandardError => e
  LOG.error "[Zoho:API] Error fetching content: #{e.message}"
  nil
end

.refresh_access_token!Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/brainiac/plugins/zoho/mail_api.rb', line 20

def refresh_access_token!
  api = Config.api_section
  uri = URI(ZOHO_TOKEN_URL)
  res = Net::HTTP.post_form(uri, {
                              "grant_type" => "refresh_token",
                              "client_id" => api["client_id"],
                              "client_secret" => api["client_secret"],
                              "refresh_token" => api["refresh_token"]
                            })

  data = JSON.parse(res.body)
  if data["access_token"]
    @access_token = data["access_token"]
    @token_expires_at = Time.now + 3300
    LOG.info "[Zoho:API] Refreshed access token"
    @access_token
  else
    LOG.error "[Zoho:API] Token refresh failed: #{data["error"]}"
    nil
  end
rescue StandardError => e
  LOG.error "[Zoho:API] Token refresh error: #{e.message}"
  nil
end

.store_token(token) ⇒ Object

Store token obtained during OAuth callback



52
53
54
55
# File 'lib/brainiac/plugins/zoho/mail_api.rb', line 52

def store_token(token)
  @access_token = token
  @token_expires_at = Time.now + 3300
end