Manage Google Analytics and UserReport services
authorThierry Florac <thierry.florac@onf.fr>
Wed, 15 Jun 2016 12:28:18 +0200
changeset 145 c7ec73c1d8be
parent 144 3198f3bcf67d
child 146 ce34989ca39f
Manage Google Analytics and UserReport services
src/pyams_skin/extension.py
src/pyams_skin/interfaces/extension.py
src/pyams_skin/viewlet/extension/analytics.py
src/pyams_skin/viewlet/extension/templates/analytics.pt
src/pyams_skin/viewlet/extension/templates/user_report.pt
src/pyams_skin/viewlet/extension/user_report.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_skin/extension.py	Wed Jun 15 12:28:18 2016 +0200
@@ -0,0 +1,68 @@
+#
+# Copyright (c) 2008-2016 Thierry Florac <tflorac AT ulthar.net>
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+
+__docformat__ = 'restructuredtext'
+
+
+# import standard library
+
+# import interfaces
+from pyams_skin.interfaces.extension import \
+    IGoogleAnalyticsInfo, GOOGLE_ANALYTICS_INFO_KEY, \
+    IUserReportInfo, USER_REPORT_INFO_KEY
+from pyams_utils.interfaces.site import ISiteRoot
+from zope.annotation.interfaces import IAnnotations
+
+# import packages
+from persistent import Persistent
+from pyams_utils.adapter import adapter_config
+from zope.interface import implementer
+from zope.schema.fieldproperty import FieldProperty
+
+
+@implementer(IGoogleAnalyticsInfo)
+class GoogleAnalyticsInfo(Persistent):
+    """Google Analytics settings class"""
+
+    enabled = FieldProperty(IGoogleAnalyticsInfo['enabled'])
+    website_id = FieldProperty(IGoogleAnalyticsInfo['website_id'])
+    verification_code = FieldProperty(IGoogleAnalyticsInfo['verification_code'])
+    activation_mode = FieldProperty(IGoogleAnalyticsInfo['activation_mode'])
+
+
+@adapter_config(context=ISiteRoot, provides=IGoogleAnalyticsInfo)
+def GoogleAnalyticsInfoFactory(context):
+    """Google Analytics settings factory"""
+    annotations = IAnnotations(context)
+    info = annotations.get(GOOGLE_ANALYTICS_INFO_KEY)
+    if info is None:
+        info = annotations[GOOGLE_ANALYTICS_INFO_KEY] = GoogleAnalyticsInfo()
+    return info
+
+
+@implementer(IUserReportInfo)
+class UserReportInfo(Persistent):
+    """User report settings class"""
+
+    enabled = FieldProperty(IUserReportInfo['enabled'])
+    account_id = FieldProperty(IUserReportInfo['account_id'])
+    activation_mode = FieldProperty(IUserReportInfo['activation_mode'])
+
+
+@adapter_config(context=ISiteRoot, provides=IUserReportInfo)
+def UserReportInfoFactory(context):
+    """User report settings factory"""
+    annotations = IAnnotations(context)
+    info = annotations.get(USER_REPORT_INFO_KEY)
+    if info is None:
+        info = annotations[USER_REPORT_INFO_KEY] = UserReportInfo()
+    return info
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_skin/interfaces/extension.py	Wed Jun 15 12:28:18 2016 +0200
@@ -0,0 +1,84 @@
+#
+# Copyright (c) 2008-2016 Thierry Florac <tflorac AT ulthar.net>
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+
+__docformat__ = 'restructuredtext'
+
+
+# import standard library
+
+# import interfaces
+
+# import packages
+from zope.interface import Interface
+from zope.schema import TextLine, Bool, Choice
+from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
+
+from pyams_skin import _
+
+
+ACTIVATED_ON_FRONT = 0
+ACTIVATED_ON_BACK = 1
+ACTIVATED_ON_BOTH = 2
+
+ACTIVATION_MODES_LABELS = {ACTIVATED_ON_FRONT: _("Front-office only"),
+                           ACTIVATED_ON_BACK: _("Back-office only"),
+                           ACTIVATED_ON_BOTH: _("Front-office and back-office")}
+
+ACTIVATION_MODES = SimpleVocabulary([SimpleTerm(k, title=v) for k, v in ACTIVATION_MODES_LABELS.items()])
+
+
+GOOGLE_ANALYTICS_INFO_KEY = 'pyams_skin.analytics_info'
+
+
+class IGoogleAnalyticsInfo(Interface):
+    """Google Analytics account info"""
+
+    enabled = Bool(title=_("Activate Google Analytics?"),
+                   description=_("Are Google Analytics statistics activated?"),
+                   required=True,
+                   default=False)
+
+    website_id = TextLine(title=_("Web site ID"),
+                          description=_("Google Analytics web site ID"),
+                          required=False)
+
+    verification_code = TextLine(title=_("Web site verification code"),
+                                 description=_("Google site verification code"),
+                                 required=False)
+
+    activation_mode = Choice(title=_("Activation mode"),
+                             description=_("Mode(s) in which statistics are activated"),
+                             vocabulary=ACTIVATION_MODES,
+                             default=ACTIVATED_ON_BOTH,
+                             required=True)
+
+
+USER_REPORT_INFO_KEY = 'pyams_skin.user_report_info'
+
+
+class IUserReportInfo(Interface):
+    """UserReport account info"""
+
+    enabled = Bool(title=_("Activate UserReport?"),
+                   description=_("Are UserReport comments and feedback activated?"),
+                   required=True,
+                   default=False)
+
+    account_id = TextLine(title=_("Account ID"),
+                          description=_("UserReport account ID, available in 'initSite' code snippet"),
+                          required=False)
+
+    activation_mode = Choice(title=_("Activation mode"),
+                             description=_("Mode(s) in which reports are activated"),
+                             vocabulary=ACTIVATION_MODES,
+                             default=ACTIVATED_ON_BOTH,
+                             required=True)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_skin/viewlet/extension/analytics.py	Wed Jun 15 12:28:18 2016 +0200
@@ -0,0 +1,52 @@
+#
+# Copyright (c) 2008-2015 Thierry Florac <tflorac AT ulthar.net>
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+
+__docformat__ = 'restructuredtext'
+
+
+# import standard library
+
+# import interfaces
+from pyams_skin.interfaces.extension import IGoogleAnalyticsInfo, ACTIVATED_ON_FRONT, ACTIVATED_ON_BACK
+from pyams_skin.interfaces.viewlet import IJSExtensionsViewletManager
+from pyams_skin.layer import IPyAMSLayer
+try:
+    from pyams_zmi.layer import IAdminLayer
+except ImportError:
+    IAdminLayer = None
+
+# import packages
+from pyams_template.template import template_config
+from pyams_viewlet.viewlet import viewlet_config, Viewlet
+
+
+@viewlet_config(name='analytics', manager=IJSExtensionsViewletManager)
+@template_config(template='templates/analytics.pt', layer=IPyAMSLayer)
+class GoogleAnalyticsViewlet(Viewlet):
+    """Google Analytics viewlet"""
+
+    def __new__(cls, context, request, view, manager):
+        info = IGoogleAnalyticsInfo(request.root)
+        if not info.enabled:
+            return None
+        if IAdminLayer is None:
+            if info.activation_mode == ACTIVATED_ON_BACK:
+                return None
+        else:
+            if ((info.activation_mode == ACTIVATED_ON_FRONT) and IAdminLayer.providedBy(request)) or \
+               ((info.activation_mode == ACTIVATED_ON_BACK) and not IAdminLayer.providedBy(request)):
+                return None
+        return Viewlet.__new__(cls)
+
+    @property
+    def config(self):
+        return IGoogleAnalyticsInfo(self.request.root)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_skin/viewlet/extension/templates/analytics.pt	Wed Jun 15 12:28:18 2016 +0200
@@ -0,0 +1,18 @@
+<!-- Google Analytics -->
+<script type="text/javascript">
+
+	var _gaq = _gaq || [];
+	_gaq.push(['_setAccount', '<tal:var content="view.config.website_id" />']);
+	_gaq.push(['_trackPageview']);
+
+	(function () {
+		var ga = document.createElement('script');
+		ga.type = 'text/javascript';
+		ga.async = true;
+		ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
+		var s = document.getElementsByTagName('script')[0];
+		s.parentNode.insertBefore(ga, s);
+	})();
+
+</script>
+<!-- end Google Analytics -->
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_skin/viewlet/extension/templates/user_report.pt	Wed Jun 15 12:28:18 2016 +0200
@@ -0,0 +1,17 @@
+<!-- UserReport snippet -->
+<script type="text/javascript">
+
+	var _urq = _urq || [];
+	_urq.push(['initSite', '<tal:var content="view.config.account_id" />']);
+
+	(function () {
+		var ur = document.createElement('script');
+		ur.type = 'text/javascript';
+		ur.async = true;
+		ur.src = document.location.protocol + '//cdn.userreport.com/userreport.js';
+		var s = document.getElementsByTagName('script')[0];
+		s.parentNode.insertBefore(ur, s);
+	})();
+
+</script>
+<!-- end UserReport -->
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_skin/viewlet/extension/user_report.py	Wed Jun 15 12:28:18 2016 +0200
@@ -0,0 +1,52 @@
+#
+# Copyright (c) 2008-2015 Thierry Florac <tflorac AT ulthar.net>
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+
+__docformat__ = 'restructuredtext'
+
+
+# import standard library
+
+# import interfaces
+from pyams_skin.interfaces.extension import IUserReportInfo, ACTIVATED_ON_FRONT, ACTIVATED_ON_BACK
+from pyams_skin.interfaces.viewlet import IJSExtensionsViewletManager
+from pyams_skin.layer import IPyAMSLayer
+try:
+    from pyams_zmi.layer import IAdminLayer
+except ImportError:
+    IAdminLayer = None
+
+# import packages
+from pyams_template.template import template_config
+from pyams_viewlet.viewlet import viewlet_config, Viewlet
+
+
+@viewlet_config(name='user-report', manager=IJSExtensionsViewletManager)
+@template_config(template='templates/user_report.pt', layer=IPyAMSLayer)
+class UserReportViewlet(Viewlet):
+    """Google Analytics viewlet"""
+
+    def __new__(cls, context, request, view, manager):
+        info = IUserReportInfo(request.root)
+        if not info.enabled:
+            return None
+        if IAdminLayer is None:
+            if info.activation_mode == ACTIVATED_ON_BACK:
+                return None
+        else:
+            if ((info.activation_mode == ACTIVATED_ON_FRONT) and IAdminLayer.providedBy(request)) or \
+               ((info.activation_mode == ACTIVATED_ON_BACK) and not IAdminLayer.providedBy(request)):
+                return None
+        return Viewlet.__new__(cls)
+
+    @property
+    def config(self):
+        return IUserReportInfo(self.request.root)