PageRenderTime 76ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/apps/feed_import/views.py

https://github.com/tosh/NewsBlur
Python | 167 lines | 136 code | 24 blank | 7 comment | 20 complexity | d1370afa207dab7bb032a4e9dc8b3444 MD5 | raw file
  1. import urlparse
  2. from utils import log as logging
  3. import oauth2 as oauth
  4. from django.contrib.sites.models import Site
  5. from django.http import HttpResponse, HttpResponseRedirect
  6. from django.conf import settings
  7. from django.core.urlresolvers import reverse
  8. from django.template import RequestContext
  9. from django.contrib.auth import login as login_user
  10. from django.shortcuts import render_to_response
  11. from apps.reader.forms import SignupForm
  12. from apps.reader.models import UserSubscription
  13. from apps.feed_import.models import OAuthToken, OPMLImporter, GoogleReaderImporter
  14. from utils import json_functions as json
  15. from utils.user_functions import ajax_login_required
  16. @ajax_login_required
  17. def opml_upload(request):
  18. xml_opml = None
  19. message = "OK"
  20. code = 1
  21. payload = {}
  22. if request.method == 'POST':
  23. if 'file' in request.FILES:
  24. logging.info(" ---> [%s] OPML Upload" % request.user)
  25. file = request.FILES['file']
  26. xml_opml = file.read()
  27. opml_importer = OPMLImporter(xml_opml, request.user)
  28. folders = opml_importer.process()
  29. feeds = UserSubscription.objects.filter(user=request.user).values()
  30. payload = dict(folders=folders, feeds=feeds)
  31. else:
  32. message = "Attach an .opml file."
  33. code = -1
  34. data = json.encode(dict(message=message, code=code, payload=payload))
  35. return HttpResponse(data, mimetype='text/plain')
  36. def reader_authorize(request):
  37. logging.info(" ---> [%s] Authorize Google Reader import (%s) - %s" % (
  38. request.user,
  39. request.session.session_key,
  40. request.META['REMOTE_ADDR'],
  41. ))
  42. oauth_key = settings.OAUTH_KEY
  43. oauth_secret = settings.OAUTH_SECRET
  44. scope = "http://www.google.com/reader/api"
  45. request_token_url = ("https://www.google.com/accounts/OAuthGetRequestToken?"
  46. "scope=%s&oauth_callback=http://%s%s") % (
  47. scope,
  48. Site.objects.get_current().domain,
  49. reverse('google-reader-callback'),
  50. )
  51. authorize_url = 'https://www.google.com/accounts/OAuthAuthorizeToken'
  52. # Grab request token from Google's OAuth
  53. consumer = oauth.Consumer(oauth_key, oauth_secret)
  54. client = oauth.Client(consumer)
  55. resp, content = client.request(request_token_url, "GET")
  56. request_token = dict(urlparse.parse_qsl(content))
  57. # Save request token and delete old tokens
  58. auth_token_dict = dict(request_token=request_token['oauth_token'],
  59. request_token_secret=request_token['oauth_token_secret'])
  60. if request.user.is_authenticated():
  61. OAuthToken.objects.filter(user=request.user).delete()
  62. auth_token_dict['user'] = request.user
  63. else:
  64. OAuthToken.objects.filter(session_id=request.session.session_key).delete()
  65. OAuthToken.objects.filter(remote_ip=request.META['REMOTE_ADDR']).delete()
  66. auth_token_dict['session_id'] = request.session.session_key
  67. auth_token_dict['remote_ip'] = request.META['REMOTE_ADDR']
  68. OAuthToken.objects.create(**auth_token_dict)
  69. redirect = "%s?oauth_token=%s" % (authorize_url, request_token['oauth_token'])
  70. return HttpResponseRedirect(redirect)
  71. def reader_callback(request):
  72. access_token_url = 'https://www.google.com/accounts/OAuthGetAccessToken'
  73. consumer = oauth.Consumer(settings.OAUTH_KEY, settings.OAUTH_SECRET)
  74. if request.user.is_authenticated():
  75. user_token = OAuthToken.objects.get(user=request.user)
  76. else:
  77. try:
  78. user_token = OAuthToken.objects.get(session_id=request.session.session_key)
  79. except OAuthToken.DoesNotExist:
  80. user_tokens = OAuthToken.objects.filter(remote_ip=request.META['REMOTE_ADDR']).order_by('-created_date')
  81. # logging.info("Found ip user_tokens: %s" % user_tokens)
  82. if user_tokens:
  83. user_token = user_tokens[0]
  84. user_token.session_id = request.session.session_key
  85. user_token.save()
  86. # logging.info("Google Reader request.GET: %s" % request.GET)
  87. # Authenticated in Google, so verify and fetch access tokens
  88. token = oauth.Token(user_token.request_token, user_token.request_token_secret)
  89. token.set_verifier(request.GET['oauth_verifier'])
  90. client = oauth.Client(consumer, token)
  91. resp, content = client.request(access_token_url, "POST")
  92. access_token = dict(urlparse.parse_qsl(content))
  93. # logging.info(" ---> [%s] OAuth Reader Content: %s -- %s" % (request.user, token, access_token))
  94. user_token.access_token = access_token.get('oauth_token')
  95. user_token.access_token_secret = access_token.get('oauth_token_secret')
  96. user_token.save()
  97. # Fetch imported feeds on next page load
  98. request.session['import_from_google_reader'] = True
  99. logging.info(" ---> [%s] Finishing Google Reader import" % request.user)
  100. if request.user.is_authenticated():
  101. return HttpResponseRedirect(reverse('index'))
  102. return HttpResponseRedirect(reverse('import-signup'))
  103. @json.json_view
  104. def import_from_google_reader(request):
  105. scope = "http://www.google.com/reader/api"
  106. sub_url = "%s/0/subscription/list" % scope
  107. code = 0
  108. if request.user.is_authenticated():
  109. user_tokens = OAuthToken.objects.filter(user=request.user)
  110. if user_tokens.count():
  111. user_token = user_tokens[0]
  112. consumer = oauth.Consumer(settings.OAUTH_KEY, settings.OAUTH_SECRET)
  113. token = oauth.Token(user_token.access_token, user_token.access_token_secret)
  114. client = oauth.Client(consumer, token)
  115. resp, content = client.request(sub_url, 'GET')
  116. reader_importer = GoogleReaderImporter(content, request.user)
  117. reader_importer.process()
  118. code = 1
  119. if 'import_from_google_reader' in request.session:
  120. del request.session['import_from_google_reader']
  121. return dict(code=code)
  122. def import_signup(request):
  123. if request.method == "POST":
  124. signup_form = SignupForm(prefix='signup', data=request.POST)
  125. if signup_form.is_valid():
  126. new_user = signup_form.save()
  127. try:
  128. user_token = OAuthToken.objects.get(session_id=request.session.session_key)
  129. except OAuthToken.DoesNotExist:
  130. user_tokens = OAuthToken.objects.filter(remote_ip=request.META['REMOTE_ADDR']).order_by('-created_date')
  131. if user_tokens:
  132. user_token = user_tokens[0]
  133. user_token.session_id = request.session.session_key
  134. user_token.save()
  135. user_token.user = new_user
  136. user_token.save()
  137. login_user(request, new_user)
  138. return HttpResponseRedirect(reverse('index'))
  139. else:
  140. signup_form = SignupForm(prefix='signup')
  141. return render_to_response('import/signup.xhtml', {
  142. 'signup_form': signup_form,
  143. }, context_instance=RequestContext(request))