Skip to content

Commit

Permalink
Merge pull request #517 from OpenUpSA/ga4-file-downloads
Browse files Browse the repository at this point in the history
Analytics for file downloads
  • Loading branch information
paulmwatson authored Mar 14, 2024
2 parents 66c7e13 + 9c16f9e commit 1ca78bb
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 17 deletions.
32 changes: 28 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["GOOGLE_ANALYTICS_ID"]
Expand Down Expand Up @@ -61,9 +62,32 @@ def track_pageview(path=None, ignore_bots=True):
return True


def track_file_download():
from pmg import app

ga_url = "https://www.google-analytics.com/mp/collect"
ga_id = app.config.get("GOOGLE_ANALYTICS_ID")
api_secret = app.config.get("GOOGLE_ANALYTICS_API_SECRET")
client_id = request.cookies.get("_ga")

user_agent = request.user_agent.string
path = request.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}}
],
}
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
16 changes: 4 additions & 12 deletions tests/views/test_files_page.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,16 @@
from tests import PMGLiveServerTestCase
from tests.fixtures import dbfixture, HouseData, CommitteeData
from universal_analytics import Tracker
from unittest.mock import patch


class TestFilesPage(PMGLiveServerTestCase):
@patch.object(Tracker, "send")
def test_questions_file_page(self, mock_tracker):
def test_questions_file_page(self):
"""
Test email alerts page (/questions/<path>)
Test files page (/questions/<path>)
"""
path = "test_file.pdf"
response = self.make_request(f"/questions/{path}", follow_redirects=False)
mock_tracker.assert_called_with(
"pageview",
"/questions/test_file.pdf",
referrer="",
uip="127.0.0.1",
userAgent="werkzeug/2.0.0",
)

self.assertEqual(302, response.status_code)
self.assertEqual("http://pmg-assets.s3-website-eu-west-1.amazonaws.com/questions/test_file.pdf", response.location)
static_host = self.app.config.get("STATIC_HOST")
self.assertEqual(response.location, f"{static_host}questions/{path}")

0 comments on commit 1ca78bb

Please sign in to comment.