def post(self, api_method, http_method='POST', expected_status=(200, ), **extra_params): if not (api_method.startswith('http://') or api_method.startswith('https://')): api_method = '%s%s%s' % (self.service_info['default_api_prefix'], api_method, self.service_info['default_api_suffix']) if self.token is None: self.token = OAuthAccessToken.get_by_key_name(self.get_cookie()) fetch = urlfetch(url=api_method, payload=self.get_signed_body(api_method, self.token, http_method, **extra_params), method=http_method) if fetch.status_code not in expected_status: raise ValueError("Error calling... Got return status: %i [%r]" % (fetch.status_code, fetch.content)) return decode_json(fetch.content)
def requestAuthenticationURL(self): obj = { 'oauth_callback':self.redirect_uri, 'oauth_consumer_key':self.twitter_consumer_key, 'oauth_nonce': getrandbits(64), 'oauth_signature_method':'HMAC-SHA1', 'oauth_timestamp':int(time.time()), 'oauth_version':'1.0' } s = getBaseString("POST","https://api.twitter.com/oauth/request_token",obj) key = self.twitter_consumer_secret + "&" obj['oauth_signature'] = hmac.new(key, s, sha1).digest().encode('base64')[:-1] for x in obj: obj[x] = encode(obj[x]) authHeader = "OAuth oauth_nonce=\"" + obj['oauth_nonce'] + "\", oauth_callback=\"" + obj['oauth_callback'] authHeader+= "\", oauth_signature_method=\"" + obj['oauth_signature_method'] + "\", oauth_timestamp=\"" authHeader+= obj['oauth_timestamp'] + "\", oauth_consumer_key=\"" + obj['oauth_consumer_key'] authHeader+= "\", oauth_signature=\"" + obj['oauth_signature'] + "\", oauth_version=\"" authHeader+= obj['oauth_version'] + "\"" result = urlfetch(url='https://api.twitter.com/oauth/request_token', method=POST, headers={'Authorization': authHeader}) if str(result.status_code) != '200': return None res = {} for x in result.content.split('&'): obj = x.split('=') res[obj[0]] = obj[1] self.user.twitter = json.dumps(res) self.user.put() return "https://api.twitter.com/oauth/authorize?oauth_token="+res['oauth_token']
def unfollowUser(self,tUser2): url = 'http://api.twitter.com/1/friendships/destroy.json' user2Id = tUser2.getProfileDetails()['id'] objC = json.loads(self.user.twitter) obj = { 'user_id':user2Id, 'oauth_consumer_key':self.twitter_consumer_key, 'oauth_nonce': getrandbits(64), 'oauth_signature_method':'HMAC-SHA1', 'oauth_token':objC['oauth_token'], 'oauth_timestamp':int(time.time()), 'oauth_version':'1.0' } s = getBaseString("POST",url,obj) key = self.twitter_consumer_secret + "&" + objC['oauth_token_secret'] obj['oauth_signature'] = hmac.new(key, s, sha1).digest().encode('base64')[:-1] for x in obj: obj[x] = encode(obj[x]) authHeader = "OAuth oauth_consumer_key=\"" + obj['oauth_consumer_key'] + "\", oauth_nonce=\"" + obj['oauth_nonce'] authHeader+= "\", oauth_signature_method=\"" + obj['oauth_signature_method'] + "\", oauth_token=\"" authHeader+= obj['oauth_token'] + "\", oauth_timestamp=\"" + obj['oauth_timestamp'] authHeader+= "\", oauth_version=\"" + obj['oauth_version'] + "\", oauth_signature=\""+obj['oauth_signature']+"\"" result = urlfetch(url=url, method=POST, payload="user_id=" + encode(str(user2Id)), headers={'Authorization': authHeader}) if str(result.status_code) == '200': return {"result":"success","data":json.loads(result.content)} return {"result":"error","error_code":result.status_code, "content":result.content}
def getRelationship(self,tUser2): url = 'http://api.twitter.com/1/friendships/show.json?source_id=%s&target_id=%s'%(self.getProfileDetails()['id_str'], tUser2.getProfileDetails()['id_str']) objC = json.loads(self.user.twitter) obj = { 'oauth_consumer_key':self.twitter_consumer_key, 'oauth_nonce': getrandbits(64), 'oauth_signature_method':'HMAC-SHA1', 'oauth_token':objC['oauth_token'], 'oauth_timestamp':int(time.time()), 'oauth_version':'1.0' } s = getBaseString("GET",url,obj) key = self.twitter_consumer_secret + "&" + objC['oauth_token_secret'] obj['oauth_signature'] = hmac.new(key, s, sha1).digest().encode('base64')[:-1] for x in obj: obj[x] = encode(obj[x]) authHeader = "OAuth oauth_consumer_key=\"" + obj['oauth_consumer_key'] + "\", oauth_nonce=\"" + obj['oauth_nonce'] authHeader+= "\", oauth_signature_method=\"" + obj['oauth_signature_method'] + "\", oauth_token=\"" authHeader+= obj['oauth_token'] + "\", oauth_timestamp=\"" + obj['oauth_timestamp'] authHeader+= "\", oauth_version=\"" + obj['oauth_version'] + "\", oauth_signature=\""+obj['oauth_signature']+"\"" result = urlfetch(url=url, method=GET, headers={'Authorization': authHeader}) if str(result.status_code) == '200': return json.loads(result.content) return None
def getLastStatusDetails(self): objC = json.loads(self.user.twitter) obj = { 'oauth_consumer_key':self.twitter_consumer_key, 'oauth_nonce': getrandbits(64), 'oauth_signature_method':'HMAC-SHA1', 'oauth_token':objC['oauth_token'], 'oauth_timestamp':int(time.time()), 'oauth_version':'1.0' } s = getBaseString("GET","http://api.twitter.com/1/account/verify_credentials.json",obj) key = self.twitter_consumer_secret + "&" + objC['oauth_token_secret'] obj['oauth_signature'] = hmac.new(key, s, sha1).digest().encode('base64')[:-1] for x in obj: obj[x] = encode(obj[x]) authHeader = "OAuth oauth_consumer_key=\"" + obj['oauth_consumer_key'] + "\", oauth_nonce=\"" + obj['oauth_nonce'] authHeader+= "\", oauth_signature_method=\"" + obj['oauth_signature_method'] + "\", oauth_token=\"" authHeader+= obj['oauth_token'] + "\", oauth_timestamp=\"" + obj['oauth_timestamp'] authHeader+= "\", oauth_version=\"" + obj['oauth_version'] + "\", oauth_signature=\""+obj['oauth_signature']+"\"" result = urlfetch(url='http://api.twitter.com/1/account/verify_credentials.json', method=GET, headers={'Authorization': authHeader}) if str(result.status_code) == '200': return json.loads(result.content) return None
def getFeed(self,feedName='user_timeline'): objC = json.loads(self.user.twitter) obj = { 'include_entities':'true', 'oauth_consumer_key':self.twitter_consumer_key, 'oauth_nonce': getrandbits(64), 'oauth_signature_method':'HMAC-SHA1', 'oauth_token':objC['oauth_token'], 'oauth_timestamp':int(time.time()), 'oauth_version':'1.0' } url = "http://api.twitter.com/1/statuses/%s.json"%feedName s = getBaseString("GET",url,obj) key = self.twitter_consumer_secret + "&" + objC['oauth_token_secret'] obj['oauth_signature'] = hmac.new(key, s, sha1).digest().encode('base64')[:-1] for x in obj: obj[x] = encode(obj[x]) authHeader = "OAuth oauth_consumer_key=\"" + obj['oauth_consumer_key'] + "\", oauth_nonce=\"" + obj['oauth_nonce'] authHeader+= "\", oauth_signature_method=\"" + obj['oauth_signature_method'] + "\", oauth_token=\"" authHeader+= obj['oauth_token'] + "\", oauth_timestamp=\"" + obj['oauth_timestamp'] authHeader+= "\", oauth_version=\"" + obj['oauth_version'] + "\", oauth_signature=\""+obj['oauth_signature']+"\"" result = urlfetch(url=url+"?include_entities=true", method=GET, headers={'Authorization': authHeader}) if str(result.status_code) == '200': return {"result":"success","data":json.loads(result.content)} return {"result":"error","message":json.loads(result.content)}
def post(self, api_method, http_method="POST", expected_status=(200,), **extra_params): if not (api_method.startswith("http://") or api_method.startswith("https://")): api_method = "%s%s%s" % ( self.service_info["default_api_prefix"], api_method, self.service_info["default_api_suffix"], ) if self.token is None: # cookie = self.get_cookie() # self.token = OAuthAccessToken.get_by_key_name(cookie['key']) raise TwitterOAuthError("You need Login.") fetch = urlfetch( url=api_method, payload=self.get_signed_body(api_method, self.token, http_method, **extra_params), method=http_method, ) self.logging("POST", api_method, fetch.status_code, **extra_params) if fetch.status_code not in expected_status: raise ValueError("Error calling... Got return status: %i [%r]" % (fetch.status_code, fetch.content)) return decode_json(fetch.content)
def get(self, api_method, http_method='GET', expected_status=(200,), **extra_params): if not (api_method.startswith('http://') or api_method.startswith('https://')): api_method = '%s%s%s' % ( self.service_info['default_api_prefix'], api_method, self.service_info['default_api_suffix'] ) if self.token is None: #cookie = self.get_cookie() #self.token = OAuthAccessToken.get_by_key_name(cookie['key']) #self.token = self.get_access_token(self) #if not self.token: # raise TwitterOAuthError("You need Login.") raise TwitterOAuthError("You need Login.") fetch = urlfetch(self.get_signed_url( api_method, self.token, http_method, **extra_params )) self.logging('GET', api_method, fetch.status_code, **extra_params) if fetch.status_code not in expected_status: raise ValueError( "Error calling... Got return status: %i [%r]" % (fetch.status_code, fetch.content) ) return decode_json(fetch.content)
def get(self, api_method, http_method='GET', expected_status=(200,), **extra_params): if not (api_method.startswith('http://') or api_method.startswith('https://')): api_method = '%s%s%s' % ( self.service_info['default_api_prefix'], api_method, self.service_info['default_api_suffix'] ) signed_url = self.get_signed_url( api_method, self.token, http_method, **extra_params ) requestComplete = 0; error = '' while requestComplete == 0: try: fetch = urlfetch(signed_url) requestComplete = 1 error = '' except DownloadError: error = "Could not retrieve from social networks. The server could not be contacted at this time. Please try again later." if error <> '': return error if fetch.status_code not in expected_status: error = "Could not retrieve from social networks. The server could not be contacted at this time. Please try again later." return error return decode_json(fetch.content)
def post(self, api_method, http_method='POST', expected_status=(200,), **extra_params): if not (api_method.startswith('http://') or api_method.startswith('https://')): api_method = '%s%s%s' % ( self.service_info['default_api_prefix'], api_method, self.service_info['default_api_suffix'] ) if self.token is None: self.token = OAuthAccessToken.get_by_key_name(self.get_cookie()) logging.info(self.get_signed_body( api_method, self.token, http_method, **extra_params )) fetch = urlfetch(url=api_method, payload=self.get_signed_body( api_method, self.token, http_method, **extra_params ), method=http_method) if fetch.status_code not in expected_status: raise ValueError( "Error calling... Got return status: %i [%r]" % (fetch.status_code, fetch.content) ) return decode_json(fetch.content)
def get_data_from_signed_url(self, __url, __token=None, __meth='GET', **extra_params): return urlfetch( self.get_signed_url(__url, __token, __meth, **extra_params)).content
def web_get(url, params=None): """ Returns the contents of (url), by accessing it through GET """ if params is not None: params_str = "" for key,value in params.items(): params_str += "{0}={1}".format(key, value) url = "{0}?{1}".format(url, params_str) return urlfetch(url, None, GET)
def get_types_data(): logging.info("Fetching %s" % TYPES_URL) resp = urlfetch(TYPES_URL) if resp.status_code != 200: raise IOError("Error fetching spreadsheet data: %s (%r)" % ( resp.status_code, resp.content )) return resp.content
def get_data_from_signed_url(self, __url, __token=None, __meth='GET', **extra_params): remote_response = urlfetch(self.get_signed_url( __url, __token, __meth, **extra_params )).content logging.info("remote response is") logging.info(remote_response) logging.info("-*-"*30) return remote_response
def verifyCredentials(self): at = "OAuth " + self.config['access_token'] res = urlfetch('https://www.googleapis.com/buzz/v1/activities/@me/@self',payload="", method=GET, headers={'Content-Type':'application/x-www-form-urlencoded','Authorization':at}) if str(res.status_code) != '200': if not self._requestNewAccessToken(): raise WrongCredentialsException() return True
def get_data(): logging.info("Fetching %s" % DATA_URL) resp = urlfetch(DATA_URL) if resp.status_code != 200: logging.error("Error fetching spreadsheet data: %s (%r)" % ( resp.status_code, resp.content )) return return resp.content
def getProfileDetails(self): at = "OAuth " + self.config['access_token'] res = urlfetch('https://www.googleapis.com/buzz/v1/people/@me/@self?alt=json&key='+API_KEY, method=GET, headers={'Authorization':at}) if str(res.status_code) == '200': res = json.loads(res.content) return res return json.loads(res.content)
def getLastStatusDetails(self): #GET /buzz/v1/activities/@me/@self?alt=json&key= self.login() at = "OAuth " + self.config['access_token'] res = urlfetch('https://www.googleapis.com/buzz/v1/activities/@me/@self?alt=json&key='+API_KEY, method=GET, headers={'Authorization':at}) if str(res.status_code) == '200': return json.loads(res.content) return None
def getUserFeed(self, paging): self.login() at = "OAuth " + self.config['access_token'] url = paging if paging else 'https://www.googleapis.com/buzz/v1/activities/@me/@consumption?alt=json&key=' + API_KEY res = urlfetch(url, method=GET, headers={'Authorization': at}) if str(res.status_code) == '200': obj = json.loads(res.content) obj['requestUrl'] = url return obj return {"result": "error", "content": res.content}
def getProfileDetails(self): at = "OAuth " + self.config['access_token'] res = urlfetch( 'https://www.googleapis.com/buzz/v1/people/@me/@self?alt=json&key=' + API_KEY, method=GET, headers={'Authorization': at}) if str(res.status_code) == '200': res = json.loads(res.content) return res return json.loads(res.content)
def getShortUrl(url): API_key = 'AIzaSyA8rEK_zgeRPz-yDkQkcDBcaziMkhdMHQY' res = urlfetch(url='https://www.googleapis.com/urlshortener/v1/url?key='+API_key, method=POST, payload=json.dumps({'longUrl':url}), headers={'Content-Type':'application/json'}) if str(res.status_code) != '200': return url return json.loads(res.content)['id']
def updateStatus(self, statusObj): #self.login() statusText = unicode(statusObj['status']).encode('utf-8') objC = json.loads(self.user.twitter) obj = { 'status': statusText, 'oauth_consumer_key': self.twitter_consumer_key, 'oauth_nonce': getrandbits(64), 'oauth_signature_method': 'HMAC-SHA1', 'oauth_token': objC['oauth_token'], 'oauth_timestamp': int(time.time()), 'oauth_version': '1.0' } s = getBaseString("POST", "http://api.twitter.com/1/statuses/update.json", obj) #return {"result":s} key = self.twitter_consumer_secret + "&" + objC['oauth_token_secret'] obj['oauth_signature'] = hmac.new(key, s, sha1).digest().encode('base64')[:-1] for x in obj: obj[x] = encode(obj[x]) authHeader = "OAuth oauth_consumer_key=\"" + obj[ 'oauth_consumer_key'] + "\", oauth_nonce=\"" + obj['oauth_nonce'] authHeader += "\", oauth_signature_method=\"" + obj[ 'oauth_signature_method'] + "\", oauth_token=\"" authHeader += obj['oauth_token'] + "\", oauth_timestamp=\"" + obj[ 'oauth_timestamp'] authHeader += "\", oauth_version=\"" + obj[ 'oauth_version'] + "\", oauth_signature=\"" + obj[ 'oauth_signature'] + "\"" res = urlfetch(url='http://api.twitter.com/1/statuses/update.json', payload="status=" + encode(statusText), method=POST, headers={'Authorization': authHeader}) if str(res.status_code) == '200': obj = json.loads(res.content) objC['total_statuses'] = objC[ 'total_statuses'] + 1 if 'total_statuses' in objC else 1 objC['latest_status_id'] = obj['id_str'] self.user.twitter = json.dumps(objC) self.user.put() obj['result'] = "success" return obj else: return { 'result': "error", 'status': res.status_code, 'message': res.content, "status": statusText }
def getLastStatusDetails(self): #GET /buzz/v1/activities/@me/@self?alt=json&key= self.login() at = "OAuth " + self.config['access_token'] res = urlfetch( 'https://www.googleapis.com/buzz/v1/activities/@me/@self?alt=json&key=' + API_KEY, method=GET, headers={'Authorization': at}) if str(res.status_code) == '200': return json.loads(res.content) return None
def getFollowing(self, page=0): at = "OAuth " + self.config['access_token'] url = 'https://www.googleapis.com/buzz/v1/people/@me/@groups/@following?max-results=100&c=%d&alt=json&key=' % ( page * 100) + API_KEY res = urlfetch(url, method=GET, headers={'Authorization': at}) if str(res.status_code) == '200': res = json.loads(res.content)['data'] try: obj = res['entry'] except Exception, e: res['entry'] = [] return res['entry']
def getFollowers(self,page=0): at = "OAuth " + self.config['access_token'] res = urlfetch('https://www.googleapis.com/buzz/v1/people/@me/@groups/@followers?max-results=100&c=%d&alt=json&key='%(page*100) +API_KEY, method=GET, headers={'Authorization':at}) if str(res.status_code) == '200': res = json.loads(res.content)['data'] try: obj = res['entry'] except Exception,e: res['entry'] = [] return res['entry']
def getUserFeed(self,paging): self.login() at = "OAuth " + self.config['access_token'] url = paging if paging else 'https://www.googleapis.com/buzz/v1/activities/@me/@consumption?alt=json&key='+API_KEY res = urlfetch(url, method=GET, headers={'Authorization':at}) if str(res.status_code) == '200': obj = json.loads(res.content) obj['requestUrl'] = url return obj return {"result":"error","content":res.content}
def do_actual_ipn_handling(payload, kwargs): if kwargs['payment_status'] != 'Completed': return '1' verification_payload = 'cmd=_notify-validate&' + payload resp = urlfetch(url=ENDPOINT, method=POST, payload=verification_payload) if resp.content != 'VERIFIED': return '2' campaign = kwargs['custom'] if not campaign: return '3' if not campaign.startswith('wikihouse.'): return '4' campaign_id = campaign.split('.', 1)[1].strip() if campaign_id not in CAMPAIGN_KEYS: return '5' receiver = kwargs['receiver_email'] if receiver != PAYPAL_ACCOUNT: return '6' currency = kwargs['mc_currency'] if currency not in CURRENCIES: return '7' gross = kwargs['mc_gross'] fee = kwargs['mc_fee'] gross_d = Decimal(gross) fee_d = Decimal(fee) net = gross_d - fee_d if net <= 0: return '8' txn_id = kwargs['txn_id'] first_name = kwargs.get('first_name') if first_name: first_name += ' ' payer_name = (first_name + kwargs.get('last_name', '')).strip() payer_email = kwargs['payer_email'] txn = PayPalTransaction.get_or_insert( key_name=txn_id, campaign_id=campaign_id, payer_email=payer_email, fee=fee, gross=gross, info_payload=payload, net=str(net), payer_name=payer_name, currency=currency ) campaign_key = CAMPAIGN_KEYS[campaign_id] campaign = Campaign.get(campaign_key) db.run_in_transaction(update_campaign_tallies, campaign, txn_id, currency, net) txn.is_handled = True txn.put() return 'OK'
def __init__(self, url): self.mainURL = url self._error_bit = False if not urlparse.urlparse(self.mainURL).scheme: self.mainURL = "http://" + self.mainURL try: self._res = urlfetch(self.mainURL) if self._res.status_code != 200: raise Exception() self.soup = bs(self._res.content) except Exception, e: self._error_bit = True raise e
def __init__(self, url): self.mainURL = url self._error_bit = False if not urlparse.urlparse(self.mainURL).scheme: self.mainURL = "http://" + self.mainURL try: self._res = urlfetch(self.mainURL) if self._res.status_code != 200: raise Exception() self.soup = bs(self._res.content) except Exception,e: self._error_bit = True raise e
def updateStatus(self, statusObj): req = {} req['data'] = {} req['data']['object'] = {} req['data']['object']['type'] = "note" req['data']['object']['content'] = statusObj['status'] if 'link' in statusObj: curUrl = statusObj['link']['url'] req['data']['object']["attachments"] = [{ "content": statusObj['link']['description'], "type": "article", "title": statusObj['link']['title'], "links": { "alternate": [{ "href": statusObj['link']['url'], "type": "text/html" }], } }] reqStr = json.dumps(req) at = "OAuth " + self.config['access_token'] res = urlfetch( 'https://www.googleapis.com/buzz/v1/activities/@me/@self?alt=json&key=' + API_KEY, payload=reqStr, method=POST, headers={ 'Authorization': at, 'Content-Type': 'application/json' }) if str(res.status_code) == '200': res = json.loads(res.content) res['result'] = 'success' gg = json.loads(self.user.google) gg['total_statuses'] = gg[ 'total_statuses'] + 1 if 'total_statuses' in gg else 1 gg['latest_status_id'] = res['data']['id'] self.user.google = json.dumps(gg) res['extra'] = req return res return { 'result': "error", 'status': res.status_code, 'message': json.loads(res.content) }
def verifyCredentials(self): at = "OAuth " + self.config['access_token'] res = urlfetch( 'https://www.googleapis.com/buzz/v1/activities/@me/@self', payload="", method=GET, headers={ 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': at }) if str(res.status_code) != '200': if not self._requestNewAccessToken(): raise WrongCredentialsException() return True
def get_exchange_rate_to_gbp(currency, cache={}): if currency == 'GBP': return 1 if currency in cache: return cache[currency] rate = memcache.get('exchange:%s' % currency) if rate: return cache.setdefault(currency, rate) url = "https://rate-exchange.appspot.com/currency?from=%s&to=GBP" % currency try: rate = decode_json(urlfetch(url).content)['rate'] except Exception, err: logging.error("currency conversion: %s" % err) return 0
def post_raw(self, api_method, http_method='POST', **extra_params): if not (api_method.startswith('http://') or api_method.startswith('https://')): api_method = '%s%s%s' % ( self.service_info['default_api_prefix'], api_method, self.service_info['default_api_suffix'] ) if self.token is None: self.token = OAuthAccessToken.get_by_key_name(self.get_cookie()) return urlfetch(url=api_method, payload=self.get_signed_body( api_method, self.token, http_method, **extra_params ), method=http_method)
def get_exchange_rate_to_gbp(currency, cache={}): if currency == 'GBP': return 1 if currency in cache: return cache[currency] rate = memcache.get('exchange:%s' % currency) if rate: return cache.setdefault(currency, rate) url = "https://rate-exchange.appspot.com/currency?from=%s&to=GBP" % currency try: rate = float(decode_json(urlfetch(url).content)['rate']) except Exception, err: logging.error("currency conversion: %s" % err) return 0
def do_actual_ipn_handling(payload, kwargs): if kwargs['payment_status'] != 'Completed': return '1' verification_payload = 'cmd=_notify-validate&' + payload resp = urlfetch(url=ENDPOINT, method=POST, payload=verification_payload) if resp.content != 'VERIFIED': return '2' campaign = kwargs['custom'] if not campaign: return '3' if not campaign.startswith('wikihouse.'): return '4' campaign_id = campaign.split('.', 1)[1].strip() if campaign_id not in CAMPAIGN_KEYS: return '5' receiver = kwargs['receiver_email'] if receiver != PAYPAL_ACCOUNT: return '6' currency = kwargs['mc_currency'] if currency not in CURRENCIES: return '7' gross = kwargs['mc_gross'] fee = kwargs['mc_fee'] gross_d = Decimal(gross) fee_d = Decimal(fee) net = gross_d - fee_d if net <= 0: return '8' txn_id = kwargs['txn_id'] first_name = kwargs.get('first_name') if first_name: first_name += ' ' payer_name = (first_name + kwargs.get('last_name', '')).strip() payer_email = kwargs['payer_email'] txn = PayPalTransaction.get_or_insert(key_name=txn_id, campaign_id=campaign_id, payer_email=payer_email, fee=fee, gross=gross, info_payload=payload, net=str(net), payer_name=payer_name, currency=currency) campaign_key = CAMPAIGN_KEYS[campaign_id] campaign = Campaign.get(campaign_key) db.run_in_transaction(update_campaign_tallies, campaign, txn_id, currency, net) txn.is_handled = True txn.put() return 'OK'
def _requestNewAccessToken(self): reqStr = ['client_id='+CLIENT_ID, 'client_secret='+CLIENT_SECRET, 'refresh_token='+self.config['refresh_token'], 'grant_type=refresh_token'] res = urlfetch('https://accounts.google.com/o/oauth2/token',payload='&'.join(reqStr), method=POST, headers={'Content-Type':'application/x-www-form-urlencoded'}) if str(res.status_code) == '200': obj = json.loads(res.content) self.config['access_token'] = obj['access_token'] self.user.google = json.dumps(self.config) self.user.put() return True else: return False
def setCredentials(self, verifier): objC = json.loads(self.user.twitter) objC['oauth_verifier'] = verifier obj = { 'oauth_consumer_key': self.twitter_consumer_key, 'oauth_nonce': getrandbits(64), 'oauth_signature_method': 'HMAC-SHA1', 'oauth_token': objC['oauth_token'], 'oauth_timestamp': int(time.time()), 'oauth_verifier': verifier, 'oauth_version': '1.0' } s = getBaseString("POST", "https://api.twitter.com/oauth/access_token", obj) key = self.twitter_consumer_secret + "&" + objC['oauth_token_secret'] obj['oauth_signature'] = hmac.new(key, s, sha1).digest().encode('base64')[:-1] for x in obj: obj[x] = encode(obj[x]) authHeader = "OAuth oauth_consumer_key=\"" + obj[ 'oauth_consumer_key'] + "\", oauth_nonce=\"" + obj['oauth_nonce'] authHeader += "\", oauth_signature_method=\"" + obj[ 'oauth_signature_method'] + "\", oauth_token=\"" authHeader += obj['oauth_token'] + "\", oauth_timestamp=\"" + obj[ 'oauth_timestamp'] authHeader += "\", oauth_verifier=\"" + obj[ 'oauth_verifier'] + "\", oauth_version=\"" #authHeader+= obj['oauth_version'] + "\"" authHeader += obj['oauth_version'] + "\", oauth_signature=\"" + obj[ 'oauth_signature'] + "\"" result = urlfetch(url='https://api.twitter.com/oauth/access_token', method=POST, headers={'Authorization': authHeader}) if str(result.status_code) == '200': res = {} for x in result.content.split('&'): obj = x.split('=') res[obj[0]] = obj[1] objC.update(res) self.user.twitter = json.dumps(objC) self.user.put() return result.content return False
def get(self, api_method, http_method="GET", expected_status=(200,), **extra_params): if not (api_method.startswith("http://") or api_method.startswith("https://")): api_method = "%s%s%s" % ( self.service_info["default_api_prefix"], api_method, self.service_info["default_api_suffix"], ) if self.token is None: self.token = OAuthAccessToken.get_by_key_name(self.get_cookie()) fetch = urlfetch(self.get_signed_url(api_method, self.token, http_method, **extra_params)) if fetch.status_code not in expected_status: raise ValueError("Error calling... Got return status: %i [%r]" % (fetch.status_code, fetch.content)) return decode_json(fetch.content)
def get(self, api_method, http_method="GET", expected_status=(200,), **extra_params): if not (api_method.startswith("http://") or api_method.startswith("https://")): api_method = "%s%s%s" % ( self.service_info["default_api_prefix"], api_method, self.service_info["default_api_suffix"], ) if self.token is None: raise MyError(500, "Error - token is not set") fetch = urlfetch(self.get_signed_url(api_method, self.token, http_method, **extra_params)) if fetch.status_code not in expected_status: raise MyError(fetch.status_code, fetch.content) return decode_json(fetch.content)
def authenticated(self,user): if self.request.get("code") not in (None,""): code = self.request.get("code") reqStr = ['code='+code, 'client_id='+CLIENT_ID, 'client_secret='+ CLIENT_SECRET, 'grant_type=authorization_code', 'redirect_uri=http://grafiteapp.appspot.com/buzz/authenticated/' ] #httpscon.request("POST","/o/oauth2/token",reqStr) res = urlfetch('https://accounts.google.com/o/oauth2/token',payload='&'.join(reqStr),method=POST) if str(res.status_code) == '200': obj = json.loads(res.content) obj['expires'] = time.time()+int(obj['expires_in']) user.google = json.dumps(obj) user.put() self.redirect('/userHome') self.error(302)
def post(self, api_method, http_method='POST', expected_status=(200,), **extra_params): if not (api_method.startswith('http://') or api_method.startswith('https://')): api_method = '%s%s%s' % ( self.service_info['default_api_prefix'], api_method, self.service_info['default_api_suffix'] ) if self.token is None: raise MyError(500, "token is not set") fetch = urlfetch(url=api_method, payload=self.get_signed_body( api_method, self.token, http_method, **extra_params ), method=http_method) if fetch.status_code not in expected_status: raise MyError(fetch.status_code, fetch.content) return decode_json(fetch.content)
def authenticated(self, user): if self.request.get("code") not in (None, ""): url = "https://graph.facebook.com/oauth/access_token?" props = [ "client_id=" + AppID, "redirect_uri=http://grafiteapp.appspot.com/facebook/authenticated/", "client_secret=" + AppSecret, "code=" + self.request.get("code"), ] url = url + "&".join(props) res = urlfetch(url) if str(res.status_code) == "200": pos = str(res.content).find("access_token=") if pos != -1: token = str(res.content)[pos + len("access_token=") :] user.facebook = json.dumps({"access_token": token, "total_statuses": 0, "latest_status_id": ""}) user.put() self.redirect("/userHome") self.error(302)
def updateImage(key, url): logging.debug("Update request! %s %s"%(key,url)) #fetch the image res = urlfetch(url) if res.status_code != 200: return {"result":"error","message":"Unable to retrieve URL"} contentType = res.headers['Content-Type'] if contentType[:contentType.find('/')].lower() != 'image': return {"result":"error","message":"Invalid Image"} record = None if ImageMap.exists(key): record = ImageMap.get_by_key_name(key) else: record = ImageMap(key_name=key) record.contentType = contentType record.image = db.Blob(res.content) record.put() return {"result":"success","key":key}
def unfollowUser(self, tUser2): url = 'http://api.twitter.com/1/friendships/destroy.json' user2Id = tUser2.getProfileDetails()['id'] objC = json.loads(self.user.twitter) obj = { 'user_id': user2Id, 'oauth_consumer_key': self.twitter_consumer_key, 'oauth_nonce': getrandbits(64), 'oauth_signature_method': 'HMAC-SHA1', 'oauth_token': objC['oauth_token'], 'oauth_timestamp': int(time.time()), 'oauth_version': '1.0' } s = getBaseString("POST", url, obj) key = self.twitter_consumer_secret + "&" + objC['oauth_token_secret'] obj['oauth_signature'] = hmac.new(key, s, sha1).digest().encode('base64')[:-1] for x in obj: obj[x] = encode(obj[x]) authHeader = "OAuth oauth_consumer_key=\"" + obj[ 'oauth_consumer_key'] + "\", oauth_nonce=\"" + obj['oauth_nonce'] authHeader += "\", oauth_signature_method=\"" + obj[ 'oauth_signature_method'] + "\", oauth_token=\"" authHeader += obj['oauth_token'] + "\", oauth_timestamp=\"" + obj[ 'oauth_timestamp'] authHeader += "\", oauth_version=\"" + obj[ 'oauth_version'] + "\", oauth_signature=\"" + obj[ 'oauth_signature'] + "\"" result = urlfetch(url=url, method=POST, payload="user_id=" + encode(str(user2Id)), headers={'Authorization': authHeader}) if str(result.status_code) == '200': return {"result": "success", "data": json.loads(result.content)} return { "result": "error", "error_code": result.status_code, "content": result.content }
def authenticated(self, user): if self.request.get("code") not in (None, ""): code = self.request.get("code") reqStr = [ 'code=' + code, 'client_id=' + CLIENT_ID, 'client_secret=' + CLIENT_SECRET, 'grant_type=authorization_code', 'redirect_uri=http://grafiteapp.appspot.com/buzz/authenticated/' ] #httpscon.request("POST","/o/oauth2/token",reqStr) res = urlfetch('https://accounts.google.com/o/oauth2/token', payload='&'.join(reqStr), method=POST) if str(res.status_code) == '200': obj = json.loads(res.content) obj['expires'] = time.time() + int(obj['expires_in']) user.google = json.dumps(obj) user.put() self.redirect('/userHome') self.error(302)
def requestAuthenticationURL(self): obj = { 'oauth_callback': self.redirect_uri, 'oauth_consumer_key': self.twitter_consumer_key, 'oauth_nonce': getrandbits(64), 'oauth_signature_method': 'HMAC-SHA1', 'oauth_timestamp': int(time.time()), 'oauth_version': '1.0' } s = getBaseString("POST", "https://api.twitter.com/oauth/request_token", obj) key = self.twitter_consumer_secret + "&" obj['oauth_signature'] = hmac.new(key, s, sha1).digest().encode('base64')[:-1] for x in obj: obj[x] = encode(obj[x]) authHeader = "OAuth oauth_nonce=\"" + obj[ 'oauth_nonce'] + "\", oauth_callback=\"" + obj['oauth_callback'] authHeader += "\", oauth_signature_method=\"" + obj[ 'oauth_signature_method'] + "\", oauth_timestamp=\"" authHeader += obj[ 'oauth_timestamp'] + "\", oauth_consumer_key=\"" + obj[ 'oauth_consumer_key'] authHeader += "\", oauth_signature=\"" + obj[ 'oauth_signature'] + "\", oauth_version=\"" authHeader += obj['oauth_version'] + "\"" result = urlfetch(url='https://api.twitter.com/oauth/request_token', method=POST, headers={'Authorization': authHeader}) if str(result.status_code) != '200': return None res = {} for x in result.content.split('&'): obj = x.split('=') res[obj[0]] = obj[1] self.user.twitter = json.dumps(res) self.user.put() return "https://api.twitter.com/oauth/authorize?oauth_token=" + res[ 'oauth_token']
def _requestNewAccessToken(self): reqStr = [ 'client_id=' + CLIENT_ID, 'client_secret=' + CLIENT_SECRET, 'refresh_token=' + self.config['refresh_token'], 'grant_type=refresh_token' ] res = urlfetch( 'https://accounts.google.com/o/oauth2/token', payload='&'.join(reqStr), method=POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}) if str(res.status_code) == '200': obj = json.loads(res.content) self.config['access_token'] = obj['access_token'] self.user.google = json.dumps(self.config) self.user.put() return True else: return False
def getRelationship(self, tUser2): url = 'http://api.twitter.com/1/friendships/show.json?source_id=%s&target_id=%s' % ( self.getProfileDetails()['id_str'], tUser2.getProfileDetails()['id_str']) objC = json.loads(self.user.twitter) obj = { 'oauth_consumer_key': self.twitter_consumer_key, 'oauth_nonce': getrandbits(64), 'oauth_signature_method': 'HMAC-SHA1', 'oauth_token': objC['oauth_token'], 'oauth_timestamp': int(time.time()), 'oauth_version': '1.0' } s = getBaseString("GET", url, obj) key = self.twitter_consumer_secret + "&" + objC['oauth_token_secret'] obj['oauth_signature'] = hmac.new(key, s, sha1).digest().encode('base64')[:-1] for x in obj: obj[x] = encode(obj[x]) authHeader = "OAuth oauth_consumer_key=\"" + obj[ 'oauth_consumer_key'] + "\", oauth_nonce=\"" + obj['oauth_nonce'] authHeader += "\", oauth_signature_method=\"" + obj[ 'oauth_signature_method'] + "\", oauth_token=\"" authHeader += obj['oauth_token'] + "\", oauth_timestamp=\"" + obj[ 'oauth_timestamp'] authHeader += "\", oauth_version=\"" + obj[ 'oauth_version'] + "\", oauth_signature=\"" + obj[ 'oauth_signature'] + "\"" result = urlfetch(url=url, method=GET, headers={'Authorization': authHeader}) if str(result.status_code) == '200': return json.loads(result.content) return None
def authenticated(self, user): if self.request.get("code") not in (None, ""): url = 'https://graph.facebook.com/oauth/access_token?' props = [ 'client_id=' + AppID, 'redirect_uri=http://grafiteapp.appspot.com/facebook/authenticated/', 'client_secret=' + AppSecret, 'code=' + self.request.get("code") ] url = url + '&'.join(props) res = urlfetch(url) if str(res.status_code) == '200': pos = str(res.content).find("access_token=") if pos != -1: token = str(res.content)[pos + len('access_token='):] user.facebook = json.dumps({ "access_token": token, "total_statuses": 0, "latest_status_id": "" }) user.put() self.redirect('/userHome') self.error(302)
def getFeed(self, feedName='user_timeline'): objC = json.loads(self.user.twitter) obj = { 'include_entities': 'true', 'oauth_consumer_key': self.twitter_consumer_key, 'oauth_nonce': getrandbits(64), 'oauth_signature_method': 'HMAC-SHA1', 'oauth_token': objC['oauth_token'], 'oauth_timestamp': int(time.time()), 'oauth_version': '1.0' } url = "http://api.twitter.com/1/statuses/%s.json" % feedName s = getBaseString("GET", url, obj) key = self.twitter_consumer_secret + "&" + objC['oauth_token_secret'] obj['oauth_signature'] = hmac.new(key, s, sha1).digest().encode('base64')[:-1] for x in obj: obj[x] = encode(obj[x]) authHeader = "OAuth oauth_consumer_key=\"" + obj[ 'oauth_consumer_key'] + "\", oauth_nonce=\"" + obj['oauth_nonce'] authHeader += "\", oauth_signature_method=\"" + obj[ 'oauth_signature_method'] + "\", oauth_token=\"" authHeader += obj['oauth_token'] + "\", oauth_timestamp=\"" + obj[ 'oauth_timestamp'] authHeader += "\", oauth_version=\"" + obj[ 'oauth_version'] + "\", oauth_signature=\"" + obj[ 'oauth_signature'] + "\"" result = urlfetch(url=url + "?include_entities=true", method=GET, headers={'Authorization': authHeader}) if str(result.status_code) == '200': return {"result": "success", "data": json.loads(result.content)} return {"result": "error", "message": json.loads(result.content)}
from google.appengine.api.urlfetch import fetch as urlfetch, GET, POST try: import json except Exception, err: from django.utils import simplejson as json def getShortUrl(url): if not hasattr(getShortUrl, 'key'): try: getShortUrl.key = open('goo-gl-key', 'r').read().strip() except Exception, e: return url #return url without shortening API_key = getShortUrl.key res = urlfetch(url='https://www.googleapis.com/urlshortener/v1/url?key=' + API_key, method=POST, payload=json.dumps({'longUrl': url}), headers={'Content-Type': 'application/json'}) if str(res.status_code) != '200': return url return json.loads(res.content)['id']
except Exception, e: res['entry'] = [] return res['entry'] return None def followUser(self, bUser2): bUserId = None try: bUserId = bUser2.getProfileDetails()['data']['id'] except Exception, e: return None bUserId = str(bUserId) at = "OAuth " + self.config['access_token'] url = 'https://www.googleapis.com/buzz/v1/people/@me/@groups/@following/%s?alt=json&key=%s' % ( bUserId, API_KEY) res = urlfetch(url, method=PUT, headers={'Authorization': at}) if str(res.status_code)[0] == '2': res = json.loads(res.content)['data'] res['result'] = 'success' return res return {'result': 'error', 'message': res.content} def unfollowUser(self, bUser2): bUserId = None try: bUserId = bUser2.getProfileDetails()['data']['id'] except Exception, e: return None bUserId = str(bUserId) at = "OAuth " + self.config['access_token'] url = 'https://www.googleapis.com/buzz/v1/people/@me/@groups/@following/%s?alt=json&key=%s' % (