Class: Postman::Processor

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

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Processor

Returns a new instance of Processor.



7
8
9
10
11
# File 'lib/postman/processor.rb', line 7

def initialize(config)
  @working_dir = config['working_dir']
  @logger = Logger.new(config['log'])
  @logger.info('Processor starting')
end

Instance Method Details

#processObject



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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/postman/processor.rb', line 13

def process

  inbox_dir = "#{@working_dir}/inbox"
  archive_dir = "#{@working_dir}/archive"
  problem_dir = "#{@working_dir}/problem"

  FileUtils.mkdir_p("#{inbox_dir}")
  FileUtils.mkdir_p("#{archive_dir}")
  FileUtils.mkdir_p("#{problem_dir}")

  Dir.foreach(inbox_dir) do |entry|
  
    next if File::directory?("#{inbox_dir}/#{entry}")
  
    @logger.debug("[mail_processor] {#{entry}} processing")
  
    mail = File.open("#{inbox_dir}/#{entry}") do |f|
      f.read
    end
  
    begin
      # parse the raw email with tmail
      parsed =  TMail::Mail.parse(mail)
    
      @logger.debug
      @logger.debug "Subject: #{parsed.subject}"
      @logger.debug "From: #{parsed.from}"
      @logger.debug "To: #{parsed.to}"
  
    rescue Exception => e
      @logger.error("[mail_processor] {#{entry}} Error parsing email: #{e.message}")
      FileUtils.mv("#{inbox_dir}/#{entry}", "#{problem_dir}/#{entry}")
      next
    end
    
    FileUtils.mv("#{inbox_dir}/#{entry}", "#{archive_dir}/#{entry}")
    
    if parsed.has_attachments?
      @logger.debug "Has #{parsed.attachments.size} attachments"
 
      parsed.attachments.each_with_index do |attachment, i|
        @logger.debug "saving #{attachment.original_filename} [#{attachment.content_type}]"
        attachment_filename = "#{archive_dir}/#{entry}__#{attachment.original_filename}"
        File.open(attachment_filename, 'w') do |f|
          f.write attachment.read
        end
      end
    
    end
  
  end
end