92 lines
2.2 KiB
Python
Raw Permalink Normal View History

2024-12-16 10:07:21 +01:00
from flask_login import current_user
from flask_socketio import join_room, leave_room
from app import hashids, socketio
from app.decorators import socketio_login_required
from app.models import User
@socketio.on('SUBSCRIBE User')
@socketio_login_required
def subscribe(user_hashid: str) -> dict:
if not isinstance(user_hashid, str):
2024-12-23 14:49:06 +01:00
return {
'code': 400,
'name': 'Bad Request',
'description': 'Invalid User ID.'
}
2024-12-16 10:07:21 +01:00
user_id = hashids.decode(user_hashid)
if not isinstance(user_id, int):
2024-12-23 14:49:06 +01:00
return {
'code': 400,
'name': 'Bad Request',
'description': 'Invalid User ID.'
}
2024-12-16 10:07:21 +01:00
user = User.query.get(user_id)
if user is None:
2024-12-23 14:49:06 +01:00
return {
'code': 404,
'name': 'Not Found',
'description': 'User not found.'
}
2024-12-16 10:07:21 +01:00
if not (
user == current_user
or current_user.is_administrator
):
2024-12-23 14:49:06 +01:00
return {
'code': 403,
'name': 'Forbidden',
'description': 'Not allowed to subscribe to this user.'
}
2024-12-16 10:07:21 +01:00
join_room(f'/users/{user.hashid}')
2024-12-23 14:49:06 +01:00
return {'code': 204, 'name': 'No Content'}
2024-12-16 10:07:21 +01:00
@socketio.on('UNSUBSCRIBE User')
@socketio_login_required
def unsubscribe(user_hashid: str) -> dict:
if not isinstance(user_hashid, str):
2024-12-23 14:49:06 +01:00
return {
'code': 400,
'name': 'Bad Request',
'description': 'Invalid User ID.'
}
2024-12-16 10:07:21 +01:00
user_id = hashids.decode(user_hashid)
if not isinstance(user_id, int):
2024-12-23 14:49:06 +01:00
return {
'code': 400,
'name': 'Bad Request',
'description': 'Invalid User ID.'
}
2024-12-16 10:07:21 +01:00
user = User.query.get(user_id)
if user is None:
2024-12-23 14:49:06 +01:00
return {
'code': 404,
'name': 'Not Found',
'description': 'User not found.'
}
2024-12-16 10:07:21 +01:00
if not (
user == current_user
or current_user.is_administrator
):
2024-12-23 14:49:06 +01:00
return {
'code': 403,
'name': 'Forbidden',
'description': 'Not allowed to unsubscribe from this user.'
}
2024-12-16 10:07:21 +01:00
leave_room(f'/users/{user.hashid}')
2024-12-23 14:49:06 +01:00
return {'code': 204, 'name': 'No Content'}