-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.rb
74 lines (60 loc) · 1.55 KB
/
app.rb
1
2
3
4
5
6
7
8
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
65
66
67
68
69
70
71
72
73
74
require 'cuba'
require 'logger'
require 'mote'
require 'http'
require 'securerandom'
Log = Logger.new(
File.exist?('app.log') ? 'app.log' : STDOUT
)
BeaconURL = "http://www.google-analytics.com/collect"
Cid = 'cid'
Cuba.define do
def log ua, ip, cid, params
response = HTTP.headers(
'User-Agent' => ua,
).post(BeaconURL, form: params)
Log.info "GA collector status: #{response.code}, cid: #{cid}, ip: #{ip}, body: #{response.body}"
end
def logHit ua, ip, cid, account, page
# https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#general
payload = {
'v' => '1',
't' => 'pageview',
'tid' => account,
'cid' => cid,
'dp' => page,
'uip' => ip,
}
log(ua, ip, cid, payload.merge(req.params))
end
def generateUUID
SecureRandom.uuid
end
def get_or_set_cid account
@cid = req.cookies[Cid]
if @cid.nil? || @cid.empty?
@cid = generateUUID
res.set_cookie(Cid, value: @cid, path: "/#{account}")
end
@cid
end
on ':account/(.+)' do |account, page|
cid = get_or_set_cid(account)
logHit(req.user_agent, req.ip, cid, account, page)
res['Cache-Control'] = 'no-cache'
res['CID'] = cid
res.status = 204
end
on ':account' do |account|
vars = {
account: account,
referer: req.referer,
}
content = IO.read('./page.html')
template = Mote.parse(content, self, vars.keys)
res.write template.call(vars)
end
on root do
res.redirect 'https://github.com/issueapp/ga-beacon'
end
end