59 lines
2.1 KiB
Python
59 lines
2.1 KiB
Python
from datetime import timedelta
|
|
|
|
from django.utils import timezone
|
|
|
|
from communications.models import ChatUserSettings
|
|
|
|
|
|
def update_chat_notification_preferences(
|
|
settings: ChatUserSettings,
|
|
*,
|
|
preferences: dict,
|
|
) -> ChatUserSettings:
|
|
"""Apply validated preferences while preserving the legacy empty toggle."""
|
|
update_fields = set()
|
|
if not preferences:
|
|
settings.notification_mode = (
|
|
ChatUserSettings.NotificationMode.MENTIONS
|
|
if settings.effective_notification_mode()
|
|
== ChatUserSettings.NotificationMode.ALL
|
|
else ChatUserSettings.NotificationMode.ALL
|
|
)
|
|
settings.muted_until = None
|
|
update_fields.update({"notification_mode", "muted_until"})
|
|
else:
|
|
mode = preferences.get("notification_mode")
|
|
if mode is not None:
|
|
settings.notification_mode = mode
|
|
update_fields.add("notification_mode")
|
|
if mode == ChatUserSettings.NotificationMode.MUTED:
|
|
settings.muted_until = None
|
|
update_fields.add("muted_until")
|
|
|
|
if "mute_for_seconds" in preferences:
|
|
seconds = preferences["mute_for_seconds"]
|
|
settings.muted_until = (
|
|
timezone.now() + timedelta(seconds=seconds) if seconds else None
|
|
)
|
|
update_fields.add("muted_until")
|
|
|
|
if "muted_until" in preferences:
|
|
settings.muted_until = preferences["muted_until"]
|
|
update_fields.add("muted_until")
|
|
|
|
for field in (
|
|
"show_notification_preview",
|
|
"notification_sound_enabled",
|
|
):
|
|
if field in preferences:
|
|
setattr(settings, field, preferences[field])
|
|
update_fields.add(field)
|
|
|
|
settings.notifications_enabled = (
|
|
settings.notification_mode == ChatUserSettings.NotificationMode.ALL
|
|
and not (settings.muted_until and settings.muted_until > timezone.now())
|
|
)
|
|
update_fields.add("notifications_enabled")
|
|
settings.save(update_fields=sorted(update_fields))
|
|
return settings
|