def oauth(): auth_flow = AuthorizationCodeGrant( credentials.get('client_id'), credentials.get('scopes'), credentials.get('client_secret'), credentials.get('redirect_url'), ) session = auth_flow.get_session(request.url) oauth2credential = session.oauth2credential token = { "client_id":oauth2credential.client_id, "access_token":oauth2credential.access_token, "expires_in_seconds": oauth2credential.expires_in_seconds, "scopes": list(oauth2credential.scopes), "grant_type": oauth2credential.grant_type, "redirect_url": oauth2credential.redirect_url, "client_secret": oauth2credential.client_secret, "refresh_token": oauth2credential.refresh_token, } client = UberRidesClient(session) response = client.get_user_profile() profile = response.json uuid = profile.get('uuid') api.set_token(uuid,token) return render_template('oauth2.html', uuid=uuid, token=token)
def create_client(self, msisdn, state, code): # state = ti12Pnewi7FHXsEWC7OAz9gqlE85ais2 & code = ovNXkhAGr2oVSFDF7fAJJGCJGZDeAU # client = UberRidesClient(session) # auth_flow = pickle.loads(self.redis.get('ub/123')) incomingMsisdn = json.loads(self.redis.get("inc/%s" % (msisdn))) auth_flow = pickle.loads(incomingMsisdn[1]) # self.redis.set("inc/%s" % (msisdn), json.dumps(incomingMsisdn)) # redirect_url = REDIRECT_URL + "?code="+str(code)+"&state="+str(self.state_uber) redirect_url = REDIRECT_URL + "?code=" + str(code) + "&state=" + str( state) # auth_flow = ClientCredentialGrant(CLIENT_ID, {'profile','request'}, CLIENT_SECRET) # auth_flow = self.AUTH # auth_flow.state_token = state # auth_flow = self.AUTH # auth_flow = AuthorizationCodeGrant(CLIENT_ID,{'profile','request'},CLIENT_SECRET,REDIRECT_URL, state) session = auth_flow.get_session(redirect_url) client = UberRidesClient(session, sandbox_mode=SANDBOX_MODE) credentials = session.oauth2credential self.redis.set("cred/%s" % (msisdn), pickle.dumps(credentials)) # print credentials response = client.get_user_profile() profile = response.json first_name = profile.get('first_name') last_name = profile.get('last_name') email = profile.get('email') return (first_name, last_name, email)
def uber_profile_exists(self): ### ----- Check if user has Uber Profile -----------# contents = self.content client_id = contents['client_id'] scopes = set(contents['scopes']) client_secret = contents['client_secret'] redirect_uri = contents['redirect_uri'] code = contents['code'] auth_flow = AuthorizationCodeGrant(client_id, scopes, client_secret, redirect_uri) auth_url = auth_flow.get_authorization_url() r = requests.get(auth_url, allow_redirects=True) encodedStr = r.url # Get rid of Url encoding decoded_url = unquote(encodedStr) idx = decoded_url.index("state=") state_str = decoded_url[idx:] # TODO: FIGURE OUT Whats going on with redirect URI new_redirect_url = redirect_uri + "?" + code + "&" + state_str # TODO: Figure this out for new session session = auth_flow.get_session(new_redirect_url) client = UberRidesClient(session, sandbox_mode=True) credentials = session.oauth2credential response = client.get_user_profile() profile = response.json email = profile.get('email') #THIS Is all a guess: has_uber_profile = True if email is not None else False return has_uber_profile
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 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 __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.")
class Uber_api(object): def __init__(self): self.url, self.auth_flow = get_auth_url() def get_AuthUrl(self): return self.url def get_AuthCredentials(self, red_url, cred): if red_url: session = self.auth_flow.get_session(red_url) self.client = UberRidesClient(session, sandbox_mode=False) cred = session.oauth2credential return cred else: session = Session(oauth2credential=cred) self.client = UberRidesClient(session, sandbox_mode=False) def user_profile(self): reponse = self.client.get_user_profile() profile = reponse.json first_name = profile.get('first_name') last_name = profile.get('last_name') email = profile.get('email') return first_name, last_name, email def user_history(self): reponse = self.client.get_user_activity() history = reponse.json return history def get_products(self, lat=37.77, lng=-122.41): response = self.client.get_products(lat, lng).json #self.product_id = pdct[0].get('product_id') return response def get_estimate_pricess(self, start_latitude=37.77, start_longitude=-122.41, end_latitude=37.79, end_longitude=-122.41): res = self.client.get_price_estimates(start_latitude=start_latitude, start_longitude=start_longitude, end_latitude=end_latitude, end_longitude=end_longitude).json return res def get_estimate_time(self, start_latitude=37.77, start_longitude=-122.41, product_id='57c0ff4e-1493-4ef9-a4df-6b961525cf92'): res = self.client.get_pickup_time_estimates( start_latitude=start_latitude, start_longitude=start_longitude, product_id=product_id).json return res def get_estimate_price(self, st_lat=37.77, st_lng=-122.41, dt_lat=37.79, dt_lng=-122.41, seat_count=2, product_id='a1111c8c-c720-46c3-8534-2fcdd730040d'): estimate = self.client.estimate_ride(product_id=product_id, start_latitude=st_lat, start_longitude=st_lng, end_latitude=dt_lat, end_longitude=dt_lng, seat_count=seat_count) est = estimate.json.get('fare') #self.fare_id = est['fare_id'] return est def request_ride(self, st_lat=37.77, st_lng=-122.41, dt_lat=37.79, dt_lng=-122.41, seat_count=2, prod_id='', fare_id=''): response = self.client.request_ride(product_id=prod_id, start_latitude=st_lat, start_longitude=st_lng, end_latitude=dt_lat, end_longitude=dt_lng, seat_count=seat_count, fare_id=fare_id) req = response.json #self.request_id = req.get('request_id') return req def riders_details(self, req_id="221448y7e32ye"): res = self.client.get_ride_details(req_id) ride = res.json return ride def process_request(self, req_id): status = 'accepted' self.client.update_sandbox_ride(req_id, status) #status = ['in_progress','accepted','completed'] # # for i in range(len(status)): # self.client.update_sandbox_ride(req_id,status[i]) # time.sleep(15) def cancel_current_ride(self): res = self.client.cancel_current_ride() return res.json def cancel_ride(self, req_id): res = self.client.cancel_ride(req_id) return res.json
def post_login(): session = auth_flow.get_session(request.url) client = UberRidesClient(session) complete_history = [] user_activity = client.get_user_activity(limit=50) result = user_activity.json ride_count = result['count'] complete_history.extend(result['history']) client_data = client.get_user_profile().json first_name = client_data['first_name'] last_name = client_data['last_name'] promo_code = client_data['promo_code'] times_ran = 1 for i in range (ride_count/50) : user_activity = client.get_user_activity(limit=50, offset=times_ran*50) result = user_activity.json complete_history.extend(result['history']) times_ran += 1 cities = set() product_types = defaultdict(int) total_distance = 0 wait_time = 0 trip_time = 0 for i in complete_history: cities.add(i['start_city']['display_name']) product_types[i['product_id']] += 1 total_distance += i['distance'] wait_time += (i['start_time'] - i['request_time'])/(60.0*60.0) trip_time += (i['end_time'] - i['start_time'])/(60.0*60.0) products = {} for key in product_types: try: productinfo = client.get_product(key) products[key] = productinfo.json except: pass uber_products = defaultdict(int) for key in product_types: try: uber_products[products[key]['display_name']] += product_types[key] except: pass data = [first_name, last_name, "PS",] for i in uber_products: data.append(i) data.append(uber_products[i]) data.extend(["PE", ride_count, len(cities), total_distance, wait_time, trip_time]) encoded_data = base64.b64encode("|".join(map(lambda x: str(x), data))) shareurl = "https://ridestats.surbhioberoi.com/result/" + encoded_data return redirect(shareurl)
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." )