pleroma/src/queries/chats.ts

280 lines
8.8 KiB
TypeScript
Raw Normal View History

2023-10-17 13:19:05 -07:00
import { InfiniteData, keepPreviousData, useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query';
import sumBy from 'lodash/sumBy';
2022-08-10 05:38:49 -07:00
2022-09-29 10:36:35 -07:00
import { importFetchedAccount, importFetchedAccounts } from 'soapbox/actions/importer';
2022-09-15 07:49:09 -07:00
import { getNextLink } from 'soapbox/api';
2022-11-02 12:28:16 -07:00
import { ChatWidgetScreens, useChatContext } from 'soapbox/contexts/chat-context';
import { useStatContext } from 'soapbox/contexts/stat-context';
2022-11-09 09:24:44 -08:00
import { useApi, useAppDispatch, useAppSelector, useFeatures, useOwnAccount } from 'soapbox/hooks';
import { normalizeChatMessage } from 'soapbox/normalizers';
import { ChatMessage } from 'soapbox/types/entities';
import { reOrderChatListItems } from 'soapbox/utils/chats';
import { flattenPages, PaginatedResult, updatePageItem } from 'soapbox/utils/queries';
2022-08-10 05:38:49 -07:00
2022-08-16 10:38:17 -07:00
import { queryClient } from './client';
import { useFetchRelationships } from './relationships';
2022-08-16 10:38:17 -07:00
2023-06-20 12:24:39 -07:00
import type { Account } from 'soapbox/schemas';
2022-09-08 09:47:19 -07:00
2022-08-10 05:38:49 -07:00
export interface IChat {
account: Account;
created_at: string;
id: string;
2022-08-26 09:41:25 -07:00
last_message: null | {
account_id: string;
chat_id: string;
content: string;
created_at: string;
id: string;
unread: boolean;
};
unread: number;
2022-08-10 05:38:49 -07:00
}
const ChatKeys = {
chat: (chatId?: string) => ['chats', 'chat', chatId] as const,
2022-09-27 12:42:24 -07:00
chatMessages: (chatId: string) => ['chats', 'messages', chatId] as const,
};
2022-10-25 10:10:53 -07:00
const useChatMessages = (chat: IChat) => {
2022-08-10 05:38:49 -07:00
const api = useApi();
2022-10-25 10:10:53 -07:00
const isBlocked = useAppSelector((state) => state.getIn(['relationships', chat.account.id, 'blocked_by']));
2022-08-10 05:38:49 -07:00
const getChatMessages = async (chatId: string, pageParam?: any): Promise<PaginatedResult<ChatMessage>> => {
2022-09-15 07:49:09 -07:00
const nextPageLink = pageParam?.link;
const uri = nextPageLink || `/api/v1/pleroma/chats/${chatId}/messages`;
2022-12-06 13:12:24 -08:00
const response = await api.get<any[]>(uri);
2022-09-15 07:49:09 -07:00
const { data } = response;
2022-08-10 05:38:49 -07:00
2022-09-15 07:49:09 -07:00
const link = getNextLink(response);
const hasMore = !!link;
2022-12-06 13:12:24 -08:00
const result = data.map(normalizeChatMessage);
2022-08-10 05:38:49 -07:00
return {
result,
2022-09-15 07:49:09 -07:00
link,
2022-08-10 05:38:49 -07:00
hasMore,
};
};
2023-10-17 13:19:05 -07:00
const queryInfo = useInfiniteQuery({
queryKey: ChatKeys.chatMessages(chat.id),
queryFn: ({ pageParam }) => getChatMessages(chat.id, pageParam),
2022-10-25 10:10:53 -07:00
enabled: !isBlocked,
2023-10-17 13:19:05 -07:00
gcTime: 0,
2022-11-03 10:55:33 -07:00
staleTime: 0,
2023-10-17 13:19:05 -07:00
initialPageParam: { link: undefined as string | undefined },
2022-08-10 05:38:49 -07:00
getNextPageParam: (config) => {
if (config.hasMore) {
2022-09-15 07:49:09 -07:00
return { link: config.link };
2022-08-10 05:38:49 -07:00
}
return undefined;
},
});
2022-12-06 13:12:24 -08:00
const data = flattenPages(queryInfo.data)?.reverse();
2022-08-10 05:38:49 -07:00
return {
...queryInfo,
data,
};
};
2022-08-26 09:41:25 -07:00
const useChats = () => {
2022-08-10 05:38:49 -07:00
const api = useApi();
2022-09-08 09:47:19 -07:00
const dispatch = useAppDispatch();
2022-09-22 14:04:52 -07:00
const features = useFeatures();
const { setUnreadChatsCount } = useStatContext();
const fetchRelationships = useFetchRelationships();
2022-08-10 05:38:49 -07:00
const getChats = async (pageParam?: any): Promise<PaginatedResult<IChat>> => {
2022-09-22 14:04:52 -07:00
const endpoint = features.chatsV2 ? '/api/v2/pleroma/chats' : '/api/v1/pleroma/chats';
2022-09-15 07:49:09 -07:00
const nextPageLink = pageParam?.link;
2022-09-22 14:04:52 -07:00
const uri = nextPageLink || endpoint;
const response = await api.get<IChat[]>(uri);
2022-09-15 07:49:09 -07:00
const { data } = response;
2022-08-26 09:41:25 -07:00
2022-09-15 07:49:09 -07:00
const link = getNextLink(response);
const hasMore = !!link;
2022-08-26 09:41:25 -07:00
setUnreadChatsCount(Number(response.headers['x-unread-messages-count']) || sumBy(data, (chat) => chat.unread));
2022-09-08 09:47:19 -07:00
// Set the relationships to these users in the redux store.
fetchRelationships.mutate({ accountIds: data.map((item) => item.account.id) });
2022-09-29 10:36:35 -07:00
dispatch(importFetchedAccounts(data.map((item) => item.account)));
2022-09-08 09:47:19 -07:00
2022-08-26 09:41:25 -07:00
return {
result: data,
hasMore,
2022-09-15 07:49:09 -07:00
link,
2022-08-26 09:41:25 -07:00
};
2022-08-10 05:38:49 -07:00
};
2023-10-17 13:19:05 -07:00
const queryInfo = useInfiniteQuery({
queryKey: ['chats', 'search'],
2023-10-17 13:19:05 -07:00
queryFn: ({ pageParam }) => getChats(pageParam),
placeholderData: keepPreviousData,
enabled: features.chats,
2023-10-17 13:19:05 -07:00
initialPageParam: { link: undefined as string | undefined },
2022-08-26 09:41:25 -07:00
getNextPageParam: (config) => {
if (config.hasMore) {
2022-09-15 07:49:09 -07:00
return { link: config.link };
2022-08-26 09:41:25 -07:00
}
return undefined;
},
2022-08-10 05:38:49 -07:00
});
2022-12-06 13:12:24 -08:00
const data = flattenPages(queryInfo.data);
2022-08-26 09:41:25 -07:00
const chatsQuery = {
...queryInfo,
data,
};
2022-08-10 05:38:49 -07:00
const getOrCreateChatByAccountId = (accountId: string) => api.post<IChat>(`/api/v1/pleroma/chats/by-account-id/${accountId}`);
return { chatsQuery, getOrCreateChatByAccountId };
};
const useChat = (chatId?: string) => {
const api = useApi();
2022-09-29 10:36:35 -07:00
const dispatch = useAppDispatch();
const fetchRelationships = useFetchRelationships();
const getChat = async () => {
if (chatId) {
const { data } = await api.get<IChat>(`/api/v1/pleroma/chats/${chatId}`);
2022-09-29 10:36:35 -07:00
fetchRelationships.mutate({ accountIds: [data.account.id] });
2022-09-29 10:36:35 -07:00
dispatch(importFetchedAccount(data.account));
return data;
}
};
2023-10-17 13:19:05 -07:00
return useQuery<IChat | undefined>({
queryKey: ChatKeys.chat(chatId),
queryFn: getChat,
gcTime: 0,
2022-11-02 12:28:16 -07:00
enabled: !!chatId,
});
};
2022-09-28 13:20:59 -07:00
const useChatActions = (chatId: string) => {
2023-06-25 10:35:09 -07:00
const { account } = useOwnAccount();
2022-08-10 05:38:49 -07:00
const api = useApi();
2022-12-20 07:47:46 -08:00
// const dispatch = useAppDispatch();
2022-11-09 09:24:44 -08:00
const { setUnreadChatsCount } = useStatContext();
2022-11-02 12:28:16 -07:00
const { chat, changeScreen } = useChatContext();
2022-08-10 05:38:49 -07:00
2022-10-28 10:01:39 -07:00
const markChatAsRead = async (lastReadId: string) => {
return api.post<IChat>(`/api/v1/pleroma/chats/${chatId}/read`, { last_read_id: lastReadId })
.then(({ data }) => {
updatePageItem(['chats', 'search'], data, (o, n) => o.id === n.id);
const queryData = queryClient.getQueryData<InfiniteData<PaginatedResult<unknown>>>(['chats', 'search']);
2022-10-28 10:01:39 -07:00
if (queryData) {
const flattenedQueryData: any = flattenPages(queryData)?.map((chat: any) => {
if (chat.id === data.id) {
return data;
} else {
return chat;
}
});
setUnreadChatsCount(sumBy(flattenedQueryData, (chat: IChat) => chat.unread));
}
2022-10-28 10:01:39 -07:00
return data;
})
2022-08-30 07:10:31 -07:00
.catch(() => null);
};
2022-08-10 05:38:49 -07:00
2023-10-17 13:19:05 -07:00
const createChatMessage = useMutation({
mutationFn: ({ chatId, content, mediaIds }: { chatId: string; content: string; mediaIds?: string[] }) => {
return api.post<ChatMessage>(`/api/v1/pleroma/chats/${chatId}/messages`, {
2023-02-08 10:24:41 -08:00
content,
media_id: (mediaIds && mediaIds.length === 1) ? mediaIds[0] : undefined, // Pleroma backwards-compat
media_ids: mediaIds,
});
},
2023-10-17 13:19:05 -07:00
retry: false,
onMutate: async (variables) => {
// Cancel any outgoing refetches (so they don't overwrite our optimistic update)
await queryClient.cancelQueries({
queryKey: ['chats', 'messages', variables.chatId],
});
2022-11-09 09:24:44 -08:00
2023-10-17 13:19:05 -07:00
// Snapshot the previous value
const prevContent = variables.content;
const prevChatMessages = queryClient.getQueryData(['chats', 'messages', variables.chatId]);
const pendingId = String(Number(new Date()));
2022-11-09 09:24:44 -08:00
2023-10-17 13:19:05 -07:00
// Optimistically update to the new value
queryClient.setQueryData(ChatKeys.chatMessages(variables.chatId), (prevResult: any) => {
const newResult = { ...prevResult };
newResult.pages = newResult.pages.map((page: any, idx: number) => {
if (idx === 0) {
return {
...page,
result: [
normalizeChatMessage({
content: variables.content,
id: pendingId,
created_at: new Date(),
account_id: account?.id,
pending: true,
unread: true,
}),
...page.result,
],
};
}
return page;
2022-11-09 09:24:44 -08:00
});
2023-10-17 13:19:05 -07:00
return newResult;
});
return { prevChatMessages, prevContent, pendingId };
2022-11-09 09:24:44 -08:00
},
2023-10-17 13:19:05 -07:00
// If the mutation fails, use the context returned from onMutate to roll back
onError: (_error: any, variables, context: any) => {
queryClient.setQueryData(['chats', 'messages', variables.chatId], context.prevChatMessages);
},
onSuccess: (response: any, variables, context) => {
const nextChat = { ...chat, last_message: response.data };
updatePageItem(['chats', 'search'], nextChat, (o, n) => o.id === n.id);
2023-10-17 13:19:05 -07:00
updatePageItem(
ChatKeys.chatMessages(variables.chatId),
normalizeChatMessage(response.data),
(o) => o.id === context.pendingId,
);
reOrderChatListItems();
},
});
2022-08-16 05:39:58 -07:00
const deleteChatMessage = (chatMessageId: string) => api.delete<IChat>(`/api/v1/pleroma/chats/${chatId}/messages/${chatMessageId}`);
2023-10-17 13:19:05 -07:00
const deleteChat = useMutation({
mutationFn: () => api.delete<IChat>(`/api/v1/pleroma/chats/${chatId}`),
2022-11-02 12:28:16 -07:00
onSuccess() {
changeScreen(ChatWidgetScreens.INBOX);
2023-10-17 13:19:05 -07:00
queryClient.invalidateQueries({ queryKey: ChatKeys.chatMessages(chatId) });
queryClient.invalidateQueries({ queryKey: ['chats', 'search'] });
},
2023-10-17 13:19:05 -07:00
});
return {
createChatMessage,
deleteChat,
deleteChatMessage,
markChatAsRead,
};
2022-08-10 05:38:49 -07:00
};
export { ChatKeys, useChat, useChatActions, useChats, useChatMessages };