mattermost-mobile-upstream/detox/e2e/support/server_api/channel.ts
Pablo Vélez 4d842026f6
Some checks failed
ci / lint-typecheck (push) Has been cancelled
ci / detox-lint-typecheck (push) Has been cancelled
ci / test (push) Has been cancelled
CodeQL / Analyze (javascript) (push) Has been cancelled
Mm 70564 channel labels use in channel creation (#10146)
* MM-70516 - Add ability to edit channel attribute values from Channel Info

* Add API methods for patching property fields and setting channel attribute requirements

* Update channel attribute clearing behavior for required and non-required fields

* MM-70564 - use channel attributes on channel creation

* Fix undefined propertyValues and ternary formatting in channel attributes

* Fix spelling of "colour" to "color" in attribute chip tests and related comments

* Add visibility checks for channel attribute labels in tests

* Fix data-integrity, permission, and accessibility issues in channel attributes: scoped pruning, atomic writes, race serialization, required clear/stale-option guards

* Fix handling of null values in apiGetChannelAttributeValue and update test assertions for channel attributes

* Improve channel attribute editor sizing for long labels, keep Save visible, and prevent keyboard overlap on Android

* Address CodeRabbit feedback for nullable values, bottom-sheet state, async validation, and reliable E2E cleanup

* lock-safe field fetch, create-time gate recheck, scoped value pruning, and tappable header chips

* Address CodeRabbit feedback: drop queued attribute saves on channel switch and use page object selectors in E2E

* Respect the ChannelAttributesRequired flag on channel creation and enable it for channel attribute E2E

* Skip required channel attribute E2E tests and stop enabling ChannelAttributesRequired on the shared server until  they move to SITE_3

* Fix clearing channel attributes on iOS by sending an empty value instead of null, and stop E2E suites from turning  off the ChannelAttributes flag mid-run

* Refactor getEmptyPropertyValue to accept string type for fieldType parameter

* E2E: give channel attribute test fields a suite-unique suffix

Pool shards may only create optional property fields named <name>_<6 hex>; fixed names were blocked by the pool guard.

* E2E: restore channel attribute cleanup checks; name network error codes

Brings back the PR's afterEach/afterAll error handling that the main merge replaced, and makes a no-response error show its codes (an AggregateError has an empty message).

* E2E: run channel attribute creation and editing specs on server B

Their 11 required-attribute tests could not run on the shared servers. Both specs now run on the mutation server with ChannelAttributesRequired on for their run, and the tests are re-enabled. setChannelAttributesRequired moves to the shared helper.

* Check header chips instead of their wrapper and use toExist for the create screen in channel attribute E2E

---------

Co-authored-by: yasserfaraazkhan <attitude3cena.yf@gmail.com>
2026-10-30 15:03:55 +01:00

365 lines
14 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {capitalize, getRandomId} from '@support/utils';
import {withTransportRetry} from '@support/utils/transport_retry';
import client from './client';
import {getResponseFromError} from './common';
// ****************************************************************
// Channels
// See https://api.mattermost.com/#tag/channels
//
// Exported API function should have the following:
// - documented using JSDoc
// - meaningful description
// - match the referenced API endpoints
// - parameter/s defined by `@param`
// - return value defined by `@return`
// ****************************************************************
/**
* Add user to channel.
* See https://api.mattermost.com/#operation/AddChannelMember
* @param {string} baseUrl - the base server URL
* @param {string} userId - The ID of user to add into the channel
* @param {string} channelId - The channel ID
* @return {Object} returns {member} on success or {error, status} on error
*/
export const apiAddUserToChannel = async (baseUrl: string, userId: string, channelId: string): Promise<any> => {
try {
const response = await client.post(
`${baseUrl}/api/v4/channels/${channelId}/members`,
{user_id: userId},
);
return {member: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Create a channel.
* See https://api.mattermost.com/#operation/CreateChannel
* @param {string} baseUrl - the base server URL
* @param {string} option.teamId - The team ID of the team to create the channel on
* @param {string} option.type - 'O' (default) for a public channel, 'P' for a private channel
* @param {string} option.prefix - prefix to name, display name, purpose, and header
* @param {Object} option.channel - channel object to be created
* @return {Object} returns {channel} on success or {error, status} on error
*/
export const apiCreateChannel = async (baseUrl: string, {teamId = null, type = 'O', prefix = 'channel', channel = null, propertyValues = undefined}: any = {}): Promise<any> => {
// No retry loop here. Creating a channel is not idempotent, and apiInit's
// retryTransient is the single retry owner for this call — a local loop on top of
// it multiplied one stalled request into more than a whole beforeAll budget. The
// empty-body check stays: a 200 with no id is a real failure, not a transport one.
const channelData = channel || generateRandomChannel(teamId, type, prefix);
// A create whose response is lost still leaves the channel on the server, and the caller
// then reads `.channel` as undefined and dies on `.id` many lines later. Read the name back
// before reporting a failure, rather than replaying a non-idempotent write. Only for
// failures where the write may still have landed: a 4xx is the server rejecting it, so
// that answer is final and is returned as-is.
const recoverByName = async (failure: any) => {
const status = failure?.status ?? 0;
const mayHaveLanded = status === 0 || status >= 500;
if (!mayHaveLanded || !teamId || !channelData?.name) {
return failure;
}
const {channel: existing} = await apiGetChannelByName(baseUrl, teamId, channelData.name);
return existing?.id ? {channel: existing} : failure;
};
try {
const body = propertyValues === undefined ? channelData : {...channelData, property_values: propertyValues};
const response = await client.post(`${baseUrl}/api/v4/channels`, body);
if (response.data?.id) {
return {channel: response.data};
}
return recoverByName({error: {message: 'empty channel in create response'}, status: response.status ?? 0});
} catch (err) {
return recoverByName(getResponseFromError(err));
}
};
/**
* Create a direct message channel.
* See https://api.mattermost.com/#operation/CreateDirectChannel
* @param {string} baseUrl - the base server URL
* @param {Array} userIds - the two user IDs to be in the direct message
* @return {Object} returns {channel} on success or {error, status} on error
*/
export const apiCreateDirectChannel = async (baseUrl: string, userIds: string[] = []): Promise<any> => {
// Idempotent: the endpoint calls App.GetOrCreateDirectChannel, so replaying a request whose
// response was lost returns the same channel rather than creating a second one. Worth
// retrying because a lost response here surfaces far from its cause -- the caller reads
// `.channel` as undefined and dies with "Cannot read properties of undefined" many lines
// later, which reads like a UI defect (MM-T4929_3).
return withTransportRetry(async () => {
try {
const response = await client.post(
`${baseUrl}/api/v4/channels/direct`,
userIds,
);
if (response.data?.id) {
return {channel: response.data};
}
return {error: {message: 'empty channel in create direct response'}, status: response.status ?? 0};
} catch (err) {
return getResponseFromError(err);
}
}, {idempotent: true, label: 'apiCreateDirectChannel'});
};
/**
* Create a group message channel.
* See https://api.mattermost.com/#operation/CreateGroupChannel
* @param {string} baseUrl - the base server URL
* @param {Array} userIds - user IDs to be in the group message channel
* @return {Object} returns {channel} on success or {error, status} on error
*/
export const apiCreateGroupChannel = async (baseUrl: string, userIds: string[] = []): Promise<any> => {
// Idempotent for the same reason as the direct channel above: App.CreateGroupChannel
// returns the existing channel on ChannelExistsError instead of failing.
return withTransportRetry(async () => {
try {
const response = await client.post(
`${baseUrl}/api/v4/channels/group`,
userIds,
);
if (response.data?.id) {
return {channel: response.data};
}
return {error: {message: 'empty channel in create group response'}, status: response.status ?? 0};
} catch (err) {
return getResponseFromError(err);
}
}, {idempotent: true, label: 'apiCreateGroupChannel'});
};
/**
* Delete a channel.
* See https://api.mattermost.com/#operation/DeleteChannel
* @param {string} baseUrl - the base server URL
* @param {string} channelId - The channel ID to be deleted
* @return {Object} returns {deleted} on success or {error, status} on error
*/
export const apiDeleteChannel = async (baseUrl: string, channelId: string): Promise<any> => {
try {
const response = await client.delete(`${baseUrl}/api/v4/channels/${channelId}`);
return {deleted: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Get a channel by name.
* See https://api.mattermost.com/#operation/GetChannelByName
* @param {string} baseUrl - the base server URL
* @param {string} teamId - team ID
* @param {string} channelName - channel name
* @return {Object} returns {channel} on success or {error, status} on error
*/
export const apiGetChannelByName = async (baseUrl: string, teamId: string, channelName: string): Promise<any> => {
try {
const response = await client.get(`${baseUrl}/api/v4/teams/${teamId}/channels/name/${channelName}`);
return {channel: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Get a channel by name and team name.
* See https://api.mattermost.com/#operation/GetChannelByNameForTeamName
* @param {string} baseUrl - the base server URL
* @param {string} teamName - team name
* @param {string} channelName - channel name
* @return {Object} returns {channel} on success or {error, status} on error
*/
export const apiGetChannelByNameAndTeamName = async (baseUrl: string, teamName: string, channelName: string): Promise<any> => {
try {
const response = await client.get(`${baseUrl}/api/v4/teams/name/${teamName}/channels/name/${channelName}`);
return {channel: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Get channels for user.
* See https://api.mattermost.com/#operation/GetChannelsForTeamForUser
* @param {string} baseUrl - the base server URL
* @param {string} userId - The user ID
* @param {string} teamId - The team ID the user belongs to
* @return {Object} returns {channels} on success or {error, status} on error
*/
export const apiGetChannelsForUser = async (baseUrl: string, userId: string, teamId: string): Promise<any> => {
try {
const response = await client.get(`${baseUrl}/api/v4/users/${userId}/teams/${teamId}/channels`);
return {channels: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Get unread messages.
* See https://api.mattermost.com/#operation/GetChannelUnread
* @param {string} baseUrl - the base server URL
* @param {string} userId - The user ID to perform view actions for
* @param {string} channelId - The channel ID that is being viewed
* @return {Object} returns response on success or {error, status} on error
*/
export const apiGetUnreadMessages = async (baseUrl: string, userId: string, channelId: string): Promise<any> => {
try {
return await client.get(`${baseUrl}/api/v4/users/${userId}/channels/${channelId}/unread`);
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Restore a channel.
* See https://api.mattermost.com/#operation/RestoreChannel
* @param {string} baseUrl - the base server URL
* @param {string} channelId - The channel ID to be restored
* @return {Object} returns {restored} on success or {error, status} on error
*/
export const apiRestoreChannel = async (baseUrl: string, channelId: string): Promise<any> => {
try {
const response = await client.post(`${baseUrl}/api/v4/channels/${channelId}/restore`);
return {restored: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Remove user from channel.
* See https://api.mattermost.com/#operation/RemoveUserFromChannel
* @param {string} baseUrl - the base server URL
* @param {string} channelId - The channel ID
* @param {string} userId - The user ID to be removed from channel
* @return {Object} returns {status} on success or {error, status} on error
*/
export const apiRemoveUserFromChannel = async (baseUrl: string, channelId: string, userId: string): Promise<any> => {
try {
const response = await client.delete(
`${baseUrl}/api/v4/channels/${channelId}/members/${userId}`,
);
return {status: response.status};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* View channel.
* See https://api.mattermost.com/#operation/ViewChannel
* @param {string} baseUrl - the base server URL
* @param {string} userId - The user ID to perform view actions for
* @param {string} channelId - The channel ID that is being viewed
* @return {Object} returns {viewed} on success or {error, status} on error
*/
export const apiViewChannel = async (baseUrl: string, userId: string, channelId: string): Promise<any> => {
try {
const response = await client.post(
`${baseUrl}/api/v4/channels/members/${userId}/view`,
{channel_id: channelId},
);
return {viewed: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Update a channel member's scheme roles (promote to or demote from channel admin).
* See https://api.mattermost.com/#operation/UpdateChannelMemberSchemeRoles
* @param {string} baseUrl - the base server URL
* @param {string} userId - The user ID
* @param {string} channelId - The channel ID
* @param {boolean} schemeAdmin - true to grant channel admin; false to revoke
* @return {Object} returns {} on success or {error, status} on error
*/
export const apiUpdateChannelMemberSchemeRoles = async (baseUrl: string, userId: string, channelId: string, schemeAdmin: boolean): Promise<any> => {
try {
await client.put(
`${baseUrl}/api/v4/channels/${channelId}/members/${userId}/schemeRoles`,
{scheme_admin: schemeAdmin, scheme_user: true},
);
return {};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Share channel with a remote (connected workspace).
* POST /api/v4/remotecluster/{remoteId}/channels/{channelId}/invite
* @param {string} baseUrl - the base server URL
* @param {string} channelId - The channel ID to share with the remote
* @param {string} remoteId - The remote cluster ID (connected workspace)
* @return {Object} returns {} on success or {error, status} on error
*/
export const apiShareChannelWithRemote = async (
baseUrl: string,
channelId: string,
remoteId: string,
): Promise<{error?: {message: string}; status?: number}> => {
try {
await client.post(
`${baseUrl}/api/v4/remotecluster/${encodeURIComponent(remoteId)}/channels/${channelId}/invite`,
);
return {};
} catch (err) {
return getResponseFromError(err);
}
};
export const generateRandomChannel = (teamId: string, type: string, prefix: string) => {
const randomId = getRandomId();
return {
team_id: teamId,
name: `${prefix}-${randomId}`,
display_name: `${capitalize(prefix)} ${randomId}`,
type,
purpose: `Channel purpose: ${prefix} ${randomId}`,
header: `Channel header: ${prefix} ${randomId}`,
};
};
export const Channel = {
apiAddUserToChannel,
apiCreateChannel,
apiCreateDirectChannel,
apiCreateGroupChannel,
apiDeleteChannel,
apiGetChannelByName,
apiGetChannelsForUser,
apiGetUnreadMessages,
apiRestoreChannel,
apiRemoveUserFromChannel,
apiShareChannelWithRemote,
apiUpdateChannelMemberSchemeRoles,
apiViewChannel,
generateRandomChannel,
};
export default Channel;