Преглед изворни кода

twitter and instagram login redirect-uri to index,changed methods for retrieving data is called in index

mk200789 пре 10 година
родитељ
комит
911a755302

+ 4 - 1
hackathon_starter/hackathon/admin.py

@@ -2,8 +2,11 @@ from django.contrib import admin
 from hackathon.models import UserProfile, Profile, InstagramProfile, TwitterProfile
 
 # Register your models here.
+class TwitterProfileAdmin(admin.ModelAdmin):
+	list_display = ('user','twitter_user')
+
 admin.site.register(UserProfile)
 admin.site.register(Profile)
 admin.site.register(InstagramProfile)
-admin.site.register(TwitterProfile)
+admin.site.register(TwitterProfile, TwitterProfileAdmin)
 

+ 144 - 134
hackathon_starter/hackathon/scripts/instagram.py

@@ -22,6 +22,7 @@ class InstagramOauthClient(object):
 
     access_token = None
     user_data = None
+    is_authorized = False
 
     def __init__(self, client_id, client_secret):
         '''
@@ -46,8 +47,9 @@ class InstagramOauthClient(object):
                 - The authorization url.
         '''
 
-        redirectUri = '&redirect_uri=http://localhost:8000/hackathon/instagram&response_type=code'
+        redirectUri = '&redirect_uri=http://127.0.0.1:8000/hackathon/&response_type=code'
         authURL = AUTHORIZATION_URL + self.client_id + redirectUri
+        #print authURL
         return authURL
 
     def get_access_token(self, code):
@@ -64,7 +66,7 @@ class InstagramOauthClient(object):
             'client_id' : self.client_id,
             'client_secret' : self.client_secret,
             'grant_type' : 'authorization_code',
-            'redirect_uri' : 'http://localhost:8000/hackathon/instagram',
+            'redirect_uri' : 'http://127.0.0.1:8000/hackathon/',
             'code' : code}
 
         authSettingUrl = urllib.urlencode(authSetting)
@@ -73,166 +75,174 @@ class InstagramOauthClient(object):
         jsonlist = json.load(content)
         self.access_token = jsonlist['access_token']
         self.user_data = jsonlist['user']
+        self.is_authorized = True
 
 
-    def get_tagged_media(self, tag):
-        '''
-        Get recent tagged media.
 
-        Parameters:
-            tag: String
-                - The tag used to search the most recent media that's tagged with it.
 
-        Returns:
-            data: Dictionary
-                - A dictionary containing recent tagged 120 media
-                  counts data pertaining to each media.
-        '''
 
-        tagUri = 'https://api.instagram.com/v1/tags/'
-        taggedMediaUrl = tagUri + tag + '/media/recent?access_token=' + self.access_token
-        req = requests.get(taggedMediaUrl)
-        content = json2.loads(req.content)
-        data = content['data']
 
-        while len(data) <= 100:
-            nextUrl = content['pagination']['next_url']
-            req = requests.get(nextUrl)
-            content = json2.loads(req.content)
-            for i in content['data']:
-                data.append(i)
-        #print len(data)
-        return data
 
+def searchForLocation(address):
+    '''
+    Parameters:
+        address: String
+            - The address is a user input.
 
-    def get_user_info(self):
-        '''
-        Get user information.
+    Returns:
+        location: Dictionary
+            - A dictionary returning the latitude, and longitude
+              of an address.
+    '''
 
-        Parameters:
-            access_token: String
-                - The access_token given after granting permission
-                  application access to Instagram data.
+    gmaps = googlemaps.Client(key=settings.GOOGLEMAP_API_KEY)
+    #geocoding and address
+    geocodeResult = gmaps.geocode(address)
 
-        Returns:
-            data: Dictionary
-                - A dictionary containing user information.
-        '''
+    if geocodeResult:
+        location = geocodeResult[0]['geometry']['location']
+        return location
 
-        userInfo = 'https://api.instagram.com/v1/users/32833691/?access_token='+self.access_token
-        req = requests.get(userInfo)
-        content = json2.loads(req.content)
-        data = content['data']
-        return data
 
+def getTaggedMedia(tag, accessToken):
+    '''
+    Get recent tagged media.
 
-    def get_user_media(self, userId):
-        '''
-        Parameters:
-            access_token: String
-                - The access_token given after granting permission
-                  application access to Instagram data.
+    Parameters:
+        tag: String
+            - The tag used to search the most recent media that's tagged with it.
 
