forked from Ivasoft/mattermost-mobile
[MM-22671] [MM-22935] Fetch posts for unread channels on loadChannelsForTeam (#4078)
* Fetch posts for unread channels on loadChannelsForTeam * Add unit tests * Remove unneeded setRetryFailed and getState * Update getChannelSinceValue comment * Move to post.js and pass in channels and channelMembers * Exclude current channel * Address PR review comments * Fix import * Fix mm-redux references
This commit is contained in:
committed by
Miguel Alatzar
parent
f39b98e4d1
commit
b2190b7b9a
217
NOTICE.txt
217
NOTICE.txt
@@ -876,223 +876,6 @@ SOFTWARE.
|
||||
|
||||
---
|
||||
|
||||
## mattermost-redux
|
||||
|
||||
This product contains 'mattermost-redux' by Mattermost.
|
||||
|
||||
Common code (API client, Redux stores, logic, utility functions) for building a Mattermost client
|
||||
|
||||
* HOMEPAGE:
|
||||
* https://github.com/mattermost/mattermost-redux
|
||||
|
||||
* LICENSE: Apache-2.0
|
||||
|
||||
Copyright 2015-present Mattermost, Inc.
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
---
|
||||
|
||||
## mime-db
|
||||
|
||||
This product contains 'mime-db' by Douglas Christopher Wilson.
|
||||
|
||||
@@ -213,7 +213,7 @@ export async function fetchChannelAndMyMember(channelId: string): Promise<Array<
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// do nothing
|
||||
// do nothing
|
||||
}
|
||||
|
||||
return actions;
|
||||
|
||||
@@ -26,16 +26,15 @@ import {
|
||||
import {getCurrentUserId} from '@mm-redux/selectors/entities/users';
|
||||
import {getTeamByName} from '@mm-redux/selectors/entities/teams';
|
||||
|
||||
import {getChannelByName as getChannelByNameSelector} from '@mm-redux/utils/channel_utils';
|
||||
import {getChannelByName as selectChannelByName} from '@mm-redux/utils/channel_utils';
|
||||
import EventEmitter from '@mm-redux/utils/event_emitter';
|
||||
import {getLastCreateAt} from '@mm-redux/utils/post_utils';
|
||||
|
||||
import {loadSidebarDirectMessagesProfiles} from '@actions/helpers/channels';
|
||||
import {getPosts, getPostsBefore, getPostsSince, getPostThread} from '@actions/views/post';
|
||||
import {getPosts, getPostsBefore, getPostsSince, getPostThread, loadUnreadChannelPosts} from '@actions/views/post';
|
||||
import {INSERT_TO_COMMENT, INSERT_TO_DRAFT} from '@constants/post_textbox';
|
||||
import {getChannelReachable} from '@selectors/channel';
|
||||
import telemetry from '@telemetry';
|
||||
import {isDirectChannelVisible, isGroupChannelVisible} from '@utils/channels';
|
||||
import {isDirectChannelVisible, isGroupChannelVisible, getChannelSinceValue} from '@utils/channels';
|
||||
import {isPendingPost} from '@utils/general';
|
||||
|
||||
const MAX_RETRIES = 3;
|
||||
@@ -59,36 +58,22 @@ export function loadChannelsByTeamName(teamName, errorHandler) {
|
||||
export function loadPostsIfNecessaryWithRetry(channelId) {
|
||||
return async (dispatch, getState) => {
|
||||
const state = getState();
|
||||
const {posts} = state.entities.posts;
|
||||
const postsIds = getPostIdsInChannel(state, channelId);
|
||||
const postIds = getPostIdsInChannel(state, channelId);
|
||||
const actions = [];
|
||||
|
||||
const time = Date.now();
|
||||
|
||||
let loadMorePostsVisible = true;
|
||||
let postAction;
|
||||
if (!postsIds || postsIds.length < ViewTypes.POST_VISIBILITY_CHUNK_SIZE) {
|
||||
if (!postIds || postIds.length < ViewTypes.POST_VISIBILITY_CHUNK_SIZE) {
|
||||
// Get the first page of posts if it appears we haven't gotten it yet, like the webapp
|
||||
postAction = getPosts(channelId);
|
||||
} else {
|
||||
const lastConnectAt = state.websocket?.lastConnectAt || 0;
|
||||
const lastGetPosts = state.views.channel.lastGetPosts[channelId];
|
||||
|
||||
let since;
|
||||
if (lastGetPosts && lastGetPosts < lastConnectAt) {
|
||||
// Since the websocket disconnected, we may have missed some posts since then
|
||||
since = lastGetPosts;
|
||||
} else {
|
||||
// Trust that we've received all posts since the last time the websocket disconnected
|
||||
// so just get any that have changed since the latest one we've received
|
||||
const postsForChannel = postsIds.map((id) => posts[id]);
|
||||
since = getLastCreateAt(postsForChannel);
|
||||
}
|
||||
|
||||
const since = getChannelSinceValue(state, channelId, postIds);
|
||||
postAction = getPostsSince(channelId, since);
|
||||
}
|
||||
|
||||
const received = await retryGetPostsAction(postAction, dispatch, getState);
|
||||
const received = await dispatch(fetchPostActionWithRetry(postAction));
|
||||
|
||||
if (received) {
|
||||
actions.push({
|
||||
@@ -109,17 +94,20 @@ export function loadPostsIfNecessaryWithRetry(channelId) {
|
||||
};
|
||||
}
|
||||
|
||||
export async function retryGetPostsAction(action, dispatch, getState, maxTries = MAX_RETRIES) {
|
||||
for (let i = 0; i <= maxTries; i++) {
|
||||
const {data} = await dispatch(action); // eslint-disable-line no-await-in-loop
|
||||
export function fetchPostActionWithRetry(action, maxTries = MAX_RETRIES) {
|
||||
return async (dispatch) => {
|
||||
for (let i = 0; i <= maxTries; i++) {
|
||||
const {data} = await dispatch(action); // eslint-disable-line no-await-in-loop
|
||||
|
||||
if (data) {
|
||||
return data;
|
||||
if (data) {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dispatch(setChannelRetryFailed(true));
|
||||
return null;
|
||||
dispatch(setChannelRetryFailed(true));
|
||||
|
||||
return null;
|
||||
};
|
||||
}
|
||||
|
||||
export function loadFilesForPostIfNecessary(postId) {
|
||||
@@ -209,7 +197,7 @@ export function selectDefaultChannel(teamId) {
|
||||
const state = getState();
|
||||
|
||||
const channelsInTeam = getChannelsNameMapInTeam(state, teamId);
|
||||
const channel = getChannelByNameSelector(channelsInTeam, getRedirectChannelNameForTeam(state, teamId));
|
||||
const channel = selectChannelByName(channelsInTeam, getRedirectChannelNameForTeam(state, teamId));
|
||||
let channelId;
|
||||
if (channel) {
|
||||
channelId = channel.id;
|
||||
@@ -470,9 +458,9 @@ export function closeGMChannel(channel) {
|
||||
}
|
||||
|
||||
export function refreshChannelWithRetry(channelId) {
|
||||
return async (dispatch, getState) => {
|
||||
return async (dispatch) => {
|
||||
dispatch(setChannelRefreshing(true));
|
||||
const posts = await retryGetPostsAction(getPosts(channelId), dispatch, getState);
|
||||
const posts = await dispatch(fetchPostActionWithRetry(getPosts(channelId)));
|
||||
const actions = [setChannelRefreshing(false)];
|
||||
|
||||
if (posts) {
|
||||
@@ -572,7 +560,8 @@ export function increasePostVisibility(channelId, postId) {
|
||||
|
||||
const pageSize = ViewTypes.POST_VISIBILITY_CHUNK_SIZE;
|
||||
|
||||
const result = await retryGetPostsAction(getPostsBefore(channelId, postId, 0, pageSize), dispatch, getState);
|
||||
const postAction = getPostsBefore(channelId, postId, 0, pageSize);
|
||||
const result = await dispatch(fetchPostActionWithRetry(postAction));
|
||||
|
||||
const actions = [{
|
||||
type: ViewTypes.LOADING_POSTS,
|
||||
@@ -664,6 +653,8 @@ export function loadChannelsForTeam(teamId, skipDispatch = false) {
|
||||
|
||||
// Fetch needed profiles from channel creators and direct channels
|
||||
dispatch(loadSidebar(data));
|
||||
|
||||
dispatch(loadUnreadChannelPosts(data.channels, data.channelMembers));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import initialState from 'app/initial_state';
|
||||
import {ChannelTypes} from '@mm-redux/action_types';
|
||||
import testHelper from 'test/test_helper';
|
||||
|
||||
import {ViewTypes} from 'app/constants';
|
||||
import * as ChannelActions from 'app/actions/views/channel';
|
||||
const {
|
||||
handleSelectChannel,
|
||||
@@ -213,7 +214,7 @@ describe('Actions.Views.Channel', () => {
|
||||
const storeActions = store.getActions();
|
||||
const storeBatchActions = storeActions.filter(({type}) => type === 'BATCH_LOAD_POSTS_IN_CHANNEL');
|
||||
const receivedPosts = storeActions.find(({type}) => type === MOCK_RECEIVED_POSTS);
|
||||
const receivedPostsAtAction = storeBatchActions[0].payload.some((action) => action.type === 'RECEIVED_POSTS_FOR_CHANNEL_AT_TIME');
|
||||
const receivedPostsAtAction = storeBatchActions[0].payload.some((action) => action.type === ViewTypes.RECEIVED_POSTS_FOR_CHANNEL_AT_TIME);
|
||||
|
||||
nextPostState = postReducer(store.getState().entities.posts, receivedPosts);
|
||||
nextPostState = postReducer(nextPostState, {
|
||||
|
||||
@@ -17,11 +17,14 @@ import {
|
||||
} from '@mm-redux/actions/posts';
|
||||
import {Client4} from '@mm-redux/client';
|
||||
import {Posts} from '@mm-redux/constants';
|
||||
import {getPost as selectPost} from '@mm-redux/selectors/entities/posts';
|
||||
import {getPost as selectPost, getPostIdsInChannel} from '@mm-redux/selectors/entities/posts';
|
||||
import {getCurrentChannelId} from '@mm-redux/selectors/entities/channels';
|
||||
import {removeUserFromList} from '@mm-redux/utils/user_utils';
|
||||
import {isUnreadChannel} from '@mm-redux/utils/channel_utils';
|
||||
|
||||
import {ViewTypes} from 'app/constants';
|
||||
import {generateId} from 'app/utils/file';
|
||||
import {ViewTypes} from '@constants';
|
||||
import {generateId} from '@utils/file';
|
||||
import {getChannelSinceValue} from '@utils/channels';
|
||||
|
||||
import {getEmojisInPosts} from './emoji';
|
||||
|
||||
@@ -390,4 +393,85 @@ function userMetadataToLoadFromPosts(state, posts = []) {
|
||||
userIds: Array.from(userIdsToLoad),
|
||||
statuses: Array.from(statusesToLoad),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function loadUnreadChannelPosts(channels, channelMembers) {
|
||||
return async (dispatch, getState) => {
|
||||
const state = getState();
|
||||
const currentChannelId = getCurrentChannelId(state);
|
||||
|
||||
const promises = [];
|
||||
const promiseTrace = [];
|
||||
|
||||
const channelMembersByChannel = {};
|
||||
channelMembers.forEach((member) => {
|
||||
channelMembersByChannel[member.channel_id] = member;
|
||||
});
|
||||
|
||||
channels.forEach((channel) => {
|
||||
if (channel.id === currentChannelId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isUnread = isUnreadChannel(channelMembersByChannel, channel);
|
||||
if (!isUnread) {
|
||||
return;
|
||||
}
|
||||
|
||||
const postIds = getPostIdsInChannel(state, channel.id);
|
||||
|
||||
let promise;
|
||||
const trace = {
|
||||
channelId: channel.id,
|
||||
since: false,
|
||||
};
|
||||
if (!postIds || !postIds.length) {
|
||||
// Get the first page of posts if it appears we haven't gotten it yet, like the webapp
|
||||
promise = Client4.getPosts(channel.id);
|
||||
} else {
|
||||
const since = getChannelSinceValue(state, channel.id, postIds);
|
||||
promise = Client4.getPostsSince(channel.id, since);
|
||||
trace.since = since;
|
||||
}
|
||||
|
||||
promises.push(promise);
|
||||
promiseTrace.push(trace);
|
||||
});
|
||||
|
||||
let posts = [];
|
||||
const actions = [];
|
||||
if (promises.length) {
|
||||
const results = await Promise.all(promises);
|
||||
results.forEach((data, index) => {
|
||||
const channelPosts = Object.values(data.posts);
|
||||
if (channelPosts.length) {
|
||||
posts = posts.concat(channelPosts);
|
||||
|
||||
const trace = promiseTrace[index];
|
||||
if (trace.since) {
|
||||
actions.push(receivedPostsSince(data, trace.channelId));
|
||||
} else {
|
||||
actions.push(receivedPostsInChannel(data, trace.channelId, true, data.prev_post_id === ''));
|
||||
}
|
||||
|
||||
actions.push({
|
||||
type: ViewTypes.RECEIVED_POSTS_FOR_CHANNEL_AT_TIME,
|
||||
channelId: trace.channelId,
|
||||
time: Date.now(),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
console.log(`Fetched ${posts.length} posts from ${promises.length} unread channels`); //eslint-disable-line no-console
|
||||
if (posts.length) {
|
||||
actions.push(receivedPosts({posts}));
|
||||
const additional = await dispatch(getPostsAdditionalDataBatch(posts));
|
||||
if (additional.length) {
|
||||
actions.push(...additional);
|
||||
}
|
||||
|
||||
dispatch(batchActions(actions));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
125
app/actions/views/post.test.js
Normal file
125
app/actions/views/post.test.js
Normal file
@@ -0,0 +1,125 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import configureStore from 'redux-mock-store';
|
||||
import thunk from 'redux-thunk';
|
||||
|
||||
import {Client4} from '@mm-redux/client';
|
||||
import {PostTypes} from '@mm-redux/action_types';
|
||||
|
||||
import * as PostSelectors from '@mm-redux/selectors/entities/posts';
|
||||
import * as ChannelUtils from '@mm-redux/utils/channel_utils';
|
||||
|
||||
import {ViewTypes} from 'app/constants';
|
||||
import initialState from 'app/initial_state';
|
||||
|
||||
import {loadUnreadChannelPosts} from '@actions/views/post';
|
||||
|
||||
describe('Actions.Views.Post', () => {
|
||||
const mockStore = configureStore([thunk]);
|
||||
|
||||
let store;
|
||||
const currentChannelId = 'current-channel-id';
|
||||
const storeObj = {
|
||||
...initialState,
|
||||
entities: {
|
||||
...initialState.entities,
|
||||
channels: {
|
||||
...initialState.entities.channels,
|
||||
currentChannelId,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const channels = [
|
||||
{id: 'channel-1'},
|
||||
{id: 'channel-2'},
|
||||
{id: 'channel-3'},
|
||||
];
|
||||
const channelMembers = [];
|
||||
|
||||
test('loadUnreadChannelPosts does not dispatch actions if no unread channels', async () => {
|
||||
ChannelUtils.isUnreadChannel = jest.fn().mockReturnValue(false);
|
||||
|
||||
store = mockStore(storeObj);
|
||||
await store.dispatch(loadUnreadChannelPosts(channels, channelMembers));
|
||||
|
||||
const storeActions = store.getActions();
|
||||
expect(storeActions).toStrictEqual([]);
|
||||
});
|
||||
|
||||
test('loadUnreadChannelPosts does not dispatch actions for current channel', async () => {
|
||||
ChannelUtils.isUnreadChannel = jest.fn().mockReturnValue(true);
|
||||
Client4.getPosts = jest.fn().mockResolvedValue({posts: ['post-1', 'post-2']});
|
||||
|
||||
store = mockStore(storeObj);
|
||||
await store.dispatch(loadUnreadChannelPosts([{id: currentChannelId}], channelMembers));
|
||||
|
||||
const storeActions = store.getActions();
|
||||
expect(storeActions).toStrictEqual([]);
|
||||
});
|
||||
|
||||
test('loadUnreadChannelPosts dispatches actions for unread channels with no postIds in channel', async () => {
|
||||
ChannelUtils.isUnreadChannel = jest.fn().mockReturnValue(true);
|
||||
Client4.getPosts = jest.fn().mockResolvedValue({posts: ['post-1', 'post-2']});
|
||||
|
||||
store = mockStore(storeObj);
|
||||
await store.dispatch(loadUnreadChannelPosts(channels, channelMembers));
|
||||
|
||||
const actionTypes = store.getActions()[0].payload.map((action) => action.type);
|
||||
|
||||
// Actions dispatched:
|
||||
// RECEIVED_POSTS_IN_CHANNEL and RECEIVED_POSTS_FOR_CHANNEL_AT_TIME for each channel.
|
||||
// RECEIVED_POSTS once, with all channel posts combined.
|
||||
expect(actionTypes.length).toBe((2 * channels.length) + 1);
|
||||
|
||||
const receivedPostsInChannelActions = actionTypes.filter((type) => type === PostTypes.RECEIVED_POSTS_IN_CHANNEL);
|
||||
expect(receivedPostsInChannelActions.length).toBe(channels.length);
|
||||
|
||||
const receivedPostsForChannelAtTimeActions = actionTypes.filter((type) => type === ViewTypes.RECEIVED_POSTS_FOR_CHANNEL_AT_TIME);
|
||||
expect(receivedPostsForChannelAtTimeActions.length).toBe(channels.length);
|
||||
|
||||
const receivedPosts = actionTypes.filter((type) => type === 'RECEIVED_POSTS');
|
||||
expect(receivedPosts.length).toBe(1);
|
||||
});
|
||||
|
||||
test('loadUnreadChannelPosts dispatches actions for unread channels with postIds in channel', async () => {
|
||||
ChannelUtils.isUnreadChannel = jest.fn().mockReturnValue(true);
|
||||
PostSelectors.getPostIdsInChannel = jest.fn().mockReturnValue(['post-id-in-channel']);
|
||||
Client4.getPostsSince = jest.fn().mockResolvedValue({posts: ['post-1', 'post-2']});
|
||||
|
||||
const lastGetPosts = {};
|
||||
channels.forEach((channel) => {
|
||||
lastGetPosts[channel.id] = Date.now();
|
||||
});
|
||||
const lastConnectAt = Date.now() + 1000;
|
||||
store = mockStore({
|
||||
...storeObj,
|
||||
views: {
|
||||
channel: {
|
||||
lastGetPosts,
|
||||
},
|
||||
},
|
||||
websocket: {
|
||||
lastConnectAt,
|
||||
},
|
||||
});
|
||||
await store.dispatch(loadUnreadChannelPosts(channels, channelMembers));
|
||||
|
||||
const actionTypes = store.getActions()[0].payload.map((action) => action.type);
|
||||
|
||||
// Actions dispatched:
|
||||
// RECEIVED_POSTS_SINCE and RECEIVED_POSTS_FOR_CHANNEL_AT_TIME for each channel.
|
||||
// RECEIVED_POSTS once, with all channel posts combined.
|
||||
expect(actionTypes.length).toBe((2 * channels.length) + 1);
|
||||
|
||||
const receivedPostsInChannelActions = actionTypes.filter((type) => type === PostTypes.RECEIVED_POSTS_SINCE);
|
||||
expect(receivedPostsInChannelActions.length).toBe(channels.length);
|
||||
|
||||
const receivedPostsForChannelAtTimeActions = actionTypes.filter((type) => type === ViewTypes.RECEIVED_POSTS_FOR_CHANNEL_AT_TIME);
|
||||
expect(receivedPostsForChannelAtTimeActions.length).toBe(channels.length);
|
||||
|
||||
const receivedPosts = actionTypes.filter((type) => type === PostTypes.RECEIVED_POSTS);
|
||||
expect(receivedPosts.length).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -129,7 +129,7 @@ export function purgeOfflineStore() {
|
||||
return {type: General.OFFLINE_STORE_PURGE};
|
||||
}
|
||||
|
||||
// A non-optimistic version of the createPost action in mattermost-redux with the file handling
|
||||
// A non-optimistic version of the createPost action in app/mm-redux with the file handling
|
||||
// removed since it's not needed.
|
||||
export function createPostForNotificationReply(post) {
|
||||
return async (dispatch, getState) => {
|
||||
|
||||
@@ -137,7 +137,6 @@ export function doReconnect(now: number) {
|
||||
const currentTeamId = getCurrentTeamId(state);
|
||||
const currentChannelId = getCurrentChannelId(state);
|
||||
const currentUserId = getCurrentUserId(state);
|
||||
const currentUser = getCurrentUser(state);
|
||||
const users = getUsers(state);
|
||||
const {lastDisconnectAt} = state.websocket;
|
||||
const actions: Array<GenericAction> = [];
|
||||
|
||||
@@ -100,7 +100,7 @@ export function getCustomEmojis(
|
||||
page = 0,
|
||||
perPage: number = General.PAGE_SIZE_DEFAULT,
|
||||
sort: string = Emoji.SORT_BY_NAME,
|
||||
loadUsers = false
|
||||
loadUsers = false,
|
||||
): ActionFunc {
|
||||
return async (dispatch: DispatchFunc, getState: GetStateFunc) => {
|
||||
let data;
|
||||
|
||||
@@ -20,7 +20,7 @@ export function getPing(): ActionFunc {
|
||||
let data;
|
||||
let pingError = new FormattedError(
|
||||
'mobile.server_ping_failed',
|
||||
'Cannot connect to the server. Please check your server URL and internet connection.'
|
||||
'Cannot connect to the server. Please check your server URL and internet connection.',
|
||||
);
|
||||
try {
|
||||
data = await Client4.ping();
|
||||
|
||||
@@ -173,11 +173,11 @@ export function searchGfycat({searchText, count = 30, startIndex = 0}: { searchT
|
||||
Client4.trackEvent(
|
||||
'gfycat',
|
||||
'views',
|
||||
{context, count: json.gfycats.length, keyword: searchText}
|
||||
{context, count: json.gfycats.length, keyword: searchText},
|
||||
);
|
||||
}
|
||||
}).catch(
|
||||
(err: any) => dispatch(errorSearching(err, searchText))
|
||||
(err: any) => dispatch(errorSearching(err, searchText)),
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -207,7 +207,7 @@ export function searchCategory({tagName = '', gfyCount = 30, cursorPos = undefin
|
||||
Client4.trackEvent(
|
||||
'gfycat',
|
||||
'views',
|
||||
{context: 'category', count: json.gfycats.length, keyword: tagName}
|
||||
{context: 'category', count: json.gfycats.length, keyword: tagName},
|
||||
);
|
||||
|
||||
// preload categories list
|
||||
@@ -215,7 +215,7 @@ export function searchCategory({tagName = '', gfyCount = 30, cursorPos = undefin
|
||||
dispatch(requestCategoriesListIfNeeded() as any);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
).catch((err: any) => dispatch(errorSearching(err, tagName)));
|
||||
};
|
||||
}
|
||||
@@ -276,7 +276,7 @@ export function searchById(gfyId: string) {
|
||||
(response: any) => {
|
||||
dispatch(receiveSearchById(gfyId, response.gfyItem));
|
||||
dispatch(cacheGifsRequest([response.gfyItem]));
|
||||
}
|
||||
},
|
||||
).catch((err: any) => dispatch(errorSearchById(err, gfyId)));
|
||||
};
|
||||
}
|
||||
@@ -366,7 +366,7 @@ export function requestCategoriesList({count = 60} = {}) {
|
||||
}).catch(
|
||||
(err: any) => {
|
||||
dispatch(categoriesListFailure(err));
|
||||
}
|
||||
},
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -490,7 +490,7 @@ export function pinPost(postId: string) {
|
||||
{
|
||||
type: ChannelTypes.INCREMENT_PINNED_POST_COUNT,
|
||||
id: post.channel_id,
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1087,7 +1087,7 @@ export function removePost(post: ExtendedPost) {
|
||||
{
|
||||
type: ChannelTypes.DECREMENT_PINNED_POST_COUNT,
|
||||
id: post.channel_id,
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -235,7 +235,7 @@ export function deleteTeam(teamId: string): ActionFunc {
|
||||
{
|
||||
type: TeamTypes.RECEIVED_TEAM_DELETED,
|
||||
data: {id: teamId},
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
dispatch(batchActions(actions));
|
||||
@@ -704,7 +704,7 @@ export function updateTeamMemberSchemeRoles(
|
||||
teamId: string,
|
||||
userId: string,
|
||||
isSchemeUser: boolean,
|
||||
isSchemeAdmin: boolean
|
||||
isSchemeAdmin: boolean,
|
||||
): ActionFunc {
|
||||
return bindClientFunc({
|
||||
clientFunc: async () => {
|
||||
|
||||
@@ -881,14 +881,14 @@ export function autocompleteUsers(term: string, teamId = '', channelId = '', opt
|
||||
type: UserTypes.RECEIVED_PROFILES_LIST_IN_CHANNEL,
|
||||
data: data.users,
|
||||
id: channelId,
|
||||
}
|
||||
},
|
||||
);
|
||||
actions.push(
|
||||
{
|
||||
type: UserTypes.RECEIVED_PROFILES_LIST_NOT_IN_CHANNEL,
|
||||
data: data.out_of_channel,
|
||||
id: channelId,
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -898,7 +898,7 @@ export function autocompleteUsers(term: string, teamId = '', channelId = '', opt
|
||||
type: UserTypes.RECEIVED_PROFILES_LIST_IN_TEAM,
|
||||
data: users,
|
||||
id: teamId,
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -983,7 +983,7 @@ export function startPeriodicStatusUpdates(): ActionFunc {
|
||||
|
||||
getStatusesByIds(userIds)(dispatch, getState);
|
||||
},
|
||||
General.STATUS_INTERVAL
|
||||
General.STATUS_INTERVAL,
|
||||
);
|
||||
|
||||
return {data: true};
|
||||
@@ -1253,7 +1253,7 @@ export function createUserAccessToken(userId: string, description: string): Acti
|
||||
{
|
||||
type: UserTypes.RECEIVED_MY_USER_ACCESS_TOKEN,
|
||||
data: {...data, token: ''},
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1282,7 +1282,7 @@ export function getUserAccessToken(tokenId: string): ActionFunc {
|
||||
{
|
||||
type: UserTypes.RECEIVED_MY_USER_ACCESS_TOKEN,
|
||||
data,
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1327,7 +1327,7 @@ export function getUserAccessTokensForUser(userId: string, page = 0, perPage: nu
|
||||
{
|
||||
type: UserTypes.RECEIVED_MY_USER_ACCESS_TOKENS,
|
||||
data,
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ export function createThunkMiddleware() {
|
||||
if (result instanceof Promise) {
|
||||
return result.catch((error) => {
|
||||
if (error.url) {
|
||||
// This is a connection error from mattermost-redux. This should've been handled
|
||||
// This is a connection error from app/mm-redux. This should've been handled
|
||||
// within the action itself, so we'll log to Sentry enough to identify where
|
||||
// that handling is missing.
|
||||
captureMessage(
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
import {Preferences} from '@mm-redux/constants';
|
||||
import {getUserIdFromChannelName} from '@mm-redux/utils/channel_utils';
|
||||
import {getLastCreateAt} from '@mm-redux/utils/post_utils';
|
||||
|
||||
export function isDirectChannelVisible(userId, myPreferences, channel) {
|
||||
const channelId = getUserIdFromChannelName(userId, channel.name);
|
||||
@@ -55,4 +56,23 @@ export function isDirectChannelAutoClosed(config, preferences, channelId, channe
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function getChannelSinceValue(state, channelId, postIds) {
|
||||
const lastGetPosts = state.views.channel.lastGetPosts[channelId];
|
||||
const lastConnectAt = state.websocket?.lastConnectAt || 0;
|
||||
|
||||
let since;
|
||||
if (lastGetPosts && lastGetPosts < lastConnectAt) {
|
||||
// Since the websocket disconnected, we may have missed some posts since then
|
||||
since = lastGetPosts;
|
||||
} else {
|
||||
// Trust that we've received all posts since the last time the websocket disconnected
|
||||
// so set `since` to the `create_at` of latest one we've received
|
||||
const {posts} = state.entities.posts;
|
||||
const channelPosts = postIds.map((id) => posts[id]);
|
||||
since = getLastCreateAt(channelPosts);
|
||||
}
|
||||
|
||||
return since;
|
||||
}
|
||||
|
||||
@@ -9,13 +9,13 @@ import {Client4} from '@mm-redux/client';
|
||||
import {General} from '@mm-redux/constants';
|
||||
import EventEmitter from '@mm-redux/utils/event_emitter';
|
||||
|
||||
import {markChannelViewedAndRead, retryGetPostsAction} from 'app/actions/views/channel';
|
||||
import {dismissAllModals, popToRoot} from 'app/actions/navigation';
|
||||
import {getPosts} from 'app/actions/views/post';
|
||||
import {markChannelViewedAndRead, fetchPostActionWithRetry} from '@actions/views/channel';
|
||||
import {dismissAllModals, popToRoot} from '@actions/navigation';
|
||||
import {getPosts} from '@actions/views/post';
|
||||
import {
|
||||
createPostForNotificationReply,
|
||||
loadFromPushNotification,
|
||||
} from 'app/actions/views/root';
|
||||
} from '@actions/views/root';
|
||||
|
||||
import {NavigationTypes, ViewTypes} from 'app/constants';
|
||||
import {getLocalizedMessage} from 'app/i18n';
|
||||
@@ -75,7 +75,7 @@ class PushNotificationUtils {
|
||||
dispatch(markChannelViewedAndRead(data.channel_id, null, false));
|
||||
} else if (data.type === 'message') {
|
||||
// get the posts for the channel as soon as possible
|
||||
retryGetPostsAction(getPosts(data.channel_id), dispatch, getState);
|
||||
dispatch(fetchPostActionWithRetry(getPosts(data.channel_id)));
|
||||
|
||||
if (foreground) {
|
||||
EventEmitter.emit(ViewTypes.NOTIFICATION_IN_APP, notification);
|
||||
@@ -121,7 +121,7 @@ class PushNotificationUtils {
|
||||
Client4.setToken(token);
|
||||
}
|
||||
|
||||
retryGetPostsAction(getPosts(data.channel_id), dispatch, getState);
|
||||
dispatch(fetchPostActionWithRetry(getPosts(data.channel_id)));
|
||||
const result = await dispatch(createPostForNotificationReply(post));
|
||||
if (result.error) {
|
||||
const locale = getCurrentLocale(state);
|
||||
|
||||
Reference in New Issue
Block a user