-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathutils.py
100 lines (73 loc) · 2.37 KB
/
utils.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
import json
import logging
import requests
from six.moves.urllib.parse import urlencode
from ckanext.googleanalytics import config
log = logging.getLogger(__name__)
EVENT_API = "CKAN API Request"
EVENT_DOWNLOAD = "CKAN Resource Download Request"
def send_event(data):
if isinstance(data, MeasurementProtocolData):
if data["event"] == EVENT_API:
return _mp_api_handler({
"action": data["object"],
"payload": data["payload"],
}, user_id=data["user_id"])
if data["event"] == EVENT_DOWNLOAD:
return _mp_download_handler({"payload": {
"resource_id": data["id"]
}})
log.warning("Only API and Download events supported by Measurement Protocol at the moment")
return
return _ga_handler(data)
class SafeJSONEncoder(json.JSONEncoder):
def default(self, _):
return None
def _mp_api_handler(data_dict, user_id=None):
log.debug(
"Sending API event to Google Analytics using the Measurement Protocol: %s",
data_dict
)
_mp_event({
"name": data_dict["action"],
"params": data_dict["payload"]
}, user_id=user_id)
def _mp_download_handler(data_dict):
log.debug(
"Sending Downlaod event to Google Analytics using the Measurement Protocol: %s",
data_dict
)
_mp_event({
"name": "file_download",
"params": data_dict["payload"],
})
def _mp_event(event, user_id=None):
data = {
"client_id": config.measurement_protocol_client_id(),
"non_personalized_ads": False,
"events": [event]
}
if user_id:
data["user_id"] = user_id
resp = requests.post(
"https://www.google-analytics.com/mp/collect",
params={
"api_secret": config.measurement_protocol_client_secret(),
"measurement_id": config.measurement_id(),
},
data=json.dumps(data, cls=SafeJSONEncoder)
)
if resp.status_code >= 300:
log.error("Cannot post event: %s", resp)
def _ga_handler(data_dict):
data = urlencode(data_dict)
log.debug("Sending API event to Google Analytics: %s", data)
requests.post(
"https://www.google-analytics.com/collect",
data,
timeout=10,
)
class UniversalAnalyticsData(dict):
pass
class MeasurementProtocolData(dict):
pass