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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# 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) ⇒ Object



115
116
117
118
119
120
121
122
123
# 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

#restartObject



111
112
113
# File 'lib/mail2cb/email_watcher.rb', line 111

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



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# 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) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# 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