ckanext-googleanalytics/ckanext/googleanalytics/plugin/__init__.py

82 lines
2.2 KiB
Python
Raw Normal View History

2019-12-09 14:23:33 +01:00
# -*- coding: utf-8 -*-
2019-11-22 15:59:22 +01:00
from __future__ import absolute_import
2019-12-09 14:23:33 +01:00
2020-07-28 22:14:15 +02:00
from six.moves.urllib.parse import urlencode
2019-11-22 15:59:22 +01:00
import logging
2019-12-09 14:23:33 +01:00
import threading
import requests
2019-11-22 15:59:22 +01:00
import ckan.plugins as p
import ckan.plugins.toolkit as tk
2019-12-09 14:23:33 +01:00
2022-05-06 16:29:58 +02:00
from ckan.exceptions import CkanConfigurationException, CkanVersionException
from ckanext.googleanalytics import helpers
2019-12-09 14:23:33 +01:00
2019-11-22 15:59:22 +01:00
log = logging.getLogger(__name__)
try:
tk.requires_ckan_version("2.9")
except CkanVersionException:
2019-12-06 12:28:13 +01:00
from ckanext.googleanalytics.plugin.pylons_plugin import GAMixinPlugin
2019-11-22 15:59:22 +01:00
else:
from ckanext.googleanalytics.plugin.flask_plugin import GAMixinPlugin
2022-05-06 16:29:58 +02:00
class GoogleAnalyticsException(CkanConfigurationException):
2019-11-22 15:59:22 +01:00
pass
class AnalyticsPostThread(threading.Thread):
"""Threaded Url POST"""
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
# grabs host from queue
data_dict = self.queue.get()
2020-07-28 22:14:15 +02:00
data = urlencode(data_dict)
2019-11-22 15:59:22 +01:00
log.debug("Sending API event to Google Analytics: " + data)
# send analytics
2022-05-06 18:28:52 +02:00
requests.post(
"http://www.google-analytics.com/collect",
data,
timeout=10,
2019-11-22 15:59:22 +01:00
)
# signals to queue job is done
self.queue.task_done()
class GoogleAnalyticsPlugin(GAMixinPlugin, p.SingletonPlugin):
2022-05-06 16:29:58 +02:00
2019-11-22 15:59:22 +01:00
p.implements(p.IConfigurable, inherit=True)
p.implements(p.IConfigurer, inherit=True)
p.implements(p.ITemplateHelpers)
def configure(self, config):
2022-05-06 16:29:58 +02:00
# spawn a pool of 5 threads, and pass them queue instance
for _i in range(5):
t = AnalyticsPostThread(self.analytics_queue)
t.setDaemon(True)
t.start()
2019-11-22 15:59:22 +01:00
2022-05-06 16:29:58 +02:00
def update_config(self, config):
tk.add_template_directory(config, "../templates")
tk.add_resource("../assets", "ckanext-googleanalytics")
2019-11-22 15:59:22 +01:00
if "googleanalytics.id" not in config:
msg = "Missing googleanalytics.id in config"
raise GoogleAnalyticsException(msg)
def get_helpers(self):
2022-05-06 18:01:29 +02:00
return helpers.get_helpers()
2019-11-22 15:59:22 +01:00
2022-05-06 18:01:29 +02:00
if tk.check_ckan_version("2.10"):
tk.blanket.config_declarations(GoogleAnalyticsPlugin)