Module: Client

Included in:
NaviClient::Cloud, NaviClient::Local
Defined in:
lib/client.rb

Instance Method Summary collapse

Instance Method Details

#configObject



214
215
216
# File 'lib/client.rb', line 214

def config
  YAML.load_file('/var/navi/config.yml')
end

#encrypt(data) ⇒ Object



190
191
192
# File 'lib/client.rb', line 190

def encrypt(data)
  Base64.encode64(data)
end

#idle_loop(imap, search_condition, folder, server, username, password) ⇒ 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



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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/client.rb', line 99

def idle_loop(imap, search_condition, folder, server, username, password)

  @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
          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 = []
      retrieve_emails(imap, search_condition, folder) { |mail| filenames << process_email(mail)}
      self.send_request(filenames)

      @logger.debug "Process Completed." if @debug

    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}"

      # timeout ? reopen connection
      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

#imap_connection(server, username, password) ⇒ Object

imap_connection

connect the app with imap server



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/client.rb', line 28

def imap_connection(server, username, password)
  # connect to IMAP server
  imap = Net::IMAP.new server, ssl: true, certs: nil, verify: false

  Net::IMAP.debug = @net_imap_debug

  # http://ruby-doc.org/stdlib-2.1.5/libdoc/net/imap/rdoc/Net/IMAP.html#method-i-capability
  capabilities = imap.capability

  @logger.debug("imap capabilities: #{capabilities.join(',')}") if @debug

  unless capabilities.include? "IDLE"
    @logger.info "'IDLE' IMAP capability not available in server: #{server}"
    imap.disconnect
    exit
  end

  # login
  imap. username, password

  # return IMAP connection handler
  imap
end

#loggerObject



2
3
4
# File 'lib/client.rb', line 2

def logger
  @logger
end

#loginObject

login

login to the navi-cloud and get the authentication token



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/client.rb', line 11

def 
  url = "#{@sso_web_url/oauth/token}"
  provider_url = url
  @token = HTTParty.post(provider_url,
                body: {
                  client_id: config["uid"], # get from sso_web application
                  client_secret: config["secret_key"],
                  grant_type: "client_credentials"
                }
               )['access_token']
end

#mkdir_if_not_exist(filepath) ⇒ Object



194
195
196
197
198
199
# File 'lib/client.rb', line 194

def mkdir_if_not_exist(filepath)
  dirname = File.dirname(filepath)
  unless File.directory?(dirname)
    FileUtils.mkdir_p(dirname)
  end
end

#process_email(mail) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/client.rb', line 157

def process_email(mail)
  meta = Hash.new
  custom_uid = (Time.now.to_f * 1000).to_s + "_" + mail.__id__.to_s

  meta["from"] = mail.from.first
  meta["to"] = mail.to.join(";") unless mail.to.nil?
  meta["cc"] = mail.cc.join(";") unless mail.cc.nil?
  meta["subject"] = mail.subject
  meta["date"] = mail.date.to_s

  if mail.multipart?
    for i in 0...mail.parts.length
      m = download(mail, custom_uid)
      meta.merge!(m) unless m.nil?
    end
  else
    m = download(mail, custom_uid)
    meta.merge!(m) unless m.nil?
  end

  save(meta, "meta/#{custom_uid}")
end

#retrieve_emails(imap, search_condition, folder, &process_email_block) ⇒ Object

retrieve_emails

retrieve any mail from a folder, followin specified serach condition for any mail retrieved call a specified block



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

def retrieve_emails(imap, search_condition, folder, &process_email_block)

  # select folder
  imap.select folder

  message_ids = imap.search(search_condition)

  if @debug
    if message_ids.empty?
      @logger.debug "\nno messages found.\n"
      return
    else
      @logger.debug "\nProcessing #{message_ids.count} mails.\n"
    end
  end
  message_ids.each_with_index do |message_id, i|
    # fetch all the email contents
    data = imap.fetch(message_id, "RFC822")
    data.each do |d|
      msg = d.attr['RFC822']
      # instantiate a Mail object to avoid further IMAP parameters nightmares
      mail = Mail.read_from_string msg

      # call the block with mail object as param
      process_email_block.call mail

      # mark as read
      if @mark_as_read
        imap.store(message_id, "+FLAGS", [:Seen])
      end
    end
  end
end

#save(data = {}, filename) ⇒ Object



180
181
182
183
184
185
186
187
188
# File 'lib/client.rb', line 180

def save(data={}, filename)
  download_path = config['download_path']
  filepath = download_path + filename + ".yml"

  mkdir_if_not_exist(filepath)

  File.write(filepath, data.to_yaml)
  return filepath
end

#send_request(in_filenames = []) ⇒ Object



146
147
148
149
150
151
152
153
154
155
# File 'lib/client.rb', line 146

def send_request(in_filenames = [])
  download_path = config['download_path']
  filename = download_path + "inputs/" + (Time.now.to_f * 1000).to_s

  File.open(filename, 'w') do |f|
    in_filenames.each { |element| f.puts(element) }
  end

  HttpService::NaviAI.start(filename, @client_type, @token)
end

#shutdown(imap) ⇒ Object



205
206
207
208
209
210
211
212
# File 'lib/client.rb', line 205

def shutdown(imap)
  imap.idle_done
  imap.logout unless imap.disconnected?
  imap.disconnect

  @logger.info "#{$0} has ended (crowd applauds)"
  exit 0
end

#time_nowObject



201
202
203
# File 'lib/client.rb', line 201

def time_now
  Time.now.utc.iso8601(3)
end