Class: Embulk::Input::GoogleAnalytics::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/embulk/input/google_analytics/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(task, is_preview = false) ⇒ Client

Returns a new instance of Client.



12
13
14
15
# File 'lib/embulk/input/google_analytics/client.rb', line 12

def initialize(task, is_preview = false)
  @task = task
  @is_preview = is_preview
end

Instance Attribute Details

#taskObject (readonly)

Returns the value of attribute task.



10
11
12
# File 'lib/embulk/input/google_analytics/client.rb', line 10

def task
  @task
end

Instance Method Details

#authObject



155
156
157
158
159
160
161
162
163
164
# File 'lib/embulk/input/google_analytics/client.rb', line 155

def auth
  retryer.with_retry do
    Google::Auth::ServiceAccountCredentials.make_creds(
      json_key_io: StringIO.new(task["json_key_content"]),
      scope: "https://www.googleapis.com/auth/analytics.readonly"
    )
  end
rescue Google::Apis::AuthorizationError => e
  raise ConfigError.new(e.message)
end

#build_report_request(page_token = nil) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/embulk/input/google_analytics/client.rb', line 128

def build_report_request(page_token = nil)
  query = {
    view_id: view_id,
    dimensions: [{name: task["time_series"]}] + task["dimensions"].map{|d| {name: d}},
    metrics: task["metrics"].map{|m| {expression: m}},
    include_empty_rows: true,
    page_size: preview? ? 10 : 10000,
  }

  if task["start_date"] || task["end_date"]
    query[:date_ranges] = [{
      start_date: task["start_date"],
      end_date: task["end_date"],
    }]
  end

  if page_token
    query[:page_token] = page_token
  end

  [query]
end

#each_report_row(&block) ⇒ Object



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
# File 'lib/embulk/input/google_analytics/client.rb', line 21

def each_report_row(&block)
  page_token = nil
  Embulk.logger.info "view_id:#{view_id} timezone has been set as '#{get_profile[:timezone]}'"

  loop do
    result = get_reports(page_token)
    report = result.to_h[:reports].first

    unless page_token
      # display for first request only
      Embulk.logger.info "Total: #{report[:data][:row_count]} rows. Fetched first response"
    end

    if !report[:data].has_key?(:rows)
      Embulk.logger.warn "Result doesn't contain rows."
      break
    end

    if report[:data][:rows].empty?
      Embulk.logger.warn "Result has 0 rows."
      break
    end

    dimensions = report[:column_header][:dimensions]
    metrics = report[:column_header][:metric_header][:metric_header_entries].map{|m| m[:name]}
    report[:data][:rows].each do |row|
      dim = dimensions.zip(row[:dimensions]).to_h
      met = metrics.zip(row[:metrics].first[:values]).to_h
      format_row = dim.merge(met)
      raw_time = format_row[task["time_series"]]
      next if too_early_data?(raw_time)
      format_row[task["time_series"]] = time_parse_with_profile_timezone(raw_time)
      block.call format_row
    end

    break if preview?

    unless page_token = report[:next_page_token]
      break
    end
    Embulk.logger.info "Fetching report with page_token: #{page_token}"
  end
end

#get_all_profilesObject



80
81
82
83
84
85
86
87
88
# File 'lib/embulk/input/google_analytics/client.rb', line 80

def get_all_profiles
  service = Google::Apis::AnalyticsV3::AnalyticsService.new
  service.authorization = auth

  Embulk.logger.debug "Fetching profile from API"
  retryer.with_retry do
    service.list_profiles("~all", "~all")
  end
end

#get_columns_listObject



119
120
121
122
123
124
125
126
# File 'lib/embulk/input/google_analytics/client.rb', line 119

def get_columns_list
  # https://developers.google.com/analytics/devguides/reporting/metadata/v3/reference/metadata/columns/list
  service = Google::Apis::AnalyticsV3::AnalyticsService.new
  service.authorization = auth
  retryer.with_retry do
    service.("ga").to_h[:items]
  end
end

#get_profileObject



65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/embulk/input/google_analytics/client.rb', line 65

def get_profile
  @profile ||=
    begin
      profile = get_all_profiles.to_h[:items].find do |prof|
        prof[:id] == view_id
      end

      unless profile
        raise Embulk::ConfigError.new("Can't find view_id:#{view_id} profile via Google Analytics API.")
      end

      profile
    end
end

#get_reports(page_token = nil) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/embulk/input/google_analytics/client.rb', line 105

def get_reports(page_token = nil)
  # https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet
  service = Google::Apis::AnalyticsreportingV4::AnalyticsReportingService.new
  service.authorization = auth

  request = Google::Apis::AnalyticsreportingV4::GetReportsRequest.new
  request.report_requests = build_report_request(page_token)

  Embulk.logger.info "Query to Core Report API: #{request.to_json}"
  retryer.with_retry do
    service.batch_get_reports request
  end
end

#preview?Boolean

Returns:

  • (Boolean)


17
18
19
# File 'lib/embulk/input/google_analytics/client.rb', line 17

def preview?
  @is_preview
end

#retryerObject



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/embulk/input/google_analytics/client.rb', line 187

def retryer
  PerfectRetry.new do |config|
    config.limit = task["retry_limit"]
    config.logger = Embulk.logger
    config.log_level = nil

    # https://developers.google.com/analytics/devguides/reporting/core/v4/errors
    # https://developers.google.com/analytics/devguides/reporting/core/v4/limits-quotas#additional_quota
    # https://github.com/google/google-api-ruby-client/blob/master/lib/google/apis/errors.rb
    # https://github.com/google/google-api-ruby-client/blob/0.9.11/lib/google/apis/core/http_command.rb#L33
    config.rescues = Google::Apis::Core::HttpCommand::RETRIABLE_ERRORS
    config.dont_rescues = [Embulk::DataError, Embulk::ConfigError]
    config.sleep = lambda{|n| task["retry_initial_wait_sec"]* (2 ** (n-1)) }
    config.raise_original_error = true
  end
end

#swap_time_zone(&block) ⇒ Object



166
167
168
169
170
171
172
# File 'lib/embulk/input/google_analytics/client.rb', line 166

def swap_time_zone(&block)
  orig_timezone = Time.zone
  Time.zone = get_profile[:timezone]
  yield
ensure
  Time.zone = orig_timezone
end

#time_parse_with_profile_timezone(time_string) ⇒ Object



90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/embulk/input/google_analytics/client.rb', line 90

def time_parse_with_profile_timezone(time_string)
  date_format =
    case task["time_series"]
    when "ga:dateHour"
      "%Y%m%d%H"
    when "ga:date"
      "%Y%m%d"
    end
  parts = Date._strptime(time_string, date_format)

  swap_time_zone do
    Time.zone.local(*parts.values_at(:year, :mon, :mday, :hour)).to_time
  end
end

#too_early_data?(time_str) ⇒ Boolean

Returns:

  • (Boolean)


174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/embulk/input/google_analytics/client.rb', line 174

def too_early_data?(time_str)
  # fetching 20160720 data on 2016-07-20, it is too early fetching
  swap_time_zone do
    now = Time.zone.now
    case task["time_series"]
    when "ga:dateHour"
      time_str.to_i >= now.strftime("%Y%m%d%H").to_i
    when "ga:date"
      time_str.to_i >= now.strftime("%Y%m%d").to_i
    end
  end
end

#view_idObject



151
152
153
# File 'lib/embulk/input/google_analytics/client.rb', line 151

def view_id
  task["view_id"]
end