Пример #1
0
def get_uber_price(source, destination):
    session = Session(server_token='V_89PqdPNV7zZO8_5G4C1tb3_-iVc3UXwd9h6JyU')
    client = UberRidesClient(session)
    begin_latitude, begin_longitude = get_coordinate(source)

    end_latitude, end_longitude = get_coordinate(destination)

    try:
        response = client.get_price_estimates(
            start_latitude=begin_latitude,
            start_longitude=begin_longitude,
            end_latitude=end_latitude,
            end_longitude=end_longitude,
            seat_count=2
        )

        estimate = response.json.get('prices')[0]['estimate']
        return estimate
    except:
        time, distance = get_time_distance(source, destination)
        time = time / 60

        #response = client.get_products(37.77, -122.41)
        latitude, longitude = get_coordinate(source)
        response = client.get_products(latitude, longitude)
        try:
            products = response.json.get('products')[6]
        except:
            response = client.get_products(37.77, -122.41)
            products = response.json.get('products')[6]

        price_detail = products['price_details']

        cost_per_minute = price_detail['cost_per_minute']
        cost_per_distance = price_detail['cost_per_distance']
        # return str(cost_per_distance) + " " + str(cost_per_minute)\
        # return products

        distance_unit = price_detail['distance_unit']
        if distance_unit == 'mile':
            distance = distance / 1609.344
        else:
            distance = distance / 1000

        service_fee = price_detail['service_fees'][0]
        booking_fee = service_fee['fee']
        uber_fee = '$' + str(int(cost_per_minute * time + cost_per_distance * distance + booking_fee))
        return uber_fee
Пример #2
0
    def getProducts(self, latitude, longitude):

        '''Returns types of cars available for in a specific area'''

        client = UberRidesClient(self.session)
        response = client.get_products(latitude, longitude)
        return response.json.get('products')
Пример #3
0
def get_UBERtimes(list_points_location):
    list_neighborhood=[]
    # list for UBER estimate time
    list_points_times=[]
    # list for the date and hour that the data are taken
    list_datetime_capture=[]
    # Configure UBER sesion
    session = Session(server_token='TZ9aAN7GMzp49djfXoMil2HJ7XxCs0Zwo8EWXd88')
    client = UberRidesClient(session)
    # for each point within list_points_location take UBER estimate time and date
    for i, value in enumerate(list_points_location):
        location = neighborhood_names[i]
        lat, lon = value 
        
        try:
            response = client.get_products(lat, lon)
            productid = response.json.get('products')[0]["product_id"]
            # get time of UBER response
            wait_time = client.get_pickup_time_estimates(lat, lon, productid)
            if wait_time.json.get('times') != []:
                list_points_times.append(wait_time.json.get('times')[0]['estimate'])
            else:
                list_points_times.append(0)
            # get date
            list_neighborhood.append(location)
            last_hour_date_time = datetime.now() - timedelta(hours = 1)
            list_datetime_capture.append(last_hour_date_time.strftime('%Y-%m-%d %H:%M:%S'))
        except: 
            print(location)
            print(lat)
            print(lon)
            print(wait_time.json.get('times'))
            pass
    return list_neighborhood, list_points_times, list_datetime_capture
Пример #4
0
class UberAccess:
    def __init__(self, contents=None):
        self.contents = self._get_contents()
        self.server_token = self.contents["server_token"]
        self.uber_session = Session(server_token=self.server_token)
        self.uber_client = UberRidesClient(self.uber_session)

    def _get_contents(self):
        # TODO: You can make this configurable later and move to setup.py, hardcoded ish for now
        infile = open("./lib/credentials.txt", "r")
        contents = infile.readline()
        contents = json.loads(contents)
        return contents

    def get_available_products(self, lat, long):
        # ------------------Available products at clients location---------#
        response = self.uber_client.get_products(lat, long)
        products = response.json.get('products')
        return products

    def get_price_estimates(self, start_lat, start_long, end_lat, end_long,
                            seat_count):
        response = self.uber_client.get_price_estimates(
            start_lat, start_long, end_lat, end_long, seat_count)
        estimate = response.json.get('prices')
        return estimate

    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
Пример #5
0
class UberClient(object):
    def __init__(self, server_token):
        """
        :type server_token: str
        """
        self.client = UberRidesClient(Session(server_token=server_token),
                                      sandbox_mode=True)

    def get_available_products(self, location):
        """
        :type location: commons.model.Location
        :rtype: list[commons.uber.UberProduct]
        """
        response = self.client.get_products(location.latitude,
                                            location.longitude)
        if response.status_code == 200:
            return map(lambda product: build_uber_product_object(product),
                       response.json.get('products'))
        else:
            raise self._build_error_from_response(response)

    def estimate_price(self, location_a, location_b):
        """
        :type location_a: commons.model.Location
        :type location_b: commons.model.Location
        :rtype: list[commons.uber.UberPricing]
        """
        response = self.client.get_price_estimates(location_a.latitude,
                                                   location_a.longitude,
                                                   location_b.latitude,
                                                   location_b.longitude)
        if response.status_code == 200:
            return map(lambda pricing: build_uber_pricing_object(pricing),
                       response.json.get("prices"))
        else:
            raise self._build_error_from_response(response)

    def estimate_3km_price(self, location_a):
        """
        :type location_a: commons.model.Location
        :rtype: list[commons.uber.UberPricing]
        """
        location_b = Location(
            latitude=location_a.latitude + DELTA_COORDINATES_FOR_3_KM,
            longitude=location_a.longitude + DELTA_COORDINATES_FOR_3_KM)
        response = self.client.get_price_estimates(location_a.latitude,
                                                   location_a.longitude,
                                                   location_b.latitude,
                                                   location_b.longitude)
        if response.status_code == 200:
            return map(lambda pricing: build_uber_pricing_object(pricing),
                       response.json.get("prices"))
        else:
            raise self._build_error_from_response(response)

    @staticmethod
    def _build_error_from_response(response):
        return IOError(
            "Could not retrieve information from Uber. Code: {} error: {}".
            format(response.status_code, response.json))
