Class: InsightsAPI::Login

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_token: nil, url: nil, **keyword_args) ⇒ Login

Returns a new instance of Login.



6
7
8
9
10
# File 'lib/insights_api/login.rb', line 6

def initialize(api_token: nil, url: nil, **keyword_args)
  @api_token = api_token
  @url = url
  @status = "Active"
end

Instance Attribute Details

#api_tokenObject

Returns the value of attribute api_token.



4
5
6
# File 'lib/insights_api/login.rb', line 4

def api_token
  @api_token
end

#urlObject

Returns the value of attribute url.



4
5
6
# File 'lib/insights_api/login.rb', line 4

def url
  @url
end

Instance Method Details

#data_export_insights(objecttype, segmentuuid, startDate, endDate, tries: 30) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/insights_api/login.rb', line 33

def data_export_insights(objecttype, segmentuuid, startDate, endDate, tries: 30)
  status = insights_fetch_all(objecttype, segmentuuid, startDate, endDate)
  if status['uuid'] == nil
    return "Failed: #{status["response"]}"
  else
    fileid = status['uuid']
  end
  for retries in 1..tries
    status = insight_getstatus(fileid)
    if status['status']== "COMPLETE"
      signedUrl = status['signedUrl']
      return status
    elsif status['status'] == "FAILED" || status['status'] == "ERROR"
      return status
    else
      sleep(60)
      retries+=1
    end
    if retries > tries - 1
      return "Timeout"
    end
  end
  return signedUrl
end

#data_export_insights_file(objecttype, segmentuuid, startDate, endDate, tries: 30) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/insights_api/login.rb', line 23

def data_export_insights_file(objecttype, segmentuuid, startDate, endDate, tries: 30)
  status = data_export_insights(objecttype, segmentuuid, startDate, endDate, tries: tries)
  if status['status']== "COMPLETE"
    signedUrl = status['signedUrl']
    return get_file(file_name: "insights-#{startDate}-#{endDate}.csv", url: signedUrl, headers: {}, count: 3, file_type: "zip")
  else
    return status
  end
end

#dateFormat(date: nil) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/insights_api/login.rb', line 91

def dateFormat(date: nil)
  date ||= DateTime.now
  if date.is_a? String
    if date.include? "T"
      return (date.to_datetime).to_s
    else
      return (date.to_date).to_s + "T#{DateTime.now.to_s(:time)}:00Z"
    end
  elsif date.instance_of?(DateTime)
    return date.to_s
  elsif date.instance_of?(Date)
    return (date.to_date).to_s + "T#{DateTime.now.to_s(:time)}:00Z"
  else
    raise "Please pass in a in format of 'YYYY-MM-DD', 'YYYY-MM-DDT00:00:00+00:00' ruby Date, or ruby DateTime"
  end
end

#describe(type: "ACCOUNT", object: "attributes") ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/insights_api/login.rb', line 138

def describe(type: "ACCOUNT", object: "attributes")
  url = "https://#{@url}/export/#{object}/#{type}"
  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  begin
    request = Net::HTTP::Get.new(uri.request_uri)
    request.basic_auth(@api_token, "")
    return http.request(request)
  rescue Exception => e
    Rails.logger.debug "[ZuoraGem]: While describing Zoura Insights objects: #{e}"
    return "Failed"
  end
end

#get_file(file_name: nil, url: nil, basic: {:username => nil, :password => nil}, headers: {}, count: 3, file_type: "zip") ⇒ Object



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
198
199
200
# File 'lib/insights_api/login.rb', line 154

