9
10
11
12
13
14
15
16
17
18
19
20
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
64
|
# File 'app/controllers/adminpanel/pages_controller.rb', line 9
def index
unless Adminpanel.analytics_profile_id.nil? || Adminpanel.analytics_key_filename.nil?
service_account_email = '266789642405-0nppij5ll43bbvhpsn986puulssdoc45@developer.gserviceaccount.com' key_file = "#{Rails.root}/#{Adminpanel.analytics_key_path}/#{Adminpanel.analytics_key_filename}" key_secret = 'notasecret' profileID = Adminpanel.analytics_profile_id
client = Google::APIClient.new(
:application_name => 'Adminpanel',
:application_version => '1.0.0')
analytics = nil
if File.exists? CACHED_API_FILE
File.open(CACHED_API_FILE) do |file|
analytics = Marshal.load(file)
end
else
analytics = client.discovered_api('analytics', API_VERSION)
File.open(CACHED_API_FILE, 'w') do |file|
Marshal.dump(analytics, file)
end
end
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
:issuer => service_account_email,
:signing_key => key
)
client.authorization.fetch_access_token!
startDate = DateTime.now.prev_month.strftime("%Y-%m-%d")
endDate = DateTime.now.strftime("%Y-%m-%d")
@visitCount = client.execute(:api_method => analytics.data.ga.get, :parameters => {
'ids' => "ga:" + profileID,
'start-date' => startDate,
'end-date' => endDate,
'dimensions' => "ga:day,ga:month",
'metrics' => "ga:visits",
'sort' => "ga:month,ga:day"
})
@visits = @visitCount.data.rows.collect do |r|
r[2]
end
@visitDates = @visitCount.data.rows.collect { |r| "#{r[0]}/#{r[1]}" }
end
end
|