Untitled

mail@pastecode.io avatar
unknown
plain_text
11 days ago
3.7 kB
2
Indexable
Never
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
import random
import string

app = Flask(__name__)
CORS(app)

# Настройки базы данных
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///messenger.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

# Модель пользователя
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(50), nullable=False)

# Модель сообщения
class Message(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    sender_id = db.Column(db.String(50), nullable=False)
    receiver_id = db.Column(db.String(50), nullable=False)
    content = db.Column(db.String(200), nullable=False)

# Генерация уникального ID пользователя
def generate_unique_id():
    while True:
        user_id = ''.join(random.choices(string.ascii_letters + string.digits, k=6))
        if not User.query.filter_by(user_id=user_id).first():
            return user_id

# Маршрут для регистрации
@app.route('/register', methods=['POST'])
def register():
    user_id = generate_unique_id()
    password = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
    
    new_user = User(user_id=user_id, password=password)
    db.session.add(new_user)
    db.session.commit()
    
    return jsonify({'user_id': user_id, 'password': password})

# Маршрут для входа
@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    user_id = data['user_id']
    password = data['password']
    
    user = User.query.filter_by(user_id=user_id, password=password).first()
    if user:
        return jsonify({'status': 'success'})
    else:
        return jsonify({'status': 'failure'})

# Маршрут для отправки сообщения
@app.route('/send_message', methods=['POST'])
def send_message():
    data = request.get_json()
    sender_id = data['sender_id']
    receiver_id = data['receiver_id']
    content = data['content']
    
    new_message = Message(sender_id=sender_id, receiver_id=receiver_id, content=content)
    db.session.add(new_message)
    db.session.commit()
    
    return jsonify({'status': 'Message sent!'})

# Маршрут для получения сообщений
@app.route('/get_messages', methods=['POST'])
def get_messages():
    data = request.get_json()
    user_id = data['user_id']
    
    messages = Message.query.filter((Message.sender_id == user_id) | (Message.receiver_id == user_id)).all()
    chat_history = [{'sender_id': msg.sender_id, 'receiver_id': msg.receiver_id, 'content': msg.content} for msg in messages]
    
    return jsonify(chat_history)

# Маршрут для получения списка чатов
@app.route('/get_chats', methods=['POST'])
def get_chats():
    data = request.get_json()
    user_id = data['user_id']
    
    # Получение всех чатов пользователя
    messages = Message.query.filter((Message.sender_id == user_id) | (Message.receiver_id == user_id)).all()
    chat_users = set()
    for msg in messages:
        if msg.sender_id != user_id:
            chat_users.add(msg.sender_id)
        if msg.receiver_id != user_id:
            chat_users.add(msg.receiver_id)

    return jsonify(list(chat_users))

if __name__ == '__main__':
    db.create_all()
    app.run(host='0.0.0.0', port=8080)
Leave a Comment