-        Returns:
-            data: Dictionary
-                - A dictionary containing user media information.
-        '''
+    Returns:
+        data: Dictionary
+            - A dictionary containing recent tagged 120 media
+              counts data pertaining to each media.
+    '''
 
-        userMediaUri = 'https://api.instagram.com/v1/users/' + str(userId)
-        userMedia = userMediaUri + '/media/recent/?access_token=' + self.access_token
-        req = requests.get(userMedia)
+    tagUri = 'https://api.instagram.com/v1/tags/'
+    taggedMediaUrl = tagUri + tag + '/media/recent?access_token=' + accessToken
+    req = requests.get(taggedMediaUrl)
+    content = json2.loads(req.content)
+    data = content['data']
+
+    while len(data) <= 100:
+        nextUrl = content['pagination']['next_url']
+        req = requests.get(nextUrl)
         content = json2.loads(req.content)
-        data = content['data']
-        return data
+        for i in content['data']:
+            data.append(i)
+    #print len(data)
+    return data
 
 
-    def search_location_ids(self, lat, lng):
-        '''
-        Parameters:
-            lat: Float
-                - The latitude of the input address
-            lng: Float
-                - The longitude of the input address
+def getUserInfo(accessToken):
+    '''
+    Get user information.
 
-        Returns:
-            listOfIds: Dictionary
-                - A dictionary returning the list of location ids
-                  of the given address coordinates.
-        '''
+    Parameters:
+        access_token: String
+            - The access_token given after granting permission
+              application access to Instagram data.
 
-        locIdUri = 'https://api.instagram.com/v1/locations/search?lat=' + str(lat)
-        location = locIdUri+'&lng='+str(lng)+'&access_token='+self.access_token+'&distance=5000'
-        req = requests.get(location)
-        data = json2.loads(req.content)
-        listOfIds = []
-        if data['meta']['code'] != 200:
-            raise Exception("Invalid response %s." % data['meta']['code'])
-        searchIds = data['data']
-        for data in searchIds:
-            for i in data:
-                if i == 'id':
-                    listOfIds.append(data[i])
-        return listOfIds
-
-
-    def search_location_media(self, listOfLocationIds):
-        '''
-        Parameters:
-            listOfLocationIds: Float
-                - list of location ids retrieve from coordinate of
-                  of searched address.
-            access_token: String
-                - The access_token given after granting permission
-                  application access to Instagram data.
+    Returns:
+        data: Dictionary
+            - A dictionary containing user information.
+    '''
 
-        Returns:
-            media: Dictionary
-                - A dictionary returning the list of recent media
-                  of the list of location ids.
-        '''
+    userInfo = 'https://api.instagram.com/v1/users/32833691/?access_token='+accessToken
+    req = requests.get(userInfo)
+    content = json2.loads(req.content)
+    data = content['data']
+    return data
 
-        media = []
-        locationUri = 'https://api.instagram.com/v1/locations/'
-        for location in listOfLocationIds:
-            mediaByLocation = locationUri+location+'/media/recent?access_token='+self.access_token
-            req = requests.get(mediaByLocation)
-            contentAll = json2.loads(req.content)
-            if contentAll['pagination']:
-                tempMedia = []
-                nextUrl = contentAll['pagination']['next_url']
-                req = requests.get(nextUrl)
-                content = json2.loads(req.content)
-                for i in content['data']:
-                    i['created_time'] = datetime.fromtimestamp(int(i['created_time']))
-                    i['created_time'] = i['created_time'].strftime('%Y-%m-%d %H:%M:%S')
-                    tempMedia.append(i)
-                media += [tempMedia]
-            else:
-                for i in contentAll['data']:
-                    for data in i:
-                        if data == 'created_time':
-                            i[data] = datetime.fromtimestamp(int(i[data]))
-                            i[data] = i[data].strftime('%Y-%m-%d %H:%M:%S')
-                media.append(contentAll['data'])
-        return media
 
+def getUserMedia(userId, accessToken):
+    '''
+    Parameters:
+        accessToken: String
+            - The access_token given after granting permission
+              application access to Instagram data.
+        userId: Integer
+            - User's instagram ID number.
 
-def searchForLocation(address):
+    Returns:
+        data: Dictionary
+            - A dictionary containing user media information.
+    '''
+
+    userMediaUri = 'https://api.instagram.com/v1/users/' + str(userId)
+    userMedia = userMediaUri + '/media/recent/?access_token=' + accessToken
+    req = requests.get(userMedia)
+    content = json2.loads(req.content)
+    data = content['data']
+    return data
+
+
+def searchLocationIds(lat, lng, accessToken):
     '''
     Parameters:
-        address: String
-            - The address is a user input.
+        lat: Float
+            - The latitude of the input address
+        lng: Float
+            - The longitude of the input address
 
     Returns:
-        location: Dictionary
-            - A dictionary returning the latitude, and longitude
-              of an address.
+        listOfIds: Dictionary
+            - A dictionary returning the list of location ids
+              of the given address coordinates.
     '''
 
