def handle_like(data): try: check_blocks = json.loads(list_resp_to_request('SELECT check_blocks(%s, %s);', [session['id'], str(data['id'])]))[0] if check_blocks == False: match = json.loads(list_resp_to_request('SELECT flike(%s, %s, now()::timestamp);', [session['id'], str(data['id'])])) emit('notif', room=data['id']) if match and match[0] == True: emit('match', {"contact": data['username']}, room=session['id']) except Exception as e: logger.error("LIKE 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_profile_by_username(): input = request.get_json() if not 'id' in session or session['id'] < 0: return redirect("http://0.0.0.0:5000/#/redirection/", code=302) try: cmd = "SELECT id, username, name, first_name, online, to_char(last_connection, 'DD.MM.YY HH24:MI:SS') AS last_connection, score, gender, sex_orientation, birth_date, profession, geoloc_show, geoloc_lat, geoloc_long, geoloc_city, short_desc, long_desc FROM users WHERE username = %s AND active = True" profile = json.loads(json_resp_to_request(cmd, [ input['username'], ])) if len(profile) == 0: return Response(status=404) profile = profile[0] cmd = "SELECT legal_tags.id, tag AS label FROM legal_tags RIGHT JOIN users_tags ON legal_tags.id = users_tags.tag_id WHERE users_tags.user_id = %s" tags = json_resp_to_request(cmd, [ int(profile['id']), ]) profile['tags_list'] = str(tags) cmd = "SELECT id, profile_pic, encode(img, 'base64') AS img FROM pictures WHERE user_id = %s ORDER BY id" profile['pictures'] = json_resp_to_request(cmd, [ profile['id'], ]) profile['self'] = False profile['liked'] = False profile['likes'] = False if session['id'] == profile['id']: profile['self'] = True else: cmd = "SELECT type, to_id FROM likes WHERE from_id = %s AND to_id = %s ORDER BY timestamp DESC limit 1;" profile_liked = json.loads( list_resp_to_request(cmd, [session['id'], profile['id']])) if profile_liked and profile_liked[0] == 1: profile['liked'] = True profile_likes_you = json.loads( list_resp_to_request(cmd, [profile['id'], session['id']])) if profile_likes_you and profile_likes_you[0] == 1: profile['likes'] = True cmd = "SELECT EXISTS (SELECT id FROM blocks WHERE from_id = %s AND to_id = %s);" profile['blocked'] = json.loads( list_resp_to_request(cmd, [session['id'], profile['id']]))[0] cmd = "SELECT EXISTS (SELECT id FROM blocks WHERE from_id = %s AND to_id = %s);" profile['blocks'] = json.loads( list_resp_to_request(cmd, [profile['id'], session['id']]))[0] return Response(json.dumps(profile), status=200, mimetype='application/json') except Exception as e: message = "No profile found for " + str(input['username']) logger.error("GET_PROFILE_BY_USERNAME - " + str(e)) return Response(status=404)
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 get_forbidden_list(): try: cmd = "(SELECT DISTINCT to_id AS id FROM blocks WHERE from_id= %s) UNION (SELECT DISTINCT from_id AS id FROM blocks WHERE to_id= %s)" black_list = json.loads( list_resp_to_request(cmd, [session['id'], session['id']])) black_list.append(session['id']) return json.dumps({"success": 1, "content": black_list}) except Exception as e: msg = f"Failed to get avoid_list for {session['id']}. " + str(e) logger.info(msg) return json.dumps({"success": -1, "message": msg})
def get_matches_list(): try: cmd = "SELECT to_id FROM matches WHERE from_id= %s UNION SELECT from_id FROM matches WHERE to_id = %s;" return json.dumps({ "status": 200, "content": list_resp_to_request(cmd, [session['id'], session['id']]) }) except Exception as e: msg = f"Failed to get matches_list for {session['id']}. " + str(e) logger.info(msg) return json.dumps({"status": 500, "message": msg})
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 get_last_search(): if not 'id' in session or session['id'] < 0: return redirect("http://0.0.0.0:5000/#/redirection/", code=302) try: cmd = "SELECT criteria FROM searchs WHERE user_id = %s ORDER by timestamp DESC limit 1" crit = json.loads(list_resp_to_request(cmd, [session['id'],])) if not crit: return Response(status= 200) crit[0]['moreSearch'] = 0 return Response(json.dumps(crit[0]), status= 200, mimetype='application/json') except Exception as e: msg = f"LASTSEARCH - Failed to get last search - {str(e)}" logger.error(msg) return Response(status= 404)
def get_blacked_list(): try: cmd = "SELECT DISTINCT from_id FROM blocks WHERE to_id= %s" return json.dumps({ "status": 200, "content": list_resp_to_request(cmd, [ session['id'], ]) }) except Exception as e: msg = f"Failed to get blacked_list for {session['id']}. " + str(e) logger.info(msg) return json.dumps({"status": 204, "message": msg})
def get_notifications_count(): if not 'id' in session or session['id'] < 0: return redirect("http://0.0.0.0:5000/#/redirection/", code=302) try: cmd = "SELECT count(id) FROM notifications WHERE to_id = %s AND seen = false;" notif = json.loads(list_resp_to_request(cmd, [ session['id'], ])) if notif: return Response(json.dumps({"new": notif[0]}), status=200, mimetype='application/json') return Response(json.dumps({"new": 0}), status=200, mimetype='application/json') except Exception as e: logger.error(f"GET_NOTIFICATIONS COUNT - {str(e)}") return Response(status=404)
def get_list_to_avoid(): forbidden_list = json.loads(get_forbidden_list()) if forbidden_list['success'] <= 0: return json.dumps({ "success": -1, "message": forbidden_list["message"] }) cmd = "SELECT DISTINCT to_id FROM views WHERE from_id = %s AND age(now(), timestamp) < INTERVAL %s UNION SELECT DISTINCT to_id FROM messages WHERE from_id = %s AND age(now(), timestamp) < INTERVAL %s;" try: avoided_list = json.loads( list_resp_to_request(cmd, [ session['id'], app.config['user_delay'], session['id'], app.config['user_delay'] ])) except Exception as e: msg = f"GET_LIST_TO_AVOID - Failed to get list to avoid for {session['id']} - {str(e)}" logger.error(msg) avoided_list = [] forbidden_list['content'].extend(avoided_list) return json.dumps({"success": 1, "content": forbidden_list['content']})
def get_profile_by_id(user_id): try: cmd = "SELECT username, name, first_name, score, gender, sex_orientation, birth_date, profession, geoloc_lat, geoloc_long, geoloc_city, short_desc, long_desc FROM users WHERE id = %s" profile = json.loads(json_resp_to_request(cmd, [ user_id, ])) if len(profile) == 0: return "" profile = profile[0] cmd = "SELECT tag FROM legal_tags LEFT JOIN users_tags ON legal_tags.id = users_tags.tag_id WHERE users_tags.user_id = %s" tags = list_resp_to_request(cmd, [ user_id, ]) profile['tags_list'] = tags profile['self'] = False if session['id'] == user_id: profile['self'] = True return json.dumps(profile) except Exception as e: logger.error("GET_PROFILE _BY_ID - ") + str(e) return ""