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 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 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 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 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 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 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 upload_file(): # check if the post request has the file part if 'file' not in request.files: raise Exception('No file part') file = request.files['file'] # if user does not select file, browser also # submit an empty part without filename if file.filename == '': raise Exception('No selected file') if file and allowed_file(file.filename): filename, file_extension = os.path.splitext(file.filename) filename = random_string() + file_extension path = "./images/" + filename file.save(path) else: raise Exception('File not allowed') url = '/uploads/' + filename resp = api_resp(0, "info", url) return Response(json.dumps(resp), status=200, content_type='application/json')
def unfollow_product(id): # TODO doc current_user.unfollow_prod(id) resp = api_resp(0, "info", "User" + ' (' + str(current_user.nick) + ') ' + "unfollows a product" + ' (' + str(id) + ') ') return Response(json.dumps(resp), status=200, content_type='application/json')
def set_mod_user(id): # TODO doc Users.query.get(int(id)).mod_me() resp = api_resp(0, "info", "All Ok") return Response(json.dumps(resp), status=200, content_type='application/json')
def delete_notifications(): Notifications.delete_all(current_user.id) resp = api_resp(0, "info", "Successful delete") return Response(json.dumps(resp), status=200, content_type='application/json')
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 delete_user(id): # TODO doc if not current_user.is_mod: raise UserNotPermission(str(current_user.nick)) Users.query.get(int(id)).delete_me() resp = api_resp(0, "info", "User: "******" deleted") return Response(json.dumps(resp), status=200, content_type='application/json')
def delete_notification_id(id): # TODO comprobar k la noty es del user loged Notifications.delete_id(id) resp = api_resp(0, "info", "Successful delete") return Response(json.dumps(resp), status=200, content_type='application/json')
def trade_confirm(id): trade = Trades.query.get(int(id)) if trade is None: raise TradeException(str(id), "Trade not found") if trade.closed_s and trade.closed_b: raise TradeException(str(id), "The trade is already closed, no chages allowed") if current_user.id == trade.user_sell: trade.switch('s') if trade.closed_s: resp = api_resp(0, "info", "Success confirm for trade " + '(' + str(id) + ')') else: resp = api_resp( 0, "info", "Success unconfirm for trade " + '(' + str(id) + ')') elif trade.user_buy == current_user.id: trade.switch('b') if trade.closed_b: resp = api_resp(0, "info", "Success confirm for trade " + '(' + str(id) + ')') else: resp = api_resp( 0, "info", "Success unconfirm for trade " + '(' + str(id) + ')') else: raise UserNotPermission( str(id), "Tis user (" + str(current_user.nick) + ") is not related with this trade") if trade.closed_s and trade.closed_b: product = Products.query.get(trade.product_id) product.sold_me() resp = api_resp( 0, "info", "Success confirm and close for trade " + '(' + str(id) + ')') return Response(json.dumps(resp), status=200, content_type='application/json')
def delete_report(id): if not current_user.is_mod: raise UserNotPermission(str(current_user.nick)) Reports.delete_by_id(id) resp = api_resp(0, "info", "Report " + str(id) + "deleted") return Response(json.dumps(resp), status=200, content_type='application/json')
def delete_comment_user(id): if not current_user.is_mod: raise UserNotPermission(str(current_user.nick)) if Comments.query.get(id) is None: raise UserException(str(id), "Comment not found") Comments.delete_comment(id) resp = api_resp(0, "info", "Comment (" + str(id) + ")deleted") return Response(json.dumps(resp), status=200, content_type='application/json')
def delete_product(id): # TODO doc 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)) Products.query.get(int(id)).delete_me() resp = api_resp(0, "info", "Product: " + str(id) + " deleted") return Response(json.dumps(resp), status=200, content_type='application/json')
def payment_check(id): if not current_user.is_mod: raise UserNotPermission(str(current_user.nick)) pay = Payments.query.get(int(id)) if pay is None: raise ProductException(str(id), "Payment of product not found") Payments.query.get(int(id)).delete_me() resp = api_resp(0, "info", "Payment: " + str(id) + " deleted") 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 delete_logged_user(): user_id = current_user.id if current_user.first_name == 'Foo': current_user.delete_me() else: token = random_string() current_user.set_token(token) subject = "Confirma para eliminar tu cuenta" link = request.host_url + 'user/' + str(user_id) + '/delete?token=' + token text = "Necesitamos que confirmes para eliminar tu cuenta, link: " + link html = "<p>Necesitamos que confirmes para eliminar tu cuenta</p>" \ "<h3> Link para eliminar: <a href='" + link + "'>Eliminar</a>!</h3><br />Se borraran todos tu datos y " \ "productos, intercambios y demás objetos asociados" send_mail(current_user.mail, current_user.first_name + " " + current_user.last_name, subject, text, html) resp = api_resp(0, "info", "User: "******" ready to deleted (mail)") 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 trade_close(id): trade = Trades.query.get(int(id)) if trade is None: raise TradeException(str(id)) if trade.user_sell != current_user.id: raise UserNotPermission( str(id), "Tis user (" + str(current_user.nick) + ") is not related with this trade") Trades.delete_id(id) resp = api_resp(0, "info", "Success delete of trade " + '(' + str(id) + ')') 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 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')