mattermost-mobile-upstream/app/queries/servers/post.ts
yasser khan 3acf3bec7a
fix: app bugs surfaced by Detox RF migration (#9789)
* app fixes surfaced by detox RF migration

Carve the app-side bug fixes from the migrate_RF_to_detox branch into
their own PR. Includes:

- NavigationStore.waitUntilScreenIsTop helper + matching switchToChannel /
  notification.test wiring (Screens.CHANNEL_LIST -> Screens.HOME)
- Detox source build + null-guard patch for Android FabricUIManagerIdlingResources
  (android/settings.gradle, android/app/build.gradle, gradle.properties)
- iOS Podfile: Alamofire 5.10 duplicate-allHeaders patch + stdlib embed for extensions
- iOS Server screen: defer push-proxy verification alert past Navigation.push to
  fix iOS 26 race
- Android NetworkClient: null-guard host extraction to prevent NPE on bad cert reports
- ephemeral_store: track recently-unsaved saved posts with 2-min TTL
- post_draft: filter undefined channel observable to prevent archived-banner flicker
- queries/servers/thread: is_following nullish-coalesce to false
- datetime: NaN guard for invalid scheduled-message timestamp (MM-T5720)
- navigation: dismissBottomSheet handles GENERIC_BOTTOM_SHEET fallback
- bottom_sheet: accessibilityViewIsModal for VoiceOver
- calls websocket_client: extend interface for optional sendBinary
- edit_profile: wrap Save Pressable in View to constrain Detox tap bounds (MM-T4989_2/MM-T3250)
- invite/summary: fix retry testID hardcoded to use the dynamic type
- channel_bookmark/bookmark_link: URL resolution timeout + setBookmarkLinkUrl
- categories_list/load_channel_error: missing return statement for error UI
- iOS MattermostShare: TestID-friendly testIDs on Swift share-extension views
- patches/react-native-network-client: Android host null-guard patch
- scripts/build.sh: copy compass-icons.ttf manually when --ignore-scripts is used
- types/modules: WebSocketClientInterface sendBinary extension

Matched detox specs that exercise these bugs land in the rf-split/detox-tests PR.

* address CodeRabbit review on PR #9789

- post_list/index.ts, thread_options/index.ts: track serverUrl in withObservables dependency keys
- post/body/index.tsx: restore React.memo(Body) to avoid per-item re-render regression
- thread.tsx, edit_profile.tsx: add pressed feedback via style callback; move inline typography to stylesheet
- bookmark_link.tsx: include queueFetch in useDidUpdate deps
- ephemeral_store.ts: complete and delete per-post recently-unsaved subjects on expiry/clear to bound growth

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test: fix stale mocks and add coverage for recently-unsaved saved posts

Update thread/preference tests for the new NavigationStore and
prepareDestroyPermanently call paths, and add unit tests for the
EphemeralStore recently-unsaved saved-post logic plus the websocket
filterStaleSavedPostPreferences path.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test: tighten recently-unsaved saved post assertions

Address CodeRabbit nitpicks on #9789:
- preference.test.ts: assert addRecentlyUnsavedSavedPost is called once
  with (serverUrl, postId) so the echoed websocket re-save is filtered.
- ephemeral_store.test.ts: assert the observed Set size (2 after two adds,
  1 after clearing one) so we catch stray/missing entries.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* docs: explain pinned posts descending sort order

The asc->desc change to queryPinnedPostsInChannel surfaced during the
detox RF migration was correct but undocumented. selectOrderedPosts
(reached via observePinnedPostsInChannel) iterates the posts array from
the end backwards expecting oldest->newest, so it requires descending
(newest-first) input, matching queryPostsInChannel. Add a comment so the
sort order isn't questioned in review.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test: cover thread/config/bottom-sheet edge cases flagged in review

Add unit tests for coverage gaps identified by CodeRabbit on #9789:
- createThreadFromNewPost: reply where the thread is missing but the root
  post exists (back-fills + auto-follows), and where neither exists (only
  records the participant, no crash)
- processReceivedThreads: thread entry with no post/participants is skipped
  without crashing
- markThreadAsUnread: unread_replies/unread_mentions from the API response
  are persisted to the local thread
- getConfigBooleanValue: 'true' -> true, non-'true' -> false, missing key
  honors the default
- dismissBottomSheet: falls back to GENERIC_BOTTOM_SHEET when only the
  generic variant is in the stack

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor(thread_options): use withServerUrl HOC

Replace the hand-rolled `ThreadOptionsWithServerUrl` wrapper (which
called `useServerUrl()` inside a function component and re-created
the element via `React.createElement`) with the existing
`withServerUrl` HOC from `@context/server`.

Composition chain becomes:
  withDatabase(withServerUrl(enhanced(ThreadOptions)))

Addresses larkox's review on app/screens/thread_options/index.ts:41:
"This is not needed. You should be able to use `withServerUrl` function."

Also tightens the Props type — `serverUrl` is now required (the HOC
guarantees it), not optional.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* chore(deps): bump react-native-network-client to 1.10.2; drop workarounds

1.10.2 upstreams both fixes that were being carried locally:

- iOS: apply_patches.rb is now idempotent
  (mattermost/react-native-network-client#167), so its bundled Alamofire
  diff can no longer double-apply. Removes the need for the Podfile
  post_install workaround that stripped the duplicate `let allHeaders`
  (Swift 6 / Xcode 26 "invalid redeclaration"). Workaround deleted.

- Android: the cert-error host null-fallback in NetworkClient.kt is now
  upstream (and improved — prefers HttpUrl host, then URI, then
  baseUrlString; references #9789). The patch-package patch
  (@mattermost+react-native-network-client+1.10.0.patch) is therefore
  obsolete and deleted. It was also a silent no-op here anyway — named
  1.10.0 while 1.10.1 was installed, so patch-package skipped it.

Addresses @enahum's review on #9789: the fix belongs in network-client,
not patched downstream — and it now is.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore(ios): update Podfile.lock for rnnc 1.10.2

Run `pod install` to sync Podfile.lock with the dependency bump in the
previous commit:
- react-native-network-client 1.10.1 → 1.10.2
- its pod checksum recomputed
- PODFILE CHECKSUM recomputed (the Podfile changed — Alamofire
  duplicate-allHeaders workaround removed)

The previous commit bumped package.json + ran npm install but did not
regenerate Podfile.lock, so the iOS lockfile-consistency check would have
failed (caught in review by @enahum).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor(thread): use shared NavigationButton for header back

Addresses @larkox's review on #9789: the thread route hand-rolled its
header back button with a raw Pressable + CompassIcon + local StyleSheet,
which is inconsistent with the rest of the app.

Switch to the shared NavigationButton component — the same pattern used by
app/screens/code/index.tsx, custom_status_clear_after, channel_bookmark, and
the getModalHeaderOptions/getLoginModalHeaderOptions helpers
(navigation.setOptions → NavigationButton with iconName/iconSize/color/
onPress/testID).

Behavior is unchanged (still navigation.goBack() via handleBack) and the
testID 'thread.navigation.back.button' is preserved for Detox. Net effect in
the app: Android now gets the standard header ripple, a larger hitSlop touch
target, and the arrow aligns like other NavigationButton headers. Removes the
local styles, Pressable, StyleSheet, and CompassIcon imports.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 13:25:42 +05:30

452 lines
16 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Database, Model, Q, Query} from '@nozbe/watermelondb';
import {of as of$, combineLatestWith, combineLatest} from 'rxjs';
import {map, switchMap, distinctUntilChanged} from 'rxjs/operators';
import {MM_TABLES} from '@constants/database';
import {SKU_SHORT_NAME} from '@constants/license';
import DatabaseManager from '@database/manager';
import EphemeralStore from '@store/ephemeral_store';
import {logDebug, logWarning} from '@utils/log';
import {updatePermalinkMetadata} from '@utils/permalink_sync';
import {queryGroupsByNames} from './group';
import {querySavedPostsPreferences} from './preference';
import {getConfigValue, observeConfigBooleanValue, observeConfigIntValue, observeIsMinimumLicenseTier} from './system';
import {queryUsersByUsername, observeUser, observeCurrentUser} from './user';
import type PostModel from '@typings/database/models/servers/post';
import type PostInChannelModel from '@typings/database/models/servers/posts_in_channel';
import type PostsInThreadModel from '@typings/database/models/servers/posts_in_thread';
const {SERVER: {POST, POSTS_IN_CHANNEL, POSTS_IN_THREAD}} = MM_TABLES;
const DEFAULT_BURN_ON_READ_DURATION_SECONDS = '600';
const DEFAULT_BURN_ON_READ_MAXIMUM_TTL_SECONDS = '604800';
export const prepareDeletePost = async (post: PostModel): Promise<Model[]> => {
const preparedModels: Model[] = [post.prepareDestroyPermanently()];
const relations: Array<Query<Model>> = [post.drafts, post.files, post.reactions];
for await (const models of relations) {
try {
models.forEach((m) => {
preparedModels.push(m.prepareDestroyPermanently());
});
} catch {
// Record not found, do nothing
}
}
// If the post is a root post, delete the postsInThread model
if (!post.rootId) {
try {
const postsInThread = await post.postsInThread.fetch();
if (postsInThread) {
postsInThread.forEach((m) => {
preparedModels.push(m.prepareDestroyPermanently());
});
}
} catch {
// Record not found, do nothing
}
}
// If thread exists, delete thread, participants and threadsInTeam
try {
const thread = await post.thread.fetch();
if (thread) {
const participants = await thread.participants.fetch();
if (participants.length) {
preparedModels.push(...participants.map((p) => p.prepareDestroyPermanently()));
}
const threadsInTeam = await thread.threadsInTeam.fetch();
if (threadsInTeam.length) {
preparedModels.push(...threadsInTeam.map((t) => t.prepareDestroyPermanently()));
}
preparedModels.push(thread.prepareDestroyPermanently());
}
} catch {
// Thread not found, do nothing
}
return preparedModels;
};
export const getPostById = async (database: Database, postId: string) => {
try {
const postModel = await database.get<PostModel>(POST).find(postId);
return postModel;
} catch {
return undefined;
}
};
export const observePost = (database: Database, postId: string) => {
return database.get<PostModel>(POST).query(Q.where('id', postId), Q.take(1)).observe().pipe(
switchMap((result) => (result.length ? result[0].observe() : of$(undefined))),
);
};
export const observePostAuthor = (database: Database, post: PostModel) => {
return observeUser(database, post.userId);
};
const getServerUrlForDatabase = (database: Database) => {
// Primary match: direct object-identity comparison (works in all normal call paths).
// Secondary match: compare internal WatermelonDB adapter `dbName` as a fallback for
// cases where the Database instance is re-wrapped. `dbName` is not part of the public
// WatermelonDB API — if the library changes its internals this fallback silently returns
// undefined and callers fall back to the non-server-aware observable (no crash, no data
// loss — the 2-minute TTL on unsaved posts still self-heals).
const databaseName = (database.adapter as {dbName?: string}).dbName;
return Object.entries(DatabaseManager.serverDatabases).find(([, serverDatabase]) => {
if (!serverDatabase) {
return false;
}
if (serverDatabase.database === database) {
return true;
}
return (serverDatabase.database.adapter as {dbName?: string}).dbName === databaseName;
})?.[0];
};
export const observePostSaved = (database: Database, postId: string, serverUrl?: string) => {
const savedPreference$ = querySavedPostsPreferences(database, postId).
observeWithColumns(['value']).pipe(
switchMap(
(pref) => of$(Boolean(pref[0]?.value === 'true')),
),
distinctUntilChanged(),
);
const resolvedServerUrl = serverUrl || getServerUrlForDatabase(database);
if (!resolvedServerUrl) {
return savedPreference$;
}
return combineLatest([savedPreference$, EphemeralStore.observeRecentlyUnsavedSavedPost(resolvedServerUrl, postId)]).pipe(
map(([isSaved, isRecentlyUnsaved]) => (isRecentlyUnsaved ? false : isSaved)),
distinctUntilChanged(),
);
};
export const queryPostsInChannel = (database: Database, channelId: string) => {
return database.get<PostInChannelModel>(POSTS_IN_CHANNEL).query(
Q.where('channel_id', channelId),
Q.sortBy('latest', Q.desc),
);
};
export const queryPostsInThread = (database: Database, rootId: string, sorted = false, includeDeleted = false) => {
const clauses: Q.Clause[] = [Q.where('root_id', rootId)];
if (!includeDeleted) {
clauses.unshift(Q.experimentalJoinTables([POST]));
clauses.push(Q.on(POST, 'delete_at', Q.eq(0)));
}
if (sorted) {
clauses.push(Q.sortBy('latest', Q.desc));
}
return database.get<PostsInThreadModel>(POSTS_IN_THREAD).query(...clauses);
};
export const queryPostReplies = (database: Database, rootId: string, excludeDeleted = true) => {
const clauses: Q.Clause[] = [Q.where('root_id', rootId)];
if (excludeDeleted) {
clauses.push(Q.where('delete_at', Q.eq(0)));
}
return database.get<PostModel>(POST).query(...clauses);
};
export const getRecentPostsInThread = async (database: Database, rootId: string) => {
const chunks = await queryPostsInThread(database, rootId, true, true).fetch();
if (chunks.length) {
const recent = chunks[0];
const post = await getPostById(database, rootId);
if (post) {
return queryPostsChunk(database, post.channelId, recent.earliest, recent.latest).fetch();
}
}
return [];
};
export const getLastPostInThread = async (database: Database, rootId: string) => {
const chunks = await queryPostsInThread(database, rootId, true, true).fetch();
if (chunks.length) {
const recent = chunks[0];
const post = await getPostById(database, rootId);
if (post) {
const posts = await queryPostsChunk(database, rootId, recent.earliest, recent.latest, true, true, 1).fetch();
return posts[0];
}
}
return undefined;
};
export const queryPostsChunk = (database: Database, id: string, earliest: number, latest: number, inThread = false, includeDeleted = false, limit = 0) => {
const conditions: Q.Where[] = [Q.where('create_at', Q.between(earliest, latest))];
if (inThread) {
conditions.push(Q.where('root_id', id));
} else {
conditions.push(Q.where('channel_id', id));
}
if (!includeDeleted) {
conditions.push(Q.where('delete_at', Q.eq(0)));
}
const clauses: Q.Clause[] = [
Q.and(
...conditions,
),
Q.sortBy('create_at', Q.desc),
];
if (limit) {
clauses.push(Q.take(limit));
}
return database.get<PostModel>(POST).query(...clauses);
};
export const getRecentPostsInChannel = async (database: Database, channelId: string, includeDeleted = false) => {
const chunks = await queryPostsInChannel(database, channelId).fetch();
if (chunks.length) {
const recent = chunks[0];
return queryPostsChunk(database, channelId, recent.earliest, recent.latest, false, includeDeleted).fetch();
}
return [];
};
export const queryPostsById = (database: Database, postIds: string[], sort?: Q.SortOrder) => {
const clauses: Q.Clause[] = [Q.where('id', Q.oneOf(postIds))];
if (sort) {
clauses.push(Q.sortBy('create_at', sort));
}
return database.get<PostModel>(POST).query(...clauses);
};
export const queryPostsByType = (database: Database, type: string) => {
const clauses: Q.Clause[] = [Q.where('type', type)];
return database.get<PostModel>(POST).query(...clauses);
};
export const queryPostsBetween = (database: Database, earliest: number, latest: number, sort: Q.SortOrder | null, userId?: string, channelId?: string, rootId?: string) => {
const andClauses = [Q.where('create_at', Q.between(earliest, latest))];
if (channelId) {
andClauses.push(Q.where('channel_id', channelId));
}
if (userId) {
andClauses.push(Q.where('user_id', userId));
}
if (rootId != null) {
andClauses.push(Q.where('root_id', rootId));
}
const clauses: Q.Clause[] = [Q.and(...andClauses)];
if (sort != null) {
clauses.push(Q.sortBy('create_at', sort));
}
return database.get<PostModel>(POST).query(...clauses);
};
export const queryPinnedPostsInChannel = (database: Database, channelId: string) => {
return database.get<PostModel>(POST).query(
Q.and(
Q.where('channel_id', channelId),
Q.where('is_pinned', Q.eq(true)),
),
// Newest-first, matching queryPostsInChannel. selectOrderedPosts (the
// consumer via observePinnedPostsInChannel) walks the array from the end
// backwards expecting oldest->newest, so it requires descending input.
Q.sortBy('create_at', Q.desc),
);
};
export const observePinnedPostsInChannel = (database: Database, channelId: string) => {
return queryPinnedPostsInChannel(database, channelId).observe();
};
export const observeSavedPostsByIds = (database: Database, postIds: string[], serverUrl?: string) => {
const savedPostIds = querySavedPostsPreferences(database).extend(
Q.where('name', Q.oneOf(postIds)),
).observeWithColumns(['name']).pipe(
switchMap((prefs) => of$(new Set(prefs.map((p) => p.name)))),
);
const resolvedServerUrl = serverUrl || getServerUrlForDatabase(database);
if (!resolvedServerUrl) {
return savedPostIds;
}
return combineLatest([savedPostIds, EphemeralStore.observeRecentlyUnsavedSavedPosts(resolvedServerUrl)]).pipe(
map(([currentSavedPostIds, recentlyUnsavedSavedPosts]) => {
return new Set([...currentSavedPostIds].filter((postId) => !recentlyUnsavedSavedPosts.has(postId)));
}),
);
};
export const getIsPostPriorityEnabled = async (database: Database) => {
const cfg = await getConfigValue(database, 'PostPriority');
return cfg === 'true';
};
export const getIsPostAcknowledgementsEnabled = async (database: Database) => {
const cfg = await getConfigValue(database, 'PostAcknowledgements');
return cfg === 'true';
};
export const observeIsPostPriorityEnabled = (database: Database) => {
return observeConfigBooleanValue(database, 'PostPriority');
};
export const observeIsBoREnabled = (database: Database) => {
const featureEnabled = observeConfigBooleanValue(database, 'EnableBurnOnRead');
const licenseValid = observeIsMinimumLicenseTier(database, SKU_SHORT_NAME.EnterpriseAdvanced);
return combineLatest([featureEnabled, licenseValid]).pipe(
switchMap(([enabled, licensed]) => of$(enabled && licensed)),
);
};
export const observeBoRConfig = (database: Database) => {
const borDurationSecondsObservable = observeConfigIntValue(database, 'BurnOnReadDurationSeconds');
const maxBoRDurationSecondsStringObservable = observeConfigIntValue(database, 'BurnOnReadMaximumTimeToLiveSeconds');
// merge all observables and return single observable of object with both values
return combineLatest([borDurationSecondsObservable, maxBoRDurationSecondsStringObservable]).pipe(
switchMap(([borDurationSeconds, borMaximumTimeToLiveSeconds]) => {
const borConfig = {
enabled: false,
borDurationSeconds: borDurationSeconds || parseInt(DEFAULT_BURN_ON_READ_DURATION_SECONDS, 10),
borMaximumTimeToLiveSeconds: borMaximumTimeToLiveSeconds || parseInt(DEFAULT_BURN_ON_READ_MAXIMUM_TTL_SECONDS, 10),
};
return of$(borConfig);
}),
);
};
export const observeIsPostAcknowledgementsEnabled = (database: Database) => {
return observeConfigBooleanValue(database, 'PostAcknowledgements');
};
export const observePersistentNotificationsEnabled = (database: Database) => {
const user = observeCurrentUser(database);
const enabledForAll = observeConfigBooleanValue(database, 'AllowPersistentNotifications');
const enabledForGuests = observeConfigBooleanValue(database, 'AllowPersistentNotificationsForGuests');
return user.pipe(
combineLatestWith(enabledForAll, enabledForGuests),
switchMap(([u, forAll, forGuests]) => {
if (u?.isGuest) {
return of$(forAll && forGuests);
}
return of$(forAll);
}),
distinctUntilChanged(),
);
};
export const countUsersFromMentions = async (database: Database, mentions: string[]) => {
const groupsQuery = queryGroupsByNames(database, mentions).fetch();
const usersQuery = queryUsersByUsername(database, mentions).fetchCount();
const [groups, usersCount] = await Promise.all([groupsQuery, usersQuery]);
return groups.reduce((acc, v) => acc + v.memberCount, usersCount);
};
export const queryPostsWithPermalinkReferences = async (
database: Database,
referencedPostId: string,
): Promise<PostModel[]> => {
try {
const clauses: Q.Clause[] = [
Q.where('metadata', Q.notEq(null)),
Q.where('delete_at', Q.eq(0)),
];
const postsWithMetadata = await database.get<PostModel>(POST).
query(...clauses).
fetch();
const referencingPosts: PostModel[] = [];
for (const post of postsWithMetadata) {
const metadata = post.metadata;
if (metadata?.embeds?.length) {
for (const embed of metadata.embeds) {
if (embed.type === 'permalink' && embed.data?.post_id === referencedPostId) {
referencingPosts.push(post);
break;
}
}
}
}
return referencingPosts;
} catch (error) {
return [];
}
};
/**
* Find posts that contain permalink previews referencing the given post ID
*/
export const findPostsWithPermalinkReferences = async (
database: Database,
referencedPostId: string,
): Promise<PostModel[]> => {
try {
const referencingPosts = await queryPostsWithPermalinkReferences(database, referencedPostId);
return referencingPosts;
} catch (error) {
logWarning('Error finding posts with permalink references:', error);
return [];
}
};
/**
* Synchronize permalink previews when a post is edited
*/
export const syncPermalinkPreviewsForEditedPost = async (
database: Database,
editedPost: Post,
): Promise<PostModel[]> => {
try {
const referencingPosts = await findPostsWithPermalinkReferences(
database,
editedPost.id,
);
if (!referencingPosts.length) {
return [];
}
const updatedPosts: PostModel[] = [];
for (const referencingPost of referencingPosts) {
const updatedPost = updatePermalinkMetadata(
referencingPost,
editedPost.id,
editedPost,
);
if (updatedPost) {
updatedPosts.push(updatedPost);
}
}
logDebug(`Updated ${updatedPosts.length} permalink previews for edited post ${editedPost.id}`);
return updatedPosts;
} catch (error) {
logWarning('Error syncing permalink previews for edited post:', error);
return [];
}
};