yandex_metrika.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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 jet.dashboard.modules import DashboardModule
  11. from django.utils.translation import ugettext_lazy as _
  12. from django.conf import settings
  13. try:
  14. from urllib import request
  15. from urllib.parse import urlencode
  16. from urllib.error import URLError, HTTPError
  17. except ImportError:
  18. import urllib2 as request
  19. from urllib2 import URLError, HTTPError
  20. from urllib import urlencode
  21. JET_MODULE_YANDEX_METRIKA_CLIENT_ID = getattr(settings, 'JET_MODULE_YANDEX_METRIKA_CLIENT_ID', '')
  22. JET_MODULE_YANDEX_METRIKA_CLIENT_SECRET = getattr(settings, 'JET_MODULE_YANDEX_METRIKA_CLIENT_SECRET', '')
  23. class YandexMetrikaClient:
  24. OAUTH_BASE_URL = 'https://oauth.yandex.ru/'
  25. API_BASE_URL = 'https://api-metrika.yandex.ru/'
  26. CLIENT_ID = JET_MODULE_YANDEX_METRIKA_CLIENT_ID
  27. CLIENT_SECRET = JET_MODULE_YANDEX_METRIKA_CLIENT_SECRET
  28. def __init__(self, access_token=None):
  29. self.access_token = access_token
  30. def request(self, base_url, url, data=None, headers=None):
  31. url = '%s%s' % (base_url, url)
  32. if data is not None:
  33. data = urlencode(data).encode()
  34. if headers is None:
  35. headers = {}
  36. req = request.Request(url, data, headers)
  37. try:
  38. f = request.urlopen(req)
  39. result = f.read().decode()
  40. result = json.loads(result)
  41. except URLError as e:
  42. return None, e
  43. return result, None
  44. def get_oauth_authorize_url(self, state=''):
  45. return '%sauthorize' \
  46. '?response_type=code' \
  47. '&state=%s' \
  48. '&client_id=%s' % (self.OAUTH_BASE_URL, state, self.CLIENT_ID)
  49. def oauth_request(self, url, data=None):
  50. return self.request(self.OAUTH_BASE_URL, url, data)
  51. def oath_token_request(self, code):
  52. data = {
  53. 'grant_type': 'authorization_code',
  54. 'code': code,
  55. 'client_id': self.CLIENT_ID,
  56. 'client_secret': self.CLIENT_SECRET
  57. }
  58. return self.oauth_request('token', data)
  59. def api_request(self, url, data=None):
  60. headers = None
  61. if self.access_token is not None:
  62. headers = {'Authorization': 'OAuth %s' % self.access_token}
  63. return self.request(self.API_BASE_URL, url, data, headers)
  64. def api_counters_request(self):
  65. return self.api_request('counters.json')
  66. def api_stat_traffic_summary(self, counter, date1, date2, group=None):
  67. if group is None:
  68. group = 'day'
  69. return self.api_request('stat/traffic/summary.json?id=%s&date1=%s&date2=%s&group=%s' % (
  70. counter,
  71. date1.strftime('%Y%m%d'),
  72. date2.strftime('%Y%m%d'),
  73. group
  74. ))
  75. class AccessTokenWidget(Widget):
  76. module = None
  77. def render(self, name, value, attrs=None):
  78. if value and len(value) > 0:
  79. link = '<a href="%s">%s</a>' % (
  80. reverse('jet-dashboard:yandex-metrika-revoke', kwargs={'pk': self.module.model.pk}),
  81. _('Revoke access')
  82. )
  83. else:
  84. link = '<a href="%s">%s</a>' % (
  85. reverse('jet-dashboard:yandex-metrika-grant', kwargs={'pk': self.module.model.pk}),
  86. _('Grant access')
  87. )
  88. if value is None:
  89. value = ''
  90. return format_html('%s<input type="hidden" name="access_token" value="%s">' % (link, value))
  91. class YandexMetrikaSettingsForm(forms.Form):
  92. access_token = forms.CharField(label=_('Access'), widget=AccessTokenWidget)
  93. counter = forms.ChoiceField(label=_('Counter'))
  94. period = forms.ChoiceField(label=_('Statistics period'), choices=(
  95. (0, _('Today')),
  96. (6, _('Last week')),
  97. (30, _('Last month')),
  98. (31 * 3 - 1, _('Last quarter')),
  99. (364, _('Last year')),
  100. ))
  101. def set_module(self, module):
  102. self.fields['access_token'].widget.module = module
  103. self.set_counter_choices(module)
  104. def set_counter_choices(self, module):
  105. counters = module.counters()
  106. if counters is not None:
  107. self.fields['counter'].choices = (('', '-- %s --' % _('none')),)
  108. self.fields['counter'].choices.extend(map(lambda x: (x['id'], x['site']), counters))
  109. else:
  110. label = _('grant access first') if module.access_token is None else _('counters loading failed')
  111. self.fields['counter'].choices = (('', '-- %s -- ' % label),)
  112. class YandexMetrikaChartSettingsForm(YandexMetrikaSettingsForm):
  113. show = forms.ChoiceField(label=_('Show'), choices=(
  114. ('visitors', _('Visitors')),
  115. ('visits', _('Visits')),
  116. ('page_views', _('Views')),
  117. ))
  118. group = forms.ChoiceField(label=_('Group'), choices=(
  119. ('day', _('By day')),
  120. ('week', _('By week')),
  121. ('month', _('By month')),
  122. ))
  123. class YandexMetrikaPeriodVisitorsSettingsForm(YandexMetrikaSettingsForm):
  124. group = forms.ChoiceField(label=_('Group'), choices=(
  125. ('day', _('By day')),
  126. ('week', _('By week')),
  127. ('month', _('By month')),
  128. ))
  129. class YandexMetrikaBase(DashboardModule):
  130. settings_form = YandexMetrikaSettingsForm
  131. ajax_load = True
  132. contrast = True
  133. period = None
  134. access_token = None
  135. expires_in = None
  136. token_type = None
  137. counter = None
  138. error = None
  139. def settings_dict(self):
  140. return {
  141. 'period': self.period,
  142. 'access_token': self.access_token,
  143. 'expires_in': self.expires_in,
  144. 'token_type': self.token_type,
  145. 'counter': self.counter
  146. }
  147. def load_settings(self, settings):
  148. try:
  149. self.period = int(settings.get('period'))
  150. except TypeError:
  151. self.period = 0
  152. self.access_token = settings.get('access_token')
  153. self.expires_in = settings.get('expires_in')
  154. self.token_type = settings.get('token_type')
  155. self.counter = settings.get('counter')
  156. def init_with_context(self, context):
  157. raise NotImplementedError('subclasses of YandexMetrika must provide a init_with_context() method')
  158. def counters(self):
  159. client = YandexMetrikaClient(self.access_token)
  160. counters, exception = client.api_counters_request()
  161. if counters is not None:
  162. return counters['counters']
  163. else:
  164. return None
  165. def format_grouped_date(self, date, group):
  166. if group == 'week':
  167. date = u'%s — %s' % (
  168. (date - datetime.timedelta(days=7)).strftime('%d.%m'),
  169. date.strftime('%d.%m')
  170. )
  171. elif group == 'month':
  172. date = date.strftime('%b, %Y')
  173. else:
  174. date = formats.date_format(date, 'DATE_FORMAT')
  175. return date
  176. def counter_attached(self):
  177. if self.access_token is None:
  178. self.error = mark_safe(_('Please <a href="%s">attach Yandex account and choose Yandex Metrika counter</a> to start using widget') % reverse('jet-dashboard:update_module', kwargs={'pk': self.model.pk}))
  179. return False
  180. elif self.counter is None:
  181. self.error = mark_safe(_('Please <a href="%s">select Yandex Metrika counter</a> to start using widget') % reverse('jet-dashboard:update_module', kwargs={'pk': self.model.pk}))
  182. return False
  183. else:
  184. return True
  185. def api_stat_traffic_summary(self, group=None):
  186. if self.counter_attached():
  187. date1 = datetime.datetime.now() - datetime.timedelta(days=self.period)
  188. date2 = datetime.datetime.now()
  189. client = YandexMetrikaClient(self.access_token)
  190. result, exception = client.api_stat_traffic_summary(self.counter, date1, date2, group)
  191. if exception is not None:
  192. error = _('API request failed.')
  193. if isinstance(exception, HTTPError) and exception.code == 403:
  194. error += _(' Try to <a href="%s">revoke and grant access</a> again') % reverse('jet-dashboard:update_module', kwargs={'pk': self.model.pk})
  195. self.error = mark_safe(error)
  196. else:
  197. return result
  198. class YandexMetrikaVisitorsTotals(YandexMetrikaBase):
  199. title = _('Yandex Metrika visitors totals')
  200. template = 'jet.dashboard/modules/yandex_metrika_visitors_totals.html'
  201. def __init__(self, title=None, period=None, **kwargs):
  202. kwargs.update({'period': period})
  203. super(YandexMetrikaVisitorsTotals, self).__init__(title, **kwargs)
  204. def init_with_context(self, context):
  205. result = self.api_stat_traffic_summary()
  206. if result is not None:
  207. try:
  208. self.children.append({'title': _('visitors'), 'value': result['totals']['visitors']})
  209. self.children.append({'title': _('visits'), 'value': result['totals']['visits']})
  210. self.children.append({'title': _('views'), 'value': result['totals']['page_views']})
  211. except KeyError:
  212. self.error = _('Bad server response')
  213. class YandexMetrikaVisitorsChart(YandexMetrikaBase):
  214. title = _('Yandex Metrika visitors chart')
  215. template = 'jet.dashboard/modules/yandex_metrika_visitors_chart.html'
  216. style = 'overflow-x: auto;'
  217. show = None
  218. group = None
  219. settings_form = YandexMetrikaChartSettingsForm
  220. class Media:
  221. js = ('jet.dashboard/vendor/chart.js/Chart.min.js', 'jet.dashboard/dashboard_modules/yandex_metrika.js')
  222. def __init__(self, title=None, period=None, show=None, group=None, **kwargs):
  223. kwargs.update({'period': period, 'show': show, 'group': group})
  224. super(YandexMetrikaVisitorsChart, self).__init__(title, **kwargs)
  225. def settings_dict(self):
  226. settings = super(YandexMetrikaVisitorsChart, self).settings_dict()
  227. settings['show'] = self.show
  228. settings['group'] = self.group
  229. return settings
  230. def load_settings(self, settings):
  231. super(YandexMetrikaVisitorsChart, self).load_settings(settings)
  232. self.show = settings.get('show')
  233. self.group = settings.get('group')
  234. def init_with_context(self, context):
  235. result = self.api_stat_traffic_summary(self.group)
  236. if result is not None:
  237. try:
  238. for data in result['data']:
  239. date = datetime.datetime.strptime(data['date'], '%Y%m%d')
  240. key = self.show if self.show is not None else 'visitors'
  241. self.children.append((date, data[key]))
  242. except KeyError:
  243. self.error = _('Bad server response')
  244. class YandexMetrikaPeriodVisitors(YandexMetrikaBase):
  245. title = _('Yandex Metrika period visitors')
  246. template = 'jet.dashboard/modules/yandex_metrika_period_visitors.html'
  247. group = None
  248. contrast = False
  249. settings_form = YandexMetrikaPeriodVisitorsSettingsForm
  250. def __init__(self, title=None, period=None, group=None, **kwargs):
  251. kwargs.update({'period': period, 'group': group})
  252. super(YandexMetrikaPeriodVisitors, self).__init__(title, **kwargs)
  253. def settings_dict(self):
  254. settings = super(YandexMetrikaPeriodVisitors, self).settings_dict()
  255. settings['group'] = self.group
  256. return settings
  257. def load_settings(self, settings):
  258. super(YandexMetrikaPeriodVisitors, self).load_settings(settings)
  259. self.group = settings.get('group')
  260. def init_with_context(self, context):
  261. result = self.api_stat_traffic_summary(self.group)
  262. if result is not None:
  263. try:
  264. for data in reversed(result['data']):
  265. date = datetime.datetime.strptime(data['date'], '%Y%m%d')
  266. date = self.format_grouped_date(date, self.group)
  267. self.children.append((date, data))
  268. except KeyError:
  269. self.error = _('Bad server response')