Пример #6
0
def findRides(lat=52.386, lon=4.873, minCapacity=-1, maxCapacity=-1, maxPrice=-1, maxTime=30, shared=False):
    print('uber?')
    session = Session(server_token='LfFtq8jnN1YYN0ZTeGetOvadi_DiCAk8nEForlLq')
    api_client = UberRidesClient(session)
    response = api_client.get_products(lat, lon)
    products = response.json.get('products')

    def not_shared(p):
        if p["shared"] and not shared:
            return False
        else:
            return p
    filteredProducts = [p for p in filter(not_shared, products)]

    if minCapacity > 0:
        filteredProducts = [p for p in filteredProducts if p['capacity'] >= minCapacity]

    if maxCapacity > 0:
        filteredProducts = [p for p in filteredProducts if p['capacity'] <= maxCapacity]

    if maxPrice > 0:
        filteredProducts = [p for p in filteredProducts if p['price_details']['minimum'] <= maxPrice]

    for p in filteredProducts:
        response = api_client.get_pickup_time_estimates(lat, lon, p['product_id'])
        try:
            time = response.json.get('times')[0]['estimate']
        except KeyError:
            p['pickup_time'] = maxTime + 1
        else:
            p['pickup_time'] = time / float(60)

    filteredProducts = [p for p in filteredProducts if p['pickup_time'] <= maxTime]

    return filteredProducts
Пример #7
0
def find_optimal_pickup(start,end):
    session = Session(server_token='ZX14_Gl4xEJcQLXyLGT_OBYVRoJXJL0tXB4ijyPp')
    client = UberRidesClient(session)

    # Get price and time estimates
    response = client.get_products(37.77, -122.41)
    products = response.json.get('products')

    pickup = start
    [pick_lat,pick_lng] = return_latlng(pickup)

    dropoff = end
    [drop_lat,drop_lng] = return_latlng(dropoff)

    pickup_list = [[pick_lat,pick_lng]]
    dropoff_list = [[drop_lat,drop_lng]]
    diff = 0.0003

    for i in range(1, 20):
        lat_diff = pick_lat - i*diff
        lng_diff = pick_lng - i*diff
        pickup_list.append([lat_diff,pick_lng])
        pickup_list.append([pick_lat,lng_diff])

    for i in range(1, 20):
        lat_diff = pick_lat + i*diff
        lng_diff = pick_lng + i*diff
        pickup_list.append([lat_diff,pick_lng])
        pickup_list.append([pick_lat,lng_diff])

    # print (my_pickup.lat,my_pickup.lng,my_dropoff.lat,my_dropoff.lng)
    cost_list = []
    ctr = 0
    for [pick_lat,pick_lng] in pickup_list:
        response = client.get_price_estimates(
            start_latitude=pick_lat,
            start_longitude=pick_lng,
            
            end_latitude=drop_lat,
            end_longitude=drop_lng,
            seat_count=1
        )

        estimate = response.json.get('prices')
        for element in estimate:
            if element['localized_display_name'] == 'POOL':
                cost_list.append([(element['low_estimate']+element['high_estimate'])/2, [pick_lat,pick_lng]])
                ctr += 1
    cost_list.sort()
    print (cost_list)
    [cost, [lat,lng]] = cost_list[0]
    print([lat,lng])
    print (cost)
    return locate_spot((lat,lng))


# start = "Newport Centre, NJ"
# end = "Portside Towers Apartments"
# find_optimal_pickup(start,end)
Пример #8
0
def get_product_id(config, lat, lon, product):
    """
    :return: the product ID of the uberX/XL for requesting a ride
    """
    session = Session(server_token=config['uber']['server_token'])  # FOR READ ONLY CALLS
    client = UberRidesClient(session)
    response = client.get_products(lat, lon)
    try:
        return filter(lambda x: x['display_name'] == product, response.json.get('products'))[0]['product_id']
    except Exception, e:
        raise ValueError('No Ubers of that type available')
