From 869d3188debf33f02d209d0d487a3869e3e0e1c3 Mon Sep 17 00:00:00 2001 From: DarkSlein Date: Sat, 24 May 2025 15:40:18 +0300 Subject: [PATCH] Added websocket unscription --- src/controllers/reservation_controller.py | 5 +++++ src/controllers/websocket_controller.py | 10 +++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/controllers/reservation_controller.py b/src/controllers/reservation_controller.py index fffb01e..5e456a0 100644 --- a/src/controllers/reservation_controller.py +++ b/src/controllers/reservation_controller.py @@ -18,6 +18,7 @@ def create_reservation(): reservation = Reservation(**request.json, creator=current_user) id = ReservationRepository.insert(reservation) notify_clients(reservation.date, reservation.room_id) + notify_clients(reservation.date) return jsonify({"message": "Reservation created successfully", "id": id}) @reservation_blueprint.route('/', methods=['DELETE']) @@ -29,8 +30,11 @@ def cancel_reservation(reservation_id): room_id = reservation["room_id"] date = reservation["date"] + result = ReservationRepository.delete(reservation_id) + notify_clients(date, room_id) + notify_clients(date) if not result or result.deleted_count == 0: return jsonify({"error": "Reservation not found"}), 404 @@ -45,6 +49,7 @@ def change_reservation(reservation_id): reservation = ReservationRepository.get_by_id(reservation_id) result = ReservationRepository.update(reservation_id, data) notify_clients(reservation["date"], reservation["room_id"]) + notify_clients(reservation["date"]) if not result or result.matched_count == 0: return jsonify({"error": "Reservation not found"}), 404 except: diff --git a/src/controllers/websocket_controller.py b/src/controllers/websocket_controller.py index dea7aa9..dd7f69d 100644 --- a/src/controllers/websocket_controller.py +++ b/src/controllers/websocket_controller.py @@ -1,5 +1,5 @@ from flask_jwt_extended import get_jwt_identity, jwt_required -from flask_socketio import emit, join_room +from flask_socketio import emit, join_room, leave_room from infra.server import socketio from repos.reservation_repo import ReservationRepository @@ -31,6 +31,14 @@ def handle_subscribe(data): reservations = ReservationRepository.list_all(filters) emit('reservations_update', reservations) +@socketio.on('unsubscribe_reservations') +def handle_unsubscribe(data): + date = data.get('date') + leave_room(date) + if 'room_id' in data: + room = f"{date}_{data['room_id']}" + leave_room(room) + def notify_clients(date, room_id=None): all_reservations = ReservationRepository.list_all({'date': date}) socketio.emit('reservations_update', all_reservations, room=date)