topic_link_util: Add support for empty topics in the backend.

Fallback links with empty topics now have correct
url and text for the "general chat" topic.
This commit is contained in:
Kislay Verma
2025-05-21 12:19:09 +05:30
committed by Tim Abbott
parent 0a7227cfbb
commit 43bf15f0fa
2 changed files with 20 additions and 13 deletions

View File

@@ -3,6 +3,8 @@
import re
import urllib.parse
from zerver.models.messages import Message
invalid_stream_topic_regex = re.compile(r"[`>*&\[\]]|(\$\$)")
@@ -42,13 +44,6 @@ def encode_hash_component(s: str) -> str:
return "".join(hash_replacements.get(c, c) for c in encoded)
def channel_topic_url(stream_id: int, stream_name: str, topic_name: str | None = None) -> str:
link = f"#narrow/channel/{stream_id}-{encode_hash_component(stream_name.replace(' ', '-'))}"
if topic_name:
link += f"/topic/{encode_hash_component(topic_name)}"
return link
def get_fallback_markdown_link(
stream_id: int, stream_name: str, topic_name: str | None = None
) -> str:
@@ -56,15 +51,19 @@ def get_fallback_markdown_link(
Generates the markdown link syntax for a stream or topic link.
"""
escape = escape_invalid_stream_topic_characters
url = channel_topic_url(stream_id, stream_name, topic_name)
if topic_name:
return f"[#{escape(stream_name)} > {escape(topic_name)}]({url})"
link = f"#narrow/channel/{stream_id}-{encode_hash_component(stream_name.replace(' ', '-'))}"
text = f"#{escape(stream_name)}"
if topic_name is not None:
link += f"/topic/{encode_hash_component(topic_name)}"
if topic_name == "":
topic_name = Message.EMPTY_TOPIC_FALLBACK_NAME
text += f" > {escape(topic_name)}"
return f"[#{escape(stream_name)}]({url})"
return f"[{text}]({link})"
def get_stream_topic_link_syntax(stream_id: int, stream_name: str, topic_name: str) -> str:
# If the topic name is such that it will generate an invalid #**stream>topic** syntax,
# If the stream/topic name is such that it will generate an invalid #**stream>topic** syntax,
# we revert to generating the normal markdown syntax for a link.
if will_produce_broken_stream_topic_link(topic_name) or will_produce_broken_stream_topic_link(
stream_name
@@ -74,7 +73,7 @@ def get_stream_topic_link_syntax(stream_id: int, stream_name: str, topic_name: s
def get_stream_link_syntax(stream_id: int, stream_name: str) -> str:
# If the topic name is such that it will generate an invalid #**stream>topic** syntax,
# If the stream name is such that it will generate an invalid #**stream** syntax,
# we revert to generating the normal markdown syntax for a link.
if will_produce_broken_stream_topic_link(stream_name):
return get_fallback_markdown_link(stream_id, stream_name)