class Mail2cb::EmailWatcher

Public Class Methods

new() click to toggle source
# File lib/mail2cb/email_watcher.rb, line 9
def initialize

  raise "REDIS_URL environment variable is required (eg redis://localhost:6739)" unless ENV["REDIS_URL"]
  raise "MYSQL_HOST environment variable is required" unless ENV["MYSQL_HOST"]
  raise "MYSQL_DATABASE environment variable is required" unless ENV["MYSQL_DATABASE"]
  raise "MYSQL_USERNAME environment variable is required" unless ENV["MYSQL_USERNAME"]
  raise "MYSQL_PASSWORD environment variable is required" unless ENV["MYSQL_PASSWORD"]

  unless ENV["AWS_ACCESS_KEY"] && ENV["AWS_SECRET_KEY"] && ENV["AWS_MAILROOM_BUCKET"]
    puts "WARNING: Attachments will store to local file system as AWS keys not provided"
  end


  ENV["MYSQL_PASSWORD"] = "" unless ENV["MYSQL_PASSWORD"]
  ENV["MYSQL_PORT"] = "3306"
  @debug = ENV["DEBUG"] == "true"

  redis_url = URI.parse(ENV["REDIS_URL"])

  $redis = Redis.new(:host => redis_url.host, :port => redis_url.port)

  Signal.trap("INT") {
    Thread.new {self.stop}.join
  }
  # Trap `Kill `
  Signal.trap("TERM") {
    Thread.new {self.stop}.join
  }

  @daemon = MailDaemon::Handler.new(:connections => configuration, :debug => @debug)
end

Public Instance Methods

configuration() click to toggle source
# File lib/mail2cb/email_watcher.rb, line 53
    def configuration
      mailboxes = []
      mysql_client do |mysql|
        sql=<<EOS
        SELECT case_blocks_email_accounts.id,
          case_blocks_accounts.id as account_id,
          case_blocks_accounts.nickname,
          case_blocks_email_accounts.imap_username,
          case_blocks_email_accounts.imap_encrypted_password,
          case_blocks_email_accounts.imap_host,
          case_blocks_email_accounts.imap_port,
          case_blocks_email_accounts.imap_ssl,
          case_blocks_email_accounts.imap_start_tls,
          case_blocks_email_accounts.imap_folder_name,
          case_blocks_email_accounts.imap_search_command,
          case_blocks_email_accounts.imap_messages_processed,
          case_blocks_email_accounts.imap_last_processed_at,
          u.authentication_token,
          case_blocks_email_accounts.id as mailbox_id,
          case_blocks_email_accounts.name as mailbox_name
        FROM case_blocks_email_accounts
        JOIN case_blocks_accounts
        ON case_blocks_email_accounts.account_id = case_blocks_accounts.id
        JOIN case_blocks_users u
        ON u.account_id = case_blocks_accounts.id
        where imap_enabled=1
        and u.is_bot=1
        and u.is_account_admin=1
EOS
        result = mysql.query(sql)
        result.each do |row|
          ssl_options = row["imap_ssl"]==1 ? {:verify_mode => OpenSSL::SSL::VERIFY_NONE} : false

          auth_token = row["authentication_token"]
          decrypted_password = Encryption.new(auth_token).decrypt(row["imap_encrypted_password"])
          puts "decrypted password: #{decrypted_password}"
          mailboxes << {:id => row["id"],
                          :account_code => row["nickname"],
                          :account_id => row["account_id"],
                          :username => row["imap_username"],
                          :host => row["imap_host"],
                          :port => row["imap_port"],
                          :password => decrypted_password,
                          :ssl_options => ssl_options,
                          :start_tls => row["imap_start_tls"]==1,
                          :name => row["imap_folder_nam"],
                          :search_command => row["imap_search_command"],
                          :message_count => row["imap_messages_processed"],
                          :last_delivered_at => row["imap_last_processed_at"],
                          :mailbox_id => row["mailbox_id"],
                          :mailbox_name => row["mailbox_name"],
                          :mailbox_default => row['smtp_is_default']==1
                        }
        end
      end
      mailboxes
    end
handle_incoming_message(options) click to toggle source
# File lib/mail2cb/email_watcher.rb, line 115
def handle_incoming_message(options)
  update_message_counts(options)
  @handler = Mail2cb::EmailHandler.new(options)
  @handler.sanitize!
  # @handler.clean_replies!
  @handler.queue!

  puts "Queued."
