mattermost-mobile-upstream/detox/e2e/support/server_api/post.ts
Pablo Vélez 7df4a0ab97
Some checks are pending
ci / lint-typecheck (push) Waiting to run
ci / detox-lint-typecheck (push) Waiting to run
ci / test (push) Waiting to run
Mm 68219 show placeholder for redacted files (#9719)
* MM-68219 - Add redacted files placeholder and related functionality

* add feature flag control and e2e tests

* adjust placeholder design, polish code, fix permalink preview issue

* polish code and add missing test

* use import path with right path

* gate post refetch behind the feature flag, refetch the open thread and avoid observeCount

* restore filesInfo for the permalink files prop added upstream

* fix stale redaction on background servers, consume the flag on every fetch path and share the viewport emitter

* replace the in-memory redaction flag with a persisted per-post epoch so ABAC file decisions survive restarts and stale posts stay hidden

* raise the redaction epoch on every resync, capture the epoch counter, only invalidate channels on role changes, and store the newer epoch when a re-verified post is otherwise unchanged

* store superseded responses unverified instead of dropping them, keep the since-fetch when re-verifying, verify permalink embeds against the linked channel, and capture the websocket epoch on arrival

* nvalidate file decisions when a user attribute field changes or all its values are cleared

* batch channel invalidations, close file viewers only when affected, reset the epoch on unstamped redaction changes, and only  re-verify the newest page's attachment posts

* re-check older channel posts a page at a time instead of one request per post

* skip the unstamped epoch lookup for posts with no files, redacted count or permalink

* keep the attribute-view retry after later invalidations, retry linked posts unless refused for the current epoch, and stop older payloads from rolling back edits via the redaction check

* MM-70905 - disable and grey out the attachment button when an ABAC pe… (#10195)

* MM-70905 - disable and grey out the attachment button when an ABAC permission policy denies uploads in the channel

* only back off render permission fetches when the server request fails, and log other errors without retrying

* remove the disableServer helper and have removeServer do both steps

* split defaultAllowed into allowWhenUnenforced and allowWhenNotEvaluated, and treat render permissions as unenforced  on servers without the decisions API

* MM-69627: Add playbook task requirements support on mobile (#10035)

* MM-69627: Add playbook task requirements support on mobile

Allow filling required task fields when checking off checklist items during
a run, gated by the same Playbooks beta setting used on web.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Address PR review feedback for task requirements

Propagate settings write failures, harden fill-requirements save/title handling, and add missing unit coverage.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Fix TypeScript errors in new unit tests

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Use defineMessages for fill requirements titles

Keep i18n extraction able to find the header titles after moving them to the route.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Address review feedback for task requirements

Update checklist items locally when saving requirement values instead of
refetching the run, add missing query/navigation tests, and apply small
callback/reduce cleanups from review.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Fix task requirements review follow-ups

Propagate local checklist write failures, clear a stale task-requirements
flag when playbooks is unsupported, and cap fill values at the desktop/
server max length.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Move requirement field into its own component

Keep one component per file on the fill-requirements screen.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69122: Add file element support to interactive dialogs (#9898)

* Implement Interactive Dialog - file upload

* update demo plugin version for e2etests

* fix and add e2etests

* review fixes

* Fix version bump checkout when a tag shares the branch name (#10229)

* Fix Android crashes caused by animated custom emoji (#10030)

* Route GIF decoding through Glide

- Keep APNG4Android for APNG, animated WebP, and animated AVIF support.
- Prepend Glide's GIF decoders to avoid APNG4Android's native GIF overflow.

* Clear Expo image resources with Glide targets

- Detach drawables when Glide clears their custom target.
- Prevent recycled GIF frame resources from remaining attached to Expo image views.

* Preserve foreground image during GIF target recycling

---------

Co-authored-by: Asaad Mahmood <asaadmahmood@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Scott Bishel <scott.bishel@mattermost.com>
Co-authored-by: Nuno Simões <nuno.simoes@mattermost.com>
Co-authored-by: MangelSpec <74370284+MangelSpec@users.noreply.github.com>

* detox - fix clobbering of feature flags that cause failures in other suites.  Also small fix of a incorrectly set test-id

---------

Co-authored-by: Asaad Mahmood <asaadmahmood@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Scott Bishel <scott.bishel@mattermost.com>
Co-authored-by: Nuno Simões <nuno.simoes@mattermost.com>
Co-authored-by: MangelSpec <74370284+MangelSpec@users.noreply.github.com>
Co-authored-by: Nate Schlossberg <nate.schlossberg@mattermost.com>
2026-10-15 15:59:13 -07:00

532 lines
19 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import path from 'path';
import {timeouts, wait} from '@support/utils';
import {withTransportRetry} from '@support/utils/transport_retry';
import client from './client';
import {apiUploadFile, getResponseFromError} from './common';
/**
* Create a new post in a channel. To create the post as a comment on another post, provide root_id.
* See https://api.mattermost.com/#operation/CreatePost
* @param {string} baseUrl - the base server URL
* @param {string} option.channelId - The channel ID to post in
* @param {string} option.message - The message contents, can be formatted with Markdown
* @param {string} option.rootId - The post ID to comment on
* @param {Object} option.props - A general object property bag to attach to the post
* @param {string[]=} option.fileIds - Optional array of file IDs to attach to the post (top-level API field)
* @param {number} option.createAt - The post creation timestamp in milliseconds since epoch, defaults to 0
* @param {boolean} option.retryOnTransportFailure - replay the POST when the connection drops
* before a response arrives. Off by default: a dropped response is ambiguous, so a replay can
* leave a duplicate post behind. Opt in only where a duplicate is harmless for the caller, and
* say why at the call site.
* @return {Object} returns {post} on success. Throws on error (never returns {error}).
*/
export const apiCreatePost = async (baseUrl: string, {channelId, message, rootId, props = {}, fileIds, createAt = 0, retryOnTransportFailure = false}: any): Promise<any> => {
const attempt = async (): Promise<any> => {
try {
const payload: Record<string, any> = {
channel_id: channelId,
message,
root_id: rootId,
props,
create_at: createAt,
};
if (fileIds?.length) {
payload.file_ids = fileIds;
}
const response = await client.post(`${baseUrl}/api/v4/posts`, payload);
return {post: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
const result = await withTransportRetry(attempt, {
idempotent: false,
allowDuplicateWrites: retryOnTransportFailure,
label: 'apiCreatePost',
});
if (result?.error || !result?.post) {
throw new Error(`apiCreatePost failed: ${JSON.stringify(result?.error ?? 'no post returned')}`);
}
return result;
};
/**
* Get posts for a channel.
* See https://api.mattermost.com/#operation/GetPostsForChannel
* @param {string} baseUrl - the base server URL
* @param {string} channelId - The channel ID to get the posts for
* @return {Object} returns {posts} on success or {error, status} on error
*/
export const apiGetPostsInChannel = async (baseUrl: string, channelId: string): Promise<any> => {
try {
const response = await client.get(`${baseUrl}/api/v4/channels/${channelId}/posts`);
const {order, posts} = response.data;
const orderedPosts = order.map((postId: string) => posts[postId]);
return {posts: orderedPosts};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Get last post in a channel.
* @param {string} baseUrl - the base server URL
* @param {string} channelId - The channel ID to get the last post
* @return {Object} returns {post} on success or {error, status} on error
*/
export const apiGetLastPostInChannel = async (
baseUrl: string,
channelId: string,
{maxAttempts = 6, intervalMs = timeouts.TWO_SEC} = {},
): Promise<any> => {
/* eslint-disable no-await-in-loop -- poll until the post is indexed */
for (let attempt = 0; attempt < maxAttempts; attempt++) {
if (attempt > 0) {
await wait(intervalMs);
} else {
await wait(timeouts.TWO_SEC);
}
const response = await apiGetPostsInChannel(baseUrl, channelId);
if (response.error) {
if (attempt === maxAttempts - 1) {
return response;
}
continue;
}
const {posts} = response;
if (posts?.length) {
return {post: posts[0]};
}
}
/* eslint-enable no-await-in-loop */
return {error: {message: `No posts found in channel ${channelId} after ${maxAttempts} attempts`}};
};
export const apiFindPostInChannelByMessage = async (
baseUrl: string,
channelId: string,
message: string,
{maxAttempts = 6, intervalMs = timeouts.TWO_SEC, exact = false} = {},
): Promise<any> => {
/* eslint-disable no-await-in-loop -- poll until the target post is indexed */
for (let attempt = 0; attempt < maxAttempts; attempt++) {
if (attempt > 0) {
await wait(intervalMs);
} else {
await wait(timeouts.TWO_SEC);
}
const response = await apiGetPostsInChannel(baseUrl, channelId);
if (response.error) {
if (attempt === maxAttempts - 1) {
return response;
}
continue;
}
const post = response.posts?.find((candidate: any) => (
exact ? candidate.message === message : candidate.message.includes(message)
));
if (post) {
return {post};
}
}
/* eslint-enable no-await-in-loop */
return {error: {message: `No post containing "${message}" found in channel ${channelId} after ${maxAttempts} attempts`}};
};
/**
* Patch a post.
* See https://api.mattermost.com/#operation/PatchPost
* @param {string} baseUrl - the base server URL
* @param {string} postId - the post ID
* @param {Object} postData - data to partially update a post
* @return {Object} returns {post} on success or {error, status} on error
*/
export const apiPatchPost = async (baseUrl: string, postId: string, postData: string): Promise<any> => {
try {
const response = await client.put(
`${baseUrl}/api/v4/posts/${postId}/patch`,
postData,
);
return {post: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Create an ephemeral post visible only to the given user.
* See https://api.mattermost.com/#operation/CreatePostEphemeral
* @param {string} baseUrl - base server URL
* @param {string} userId - user ID that can see the ephemeral post
* @param {{channel_id: string, message: string, root_id?: string, props?: Record<string, unknown>}} post - ephemeral post payload
* @return {Object} returns {post} on success or {error, status} on error
*/
export const apiCreatePostEphemeral = async (
baseUrl: string,
userId: string,
post: {channel_id: string; message: string; root_id?: string; props?: Record<string, unknown>},
): Promise<any> => {
try {
const response = await client.post(`${baseUrl}/api/v4/posts/ephemeral`, {
user_id: userId,
post,
});
return {post: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Create an incoming webhook.
* See https://api.mattermost.com/#operation/CreateIncomingWebhook
* @param {string} baseUrl - base server URL
* @param {{channel_id: string, display_name: string}} hook - incoming webhook payload
* @return {Object} returns {hook} on success or {error, status} on error
*/
export const apiCreateIncomingWebhook = async (
baseUrl: string,
hook: {channel_id: string; display_name: string},
): Promise<any> => {
try {
const response = await client.post(`${baseUrl}/api/v4/hooks/incoming`, hook);
return {hook: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* POST a payload to an incoming webhook URL path (`/hooks/{id}`).
* @param {string} baseUrl - base server URL
* @param {string} hookId - incoming webhook id/path
* @param {Record<string, unknown>} payload - body sent to the webhook
* @return {Object} returns {data} on success or {error, status} on error
*/
export const apiPostIncomingWebhook = async (
baseUrl: string,
hookId: string,
payload: Record<string, unknown>,
): Promise<any> => {
try {
const response = await client.post(`${baseUrl}/hooks/${hookId}`, payload);
return {data: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Pin a post in its channel.
* See https://api.mattermost.com/#operation/PinPost
* @param {string} baseUrl - the base server URL
* @param {string} postId - the post ID
* @return {Object} returns {data} on success or {error, status} on error
*/
export const apiPinPost = async (baseUrl: string, postId: string): Promise<any> => {
try {
const response = await client.post(`${baseUrl}/api/v4/posts/${postId}/pin`);
return {data: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Upload a file to a channel via the Mattermost REST API.
* See https://api.mattermost.com/#operation/UploadFile
* @param {string} baseUrl - the base server URL
* @param {string} channelId - The channel ID to upload the file to
* @param {string} absFilePath - The absolute path to the file to upload
* @param {Object} [options]
* @param {boolean} [options.forBookmark] - Upload with bookmark=true so CreatorId is
* "bookmark" (required before creating a type=file channel bookmark).
* @return {Object} returns {fileId} on success or {error, status} on error
*/
export const apiUploadFileToChannel = async (
baseUrl: string,
channelId: string,
absFilePath: string,
options?: {forBookmark?: boolean},
): Promise<any> => {
const query = new URLSearchParams({channel_id: channelId});
if (options?.forBookmark) {
// Server sets FileInfo.CreatorId to "bookmark" when bookmark=true
// (required by ChannelBookmark store for type=file bookmarks).
query.set('bookmark', 'true');
}
// A replayed upload can leave an extra FileInfo behind, but an unreferenced file is
// invisible to every assertion in the suite, and losing the upload fails the test
// outright — so a duplicate is the cheaper outcome here.
const result = await withTransportRetry(() => apiUploadFile('files', absFilePath, {
url: `${baseUrl}/api/v4/files?${query.toString()}`,
method: 'POST',
}), {idempotent: false, allowDuplicateWrites: true, label: 'apiUploadFileToChannel'});
if (result.error) {
return result;
}
const fileId = result.data?.file_infos?.[0]?.id;
if (!fileId) {
return {error: {message: 'Upload response missing file_infos[0].id'}};
}
return {fileId};
};
/**
* Upload a fixture image and create a post with that image attached.
* @param {string} baseUrl - the base server URL
* @param {string} channelId - The channel ID to post in
* @param {string} rootId - (optional) root post ID for thread replies
* @return {Object} returns {post, fileId} on success. Throws after transport retries if upload or create fails.
*/
export const apiCreatePostWithImageAttachment = async (baseUrl: string, channelId: string, rootId = ''): Promise<any> => {
const absFilePath = path.resolve(__dirname, '../../support/fixtures/image.png');
const {fileId, error: uploadError} = await apiUploadFileToChannel(baseUrl, channelId, absFilePath);
if (uploadError || !fileId) {
throw new Error(`apiCreatePostWithImageAttachment: upload failed: ${JSON.stringify(uploadError)}`);
}
const {post, error: postError} = await apiCreatePost(baseUrl, {
channelId,
message: '',
rootId: rootId || undefined,
fileIds: [fileId],
});
if (postError || !post?.id) {
throw new Error(`apiCreatePostWithImageAttachment: create post failed: ${JSON.stringify(postError)}`);
}
if (!post.file_ids || !post.file_ids.includes(fileId)) {
throw new Error(`apiCreatePostWithImageAttachment: server did not attach file. post.file_ids=${JSON.stringify(post.file_ids)}, fileId=${fileId}`);
}
return {post, fileId};
};
/**
* Get the public (unauthenticated) link for a file. Requires the file to be attached to a
* post and `FileSettings.EnablePublicLink` to be true.
* See https://api.mattermost.com/#operation/GetFileLink
* @param {string} baseUrl - the base server URL
* @param {string} fileId - the file ID
* @return {Object} returns {link} on success or {error, status} on error
*/
export const apiGetFilePublicLink = async (baseUrl: string, fileId: string): Promise<any> => {
return withTransportRetry(async () => {
try {
const response = await client.get(`${baseUrl}/api/v4/files/${fileId}/link`);
return {link: response.data?.link};
} catch (err) {
return getResponseFromError(err);
}
}, {idempotent: true, label: 'apiGetFilePublicLink'});
};
export const apiGetFlaggedPosts = async (baseUrl: string, userId: string): Promise<{order: string[]; posts: Record<string, any>; error?: any}> => {
try {
const response = await client.get(`${baseUrl}/api/v4/users/${userId}/posts/flagged`);
return {order: response.data?.order ?? [], posts: response.data?.posts ?? {}};
} catch (err) {
// Callers must not read the empty order as "no flagged posts" — see waitForPostUnflagged.
return {order: [], posts: {}, ...getResponseFromError(err)};
}
};
export const waitForPostFlagged = async (baseUrl: string, userId: string, postId: string, maxAttempts = 10): Promise<void> => {
/* eslint-disable no-await-in-loop -- poll until post appears in flagged index */
for (let i = 0; i < maxAttempts; i++) {
const {order} = await apiGetFlaggedPosts(baseUrl, userId);
if (order.includes(postId)) {
return;
}
if (i < maxAttempts - 1) {
await wait(2000);
}
}
/* eslint-enable no-await-in-loop */
throw new Error(`Post ${postId} not flagged after ${maxAttempts} attempts`);
};
export const waitForPostUnflagged = async (baseUrl: string, userId: string, postId: string, maxAttempts = 10): Promise<void> => {
/* eslint-disable no-await-in-loop -- poll until post disappears from flagged index */
for (let i = 0; i < maxAttempts; i++) {
const {order, error} = await apiGetFlaggedPosts(baseUrl, userId);
if (!error && !order.includes(postId)) {
return;
}
if (i < maxAttempts - 1) {
await wait(2000);
}
}
/* eslint-enable no-await-in-loop */
throw new Error(`Post ${postId} still flagged after ${maxAttempts} attempts`);
};
export const waitForPostPinned = async (
baseUrl: string,
channelId: string,
postId: string,
maxAttempts = 10,
): Promise<void> => {
/* eslint-disable no-await-in-loop -- poll until server reports is_pinned */
for (let i = 0; i < maxAttempts; i++) {
const {posts, error} = await apiGetPostsInChannel(baseUrl, channelId);
if (!error) {
const post = posts?.find((candidate: any) => candidate.id === postId);
if (post?.is_pinned) {
return;
}
}
if (i < maxAttempts - 1) {
await wait(timeouts.TWO_SEC);
}
}
/* eslint-enable no-await-in-loop */
throw new Error(`Post ${postId} not pinned after ${maxAttempts} attempts`);
};
export const waitForPostUnpinned = async (
baseUrl: string,
channelId: string,
postId: string,
maxAttempts = 10,
): Promise<void> => {
/* eslint-disable no-await-in-loop -- poll until server clears is_pinned */
for (let i = 0; i < maxAttempts; i++) {
const {posts, error} = await apiGetPostsInChannel(baseUrl, channelId);
if (!error) {
const post = posts?.find((candidate: any) => candidate.id === postId);
if (post && !post.is_pinned) {
return;
}
}
if (i < maxAttempts - 1) {
await wait(timeouts.TWO_SEC);
}
}
/* eslint-enable no-await-in-loop */
throw new Error(`Post ${postId} still pinned after ${maxAttempts} attempts`);
};
export const waitForPostMessage = async (
baseUrl: string,
channelId: string,
postId: string,
expectedMessage: string,
maxAttempts = 10,
): Promise<void> => {
/* eslint-disable no-await-in-loop -- poll until the edited post is returned by the server */
for (let i = 0; i < maxAttempts; i++) {
const {posts, error} = await apiGetPostsInChannel(baseUrl, channelId);
if (!error) {
const post = posts?.find((candidate: any) => candidate.id === postId);
if (post?.message === expectedMessage) {
return;
}
}
if (i < maxAttempts - 1) {
await wait(timeouts.TWO_SEC);
}
}
/* eslint-enable no-await-in-loop */
throw new Error(`Post ${postId} did not update to "${expectedMessage}" after ${maxAttempts} attempts`);
};
/**
* Search posts (same endpoint recent mentions uses).
* See https://api.mattermost.com/#operation/SearchPosts
*/
export const apiSearchPosts = async (
baseUrl: string,
terms: string,
{isOrSearch = true, teamId = ''}: {isOrSearch?: boolean; teamId?: string} = {},
): Promise<{order?: string[]; posts?: Record<string, any>; error?: unknown}> => {
try {
const response = await client.post(`${baseUrl}/api/v4/posts/search`, {
terms,
is_or_search: isOrSearch,
...(teamId ? {team_id: teamId} : {}),
});
return {
order: response.data?.order,
posts: response.data?.posts,
};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Poll search until it returns the expected post message. Recent Mentions is
* search-backed; channel GET can succeed while search still serves the old text.
*/
export const waitForPostMessageInSearch = async (
baseUrl: string,
terms: string,
postId: string,
expectedMessage: string,
maxAttempts = 15,
): Promise<void> => {
/* eslint-disable no-await-in-loop -- poll search index until it catches up */
for (let i = 0; i < maxAttempts; i++) {
const {posts, error} = await apiSearchPosts(baseUrl, terms);
if (!error && posts?.[postId]?.message === expectedMessage) {
return;
}
if (i < maxAttempts - 1) {
await wait(timeouts.TWO_SEC);
}
}
/* eslint-enable no-await-in-loop */
throw new Error(
`Search did not return post ${postId} with message "${expectedMessage}" after ${maxAttempts} attempts`,
);
};
export const Post = {
apiCreatePost,
apiCreatePostEphemeral,
apiCreateIncomingWebhook,
apiCreatePostWithImageAttachment,
apiFindPostInChannelByMessage,
apiGetLastPostInChannel,
apiGetPostsInChannel,
apiPinPost,
apiPatchPost,
apiPostIncomingWebhook,
apiSearchPosts,
apiUploadFileToChannel,
apiGetFilePublicLink,
apiGetFlaggedPosts,
waitForPostFlagged,
waitForPostMessage,
waitForPostMessageInSearch,
waitForPostPinned,
waitForPostUnflagged,
waitForPostUnpinned,
};
export default Post;