Skip to content

Commit

Permalink
Merge pull request #73 from mc18g13/add-user-id-to-api-measurement-ev…
Browse files Browse the repository at this point in the history
…ents

add user id to api calls
  • Loading branch information
smotornyuk authored Jun 24, 2024
2 parents 24d9a7f + c9c813e commit 09ec707
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 deletions.
27 changes: 16 additions & 11 deletions ckanext/googleanalytics/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ def send_event(data):
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"],
"resource_id": data["id"]
}})

log.warning("Only API and Download events supported by Measurement Protocol at the moment")
Expand All @@ -36,15 +36,15 @@ def default(self, _):
return None


def _mp_api_handler(data_dict):
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):
Expand All @@ -58,18 +58,23 @@ def _mp_download_handler(data_dict):
})


def _mp_event(event):
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()
"measurement_id": config.measurement_id(),
},
data=json.dumps({
"client_id": config.measurement_protocol_client_id(),
"non_personalized_ads": False,
"events": [event]
}, cls=SafeJSONEncoder)
data=json.dumps(data, cls=SafeJSONEncoder)
)

if resp.status_code >= 300:
Expand Down
1 change: 1 addition & 0 deletions ckanext/googleanalytics/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ def _post_analytics(
"function": request_function,
"id": request_id,
"payload": request_payload,
"user_id": hashlib.md5(six.ensure_binary(tk.c.user)).hexdigest()
})

else:
Expand Down

0 comments on commit 09ec707

Please sign in to comment.