views.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. # Django
  2. from django.shortcuts import render
  3. from django.contrib.auth import logout
  4. from django.template import RequestContext, loader
  5. from django.contrib.auth import authenticate, login
  6. from django.http import HttpResponse, HttpResponseRedirect
  7. from django.conf import settings
  8. from django.contrib.auth import authenticate, login, logout
  9. from django.contrib.auth.models import User
  10. from django.contrib.auth.decorators import login_required
  11. from django.views.decorators.csrf import csrf_exempt
  12. from django.http import JsonResponse
  13. # Scripts
  14. from scripts.steam import gamespulling, steamidpulling
  15. from scripts.github import *
  16. from scripts.tumblr import TumblrOauthClient
  17. from scripts.twilioapi import *
  18. from scripts.instagram import InstagramOauthClient
  19. from scripts.scraper import steamDiscounts
  20. from scripts.quandl import *
  21. from scripts.paypal import PaypalOauthClient
  22. # Python
  23. import oauth2 as oauth
  24. from rest_framework.renderers import JSONRenderer
  25. from rest_framework.parsers import JSONParser
  26. # Models
  27. from hackathon.models import Snippet, Profile
  28. from hackathon.serializers import SnippetSerializer
  29. from hackathon.forms import UserForm
  30. getTumblr = TumblrOauthClient(settings.TUMBLR_CONSUMER_KEY, settings.TUMBLR_CONSUMER_SECRET)
  31. getInstagram = InstagramOauthClient(settings.INSTAGRAM_CLIENT_ID, settings.INSTAGRAM_CLIENT_SECRET)
  32. getPaypal = PaypalOauthClient(settings.PAYPAL_CLIENT_ID, settings.PAYPAL_CLIENT_SECRET)
  33. def index(request):
  34. context = {'hello': 'world'}
  35. return render(request, 'hackathon/index.html', context)
  36. ##################
  37. # API Examples #
  38. ##################
  39. def api_examples(request):
  40. instagram_url =getInstagram.get_authorize_url()
  41. if not getTumblr.accessed:
  42. obtain_oauth_verifier = getTumblr.authorize_url()
  43. else:
  44. obtain_oauth_verifier = '/hackathon/tumblr'
  45. #obtain_oauth_verifier = getTumblr.authorize_url()
  46. context = {'title': 'API Examples Page', 'tumblr_url': obtain_oauth_verifier, 'instagram_url':instagram_url}
  47. return render(request, 'hackathon/api_examples.html', context)
  48. #################
  49. # STEAM API #
  50. #################
  51. def steam(request):
  52. #Should link to test of Steam API example.
  53. key = '231E98D442E52B87110816C3D5114A1D'
  54. SteamUN = "Marorin"
  55. steamID = steamidpulling(SteamUN, key)
  56. game = gamespulling(steamID, key)
  57. return render(request,'hackathon/steam.html', {"game": game })
  58. def steamDiscountedGames(request):
  59. data = steamDiscounts()
  60. return JsonResponse({ 'data': data })
  61. #################
  62. # FACEBOOK API #
  63. #################
  64. def facebook(request):
  65. '''A sample application that will publish a status update after going into the login process using the Javascript SDK '''
  66. yourappid = '364831617044713'
  67. return render(request, 'hackathon/facebook.html', { 'yourappid' : yourappid })
  68. #################
  69. # QUANDL API #
  70. #################
  71. def quandlDowJones(request):
  72. '''Returns JSON response about the latest dowjones index.'''
  73. APIKEY = 'fANs6ykrCdAxas7zpMz7'
  74. dowjonesdata = fetchData(APIKEY, 'https://www.quandl.com/api/v1/datasets/BCB/UDJIAD1.json?')
  75. print dowjonesdata
  76. return JsonResponse({'data': dowjonesdata})
  77. def quandlSnp500(request):
  78. '''Returns JSON response about the latest SNP 500 index.'''
  79. APIKEY = 'fANs6ykrCdAxas7zpMz7'
  80. snpdata = fetchData(APIKEY, 'https://www.quandl.com/api/v1/datasets/YAHOO/INDEX_GSPC.json?')
  81. return JsonResponse({'data': snpdata})
  82. def quandlNasdaq(request):
  83. '''Returns JSON response about the latest nasdaq index.'''
  84. APIKEY = 'fANs6ykrCdAxas7zpMz7'
  85. nasdaqdata = fetchData(APIKEY, 'https://www.quandl.com/api/v1/datasets/NASDAQOMX/COMP.json?')
  86. return JsonResponse({'data': nasdaqdata})
  87. def quandlstocks(request):
  88. APIKEY = 'fANs6ykrCdAxas7zpMz7'
  89. everyData = {}
  90. dowjonesdata = fetchData(APIKEY, 'https://www.quandl.com/api/v1/datasets/BCB/UDJIAD1.json?')
  91. everyData['dow'] = dowjonesdata
  92. snpdata = fetchData(APIKEY, 'https://www.quandl.com/api/v1/datasets/YAHOO/INDEX_GSPC.json?')
  93. everyData['snp'] = snpdata
  94. nasdaqdata = fetchData(APIKEY, 'https://www.quandl.com/api/v1/datasets/NASDAQOMX/COMP.json?')
  95. everyData['nasdaq'] = nasdaqdata
  96. return render(request, 'hackathon/quandl.html', { 'everyData': everyData })
  97. #################
  98. # GITHUB API #
  99. #################
  100. def githubUser(request):
  101. '''Returns JSON response about a specific Github User'''
  102. parsedData = {}
  103. parsedData['userData'] = getUserData(settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
  104. return JsonResponse({ 'data': parsedData })
  105. def githubTopRepositories(request):
  106. '''Returns JSON response of a User's Top Committed repositories'''
  107. parsedData = {}
  108. repositories = getUserRepositories(settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
  109. list = getTopContributedRepositories(repositories, settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
  110. filtered = filterCommits(list)
  111. parsedData['committed'] = filtered
  112. return JsonResponse({ 'data': parsedData })
  113. def githubResume(request):
  114. '''A sample application which pulls various Github data to form a Resume of sorts'''
  115. allData = {}
  116. userData = getUserData(settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
  117. repositories = getUserRepositories(settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
  118. list = getTopContributedRepositories(repositories, settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
  119. filtered = filterCommits(list)
  120. stargazers = getStarGazerCount(settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
  121. filteredStargazers = filterStarGazerCount(stargazers)
  122. forkedRepos = getForkedRepositories(settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
  123. allData['userData'] = userData
  124. allData['filteredData'] = filtered
  125. allData['filteredStargazers'] = filteredStargazers
  126. allData['forkedRepos'] = forkedRepos
  127. return render(request, 'hackathon/github.html', { 'data': allData })
  128. #################
  129. # TUMBLR API #
  130. #################
  131. def tumblr(request):
  132. ''' Tumblr api calls '''
  133. if not getTumblr.accessed:
  134. oauth_verifier = request.GET.get('oauth_verifier')
  135. getTumblr.access_token_url(oauth_verifier)
  136. if request.user not in User.objects.all():
  137. try:
  138. user_info, total_blog = getTumblr.getUserInfo()
  139. username = str(user_info['name'])+ "2"
  140. user = User.objects.get(username=username)
  141. except User.DoesNotExist:
  142. user_info, total_blog = getTumblr.getUserInfo()
  143. username = str(user_info['name'])+ "2"
  144. new_user = User.objects.create_user(username, username+'@example.com','password')
  145. new_user.save()
  146. profile =Profile()
  147. profile.user = new_user
  148. profile.oauth_token = getTumblr.oauth_token
  149. profile.oauth_secret = getTumblr.oauth_token_secret
  150. profile.save()
  151. user = authenticate(username=username, password='password')
  152. login(request, user)
  153. #get blogger twitterthecomic's blog information
  154. blog = getTumblr.getBlogInfo('twitterthecomic')
  155. #get tags that was tagged along starbucks
  156. tagged_blog = getTumblr.getTaggedInfo("starbucks")
  157. #get blog information tagged with starbucks
  158. blogontag = getTumblr.getTaggedBlog("starbucks")
  159. context = {'title': "What's up Starbucks?", 'blogData': blog, 'blogTag': tagged_blog, 'blogontag': blogontag}
  160. return render(request, 'hackathon/tumblr.html', context)
  161. ####################
  162. # INSTAGRAM API #
  163. ####################
  164. def instagram(request):
  165. code = request.GET['code']
  166. getInstagram.get_access_token(code)
  167. if request.user not in User.objects.all():
  168. try:
  169. user = User.objects.get(username=getInstagram.user_data['username'] )
  170. except User.DoesNotExist:
  171. username = getInstagram.user_data['username']
  172. new_user = User.objects.create_user(username, username+'@example.com', 'password')
  173. new_user.save()
  174. profile = Profile()
  175. profile.user = new_user
  176. profile.oauth_token = getInstagram.client_id
  177. #since instagram doesnt have oauth_secret value, using this field to temp set in access token
  178. # for JSON response
  179. profile.oauth_secret = getInstagram.access_token
  180. profile.save()
  181. user = authenticate(username=getInstagram.user_data['username'], password='password')
  182. login(request, user)
  183. search_tag = 'kitten'
  184. #return tagged objects
  185. tagged_media = getInstagram.get_tagged_media(search_tag)
  186. context = {'title': 'Instagram', 'tagged_media': tagged_media, 'search_tag': search_tag}
  187. return render(request, 'hackathon/instagram.html', context)
  188. def instagramUser(request):
  189. ''' Returns JSON response about a specific Instagram User. '''
  190. user_id = User.objects.get(username='mk200789').id
  191. access_token = Profile.objects.get(user=user_id).oauth_secret
  192. parsedData = getInstagram.get_user_info(access_token)
  193. return JsonResponse({ 'data': parsedData })
  194. def instagramUserMedia(request):
  195. ''' Returns JSON response about a specific Instagram User's Media. '''
  196. user_id = User.objects.get(username='mk200789').id
  197. access_token = Profile.objects.get(user=user_id).oauth_secret
  198. parsedData = getInstagram.get_user_media(32833691,access_token)
  199. return JsonResponse({'data': parsedData })
  200. def instagramMediaByLocation(request):
  201. if request.method == 'GET':
  202. if request.GET.items():
  203. if request.user in User.objects.all():
  204. address = request.GET.get('address_field')
  205. user_id = User.objects.get(username=request.user).id
  206. access_token = Profile.objects.get(user=user_id).oauth_secret
  207. #lat, lng = getInstagram.search_for_location(address, access_token)
  208. geocode_result = getInstagram.search_for_location(address, access_token)
  209. if geocode_result:
  210. location_ids =getInstagram.search_location_ids(geocode_result['lat'], geocode_result['lng'], access_token)
  211. media = getInstagram.search_location_media(location_ids, access_token)
  212. title = address
  213. else:
  214. title, media,location_ids, geocode_result = 'Media by location', '','', ''
  215. context = {'title': title, 'geocode_result':geocode_result, 'media':media, 'list_id':location_ids}
  216. return render(request, 'hackathon/instagram_q.html', context)
  217. ####################
  218. # PAYPAL API #
  219. ####################
  220. def paypal(request):
  221. authorization_code = request.GET['code']
  222. refresh_token = getPaypal.get_access_token(authorization_code)
  223. getPaypal.get_refresh_token(refresh_token)
  224. context = {'title':'paypal'}
  225. return render(request, 'hackathon/paypal.html', context)
  226. ##################
  227. # LINKED IN API #
  228. ##################
  229. def linkedin(request):
  230. userinfo = getUserInfo()
  231. context = {'title': 'linkedin Example','userdata': userinfo}
  232. return render(request, 'hackathon/linkedin.html', context)
  233. #########################
  234. # Snippet RESTful Model #
  235. #########################
  236. class JSONResponse(HttpResponse):
  237. """
  238. An HttpResponse that renders its content into JSON.
  239. """
  240. def __init__(self, data, **kwargs):
  241. content = JSONRenderer().render(data)
  242. kwargs['content_type'] = 'application/json'
  243. super(JSONResponse, self).__init__(content, **kwargs)
  244. @csrf_exempt
  245. def snippet_list(request):
  246. """
  247. List all code snippets, or create a new snippet.
  248. """
  249. if request.method == 'GET':
  250. snippets = Snippet.objects.all()
  251. serializer = SnippetSerializer(snippets, many=True)
  252. return JSONResponse(serializer.data)
  253. ##################
  254. # Twilio API #
  255. ##################
  256. def twilio(request):
  257. # Test credentials
  258. # sendSMS('Meow', '+13473282978', '+13473781813')
  259. if request.method == 'POST':
  260. number = request.POST.get('number')
  261. message = request.POST.get('message')
  262. sendSMS(str(message), str(number), '+13473781813')
  263. context = {'message': 'Your message has been sent successfully!'}
  264. return HttpResponseRedirect('/hackathon/api/')
  265. return render(request, 'hackathon/twilio.html')
  266. ######################
  267. # Registration Views #
  268. ######################
  269. def register(request):
  270. registered = False
  271. if request.method == 'POST':
  272. user_form = UserForm(data=request.POST)
  273. if user_form.is_valid():
  274. user = user_form.save()
  275. user.set_password(user.password)
  276. user.save()
  277. registered = True
  278. else:
  279. print user_form.errors
  280. else:
  281. user_form = UserForm()
  282. return render(request,
  283. 'hackathon/register.html',
  284. {'user_form': user_form, 'registered': registered} )
  285. def user_login(request):
  286. if request.method == 'POST':
  287. username = request.POST.get('username')
  288. password = request.POST.get('password')
  289. user = authenticate(username=username, password=password)
  290. if user:
  291. if user.is_active:
  292. login(request, user)
  293. return HttpResponseRedirect('/hackathon/')
  294. else:
  295. return HttpResponse("Your Django Hackathon account is disabled.")
  296. else:
  297. print "Invalid login details: {0}, {1}".format(username, password)
  298. return HttpResponse("Invalid login details supplied.")
  299. else:
  300. return render(request, 'hackathon/login.html', {})
  301. def user_logout(request):
  302. logout(request)
  303. return HttpResponseRedirect('/hackathon/')
  304. def instagram_login(request):
  305. instagram_url =getInstagram.get_authorize_url()
  306. return HttpResponseRedirect(instagram_url)
  307. def tumblr_login(request):
  308. tumblr_url = getTumblr.authorize_url()
  309. return HttpResponseRedirect(tumblr_url)