From 62ec5a35139c309ed22fcef7d1f2a9f8fb52da81 Mon Sep 17 00:00:00 2001 From: sophie <16087569+sophie_liang@user.noreply.gitee.com> Date: Wed, 8 Apr 2026 09:06:37 +0800 Subject: [PATCH] vue-office --- backend/app/api/chat.py | 225 +++++++++++++ backend/requirements.txt | 1 + frontend/package-lock.json | 89 ++++- frontend/package.json | 3 + frontend/src/components/FilePreviewModal.vue | 327 ++++++++++++++++--- frontend/src/views/ChatView.vue | 9 +- 6 files changed, 598 insertions(+), 56 deletions(-) diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index 5d4a4052..0dbd56cf 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -5,8 +5,14 @@ backend/app/api/chat.py 引用文件:flask, services.dify, decorators, models 逻辑关系:作为前端与 Dify 之间的 BFF 层,负责转发请求并流式返回结果 """ +import io +import ipaddress +from urllib.parse import urlparse + +import requests from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app from sqlalchemy import func, desc +from openpyxl import load_workbook from app.services.dify import DifyService from app.services.integration_api import IntegrationApiService from app.decorators import require_agent_permission @@ -17,6 +23,66 @@ from app import db chat_bp = Blueprint('chat', __name__) +def _is_allowed_preview_url(target_url: str) -> bool: + """ + 预览代理 URL 白名单校验。 + 仅允许: + 1) 配置中的集成服务主机; + 2) 本机地址; + 3) 私网 IP 或常见内网域名(.local/.lan)。 + """ + try: + parsed = urlparse(target_url) + if parsed.scheme not in ("http", "https"): + return False + host = (parsed.hostname or "").strip().lower() + if not host: + return False + + # 显式放行配置中的集成服务主机。 + integration_base = (current_app.config.get("INTEGRATION_API_BASE") or "").strip() + if integration_base: + integration_host = (urlparse(integration_base).hostname or "").strip().lower() + if integration_host and host == integration_host: + return True + + if host in ("localhost", "127.0.0.1", "::1"): + return True + + try: + ip = ipaddress.ip_address(host) + return ip.is_private or ip.is_loopback + except ValueError: + # 非 IP 主机:仅放行内网风格本地域名。 + return host.endswith(".local") or host.endswith(".lan") + except Exception: + return False + + +def _fetch_preview_source_bytes(file_url: str): + """ + 从上游文件 URL 拉取二进制内容(供预览接口复用)。 + 返回: (content_bytes, content_type, error_tuple) + 其中 error_tuple = (message, status_code);成功时为 None。 + """ + try: + upstream = requests.get(file_url, 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) + + if upstream.status_code != 200: + return None, None, (f'upstream returned status {upstream.status_code}', 502) + + content = upstream.content or b'' + max_size = 15 * 1024 * 1024 + if len(content) > max_size: + return None, None, ('file too large for online preview', 413) + + content_type = (upstream.headers.get('content-type') or '').split(';')[0].strip().lower() + return content, content_type, None + + @chat_bp.route('/sessions', methods=['GET']) @require_agent_permission def get_chat_sessions(): @@ -242,3 +308,162 @@ def resolve_source_file(): 'source_download_url': payload.get('source_download_url'), 'download_url_expires_at': payload.get('download_url_expires_at'), }) + + +@chat_bp.route('/preview-excel', methods=['GET']) +@require_agent_permission +def preview_excel(): + """ + 内网 Excel 预览接口(简版可上线)。 + 说明: + - 当前仅支持 xlsx; + - xls 返回 415,由前端走下载兜底。 + """ + file_url = (request.args.get('url') or '').strip() + if not file_url: + return jsonify({'error': 'url is required'}), 400 + + if not _is_allowed_preview_url(file_url): + return jsonify({'error': 'url is not allowed for preview'}), 403 + + parsed = urlparse(file_url) + ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower() + if ext == 'xls': + return jsonify({'error': 'xls is not supported in online preview'}), 415 + if ext and ext not in ('xlsx',): + return jsonify({'error': 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) + if err: + msg, code = err + return jsonify({'error': msg}), code + + try: + wb = load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True) + except Exception as e: + current_app.logger.warning("[excel-preview] parse workbook failed: %s", e) + return jsonify({'error': 'failed to parse excel file'}), 422 + + if not wb.sheetnames: + return jsonify({'error': '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: + return jsonify({'error': 'url is required'}), 400 + if not _is_allowed_preview_url(file_url): + return jsonify({'error': 'url is not allowed for preview'}), 403 + + parsed = urlparse(file_url) + ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower() + allowed = {'md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'} + if ext and ext not in allowed: + return jsonify({'error': f'unsupported text extension: {ext}'}), 415 + + content, content_type, err = _fetch_preview_source_bytes(file_url) + if err: + msg, code = err + return jsonify({'error': 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: + return jsonify({'error': 'failed to decode text file'}), 422 + + return jsonify({ + 'content': text, + 'content_type': content_type or 'text/plain', + 'ext': 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: + return jsonify({'error': 'url is required'}), 400 + if not _is_allowed_preview_url(file_url): + return jsonify({'error': 'url is not allowed for preview'}), 403 + + parsed = urlparse(file_url) + ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower() + content, content_type, err = _fetch_preview_source_bytes(file_url) + if err: + msg, code = err + return jsonify({'error': msg}), code + + fallback_types = { + 'pdf': 'application/pdf', + 'doc': 'application/msword', + 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + } + if ext == 'pdf' and not content.startswith(b'%PDF-'): + return jsonify({'error': 'upstream did not return a valid pdf binary'}), 422 + + mime = fallback_types.get(ext) or content_type or 'application/octet-stream' + + filename = (request.args.get('name') or '').strip() or f'preview.{ext or "bin"}' + resp = Response(content, status=200, mimetype=mime) + resp.headers['Content-Disposition'] = f'inline; filename="{filename}"' + resp.headers['Cache-Control'] = 'no-store' + return resp diff --git a/backend/requirements.txt b/backend/requirements.txt index 1d3ad939..9679e5d2 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -10,3 +10,4 @@ gunicorn gevent pydantic python-dotenv +openpyxl diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 8d37eac8..4f919d0a 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -10,6 +10,9 @@ "dependencies": { "@tailwindcss/forms": "^0.5.11", "@tailwindcss/typography": "^0.5.19", + "@vue-office/docx": "^1.6.3", + "@vue-office/excel": "^1.7.14", + "@vue-office/pdf": "^1.6.5", "axios": "^1.13.5", "highlight.js": "^11.11.1", "lucide-vue-next": "^0.575.0", @@ -556,7 +559,6 @@ "integrity": "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "undici-types": "~7.16.0" } @@ -607,6 +609,57 @@ "vscode-uri": "^3.0.8" } }, + "node_modules/@vue-office/docx": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/@vue-office/docx/-/docx-1.6.3.tgz", + "integrity": "sha512-Cs+3CAaRBOWOiW4XAhTwwxJ0dy8cPIf6DqfNvYcD3YACiLwO4kuawLF2IAXxyijhbuOeoFsfvoVbOc16A/4bZA==", + "hasInstallScript": true, + "license": "MIT", + "peerDependencies": { + "@vue/composition-api": "^1.7.1", + "vue": "^2.0.0 || >=3.0.0", + "vue-demi": "^0.14.6" + }, + "peerDependenciesMeta": { + "@vue/composition-api": { + "optional": true + } + } + }, + "node_modules/@vue-office/excel": { + "version": "1.7.14", + "resolved": "https://registry.npmjs.org/@vue-office/excel/-/excel-1.7.14.tgz", + "integrity": "sha512-pVUgt+emDQUnW7q22CfnQ+jl43mM/7IFwYzOg7lwOwPEbiVB4K4qEQf+y/bc4xGXz75w1/e3Kz3G6wAafmFBFg==", + "hasInstallScript": true, + "license": "MIT", + "peerDependencies": { + "@vue/composition-api": "^1.7.1", + "vue": "^2.0.0 || >=3.0.0", + "vue-demi": "^0.14.6" + }, + "peerDependenciesMeta": { + "@vue/composition-api": { + "optional": true + } + } + }, + "node_modules/@vue-office/pdf": { + "version": "1.6.5", + "resolved": "https://registry.npmjs.org/@vue-office/pdf/-/pdf-1.6.5.tgz", + "integrity": "sha512-3BePzeA5wji2JoZGJhdlc3XEXs6gMcSnBXrBXlGGfhZHjNijxcHa9V5Ibm8dDKoEwPPsfg+kf4TGP9/2GBR8jQ==", + "hasInstallScript": true, + "license": "MIT", + "peerDependencies": { + "@vue/composition-api": "^1.7.1", + "vue": "^2.0.0 || >=3.0.0", + "vue-demi": "^0.14.6" + }, + "peerDependenciesMeta": { + "@vue/composition-api": { + "optional": true + } + } + }, "node_modules/@vue/compiler-core": { "version": "3.5.28", "resolved": "https://mirrors.tencent.com/npm/@vue/compiler-core/-/compiler-core-3.5.28.tgz", @@ -912,7 +965,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", @@ -2003,7 +2055,6 @@ "resolved": "https://mirrors.tencent.com/npm/picomatch/-/picomatch-4.0.3.tgz", "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -2048,7 +2099,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", @@ -2390,7 +2440,6 @@ "resolved": "https://mirrors.tencent.com/npm/tailwindcss/-/tailwindcss-3.4.17.tgz", "integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==", "license": "MIT", - "peer": true, "dependencies": { "@alloc/quick-lru": "^5.2.0", "arg": "^5.0.2", @@ -2492,7 +2541,6 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "devOptional": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -2551,7 +2599,6 @@ "integrity": "sha512-RHX7IvsJlEfjyA1rS7MY0UsmF91etdLAamslHR5lfuO3W/BXRdXm2tRE64ztpSPZbKqB4wAAZ0AwtF6QzfKZLA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@oxc-project/runtime": "0.114.0", "lightningcss": "^1.31.1", @@ -2637,7 +2684,6 @@ "resolved": "https://mirrors.tencent.com/npm/vue/-/vue-3.5.28.tgz", "integrity": "sha512-BRdrNfeoccSoIZeIhyPBfvWSLFP4q8J3u8Ju8Ug5vu3LdD+yTM13Sg4sKtljxozbnuMu1NB1X5HBHRYUzFocKg==", "license": "MIT", - "peer": true, "dependencies": { "@vue/compiler-dom": "3.5.28", "@vue/compiler-sfc": "3.5.28", @@ -2654,6 +2700,33 @@ } } }, + "node_modules/vue-demi": { + "version": "0.14.10", + "resolved": "https://registry.npmjs.org/vue-demi/-/vue-demi-0.14.10.tgz", + "integrity": "sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==", + "hasInstallScript": true, + "license": "MIT", + "peer": true, + "bin": { + "vue-demi-fix": "bin/vue-demi-fix.js", + "vue-demi-switch": "bin/vue-demi-switch.js" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "@vue/composition-api": "^1.0.0-rc.1", + "vue": "^3.0.0-0 || ^2.6.0" + }, + "peerDependenciesMeta": { + "@vue/composition-api": { + "optional": true + } + } + }, "node_modules/vue-i18n": { "version": "11.2.8", "resolved": "https://mirrors.tencent.com/npm/vue-i18n/-/vue-i18n-11.2.8.tgz", diff --git a/frontend/package.json b/frontend/package.json index c7f94bf0..a91dff5f 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -11,6 +11,9 @@ "dependencies": { "@tailwindcss/forms": "^0.5.11", "@tailwindcss/typography": "^0.5.19", + "@vue-office/docx": "^1.6.3", + "@vue-office/excel": "^1.7.14", + "@vue-office/pdf": "^1.6.5", "axios": "^1.13.5", "highlight.js": "^11.11.1", "lucide-vue-next": "^0.575.0", diff --git a/frontend/src/components/FilePreviewModal.vue b/frontend/src/components/FilePreviewModal.vue index 4dce2d32..d5c655e7 100644 --- a/frontend/src/components/FilePreviewModal.vue +++ b/frontend/src/components/FilePreviewModal.vue @@ -10,15 +10,32 @@ */ import { computed, ref, watch } from 'vue'; import { marked } from 'marked'; +import VueOfficeDocx from '@vue-office/docx'; +import VueOfficeExcel from '@vue-office/excel'; +import '@vue-office/docx/lib/index.css'; +import '@vue-office/excel/lib/index.css'; interface PreviewFile { name: string; url: string; } +interface ExcelPreviewData { + sheet_name: string; + sheets: string[]; + columns: string[]; + rows: Array>; + limit: number; + truncated: boolean; +} + +type OfficeKind = 'docx' | 'excel' | null; + const props = defineProps<{ modelValue: boolean; file: PreviewFile | null; + agentId?: number | null; + authHeaders?: Record; }>(); const emit = defineEmits<{ @@ -28,11 +45,15 @@ const emit = defineEmits<{ const isLoading = ref(false); const error = ref(''); const markdownHtml = ref(''); +const excelPreview = ref(null); +const officeSrc = ref(''); +const officeKind = ref(null); +const officeObjectUrl = ref(''); /** - * Extract extension from URL or filename. - * - Drops query string first (for signed URLs). - * - Returns lowercase extension without dot. + * 从 URL 或文件名中提取扩展名。 + * - 会先去掉 query 参数(兼容签名链接)。 + * - 返回小写扩展名(不含点号)。 */ const getExt = (raw: string) => { const clean = (raw.split('?')[0] ?? '').toLowerCase(); @@ -47,21 +68,23 @@ const ext = computed(() => { return getExt(props.file?.name || ''); }); -const preferredMode = computed<'markdown' | 'image' | 'iframe'>(() => { +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'].includes(ext.value)) return 'markdown'; + if (['md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'].includes(ext.value)) return 'markdown'; + if (['xlsx'].includes(ext.value)) return 'office'; + if (['docx'].includes(ext.value)) return 'office'; return 'iframe'; }); -const resolvedMode = ref<'markdown' | 'image' | 'iframe'>('iframe'); +const resolvedMode = ref<'markdown' | 'image' | 'iframe' | 'sheet' | 'office'>('iframe'); const isOfficeDoc = computed(() => ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'].includes(ext.value)); /** - * Decide whether Office Online Viewer can be used safely. - * Requirements (practical): - * - Office-like file type. - * - HTTPS URL. - * - Publicly reachable host (not localhost/private subnet). + * 判断当前文件是否可使用微软 Office 在线预览。 + * 实际条件: + * - 必须是 Office 文档类型; + * - 必须是 HTTPS; + * - 主机必须公网可达(非 localhost/私网网段)。 */ const canUseOfficeOnlineViewer = computed(() => { const raw = props.file?.url || ''; @@ -88,60 +111,205 @@ const canUseOfficeOnlineViewer = computed(() => { } }); -const needsOfficeFallback = computed(() => isOfficeDoc.value && !canUseOfficeOnlineViewer.value); +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()}`; +}); /** - * Compute iframe source. - * - Office docs with public HTTPS: use Office Online embed endpoint. - * - Otherwise: fallback to raw file URL (browser/native handling). + * 计算 iframe 预览地址。 + * - pdf/doc/docx 优先走后端同源代理地址; + * - Office 文档且满足公网 HTTPS 时,走微软在线预览; + * - 其余返回原始 URL,由浏览器自行处理。 */ const iframeSrc = computed(() => { - if (!props.file?.url) return ''; + if (!props.file?.url || !props.agentId) return ''; + if (ext.value === 'pdf') { + // PDF must use authenticated fetched blob URL; do not fallback to raw URL. + return officeObjectUrl.value; + } if (isOfficeDoc.value && canUseOfficeOnlineViewer.value) { - return `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(props.file.url)}`; + 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; }); const close = () => emit('update:modelValue', false); +const clearOfficeObjectUrl = () => { + if (officeObjectUrl.value) { + URL.revokeObjectURL(officeObjectUrl.value); + officeObjectUrl.value = ''; + } + officeSrc.value = ''; + officeKind.value = null; +}; + +const loadOfficeContent = async () => { + if (!props.file?.url) return; + if (!props.agentId) throw new Error('agent_id is required for office preview'); + + const params = new URLSearchParams({ + agent_id: String(props.agentId), + url: props.file.url, + name: props.file.name || '', + }); + const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, { + headers: props.authHeaders || {}, + }); + if (!res.ok) { + const err = await res.json().catch(() => ({})); + throw new Error(err?.error || `HTTP ${res.status}`); + } + + const blob = await res.blob(); + clearOfficeObjectUrl(); + officeObjectUrl.value = URL.createObjectURL(blob); + officeSrc.value = officeObjectUrl.value; + + if (ext.value === 'docx') officeKind.value = 'docx'; + else if (ext.value === 'xlsx') officeKind.value = 'excel'; + else officeKind.value = null; +}; + +const loadPdfContent = async () => { + if (!props.file?.url) return; + if (!props.agentId) throw new Error('agent_id is required for pdf preview'); + + const params = new URLSearchParams({ + agent_id: String(props.agentId), + url: props.file.url, + name: props.file.name || '', + }); + const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, { + headers: props.authHeaders || {}, + }); + if (!res.ok) { + const err = await res.json().catch(() => ({})); + throw new Error(err?.error || `HTTP ${res.status}`); + } + + 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'); + } + + clearOfficeObjectUrl(); + const blob = new Blob([buf], { type: 'application/pdf' }); + officeObjectUrl.value = URL.createObjectURL(blob); +}; + /** - * Load preview content when modal/file changes. - * Strategy: - * 1) Reset state and choose preferred mode by extension. - * 2) Only actively fetch for markdown/text mode. - * 3) Auto-switch mode by response content-type (image/binary/text). - * 4) Parse markdown to HTML on success; set error on failure. + * 在弹窗/文件变化时加载预览内容。 + * 流程: + * 1) 重置状态并按扩展名确定优先模式; + * 2) Excel 走后端 /preview-excel 返回表格数据; + * 3) 文本类走后端 /preview-text 返回文本并渲染 Markdown; + * 4) 其他格式交由 iframe 或降级策略处理; + * 5) 失败写入 error,前端展示可读错误信息。 */ const loadContent = async () => { error.value = ''; markdownHtml.value = ''; + excelPreview.value = null; + clearOfficeObjectUrl(); if (!props.modelValue || !props.file) return; if (!props.file?.url) return; resolvedMode.value = preferredMode.value; + + if (ext.value === 'pdf') { + isLoading.value = true; + try { + await loadPdfContent(); + resolvedMode.value = 'iframe'; + } catch (e: any) { + error.value = e?.message || 'Failed to preview pdf'; + resolvedMode.value = 'iframe'; + } finally { + isLoading.value = false; + } + return; + } + + if (preferredMode.value === 'office') { + isLoading.value = true; + try { + await loadOfficeContent(); + if (!officeKind.value) { + throw new Error(`Unsupported office preview extension: ${ext.value}`); + } + resolvedMode.value = 'office'; + } catch (e: any) { + error.value = e?.message || 'Failed to preview office file'; + resolvedMode.value = 'iframe'; + } finally { + isLoading.value = false; + } + return; + } + if (preferredMode.value === 'sheet') { + if (!props.agentId) { + error.value = 'agent_id is required for excel preview'; + return; + } + isLoading.value = true; + try { + const params = new URLSearchParams({ + agent_id: String(props.agentId), + url: props.file.url, + limit: '100', + }); + const res = await fetch(`/api/chat/preview-excel?${params.toString()}`, { + headers: props.authHeaders || {}, + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) { + throw new Error(data?.error || `HTTP ${res.status}`); + } + excelPreview.value = data as ExcelPreviewData; + resolvedMode.value = 'sheet'; + } catch (e: any) { + error.value = e?.message || 'Failed to preview excel'; + resolvedMode.value = 'iframe'; + } finally { + isLoading.value = false; + } + return; + } + if (preferredMode.value !== 'markdown') return; isLoading.value = true; try { - const res = await fetch(props.file.url); + if (!props.agentId) { + throw new Error('agent_id is required for text preview'); + } + const params = new URLSearchParams({ + agent_id: String(props.agentId), + url: props.file.url, + }); + const res = await fetch(`/api/chat/preview-text?${params.toString()}`, { + headers: props.authHeaders || {}, + }); if (!res.ok) { - throw new Error(`HTTP ${res.status}`); + const err = await res.json().catch(() => ({})); + throw new Error(err?.error || `HTTP ${res.status}`); } - const contentType = (res.headers.get('content-type') || '').toLowerCase(); - if (contentType.startsWith('image/')) { - resolvedMode.value = 'image'; - return; - } - if ( - contentType && - !contentType.includes('text/') && - !contentType.includes('markdown') && - !contentType.includes('application/json') - ) { - resolvedMode.value = 'iframe'; - return; - } - const text = await res.text(); + const payload = await res.json(); + const text = String(payload?.content || ''); markdownHtml.value = marked.parse(text) as string; } catch (e: any) { error.value = e?.message || 'Failed to load file'; @@ -151,10 +319,10 @@ const loadContent = async () => { }; /** - * Reactively reload preview when: - * - modal visibility changes - * - file URL changes - * - file name changes + * 响应式重载: + * - 弹窗显隐变化; + * - 文件 URL 变化; + * - 文件名变化。 */ watch( () => [props.modelValue, props.file?.url, props.file?.name], @@ -163,6 +331,15 @@ watch( }, { immediate: true } ); + +watch( + () => props.modelValue, + (v) => { + if (!v) { + clearOfficeObjectUrl(); + } + } +);