Class: MailDaemon::ImapWatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/mail_daemon/imap_watcher.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ ImapWatcher

Returns a new instance of ImapWatcher.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/mail_daemon/imap_watcher.rb', line 5

def initialize(options)
  @options = options
  @watchers = []

  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"]

  ENV["MYSQL_PASSWORD"] = "" unless ENV["MYSQL_PASSWORD"]
  ENV["MYSQL_PORT"] = "3306"

  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
  }

  restart
end

Instance Method Details

#restartObject



62
63
64
65
66
# File 'lib/mail_daemon/imap_watcher.rb', line 62

def restart
  stop
  setup_watchers
  start
end

#running?Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/mail_daemon/imap_watcher.rb', line 68

def running?
  !!@watchers.detect{|watcher| watcher.running? }
end

#setup_watchersObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/mail_daemon/imap_watcher.rb', line 34

def setup_watchers
  # load uptodate config

  watchers = []
  mysql_client do |mysql|
    statement = mysql.prepare("SELECT * FROM case_blocks_email_accounts where imap_enabled=1")
    result = statement.execute()
    result.each do |row|
      ssl = row["imap_ssl"]==1 ? {:verify_mode => "none"} : false
      decrypted_password = Encryption.new.decrypt(row["imap_encrypted_password"])
      watchers << Imap::Connection.new({:email => row["imap_username"], :host => row["imap_host"], :port => row["imap_port"], :password => decrypted_password, :ssl => ssl, :start_tls => row["imap_start_tls"]==1, :name => row["imap_folder_name"], :search_command => row["imap_search_command"], :message_count => row["imap_messages_processed"], :last_delivered_at => row["imap_last_delivered_at"], :delivery_method=>"sidekiq", :delivery_options=>{:redis_url => ENV["REDIS_URL"], :queue => "email_handler", :worker=>"EmailHandlerWorker"}})
    end
  end

end

#startObject



50
51
52
53
54
55
56
# File 'lib/mail_daemon/imap_watcher.rb', line 50

def start
  watchers.each do |watcher|
    watcher.watch do |message|
      ap message
    end
  end
end

#stopObject



58
59
60
# File 'lib/mail_daemon/imap_watcher.rb', line 58

def stop
  watchers.map{|watcher| watcher.stop! }
end