Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
zerver: API to create channel.
apoorvapendse6203861529ed
diff --git a/api_docs/changelog.md b/api_docs/changelog.mdindex 08204d28950..b1a63b042c4 100644--- a/api_docs/changelog.md+++ b/api_docs/changelog.md@@ -20,6 +20,13 @@ format used by the Zulip server that they are interacting with.## Changes in Zulip 11.0+**Feature level 417**++* [`POST channels/create`](/api/create-channel): Added a dedicated+ endpoint for creating a new channel. Previously, channel creation+ was done entirely through+ [`POST /users/me/subscriptions`](/api/subscribe).+**Feature level 416*** [`POST /invites`](/api/send-invites), [`POSTdiff --git a/api_docs/include/rest-endpoints.md b/api_docs/include/rest-endpoints.mdindex 78eb704a707..e438061a5dd 100644--- a/api_docs/include/rest-endpoints.md+++ b/api_docs/include/rest-endpoints.md@@ -62,7 +62,7 @@* [Get all channels](/api/get-streams)* [Get a channel by ID](/api/get-stream-by-id)* [Get channel ID](/api/get-stream-id)-* [Create a channel](/api/create-stream)+* [Create a channel](/api/create-channel)* [Update a channel](/api/update-stream)* [Archive a channel](/api/archive-stream)* [Get channel's email address](/api/get-stream-email-address)diff --git a/version.py b/version.pyindex 80405dfe9db..40a408a3241 100644--- a/version.py+++ b/version.py@@ -34,7 +34,7 @@ DESKTOP_WARNING_VERSION = "5.9.3"# new level means in api_docs/changelog.md, as well as "**Changes**"# entries in the endpoint's documentation in `zulip.yaml`.-API_FEATURE_LEVEL = 416+API_FEATURE_LEVEL = 417# 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. Bumpdiff --git a/zerver/lib/exceptions.py b/zerver/lib/exceptions.pyindex 8fd31383d27..2ebdd1e532a 100644--- a/zerver/lib/exceptions.py+++ b/zerver/lib/exceptions.py@@ -17,6 +17,7 @@ class ErrorCode(Enum):BAD_NARROW = auto()CANNOT_DEACTIVATE_LAST_USER = auto()MISSING_HTTP_EVENT_HEADER = auto()+ CHANNEL_ALREADY_EXISTS = auto()STREAM_DOES_NOT_EXIST = auto()UNAUTHORIZED_PRINCIPAL = auto()UNSUPPORTED_WEBHOOK_EVENT_TYPE = auto()@@ -174,6 +175,20 @@ class UnauthorizedError(JsonableError):return extra_headers_dict+class ChannelExistsError(JsonableError):+ code = ErrorCode.CHANNEL_ALREADY_EXISTS+ http_status_code = 409+ data_fields = ["channel_name"]++ def __init__(self, channel_name: str) -> None:+ self.channel_name = channel_name++ @staticmethod+ @override+ def msg_format() -> str:+ return _("Channel '{channel_name}' already exists")++class StreamDoesNotExistError(JsonableError):code = ErrorCode.STREAM_DOES_NOT_EXISTdata_fields = ["stream"]diff --git a/zerver/lib/streams.py b/zerver/lib/streams.pyindex 53b3a0b711e..8b376ffee9f 100644--- a/zerver/lib/streams.py+++ b/zerver/lib/streams.py@@ -13,6 +13,7 @@ from zerver.lib.default_streams import get_default_stream_ids_for_realmfrom zerver.lib.exceptions import (CannotAdministerChannelError,CannotSetTopicsPolicyError,+ ChannelExistsError,IncompatibleParametersError,JsonableError,OrganizationOwnerRequiredError,@@ -992,7 +993,7 @@ def check_stream_name_available(realm: Realm, name: str) -> None:check_stream_name(name)try:get_stream(name, realm)- raise JsonableError(_("Channel name is already in use."))+ raise ChannelExistsError(name)except Stream.DoesNotExist:passdiff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.pyindex 6e415368a25..2b4a6eb98eb 100644--- a/zerver/lib/test_classes.py+++ b/zerver/lib/test_classes.py@@ -1618,6 +1618,39 @@ Output:self.assert_json_success(result)return result+ # Create a stream by making an API request+ def create_channel_via_post(+ self,+ user: UserProfile,+ subscribers: list[str] | list[int] | None = None,+ name: str | None = None,+ extra_post_data: Mapping[str, Any] = {},+ invite_only: bool = False,+ is_web_public: bool = False,+ **extra: str,+ ) -> "TestHttpResponse":+ if subscribers is None:+ subscribers = [user.id]++ post_data = {+ "name": name,+ "subscribers": orjson.dumps(subscribers).decode(),+ "is_web_public": orjson.dumps(is_web_public).decode(),+ "invite_only": orjson.dumps(invite_only).decode(),+ }++ post_data.update(extra_post_data)+ with self.artificial_transaction_savepoint():+ result = self.api_post(+ user,+ "/api/v1/channels/create",+ post_data,+ intentionally_undocumented=False,+ **extra,+ )++ return result+def subscribed_stream_name_list(self, user: UserProfile) -> str:# This is currently only used for producing error messages.subscribed_streams = gather_subscriptions(user)[0]diff --git a/zerver/openapi/python_examples.py b/zerver/openapi/python_examples.pyindex b4184388ee3..b837ab35e1e 100644--- a/zerver/openapi/python_examples.py+++ b/zerver/openapi/python_examples.py@@ -1904,6 +1904,20 @@ def update_user_group_members(client: Client, user_group_id: int) -> None:validate_against_openapi_schema(result, "/user_groups/{group_id}/members", "post", "200")+@openapi_test_function("/channels/create:post")+def add_channel(client: Client) -> None:+ # {code_example|start}+ request = {+ "name": "music_group",+ "description": "Channel for discussing and learning about music.",+ "subscribers": [],+ }+ result = client.call_endpoint(url="channels/create", method="POST", request=request)+ # {code_example|end}+ assert_success_response(result)+ validate_against_openapi_schema(result, "/channels/create", "post", "200")++def test_invalid_api_key(client_with_invalid_key: Client) -> None:result = client_with_invalid_key.get_subscriptions()assert_error_response(result, code="UNAUTHORIZED")@@ -2020,6 +2034,7 @@ def test_users(client: Client, owner_client: Client) -> None:def test_streams(client: Client, nonadmin_client: Client) -> None:add_subscriptions(client)+ add_channel(client)test_add_subscriptions_already_subscribed(client)get_subscriptions(client)stream_id = get_stream_id(client)diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex bb571ef44c3..3094b7fe8f8 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -12048,22 +12048,7 @@ paths:type: integerexample: 1send_new_subscription_messages:- description: |- Whether any other users newly subscribed via this request should be- sent a Notification Bot DM notifying them about their new- subscription.-- The server will never send Notification Bot DMs if more than- `max_bulk_new_subscription_messages` (available in the [`POST- /register`](/api/register-queue) response) users were subscribed in- this request.-- **Changes**: Before Zulip 11.0 (feature level 397), new subscribers- were always sent a Notification Bot DM, which was unduly expensive- when bulk-subscribing thousands of users to a channel.- type: boolean- default: true- example: true+ $ref: "#/components/schemas/SendNewSubscriptionMessages"required:- subscriptionsencoding:@@ -23503,6 +23488,221 @@ paths:responses:"200":$ref: "#/components/responses/SimpleSuccess"++ /channels/create:+ post:+ tags: ["channels"]+ operationId: create-channel+ summary: Create a channel+ description: |+ Create a new [channel](/help/create-channels) and optionally+ subscribe users to the newly created channel. The initial [channel settings](/api/update-stream)+ will be determined by the optional parameters, like `invite_only`, detailed below.++ **Changes**: New in Zulip 11.0 (feature level 417). Previously, this was only possible via+ the [`POST /api/subscribe`](/api/subscribe) endpoint, which handled both creation and subscription.+ x-curl-examples-parameters:+ oneOf:+ - type: include+ parameters:+ enum:+ - name+ - subscribers+ requestBody:+ content:+ application/x-www-form-urlencoded:+ schema:+ type: object+ description: |+ An object containing the top-level fields used to create a channel.+ properties:+ name:+ type: string+ description: |+ The name of the new channel.++ Clients should use the `max_stream_name_length` returned by the+ [`POST /register`](/api/register-queue) endpoint to determine+ the maximum channel name length.+ example: "music"+ description:+ type: string+ description: |+ The [description](/help/change-the-channel-description)+ to use for the new channel being created, in text/markdown format.++ Clients should use the `max_stream_description_length` returned+ by the [`POST /register`](/api/register-queue) endpoint to+ determine the maximum channel description length.+ example: "Channel for discussing all things music!"+ subscribers:+ description: |+ A list of user IDs (preferred) or Zulip API email+ addresses of the users to be subscribed to the new channel specified in the `channel` parameter.+ oneOf:+ - type: array+ items:+ type: string+ - type: array+ items:+ type: integer+ example: [16, 12]+ announce:+ description: |+ This determines whether [notification bot](/help/configure-automated-notices)+ will send an announcement about the new channel's creation.+ type: boolean+ default: false+ example: true+ invite_only:+ description: |+ This parameter and the ones+ that follow are used to request an initial configuration of the new channel.++ This parameter determines whether the newly created channel will be+ a private channel.+ type: boolean+ default: false+ example: true+ is_web_public:+ description: |+ This parameter determines whether the newly created channel will be+ a web-public channel.++ Note that creating web-public channels requires the+ `WEB_PUBLIC_STREAMS_ENABLED` [server setting][server-settings]+ to be enabled on the Zulip server in question, the organization+ to have enabled the `enable_spectator_access` realm setting, and+ the current user to have permission under the organization's+ `can_create_web_public_channel_group` realm setting.++ [server-settings]: https://zulip.readthedocs.io/en/stable/production/settings.html+ type: boolean+ default: false+ example: true+ is_default_stream:+ description: |+ This parameter determines whether the newly created channel will be+ added as a [default channel][default-channels] for new users joining+ the organization.++ [default-channels]: /help/set-default-channels-for-new-users+ type: boolean+ default: false+ example: true+ folder_id:+ $ref: "#/components/schemas/FolderId"+ send_new_subscription_messages:+ $ref: "#/components/schemas/SendNewSubscriptionMessages"+ topics_policy:+ $ref: "#/components/schemas/TopicsPolicy"+ history_public_to_subscribers:+ $ref: "#/components/schemas/HistoryPublicToSubscribers"+ message_retention_days:+ $ref: "#/components/schemas/MessageRetentionDays"+ can_add_subscribers_group:+ $ref: "#/components/schemas/ChannelCanAddSubscribersGroup"+ can_delete_any_message_group:+ $ref: "#/components/schemas/CanDeleteAnyMessageGroup"+ can_delete_own_message_group:+ $ref: "#/components/schemas/CanDeleteOwnMessageGroup"+ can_remove_subscribers_group:+ $ref: "#/components/schemas/CanRemoveSubscribersGroup"+ can_administer_channel_group:+ $ref: "#/components/schemas/CanAdministerChannelGroup"+ can_move_messages_out_of_channel_group:+ $ref: "#/components/schemas/CanMoveMessagesOutOfChannelGroup"+ can_move_messages_within_channel_group:+ $ref: "#/components/schemas/CanMoveMessagesWithinChannelGroup"+ can_send_message_group:+ $ref: "#/components/schemas/CanSendMessageGroup"+ can_subscribe_group:+ $ref: "#/components/schemas/CanSubscribeGroup"+ can_resolve_topics_group:+ $ref: "#/components/schemas/CanResolveTopicsGroup"+ required:+ - name+ - subscribers+ encoding:+ announce:+ contentType: application/json+ can_add_subscribers_group:+ contentType: application/json+ can_administer_channel_group:+ contentType: application/json+ can_move_messages_out_of_channel_group:+ contentType: application/json+ can_move_messages_within_channel_group:+ contentType: application/json+ can_remove_subscribers_group:+ contentType: application/json+ can_resolve_topics_group:+ contentType: application/json+ can_send_message_group:+ contentType: application/json+ can_subscribe_group:+ contentType: application/json+ subscribers:+ contentType: application/json+ invite_only:+ contentType: application/json+ is_web_public:+ contentType: application/json+ is_default_stream:+ contentType: application/json+ history_public_to_subscribers:+ contentType: application/json+ folder_id:+ contentType: application/json+ topics_policy:+ contentType: application/json+ required: true++ responses:+ "200":+ description: Success.+ content:+ application/json:+ schema:+ description: "Success response for creating a channel."+ allOf:+ - $ref: "#/components/schemas/JsonSuccessBase"+ - type: object+ additionalProperties: false+ properties:+ result: {}+ msg: {}+ ignored_parameters_unsupported: {}+ id:+ type: integer+ description: "The ID of the newly created channel."+ example: {"result": "success", "msg": "", "id": 50}+ "409":+ description: Bad request.+ content:+ application/json:+ schema:+ description: "Bad request as channel already exists."+ allOf:+ - $ref: "#/components/schemas/CodedError"+ - type: object+ properties:+ result:+ type: string+ example: "error"+ msg:+ type: string+ example: "Channel 'discussions' already exists"+ code:+ type: string+ example: "CHANNEL_ALREADY_EXISTS"+ example:+ {+ result: "error",+ msg: "Channel 'discussions' already exists",+ code: "CHANNEL_ALREADY_EXISTS",+ }+/user_groups/create:post:operationId: create-user-group@@ -28402,6 +28602,23 @@ components:New in Zulip 11.0 (feature level 392).[realm-topics-policy]: /help/require-topics#set-the-default-general-chat-topic-configuration+ SendNewSubscriptionMessages:+ description: |+ Whether any other users newly subscribed via this request should be+ sent a Notification Bot DM notifying them about their new+ subscription.++ The server will never send Notification Bot DMs if more than+ `max_bulk_new_subscription_messages` (available in the [`POST+ /register`](/api/register-queue) response) users were subscribed in+ this request.++ **Changes**: Before Zulip 11.0 (feature level 397), new subscribers+ were always sent a Notification Bot DM, which was unduly expensive+ when bulk-subscribing thousands of users to a channel.+ type: boolean+ default: true+ example: trueChannelCanAddSubscribersGroup:allOf:- $ref: "#/components/schemas/GroupSettingValue"diff --git a/zerver/tests/test_channel_creation.py b/zerver/tests/test_channel_creation.pyindex 1d08bd39d95..31ff60f5289 100644--- a/zerver/tests/test_channel_creation.py+++ b/zerver/tests/test_channel_creation.py@@ -31,7 +31,7 @@ from zerver.models import ()from zerver.models.groups import SystemGroupsfrom zerver.models.realms import get_realm-from zerver.models.streams import get_stream+from zerver.models.streams import StreamTopicsPolicyEnum, get_streamfrom zerver.models.users import active_non_guest_user_ids@@ -269,6 +269,310 @@ class TestCreateStreams(ZulipTestCase):)self.assert_json_error(result, "A default channel cannot be private.")+ def test_create_stream_using_add_channel(self) -> None:+ user_profile = self.example_user("iago")+ result = self.create_channel_via_post(user_profile, name="basketball")+ self.assert_json_success(result)+ stream = get_stream("basketball", user_profile.realm)+ self.assertEqual(stream.name, "basketball")++ cordelia = self.example_user("cordelia")+ nobody_group = NamedUserGroup.objects.get(+ name=SystemGroups.NOBODY, realm=cordelia.realm, is_system_group=True+ )++ channel_folder = check_add_channel_folder(+ user_profile.realm, "sports", "", acting_user=user_profile+ )+ result = self.create_channel_via_post(+ user_profile,+ name="testchannel",+ extra_post_data=dict(+ description="test channel",+ can_administer_channel_group=orjson.dumps(+ {+ "direct_members": [cordelia.id],+ "direct_subgroups": [nobody_group.id],+ }+ ).decode(),+ folder_id=orjson.dumps(channel_folder.id).decode(),+ ),+ )+ self.assert_json_success(result)+ stream = get_stream("testchannel", user_profile.realm)+ self.assertEqual(stream.name, "testchannel")+ self.assertEqual(stream.description, "test channel")++ # Creating an existing channel should return an error.+ result = self.create_channel_via_post(user_profile, name="basketball")+ self.assert_json_error(result, "Channel 'basketball' already exists", status_code=409)++ # Test creating channel with no subscribers+ post_data = {+ "name": "no-sub-channel",+ "subscribers": orjson.dumps([]).decode(),+ }++ result = self.api_post(+ user_profile,+ "/api/v1/channels/create",+ post_data,+ intentionally_undocumented=True,+ )+ self.assert_json_success(result)+ stream = get_stream("no-sub-channel", user_profile.realm)+ self.assertEqual(stream.name, "no-sub-channel")+ self.assertEqual(stream.subscriber_count, 0)++ def test_channel_creation_miscellaneous(self) -> None:+ iago = self.example_user("iago")+ desdemona = self.example_user("desdemona")+ cordelia = self.example_user("cordelia")++ result = self.create_channel_via_post(+ iago, extra_post_data={"message_retention_days": orjson.dumps(10).decode()}+ )+ self.assert_json_error(result, "Must be an organization owner")++ result = self.create_channel_via_post(+ desdemona,+ [iago.id],+ name="new_channel",+ extra_post_data={"message_retention_days": orjson.dumps(10).decode()},+ )+ self.assert_json_success(result)+ stream = get_stream("new_channel", desdemona.realm)+ self.assertEqual(stream.name, "new_channel")+ self.assertEqual(stream.message_retention_days, 10)++ # Default streams can only be created by admins+ result = self.create_channel_via_post(+ iago,+ name="testing_channel1",+ extra_post_data={"is_default_stream": orjson.dumps(True).decode()},+ invite_only=True,+ )+ self.assert_json_error(result, "A default channel cannot be private.")++ result = self.create_channel_via_post(+ iago,+ name="testing_channel1",+ extra_post_data={"is_default_stream": orjson.dumps(True).decode()},+ invite_only=False,+ )+ self.assert_json_success(result)+ stream = get_stream("testing_channel1", iago.realm)+ self.assertEqual(stream.name, "testing_channel1")+ self.assertTrue(stream.id in get_default_stream_ids_for_realm(iago.realm.id))++ # Only org owners can create web public streams by default, if they are enabled.+ with self.settings(WEB_PUBLIC_STREAMS_ENABLED=False):+ self.assertFalse(desdemona.realm.has_web_public_streams())+ result = self.create_channel_via_post(+ desdemona,+ name="testing_web_public_channel",+ is_web_public=True,+ )+ self.assert_json_error(result, "Web-public channels are not enabled.")++ with self.settings(WEB_PUBLIC_STREAMS_ENABLED=True):+ self.assertTrue(desdemona.realm.has_web_public_streams())+ result = self.create_channel_via_post(+ desdemona,+ name="testing_web_public_channel",+ is_web_public=True,+ )+ self.assert_json_success(result)+ stream = get_stream("testing_web_public_channel", desdemona.realm)+ self.assertEqual(stream.name, "testing_web_public_channel")++ polonius = self.example_user("polonius")+ result = self.create_channel_via_post(+ polonius,+ name="testing_channel4",+ invite_only=True,+ )+ self.assert_json_error(result, "Not allowed for guest users")++ # topics policy+ owners = NamedUserGroup.objects.get(+ name=SystemGroups.OWNERS, realm=cordelia.realm, is_system_group=True+ )+ do_change_realm_permission_group_setting(+ cordelia.realm, "can_set_topics_policy_group", owners, acting_user=None+ )+ self.assertTrue(desdemona.can_set_topics_policy())+ self.assertFalse(cordelia.can_set_topics_policy())+ result = self.create_channel_via_post(+ cordelia,+ name="testing_channel4",+ extra_post_data={+ "topics_policy": orjson.dumps(+ StreamTopicsPolicyEnum.disable_empty_topic.name+ ).decode()+ },+ )+ self.assert_json_error(result, "Insufficient permission")++ result = self.create_channel_via_post(+ desdemona,+ name="testing_channel4",+ extra_post_data={+ "topics_policy": orjson.dumps(+ StreamTopicsPolicyEnum.disable_empty_topic.name+ ).decode()+ },+ )+ self.assert_json_success(result)+ stream = get_stream("testing_channel4", desdemona.realm)+ self.assertEqual(stream.name, "testing_channel4")+ self.assertEqual(stream.topics_policy, StreamTopicsPolicyEnum.disable_empty_topic.value)++ realm = get_realm("zephyr")+ starnine = self.mit_user("starnine")+ espuser = self.mit_user("espuser")+ result = self.create_channel_via_post(+ starnine, [espuser.id], name="zephyr_channel", subdomain="zephyr"+ )+ self.assert_json_error(+ result, "You can only invite other Zephyr mirroring users to private channels."+ )++ result = self.create_channel_via_post(+ starnine, [espuser.id], name="zephyr_channel", invite_only=True, subdomain="zephyr"+ )+ self.assert_json_success(result)+ stream = get_stream("zephyr_channel", realm)+ self.assertEqual(stream.name, "zephyr_channel")++ def _test_group_based_settings_for_creating_channels(+ self,+ stream_policy: str,+ *,+ invite_only: bool,+ is_web_public: bool,+ ) -> None:+ def check_permission_to_create_channel(+ user: UserProfile, stream_name: str, *, expect_fail: bool = False+ ) -> None:+ result = self.create_channel_via_post(+ user,+ name=stream_name,+ invite_only=invite_only,+ is_web_public=is_web_public,+ )+ if expect_fail:+ self.assert_json_error(result, "Insufficient permission")+ return++ self.assert_json_success(result)+ self.assertTrue(+ Stream.objects.filter(name=stream_name, realm_id=user.realm.id).exists()+ )++ cordelia = self.example_user("cordelia")+ iago = self.example_user("iago")+ desdemona = self.example_user("desdemona")++ # System groups case+ nobody_group = NamedUserGroup.objects.get(+ name=SystemGroups.NOBODY, realm=cordelia.realm, is_system_group=True+ )+ do_change_realm_permission_group_setting(+ cordelia.realm, stream_policy, nobody_group, acting_user=None+ )++ check_permission_to_create_channel(+ cordelia,+ "testing_channel_group_permission1",+ expect_fail=True,+ )++ check_permission_to_create_channel(+ iago, "testing_channel_group_permission1", expect_fail=True+ )++ member_group = NamedUserGroup.objects.get(+ name=SystemGroups.MEMBERS, realm=cordelia.realm, is_system_group=True+ )+ do_change_realm_permission_group_setting(+ cordelia.realm, stream_policy, member_group, acting_user=None+ )+ check_permission_to_create_channel(+ cordelia,+ "testing_channel_group_permission1",+ )++ check_permission_to_create_channel(iago, "testing_channel_group_permission2")++ admin_group = NamedUserGroup.objects.get(+ name=SystemGroups.ADMINISTRATORS, realm=cordelia.realm, is_system_group=True+ )+ do_change_realm_permission_group_setting(+ cordelia.realm, stream_policy, admin_group, acting_user=None+ )+ check_permission_to_create_channel(+ cordelia,+ "testing_channel_group_permission3",+ expect_fail=True,+ )+ check_permission_to_create_channel(iago, "testing_channel_group_permission3")++ # User defined group case+ leadership_group = check_add_user_group(+ cordelia.realm, "Leadership", [desdemona], acting_user=desdemona+ )+ do_change_realm_permission_group_setting(+ cordelia.realm, stream_policy, leadership_group, acting_user=None+ )+ check_permission_to_create_channel(+ cordelia,+ "testing_channel_group_permission4",+ expect_fail=True,+ )+ check_permission_to_create_channel(+ desdemona,+ "testing_channel_group_permission4",+ )++ # Anonymous group case+ staff_group = check_add_user_group(cordelia.realm, "Staff", [iago], acting_user=iago)+ setting_group = self.create_or_update_anonymous_group_for_setting([cordelia], [staff_group])+ do_change_realm_permission_group_setting(+ cordelia.realm, stream_policy, setting_group, acting_user=None+ )+ check_permission_to_create_channel(+ desdemona,+ "testing_channel_group_permission5",+ expect_fail=True,+ )+ check_permission_to_create_channel(iago, "testing_channel_group_permission5")+ check_permission_to_create_channel(+ cordelia,+ "testing_channel_group_permission6",+ )++ def test_group_based_permisions_for_creating_private_streams(self) -> None:+ self._test_group_based_settings_for_creating_channels(+ "can_create_private_channel_group",+ invite_only=True,+ is_web_public=False,+ )++ def test_group_based_permisions_for_creating_public_streams(self) -> None:+ self._test_group_based_settings_for_creating_channels(+ "can_create_public_channel_group",+ invite_only=False,+ is_web_public=False,+ )++ def test_group_based_permisions_for_creating_web_public_streams(self) -> None:+ self._test_group_based_settings_for_creating_channels(+ "can_create_web_public_channel_group",+ invite_only=False,+ is_web_public=True,+ )+def test_history_public_to_subscribers_zephyr_realm(self) -> None:realm = get_realm("zephyr")diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.pyindex a8af35b3950..1755a9856ac 100644--- a/zerver/tests/test_subs.py+++ b/zerver/tests/test_subs.py@@ -1439,9 +1439,9 @@ class StreamAdminTest(ZulipTestCase):result = self.client_patch(f"/json/streams/{stream.id}", {"new_name": "stream_name1"})self.assert_json_error(result, "Channel already has that name.")result = self.client_patch(f"/json/streams/{stream.id}", {"new_name": "Denmark"})- self.assert_json_error(result, "Channel name is already in use.")+ self.assert_json_error(result, "Channel 'Denmark' already exists", status_code=409)result = self.client_patch(f"/json/streams/{stream.id}", {"new_name": "denmark "})- self.assert_json_error(result, "Channel name is already in use.")+ self.assert_json_error(result, "Channel 'denmark' already exists", status_code=409)# Do a rename that is case-only--this should succeed.result = self.client_patch(f"/json/streams/{stream.id}", {"new_name": "sTREAm_name1"})diff --git a/zerver/views/streams.py b/zerver/views/streams.pyindex 97d5d65cf77..7a2a950a351 100644--- a/zerver/views/streams.py+++ b/zerver/views/streams.py@@ -74,8 +74,10 @@ from zerver.lib.streams import (access_stream_for_delete_or_update_requiring_metadata_access,access_web_public_stream,channel_events_topic_name,+ check_channel_creation_permissions,check_stream_name_available,check_zephyr_realm_invite_conditions,+ create_stream_if_needed,do_get_streams,filter_stream_authorization_for_adding_subscribers,get_anonymous_group_membership_dict_for_streams,@@ -710,6 +712,138 @@ def access_requested_group_permissions(return group_settings_map, anonymous_group_membership[email protected](savepoint=False)+@require_non_guest_user+@typed_endpoint+def create_channel(+ request: HttpRequest,+ user_profile: UserProfile,+ *,+ announce: Json[bool] = False,+ can_add_subscribers_group: Json[int | UserGroupMembersData] | None = None,+ can_delete_any_message_group: Json[int | UserGroupMembersData] | None = None,+ can_delete_own_message_group: Json[int | UserGroupMembersData] | None = None,+ can_administer_channel_group: Json[int | UserGroupMembersData] | None = None,+ can_move_messages_out_of_channel_group: Json[int | UserGroupMembersData] | None = None,+ can_move_messages_within_channel_group: Json[int | UserGroupMembersData] | None = None,+ can_remove_subscribers_group: Json[int | UserGroupMembersData] | None = None,+ can_resolve_topics_group: Json[int | UserGroupMembersData] | None = None,+ can_send_message_group: Json[int | UserGroupMembersData] | None = None,+ can_subscribe_group: Json[int | UserGroupMembersData] | None = None,+ description: ChannelDescription = None,+ folder_id: Json[int] | None = None,+ history_public_to_subscribers: Json[bool] | None = None,+ invite_only: Json[bool] = False,+ is_web_public: Json[bool] = False,+ is_default_stream: Json[bool] = False,+ message_retention_days: Json[str] | Json[int] = RETENTION_DEFAULT,+ name: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)],+ send_new_subscription_messages: Json[bool] = True,+ subscribers: Json[list[str] | list[int]],+ topics_policy: Json[TopicsPolicy] = None,+) -> HttpResponse:+ realm = user_profile.realm+ request_settings_dict = locals()++ check_stream_name_available(realm, name)++ folder: ChannelFolder | None = None+ if folder_id is not None:+ folder = get_channel_folder_by_id(folder_id, realm)++ if description is None:+ description = ""++ parsed_message_retention_days = parse_message_retention_days(+ message_retention_days, Stream.MESSAGE_RETENTION_SPECIAL_VALUES_MAP+ )++ topics_policy_value = None+ validated_topics_policy = validate_topics_policy(topics_policy, user_profile)+ if validated_topics_policy is not None:+ topics_policy_value = validated_topics_policy.value++ is_subscribing_other_users = False+ if len(subscribers) > 0 and not all(user_id == user_profile.id for user_id in subscribers):+ is_subscribing_other_users = True++ check_zephyr_realm_invite_conditions(is_subscribing_other_users, realm, invite_only)++ check_channel_creation_permissions(+ user_profile,+ is_default_stream=is_default_stream,+ invite_only=invite_only,+ is_web_public=is_web_public,+ message_retention_days=parsed_message_retention_days,+ )++ group_settings_map, anonymous_group_membership = access_requested_group_permissions(+ user_profile,+ realm,+ request_settings_dict,+ )++ new_channel, created = create_stream_if_needed(+ realm,+ name,+ stream_description=description,+ invite_only=invite_only,+ history_public_to_subscribers=history_public_to_subscribers,+ is_web_public=is_web_public,+ message_retention_days=parsed_message_retention_days,+ anonymous_group_membership=anonymous_group_membership,+ acting_user=user_profile,+ can_add_subscribers_group=group_settings_map["can_add_subscribers_group"],+ can_administer_channel_group=group_settings_map["can_administer_channel_group"],+ can_move_messages_out_of_channel_group=group_settings_map[+ "can_move_messages_out_of_channel_group"+ ],+ can_move_messages_within_channel_group=group_settings_map[+ "can_move_messages_within_channel_group"+ ],+ can_send_message_group=group_settings_map["can_send_message_group"],+ can_remove_subscribers_group=group_settings_map["can_remove_subscribers_group"],+ can_subscribe_group=group_settings_map["can_subscribe_group"],+ can_resolve_topics_group=group_settings_map["can_resolve_topics_group"],+ folder=folder,+ topics_policy=topics_policy_value,+ )++ if is_default_stream:+ do_add_default_stream(new_channel)++ if len(subscribers) == 0:+ return json_success(+ request,+ data={"id": new_channel.id},+ )++ new_subscribers = bulk_principals_to_user_profiles(subscribers, user_profile)+ bulk_add_subscriptions(+ realm,+ [new_channel],+ new_subscribers,+ acting_user=user_profile,+ )+ if (+ send_new_subscription_messages+ and len(new_subscribers) <= settings.MAX_BULK_NEW_SUBSCRIPTION_MESSAGES+ ):+ send_messages_for_new_subscribers(+ user_profile=user_profile,+ subscribers=new_subscribers,+ new_subscriptions={str(user.id): [name] for user in new_subscribers},+ id_to_user_profile={str(user.id): user for user in new_subscribers},+ created_streams=[new_channel],+ announce=announce,+ )++ return json_success(+ request,+ data={"id": new_channel.id},+ )++@transaction.atomic(savepoint=False)@require_non_guest_user@typed_endpointdiff --git a/zproject/urls.py b/zproject/urls.pyindex de7ce591887..ea27f73a42f 100644--- a/zproject/urls.py+++ b/zproject/urls.py@@ -188,6 +188,7 @@ from zerver.views.storage import get_storage, remove_storage, update_storagefrom zerver.views.streams import (add_default_stream,add_subscriptions_backend,+ create_channel,create_default_stream_group,deactivate_stream_backend,delete_in_topic,@@ -531,6 +532,7 @@ v1_api_and_json_patterns = [# streams -> zerver.views.streams# (this API is only used externally)rest_path("streams", GET=get_streams_backend),+ rest_path("channels/create", POST=create_channel),# GET returns `stream_id`, stream name should be encoded in the URL query (in `stream` param)rest_path("get_stream_id", GET=json_get_stream_id),# GET returns "stream info" (undefined currently?), HEAD returns whether stream exists (200 or 404)