Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Delete the files uploaded in the external dialog box #1880 #1967

Merged
merged 1 commit into from
Aug 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions web/src/components/message-input/index.less
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
}
.listWrapper {
padding: 0 10px;
overflow: auto;
max-height: 170px;
}
.inputWrapper {
border-radius: 8px;
Expand Down
78 changes: 59 additions & 19 deletions web/src/components/message-input/index.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import { Authorization } from '@/constants/authorization';
import { useTranslate } from '@/hooks/common-hooks';
import {
useDeleteDocument,
useFetchDocumentInfosByIds,
useRemoveNextDocument,
} from '@/hooks/document-hooks';
import { getAuthorization } from '@/utils/authorization-util';
import { getExtension } from '@/utils/document-util';
import { formatBytes } from '@/utils/file-util';
import { CloseCircleOutlined, LoadingOutlined } from '@ant-design/icons';
import {
CloseCircleOutlined,
InfoCircleOutlined,
LoadingOutlined,
} from '@ant-design/icons';
import type { GetProp, UploadFile } from 'antd';
import {
Button,
Expand Down Expand Up @@ -41,6 +46,16 @@ const getFileIds = (fileList: UploadFile[]) => {
return ids;
};

const isUploadError = (file: UploadFile) => {
const retcode = get(file, 'response.retcode');
return typeof retcode === 'number' && retcode !== 0;
};

const isUploadSuccess = (file: UploadFile) => {
const retcode = get(file, 'response.retcode');
return typeof retcode === 'number' && retcode === 0;
};

interface IProps {
disabled: boolean;
value: string;
Expand All @@ -50,6 +65,7 @@ interface IProps {
onInputChange: ChangeEventHandler<HTMLInputElement>;
conversationId: string;
uploadUrl?: string;
isShared?: boolean;
}

const getBase64 = (file: FileType): Promise<string> =>
Expand All @@ -61,6 +77,7 @@ const getBase64 = (file: FileType): Promise<string> =>
});

const MessageInput = ({
isShared = false,
disabled,
value,
onPressEnter,
Expand All @@ -72,6 +89,7 @@ const MessageInput = ({
}: IProps) => {
const { t } = useTranslate('chat');
const { removeDocument } = useRemoveNextDocument();
const { deleteDocument } = useDeleteDocument();
const { data: documentInfos, setDocumentIds } = useFetchDocumentInfosByIds();

const [fileList, setFileList] = useState<UploadFile[]>([]);
Expand All @@ -89,7 +107,7 @@ const MessageInput = ({

const handlePressEnter = useCallback(async () => {
if (isUploadingFile) return;
const ids = getFileIds(fileList);
const ids = getFileIds(fileList.filter((x) => isUploadSuccess(x)));

onPressEnter(ids);
setFileList([]);
Expand All @@ -98,14 +116,24 @@ const MessageInput = ({
const handleRemove = useCallback(
async (file: UploadFile) => {
const ids = get(file, 'response.data', []);
if (ids.length) {
await removeDocument(ids[0]);
// Upload Successfully
if (Array.isArray(ids) && ids.length) {
if (isShared) {
await deleteDocument(ids);
} else {
await removeDocument(ids[0]);
}
setFileList((preList) => {
return preList.filter((x) => getFileId(x) !== ids[0]);
});
} else {
// Upload failed
setFileList((preList) => {
return preList.filter((x) => x.uid !== file.uid);
});
}
},
[removeDocument],
[removeDocument, deleteDocument, isShared],
);

const getDocumentInfoById = useCallback(
Expand Down Expand Up @@ -192,6 +220,11 @@ const MessageInput = ({
<LoadingOutlined style={{ fontSize: 24 }} spin />
}
/>
) : !getFileId(item) ? (
<InfoCircleOutlined
size={30}
// width={30}
></InfoCircleOutlined>
) : (
<FileIcon id={id} name={item.name}></FileIcon>
)}
Expand All @@ -202,26 +235,33 @@ const MessageInput = ({
>
<b> {item.name}</b>
</Text>
{item.percent !== 100 ? (
t('uploading')
) : !item.response ? (
t('parsing')
{isUploadError(item) ? (
t('uploadFailed')
) : (
<Space>
<span>{fileExtension?.toUpperCase()},</span>
<span>
{formatBytes(getDocumentInfoById(id)?.size ?? 0)}
</span>
</Space>
<>
{item.percent !== 100 ? (
t('uploading')
) : !item.response ? (
t('parsing')
) : (
<Space>
<span>{fileExtension?.toUpperCase()},</span>
<span>
{formatBytes(
getDocumentInfoById(id)?.size ?? 0,
)}
</span>
</Space>
)}
</>
)}
</Flex>
</Flex>

{item.status !== 'uploading' && (
<CloseCircleOutlined
className={styles.deleteIcon}
onClick={() => handleRemove(item)}
/>
<span className={styles.deleteIcon}>
<CloseCircleOutlined onClick={() => handleRemove(item)} />
</span>
)}
</Card>
</List.Item>
Expand Down
20 changes: 20 additions & 0 deletions web/src/hooks/document-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,3 +313,23 @@ export const useRemoveNextDocument = () => {

return { data, loading, removeDocument: mutateAsync };
};

export const useDeleteDocument = () => {
// const queryClient = useQueryClient();
const {
data,
isPending: loading,
mutateAsync,
} = useMutation({
mutationKey: ['deleteDocument'],
mutationFn: async (documentIds: string[]) => {
const data = await kbService.document_delete({ doc_ids: documentIds });
// if (data.retcode === 0) {
// queryClient.invalidateQueries({ queryKey: ['fetchFlowList'] });
// }
return data;
},
});

return { data, loading, deleteDocument: mutateAsync };
};
1 change: 1 addition & 0 deletions web/src/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,7 @@ The above is the content you need to summarize.`,
searching: 'searching...',
parsing: 'Parsing',
uploading: 'Uploading',
uploadFailed: 'Upload failed',
},
setting: {
profile: 'Profile',
Expand Down
1 change: 1 addition & 0 deletions web/src/locales/zh-traditional.ts
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,7 @@ export default {
searching: '搜索中',
parsing: '解析中',
uploading: '上傳中',
uploadFailed: '上傳失敗',
},
setting: {
profile: '概述',
Expand Down
1 change: 1 addition & 0 deletions web/src/locales/zh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,7 @@ export default {
searching: '搜索中',
parsing: '解析中',
uploading: '上传中',
uploadFailed: '上传失败',
},
setting: {
profile: '概要',
Expand Down
1 change: 1 addition & 0 deletions web/src/pages/chat/share/large.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ const ChatContainer = () => {
</Flex>

<MessageInput
isShared
value={value}
disabled={false}
sendDisabled={sendDisabled}
Expand Down
30 changes: 17 additions & 13 deletions web/src/pages/chat/shared-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
} from '@/hooks/chat-hooks';
import { useSendMessageWithSse } from '@/hooks/logic-hooks';
import { useOneNamespaceEffectsLoading } from '@/hooks/store-hooks';
import { IAnswer } from '@/interfaces/database/chat';
import { IAnswer, Message } from '@/interfaces/database/chat';
import api from '@/utils/api';
import omit from 'lodash/omit';
import trim from 'lodash/trim';
Expand Down Expand Up @@ -57,22 +57,23 @@ export const useSelectCurrentSharedConversation = (conversationId: string) => {

const ref = useScrollToBottom(currentConversation);

const addNewestConversation = useCallback((message: string) => {
const addNewestConversation = useCallback((message: Partial<Message>) => {
setCurrentConversation((pre) => {
return {
...pre,
message: [
...(pre.message ?? []),
{
role: MessageType.User,
content: message,
content: message.content,
doc_ids: message.doc_ids,
id: uuid(),
} as IMessage,
{
role: MessageType.Assistant,
content: '',
id: uuid(),
reference: [],
reference: {},
} as IMessage,
],
};
Expand Down Expand Up @@ -140,7 +141,7 @@ export const useSendButtonDisabled = (value: string) => {

export const useSendSharedMessage = (
conversation: IClientConversation,
addNewestConversation: (message: string) => void,
addNewestConversation: (message: Partial<Message>, answer?: string) => void,
removeLatestMessage: () => void,
setCurrentConversation: Dispatch<SetStateAction<IClientConversation>>,
addNewestAnswer: (answer: IAnswer) => void,
Expand Down Expand Up @@ -205,14 +206,17 @@ export const useSendSharedMessage = (
}
}, [answer, addNewestAnswer]);

const handlePressEnter = useCallback(() => {
if (trim(value) === '') return;
if (done) {
setValue('');
addNewestConversation(value);
handleSendMessage(value.trim());
}
}, [addNewestConversation, done, handleSendMessage, setValue, value]);
const handlePressEnter = useCallback(
(documentIds: string[]) => {
if (trim(value) === '') return;
if (done) {
setValue('');
addNewestConversation({ content: value, doc_ids: documentIds });
handleSendMessage(value.trim());
}
},
[addNewestConversation, done, handleSendMessage, setValue, value],
);

return {
handlePressEnter,
Expand Down
5 changes: 5 additions & 0 deletions web/src/services/knowledge-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const {
get_document_list,
document_change_status,
document_rm,
document_delete,
document_create,
document_change_parser,
document_thumbnails,
Expand Down Expand Up @@ -131,6 +132,10 @@ const methods = {
url: knowledge_graph,
method: 'get',
},
document_delete: {
url: document_delete,
method: 'delete',
},
};

const kbService = registerServer<keyof typeof methods>(methods, request);
Expand Down
1 change: 1 addition & 0 deletions web/src/utils/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export default {
get_document_list: `${api_host}/document/list`,
document_change_status: `${api_host}/document/change_status`,
document_rm: `${api_host}/document/rm`,
document_delete: `${api_host}/api/document`,
document_rename: `${api_host}/document/rename`,
document_create: `${api_host}/document/create`,
document_run: `${api_host}/document/run`,
Expand Down
4 changes: 3 additions & 1 deletion web/src/utils/register-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ type Service<T extends string> = Record<
(params?: any, urlAppendix?: string) => any
>;

const Methods = ['post', 'delete', 'put'];

const registerServer = <T extends string>(
opt: Record<T, { url: string; method: string }>,
request: RequestMethod,
Expand All @@ -18,7 +20,7 @@ const registerServer = <T extends string>(
if (urlAppendix) {
url = url + '/' + urlAppendix;
}
if (opt[key].method === 'post' || opt[key].method === 'POST') {
if (Methods.some((x) => x === opt[key].method.toLowerCase())) {
return request(url, {
method: opt[key].method,
data: params,
Expand Down