From 35dfdebaa23414d3b2615855c1fe0283dba668da Mon Sep 17 00:00:00 2001 From: michaelglenister Date: Mon, 18 Mar 2024 15:44:52 +0200 Subject: [PATCH 1/2] Add file_download event params --- pmg/utils.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/pmg/utils.py b/pmg/utils.py index 3a15210d..4d8ca53e 100644 --- a/pmg/utils.py +++ b/pmg/utils.py @@ -6,6 +6,7 @@ from flask_security import current_user import requests import json +import os # Useragents that are bots BOTS_RE = re.compile("(bot|spider|cloudfront|slurp)", re.I) @@ -70,15 +71,22 @@ def track_file_download(): api_secret = app.config.get("GOOGLE_ANALYTICS_API_SECRET") client_id = request.cookies.get("_ga") - user_agent = request.user_agent.string path = request.path + file_name, file_extension = os.path.splitext(path) url = f"{ga_url}?measurement_id={ga_id}&api_secret={api_secret}" payload = { "client_id": client_id, "non_personalized_ads": "false", "events": [ - {"name": "file_download", "params": {"userAgent": user_agent, "path": path}} + { + "name": "file_download", + "params": { + "file_extension": file_extension.replace(".", ""), + "file_name": file_name, + "link_url": request.url, + }, + } ], } requests.post(url, data=json.dumps(payload), verify=True) From dcc2319d27e349ed56ab954450b1e8b2ea8b2bf6 Mon Sep 17 00:00:00 2001 From: michaelglenister Date: Tue, 19 Mar 2024 10:59:15 +0200 Subject: [PATCH 2/2] Add more params to file_download event --- pmg/utils.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/pmg/utils.py b/pmg/utils.py index 4d8ca53e..e07eb23b 100644 --- a/pmg/utils.py +++ b/pmg/utils.py @@ -72,7 +72,9 @@ def track_file_download(): client_id = request.cookies.get("_ga") path = request.path - file_name, file_extension = os.path.splitext(path) + last_slash_index = path.rfind("/") + file_dir = path[:last_slash_index] + page_location = f"{request.url_root}{file_dir[1:]}" url = f"{ga_url}?measurement_id={ga_id}&api_secret={api_secret}" payload = { @@ -82,9 +84,11 @@ def track_file_download(): { "name": "file_download", "params": { - "file_extension": file_extension.replace(".", ""), - "file_name": file_name, + "file_extension": path.split(".")[-1], + "file_name": path, "link_url": request.url, + "page_location": page_location, + "page_referrer": request.referrer, }, } ],