views.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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 *
  19. from scripts.scraper import steamDiscounts
  20. from scripts.quandl import *
  21. from scripts.twitter import TwitterOauthClient
  22. from scripts.nytimes import *
  23. from scripts.meetup import *
  24. from scripts.linkedin import LinkedinOauthClient
  25. from scripts.yelp import requestData
  26. # Python
  27. import oauth2 as oauth
  28. import simplejson as json
  29. from rest_framework.renderers import JSONRenderer
  30. from rest_framework.parsers import JSONParser
  31. # Models
  32. from hackathon.models import Snippet, Profile, InstagramProfile, TwitterProfile, MeetupToken, GithubProfile, LinkedinProfile
  33. from hackathon.serializers import SnippetSerializer
  34. from hackathon.forms import UserForm
  35. profile_track = None
  36. getTumblr = TumblrOauthClient(settings.TUMBLR_CONSUMER_KEY, settings.TUMBLR_CONSUMER_SECRET)
  37. getInstagram = InstagramOauthClient(settings.INSTAGRAM_CLIENT_ID, settings.INSTAGRAM_CLIENT_SECRET)
  38. getTwitter = TwitterOauthClient(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET, settings.TWITTER_ACCESS_TOKEN, settings.TWITTER_ACCESS_TOKEN_SECRET)
  39. getGithub = GithubOauthClient('2a11ce63ea7952d21f02', '7e20f82a34698fb33fc837186e96b12aaca2618d')
  40. getLinkedIn = LinkedinOauthClient(settings.LINKEDIN_CLIENT_ID, settings.LINKEDIN_CLIENT_SECRET)
  41. def index(request):
  42. print "index: " + str(request.user)
  43. if not request.user.is_active:
  44. if request.GET.items():
  45. if profile_track == 'github':
  46. code = request.GET['code']
  47. getGithub.get_access_token(code)
  48. getGithub.getUserInfo()
  49. print getGithub.access_token
  50. try:
  51. user = User.objects.get(username = getGithub.username + '_github')
  52. except User.DoesNotExist:
  53. username = getGithub.username + '_github'
  54. new_user = User.objects.create_user(username, username+'@madewithgithub.com', 'password')
  55. new_user.save()
  56. try:
  57. profile = GithubProfile.objects.get(user = new_user.id)
  58. profile.access_token = getGithub.access_token
  59. except GithubProfile.DoesNotExist:
  60. profile = GithubProfile(user=new_user, access_token=getGithub.access_token, scopes=getGithub.scopes ,github_user=getGithub.username)
  61. profile.save()
  62. #profile = GithubProfile(user=new_user, access_token=getGithub.access_token, scopes=getGithub.scopes ,github_user=getGithub.username)
  63. #profile.save()
  64. user = authenticate(username=getGithub.username+'_github', password='password')
  65. login(request, user)
  66. elif profile_track == 'twitter':
  67. oauth_verifier = request.GET['oauth_verifier']
  68. getTwitter.get_access_token_url(oauth_verifier)
  69. try:
  70. user = User.objects.get(username = getTwitter.username + '_twitter')#(username=getTwitter.username)
  71. except User.DoesNotExist:
  72. username = getTwitter.username + '_twitter'
  73. new_user = User.objects.create_user(username, username+'@madewithtwitter.com', 'password')
  74. new_user.save()
  75. profile = TwitterProfile(user = new_user,oauth_token = getTwitter.oauth_token, oauth_token_secret= getTwitter.oauth_token_secret, twitter_user=getTwitter.username)
  76. profile.save()
  77. user = authenticate(username=getTwitter.username+'_twitter', password='password')
  78. login(request, user)
  79. elif profile_track == 'instagram':
  80. code = request.GET['code']
  81. getInstagram.get_access_token(code)
  82. try:
  83. user = User.objects.get(username=getInstagram.user_data['username']+'_instagram')
  84. except User.DoesNotExist:
  85. username = getInstagram.user_data['username']+'_instagram'
  86. new_user = User.objects.create_user(username, username+'@madewithinstagram.com', 'password')
  87. new_user.save()
  88. profile = InstagramProfile(user = new_user, access_token = getInstagram.access_token, instagram_user=getInstagram.user_data['username'])
  89. profile.save()
  90. user = authenticate(username=getInstagram.user_data['username']+'_instagram' , password='password')
  91. login(request, user)
  92. elif profile_track == 'linkedin':
  93. code = request.GET['code']
  94. getLinkedIn.get_access_token(code)
  95. getLinkedIn.getUserInfo()
  96. try:
  97. user = User.objects.get(username=getLinkedIn.user_id+'_linkedin')
  98. except User.DoesNotExist:
  99. username = getLinkedIn.user_id+'_linkedin'
  100. new_user = User.objects.create_user(username, username+'@madwithlinkedin.com', 'password')
  101. new_user.save()
  102. try:
  103. profile =LinkedinProfile.objects.get(user = new_user.id)
  104. profile.access_token = LinkedinProfile.access_token
  105. except LinkedinProfile.DoesNotExist:
  106. profile = LinkedinProfile(user=new_user, access_token=getLinkedIn.access_token, linkedin_user=getLinkedIn.user_id)
  107. profile.save()
  108. user = authenticate(username=getLinkedIn.user_id+'_linkedin', password='password')
  109. login(request, user)
  110. else:
  111. if request.GET.items():
  112. user = User.objects.get(username = request.user.username)
  113. if profile_track == 'github':
  114. code = request.GET['code']
  115. getGithub.get_access_token(code)
  116. getGithub.getUserInfo()
  117. try:
  118. githubUser = GithubProfile.objects.get(user=user.id)
  119. except GithubProfile.DoesNotExist:
  120. profile = GithubProfile(user=new_user, access_token=getGithub.access_token, scopes=getGithub.scopes ,github_user=getGithub.username)
  121. profile.save()
  122. elif profile_track == 'twitter':
  123. oauth_verifier = request.GET['oauth_verifier']
  124. getTwitter.get_access_token_url(oauth_verifier)
  125. try:
  126. twitterUser = TwitterProfile.objects.get(user = user.id)
  127. except TwitterProfile.DoesNotExist:
  128. profile = TwitterProfile(user = user, oauth_token = getTwitter.oauth_token, oauth_token_secret= getTwitter.oauth_token_secret, twitter_user=getTwitter.username)
  129. profile.save()
  130. elif profile_track == 'instagram':
  131. code = request.GET['code']
  132. getInstagram.get_access_token(code)
  133. try:
  134. instagramUser = InstagramProfile.objects.get(user= user.id)
  135. except InstagramProfile.DoesNotExist:
  136. profile = InstagramProfile(user = user, access_token = getInstagram.access_token, instagram_user=getInstagram.user_data['username'])
  137. profile.save()
  138. elif profile_track == 'linkedin':
  139. code = request.GET['code']
  140. getLinkedIn.get_access_token(code)
  141. getLinkedIn.getUserInfo()
  142. try:
  143. linkedinUser = LinkedinProfile.objects.get(user=user.id)
  144. except LinkedinProfile.DoesNotExist:
  145. profile = LinkedinProfile(user = user, access_token = getLinkedIn.access_token, linkedin_user=getLinkedIn.user_id)
  146. profile.save()
  147. context = {'hello': 'world'}
  148. return render(request, 'hackathon/index.html', context)
  149. ##################
  150. # API Examples #
  151. ##################
  152. def api_examples(request):
  153. instagram_url = getInstagram.get_authorize_url()
  154. if not getTumblr.accessed:
  155. obtain_oauth_verifier = getTumblr.authorize_url()
  156. else:
  157. obtain_oauth_verifier = '/hackathon/tumblr'
  158. #obtain_oauth_verifier = getTumblr.authorize_url()
  159. context = {'title': 'API Examples Page', 'tumblr_url': obtain_oauth_verifier, 'instagram_url':instagram_url}
  160. return render(request, 'hackathon/api_examples.html', context)
  161. #################
  162. # STEAM API #
  163. #################
  164. def steam(request):
  165. #Should link to test of Steam API example.
  166. key = '231E98D442E52B87110816C3D5114A1D'
  167. SteamUN = "Marorin"
  168. steamID = steamidpulling(SteamUN, key)
  169. game = gamespulling(steamID, key)
  170. return render(request,'hackathon/steam.html', {"game": game })
  171. def steamDiscountedGames(request):
  172. data = steamDiscounts()
  173. return JsonResponse({ 'data': data })
  174. #################
  175. # FACEBOOK API #
  176. #################
  177. def facebook(request):
  178. '''A sample application that will publish a status update after going into the login process using the Javascript SDK '''
  179. yourappid = '364831617044713'
  180. return render(request, 'hackathon/facebook.html', { 'yourappid' : yourappid })
  181. #################
  182. # YELP API #
  183. #################
  184. def yelp(request):
  185. data = {}
  186. if request.method == 'POST':
  187. location = request.POST.get('location')
  188. data = requestData(location)
  189. return render(request, 'hackathon/yelp.html', { 'data': data })
  190. #################
  191. # MEETUP API #
  192. #################
  193. def meetup(request):
  194. REDIRECT_URI = 'http://127.0.0.1:8000/hackathon/meetupToken'
  195. AUTHORIZE_URL = 'https://secure.meetup.com/oauth2/authorize?client_id=' + settings.MEETUP_CONSUMER_KEY + '&response_type=code' + '&redirect_uri=' + REDIRECT_URI
  196. return HttpResponseRedirect(AUTHORIZE_URL)
  197. def meetupToken(request):
  198. # print request.GET.get('code')
  199. access_token_url = 'https://secure.meetup.com/oauth2/access?'
  200. REDIRECT_URI = 'http://127.0.0.1:8000/hackathon/meetupToken'
  201. url = access_token_url + 'client_id=' + settings.MEETUP_CONSUMER_KEY + '&client_secret=' + settings.MEETUP_CONSUMER_SECRET + '&grant_type=authorization_code' + '&redirect_uri=' + REDIRECT_URI + '&code=' + request.GET.get('code')
  202. response = requests.post(url)
  203. access_token = json.loads(response.content)['access_token']
  204. # print access_token
  205. #if not MeetupToken.objects.all()[0]:
  206. if not MeetupToken.objects.all().exists():
  207. meetupToken = MeetupToken(access_token = access_token)
  208. meetupToken.save()
  209. else:
  210. meetupToken = MeetupToken(access_token = access_token)
  211. MeetupToken.objects.all()[0] = meetupToken
  212. return HttpResponseRedirect('http://127.0.0.1:8000/hackathon/meetupUser/')
  213. def meetupUser(request):
  214. if not MeetupToken.objects.all().exists():
  215. return HttpResponseRedirect('http://127.0.0.1:8000/hackathon/meetup')
  216. access_token = MeetupToken.objects.all()[0]
  217. meetupData = {}
  218. userData = retrieveUserData('https://api.meetup.com/2/member/self/?access_token=' + str(access_token))
  219. meetupData['userData'] = userData
  220. return render(request, 'hackathon/meetup.html', { 'data': meetupData })
  221. #################
  222. # QUANDL API #
  223. #################
  224. def quandlDowJones(request):
  225. '''Returns JSON response about the latest dowjones index.'''
  226. dowjonesdata = fetchData(settings.QUANDLAPIKEY, 'https://www.quandl.com/api/v1/datasets/BCB/UDJIAD1.json?')
  227. print dowjonesdata
  228. return JsonResponse({'data': dowjonesdata})
  229. def quandlSnp500(request):
  230. '''Returns JSON response about the latest SNP 500 index.'''
  231. snpdata = fetchData(settings.QUANDLAPIKEY, 'https://www.quandl.com/api/v1/datasets/YAHOO/INDEX_GSPC.json?')
  232. return JsonResponse({'data': snpdata})
  233. def quandlNasdaq(request):
  234. '''Returns JSON response about the latest nasdaq index.'''
  235. nasdaqdata = fetchData(settings.QUANDLAPIKEY, 'https://www.quandl.com/api/v1/datasets/NASDAQOMX/COMP.json?')
  236. return JsonResponse({'data': nasdaqdata})
  237. def quandlapple(request):
  238. '''Returns JSON response about the latest apple stock.'''
  239. appledata = fetchstockData(settings.QUANDLAPIKEY, 'https://www.quandl.com/api/v1/datasets/GOOG/NASDAQ_AAPL.json')
  240. return JsonResponse({'data': appledata})
  241. def quandlNasdaqdiff(request):
  242. '''Returns JSON response about the latest nasdaq index.'''
  243. nasdaqdata = rdiffData(settings.QUANDLAPIKEY, 'https://www.quandl.com/api/v1/datasets/NASDAQOMX/COMP.json?')
  244. return JsonResponse({'data': nasdaqdata})
  245. def quandlSnp500diff(request):
  246. '''Returns JSON response about the latest SNP 500 index.'''
  247. snpdata = rdiffData(settings.QUANDLAPIKEY, 'https://www.quandl.com/api/v1/datasets/YAHOO/INDEX_GSPC.json?')
  248. return JsonResponse({'data': snpdata})
  249. def quandlDowJonesdiff(request):
  250. '''Returns JSON response about the latest dowjones index.'''
  251. dowjonesdata = rdiffData(settings.QUANDLAPIKEY, 'https://www.quandl.com/api/v1/datasets/BCB/UDJIAD1.json?')
  252. return JsonResponse({'data': dowjonesdata})
  253. def quandlapplediff(request):
  254. '''Returns JSON response about the latest apple stock.'''
  255. appledata = rdiffData(settings.QUANDLAPIKEY, 'https://www.quandl.com/api/v1/datasets/GOOG/NASDAQ_AAPL.json')
  256. return JsonResponse({'data': appledata})
  257. def quandlstocks(request):
  258. everyData = {}
  259. dowjonesdata = fetchData(settings.QUANDLAPIKEY, 'https://www.quandl.com/api/v1/datasets/BCB/UDJIAD1.json?')
  260. everyData['dow'] = dowjonesdata
  261. everyData['dowdiff'] = rdiffData(settings.QUANDLAPIKEY, 'https://www.quandl.com/api/v1/datasets/BCB/UDJIAD1.json?')
  262. snpdata = fetchData(settings.QUANDLAPIKEY, 'https://www.quandl.com/api/v1/datasets/YAHOO/INDEX_GSPC.json?')
  263. everyData['snp'] = snpdata
  264. everyData['snpdiff'] = rdiffData(settings.QUANDLAPIKEY, 'https://www.quandl.com/api/v1/datasets/YAHOO/INDEX_GSPC.json?')
  265. nasdaqdata = fetchData(settings.QUANDLAPIKEY, 'https://www.quandl.com/api/v1/datasets/NASDAQOMX/COMP.json?')
  266. everyData['nasdaq'] = nasdaqdata
  267. everyData['nasdaqdiff'] = rdiffData(settings.QUANDLAPIKEY, 'https://www.quandl.com/api/v1/datasets/NASDAQOMX/COMP.json?')
  268. everyData['apple'] = fetchstockData(settings.QUANDLAPIKEY, 'https://www.quandl.com/api/v1/datasets/GOOG/NASDAQ_AAPL.json')
  269. everyData['applediff'] = rdiffData(settings.QUANDLAPIKEY, 'https://www.quandl.com/api/v1/datasets/GOOG/NASDAQ_AAPL.json')
  270. return render(request, 'hackathon/quandl.html', { 'everyData': everyData })
  271. #################
  272. # NYTIMES API #
  273. #################
  274. def nytimespop(request):
  275. '''Returns JSON response about the most viewed articles for the last 24 hours.'''
  276. popdata = fetcharticle(settings.POPAPIKEY, 'http://api.nytimes.com/svc/mostpopular/v2/mostviewed/all-sections/1.json?')
  277. return JSONResponse({'data': popdata})
  278. def nytimestop(request):
  279. '''Returns JSON response about the articles located in the homepage'''
  280. topdata = fetcharticle(settings.TOPAPIKEY, 'http://api.nytimes.com/svc/topstories/v1/home.json?')
  281. return JSONResponse({'data': topdata})
  282. def nytimesarticles(request):
  283. everyData = {}
  284. popdata = fetcharticle(settings.POPAPIKEY, 'http://api.nytimes.com/svc/mostpopular/v2/mostviewed/all-sections/1.json?')
  285. topdata = topdata = fetcharticle(settings.TOPAPIKEY, 'http://api.nytimes.com/svc/topstories/v1/home.json?')
  286. everyData['top'] = topdata
  287. everyData['pop'] = popdata
  288. return render(request, 'hackathon/nytimes.html', { 'everyData': everyData })
  289. #################
  290. # GITHUB API #
  291. #################
  292. def githubUser(request):
  293. '''Returns Github Profile data for a specific user.'''
  294. parsedData = {}
  295. if request.method == 'POST':
  296. user = request.POST.get('user')
  297. parsedData['userData'] = getUserData(user, settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
  298. return render(request, 'hackathon/github.html', {'data': parsedData})
  299. # return JsonResponse({ 'data': parsedData })
  300. def githubTopRepositories(request):
  301. '''Returns Top Commited Repositories for a specific Github User'''
  302. parsedData = {}
  303. if request.method == 'POST':
  304. user = request.POST.get('user')
  305. repositories = getUserRepositories(user, settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
  306. list = getTopContributedRepositories(user, repositories, settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
  307. filtered = filterCommits(list)
  308. parsedData['committed'] = filtered
  309. print parsedData
  310. return render(request, 'hackathon/githubTopRepositories.html', {'data': parsedData})
  311. # return JsonResponse({ 'data': parsedData })
  312. def githubResume(request):
  313. '''A sample application which pulls various Github data to form a Resume of sorts'''
  314. allData = {}
  315. userData = getUserData('DrkSephy', settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
  316. repositories = getUserRepositories('DrkSephy', settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
  317. list = getTopContributedRepositories('DrkSephy', repositories, settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
  318. filtered = filterCommits(list)
  319. stargazers = getStarGazerCount('DrkSephy', settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
  320. filteredStargazers = filterStarGazerCount(stargazers)
  321. forkedRepos = getForkedRepositories('DrkSephy', settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET)
  322. allData['userData'] = userData
  323. allData['filteredData'] = filtered
  324. allData['filteredStargazers'] = filteredStargazers
  325. allData['forkedRepos'] = forkedRepos
  326. return render(request, 'hackathon/githubResume.html', { 'data': allData })
  327. #################
  328. # TUMBLR API #
  329. #################
  330. def tumblr(request):
  331. ''' Tumblr api calls '''
  332. if not getTumblr.accessed:
  333. oauth_verifier = request.GET.get('oauth_verifier')
  334. getTumblr.access_token_url(oauth_verifier)
  335. if request.user not in User.objects.all():
  336. try:
  337. user_info, total_blog = getTumblr.getUserInfo()
  338. username = str(user_info['name'])+ "2"
  339. user = User.objects.get(username=username)
  340. except User.DoesNotExist:
  341. user_info, total_blog = getTumblr.getUserInfo()
  342. username = str(user_info['name'])+ "2"
  343. new_user = User.objects.create_user(username, username+'@tumblr.com','password')
  344. new_user.save()
  345. profile =Profile()
  346. profile.user = new_user
  347. profile.oauth_token = getTumblr.oauth_token
  348. profile.oauth_secret = getTumblr.oauth_token_secret
  349. profile.save()
  350. user = authenticate(username=username, password='password')
  351. login(request, user)
  352. #get blogger twitterthecomic's blog information
  353. blog = getTumblr.getBlogInfo('twitterthecomic')
  354. #get tags that was tagged along starbucks
  355. tagged_blog = getTumblr.getTaggedInfo("starbucks")
  356. #get blog information tagged with starbucks
  357. blogontag = getTumblr.getTaggedBlog("starbucks")
  358. context = {'title': "What's up Starbucks?", 'blogData': blog, 'blogTag': tagged_blog, 'blogontag': blogontag}
  359. return render(request, 'hackathon/tumblr.html', context)
  360. ####################
  361. # INSTAGRAM API #
  362. ####################
  363. def instagram(request):
  364. print getInstagram.is_authorized
  365. if getInstagram.is_authorized:
  366. if request.method == 'GET':
  367. if request.GET.items():
  368. instagram_tag = request.GET.get('instagram_tag')
  369. instagramUser = InstagramProfile.objects.get(user = request.user)
  370. tagged_media = getTaggedMedia(instagram_tag, instagramUser.access_token)
  371. else:
  372. instagram_tag, tagged_media = '', ''
  373. else:
  374. global profile_track
  375. profile_track = 'instagram'
  376. instagram_url =getInstagram.get_authorize_url()
  377. return HttpResponseRedirect(instagram_url)
  378. context = {'title': 'Instagram', 'tagged_media': tagged_media, 'search_tag': instagram_tag}
  379. return render(request, 'hackathon/instagram.html', context)
  380. def instagramUser(request):
  381. ''' Returns JSON response about a specific Instagram User. '''
  382. access_token = InstagramProfile.objects.get(instagram_user='mk200789').access_token
  383. parsedData = getUserInfo(access_token)
  384. return JsonResponse({ 'data': parsedData })
  385. def instagramUserMedia(request):
  386. ''' Returns JSON response about a specific Instagram User's Media. '''
  387. access_token = InstagramProfile.objects.get(instagram_user='mk200789').access_token
  388. parsedData = getUserMedia(32833691, access_token)
  389. return JsonResponse({'data': parsedData })
  390. def instagramMediaByLocation(request):
  391. print request.user
  392. if request.method == 'GET':
  393. if request.GET.items():
  394. #check if user has a User profile
  395. if request.user in User.objects.all():
  396. #check if user has an Instagram profile
  397. user = User.objects.get(username=request.user)
  398. #if user has an Instagram profile, query the search
  399. if InstagramProfile.objects.all().filter(user=user.id):
  400. address = request.GET.get('address_field')
  401. access_token = InstagramProfile.objects.get(user=user.id).access_token
  402. geocode_result = searchForLocation(address)
  403. if geocode_result:
  404. location_ids = searchLocationIds(geocode_result['lat'], geocode_result['lng'], access_token)
  405. media = searchLocationMedia(location_ids, access_token)
  406. title = address
  407. err_msg = ''
  408. else:
  409. title, media, err_msg, location_ids, geocode_result = 'Media by location','', str(request.user)+ ' does not have an InstagramProfile','', ''
  410. else:
  411. title, media, err_msg, location_ids, geocode_result = 'Media by location', '','', '', ''
  412. context = {'title': title, 'geocode_result':geocode_result, 'media':media, 'list_id':location_ids, 'err_msg': err_msg}
  413. return render(request, 'hackathon/instagram_q.html', context)
  414. ####################
  415. # TWITTER API #
  416. ####################
  417. def twitter(request):
  418. if getTwitter.is_authorized:
  419. value = getTwitter.get_trends_available(settings.YAHOO_CONSUMER_KEY)
  420. else:
  421. global profile_track
  422. profile_track = 'twitter'
  423. twitter_url = getTwitter.get_authorize_url()
  424. return HttpResponseRedirect(twitter_url)
  425. context ={'title': 'twitter', 'value': value}
  426. return render(request, 'hackathon/twitter.html', context)
  427. def twitterTweets(request):
  428. print getTwitter.is_authorized
  429. if getTwitter.is_authorized:
  430. #content = getTwitter.get_tweets()
  431. if request.method == 'GET':
  432. if request.GET.items():
  433. tweets = request.GET.get('tweets')
  434. content, jsonlist = getTwitter.get_tweets(tweets)
  435. else:
  436. content, jsonlist = '', ''
  437. else:
  438. global profile_track
  439. profile_track = 'twitter'
  440. twitter_url = getTwitter.get_authorize_url()
  441. return HttpResponseRedirect(twitter_url)
  442. context ={'title': 'twitter tweet', 'content': content, 'data': jsonlist}
  443. return render(request, 'hackathon/twitter_tweet.html', context)
  444. ##################
  445. # LINKEDIN API #
  446. ##################
  447. def linkedin(request):
  448. if getLinkedIn.is_authorized:
  449. content = getLinkedIn.getUserInfo()
  450. else:
  451. global profile_track
  452. profile_track = 'linkedin'
  453. linkedin_url = getLinkedIn.get_authorize_url()
  454. return HttpResponseRedirect(linkedin_url)
  455. context = {'title': 'linkedin example', 'content': content}
  456. return render(request, 'hackathon/linkedin.html', context)
  457. #########################
  458. # Snippet RESTful Model #
  459. #########################
  460. class JSONResponse(HttpResponse):
  461. """
  462. An HttpResponse that renders its content into JSON.
  463. """
  464. def __init__(self, data, **kwargs):
  465. content = JSONRenderer().render(data)
  466. kwargs['content_type'] = 'application/json'
  467. super(JSONResponse, self).__init__(content, **kwargs)
  468. @csrf_exempt
  469. def snippet_list(request):
  470. """
  471. List all code snippets, or create a new snippet.
  472. """
  473. if request.method == 'GET':
  474. snippets = Snippet.objects.all()
  475. serializer = SnippetSerializer(snippets, many=True)
  476. return JSONResponse(serializer.data)
  477. ##################
  478. # Twilio API #
  479. ##################
  480. def twilio(request):
  481. if request.method == 'POST':
  482. number = request.POST.get('number')
  483. message = request.POST.get('message')
  484. sendSMS(str(message), str(number), '+13473781813')
  485. context = {'message': 'Your message has been sent successfully!'}
  486. return HttpResponseRedirect('/hackathon/api/')
  487. return render(request, 'hackathon/twilio.html')
  488. ######################
  489. # Registration Views #
  490. ######################
  491. def register(request):
  492. registered = False
  493. if request.method == 'POST':
  494. user_form = UserForm(data=request.POST)
  495. if user_form.is_valid():
  496. user = user_form.save()
  497. user.set_password(user.password)
  498. user.save()
  499. registered = True
  500. else:
  501. print user_form.errors
  502. else:
  503. user_form = UserForm()
  504. return render(request,
  505. 'hackathon/register.html',
  506. {'user_form': user_form, 'registered': registered} )
  507. def user_login(request):
  508. if request.method == 'POST':
  509. username = request.POST.get('username')
  510. password = request.POST.get('password')
  511. user = authenticate(username=username, password=password)
  512. if user:
  513. if user.is_active:
  514. login(request, user)
  515. return HttpResponseRedirect('/hackathon/')
  516. else:
  517. return HttpResponse("Your Django Hackathon account is disabled.")
  518. else:
  519. print "Invalid login details: {0}, {1}".format(username, password)
  520. return HttpResponse("Invalid login details supplied.")
  521. else:
  522. return render(request, 'hackathon/login.html', {})
  523. def user_logout(request):
  524. logout(request)
  525. return HttpResponseRedirect('/hackathon/')
  526. def instagram_login(request):
  527. global profile_track
  528. profile_track = 'instagram'
  529. instagram_url = getInstagram.get_authorize_url()
  530. return HttpResponseRedirect(instagram_url)
  531. def tumblr_login(request):
  532. global profile_track
  533. profile_track = 'tumblr'
  534. tumblr_url = getTumblr.authorize_url()
  535. return HttpResponseRedirect(tumblr_url)
  536. def twitter_login(request):
  537. global profile_track
  538. profile_track = 'twitter'
  539. twitter_url = getTwitter.get_authorize_url()
  540. return HttpResponseRedirect(twitter_url)
  541. def github_login(request):
  542. global profile_track
  543. profile_track = 'github'
  544. github_url = getGithub.get_authorize_url()
  545. return HttpResponseRedirect(github_url)
  546. def linkedin_login(request):
  547. global profile_track
  548. profile_track = 'linkedin'
  549. linkedin_url = getLinkedIn.get_authorize_url()
  550. return HttpResponseRedirect(linkedin_url)