def business_oauth2credential(): """Create OAuth2Credential class to hold access token information.""" return OAuth2Credential(client_id=CLIENT_ID, access_token=ACCESS_TOKEN, expires_in_seconds=EXPIRES_IN_SECONDS, scopes=BUSINESS_SCOPES, grant_type=auth.CLIENT_CREDENTIALS_GRANT, client_secret=CLIENT_SECRET)
def client_credential_oauth2credential(): return OAuth2Credential( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_url=None, access_token=ACCESS_TOKEN, expires_in_seconds=EXPIRES_IN_SECONDS, scopes=CLIENT_CREDENTIALS_SCOPES, grant_type=auth.CLIENT_CREDENTIALS_GRANT, refresh_token=None, )
def auth_code_oauth2credential(): return OAuth2Credential( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_url=REDIRECT_URL, access_token=ACCESS_TOKEN, expires_in_seconds=EXPIRES_IN_SECONDS, scopes=SCOPES, grant_type=auth.AUTHORIZATION_CODE_GRANT, refresh_token=REFRESH_TOKEN, )
def implicit_oauth2credential(): return OAuth2Credential( client_id=CLIENT_ID, client_secret=None, redirect_url=REDIRECT_URL, access_token=ACCESS_TOKEN, expires_in_seconds=EXPIRES_IN_SECONDS, scopes=SCOPES, grant_type=auth.IMPLICIT_GRANT, refresh_token=None, )
def oauth2credential(): """Create OAuth2Credential class to hold access token information.""" return OAuth2Credential( client_id=CLIENT_ID, redirect_url=REDIRECT_URL, access_token=ACCESS_TOKEN, expires_in_seconds=EXPIRES_IN_SECONDS, scopes=SCOPES, grant_type=auth.AUTHORIZATION_CODE_GRANT, client_secret=CLIENT_SECRET, refresh_token=REFRESH_TOKEN, )
def get_vtc_session(): user_id = session.get('user_id') if user_id is None: return user = User.query.filter_by(id=user_id).first() if user is None: return # if oauth2credential is None: # return false if user.uber_access_token is not None: uber_oauth2credentials = OAuth2Credential( client_id=uber_credentials['client_id'], scopes=uber_credentials['scopes'], redirect_url=uber_credentials['redirect_url'], client_secret=uber_credentials['client_secret'], access_token=user.uber_access_token, refresh_token=user.uber_refresh_token, expires_in_seconds=user.uber_expires_in_seconds, grant_type=user.uber_grant_type) g.uber_session = Session(oauth2credential=uber_oauth2credentials) g.uber_client = UberRidesClient(g.uber_session, sandbox_mode=(env != 'prod')) if user.lyft_access_token is not None: lyft_oauth2credentials = OAuth2Credential( client_id=lyft_credentials['client_id'], scopes=lyft_credentials['scopes'], redirect_url=lyft_credentials['redirect_url'], client_secret=lyft_credentials['client_secret'], access_token=user.lyft_access_token, refresh_token=user.lyft_refresh_token, expires_in_seconds=user.lyft_expires_in_seconds, grant_type=user.lyft_grant_type) g.lyft_session = Session(oauth2credential=lyft_oauth2credentials) g.lyft_client = LyftRidesClient(g.lyft_session)
def request_uber(): """Make sandbox Uber ride request""" search = Search.query.order_by(Search.date.desc()).first() search.uber_request = True db.session.commit() credentials2 = import_oauth2_credentials() oauth2credential = OAuth2Credential( client_id=credentials2.get('client_id'), access_token=sesh.get('access_token'), expires_in_seconds=credentials2.get('expires_in_seconds'), scopes=credentials2.get('scopes'), grant_type=credentials2.get('grant_type'), redirect_url=credentials2.get('redirect_url'), client_secret=credentials2.get('client_secret'), refresh_token=credentials2.get('refresh_token'), ) uber_session = Session(oauth2credential=oauth2credential) uber_client = UberRidesClient(uber_session, sandbox_mode=True) # receive data from Ajax call start_lat = request.form.get('start_lat') start_lng = request.form.get('start_lng') end_lat = request.form.get('end_lat') end_lng = request.form.get('end_lng') response = uber_client.get_products(37.3688301, -122.0363495) products = response.json.get('products') product_id = products[0].get('product_id') # make sandbox calls ride_request = uber_client.request_ride(product_id=product_id, start_latitude=37.3688301, start_longitude=-122.0363495, end_latitude=37.8003415, end_longitude=-122.4331332) ride_details = ride_request.json ride_id = ride_details.get('request_id') get_ride = uber_client.update_sandbox_ride(ride_id, 'accepted') send_uber_text(); return jsonify(ride_details)
def getUberClient(credentials): oauth2credential = OAuth2Credential( client_id=credentials.get('client_id'), access_token=credentials.get('access_token'), expires_in_seconds=credentials.get('expires_in_seconds'), scopes=credentials.get('scopes'), grant_type=credentials.get('grant_type'), redirect_url=credentials.get('redirect_url'), client_secret=credentials.get('client_secret'), refresh_token=credentials.get('refresh_token'), ) session = Session(oauth2credential=oauth2credential) return UberRidesClient(session)
def client_credential_grant_session(): """Create a Session from Client Credential Grant.""" oauth2credential = OAuth2Credential( client_id=None, redirect_url=None, access_token=ACCESS_TOKEN, expires_in_seconds=EXPIRES_IN_SECONDS, scopes=SCOPES_SET, grant_type=auth.CLIENT_CREDENTIAL_GRANT, client_secret=None, refresh_token=None, ) return Session(oauth2credential=oauth2credential)
def authorization_code_grant_session(): """Create a Session from Auth Code Grant Credential.""" oauth2credential = OAuth2Credential( client_id=None, redirect_url=None, access_token=ACCESS_TOKEN, expires_in_seconds=EXPIRES_IN_SECONDS, scopes=SCOPES_SET, grant_type=auth.AUTHORIZATION_CODE_GRANT, client_secret=None, refresh_token=REFRESH_TOKEN, ) return Session(oauth2credential=oauth2credential)
def implicit_grant_session(): """Create a Session from Implicit Grant Credential.""" oauth2credential = OAuth2Credential( client_id=None, redirect_url=None, access_token=ACCESS_TOKEN, expires_in_seconds=EXPIRES_IN_SECONDS, scopes=SCOPES_SET, grant_type=auth.IMPLICIT_GRANT, client_secret=None, refresh_token=None, ) return Session(oauth2credential=oauth2credential)
def search(): """Show search form and create user object if not in database.""" if 'access_token' not in sesh: return redirect(url_for('index')) else: credentials2 = import_oauth2_credentials() oauth2credential = OAuth2Credential( client_id=credentials2.get('client_id'), access_token=sesh.get('access_token'), expires_in_seconds=credentials2.get('expires_in_seconds'), scopes=credentials2.get('scopes'), grant_type=credentials2.get('grant_type'), redirect_url=credentials2.get('redirect_url'), client_secret=credentials2.get('client_secret'), refresh_token=credentials2.get('refresh_token'), ) uber_session = Session(oauth2credential=oauth2credential) uber_client = UberRidesClient(uber_session, sandbox_mode=True) user_profile = uber_client.get_user_profile().json sesh['user'] = { 'first_name': user_profile.get('first_name'), 'last_name': user_profile.get('last_name'), 'email': user_profile.get('email'), 'phone': user_profile.get('phone'), 'img_url': user_profile.get('picture') } if db.session.query(User).filter( User.email == user_profile['email']).count() == 0: user = User(first_name=user_profile.get('first_name'), last_name=user_profile.get('last_name'), img_url=user_profile.get('picture'), email=user_profile.get('email')) db.session.add(user) db.session.commit() return render_template( 'search.html', first_name=sesh['user'].get('first_name'), img_url=sesh['user'].get('img_url'), )
def create_uber_client(credentials): """Create an UberRidesClient from OAuth 2.0 credentials. Parameters credentials (dict) Dictionary of OAuth 2.0 credentials. Returns (UberRidesClient) An authorized UberRidesClient to access API resources. """ oauth2credential = OAuth2Credential( client_id=credentials.get('client_id'), access_token=credentials.get('access_token'), expires_in_seconds=credentials.get('expires_in_seconds'), scopes=credentials.get('scopes'), grant_type=credentials.get('grant_type'), redirect_url=credentials.get('redirect_url'), client_secret=credentials.get('client_secret'), refresh_token=credentials.get('refresh_token'), ) session = Session(oauth2credential=oauth2credential) return UberRidesClient(session, sandbox_mode=True)
def get_estimate(name_orig='home', name_dest='work', detail=False): if name_orig not in places or name_dest not in places: sys.exit('one or both unknown place names') orig = places[name_orig] dest = places[name_dest] storage = None if os.path.exists(utils.STORAGE_FILENAME): with open(utils.STORAGE_FILENAME, 'r') as storage_file: storage = safe_load(storage_file) api_client = None if storage and 'expires_in_seconds' in storage and int( time.time()) < storage['expires_in_seconds']: api_client = UberRidesClient( Session(oauth2credential=OAuth2Credential(**storage)), sandbox_mode=True) else: credentials = import_app_credentials() api_client = authorization_code_grant_flow( credentials, utils.STORAGE_FILENAME, ) products1, response1 = _get_estimate_response(api_client, orig, dest) products2, response2 = _get_estimate_response(api_client, dest, orig) print('{time}: {place1}->{place2}: {price1}, {place2}->{place1}: {price2}'. format(time=time.strftime("%x %X"), place1=name_orig, place2=name_dest, price1=response1.json.get('fare').get('display'), price2=response2.json.get('fare').get('display'))) if detail: _print_detail(products1, response1) _print_detail(products2, response2)
def get_session(self, redirect_url): """Create Session to store credentials. Parameters redirect_url (str) The full URL that the Uber server redirected to after the user authorized your app. Returns (Session) A Session object with OAuth 2.0 credentials. Raises UberIllegalState (APIError) Raised if redirect URL contains an error. """ query_params = self._extract_query(redirect_url) error = query_params.get('error') if error: raise UberIllegalState(error) # convert space delimited string to set scopes = query_params.get('scope') scopes_set = {scope for scope in scopes.split()} oauth2credential = OAuth2Credential( client_id=self.client_id, redirect_url=self.redirect_url, access_token=query_params.get('access_token'), expires_in_seconds=query_params.get('expires_in'), scopes=scopes_set, grant_type=auth.IMPLICIT_GRANT, ) return Session(oauth2credential=oauth2credential)
def __uber_action(self, nlu_entities=None): uber = None if nlu_entities is not None: if 'location' in nlu_entities: entities3=nlu_entities['search_query'][0]["value"] entities1=nlu_entities['location'][0]["value"] entities2=nlu_entities['location'][1]["value"] print entities3 print entities1 print entities2 if entities1 and entities2 is not None: response= requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=' %entities1) #add key resp_json_payload = response.json() lat1=(resp_json_payload['results'][0]['geometry']['location']['lat']) lng1=(resp_json_payload['results'][0]['geometry']['location']['lng']) response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=' %entities2) #add key resp_json_payload = response.json() lat2=(resp_json_payload['results'][0]['geometry']['location']['lat']) lng2=(resp_json_payload['results'][0]['geometry']['location']['lng']) oauth2credential = OAuth2Credential( client_id='', #add client id access_token='', #get access token expires_in_seconds= '2592000', scopes='all_trips delivery history history_lite places profile request request_receipt ride_widgets', grant_type='authorization_code', redirect_url='', #add redirect_url client_secret='', #add client secret refresh_token='', # add refresh token ) session = Session(oauth2credential=oauth2credential) client = UberRidesClient(session, sandbox_mode=True) print (client) response = client.get_products(lat1, lng1) credentials = session.oauth2credential #print (response) response = client.get_user_profile() profile = response.json # response_uber = client.get_price_estimates( # start_latitude=lat1, # start_longitude=lng1, # end_latitude=lat2, # end_longitude=lng2, # seat_count=1 # ) # estimate = response_uber.json.get('prices') # print estimate[0]['high_estimate'] # print estimate[0]['low_estimate'] # print estimate[0]['localized_display_name'] # print estimate[0]['currency_code'] # currency = estimate[0]['currency_code'] # hi_est = str(estimate[0]['high_estimate']) + str(estimate[0]['currency_code']) # low_est = str(estimate[0]['low_estimate']) + str(estimate[0]['currency_code']) # type_cab = estimate[0]['localized_display_name'] # print estimate[0] response = client.get_products(lat1, lng1) products = response.json.get('products') #print(products) if entities3 == 'Uber go': for i in range(1,5): if products[i]['display_name']=='uberGO': product_id = products[i].get('product_id') type_cab = products[i].get('display_name') elif entities3 == 'Uber pool': for i in range(1,5): if products[i]['display_name']=='POOL': product_id = products[i].get('product_id') type_cab = products[i].get('display_name') else: product_id = products[0].get('product_id') type_cab = products[0].get('display_name') estimate = client.estimate_ride( product_id=product_id, start_latitude=lat1, start_longitude=lng1, end_latitude=lat2, end_longitude=lng2, seat_count=1 ) fare = estimate.json.get('fare') bas = fare['display'] client.cancel_current_ride() response = client.request_ride( product_id=product_id, start_latitude=lat1, start_longitude=lng1, end_latitude=lat2, end_longitude=lng2, seat_count=1, fare_id=fare['fare_id'] ) request = response.json print request request_id = request.get('request_id') url = 'https://sandbox-api.uber.com/v1.2/sandbox/requests/' + request_id ur = 'https://sandbox-api.uber.com/v1.2/requests/' + request_id + '/map' token = "" #insert token data = { "status": "accepted" } headers = {'Authorization': 'Bearer ' + token, "Content-Type": "application/json"} #Call REST API respons = requests.put(url, data=json.dumps(data), headers=headers) respon = requests.get(ur, headers=headers) response = client.get_ride_details(request_id) ride = response.json print ride status = ride.get('status') dri_name = ride.get('driver').get('name') dri_pic = ride.get('driver').get('picture_url') eta = ride.get('destination').get('eta') car_pix = ride.get('vehicle').get('picture_url') # product_name1 = products[3]['display_name'] #GO # product_nam2 = products[2]['display_name'] #POOL uber_action = "Sure. Booking your uber from %s to %s. Your cab type is %s and estimated time of arrival is %s and fare will be approx %s" % (entities1, entities2, type_cab, eta, bas) cab_data = {"cabtype": type_cab, 'maxfare': bas, "minfare": eta, 'to': entities2, 'from': entities1, 'status':status, 'driver': dri_name, 'pic': dri_pic, 'car': car_pix, 'map':ur} #print cab_data requests.post("http://localhost:8080/cab", data=json.dumps(cab_data)) self.speech.synthesize_text(uber_action) else: self.__text_action("I'm sorry, I don't think that their is any cab available between these two locations.")
def __uber_action(self, nlu_entities=None): uber = None if nlu_entities is not None: if 'location' in nlu_entities: entities3 = nlu_entities['search_query'][0]["value"] entities1 = nlu_entities['location'][0]["value"] entities2 = nlu_entities['location'][1]["value"] print(entities3) print(entities1) print(entities2) if entities1 and entities2 is not None: response = requests.get( 'https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=AIzaSyAx_nPgGLpiiak3Ey0YgDaJjoqlcjZko1A' % entities1) # add key resp_json_payload = response.json() lat1 = ( resp_json_payload['results'][0]['geometry']['location']['lat']) lng1 = ( resp_json_payload['results'][0]['geometry']['location']['lng']) response = requests.get( 'https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=AIzaSyAx_nPgGLpiiak3Ey0YgDaJjoqlcjZko1A' % entities2) # add key resp_json_payload = response.json() lat2 = ( resp_json_payload['results'][0]['geometry']['location']['lat']) lng2 = ( resp_json_payload['results'][0]['geometry']['location']['lng']) oauth2credential = OAuth2Credential( client_id='FxkO4ImvByXu-7Dm1vYMHcKIt3C-3-LX ', # add client id access_token= 'JA. -HsSUvO2XciOsCC3M25dwxYZTxyr4T9WKRKW8SawMVLucIKNmSZSZtvuE2LUMfb_ykrWxDAAAAIhIo1wfiuri3URzNyQAAABiMGQ4NTgwMy0zOGEwLTQyYjMtODA2ZS03YTRjZjhlMTk2ZWU', # get access token expires_in_seconds='2592000', scopes= 'all_trips delivery history history_lite places profile request request_receipt ride_widgets', grant_type='authorization_code', redirect_url= 'http://localhost:8080/redirect_uri', # add redirect_url client_secret= 'hAjOfJ-OPiQ3dntDT9KtiLxwitcXrxu8-pNPRuzP', # add client secret refresh_token='', # add refresh token ) from uber_rides.auth import AuthorizationCodeGrant redirect_url = 'https://localhost:8080/redirect_uri', # add redirect_url auth_flow = AuthorizationCodeGrant( client_id='FxkO4ImvByXu-7Dm1vYMHcKIt3C-3-LX ', # add client id # access_token='JA.VUNmGAAAAAAAEgASAAAABwAIAAwAAAAAAAAAEgAAAAAAAAG8AAAAFAAAAAAADgAQAAQAAAAIAAwAAAAOAAAAkAAAABwAAAAEAAAAEAAAAKJLlVbnq3rq5cidLOUCeZZsAAAAxfnlfHgkh1D_dT92vApueOOrPLV79RicmAdIVBZXV4jUZfneV1jq3pcF2Xwdd5AIaCpvZxVY32u-HsSUvO2XciOsCC3M25dwxYZTxyr4T9WKRKW8SawMVLucIKNmSZSZtvuE2LUMfb_ykrWxDAAAAIhIo1wfiuri3URzNyQAAABiMGQ4NTgwMy0zOGEwLTQyYjMtODA2ZS03YTRjZjhlMTk2ZWU', # get access token # expires_in_seconds='2592000', scopes= 'all_trips delivery history history_lite places profile request request_receipt ride_widgets', # scopes='ride_widgets', # grant_type='authorization_code', redirect_url= 'https://localhost:8080/redirect_uri', # add redirect_url client_secret= 'hAjOfJ-OPiQ3dntDT9KtiLxwitcXrxu8-pNPRuzP', # add client secret # refresh_token='', # add refresh token ) redirect_url = 'https://localhost:8080/redirect_uri', # add redirect_url auth_url = auth_flow.get_authorization_url() #session = auth_flow.get_session(redirect_url) session = Session(oauth2credential=oauth2credential) print(session) client = UberRidesClient(session, sandbox_mode=True) print(client) response = client.get_products(lat1, lng1) credentials = session.oauth2credential print(response) response = client.get_user_profile() profile = response.json print(profile) # response_uber = client.get_price_estimates( # start_latitude=lat1, # start_longitude=lng1, # end_latitude=lat2, # end_longitude=lng2, # seat_count=1 # ) # estimate = response_uber.json.get('prices') # print estimate[0]['high_estimate'] # print estimate[0]['low_estimate'] # print estimate[0]['localized_display_name'] # print estimate[0]['currency_code'] # currency = estimate[0]['currency_code'] # hi_est = str(estimate[0]['high_estimate']) + str(estimate[0]['currency_code']) # low_est = str(estimate[0]['low_estimate']) + str(estimate[0]['currency_code']) # type_cab = estimate[0]['localized_display_name'] # print estimate[0] response = client.get_products(lat1, lng1) products = response.json.get('products') # print(products) if entities3 == 'Uber go': for i in range(1, 5): if products[i]['display_name'] == 'uberGO': product_id = products[i].get('product_id') type_cab = products[i].get('display_name') elif entities3 == 'Uber pool': for i in range(1, 5): if products[i]['display_name'] == 'POOL': product_id = products[i].get('product_id') type_cab = products[i].get('display_name') else: product_id = products[0].get('product_id') type_cab = products[0].get('display_name') estimate = client.estimate_ride(product_id=product_id, start_latitude=lat1, start_longitude=lng1, end_latitude=lat2, end_longitude=lng2, seat_count=1) fare = estimate.json.get('fare') bas = fare['display'] client.cancel_current_ride() response = client.request_ride(product_id=product_id, start_latitude=lat1, start_longitude=lng1, end_latitude=lat2, end_longitude=lng2, seat_count=1, fare_id=fare['fare_id']) request = response.json print(request) request_id = request.get('request_id') url = 'https://sandbox-api.uber.com/v1.2/sandbox/requests/' + request ur = 'https://sandbox-api.uber.com/v1.2/requests/' + request + '/map' token = "hAjOfJ-OPiQ3dntDT9KtiLxwitcXrxu8-pNPRuzP" # insert token data = {"status": "accepted"} headers = { 'Authorization': 'Bearer ' + token, "Content-Type": "application/json" } # Call REST API response = requests.put(url, data=json.dumps(data), headers=headers) response = requests.get(ur, headers=headers) response = client.get_ride_details(request_id) ride = response.json print(ride) status = ride.get('status') dri_name = ride.get('driver').get('name') dri_pic = ride.get('driver').get('picture_url') eta = ride.get('destination').get('eta') car_pix = ride.get('vehicle').get('picture_url') # product_name1 = products[3]['display_name'] #GO # product_nam2 = products[2]['display_name'] #POOL uber_action = "Sure. Booking your uber from %s to %s. Your cab type is %s and estimated time of arrival is %s and fare will be approx %s" % ( entities1, entities2, type_cab, eta, bas) cab_data = { "cabtype": type_cab, 'maxfare': bas, "minfare": eta, 'to': entities2, 'from': entities1, 'status': status, 'driver': dri_name, 'pic': dri_pic, 'car': car_pix, 'map': ur } # print cab_data requests.post("http://localhost:8080/cab", data=json.dumps(cab_data)) self.speech.synthesize_text(uber_action) else: self.__text_action( "I'm sorry, I don't think that their is any cab available between these two locations." )