Class: Embulk::Input::GoogleAnalytics::Client
- Inherits:
-
Object
- Object
- Embulk::Input::GoogleAnalytics::Client
- Defined in:
- lib/embulk/input/google_analytics/client.rb
Instance Attribute Summary collapse
-
#task ⇒ Object
readonly
Returns the value of attribute task.
Instance Method Summary collapse
- #auth ⇒ Object
- #build_report_request(page_token = nil) ⇒ Object
- #each_report_row(&block) ⇒ Object
- #get_all_profiles ⇒ Object
- #get_columns_list ⇒ Object
- #get_custom_dimensions ⇒ Object
- #get_metadata_columns ⇒ Object
- #get_profile ⇒ Object
- #get_reports(page_token = nil) ⇒ Object
-
#initialize(task, is_preview = false) ⇒ Client
constructor
A new instance of Client.
- #preview? ⇒ Boolean
- #retryer ⇒ Object
- #swap_time_zone(&block) ⇒ Object
- #time_parse_with_profile_timezone(time_string) ⇒ Object
- #too_early_data?(time_str) ⇒ Boolean
- #view_id ⇒ Object
Constructor Details
#initialize(task, is_preview = false) ⇒ Client
Returns a new instance of Client.
16 17 18 19 |
# File 'lib/embulk/input/google_analytics/client.rb', line 16 def initialize(task, is_preview = false) @task = task @is_preview = is_preview end |
Instance Attribute Details
#task ⇒ Object (readonly)
Returns the value of attribute task.
14 15 16 |
# File 'lib/embulk/input/google_analytics/client.rb', line 14 def task @task end |
Instance Method Details
#auth ⇒ Object
173 174 175 176 177 178 179 180 181 182 |
# File 'lib/embulk/input/google_analytics/client.rb', line 173 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.) end |
#build_report_request(page_token = nil) ⇒ Object
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 |
# File 'lib/embulk/input/google_analytics/client.rb', line 146 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
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 64 65 66 67 68 |
# File 'lib/embulk/input/google_analytics/client.rb', line 25 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) format_row["view_id"] = view_id 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_profiles ⇒ Object
85 86 87 88 89 90 91 92 93 |
# File 'lib/embulk/input/google_analytics/client.rb', line 85 def get_all_profiles service = Google::Apis::AnalyticsV3::AnalyticsService.new service. = auth Embulk.logger.debug "Fetching profile from API" retryer.with_retry do service.list_profiles("~all", "~all") end end |
#get_columns_list ⇒ Object
124 125 126 |
# File 'lib/embulk/input/google_analytics/client.rb', line 124 def get_columns_list get_custom_dimensions + end |
#get_custom_dimensions ⇒ Object
137 138 139 140 141 142 143 144 |
# File 'lib/embulk/input/google_analytics/client.rb', line 137 def get_custom_dimensions # https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/customDimensions/list service = Google::Apis::AnalyticsV3::AnalyticsService.new service. = auth retryer.with_retry do service.list_custom_dimensions(get_profile[:account_id], get_profile[:web_property_id]).to_h[:items] end end |
#get_metadata_columns ⇒ Object
128 129 130 131 132 133 134 135 |
# File 'lib/embulk/input/google_analytics/client.rb', line 128 def # https://developers.google.com/analytics/devguides/reporting/metadata/v3/reference/metadata/columns/list service = Google::Apis::AnalyticsV3::AnalyticsService.new service. = auth retryer.with_retry do service.("ga").to_h[:items] end end |
#get_profile ⇒ Object
70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/embulk/input/google_analytics/client.rb', line 70 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
110 111 112 113 114 115 116 117 118 119 120 121 122 |
# File 'lib/embulk/input/google_analytics/client.rb', line 110 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. = 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
21 22 23 |
# File 'lib/embulk/input/google_analytics/client.rb', line 21 def preview? @is_preview end |
#retryer ⇒ Object
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 |
# File 'lib/embulk/input/google_analytics/client.rb', line 205 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
184 185 186 187 188 189 190 |
# File 'lib/embulk/input/google_analytics/client.rb', line 184 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
95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
# File 'lib/embulk/input/google_analytics/client.rb', line 95 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
192 193 194 195 196 197 198 199 200 201 202 203 |
# File 'lib/embulk/input/google_analytics/client.rb', line 192 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_id ⇒ Object
169 170 171 |
# File 'lib/embulk/input/google_analytics/client.rb', line 169 def view_id task["view_id"] end |