Пример #9
0
def orderUber():
	headers = {
	    'Accept': 'application/json',
	    'server_token': 'DA36VIywvzdAcUd7f9RhRA-JZp3R8H8dRbzA68YN',
	    'Client Secret': 'jdW4INDoXyd2-DXZUJueZhuoLEPeY3p0oxzlFqxg',
	    'Authorization': 'Bearer KA.eyJ2ZXJzaW9uIjoyLCJpZCI6Im9oOTcvMENxUlFpUmZhMlVqbHlNSGc9PSIsImV4cGlyZXNfYXQiOjE1MTkxMDY1ODcsInBpcGVsaW5lX2tleV9pZCI6Ik1RPT0iLCJwaXBlbGluZV9pZCI6MX0.vj7eUx5AjKrYZnYOpari2uUBsnL2zt9VJIz0l-hauxg'

	}	
	# Get products for a location
	session = Session(server_token='DA36VIywvzdAcUd7f9RhRA-JZp3R8H8dRbzA68YN')
	client = UberRidesClient(session,sandbox_mode=True)
	url = 'https://sandbox-api.uber.com/<version>'	

	# r = requests.get(url, headers=headers)
	print 'here'
	response = client.get_products(37.77, -122.41)
	products = response.json.get('products')
	print 'here'
	product_id = products[0].get('product_id')
	print 'here'
	# Get upfront fare and start/end locations
	estimate = client.estimate_ride(
	    product_id=product_id,
	    start_latitude=37.77,
	    start_longitude=-122.41,
	    end_latitude=10.79,
	    end_longitude=-122.41,
	    seat_count=1
	)
	fare = estimate.json.get('fare')

	# # Request a ride with upfront fare and start/end locations
	# response = client.request_ride(
	#     product_id=product_id,
	#     start_latitude=37.77,
	#     start_longitude=-122.41,
	#     end_latitude=37.79,
	#     end_longitude=-122.41,
	#     seat_count=2,
	#     fare_id=fare['fare_id']
	# )

	# request = response.json
	# request_id = request.get('request_id')

	# # Request ride details using `request_id`
	# response = client.get_ride_details(request_id)
	# ride = response.json

	# # Cancel a ride
	# response = client.cancel_ride(request_id)
	# ride = response.json

# orderUber()
Пример #10
0
def get_product_id(config, lat, lon, product):
    """
    :return: the product ID of the uberX/XL for requesting a ride
    """
    session = Session(server_token=config['uber']['server_token'])  # FOR READ ONLY CALLS
    client = UberRidesClient(session)
    response = client.get_products(lat, lon)
    try:
        return filter(lambda x: x['display_name'] == product, response.json.get('products'))[0]['product_id']
    except Exception, e:
        raise ValueError('No Ubers of that type available')
Пример #11
0
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 get_uber_products(start_latitude, start_longitude, redirect_url):
    auth_flow = AuthorizationCodeGrant(
        CLIENT_ID,
        PERMISSION_SCOPE,
        CLIENT_SECRET,
        REDIRECT_URI)
    auth_url = auth_flow.get_authorization_url()

    session = auth_flow.get_session(redirect_url)
    client = UberRidesClient(session)
    credentials = session.oauth2credential

    response = client.get_products(37.77, -122.41)
    products = response.json.get('products')
    print products
Пример #13
0
class UberPriceEstimate(object):
	SERVER_TOKEN = os.environ.get('UBER_SERVER_TOKEN') 
	def __init__(self):
		self.session = Session(server_token=UberPriceEstimate.SERVER_TOKEN) 
		self.client = UberRidesClient(self.session)

	def getProducts(self, type, lat, long):
		response = self.client.get_products(lat, long)
		products = response.json.get('products')
		for product in products:
			if product["display_name"] == type:
				return product
		return None
	def getEstimate(self, product, startLat, startLong, endLat, endLong):
		estimate = self.client.estimate_ride( product_id=product.get('product_id'), start_latitude=startLat, start_longitude=startLong, end_latitude=endLat, end_longitude=endLong )
		print estimate
Пример #14
0
    def update(self):
        """Get the latest product info and estimates from the Uber API."""
        from uber_rides.client import UberRidesClient
        client = UberRidesClient(self._session)

        self.products = {}

        products_response = client.get_products(
            self.start_latitude, self.start_longitude)

        products = products_response.json.get('products')

        for product in products:
            self.products[product['product_id']] = product

        if self.end_latitude is not None and self.end_longitude is not None:
            price_response = client.get_price_estimates(
                self.start_latitude,
                self.start_longitude,
                self.end_latitude,
                self.end_longitude)

            prices = price_response.json.get('prices', [])

            for price in prices:
                product = self.products[price['product_id']]
                price_details = product.get("price_details")
                product["duration"] = price.get('duration', '0')
                product["distance"] = price.get('distance', '0')
                if price_details is not None:
                    price_details["estimate"] = price.get('estimate',
                                                          '0')
                    price_details["high_estimate"] = price.get('high_estimate',
                                                               '0')
                    price_details["low_estimate"] = price.get('low_estimate',
                                                              '0')
                    surge_multiplier = price.get('surge_multiplier', '0')
                    price_details["surge_multiplier"] = surge_multiplier

        estimate_response = client.get_pickup_time_estimates(
            self.start_latitude, self.start_longitude)

        estimates = estimate_response.json.get('times')

        for estimate in estimates:
            self.products[estimate['product_id']][
                "time_estimate_seconds"] = estimate.get('estimate', '0')
