Skip to content

Commit

Permalink
Web: Fixed the download and preview file not auth.
Browse files Browse the repository at this point in the history
  • Loading branch information
baifachuan committed Nov 26, 2024
1 parent 07bb2a6 commit d6e4413
Show file tree
Hide file tree
Showing 9 changed files with 130 additions and 50 deletions.
2 changes: 1 addition & 1 deletion api/apps/file_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ def rename():


@manager.route('/get/<file_id>', methods=['GET'])
# @login_required
@login_required
def get(file_id):
try:
e, file = FileService.get_by_id(file_id)
Expand Down
2 changes: 2 additions & 0 deletions web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"@ant-design/icons": "^5.2.6",
"@ant-design/pro-components": "^2.6.46",
"@ant-design/pro-layout": "^7.17.16",
"@antv/g": "^6.1.11",
"@antv/g6": "^5.0.10",
"@js-preview/excel": "^1.7.8",
"@tanstack/react-query": "^5.40.0",
Expand All @@ -46,6 +47,7 @@
"react-force-graph": "^1.44.4",
"react-i18next": "^14.0.0",
"react-markdown": "^9.0.1",
"react-pdf": "^9.1.1",
"react-pdf-highlighter": "^6.1.0",
"react-string-replace": "^1.1.1",
"react-syntax-highlighter": "^15.5.0",
Expand Down
34 changes: 34 additions & 0 deletions web/src/hooks/file-manager-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ResponseType } from '@/interfaces/database/base';
import { IFolder } from '@/interfaces/database/file-manager';
import { IConnectRequestBody } from '@/interfaces/request/file-manager';
import fileManagerService from '@/services/file-manager-service';
import { downloadFileFromBlob } from '@/utils/file-util';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { PaginationProps, UploadFile, message } from 'antd';
import React, { useCallback } from 'react';
Expand Down Expand Up @@ -114,6 +115,39 @@ export const useDeleteFile = () => {
return { data, loading, deleteFile: mutateAsync };
};

export const useDownloadFile = () => {
const {
data,
isPending: loading,
mutateAsync,
} = useMutation({
mutationKey: ['downloadFile'],
mutationFn: async (params: { id: string; filename?: string }) => {
const response = await fileManagerService.getFile({}, params.id);
const blob = new Blob([response.data], { type: response.data.type });
downloadFileFromBlob(blob, params.filename);
},
});
return { data, loading, downloadFile: mutateAsync };
};

export const useLoadFile = () => {
const {
data,
isPending: loading,
mutateAsync,
error,
} = useMutation({
mutationKey: ['downloadFile'],
mutationFn: async (params: { id: string }) => {
const response = await fileManagerService.getFile({}, params.id);
const blob = new Blob([response.data], { type: response.data.type });
return blob;
},
});
return { data, loading, loadFile: mutateAsync, error };
};

