Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
message_edit: Refactor message edit code.
Sahil Batra37f2c5bc788d
diff --git a/zerver/actions/message_edit.py b/zerver/actions/message_edit.pyindex 0699af0e087..ed0e97b9b18 100644--- a/zerver/actions/message_edit.py+++ b/zerver/actions/message_edit.py@@ -67,7 +67,7 @@ from zerver.lib.topic import (update_edit_history,update_messages_for_topic_edit,)-from zerver.lib.types import EditHistoryEvent+from zerver.lib.types import DirectMessageEditRequest, EditHistoryEvent, StreamMessageEditRequestfrom zerver.lib.url_encoding import near_stream_message_urlfrom zerver.lib.user_message import bulk_insert_all_umsfrom zerver.lib.user_topics import get_users_with_user_topic_visibility_policy@@ -160,26 +160,13 @@ def validate_user_can_edit_message(def maybe_send_resolve_topic_notifications(*,user_profile: UserProfile,- stream: Stream,- old_topic_name: str,- new_topic_name: str,+ message_edit_request: StreamMessageEditRequest,changed_messages: QuerySet[Message],- pre_truncation_new_topic_name: str,) -> tuple[int | None, bool]:"""Returns resolved_topic_message_id if resolve topic notifications were in fact sent."""# Note that topics will have already been stripped in check_update_message.- resolved_prefix_len = len(RESOLVED_TOPIC_PREFIX)- topic_resolved: bool = (- new_topic_name.startswith(RESOLVED_TOPIC_PREFIX)- and not old_topic_name.startswith(RESOLVED_TOPIC_PREFIX)- and pre_truncation_new_topic_name[resolved_prefix_len:] == old_topic_name- )- topic_unresolved: bool = (- old_topic_name.startswith(RESOLVED_TOPIC_PREFIX)- and not new_topic_name.startswith(RESOLVED_TOPIC_PREFIX)- and old_topic_name.lstrip(RESOLVED_TOPIC_PREFIX) == new_topic_name- )-+ topic_resolved = message_edit_request.topic_resolved+ topic_unresolved = message_edit_request.topic_unresolvedif not topic_resolved and not topic_unresolved:# If there's some other weird topic that does not toggle the# state of "topic starts with RESOLVED_TOPIC_PREFIX", we do@@ -196,13 +183,16 @@ def maybe_send_resolve_topic_notifications(# not a bug with the "resolve topics" feature.return None, False+ stream = message_edit_request.orig_stream# Sometimes a user might accidentally resolve a topic, and then# have to undo the action. We don't want to spam "resolved",# "unresolved" messages one after another in such a situation.# For that reason, we apply a short grace period during which# such an undo action will just delete the previous notification# message instead.- if maybe_delete_previous_resolve_topic_notification(user_profile, stream, new_topic_name):+ if maybe_delete_previous_resolve_topic_notification(+ user_profile, stream, message_edit_request.target_topic_name+ ):return None, True# Compute the users who either sent or reacted to messages that@@ -226,7 +216,7 @@ def maybe_send_resolve_topic_notifications(resolved_topic_message_id = internal_send_stream_message(sender,stream,- new_topic_name,+ message_edit_request.target_topic_name,notification_string.format(user=user_mention,),@@ -262,23 +252,21 @@ def maybe_delete_previous_resolve_topic_notification(def send_message_moved_breadcrumbs(target_message: Message,user_profile: UserProfile,- old_stream: Stream,- old_topic_name: str,+ message_edit_request: StreamMessageEditRequest,old_thread_notification_string: StrPromise | None,- new_stream: Stream,- new_topic_name: str | None,new_thread_notification_string: StrPromise | None,changed_messages_count: int,) -> None:# Since moving content between streams is highly disruptive,# it's worth adding a couple tombstone messages showing what# happened.+ old_stream = message_edit_request.orig_streamsender = get_system_bot(settings.NOTIFICATION_BOT, old_stream.realm_id)- if new_topic_name is None:- new_topic_name = old_topic_name-user_mention = silent_mention_syntax_for_user(user_profile)+ old_topic_name = message_edit_request.orig_topic_name+ new_stream = message_edit_request.target_stream+ new_topic_name = message_edit_request.target_topic_nameold_topic_link = f"#**{old_stream.name}>{old_topic_name}**"new_topic_link = f"#**{new_stream.name}>{new_topic_name}**"message = {@@ -534,12 +522,9 @@ def update_message_content(def do_update_message(user_profile: UserProfile,target_message: Message,- new_stream: Stream | None,- topic_name: str | None,- propagate_mode: str | None,+ message_edit_request: StreamMessageEditRequest | DirectMessageEditRequest,send_notification_to_old_thread: bool,send_notification_to_new_thread: bool,- content: str | None,rendering_result: MessageRenderingResult | None,prior_mention_user_ids: set[int],mention_data: MentionData | None = None,@@ -547,15 +532,17 @@ def do_update_message("""The main function for message editing. A message edit event canmodify:- * the message's content (in which case the caller will have- set both content and rendered_content),- * the topic, in which case the caller will have set topic_name+ * the message's content (in which case the caller will have set+ both content and rendered_content in message_edit_request object),+ * the topic, in which case the caller will have set target_topic_name+ field with the new topic name in message_edit_request object* or both message's content and the topic* or stream and/or topic, in which case the caller will have set- new_stream and/or topic_name.+ target_stream and/or target_topic_name to their new values in+ message_edit_request object.- With topic edits, propagate_mode determines whether other message- also have their topics edited.+ With topic edits, propagate_mode field in message_edit_request+ determines whether other message also have their topics edited."""timestamp = timezone_now()target_message.last_edit_time = timestamp@@ -576,13 +563,6 @@ def do_update_message(realm = user_profile.realmattachment_reference_change = AttachmentChangeResult(False, [])- stream_being_edited = None- if target_message.is_stream_message():- stream_id = target_message.recipient.type_id- stream_being_edited = get_stream_by_id_in_realm(stream_id, realm)- event["stream_name"] = stream_being_edited.name- event["stream_id"] = stream_being_edited.id-ums = UserMessage.objects.filter(message=target_message.id)def user_info(um: UserMessage) -> dict[str, Any]:@@ -591,20 +571,15 @@ def do_update_message("flags": um.flags_list(),}- if target_message.is_stream_message():- if topic_name is not None:- new_topic_name = topic_name- else:- new_topic_name = target_message.topic_name()-+ if isinstance(message_edit_request, StreamMessageEditRequest):stream_topic: StreamTopicTarget | None = StreamTopicTarget(- stream_id=stream_id,- topic_name=new_topic_name,+ stream_id=message_edit_request.orig_stream.id,+ topic_name=message_edit_request.target_topic_name,)else:stream_topic = None- if content is not None:+ if message_edit_request.is_content_edited:assert rendering_result is not None# mention_data is required if there's a content edit.@@ -613,7 +588,7 @@ def do_update_message(update_message_content(user_profile,target_message,- content,+ message_edit_request.content,rendering_result,prior_mention_user_ids,mention_data,@@ -629,7 +604,7 @@ def do_update_message()target_message.has_attachment = attachment_reference_change.did_attachment_change- if not target_message.is_stream_message():+ if isinstance(message_edit_request, DirectMessageEditRequest):update_edit_history(target_message, timestamp, edit_history_event)# This does message.save(update_fields=[...])@@ -644,17 +619,21 @@ def do_update_message(changed_messages_count, attachment_reference_change.detached_attachments)- if topic_name is not None or new_stream is not None:- assert propagate_mode is not None- orig_topic_name = target_message.topic_name()- event["propagate_mode"] = propagate_mode+ assert isinstance(message_edit_request, StreamMessageEditRequest)++ stream_being_edited = message_edit_request.orig_stream+ orig_topic_name = message_edit_request.orig_topic_name++ event["stream_name"] = stream_being_edited.name+ event["stream_id"] = stream_being_edited.id++ if message_edit_request.is_message_moved:+ event["propagate_mode"] = message_edit_request.propagate_modeusers_losing_access = UserProfile.objects.none()user_ids_gaining_usermessages: list[int] = []- if new_stream is not None:- assert content is None- assert target_message.is_stream_message()- assert stream_being_edited is not None+ if message_edit_request.is_stream_edited:+ new_stream = message_edit_request.target_streamedit_history_event["prev_stream"] = stream_being_edited.idedit_history_event["stream"] = new_stream.id@@ -663,7 +642,7 @@ def do_update_message(target_message.recipient_id = new_stream.recipient_idevent["new_stream_id"] = new_stream.id- event["propagate_mode"] = propagate_mode+ event["propagate_mode"] = message_edit_request.propagate_mode# When messages are moved from one stream to another, some# users may lose access to those messages, including guest@@ -679,7 +658,7 @@ def do_update_message(old_stream_all_users = UserProfile.objects.filter(id__in=Subscription.objects.filter(recipient__type=Recipient.STREAM,- recipient__type_id=stream_id,+ recipient__type_id=stream_being_edited.id,).values_list("user_profile_id")).only("id")@@ -722,12 +701,8 @@ def do_update_message(# modify the original set of UserMessage objects queried.unmodified_user_messages = ums- # We save the full topic name so that checks that require comparison- # between the original topic and the topic name passed into this function- # will not be affected by the potential truncation of topic_name below.- pre_truncation_topic_name = topic_name- if topic_name is not None:- topic_name = truncate_topic(topic_name)+ if message_edit_request.is_topic_edited:+ topic_name = message_edit_request.target_topic_nametarget_message.set_topic_name(topic_name)# These fields have legacy field names.@@ -744,12 +719,9 @@ def do_update_message(## We need to calculate 'target_topic_has_messages' here,# as we are moving the messages in the next step.- if topic_name is not None or new_stream is not None:- assert stream_being_edited is not None- assert orig_topic_name is not None-- target_stream: Stream = new_stream if new_stream is not None else stream_being_edited- target_topic_name: str = topic_name if topic_name is not None else orig_topic_name+ if message_edit_request.is_message_moved:+ target_stream = message_edit_request.target_stream+ target_topic_name = message_edit_request.target_topic_nameassert target_stream.recipient_id is not Nonetarget_topic_has_messages = messages_for_topic(@@ -762,30 +734,23 @@ def do_update_message(save_changes_for_propagation_mode = lambda: Message.objects.filter(id=target_message.id).select_related(*Message.DEFAULT_SELECT_RELATED)- if propagate_mode in ["change_later", "change_all"]:- assert topic_name is not None or new_stream is not None- assert stream_being_edited is not None-+ if message_edit_request.propagate_mode in ["change_later", "change_all"]:# Other messages should only get topic/stream fields in their edit history.topic_only_edit_history_event: EditHistoryEvent = {"user_id": edit_history_event["user_id"],"timestamp": edit_history_event["timestamp"],}- if topic_name is not None:+ if message_edit_request.is_topic_edited:topic_only_edit_history_event["prev_topic"] = edit_history_event["prev_topic"]topic_only_edit_history_event["topic"] = edit_history_event["topic"]- if new_stream is not None:+ if message_edit_request.is_stream_edited:topic_only_edit_history_event["prev_stream"] = edit_history_event["prev_stream"]topic_only_edit_history_event["stream"] = edit_history_event["stream"]later_messages, save_changes_for_propagation_mode = update_messages_for_topic_edit(acting_user=user_profile,edited_message=target_message,- propagate_mode=propagate_mode,- orig_topic_name=orig_topic_name,- topic_name=topic_name,- new_stream=new_stream,- old_stream=stream_being_edited,+ message_edit_request=message_edit_request,edit_history_event=topic_only_edit_history_event,last_edit_time=timestamp,)@@ -793,9 +758,7 @@ def do_update_message(changed_message_ids = list(changed_messages.values_list("id", flat=True))changed_messages_count = len(changed_message_ids)- if new_stream is not None:- assert stream_being_edited is not None-+ if message_edit_request.is_stream_edited:# The fact that the user didn't have a UserMessage# originally means we can infer that the user was not# mentioned in the original message (even if mention@@ -833,7 +796,7 @@ def do_update_message(# Reset the Attachment.is_*_public caches for all messages# moved to another stream with different access permissions.- if new_stream.invite_only != stream_being_edited.invite_only:+ if message_edit_request.target_stream.invite_only != stream_being_edited.invite_only:Attachment.objects.filter(messages__in=changed_messages.values("id")).update(is_realm_public=None,)@@ -841,7 +804,7 @@ def do_update_message(is_realm_public=None,)- if new_stream.is_web_public != stream_being_edited.is_web_public:+ if message_edit_request.target_stream.is_web_public != stream_being_edited.is_web_public:Attachment.objects.filter(messages__in=changed_messages.values("id")).update(is_web_public=None,)@@ -873,9 +836,9 @@ def do_update_message(# newly sent messages anyway) and having magical live-updates# where possible.users_to_be_notified = list(map(user_info, unmodified_user_messages))- if stream_being_edited is not None and stream_being_edited.is_history_public_to_subscribers():+ if stream_being_edited.is_history_public_to_subscribers():subscriptions = get_active_subscriptions_for_stream_id(- stream_id, include_deactivated_users=False+ message_edit_request.target_stream.id, include_deactivated_users=False)# We exclude long-term idle users, since they by# definition have no active clients.@@ -888,7 +851,7 @@ def do_update_message(user_profile_id__in=[um.user_profile_id for um in unmodified_user_messages])- if new_stream is not None:+ if message_edit_request.is_stream_edited:subscriptions = subscriptions.exclude(user_profile__in=users_losing_access)# TODO: Guest users don't see the new moved topic@@ -920,10 +883,8 @@ def do_update_message(# whether we've moved the entire topic, or just part of it. We# make that determination here.moved_all_visible_messages = False- if topic_name is not None or new_stream is not None:- assert stream_being_edited is not None-- if propagate_mode == "change_all":+ if message_edit_request.is_message_moved:+ if message_edit_request.propagate_mode == "change_all":moved_all_visible_messages = Trueelse:# With other propagate modes, if the user in fact moved@@ -959,10 +920,6 @@ def do_update_message(## This rule corresponds to checking moved_all_visible_messages.if moved_all_visible_messages:- assert stream_being_edited is not None- assert target_stream is not None- assert target_topic_name is not None-stream_inaccessible_to_user_profiles: list[UserProfile] = []orig_topic_user_profile_to_visibility_policy: dict[UserProfile, int] = {}target_topic_user_profile_to_visibility_policy: dict[UserProfile, int] = {}@@ -970,7 +927,10 @@ def do_update_message(for user_topic in get_users_with_user_topic_visibility_policy(stream_being_edited.id, orig_topic_name):- if new_stream is not None and user_topic.user_profile_id in user_ids_losing_access:+ if (+ message_edit_request.is_stream_edited+ and user_topic.user_profile_id in user_ids_losing_access+ ):stream_inaccessible_to_user_profiles.append(user_topic.user_profile)else:orig_topic_user_profile_to_visibility_policy[user_topic.user_profile] = (@@ -1097,21 +1057,20 @@ def do_update_message(resolved_topic_message_id = Noneresolved_topic_message_deleted = False- if topic_name is not None and content is None and new_stream is None:- assert stream_being_edited is not None- assert pre_truncation_topic_name is not None+ if (+ message_edit_request.is_topic_edited+ and not message_edit_request.is_content_edited+ and not message_edit_request.is_stream_edited+ ):resolved_topic_message_id, resolved_topic_message_deleted = (maybe_send_resolve_topic_notifications(user_profile=user_profile,- stream=stream_being_edited,- old_topic_name=orig_topic_name,- new_topic_name=topic_name,+ message_edit_request=message_edit_request,changed_messages=changed_messages,- pre_truncation_new_topic_name=pre_truncation_topic_name,))- if (new_stream is not None or topic_name is not None) and stream_being_edited is not None:+ if message_edit_request.is_message_moved:# Notify users that the topic was moved.old_thread_notification_string = Noneif send_notification_to_old_thread:@@ -1134,24 +1093,18 @@ def do_update_message(new_thread_notification_string = Noneif send_notification_to_new_thread and (# The stream changed -> eligible to notify.- new_stream is not None+ message_edit_request.is_stream_edited# The topic changed -> eligible to notify.or (- pre_truncation_topic_name is not None- and orig_topic_name.lstrip(RESOLVED_TOPIC_PREFIX)- != pre_truncation_topic_name.lstrip(RESOLVED_TOPIC_PREFIX)- )- or not (- # We have not completed our obligation to notify about a- # resolve topic, which happens if either we sent a notification or- # deleted a very recent previous notification.- resolved_topic_message_id or resolved_topic_message_deleted+ message_edit_request.is_topic_edited+ and not message_edit_request.topic_resolved+ and not message_edit_request.topic_unresolved)):- stream_for_new_topic = new_stream if new_stream is not None else stream_being_edited+ stream_for_new_topic = message_edit_request.target_streamassert stream_for_new_topic.recipient_id is not None- new_topic_name = topic_name if topic_name is not None else orig_topic_name+ new_topic_name = message_edit_request.target_topic_name# We calculate whether the user moved the entire topic# using that user's own permissions, which is important to@@ -1185,11 +1138,8 @@ def do_update_message(send_message_moved_breadcrumbs(target_message,user_profile,- stream_being_edited,- orig_topic_name,+ message_edit_request,old_thread_notification_string,- new_stream if new_stream is not None else stream_being_edited,- topic_name,new_thread_notification_string,changed_messages_count,)@@ -1291,6 +1241,84 @@ def check_time_limit_for_change_all_propagate_mode()+def get_message_edit_request_object(+ *,+ message: Message,+ user_profile: UserProfile,+ propagate_mode: str,+ stream_id: int | None = None,+ topic_name: str | None = None,+ content: str | None = None,+) -> StreamMessageEditRequest | DirectMessageEditRequest:+ if not message.is_stream_message():+ # We have already validated the code to have content+ # as not None.+ assert content is not None+ return DirectMessageEditRequest(+ content=content,+ orig_content=message.content,+ is_content_edited=True,+ )++ is_content_edited = False+ new_content = message.content+ if content is not None:+ is_content_edited = True+ if content.rstrip() == "":+ content = "(deleted)"+ new_content = normalize_body(content)++ is_topic_edited = False+ topic_resolved = False+ topic_unresolved = False+ old_topic_name = message.topic_name()+ target_topic_name = old_topic_name++ if topic_name is not None:+ is_topic_edited = True+ pre_truncation_target_topic_name = topic_name+ target_topic_name = truncate_topic(topic_name)++ resolved_prefix_len = len(RESOLVED_TOPIC_PREFIX)+ topic_resolved = (+ target_topic_name.startswith(RESOLVED_TOPIC_PREFIX)+ and not old_topic_name.startswith(RESOLVED_TOPIC_PREFIX)+ and pre_truncation_target_topic_name[resolved_prefix_len:] == old_topic_name+ )+ topic_unresolved = (+ old_topic_name.startswith(RESOLVED_TOPIC_PREFIX)+ and not target_topic_name.startswith(RESOLVED_TOPIC_PREFIX)+ and old_topic_name.lstrip(RESOLVED_TOPIC_PREFIX) == target_topic_name+ )++ orig_stream_id = message.recipient.type_id+ orig_stream = get_stream_by_id_in_realm(orig_stream_id, message.realm)++ is_stream_edited = False+ target_stream = orig_stream+ if stream_id is not None:+ target_stream = access_stream_by_id_for_message(+ user_profile, stream_id, require_active=True+ )[0]+ is_stream_edited = True++ return StreamMessageEditRequest(+ is_content_edited=is_content_edited,+ content=new_content,+ is_topic_edited=is_topic_edited,+ target_topic_name=target_topic_name,+ is_stream_edited=is_stream_edited,+ topic_resolved=topic_resolved,+ topic_unresolved=topic_unresolved,+ orig_content=message.content,+ orig_topic_name=old_topic_name,+ orig_stream=orig_stream,+ propagate_mode=propagate_mode,+ target_stream=target_stream,+ is_message_moved=is_stream_edited or is_topic_edited,+ )++@transaction.atomic(durable=True)def check_update_message(user_profile: UserProfile,@@ -1318,11 +1346,11 @@ def check_update_message(if content is not None:validate_user_can_edit_message(user_profile, message, edit_limit_buffer)- # The zerver/views/message_edit.py call point already strips this- # via OptionalTopic; so we can delete this line if we arrange a- # contract where future callers in the embedded bots system strip- # use OptionalTopic as well (or otherwise are guaranteed to strip input).if topic_name is not None:+ # The zerver/views/message_edit.py call point already strips this+ # via OptionalTopic; so we can delete this line if we arrange a+ # contract where future callers in the embedded bots system strip+ # use OptionalTopic as well (or otherwise are guaranteed to strip input).topic_name = topic_name.strip()topic_name = maybe_rename_general_chat_to_empty_topic(topic_name)if topic_name == message.topic_name():@@ -1330,37 +1358,47 @@ def check_update_message(validate_message_edit_payload(message, stream_id, topic_name, propagate_mode, content)- if topic_name is not None and not user_profile.can_move_messages_to_another_topic():- raise JsonableError(_("You don't have permission to edit this message"))+ message_edit_request = get_message_edit_request_object(+ message=message,+ user_profile=user_profile,+ propagate_mode=propagate_mode,+ stream_id=stream_id,+ topic_name=topic_name,+ content=content,+ )- # If there is a change to the topic, check that the user is allowed to- # edit it and that it has not been too long. If user is not admin or moderator,- # and the time limit for editing topics is passed, raise an error.if (- topic_name is not None- and user_profile.realm.move_messages_within_stream_limit_seconds is not None- and not user_profile.is_realm_admin- and not user_profile.is_moderator+ isinstance(message_edit_request, StreamMessageEditRequest)+ and message_edit_request.is_topic_edited):- deadline_seconds = (- user_profile.realm.move_messages_within_stream_limit_seconds + edit_limit_buffer- )- if (timezone_now() - message.date_sent) > timedelta(seconds=deadline_seconds):- raise JsonableError(_("The time limit for editing this message's topic has passed."))+ if not user_profile.can_move_messages_to_another_topic():+ raise JsonableError(_("You don't have permission to edit this message"))++ # If there is a change to the topic, check that the user is allowed to+ # edit it and that it has not been too long. If user is not admin or moderator,+ # and the time limit for editing topics is passed, raise an error.+ if (+ user_profile.realm.move_messages_within_stream_limit_seconds is not None+ and not user_profile.is_realm_admin+ and not user_profile.is_moderator+ ):+ deadline_seconds = (+ user_profile.realm.move_messages_within_stream_limit_seconds + edit_limit_buffer+ )+ if (timezone_now() - message.date_sent) > timedelta(seconds=deadline_seconds):+ raise JsonableError(+ _("The time limit for editing this message's topic has passed.")+ )rendering_result = Nonelinks_for_embed: set[str] = set()prior_mention_user_ids: set[int] = set()mention_data: MentionData | None = None- if content is not None:- if content.rstrip() == "":- content = "(deleted)"- content = normalize_body(content)-+ if message_edit_request.is_content_edited:mention_backend = MentionBackend(user_profile.realm_id)mention_data = MentionData(mention_backend=mention_backend,- content=content,+ content=message_edit_request.content,message_sender=message.sender,)prior_mention_user_ids = get_mentions_for_message_updates(message.id)@@ -1371,7 +1409,7 @@ def check_update_message(# Note: If rendering fails, the called code will raise a JsonableError.rendering_result = render_incoming_message(message,- content,+ message_edit_request.content,user_profile.realm,mention_data=mention_data,)@@ -1395,48 +1433,46 @@ def check_update_message(mentioned_group_ids = list(rendering_result.mentions_user_group_ids)check_user_group_mention_allowed(user_profile, mentioned_group_ids)- new_stream = None+ if isinstance(message_edit_request, StreamMessageEditRequest):+ if message_edit_request.is_stream_edited:+ assert message.is_stream_message()+ if not user_profile.can_move_messages_between_streams():+ raise JsonableError(_("You don't have permission to move this message"))- if stream_id is not None:- assert message.is_stream_message()- if not user_profile.can_move_messages_between_streams():- raise JsonableError(_("You don't have permission to move this message"))+ check_stream_access_based_on_can_send_message_group(+ user_profile, message_edit_request.target_stream+ )- new_stream = access_stream_by_id_for_message(user_profile, stream_id, require_active=True)[- 0- ]- check_stream_access_based_on_can_send_message_group(user_profile, new_stream)+ if (+ user_profile.realm.move_messages_between_streams_limit_seconds is not None+ and not user_profile.is_realm_admin+ and not user_profile.is_moderator+ ):+ deadline_seconds = (+ user_profile.realm.move_messages_between_streams_limit_seconds+ + edit_limit_buffer+ )+ if (timezone_now() - message.date_sent) > timedelta(seconds=deadline_seconds):+ raise JsonableError(+ _("The time limit for editing this message's channel has passed")+ )if (- user_profile.realm.move_messages_between_streams_limit_seconds is not None+ propagate_mode == "change_all"and not user_profile.is_realm_adminand not user_profile.is_moderator+ and message_edit_request.is_message_moved):- deadline_seconds = (- user_profile.realm.move_messages_between_streams_limit_seconds + edit_limit_buffer+ check_time_limit_for_change_all_propagate_mode(+ message, user_profile, topic_name, stream_id)- if (timezone_now() - message.date_sent) > timedelta(seconds=deadline_seconds):- raise JsonableError(- _("The time limit for editing this message's channel has passed")- )-- if (- propagate_mode == "change_all"- and not user_profile.is_realm_admin- and not user_profile.is_moderator- and (topic_name is not None or stream_id is not None)- ):- check_time_limit_for_change_all_propagate_mode(message, user_profile, topic_name, stream_id)updated_message_result = do_update_message(user_profile,message,- new_stream,- topic_name,- propagate_mode,+ message_edit_request,send_notification_to_old_thread,send_notification_to_new_thread,- content,rendering_result,prior_mention_user_ids,mention_data,@@ -1459,13 +1495,18 @@ def check_update_message(# cron job handle updating the old stream. User might still want# to interact with the old stream and keeping it placed in the same# position in the left sidebar might help user.- if stream_id is not None and new_stream is not None and not new_stream.is_recently_active:+ if (+ isinstance(message_edit_request, StreamMessageEditRequest)+ and message_edit_request.is_stream_edited+ and not message_edit_request.target_stream.is_recently_active+ ):date_days_ago = timezone_now() - timedelta(days=Stream.LAST_ACTIVITY_DAYS_BEFORE_FOR_ACTIVE)+ new_stream = message_edit_request.target_streamis_stream_active = Message.objects.filter(date_sent__gte=date_days_ago,recipient__type=Recipient.STREAM,realm=user_profile.realm,- recipient__type_id=stream_id,+ recipient__type_id=new_stream.id,).exists()if is_stream_active != new_stream.is_recently_active:diff --git a/zerver/lib/topic.py b/zerver/lib/topic.pyindex 3e0a9ec971d..e406b134069 100644--- a/zerver/lib/topic.py+++ b/zerver/lib/topic.py@@ -7,9 +7,9 @@ from django.db import connectionfrom django.db.models import F, Func, JSONField, Q, QuerySet, Subquery, TextField, Valuefrom django.db.models.functions import Cast-from zerver.lib.types import EditHistoryEvent+from zerver.lib.types import EditHistoryEvent, StreamMessageEditRequestfrom zerver.lib.utils import assert_is_not_none-from zerver.models import Message, Reaction, Stream, UserMessage, UserProfile+from zerver.models import Message, Reaction, UserMessage, UserProfile# Only use these constants for events.ORIG_TOPIC = "orig_subject"@@ -118,26 +118,23 @@ def update_edit_history(def update_messages_for_topic_edit(acting_user: UserProfile,edited_message: Message,- propagate_mode: str,- orig_topic_name: str,- topic_name: str | None,- new_stream: Stream | None,- old_stream: Stream,+ message_edit_request: StreamMessageEditRequest,edit_history_event: EditHistoryEvent,last_edit_time: datetime,) -> tuple[QuerySet[Message], Callable[[], QuerySet[Message]]]:# Uses index: zerver_message_realm_recipient_upper_subject+ old_stream = message_edit_request.orig_streammessages = Message.objects.filter(realm_id=old_stream.realm_id,recipient_id=assert_is_not_none(old_stream.recipient_id),- subject__iexact=orig_topic_name,+ subject__iexact=message_edit_request.orig_topic_name,)- if propagate_mode == "change_all":+ if message_edit_request.propagate_mode == "change_all":messages = messages.exclude(id=edited_message.id)- if propagate_mode == "change_later":+ if message_edit_request.propagate_mode == "change_later":messages = messages.filter(id__gt=edited_message.id)- if new_stream is not None:+ if message_edit_request.is_stream_edited:# If we're moving the messages between streams, only move# messages that the acting user can access, so that one cannot# gain access to messages through moving them.@@ -183,10 +180,10 @@ def update_messages_for_topic_edit(TextField(),),}- if new_stream is not None:- update_fields["recipient"] = new_stream.recipient- if topic_name is not None:- update_fields["subject"] = topic_name+ if message_edit_request.is_stream_edited:+ update_fields["recipient"] = message_edit_request.target_stream.recipient+ if message_edit_request.is_topic_edited:+ update_fields["subject"] = message_edit_request.target_topic_name# The update will cause the 'messages' query to no longer match# any rows; we capture the set of matching ids first, do thediff --git a/zerver/lib/types.py b/zerver/lib/types.pyindex 46768652316..2fc1f7ad69b 100644--- a/zerver/lib/types.py+++ b/zerver/lib/types.py@@ -2,7 +2,10 @@ from collections.abc import Callablefrom dataclasses import dataclass, fieldfrom datetime import datetimefrom enum import IntEnum-from typing import Any, TypeAlias, TypeVar+from typing import TYPE_CHECKING, Any, TypeAlias, TypeVar++if TYPE_CHECKING:+ from zerver.models import Streamfrom django_stubs_ext import StrPromisefrom typing_extensions import NotRequired, TypedDict@@ -358,3 +361,27 @@ class AnalyticsDataUploadLevel(IntEnum):BASIC = 1BILLING = 2ALL = 3+++@dataclass+class StreamMessageEditRequest:+ is_content_edited: bool+ is_topic_edited: bool+ is_stream_edited: bool+ is_message_moved: bool+ topic_resolved: bool+ topic_unresolved: bool+ content: str+ target_topic_name: str+ target_stream: "Stream"+ orig_content: str+ orig_topic_name: str+ orig_stream: "Stream"+ propagate_mode: str+++@dataclass+class DirectMessageEditRequest:+ content: str+ orig_content: str+ is_content_edited: booldiff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.pyindex 6021a27be19..0e9d04b3293 100644--- a/zerver/tests/test_events.py+++ b/zerver/tests/test_events.py@@ -51,7 +51,11 @@ from zerver.actions.invites import (do_revoke_user_invite,)from zerver.actions.message_delete import do_delete_messages-from zerver.actions.message_edit import do_update_embedded_data, do_update_message+from zerver.actions.message_edit import (+ do_update_embedded_data,+ do_update_message,+ get_message_edit_request_object,+)from zerver.actions.message_flags import do_update_message_flagsfrom zerver.actions.muted_users import do_mute_user, do_unmute_userfrom zerver.actions.onboarding_steps import do_mark_onboarding_step_as_read@@ -602,16 +606,21 @@ class NormalActionsTest(BaseAction):message_sender=self.example_user("cordelia"),)+ message_edit_request = get_message_edit_request_object(+ message=pm,+ user_profile=self.user_profile,+ propagate_mode="change_one",+ stream_id=None,+ topic_name=None,+ content=content,+ )with self.verify_action(state_change_expected=False) as events:do_update_message(self.user_profile,pm,- None,- None,- None,+ message_edit_request,False,False,- content,rendering_result,prior_mention_user_ids,mention_data,@@ -906,16 +915,21 @@ class NormalActionsTest(BaseAction):message_sender=iago,)+ message_edit_request = get_message_edit_request_object(+ message=message,+ user_profile=self.user_profile,+ propagate_mode="change_one",+ stream_id=None,+ topic_name=None,+ content=content,+ )with self.verify_action(state_change_expected=False) as events:do_update_message(self.user_profile,message,- None,- None,- None,+ message_edit_request,False,False,- content,rendering_result,prior_mention_user_ids,mention_data,@@ -934,17 +948,23 @@ class NormalActionsTest(BaseAction):topic_name = "new_topic"propagate_mode = "change_all"+ message_edit_request = get_message_edit_request_object(+ message=message,+ user_profile=self.user_profile,+ propagate_mode=propagate_mode,+ stream_id=None,+ topic_name=topic_name,+ content=None,+ )+with self.verify_action(state_change_expected=True) as events:do_update_message(self.user_profile,message,- None,- topic_name,- propagate_mode,+ message_edit_request,False,False,None,- None,prior_mention_user_ids,mention_data,)@@ -983,6 +1003,14 @@ class NormalActionsTest(BaseAction):propagate_mode = "change_all"prior_mention_user_ids = set()+ message_edit_request = get_message_edit_request_object(+ message=message,+ user_profile=self.user_profile,+ propagate_mode=propagate_mode,+ stream_id=stream.id,+ topic_name=None,+ content=None,+ )with self.verify_action(state_change_expected=True,# There are 3 events generated for this action@@ -993,13 +1021,10 @@ class NormalActionsTest(BaseAction):do_update_message(self.user_profile,message,- stream,- None,- propagate_mode,+ message_edit_request,True,True,None,- None,set(),None,)@@ -1022,6 +1047,14 @@ class NormalActionsTest(BaseAction):propagate_mode = "change_all"prior_mention_user_ids = set()+ message_edit_request = get_message_edit_request_object(+ message=message,+ user_profile=self.user_profile,+ propagate_mode="change_one",+ stream_id=stream.id,+ topic_name="final_topic",+ content=None,+ )with self.verify_action(state_change_expected=True,# Skip "update_message_flags" to exercise the code path@@ -1035,13 +1068,10 @@ class NormalActionsTest(BaseAction):do_update_message(self.user_profile,message,- stream,- "final_topic",- propagate_mode,+ message_edit_request,True,True,None,- None,set(),None,)diff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.pyindex 9371f2e292e..eba06196471 100644--- a/zerver/tests/test_message_fetch.py+++ b/zerver/tests/test_message_fetch.py@@ -14,7 +14,7 @@ from typing_extensions import overridefrom analytics.lib.counts import COUNT_STATSfrom analytics.models import RealmCount-from zerver.actions.message_edit import do_update_message+from zerver.actions.message_edit import do_update_message, get_message_edit_request_objectfrom zerver.actions.reactions import check_add_reactionfrom zerver.actions.realm_settings import do_set_realm_propertyfrom zerver.actions.uploads import do_claim_attachments@@ -4988,15 +4988,20 @@ class MessageHasKeywordsTest(ZulipTestCase):rendering_result = render_message_markdown(msg, content)mention_backend = MentionBackend(realm_id)mention_data = MentionData(mention_backend, content, msg.sender)+ message_edit_request = get_message_edit_request_object(+ message=msg,+ user_profile=hamlet,+ propagate_mode="change_one",+ stream_id=None,+ topic_name=None,+ content=content,+ )do_update_message(hamlet,msg,- None,- None,- "change_one",+ message_edit_request,False,False,- content,rendering_result,set(),mention_data=mention_data,diff --git a/zerver/tests/test_message_move_topic.py b/zerver/tests/test_message_move_topic.pyindex fcdeefabb09..f768d279590 100644--- a/zerver/tests/test_message_move_topic.py+++ b/zerver/tests/test_message_move_topic.py@@ -11,6 +11,7 @@ from zerver.actions.message_delete import do_delete_messagesfrom zerver.actions.message_edit import (check_update_message,do_update_message,+ get_message_edit_request_object,maybe_send_resolve_topic_notifications,)from zerver.actions.reactions import do_add_reaction@@ -19,6 +20,7 @@ from zerver.actions.user_topics import do_set_user_topic_visibility_policyfrom zerver.lib.message import truncate_topicfrom zerver.lib.test_classes import ZulipTestCase, get_topic_messagesfrom zerver.lib.topic import RESOLVED_TOPIC_PREFIX, messages_for_topic+from zerver.lib.types import StreamMessageEditRequestfrom zerver.lib.user_topics import (get_users_with_user_topic_visibility_policy,set_topic_visibility_policy,@@ -140,15 +142,20 @@ class MessageMoveTopicTest(ZulipTestCase):topic_name: str,users_to_be_notified: list[dict[str, Any]],) -> None:+ message_edit_request = get_message_edit_request_object(+ message=message,+ user_profile=user_profile,+ propagate_mode="change_later",+ stream_id=None,+ topic_name=topic_name,+ content=None,+ )do_update_message(user_profile=user_profile,target_message=message,- new_stream=None,- topic_name=topic_name,- propagate_mode="change_later",+ message_edit_request=message_edit_request,send_notification_to_old_thread=False,send_notification_to_new_thread=False,- content=None,rendering_result=None,prior_mention_user_ids=set(),mention_data=None,@@ -1742,13 +1749,19 @@ class MessageMoveTopicTest(ZulipTestCase):assert stream.recipient_id is not Nonechanged_messages = messages_for_topic(stream.realm_id, stream.recipient_id, original_topic)resolve_topic = RESOLVED_TOPIC_PREFIX + original_topic+ message_edit_request = get_message_edit_request_object(+ message=message,+ user_profile=admin_user,+ propagate_mode="change_all",+ stream_id=None,+ topic_name=resolve_topic,+ content=None,+ )+ assert isinstance(message_edit_request, StreamMessageEditRequest)maybe_send_resolve_topic_notifications(user_profile=admin_user,- stream=stream,- old_topic_name=original_topic,- new_topic_name=resolve_topic,+ message_edit_request=message_edit_request,changed_messages=changed_messages,- pre_truncation_new_topic_name=resolve_topic,)topic_messages = get_topic_messages(admin_user, stream, resolve_topic)