end
restart() click to toggle source
# File lib/mail2cb/email_watcher.rb, line 111
def restart
  @daemon.reload(:connections => configuration)
end
start() click to toggle source
# File lib/mail2cb/email_watcher.rb, line 41
def start
  Thread.new do
    @daemon.start do |message, type|
      if type == "status_update"
        update_status(message)
      else
        handle_incoming_message(message)
      end
    end
  end
end
update_message_counts(options) click to toggle source
# File lib/mail2cb/email_watcher.rb, line 125
def update_message_counts(options)
  begin
    options[:mailbox][:message_count] = options[:mailbox][:message_count] + 1
    options[:mailbox][:last_delivered_at] = DateTime.now

    if (ENV["FAYE_HOST"])
      Thread.new { EventMachine.run } unless EventMachine.reactor_running?
      Thread.pass until EventMachine.reactor_running?
      client = Faye::Client.new("#{ENV["FAYE_HOST"]}:#{ENV["FAYE_PORT"]}/faye")
      client.publish("/case_blocks/account/#{options[:mailbox][:account_id]}/imap_server_new_message/#{options[:mailbox][:id]}", {'message_count' => options[:mailbox][:message_count], 'last_delivered_at' => options[:mailbox][:last_delivered_at]})
      client.disconnect
    end
    mysql_client do |mysql|
      status_message = options[:status]
      mysql.query("UPDATE case_blocks_email_accounts SET imap_messages_processed='#{options[:mailbox][:message_count]}', imap_last_processed_at='#{options[:mailbox][:last_delivered_at]}' where id=#{options[:mailbox][:id]}")
    end
  rescue => e
    puts e.message
    puts e.backtrace.join("\n")
  end
end
update_status(options) click to toggle source
# File lib/mail2cb/email_watcher.rb, line 147
def update_status(options)
  begin
    puts "Status Update: #{options[:status]} for #{options[:mailbox][:username]}"
    if (ENV["FAYE_HOST"])
      Thread.new { EventMachine.run } unless EventMachine.reactor_running?
      Thread.pass until EventMachine.reactor_running?
      client = Faye::Client.new("#{ENV["FAYE_HOST"]}:#{ENV["FAYE_PORT"]}/faye")
      client.publish("/case_blocks/account/#{options[:mailbox][:account_id]}/imap_server_status_updated/#{options[:mailbox][:id]}", {'status' => options[:status].gsub("_", " ")})
      client.disconnect
    end
    mysql_client do |mysql|
      status_message = options[:status]
      mysql.query("UPDATE case_blocks_email_accounts SET imap_status='#{options[:status]}', imap_status_message='#{status_message}' where id=#{options[:mailbox][:id]}")
    end
  rescue => e
    puts e.message
    puts e.backtrace.join("\n")
  end
end

Private Instance Methods

mailbox_status(watcher) click to toggle source
# File lib/mail2cb/email_watcher.rb, line 184
def mailbox_status(watcher)
  if watcher.logging_in?
    :logging_in
  elsif watcher.logged_in?
    :connected
  else
    :disconnected
  end
end
mailbox_status_colour(watcher) click to toggle source
# File lib/mail2cb/email_watcher.rb, line 193
def mailbox_status_colour(watcher)
  if watcher.logging_in?
    "orange"
  elsif watcher.logged_in?
    "green"
  else
    "red"
  end
end
mailbox_status_message(watcher) click to toggle source
# File lib/mail2cb/email_watcher.rb, line 175
def mailbox_status_message(watcher)
  if watcher.logging_in?
    "Connecting and Logging into server"
  elsif watcher.logged_in?
    "Connected"
  else
    "Disconnected"
  end
end
mysql_client() { |client| ... } click to toggle source
# File lib/mail2cb/email_watcher.rb, line 169
def mysql_client(&block)
  client = Mysql2::Client.new(:host => ENV["MYSQL_HOST"], :port => ENV["MYSQL_PORT"], :username => ENV["MYSQL_USERNAME"], :password => ENV["MYSQL_PASSWORD"], :database => ENV["MYSQL_DATABASE"])
  yield client
  client.close
end