-    gmaps = googlemaps.Client(key=settings.GOOGLEMAP_API_KEY)
-    #geocoding and address
-    geocodeResult = gmaps.geocode(address)
+    locIdUri = 'https://api.instagram.com/v1/locations/search?lat=' + str(lat)
+    location = locIdUri+'&lng='+str(lng)+'&access_token='+ accessToken+'&distance=5000'
+    req = requests.get(location)
+    data = json2.loads(req.content)
+    listOfIds = []
+    if data['meta']['code'] != 200:
+        raise Exception("Invalid response %s." % data['meta']['code'])
+    searchIds = data['data']
+    for data in searchIds:
+        for i in data:
+            if i == 'id':
+                listOfIds.append(data[i])
+    return listOfIds
+
+
+def searchLocationMedia(listOfLocationIds, accessToken):
+    '''
+    Parameters:
+        listOfLocationIds: Float
+            - list of location ids retrieve from coordinate of
+              of searched address.
+        access_token: String
+            - The access_token given after granting permission
+              application access to Instagram data.
 
-    if geocodeResult:
-        location = geocodeResult[0]['geometry']['location']
-        return location
+    Returns:
+        media: Dictionary
+            - A dictionary returning the list of recent media
+              of the list of location ids.
+    '''
+
+    media = []
+    locationUri = 'https://api.instagram.com/v1/locations/'
+    for location in listOfLocationIds:
+        mediaByLocation = locationUri+location+'/media/recent?access_token='+ accessToken
+        req = requests.get(mediaByLocation)
+        contentAll = json2.loads(req.content)
+        if contentAll['pagination']:
+            tempMedia = []
+            nextUrl = contentAll['pagination']['next_url']
+            req = requests.get(nextUrl)
+            content = json2.loads(req.content)
+            for i in content['data']:
+                i['created_time'] = datetime.fromtimestamp(int(i['created_time']))
+                i['created_time'] = i['created_time'].strftime('%Y-%m-%d %H:%M:%S')
+                tempMedia.append(i)
+            media += [tempMedia]
+        else:
+            for i in contentAll['data']:
+                for data in i:
+                    if data == 'created_time':
+                        i[data] = datetime.fromtimestamp(int(i[data]))
+                        i[data] = i[data].strftime('%Y-%m-%d %H:%M:%S')
+            media.append(contentAll['data'])
+    return media

+ 177 - 156
hackathon_starter/hackathon/scripts/twitter.py

@@ -11,227 +11,248 @@ import requests
 import base64, random
 import urllib
 import binascii
-import time, collections, json, hmac, hashlib
+import time, collections, hmac, hashlib
 import simplejson as json2
 
-request_token_url = 'https://api.twitter.com/oauth/request_token'
-access_token_url = 'https://api.twitter.com/oauth/access_token'
-authorize_url = 'https://api.twitter.com/oauth/authorize'
+REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token'
+ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token'
+AUTHORIZE_URL = 'https://api.twitter.com/oauth/authorize'
 
 class TwitterOauthClient(object):
