def update_prod_info(id): if not request.is_json: raise JSONExceptionHandler() product = Products.query.get(int(id)) if product is None: raise ProductException(str(id), "Product not found") if product.user_id != current_user.id: raise UserNotPermission(str(current_user.id), "This user doesnt own this product" + str(id)) content = request.get_json() title = content["title"] price = float(content["price"]) descript = content["descript"] bid = datetime.datetime.strptime(content["bid_date"], "%Y-%m-%d %H:%M:%S") if 'bid_date' in content else None categories = content["categories"] photo_urls = content["photo_urls"] place = content["place"] main_img = content["main_img"] if not isinstance(categories, list): raise JSONExceptionHandler("Bad format for categories, need an array") if not isinstance(photo_urls, list): raise JSONExceptionHandler("Bad format for photo_urls, need an array") CatProducts.delete_cats_by_prod(id) Images.delete_images_by_prod(id) for cat in categories: if len(cat) <= 1: raise ProductException(title, "Invalid categorie: " + cat) Categories.add_cat(cat) CatProducts.add_prod(cat, id) for photo in photo_urls: Images.add_photo(photo, id) # Notificaiones if product.price > price: users_ids = Follows.get_users_follow_prod(product.id) for user_id in users_ids: push_notify(user_id, "El precio del producto ha bajado! :D", int(product.id)) elif product.price < price: users_ids = Follows.get_users_follow_prod(product.id) for user_id in users_ids: push_notify(user_id, "El precio del producto ha subido :(", int(product.id)) product.update_me(title, price, descript, bid, place, main_img) resp = api_resp(0, "info", "Product: " + str(id) + ' (' + title + ') ' + "updated") return Response(json.dumps(resp), status=200, content_type='application/json')
def create_payment(): if not request.is_json: raise JSONExceptionHandler() content = request.get_json() amount = content["amount"] iban = content["iban"] boost_date = datetime.datetime.strptime(content["boost_date"], "%Y-%m-%d") product_id = int(content["product_id"]) product = Products.query.get(int(product_id)) if product is None: raise ProductException(str(id), "Product not found") payment_id = Payments.add(amount, iban, product_id, boost_date) # Notificaciones for cat in CatProducts.get_cat_names_by_prod(product_id): users_ids = Interests.get_users_interest_cat(cat) for user_id in users_ids: push_notify(user_id, "Nuevo producto en una categoria que te interesa", int(product_id), cat) resp = api_resp(0, "info", str(payment_id)) return Response(json.dumps(resp), status=200, content_type='application/json')
def search_products_advanced(): if not request.is_json: raise JSONExceptionHandler() content = request.get_json() title = content["title"] if 'title' in content else None price_min = float(content["price_min"]) if 'price_min' in content else None price_max = float(content["price_max"]) if 'price_max' in content else None place = str(content["place"]) if 'place' in content else None desc = str(content["descript"]) if 'descript' in content else None category = str(content["category"]) if 'category' in content else None user_id = current_user.id if current_user.id is not None else None products = Products.search_adv(user_id, title, price_min, price_max, place, desc, category) products_list = [] for prod in products: item = { "id": str(prod.id), "title": str(prod.title), "price": float(prod.price), "user_nick": str(Users.get_nick(prod.user_id)), "bid_date": str(prod.bid_date), "main_img": str(prod.main_img), "visits": int(prod.visits) } products_list.append(item) json_users = {"length": len(products_list), "list": products_list} return Response(json.dumps(json_users), status=200, content_type='application/json')
def update_logged_user(): # TODO Doc if not request.is_json: raise JSONExceptionHandler() content = request.get_json() nick = content["nick"] first_name = content["first_name"] last_name = content["last_name"] phone = int(content["phone"]) fnac = datetime.datetime.strptime(content["fnac"], "%Y-%m-%d") dni = int(content["dni"]) place = content["place"] mail = content["mail"] avatar = content["avatar"] desc = content["desc"] user_id = current_user.id user = Users.query.get(int(user_id)) user.update_me(nick, first_name, last_name, phone, fnac, dni, place, mail, avatar, desc) resp = api_resp(0, "info", "User: "******"updated") return Response(json.dumps(resp), status=200, content_type='application/json')
def update_user(id): # TODO doc if not current_user.is_mod: raise UserNotPermission(str(current_user.nick)) if not request.is_json: raise JSONExceptionHandler() user = Users.query.get(int(id)) content = request.get_json() nick = content["nick"] first_name = content["first_name"] last_name = content["mail"] phone = int(content["phone"]) fnac = datetime.datetime.strptime(content["fnac"], "%Y-%m-%d") dni = int(content["dni"]) place = content["place"] mail = content["place"] desc = content["desc"] avatar = content["avatar"] is_mod = content["is_mod"] ban_reason = content["ban_reason"] token = content["token"] points = content["points"] user.update_me(nick, first_name, last_name, phone, fnac, dni, place, mail, avatar, desc, is_mod, ban_reason, token, points, None) resp = api_resp(0, "info", "User: "******"updated") return Response(json.dumps(resp), status=200, content_type='application/json')
def login(): if not request.is_json: raise JSONExceptionHandler() content = request.get_json() nick = content["nick"] pass_ = content["pass"] remember = content["remember"] user = Users.query.filter_by(nick=nick).first() if user is None: raise UserException(str(nick)) if not user.is_validated: raise UserException(str(nick), "Mail not validated") if not user.check_password(pass_): raise UserPassException(str(nick)) if user.ban_until is not None: ban_date = datetime.datetime.strptime(str(user.ban_until), "%Y-%m-%d") if ban_date > datetime.datetime.utcnow(): raise UserBanned(str(nick), None, user.ban_until, user.ban_reason, None) login_user(user, remember=bool(remember)) resp = api_resp(0, "info", "User: "******" logged") return Response(json.dumps(resp), status=200, content_type='application/json')
def bid_up_prod(id): if not request.is_json: raise JSONExceptionHandler() product = Products.query.get(int(id)) if product is None: raise ProductException(str(id), "Product not found") if product.user_id != current_user.id: raise UserNotPermission(str(current_user.id), "This user doesnt own this product" + str(id)) content = request.get_json() bid = datetime.datetime.strptime(content["bid_until"], "%Y-%m-%d %H:%M:%S") product.bid_set(bid) resp = api_resp( 0, "info", "Product: " + str(id) + ' (' + str(product.title) + ') ' + "set bid for " + bid.strftime("%Y-%m-%d %H:%M:%S")) return Response(json.dumps(resp), status=200, content_type='application/json')
def post_bid(id): # TODO doc if not request.is_json: raise JSONExceptionHandler() content = request.get_json() bid = Products.query.get(id) if bid is None: raise ProductException(str(id), "Product not found") if bid.bid_date is None: raise ProductException(str(id), "Product isnt a bid") else: if bid.bid_date < datetime.datetime.utcnow(): raise ProductException(str(id), "Bid out of time") money = float(content["bid"]) Bids.add_bid(id, current_user.id, money) resp = api_resp( 0, "info", "Successful bid with " + str(money) + " to " + str(id) + " bid") return Response(json.dumps(resp), status=200, content_type='application/json')
def new_notification(): if not request.is_json: raise JSONExceptionHandler() content = request.get_json() user = int(content["user_id"]) product = int(content["product_id"]) category = str(content["category"]) text = str(content["text"]) if product == 0: product = None if category == "null": category = None Notifications.push(user, text, product, category) resp = api_resp(0, "info", "Notification pushed") return Response(json.dumps(resp), status=200, content_type='application/json')
def new_message(trade_id): if not request.is_json: raise JSONExceptionHandler() content = request.get_json() text = content["body"] trade = Trades.query.get(trade_id) if trade is None: raise TradeException(trade_id, "This trade isnt exist") user_from = current_user.id if trade.user_sell == user_from: user_to = trade.user_buy elif trade.user_buy == user_from: user_to = trade.user_sell else: raise TradeException(trade_id, "This user inst related with this trade") Messages.new_msg(trade_id, user_to, user_from, text) resp = api_resp(0, "info", "Message created") return Response(json.dumps(resp), status=200, content_type='application/json')
def create_product(): if not request.is_json: raise JSONExceptionHandler() content = request.get_json() title = content["title"] price = float(content["price"]) user_id = str(current_user.id) descript = content["descript"] categories = content["categories"] photo_urls = content["photo_urls"] place = content["place"] main_img = content["main_img"] if not isinstance(categories, list): raise JSONExceptionHandler("Bad format for categories, need an array") if not isinstance(photo_urls, list): raise JSONExceptionHandler("Bad format for photo_urls, need an array") product_id = Products.new_product(user_id, title, descript, price, place, main_img) for cat in categories: if len(cat) <= 1: raise ProductException(title, "Invalid categorie: " + cat) Categories.add_cat(cat) CatProducts.add_prod(cat, product_id) for photo in photo_urls: Images.add_photo(photo, product_id) # Notificaciones for cat in CatProducts.get_cat_names_by_prod(product_id): users_ids = Interests.get_users_interest_cat(cat) for user_id in users_ids: push_notify(user_id, "Nuevo producto en una categoria que te interesa", int(product_id), cat) resp = api_resp(0, "info", str(product_id)) return Response(json.dumps(resp), status=200, content_type='application/json')
def set_ban_prod(id): # TODO doc if not current_user.is_mod: raise UserNotPermission(str(current_user.nick)) if not request.is_json: raise JSONExceptionHandler() content = request.get_json() ban_reason = content["ban_reason"] Products.query.get(int(id)).ban_me(ban_reason) resp = api_resp(0, "info", "Product" + ' (' + str(id) + ') ' + "banned") return Response(json.dumps(resp), status=200, content_type='application/json')
def delete_interest(): if not request.is_json: raise JSONExceptionHandler() content = request.get_json() categories_list = content["list"] user = current_user.id for cat in categories_list: Interests.delete_interest(cat, user) resp = api_resp(0, "info", "Successful delete") return Response(json.dumps(resp), status=200, content_type='application/json')
def set_ban_user(id): # TODO doc if not current_user.is_mod: raise UserNotPermission(str(current_user.nick)) if not request.is_json: raise JSONExceptionHandler() content = request.get_json() ban_reason = content["ban_reason"] ban_until = datetime.datetime.strptime(content["ban_until"], "%Y-%m-%d") Users.query.get(int(id)).ban_me(ban_reason,ban_until) resp = api_resp(0, "info", "User" + ' (' + str(id) + ') ' + "banned") return Response(json.dumps(resp), status=200, content_type='application/json')
def new_comment_user(id): if not request.is_json: raise JSONExceptionHandler() content = request.get_json() body = content["body"] points = int(content["points"]) cmmnt_id = Comments.add_comment(id, current_user.id, body) user = Users.query.get(id) user.point_me(points) resp = api_resp(0, "info", str(cmmnt_id)) return Response(json.dumps(resp), status=200, content_type='application/json')
def new_interest(): if not request.is_json: raise JSONExceptionHandler() content = request.get_json() categories_list = content["list"] user = current_user.id for cat in categories_list: if not Categories.exist(cat): ProductException(cat, "Invalid categorie: " + cat) Interests.add_interest(cat, user) resp = api_resp(0, "info", "Interest pushed") return Response(json.dumps(resp), status=200, content_type='application/json')
def new_report(): if not request.is_json: raise JSONExceptionHandler() content = request.get_json() user_id = int(content["user_id"]) if 'product_id' in content: product_id = int(content["product_id"]) else: product_id = None reason = str(content["reason"]) id = Reports.new_report(user_id, product_id, reason) resp = api_resp(0, "info", str(id)) return Response(json.dumps(resp), status=200, content_type='application/json')
def create_user(): """ Add user to the database getting the info from the json of the request :returns: api response with the id of the new user :raises: KeyError, JSONExceptionHandler """ if not request.is_json: raise JSONExceptionHandler() content = request.get_json() nick: str = content["nick"] first_name = content["first_name"] last_name = content["last_name"] pass_ = content["pass"] phone = int(content["phone"]) fnac = datetime.datetime.strptime(content["fnac"], "%Y-%m-%d") dni = int(content["dni"]) place = content["place"] mail = content["mail"] token = random_string() user_id = Users.new_user(nick, last_name, first_name, phone, dni, place, pass_, fnac, mail, token) subject = "Confirma tu cuenta" link = request.host_url + 'user/' + str(user_id) + '/validate?token=' + token text = "Necesitamos que confirmes tu cuenta para poder iniciar sesión en nuestra aplicación, link:" + link html = "<p>Necesitamos que confirmes tu cuenta para poder iniciar sesión en nuestra aplicación</p>" \ "<h3> Link para confirmar: <a href='" + link + "'>Validar</a>!</h3><br />Comienza a intercambiar!" if first_name == 'Foo': user = Users.query.get(int(user_id)) user.validate_me() else: send_mail(mail, first_name + " " + last_name, subject, text, html) resp = api_resp(0, "info", user_id) return Response(json.dumps(resp), status=200, content_type='application/json')
def trade_offer(id): if not request.is_json: raise JSONExceptionHandler() content = request.get_json() price = float(content["price"]) products = content["products"] trade = Trades.query.get(int(id)) if trade is None: raise TradeException(str(id)) if trade.closed_s and trade.closed_b: raise TradeException(str(id), "The trade is already closed, no chages allowed") if trade.closed_s or trade.closed_b: raise TradeException(str(id), "The trade is on confirm status") if trade.user_sell != current_user.id and trade.user_buy != current_user.id: raise UserNotPermission( str(id), "This user (" + str(current_user.nick) + ") is not related with this trade") # Set the price trade.set_price(price) # Add products to the offer for p in products: TradesOffers.add_product(id, p) resp = api_resp(0, "info", "Successful new offer") return Response(json.dumps(resp), status=200, content_type='application/json')
def create_trade(): if not request.is_json: raise JSONExceptionHandler() content = request.get_json() seller_id = content["seller_id"] buyer_id = content["buyer_id"] product_id = int(content["product_id"]) product = Products.query.get(int(product_id)) if product is None: raise ProductException(str(id), "Product not found") trade_id = Trades.add(product_id, seller_id, buyer_id) resp = api_resp(0, "info", str(trade_id)) return Response(json.dumps(resp), status=200, content_type='application/json')