-
Notifications
You must be signed in to change notification settings - Fork 1
/
google_analytics_feeds.rb
312 lines (254 loc) · 6.37 KB
/
google_analytics_feeds.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
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
require 'ox'
require 'addressable/uri'
require 'stringio'
require 'faraday'
module GoogleAnalyticsFeeds
class AuthenticationError < StandardError ; end
class HttpError < StandardError ; end
class Session
CLIENT_LOGIN_URI = "https://www.google.com/accounts/ClientLogin"
def initialize(connection=Faraday.default_connection)
@connection = connection
end
def login(username, password)
return @token if @token
response = @connection.post(CLIENT_LOGIN_URI,
'Email' => username,
'Passwd' => password,
'accountType' => 'HOSTED_OR_GOOGLE',
'service' => 'analytics',
'source' => 'ruby-google-analytics-feeds')
if response.success?
@token = response.body.match(/^Auth=(.*)$/)[1]
else
raise AuthenticationError
end
end
def fetch_report(report, handler=nil, &block)
handler = block if handler.nil?
response = report.retrieve(@token, @connection)
if response.success?
DataFeedParser.new(handler).parse_rows(StringIO.new(response.body))
else
raise HttpError.new
end
end
end
# A SAX-style row handler.
#
# Extend this class and override the methods you care about to
# handle data feed row data.
class RowHandler
def start_rows
end
def row(row)
end
def end_rows
end
end
module Naming
# Returns a ruby-friendly symbol from a google analytics name.
#
# For example:
#
# name_to_symbol("ga:visitorType") # => :visitor_type
def name_to_symbol(name)
name.sub(/^ga\:/,'').gsub(/(.)([A-Z])/,'\1_\2').downcase.to_sym
end
# Returns a google analytics name from a ruby symbol.
#
# For example:
#
# symbol_to_name(:visitor_type) # => "ga:visitorType"
def symbol_to_name(sym)
parts = sym.to_s.split("_").map(&:capitalize)
parts[0].downcase!
"ga:" + parts.join('')
end
end
# Parses rows from the GA feed via SAX. Clients shouldn't have to
# use this - use a RowHandler instead.
class RowParser < ::Ox::Sax
include Naming
def initialize(handler)
@handler = handler
end
def start_element(element)
case element
when :entry
@row = {}
when :"dxp:dimension", :"dxp:metric"
@property = {}
end
end
def attr(name, value)
if @property
@property[name] = value
end
end
def end_element(element)
case element
when :entry
handle_complete_row
@row = nil
when :"dxp:dimension", :"dxp:metric"
handle_complete_property
@property = nil
end
end
private
def handle_complete_row
@handler.row(@row)
end
def handle_complete_property
if @row
value = @property[:value]
if @property[:type] == "integer"
value = Integer(value)
end
name = name_to_symbol(@property[:name])
@row[name] = value
end
end
end
class FilterBuilder
include Naming
def initialize
@filters = []
end
def build(&block)
instance_eval(&block)
@filters.join(';')
end
# TODO: remove duplication
def eql(name, value)
filter(name, value, '==')
end
def not_eql(name, value)
filter(name, value, '!=')
end
def contains(n, v)
filter(n, v, '=@')
end
def not_contains(n, v)
filter(n, v, '!@')
end
def gt(n, v)
filter(n, v, '>')
end
def gte(n, v)
filter(n, v, '>=')
end
def lt(n, v)
filter(n, v, '<')
end
def lte(n, v)
filter(n, v, '<=')
end
def match(n, v)
filter(n, v, '=~')
end
def not_match(n, v)
filter(n, v, '!~')
end
private
def filter(name, value, operation)
@filters << [symbol_to_name(name), operation, value.to_s].join('')
end
end
class DataFeed
include Naming
BASE_URI = "https://www.googleapis.com/analytics/v2.4/data"
def initialize
@params = {}
end
def profile(id)
clone_and_set {|params|
params['ids'] = symbol_to_name(id)
}
end
def metrics(*vals)
clone_and_set {|params|
params['metrics'] = vals.map {|v| symbol_to_name(v) }.join(',')
}
end
def dimensions(*vals)
clone_and_set {|params|
params['dimensions'] = vals.map {|v| symbol_to_name(v) }.join(',')
}
end
def dates(start_date, end_date)
clone_and_set {|params|
params['start-date'] = start_date.strftime("%Y-%m-%d")
params['end-date'] = end_date.strftime("%Y-%m-%d")
}
end
def start_index(i)
clone_and_set {|params|
params['start-index'] = i.to_s
}
end
def max_results(i)
clone_and_set {|params|
params['max-results'] = i.to_s
}
end
def filters(&block)
builder =
clone_and_set {|params|
params['filters'] = FilterBuilder.new.build(&block)
}
end
# Sorts the result set by a column.
#
# Direction can be :asc or :desc.
def sort(column, direction)
clone_and_set {|params|
c = symbol_to_name(column)
params['sort'] = (direction == :desc ? "-#{c}" : c)
}
end
def uri
uri = Addressable::URI.parse(BASE_URI)
uri.query_values = @params
uri.to_s.gsub("%40", "~")
end
alias :to_s :uri
def retrieve(session_token, connection)
connection.get(uri) do |request|
request.headers['Authorization'] =
"GoogleLogin auth=#{session_token}"
end
end
def clone
obj = super
obj.instance_variable_set(:@params, @params.clone)
obj
end
protected
attr_reader :params
private
def clone_and_set
obj = clone
yield obj.params
obj
end
end
class DataFeedParser
def initialize(handler)
if handler.kind_of?(Proc)
@handler = Class.new(RowHandler, &handler).new
elsif handler.kind_of?(Class)
@handler = handler.new
else
@handler = handler
end
end
# Parse rows from an IO object.
def parse_rows(io)
@handler.start_rows
Ox.sax_parse(RowParser.new(@handler), io)
@handler.end_rows
end
end
end