-	'''
-	Python Client for Twitter API.
-	'''	
-
-	oauth_token = None
-	oauth_token_secret = None
-
-
-	def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret):
-		'''
-		Parameters:
-			consumer_key: String
-				- The consumer_key from registering application
-				  on Instagram.
-			consumer_secret: String
-				- The consumer_secret from registering application
-				  on Instagram.
-		'''		
-		self.consumer_key = consumer_key
-		self.consumer_secret = consumer_secret
-		self.access_token = access_token
-		self.access_token_secret = access_token_secret
-		self.consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret)
-		
-
-	def get_authorize_url(self):
-		'''
-		Obtained oauth_token and oauth_token_secret from request_token_url,
-		returns an authorize url. 
-
-		From the redirect url, we obtain the oauth verifier.
-		'''
-
-		client = oauth.Client(self.consumer)
-		resp, content = client.request(request_token_url, 'GET')
-
-		if int(resp['status']) != 200:
-			raise Exception('Invalid response %s' %resp['status'])
-
-		request_token = dict(urlparse.parse_qsl(content))
-
-		#temporary
-		self.oauth_token = request_token['oauth_token']
-		self.oauth_token_secret  = request_token['oauth_token_secret']
-		print self.oauth_token
-
-		#link to authorize app access twitter data and return to twitter api example page
-		link = authorize_url+"?oauth_token="+self.oauth_token+"&redirect_uri=http%3A%2F%2Flocalhost%3A8000/hackathon/twitter/"
-		return link
+    '''
+    Python Client for Twitter API.
+    '''
+
+    oauth_token = None
+    oauth_token_secret = None
+    username = None
+    is_authorized = False
+
+
+    def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret):
+        '''
+        Parameters:
+            consumer_key: String
+                - The consumer_key from registering application
+                  on Instagram.
+            consumer_secret: String
+                - The consumer_secret from registering application
+                  on Instagram.
+        '''
+
+        self.consumer_key = consumer_key
+        self.consumer_secret = consumer_secret
+        self.access_token = access_token
+        self.access_token_secret = access_token_secret
+        self.consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret)
+
+
+    def get_authorize_url(self):
+        '''
+        Obtained oauth_token and oauth_token_secret from request_token_url,
+        returns an authorize url.
+
+        From the redirect url, we obtain the oauth verifier.
+
+        Returns:
+            authURL: String
+                - The authorization url.
+        '''
+
+        client = oauth.Client(self.consumer)
+        resp, content = client.request(REQUEST_TOKEN_URL, 'GET')
+
+        if int(resp['status']) != 200:
+            raise Exception('Invalid response %s' %resp['status'])
+
+        requestToken = dict(urlparse.parse_qsl(content))
+
+        #temporary
+        self.oauth_token = requestToken['oauth_token']
+        self.oauth_token_secret = requestToken['oauth_token_secret']
+        #print self.oauth_token
+
+        #link to authorize app access twitter data and return to twitter api example page
+        redirectUri = '&redirect_uri=http%3A%2F%2Flocalhost%3A8000/hackathon/twitter/'
+        authURL = AUTHORIZE_URL+"?oauth_token="+self.oauth_token+redirectUri
+        return authURL
+
 
-	def get_access_token_url(self, oauth_verifier):
-		
-		token = oauth.Token(self.oauth_token, self.oauth_token_secret)
-		token.set_verifier(oauth_verifier)
+    def get_access_token_url(self, oauthVerifier):
+        '''
+        Get access token from redirect url.
 
-		client = oauth.Client(self.consumer, token)
-		resp, content = client.request(access_token_url, 'POST')
-		
-		if int(resp['status']) != 200:
-			raise Exception('Invalid response %s' %resp['status'])
+        Parameters:
+            oauthVerifier: String
+                - A paramater retrieved from scraping the redirect url.
 
-		print content
-		access_token = dict(urlparse.parse_qsl(content))
+        Returns:
+            data: Dictionary
+                - A dictionary containing recent tagged 120 media
+                  counts data pertaining to each media.
+        '''
 
-		#permanent
-		self.oauth_token = access_token['oauth_token']
-		self.oauth_token_secret = access_token['oauth_token_secret']
-		self.user_id = access_token['user_id']
-		self.username = access_token['screen_name']
+        token = oauth.Token(self.oauth_token, self.oauth_token_secret)
+        token.set_verifier(oauthVerifier)
 
+        client = oauth.Client(self.consumer, token)
+        resp, content = client.request(ACCESS_TOKEN_URL, 'POST')
 
+        if int(resp['status']) != 200:
+            raise Exception('Invalid response %s' %resp['status'])
 
+        #print content
+        accessToken = dict(urlparse.parse_qsl(content))
 
-	def get_trends_available(self, yahoo_consumer_key):
-		method = "get"
-		link = 'https://api.twitter.com/1.1/trends/available.json'
-		link_parameters = {}
-		#link = 'https://api.twitter.com/1.1/trends/closest.json'
-		#link_parameters = {'lat':'40.782032', 'long':'-73.9717188'}
-		#link = 'https://api.twitter.com/1.1/trends/place.json'
-		#link_parameters = {'id': '1'}
-		
+        #permanent
+        self.oauth_token = accessToken['oauth_token']
+        self.oauth_token_secret = accessToken['oauth_token_secret']
+        self.username = accessToken['screen_name']
+        self.is_authorized = True
 
-		oauth_parameters = get_oauth_parameters(
-		    self.consumer_key,
-		    self.access_token
-		)
 
