Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
fetch_messages: Add support for empty topic names.
Prakhar Pratyush5d9beb3655db
diff --git a/api_docs/changelog.md b/api_docs/changelog.mdindex cac81014721..d526583c093 100644--- a/api_docs/changelog.md+++ b/api_docs/changelog.md@@ -40,6 +40,11 @@ format used by the Zulip server that they are interacting with.field replacing the empty string for channel messages:* `subject` field in the `message` event type+* [`GET /messages`](/api/get-messages),+ [`GET /messages/{message_id}`](/api/get-message): Added `allow_empty_topic_name`+ boolean parameter to decide whether the topic names in the fetched messages+ can be empty strings.+**Feature level 333*** [Message formatting](/api/message-formatting): System groups can nowdiff --git a/api_docs/construct-narrow.md b/api_docs/construct-narrow.mdindex 36f37ecf9cd..fd4f393cc6f 100644--- a/api_docs/construct-narrow.md+++ b/api_docs/construct-narrow.md@@ -51,8 +51,16 @@ important optimization when fetching messages in certain cases (e.g.,when [adding the `read` flag to a user's personalmessages](/api/update-message-flags-for-narrow)).+Note: When the value of `realm_empty_topic_display_name` found in+the [POST /register](/api/register-queue) response is used as an operand+for the `"topic"` operator in the narrow, it is interpreted+as an empty string.+## Changes+* Before Zulip 10.0 (feature level 334), empty string was not a valid+ topic name for channel messages.+* In Zulip 9.0 (feature level 271), support was added for a new filteroperator, `with`, which uses a [message ID](#message-ids) for itsoperand, and is designed for creating permanent links to topics.diff --git a/tools/linter_lib/custom_check.py b/tools/linter_lib/custom_check.pyindex 5bc3decb28f..bd914e3a7c3 100644--- a/tools/linter_lib/custom_check.py+++ b/tools/linter_lib/custom_check.py@@ -248,6 +248,11 @@ python_rules = RuleList("exclude_line": {("zerver/lib/message.py", "message__subject__iexact=message.topic_name(),"),("zerver/views/streams.py", "message__subject__iexact=topic_name,"),+ ("zerver/lib/message_cache.py", 'and obj["subject"] == ""'),+ (+ "zerver/lib/message_cache.py",+ 'obj["subject"] = Message.EMPTY_TOPIC_FALLBACK_NAME',+ ),},"include_only": {"zerver/data_import/",diff --git a/zerver/lib/message.py b/zerver/lib/message.pyindex ebfcbf4dd15..4d94de2b333 100644--- a/zerver/lib/message.py+++ b/zerver/lib/message.py@@ -212,6 +212,7 @@ def messages_for_ids(search_fields: dict[int, dict[str, str]],apply_markdown: bool,client_gravatar: bool,+ allow_empty_topic_name: bool,allow_edit_history: bool,user_profile: UserProfile | None,realm: Realm,@@ -257,6 +258,7 @@ def messages_for_ids(message_list,apply_markdown=apply_markdown,client_gravatar=client_gravatar,+ allow_empty_topic_name=allow_empty_topic_name,realm=realm,user_recipient_id=None if user_profile is None else user_profile.recipient_id,)diff --git a/zerver/lib/message_cache.py b/zerver/lib/message_cache.pyindex 7556ce5fc8b..93d683f964a 100644--- a/zerver/lib/message_cache.py+++ b/zerver/lib/message_cache.py@@ -164,6 +164,7 @@ class MessageDict:*,apply_markdown: bool,client_gravatar: bool,+ allow_empty_topic_name: bool,realm: Realm,user_recipient_id: int | None,) -> None:@@ -184,6 +185,7 @@ class MessageDict:obj,apply_markdown=apply_markdown,client_gravatar=client_gravatar,+ allow_empty_topic_name=allow_empty_topic_name,skip_copy=True,can_access_sender=can_access_sender,realm_host=realm.host,@@ -196,6 +198,7 @@ class MessageDict:*,apply_markdown: bool,client_gravatar: bool,+ allow_empty_topic_name: bool,keep_rendered_content: bool = False,skip_copy: bool = False,can_access_sender: bool,@@ -210,6 +213,15 @@ class MessageDict:if not skip_copy:obj = copy.copy(obj)+ # Compatibility code to change topic="" to topic=Message.EMPTY_TOPIC_FALLBACK_NAME+ # for older clients with no support for empty topic name.+ if (+ obj["recipient_type"] == Recipient.STREAM+ and obj["subject"] == ""+ and not allow_empty_topic_name+ ):+ obj["subject"] = Message.EMPTY_TOPIC_FALLBACK_NAME+if obj["sender_email_address_visibility"] != UserProfile.EMAIL_ADDRESS_VISIBILITY_EVERYONE:# If email address of the sender is only available to administrators,# clients cannot compute gravatars, so we force-set it to false.@@ -247,6 +259,11 @@ class MessageDict:for item in obj.get("edit_history", []):if "prev_rendered_content_version" in item:del item["prev_rendered_content_version"]+ if not allow_empty_topic_name:+ if "prev_topic" in item and item["prev_topic"] == "":+ item["prev_topic"] = Message.EMPTY_TOPIC_FALLBACK_NAME+ if "topic" in item and item["topic"] == "":+ item["topic"] = Message.EMPTY_TOPIC_FALLBACK_NAMEif not keep_rendered_content:del obj["rendered_content"]diff --git a/zerver/lib/narrow.py b/zerver/lib/narrow.pyindex 437914cfcee..a7698cc9675 100644--- a/zerver/lib/narrow.py+++ b/zerver/lib/narrow.py@@ -49,6 +49,7 @@ from zerver.lib.streams import (get_stream_by_narrow_operand_access_unchecked,get_web_public_streams_queryset,)+from zerver.lib.topic import maybe_rename_general_chat_to_empty_topicfrom zerver.lib.topic_sqlalchemy import (get_followed_topic_condition_sa,get_resolved_topic_condition_sa,@@ -900,6 +901,20 @@ def can_narrow_define_conversation(narrow: list[NarrowParameter]) -> bool:return False+def update_narrow_terms_containing_empty_topic_fallback_name(+ narrow: list[NarrowParameter] | None,+) -> list[NarrowParameter] | None:+ if narrow is None:+ return narrow++ for term in narrow:+ if term.operator == "topic":+ term.operand = maybe_rename_general_chat_to_empty_topic(term.operand)+ break++ return narrow++# This function implements the core logic of the `with` operator,# which is designed to support permanent links to a topic that# robustly function if the topic is moved.diff --git a/zerver/lib/outgoing_webhook.py b/zerver/lib/outgoing_webhook.pyindex 8ebd917e9a4..ea82cf729d5 100644--- a/zerver/lib/outgoing_webhook.py+++ b/zerver/lib/outgoing_webhook.py@@ -62,6 +62,7 @@ class GenericOutgoingWebhookService(OutgoingWebhookServiceInterface):event["message"],apply_markdown=False,client_gravatar=False,+ allow_empty_topic_name=True,keep_rendered_content=True,can_access_sender=check_user_can_access_all_users(self.user_profile)or check_can_access_user(diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex cbe2a314ab3..da5c14e3097 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -6808,6 +6808,22 @@ paths:items:type: integerexample: [1, 2, 3]+ - name: allow_empty_topic_name+ in: query+ description: |+ Whether the client supports processing the empty string as a topic in the+ topic name fields in the returned data, including in returned edit_history data.++ If `false`, the server will use the value of `realm_empty_topic_display_name`+ found in the [`POST /register`](/api/register-queue) response instead of empty string+ to represent the empty string topic in its response.++ **Changes**: New in Zulip 10.0 (feature level 334). Previously, the empty string+ was not a valid topic.+ schema:+ type: boolean+ default: false+ example: trueresponses:"200":description: Success.@@ -8140,6 +8156,22 @@ paths:type: booleandefault: trueexample: false+ - name: allow_empty_topic_name+ in: query+ description: |+ Whether the client supports processing the empty string as a topic in the+ topic name fields in the returned data, including in returned edit_history data.++ If `false`, the server will use the value of `realm_empty_topic_display_name`+ found in the [`POST /register`](/api/register-queue) response instead of empty string+ to represent the empty string topic in its response.++ **Changes**: New in Zulip 10.0 (feature level 334). Previously, the empty string+ was not a valid topic.+ schema:+ type: boolean+ default: false+ example: trueresponses:"200":description: Success.diff --git a/zerver/tests/test_message_dict.py b/zerver/tests/test_message_dict.pyindex 58924035cc8..e51ba5ca52f 100644--- a/zerver/tests/test_message_dict.py+++ b/zerver/tests/test_message_dict.py@@ -80,6 +80,7 @@ class MessageDictTest(ZulipTestCase):wide_dict,apply_markdown=apply_markdown,client_gravatar=client_gravatar,+ allow_empty_topic_name=True,can_access_sender=True,realm_host=get_realm("zulip").host,is_incoming_1_to_1=False,@@ -97,6 +98,7 @@ class MessageDictTest(ZulipTestCase):[unhydrated_dict],apply_markdown=apply_markdown,client_gravatar=client_gravatar,+ allow_empty_topic_name=True,realm=get_realm("zulip"),user_recipient_id=None,)@@ -180,6 +182,7 @@ class MessageDictTest(ZulipTestCase):objs,apply_markdown=False,client_gravatar=False,+ allow_empty_topic_name=True,realm=realm,user_recipient_id=None,)@@ -417,6 +420,7 @@ class MessageHydrationTest(ZulipTestCase):search_fields={},apply_markdown=True,client_gravatar=True,+ allow_empty_topic_name=True,allow_edit_history=False,user_profile=cordelia,realm=cordelia.realm,@@ -465,6 +469,7 @@ class MessageHydrationTest(ZulipTestCase):search_fields={},apply_markdown=True,client_gravatar=True,+ allow_empty_topic_name=True,allow_edit_history=False,user_profile=self.example_user("polonius"),realm=realm,@@ -510,6 +515,7 @@ class MessageHydrationTest(ZulipTestCase):search_fields={},apply_markdown=True,client_gravatar=True,+ allow_empty_topic_name=True,allow_edit_history=False,user_profile=cordelia,realm=cordelia.realm,@@ -555,6 +561,7 @@ class TestMessageForIdsDisplayRecipientFetching(ZulipTestCase):search_fields={},apply_markdown=True,client_gravatar=True,+ allow_empty_topic_name=True,allow_edit_history=False,user_profile=cordelia,realm=cordelia.realm,@@ -578,6 +585,7 @@ class TestMessageForIdsDisplayRecipientFetching(ZulipTestCase):search_fields={},apply_markdown=True,client_gravatar=True,+ allow_empty_topic_name=True,allow_edit_history=False,user_profile=cordelia,realm=cordelia.realm,@@ -602,6 +610,7 @@ class TestMessageForIdsDisplayRecipientFetching(ZulipTestCase):search_fields={},apply_markdown=True,client_gravatar=True,+ allow_empty_topic_name=True,allow_edit_history=False,user_profile=cordelia,realm=cordelia.realm,@@ -638,6 +647,7 @@ class TestMessageForIdsDisplayRecipientFetching(ZulipTestCase):search_fields={},apply_markdown=True,client_gravatar=True,+ allow_empty_topic_name=True,allow_edit_history=False,user_profile=cordelia,realm=cordelia.realm,diff --git a/zerver/tests/test_message_edit.py b/zerver/tests/test_message_edit.pyindex c699e16c72a..e24a5c09cbb 100644--- a/zerver/tests/test_message_edit.py+++ b/zerver/tests/test_message_edit.py@@ -49,6 +49,7 @@ class EditMessageTest(ZulipTestCase):search_fields={},apply_markdown=False,client_gravatar=False,+ allow_empty_topic_name=True,allow_edit_history=True,user_profile=None,realm=msg.realm,diff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.pyindex 088e9022365..9371f2e292e 100644--- a/zerver/tests/test_message_fetch.py+++ b/zerver/tests/test_message_fetch.py@@ -4087,6 +4087,7 @@ class GetOldMessagesTest(ZulipTestCase):wide_dict,apply_markdown=True,client_gravatar=False,+ allow_empty_topic_name=True,can_access_sender=True,realm_host=get_realm("zulip").host,is_incoming_1_to_1=False,diff --git a/zerver/tests/test_message_send.py b/zerver/tests/test_message_send.pyindex cb7ddd7e460..6e75ae7c259 100644--- a/zerver/tests/test_message_send.py+++ b/zerver/tests/test_message_send.py@@ -1651,6 +1651,7 @@ class StreamMessagesTest(ZulipTestCase):[dct],apply_markdown=True,client_gravatar=False,+ allow_empty_topic_name=True,realm=user_profile.realm,user_recipient_id=None,)diff --git a/zerver/tests/test_message_topics.py b/zerver/tests/test_message_topics.pyindex 3d6f242fb1e..a6747347e8d 100644--- a/zerver/tests/test_message_topics.py+++ b/zerver/tests/test_message_topics.py@@ -1,6 +1,7 @@import timefrom unittest import mock+import orjsonfrom django.utils.timezone import now as timezone_nowfrom zerver.actions.streams import do_change_stream_permission@@ -416,3 +417,113 @@ class EmptyTopicNameTest(ZulipTestCase):self.send_stream_message(iago, "Denmark", topic_name=Message.EMPTY_TOPIC_FALLBACK_NAME)events = client.event_queue.contents()self.assertEqual(events[1]["message"]["subject"], Message.EMPTY_TOPIC_FALLBACK_NAME)++ def test_fetch_messages(self) -> None:+ hamlet = self.example_user("hamlet")+ self.login_user(hamlet)++ first_message_id = self.send_stream_message(hamlet, "Denmark", topic_name="")+ second_message_id = self.send_stream_message(+ hamlet, "Denmark", topic_name=Message.EMPTY_TOPIC_FALLBACK_NAME+ )++ # Fetch using `/messages` endpoint.+ params = {+ "allow_empty_topic_name": "false",+ "message_ids": orjson.dumps([first_message_id, second_message_id]).decode(),+ }+ result = self.client_get("/json/messages", params)+ data = self.assert_json_success(result)+ self.assert_length(data["messages"], 2)+ for message in data["messages"]:+ self.assertEqual(message["subject"], Message.EMPTY_TOPIC_FALLBACK_NAME)++ params = {+ "allow_empty_topic_name": "true",+ "message_ids": orjson.dumps([first_message_id, second_message_id]).decode(),+ }+ result = self.client_get("/json/messages", params)+ data = self.assert_json_success(result)+ self.assert_length(data["messages"], 2)+ for message in data["messages"]:+ self.assertEqual(message["subject"], "")++ get_params = {+ "allow_empty_topic_name": "false",+ "anchor": "newest",+ "num_before": 2,+ "num_after": 0,+ "narrow": orjson.dumps(+ [+ {"operator": "channel", "operand": "Denmark"},+ {"operator": "topic", "operand": Message.EMPTY_TOPIC_FALLBACK_NAME},+ ]+ ).decode(),+ }+ result = self.client_get("/json/messages", get_params)+ data = self.assert_json_success(result)+ self.assert_length(data["messages"], 2)+ for message in data["messages"]:+ self.assertEqual(message["subject"], Message.EMPTY_TOPIC_FALLBACK_NAME)++ # Fetch using `/messages/{message_id}` endpoint.+ result = self.client_get(+ f"/json/messages/{first_message_id}", {"allow_empty_topic_name": "false"}+ )+ data = self.assert_json_success(result)+ self.assertEqual(data["message"]["subject"], Message.EMPTY_TOPIC_FALLBACK_NAME)++ result = self.client_get(+ f"/json/messages/{second_message_id}", {"allow_empty_topic_name": "false"}+ )+ data = self.assert_json_success(result)+ self.assertEqual(data["message"]["subject"], Message.EMPTY_TOPIC_FALLBACK_NAME)++ result = self.client_get(+ f"/json/messages/{first_message_id}", {"allow_empty_topic_name": "true"}+ )+ data = self.assert_json_success(result)+ self.assertEqual(data["message"]["subject"], "")++ result = self.client_get(+ f"/json/messages/{second_message_id}", {"allow_empty_topic_name": "true"}+ )+ data = self.assert_json_success(result)+ self.assertEqual(data["message"]["subject"], "")++ # Verify `edit_history` objects.+ params = {"topic": "new topic name"}+ result = self.client_patch(f"/json/messages/{first_message_id}", params)+ self.assert_json_success(result)++ result = self.client_get(+ f"/json/messages/{first_message_id}", {"allow_empty_topic_name": "false"}+ )+ data = self.assert_json_success(result)+ self.assertEqual(+ data["message"]["edit_history"][0]["prev_topic"], Message.EMPTY_TOPIC_FALLBACK_NAME+ )++ result = self.client_get(+ f"/json/messages/{first_message_id}", {"allow_empty_topic_name": "true"}+ )+ data = self.assert_json_success(result)+ self.assertEqual(data["message"]["edit_history"][0]["prev_topic"], "")++ params = {"topic": ""}+ result = self.client_patch(f"/json/messages/{first_message_id}", params)+ self.assert_json_success(result)++ result = self.client_get(+ f"/json/messages/{first_message_id}", {"allow_empty_topic_name": "false"}+ )+ data = self.assert_json_success(result)+ self.assertEqual(+ data["message"]["edit_history"][0]["topic"], Message.EMPTY_TOPIC_FALLBACK_NAME+ )++ result = self.client_get(+ f"/json/messages/{first_message_id}", {"allow_empty_topic_name": "true"}+ )+ data = self.assert_json_success(result)+ self.assertEqual(data["message"]["edit_history"][0]["topic"], "")diff --git a/zerver/tests/test_openapi.py b/zerver/tests/test_openapi.pyindex 1e64dd0ea25..3bac4a9766d 100644--- a/zerver/tests/test_openapi.py+++ b/zerver/tests/test_openapi.py@@ -790,7 +790,9 @@ class TestCurlExampleGeneration(ZulipTestCase):def test_generate_and_render_curl_with_array_example(self) -> None:generated_curl_example = self.curl_example(- "/messages", "GET", exclude=["use_first_unread_anchor", "message_ids"]+ "/messages",+ "GET",+ exclude=["use_first_unread_anchor", "message_ids", "allow_empty_topic_name"],)expected_curl_example = ["```curl",@@ -866,7 +868,13 @@ class TestCurlExampleGeneration(ZulipTestCase):generated_curl_example = self.curl_example("/messages","GET",- exclude=["client_gravatar", "apply_markdown", "use_first_unread_anchor", "message_ids"],+ exclude=[+ "client_gravatar",+ "apply_markdown",+ "use_first_unread_anchor",+ "message_ids",+ "allow_empty_topic_name",+ ],)expected_curl_example = ["```curl",diff --git a/zerver/tornado/event_queue.py b/zerver/tornado/event_queue.pyindex 8ef9b524fcf..e170199bb5f 100644--- a/zerver/tornado/event_queue.py+++ b/zerver/tornado/event_queue.py@@ -29,7 +29,7 @@ from zerver.lib.narrow_predicate import build_narrow_predicatefrom zerver.lib.notification_data import UserMessageNotificationsDatafrom zerver.lib.queue import queue_json_publish_rollback_unsafe, retry_eventfrom zerver.middleware import async_request_timer_restart-from zerver.models import CustomProfileField, Message+from zerver.models import CustomProfileFieldfrom zerver.tornado.descriptors import clear_descriptor_by_handler_id, set_descriptor_by_handler_idfrom zerver.tornado.exceptions import BadEventQueueIdErrorfrom zerver.tornado.handlers import finish_handler, get_handler_by_id, handler_stats_string@@ -1133,6 +1133,7 @@ def process_message_event(*,apply_markdown: bool,client_gravatar: bool,+ allow_empty_topic_name: bool,can_access_sender: bool,is_incoming_1_to_1: bool,) -> dict[str, Any]:@@ -1140,6 +1141,7 @@ def process_message_event(wide_dict,apply_markdown=apply_markdown,client_gravatar=client_gravatar,+ allow_empty_topic_name=allow_empty_topic_name,can_access_sender=can_access_sender,realm_host=realm_host,is_incoming_1_to_1=is_incoming_1_to_1,@@ -1222,20 +1224,11 @@ def process_message_event(message_dict = get_client_payload(apply_markdown=client.apply_markdown,client_gravatar=client.client_gravatar,+ allow_empty_topic_name=client.empty_topic_name,can_access_sender=can_access_sender,is_incoming_1_to_1=wide_dict["recipient_id"] == client.user_recipient_id,)- # Compatibility code to change subject="" to subject=Message.EMPTY_TOPIC_FALLBACK_NAME- # for older clients with no UI support for empty topic name.- if (- recipient_type_name == "stream"- and not client.empty_topic_name- and wide_dict["subject"] == ""- ):- message_dict = message_dict.copy()- message_dict["subject"] = Message.EMPTY_TOPIC_FALLBACK_NAME-# Make sure Zephyr mirroring bots know whether stream is invite-onlyif "mirror" in client.client_type_name and event_template.get("invite_only"):message_dict = message_dict.copy()diff --git a/zerver/views/message_edit.py b/zerver/views/message_edit.pyindex 18a43615f41..11fb482fa66 100644--- a/zerver/views/message_edit.py+++ b/zerver/views/message_edit.py@@ -195,6 +195,7 @@ def json_fetch_raw_message(*,message_id: PathOnly[NonNegativeInt],apply_markdown: Json[bool] = True,+ allow_empty_topic_name: Json[bool] = False,) -> HttpResponse:if not maybe_user_profile.is_authenticated:realm = get_valid_realm_from_request(request)@@ -224,6 +225,7 @@ def json_fetch_raw_message(apply_markdown=apply_markdown,client_gravatar=True,allow_edit_history=allow_edit_history,+ allow_empty_topic_name=allow_empty_topic_name,user_profile=user_profile,realm=message.realm,)diff --git a/zerver/views/message_fetch.py b/zerver/views/message_fetch.pyindex 7e8eb83955f..c1654c5c053 100644--- a/zerver/views/message_fetch.py+++ b/zerver/views/message_fetch.py@@ -25,6 +25,7 @@ from zerver.lib.narrow import (is_spectator_compatible,is_web_public_narrow,parse_anchor_value,+ update_narrow_terms_containing_empty_topic_fallback_name,update_narrow_terms_containing_with_operator,)from zerver.lib.request import RequestNotes@@ -118,6 +119,7 @@ def get_messages_backend(] = False,client_gravatar: Json[bool] = True,apply_markdown: Json[bool] = True,+ allow_empty_topic_name: Json[bool] = False,client_requested_message_ids: Annotated[Json[list[NonNegativeInt] | None], ApiParamConfig("message_ids")] = None,@@ -144,6 +146,7 @@ def get_messages_backend(anchor = parse_anchor_value(anchor_val, use_first_unread_anchor_val)realm = get_valid_realm_from_request(request)+ narrow = update_narrow_terms_containing_empty_topic_fallback_name(narrow)narrow = update_narrow_terms_containing_with_operator(realm, maybe_user_profile, narrow)num_of_messages_requested = num_before + num_after@@ -302,6 +305,7 @@ def get_messages_backend(search_fields=search_fields,apply_markdown=apply_markdown,client_gravatar=client_gravatar,+ allow_empty_topic_name=allow_empty_topic_name,allow_edit_history=realm.allow_edit_history,user_profile=user_profile,realm=realm,