google_analytics_views.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. try:
  2. from django.core.urlresolvers import reverse
  3. except ImportError: # Django 1.11
  4. from django.urls import reverse
  5. from django.conf.urls import url
  6. from django.contrib import messages
  7. from django.shortcuts import redirect
  8. from httplib2 import ServerNotFoundError
  9. from jet.dashboard.dashboard_modules.google_analytics import GoogleAnalyticsClient, ModuleCredentialStorage
  10. from jet.dashboard.models import UserDashboardModule
  11. from jet.dashboard import dashboard
  12. from django.http import HttpResponse
  13. from oauth2client.client import FlowExchangeError
  14. from django.utils.translation import ugettext_lazy as _
  15. def google_analytics_grant_view(request, pk):
  16. redirect_uri = request.build_absolute_uri(reverse('jet-dashboard:google-analytics-callback'))
  17. client = GoogleAnalyticsClient(redirect_uri=redirect_uri)
  18. return redirect(client.get_oauth_authorize_url(pk))
  19. def google_analytics_revoke_view(request, pk):
  20. try:
  21. module = UserDashboardModule.objects.get(pk=pk)
  22. ModuleCredentialStorage(module).delete()
  23. return redirect(reverse('jet-dashboard:update_module', kwargs={'pk': module.pk}))
  24. except UserDashboardModule.DoesNotExist:
  25. return HttpResponse(_('Module not found'))
  26. def google_analytics_callback_view(request):
  27. module = None
  28. try:
  29. state = request.GET['state']
  30. module = UserDashboardModule.objects.get(pk=state)
  31. redirect_uri = request.build_absolute_uri(reverse('jet-dashboard:google-analytics-callback'))
  32. client = GoogleAnalyticsClient(redirect_uri=redirect_uri)
  33. client.set_credential_from_request(request)
  34. ModuleCredentialStorage(module).put(client.credential)
  35. except (FlowExchangeError, ValueError, ServerNotFoundError):
  36. messages.error(request, _('API request failed.'))
  37. except KeyError:
  38. return HttpResponse(_('Bad arguments'))
  39. except UserDashboardModule.DoesNotExist:
  40. return HttpResponse(_('Module not found'))
  41. return redirect(reverse('jet-dashboard:update_module', kwargs={'pk': module.pk}))
  42. dashboard.urls.register_urls([
  43. url(r'^google-analytics/grant/(?P<pk>\d+)/$', google_analytics_grant_view, name='google-analytics-grant'),
  44. url(r'^google-analytics/revoke/(?P<pk>\d+)/$', google_analytics_revoke_view, name='google-analytics-revoke'),
  45. url(r'^google-analytics/callback/', google_analytics_callback_view, name='google-analytics-callback'),
  46. ])