mattermost-mobile-upstream/detox/e2e/support/server_api/post.ts
yasser khan a5d81c6b24
ci(e2e): port E2E CI stack to release-2.43 to unblock merges (#10004)
* chore(e2e): Fix e2e artifact upload path for CMT workflow (#9955)

* chore(e2e): Fix e2e artifact upload path for CMT workflow

* test(e2e): Replace MM-T placeholder test keys with real Zephyr Scale IDs

- Classification Banner (18 tests): MM-T6196–MM-T6205, MM-T6206–MM-T6208, MM-T6209–MM-T6213
- mm_blocks (incoming webhook + ephemeral): MM-T6214–MM-T6240 (27 tests)
- Fixes TM4J test-case linking by ensuring all test titles use real MM-T#### keys
- Tightens getTM4JTestCases filter regex from /(MM-T)\w+/ to /MM-T\d+/ to prevent
  crashes when non-numeric MM-T placeholders slip through before Zephyr linkage


- Scan all Xcode_*.app directories and filter for major version >= 26 to
  future-proof against Xcode 30+ releases (current glob pattern maxes at 29)
- Extract version from directory name, validate major >= 26, sort and select highest
- Add least-privilege job-level permissions (contents: read) to build jobs
  (build-ios-simulator, build-android-apk, build-android-apk-maestro) to scope
  actions/checkout and actions/upload-artifact access

* fix: apply CodeRabbit review feedback

Require Xcode 26.1+ for iOS prepare, standardize E2E titles to MM-TXXXX_N,
and bound Zephyr test-case id matching to complete identifiers.


* fix(e2e): Grant actions:write on CMT build jobs for artifact upload

Job-level contents:read alone strips upload-artifact permission; match
e2e-detox-pr.yml so ios/android/maestro builds can publish artifacts.

* feat(e2e): Integrate TSIO reporting (#9925)


Retire legacy maestro per-platform contexts from cancel-e2e-runs and
document the canonical PR, master, and CMT status context mapping.
Wire Detox + Maestro (PR/main/CMT) into Test System IO with a single
commit status (e2e/mobile; CMT uses e2e/compatibility-matrix-testing)
and groups mobile-pr / mobile-main / cmt-mobile.

Upload shard results with correct framework labels, merge Jest shards
into TSIO Detox shape, stub missing/dead shards as failures, and post
channel summaries after status settles. Matterwick MASTER is treated as
MAIN for mobile-main routing.

Also harden report/fail paths, stage Maestro screenshots per flow for
TSIO galleries, fix a few Detox setup/testID issues, and skip known
platform flakes so the pipeline stays actionable while TSIO lands.

* ci(e2e): per-job TSIO report groups, commit statuses, and webhook sidecar (#9969)

* ci(e2e): per-job TSIO report groups and commit statuses

E2E jobs previously shared a single `e2e/mobile` commit status backed by one
TSIO report group, so concurrent platform legs raced to finalize the group and
clobbered each other's results. Give each Detox/Maestro job its own report
group (`mobile-<flow>-<job>`, total_reports_expected=1) and its own commit
status context (`detox-ios`, `detox-android`, `detox-ipad`, `maestro-ios`,
`maestro-android`); CMT reports per shard plus an umbrella context.

Channel notifications move to a single rollup step so N platform legs no
longer spam the webhook, and the five-server topology is dispatched with
explicit per-platform inputs that still resolve to the existing SITE_*_URL
contract consumed by the test config.

Also adds the webhook sidecar launcher, Android emulator CI prep, and TSIO
screenshot path linking that keeps folder basenames matching Jest full names.

The new detox type-check job surfaced pre-existing broken import paths in
maestro/fixtures/calls_seed.ts, which pointed at detox/detox/e2e; corrected so
the guard passes on its own first run.

Note: the CMT matrix now reads per-platform server URLs (`ios_site_1_url`,
`android_site_1_url`, `site_3_url`) instead of a single `url`, which needs the
matching Matterwick dispatch change to land alongside this.

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

* ci(e2e): aggregate CMT channel rollup from TSIO and wire notify secrets

The CMT umbrella posted a placeholder summary built from CI job outcomes
(passed:0, failed:0|1, reports:[]), so the release channel message carried no
per-leg detail. It now runs the same tsio-channel-notify-rollup.js path as
PR/main: cmt-identity emits a per-shard TSIO config map and the rollup polls
every shard group, so counts and per-leg rows come from TSIO. The rollup job
also needs id-token: write to mint its OIDC token.

Webhook secrets used by the per-job TSIO finalize steps were referenced but
never declared in the templates' workflow_call.secrets, so GitHub resolved them
to empty strings and channel notify silently no-opped. Declare them in the
iOS/Android/Maestro templates and forward them from e2e-detox.yml and the CMT
callers. The Maestro PR path worked only because its callers use
secrets: inherit.

Also from review:
- split-tests.js emitted two matrix jobs at parallelism=1 when mm_blocks specs
  were present; merge into one shard instead of exceeding the requested count.
- Move the Android ARTIFACT_RUN_ID emptiness check ahead of download-artifact,
  which consumes it and otherwise fails with an opaque API error.
- resolve-tsio-job-config.sh now reuses webhookBucketForReportName instead of
  re-deriving the bucket prefix with a looser startsWith check.

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

* ci(e2e): add local preflight for CI PRs

The webhook-secret and OIDC-permission gaps in this branch were invisible
locally and in a green CI run — the affected steps exit 0 and just skip the
notify or commit status. Add a script engineers can run before opening a PR that
touches .github/ or detox/utils:

  cd detox && npm run preflight:ci        # :ci-fast skips lint + tsc

It runs actionlint (which flags secrets not declared in a callee's
workflow_call.secrets), scans for exit-code capture broken by a trailing
backslash, asserts every job running a TSIO OIDC script declares
id-token: write, then runs the detox/utils tests and npm run check. actionlint
and the CodeRabbit CLI are optional and skipped with an install hint when absent.

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

* ci(e2e): use mktemp for preflight logs

Fixed /tmp log paths can be pre-created as symlinks, so the preflight
script would truncate whatever they point at (CWE-377). Create both logs
with mktemp and drop them on exit.

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

* ci(e2e): address review feedback on TSIO statuses and sidecar

A cancelled E2E run reached no conclusion, so posting `success` on its
commit statuses let a PR merge on a check that never ran. Cancelled runs
now post `pending`; `success` is reserved for the one deliberate bypass,
the E2E/Override label.

Commit-status contexts move into the `e2e-test/*` namespace to match the
mattermost monorepo, with the prefix owned by build-tsio-job-config.js and
mirrored in the cancel action's context list. Legacy unprefixed and `e2e/*`
contexts are dropped rather than carried forward.

The `preflight:ci` script and its OIDC-permission checker duplicated what
actionlint, the unit tests and `npm run check` already do, so they are
removed and detox/CLAUDE.md documents the underlying failure modes and the
commands to catch them instead.

cloudflared and the TSIO CLI are pinned to known-good releases rather than
`latest`, and detox/README.md now documents the webhook sidecar: when a
tunnel is needed, the WEBHOOK_PUBLIC_BASE_URL / CLOUDFLARED_TUNNEL_TOKEN
precedence, and why quick tunnels report callbacks as unreachable.

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

* ci(e2e): detect upstream cancellation and surface status reset failures

generate-report runs with always(), so job.status stays "success" when an
upstream job is cancelled and TSIO was published as a real failure. Read the
generate-specs/e2e-* needs results so a cancelled run is reported as such.

In cancel-e2e-runs, only reset the E2E commit statuses for runs that were
actually stopped — a run we failed to cancel keeps publishing its own results.
Aggregate createCommitStatus failures across every context and fail the action
afterwards instead of silently warning, so a stale check cannot go unnoticed.

---------

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

* fix(e2e): Quarantine proven flakes and harden Detox harness (#9971)

* ci(e2e): make E2E/Override waive checks instead of cancelling runs (#9975)

* ci(e2e): make E2E/Override waive checks instead of cancelling runs

E2E/Override previously cancelled in-flight E2E runs and posted success on
their commit statuses. Cancelling destroys the very signal the maintainer
might still want, and reporting success for a run that never finished
attributes a conclusion to work that never happened.

Override now means one thing only: the required e2e-test/* contexts go green
so the PR can merge. Runs keep going and keep reporting to TSIO.

- Add .github/actions/e2e-override-status to post success (or pending) on all
  five required e2e-test/* contexts for a SHA.
- Label manager posts success on `labeled` and pending on `unlabeled`, so
  removing the escape hatch re-blocks the PR instead of leaving a stale waiver
  on the head SHA. It comments the runs it left running rather than killing
  them, and drops to `actions: read` now that it never cancels.
- tsio-report-status re-reads the PR labels before posting a failure. Because
  runs are no longer cancelled, a result landing after the override was applied
  would otherwise re-red a check the maintainer deliberately bypassed. The
  lookup fails closed so an unreadable label list cannot turn a real failure
  green, and the step itself no longer fails under override.
- Guard e2e-cancel-on-label-removal: stripping E2E/Run* is exactly what the
  Honor E2E/Override step does, so without this the indirect unlabeled event
  would cancel the runs the redesign is meant to preserve.
- e2e-detox-pr posts the success itself when the policy skips E2E, since every
  downstream job is skipped and a skipped job leaves the required contexts
  absent, blocking the merge forever.
- cancel-e2e-runs drops status_state: a cancelled run has no conclusion to
  report, so it always resets to pending.
- Thread `issues: read` through the reusable workflow callers so finalize can
  read the labels; a reusable workflow cannot escalate past its caller.

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

* ci(e2e): derive required E2E contexts from one definition

The override and cancel actions each carried their own copy of the five
required e2e-test/* contexts, kept aligned with build-tsio-job-config.js by
comment alone. A job renamed in PR_MAIN_JOBS would silently leave the actions
waiving or resetting a context that no longer exists, so a PR either cannot
merge or merges while a real context still blocks it.

Export E2E_STATUS_CONTEXTS from detox/utils/build-tsio-job-config.js, derived
from PR_MAIN_JOBS, and require it from both composite actions. github-script
resolves relative requires against the workspace, and every call site already
checks out the repo before using the action.

Also set persist-credentials: false on the e2e-label-manager checkout, matching
the other checkout steps.

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

* ci(e2e): drop the cancel action for native concurrency, keep GitHub calls in Actions

Review feedback from @saturninoabril.

Superseding an in-flight E2E run is what GitHub's `concurrency` already does, so
`e2e-detox-pr.yml` now declares `concurrency: e2e-<ref>` with `cancel-in-progress`
instead of cancelling from a step inside the run that supersedes it. The older run
is cancelled the moment the new dispatch is created rather than once a runner picks
up the first job.

That removes the only two remaining callers of `.github/actions/cancel-e2e-runs`,
along with the commit statuses it forced to `pending` on cancel — a cancelled run
has no conclusion to report, so the state is left to GitHub. Forcing a commit status
is now reserved for real test results and the override waiver. The action is deleted.

`e2e-cancel-on-label-removal.yml` goes with it: with `E2E/Run` on its way out and
override no longer cancelling, removing the label to stop a run has no remaining
practical case, and dropping the workflow also removes the back-door cancel guard
it needed.

The `E2E/Override` lookup moves out of `tsio-report-status.js` into a new
`.github/actions/e2e-override-label` composite action, which the finalize steps
call and pass in via `--e2e-override`. Talking to GitHub stays in the Actions
layer and the reporter is left deciding on its inputs.

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

* ci(e2e): paginate PR label lookups for E2E/Override

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

* ci(e2e): re-post E2E/Override success on new commits

Override success is SHA-scoped: it is posted only on the head SHA at
label-apply time (e2e-label-manager 'labeled' path) and when Matterwick
dispatches e2e-detox-pr.yml (post-e2e-override-status). On a push after
E2E/Override is applied, refresh-e2e-run-label strips the run labels and
returns — Matterwick is not dispatched, so the new head SHA gets no
e2e-test/* statuses. With those checks Required, the new commit is
blocked until the label is re-toggled.

Carry the override onto the new commit: refresh-e2e-run-label now emits
an e2e_override output, and when it is set a gated checkout +
e2e-override-status step re-posts success on the new head SHA. Reuses
the existing e2e-override-status action (same 5 required e2e-test/*
contexts, same 'E2E bypassed' description), so it is idempotent with the
labeled path. Adds statuses: write / contents: read to the job.

Note: refresh-e2e-run-label is gated on base.ref == 'main', so stacked
PRs (base != main) are not covered; non-main-base already posts success
at dispatch time.

---------

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

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 16:50:34 +05:30

499 lines
17 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 client from './client';
import {apiUploadFile, getResponseFromError} from './common';
// ****************************************************************
// Posts
// See https://api.mattermost.com/#tag/posts
//
// 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`
// ****************************************************************
/**
* 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 - Array of file IDs to attach to the post (top-level API field)
* @param {Date} option.createAt - The date the post is created at
* @return {Object} returns {post} on success or {error, status} on error
*/
export const apiCreatePost = async (baseUrl: string, {channelId, message, rootId, props = {}, fileIds, createAt = 0}: any): 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);
}
};
/**
* 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} = {},
): 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) => 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');
}
const result = await apiUploadFile('files', absFilePath, {
url: `${baseUrl}/api/v4/files?${query.toString()}`,
method: 'POST',
});
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 or {error, status} on error
*/
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) {
return {error: uploadError};
}
const {post, error: postError} = await apiCreatePost(baseUrl, {
channelId,
message: '',
rootId: rootId || undefined,
fileIds: [fileId],
});
if (postError) {
return {error: postError};
}
if (!post.file_ids || !post.file_ids.includes(fileId)) {
return {error: {message: `Server did not attach file to post. post.file_ids=${JSON.stringify(post.file_ids)}, fileId=${fileId}`}};
}
return {post, fileId};
};
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,
apiGetFlaggedPosts,
waitForPostFlagged,
waitForPostMessage,
waitForPostMessageInSearch,
waitForPostPinned,
waitForPostUnflagged,
waitForPostUnpinned,
};
export default Post;