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.pyindex 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_nowfrom zerver.lib.exceptions import ValidationFailureErrorfrom 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_playgroundsfrom zerver.models.users import active_user_idsfrom zerver.tornado.django_api import send_event_on_commitdiff --git a/zerver/lib/events.py b/zerver/lib/events.pyindex 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_LENGTHfrom zerver.models.linkifiers import linkifiers_for_realmfrom zerver.models.realm_emoji import get_all_custom_emoji_for_realm+from zerver.models.realm_playgrounds import get_realm_playgroundsfrom zerver.models.realms import get_realm_domainsfrom zerver.tornado.django_api import get_user_events, request_event_queuefrom zproject.backends import email_auth_enabled, password_auth_enableddiff --git a/zerver/models/__init__.py b/zerver/models/__init__.pyindex 101adf92751..faa24d3d0f2 100644--- a/zerver/models/__init__.py+++ b/zerver/models/__init__.py@@ -9,7 +9,6 @@ from datetime import datetime, timedelta, timezonefrom typing import Any, Callable, Dict, List, Optional, Set, Tuple, TypedDict, TypeVar, Unionimport orjson-import uri_templatefrom bitfield import BitFieldfrom bitfield.types import Bit, BitHandlerfrom django.conf import settings@@ -19,7 +18,6 @@ from django.contrib.postgres.indexes import GinIndexfrom django.contrib.postgres.search import SearchVectorFieldfrom django.core.exceptions import ValidationErrorfrom django.core.serializers.json import DjangoJSONEncoder-from django.core.validators import RegexValidatorfrom django.db import models, transactionfrom django.db.backends.base.base import BaseDatabaseWrapperfrom 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 SystemGroupsfrom zerver.models.groups import UserGroup as UserGroupfrom zerver.models.groups import UserGroupMembership as UserGroupMembershipfrom zerver.models.linkifiers import RealmFilter as RealmFilter-from zerver.models.linkifiers import url_template_validatorfrom zerver.models.realm_emoji import RealmEmoji as RealmEmoji+from zerver.models.realm_playgrounds import RealmPlayground as RealmPlaygroundfrom zerver.models.realms import Realm as Realmfrom zerver.models.realms import RealmAuthenticationMethod as RealmAuthenticationMethodfrom 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.pynew file mode 100644index 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.pyindex 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 SystemGroupsfrom zerver.models.linkifiers import linkifiers_for_realmfrom zerver.models.realm_emoji import EmojiInfo, get_all_custom_emoji_for_realm+from zerver.models.realm_playgrounds import get_realm_playgroundsfrom zerver.models.realms import RealmDomainDict, get_realm, get_realm_domains