Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

user_settings: Add support to bulk change user setting.

Sahil Batrae2075a34a8fe
diff --git a/zerver/actions/user_settings.py b/zerver/actions/user_settings.py
index 41c76c9c7ba..4c5db724e06 100644
--- a/zerver/actions/user_settings.py
+++ b/zerver/actions/user_settings.py
@@ -12,9 +12,9 @@ from confirmation.settings import STATUS_REVOKED, STATUS_USED
from zerver.actions.presence import do_update_user_presence
from zerver.lib.avatar import avatar_url
from zerver.lib.cache import (
+ bulk_flush_users,
cache_delete,
delete_user_profile_caches,
- flush_user_profile,
user_profile_by_api_key_cache_key,
)
from zerver.lib.create_user import get_display_email_address
@@ -35,6 +35,7 @@ from zerver.lib.utils import generate_api_key
from zerver.models import (
Draft,
EmailChangeStatus,
+ Realm,
RealmAuditLog,
ScheduledEmail,
ScheduledMessageNotificationEmail,
@@ -437,7 +438,6 @@ def update_scheduled_email_notifications_time(
)
[email protected](savepoint=False)
def do_change_user_setting(
user_profile: UserProfile,
setting_name: str,
@@ -445,8 +445,23 @@ def do_change_user_setting(
*,
acting_user: UserProfile | None,
) -> None:
- old_value = getattr(user_profile, setting_name)
+ bulk_change_user_setting(
+ user_profile.realm, [user_profile], setting_name, setting_value, acting_user=acting_user
+ )
+
+
[email protected](savepoint=False)
+def bulk_change_user_setting(
+ realm: Realm,
+ user_profiles: list[UserProfile],
+ setting_name: str,
+ setting_value: bool | str | int | Enum,
+ *,
+ acting_user: UserProfile | None,
+) -> None:
event_time = timezone_now()
+ audit_logs = []
+ old_values = {}
if isinstance(setting_value, Enum):
db_setting_value = setting_value.value
@@ -467,32 +482,43 @@ def do_change_user_setting(
else:
assert isinstance(db_setting_value, property_type)
assert isinstance(event_value, property_type)
- setattr(user_profile, setting_name, db_setting_value)
- # TODO: Move these database actions into a transaction.atomic block.
- user_profile.save(update_fields=[setting_name])
+ for user in user_profiles:
+ old_value = getattr(user, setting_name)
+ old_values[user.id] = old_value
+
+ setattr(user, setting_name, db_setting_value)
+
+ audit_logs.append(
+ RealmAuditLog(
+ realm=user.realm,
+ event_type=AuditLogEventType.USER_SETTING_CHANGED,
+ event_time=event_time,
+ acting_user=acting_user,
+ modified_user=user,
+ extra_data={
+ RealmAuditLog.OLD_VALUE: old_value,
+ RealmAuditLog.NEW_VALUE: db_setting_value,
+ "property": setting_name,
+ },
+ )
+ )
- RealmAuditLog.objects.create(
- realm=user_profile.realm,
- event_type=AuditLogEventType.USER_SETTING_CHANGED,
- event_time=event_time,
- acting_user=acting_user,
- modified_user=user_profile,
- extra_data={
- RealmAuditLog.OLD_VALUE: old_value,
- RealmAuditLog.NEW_VALUE: db_setting_value,
- "property": setting_name,
- },
- )
+ UserProfile.objects.bulk_update(user_profiles, [setting_name])
+ RealmAuditLog.objects.bulk_create(audit_logs)
# Disabling digest emails should clear a user's email queue
if setting_name == "enable_digest_emails" and not db_setting_value:
+ assert len(user_profiles) == 1
+ user_profile = user_profiles[0]
clear_scheduled_emails([user_profile.id], ScheduledEmail.DIGEST)
if setting_name == "email_notifications_batching_period_seconds":
- assert isinstance(old_value, int)
- assert isinstance(db_setting_value, int)
- update_scheduled_email_notifications_time(user_profile, old_value, db_setting_value)
+ for user_profile in user_profiles:
+ old_value = old_values[user_profile.id]
+ assert isinstance(old_value, int)
+ assert isinstance(db_setting_value, int)
+ update_scheduled_email_notifications_time(user_profile, old_value, db_setting_value)
event = {
"type": "user_settings",
@@ -505,11 +531,14 @@ def do_change_user_setting(
assert isinstance(db_setting_value, str)
event["language_name"] = get_language_name(db_setting_value)
- transaction.on_commit(lambda: flush_user_profile(sender=UserProfile, instance=user_profile))
+ transaction.on_commit(lambda: bulk_flush_users(user_profiles=user_profiles, realm=realm))
- send_event_on_commit(user_profile.realm, event, [user_profile.id])
+ user_ids = [u.id for u in user_profiles]
+ send_event_on_commit(realm, event, user_ids)
if setting_name == "allow_private_data_export":
+ assert len(user_profiles) == 1
+ user_profile = user_profiles[0]
realm_export_event = {
"type": "realm_export_consent",
"user_id": user_profile.id,
@@ -518,11 +547,13 @@ def do_change_user_setting(
send_event_on_commit(
user_profile.realm,
realm_export_event,
- list(user_profile.realm.get_human_admin_users().values_list("id", flat=True)),
+ list(realm.get_human_admin_users().values_list("id", flat=True)),
)
# Updates to the time zone display setting are sent to all users
if setting_name == "timezone":
+ assert len(user_profiles) == 1
+ user_profile = user_profiles[0]
payload = dict(
email=user_profile.email,
user_id=user_profile.id,
@@ -530,12 +561,15 @@ def do_change_user_setting(
)
timezone_event = dict(type="realm_user", op="update", person=payload)
send_event_on_commit(
- user_profile.realm,
+ realm,
timezone_event,
get_user_ids_who_can_access_user(user_profile),
)
if setting_name == "email_address_visibility":
+ assert len(user_profiles) == 1
+ user_profile = user_profiles[0]
+ old_value = old_values[user_profile.id]
send_delivery_email_update_events(
user_profile, old_value, user_profile.email_address_visibility
)
@@ -558,7 +592,7 @@ def do_change_user_setting(
# for them since all that's happened is that we stopped syncing changes,
# not deleted every previously synced draft - to do that use the DELETE
# endpoint.
- Draft.objects.filter(user_profile=user_profile).delete()
+ Draft.objects.filter(user_profile__in=user_profiles).delete()
if setting_name == "presence_enabled":
# The presence_enabled setting's primary function is to stop
@@ -569,6 +603,10 @@ def do_change_user_setting(
# user's current presence state as consistent with the new
# setting; not doing so can make it look like the settings
# change didn't have any effect.
+
+ assert len(user_profiles) == 1
+ user_profile = user_profiles[0]
+
if db_setting_value:
status = UserPresence.LEGACY_STATUS_ACTIVE_INT
presence_time = timezone_now()
diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.py
index cef674a94f8..f44c2df3dba 100644
--- a/zerver/lib/test_classes.py
+++ b/zerver/lib/test_classes.py
@@ -49,6 +49,7 @@ from corporate.models.plans import CustomerPlan
from zerver.actions.message_send import check_send_message, check_send_stream_message
from zerver.actions.realm_settings import do_change_realm_permission_group_setting
from zerver.actions.streams import bulk_add_subscriptions, bulk_remove_subscriptions
+from zerver.actions.user_settings import do_change_user_setting
from zerver.actions.users import do_change_user_role
from zerver.decorator import do_two_factor_login
from zerver.lib.cache import bounce_key_prefix_for_testing
@@ -2381,6 +2382,10 @@ class ZulipTestCase(ZulipTestCaseMixin, TestCase):
"""
do_change_user_role(user, role, acting_user=None)
+ def set_user_setting(self, user: UserProfile, setting_name: str, value: bool) -> None:
+ with self.captureOnCommitCallbacks(execute=True):
+ do_change_user_setting(user, setting_name, value, acting_user=None)
+
def get_row_pks_in_all_tables() -> Iterator[tuple[str, set[int]]]:
all_models = apps.get_models(include_auto_created=True)
diff --git a/zerver/tests/test_message_notification_emails.py b/zerver/tests/test_message_notification_emails.py
index 6d0dff0e3a0..8cc3d41d6f2 100644
--- a/zerver/tests/test_message_notification_emails.py
+++ b/zerver/tests/test_message_notification_emails.py
@@ -1161,16 +1161,12 @@ class TestMessageNotificationEmails(ZulipTestCase):
realm.save(update_fields=["message_content_allowed_in_email_notifications"])
# Emails have missed message content when message content is enabled by the user
- do_change_user_setting(
- user, "message_content_in_email_notifications", True, acting_user=None
- )
+ self.set_user_setting(user, "message_content_in_email_notifications", True)
mail.outbox = []
self._extra_context_in_missed_personal_messages(show_message_content=True)
# Emails don't have missed message content when message content is disabled by the user
- do_change_user_setting(
- user, "message_content_in_email_notifications", False, acting_user=None
- )
+ self.set_user_setting(user, "message_content_in_email_notifications", False)
mail.outbox = []
self._extra_context_in_missed_personal_messages(
show_message_content=False, message_content_disabled_by_user=True
@@ -1182,17 +1178,13 @@ class TestMessageNotificationEmails(ZulipTestCase):
realm.message_content_allowed_in_email_notifications = False
realm.save(update_fields=["message_content_allowed_in_email_notifications"])
- do_change_user_setting(
- user, "message_content_in_email_notifications", True, acting_user=None
- )
+ self.set_user_setting(user, "message_content_in_email_notifications", True)
mail.outbox = []
self._extra_context_in_missed_personal_messages(
show_message_content=False, message_content_disabled_by_realm=True
)
- do_change_user_setting(
- user, "message_content_in_email_notifications", False, acting_user=None
- )
+ self.set_user_setting(user, "message_content_in_email_notifications", False)
mail.outbox = []
self._extra_context_in_missed_personal_messages(
show_message_content=False,
diff --git a/zerver/tests/test_zcommand.py b/zerver/tests/test_zcommand.py
index 020c35561c5..84607d3dd47 100644
--- a/zerver/tests/test_zcommand.py
+++ b/zerver/tests/test_zcommand.py
@@ -32,6 +32,7 @@ class ZcommandTest(ZulipTestCase):
response_dict = self.assert_json_success(result)
self.assertIn("Changed to dark theme", response_dict["msg"])
+ self.login("hamlet")
result = self.client_post("/json/zcommand", payload)
response_dict = self.assert_json_success(result)
self.assertIn("still in dark theme", response_dict["msg"])
@@ -47,6 +48,7 @@ class ZcommandTest(ZulipTestCase):
response_dict = self.assert_json_success(result)
self.assertIn("Changed to light theme", response_dict["msg"])
+ self.login("hamlet")
result = self.client_post("/json/zcommand", payload)
response_dict = self.assert_json_success(result)
self.assertIn("still in light theme", response_dict["msg"])
@@ -62,6 +64,7 @@ class ZcommandTest(ZulipTestCase):
self.assert_json_success(result)
self.assert_in_response("Changed to fluid-width mode!", result)
+ self.login("hamlet")
result = self.client_post("/json/zcommand", payload)
self.assert_json_success(result)
self.assert_in_response("You are still in fluid width mode", result)
@@ -77,6 +80,7 @@ class ZcommandTest(ZulipTestCase):
self.assert_json_success(result)
self.assert_in_response("Changed to fixed-width mode!", result)
+ self.login("hamlet")
result = self.client_post("/json/zcommand", payload)
self.assert_json_success(result)
self.assert_in_response("You are still in fixed width mode", result)