Пример #15
0
    def update(self):
        """Get the latest product info and estimates from the Uber API."""
        from uber_rides.client import UberRidesClient
        client = UberRidesClient(self._session)

        self.products = {}

        products_response = client.get_products(self.start_latitude,
                                                self.start_longitude)

        products = products_response.json.get('products')

        for product in products:
            self.products[product['product_id']] = product

        if self.end_latitude is not None and self.end_longitude is not None:
            price_response = client.get_price_estimates(
                self.start_latitude, self.start_longitude, self.end_latitude,
                self.end_longitude)

            prices = price_response.json.get('prices', [])

            for price in prices:
                product = self.products[price['product_id']]
                product['duration'] = price.get('duration', '0')
                product['distance'] = price.get('distance', '0')
                price_details = product.get('price_details')
                if product.get('price_details') is None:
                    price_details = {}
                price_details['estimate'] = price.get('estimate', '0')
                price_details['high_estimate'] = price.get(
                    'high_estimate', '0')
                price_details['low_estimate'] = price.get('low_estimate', '0')
                price_details['currency_code'] = price.get('currency_code')
                surge_multiplier = price.get('surge_multiplier', '0')
                price_details['surge_multiplier'] = surge_multiplier
                product['price_details'] = price_details

        estimate_response = client.get_pickup_time_estimates(
            self.start_latitude, self.start_longitude)

        estimates = estimate_response.json.get('times')

        for estimate in estimates:
            self.products[estimate['product_id']][
                'time_estimate_seconds'] = estimate.get('estimate', '0')
Пример #16
0
    def update(self):
        """Get the latest product info and estimates from the Uber API."""
        from uber_rides.client import UberRidesClient
        client = UberRidesClient(self._session)

        self.products = {}

        products_response = client.get_products(
            self.start_latitude, self.start_longitude)

        products = products_response.json.get("products")

        for product in products:
            self.products[product["product_id"]] = product

        if self.end_latitude is not None and self.end_longitude is not None:
            price_response = client.get_price_estimates(
                self.start_latitude, self.start_longitude,
                self.end_latitude, self.end_longitude)

            prices = price_response.json.get("prices", [])

            for price in prices:
                product = self.products[price["product_id"]]
                product["duration"] = price.get("duration", "0")
                product["distance"] = price.get("distance", "0")
                price_details = product.get("price_details")
                if product.get("price_details") is None:
                    price_details = {}
                price_details["estimate"] = price.get("estimate", "0")
                price_details["high_estimate"] = price.get("high_estimate",
                                                           "0")
                price_details["low_estimate"] = price.get("low_estimate", "0")
                price_details["currency_code"] = price.get("currency_code")
                surge_multiplier = price.get("surge_multiplier", "0")
                price_details["surge_multiplier"] = surge_multiplier
                product["price_details"] = price_details

        estimate_response = client.get_pickup_time_estimates(
            self.start_latitude, self.start_longitude)

        estimates = estimate_response.json.get("times")

        for estimate in estimates:
            self.products[estimate["product_id"]][
                "time_estimate_seconds"] = estimate.get("estimate", "0")
Пример #17
0
def uberSearch(inputString):
	uberDestination = re.findall(r'let us roll out to [\w\s+]',inputString)

	headers = {
	    'Accept': 'application/json',
	    'server_token': 'DA36VIywvzdAcUd7f9RhRA-JZp3R8H8dRbzA68YN',
	    'Client Secret': 'jdW4INDoXyd2-DXZUJueZhuoLEPeY3p0oxzlFqxg',
	    'Access Token': 'KA.eyJ2ZXJzaW9uIjoyLCJpZCI6Ik5jZDB0VVVEVFZtZ2IvY0xsWkt3U0E9PSIsImV4cGlyZXNfYXQiOjE1MTkxMDM4ODYsInBpcGVsaW5lX2tleV9pZCI6Ik1RPT0iLCJwaXBlbGluZV9pZCI6MX0.NpfNmxCfqBbtzOav7ofBa-IgT_DPbJK-svPxOePgNis'

	}
	# myBaseAPI = 'https://api.spotify.com/v1/search?'
	# url = myBaseAPI + urllib.urlencode({"q" : query, "type" : 'track'})	

	# r = requests.get(url, headers=headers)

	# json = r.json()

	# trackData = json['tracks']['items'][0]
	# # trackData = json['tracks']['items'][0]['uri']
	# return trackData



	session = Session(server_token='DA36VIywvzdAcUd7f9RhRA-JZp3R8H8dRbzA68YN')
	client = UberRidesClient(session)

	response = client.get_products(37.77, -122.41)
	products = response.json.get('products')


	response = client.get_price_estimates(
	start_latitude=37.770,
	start_longitude=-122.411,
	end_latitude=37.791,
	end_longitude=-122.405,
	seat_count=2
	)



	# json = r.json()

	estimate = response.json.get('prices')
	return estimate
Пример #18
0
def get_data_from_uber(location):
    """
    Method to get data from Uber API

    Parameters
    ----------
    location: string
        location should be ideally city

    Returns
    -------
    foursquare_data: JSON
        JSON response from a foursquare API
    """
    lat, lng = get_lat_long(location)
    session = Session(
        server_token=config.get('uber_app_info', 'uber_server_token'))
    client = UberRidesClient(session)
    response = client.get_products(lat, lng)
    uber_products = response.json.get('products')
    return (uber_products)
Пример #19
0
	def __init__(self):
		session = Session(server_token='')

		client = UberRidesClient(session)

		response = client.get_products(37.77, -122.41)

		products = response.json.get('products')


		#ubers variable contains all available products in json format
		ubers = json.loads(json.dumps(products))

		cab_list = []

		for uber in ubers:
			ucab = uber_cab(uber['display_name'],uber['shared'],uber['description'],uber['capacity'])
			print ucab.getDetails()
			cab_list.append(ucab)

		return cab_list
