forked from kevindavis/segment-relay
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplication.rb
More file actions
146 lines (126 loc) · 4.03 KB
/
application.rb
File metadata and controls
146 lines (126 loc) · 4.03 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
require 'rubygems'
require 'bundler'
require 'pg'
require 'rack'
require 'rack/contrib'
require 'json'
require 'httparty'
Bundler.require :default, (ENV['RACK_ENV'] || 'development').to_sym
# Basic Sinatra app that takes segment webhook posts and inserts them in a PG DB
class Application < Sinatra::Base
GA_ENDPOINT = 'http://www.google-analytics.com/collect'
configure :production, :development do
enable :logging
end
def initialize
unless ENV['DATABASE_URL']
puts "DATABASE_URL not specified - exiting"
exit
end
uri = URI.parse(ENV['DATABASE_URL'])
begin
@db = PG.connect(uri.hostname, uri.port, nil, nil, uri.path[1..-1], uri.user, uri.password)
rescue
puts 'Problem connecting to Postgres. Exiting.'
exit
end
super
end
post '/' do
logger.info params.inspect
if params[:type] == 'track'
begin
query_params = [
params[:event],
params[:timestamp],
params[:userId],
params[:properties].to_json
]
@db.exec("INSERT INTO events ( \
event_name, \
occurred_at, \
user_id, \
details \
) VALUES ($1, $2, $3, $4)",
query_params)
logger.info "Inserting an event into the database: #{query_params.inspect}"
rescue PG::Error => err
logger.error "Problem with (#{params[:event]}) @#{params[:timestamp]}"
logger.error err.message
end
if params[:event] == 'Completed Order'
post_to_ga(params)
end
end
end
def post_to_ga(event)
body = {
v: 1,
tid: ENV['GA_TRACKING_ID'],
t: 'event',
ec: 'All',
ea: 'Completed Order',
ev: event[:properties]['revenue'],
el: event[:properties]['product_skus'].first,
uid: event[:userId],
}
body.merge! ({ cid: event[:context]['GoogleAnalytics']['clientId'] }) if event[:context]['GoogleAnalytics']
if event[:context]['campaign']
utm_source = event[:context]['campaign']['source']
utm_medium = event[:context]['campaign']['medium']
body.merge! ({
cn: event[:context]['campaign']['name'],
cc: event[:context]['campaign']['content']
})
end
if event[:context]['referrer']
begin
referring_domain = URI.parse(event[:context]['referrer']['url'])
rescue URI::InvalidURIError => e
referring_domain = nil
end
body.merge! ({ dr: referring_domain.to_s })
end
source, medium = forge_source_medium(utm_source, utm_medium, referring_domain)
body.merge! ({
cs: source,
cm: medium
})
begin
response = HTTParty.post(GA_ENDPOINT, body: body)
if response.code != 200
logger.error "Problem notifying GA for #{body.inspect}"
else
logger.info "Inserted an event into GA: #{body.inspect}"
end
rescue Exception => e
logger.error "Problem notifying GA: #{e.message}"
end
end
def forge_source_medium(utm_source, utm_medium, referring_domain)
# working off of: https://support.google.com/analytics/answer/3297892?hl=en
# organic: <source> / organic
# referrer: <referring domain> / referral
# direct: nil / (none)
# UTM params take priority over the domain they came from
if utm_source
source = utm_source
elsif referring_domain && match = /bing|google/.match(referring_domain.hostname)
source = match[0]
elsif referring_domain
source = referring_domain.hostname
else
source = nil
end
if utm_medium
medium = utm_medium
elsif referring_domain && match = /bing|google/.match(referring_domain.hostname)
medium = 'organic'
elsif referring_domain
medium = 'referral'
else
medium = '(none)'
end
return source, medium
end
end