diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index e37559b0..d78f0aa9 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -7,6 +7,9 @@ backend/app/api/chat.py """ import io import ipaddress +import tempfile +import os +import subprocess from urllib.parse import urlparse import requests @@ -66,69 +69,111 @@ def _fetch_preview_source_bytes(file_url: str): 返回: (content_bytes, content_type, error_tuple) 其中 error_tuple = (message, status_code);成功时为 None。 """ + import base64 + import json + import time + import sqlalchemy as sa + from urllib.parse import parse_qs + headers = {} base_url = current_app.config.get('INTEGRATION_API_BASE', '') api_key = current_app.config.get('INTEGRATION_API_KEY', '') - # 尝试解析 token 并续期 - if base_url and file_url.startswith(base_url) and 'token=' in file_url: + def _resolve_latest_integration_url(raw_url: str): + dataset_id = '' + remote_document_id = '' try: - import base64 - import json - from urllib.parse import urlparse, parse_qs - parsed = urlparse(file_url) + parsed = urlparse(raw_url) qs = parse_qs(parsed.query) - if 'token' in qs: - token = qs['token'][0] + token = (qs.get('token') or [''])[0] + if token: parts = token.split('.') if len(parts) >= 2: payload_b64 = parts[1] payload_b64 += '=' * (-len(payload_b64) % 4) - payload_str = base64.urlsafe_b64decode(payload_b64).decode('utf-8') - payload_data = json.loads(payload_str) - - # 检查是否过期,或者直接重新获取 - import time + payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8')) + dataset_id = str(payload_data.get('dataset_id') or '').strip() + remote_document_id = str(payload_data.get('remote_document_id') or '').strip() + except Exception: + pass + + if not dataset_id or not remote_document_id: + try: + stmt = sa.text("CAST(retriever_resources AS TEXT) LIKE :url") + log = db.session.query(ChatLog).filter(stmt).params(url=f'%{raw_url}%').order_by(ChatLog.created_at.desc()).first() + if log and log.retriever_resources: + for r in log.retriever_resources: + source_url = str(r.get('source_download_url') or '') + if source_url == raw_url or (source_url and source_url.split('&token=')[0] == raw_url.split('&token=')[0]): + dataset_id = dataset_id or str(r.get('dataset_id') or r.get('metadata', {}).get('dataset_id') or '').strip() + remote_document_id = remote_document_id or str( + r.get('remote_document_id') or r.get('metadata', {}).get('remote_document_id') or r.get('document_id') or '' + ).strip() + if dataset_id and remote_document_id: + break + except Exception as e: + current_app.logger.warning("[file-preview] failed to find IDs in ChatLog: %s", e) + + if dataset_id and remote_document_id: + new_info = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id) + if new_info and new_info.get('source_download_url'): + current_app.logger.info("[file-preview] refreshed integration url for dataset=%s doc=%s", dataset_id, remote_document_id) + return new_info['source_download_url'] + return raw_url + + def _build_headers(raw_url: str): + next_headers = {} + if base_url and raw_url.startswith(base_url) and api_key: + next_headers['X-Integration-Key'] = api_key + return next_headers + + def _should_refresh_from_response(resp) -> bool: + ctype = (resp.headers.get('content-type') or '').split(';')[0].strip().lower() + if resp.status_code == 401: + return True + if ctype == 'application/json': + body = (resp.content or b'')[:512].decode('utf-8', errors='ignore').lower() + if 'unauthorized' in body or '"error"' in body: + return True + return False + + if base_url and file_url.startswith(base_url) and 'token=' in file_url: + try: + parsed = urlparse(file_url) + qs = parse_qs(parsed.query) + token = (qs.get('token') or [''])[0] + if token: + parts = token.split('.') + if len(parts) >= 2: + payload_b64 = parts[1] + payload_b64 += '=' * (-len(payload_b64) % 4) + payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8')) exp = payload_data.get('exp', 0) - if exp and exp < time.time() + 300: # 如果已经过期或者即将在 5 分钟内过期 - dataset_id = payload_data.get('dataset_id') - remote_document_id = payload_data.get('remote_document_id') - - # 如果旧版本的 token 里没有这俩 ID,尝试从聊天记录反查 - if not dataset_id or not remote_document_id: - from app.models import ChatLog - from app import db - import sqlalchemy as sa - try: - stmt = sa.text("CAST(retriever_resources AS TEXT) LIKE :url") - log = db.session.query(ChatLog).filter(stmt).params(url=f'%{file_url}%').order_by(ChatLog.created_at.desc()).first() - if log and log.retriever_resources: - for r in log.retriever_resources: - if r.get('source_download_url') == file_url: - dataset_id = dataset_id or r.get('dataset_id') or r.get('metadata', {}).get('dataset_id') - remote_document_id = remote_document_id or r.get('remote_document_id') or r.get('metadata', {}).get('remote_document_id') or r.get('document_id') - if dataset_id and remote_document_id: - break - except Exception as e: - current_app.logger.warning("[file-preview] failed to find IDs in ChatLog: %s", e) - - if dataset_id and remote_document_id: - new_info = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id) - if new_info and new_info.get('source_download_url'): - file_url = new_info['source_download_url'] - current_app.logger.info("[file-preview] refreshed expired integration url for dataset=%s doc=%s", dataset_id, remote_document_id) + if exp and exp < time.time() + 300: + file_url = _resolve_latest_integration_url(file_url) except Exception as e: current_app.logger.warning("[file-preview] failed to refresh expired integration token: %s", e) - if base_url and file_url.startswith(base_url) and api_key: - headers['X-Integration-Key'] = api_key - + headers = _build_headers(file_url) try: upstream = requests.get(file_url, headers=headers, timeout=(5, 20)) except requests.RequestException as e: current_app.logger.warning("[file-preview] upstream request failed: %s", e) return None, None, ('failed to fetch source file', 502) + # 某些旧历史记录中的 source_download_url 已过期,但上游可能返回 200 + JSON 错误体。 + # 这里统一视为“坏链接”,刷新最新下载地址后重试一次。 + if base_url and file_url.startswith(base_url) and 'token=' in file_url and _should_refresh_from_response(upstream): + refreshed_url = _resolve_latest_integration_url(file_url) + if refreshed_url != file_url: + headers = _build_headers(refreshed_url) + try: + upstream = requests.get(refreshed_url, headers=headers, timeout=(5, 20)) + file_url = refreshed_url + except requests.RequestException as e: + current_app.logger.warning("[file-preview] refreshed upstream request failed: %s", e) + return None, None, ('failed to fetch source file', 502) + if upstream.status_code != 200: return None, None, (f'upstream returned status {upstream.status_code}', 502) @@ -138,8 +183,103 @@ def _fetch_preview_source_bytes(file_url: str): return None, None, ('file too large for online preview', 413) content_type = (upstream.headers.get('content-type') or '').split(';')[0].strip().lower() + if content_type == 'application/json': + body = content[:512].decode('utf-8', errors='ignore') + current_app.logger.warning("[file-preview] upstream returned json instead of binary url=%s body=%s", file_url, body) + return None, None, ('upstream returned invalid preview payload', 502) return content, content_type, None +def _convert_office_to_pdf(content: bytes, ext: str) -> bytes: + """ + 使用 LibreOffice 将 office 文件转为 PDF + """ + with tempfile.TemporaryDirectory() as temp_dir: + input_path = os.path.join(temp_dir, f"input.{ext}") + with open(input_path, 'wb') as f: + f.write(content) + + commands = [ + 'soffice', + 'libreoffice', + r'C:\Program Files\LibreOffice\program\soffice.exe', + r'C:\Program Files (x86)\LibreOffice\program\soffice.exe' + ] + + success = False + for cmd in commands: + try: + process = subprocess.run( + [cmd, '--headless', '--convert-to', 'pdf', '--outdir', temp_dir, input_path], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + timeout=60 + ) + if process.returncode == 0: + success = True + break + else: + current_app.logger.warning(f"LibreOffice command {cmd} failed: {process.stderr.decode('utf-8', errors='ignore')}") + except (FileNotFoundError, subprocess.TimeoutExpired): + continue + + # 如果 LibreOffice 失败,且是在 Windows 系统下,尝试调用本地安装的 WPS 或 MS Office + if not success and os.name == 'nt': + try: + import win32com.client + import pythoncom + pythoncom.CoInitialize() + output_path = os.path.join(temp_dir, "input.pdf") + + if ext in ('doc', 'docx'): + try: + app = win32com.client.Dispatch("KWPS.Application") # 尝试 WPS Word + except Exception: + app = win32com.client.Dispatch("Word.Application") # 回退 MS Word + app.Visible = False + doc = app.Documents.Open(os.path.abspath(input_path)) + doc.SaveAs(os.path.abspath(output_path), FileFormat=17) # 17 = wdFormatPDF + doc.Close() + app.Quit() + success = True + + elif ext in ('ppt', 'pptx'): + try: + app = win32com.client.Dispatch("KWPP.Application") # 尝试 WPS PPT + except Exception: + app = win32com.client.Dispatch("PowerPoint.Application") # 回退 MS PPT + app.Visible = False + presentation = app.Presentations.Open(os.path.abspath(input_path), WithWindow=False) + presentation.SaveAs(os.path.abspath(output_path), 32) # 32 = ppSaveAsPDF + presentation.Close() + app.Quit() + success = True + + elif ext in ('xls', 'xlsx'): + try: + app = win32com.client.Dispatch("KET.Application") # 尝试 WPS Excel + except Exception: + app = win32com.client.Dispatch("Excel.Application") # 回退 MS Excel + app.Visible = False + wb = app.Workbooks.Open(os.path.abspath(input_path)) + wb.ExportAsFixedFormat(0, os.path.abspath(output_path)) # 0 = xlTypePDF + wb.Close(False) + app.Quit() + success = True + except ImportError: + current_app.logger.warning("pywin32 not installed, cannot fallback to WPS/MS Office COM API.") + except Exception as e: + current_app.logger.warning(f"WPS/MS Office COM conversion failed: {e}") + + if not success: + raise Exception("Failed to convert document to PDF using LibreOffice or WPS/MS Office") + + output_path = os.path.join(temp_dir, "input.pdf") + if os.path.exists(output_path): + with open(output_path, 'rb') as f: + return f.read() + else: + raise Exception("PDF output not found after conversion") + @chat_bp.route('/sessions', methods=['GET']) @require_agent_permission @@ -571,6 +711,16 @@ def preview_file_raw(): msg, code = err return jsonify({'error': msg}), code + # 如果是无法纯前端渲染的旧版 Office 或 PPT 格式,尝试转为 PDF 供前端统一渲染 + if ext in ('doc', 'ppt', 'pptx') and request.args.get('download') != '1': + try: + content = _convert_office_to_pdf(content, ext) + ext = 'pdf' + content_type = 'application/pdf' + except Exception as e: + current_app.logger.error("[file-preview] LibreOffice conversion failed: %s", e) + # 转换失败则回退到原始格式 + fallback_types = { 'pdf': 'application/pdf', 'doc': 'application/msword', diff --git a/backend/requirements.txt b/backend/requirements.txt index d8e1b18b..4cd8d864 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -14,3 +14,4 @@ openpyxl pycryptodome PyJWT cryptography +pywin32 diff --git a/frontend/dist/index.html b/frontend/dist/index.html index 89620a59..bb754957 100644 --- a/frontend/dist/index.html +++ b/frontend/dist/index.html @@ -1,20 +1,19 @@ - - - - - - - - - - - - AI工作台 - - - - -
- - - + + + + + + + + + + + + AI工作台 + + + + +
+ + diff --git a/frontend/src/components/FilePreviewModal.vue b/frontend/src/components/FilePreviewModal.vue index 3127b42d..ae914505 100644 --- a/frontend/src/components/FilePreviewModal.vue +++ b/frontend/src/components/FilePreviewModal.vue @@ -64,67 +64,26 @@ const getExt = (raw: string) => { }; const ext = computed(() => { - // URL extension has higher priority than display name. - const byUrl = getExt(props.file?.url || ''); - if (byUrl) return byUrl; - return getExt(props.file?.name || ''); + // Display name extension has higher priority than URL. + const byName = getExt(props.file?.name || ''); + if (byName) return byName; + return getExt(props.file?.url || ''); }); const preferredMode = computed<'markdown' | 'image' | 'iframe' | 'sheet' | 'office'>(() => { if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'].includes(ext.value)) return 'image'; if (['md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'].includes(ext.value)) return 'markdown'; - if (['xlsx', 'xls'].includes(ext.value)) return 'office'; - if (['docx', 'doc', 'pdf'].includes(ext.value)) return 'iframe'; + if (['xlsx', 'xls'].includes(ext.value)) return 'sheet'; + if (['docx'].includes(ext.value)) return 'office'; + if (['doc', 'ppt', 'pptx', 'pdf'].includes(ext.value)) return 'iframe'; return 'iframe'; }); + const resolvedMode = ref<'markdown' | 'image' | 'iframe' | 'sheet' | 'office'>('iframe'); -const isOfficeDoc = computed(() => ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'].includes(ext.value)); - -/** - * 判断当前文件是否可使用微软 Office 在线预览。 - * 实际条件: - * - 必须是 Office 文档类型; - * - 必须是 HTTPS; - * - 主机必须公网可达(非 localhost/私网网段)。 - */ -const canUseOfficeOnlineViewer = computed(() => { - const raw = props.file?.url || ''; - if (!raw || !isOfficeDoc.value) return false; - try { - const u = new URL(raw, window.location.origin); - // Office online viewer usually requires a publicly reachable HTTPS URL. - // Private-network or local addresses typically render as blank pages. - if (u.protocol !== 'https:') return false; - const host = u.hostname; - if ( - host === 'localhost' || - host === '127.0.0.1' || - host === '::1' || - /^10\./.test(host) || - /^192\.168\./.test(host) || - /^172\.(1[6-9]|2\d|3[0-1])\./.test(host) - ) { - return false; - } - return true; - } catch { - return false; - } -}); - -const needsOfficeFallback = computed( - () => ['ppt', 'pptx'].includes(ext.value) && !canUseOfficeOnlineViewer.value -); - -const previewRawUrl = computed(() => { - if (!props.file?.url || !props.agentId) return ''; - const params = new URLSearchParams({ - agent_id: String(props.agentId), - url: props.file.url, - name: props.file.name || '', - }); - return `/api/chat/preview-file-raw?${params.toString()}`; +const needsOfficeFallback = computed(() => { + // We no longer need fallback for doc/ppt/pptx because they are converted to PDF by the backend + return false; }); /** @@ -135,16 +94,11 @@ const previewRawUrl = computed(() => { */ const iframeSrc = computed(() => { if (!props.file?.url || !props.agentId) return ''; - if (ext.value === 'pdf') { - // PDF must use authenticated fetched blob URL; do not fallback to raw URL. + if (['pdf', 'doc', 'ppt', 'pptx'].includes(ext.value)) { + // These formats must use the authenticated fetch -> blob flow only. + // Never fallback to a protected iframe URL, otherwise it returns Unauthorized. return officeObjectUrl.value; } - if (isOfficeDoc.value && canUseOfficeOnlineViewer.value) { - return `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(previewRawUrl.value)}`; - } - if (['doc', 'docx'].includes(ext.value)) { - return previewRawUrl.value; - } return props.file.url; }); @@ -244,13 +198,18 @@ const loadPdfContent = async () => { } const buf = await res.arrayBuffer(); - const head = new TextDecoder().decode(buf.slice(0, 5)); - if (head !== '%PDF-') { - throw new Error('Invalid PDF binary from preview API'); - } + // const head = new TextDecoder().decode(buf.slice(0, 5)); + // 暂时取消对 PDF header 的强校验,因为 docx 等文件也会调用该函数生成 Blob 并渲染在 iframe 或下载中 + // if (head !== '%PDF-') { + // throw new Error('Invalid PDF binary from preview API'); + // } clearOfficeObjectUrl(); - const blob = new Blob([buf], { type: 'application/pdf' }); + let type = 'application/octet-stream'; + if (ext.value === 'pdf' || ['doc', 'ppt', 'pptx'].includes(ext.value)) type = 'application/pdf'; + else if (ext.value === 'docx') type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; + + const blob = new Blob([buf], { type }); officeObjectUrl.value = URL.createObjectURL(blob); }; @@ -272,13 +231,17 @@ const loadContent = async () => { if (!props.file?.url) return; resolvedMode.value = preferredMode.value; - if (ext.value === 'pdf') { + if (['pdf', 'doc', 'docx', 'ppt', 'pptx'].includes(ext.value) && preferredMode.value === 'iframe') { + if (needsOfficeFallback.value) { + resolvedMode.value = 'iframe'; + return; + } isLoading.value = true; try { - await loadPdfContent(); + await loadPdfContent(); // This fetches as Blob, and sets officeObjectUrl which will be used in iframeSrc resolvedMode.value = 'iframe'; } catch (e: any) { - error.value = e?.message || 'Failed to preview pdf'; + error.value = e?.message || `Failed to preview ${ext.value}`; resolvedMode.value = 'iframe'; } finally { isLoading.value = false; @@ -286,7 +249,7 @@ const loadContent = async () => { return; } - if (preferredMode.value === 'office') { + if (preferredMode.value === 'office' && !needsOfficeFallback.value) { isLoading.value = true; try { await loadOfficeContent(); @@ -469,14 +432,14 @@ watch(
- + class="w-full h-full min-h-[480px] border-0" + allow="clipboard-read; clipboard-write" + >
- - Open in new tab - - - Download file - + + + + + {{ isDownloading ? '下载中...' : '下载文件' }} +