def get(self, id): logger.getLogger().debug("GET at /trips/" + str(id)) # (validate-token) Validate user token if not "UserToken" in request.headers: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token") token = request.headers['UserToken'] (valid, response) = TokenGenerator.validateToken(token) if not valid: return ResponseMaker.response_error(constants.UNAUTHORIZED, "Unauthorized") active_trips = MongoController.getCollection("active_trips") trip = list(active_trips.find({"_id": id})) if len(trip) == 0: return ResponseMaker.response_error(constants.NOT_FOUND, "Not found") # This should never happen if len(trip) > 1: return ResponseMaker.response_error( constants.ERROR, "Internal server error - more than one trip with same ID") trip = trip[0] print(trip) return ResponseMaker.response_object(constants.SUCCESS, ["message", "trip"], ["OK", trip])
def get(self, id): logger.getLogger().debug("GET at /users/userId/cars " + str(id)) if not "UserToken" in request.headers: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token") token = request.headers['UserToken'] (valid, decoded) = TokenGenerator.validateToken(token) print(decoded) if not valid or (decoded['_id'] != id): return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden") cars = [ user for user in self.users.find() if user['_id'] == id and user['type'] == 'driver' ] try: if (len(cars) == 0): print("FETECHING CARS...") status_code, cars = ServerRequest.getUserCars(id) except Exception as e: return ResponseMaker.response_error( constants.NOT_FOUND, "User id did not match any existing users.") return ResponseMaker.response_object(constants.SUCCESS, ['cars'], cars)
def cancel_handler(self, action, trip, userId): if not userId == trip["passengerId"] and not userId == trip["driverId"]: return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden - you are not the owner of this trip") if not trip["state"] in TripStates.TRIP_CANCELABLE: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - this trip cannot be cancelled") active_trips = MongoController.getCollection("active_trips") active_trips.remove( { "_id" : trip["_id"] }) users = MongoController.getCollection("online") users.update( { "_id" : trip["passengerId"] }, { "$set" : { "state" : User.USER_PSG_IDLE, "tripId" : "" } }) if userId != trip["passengerId"]: passenger = list(users.find({ "_id" : trip["passengerId"]}))[0] NotificationSender().notifyUser(passenger["username"], "Your trip has been canceled!") # If trip had a driver, change it's state if trip["driverId"] >= 0: users.update( { "_id" : trip["driverId"] }, { "$set" : { "state" : User.USER_DRV_IDLE, "tripId" : "" } }) # Send firebase notification driver = list(users.find({ "_id" : trip["driverId"]}))[0] NotificationSender().notifyUser(driver["username"], "Your trip has been canceled!") return ResponseMaker.response_object(constants.SUCCESS, ["message", "action", "trip"], ["Trip was deleted. Passenger updated.", action["action"], trip])
def post(self): print(request.json) logger.getLogger().debug("POST at /trips/estimation") logger.getLogger().debug(request.json) try: # (validate-token) Validate user token if not "UserToken" in request.headers: return ResponseMaker.response_error( constants.PARAMERR, "Bad request - missing token") token = request.headers['UserToken'] (valid, response) = TokenGenerator.validateToken(token) if not valid: return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden") #Send trip estimation request to shared server. (status, response) = ServerRequest.estimateTrip(request.json) if (status != constants.SUCCESS): return ResponseMaker.response_error(status, response["message"]) return ResponseMaker.response_object(status, ["cost"], [response]) except Exception as e: logger.getLogger().error("Error " + str(e)) return ResponseMaker.response_error(constants.ERROR, "Unexpected error" + str(e))
def delete(self, id): print("DELETE at /users/id") logger.getLogger().debug("DELETE at /users/" + str(id)) if not "UserToken" in request.headers: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token") token = request.headers['UserToken'] (valid, decoded) = TokenGenerator.validateToken(token) print(decoded) if not valid or (decoded['_id'] != id): return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden") #Ask Shared-Server to delete this user delete_success, status_code = ServerRequest.deleteUser(id) if delete_success: #Delete in local data-base candidates = [ User.UserJSON(user) for user in self.users.find() if user['_id'] == id ] self.users.delete_many({"_id": id}) logger.getLogger().info("Successfully deleted user.") else: logger.getLogger().error( "Attempted to delete user with non-existent id.") return ResponseMaker.response_error(status_code, "Delete error") return ResponseMaker.response_object(constants.DELETE_SUCCESS, ['user'], candidates)
def get(self, id): logger.getLogger().debug("GET at /users/" + str(id)) if not "UserToken" in request.headers: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token") token = request.headers['UserToken'] (valid, decoded) = TokenGenerator.validateToken(token) print("GET at /user/id") candidates = [user for user in self.users.find() if user['_id'] == id] if len(candidates) == 0: #If not available in local data-base, ask Shared-Server for user info. (status, response) = ServerRequest.getUser(id) if (status != constants.SUCCESS): return ResponseMaker.response_error(status, response["message"]) candidates = [response] user = candidates[0] self.users.insert_one(user) if len(candidates) == 0: logger.getLogger().error( "Attempted to retrieve user with non-existent id.") return ResponseMaker.response_error(constants.NOT_FOUND, "User id not found:" + str(e)) return ResponseMaker.response_object(constants.SUCCESS, ['user'], [User.UserJSON(candidates[0])])
def get(self, userId, carId): logger.getLogger().debug("GET at /users/" + str(userId) + "/carId/" + str(carId)) if not "UserToken" in request.headers: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token") token = request.headers['UserToken'] (valid, decoded) = TokenGenerator.validateToken(token) print(decoded) if not valid or (decoded['_id'] != userId): return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden") car = [ ] #[ car for car in self.users.find( { $and: [ { "_id": { $eq : userId} }, { "cars._id": { $eq : carId } } ] } , { cars : 1 } ) if car["_id"]==carId ] try: if (len(car) == 0): status_code, car = ServerRequest.getUserCar(userId, carId) return ResponseMaker.response_object(constants.SUCCESS, ['car'], car["properties"]) except Exception as e: return ResponseMaker.response_error(constants.ERROR, "Unexpected error")
def rate_handler(self, action, trip, userId): if not userId == trip["passengerId"]: return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden - you were not the passenger of this trip") if not trip["state"] == TripStates.TRIP_FINISHED: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - this trip cannot be rated") if action["rating"] > 5 or action["rating"] < 0: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - thats not a valid rating") # Retrieve driver users = MongoController.getCollection("online") passenger = list(users.find({"_id" : userId}))[0] driver = list(users.find({"_id" : trip["driverId"]}))[0] if not passenger["state"] == User.USER_PSG_ARRIVED: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - wrong passenger state") active_trips = MongoController.getCollection("active_trips") active_trips.update( { "_id" : trip["_id"] }, { "$set" : { "state" : TripStates.TRIP_FINISHED_RATED } } ) rating_count = driver["rating"]["rateCount"] + 1 current_rate = driver["rating"]["rate"] + action["rating"] logger.getLogger().debug("User [" + str(passenger["_id"]) + "] rated with " + str(action["rating"]) + " driver [" + str(driver["_id"]) + "]") users.update( { "_id" : driver["_id"] }, { "$set" : { "rating.rateCount" : rating_count } } ) users.update( { "_id" : driver["_id"] }, { "$set" : { "rating.rate" : current_rate } } ) NotificationSender().notifyUser(driver["username"], "You just got a new review!") return ResponseMaker.response_object(constants.SUCCESS, ["message", "action", "trip"], ["Rating saved.", action["action"], trip])
def payment_handler(self, action, trip, userId): if not userId == trip["passengerId"]: return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden - you were not the passenger of this trip") if not trip["state"] in TripStates.TRIP_ABLE_TO_PAY: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - this trip cannot be payed yet") shared_trip = { "trip" : TripStates.trip_to_shared(trip), "paymethod" : action["paymethod"] } try: (status_code, response) = ServerRequest.createTrip(shared_trip) except Exception as e: logger.getLogger().exception(str(e)) print(str(e)) return ResponseMaker.response_error(500, "Internal Error") logger.getLogger().exception(shared_trip) if not status_code == constants.CREATE_SUCCESS: return ResponseMaker.response_object(status_code, ["message", "to_shared"], ["Payment API error, try again", shared_trip]) active_trips = MongoController.getCollection("active_trips") active_trips.update( { "_id" : trip["_id"] }, { "$set" : { "state" : TripStates.TRIP_PAYED } } ) active_trips.remove( { "_id" : trip["_id"] } ) users = MongoController.getCollection("online") users.update( { "_id" : userId }, { "$set" : { "state" : User.USER_PSG_IDLE} } ) users.update( { "_id" : userId }, { "$set" : { "tripId" : "" } } ) return ResponseMaker.response_object(status_code, ["paymethod"], [response])
def finish_handler_any(self, action, trip, user): users = MongoController.getCollection("online") active_trips = MongoController.getCollection("active_trips") if user["type"] == User.USER_TYPE_PASSENGER: if user["state"] != User.USER_PSG_TRAVELING: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - passenger is not traveling") trip_state = TripStates.TRIP_FINISHED_PASSENGER user_state = User.USER_PSG_WAITING_FINISH theother = list(users.find({ "_id" : trip["driverId"]}))[0] if user["type"] == User.USER_TYPE_DRIVER: if user["state"] != User.USER_DRV_TRAVELING: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - driver is not traveling") trip_state = TripStates.TRIP_FINISHED_DRIVER user_state = User.USER_DRV_WAITING_FINISH theother = list(users.find({ "_id" : trip["passengerId"]}))[0] active_trips.update( { "_id" : trip["_id"] }, { "$set" : { "state" : trip_state } } ) users.update( { "_id" : user["_id"] }, { "$set" : { "state" : user_state } } ) NotificationSender().notifyUser(theother["username"], user["username"] + " wants to finish the trip!") return ResponseMaker.response_object(constants.SUCCESS, ["message", "action", "trip"], ["Trip was updated.", action["action"], trip])
def finish_handler(self, action, trip, userId): if not userId == trip["passengerId"] and not userId == trip["driverId"]: return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden - you are not part of this trip") if trip["state"] not in TripStates.TRIP_FINISH_VALID: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - trip is not started") # Retrieve user users = MongoController.getCollection("online") user = list(users.find({"_id" : userId})) if len(user) > 1: return ResponseMaker.response_error(constants.ERROR, "Internal server error - more than one user with same ID.") if len(user) == 0: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - user not found") user = user [0] # Anyone can finish first if trip["state"] == TripStates.TRIP_STARTED: return self.finish_handler_any(action, trip, user) elif trip["state"] == TripStates.TRIP_FINISHED_DRIVER: return self.finish_handler_passenger(action, trip, user) elif trip["state"] == TripStates.TRIP_FINISHED_PASSENGER: return self.finish_handler_driver(action, trip, user) return ResponseMaker.response_error(constants.PARAMERR, "Internal server error.")
def start_handler(self, action, trip, userId): if not userId == trip["passengerId"] and not userId == trip["driverId"]: return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden - you are not the owner of this trip") if trip["state"] not in TripStates.TRIP_START_VALID: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - this trip cannot start") # Retrieve user users = MongoController.getCollection("online") user = list(users.find({"_id" : userId})) if len(user) > 1: return ResponseMaker.response_error(constants.ERROR, "Internal server error - more than one user with same ID.") if len(user) == 0: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - user not found") user = user[0] #dist = Distances.computeDistance(user["coord"], trip["directions"]["origin"]) #logger.getLogger().debug("Distance from user [" + user["username"] + "] to starting point is " + str(dist)) #if dist > MAXIMUM_USER_DISTANCE: # return ResponseMaker.response_error(constants.PARAMERR, "Bad request - you are too far away from the starting point") # Anyone can accept first if trip["state"] == TripStates.TRIP_CONFIRMED: return self.start_handler_any(action, trip, user) elif trip["state"] == TripStates.TRIP_STARTED_DRIVER: return self.start_handler_passenger(action, trip, user) elif trip["state"] == TripStates.TRIP_STARTED_PASSENGER: return self.start_handler_driver(action, trip, user) return ResponseMaker.response_error(constants.PARAMERR, "Internal server error.")
def post(self): print(request.json) logger.getLogger().debug("POST at /users/logout") logger.getLogger().debug(request.json) if not "UserToken" in request.headers: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token") token = request.headers['UserToken'] result = TokenGenerator.validateToken(token) # (mongodb) Return all logged in users. users_online = MongoController.getCollection("online") user = [ User.UserJSON(user) for user in users_online.find() if (user['username'] == result[1]['username']) ] if (len(user) == 0): return ResponseMaker.response_error(constants.NOT_FOUND, "User not found") #users_online.delete_many(user[0]); users_online.update({"_id": user[0]["_id"]}, {"$set": { "online": False }}) return ResponseMaker.response_object(constants.SUCCESS, ['user'], [user[0]])
def start_handler_any(self, action, trip, user): users = MongoController.getCollection("online") active_trips = MongoController.getCollection("active_trips") if user["type"] == User.USER_TYPE_PASSENGER: if user["state"] != User.USER_PSG_WAITING_DRIVER: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - passenger is not waiting for driver") trip_state = TripStates.TRIP_STARTED_PASSENGER user_state = User.USER_PSG_WAITING_START theother = list(users.find({ "_id" : trip["driverId"]}))[0] if user["type"] == User.USER_TYPE_DRIVER: if user["state"] != User.USER_DRV_GOING_TO_PICKUP: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - driver is not going to pickup") trip_state = TripStates.TRIP_STARTED_DRIVER user_state = User.USER_DRV_WAITING_START theother = list(users.find({ "_id" : trip["passengerId"]}))[0] active_trips.update( { "_id" : trip["_id"] }, { "$set" : { "time_start_waiting" : datetime.datetime.now().isoformat() } } ) active_trips.update( { "_id" : trip["_id"] }, { "$set" : { "state" : trip_state } } ) users.update( { "_id" : user["_id"] }, { "$set" : { "state" : user_state } } ) # Send notification to the other user NotificationSender().notifyUser(theother["username"], user["username"] + " is ready to start the trip!") trip = list(active_trips.find({"_id" : trip["_id"]}))[0] return ResponseMaker.response_object(constants.SUCCESS, ["message", "action", "trip"], ["Trip was updated.", action["action"], trip])
def get(self): logger.getLogger().debug("GET at /trips") # (validate-token) Validate user token if not "UserToken" in request.headers: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token") token = request.headers['UserToken'] (valid, requester) = TokenGenerator.validateToken(token) if not valid: return ResponseMaker.response_error(constants.UNAUTHORIZED, "Unauthorized") # Check if user is 1) logged in, and 2) a passenger (user, is_passenger) = self.userId_is_passenger(requester["_id"]) if user == None: return ResponseMaker.response_error( constants.PARAMERR, "Bad request - user is not logged in") if is_passenger: return ResponseMaker.response_error( constants.FORBIDDEN, "Forbidden - user is not driver") logger.getLogger().debug("The 'driver' requesting trips is: " + str(user["_id"]) + "-" + user["username"]) ## Actual getting of the trips! params = request.args active_trips = MongoController.getCollection("active_trips") trips = list(active_trips.find()) if "filter" in params: trips = [ trip for trip in trips if trip["state"] == params["filter"] ] if "sort" in params and params["sort"] == "near": trips.sort(key=lambda x: Distances.computeDistance( user["coord"], x["directions"]["origin"])) if "limit" in params: limit = int(params["limit"]) if limit > 0: trips = trips[:(limit)] return ResponseMaker.response_object(constants.SUCCESS, ["message", "trips"], ["Getting trips!", trips])
def post(self): logger.getLogger().debug("POST at /directions") logger.getLogger().debug(request.json) print(request.json) # Check user validity if not "UserToken" in request.headers: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token") token = request.headers['UserToken'] (valid, decoded) = TokenGenerator.validateToken(token) if not valid: return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden") # Check endpoints are in the request if not request.json: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing parameters") if not "origin" in request.json or not "destination" in request.json: return ResponseMaker.response_error(constants.PARAMERR, "Bad request") origin = request.json['origin'] destination = request.json['destination'] # Check for coordinates on endpoints if not "lat" in origin or not "lng" in origin: return ResponseMaker.response_error(constants.PARAMERR, "Bad request") if not "lat" in destination or not "lng" in destination: return ResponseMaker.response_error(constants.PARAMERR, "Bad request") origin_str = "origin=" + str(origin["lat"]) + "," + str(origin["lng"]) print("origin_str = " + origin_str) destination_str = "destination=" + str(destination["lat"]) + "," + str(destination["lng"]) r = requests.get(GOOGLE_DIRECTIONS + "?" + origin_str + "&" + destination_str + "&key=" + GOOGLE_API_KEY) r = r.json() print(r) if r["status"] != "OK": return ResponseMaker.response_error(500, "Google API error: " + r["status"]) r = self.convert_response(r) trip = {} trip["directions"] = r trip["driverId"] = -1 trip["passengerId"] = decoded["_id"] # (shared) Ask shared for a trip cost estimation try: (status_code, response) = ServerRequest.estimateTrip(TripStates.trip_to_shared(trip)) except Exception as e: logger.getLogger().exception("No cost estimation from server: " + str(e)) if not status_code == constants.SUCCESS: logger.getLogger().exception("No cost estimation from server: " + str(e)) cost = {} else: cost = response["cost"] return ResponseMaker.response_object(200, ["directions", "cost"], [r, cost])
def finish_handler_driver(self, action, trip, user): users = MongoController.getCollection("online") active_trips = MongoController.getCollection("active_trips") if user["state"] != User.USER_DRV_TRAVELING: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - driver is not traveling") passenger = list(users.find({ "_id" : trip["passengerId"]}))[0] if passenger["state"] != User.USER_PSG_WAITING_FINISH: return ResponseMaker.response_error(constants.ERROR, "Internal server error - passenger in a bad state") active_trips.update( { "_id" : trip["_id"] }, { "$set" : { "state" : TripStates.TRIP_FINISHED } } ) active_trips.update( { "_id" : trip["_id"] }, { "$set" : { "time_finish" : datetime.datetime.now().isoformat() } } ) users.update( { "_id" : user["_id"]}, { "$set" : { "state" : User.USER_DRV_IDLE } } ) users.update( { "_id" : user["_id"]}, { "$set" : { "tripId" : "" } } ) users.update( { "_id" : passenger["_id"] }, { "$set" : { "state" : User.USER_PSG_ARRIVED } } ) return ResponseMaker.response_object(constants.SUCCESS, ["message", "action", "trip"], ["Trip just started.", action["action"], trip])
def post(self): print(request.json) logger.getLogger().debug("POST at /users") logger.getLogger().debug(request.json) # (shared-server) Send new user data to shared server. (status, response) = ServerRequest.createUser(request.json) if (status != constants.CREATE_SUCCESS): return ResponseMaker.response_error(status, response['message']) user_js = User.UserJSON(response) users_online = MongoController.getCollection("online") users_online.insert_one(user_js) return ResponseMaker.response_object(status, ['user'], [user_js])
def post(self): logger.getLogger().debug("POST at /users/login") logger.getLogger().debug(request.json) try: # (shared-server) First ask shared server for credentials validation (valid, response) = ServerRequest.validateUser(request.json) if not valid: logger.getLogger().debug( 'Error 418: I\' m a teapot and your credentials are not valid!' ) return ResponseMaker.response_error(response.status_code, "Shared server error") logger.getLogger().debug( "Credentials are valid, server responsed with user") user_js = User.UserJSON(response) # (token-generation) Generate a new UserToken for that user token = TokenGenerator.generateToken(response) users_online = MongoController.getCollection("online") # (mongodb) If credentials are valid, and user is not here, add it for user in users_online.find(): if user_js["_id"] == user["_id"]: # Found it! Checking refs! logger.getLogger().debug( "User trying to log in already found in the local db") if user_js["_ref"] != user["_ref"]: logger.getLogger().debug( "Login of an user already in bdd. _ref is old") user_js = User.UserUpdateDedicatedFields(user_js, user) else: user_js = user break user_js["online"] = True users_online.update({"_id": user_js["_id"]}, user_js, upsert=True) return ResponseMaker.response_object(constants.SUCCESS, ['user', 'token'], [user_js, token]) except Exception as e: logger.getLogger().exception(str(e)) print(str(e)) return ResponseMaker.response_error(500, "Internal Error")
def start_handler_driver(self, action, trip, user): users = MongoController.getCollection("online") active_trips = MongoController.getCollection("active_trips") if user["state"] != User.USER_DRV_GOING_TO_PICKUP: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - driver is not going to pickup") passenger = list(users.find({ "_id" : trip["passengerId"]}))[0] if passenger["state"] != User.USER_PSG_WAITING_START: return ResponseMaker.response_error(constants.ERROR, "Internal server error - passenger in a bad state") active_trips.update( { "_id" : trip["_id"] }, { "$set" : { "state" : TripStates.TRIP_STARTED } } ) active_trips.update( { "_id" : trip["_id"] }, { "$set" : { "time_start" : datetime.datetime.now().isoformat() } } ) users.update( { "_id" : user["_id"]}, { "$set" : { "state" : User.USER_DRV_TRAVELING} } ) users.update( { "_id" : passenger["_id"] }, { "$set" : { "state" : User.USER_PSG_TRAVELING} } ) trip = list(active_trips.find({"_id" : trip["_id"]}))[0] return ResponseMaker.response_object(constants.SUCCESS, ["message", "action", "trip"], ["Trip just started.", action["action"], trip])
def post(self): logger.getLogger().debug("POST at /payment") # (validate-token) Validate user token if not "UserToken" in request.headers: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token") users = MongoController.getCollection("online") active_trips = MongoController.getCollection("active_trips") payment_info = request.json trip = list(active_trips.find({"_id" : payment_info["trip"]["_id"]})) if len(trip) == 0: return ResponseMaker.response_error(constants.NOT_FOUND, "Error - this trip has no pending payment.") if payment_info["passengerId"] != trip["passengerId"]: return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden - you are not the owner of this trip.") if trip["state"] != TripStates.TRIP_FINISHED: return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden - this trip has not concluded.") try: status_code, response = ServerRequest.makePayment(trip["passengerId"],payment_info) if status_code == constants.SUCCESS: transaction = response active_trips.delete({"_id":trip["_id"]}) users.update({"_id":trip["passengerId"]}, {"$set":{"state":User.USER_PSG_IDLE, "tripId" : "" }}) users.update({"_id":trip["driverId"]}, {"$set":{"state":User.USER_DRV_IDLE, "tripId" : "" }}) NotificationSender.notifyUser(trip["passengerId"], "Your payment was successfully processed. Thank you for choosing FIUBER.") logger.getLogger().debug("Trip " + str(trip["_id"]) + "successfully paid.") return ResponseMaker.response_object(constants.SUCCESS, ["transaction"], transaction) logger.getLogger().error("ERROR ocurred when attempting to pay trip: " + str(trip["_id"])) return ResponseMaker.response_error(constants.ERROR, "This transaction was unsuccessful. " + str(response["message"])) except Exception as e: return ResponseMaker.response_error(constants.ERROR, "Error - an error ocurred during this transaction.")
def put(self, id): print(id) print("PUT at /user/" + str(id) + "/rating") logger.getLogger().debug("PUT at /users/" + str(id) + "/rating") if not "UserToken" in request.headers: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token") token = request.headers['UserToken'] (valid, decoded) = TokenGenerator.validateToken(token) if not valid or (decoded['_id'] != id): return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden") try: new_score = request.json["rate"] rating_count = [ user["rating"]["rateCount"] for user in self.users.find() if user['_id'] == id and user['type'] == "driver" ][0] current_rate = [ user["rating"]["rate"] for user in self.users.find() if user['_id'] == id and user['type'] == "driver" ][0] if len(rating_count) == 0 and len(current_rate) == 0: return ResponseMaker.response_error(constants.NOT_FOUND, "User id not found.") #Recalculate rating rating_count += 1 current_rate = current_rate + new_score #Update in local data-base self.users.update({'_id': id}, { "$set": { "rating.rateCount": rating_count, "rating.rate": current_rate } }, upsert=True) logger.getLogger().info("Successfully updated driver rating") driver = [ user for user in self.users.find() if user['_id'] == id and user['type'] == "driver" ][0] return ResponseMaker.response_object(constants.SUCCESS, ['rating'], [User.RatingUserJSON(driver)]) except ValueError as e: logger.getLogger().error(str(e)) return ResponseMaker.response_error(constants.UPDATE_CONFLICT, "User update failed:" + str(e)) except requests.exceptions.Timeout as e: logger.getLogger().error(str(e)) return ResponseMaker.response_error(constants.REQ_TIMEOUT, "User update failed:" + str(e)) except Exception as e: logger.getLogger().error(str(e)) return ResponseMaker.response_error(constants.ERROR, str(e))
def delete(self, userId, carId): print("DELETE at /users/id") logger.getLogger().debug("DELETE at /users/" + str(userId) + "/cars/" + str(carId)) if not "UserToken" in request.headers: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token") token = request.headers['UserToken'] (valid, decoded) = TokenGenerator.validateToken(token) print(decoded) if not valid or (decoded['_id'] != userId): return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden") try: #Ask Shared-Server to delete this user delete_success, status_code = ServerRequest.deleteUserCar( userId, carId) if delete_success: #Delete in local data-base self.users.update({"_id": id}, {'$pull': { "cars": { "_id": carId } }}) logger.getLogger().info("Successfully deleted user car.") return ResponseMaker.response_object(constants.DELETE_SUCCESS, ['car'], {"id": carId}) else: logger.getLogger().error( "Attempted to delete car with non-existent id.") return ResponseMaker.response_error(status_code, "Delete error") except Exception as e: print(str(e)) return ResponseMaker.response_error(constants.ERROR, "Unexpected error")
def get(self): logger.getLogger().debug("GET at /users") # (validate-token) Validate user token if not "UserToken" in request.headers: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token") token = request.headers['UserToken'] (valid, response) = TokenGenerator.validateToken(token) if not valid: return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden") # (mongodb) Return all logged in users. users_online = MongoController.getCollection("online") aux = [User.UserJSON(user) for user in users_online.find()] user = list(users_online.find({"_id": response["_id"]})) if len(user) == 0: return ResponseMaker.response_error( constants.PARAMERR, "Bad request - you may not be loged in") user = user[0] ## Aditional params (only supporting "sort") params = request.args if "filter" in params: aux = [u for u in aux if u["type"] == params["filter"]] if "sort" in params and params["sort"] == "near": aux.sort(key=lambda x: Distances.computeDistance( user["coord"], x["coord"])) if "limit" in params: limit = int(params["limit"]) if limit > 0: aux = aux[:(limit)] return ResponseMaker.response_object(constants.SUCCESS, ['users'], [aux])
def get(self, id): logger.getLogger().debug("GET at /users/" + str(id) + "/transactions") if not "UserToken" in request.headers: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token") token = request.headers['UserToken'] (valid, decoded) = TokenGenerator.validateToken(token) print(decoded) if not valid or (decoded['_id'] != id): return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden") transactions = []#TODO:try fetch transactions from local database try: if (len(transactions) == 0): status_code, transactions = ServerRequest.getUserTransactions(id) except Exception as e: return ResponseMaker.response_error(constants.NOT_FOUND, "User id did not match any existing users." + str(e)) return ResponseMaker.response_object(constants.SUCCESS, ['transactions'], [transactions])
def get(self): logger.getLogger().debug("GET at /payment") # (validate-token) Validate user token if not "UserToken" in request.headers: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token") token = request.headers['UserToken'] (valid, response) = TokenGenerator.validateToken(token) if not valid: return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden") status_code, response = ServerRequest.getPaymethods() if (status_code != constants.SUCCESS): return ResponseMaker.response_object(constants.ERROR, response['message']) print(response) return ResponseMaker.response_object(constants.SUCCESS, ['paymethods'], [response['paymethods']])
def reject_handler(self, action, trip, userId): if not userId == trip["passengerId"]: return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden - you are not the passenger of this trip") users = MongoController.getCollection("online") passenger = list(users.find({"_id" : userId})) if len(passenger) > 1: return ResponseMaker.response_error(constants.ERROR, "Internal server error - more than one user with same ID.") if len(passenger) == 0: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - user not found") passenger = passenger[0] if not trip["state"] == TripStates.TRIP_ACCEPTED: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - wrong trip state") if not passenger["state"] == User.USER_PSG_SELECTING_DRIVER: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - wrong passenger state") driver = list(users.find({ "_id" : trip["driverId"]}))[0] active_trips = MongoController.getCollection("active_trips") active_trips.update( { "_id" : trip["_id"] }, { "$set" : { "state" : TripStates.TRIP_PROPOSED } } ) active_trips.update( { "_id" : trip["_id"] }, { "$set" : { "driverId" : -1 } }) users.update( { "_id" : userId }, { "$set" : { "state" : User.USER_PSG_WAITING_ACCEPT } } ) users.update( { "_id" : trip["driverId"] }, { "$set" : { "state" : User.USER_DRV_IDLE } } ) users.update( { "_id" : trip["driverId"] }, { "$set" : { "tripId" : "" } } ) NotificationSender().notifyUser(driver["username"], "Trip rejected") NotificationSender().notifyUser(passenger["username"], "Driver rejected!") trip = list(active_trips.find({"_id" : trip["_id"]}))[0] return ResponseMaker.response_object(constants.SUCCESS, ["message", "action", "trip"], ["Trip was updated.", action["action"], trip])
def post(self, id): print(request.json) logger.getLogger().debug("POST at /users/cars") logger.getLogger().debug(request.json) try: if not "UserToken" in request.headers: return ResponseMaker.response_error( constants.PARAMERR, "Bad request - missing token") token = request.headers['UserToken'] (valid, decoded) = TokenGenerator.validateToken(token) print(decoded) if not valid or (decoded['_id'] != id): return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden") #Create car at shared server. (status, response) = ServerRequest.createUserCar(id, request.json) if (status != constants.CREATE_SUCCESS): return ResponseMaker.response_error(status, response["message"]) #Update local database car = response car["_id"] = car.pop("id") self.users.update({"_id": id}, {"$push": {"cars": car}}) return ResponseMaker.response_object(status, ["car"], [car]) except Exception as e: logger.getLogger().debug(str(e)) print(str(e)) return ResponseMaker.response_error(constants.ERROR, "Unexpected error: " + str(e))
def get(self, id): logger.getLogger().debug("GET at /users/" + str(id) + "/trips") if not "UserToken" in request.headers: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token") token = request.headers['UserToken'] (valid, decoded) = TokenGenerator.validateToken(token) if not valid or (decoded['_id'] != id): return ResponseMaker.response_error(constants.UNAUTHORIZED, "Unauthorized") print("GET at /user/id/trips") #Search local database trips = [] #[user for user in self.users.find() if user['_id'] == id] if len(trips) == 0: #If not available in local data-base, ask Shared-Server for user info. (status, response) = ServerRequest.getUserTrips(id) if (status != constants.SUCCESS): return ResponseMaker.response_error(status, response["message"]) #TODO: fetch user from ss and store locally trips = response if (status == constants.NOT_FOUND): logger.getLogger().error( "Attempted to retrieve non-existent user trip list.") return ResponseMaker.response_error(constants.NOT_FOUND, "Trip list not found.") return ResponseMaker.response_object(constants.SUCCESS, ['trips'], [trips])
def get(self, id): logger.getLogger().debug("GET at /users/" + str(id) + "/rating") if not "UserToken" in request.headers: return ResponseMaker.response_error(constants.PARAMERR, "Bad request - missing token") token = request.headers['UserToken'] (valid, decoded) = TokenGenerator.validateToken(token) if not valid or (decoded['_id'] != id): return ResponseMaker.response_error(constants.FORBIDDEN, "Forbidden") try: print("GET at /users/" + str(id) + "/rating") candidates = [ user for user in self.users.find() if user['_id'] == id ] if len(candidates) == 0: #If not available in local data-base, ask Shared-Server for user info. (status, response) = ServerRequest.getUser(id) if (status != constants.SUCCESS): return ResponseMaker.response_error( status, response["message"]) candidates = [response] if len(candidates) == 0: logger.getLogger().error( "Attempted to retrieve user with non-existent id.") return ResponseMaker.response_error( constants.NOT_FOUND, "User id not found:" + str(e)) if candidates[0]["type"] != "driver": return ResponseMaker.response_error( constants.PARAMERR, "The requested user is not a driver. Only drivers receive ratings." ) return ResponseMaker.response_object( constants.SUCCESS, ['rating'], [User.RatingUserJSON(candidates[0])]) except Exception as e: logger.getLogger().error(str(e)) return ResponseMaker.response_error(constants.ERROR, str(e))