Пример #20
0
def get_products_bysort(start_latitude=37.77,
                        start_longitude=-122.41,
                        end_latitude=37.79,
                        end_longitude=-122.41,
                        category="pool",
                        sender_id="758758758758"):
    uber = Uber_api
    source_ub = './cab_utils/data/uber'
    cred = retrieve_cred(source=source_ub, fbid=sender_id)
    #ub_client = uber.get_AuthCredentials(False, cred)
    #products = uber.get_products()
    #prices = uber.get_estimate_pricess()
    session = Session(oauth2credential=cred)
    client = UberRidesClient(session)
    products = client.get_products(latitude=start_latitude,
                                   longitude=start_longitude).json
    prices = client.get_price_estimates(start_latitude=start_latitude,
                                        start_longitude=start_longitude,
                                        end_latitude=end_latitude,
                                        end_longitude=end_longitude).json
    pro = []
    for i in range(len(products['products']) - 1):
        store = {}
        if category in products['products'][i]['display_name'].lower():
            store['title'] = products['products'][i]['display_name']
            store['pro_id'] = products['products'][i]['product_id']
            store['price'] = {
                'cost': prices['prices'][i]['estimate'],
                'high_price': prices['prices'][i]['high_estimate']
            }
            store['time'] = client.get_pickup_time_estimates(
                start_latitude=start_latitude,
                start_longitude=start_longitude,
                product_id=store['pro_id']).json
            store['image_url'] = products['products'][i]['image']
            store['description'] = products['products'][i]['description']
            store['capacity'] = products['products'][i]['capacity']
            pro.append(store)

    return pro
Пример #21
0
def ride(address):
    send_url = 'http://freegeoip.net/json'
    r = requests.get(send_url)
    j = json.loads(r.text)
    latA = j['latitude']
    lonA = j['longitude']

    session = Session(server_token='**********')
    client = UberRidesClient(session)

    # address=input("please enter destination?")

    location = geolocator.geocode(address)
    # print("\n")
    # print("\n")
    lat_d = location.latitude
    long_d = location.longitude
    # print(location.address)
    # print("\n")
    # print("\n")
    # # print((location.latitude, location.longitude))
    # print("\n")
    # print("\n")

    # print (products)
    response = client.get_products(latA, lonA)  # start long lag
    products = response.json.get('products')
    response = client.get_price_estimates(start_latitude=latA,
                                          start_longitude=lonA,
                                          end_latitude=lat_d,
                                          end_longitude=long_d,
                                          seat_count=2)

    estimate = response.json.get('prices')

    response = json.dumps(estimate, indent=4, sort_keys=True)

    #print (response)
    return estimate
Пример #22
0
    def getUberEstimate(startLat, startLng, endLat, endLng, startName,
                        endName):
        session = Session(server_token=config.uber['server_token'])
        client = UberRidesClient(session)

        response = client.get_products(startLat, startLng)
        products = response.json.get('products')

        response = client.get_price_estimates(start_latitude=startLat,
                                              start_longitude=startLng,
                                              end_latitude=endLat,
                                              end_longitude=endLng,
                                              seat_count=2)

        estimate = response.json.get('prices')
        del estimate[0]

        startNickname = quote(startName)
        endNickname = quote(endName)

        results = []
        for x in estimate:
            link = "https://m.uber.com/ul/?client_id=<CLIENT_ID>&action=setPickup&pickup[latitude]=" + startLat + "&pickup[longitude]=" + startLng + "&pickup[formatted_address]=" + startNickname + "&dropoff[latitude]=" + endLat + "&dropoff[longitude]=" + endLng + "&dropoff[formatted_address]=" + endNickname + "&product_id=" + x[
                "product_id"] + "&link_text=View%20team%20roster&partner_deeplink=partner%3A%2F%2Fteam%2F9383"

            obj = {
                "brand": "Uber",
                "name": x["display_name"],
                "low_estimate": x["low_estimate"],
                "high_estimate": x["high_estimate"],
                "avg_estimate": ((x["low_estimate"] + x["high_estimate"]) / 2),
                "duration": x["duration"],
                "link": link
            }

            results.append(obj)

        return results
def call_uber(flight_number, flight_origin_date):
    coords = get_coords(flight_number, flight_origin_date)
    server_token = "GSYPRMkSl_a7qQn8FH6d4imBjBnvrTWhh-6OzVPX"
    session = Session(server_token)
    client = UberRidesClient(session)
    response = client.get_products(coords[0], coords[1])
    products = response.json.get('products')
    auth_flow = AuthorizationCodeGrant(
        "gT2GLeVlXMQkrWWBO872bcjHK168Tr8W",
        None,
        "fQMuhWzwuvMiy2yl31qDu4xIRMP0DIVQQUtJy3hj",
        None,
    )
    auth_url = auth_flow.get_authorization_url()
    session = auth_flow.get_session()
    client = UberRidesClient(session, sandbox_mode=True)
    credentials = session.oauth2credential
    get_coords()
    response = client.request_ride(
        start_latitude=coords[0],
        start_longitude=coords[1],
    )
    ride_details = response.json
    ride_id = ride_details.get('request_id')
Пример #24
0
state = ns[:ns.find('&')]
print auth_url
print state

