google_analytics.py 14 KB

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