diff --git a/pmg/utils.py b/pmg/utils.py index 627797dd..c6f70bf5 100644 --- a/pmg/utils.py +++ b/pmg/utils.py @@ -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) @@ -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"] @@ -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"): diff --git a/pmg/views.py b/pmg/views.py index dc586540..3bd82887 100644 --- a/pmg/views.py +++ b/pmg/views.py @@ -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) diff --git a/tests/views/test_files_page.py b/tests/views/test_files_page.py index 3dbf315b..ce5fbe67 100644 --- a/tests/views/test_files_page.py +++ b/tests/views/test_files_page.py @@ -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/) + Test files page (/questions/) """ 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}")