Source code for core.analytics
import importlib
import contextlib
import os
from collections import defaultdict
from sqlalchemy.orm.session import Session
from .model import ExternalIntegration
from .config import CannotLoadConfiguration
from .util.datetime_helpers import utc_now
[docs]class Analytics(object):
GLOBAL_ENABLED = None
LIBRARY_ENABLED = set()
def __init__(self, _db):
self.sitewide_providers = []
self.library_providers = defaultdict(list)
self.initialization_exceptions = {}
Analytics.GLOBAL_ENABLED = False
Analytics.LIBRARY_ENABLED = set()
# Find a list of all the ExternalIntegrations set up with a
# goal of analytics.
integrations = _db.query(ExternalIntegration).filter(ExternalIntegration.goal==ExternalIntegration.ANALYTICS_GOAL)
# Turn each integration into an analytics provider.
for integration in integrations:
kwargs = {}
module = integration.protocol
if module.startswith('.'):
# This is a relative import. Import it relative to
# this module. This should only happen during tests.
kwargs['package'] =__name__
else:
# This is an absolute import. Trust sys.path to find it.
pass
try:
provider_module = importlib.import_module(module, **kwargs)
provider_class = getattr(provider_module, "Provider", None)
if provider_class:
if not integration.libraries:
provider = provider_class(integration)
self.sitewide_providers.append(provider)
Analytics.GLOBAL_ENABLED = True
else:
for library in integration.libraries:
provider = provider_class(integration, library)
self.library_providers[library.id].append(provider)
Analytics.LIBRARY_ENABLED.add(library.id)
else:
self.initialization_exceptions[integration.id] = "Module %s does not have Provider defined." % module
except (ImportError, CannotLoadConfiguration) as e:
self.initialization_exceptions[integration.id] = e
[docs] def collect_event(self, library, license_pool, event_type, time=None, **kwargs):
if not time:
time = utc_now()
providers = list(self.sitewide_providers)
if library:
providers.extend(self.library_providers[library.id])
for provider in providers:
provider.collect_event(library, license_pool, event_type, time, **kwargs)