Class: MailDaemon::Handler

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

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Handler

Returns a new instance of Handler.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/mail_daemon.rb', line 19

def initialize(options)
  setup_options(options)
  default_option :connections, []
  default_option :debug, false

  puts "Setting up Signal Traps" if @options[:debug]
  Signal.trap("INT") {
    Thread.new {self.stop}.join
  }
  # Trap `Kill `
  Signal.trap("TERM") {
    Thread.new {self.stop}.join
  }
end

Instance Method Details

#reload(options) ⇒ Object



54
55
56
57
# File 'lib/mail_daemon.rb', line 54

def reload(options)
  reload_options(options)
  self.restart
end

#restartObject



34
35
36
37
38
39
40
41
# File 'lib/mail_daemon.rb', line 34

def restart
  puts "Restarting... " if @options[:debug]
  self.stop if self.running?
  Thread.new do
    puts "Starting in new thread " if @options[:debug]
    self.start(&@client_handler_block)
  end
end

#running?Boolean

Returns:

  • (Boolean)


43
44
45
46
# File 'lib/mail_daemon.rb', line 43

def running?
  return false unless @watchers
  @watchers.any?{|watcher| watcher.running?}
end

#start(&block) ⇒ Object



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
# File 'lib/mail_daemon.rb', line 59

def start(&block)
  @watchers = []

  @client_handler_block = block

  @options[:connections].each do |mailbox|
    mailbox[:ssl_options] = {:verify_mode => OpenSSL::SSL::VERIFY_NONE} if mailbox[:ssl]

    puts "Setting up watcher for #{mailbox[:username]}" if @options[:debug]
    @watchers << MailDaemon::Imap::Watcher.new(@options.merge(mailbox))
  end
  @threads = []
  @watchers.each do |watcher|
    @threads << Thread.new do
      begin
        watcher.start do |message|
          type = message.delete(:type)
          yield message, type
        end
      rescue => e
        puts "#{watcher}: #{e.message}" 
      end
    end
  end

  @threads.map{|t| t.join}

end

#stopObject

Signal catching



49
50
51
52
# File 'lib/mail_daemon.rb', line 49

def stop
  @watchers.map{|watcher| watcher.stop}
  @threads.map{|t| t.kill }
end