# redirect_uri = YOUR_REDIRECT_URL + '?code=' + access_token  + '&state=' + state
# print redirect_uri
# http://localhost/?state=o0tbQ7VtRzzBYtn0OALmjQY3XATB9UaU&code=fKW6qXnhmL1Naz6NvQ5TRwFkbZinNQ#_

redirect_uri = 'http://localhost/?state=' + state + '&code=t0Kq2Sfa55PifYK4L4cFiPTtfoBfrl#_'
session = auth_flow.get_session(redirect_uri)
client = UberRidesClient(session)
credentials = session.oauth2credential

print credentials

# session = Session(server_token=YOUR_SERVER_TOKEN)
# client = UberRidesClient(session)
response = client.get_products(40.488101, -74.437934)
products = response.json.get('products')

product_id = products[0].get('product_id')
print products[0].get('display_name')
estimate = client.estimate_ride(product_id=product_id,
                                start_latitude=40.488101,
                                start_longitude=-74.437934,
                                end_latitude=40.502744,
                                end_longitude=-74.448545,
                                seat_count=2)

fare = estimate.json.get('fare')
print fare
Пример #25
0
def requests2():

    from uber_rides.client import UberRidesClient
    from uber_rides.session import Session

    sessionUberRides = Session(server_token=config.get('server_token'))

    client = UberRidesClient(sessionUberRides, sandbox_mode=True)
    print sessionUberRides

    response = client.get_products(config.get('start_latitude'),
                                   config.get('start_longitude'))
    products = response.json.get('products')
    product_id = products[0].get('product_id')

    print product_id

    print response.status_code
    client = UberRidesClient(generate_oauth_service(), sandbox_mode=True)

    responseUber = client.request_ride(
        product_id=product_id,
        start_latitude=config.get('start_latitude'),
        start_longitude=config.get('start_longitude'),
        end_latitude=config.get('end_latitude'),
        end_longitude=config.get('end_longitude'),
    )

    print responseUber
    ride_details = responseUber.json
    print ride_details
    ride_id = ride_details.get('request_id')

    responseUber = client.update_sandbox_ride(ride_id, 'accepted')

    # url = config.get('base_uber_url_SANDBOX') + 'requests'
    # params = {
    #     'start_latitude': config.get('start_latitude'),
    #     'start_longitude': config.get('start_longitude'),
    #     'end_latitude': config.get('end_latitude'),
    #     'end_longitude': config.get('end_longitude'),
    # }
    #
    #
    # print url, generate_ride_headers(session.get('access_token'))
    # response = app.requests_session.post(
    #     url,
    #     headers=generate_ride_headers(session.get('access_token')),
    #     data=params
    # )
    #
    #
    # print response

    if response.status_code != 204:
        return 'There was an error ' + response
    return render_template(
        'results.html',
        endpoint='requests',
        data=responseUber,
    )
Пример #26
0
'''

https://developer.uber.com/docs/riders/ride-requests/tutorials/api/python

Fenway Park, Boston, MA, US
Latitude and longitude coordinates are: 42.346268, -71.095764.

125 Summer St, Boston, MA 02110
Latitude and longitude coordinates are: 42.345597,-71.041276

'''

session = Session(server_token='Uvu3eEPnLtPKCbTU7KrCko5jo1ua4CVgYAqd0JfO')
client = UberRidesClient(session)

response = client.get_products(42.34, -71.09)
print(response)
products = response.json.get('products')

print("products")

for p in products:
    print(p)

response = client.get_price_estimates(start_latitude=42.346,
                                      start_longitude=-71.09,
                                      end_latitude=42.345,
                                      end_longitude=-71.041,
                                      seat_count=2)

prices = response.json.get('prices')
Пример #27
0
# coding=utf-8
from uber_rides.session import Session
from uber_rides.client import UberRidesClient

from config.uber_config import UberToken

session = Session(server_token=UberToken) # Fazer autenticação do APP
client = UberRidesClient(session) # Criar sessão

response = client.get_products(-5.8368171,-35.2065031)
products = response.json.get('products')
for product in products:
    print product['short_description'],':', product['product_id']
Пример #28
0
from uber_rides.session import Session
from uber_rides.client import UberRidesClient
from utils.geolocation import Address
import pprint
import pandas as pd

session = Session(server_token="AT8uiEHjg8hx785Dnfo2uR48aD3A7B6G13-5N3rf")
client = UberRidesClient(session)

start_address = Address(
    "Charing Cross Hospital, Fulham Palace Road, London, W6 8RF")
end_address = Address("14 Digby Mansions, London, W6 9DE")

response = client.get_products(start_address.lat, start_address.lng)
products = response.json.get("products")

response2 = client.get_price_estimates(start_address.lat,
                                       start_address.lng,
                                       end_address.lat,
                                       end_address.lng,
                                       seat_count=2)
estimate = response2.json.get("prices")
# pprint.pprint(estimate)
# print(len(estimate))

uberX_estimate = next(
    (item for item in estimate if item["display_name"] == "uberX"), None)
# pprint.pprint(uberX_estimate)
# print(uberX_estimate.get("display_name"))
# print(uberX_estimate.get("distance"))
# print(uberX_estimate.get("product_id"))
Пример #29
0
	def getProducts(self, type, lat, long):
		response = self.client.get_products(lat, long)
		products = response.json.get('products')
		for product in products:
			if product["display_name"] == type:
				return product
		return None
	def getEstimate(self, product, startLat, startLong, endLat, endLong):
		estimate = self.client.estimate_ride( product_id=product.get('product_id'), start_latitude=startLat, start_longitude=startLong, end_latitude=endLat, end_longitude=endLong )
		print estimate

