yandex_metrika.py 13 KB

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