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 @@ - - -
- - - - - - - - -