Class: Mail2cb::EmailWatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/mail2cb/email_watcher.rb

Instance Method Summary collapse

Constructor Details

#initializeEmailWatcher

Returns a new instance of EmailWatcher.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# 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

Instance Method Details

#configurationObject



53
54
55
56
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
88
89
90
91
92
# File 'lib/mail2cb/email_watcher.rb', line 53

def configuration
  mailboxes = []
  mysql_client do |mysql|
    sql="    SELECT case_blocks_email_accounts.id,\n      case_blocks_accounts.id as account_id,\n      case_blocks_accounts.nickname,\n      case_blocks_email_accounts.imap_username,\n      case_blocks_email_accounts.imap_encrypted_password,\n      case_blocks_email_accounts.imap_host,\n      case_blocks_email_accounts.imap_port,\n      case_blocks_email_accounts.imap_ssl,\n      case_blocks_email_accounts.imap_start_tls,\n      case_blocks_email_accounts.imap_folder_name,\n      case_blocks_email_accounts.imap_search_command,\n      case_blocks_email_accounts.imap_messages_processed,\n      case_blocks_email_accounts.imap_last_processed_at,\n      u.authentication_token\n    FROM case_blocks_email_accounts\n    JOIN case_blocks_accounts\n    ON case_blocks_email_accounts.account_id = case_blocks_accounts.id\n    JOIN case_blocks_users u\n    ON u.account_id = case_blocks_accounts.id\n    where imap_enabled=1\n    and u.is_bot=1\n    and u.is_account_admin=1\n"
    statement = mysql.prepare(sql)
    result = statement.execute()
    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"]}
    end
  end
  mailboxes
end

#handle_incoming_message(options) ⇒ Object



98
99
100
101
102
103
104
105
106
# File 'lib/mail2cb/email_watcher.rb', line 98

def handle_incoming_message(options)
  update_message_counts(options)
  @handler = Mail2cb::EmailHandler.new(options)
  @handler.sanitize!
  # @handler.clean_replies!
  @handler.queue!

  puts "Queued."
end

#restartObject



94
95
96
# File 'lib/mail2cb/email_watcher.rb', line 94

def restart
  @daemon.reload(:connections => configuration)
end

#startObject



41
42
43
44
45
46
47
48
49
50
51
# 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) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/mail2cb/email_watcher.rb', line 108

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]
      statement = mysql.prepare("UPDATE case_blocks_email_accounts SET imap_messages_processed='#{options[:mailbox][:message_count]}', imap_last_processed_at='#{options[:mailbox][:last_delivered_at]}' where id=?")
      statement.execute(options[:mailbox][:id])
    end
  rescue => e
    puts e.message
    puts e.backtrace.join("\n")
  end
end

#update_status(options) ⇒ Object



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/mail2cb/email_watcher.rb', line 131

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]
      statement = mysql.prepare("UPDATE case_blocks_email_accounts SET imap_status='#{options[:status]}', imap_status_message='#{status_message}' where id=?")
      statement.execute(options[:mailbox][:id])
    end
  rescue => e
    puts e.message
    puts e.backtrace.join("\n")
  end
end