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.

models: Extract zerver.models.realm_playgrounds.

Anders Kaseorg33610c87829c
diff --git a/zerver/actions/realm_playgrounds.py b/zerver/actions/realm_playgrounds.py
index a8adb974c8d..b08bcf046a4 100644
--- a/zerver/actions/realm_playgrounds.py
+++ b/zerver/actions/realm_playgrounds.py
@@ -6,7 +6,8 @@ from django.utils.timezone import now as timezone_now
from zerver.lib.exceptions import ValidationFailureError
from zerver.lib.types import RealmPlaygroundDict
-from zerver.models import Realm, RealmAuditLog, RealmPlayground, UserProfile, get_realm_playgrounds
+from zerver.models import Realm, RealmAuditLog, RealmPlayground, UserProfile
+from zerver.models.realm_playgrounds import get_realm_playgrounds
from zerver.models.users import active_user_ids
from zerver.tornado.django_api import send_event_on_commit
diff --git a/zerver/lib/events.py b/zerver/lib/events.py
index 4aaff684628..2ba72c941c3 100644
--- a/zerver/lib/events.py
+++ b/zerver/lib/events.py
@@ -81,11 +81,11 @@ from zerver.models import (
UserTopic,
custom_profile_fields_for_realm,
get_default_stream_groups,
- get_realm_playgrounds,
)
from zerver.models.constants import MAX_TOPIC_NAME_LENGTH
from zerver.models.linkifiers import linkifiers_for_realm
from zerver.models.realm_emoji import get_all_custom_emoji_for_realm
+from zerver.models.realm_playgrounds import get_realm_playgrounds
from zerver.models.realms import get_realm_domains
from zerver.tornado.django_api import get_user_events, request_event_queue
from zproject.backends import email_auth_enabled, password_auth_enabled
diff --git a/zerver/models/__init__.py b/zerver/models/__init__.py
index 101adf92751..faa24d3d0f2 100644
--- a/zerver/models/__init__.py
+++ b/zerver/models/__init__.py
@@ -9,7 +9,6 @@ from datetime import datetime, timedelta, timezone
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, TypedDict, TypeVar, Union
import orjson
-import uri_template
from bitfield import BitField
from bitfield.types import Bit, BitHandler
from django.conf import settings
@@ -19,7 +18,6 @@ from django.contrib.postgres.indexes import GinIndex
from django.contrib.postgres.search import SearchVectorField
from django.core.exceptions import ValidationError
from django.core.serializers.json import DjangoJSONEncoder
-from django.core.validators import RegexValidator
from django.db import models, transaction
from django.db.backends.base.base import BaseDatabaseWrapper
from django.db.models import CASCADE, Exists, F, OuterRef, Q, QuerySet
@@ -56,7 +54,6 @@ from zerver.lib.types import (
GroupPermissionSetting,
ProfileDataElementBase,
ProfileDataElementValue,
- RealmPlaygroundDict,
RealmUserValidator,
UnspecifiedValue,
UserDisplayRecipient,
@@ -78,8 +75,8 @@ from zerver.models.groups import SystemGroups
from zerver.models.groups import UserGroup as UserGroup
from zerver.models.groups import UserGroupMembership as UserGroupMembership
from zerver.models.linkifiers import RealmFilter as RealmFilter
-from zerver.models.linkifiers import url_template_validator
from zerver.models.realm_emoji import RealmEmoji as RealmEmoji
+from zerver.models.realm_playgrounds import RealmPlayground as RealmPlayground
from zerver.models.realms import Realm as Realm
from zerver.models.realms import RealmAuthenticationMethod as RealmAuthenticationMethod
from zerver.models.realms import RealmDomain as RealmDomain
@@ -187,81 +184,6 @@ def get_recipient_ids(
return to, recipient_type_str
-class RealmPlayground(models.Model):
- """Server side storage model to store playground information needed by our
- 'view code in playground' feature in code blocks.
- """
-
- MAX_PYGMENTS_LANGUAGE_LENGTH = 40
-
- realm = models.ForeignKey(Realm, on_delete=CASCADE)
- url_template = models.TextField(validators=[url_template_validator])
-
- # User-visible display name used when configuring playgrounds in the settings page and
- # when displaying them in the playground links popover.
- name = models.TextField(db_index=True)
-
- # This stores the pygments lexer subclass names and not the aliases themselves.
- pygments_language = models.CharField(
- db_index=True,
- max_length=MAX_PYGMENTS_LANGUAGE_LENGTH,
- # We validate to see if this conforms to the character set allowed for a
- # language in the code block.
- validators=[
- RegexValidator(
- regex=r"^[ a-zA-Z0-9_+-./#]*$", message=_("Invalid characters in pygments language")
- )
- ],
- )
-
- class Meta:
- unique_together = (("realm", "pygments_language", "name"),)
-
- @override
- def __str__(self) -> str:
- return f"{self.realm.string_id}: {self.pygments_language} {self.name}"
-
- @override
- def clean(self) -> None:
- """Validate whether the URL template is valid for the playground,
- ensuring that "code" is the sole variable present in it.
-
- Django's `full_clean` calls `clean_fields` followed by `clean` method
- and stores all ValidationErrors from all stages to return as JSON.
- """
-
- # Do not continue the check if the url template is invalid to begin
- # with. The ValidationError for invalid template will only be raised by
- # the validator set on the url_template field instead of here to avoid
- # duplicates.
- if not uri_template.validate(self.url_template):
- return
-
- # Extract variables used in the URL template.
- template_variables = set(uri_template.URITemplate(self.url_template).variable_names)
-
- if "code" not in template_variables:
- raise ValidationError(_('Missing the required variable "code" in the URL template'))
-
- # The URL template should only contain a single variable, which is "code".
- if len(template_variables) != 1:
- raise ValidationError(
- _('"code" should be the only variable present in the URL template'),
- )
-
-
-def get_realm_playgrounds(realm: Realm) -> List[RealmPlaygroundDict]:
- return [
- RealmPlaygroundDict(
- id=playground.id,
- name=playground.name,
- pygments_language=playground.pygments_language,
- url_template=playground.url_template,
- )
- for playground in RealmPlayground.objects.filter(realm=realm).all()
- ]
-
-
class Recipient(models.Model):
"""Represents an audience that can potentially receive messages in Zulip.
diff --git a/zerver/models/realm_playgrounds.py b/zerver/models/realm_playgrounds.py
new file mode 100644
index 00000000000..92b8df125e8
--- /dev/null
+++ b/zerver/models/realm_playgrounds.py
@@ -0,0 +1,88 @@
+from typing import List
+
+import uri_template
+from django.core.exceptions import ValidationError
+from django.core.validators import RegexValidator
+from django.db import models
+from django.db.models import CASCADE
+from django.utils.translation import gettext as _
+from typing_extensions import override
+
+from zerver.lib.types import RealmPlaygroundDict
+from zerver.models.linkifiers import url_template_validator
+from zerver.models.realms import Realm
+
+
+class RealmPlayground(models.Model):
+ """Server side storage model to store playground information needed by our
+ 'view code in playground' feature in code blocks.
+ """
+
+ MAX_PYGMENTS_LANGUAGE_LENGTH = 40
+
+ realm = models.ForeignKey(Realm, on_delete=CASCADE)
+ url_template = models.TextField(validators=[url_template_validator])
+
+ # User-visible display name used when configuring playgrounds in the settings page and
+ # when displaying them in the playground links popover.
+ name = models.TextField(db_index=True)
+
+ # This stores the pygments lexer subclass names and not the aliases themselves.
+ pygments_language = models.CharField(
+ db_index=True,
+ max_length=MAX_PYGMENTS_LANGUAGE_LENGTH,
+ # We validate to see if this conforms to the character set allowed for a
+ # language in the code block.
+ validators=[
+ RegexValidator(
+ regex=r"^[ a-zA-Z0-9_+-./#]*$", message=_("Invalid characters in pygments language")
+ )
+ ],
+ )
+
+ class Meta:
+ unique_together = (("realm", "pygments_language", "name"),)
+
+ @override
+ def __str__(self) -> str:
+ return f"{self.realm.string_id}: {self.pygments_language} {self.name}"
+
+ @override
+ def clean(self) -> None:
+ """Validate whether the URL template is valid for the playground,
+ ensuring that "code" is the sole variable present in it.
+
+ Django's `full_clean` calls `clean_fields` followed by `clean` method
+ and stores all ValidationErrors from all stages to return as JSON.
+ """
+
+ # Do not continue the check if the url template is invalid to begin
+ # with. The ValidationError for invalid template will only be raised by
+ # the validator set on the url_template field instead of here to avoid
+ # duplicates.
+ if not uri_template.validate(self.url_template):
+ return
+
+ # Extract variables used in the URL template.
+ template_variables = set(uri_template.URITemplate(self.url_template).variable_names)
+
+ if "code" not in template_variables:
+ raise ValidationError(_('Missing the required variable "code" in the URL template'))
+
+ # The URL template should only contain a single variable, which is "code".
+ if len(template_variables) != 1:
+ raise ValidationError(
+ _('"code" should be the only variable present in the URL template'),
+ )
+
+
+def get_realm_playgrounds(realm: Realm) -> List[RealmPlaygroundDict]:
+ return [
+ RealmPlaygroundDict(
+ id=playground.id,
+ name=playground.name,
+ pygments_language=playground.pygments_language,
+ url_template=playground.url_template,
+ )
+ for playground in RealmPlayground.objects.filter(realm=realm).all()
+ ]
diff --git a/zerver/tests/test_audit_log.py b/zerver/tests/test_audit_log.py
index c0855687b0d..6abf973362f 100644
--- a/zerver/tests/test_audit_log.py
+++ b/zerver/tests/test_audit_log.py
@@ -81,12 +81,12 @@ from zerver.models import (
Subscription,
UserGroup,
UserProfile,
- get_realm_playgrounds,
get_stream,
)
from zerver.models.groups import SystemGroups
from zerver.models.linkifiers import linkifiers_for_realm
from zerver.models.realm_emoji import EmojiInfo, get_all_custom_emoji_for_realm
+from zerver.models.realm_playgrounds import get_realm_playgrounds
from zerver.models.realms import RealmDomainDict, get_realm, get_realm_domains