yandex_metrika.py 13 KB

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