google_analytics_views.py 2.3 KB

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