def con(): if 'id' in session and session['id'] > 0: try: join_room(session['id']) emit('connect_' + str(session['id']), broadcast=True) except Exception as e: logger.error("ERROR ON CONNECT - " + str(e))
def joinRoom(data): try: session['id'] = data join_room(session['id']) emit('connect_' + str(session['id']), broadcast=True) except Exception as e: logger.error("ERROR ON LOGIN - " + str(e))
def get_profile_pic_and_username_by_id(): if not 'id' in session or session['id'] < 0: return redirect("http://0.0.0.0:5000/#/redirection", code=302) try: cmd = "WITH matches_id AS (SELECT to_id AS match_id from matches WHERE from_id = %s UNION SELECT from_id AS match_id from matches WHERE to_id = %s), \ cmessages AS (SELECT to_id, count(id) AS count FROM messages WHERE to_id = %s AND NOT (from_id IN (SELECT hidden_ids.id FROM get_hidden(%s) AS hidden_ids)) AND \ EXISTS (SELECT * FROM matches_id WHERE match_id = from_id) \ AND seen = False GROUP BY to_id)\ SELECT users.id, users.username, encode(img, 'base64') AS img,(geoloc_lat is null) AS geoloc_empty, complete, mail, pictures.id AS pic_id, coalesce(cmessages.count, 0) AS msg_count FROM users \ RIGHT JOIN pictures ON users.id = pictures.user_id \ LEFT JOIN cmessages ON cmessages.to_id = pictures.user_id \ WHERE user_id = %s AND profile_pic = True \ GROUP BY users.id, username, pictures.img, pic_id, cmessages.count" res = json.loads( json_resp_to_request(cmd, [ session['id'], session['id'], session['id'], session['id'], session['id'] ])) if not res: cmd = "SELECT users.id, users.username FROM users WHERE id = %s" res = json.loads(json_resp_to_request(cmd, [ session['id'], ])) return Response(json.dumps(res[0]), status=200, mimetype='application/json') except Exception as e: raise logger.error("NAVBAR - " + str(e)) return Response(status=404)
def putindb(json_input): try: token = generate_confirmation_token(json_input['mail']) cryptedpassword = crypt_pwd(json_input['password']) cmd = "INSERT INTO users(timestamp, mail, password, username, name, first_name) VALUES(now(), %s, %s, %s, %s, %s);" args = [ json_input['mail'], cryptedpassword, json_input['username'], json_input['name'], json_input['first_name'] ] with psycopg2.connect("dbname='matcha' user=%s password=%s" % (os.environ['MATCHA_USER'], os.environ['MATCHA_PASSWORD'])) as conn: with conn.cursor() as cur: cur.execute(cmd, (args)) send_mail( json_input['mail'], "Bienvenue sur Matcha", render_template( 'mails/confirmation.html', user_name=json_input['username'], confirm_url="http://0.0.0.0:5000/confirm/%s" % (token))) conn.commit() return Response(status=200) except Exception as e: logger.error("ERROR ON PUTINDB - " + str(e)) return Response(status=404)
def get_messages(): if not 'id' in session or session['id'] < 0: return redirect("http://0.0.0.0:5000/#/redirection/", code=302) logger.debug("GET_MESSAGES " + str(session['id'])) if not 'offset' in session or not session['offset']: session['offset'] = 0 data = request.get_json() if 'offset' in data: session['offset'] = data['offset'] cmd = "SELECT * FROM (SELECT * from messages WHERE (from_id = %s AND to_id = %s) OR (from_id = %s AND to_id = %s) ORDER BY timestamp DESC limit %s offset %s) AS t ORDER BY timestamp" try: messages = json_resp_to_request(cmd, [ session['id'], data['contact'], data['contact'], session['id'], app.config['messages_step'], session['offset'] * app.config['messages_step'] ]) return Response(json.dumps({ "id": data['contact'], "content": messages }), status=200, mimetype='application/json') except Exception as e: msg = f"Failed to get messages for {session['id']} and {data['contact']}. " + str( e) logger.error(msg) return Response(status=204)
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 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 report(): json_input = request.get_json()['data'] if not 'id' in session or session['id'] < 0: return redirect("http://0.0.0.0:5000/#/redirection/", code=302) try: cmd = "INSERT INTO REPORTS(from_id, to_id, timestamp, fakeprofile, behaviour, scam, other, comment) VALUES(%s, %s, now(), %s, %s, %s, %s, %s);" (cmd, (session['id'], json_input['to_id'], json_input['charges']['fakeProfile'], json_input['charges']['behaviour'], json_input['charges']['scam'], json_input['charges']['other'], json_input['comment'])) return Response(status=200) except Exception as e: logger.error("ERROR ON REPORT - " + str(e)) return Response(status= 404)
def mail_to_reset_pwd(): json_input = request.get_json() try: if (check_mail_availability(json_input['mail'])): return "Your are not registered." token = generate_confirmation_token(json_input['mail']) send_mail(json_input['mail'], "Reset password", render_template('mails/resetpwd.html', confirm_url ="http://0.0.0.0:5000/#/resetpassword/%s"%(token))) return Response(status= 200) except Exception as e: logger.error("ERROR ON RESETPWD - " + str(e)) 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 leave(): try: with psycopg2.connect("dbname='matcha' user=%s password=%s" % (os.environ['MATCHA_USER'], os.environ['MATCHA_PASSWORD'])) as conn: with conn.cursor() as cur: cur.execute("UPDATE users SET online = false, last_connection = now() WHERE id = %s; ", (session['id'],)) conn.commit() cur.execute("SELECT to_char(last_connection, 'DD.MM.YY HH24:MI:SS') AS last_connection FROM users WHERE id = %s;", (session['id'],)) c = cur.fetchone() except Exception as e: logger.error("Logout not registered in users table - User :"******"last" : c[0]}, broadcast=True) session.pop('id')
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 createuser(): json_input = request.get_json() try: if (not check_mail_availability(json_input['mail'])): return Response(status=401) if (existing_username(json_input['username']) == True): return Response(status=401) else: return putindb(json_input) except Exception as e: logger.error("ERROR ON CREATEUSER - " + str(e)) return Response(status=404)
def get_tags(): if not 'id' in session or session['id'] < 0: return redirect("http://0.0.0.0:5000/#/redirection/", code=302) try: cmd = "SELECT id, tag AS label FROM legal_tags ORDER BY tag" all = json_resp_to_request(cmd, (True, )) return Response(json.dumps(all), status=200, mimetype='application/json') except Exception as e: logger.error("ALLTAGS - " + str(e)) return Response(status=404)
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 reset_password(): try: json_input = request.get_json() token = json_input["token"] email = confirm_token(token) cryptedpassword = hashlib.sha256() cryptedpassword.update(json_input['password'].encode('utf-8')) cmd = "UPDATE %s SET password='******' WHERE mail='%s';" %(app.config['users_table'], cryptedpassword.hexdigest(), email) send_cmd(cmd) return Response(status= 200) except: logger.error("ERROR ON RESET PASSWORD - " + str(e)) return Response(status= 404)
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_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 match(): criteria = request.get_json() if not 'id' in session or session['id'] < 0: return redirect("http://0.0.0.0:5000/#/redirection/", code=302) try : ptm = json.loads(get_profile_by_id(session['id'])) tags_list = json.loads(ptm['tags_list']) tags_list2 = '\', \''.join(tags_list) tags_list2 = "('" + tags_list2 + "')" cmd = "SELECT id, username, age || ' ans' as age, age_diff, total_score, 'A ' || round(cast(distance as decimal), 0) ||' km' as distance, tag_score, short_desc, popularity_mark, img FROM get_matches(CAST(%s AS INTEGER), CAST(%s AS INTEGER), CAST(%s AS INTEGER))" best_matches = json.loads(json_resp_to_request(cmd, [session['id'], int(app.config['users_results_nb_matches']), criteria['matchMore']])) return Response(json.dumps(str(json.dumps(best_matches))), status=200, mimetype='application/json') except Exception as e: logger.error("ERROR GETTING MATCH FOR " + str(session['id']) + ' ' + str(e)) return Response(status=404)
def update_mail(): json_input = request.get_json() try: if (not check_mail_availability(json_input['mail'])): return Response(status=401) else: token_mail = generate_confirmation_token(str(json_input['mail'])) token_id = generate_confirmation_token(str(session['id'])) send_mail( json_input['mail'], "Changement d'identifiants", render_template( 'mails/resetmail.html', confirm_url="http://0.0.0.0:5000/confirm/mail/%s/%s/" % (token_mail, token_id))) return Response(status=200) except Exception as e: logger.error("ERROR ON RESETMAIL - " + str(e)) return Response(status=404)
def logout(): if not 'id' in session or session['id'] < 0: return redirect("http://0.0.0.0:5000/#/redirection/", code=302) try: with psycopg2.connect("dbname='matcha' user=%s password=%s" % (os.environ['MATCHA_USER'], os.environ['MATCHA_PASSWORD'])) as conn: with conn.cursor() as cur: cur.execute( "UPDATE users SET online = false, last_connection = now() WHERE id = %s; ", (session['id'], )) conn.commit() except: logger.error("Logout not registered in users table - User :"******"LOGOUT + {session['id']}") session.pop('id') return Response(status=200)
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 settings_reset_password(): try: json_input = request.get_json() user_password = crypt_pwd(json_input["user_password"]) new_password = crypt_pwd(json_input["new_password"]) cmd = "SELECT password FROM users WHERE id = %s" args = [session['id']] try: data = json.loads((json_resp_to_request(cmd, args))) if data[0]['password'] == user_password: cmd = "UPDATE users SET password='******' WHERE id='%s';" %(new_password, session['id']) send_cmd(cmd) return Response(status= 200) else: return Response(status= 401) except Exception as e: logger.error("ERROR ON SETTINGS_RESET_PASSWORD - " + str(e)) return Response(status= 404) except Exception as e: logger.error("ERROR ON SETTINGS_RESET_PASSWORD - " + str(e)) return Response(status= 404)
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 ""
def get_users_list(): if not 'id' in session or session['id'] < 0: return redirect("http://0.0.0.0:5000/#/redirection/", code=302) cmd = "WITH messages AS (SELECT from_id, count(id) AS msg_nb FROM messages WHERE to_id = %s AND seen = false GROUP BY from_id)\ SELECT match_user_id, username, encode(img, 'base64') AS img, coalesce(messages.msg_nb, 0) AS msg_nb FROM (SELECT from_id as match_user_id FROM matches \ WHERE to_id = %s UNION SELECT to_id as match_user_id FROM matches WHERE from_id = %s) AS matches_ids \ LEFT JOIN users on match_user_id = users.id LEFT JOIN pictures on match_user_id = pictures.user_id \ LEFT JOIN messages ON messages.from_id = users.id \ WHERE (profile_pic = true OR img IS NULL) GROUP BY match_user_id, username, img, msg_nb" try: return Response(json.dumps( json.loads( json_resp_to_request( cmd, [session['id'], session['id'], session['id']]))), status=200, mimetype='application/json') except Exception as e: msg = f"Failed to get messages_users_list for {session['id']}. " + str( e) logger.error(msg) return Response(status=204)
def login(): json_input = request.get_json() logger.debug("LOGIN - input: " + str(json_input)) pwd = crypt_pwd(json_input['password']) cmd = "SELECT id, username FROM users WHERE mail = %s AND password = %s" args = [json_input['mail'], pwd] try: data = json.loads((json_resp_to_request(cmd, args))) if not data or data is None: return Response(status=401, mimetype='application/json') try: with psycopg2.connect("dbname='matcha' user=%s password=%s" % (os.environ['MATCHA_USER'], os.environ['MATCHA_PASSWORD'])) as conn: with conn.cursor() as cur: cur.execute( "UPDATE users SET last_connection = now() WHERE mail = %s;", (json_input['mail'], )) conn.commit() cur.execute( "UPDATE users SET online = true WHERE mail = %s;", (json_input['mail'], )) conn.commit() except: logger.error("Connection not registered in users table - User :"******"An error occured. Please retry later." response = Response(json.dumps(message), status=300, mimetype='application/json') return response
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)