Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
url_decoding: Add `parse_narrow_url`.
PieterCK3773ba10e122
diff --git a/web/src/hash_util.ts b/web/src/hash_util.tsindex 475759b94ca..9cc6af146d8 100644--- a/web/src/hash_util.ts+++ b/web/src/hash_util.ts@@ -182,6 +182,9 @@ export function search_public_streams_notice_url(terms: NarrowTerm[]): string {}export function parse_narrow(hash: string[]): NarrowTerm[] | undefined {+ // There's a Python copy of this function in `zerver/lib/url_decoding.py`+ // called `parse_narrow_url`, the two should be kept roughly in sync.+// This will throw an exception when passed an invalid hash// at the decodeHashComponent call, handle appropriately.let i;diff --git a/zerver/lib/narrow_helpers.py b/zerver/lib/narrow_helpers.pyindex 1dc31a69146..c1352050567 100644--- a/zerver/lib/narrow_helpers.py+++ b/zerver/lib/narrow_helpers.py@@ -28,13 +28,14 @@ from django.conf import settings@dataclassclass NarrowTerm:operator: str- operand: str+ operand: str | int | list[int]negated: bool@dataclassclass NeverNegatedNarrowTerm(NarrowTerm):negated: bool = field(default=False, init=False)+ operand: strdef narrow_dataclasses_from_tuples(diff --git a/zerver/lib/url_decoding.py b/zerver/lib/url_decoding.pyindex bff76444b76..a6736da7a49 100644--- a/zerver/lib/url_decoding.py+++ b/zerver/lib/url_decoding.py@@ -1,7 +1,10 @@-from urllib.parse import urlsplit+from urllib.parse import unquote, urlsplitfrom django.conf import settings+from zerver.lib.narrow_helpers import NarrowTerm+from zerver.lib.topic import DB_TOPIC_NAME+def is_same_server_message_link(url: str) -> bool:split_result = urlsplit(url)@@ -24,3 +27,117 @@ def is_same_server_message_link(url: str) -> bool:ends_with_near_message_id = fragment_parts[-2] == "near" and fragment_parts[-1].isdigit()return category == "narrow" and section in {"channel", "dm"} and ends_with_near_message_id+++CHANNEL_SYNONYMS = {"stream": "channel", "streams": "channels"}++OPERATOR_SYNONYMS = {+ **CHANNEL_SYNONYMS,+ # "pm-with:" was renamed to "dm:"+ "pm-with": "dm",+ # "group-pm-with:" was replaced with "dm-including:"+ "group-pm-with": "dm-including",+ "from": "sender",+ DB_TOPIC_NAME: "topic",+}+++def canonicalize_operator_synonyms(text: str) -> str:+ text = text.lower()+ if text in OPERATOR_SYNONYMS.values():+ return text+ if text in OPERATOR_SYNONYMS:+ return OPERATOR_SYNONYMS[text]+ return text+++def parse_recipient_slug(slug: str) -> tuple[int | list[int], str] | None:+ """+ Parses operands formatted in slug containing object ID or IDs.+ Typical of "channel" or private message operands.++ Doesn't parse the legacy pre-2018 stream slug format, which would+ require using data for what channels exist for a proper parse.+ e.g. "stream-name"++ Returns a tuple of parsed ids and the recipient info (channel name,+ DM'ed users name, etc) or only `None` if the operand is invalid.+ e.g.+ - "12,13,14-group" -> ([12, 13, 14], "group")+ - "89-Markl" -> (89, "Markl")+ - "stream-name" -> None+ """+ try:+ ids_string, suffix = slug.split("-", maxsplit=1)+ ids = [int(id) for id in ids_string.split(",")]+ return (ids if len(ids) > 1 else ids[0], suffix)+ except ValueError:+ # We expect this to happen both for invalid URLs and legacy+ # pre-2018 channel link URLs that don't have a channel ID in+ # the slug.+ return None+++def decode_hash_component(string: str) -> str:+ # This matches the web app's implementation of decodeHashComponent.+ return unquote(string.replace(".", "%"))+++def decode_narrow_operand(operator: str, operand: str) -> str | int | list[int]:+ # These have the similar slug formatting for their operands which+ # contain object ID(s).+ if operator in ["dm-including", "dm", "sender", "channel"]:+ result = parse_recipient_slug(operand)+ return result[0] if isinstance(result, tuple) else ""++ if operator == "near":+ return int(operand) if operand.isdigit() else ""++ operand = decode_hash_component(operand).strip()++ return operand+++def parse_narrow_url(+ narrow_url: str,+) -> list[NarrowTerm] | None:+ """This server implementation is intended to match the algorithm+ for the web app's `parse_narrow` in `hash_util.ts`. It largely+ behaves the same way and has the same purpose: to parse a narrow+ URL into a list of `NarrowTerm`.++ The key difference from the web app implementation is that this+ does not validate the referenced objects (users and channels).+ """+ split_result = urlsplit(narrow_url)+ fragment = split_result.fragment+ fragment_parts = fragment.split("/")++ terms: list[NarrowTerm] = []++ for i in range(1, len(fragment_parts), 2):+ raw_operator = decode_hash_component(fragment_parts[i]).strip()++ if not raw_operator:+ return None++ negated = False+ if raw_operator.startswith("-"):+ negated = True+ raw_operator = raw_operator[1:]+ operator = canonicalize_operator_synonyms(raw_operator)++ try:+ raw_operand = fragment_parts[i + 1]+ except IndexError:+ raw_operand = ""+ operand = decode_narrow_operand(operator, raw_operand)++ if operand == "" and operator not in ["topic"]:+ # The empty string is a valid topic (realm_empty_topic_display_name).+ #+ # Other empty string operands are invalid.+ return None++ terms.append(NarrowTerm(operator, operand, negated))+ return termsdiff --git a/zerver/tests/fixtures/narrow_url_to_narrow_terms.json b/zerver/tests/fixtures/narrow_url_to_narrow_terms.jsonnew file mode 100644index 00000000000..f99ec84af56--- /dev/null+++ b/zerver/tests/fixtures/narrow_url_to_narrow_terms.json@@ -0,0 +1,184 @@++[+ {+ "name": "channel_link",+ "near_link": "http://testserver/#narrow/channel/13-Denmark",+ "expected_output": [+ {+ "operator": "channel",+ "operand": 13,+ "negated": false+ }+ ]+ },+ {+ "name": "topic_link",+ "near_link": "http://testserver/#narrow/channel/13-Denmark/topic/desktop",+ "expected_output": [+ {+ "operator": "channel",+ "operand": 13,+ "negated": false+ },+ {+ "operator": "topic",+ "operand": "desktop",+ "negated": false+ }+ ]+ },+ {+ "name": "decoded_topic_link",+ "near_link": "http://testserver/#narrow/channel/13-Denmark/topic/Broken.20Inline.20giphy.20preview.20.2F.20Messed.20up.20with.20camo",+ "expected_output": [+ {+ "operator": "channel",+ "operand": 13,+ "negated": false+ },+ {+ "operator": "topic",+ "operand": "Broken Inline giphy preview / Messed up with camo",+ "negated": false+ }+ ]+ },+ {+ "name": "missing_topic_operand",+ "near_link": "http://testserver/#narrow/channel/13-Denmark/topic",+ "expected_output": [+ {+ "operator": "channel",+ "operand": 13,+ "negated": false+ },+ {+ "operator": "topic",+ "operand": "",+ "negated": false+ }+ ]+ },+ {+ "name": "channel_message_link",+ "near_link": "http://testserver/#narrow/channel/13-Denmark/topic/desktop/near/555",+ "expected_output": [+ {+ "operator": "channel",+ "operand": 13,+ "negated": false+ },+ {+ "operator": "topic",+ "operand": "desktop",+ "negated": false+ },+ {+ "operator": "near",+ "operand": 555,+ "negated": false+ }+ ]+ },+ {+ "name": "dm_link",+ "near_link": "http://testserver/#narrow/dm/95-Calcifer",+ "expected_output": [+ {+ "operator": "dm",+ "operand": 95,+ "negated": false+ }+ ]+ },+ {+ "name": "near_dm_link",+ "near_link": "http://testserver/#narrow/dm/15-John/near/19",+ "expected_output": [+ {+ "operator": "dm",+ "operand": 15,+ "negated": false+ },+ {+ "operator": "near",+ "operand": 19,+ "negated": false+ }+ ]+ },+ {+ "name": "gdm_link",+ "near_link": "http://testserver/#narrow/dm/15,12,13-group",+ "expected_output": [+ {+ "operator": "dm",+ "operand": [15,12,13],+ "negated": false+ }+ ]+ },+ {+ "name": "near_gdm_link",+ "near_link": "http://testserver/#narrow/dm/15,12,13-group/near/12",+ "expected_output": [+ {+ "operator": "dm",+ "operand": [15,12,13],+ "negated": false+ },+ {+ "operator": "near",+ "operand": 12,+ "negated": false+ }+ ]+ },+ {+ "name": "legacy_channel_synonym",+ "near_link": "http://testserver/#narrow/stream/13-Denmark",+ "expected_output": [+ {+ "operator": "channel",+ "operand": 13,+ "negated": false+ }+ ]+ },+ {+ "name": "hypothetical_negated_link",+ "near_link": "http://testserver/#narrow/-channel/13-Denmark",+ "expected_output": [+ {+ "operator": "channel",+ "operand": 13,+ "negated": true+ }+ ]+ },+ {+ "name": "legacy_channel_slug_unsupported",+ "near_link": "http://testserver/#narrow/channel/test-here",+ "expected_output": null+ },+ {+ "name": "broken_link_no_channel_operand",+ "near_link": "http://testserver/#narrow/channel/%20",+ "expected_output": null+ },+ {+ "name": "broken_link_other_operand",+ "near_link": "http://testserver/#narrow/near/%20",+ "expected_output": null+ },+ {+ "name": "broken_link_no_operator",+ "near_link": "http://testserver/#narrow/%20/test-here",+ "expected_output": null+ },+ {+ "name": "broken_link_invalid_message_operand",+ "near_link": "http://testserver/#narrow/near/13-Denmark",+ "expected_output": null+ }+]diff --git a/zerver/tests/test_url_decoding.py b/zerver/tests/test_url_decoding.pyindex b9a542c83b1..af1ba255c10 100644--- a/zerver/tests/test_url_decoding.py+++ b/zerver/tests/test_url_decoding.py@@ -1,7 +1,8 @@import orjson+from zerver.lib.narrow_helpers import NarrowTermfrom zerver.lib.test_classes import ZulipTestCase-from zerver.lib.url_decoding import is_same_server_message_link+from zerver.lib.url_decoding import is_same_server_message_link, parse_narrow_urlclass URLDecodeTest(ZulipTestCase):@@ -11,3 +12,22 @@ class URLDecodeTest(ZulipTestCase):self.assertEqual(is_same_server_message_link(test["message_link"]), test["expected_output"])+++class NarrowURLDecodeTest(ZulipTestCase):+ def test_decode_narrow_url(self) -> None:+ tests = orjson.loads(self.fixture_data("narrow_url_to_narrow_terms.json"))++ for test_case in tests:+ with self.subTest(name=test_case["name"]):+ parsed_terms = parse_narrow_url(test_case["near_link"])+ expected_output = test_case.get("expected_output")++ if expected_output is None:+ self.assertEqual(parsed_terms, expected_output)+ else:+ assert parsed_terms is not None+ expected_narrow_terms: list[NarrowTerm] = [+ NarrowTerm(**term) for term in expected_output+ ]+ self.assertListEqual(parsed_terms, expected_narrow_terms)