Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
linkifiers: Add reverse_template to RealmLinkifier.
Shubham Padiab18fea521f73
diff --git a/api_docs/unmerged.d/ZF-9993b5.md b/api_docs/unmerged.d/ZF-9993b5.mdindex 11815d2052b..2b9c2d1ec1c 100644--- a/api_docs/unmerged.d/ZF-9993b5.md+++ b/api_docs/unmerged.d/ZF-9993b5.md@@ -1,6 +1,10 @@* [`GET /events`](/api/get-events), [`GET /realm/linkifiers`](/api/get-linkifiers),[`POST /realm/filters`](/api/add-linkifier),[`PATCH /realm/filters/{filter_id}`](/api/update-linkifier):- Added `example_input` to linkifier objects to provide a sample string matching the pattern.- This is required for reverse linkifiers. Pass an empty string during PATCH to set this- field back to null.+ Added `example_input` and `reverse_template` to linkifier objects.+ `example_input` is a sample string matching the url_pattern for the linkifier.+ `reverse_template` is a string that can process input params and turn a url into+ it's abbreviated form.+ `reverse_template` requires `example_input` to be provided.+ Pass an empty string during PATCH to set either of these fields back to null, given+ they satisfy the requirements stated above.diff --git a/web/src/state_data.ts b/web/src/state_data.tsindex afee5a2a77d..fd0b88d399f 100644--- a/web/src/state_data.ts+++ b/web/src/state_data.ts@@ -409,6 +409,7 @@ export const realm_linkifier_schema = z.object({url_template: z.string(),id: z.number(),example_input: z.optional(z.nullable(z.string())),+ reverse_template: z.optional(z.nullable(z.string())),});export const realm_report_message_types = z.object({diff --git a/zerver/actions/realm_linkifiers.py b/zerver/actions/realm_linkifiers.pyindex d8ef528845e..a988b803394 100644--- a/zerver/actions/realm_linkifiers.py+++ b/zerver/actions/realm_linkifiers.py@@ -27,12 +27,14 @@ def do_add_linkifier(pattern: str,url_template: str,example_input: str | None = None,+ reverse_template: str | None = None,*,acting_user: UserProfile | None,) -> int:pattern = pattern.strip()url_template = url_template.strip()example_input = normalize_optional_text(example_input)+ reverse_template = normalize_optional_text(reverse_template)# This makes sure that the new linkifier is always ordered the last modulo# the rare race condition.max_order = RealmFilter.objects.aggregate(Max("order"))["order__max"]@@ -42,6 +44,7 @@ def do_add_linkifier(pattern=pattern,url_template=url_template,example_input=example_input,+ reverse_template=reverse_template,)else:linkifier = RealmFilter(@@ -49,6 +52,7 @@ def do_add_linkifier(pattern=pattern,url_template=url_template,example_input=example_input,+ reverse_template=reverse_template,order=max_order + 1,)linkifier.full_clean()@@ -67,6 +71,7 @@ def do_add_linkifier(url_template=url_template,id=linkifier.id,example_input=example_input,+ reverse_template=reverse_template,),},)@@ -105,6 +110,7 @@ def do_remove_linkifier("pattern": pattern,"url_template": url_template,"example_input": realm_linkifier.example_input,+ "reverse_template": realm_linkifier.reverse_template,},},)@@ -118,6 +124,7 @@ def do_update_linkifier(pattern: str,url_template: str,example_input: str | None = None,+ reverse_template: str | None = None,*,acting_user: UserProfile | None,) -> None:@@ -127,6 +134,7 @@ def do_update_linkifier(linkifier.pattern = patternlinkifier.url_template = url_templatelinkifier.example_input = normalize_optional_text(example_input)+ linkifier.reverse_template = normalize_optional_text(reverse_template)# Validation of fields is done by full_clean.linkifier.full_clean()@@ -135,6 +143,8 @@ def do_update_linkifier(# takes care of converting empty string to None.if example_input is not None:update_fields.append("example_input")+ if reverse_template is not None:+ update_fields.append("reverse_template")linkifier.save(update_fields=update_fields)realm_linkifiers = linkifiers_for_realm(realm.id)@@ -150,6 +160,7 @@ def do_update_linkifier(url_template=url_template,id=linkifier.id,example_input=linkifier.example_input,+ reverse_template=linkifier.reverse_template,),},)diff --git a/zerver/lib/event_types.py b/zerver/lib/event_types.pyindex f842356e85b..2970c3d4ca9 100644--- a/zerver/lib/event_types.py+++ b/zerver/lib/event_types.py@@ -539,6 +539,7 @@ class RealmLinkifier(BaseModel):url_template: strid: intexample_input: str | None = None+ reverse_template: str | None = Noneclass EventRealmLinkifiers(BaseEvent):diff --git a/zerver/lib/exceptions.py b/zerver/lib/exceptions.pyindex cd63f33c41d..ba87c2fd11f 100644--- a/zerver/lib/exceptions.py+++ b/zerver/lib/exceptions.py@@ -231,6 +231,19 @@ class IncompatibleParametersError(JsonableError):return _("Unsupported parameter combination: {parameters}")+class MissingDependentParameterError(JsonableError):+ data_fields = ["required_parameter", "set_parameter"]++ def __init__(self, required_parameter: str, set_parameter: str) -> None:+ self.required_parameter = required_parameter+ self.set_parameter = set_parameter++ @staticmethod+ @override+ def msg_format() -> str:+ return _("{required_parameter} is required when {set_parameter} is set.")++class CannotDeactivateLastUserError(JsonableError):code = ErrorCode.CANNOT_DEACTIVATE_LAST_USERdata_fields = ["is_last_owner", "entity"]diff --git a/zerver/lib/types.py b/zerver/lib/types.pyindex 723bd968724..1aaddad0972 100644--- a/zerver/lib/types.py+++ b/zerver/lib/types.py@@ -78,6 +78,7 @@ class LinkifierDict(TypedDict):url_template: strid: intexample_input: str | None+ reverse_template: str | Noneclass Unset:diff --git a/zerver/migrations/0784_realmfilter_reverse_template.py b/zerver/migrations/0784_realmfilter_reverse_template.pynew file mode 100644index 00000000000..c4580fc28e8--- /dev/null+++ b/zerver/migrations/0784_realmfilter_reverse_template.py@@ -0,0 +1,15 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("zerver", "0783_realmfilter_example_input"),+ ]++ operations = [+ migrations.AddField(+ model_name="realmfilter",+ name="reverse_template",+ field=models.TextField(blank=True, null=True),+ ),+ ]diff --git a/zerver/models/linkifiers.py b/zerver/models/linkifiers.pyindex a51ebcb7614..1316505ea6a 100644--- a/zerver/models/linkifiers.py+++ b/zerver/models/linkifiers.py@@ -9,6 +9,7 @@ from typing_extensions import overridefrom zerver.lib import cachefrom zerver.lib.cache import cache_delete, cache_with_key+from zerver.lib.exceptions import MissingDependentParameterErrorfrom zerver.lib.per_request_cache import (flush_per_request_cache,return_same_value_during_entire_request,@@ -59,6 +60,7 @@ class RealmFilter(models.Model):pattern = models.TextField()url_template = models.TextField(validators=[url_template_validator])example_input = models.TextField(blank=True, null=True)+ reverse_template = models.TextField(blank=True, null=True)# Linkifiers are applied in a message/topic in order; the processing order# is important when there are overlapping patterns.order = models.IntegerField(default=0)@@ -83,6 +85,9 @@ class RealmFilter(models.Model):pattern = filter_pattern_validator(self.pattern)group_set = set(pattern.groupindex.keys())+ if self.reverse_template is not None and self.example_input is None:+ raise MissingDependentParameterError("example_input", "reverse_template")+if self.example_input is not None:example_input = self.example_input.strip()if example_input and pattern.search(example_input) is None:@@ -132,6 +137,7 @@ def linkifiers_for_realm(realm_id: int) -> list[LinkifierDict]:url_template=linkifier.url_template,id=linkifier.id,example_input=linkifier.example_input,+ reverse_template=linkifier.reverse_template,)for linkifier in RealmFilter.objects.filter(realm_id=realm_id).order_by("order")]diff --git a/zerver/openapi/python_examples.py b/zerver/openapi/python_examples.pyindex 157d2224dcc..38336a44f18 100644--- a/zerver/openapi/python_examples.py+++ b/zerver/openapi/python_examples.py@@ -666,6 +666,8 @@ def add_realm_filter(client: Client) -> int:request = {"pattern": "#(?P<id>[0-9]+)","url_template": "https://github.com/zulip/zulip/issues/{id}",+ "example_input": "#1234",+ "reverse_template": "#{id}",}result = client.call_endpoint("/realm/filters", method="POST", request=request)# {code_example|end}@@ -681,6 +683,8 @@ def update_realm_filter(client: Client, filter_id: int) -> None:request = {"pattern": "#(?P<id>[0-9]+)","url_template": "https://github.com/zulip/zulip/issues/{id}",+ "example_input": "#1234",+ "reverse_template": "#{id}",}result = client.call_endpoint(url=f"/realm/filters/{filter_id}", method="PATCH", request=requestdiff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex 574cd493410..a7e5fa0e9ac 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -4014,6 +4014,17 @@ paths:An example input string that matches the linkifier's pattern.This is required for reverse linkifiers.+ **Changes**: New in Zulip 12.0 (feature level ZF-9993b5).+ reverse_template:+ type: string+ nullable: true+ description: |+ A simple template using `{variable}` for variables that can+ be used to generate the Markdown linkifier syntax, given a+ URL matching the URL template.++ `{{ "{{/}}" }}` can be used for literal `{/}` characters.+**Changes**: New in Zulip 12.0 (feature level ZF-9993b5).example:{@@ -4025,6 +4036,7 @@ paths:"url_template": "https://realm.com/my_realm_filter/{id}","id": 1,"example_input": "#1234",+ "reverse_template": "#{id}",},],"id": 0,@@ -15590,6 +15602,17 @@ paths:An example input string that matches the linkifier's pattern.This is required for reverse linkifiers.+ **Changes**: New in Zulip 12.0 (feature level ZF-9993b5).+ reverse_template:+ type: string+ nullable: true+ description: |+ A simple template using `{variable}` for variables that can+ be used to generate the Markdown linkifier syntax, given a+ URL matching the URL template.++ `{{ "{{/}}" }}` can be used for literal `{/}` characters.+**Changes**: New in Zulip 12.0 (feature level ZF-9993b5).example:{@@ -15601,6 +15624,7 @@ paths:"url_template": "https://github.com/zulip/zulip/issues/{id}","id": 1,"example_input": "#1234",+ "reverse_template": "#{id}",},],"result": "success",@@ -15668,6 +15692,22 @@ paths:An example input string that matches the linkifier's pattern.This is required for reverse linkifiers.+ **Changes**: New in Zulip 12.0 (feature level ZF-9993b5).+ reverse_template:+ type: string+ nullable: true+ example: "#{id}"+ description: |+ A simple template using `{variable}` for variables that can+ be used to generate the Markdown linkifier syntax, given a+ URL matching the URL template.++ `{{ "{{/}}" }}` can be used for literal `{/}` characters.++ Server verifies that variables extracted from example_input using+ url_pattern when passed to reverse_template returns example_input+ back to us.+**Changes**: New in Zulip 12.0 (feature level ZF-9993b5).required:- pattern@@ -15750,6 +15790,23 @@ paths:This is required for reverse linkifiers. Passing an empty stringwill set this field back to null.+ **Changes**: New in Zulip 12.0 (feature level ZF-9993b5).+ reverse_template:+ type: string+ nullable: true+ example: "#{id}"+ description: |+ A simple template using `{variable}` for variables that can+ be used to generate the Markdown linkifier syntax, given a+ URL matching the URL template. Passing an empty string+ will set this field back to null.++ Server verifies that variables extracted from example_input using+ url_pattern when passed to reverse_template returns example_input+ back to us.++ `{{ "{{/}}" }}` can be used for literal `{/}` characters.+**Changes**: New in Zulip 12.0 (feature level ZF-9993b5).required:- patterndiff --git a/zerver/tests/test_audit_log.py b/zerver/tests/test_audit_log.pyindex 4404d6e5298..02dcae6ecfb 100644--- a/zerver/tests/test_audit_log.py+++ b/zerver/tests/test_audit_log.py@@ -1109,6 +1109,7 @@ class TestRealmAuditLog(ZulipTestCase):url_template="https://realm.com/my_realm_filter/{id}",id=linkifier_id,example_input="#1",+ reverse_template=None,)expected_extra_data = {"realm_linkifiers": [*initial_linkifiers, added_linkfier],@@ -1139,6 +1140,7 @@ class TestRealmAuditLog(ZulipTestCase):url_template="https://realm.com/my_realm_filter/issues/{id}",id=linkifier_id,example_input="#15",+ reverse_template=None,)expected_extra_data = {"realm_linkifiers": [*initial_linkifiers, changed_linkifier],@@ -1165,6 +1167,7 @@ class TestRealmAuditLog(ZulipTestCase):"pattern": "#(?P<id>[0-9]+)","url_template": "https://realm.com/my_realm_filter/issues/{id}","example_input": "#15",+ "reverse_template": None,}expected_extra_data = {"realm_linkifiers": initial_linkifiers,diff --git a/zerver/tests/test_markdown.py b/zerver/tests/test_markdown.pyindex ce985a735a9..00e9fb47c50 100644--- a/zerver/tests/test_markdown.py+++ b/zerver/tests/test_markdown.py@@ -1889,7 +1889,11 @@ class MarkdownLinkifierTest(ZulipTestCase):self.assertEqual(linkifiers_for_realm(realm.id), [])linkifier = RealmFilter(- realm=realm, pattern=r"whatever", url_template="whatever", example_input="whatever"+ realm=realm,+ pattern=r"whatever",+ url_template="whatever",+ example_input="whatever",+ reverse_template="whatever",)linkifier.save()@@ -1902,6 +1906,7 @@ class MarkdownLinkifierTest(ZulipTestCase):"pattern": "whatever","url_template": "whatever","example_input": "whatever",+ "reverse_template": "whatever",}],)@@ -1919,6 +1924,7 @@ class MarkdownLinkifierTest(ZulipTestCase):"pattern": "whatever","url_template": "whatever","example_input": "whatever",+ "reverse_template": "whatever",}],)diff --git a/zerver/tests/test_realm_linkifiers.py b/zerver/tests/test_realm_linkifiers.pyindex d1339383a7d..2aeb56cf2dc 100644--- a/zerver/tests/test_realm_linkifiers.py+++ b/zerver/tests/test_realm_linkifiers.py@@ -63,18 +63,29 @@ class RealmFilterTest(ZulipTestCase):data["pattern"] = r"ZUL-(?P<id>\d+)"data["url_template"] = "https://realm.com/my_realm_filter/{id}"data["example_input"] = "no match"+ data["reverse_template"] = "ZUL-{id}"result = self.client_post("/json/realm/filters", info=data)self.assert_json_error(result, "Example input does not match the linkifier pattern.")+ data = {+ "pattern": r"ZUL-(?P<id>\d+)",+ "url_template": "https://realm.com/my_realm_filter/{id}",+ "reverse_template": "ZUL-{id}",+ }+ result = self.client_post("/json/realm/filters", info=data)+ self.assert_json_error(result, "example_input is required when reverse_template is set.")+data = {"pattern": r"ZUL-(?P<id>\d+)","url_template": "https://realm.com/my_realm_filter/#hashtag/{id}","example_input": "ZUL-15",+ "reverse_template": "ZUL-{id}",}result = self.client_post("/json/realm/filters", info=data)self.assert_json_success(result)self.assertIsNotNone(re.match(data["pattern"], "ZUL-15"))data.pop("example_input")+ data.pop("reverse_template")data["pattern"] = r"ZUL2-(?P<id>\d+)"data["url_template"] = "https://realm.com/my_realm_filter/?value={id}"diff --git a/zerver/views/realm_linkifiers.py b/zerver/views/realm_linkifiers.pyindex 5b4655a4d15..a5276949a33 100644--- a/zerver/views/realm_linkifiers.py+++ b/zerver/views/realm_linkifiers.py@@ -32,6 +32,7 @@ def create_linkifier(pattern: str,url_template: str,example_input: str | None = None,+ reverse_template: str | None = None,) -> HttpResponse:try:linkifier_id = do_add_linkifier(@@ -39,6 +40,7 @@ def create_linkifier(pattern=pattern,url_template=url_template,example_input=example_input,+ reverse_template=reverse_template,acting_user=user_profile,)return json_success(request, data={"id": linkifier_id})@@ -67,6 +69,7 @@ def update_linkifier(pattern: str,url_template: str,example_input: str | None = None,+ reverse_template: str | None = None,) -> HttpResponse:try:do_update_linkifier(@@ -75,6 +78,7 @@ def update_linkifier(pattern=pattern,url_template=url_template,example_input=example_input,+ reverse_template=reverse_template,acting_user=user_profile,)return json_success(request)