#uber = UberPriceEstimate()
#product = uber.getProducts("POOL", 37.5334522, -122.2718777)
#print uber.getEstimate(product, 37.5334522, -122.2718777, 37.4059503, -121.9399195)
#print uber.getEstimate(product, 37.770, -122.411, 37.791, -122.405)

session = Session(server_token=os.environ.get('UBER_SERVER_TOKEN'))
client = UberRidesClient(session, sandbox_mode=True)
response = client.get_products(37.77, -122.41)
products = response.json.get('products')
print products
estimate = client.estimate_ride(
    product_id=products[0].get('product_id'),
    start_latitude=37.770,
    start_longitude=-122.411,
    end_latitude=37.791,
    end_longitude=-122.405
)
print estimate
Пример #30
0
def callUber(access_token):
    api_call_headers = {'Authorization': 'Bearer ' + access_token}
    api_url = "https://sandbox-api.uber.com/v1.2"

    start = [-37.818182, 144.968484]  # lat lng of user's location at last pub
    end = [-37.809419, 144.969887]  # user's home address lat lng

    session = Session(server_token="CUofQlGNUbYK3x9FjX0AtlFjEJCak4O59V61YeGs")
    # session = auth_flow.get_session(redirect_url)
    client = UberRidesClient(session, sandbox_mode=True)
    # credentials = session.oauth2credential
    response = client.get_products(start[0], start[1])
    products = response.json.get('products')
    product_id = products[0].get('product_id')  # get first car

    # print(product_id)
    data = {
        "product_id": product_id,
        "start_latitude": str(start[0]),
        "start_longitude": str(start[1]),
        "end_latitude": str(end[0]),
        "end_longitude": str(end[1])
    }

    estimate_url = api_url + "/estimates/price?product_id=" + product_id + "&start_latitude=" + str(
        data['start_latitude']) + "&start_longitude=" + str(
            data['start_longitude']) + "&end_latitude=" + str(
                data['end_latitude']) + "&end_longitude=" + str(
                    data['end_longitude'])
    # estimate_url = api_url + "/estimates/price"

    # estimate_url = api_url + "/estimates/price?product_id=14095ef9-8f25-4c95-b523-82ea721f4b5a&amp; start_latitude=-37.818182&amp; start_longitude=144.968484&amp; end_latitude=-37.809419&amp; end_longitude=144.969887&amp; access_token=JA.VUNmGAAAAAAAEgASAAAABwAIAAwAAAAAAAAAEgAAAAAAAAG8AAAAFAAAAAAADgAQAAQAAAAIAAwAAAAOAAAAkAAAABwAAAAEAAAAEAAAAKeHcU4e3TOpwemfJhsSFOdsAAAAWdOPQXzAGGM_PgSOyLyYAG_s7EXFVUMPvD8VGkEcqNkUhxbVsuEmgsH0zOdlmJLuspmygp_zS-XGybm4vmUCUImoMjNo1hjNIK-XGuGhSuQ-VYj2gOsByzGu3tLPMBrjin56zodEXVk1TQahDAAAAO78zhNV3nrrsom5JCQAAABiMGQ4NTgwMy0zOGEwLTQyYjMtODA2ZS03YTRjZjhlMTk2ZWU"

    estimate = requests.get(estimate_url, headers=api_call_headers)
    data["product_id"] = json.loads(
        estimate.content)['prices'][0]['product_id']
    print()

    fare_headers = {
        'Authorization': 'Bearer ' + access_token,
        'Content-Type': 'application/json'
    }

    data_json = '''{ "product_id": product_id, "start_latitude": str(start[0]), "start_longitude": str(start[1]), "end_latitude": str(end[0]), "end_longitude": str(end[1])}'''
    # fare_url = api_url + "/requests/estimate?product_id=" + product_id + "&start_latitude=" + str(data['start_latitude']) + "&start_longitude=" + str(data['start_longitude']) + "&end_latitude=" + str(data['end_latitude']) + "&end_longitude=" + str(data['end_longitude'])
    fare_url = api_url + "/requests/estimate"
    get_fare = requests.post(fare_url,
                             headers=fare_headers,
                             data=json.dumps(data))
    fare = json.loads(get_fare.content)['fare']['fare_id']

    # fake request
    data = {
        'fare_id': fare,
        'start_latitude': start[0],
        'start_longitude': start[1],
        'end_latitude': end[0],
        'end_longitude': end[1],
    }
    print("hello")
    # make the fake request
    r = requests.post(api_url + "/requests",
                      headers=fare_headers,
                      data=json.dumps(data))
    print("hello")
