-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
executable file
·511 lines (429 loc) · 16 KB
/
__init__.py
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
"""
Google Analytics Sous Chefs.
"""
from datetime import datetime, timedelta
import copy
import time
from collections import defaultdict, Counter
from operator import itemgetter
import googleanalytics as ga
import pytz
from newslynx.sc import SousChef
from newslynx import settings
from newslynx.lib import dates
from newslynx.lib import url
from newslynx.lib import stats
class SCGoogleAnalytics(SousChef):
timeout = 3600 * 6 # Six hours
def connect(self):
self.profiles = []
tokens = self.auths.get('google-analytics', None)
properties = tokens.pop('properties', [])
if not tokens:
raise Exception(
'You must authenticate with google analytics to use this sous chef.')
if not len(properties):
raise Exception(
'You must specify a list of google analytics properties to track. '
'Try re-authenticating.')
# authenticate with accounts
conn_kw = {
'refresh_token': tokens.get('refresh_token', None),
'client_id': settings.GOOGLE_ANALYTICS_CLIENT_ID,
'client_secret': settings.GOOGLE_ANALYTICS_CLIENT_SECRET
}
try:
accounts = ga.authenticate(**conn_kw)
except Exception as e:
raise Exception('Error connecting to google analytics: {}'
.format(e.message))
# search for configured profiles.
for account in accounts:
for prop in account.webproperties:
for p in properties:
if not p['property'] == prop.url:
continue
for prof in prop.profiles:
self.log.info('Fetching data for {}'.format(p['profile']))
if not prof.name == p['profile']:
continue
if prof not in self.profiles:
self.profiles.append(prof)
break
if not len(self.profiles):
raise Exception(
'Could not find active profiles for {}'.format(properties))
def setup(self):
"""
Connect to googla analytcs, select properties, get content items.
"""
self.connect()
self._gen_lookups()
def _gen_lookups(self):
"""
Create a tree of
domain => path > content item ids.
for fast lookups against google analytics urls.
Fallback to lookup of url > content item ids.
"""
# create containers
self.domain_lookup = defaultdict(lambda: defaultdict(list))
self.url_lookup = defaultdict(list)
# populate with ALL content items.
for c in self.api.orgs.simple_content():
u = c.pop('url', None)
domain = c.pop('domain', None)
if u and domain:
# parse path
p = url.get_path(u)
# standardize home domains.
if p == "" or p == "/":
p = "/"
elif not p:
continue
# build up list of ids.
self.domain_lookup[domain][p].append(c['id'])
self.url_lookup[u].append(c['id'])
def reconcile_urls(self, row, prof):
"""
This is where the ugly, ugly magic happens.
"""
domain = row.pop('domain', None)
path = row.pop('path', None)
if path != '/' and path.endswith('/'):
path = path[:-1]
prof_url = prof.raw.get('websiteUrl', None)
# get the canonical domain:
base = None
if not domain or 'not set' in domain:
if prof_url:
base = copy.copy(prof_url)
# absolutify paths with domains.
elif not path.startswith('/'):
base = copy.copy(path)
else:
base = copy.copy(domain)
if not base:
raise Exception('Could not process {}{}'.format(domain, path))
base_url = url.prepare(base, canonicalize=False, expand=False)
domain = url.get_domain(base_url)
# lookup via domain + path.
found = False
if domain in self.domain_lookup and path in self.domain_lookup[domain]:
for cid in self.domain_lookup.get(domain, {}).get(path, []):
found = True
r = copy.copy(row)
r['content_item_id'] = cid
yield r
# lookup via full url
if not found:
u = url.join(base_url, path)
for cid in self.url_lookup.get(u, []):
r = copy.copy(row)
r['content_item_id'] = cid
yield r
def fetch(self, prof):
pass
def format(self, data):
return data
def run(self):
for prof in self.profiles:
data = self.fetch(prof)
for row in self.format(data, prof):
yield row
class ContentTimeseries(SCGoogleAnalytics):
METRICS = {
'pageviews': 'ga_pageviews',
'timeOnPage': 'ga_total_time_on_page',
'exits': 'ga_exits',
'entrances': 'ga_entrances'
}
DIMENSIONS = {
'hostname': 'domain',
'pagePath': 'path',
'dateHour': 'datetime'
}
SORT_KEYS = [
'-dateHour',
'-pagePath'
]
def fetch(self, prof):
days = self.options.get('days', 5)
start = (dates.now() - timedelta(days=days)).date().isoformat()
prepend_ga_str = lambda item: 'ga:{}'.format(item)
ga_metric_names = map(prepend_ga_str, self.METRICS.keys())
ga_dimension_names = map(prepend_ga_str, self.DIMENSIONS.keys())
i = 1
while 1:
q = prof.core.query\
.set(metrics=ga_metric_names)\
.set(dimensions=ga_dimension_names)\
.range(start, days=days)\
.sort(*self.SORT_KEYS)\
.limit(i, i+1000)
self.log.info('Running query:\n\t{}\n\tat limit {}'.format(q.raw, i))
i += 1000
r = q.execute()
if not len(r.rows):
break
for row in r.rows:
yield row
def format_row_names(self, row):
"""
Rename rows based on metric / dimension lookups.
"""
new_row = {}
for k, v in row._asdict().iteritems():
k = k.replace('_', '').lower().strip()
if k in self.col_lookup:
new_row[self.col_lookup[k]] = v
else:
new_row[k] = v
return new_row
def format_date(self, dt, tz=None):
"""
Convert datehour to utc based on the profile's timezone
"""
if not tz:
tz = pytz.utc
if not isinstance(dt, datetime):
dt = datetime.strptime(dt, '%Y%m%d%H')
dt = dt.replace(tzinfo=tz)
dt = dates.convert_to_utc(dt)
# round to nearest hour
dt += timedelta(minutes=30)
dt -= timedelta(minutes=dt.minute % 60)
return dt
def pre_format(self, data, prof):
"""
Cleanup numbers, date, and column names.
"""
# create lookups.
self.col_lookup = {k.lower(): v for k, v in self.METRICS.items()}
self.col_lookup.update({k.lower(): v for k, v in self.DIMENSIONS.items()})
# get timezone from profile
tz = prof.raw.get('timezone', None)
if tz:
tz = pytz.timezone(tz)
# iterate through results and parse.
for row in data:
row = self.format_row_names(row)
# format date
row['datetime'] = self.format_date(row['datetime'], tz=tz)
# format numerics
for k, v in copy.copy(row).items():
if k not in ['datetime', 'domain', 'path']:
row[k] = stats.parse_number(v)
# reconcile urls.
for r in self.reconcile_urls(row, prof):
yield r
def format(self, data, prof):
"""
because of how we parse the urls, there can be multiple distinct rows of datetime + content_item id.
normalize them here.
"""
d = defaultdict(lambda: defaultdict(Counter))
for r in self.pre_format(data, prof):
for m, v in r.items():
if m not in ['content_item_id', 'datetime']:
d[r['content_item_id']][r['datetime']][m] += v
for cid in d.keys():
for dt in d[cid].keys():
metrics = dict(d[cid].get(dt, {}))
metrics.update({'content_item_id': cid, 'datetime': dt})
yield metrics
def load(self, data):
d = list(data)
status_resp = self.api.content.bulk_create_timeseries(data=d)
return self.api.jobs.poll(**status_resp)
# class ContentDomainFacets(SousChef):
# pass
class ContentDomainFacets(SCGoogleAnalytics):
METRICS = {
'pageviews': 'pageviews',
}
DIMENSIONS = {
'hostname': 'domain',
'pagePath': 'path',
'fullReferrer': 'referrer'
}
SEARCH_REFERRERS = [
'google', 'bing', 'ask', 'aol',
'yahoo', 'comcast', 'search-results',
'disqus', 'cnn', 'aol', 'baidu'
]
def parse_referrer(self, row):
"""
Parse a referrer.
"""
referrer = row.get('referrer')
if not referrer:
return row
if referrer == "(not set)":
row['referrer'] = 'null'
row['ref_domain'] = 'null'
elif referrer == "(direct)":
row['referrer'] = 'direct'
row['ref_domain'] = 'direct'
elif referrer in self.SEARCH_REFERRERS:
row['referrer'] = referrer
row['ref_domain'] = referrer
# special handling.
elif 't.co' in referrer:
row['referrer'] = url.prepare(referrer, expand=False, canonicalize=False)
row['ref_domain'] = 'twitter'
elif 'facebook' in referrer:
row['referrer'] = url.prepare(referrer, expand=False, canonicalize=False)
row['ref_domain'] = 'facebook'
else:
row['referrer'] = url.prepare(referrer, expand=False, canonicalize=False)
row['ref_domain'] = url.get_simple_domain(row['referrer'])
return row
def fetch(self, prof):
days = self.options.get('days', 30)
start = (dates.now() - timedelta(days=days)).date().isoformat()
prepend_ga_str = lambda item: 'ga:{}'.format(item)
ga_metric_names = map(prepend_ga_str, self.METRICS.keys())
ga_dimension_names = map(prepend_ga_str, self.DIMENSIONS.keys())
i = 1
while 1:
q = prof.core.query\
.set(metrics=ga_metric_names)\
.set(dimensions=ga_dimension_names)\
.range(start, days=days)\
.limit(i, i+1000)
self.log.info('Running query:\n\t{}\n\tat limit {}'.format(q.raw, i))
i += 1000
r = q.execute()
# pause in between queries.
time.sleep(5)
if not len(r.rows):
break
for row in r.rows:
yield row
def format_row_names(self, row):
"""
Rename rows based on metric / dimension lookups.
"""
new_row = {}
for k, v in row._asdict().iteritems():
k = k.replace('_', '').lower().strip()
if k in self.col_lookup:
new_row[self.col_lookup[k]] = v
else:
new_row[k] = v
return new_row
def pre_format(self, data, prof):
"""
Parse + reconcile
"""
self.col_lookup = {k.lower(): v for k, v in self.METRICS.items()}
self.col_lookup.update({k.lower(): v for k, v in self.DIMENSIONS.items()})
for row in data:
row = self.format_row_names(row)
row = self.parse_referrer(row)
row['pageviews'] = stats.parse_number(row.get('pageviews', 0))
for r in self.reconcile_urls(row, prof):
yield r
def format(self, data, prof):
data = list(data)
# build up facets.
facets = defaultdict(lambda: defaultdict(lambda: defaultdict(float)))
for row in self.pre_format(data, prof):
cid = row['content_item_id']
facets[cid]['ga_pageviews_by_domain'][row['ref_domain']] \
+= row['pageviews']
if url.is_article(row['referrer']):
facets[cid]['ga_pageviews_by_article_referrer'][row['referrer']] \
+= row['pageviews']
# format into newslnyx facets.
for cid, value in dict(facets).iteritems():
row = {'content_item_id': cid}
for metric, _facets in value.iteritems():
row[metric] = []
n_facets = 0
for k, v in sorted(_facets.iteritems(), key=itemgetter(1), reverse=True):
n_facets += 1
if n_facets >= self.options['max_facets']:
break
row[metric].append({'facet': k, 'value': v})
yield row
def load(self, data):
"""
Load
"""
d = list(data)
status_resp = self.api.content.bulk_create_summary(data=d)
return self.api.jobs.poll(**status_resp)
class ContentDeviceSummaries(SCGoogleAnalytics):
METRICS = {
'pageviews': 'pageviews'
}
DIMENSIONS = {
'hostname': 'domain',
'pagePath': 'path',
'deviceCategory': 'device'
}
def fetch(self, prof):
days = self.options.get('days', 30)
start = (dates.now() - timedelta(days=days)).date().isoformat()
prepend_ga_str = lambda item: 'ga:{}'.format(item)
ga_metric_names = map(prepend_ga_str, self.METRICS.keys())
ga_dimension_names = map(prepend_ga_str, self.DIMENSIONS.keys())
i = 1
while 1:
q = prof.core.query\
.set(metrics=ga_metric_names)\
.set(dimensions=ga_dimension_names)\
.range(start, days=days)\
.limit(i, i+1000)
self.log.info('Running query:\n\t{}\n\tat limit {}'.format(q.raw, i))
i += 1000
r = q.execute()
if not len(r.rows):
break
for row in r.rows:
yield row
def format_row_names(self, row):
"""
Rename rows based on metric / dimension lookups.
"""
new_row = {}
for k, v in row._asdict().iteritems():
k = k.replace('_', '').lower().strip()
if k in self.col_lookup:
new_row[self.col_lookup[k]] = v
else:
new_row[k] = v
return new_row
def pre_format(self, data, prof):
"""
Lookup content item ids.
"""
# create lookups.
self.col_lookup = {k.lower(): v for k, v in self.METRICS.items()}
self.col_lookup.update({k.lower(): v for k, v in self.DIMENSIONS.items()})
for row in data:
row = self.format_row_names(row)
row['device'] = row['device'].lower()
for r in self.reconcile_urls(row, prof):
yield r
def format(self, data, prof):
# group counts.
counts = defaultdict(Counter)
for row in self.pre_format(data, prof):
counts[row['content_item_id']][row['device']] += row.get('pageviews', 0)
for cid, facets in counts.iteritems():
row = {'content_item_id': cid}
# fill in zeros.
for k in ['mobile', 'desktop', 'tablet']:
if k not in facets:
facets[k] = 0
# populate metrics.
for k in ['mobile', 'desktop', 'tablet']:
row['ga_pageviews_'+k] = stats.parse_number(facets[k])
yield row
def load(self, data):
d = list(data)
status_resp = self.api.content.bulk_create_summary(data=d)
return self.api.jobs.poll(**status_resp)