def handle_dislike(data): try: check_blocks = json.loads(list_resp_to_request('SELECT check_blocks(%s, %s);', [session['id'], data]))[0] if check_blocks == False: send_cmd_with_args("SELECT fdislike(%s, %s, now()::timestamp);", ((session['id']), data)) emit('notif', room=data) except Exception as e: logger.error("DISLIKE NOT SENT - " + str(data) + ' ' + str(e))
def confirm_mail_update(token_mail, token_id): try: email = confirm_token(token_mail) user_id = confirm_token(token_id) cmd = "UPDATE users SET mail = %s WHERE id = %s;" send_cmd_with_args(cmd, (email, user_id)) return redirect("http://0.0.0.0:5000/#/updatedmail/success/", code=302) except Exception as e: logger.error("RESETMAIL - " + str(e)) return redirect("http://0.0.0.0:5000/#/updatedmail/failure/", code=304)
def remove_match(): if not 'id' in session or session['id'] < 0: return redirect("http://0.0.0.0:5000/#/redirection/", code=302) criteria = request.get_json() cmd = "INSERT INTO nogos(from_id, to_id, timestamp) VALUES(%s, %s, now());" try: send_cmd_with_args(cmd, [session['id'], criteria['user_id']]) return Response(status= 200) except: return Response(status= 404)
def set_seen(): if not 'id' in session or session['id'] < 0: return redirect("http://0.0.0.0:5000/#/redirection/", code=302) data = request.get_json() try: cmd = "UPDATE messages SET seen = true WHERE from_id = %s AND to_id = %s;" send_cmd_with_args(cmd, (data['contact'], session['id'])) return Response(status=200) except Exception as e: logger.error("Failed to set messages as seen") return Response(status=202)
def clean_user_db(): cmd = "SELECT id, timestamp from users WHERE active = false ORDER BY timestamp" try: unactive_ids = json.loads(json_resp_to_request(cmd, (False,))) ids_to_delete = [] for user in unactive_ids: if (datetime.now() - datetime.strptime(user['timestamp'], "%Y-%m-%dT%H:%M:%S.%f") >= timedelta(0, app.config['clear_users_timedelta'])): ids_to_delete.append(str(user['id'])) cmd = "DELETE FROM users WHERE id IN (" + (', '.join(ids_to_delete)) + ');' send_cmd_with_args(cmd, (True, )) except: logger.error('CLEAN_USER_DB error')
def validate(token_mail): try: email = confirm_token(token_mail) cmd = "UPDATE users SET active = True WHERE mail=%s;" send_cmd_with_args(cmd, [ email, ]) return redirect("http://0.0.0.0:5000/#/registration/success/", code=302) except Exception as e: logger.error("ERROR ON CONFIRM MAIL TOKEN - " + str(e)) return redirect("http://0.0.0.0:5000/#/registration/failure/", code=304)
def private_message(data): if 'id' in session and session['id'] > 0: cmd = "SELECT EXISTS (SELECT id from matches where from_id = %s and to_id = %s UNION SELECT id from matches WHERE from_id = %s AND to_id = %s);" try: res = json.loads(list_resp_to_request(cmd, (session['id'], data["to"], data["to"], session['id']))) if res and res[0] == True: emit("private_message", {"message": data["message"], "to": data["to"], "from": session["id"]}, room=data["to"]) emit("new_message", {"message": data["message"], "to": data["to"], "from": session["id"]}, room=data["to"]) emit("message_was_sent", {"message": data["message"], "to": data["to"], "from": session["id"]}, room=session['id']) send_cmd_with_args("SELECT msg(%s, %s, %s)", [session['id'], data['to'], data['message']]) emit("message_was_registered", {"content":data["message"]}, room=session['id']) except Exception as e: logger.error("PRIVATE_MESSAGE NOT SENT - " + str(data) + ' ' + str(e))
def search(): if not 'id' in session or session['id'] < 0: return redirect("http://0.0.0.0:5000/#/redirection/", code=302) criteria = request.get_json() if not criteria: return Response(json.dumps({'criteria': criteria, 'res': None}), status= 200, mimetype='application/json') if 'data' in criteria: criteria = json.loads(criteria['data']) ptm = json.loads(get_profile_by_id(session['id'])) if len(ptm) == 0: return Response(status= 404) if 'gender' in criteria and criteria['gender'] is not None: search_gender = criteria['gender']['genderCode'] else: try: cmd = "SELECT sex_orientation FROM users WHERE id = %s" search_gender = json.loads(list_resp_to_request(cmd, [session['id'], ]))[0] except: logger.error(f"SEARCH - Failed to get sex_orientation of {session['id']}") search_gender = 'M|F' try: cmd = "SELECT gender FROM users WHERE id = %s" user_gender = json.loads(list_resp_to_request(cmd, [session['id'], ]))[0] except Exception as e: msg = f"SEARCH - Failed to get gender of {session['id']} + {str(e)}" logger.error(msg) return Response(status= 401) if not criteria['geoloc']['city']: criteria["geoloc"] = json.dumps({"city": ptm["geoloc_city"], "distance" : 1000}) criteria["geoloc"] = json.loads(criteria["geoloc"]) geoloc = criteria["geoloc"] if str(geoloc["city"]).lower() == str(ptm["geoloc_city"]).lower(): coord = (ptm['geoloc_lat'], ptm['geoloc_long']) else: geolocator = Nominatim() location = geolocator.geocode(geoloc['city']) if not location: return Response(json.dumps({'crit': criteria, 'res': None}), status= 200, mimetype='application/json') coord = (location.latitude, location.longitude) cmd = "SELECT id, username, distance, age, age_diff, short_desc, popularity_score, gender, tag_score, img FROM search(%s, %s, %s, CAST( %s AS REAL), CAST(%s AS REAL), CAST(%s AS VARCHAR), CAST( %s AS VARCHAR), %s, %s, %s, CAST( %s AS integer[]), %s, %s, %s)" try: found_list = json.loads(json_resp_to_request(cmd, (session['id'], criteria['age']['max'], criteria['age']['min'], coord[0], coord[1], search_gender, user_gender, geoloc['distance'], criteria['popularity']['min'], criteria['popularity']['max'], criteria['tags'], app.config['users_results_nb'], (criteria['moreSearch']) * app.config['users_results_nb'], criteria['currentOrder']))) if len(found_list) <= 0: return Response(json.dumps({'crit': criteria, 'res': None}), status= 200, mimetype='application/json') send_cmd_with_args("INSERT INTO searchs(user_id, criteria, timestamp) VALUES(%s, %s, now());", [session['id'], json.dumps(criteria)]) res = {'crit': criteria, 'res': found_list} return Response(json.dumps(res), status= 200, mimetype='application/json') except Exception as e: msg = f"SEARCH - Failed to get results for search of {session['id']} : {str(criteria)} - {str(e)}" logger.error(msg) return Response(status= 404)
def get_notifications(): if not 'id' in session or session['id'] < 0: return redirect("http://0.0.0.0:5000/#/redirection/", code=302) try: cmd = "SELECT notifications.id, notifications.from_id, users.username, encode(img, 'base64') AS img, notifications.type, notifications.seen, notifications.timestamp \ from notifications INNER JOIN users on users.id = notifications.from_id \ LEFT JOIN pictures ON users.id = pictures.user_id \ WHERE to_id = %s AND (profile_pic = true OR img IS NULL) AND check_blocks(%s, notifications.from_id) = false \ ORDER BY timestamp DESC" notif = json.loads( json_resp_to_request(cmd, [session['id'], session['id']])) cmd = "UPDATE notifications SET seen = true WHERE to_id = %s;" send_cmd_with_args(cmd, [ session['id'], ]) expression = {} expression['L'] = ' a aimé votre profil' expression['D'] = ' n\'aime plus votre profil' expression['V'] = ' a vu votre profil' expression['M'] = 'Vous avez un match avec ' if len(notif) == 0: return Response(status=204, mimetype='application/json') for notification in notif: if notification["type"] == 'M': notification[ "text"] = 'Vous avez un match avec ' + notification[ 'username'] else: notification["text"] = notification['username'] + expression[ notification['type']] return Response(json.dumps(notif), status=200, mimetype='application/json') except Exception as e: logger.error(f"GET_NOTIFICATIONS - {str(e)}") return Response(status=404)
def handle_unblock(data): try: send_cmd_with_args('DELETE FROM blocks WHERE from_id = %s AND to_id = %s', [session['id'], data]) except Exception as e: logger.error("UNBLOCK NOT SENT - " + str(data) + ' ' + str(e))
def handle_block(data): try: send_cmd_with_args("SELECT fblocks(%s, %s, now()::timestamp);", ((session['id']), data)) except Exception as e: logger.error("BLOCK NOT SENT - " + str(data) + ' ' + str(e))