mirror of
https://github.com/mattermost/mattermost-mobile.git
synced 2026-11-06 19:00:14 +00:00
* 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>
586 lines
20 KiB
TypeScript
586 lines
20 KiB
TypeScript
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
|
// See LICENSE.txt for license information.
|
|
|
|
import {markTeamThreadsAsRead, markThreadAsViewed, processReceivedThreads, switchToThread, updateTeamThreadsSync, updateThread} from '@actions/local/thread';
|
|
import {fetchPostThread} from '@actions/remote/post';
|
|
import {General} from '@constants';
|
|
import DatabaseManager from '@database/manager';
|
|
import {removeDuplicatesModels} from '@helpers/database';
|
|
import PushNotifications from '@init/push_notifications';
|
|
import AppsManager from '@managers/apps_manager';
|
|
import NetworkManager from '@managers/network_manager';
|
|
import {getPostById} from '@queries/servers/post';
|
|
import {getConfigValue, getCurrentChannelId, getCurrentTeamId} from '@queries/servers/system';
|
|
import {getIsCRTEnabled, getThreadById, getTeamThreadsSyncData} from '@queries/servers/thread';
|
|
import {getCurrentUser} from '@queries/servers/user';
|
|
import {getFullErrorMessage} from '@utils/errors';
|
|
import {logDebug, logError} from '@utils/log';
|
|
import {showThreadFollowingSnackbar} from '@utils/snack_bar';
|
|
import {getThreadsListEdges} from '@utils/thread';
|
|
|
|
import {forceLogoutIfNecessary} from './session';
|
|
|
|
import type {Client} from '@client/rest';
|
|
import type Model from '@nozbe/watermelondb/Model';
|
|
|
|
type FetchThreadsOptions = {
|
|
before?: string;
|
|
after?: string;
|
|
perPage?: number;
|
|
deleted?: boolean;
|
|
unread?: boolean;
|
|
since?: number;
|
|
totalsOnly?: boolean;
|
|
excludeDirect?: boolean;
|
|
};
|
|
|
|
enum Direction {
|
|
Up,
|
|
Down,
|
|
}
|
|
|
|
export const fetchAndSwitchToThread = async (serverUrl: string, rootId: string, isFromNotification = false, groupLabel?: RequestGroupLabel) => {
|
|
const database = DatabaseManager.serverDatabases[serverUrl]?.database;
|
|
if (!database) {
|
|
return {error: `${serverUrl} database not found`};
|
|
}
|
|
|
|
// Load thread before we open to the thread modal
|
|
fetchPostThread(serverUrl, rootId, undefined, false, groupLabel);
|
|
|
|
// Mark thread as read
|
|
const isCRTEnabled = await getIsCRTEnabled(database);
|
|
if (isCRTEnabled) {
|
|
const post = await getPostById(database, rootId);
|
|
if (post) {
|
|
const thread = await getThreadById(database, rootId);
|
|
if (thread?.isFollowing) {
|
|
markThreadAsViewed(serverUrl, thread.id);
|
|
}
|
|
}
|
|
}
|
|
|
|
await switchToThread(serverUrl, rootId, isFromNotification);
|
|
|
|
if (await AppsManager.isAppsEnabled(serverUrl)) {
|
|
// Getting the post again in case we didn't had it at the beginning
|
|
const post = await getPostById(database, rootId);
|
|
const currentChannelId = await getCurrentChannelId(database);
|
|
|
|
if (post) {
|
|
if (currentChannelId === post?.channelId) {
|
|
AppsManager.copyMainBindingsToThread(serverUrl, currentChannelId);
|
|
} else {
|
|
AppsManager.fetchBindings(serverUrl, post.channelId, true, groupLabel);
|
|
}
|
|
}
|
|
}
|
|
|
|
return {};
|
|
};
|
|
|
|
export const fetchThread = async (serverUrl: string, teamId: string, threadId: string, extended?: boolean) => {
|
|
try {
|
|
const client = NetworkManager.getClient(serverUrl);
|
|
const thread = await client.getThread('me', teamId, threadId, extended);
|
|
|
|
await processReceivedThreads(serverUrl, [thread], teamId);
|
|
|
|
return {data: thread};
|
|
} catch (error) {
|
|
logDebug('error on fetchThread', getFullErrorMessage(error));
|
|
forceLogoutIfNecessary(serverUrl, error);
|
|
return {error};
|
|
}
|
|
};
|
|
|
|
export const updateTeamThreadsAsRead = async (serverUrl: string, teamId: string) => {
|
|
try {
|
|
const client = NetworkManager.getClient(serverUrl);
|
|
const data = await client.updateTeamThreadsAsRead('me', teamId);
|
|
|
|
// Update locally
|
|
await markTeamThreadsAsRead(serverUrl, teamId);
|
|
|
|
return {data};
|
|
} catch (error) {
|
|
logDebug('error on updateTeamThreadsAsRead', getFullErrorMessage(error));
|
|
forceLogoutIfNecessary(serverUrl, error);
|
|
return {error};
|
|
}
|
|
};
|
|
|
|
export const markThreadAsRead = async (serverUrl: string, teamId: string | undefined, threadId: string, updateLastViewed = true) => {
|
|
try {
|
|
const client = NetworkManager.getClient(serverUrl);
|
|
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
|
|
|
|
const timestamp = Date.now();
|
|
|
|
// DM/GM doesn't have a teamId, so we pass the current team id
|
|
let threadTeamId = teamId;
|
|
if (!threadTeamId) {
|
|
threadTeamId = await getCurrentTeamId(database);
|
|
}
|
|
const data = await client.markThreadAsRead('me', threadTeamId, threadId, timestamp);
|
|
|
|
// Update locally
|
|
await updateThread(serverUrl, threadId, {
|
|
last_viewed_at: updateLastViewed ? timestamp : undefined,
|
|
unread_replies: 0,
|
|
unread_mentions: 0,
|
|
});
|
|
|
|
const isCRTEnabled = await getIsCRTEnabled(database);
|
|
const post = await getPostById(database, threadId);
|
|
if (post) {
|
|
if (isCRTEnabled) {
|
|
PushNotifications.removeThreadNotifications(serverUrl, threadId);
|
|
} else {
|
|
PushNotifications.removeChannelNotifications(serverUrl, post.channelId);
|
|
}
|
|
}
|
|
|
|
return {data};
|
|
} catch (error) {
|
|
logDebug('error on markThreadAsRead', getFullErrorMessage(error));
|
|
forceLogoutIfNecessary(serverUrl, error);
|
|
return {error};
|
|
}
|
|
};
|
|
|
|
export const markThreadAsUnread = async (serverUrl: string, teamId: string, threadId: string, postId: string) => {
|
|
try {
|
|
const client = NetworkManager.getClient(serverUrl);
|
|
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
|
|
|
|
// DM/GM doesn't have a teamId, so we pass the current team id
|
|
let threadTeamId = teamId;
|
|
if (!threadTeamId) {
|
|
threadTeamId = await getCurrentTeamId(database);
|
|
}
|
|
|
|
const data = await client.markThreadAsUnread('me', threadTeamId, threadId, postId);
|
|
|
|
// Update locally using response data so unread_replies is set immediately
|
|
// (without waiting for the THREAD_READ_CHANGED WS event)
|
|
const post = await getPostById(database, postId);
|
|
if (post) {
|
|
await updateThread(serverUrl, threadId, {
|
|
last_viewed_at: post.createAt - 1,
|
|
viewed_at: post.createAt - 1,
|
|
unread_replies: data?.unread_replies ?? 1,
|
|
unread_mentions: data?.unread_mentions ?? 0,
|
|
});
|
|
}
|
|
|
|
return {data};
|
|
} catch (error) {
|
|
logDebug('error on markThreadAsUnread', getFullErrorMessage(error));
|
|
forceLogoutIfNecessary(serverUrl, error);
|
|
return {error};
|
|
}
|
|
};
|
|
|
|
export const updateThreadFollowing = async (serverUrl: string, teamId: string, threadId: string, state: boolean, showSnackBar: boolean) => {
|
|
try {
|
|
const client = NetworkManager.getClient(serverUrl);
|
|
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
|
|
|
|
// DM/GM doesn't have a teamId, so we pass the current team id
|
|
let threadTeamId = teamId;
|
|
if (!threadTeamId) {
|
|
threadTeamId = await getCurrentTeamId(database);
|
|
}
|
|
|
|
const data = await client.updateThreadFollow('me', threadTeamId, threadId, state);
|
|
|
|
// Update locally
|
|
await updateThread(serverUrl, threadId, {is_following: state});
|
|
|
|
if (showSnackBar) {
|
|
const onUndo = () => updateThreadFollowing(serverUrl, teamId, threadId, !state, false);
|
|
showThreadFollowingSnackbar(state, onUndo);
|
|
}
|
|
|
|
return {data};
|
|
} catch (error) {
|
|
logDebug('error on updateThreadFollowing', getFullErrorMessage(error));
|
|
forceLogoutIfNecessary(serverUrl, error);
|
|
return {error};
|
|
}
|
|
};
|
|
|
|
export const fetchThreads = async (
|
|
serverUrl: string,
|
|
teamId: string,
|
|
options: FetchThreadsOptions,
|
|
direction?: Direction,
|
|
pages?: number,
|
|
groupLabel?: RequestGroupLabel,
|
|
) => {
|
|
const operator = DatabaseManager.serverDatabases[serverUrl]?.operator;
|
|
if (!operator) {
|
|
return {error: `${serverUrl} database not found`};
|
|
}
|
|
const {database} = operator;
|
|
|
|
let client: Client;
|
|
try {
|
|
client = NetworkManager.getClient(serverUrl);
|
|
} catch (error) {
|
|
return {error};
|
|
}
|
|
|
|
const fetchDirection = direction ?? Direction.Up;
|
|
|
|
const currentUser = await getCurrentUser(database);
|
|
if (!currentUser) {
|
|
return {error: 'currentUser not found'};
|
|
}
|
|
|
|
const version = await getConfigValue(database, 'Version');
|
|
const threadsData: Thread[] = [];
|
|
|
|
let currentPage = 0;
|
|
const fetchThreadsFunc = async (opts: FetchThreadsOptions) => {
|
|
const {before, after, perPage = General.CRT_CHUNK_SIZE, deleted, unread, since, excludeDirect = false} = opts;
|
|
|
|
currentPage++;
|
|
const {threads} = await client.getThreads(
|
|
currentUser.id, teamId,
|
|
before, after, perPage,
|
|
deleted, unread, since, false, version,
|
|
excludeDirect, groupLabel,
|
|
);
|
|
if (threads.length) {
|
|
// Mark all fetched threads as following
|
|
for (const thread of threads) {
|
|
thread.is_following = thread.is_following ?? true;
|
|
}
|
|
|
|
threadsData.push(...threads);
|
|
|
|
if (threads.length === perPage && (pages == null || currentPage < pages!)) {
|
|
const newOptions: FetchThreadsOptions = {perPage, deleted, unread, since};
|
|
if (fetchDirection === Direction.Down) {
|
|
const last = threads[threads.length - 1];
|
|
newOptions.before = last.id;
|
|
} else {
|
|
const first = threads[0];
|
|
newOptions.after = first.id;
|
|
}
|
|
await fetchThreadsFunc(newOptions);
|
|
}
|
|
}
|
|
};
|
|
|
|
try {
|
|
await fetchThreadsFunc(options);
|
|
} catch (error) {
|
|
logDebug('error on fetchThreads', getFullErrorMessage(error));
|
|
if (__DEV__) {
|
|
throw error;
|
|
}
|
|
return {error};
|
|
}
|
|
|
|
return {error: false, threads: threadsData};
|
|
};
|
|
|
|
export const syncThreadsIfNeeded = async (
|
|
serverUrl: string, isCRTEnabled: boolean, teams?: Team[],
|
|
fetchOnly = false, groupLabel?: RequestGroupLabel,
|
|
) => {
|
|
try {
|
|
if (!isCRTEnabled) {
|
|
return {models: []};
|
|
}
|
|
|
|
const {operator} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
|
|
const promises = [];
|
|
const models: Model[][] = [];
|
|
|
|
if (teams?.length) {
|
|
for (const team of teams) {
|
|
promises.push(syncTeamThreads(serverUrl, team.id, {excludeDirect: true, fetchOnly: true, groupLabel}));
|
|
}
|
|
}
|
|
|
|
if (promises.length) {
|
|
const results = await Promise.all(promises);
|
|
for (const r of results) {
|
|
if (r.models?.length) {
|
|
models.push(r.models);
|
|
}
|
|
}
|
|
}
|
|
|
|
const flat = removeDuplicatesModels(models.flat());
|
|
if (!fetchOnly && flat.length) {
|
|
await operator.batchRecords(flat, 'syncThreadsIfNeeded');
|
|
}
|
|
|
|
return {models: flat};
|
|
} catch (error) {
|
|
logError('syncThreadsIfNeeded: Error', error);
|
|
return {error, models: undefined};
|
|
}
|
|
};
|
|
|
|
type SyncThreadOptions = {
|
|
excludeDirect?: boolean;
|
|
fetchOnly?: boolean;
|
|
refresh?: boolean;
|
|
groupLabel?: RequestGroupLabel;
|
|
}
|
|
|
|
export const syncTeamThreads = async (
|
|
serverUrl: string,
|
|
teamId: string,
|
|
{
|
|
excludeDirect = false,
|
|
fetchOnly = false,
|
|
refresh = false,
|
|
groupLabel,
|
|
}: SyncThreadOptions = {},
|
|
) => {
|
|
try {
|
|
const {database, operator} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
|
|
const syncData = await getTeamThreadsSyncData(database, teamId);
|
|
const syncDataUpdate = {
|
|
id: teamId,
|
|
} as TeamThreadsSync;
|
|
|
|
const threads: Thread[] = [];
|
|
|
|
/**
|
|
* If Syncing for the first time,
|
|
* - Get all unread threads to show the right badges
|
|
* - Get latest threads to show by default in the global threads screen
|
|
* Else
|
|
* - Get all threads since last sync
|
|
*/
|
|
if (!syncData || !syncData?.latest) {
|
|
const [allUnreadThreads, latestThreads] = await Promise.all([
|
|
fetchThreads(
|
|
serverUrl,
|
|
teamId,
|
|
{unread: true, excludeDirect},
|
|
Direction.Down,
|
|
undefined,
|
|
groupLabel,
|
|
),
|
|
fetchThreads(
|
|
serverUrl,
|
|
teamId,
|
|
{excludeDirect},
|
|
undefined,
|
|
1,
|
|
groupLabel,
|
|
),
|
|
]);
|
|
if (allUnreadThreads.error || latestThreads.error) {
|
|
return {error: allUnreadThreads.error || latestThreads.error};
|
|
}
|
|
|
|
if (latestThreads.threads?.length) {
|
|
// We are fetching the threads for the first time. We get "latest" and "earliest" values.
|
|
// At this point we may receive threads without replies, so we also check the post.create_at timestamp.
|
|
const {earliestThread, latestThread} = getThreadsListEdges(latestThreads.threads);
|
|
syncDataUpdate.latest = Math.max(latestThread.last_viewed_at, latestThread.last_reply_at, latestThread.post.create_at);
|
|
syncDataUpdate.earliest = earliestThread.last_reply_at || earliestThread.post.create_at;
|
|
|
|
threads.push(...latestThreads.threads);
|
|
}
|
|
if (allUnreadThreads.threads?.length) {
|
|
const dedupe = new Set(latestThreads.threads?.map((t) => t.id));
|
|
const unread = allUnreadThreads.threads.filter((u) => !dedupe.has(u.id));
|
|
threads.push(...unread);
|
|
}
|
|
} else {
|
|
const [allUnreadThreads, allNewThreads] = await Promise.all([
|
|
fetchThreads(
|
|
serverUrl,
|
|
teamId,
|
|
{unread: true, excludeDirect},
|
|
Direction.Down,
|
|
undefined,
|
|
groupLabel,
|
|
),
|
|
fetchThreads(
|
|
serverUrl,
|
|
teamId,
|
|
{deleted: true, since: refresh ? undefined : syncData.latest + 1, excludeDirect},
|
|
Direction.Down,
|
|
undefined,
|
|
groupLabel,
|
|
),
|
|
]);
|
|
|
|
if (allNewThreads.error) {
|
|
return {error: allNewThreads.error};
|
|
}
|
|
if (allNewThreads.threads?.length) {
|
|
// As we are syncing, we get all new threads and we will update the "latest" value.
|
|
const {latestThread} = getThreadsListEdges(allNewThreads.threads);
|
|
const latestDate = Math.max(latestThread.last_reply_at, latestThread.last_viewed_at, latestThread.post.create_at);
|
|
syncDataUpdate.latest = Math.max(syncData.latest, latestDate);
|
|
|
|
threads.push(...allNewThreads.threads);
|
|
}
|
|
if (allUnreadThreads.threads?.length) {
|
|
const dedupe = new Set(allNewThreads.threads?.map((t) => t.id));
|
|
const unread = allUnreadThreads.threads.filter((u) => !dedupe.has(u.id));
|
|
threads.push(...unread);
|
|
}
|
|
}
|
|
|
|
const models: Model[] = [];
|
|
|
|
if (threads.length) {
|
|
const {error, models: threadModels = []} = await processReceivedThreads(serverUrl, threads, teamId, true);
|
|
if (error) {
|
|
return {error};
|
|
}
|
|
|
|
if (threadModels?.length) {
|
|
models.push(...threadModels);
|
|
}
|
|
|
|
if (syncDataUpdate.earliest || syncDataUpdate.latest) {
|
|
const {models: updateModels} = await updateTeamThreadsSync(serverUrl, syncDataUpdate, true);
|
|
if (updateModels?.length) {
|
|
models.push(...updateModels);
|
|
}
|
|
}
|
|
|
|
if (!fetchOnly && models?.length) {
|
|
try {
|
|
await operator.batchRecords(models, 'syncTeamThreads');
|
|
} catch (err) {
|
|
if (__DEV__) {
|
|
throw err;
|
|
}
|
|
return {error: err};
|
|
}
|
|
}
|
|
}
|
|
return {error: false, models};
|
|
} catch (error) {
|
|
return {error};
|
|
}
|
|
};
|
|
|
|
export const loadEarlierThreads = async (serverUrl: string, teamId: string, lastThreadId: string, prepareRecordsOnly = false) => {
|
|
try {
|
|
const {operator} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
|
|
|
|
/*
|
|
* - We will fetch one page of old threads
|
|
* - Update the sync data with the earliest thread last_reply_at timestamp
|
|
*/
|
|
const fetchedThreads = await fetchThreads(
|
|
serverUrl,
|
|
teamId,
|
|
{
|
|
before: lastThreadId,
|
|
},
|
|
undefined,
|
|
1,
|
|
);
|
|
if (fetchedThreads.error) {
|
|
return {error: fetchedThreads.error};
|
|
}
|
|
|
|
const models: Model[] = [];
|
|
const threads = fetchedThreads.threads || [];
|
|
|
|
if (threads?.length) {
|
|
const {error, models: threadModels = []} = await processReceivedThreads(serverUrl, threads, teamId, true);
|
|
if (error) {
|
|
return {error};
|
|
}
|
|
|
|
if (threadModels?.length) {
|
|
models.push(...threadModels);
|
|
}
|
|
|
|
const {earliestThread} = getThreadsListEdges(threads);
|
|
const syncDataUpdate = {
|
|
id: teamId,
|
|
earliest: earliestThread.last_reply_at,
|
|
} as TeamThreadsSync;
|
|
const {models: updateModels} = await updateTeamThreadsSync(serverUrl, syncDataUpdate, true);
|
|
if (updateModels?.length) {
|
|
models.push(...updateModels);
|
|
}
|
|
|
|
if (!prepareRecordsOnly && models?.length) {
|
|
try {
|
|
await operator.batchRecords(models, 'loadEarlierThreads');
|
|
} catch (err) {
|
|
if (__DEV__) {
|
|
throw err;
|
|
}
|
|
return {error: err};
|
|
}
|
|
}
|
|
}
|
|
|
|
return {models, threads};
|
|
} catch (error) {
|
|
return {error};
|
|
}
|
|
};
|
|
|
|
const handlePostDeletedForChannelIfNeededBatch: Record<string, {
|
|
timeout: NodeJS.Timeout | undefined;
|
|
teamIds: Set<string>;
|
|
}> = {};
|
|
|
|
const handlePostDeletedForChannelIfNeededBatchTimeout = 500;
|
|
|
|
export const batchTeamThreadSync = async (serverUrl: string, teamId: string) => {
|
|
try {
|
|
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
|
|
const isCRTEnabled = await getIsCRTEnabled(database);
|
|
if (!isCRTEnabled) {
|
|
return;
|
|
}
|
|
|
|
let existingBatch = handlePostDeletedForChannelIfNeededBatch[serverUrl];
|
|
if (!existingBatch) {
|
|
existingBatch = {
|
|
timeout: undefined,
|
|
teamIds: new Set(),
|
|
};
|
|
handlePostDeletedForChannelIfNeededBatch[serverUrl] = existingBatch;
|
|
}
|
|
|
|
clearTimeout(existingBatch.timeout);
|
|
|
|
existingBatch.teamIds.add(teamId);
|
|
|
|
existingBatch.timeout = setTimeout(async () => {
|
|
const batch = handlePostDeletedForChannelIfNeededBatch[serverUrl];
|
|
if (!batch) {
|
|
return;
|
|
}
|
|
delete handlePostDeletedForChannelIfNeededBatch[serverUrl];
|
|
|
|
const includeDirect = batch.teamIds.has('');
|
|
const teamIds = Array.from(batch.teamIds).filter((t) => t !== '');
|
|
const promises = teamIds.map((t, idx) => syncTeamThreads(serverUrl, t, {excludeDirect: !includeDirect || idx !== 0, refresh: true, fetchOnly: false}));
|
|
const results = await Promise.all(promises);
|
|
for (const r of results) {
|
|
if (r.error) {
|
|
logError('batchTeamThreadSync: Error', r.error);
|
|
}
|
|
}
|
|
}, handlePostDeletedForChannelIfNeededBatchTimeout);
|
|
} catch (error) {
|
|
logError('handlePostDeletedForChannelIfNeeded: Error', error);
|
|
}
|
|
};
|