Пример #31
0
def requests2():

    from uber_rides.client import UberRidesClient
    from uber_rides.session import Session


    sessionUberRides = Session(server_token=config.get('server_token'))

    client = UberRidesClient(sessionUberRides, sandbox_mode=True)
    print sessionUberRides

    response = client.get_products(config.get('start_latitude'), config.get('start_longitude'))
    products = response.json.get('products')
    product_id = products[0].get('product_id')

    print product_id

    print response.status_code
    client = UberRidesClient(generate_oauth_service(), sandbox_mode=True)

    responseUber = client.request_ride(
        product_id=product_id,
        start_latitude=config.get('start_latitude'),
        start_longitude=config.get('start_longitude'),
        end_latitude=config.get('end_latitude'),
        end_longitude=config.get('end_longitude'),
    )

    print responseUber
    ride_details = responseUber.json
    print ride_details
    ride_id = ride_details.get('request_id')

    responseUber = client.update_sandbox_ride(ride_id, 'accepted')


    # url = config.get('base_uber_url_SANDBOX') + 'requests'
    # params = {
    #     'start_latitude': config.get('start_latitude'),
    #     'start_longitude': config.get('start_longitude'),
    #     'end_latitude': config.get('end_latitude'),
    #     'end_longitude': config.get('end_longitude'),
    # }
    #
    #
    # print url, generate_ride_headers(session.get('access_token'))
    # response = app.requests_session.post(
    #     url,
    #     headers=generate_ride_headers(session.get('access_token')),
    #     data=params
    # )
    #
    #
    # print response

    if response.status_code != 204 :
        return 'There was an error ' + response
    return render_template(
        'results.html',
        endpoint='requests',
        data=responseUber,
    )
Пример #32
0
from uber_rides.client import UberRidesClient
import requests
import webbrowser
import oauth2

session = Session(server_token="CUofQlGNUbYK3x9FjX0AtlFjEJCak4O59V61YeGs")
client = UberRidesClient(session)

# get user to log in
url = "https://login.uber.com/oauth/v2/authorize?response_type=code&client_id=bNuMgUk4XDsvlVbnnLtJwwEitiflHMPG&scope" \
      "=history+history_lite+places+profile+request_receipt&redirect_uri=http://localhost:3000"
webbrowser.open(url)
print()

# Get products for a location
response = client.get_products(37.77, -122.41)
products = response.json.get('products')

product_id = products[0].get('product_id')

# Get upfront fare and start/end locations
estimate = client.estimate_ride(product_id=product_id,
                                start_latitude=37.77,
                                start_longitude=-122.41,
                                end_latitude=37.79,
                                end_longitude=-122.41,
                                seat_count=2)
fare = estimate.json.get('fare')

# Request a ride with upfront fare and start/end locations
response = client.request_ride(product_id=product_id,
Пример #33
0
from uber_rides.session import Session
from pprint import pprint
session = Session(server_token='qZLzWGMbxgTW4uZIlE0zZ7OA2oQRwV88qyVIyi3a')

from uber_rides.client import UberRidesClient
client = UberRidesClient(session)
response = client.get_products(-23.197338, -45.892197)
products = response.json.get('products')
for p in products:
  print ('Disponível no local:', p['display_name'])
  pprint (p['price_details'])

Пример #34
0
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
Пример #35
0
    def getProducts(self, latitude, longitude):
        '''Returns types of cars available for in a specific area'''

        client = UberRidesClient(self.session)
        response = client.get_products(latitude, longitude)
        return response.json.get('products')
Пример #36
0
class UberFacade:
    def __init__(self):
        self._session = Session(server_token=SERVER_TOKEN)
        self._client = UberRidesClient(self._session)

    def get_rides(self, city):
        latitude, longtitude = self._lat_lot_of_city(city)
        response = self._client.get_products(latitude, longtitude)
        response = response.json.get('products')
        all_offers = list()
        for offer in response:
            all_offers.append({
                'name': offer['display_name'],
                'price_details': offer['price_details'],
                'logo': offer['image'],
                'capacity': offer['capacity'],
            })
        return all_offers

    def get_rides_from_to(self, from_, to_, seats=1):
        from_latitude, from_longtitude = self._lat_lot_of_city(from_)
        to_latitude, to_longtitude = self._lat_lot_of_city(to_)
        prices = self._client.get_price_estimates(
            start_latitude=from_latitude,
            start_longitude=from_longtitude,
            end_latitude=to_latitude,
            end_longitude=to_longtitude,
            seat_count=seats)
        best = None
        for price in prices.json['prices']:
            if (price['high_estimate'] is None or price['low_estimate'] is None
                    or price['currency_code'] is None):
                continue
            if best is None:
                best = price
            if (best['low_estimate'] < price['low_estimate']):
                best = price
        result = {
            key: val
            for key, val in best.items()
            if key in ('currency_code', 'low_estimate', 'high_estimate')
        }
        # dystans w linii prostej !
        result['distance'] = distance(
            Point(from_latitude, from_longtitude),
            Point(to_latitude, to_longtitude),
        ).kilometers
        if result['currency_code'] != 'EUR':
            result['low_estimate'], result[
                'high_estimate'] = self._convert_currencies(
                    [result['low_estimate'], result['high_estimate']],
                    result['currency_code'],
                    'EUR',
                )
            result['currency_code'] = 'EUR'
        return result

    def _lat_lot_of_city(self, city):
        loc = geolocator.geocode(city)
        return loc.latitude, loc.longitude

    def _convert_currencies(self, amounts, from_currency, to_currency):
        convert_coeff = requests.get(
            CURRENCY_API_URL,
            params={
                'symbols': '{0},{1}'.format(from_currency, to_currency)
            },
        ).json()['rates'][from_currency]
        return [int(amount / convert_coeff) for amount in amounts]
Пример #37
0
    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.")                
Пример #38
0
    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."
            )