Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

linkifiers: Add alternative_url_templates to model and API.

Shubham Padia774b8d299430
diff --git a/api_docs/changelog.md b/api_docs/changelog.md
index d181cfa18b8..ea0af096057 100644
--- a/api_docs/changelog.md
+++ b/api_docs/changelog.md
@@ -20,6 +20,19 @@ format used by the Zulip server that they are interacting with.
## Changes in Zulip 12.0
+**Feature level 478**
+
+* [`POST /realm/filters`](/api/add-linkifier),
+ [`PATCH /realm/filters/{filter_id}`](/api/update-linkifier): Added
+ `alternative_url_templates` parameter for specifying additional URL
+ templates used only for reverse linkification (converting pasted URLs
+ to linkifier pattern text). These templates have no effect on forward
+ linkification.
+* [`GET /realm/linkifiers`](/api/get-linkifiers),
+ [`POST /register`](/api/register-queue),
+ [`GET /events`](/api/get-events): Linkifier objects now include the
+ `alternative_url_templates` field.
+
**Feature level 477**
* `PATCH /realm`, [`POST /register`](/api/register-queue),
diff --git a/version.py b/version.py
index e283dc85a4a..efa341c3418 100644
--- a/version.py
+++ b/version.py
@@ -33,7 +33,7 @@ DESKTOP_WARNING_VERSION = "5.9.3"
# https://zulip.readthedocs.io/en/latest/documentation/api.html#step-by-step-guide
# Also available at docs/documentation/api.md.
-API_FEATURE_LEVEL = 477
+API_FEATURE_LEVEL = 478
# Bump the minor PROVISION_VERSION to indicate that folks should provision
# only when going from an old version of the code to a newer version. Bump
diff --git a/zerver/actions/realm_linkifiers.py b/zerver/actions/realm_linkifiers.py
index a988b803394..326019f52d0 100644
--- a/zerver/actions/realm_linkifiers.py
+++ b/zerver/actions/realm_linkifiers.py
@@ -28,6 +28,7 @@ def do_add_linkifier(
url_template: str,
example_input: str | None = None,
reverse_template: str | None = None,
+ alternative_url_templates: list[str] | None = None,
*,
acting_user: UserProfile | None,
) -> int:
@@ -35,6 +36,8 @@ def do_add_linkifier(
url_template = url_template.strip()
example_input = normalize_optional_text(example_input)
reverse_template = normalize_optional_text(reverse_template)
+ if alternative_url_templates is None:
+ alternative_url_templates = []
# 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"]
@@ -45,6 +48,7 @@ def do_add_linkifier(
url_template=url_template,
example_input=example_input,
reverse_template=reverse_template,
+ alternative_url_templates=alternative_url_templates,
)
else:
linkifier = RealmFilter(
@@ -53,6 +57,7 @@ def do_add_linkifier(
url_template=url_template,
example_input=example_input,
reverse_template=reverse_template,
+ alternative_url_templates=alternative_url_templates,
order=max_order + 1,
)
linkifier.full_clean()
@@ -72,6 +77,7 @@ def do_add_linkifier(
id=linkifier.id,
example_input=example_input,
reverse_template=reverse_template,
+ alternative_url_templates=linkifier.alternative_url_templates,
),
},
)
@@ -111,6 +117,7 @@ def do_remove_linkifier(
"url_template": url_template,
"example_input": realm_linkifier.example_input,
"reverse_template": realm_linkifier.reverse_template,
+ "alternative_url_templates": realm_linkifier.alternative_url_templates,
},
},
)
@@ -125,6 +132,7 @@ def do_update_linkifier(
url_template: str,
example_input: str | None = None,
reverse_template: str | None = None,
+ alternative_url_templates: list[str] | None = None,
*,
acting_user: UserProfile | None,
) -> None:
@@ -135,6 +143,8 @@ def do_update_linkifier(
linkifier.url_template = url_template
linkifier.example_input = normalize_optional_text(example_input)
linkifier.reverse_template = normalize_optional_text(reverse_template)
+ if alternative_url_templates is not None:
+ linkifier.alternative_url_templates = alternative_url_templates
# Validation of fields is done by full_clean.
linkifier.full_clean()
@@ -145,6 +155,8 @@ def do_update_linkifier(
update_fields.append("example_input")
if reverse_template is not None:
update_fields.append("reverse_template")
+ if alternative_url_templates is not None:
+ update_fields.append("alternative_url_templates")
linkifier.save(update_fields=update_fields)
realm_linkifiers = linkifiers_for_realm(realm.id)
@@ -161,6 +173,7 @@ def do_update_linkifier(
id=linkifier.id,
example_input=linkifier.example_input,
reverse_template=linkifier.reverse_template,
+ alternative_url_templates=linkifier.alternative_url_templates,
),
},
)
diff --git a/zerver/lib/event_types.py b/zerver/lib/event_types.py
index 5b4711a19c5..9a2adfc6601 100644
--- a/zerver/lib/event_types.py
+++ b/zerver/lib/event_types.py
@@ -523,6 +523,7 @@ class RealmLinkifier(BaseModel):
id: int
example_input: str | None = None
reverse_template: str | None = None
+ alternative_url_templates: list[str] = []
class EventRealmLinkifiers(BaseEvent):
diff --git a/zerver/lib/types.py b/zerver/lib/types.py
index b30a795f989..95e13b9181c 100644
--- a/zerver/lib/types.py
+++ b/zerver/lib/types.py
@@ -79,6 +79,7 @@ class LinkifierDict(TypedDict):
id: int
example_input: str | None
reverse_template: str | None
+ alternative_url_templates: list[str]
class Unset:
diff --git a/zerver/migrations/0788_realmfilter_alternative_url_templates.py b/zerver/migrations/0788_realmfilter_alternative_url_templates.py
new file mode 100644
index 00000000000..f5f048946db
--- /dev/null
+++ b/zerver/migrations/0788_realmfilter_alternative_url_templates.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("zerver", "0787_alter_realm_workplace_users_group"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="realmfilter",
+ name="alternative_url_templates",
+ field=models.JSONField(blank=True, default=list),
+ ),
+ ]
diff --git a/zerver/models/linkifiers.py b/zerver/models/linkifiers.py
index 1e9f2645b1b..d4237d7e4c1 100644
--- a/zerver/models/linkifiers.py
+++ b/zerver/models/linkifiers.py
@@ -94,6 +94,7 @@ class RealmFilter(models.Model):
url_template = models.TextField(validators=[url_template_validator])
example_input = models.TextField(blank=True, null=True)
reverse_template = models.TextField(blank=True, null=True)
+ alternative_url_templates = models.JSONField(default=list, blank=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)
@@ -166,6 +167,33 @@ class RealmFilter(models.Model):
params={"name": name},
)
+ for alternative_template in self.alternative_url_templates:
+ url_template_validator(alternative_template)
+
+ alternative_template_variables = set(
+ uri_template.URITemplate(alternative_template).variable_names
+ )
+
+ missing_in_pattern = alternative_template_variables - group_set
+ if len(missing_in_pattern) > 0:
+ name = min(missing_in_pattern)
+ raise ValidationError(
+ _(
+ "Group %(name)r in alternative URL template is not present in linkifier pattern."
+ ),
+ params={"name": name},
+ )
+
+ missing_in_alternative = group_set - alternative_template_variables
+ if len(missing_in_alternative) > 0:
+ name = min(missing_in_alternative)
+ raise ValidationError(
+ _(
+ "Group %(name)r in linkifier pattern is not present in alternative URL template."
+ ),
+ params={"name": name},
+ )
+
def get_linkifiers_cache_key(realm_id: int) -> str:
return f"{cache.KEY_PREFIX}:all_linkifiers_for_realm:{realm_id}"
@@ -181,6 +209,7 @@ def linkifiers_for_realm(realm_id: int) -> list[LinkifierDict]:
id=linkifier.id,
example_input=linkifier.example_input,
reverse_template=linkifier.reverse_template,
+ alternative_url_templates=linkifier.alternative_url_templates,
)
for linkifier in RealmFilter.objects.filter(realm_id=realm_id).order_by("order")
]
diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yaml
index 090746363c0..1a3bb37babb 100644
--- a/zerver/openapi/zulip.yaml
+++ b/zerver/openapi/zulip.yaml
@@ -4042,6 +4042,19 @@ paths:
`{{ "{{/}}" }}` can be used for literal `{/}` characters.
**Changes**: New in Zulip 12.0 (feature level 471).
+ alternative_url_templates:
+ type: array
+ items:
+ type: string
+ description: |
+ An array of additional [RFC 6570][rfc6570] compliant URL
+ template strings that are used for reverse linkification
+ (converting pasted URLs to linkifier pattern text). These
+ templates have no effect on forward linkification.
+
+ [rfc6570]: https://www.rfc-editor.org/rfc/rfc6570.html
+
+ **Changes**: New in Zulip 12.0 (feature level e2b257).
example:
{
"type": "realm_linkifiers",
@@ -4053,6 +4066,10 @@ paths:
"id": 1,
"example_input": "#1234",
"reverse_template": "#{id}",
+ "alternative_url_templates":
+ [
+ "https://realm.com/my_realm_filter/issue/{id}",
+ ],
},
],
"id": 0,
@@ -15655,6 +15672,19 @@ paths:
`{{ "{{/}}" }}` can be used for literal `{/}` characters.
**Changes**: New in Zulip 12.0 (feature level 471).
+ alternative_url_templates:
+ type: array
+ items:
+ type: string
+ description: |
+ An array of additional [RFC 6570][rfc6570] compliant URL
+ template strings that are used for reverse linkification
+ (converting pasted URLs to linkifier pattern text). These
+ templates have no effect on forward linkification.
+
+ [rfc6570]: https://www.rfc-editor.org/rfc/rfc6570.html
+
+ **Changes**: New in Zulip 12.0 (feature level e2b257).
example:
{
"msg": "",
@@ -15666,6 +15696,8 @@ paths:
"id": 1,
"example_input": "#1234",
"reverse_template": "#{id}",
+ "alternative_url_templates":
+ ["https://github.com/zulip/zulip/pull/{id}"],
},
],
"result": "success",
@@ -15750,9 +15782,26 @@ paths:
back to us.
**Changes**: New in Zulip 12.0 (feature level 471).
+ alternative_url_templates:
+ type: array
+ items:
+ type: string
+ example: ["https://github.com/zulip/zulip/pull/{id}"]
+ description: |
+ An array of additional [RFC 6570][rfc6570] compliant URL
+ template strings that are used for reverse linkification
+ (converting pasted URLs to linkifier pattern text). These
+ templates have no effect on forward linkification.
+
+ [rfc6570]: https://www.rfc-editor.org/rfc/rfc6570.html
+
+ **Changes**: New in Zulip 12.0 (feature level e2b257).
required:
- pattern
- url_template
+ encoding:
+ alternative_url_templates:
+ contentType: application/json
responses:
"200":
description: Success.
@@ -15849,9 +15898,26 @@ paths:
`{{ "{{/}}" }}` can be used for literal `{/}` characters.
**Changes**: New in Zulip 12.0 (feature level 471).
+ alternative_url_templates:
+ type: array
+ items:
+ type: string
+ example: ["https://github.com/zulip/zulip/pull/{id}"]
+ description: |
+ An array of additional [RFC 6570][rfc6570] compliant URL
+ template strings that are used for reverse linkification
+ (converting pasted URLs to linkifier pattern text). These
+ templates have no effect on forward linkification.
+
+ [rfc6570]: https://www.rfc-editor.org/rfc/rfc6570.html
+
+ **Changes**: New in Zulip 12.0 (feature level e2b257).
required:
- pattern
- url_template
+ encoding:
+ alternative_url_templates:
+ contentType: application/json
responses:
"200":
$ref: "#/components/responses/SimpleSuccess"
diff --git a/zerver/tests/test_audit_log.py b/zerver/tests/test_audit_log.py
index ffc99ee1145..f9dce6e6a13 100644
--- a/zerver/tests/test_audit_log.py
+++ b/zerver/tests/test_audit_log.py
@@ -1103,6 +1103,7 @@ class TestRealmAuditLog(ZulipTestCase):
url_template="https://realm.com/my_realm_filter/{id}",
example_input="#1",
reverse_template="#{id}",
+ alternative_url_templates=["https://realm.com/my_realm_filter/pull/{id}"],
acting_user=user,
)
@@ -1112,6 +1113,7 @@ class TestRealmAuditLog(ZulipTestCase):
id=linkifier_id,
example_input="#1",
reverse_template="#{id}",
+ alternative_url_templates=["https://realm.com/my_realm_filter/pull/{id}"],
)
expected_extra_data = {
"realm_linkifiers": [*initial_linkifiers, added_linkfier],
@@ -1136,6 +1138,10 @@ class TestRealmAuditLog(ZulipTestCase):
url_template="https://realm.com/my_realm_filter/issues/{id}",
example_input="#15",
reverse_template="#{id}",
+ alternative_url_templates=[
+ "https://realm.com/my_realm_filter/pull/{id}",
+ "https://realm.com/my_realm_filter/discussions/{id}",
+ ],
acting_user=user,
)
changed_linkifier = LinkifierDict(
@@ -1144,6 +1150,10 @@ class TestRealmAuditLog(ZulipTestCase):
id=linkifier_id,
example_input="#15",
reverse_template="#{id}",
+ alternative_url_templates=[
+ "https://realm.com/my_realm_filter/pull/{id}",
+ "https://realm.com/my_realm_filter/discussions/{id}",
+ ],
)
expected_extra_data = {
"realm_linkifiers": [*initial_linkifiers, changed_linkifier],
@@ -1171,6 +1181,10 @@ class TestRealmAuditLog(ZulipTestCase):
"url_template": "https://realm.com/my_realm_filter/issues/{id}",
"example_input": "#15",
"reverse_template": "#{id}",
+ "alternative_url_templates": [
+ "https://realm.com/my_realm_filter/pull/{id}",
+ "https://realm.com/my_realm_filter/discussions/{id}",
+ ],
}
expected_extra_data = {
"realm_linkifiers": initial_linkifiers,
diff --git a/zerver/tests/test_markdown.py b/zerver/tests/test_markdown.py
index 00e9fb47c50..b29c5bd9688 100644
--- a/zerver/tests/test_markdown.py
+++ b/zerver/tests/test_markdown.py
@@ -1907,6 +1907,7 @@ class MarkdownLinkifierTest(ZulipTestCase):
"url_template": "whatever",
"example_input": "whatever",
"reverse_template": "whatever",
+ "alternative_url_templates": [],
}
],
)
@@ -1925,6 +1926,7 @@ class MarkdownLinkifierTest(ZulipTestCase):
"url_template": "whatever",
"example_input": "whatever",
"reverse_template": "whatever",
+ "alternative_url_templates": [],
}
],
)
diff --git a/zerver/tests/test_realm_linkifiers.py b/zerver/tests/test_realm_linkifiers.py
index 23cefb619a2..d1ca7c5cf0c 100644
--- a/zerver/tests/test_realm_linkifiers.py
+++ b/zerver/tests/test_realm_linkifiers.py
@@ -338,6 +338,95 @@ class RealmFilterTest(ZulipTestCase):
result = self.client_patch(f"/json/realm/filters/{linkifier_id}", info=data)
self.assert_json_error(result, "Invalid URL template.")
+ def test_alternative_url_templates(self) -> None:
+ self.login("iago")
+
+ # Create a linkifier with alternative URL templates.
+ data = {
+ "pattern": r"#(?P<id>[0-9]+)",
+ "url_template": "https://github.com/zulip/zulip/issues/{id}",
+ "alternative_url_templates": orjson.dumps(
+ ["https://github.com/zulip/zulip/pull/{id}"]
+ ).decode(),
+ }
+ result = self.client_post("/json/realm/filters", info=data)
+ linkifier_id = self.assert_json_success(result)["id"]
+
+ # Verify the alternative URL templates are returned.
+ result = self.client_get("/json/realm/linkifiers")
+ linkifiers = self.assert_json_success(result)["linkifiers"]
+ self.assert_length(linkifiers, 1)
+ self.assertEqual(
+ linkifiers[0]["alternative_url_templates"],
+ ["https://github.com/zulip/zulip/pull/{id}"],
+ )
+
+ # Update to add more alternative URL templates.
+ data = {
+ "pattern": r"#(?P<id>[0-9]+)",
+ "url_template": "https://github.com/zulip/zulip/issues/{id}",
+ "alternative_url_templates": orjson.dumps(
+ [
+ "https://github.com/zulip/zulip/pull/{id}",
+ "https://github.com/zulip/zulip/discussions/{id}",
+ ]
+ ).decode(),
+ }
+ result = self.client_patch(f"/json/realm/filters/{linkifier_id}", info=data)
+ self.assert_json_success(result)
+
+ result = self.client_get("/json/realm/linkifiers")
+ linkifiers = self.assert_json_success(result)["linkifiers"]
+ self.assertEqual(
+ linkifiers[0]["alternative_url_templates"],
+ [
+ "https://github.com/zulip/zulip/pull/{id}",
+ "https://github.com/zulip/zulip/discussions/{id}",
+ ],
+ )
+
+ # Update to clear alternative URL templates.
+ data = {
+ "pattern": r"#(?P<id>[0-9]+)",
+ "url_template": "https://github.com/zulip/zulip/issues/{id}",
+ "alternative_url_templates": orjson.dumps([]).decode(),
+ }
+ result = self.client_patch(f"/json/realm/filters/{linkifier_id}", info=data)
+ self.assert_json_success(result)
+
+ result = self.client_get("/json/realm/linkifiers")
+ linkifiers = self.assert_json_success(result)["linkifiers"]
+ self.assertEqual(linkifiers[0]["alternative_url_templates"], [])
+
+ # Invalid RFC 6570 template should be rejected.
+ data = {
+ "pattern": r"#(?P<id>[0-9]+)",
+ "url_template": "https://github.com/zulip/zulip/issues/{id}",
+ "alternative_url_templates": orjson.dumps(["https://example.com/{foo"]).decode(),
+ }
+ result = self.client_post("/json/realm/filters", info=data)
+ self.assert_json_error(result, "Invalid URL template.")
+
+ # Variable not in pattern should be rejected.
+ data["alternative_url_templates"] = orjson.dumps(["https://example.com/{other}"]).decode()
+ result = self.client_post("/json/realm/filters", info=data)
+ self.assert_json_error(
+ result,
+ "Group 'other' in alternative URL template is not present in linkifier pattern.",
+ )
+
+ # Missing pattern group in alternative template should be rejected.
+ data["pattern"] = r"(?P<org>[a-z]+)#(?P<id>[0-9]+)"
+ data["url_template"] = "https://github.com/{org}/issues/{id}"
+ data["alternative_url_templates"] = orjson.dumps(
+ ["https://github.com/zulip/pull/{id}"]
+ ).decode()
+ result = self.client_post("/json/realm/filters", info=data)
+ self.assert_json_error(
+ result,
+ "Group 'org' in linkifier pattern is not present in alternative URL template.",
+ )
+
def test_valid_urls(self) -> None:
valid_urls = [
"http://example.com/",
diff --git a/zerver/views/realm_linkifiers.py b/zerver/views/realm_linkifiers.py
index a5276949a33..9082c825e34 100644
--- a/zerver/views/realm_linkifiers.py
+++ b/zerver/views/realm_linkifiers.py
@@ -33,6 +33,7 @@ def create_linkifier(
url_template: str,
example_input: str | None = None,
reverse_template: str | None = None,
+ alternative_url_templates: Json[list[str]] | None = None,
) -> HttpResponse:
try:
linkifier_id = do_add_linkifier(
@@ -41,6 +42,7 @@ def create_linkifier(
url_template=url_template,
example_input=example_input,
reverse_template=reverse_template,
+ alternative_url_templates=alternative_url_templates,
acting_user=user_profile,
)
return json_success(request, data={"id": linkifier_id})
@@ -70,6 +72,7 @@ def update_linkifier(
url_template: str,
example_input: str | None = None,
reverse_template: str | None = None,
+ alternative_url_templates: Json[list[str]] | None = None,
) -> HttpResponse:
try:
do_update_linkifier(
@@ -79,6 +82,7 @@ def update_linkifier(
url_template=url_template,
example_input=example_input,
reverse_template=reverse_template,
+ alternative_url_templates=alternative_url_templates,
acting_user=user_profile,
)
return json_success(request)