2022-03-22 06:44:17 +00:00
|
|
|
require 'net/imap'
|
|
|
|
|
2021-11-19 06:22:27 +00:00
|
|
|
class Inboxes::FetchImapEmailsJob < ApplicationJob
|
|
|
|
queue_as :low
|
|
|
|
|
|
|
|
def perform(channel)
|
2022-03-22 06:44:17 +00:00
|
|
|
return unless should_fetch_email?(channel)
|
|
|
|
|
2022-06-02 06:08:58 +00:00
|
|
|
fetch_mail_for_channel(channel)
|
2022-05-26 14:53:00 +00:00
|
|
|
# clearing old failures like timeouts since the mail is now successfully processed
|
|
|
|
channel.reauthorized!
|
2022-11-09 04:23:46 +00:00
|
|
|
rescue *ExceptionList::IMAP_EXCEPTIONS
|
2022-03-22 06:44:17 +00:00
|
|
|
channel.authorization_error!
|
2022-07-08 09:39:06 +00:00
|
|
|
rescue EOFError => e
|
|
|
|
Rails.logger.error e
|
2022-03-22 06:44:17 +00:00
|
|
|
rescue StandardError => e
|
2022-05-09 08:53:19 +00:00
|
|
|
ChatwootExceptionTracker.new(e, account: channel.account).capture_exception
|
2022-03-22 06:44:17 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def should_fetch_email?(channel)
|
|
|
|
channel.imap_enabled? && !channel.reauthorization_required?
|
|
|
|
end
|
2021-12-15 12:01:16 +00:00
|
|
|
|
2022-06-02 06:08:58 +00:00
|
|
|
def fetch_mail_for_channel(channel)
|
2022-03-22 06:44:17 +00:00
|
|
|
# TODO: rather than setting this as default method for all mail objects, lets if can do new mail object
|
|
|
|
# using Mail.retriever_method.new(params)
|
2021-11-19 06:22:27 +00:00
|
|
|
Mail.defaults do
|
|
|
|
retriever_method :imap, address: channel.imap_address,
|
|
|
|
port: channel.imap_port,
|
2022-04-11 14:07:20 +00:00
|
|
|
user_name: channel.imap_login,
|
2021-11-19 06:22:27 +00:00
|
|
|
password: channel.imap_password,
|
|
|
|
enable_ssl: channel.imap_enable_ssl
|
|
|
|
end
|
|
|
|
|
2022-07-08 11:13:24 +00:00
|
|
|
Mail.find(what: :last, count: 10, order: :asc).each do |inbound_mail|
|
|
|
|
next if channel.inbox.messages.find_by(source_id: inbound_mail.message_id).present?
|
2022-06-02 06:08:58 +00:00
|
|
|
|
|
|
|
process_mail(inbound_mail, channel)
|
2021-11-19 06:22:27 +00:00
|
|
|
end
|
|
|
|
end
|
2022-06-02 06:08:58 +00:00
|
|
|
|
|
|
|
def process_mail(inbound_mail, channel)
|
|
|
|
Imap::ImapMailbox.new.process(inbound_mail, channel)
|
|
|
|
rescue StandardError => e
|
|
|
|
ChatwootExceptionTracker.new(e, account: channel.account).capture_exception
|
|
|
|
end
|
2021-11-19 06:22:27 +00:00
|
|
|
end
|