export const useRenameFile = () => {
const queryClient = useQueryClient();
const { t } = useTranslation();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { useShowDeleteConfirm, useTranslate } from '@/hooks/common-hooks';
import { useRemoveNextDocument } from '@/hooks/document-hooks';
import { IDocumentInfo } from '@/interfaces/database/document';
import { api_host } from '@/utils/api';
import { downloadFile } from '@/utils/file-util';
import { downloadDocument } from '@/utils/file-util';
import {
DeleteOutlined,
DownloadOutlined,
Expand Down Expand Up @@ -40,8 +39,8 @@ const ParsingActionCell = ({
};

const onDownloadDocument = () => {
downloadFile({
url: `${api_host}/document/get/${documentId}`,
downloadDocument({
id: documentId,
filename: record.name,
});
};
Expand Down
53 changes: 32 additions & 21 deletions web/src/pages/document-viewer/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { Authorization } from '@/constants/authorization';
import { getAuthorization } from '@/utils/authorization-util';
import jsPreviewExcel from '@js-preview/excel';
import axios from 'axios';
import mammoth from 'mammoth';
Expand All @@ -23,7 +25,12 @@ export const useCatchError = (api: string) => {

export const useFetchDocument = () => {
const fetchDocument = useCallback(async (api: string) => {
const ret = await axios.get(api, { responseType: 'arraybuffer' });
const ret = await axios.get(api, {
headers: {
[Authorization]: getAuthorization(),
},
responseType: 'arraybuffer',
});
return ret;
}, []);

Expand Down Expand Up @@ -64,30 +71,34 @@ export const useFetchExcel = (filePath: string) => {

export const useFetchDocx = (filePath: string) => {
const [succeed, setSucceed] = useState(true);
const [error, setError] = useState<string>();
const { fetchDocument } = useFetchDocument();
const containerRef = useRef<HTMLDivElement>(null);
const { error } = useCatchError(filePath);

const fetchDocumentAsync = useCallback(async () => {
const jsonFile = await fetchDocument(filePath);
mammoth
.convertToHtml(
{ arrayBuffer: jsonFile.data },
{ includeDefaultStyleMap: true },
)
.then((result) => {
setSucceed(true);
const docEl = document.createElement('div');
docEl.className = 'document-container';
docEl.innerHTML = result.value;
const container = containerRef.current;
if (container) {
container.innerHTML = docEl.outerHTML;
}
})
.catch(() => {
setSucceed(false);
});
try {
const jsonFile = await fetchDocument(filePath);
mammoth
.convertToHtml(
{ arrayBuffer: jsonFile.data },
{ includeDefaultStyleMap: true },
)
.then((result) => {
setSucceed(true);
const docEl = document.createElement('div');
docEl.className = 'document-container';
docEl.innerHTML = result.value;
const container = containerRef.current;
if (container) {
container.innerHTML = docEl.outerHTML;
}
})
.catch(() => {
setSucceed(false);
});
} catch (error: any) {
setError(error.toString());
}
}, [filePath, fetchDocument]);

useEffect(() => {
Expand Down
16 changes: 13 additions & 3 deletions web/src/pages/document-viewer/pdf/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import { Authorization } from '@/constants/authorization';
import { getAuthorization } from '@/utils/authorization-util';
import { Skeleton } from 'antd';
import { PdfHighlighter, PdfLoader } from 'react-pdf-highlighter';
import FileError from '../file-error';
import { useCatchError } from '../hooks';
type PdfLoaderProps = React.ComponentProps<typeof PdfLoader> & {
httpHeaders?: Record<string, string>;
};

const Loader = PdfLoader as React.ComponentType<PdfLoaderProps>;

interface IProps {
url: string;
Expand All @@ -10,11 +17,14 @@ interface IProps {
const PdfPreviewer = ({ url }: IProps) => {
const { error } = useCatchError(url);
const resetHash = () => {};

const httpHeaders = {
[Authorization]: getAuthorization(),
};
return (
<div style={{ width: '100%', height: '100%' }}>
<PdfLoader
<Loader
url={url}
httpHeaders={httpHeaders}
beforeLoad={<Skeleton active />}
workerSrc="/pdfjs-dist/pdf.worker.min.js"
errorMessage={<FileError>{error}</FileError>}
Expand All @@ -37,7 +47,7 @@ const PdfPreviewer = ({ url }: IProps) => {
/>
);
}}
</PdfLoader>
</Loader>
</div>
);
};
Expand Down
13 changes: 9 additions & 4 deletions web/src/pages/file-manager/action-cell/index.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import NewDocumentLink from '@/components/new-document-link';
import SvgIcon from '@/components/svg-icon';
import { useTranslate } from '@/hooks/common-hooks';
import { useDownloadFile } from '@/hooks/file-manager-hooks';
import { IFile } from '@/interfaces/database/file-manager';
import { api_host } from '@/utils/api';
import {
getExtension,
isSupportedPreviewDocumentType,
} from '@/utils/document-util';
import { downloadFile } from '@/utils/file-util';
import {
DeleteOutlined,
DownloadOutlined,
Expand Down Expand Up @@ -42,12 +41,13 @@ const ActionCell = ({
[documentId],
setSelectedRowKeys,
);
const { downloadFile, loading } = useDownloadFile();
const extension = getExtension(record.name);
const isKnowledgeBase = record.source_type === 'knowledgebase';

const onDownloadDocument = () => {
downloadFile({
url: `${api_host}/file/get/${documentId}`,
id: documentId,
filename: record.name,
});
};
Expand Down Expand Up @@ -106,7 +106,12 @@ const ActionCell = ({
)}
{record.type !== 'folder' && (
<Tooltip title={t('download', { keyPrefix: 'common' })}>
<Button type="text" disabled={beingUsed} onClick={onDownloadDocument}>
<Button
type="text"
disabled={beingUsed}
loading={loading}
onClick={onDownloadDocument}
>
<DownloadOutlined size={20} />
</Button>
</Tooltip>
Expand Down
7 changes: 6 additions & 1 deletion web/src/services/file-manager-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,16 @@ const methods = {
url: connectFileToKnowledge,
method: 'post',
},
getDocumentFile: {
getFile: {
url: getFile,
method: 'get',
responseType: 'blob',
},
getDocumentFile: {
url: get_document_file,
method: 'get',
responseType: 'blob',
},
moveFile: {
url: moveFile,
method: 'post',
Expand Down
46 changes: 30 additions & 16 deletions web/src/utils/file-util.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import fileManagerService from '@/services/file-manager-service';
import { UploadFile } from 'antd';

export const transformFile2Base64 = (val: any): Promise<any> => {
Expand Down Expand Up @@ -62,28 +63,41 @@ export const getBase64FromUploadFileList = async (fileList?: UploadFile[]) => {
return '';
};

export const downloadFile = ({
url,
export const downloadFileFromBlob = (blob: Blob, name?: string) => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
if (name) {
a.download = name;
}
a.click();
window.URL.revokeObjectURL(url);
};

export const downloadFile = async ({
id,
filename,
target,
}: {
url: string;
id: string;
filename?: string;
target?: string;
}) => {
const downloadElement = document.createElement('a');
downloadElement.style.display = 'none';
downloadElement.href = url;
if (target) {
downloadElement.target = '_blank';
}
downloadElement.rel = 'noopener noreferrer';
if (filename) {
downloadElement.download = filename;
}
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
const response = await fileManagerService.getFile({}, id);
const blob = new Blob([response.data], { type: response.data.type });
downloadFileFromBlob(blob, filename);
};

export const downloadDocument = async ({
id,
filename,
}: {
id: string;
filename?: string;
}) => {
const response = await fileManagerService.getDocumentFile({}, id);
const blob = new Blob([response.data], { type: response.data.type });
downloadFileFromBlob(blob, filename);
};

const Units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
Expand Down

0 comments on commit d6e4413

Please sign in to comment.