-		oauth_parameters['oauth_signature'] = generate_signature(
-		    method,
-		    link,
-		    link_parameters,
-		    oauth_parameters,
-		    self.consumer_key,
-		    self.consumer_secret,
-		    self.access_token_secret
-		)
+    def get_trends_available(self, yahooConsumerKey):
+        '''
+        Get the locations that Twitter has trending topic information for.
 
-		headers = {'Authorization': create_auth_header(oauth_parameters)}
+        '''
 
-		if link_parameters:
-			link += '?'+urllib.urlencode(link_parameters)
+        method = "get"
+        link = 'https://api.twitter.com/1.1/trends/available.json'
+        linkParameters = {}
+        #link = 'https://api.twitter.com/1.1/trends/closest.json'
+        #link_parameters = {'lat':'40.782032', 'long':'-73.9717188'}
+        #link = 'https://api.twitter.com/1.1/trends/place.json'
+        #link_parameters = {'id': '1'}
 
-		req = requests.get(link, headers=headers)
-		#print req.status_code
-		
-		if int(req.status_code) != 200:
-			raise Exception('Invalid response %s' %req.status_code)
-
-		content = json2.loads(req.content)
-		#print len(content)
-		
-		for place in content:
-			for e in place:
-				if e == 'url':
-					request_neighbor_data=  requests.get(place[e]+'/neighbors?appid='+yahoo_consumer_key+'&format=json')
-					#print request_neighbor_data.status_code
-					if request_neighbor_data.status_code == 200:
-						neighbor = json2.loads(request_neighbor_data.content)
-					else:
-						neighbor = {}
+        oauthParameters = getOauthParameters(
+            self.consumer_key,
+            self.access_token
+        )
 
-			place['neighbor'] = neighbor
-					#print place
+        oauthParameters['oauth_signature'] = generateSignature(
+            method,
+            link,
+            linkParameters,
+            oauthParameters,
+            self.consumer_secret,
+            self.access_token_secret
+        )
 
+        headers = {'Authorization': createAuthHeader(oauthParameters)}
 
-		return content
-		
+        if linkParameters:
+            link += '?'+urllib.urlencode(linkParameters)
 
+        req = requests.get(link, headers=headers)
+        #print req.status_code
 
+        if int(req.status_code) != 200:
+            raise Exception('Invalid response %s' %req.status_code)
 
+        content = json2.loads(req.content)
+        #print len(content)
 
-def percent_encode(string):
-	'''
-	Percent encode strings.
-	'''
-	return urllib.quote(string, safe='~')
+        for place in content:
+            for item in place:
+                if item == 'url':
+                    url = place[item]+'/neighbors?appid='+yahooConsumerKey+'&format=json'
+                    requestNeighborData = requests.get(url)
+                    #print request_neighbor_data.status_code
+                    if requestNeighborData.status_code == 200:
+                        neighbor = json2.loads(requestNeighborData.content)
+                    else:
+                        neighbor = {}
 
+            place['neighbor'] = neighbor
+                    #print place
 
-def get_nonce():
-	'''
-	Generate unique token per request.
-	'''
 
-	n = base64.b64encode(''.join([str(random.randint(0, 9)) for i in range(24)]))
-	return n
+        return content
 
 
-def generate_signature(method, link, link_parameters, oauth_parameters, oauth_consumer_key, oauth_consumer_secret, oauth_token_secret=None, status=None):
+
+def percentEncode(string):
+    '''
+    Percent encode strings.
+    '''
+    return urllib.quote(string, safe='~')
+
+
+def getNonce():
+    '''
+    Generate unique token per request.
+    '''
+
+    nonce = base64.b64encode(''.join([str(random.randint(0, 9)) for i in range(24)]))
+    return nonce
+
+
+def generateSignature(method, link, linkParameters, oauthParameters,
+                      oauthConsumerSecret, oauthTokenSecret=None):
     '''
     Generate signature.
     '''
-    if link_parameters:
-    	new_dict = dict(oauth_parameters, **link_parameters)
-    	parameters = urllib.urlencode(collections.OrderedDict(sorted(new_dict.items())))
+
+    if linkParameters:
+        newDict = dict(oauthParameters, **linkParameters)
+        params = urllib.urlencode(collections.OrderedDict(sorted(newDict.items())))
     else:
-    	parameters = urllib.urlencode(collections.OrderedDict(sorted(oauth_parameters.items())))
+        params = urllib.urlencode(collections.OrderedDict(sorted(oauthParameters.items())))
 
     #Create your Signature Base String
