331 lines
14 KiB
Python
331 lines
14 KiB
Python
"""
|
|
api/chat/previews.py
|
|
|
|
用途:处理聊天来源文件、Excel、文本及原始文件预览路由。
|
|
依赖:chat.shared、chat.preview_support、Dify 与共享盘数据源。
|
|
逻辑:校验预览来源后获取文件内容,按格式转换并返回安全的预览响应。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from .shared import * # noqa: F403
|
|
from . import chat_bp
|
|
from .preview_support import (
|
|
_convert_office_to_pdf,
|
|
_detect_excel_format,
|
|
_extract_placeholder_text,
|
|
_fetch_dify_text_document,
|
|
_fetch_preview_source_bytes,
|
|
_is_allowed_preview_url,
|
|
_load_excel_workbook,
|
|
)
|
|
|
|
|
|
@chat_bp.route('/source-file', methods=['GET'])
|
|
@require_agent_permission
|
|
def resolve_source_file():
|
|
"""
|
|
Resolve original source download URL by Dify dataset/document IDs.
|
|
"""
|
|
dataset_id = (request.args.get('dataset_id') or '').strip()
|
|
remote_document_id = (request.args.get('remote_document_id') or '').strip()
|
|
if not dataset_id or not remote_document_id:
|
|
current_app.logger.warning('[source-file] missing required params: dataset_id=%r remote_document_id_present=%s remote_document_id_preview=%r query_args=%s', dataset_id, bool(remote_document_id), remote_document_id[:8] + '...' if remote_document_id else '', dict(request.args))
|
|
raise ValidationError('dataset_id and remote_document_id are required')
|
|
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
|
|
if not payload:
|
|
raise NotFoundError('source file mapping not found')
|
|
|
|
source_ext = str(payload.get('source_ext') or '').strip().lower()
|
|
source_download_url = payload.get('source_download_url')
|
|
|
|
return jsonify({
|
|
'dataset_id': dataset_id,
|
|
'remote_document_id': remote_document_id,
|
|
'source_filename': payload.get('source_filename'),
|
|
'source_ext': source_ext,
|
|
'source_download_url': source_download_url,
|
|
'download_url_expires_at': payload.get('download_url_expires_at'),
|
|
})
|
|
|
|
@chat_bp.route('/source-file-text', methods=['GET'])
|
|
@require_agent_permission
|
|
def source_file_text():
|
|
dataset_id = (request.args.get('dataset_id') or '').strip()
|
|
remote_document_id = (request.args.get('remote_document_id') or '').strip()
|
|
if not dataset_id or not remote_document_id:
|
|
raise ValidationError('dataset_id and remote_document_id are required')
|
|
|
|
text = _fetch_dify_text_document(dataset_id, remote_document_id)
|
|
if not text:
|
|
raise NotFoundError('failed to resolve text source file')
|
|
|
|
filename = f'{remote_document_id}.txt'
|
|
return Response(
|
|
text,
|
|
status=200,
|
|
mimetype='text/plain; charset=utf-8',
|
|
headers={
|
|
'Content-Disposition': f'inline; filename="{filename}"',
|
|
'Cache-Control': 'no-store',
|
|
},
|
|
)
|
|
|
|
@chat_bp.route('/preview-excel', methods=['GET'])
|
|
@require_agent_permission
|
|
def preview_excel():
|
|
"""
|
|
内网 Excel 预览接口(简版可上线)。
|
|
说明:
|
|
- xlsx 直接解析;
|
|
- xls 先转为 xlsx 后再解析。
|
|
"""
|
|
file_url = (request.args.get('url') or '').strip()
|
|
if not file_url:
|
|
raise ValidationError('url is required')
|
|
if not _is_allowed_preview_url(file_url):
|
|
raise ForbiddenError('url is not allowed for preview')
|
|
parsed = urlparse(file_url)
|
|
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
|
name = (request.args.get('name') or '').strip()
|
|
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
|
|
ext = url_path_ext or name_ext
|
|
if ext and ext not in ('xlsx', 'xls'):
|
|
raise_for_status(f'unsupported file extension: {ext}', 415)
|
|
try:
|
|
limit = int(request.args.get('limit', 100))
|
|
except ValueError:
|
|
limit = 100
|
|
limit = max(1, min(limit, 300))
|
|
content, _, err = _fetch_preview_source_bytes(file_url, max_size=50 * 1024 * 1024)
|
|
if err:
|
|
msg, code = err
|
|
raise_for_status(msg, code)
|
|
|
|
detected_ext = _detect_excel_format(content or b'', ext)
|
|
if detected_ext not in ('xlsx', 'xls'):
|
|
raise_for_status(f'unsupported file extension: {ext or detected_ext or "unknown"}', 415)
|
|
|
|
try:
|
|
wb = _load_excel_workbook(content, detected_ext)
|
|
except Exception as e:
|
|
current_app.logger.warning(
|
|
"[excel-preview] parse workbook failed ext=%s detected_ext=%s size=%s name=%s url=%s err=%r",
|
|
ext,
|
|
detected_ext,
|
|
len(content or b''),
|
|
name,
|
|
file_url,
|
|
e,
|
|
)
|
|
details: dict = {}
|
|
if current_app.config.get('DEBUG') or os.getenv('ENV_NAME', 'dev').strip().lower() == 'dev':
|
|
details = {'detail': str(e), 'ext': ext, 'detected_ext': detected_ext, 'size': len(content or b'')}
|
|
raise AppError(code='VALIDATION.UNPROCESSABLE', message='failed to parse excel file', http_status=422, details=details)
|
|
if not wb.sheetnames:
|
|
raise_for_status('workbook has no sheets', 422)
|
|
requested_sheet = (request.args.get('sheet') or '').strip()
|
|
sheet_name = requested_sheet if requested_sheet in wb.sheetnames else wb.sheetnames[0]
|
|
ws = wb[sheet_name]
|
|
rows = []
|
|
for row in ws.iter_rows(values_only=True):
|
|
normalized = []
|
|
for cell in row:
|
|
if cell is None:
|
|
normalized.append('')
|
|
elif isinstance(cell, (int, float, bool)):
|
|
normalized.append(cell)
|
|
else:
|
|
normalized.append(str(cell))
|
|
rows.append(normalized)
|
|
if len(rows) >= limit:
|
|
break
|
|
max_cols = max((len(r) for r in rows), default=0)
|
|
for r in rows:
|
|
if len(r) < max_cols:
|
|
r.extend([''] * (max_cols - len(r)))
|
|
columns = [f'COL_{i + 1}' for i in range(max_cols)]
|
|
return jsonify({'sheet_name': sheet_name, 'sheets': wb.sheetnames, 'columns': columns, 'rows': rows, 'limit': limit, 'truncated': len(rows) >= limit})
|
|
|
|
@chat_bp.route('/preview-text', methods=['GET'])
|
|
@require_agent_permission
|
|
def preview_text():
|
|
"""
|
|
文本类文件预览接口(内网代理)。
|
|
支持:md/markdown/txt/csv/vtt/properties/html/htm
|
|
"""
|
|
file_url = (request.args.get('url') or '').strip()
|
|
if not file_url:
|
|
raise ValidationError('url is required')
|
|
if not _is_allowed_preview_url(file_url):
|
|
raise ForbiddenError('url is not allowed for preview')
|
|
parsed = urlparse(file_url)
|
|
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
|
name = (request.args.get('name') or '').strip()
|
|
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
|
|
explicit_ext = (request.args.get('ext') or '').strip().lower()
|
|
ext = explicit_ext or url_path_ext or name_ext
|
|
allowed = {'md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'}
|
|
if ext and ext not in allowed:
|
|
raise_for_status(f'unsupported text extension: {ext}', 415)
|
|
max_size = 100 * 1024 * 1024 if request.args.get('download') == '1' else 15 * 1024 * 1024
|
|
content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size)
|
|
if err:
|
|
msg, code = err
|
|
raise_for_status(msg, code)
|
|
text = None
|
|
for enc in ('utf-8', 'utf-8-sig', 'gb18030', 'latin-1'):
|
|
try:
|
|
text = content.decode(enc)
|
|
break
|
|
except Exception:
|
|
continue
|
|
if text is None:
|
|
raise_for_status('failed to decode text file', 422)
|
|
return jsonify({'content': text, 'content_type': content_type or 'text/plain', 'ext': ext})
|
|
|
|
def _guess_ext_from_content(content: bytes, default_ext: str) -> str:
|
|
"""
|
|
根据文件内容(Magic Bytes)纠正可能的错误扩展名
|
|
"""
|
|
import io
|
|
import zipfile
|
|
|
|
if not content:
|
|
return default_ext
|
|
if content.startswith(b'%PDF-'):
|
|
return 'pdf'
|
|
if content.startswith(b'PK\x03\x04'):
|
|
# ZIP 归档,进一步检查内部目录判断是 docx/xlsx/pptx。
|
|
try:
|
|
with zipfile.ZipFile(io.BytesIO(content)) as zf:
|
|
names = {name.lower() for name in zf.namelist()}
|
|
if any(name.startswith('word/') for name in names):
|
|
return 'docx'
|
|
if any(name.startswith('xl/') for name in names):
|
|
return 'xlsx'
|
|
if any(name.startswith('ppt/') for name in names):
|
|
return 'pptx'
|
|
except Exception:
|
|
pass
|
|
if default_ext == 'doc':
|
|
return 'docx'
|
|
if default_ext == 'xls':
|
|
return 'xlsx'
|
|
if default_ext == 'ppt':
|
|
return 'pptx'
|
|
if default_ext in ('docx', 'xlsx', 'pptx'):
|
|
return default_ext
|
|
return 'docx'
|
|
if content.startswith(b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1'):
|
|
# OLE 复合文件,通常是 doc, xls, ppt 等。
|
|
if default_ext == 'docx': return 'doc'
|
|
if default_ext == 'xlsx': return 'xls'
|
|
if default_ext == 'pptx': return 'ppt'
|
|
if default_ext in ('doc', 'xls', 'ppt'): return default_ext
|
|
return 'doc'
|
|
return default_ext
|
|
|
|
@chat_bp.route('/preview-file-raw', methods=['GET'])
|
|
@require_agent_permission
|
|
def preview_file_raw():
|
|
"""
|
|
二进制文件内网代理预览接口。
|
|
用途:
|
|
- 为 pdf/doc/docx 生成可被前端 iframe 访问的同源地址;
|
|
- 尽量使用 inline 响应头,避免强制下载。
|
|
"""
|
|
file_url = (request.args.get('url') or '').strip()
|
|
if not file_url:
|
|
raise ValidationError('url is required')
|
|
if not _is_allowed_preview_url(file_url):
|
|
raise ForbiddenError('url is not allowed for preview')
|
|
parsed = urlparse(file_url)
|
|
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
|
name = (request.args.get('name') or '').strip()
|
|
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
|
|
original_ext = url_path_ext or name_ext
|
|
ext = original_ext
|
|
is_download = request.args.get('download') == '1'
|
|
max_size = None if is_download else 15 * 1024 * 1024
|
|
content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size)
|
|
if err:
|
|
msg, code = err
|
|
raise_for_status(msg, code)
|
|
|
|
# 根据文件二进制头部纠正扩展名,防止文件本身是 docx 却被命名为 doc,导致转换或下载后乱码
|
|
real_ext = _guess_ext_from_content(content, ext)
|
|
if real_ext != ext:
|
|
current_app.logger.info(f"[file-preview] corrected extension from {ext} to {real_ext}")
|
|
ext = real_ext
|
|
if name and '.' in name:
|
|
name = f"{name.rsplit('.', 1)[0]}.{ext}"
|
|
elif name:
|
|
name = f"{name}.{ext}"
|
|
|
|
# 仅当文件真实格式仍然是旧版 Office/PPT 时才转 PDF。
|
|
# 如果原始文件名是 .doc 但内容实际是 .docx,则交给前端 Office 组件渲染,
|
|
# 避免在服务端走旧版转换链路导致长时间卡住。
|
|
needs_pdf_conversion = (
|
|
request.args.get('download') != '1'
|
|
and ext in ('doc', 'ppt', 'pptx')
|
|
)
|
|
if needs_pdf_conversion:
|
|
try:
|
|
content = _convert_office_to_pdf(content, ext)
|
|
ext = 'pdf'
|
|
content_type = 'application/pdf'
|
|
if name and '.' in name:
|
|
name = f"{name.rsplit('.', 1)[0]}.pdf"
|
|
elif name:
|
|
name = f"{name}.pdf"
|
|
except Exception as e:
|
|
current_app.logger.error("[file-preview] LibreOffice conversion failed: %s", e)
|
|
placeholder_text = _extract_placeholder_text(content)
|
|
if placeholder_text:
|
|
content = placeholder_text.encode('utf-8')
|
|
ext = 'txt'
|
|
content_type = 'text/plain; charset=utf-8'
|
|
if name and '.' in name:
|
|
name = f"{name.rsplit('.', 1)[0]}.txt"
|
|
elif name:
|
|
name = f"{name}.txt"
|
|
current_app.logger.info('[file-preview] office preview degraded to text placeholder for %s', file_url)
|
|
else:
|
|
raise AppError(
|
|
code='VALIDATION.UNPROCESSABLE',
|
|
message='failed to convert office file for preview',
|
|
http_status=422,
|
|
)
|
|
|
|
fallback_types = {
|
|
'pdf': 'application/pdf',
|
|
'doc': 'application/msword',
|
|
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
'xls': 'application/vnd.ms-excel',
|
|
'csv': 'text/csv',
|
|
'txt': 'text/plain',
|
|
'md': 'text/markdown',
|
|
'markdown': 'text/markdown',
|
|
'html': 'text/html',
|
|
'htm': 'text/html',
|
|
}
|
|
if ext == 'pdf' and not content.startswith(b'%PDF-'):
|
|
placeholder_text = _extract_placeholder_text(content)
|
|
if placeholder_text:
|
|
content = placeholder_text.encode('utf-8')
|
|
content_type = 'text/plain; charset=utf-8'
|
|
current_app.logger.info('[file-preview] pdf preview degraded to text placeholder for %s', file_url)
|
|
mime = content_type or fallback_types.get(ext) or 'application/octet-stream'
|
|
from urllib.parse import quote
|
|
filename = (request.args.get('name') or '').strip() or f"preview.{ext or 'bin'}"
|
|
encoded_filename = quote(filename)
|
|
ascii_filename = filename.encode('ascii', 'ignore').decode('ascii') or f"preview.{ext or 'bin'}"
|
|
disposition_type = 'attachment' if is_download else 'inline'
|
|
resp = Response(content, status=200, mimetype=mime)
|
|
resp.headers['Content-Disposition'] = f"""{disposition_type}; filename="{ascii_filename}"; filename*=UTF-8''{encoded_filename}"""
|
|
resp.headers['Cache-Control'] = 'no-store'
|
|
resp.headers['X-Preview-Actual-Ext'] = ext or ''
|
|
resp.headers['X-Preview-Original-Ext'] = original_ext or ''
|
|
return resp
|