mirror of
https://github.com/zulip/zulip.git
synced 2025-11-02 04:53:36 +00:00
JsonableError has two major benefits over json_error: * It can be raised from anywhere in the codebase, rather than being a return value, which is much more convenient for refactoring, as one doesn't potentially need to change error handling style when extracting a bit of view code to a function. * It is guaranteed to contain the `code` property, which is helpful for API consistency. Various stragglers are not updated because JsonableError requires subclassing in order to specify custom data or HTTP status codes.
70 lines
2.2 KiB
Python
70 lines
2.2 KiB
Python
from django.core.exceptions import ValidationError
|
|
from django.http import HttpRequest, HttpResponse
|
|
from django.utils.translation import gettext as _
|
|
|
|
from zerver.decorator import require_realm_admin
|
|
from zerver.lib.actions import do_add_linkifier, do_remove_linkifier, do_update_linkifier
|
|
from zerver.lib.exceptions import JsonableError
|
|
from zerver.lib.request import REQ, has_request_variables
|
|
from zerver.lib.response import json_error, json_success
|
|
from zerver.models import RealmFilter, UserProfile, linkifiers_for_realm
|
|
|
|
|
|
# Custom realm linkifiers
|
|
def list_linkifiers(request: HttpRequest, user_profile: UserProfile) -> HttpResponse:
|
|
linkifiers = linkifiers_for_realm(user_profile.realm_id)
|
|
return json_success({"linkifiers": linkifiers})
|
|
|
|
|
|
@require_realm_admin
|
|
@has_request_variables
|
|
def create_linkifier(
|
|
request: HttpRequest,
|
|
user_profile: UserProfile,
|
|
pattern: str = REQ(),
|
|
url_format_string: str = REQ(),
|
|
) -> HttpResponse:
|
|
try:
|
|
linkifier_id = do_add_linkifier(
|
|
realm=user_profile.realm,
|
|
pattern=pattern,
|
|
url_format_string=url_format_string,
|
|
)
|
|
return json_success({"id": linkifier_id})
|
|
except ValidationError as e:
|
|
return json_error(e.messages[0], data={"errors": dict(e)})
|
|
|
|
|
|
@require_realm_admin
|
|
def delete_linkifier(
|
|
request: HttpRequest, user_profile: UserProfile, filter_id: int
|
|
) -> HttpResponse:
|
|
try:
|
|
do_remove_linkifier(realm=user_profile.realm, id=filter_id)
|
|
except RealmFilter.DoesNotExist:
|
|
raise JsonableError(_("Linkifier not found."))
|
|
return json_success()
|
|
|
|
|
|
@require_realm_admin
|
|
@has_request_variables
|
|
def update_linkifier(
|
|
request: HttpRequest,
|
|
user_profile: UserProfile,
|
|
filter_id: int,
|
|
pattern: str = REQ(),
|
|
url_format_string: str = REQ(),
|
|
) -> HttpResponse:
|
|
try:
|
|
do_update_linkifier(
|
|
realm=user_profile.realm,
|
|
id=filter_id,
|
|
pattern=pattern,
|
|
url_format_string=url_format_string,
|
|
)
|
|
return json_success()
|
|
except RealmFilter.DoesNotExist:
|
|
raise JsonableError(_("Linkifier not found."))
|
|
except ValidationError as e:
|
|
return json_error(e.messages[0], data={"errors": dict(e)})
|