func main() {
	// Read API auth options
	var options uber.RequestOptions
	fileContents, err := ioutil.ReadFile("./uber-client/options.json")
	if err != nil {
		log.Fatal(err)
	}

	if e := json.Unmarshal(fileContents, &options); e != nil {
		log.Fatal(err)
	}

	// Create a Client for executing API operations
	client := uber.Create(&options)

	// Retrieve products based on lat/long coords
	pl := &uber.Products{}
	pl.Latitude = WhiteHouseLat
	pl.Longitude = WhiteHouseLong
	if e := client.Get(pl); e != nil {
		log.Fatal(e)
	}

	fmt.Println("Here are the Uber options available for your area: \n")
	for _, product := range pl.Products {
		fmt.Println(product.DisplayName + ": " + product.Description)
	}

	// Retrieve price estimates based on start and end lat/long coords
	pe := &uber.PriceEstimates{}
	pe.StartLatitude = WhiteHouseLat
	pe.StartLongitude = WhiteHouseLong
	pe.EndLatitude = USCapitolLat
	pe.EndLongitude = USCapitolLong
	if e := client.Get(pe); e != nil {
		log.Fatal(e)
	}

	fmt.Println("\nHere are the Uber price estimates from The White House to the United States Capitol: \n")
	for _, price := range pe.Prices {
		fmt.Println(price.DisplayName + ": " + price.Estimate + "; Surge: " + strconv.FormatFloat(price.SurgeMultiplier, 'f', 2, 32))
	}

	// Retrieve ETA estimates based on start lat/long coords
	te := &uber.TimeEstimates{}
	te.StartLatitude = WhiteHouseLat
	te.StartLongitude = WhiteHouseLong
	if e := client.Get(te); e != nil {
		log.Fatal(e)
	}

	fmt.Println("\nHere are the Uber ETA estimates if leaving from The White House: \n")
	for n, eta := range te.Times {
		fmt.Println(eta.DisplayName + ": " + strconv.Itoa(eta.Estimate/60))
		if n == len(te.Times)-1 {
			fmt.Print("\n")
		}
	}
}
//
// Uber
//
func GetUberClient() *uber.Client {
	uber_options := uber.RequestOptions{
		ServerToken:  "wvL_d5XSDnAARmPuSj9hGVYsjgSr91zoO0KFYCg6",
		ClientId:     "WO12XDLKoKlKeHJIMw_oNvpqOm30lteG",
		ClientSecret: "NdktLcJcLmgVGo6-rcYFkFrvFYWAcIKgnBfixoIc",
		AppName:      "PujaAssignment",
	}

	return uber.Create(&uber_options)
}
Beispiel #3
0
func PutTrip(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	//ac:= p.ByName("id")
	ac := p[0].Value
	var dbresult UserPostResponse
	var finalresponse UserPutResponse
	var r1 ResponsefromDB
	var r2 ResponsefromDB
	sessionss := getSession()
	er := sessionss.DB("trip-planner").C("trip").Find(bson.M{"id": ac}).One(&dbresult)
	if er != nil {
		panic(er)
	} else {

		var ids int
		if currentPos == 0 {
			ids, err := strconv.Atoi(dbresult.StartingPositionid)
			if err != nil {
				// handle error
				fmt.Println(err)
			}
			fmt.Println(ids)
			fmt.Println(reflect.TypeOf(ids))

		} else {
			ids, err := strconv.Atoi(dbresult.BestrouteIds[currentPos-1])

			if err != nil {
				// handle error
				fmt.Println(err)
			}
			fmt.Println(ids)

		}

		err := sessionss.DB("trip-planner").C("locations").Find(bson.M{"id": ids}).One(&r1)
		if err != nil {
			fmt.Println("Here is the error2")
			log.Println(err.Error())
			panic(err)
		}

		ids, err = strconv.Atoi(dbresult.BestrouteIds[currentPos])
		if err != nil {
			// handle error
			fmt.Println(err)
		}
		newsesss := getSession()
		err = newsesss.DB("trip-planner").C("locations").Find(bson.M{"id": ids}).One(&r2)
		if err != nil {
			panic(err)
		}
	}
	finalresponse.ID = strconv.Itoa(otherint)
	finalresponse.BestRouteLocationIds = dbresult.BestrouteIds
	finalresponse.StartingFromLocationID = dbresult.StartingPositionid
	finalresponse.TotalUberCost = dbresult.Totalcost
	finalresponse.TotalUberDuration = dbresult.Totalduration

	if finalresponse.Status != "completed" {
		if finalresponse.Status == "planning" && len(finalresponse.NextDestinationLocationID) == 0 {
			finalresponse.Status = "requesting"
			finalresponse.NextDestinationLocationID = finalresponse.BestRouteLocationIds[0]
		} else if finalresponse.StartingFromLocationID == finalresponse.NextDestinationLocationID {
			finalresponse.Status = "completed"
		} else {
			finalresponse.Status = "requesting"
			finalresponse.NextDestinationLocationID = dbresult.BestrouteIds[currentPos]
		}
	}

	var options uber.RequestOptions
	options.ServerToken = "uiiQ8zd9D4GHSDdsmT_mzIw7DXS67enDl5tXuc-p"
	options.ClientId = "c6jVXK_x-UXgKRsNUdyDb2omyFjVyKPy"
	options.ClientSecret = "vVksauQ2gWAVFxlYDi4GDi65J_f-zVxmVFqibMyA"
	options.AppName = "Golang Application"
	options.BaseUrl = "https://sandbox-api.uber.com/v1/"
	client := uber.Create(&options)

	pl := &uber.Products{}
	pl.Latitude = r1.Coordinate.Lat
	pl.Longitude = r1.Coordinate.Lng
	if e := client.Get(pl); e != nil {
		fmt.Println(e)
	}
	var productid string
	i := 0
	for _, product := range pl.Products {
		if i == 0 {
			productid = product.ProductId
		}
	}

	var ride RideReq
	ride.StartLatitude = strconv.FormatFloat(r1.Coordinate.Lat, 'f', 6, 64)
	ride.StartLongitude = strconv.FormatFloat(r1.Coordinate.Lng, 'f', 6, 64)
	ride.EndLatitude = strconv.FormatFloat(r2.Coordinate.Lat, 'f', 6, 64)
	ride.EndLongitude = strconv.FormatFloat(r2.Coordinate.Lng, 'f', 6, 64)
	ride.ProductID = productid
	ridejson, _ := json.Marshal(ride)
	url := "https://sandbox-api.uber.com/v1/requests"
	requ, err := http.NewRequest("POST", url, bytes.NewBuffer(ridejson))
	if err != nil {
		panic(err)
	}
	requ.Header.Set("Authorization", "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZXMiOlsicHJvZmlsZSIsInJlcXVlc3QiLCJyZXF1ZXN0X3JlY2VpcHQiLCJoaXN0b3J5X2xpdGUiXSwic3ViIjoiZDdjY2JjYmMtZmU0MS00NTYwLThiNTQtN2QxY2E0Y2MzOGZkIiwiaXNzIjoidWJlci11czEiLCJqdGkiOiIwYjk3MThlMi0yOGViLTQ4YjctODc4MS0xM2ZiYWI2NDU5ZGUiLCJleHAiOjE0NTA3NjUwNDIsImlhdCI6MTQ0ODE3MzA0MiwidWFjdCI6ImdjcHJ1SHBlcmsxcm9ObWNJcUc5MDh5OTloYW1aZiIsIm5iZiI6MTQ0ODE3Mjk1MiwiYXVkIjoiYzZqVlhLX3gtVVhnS1JzTlVkeURiMm9teUZqVnlLUHkifQ.iu0wdQ-xEhu3uxNkFFz1N2vEVA1f-bil7_UzSMdkP8mBh-Ao4r3lGRrOCGiYg9fZuHjxNI8_ijpa8V-iJtD3lfkLZ1y-9uNSNLUcbJBGYQyNo3ucJ3BqIXVx6XIEw7AYP72kz9n5kjIEszYNG25yIF4-I2cYtgWxZrt_nv1_dCkdMVtRQ7WrAZFOkjv45tPH1yLYyuH8x56kZ5wEvrHkZKaLgzsgI9-UOBpy9dhaYuHDVqqbltz94N8wdw_RMGaUc4xKAsX2nSAMrnh-QGHl3L9c0ZzjAtgGPZ1RgweDdfrSc4vPUbI72HQLarwuVyhIcJ5LE7ArT0mHM_ZtS7ZDrA")
	requ.Header.Set("Content-Type", "application/json")
	outdata, err := ioutil.ReadAll(requ.Body)
	var abc Responsefromoauth
	err = json.Unmarshal(outdata, &abc)
	finalresponse.UberWaitTimeEta = abc.Eta
	updatejson, err := json.Marshal(finalresponse)
	if err != nil {
		fmt.Println("Error")
		return
	}
	otherint = otherint + 1
	currentPos = currentPos + 1
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(201)
	fmt.Fprintf(w, "%s", updatejson)

}
Beispiel #4
0
func PlanTrip(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	decoder := json.NewDecoder(r.Body)
	var u UserPostRequest
	err := decoder.Decode(&u)
	if err != nil {
		log.Println(err.Error())
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	fmt.Println(u.StartingPositionid)

	var options uber.RequestOptions
	options.ServerToken = "uiiQ8zd9D4GHSDdsmT_mzIw7DXS67enDl5tXuc-p"
	options.ClientId = "c6jVXK_x-UXgKRsNUdyDb2omyFjVyKPy"
	options.ClientSecret = "vVksauQ2gWAVFxlYDi4GDi65J_f-zVxmVFqibMyA"
	options.AppName = "Golang Application"
	options.BaseUrl = "https://sandbox-api.uber.com/v1/"

	client := uber.Create(&options)
	startingidstring, error := strconv.Atoi(u.StartingPositionid)
	if error != nil {
		panic(error)
	}
	var updatedmsg Response
	sess := getSession()
	er := sess.DB("trip-planner").C("locations").Find(bson.M{"id": startingidstring}).One(&updatedmsg)
	if er != nil {
		panic(er)
	}

	index := 0
	totalprice := 0
	totaldistance := 0.0
	totalduration := 0
	bestroute := make([]int, len(u.OtherPositionids))
	m := make(map[int]string)
	for _, ids := range u.OtherPositionids {
		otherids, err1 := strconv.Atoi(ids)
		if err1 != nil {
			panic(err1)
		}
		var otherlocid ResponsefromDB
		session := getSession()
		er = session.DB("trip-planner").C("locations").Find(bson.M{"id": otherids}).One(&otherlocid)
		if er != nil {
			panic(er)
		}
		x := &uber.PriceEstimates{}
		x.StartLatitude = updatedmsg.Coordinate.Lat
		x.StartLongitude = updatedmsg.Coordinate.Lng
		x.EndLatitude = otherlocid.Coordinate.Lat
		x.EndLongitude = otherlocid.Coordinate.Lng
		if e := client.Get(x); e != nil {
			fmt.Println(e)
		}
		totaldistance = totaldistance + x.Prices[0].Distance
		totalduration = totalduration + x.Prices[0].Duration
		totalprice = totalprice + x.Prices[0].LowEstimate
		bestroute[index] = x.Prices[0].LowEstimate
		m[x.Prices[0].LowEstimate] = ids
		index = index + 1
	}
	sort.Ints(bestroute)
	var postuber UserPostResponse
	tripID = tripID + 1
	postuber.Id = strconv.Itoa(tripID)
	postuber.Distance = totaldistance
	postuber.Totalcost = totalprice
	postuber.Totalduration = totalduration
	postuber.Status = "Planning"
	postuber.StartingPositionid = strconv.Itoa(startingidstring)
	postuber.BestrouteIds = make([]string, len(u.OtherPositionids))
	index = 0
	for _, ind := range bestroute {
		postuber.BestrouteIds[index] = m[ind]
		index = index + 1
	}
	sessions := getSession()
	collection := sessions.DB("trip-planner").C("trip")
	e := collection.Insert(postuber)
	if e != nil {
		panic(e)
	}
	js, err := json.Marshal(postuber)
	if err != nil {
		fmt.Println("Error")
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(201)
	fmt.Fprintf(w, "%s", js)
}
func (uc UserController) createpost(rw http.ResponseWriter, req *http.Request, _ httprouter.Params) {

	body, err := ioutil.ReadAll(req.Body)

	u := UberPOSTRequest{}

	users := UberApiResponse{}

	err = json.Unmarshal(body, &u)
	if err != nil {
		fmt.Println("error is", err)
	}

	//PERM LOGIC

	var in []string
	in = u.Location_ids
	l := permutations(in)
	fmt.Println("\n", l)
	fmt.Println("len is", len(l))
	StartResult := UserLocation{}

	EndResult := UserLocation{}
	var count int
	count = len(l)
	FinalCostArray := make([]int, count)
	FinalDurationArray := make([]int, count)
	FinalDistanceArray := make([]float64, count)

	var minimum int
	var value int
	var BestRoute int
	for k := 0; k < len(l); k++ {
		var CostUber int
		CostUber = 0
		var DurationUber int
		DurationUber = 0
		var DistanceUber float64
		DistanceUber = 0
		StartingLocid := u.Starting_from_location_id

		for m := 0; m < len(in)+1; m++ {

			oid := bson.ObjectIdHex(StartingLocid)
			uc.session.DB("mongodatabase").C("CMPE273").FindId(oid).One(&StartResult)

			var EndLocationId string

			if m < len(in) {

				EndLocationId = l[k][m]
			}

			if m == len(in) {

				EndLocationId = StartingLocid
			}

			endoid := bson.ObjectIdHex(EndLocationId)
			uc.session.DB("mongodatabase").C("CMPE273").FindId(endoid).One(&EndResult) //  if err != nil {
			fmt.Println("long is", EndResult.Coordinate.Longitude)
			fmt.Println("lat is", EndResult.Coordinate.Latitude)

			var StartLat float64
			var StartLong float64
			var EndLat float64
			var EndLong float64

			StartLat = StartResult.Coordinate.Latitude
			StartLong = StartResult.Coordinate.Longitude
			EndLat = EndResult.Coordinate.Latitude
			EndLong = EndResult.Coordinate.Longitude

			fmt.Println("welcome to uber")

			options1 := uber.RequestOptions{
				ServerToken:  "GyJ-Y_iqijuAFgEd5rQBN0XV9Ojy6ybKWgvET6jd",
				ClientId:     "VS8-KN-nVJ4jWyDEYdBQnZU-muBpHicd",
				ClientSecret: "aK9O5H02Uuq6n34x74SJaM6QgMy7UAkIJqzjMeRd",
				AppName:      "mongodatabaseDeepa",
			}

			client := uber.Create(&options1)

			pe := &uber.PriceEstimates{}
			pe.StartLatitude = StartLat
			pe.StartLongitude = StartLong
			pe.EndLatitude = EndLat
			pe.EndLongitude = EndLong
			if e := client.Get(pe); e != nil {
				log.Fatal(e)
			}

			var PriceUber int
			PriceUber = 0
			var DisUber float64
			DisUber = 0
			var DurUber int
			DurUber = 0

			fmt.Println("\nHere are the Uber price estimates: \n")
			for _, price := range pe.Prices {
				if price.DisplayName == "uberX" {
					PriceUber = price.LowEstimate

					DurUber = price.Duration
					DisUber = price.Distance
					fmt.Println(price.DisplayName + ": " + strconv.Itoa(price.LowEstimate))

				}

			}

			CostUber = CostUber + PriceUber
			DurationUber = DurationUber + DurUber
			DistanceUber = DistanceUber + DisUber

			if m < len(in) {

				StartingLocid = l[k][m]
				fmt.Println("swapped start loc id is ****************", StartingLocid)
			}
			fmt.Println("Cost uber is", CostUber)

		} //inner loop ends here

		FinalCostArray[k] = CostUber
		FinalDurationArray[k] = DurationUber
		FinalDistanceArray[k] = DistanceUber //float 64 to int

	}

	fmt.Println("final cost array contains", FinalCostArray)
	fmt.Println("final duration array contains", FinalDurationArray)
	fmt.Println("final distance array contains", FinalDistanceArray)

	minimum = FinalCostArray[0]
	fmt.Println("minimum value us", minimum)
	fmt.Println("len is", len(FinalCostArray))
	for i := 1; i < len(FinalCostArray); i++ {
		fmt.Println("i is", i)
		if value > FinalCostArray[i] {

			value = FinalCostArray[i]
			fmt.Println("value is ", value)
			minimum = value
			BestRoute = i

			fmt.Println("minimum value  inside if loop is", minimum)
		}

	}
	fmt.Println("total uber cost is", minimum)
	fmt.Println("minimum is on location", BestRoute)

	fmt.Println("best location", l[BestRoute])
	fmt.Println("best location distance", FinalDistanceArray[BestRoute])
	fmt.Println("best location duration", FinalDurationArray[BestRoute])

	users.Id = bson.NewObjectId()
	users.Status = "planning"
	users.Starting_from_location_id = u.Starting_from_location_id
	users.Best_route_location_ids = l[BestRoute]
	users.Total_uber_costs = FinalCostArray[BestRoute]
	users.Total_uber_duration = FinalDurationArray[BestRoute]
	users.Total_distance = FinalDistanceArray[BestRoute]

	//Write the user to mongolab
	uc.session.DB("mongodatabase").C("CMPE273Assignment3").Insert(users)

	// Marshal provided interface into JSON structure
	uj, _ := json.Marshal(users)

	rw.Header().Set("Content-Type", "application/json")
	rw.WriteHeader(201)
	fmt.Fprintf(rw, "%s", uj)

}