-    signature_base_string = ( method.upper() + '&' + percent_encode(str(link)) + '&' + percent_encode(parameters))
+    signatureBaseString = (method.upper()+'&'+percentEncode(str(link))+'&'+percentEncode(params))
 
     #Get the signing key
-    signing_key = create_signing_key(oauth_consumer_secret, oauth_token_secret)
+    signingKey = createSigningKey(oauthConsumerSecret, oauthTokenSecret)
 
-    return calculate_signature(signing_key, signature_base_string)
+    return calculateSignature(signingKey, signatureBaseString)
 
 
 
-def calculate_signature(signing_key, signature_base_string):
+def calculateSignature(signingKey, signatureBaseString):
     '''
     Calculate signature using HMAC-SHA1 hashing algorithm.
     '''
-    hashed = hmac.new(signing_key, signature_base_string, hashlib.sha1)
+    hashed = hmac.new(signingKey, signatureBaseString, hashlib.sha1)
 
     sig = binascii.b2a_base64(hashed.digest())[:-1]
 
-    return percent_encode(sig)
+    return percentEncode(sig)
 
 
-def create_signing_key(oauth_consumer_secret, oauth_token_secret):
+def createSigningKey(oauthConsumerSecret, oauthTokenSecret):
     '''
     Creates a key to sign the request with.
     '''
 
-    signing_key = percent_encode(oauth_consumer_secret) + '&' + percent_encode(oauth_token_secret)
+    signingKey = percentEncode(oauthConsumerSecret) + '&' + percentEncode(oauthTokenSecret)
 
-    return signing_key
+    return signingKey
 
 
-def create_auth_header(parameters):
-	'''
-	Format authorization header with oath parameters.
-	'''
+def createAuthHeader(parameters):
+    '''
+    Format authorization header with oath parameters.
+    '''
 
-	ordered_parameters = collections.OrderedDict(sorted(parameters.items()))
-	auth_header = ('%s="%s"' % (k, v) for k, v in ordered_parameters.iteritems())
+    orderedParameters = collections.OrderedDict(sorted(parameters.items()))
+    authHeader = ('%s="%s"' % (k, v) for k, v in orderedParameters.iteritems())
 
-	return "OAuth " + ', '.join(auth_header)
+    return "OAuth " + ', '.join(authHeader)
 
 
-def get_oauth_parameters(consumer_key, access_token):
+def getOauthParameters(consumerKey, accessToken):
     '''
     Returns parameters for making requests.
     '''
