Class: EmailFetchAndProcess

Inherits:
Object
  • Object
show all
Defined in:
lib/email-fetch-and-process.rb,
lib/email-fetch-and-process/version.rb

Overview

Wrap up the logic to iterate through a bunch of fetch and handle jobs. This is the simplest thing that can work code. It could be generalized a lot pretty easily.

Defined Under Namespace

Classes: Job

Constant Summary collapse

VERSION =
'0.1.3'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ EmailFetchAndProcess

Returns a new instance of EmailFetchAndProcess.



57
58
59
60
# File 'lib/email-fetch-and-process.rb', line 57

def initialize(args = {})
  @args = default_args.merge args
  @destination = '/tmp'
end

Instance Attribute Details

#destinationObject

Returns the value of attribute destination.



55
56
57
# File 'lib/email-fetch-and-process.rb', line 55

def destination
  @destination
end

Instance Method Details

#default_argsObject



62
63
64
65
66
67
68
69
70
71
# File 'lib/email-fetch-and-process.rb', line 62

def default_args
  {
    host: '127.0.0.1',
    port: 993,
    tls: true,
    id: nil,
    password: nil,
    mailbox: 'INBOX'
  }
end

#handle_parts(parts, job, msg_ids) ⇒ Object



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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/email-fetch-and-process.rb', line 80

def handle_parts(parts, job, msg_ids)
  parts.each do |part|
    if !part.parts.empty?
      handle_parts(part.parts, job, msg_ids)
    else
      begin
        name = if job.filename.to_s.empty?
                 part.header[:content_disposition].filename || part.filename rescue part.filename
               else
                 job.filename
               end
        name = Mail::Encodings.decode_encode(name, :decode) if name rescue name
      rescue StandardError => e
        puts e, e.backtrace.inspect
        next
      end
      next unless name

      @body_index += 1
      attachment = part
      final_destination = job.destination || @destination
      attachment_path = File.expand_path(File.join(final_destination, name))
      attachment_path = nil unless attachment_path =~ /^#{final_destination}/
      next unless final_destination != attachment_path

      if attachment && attachment_path
        file_path = File.join([final_destination, job.subdirectory, name].compact)
        atch = attachment.body.to_s
        FileUtils.mkdir_p File.dirname(file_path) unless FileTest.exist? File.dirname(file_path)
        File.open(file_path, 'wb+') do |fh|
          fh.write atch.respond_to?(:each) ? atch.join : atch
        end
        sha_new = `/usr/bin/shasum "#{file_path}"`.split(/\s+/).first
        sha_old = nil
        FileTest.exist?("#{file_path}.sha") &&
          File.open("#{file_path}.sha", 'r') { |fh| sha_old = fh.read.chomp }
        if sha_new != sha_old
          command_to_run = job.action.gsub(/FILEPATH/, Shellwords.escape(file_path)).
            gsub(/DESTINATION/, Shellwords.escape(final_destination))
          system(command_to_run) &&
            File.open("#{file_path}.sha", 'w+') { |fh| fh.write sha_new }
        end
      end
    end
  end
end

#imap_connectionObject



73
74
75
76
77
78
# File 'lib/email-fetch-and-process.rb', line 73

def imap_connection
  imap = Net::IMAP.new(@args[:host], port: @args[:port], ssl: { verify_mode: OpenSSL::SSL::VERIFY_NONE })
  imap.(@args[:id], @args[:password])
  imap.examine(@args[:mailbox])
  imap
end

#run(jobs = []) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/email-fetch-and-process.rb', line 127

def run(jobs = [])
  @imap = imap_connection

  jobs.each do |job|
    msg_ids = if job.multiple_fetch_terms?
                all_ids = []
                job.fetch.each { |j| all_ids += @imap.search(j) }
                all_ids
              else
                @imap.search(job.fetch)
              end
    next if msg_ids.nil? || msg_ids.empty?

    begin
      msgs = @imap.fetch(msg_ids, %w[ENVELOPE RFC822])
      msg = msgs.max_by { |m| Time.parse(m['attr']['ENVELOPE'].date) }.attr['RFC822']

      @body_index = 1
    rescue StandardError => err
      puts "Error: #{err}\n#{err.backtrace.join("\n")}"
      @imap = imap_connection
      next
    end
    body = Mail.read_from_string msg
    handle_parts(body.attachments, job, msg_ids) unless body.attachments.empty?
  end

  @imap.close
end