Method: NaviClient::Local#idle_loop

Defined in:
lib/local/navi_local_client.rb

#idle_loop(imap, search_condition, folder, server, username, password, callback = nil, navi_control = nil) ⇒ Object

idle_loop

check for any further mail with “real-time” responsiveness. retrieve any mail from a folder, following specified search condition for any mail retrieved call a specified block



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/local/navi_local_client.rb', line 141

def idle_loop(imap, search_condition, folder, server, username, password, callback = nil, navi_control = nil)

  @logger.info "\nwaiting new mails (IDLE loop)..."

  loop do
    begin
      imap.select folder
      imap.idle do |resp|

        # You'll get all the things from the server. For new emails (EXISTS)
        if resp.kind_of?(Net::IMAP::UntaggedResponse) and resp.name == "EXISTS"

          # @logger.debug resp.inspect if @debug
          # Got something. Send DONE. This breaks you out of the blocking call
          @logger.debug "New mail received" if @debug
          imap.idle_done
        end
      end

      # We're out, which means there are some emails ready for us.
      # Go do a search for UNSEEN and fetch them.
      filenames = []
      stamp = (Time.now.to_f * 1000).to_s
      retrieve_emails(imap, search_condition, folder) { |mail, i, isLast, id|
        callback.call(mail, i, id, false) unless callback.nil?
        filenames << process_email(mail, id, stamp)
        callback.call(mail, i, id, true) unless callback.nil?
      }

      @logger.info "Sending Request for #{filenames.size} emails to Navi AI."
      navi_control.call(true) unless navi_control.nil?
      stamp = (Time.now.to_f * 1000).to_s
      self.send_request(filenames, stamp, is_last: true)

      # HTTPService::NaviAI.generate_csv("#{@gen_csv_url}?email=#{username}", @token)

      @logger.debug "Process Completed." if @debug
      navi_control.call(false) unless navi_control.nil?

    rescue SignalException => e
      # http://stackoverflow.com/questions/2089421/capturing-ctrl-c-in-ruby
      @logger.info "Signal received at #{time_now}: #{e.class}. #{e.message}"
      shutdown imap

    rescue Net::IMAP::Error => e
      @logger.error "Net::IMAP::Error at #{time_now}: #{e.class}. #{e.message}"
      imap = imap_connection(server, username, password) #if e.message == 'connection closed'
      @logger.info "reconnected to server: #{server}"

    rescue Exception => e
      @logger.error "Something went wrong at #{time_now}: #{e.class}. #{e.message}"

      imap = imap_connection(server, username, password)
      @logger.info "reconnected to server: #{server}"
    end
  end
end