-    oauth_parameters = {
+    oauthParameters = {
         'oauth_timestamp': str(int(time.time())),
         'oauth_signature_method': "HMAC-SHA1",
         'oauth_version': "1.0",
-        'oauth_token': access_token,
-        'oauth_nonce': get_nonce(),
-        'oauth_consumer_key': consumer_key
+        'oauth_token': accessToken,
+        'oauth_nonce': getNonce(),
+        'oauth_consumer_key': consumerKey
     }
 
-    return oauth_parameters
-
-    
+    return oauthParameters

+ 2 - 2
hackathon_starter/hackathon/templates/hackathon/api_examples.html

@@ -11,8 +11,8 @@
 			<div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/linkedin/">LinkedIn Example</a></div>
 		-->
 		<div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/twilio/">Twilio Example</a></div>
-		<div class="col-sm-4"><a href="{{instagram_url}}">Instagram Example</a></div>
-		<div class="col-sm-4"><a href="{{twitter_url}}">Twitter Example</a></div>
+		<div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/instagram/">Instagram Example</a></div>
+		<div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/twitter/">Twitter Example</a></div>
 		<div class="col-sm-4"><a href="http://localhost:8000/hackathon/quandlstocks/">Quandl Example</a></div>
 
   	</div>

+ 64 - 61
hackathon_starter/hackathon/views.py

@@ -32,12 +32,46 @@ from hackathon.serializers import SnippetSerializer
 from hackathon.forms import UserForm
 
 
-
 getTumblr = TumblrOauthClient(settings.TUMBLR_CONSUMER_KEY, settings.TUMBLR_CONSUMER_SECRET)
 getInstagram = InstagramOauthClient(settings.INSTAGRAM_CLIENT_ID, settings.INSTAGRAM_CLIENT_SECRET)
 getTwitter = TwitterOauthClient(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET, settings.TWITTER_ACCESS_TOKEN, settings.TWITTER_ACCESS_TOKEN_SECRET)
 
 def index(request):
+    print "index: " + str(request.user)
+
+    #check returned parameters, if there is user logged in via social media
+    if request.GET.items():
+        if 'oauth_verifier' in request.GET.keys():
+            oauth_verifier = request.GET['oauth_verifier']
+            getTwitter.get_access_token_url(oauth_verifier) 
+
+            if not User.objects.all().filter(username=request.user.username):
+                try:
+                    user = User.objects.get(username = getTwitter.username + '_twitter')#(username=getTwitter.username)
+                except User.DoesNotExist:
+                    username = getTwitter.username + '_twitter'
+                    new_user = User.objects.create_user(username, username+'@madewithtwitter.com', 'password')
+                    new_user.save()
+                    profile = TwitterProfile(user = new_user,oauth_token = getTwitter.oauth_token, oauth_token_secret= getTwitter.oauth_token_secret, twitter_user=getTwitter.username)
+                    profile.save()
+                user = authenticate(username=getTwitter.username+'_twitter', password='password')
+                login(request, user)
+        elif 'code' in request.GET.keys():
+            code = request.GET['code']
+            getInstagram.get_access_token(code)
+
+            if not User.objects.all().filter(username=request.user.username):
+                try:  
+                    user = User.objects.get(username=getInstagram.user_data['username']+'_instagram')
+                except User.DoesNotExist:
+                    username = getInstagram.user_data['username']+'_instagram'
+                    new_user = User.objects.create_user(username, username+'@madewithinstagram.com', 'password')
+                    new_user.save()
+                    profile = InstagramProfile(user = new_user, access_token = getInstagram.access_token, instagram_user=getInstagram.user_data['username'])
+                    profile.save()
+                user = authenticate(username=getInstagram.user_data['username']+'_instagram' , password='password')
+                login(request, user) 
+
     context = {'hello': 'world'}
     return render(request, 'hackathon/index.html', context)
 
@@ -48,13 +82,12 @@ def index(request):
 
 def api_examples(request):
     instagram_url =getInstagram.get_authorize_url()
-    twitter_url = getTwitter.get_authorize_url()
     if not getTumblr.accessed:
         obtain_oauth_verifier = getTumblr.authorize_url()
     else:
         obtain_oauth_verifier = '/hackathon/tumblr'
     #obtain_oauth_verifier = getTumblr.authorize_url()
-    context = {'title': 'API Examples Page', 'tumblr_url': obtain_oauth_verifier, 'instagram_url':instagram_url, 'twitter_url':twitter_url}
+    context = {'title': 'API Examples Page', 'tumblr_url': obtain_oauth_verifier, 'instagram_url':instagram_url}
     return render(request, 'hackathon/api_examples.html', context)
 
 #################
@@ -200,37 +233,22 @@ def tumblr(request):
 ####################
 
 def instagram(request):
-    code = request.GET['code']
-    getInstagram.get_access_token(code)
-
-    #check if user in User profile
-    if not User.objects.all().filter(username=request.user.username):
-        print "anno"
-        try:  
-            user = User.objects.get(username=getInstagram.user_data['username'])
-        except User.DoesNotExist:
-            username = getTwitter.username 
-            new_user = User.objects.create_user(username, username+'@madewithinstagram.com', 'password')
-            new_user.save()
-            profile = InstagramProfile(user = new_user, access_token = getInstagram.access_token, instagram_user=new_user.username+'instagram')
-            profile.save()
-        user = authenticate(username=getInstagram.user_data['username'] , password='password')
-        login(request, user)            
-    else:
-        print "exist instagram"
-        #check if user has an Instragram profile
-        try:  
-            user = User.objects.get(username=request.user.username)
-            twitterUser = InstagramProfile.objects.get(user=user.id)
+    print getInstagram.is_authorized
+    if getInstagram.is_authorized:
+        try:
+            user = User.objects.get(username=request.user)
+            instagramUser = InstagramProfile.objects.get(user=user.id)
         except InstagramProfile.DoesNotExist:
             new_user = User.objects.get(username=request.user.username)
             profile = InstagramProfile(user = new_user, access_token = getInstagram.access_token, instagram_user=new_user.username+'@instagram')
-            profile.save()  
-
-
+            profile.save()
+    else:
+        instagram_url =getInstagram.get_authorize_url()
+        return HttpResponseRedirect(instagram_url)
+    
     search_tag = 'kitten'
     #return tagged objects
-    tagged_media = getInstagram.get_tagged_media(search_tag)
+    tagged_media = getTaggedMedia(search_tag, instagramUser.access_token)
 
     context = {'title': 'Instagram', 'tagged_media': tagged_media, 'search_tag': search_tag}
     return render(request, 'hackathon/instagram.html', context)
@@ -238,16 +256,15 @@ def instagram(request):
 def instagramUser(request):
     ''' Returns JSON response about a specific Instagram User. '''
 
-    user_id = User.objects.get(username='mk200789').id
-    access_token = Profile.objects.get(user=user_id).oauth_secret
-    parsedData = getInstagram.get_user_info()
+    access_token = InstagramProfile.objects.get(instagram_user='mk200789').access_token
+    parsedData = getUserInfo(access_token)
     return JsonResponse({ 'data': parsedData })
 
 def instagramUserMedia(request):
     ''' Returns JSON response about a specific Instagram User's Media. '''
-    user_id = User.objects.get(username='mk200789').id
-    access_token = Profile.objects.get(user=user_id).oauth_secret
-    parsedData = getInstagram.get_user_media(32833691)
+
+    access_token = InstagramProfile.objects.get(instagram_user='mk200789').access_token
+    parsedData = getUserMedia(32833691, access_token)
     return JsonResponse({'data': parsedData })
 
 def instagramMediaByLocation(request):
@@ -261,11 +278,11 @@ def instagramMediaByLocation(request):
                 #if user has an Instagram profile, query the search
                 if InstagramProfile.objects.all().filter(user=user.id):
                     address = request.GET.get('address_field')
-                    instagramUser = InstagramProfile.objects.get(user=user.id)
+                    access_token = InstagramProfile.objects.get(user=user.id).access_token
                     geocode_result = searchForLocation(address)
                     if geocode_result:
-                        location_ids =getInstagram.search_location_ids(geocode_result['lat'], geocode_result['lng'])
-                        media = getInstagram.search_location_media(location_ids)
+                        location_ids = searchLocationIds(geocode_result['lat'], geocode_result['lng'], access_token)
+                        media = searchLocationMedia(location_ids, access_token)
                         title = address
                         err_msg = ''
                 else:
@@ -281,36 +298,22 @@ def instagramMediaByLocation(request):
 ####################
 #   TWITTER API    #
 ####################
-def twitter(request):
-    oauth_verifier = request.GET['oauth_verifier']
-    getTwitter.get_access_token_url(oauth_verifier)   
-    print request.user
 
-    if not User.objects.all().filter(username=request.user.username):
-        try:  
-            user = User.objects.get(username=getTwitter.username)
-        except User.DoesNotExist:
-            username = getTwitter.username 
-            new_user = User.objects.create_user(username, username+'@madewithtwitter.com', 'password')
-            new_user.save()
-            profile = TwitterProfile(user = new_user,oauth_token = getTwitter.oauth_token, oauth_token_secret= getTwitter.oauth_token_secret, twitter_user=new_user.username+'twitter')
-            profile.save()
-        user = authenticate(username=getTwitter.username, password='password')
-        login(request, user)            
-    else:
-        print "exist twitter"
-        #check if user has an Instragram profile
-        try:  
+def twitter(request):
+    if getTwitter.is_authorized:
+        try:
             user = User.objects.get(username=request.user.username)
             twitterUser = TwitterProfile.objects.get(user=user.id)
         except TwitterProfile.DoesNotExist:
             new_user = User.objects.get(username=request.user.username)
-            profile = TwitterProfile(user = new_user, oauth_token = getTwitter.oauth_token, oauth_token_secret = getTwitter.oauth_token_secret, twitter_user=new_user.username+'@twitter')
-            profile.save()            
+            profile = TwitterProfile(user = new_user, oauth_token = getTwitter.oauth_token, oauth_token_secret = getTwitter.oauth_token_secret, twitter_user=getTwitter.username)
+            profile.save()
 
+    else:
+        tumblr_url = getTwitter.get_authorize_url()
+        return HttpResponseRedirect(tumblr_url)
 
     value = getTwitter.get_trends_available(settings.YAHOO_CONSUMER_KEY)
-    #yahoo_woeid_link = 'http://where.yahooapis.com/v1/place/'+returned_woeid+'?appid='+settings.YAHOO_CONSUMER_KEY
 
     context ={'title': 'twitter', 'value': value}
     return render(request, 'hackathon/twitter.html', context)
@@ -423,5 +426,5 @@ def tumblr_login(request):
     return HttpResponseRedirect(tumblr_url)
 
 def twitter_login(request):
-    twitter_url = getTwitter.get_authorize_url()
+    twitter_url = getTwitter.get_authorize_url()     
     return HttpResponseRedirect(twitter_url)