google_analytics.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. # encoding: utf-8
  2. import datetime
  3. import json
  4. from django import forms
  5. try:
  6. from django.core.urlresolvers import reverse
  7. except ImportError: # Django 1.11
  8. from django.urls import reverse
  9. from django.forms import Widget
  10. from django.utils import formats
  11. from django.utils.html import format_html
  12. from django.utils.safestring import mark_safe
  13. from django.utils.text import capfirst
  14. from googleapiclient.discovery import build
  15. import httplib2
  16. from jet.dashboard.modules import DashboardModule
  17. from oauth2client.client import flow_from_clientsecrets, OAuth2Credentials, AccessTokenRefreshError, Storage
  18. from django.utils.translation import ugettext_lazy as _
  19. from django.conf import settings
  20. from django.utils.encoding import force_text
  21. try:
  22. from django.utils.encoding import force_unicode
  23. except ImportError:
  24. from django.utils.encoding import force_text as force_unicode
  25. try:
  26. from django.forms.utils import flatatt
  27. except ImportError:
  28. from django.forms.util import flatatt
  29. JET_MODULE_GOOGLE_ANALYTICS_CLIENT_SECRETS_FILE = getattr(
  30. settings,
  31. 'JET_MODULE_GOOGLE_ANALYTICS_CLIENT_SECRETS_FILE',
  32. ''
  33. )
  34. class ModuleCredentialStorage(Storage):
  35. def __init__(self, module):
  36. super(ModuleCredentialStorage, self).__init__()
  37. self.module = module
  38. def locked_get(self):
  39. pass
  40. def locked_put(self, credentials):
  41. pass
  42. def locked_delete(self):
  43. pass
  44. def get(self):
  45. try:
  46. settings = json.loads(self.module.settings)
  47. credential = settings['credential']
  48. return OAuth2Credentials.from_json(credential)
  49. except (ValueError, KeyError):
  50. return None
  51. def put(self, credentials):
  52. self.module.update_settings({'credential': credentials.to_json()})
  53. def delete(self):
  54. self.module.pop_settings(('credential',))
  55. class GoogleAnalyticsClient:
  56. credential = None
  57. analytics_service = None
  58. def __init__(self, storage=None, redirect_uri=None):
  59. self.FLOW = flow_from_clientsecrets(
  60. JET_MODULE_GOOGLE_ANALYTICS_CLIENT_SECRETS_FILE,
  61. scope='https://www.googleapis.com/auth/analytics.readonly',
  62. redirect_uri=redirect_uri,
  63. prompt='consent'
  64. )
  65. if storage is not None:
  66. credential = storage.get()
  67. credential.set_store(storage)
  68. self.set_credential(credential)
  69. def get_oauth_authorize_url(self, state=''):
  70. self.FLOW.params['state'] = state
  71. authorize_url = self.FLOW.step1_get_authorize_url()
  72. return authorize_url
  73. def set_credential(self, credential):
  74. self.credential = credential
  75. self.set_analytics_service(self.credential)
  76. def set_credential_from_request(self, request):
  77. self.set_credential(self.FLOW.step2_exchange(request.GET))
  78. def set_analytics_service(self, credential):
  79. http = httplib2.Http()
  80. http = credential.authorize(http)
  81. self.analytics_service = build('analytics', 'v3', http=http)
  82. def api_profiles(self):
  83. if self.analytics_service is None:
  84. return None, None
  85. try:
  86. profiles = self.analytics_service.management().profiles().list(
  87. accountId='~all',
  88. webPropertyId='~all'
  89. ).execute()
  90. return profiles['items'], None
  91. except (TypeError, KeyError) as e:
  92. return None, e
  93. def api_ga(self, profile_id, date1, date2, group=None):
  94. if self.analytics_service is None:
  95. return None, None
  96. if group == 'day':
  97. dimensions = 'ga:date'
  98. elif group == 'week':
  99. dimensions = 'ga:year,ga:week'
  100. elif group == 'month':
  101. dimensions = 'ga:year,ga:month'
  102. else:
  103. dimensions = ''
  104. try:
  105. data = self.analytics_service.data().ga().get(
  106. ids='ga:' + profile_id,
  107. start_date=date1.strftime('%Y-%m-%d'),
  108. end_date=date2.strftime('%Y-%m-%d'),
  109. metrics='ga:users,ga:sessions,ga:pageviews',
  110. dimensions=dimensions
  111. ).execute()
  112. return data, None
  113. except TypeError as e:
  114. return None, e
  115. class CredentialWidget(Widget):
  116. module = None
  117. def render(self, name, value, attrs=None):
  118. if value and len(value) > 0:
  119. link = '<a href="%s">%s</a>' % (
  120. reverse('jet-dashboard:google-analytics-revoke', kwargs={'pk': self.module.model.pk}),
  121. force_text(_('Revoke access'))
  122. )
  123. else:
  124. link = '<a href="%s">%s</a>' % (
  125. reverse('jet-dashboard:google-analytics-grant', kwargs={'pk': self.module.model.pk}),
  126. force_text(_('Grant access'))
  127. )
  128. attrs = self.build_attrs({
  129. 'type': 'hidden',
  130. 'name': 'credential',
  131. })
  132. attrs['value'] = force_unicode(value) if value else ''
  133. return format_html('%s<input{} />' % link, flatatt(attrs))
  134. class GoogleAnalyticsSettingsForm(forms.Form):
  135. credential = forms.CharField(label=_('Access'), widget=CredentialWidget)
  136. counter = forms.ChoiceField(label=_('Counter'))
  137. period = forms.ChoiceField(label=_('Statistics period'), choices=(
  138. (0, _('Today')),
  139. (6, _('Last week')),
  140. (30, _('Last month')),
  141. (31 * 3 - 1, _('Last quarter')),
  142. (364, _('Last year')),
  143. ))
  144. def set_module(self, module):
  145. self.fields['credential'].widget.module = module
  146. self.set_counter_choices(module)
  147. def set_counter_choices(self, module):
  148. counters = module.counters()
  149. if counters is not None:
  150. self.fields['counter'].choices = (('', '-- %s --' % force_text(_('none'))),)
  151. self.fields['counter'].choices.extend(map(lambda x: (x['id'], x['websiteUrl']), counters))
  152. else:
  153. label = force_text(_('grant access first')) if module.credential is None else force_text(_('counters loading failed'))
  154. self.fields['counter'].choices = (('', '-- %s -- ' % label),)
  155. class GoogleAnalyticsChartSettingsForm(GoogleAnalyticsSettingsForm):
  156. show = forms.ChoiceField(label=_('Show'), choices=(
  157. ('ga:users', capfirst(_('users'))),
  158. ('ga:sessions', capfirst(_('sessions'))),
  159. ('ga:pageviews', capfirst(_('views'))),
  160. ))
  161. group = forms.ChoiceField(label=_('Group'), choices=(
  162. ('day', _('By day')),
  163. ('week', _('By week')),
  164. ('month', _('By month')),
  165. ))
  166. class GoogleAnalyticsPeriodVisitorsSettingsForm(GoogleAnalyticsSettingsForm):
  167. group = forms.ChoiceField(label=_('Group'), choices=(
  168. ('day', _('By day')),
  169. ('week', _('By week')),
  170. ('month', _('By month')),
  171. ))
  172. class GoogleAnalyticsBase(DashboardModule):
  173. settings_form = GoogleAnalyticsSettingsForm
  174. ajax_load = True
  175. contrast = True
  176. period = None
  177. credential = None
  178. counter = None
  179. error = None
  180. storage = None
  181. def __init__(self, title=None, period=None, **kwargs):
  182. kwargs.update({'period': period})
  183. super(GoogleAnalyticsBase, self).__init__(title, **kwargs)
  184. def settings_dict(self):
  185. return {
  186. 'period': self.period,
  187. 'credential': self.credential,
  188. 'counter': self.counter
  189. }
  190. def load_settings(self, settings):
  191. try:
  192. self.period = int(settings.get('period'))
  193. except TypeError:
  194. self.period = 0
  195. self.credential = settings.get('credential')
  196. self.storage = ModuleCredentialStorage(self.model)
  197. self.counter = settings.get('counter')
  198. def init_with_context(self, context):
  199. raise NotImplementedError('subclasses of GoogleAnalytics must provide a init_with_context() method')
  200. def counters(self):
  201. try:
  202. client = GoogleAnalyticsClient(self.storage)
  203. profiles, exception = client.api_profiles()
  204. return profiles
  205. except Exception:
  206. return None
  207. def get_grouped_date(self, data, group):
  208. if group == 'week':
  209. date = datetime.datetime.strptime(
  210. '%s-%s-%s' % (data['ga_year'], data['ga_week'], '0'),
  211. '%Y-%W-%w'
  212. )
  213. elif group == 'month':
  214. date = datetime.datetime.strptime(data['ga_year'] + data['ga_month'], '%Y%m')
  215. else:
  216. date = datetime.datetime.strptime(data['ga_date'], '%Y%m%d')
  217. return date
  218. def format_grouped_date(self, data, group):
  219. date = self.get_grouped_date(data, group)
  220. if group == 'week':
  221. date = u'%s — %s' % (
  222. (date - datetime.timedelta(days=6)).strftime('%d.%m'),
  223. date.strftime('%d.%m')
  224. )
  225. elif group == 'month':
  226. date = date.strftime('%b, %Y')
  227. else:
  228. date = formats.date_format(date, 'DATE_FORMAT')
  229. return date
  230. def counter_attached(self):
  231. if self.credential is None:
  232. self.error = mark_safe(_('Please <a href="%s">attach Google account and choose Google Analytics counter</a> to start using widget') % reverse('jet-dashboard:update_module', kwargs={'pk': self.model.pk}))
  233. return False
  234. elif self.counter is None:
  235. self.error = mark_safe(_('Please <a href="%s">select Google Analytics counter</a> to start using widget') % reverse('jet-dashboard:update_module', kwargs={'pk': self.model.pk}))
  236. return False
  237. else:
  238. return True
  239. def api_ga(self, group=None):
  240. if self.counter_attached():
  241. date1 = datetime.datetime.now() - datetime.timedelta(days=self.period)
  242. date2 = datetime.datetime.now()
  243. try:
  244. client = GoogleAnalyticsClient(self.storage)
  245. result, exception = client.api_ga(self.counter, date1, date2, group)
  246. if exception is not None:
  247. raise exception
  248. return result
  249. except Exception as e:
  250. error = _('API request failed.')
  251. if isinstance(e, AccessTokenRefreshError):
  252. error += _(' Try to <a href="%s">revoke and grant access</a> again') % reverse('jet-dashboard:update_module', kwargs={'pk': self.model.pk})
  253. self.error = mark_safe(error)
  254. class GoogleAnalyticsVisitorsTotals(GoogleAnalyticsBase):
  255. """
  256. Google Analytics widget that shows total number of users, sessions and viewers for a particular period of time.
  257. Period may be following: Today, Last week, Last month, Last quarter, Last year
  258. """
  259. title = _('Google Analytics visitors totals')
  260. template = 'jet.dashboard/modules/google_analytics_visitors_totals.html'
  261. #: Which period should be displayed. Allowed values - integer of days
  262. period = None
  263. def __init__(self, title=None, period=None, **kwargs):
  264. kwargs.update({'period': period})
  265. super(GoogleAnalyticsVisitorsTotals, self).__init__(title, **kwargs)
  266. def init_with_context(self, context):
  267. result = self.api_ga()
  268. if result is not None:
  269. try:
  270. self.children.append({'title': _('users'), 'value': result['totalsForAllResults']['ga:users']})
  271. self.children.append({'title': _('sessions'), 'value': result['totalsForAllResults']['ga:sessions']})
  272. self.children.append({'title': _('views'), 'value': result['totalsForAllResults']['ga:pageviews']})
  273. except KeyError:
  274. self.error = _('Bad server response')
  275. class GoogleAnalyticsVisitorsChart(GoogleAnalyticsBase):
  276. """
  277. Google Analytics widget that shows users/sessions/viewer chart for a particular period of time.
  278. Data is grouped by day, week or month
  279. Period may be following: Today, Last week, Last month, Last quarter, Last year
  280. """
  281. title = _('Google Analytics visitors chart')
  282. template = 'jet.dashboard/modules/google_analytics_visitors_chart.html'
  283. style = 'overflow-x: auto;'
  284. #: Which period should be displayed. Allowed values - integer of days
  285. period = None
  286. #: What data should be shown. Possible values: ``ga:users``, ``ga:sessions``, ``ga:pageviews``
  287. show = None
  288. #: Sets grouping of data. Possible values: ``day``, ``week``, ``month``
  289. group = None
  290. settings_form = GoogleAnalyticsChartSettingsForm
  291. class Media:
  292. js = ('jet.dashboard/vendor/chart.js/Chart.min.js', 'jet.dashboard/dashboard_modules/google_analytics.js')
  293. def __init__(self, title=None, period=None, show=None, group=None, **kwargs):
  294. kwargs.update({'period': period, 'show': show, 'group': group})
  295. super(GoogleAnalyticsVisitorsChart, self).__init__(title, **kwargs)
  296. def settings_dict(self):
  297. settings = super(GoogleAnalyticsVisitorsChart, self).settings_dict()
  298. settings['show'] = self.show
  299. settings['group'] = self.group
  300. return settings
  301. def load_settings(self, settings):
  302. super(GoogleAnalyticsVisitorsChart, self).load_settings(settings)
  303. self.show = settings.get('show')
  304. self.group = settings.get('group')
  305. def init_with_context(self, context):
  306. result = self.api_ga(self.group)
  307. if result is not None:
  308. try:
  309. for data in result['rows']:
  310. row_data = {}
  311. i = 0
  312. for column in result['columnHeaders']:
  313. row_data[column['name'].replace(':', '_')] = data[i]
  314. i += 1
  315. date = self.get_grouped_date(row_data, self.group)
  316. self.children.append((date, row_data[self.show.replace(':', '_')]))
  317. except KeyError:
  318. self.error = _('Bad server response')
  319. class GoogleAnalyticsPeriodVisitors(GoogleAnalyticsBase):
  320. """
  321. Google Analytics widget that shows users, sessions and viewers for a particular period of time.
  322. Data is grouped by day, week or month
  323. Period may be following: Today, Last week, Last month, Last quarter, Last year
  324. """
  325. title = _('Google Analytics period visitors')
  326. template = 'jet.dashboard/modules/google_analytics_period_visitors.html'
  327. #: Which period should be displayed. Allowed values - integer of days
  328. period = None
  329. #: Sets grouping of data. Possible values: ``day``, ``week``, ``month``
  330. group = None
  331. contrast = False
  332. settings_form = GoogleAnalyticsPeriodVisitorsSettingsForm
  333. def __init__(self, title=None, period=None, group=None, **kwargs):
  334. kwargs.update({'period': period, 'group': group})
  335. super(GoogleAnalyticsPeriodVisitors, self).__init__(title, **kwargs)
  336. def settings_dict(self):
  337. settings = super(GoogleAnalyticsPeriodVisitors, self).settings_dict()
  338. settings['group'] = self.group
  339. return settings
  340. def load_settings(self, settings):
  341. super(GoogleAnalyticsPeriodVisitors, self).load_settings(settings)
  342. self.group = settings.get('group')
  343. def init_with_context(self, context):
  344. result = self.api_ga(self.group)
  345. if result is not None:
  346. try:
  347. for data in reversed(result['rows']):
  348. row_data = {}
  349. i = 0
  350. for column in result['columnHeaders']:
  351. row_data[column['name'].replace(':', '_')] = data[i]
  352. i += 1
  353. date = self.format_grouped_date(row_data, self.group)
  354. self.children.append((date, row_data))
  355. except KeyError:
  356. self.error = _('Bad server response')