Skip to content

Commit

Permalink
GA4 file download
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelglenister committed Mar 7, 2024
1 parent 2e3a388 commit d3e94f5
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
29 changes: 25 additions & 4 deletions pmg/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
from universal_analytics import Tracker, HTTPRequest
from flask import request
from flask_security import current_user

import requests
import json

# Useragents that are bots
BOTS_RE = re.compile("(bot|spider|cloudfront|slurp)", re.I)
Expand All @@ -29,7 +30,7 @@ def levenshtein(first, second, transpositions=False):


def track_pageview(path=None, ignore_bots=True):
""" User Google Analytics to track this pageview. """
"""User Google Analytics to track this pageview."""
from pmg import app

ga_id = app.config.get("GOOGLE_ANALYTICS_ID")
Expand Down Expand Up @@ -61,9 +62,29 @@ def track_pageview(path=None, ignore_bots=True):
return True


def track_file_download():
from pmg import app

ga_id = app.config.get("GOOGLE_ANALYTICS_ID")
api_secret = ""
client_id = request.cookies.get("_ga")

user_agent = request.user_agent.string
path = path or request.path

url = f"https://www.google-analytics.com/debug/mp/collect?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}}],
}
requests.post(url, data=json.dumps(payload), verify=True)

return True


def externalise_url(url):
""" Externalise a URL based on the request scheme and host.
"""
"""Externalise a URL based on the request scheme and host."""
from pmg import app

if url.startswith("http"):
Expand Down
2 changes: 1 addition & 1 deletion pmg/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -1786,7 +1786,7 @@ def docs(path, dir=""):

# report to google analytics
try:
utils.track_pageview()
utils.track_file_download()
except Exception as e:
logger.error("Error tracking pageview: %s" % e, exc_info=e)

Expand Down

0 comments on commit d3e94f5

Please sign in to comment.