def get_file(file_name: nil, url: nil,  basic: {:username => nil, :password => nil}, headers: {}, count: 3, file_type: "zip")
  tries ||= 2
  temp_file = nil
  uri = URI(url)
  Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    request = Net::HTTP::Get.new(uri)
    headers.each do |k,v|
      request["#{k}"] = v
    end
    request.basic_auth(basic[:username], basic[:password]) if (!basic[:username].blank? && !basic[:password].blank?)
    http.request request do |response|
      case response
      when Net::HTTPNotFound
        Rails.logger.fatal("[ZuoraGem]: 404 - Not Found")
        raise response

      when Net::HTTPUnauthorized
        raise ZuoraAPI::Exceptions::ZuoraAPISessionError.new(zuora_client.current_error) if count <= 0
        Rails.logger.fatal("[ZuoraGem]: Retry")
        zuora_client.new_session
        return get_file(:url => url, :count => count - 1, :headers => headers)

      when Net::HTTPClientError
        Rails.logger.debug("[ZuoraGem]: #{response}")
        raise response

      when Net::HTTPOK
        Tempfile.open([file_name.rpartition('.').first, ".#{file_name.rpartition('.').last}"], "#{Rails.root}/tmp") do |tmp_file|
          temp_file ||= tmp_file
          tmp_file.binmode if (response.to_hash["content-type"].include?("application/zip") || response.to_hash["content-type"] == "application/zip")
          response.read_body do |chunk|
            tmp_file.write chunk.force_encoding("UTF-8")
          end
        end
      end
    end
  end

  rescue => ex
    raise ex if tries.zero?

    tries -= 1
    sleep 3
    retry
  else
    return temp_file
end

#gzip_file(filePath) ⇒ Object



202
203
204
205
206
207
208
209
210
211
# File 'lib/insights_api/login.rb', line 202

def gzip_file(filePath)
  require "zip"
  Zlib::GzipWriter.open(filePath + ".gz") do |gzip|
     open(filePath, "rb") do |f|
        f.each_chunk() {|chunk| gzip.write chunk }
      end
    gzip.close
  end
  return filePath+ ".gz"
end

#insight_getstatus(uuid) ⇒ Object



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

def insight_getstatus(uuid)
  response = HTTParty.get(
          "https://#{@url}/export/status/#{uuid}",
          :basic_auth => { :username => @api_token })
  if response.code == 200
    parsed = JSON.parse(response.body)
    return parsed
  #error handing here
  end
end

#insights_fetch_all(objecttype, segmentuuid, startDate, endDate) ⇒ Object



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

def insights_fetch_all(objecttype, segmentuuid, startDate, endDate)
  if segmentuuid.is_a? Array
    segmentsForAPI = segmentuuid.join('","')
  elsif segmentuuid.is_a? String
    segmentsForAPI = segmentuuid
  elsif segmentuuid.is_a? Integer
    segmentsForAPI = segmentuuid.to_s
  else
    raise "Error fetching Insights data: Segmentuuid must be either an array of uuids or an single uuid in string or interger format."
  end

  response = HTTParty.post(
          "https://#{@url}/export/type/#{objecttype}",
          :basic_auth => { :username => @api_token },
          :headers => {'Content-Type'=> "Application/json"},
          :body =>
          '
          {
            "endDate": "' + (dateFormat(date: endDate)).to_s + '",
            "startDate":"' + (dateFormat(date: startDate)).to_s + '",
            "segments": [
              "'+segmentsForAPI+'"
            ]
          }
          ')
  if response.code == 200
    parsed = JSON.parse(response.body)
    return parsed
  else
    return {"uuid"=> nil, "status"=>"Error", "signedUrl"=>"signedUrl", "response" => response.body}
  end
end

#upload_into_insights(dataSourceName, recordType, batchDate, filePath) ⇒ Object



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
# File 'lib/insights_api/login.rb', line 108

def upload_into_insights(dataSourceName, recordType, batchDate, filePath)
  begin
    temp_date = dateFormat(date: batchDate)
    response = HTTParty.post(
      "https://#{@url}/files/upload",
      :basic_auth => { :username => @api_token }, :body => {
      :dataSource => dataSourceName, :recordType => recordType,
      :batchDate => temp_date})
    parsed = JSON.parse(response.body)
    signedUrl = parsed['signedUrl']
    if !File.extname(filePath) == ".gz"
      zipPath = gzip_file(filePath)
    else
      zipPath = filePath
    end

    gzippedFile = File.open(zipPath)
    post = HTTParty.put(signedUrl,
      :body => gzippedFile.read)
    if post.code == 200
      return {"status"=>"COMPLETE", "signedUrl"=>"#{signedUrl}", "response" => post.code, "batchDate" => "#{temp_date}"}
    else
      return {"status"=>"Error", "signedUrl"=>"#{signedUrl}", "response" => post.code, "message"=> "#{post.message}", "batchDate" => "#{temp_date}"}
    end
  rescue Exception => e
      Rails.logger.debug "[ZuoraGem]: While uploading to insights Error: #{e}"
    raise e
  end
end