Skip to content

Instantly share code, notes, and snippets.

@kkosuge
Forked from soramugi/Gemfile
Last active December 6, 2015 02:17
Show Gist options
  • Save kkosuge/97a0ca38c84248c941c2 to your computer and use it in GitHub Desktop.
Save kkosuge/97a0ca38c84248c941c2 to your computer and use it in GitHub Desktop.
GoogleAnalyticsに登録してるサイト全ての昨日のPV数出すやつ
#!/usr/bin/env ruby
# -*- encoding: utf-8 -*-
# 参考
# http://qiita.com/kazuph/items/2cf81a84985e894e9682
# http://bekkou68.hatenablog.com/entry/2014/08/20/222032
#
# api試すページ
# https://developers.google.com/apis-explorer/#s/analytics/v3/
require 'pp'
require 'json'
require 'pry'
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
require 'google/api_client/auth/file_storage'
Encoding.default_external='utf-8'
class PrevPageView
CREDENTIAL_STORE_FILE = "#{$0}-oauth2.json"
def initialize
client
authorize!
end
def client
@client ||= Google::APIClient.new(:application_name => 'TestProject', :application_version => '0.0.1')
end
def authorize!
authfile = Google::APIClient::FileStorage.new(CREDENTIAL_STORE_FILE)
unless authfile.authorization.nil?
@client.authorization = authfile.authorization
else
# ここでDLしたJSONを読み込んでいるので同じディレクトリにclient_secrets.jsonを置いておくこと
client_secrets = Google::APIClient::ClientSecrets.load
flow = Google::APIClient::InstalledAppFlow.new(
:client_id => client_secrets.client_id,
:client_secret => client_secrets.client_secret,
:scope => ['https://www.googleapis.com/auth/analytics.readonly']
)
@client.authorization = flow.authorize
authfile.write_credentials(@client.authorization.dup) # 認証情報をファイルに保存
end
@client
end
def analytics
@analytics ||= client.discovered_api('analytics', 'v3')
end
def date
target_date.to_s
end
def target_date
Date.today.prev_day
end
def page_view(profile_id, date=Date.today)
result = client.execute(
:api_method => analytics.data.ga.get,
:parameters => {
'ids' => "ga:" + profile_id,
'start-date' => date.to_s,
'end-date' => date.to_s,
'metrics' => 'ga:pageviews',
}
)
body = JSON.parse(result.response.body)
return body['error']['message'] if body['error']
body['totalsForAllResults']['ga:pageviews'].to_i
end
def profiles_list
result = client.execute(
:api_method => analytics.management.profiles.list,
:parameters => {
'accountId' => "~all",
'webPropertyId' => "~all",
}
)
body = JSON.parse(result.response.body)
return body['error']['message'] if body['error']
data = body['items'].map do |item|
target_pv = page_view(item['id'], target_date)
prev_pv = page_view(item['id'], target_date.prev_day)
[target_pv, item['websiteUrl'], (target_pv - prev_pv)]
end
data.sort {|(k1, v1), (k2, v2)| k2 <=> k1 }
end
end
prev_page_view = PrevPageView.new
pp prev_page_view.date
pp prev_page_view.profiles_list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment