Skip to content

Commit d37c2ba

Browse files
authored
Merge pull request #1 from ant-in-giant/v004
V004
2 parents c9fb357 + 8e9fc38 commit d37c2ba

File tree

4 files changed

+99
-43
lines changed

4 files changed

+99
-43
lines changed

CHANGELOG.md

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Change Log
2+
3+
## v0.0.4
4+
2020.10.31
5+
- 複数サイトを1つの Heroku アプリでサービスメトリック採取できるように対応
6+
7+
8+
## v0.0.3
9+
2020.07.27
10+
- 複数サイトのPVを同一グラフに表示する調整
11+
- refs Pubs/Mackerel Ambassador (sogaoh) blogs/
12+
- [GoogleAnalyticsで取得したアクティブユーザー数を定期的にMackerelサービスメトリックに投稿する (1)](https://esa-pages.io/p/sharing/6641/posts/976/ebc3295116a84b02c966.html)
13+
- [GoogleAnalyticsで取得したアクティブユーザー数を定期的にMackerelサービスメトリックに投稿する (2)](https://esa-pages.io/p/sharing/6641/posts/979/7ba0cdf6e32419970274.html)
14+
15+
## v0.0.2
16+
2020.07.27
17+
- 単一サイト毎のサービスメトリック送信
18+
19+
## v0.0.1
20+
2016.09.18
21+
- [a-know さんのオリジナル版公開](https://github.com/a-know/currentvisitor2mackerel)
22+
- refs [Google Analyticsの「現在の訪問人数」を Mackerel に投稿する heroku app を作ったよ - えいのうにっき](http://blog.a-know.me/entry/2016/09/19/162242)
23+

README.md

+5-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ Post current visitor number of Google Analytics to [mackerel.io](https://mackere
44
## heroku app deploy button
55
[![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy)
66

7-
## How to use
7+
8+
## References
89
In Japanese.
910

10-
[Google Analyticsの「現在の訪問人数」を Mackerel に投稿する heroku app を作ったよ](http://blog.a-know.me/entry/2016/09/19/162242)
11+
[GoogleAnalyticsで取得したアクティブユーザー数を定期的にMackerelサービスメトリックに投稿する の関連コード](https://github.com/sogaoh/mackerel-practice/tree/master/google-01)
12+
[Google Analyticsの「現在の訪問人数」を Mackerel に投稿する heroku app を作ったよ - えいのうにっき](http://blog.a-know.me/entry/2016/09/19/162242)
13+

app.json

+3-7
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,13 @@
66
"description": "Google Cloud Platform Service Account Email Address.",
77
"value": "[email protected]"
88
},
9-
"PROFILE_ID": {
10-
"description": "Google Analytics Profile ID.",
11-
"value": "12345678"
12-
},
139
"GOOGLE_API_KEY": {
1410
"description": "Google Cloud Platform Service Account's RSA private key.",
1511
"value": "-----BEGIN RSA PRIVATE KEY-----\nxxxx\n-----END RSA PRIVATE KEY-----"
1612
},
17-
"WEBSITE_NAME": {
18-
"description": "Website name Google Analytics embedded.",
19-
"value": "hoge-blog"
13+
"SITE_AND_VIEW_ID_JSON": {
14+
"description": "Website names (Google Analytics embedded) & Google Analytics View IDs.",
15+
"value": "[{\"hoge-blog\":12345678},{\"fuga-blog\":23456789}]"
2016
},
2117
"MACKEREL_API_KEY": {
2218
"description": "Your organization's api-key of mackerel.io.",

app.rb

+68-34
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
require 'net/http'
33
require 'uri'
44
require 'google/api_client'
5+
require 'json'
56

67

78
get '/' do
@@ -10,53 +11,86 @@
1011
get '/post' do
1112
# Update these to match your own apps credentials
1213
service_account_email = ENV['SERVICE_ACCOUNT_EMAIL'] # Email of service account
13-
profile_id = ENV['PROFILE_ID'] # Analytics profile ID.
1414

1515
# Get the Google API client
1616
client = Google::APIClient.new(
17-
:application_name => 'current visitor of Google Analytics post to mackerel.io',
18-
:application_version => '0.0.3'
17+
:application_name => 'current visitor of Google Analytics post to mackerel.io',
18+
:application_version => '0.0.4'
1919
)
2020

2121
key = OpenSSL::PKey::RSA.new(ENV['GOOGLE_API_KEY'].gsub("\\n", "\n"))
2222
client.authorization = Signet::OAuth2::Client.new(
23-
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
24-
:audience => 'https://accounts.google.com/o/oauth2/token',
25-
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
26-
:issuer => service_account_email,
27-
:signing_key => key,
23+
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
24+
:audience => 'https://accounts.google.com/o/oauth2/token',
25+
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
26+
:issuer => service_account_email,
27+
:signing_key => key,
2828
)
2929

3030
# Request a token for our service account
3131
client.authorization.fetch_access_token!
3232

3333
# Get the analytics API
34-
analytics = client.discovered_api('analytics','v3')
35-
36-
# Execute the query, get the value like `[["1"]]`
37-
response = client.execute(:api_method => analytics.data.realtime.get, :parameters => {
38-
'ids' => "ga:" + profile_id,
39-
'metrics' => "ga:activeVisitors",
40-
}).data.rows
41-
42-
number = response.empty? ? 0 : response.first.first.to_i
43-
payload = [ {
44-
name: "current_visitors.#{ENV['WEBSITE_NAME']}",
45-
time: Time.now.to_i,
46-
value: number,
47-
} ].to_json
48-
49-
uri = URI.parse("https://mackerel.io/api/v0/services/#{ENV['MACKEREL_SERVICE_NAME']}/tsdb")
50-
Net::HTTP.new(uri.host, uri.port).tap do |https|
51-
https.use_ssl = true
52-
req = Net::HTTP::Post.new(uri.request_uri).tap do |q|
53-
q['Content-Type'] = 'application/json'
54-
q['X-Api-Key'] = ENV['MACKEREL_API_KEY']
55-
q.body = payload
34+
analytics = client.discovered_api('analytics', 'v3')
35+
36+
# Get visitors of plural sites
37+
site_and_view_id_json = JSON.parse(ENV['SITE_AND_VIEW_ID_JSON'])
38+
39+
responses = {}
40+
result_status = 0
41+
site_and_view_id_json.each do |site_and_view_id|
42+
site_and_view_id.each do |site, view_id|
43+
#p "site=#{site}、view_id=#{view_id}"
44+
45+
# Execute the query, get the value like `[["1"]]`
46+
response = client.execute(:api_method => analytics.data.realtime.get, :parameters => {
47+
'ids' => "ga:" + "#{view_id}", # Analytics view ID.
48+
'metrics' => "ga:activeVisitors",
49+
}).data.rows
50+
51+
number = response.empty? ? 0 : response.first.first.to_i
52+
payload = [{
53+
name: "current_visitors.#{site}",
54+
time: Time.now.to_i,
55+
value: number,
56+
}].to_json
57+
58+
uri = URI.parse("https://mackerel.io/api/v0/services/#{ENV['MACKEREL_SERVICE_NAME']}/tsdb")
59+
Net::HTTP.new(uri.host, uri.port).tap do |https|
60+
https.use_ssl = true
61+
req = Net::HTTP::Post.new(uri.request_uri).tap do |q|
62+
q['Content-Type'] = 'application/json'
63+
q['X-Api-Key'] = ENV['MACKEREL_API_KEY']
64+
q.body = payload
65+
end
66+
res = https.request(req)
67+
68+
responses.store("#{site}", :result => {:status => res.code, :body => "#{res.body}"})
69+
result_status = [result_status, res.code.to_i].max
70+
end
5671
end
57-
res = https.request(req)
58-
status res.code
59-
headers 'Content-Type' => 'application/json'
60-
body "#{res.body}"
6172
end
73+
74+
headers 'Content-Type' => 'application/json'
75+
status result_status
76+
resp = {
77+
body: responses,
78+
}
79+
resp.to_json
80+
end
81+
82+
get '/sites' do
83+
site_and_view_id_json = JSON.parse(ENV['SITE_AND_VIEW_ID_JSON'])
84+
85+
site_and_view_id_json.each do |site_and_view_id|
86+
site_and_view_id.each do |site,view_id|
87+
p "site=#{site}, viewId=#{view_id}"
88+
end
89+
end
90+
91+
content_type :json
92+
response = {
93+
body: site_and_view_id_json,
94+
}
95+
response.to_json
6296
end

0 commit comments

Comments
 (0)