""" api/chat/preview_support.py 用途:提供聊天文件预览所需的来源校验、文件获取和格式转换操作。 依赖:chat.shared、requests、LibreOffice、openpyxl、共享盘配置。 逻辑:由 previews 路由调用,限制可访问路径与 URL,并将 Office/Excel 内容转换为可预览格式。 """ from __future__ import annotations from .shared import * # noqa: F403 from urllib.parse import urljoin def _normalize_allowed_share_path(path_value: str) -> tuple[str, str]: """ 统一归一化 Windows UNC / Windows 本地盘符 / Linux 挂载目录路径。 Returns: (path_kind, normalized_path) - path_kind: 'windows' | 'posix' | '' - normalized_path: 归一化后的绝对路径文本 """ raw_value = str(path_value or '').strip().strip('"') if not raw_value: return ('', '') if raw_value.startswith('\\\\'): normalized = raw_value.replace('/', '\\') normalized = '\\\\' + normalized[2:].rstrip('\\') return ('windows', normalized) if len(raw_value) >= 3 and raw_value[1] == ':' and raw_value[2] in ('\\', '/'): normalized = ntpath.normpath(raw_value.replace('/', '\\')).rstrip('\\') return ('windows', normalized) if raw_value.startswith('/'): normalized = posixpath.normpath(raw_value.replace('\\', '/')) return ('posix', normalized.rstrip('/')) return ('', '') def _is_path_within_allowed_root(target_path: str, root_path: str) -> bool: target_kind, normalized_target = _normalize_allowed_share_path(target_path) root_kind, normalized_root = _normalize_allowed_share_path(root_path) if not normalized_target or not normalized_root or target_kind != root_kind: return False if target_kind == 'windows': target_lower = normalized_target.lower() root_lower = normalized_root.lower() return target_lower == root_lower or target_lower.startswith(root_lower.rstrip('\\') + '\\') return normalized_target == normalized_root or normalized_target.startswith(normalized_root.rstrip('/') + '/') def _is_allowed_share_path(target_url: str) -> bool: target_kind, normalized_target = _normalize_allowed_share_path(target_url) if not normalized_target: return False history_share_root = '' history_local_root = '' if has_request_context(): history_share_root = str(current_app.config.get('FIXED_ASSET_HISTORY_SHARE_ROOT') or '').strip() history_local_root = str(current_app.config.get('FIXED_ASSET_HISTORY_LOCAL_ROOT') or '').strip() if not history_share_root: history_share_root = str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or '').strip() if not history_local_root: history_local_root = str(Config.FIXED_ASSET_HISTORY_LOCAL_ROOT or '').strip() roots = [ PLM_PREVIEW_SHARE_ROOT, history_share_root, history_local_root, ] return any(root and _is_path_within_allowed_root(normalized_target, root) for root in roots) def _is_internal_relative_preview_url(target_url: str) -> bool: """ 判断是否为当前站点内部的根路径预览地址。 用途:培训资料里的知识库文件会下发 `/api/kb/.../source-file` 这类相对地址, 预览代理必须把它视为“当前站点受保护资源”,而不是误判成非法外链。 """ raw = str(target_url or '').strip() return raw.startswith('/api/') def _resolve_internal_preview_url(target_url: str) -> str: """ 将站内相对预览地址补成完整绝对 URL,供 requests 访问。 AI 触发时机:当预览接口收到 `/api/...` 形式的受保护资源时使用, 必须补齐当前请求 Host,才能把登录态透传给后续内部文件下载接口。 """ raw = str(target_url or '').strip() if not raw or not _is_internal_relative_preview_url(raw) or not has_request_context(): return raw return urljoin(request.host_url, raw) def _is_allowed_preview_url(target_url: str) -> bool: """ 预览代理 URL 白名单校验。 仅允许: 1) 配置中的集成服务主机; 2) 本机地址; 3) 私网 IP 或常见内网域名(.local/.lan)。 """ try: if _is_allowed_share_path(target_url): return True if _is_internal_relative_preview_url(target_url) and has_request_context(): return True 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 = (IntegrationApiService.get_base_url() or '').strip() if integration_base: integration_host = (urlparse(integration_base).hostname or '').strip().lower() if integration_host and host == integration_host: return True # 放行当前请求的 Host (前端能够访问本接口说明 Host 是受信任的自身域名/IP) if has_request_context(): req_host = (request.host.split(':')[0] or "").strip().lower() if host == req_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") or host.endswith(".well-trust.com") except Exception: return False def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 * 1024): """ 从上游文件 URL 拉取二进制内容(供预览接口复用)。 如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。 返回: (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 file_url = _resolve_internal_preview_url(file_url) if _is_allowed_share_path(file_url): _path_kind, normalized_path = _normalize_allowed_share_path(file_url) try: if not os.path.isfile(normalized_path): return (None, None, ('source file not found', 404)) file_size = os.path.getsize(normalized_path) if max_size is not None and file_size > max_size: return (None, None, ('file too large for online preview', 413)) with open(normalized_path, 'rb') as fh: content = fh.read() except OSError as exc: current_app.logger.warning('[file-preview] failed to read share path %s: %s', normalized_path, exc) return (None, None, ('failed to read source file', 502)) guessed_type = (mimetypes.guess_type(normalized_path)[0] or '').strip().lower() if _extract_placeholder_text(content): guessed_type = 'text/plain; charset=utf-8' return (content, guessed_type, None) try: from app.services.fixed_asset_image import FixedAssetImageService content, content_type, asset_image_err = FixedAssetImageService.fetch_preview_bytes( file_url, max_size=max_size, ) if content is not None or asset_image_err is not None: return (content, content_type, asset_image_err) except Exception as exc: current_app.logger.warning('[file-preview] fixed asset image fetch failed url=%s err=%s', file_url, exc) headers = {} base_url = IntegrationApiService.get_base_url() api_key = IntegrationApiService.get_api_key() def _resolve_latest_integration_url(raw_url: str): dataset_id = '' remote_document_id = '' try: parsed = urlparse(raw_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')) 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: if not isinstance(r, dict): continue 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]): resolved_dataset_id, resolved_remote_document_id = DifyService._extract_dify_ids(r) dataset_id = dataset_id or str(resolved_dataset_id or '').strip() remote_document_id = remote_document_id or str(resolved_remote_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 = {} is_trusted = False if base_url and raw_url.startswith(base_url): is_trusted = True elif _is_allowed_preview_url(raw_url): is_trusted = True else: try: parsed = urlparse(raw_url) host = (parsed.hostname or "").strip().lower() if has_request_context(): req_host = (request.host.split(':')[0] or "").strip().lower() if host == req_host: is_trusted = True if host in ("localhost", "127.0.0.1", "::1"): is_trusted = True except Exception: pass current_app.logger.info(f"[_build_headers] raw_url={raw_url}, is_trusted={is_trusted}") if is_trusted: if api_key: next_headers['X-Integration-Key'] = api_key if has_request_context(): auth_header = (request.headers.get('Authorization') or '').strip() cookie_header = (request.headers.get('Cookie') or '').strip() if auth_header: next_headers['Authorization'] = auth_header if cookie_header: next_headers['Cookie'] = cookie_header 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 resp.status_code in (403, 404) and 'token=' in file_url: 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 def _retry_with_refreshed_url(raw_url: str): refreshed_url = _resolve_latest_integration_url(raw_url) if not refreshed_url or refreshed_url == raw_url: return None, raw_url retry_headers = _build_headers(refreshed_url) try: return requests.get(refreshed_url, headers=retry_headers, timeout=(5, 20)), refreshed_url except requests.RequestException as e: current_app.logger.warning('[file-preview] refreshed upstream request failed: %s', e) return None, refreshed_url if '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: 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) 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)) if 'token=' in file_url and _should_refresh_from_response(upstream): refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url) if refreshed_upstream is not None: upstream = refreshed_upstream file_url = refreshed_url if upstream.status_code != 200: if 'token=' in file_url: refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url) if refreshed_upstream is not None: upstream = refreshed_upstream file_url = refreshed_url current_app.logger.warning(f"[file-preview] upstream returned status {upstream.status_code} for {file_url}") if upstream.status_code == 404: return None, None, ('source file not found', 404) return None, None, (f'upstream returned status {upstream.status_code}', 502) content = upstream.content or b'' if max_size is not None and 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() 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 _extract_placeholder_text(content: bytes) -> str: sample = content[:2048] for enc in ('utf-16le', 'utf-8', 'utf-8-sig', 'gb18030', 'latin-1'): try: text = sample.decode(enc).replace('\x00', '').strip() except Exception: continue if not text: continue lines = [line.strip() for line in text.splitlines() if line.strip()] if not lines: continue first_line = lines[0][:160] if any((token in first_line for token in ('该文件', '机密文件', '未经允许', '法律风险', '禁止', '保密'))): return first_line return '' def _fetch_dify_text_document(dataset_id: str, remote_document_id: str) -> str | None: """ 对于 Dify 中以 text_model / txt 形式存储的文档, 直接拼接 segments 内容,避免依赖可能失效的 file-preview 签名链接。 """ if not dataset_id or not remote_document_id: return None try: from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService service = KbDifySyncService() document_payload = service.get_document( dataset_id=str(dataset_id), document_id=str(remote_document_id), ) if not isinstance(document_payload, dict): return None upload_info = ( ((document_payload.get('data_source_info') or {}).get('upload_file')) if isinstance(document_payload.get('data_source_info'), dict) else {} ) or {} source_ext = str(upload_info.get('extension') or '').strip().lower() doc_form = str(document_payload.get('doc_form') or '').strip().lower() mime_type = str(upload_info.get('mime_type') or '').strip().lower() is_text_doc = ( source_ext in ('txt', 'md', 'markdown', 'csv', 'html', 'htm', 'properties', 'vtt') or doc_form == 'text_model' or mime_type.startswith('text/') ) if not is_text_doc: return None segments_payload = service._request( 'GET', f'/datasets/{dataset_id}/documents/{remote_document_id}/segments?limit=1000', ) rows = [] if isinstance(segments_payload, dict): rows = segments_payload.get('data') or [] elif isinstance(segments_payload, list): rows = segments_payload if not isinstance(rows, list) or not rows: return None ordered_rows = sorted( [row for row in rows if isinstance(row, dict)], key=lambda row: (int(row.get('position') or 0), str(row.get('id') or '')), ) parts: list[str] = [] for row in ordered_rows: text = str(row.get('content') or '').strip() if text: parts.append(text) return '\n\n'.join(parts).strip() or None except Exception as e: current_app.logger.warning( '[source-file-text] failed to fetch dify text document dataset=%s doc=%s err=%s', dataset_id, remote_document_id, e, ) return None def _convert_office_to_pdf(content: bytes, ext: str) -> bytes: """ 使用 LibreOffice 或 WPS/MS Office 将 office 文件转为 PDF """ import shutil temp_dir = tempfile.mkdtemp() try: input_path = os.path.join(temp_dir, f"input.{ext}") with open(input_path, 'wb') as f: f.write(content) commands = ['soffice', 'libreoffice', 'C:\\Program Files\\LibreOffice\\program\\soffice.exe', '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 if not success and os.name == 'nt': app = None doc_obj = None pythoncom = None try: import win32com.client import pythoncom pythoncom.CoInitialize() output_path = os.path.join(temp_dir, 'input.pdf') if ext in ('doc', 'docx'): try: from pathlib import Path from edkb_system.skills.word_bridge import convert_with_word convert_with_word(Path(input_path), Path(output_path), 17) success = True except Exception as word_bridge_exc: current_app.logger.warning("Word bridge conversion failed: %s", word_bridge_exc) if not success and ext in ('doc', 'docx'): try: # 对旧版 .doc,MS Word 的 PDF 导出兼容性通常优于 WPS app = win32com.client.Dispatch("Word.Application") except Exception: app = win32com.client.Dispatch("KWPS.Application") app.Visible = False app.DisplayAlerts = False input_abs = os.path.abspath(input_path) output_abs = os.path.abspath(output_path) try: doc_obj = app.Documents.Open( FileName=input_abs, ConfirmConversions=False, ReadOnly=True, AddToRecentFiles=False, Visible=False, NoEncodingDialog=True, OpenAndRepair=True, ) except TypeError: doc_obj = app.Documents.Open(input_abs, ReadOnly=True) try: # 旧版 WPS/Word 对 ExportAsFixedFormat 的兼容通常优于 SaveAs(FileFormat=17) doc_obj.ExportAsFixedFormat(output_abs, 17) # 17 = wdExportFormatPDF except Exception: doc_obj.SaveAs(output_abs, 17) # 17 = wdFormatPDF success = True elif ext in ('ppt', 'pptx'): try: app = win32com.client.Dispatch('KWPP.Application') except Exception: app = win32com.client.Dispatch('PowerPoint.Application') app.Visible = False try: app.DisplayAlerts = False except Exception: pass doc_obj = app.Presentations.Open(os.path.abspath(input_path), ReadOnly=True, WithWindow=False) doc_obj.SaveAs(os.path.abspath(output_path), 32) # 32 = ppSaveAsPDF success = True elif ext in ('xls', 'xlsx'): try: app = win32com.client.Dispatch('KET.Application') except Exception: app = win32com.client.Dispatch('Excel.Application') app.Visible = False app.DisplayAlerts = False doc_obj = app.Workbooks.Open(os.path.abspath(input_path), ReadOnly=True) doc_obj.ExportAsFixedFormat(0, os.path.abspath(output_path)) # 0 = xlTypePDF 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}") finally: if doc_obj is not None: try: doc_obj.Close(False) except Exception: pass if app is not None: try: app.Quit() except Exception: pass if pythoncom is not None: try: pythoncom.CoUninitialize() except Exception: pass 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") finally: shutil.rmtree(temp_dir, ignore_errors=True) def _convert_excel_to_xlsx(content: bytes, ext: str) -> bytes: """ 使用 LibreOffice 将老式 `.xls` 转为 `.xlsx`,供在线预览解析。 """ normalized_ext = (ext or '').strip().lower() if normalized_ext != 'xls': return content with tempfile.TemporaryDirectory() as temp_dir: input_path = os.path.join(temp_dir, 'input.xls') output_path = os.path.join(temp_dir, 'input.xlsx') with open(input_path, 'wb') as f: f.write(content) commands = ['soffice', 'libreoffice', 'C:\\Program Files\\LibreOffice\\program\\soffice.exe', 'C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe'] errors = [] for cmd in commands: try: process = subprocess.run([cmd, '--headless', '--convert-to', 'xlsx', '--outdir', temp_dir, input_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60) except (FileNotFoundError, subprocess.TimeoutExpired) as e: errors.append(f'{cmd}: {e}') continue if process.returncode == 0 and os.path.exists(output_path): with open(output_path, 'rb') as f: return f.read() stderr = process.stderr.decode('utf-8', errors='ignore').strip() errors.append(f"{cmd}: {stderr or f'code={process.returncode}'}") allow_windows_excel_preview = ( os.getenv('ENABLE_WINDOWS_EXCEL_PREVIEW_CONVERSION', '').strip().lower() in ('1', 'true', 'yes', 'on') ) if allow_windows_excel_preview: if _convert_excel_via_windows_office(input_path, output_path): with open(output_path, 'rb') as f: return f.read() errors.append("windows-office: failed to convert xls via WPS/MS Excel") else: errors.append("windows-office: disabled for preview to avoid interactive Office dialogs") joined = "; ".join(errors) if errors else "no converter attempted" raise RuntimeError(f"failed to convert xls to xlsx: {joined}") def _convert_excel_via_windows_office(input_path: str, output_path: str) -> bool: """ 在 Windows 环境下使用 WPS/MS Excel 将 `.xls` 转为 `.xlsx`。 LibreOffice 不存在时,给在线预览提供兜底转换能力。 """ if os.name != 'nt': return False try: import pythoncom import win32com.client except ImportError: current_app.logger.warning('pywin32 not installed, cannot fallback to WPS/MS Excel for xls preview.') return False app = None workbook = None pythoncom.CoInitialize() try: try: app = win32com.client.Dispatch('KET.Application') except Exception: app = win32com.client.Dispatch('Excel.Application') app.Visible = False app.DisplayAlerts = False workbook = app.Workbooks.Open(os.path.abspath(input_path)) workbook.SaveAs(os.path.abspath(output_path), FileFormat=51) workbook.Close(False) workbook = None app.Quit() app = None return os.path.exists(output_path) except Exception as exc: current_app.logger.warning('WPS/MS Excel conversion failed for xls preview: %s', exc) return False finally: try: if workbook is not None: workbook.Close(False) except Exception: pass try: if app is not None: app.Quit() except Exception: pass try: pythoncom.CoUninitialize() except Exception: pass def _detect_excel_format(content: bytes, ext: str) -> str: """ 根据文件头兜底判断 Excel 实际格式,避免只依赖 URL/文件名扩展名。 - OLE 复合文档头: 老式 `.xls` - ZIP 头: `.xlsx` """ normalized_ext = (ext or '').strip().lower() head = content[:8] if content else b'' if head.startswith(b'PK\x03\x04'): return 'xlsx' if head.startswith(b'\xd0\xcf\x11\xe0'): return 'xls' return normalized_ext def _load_excel_workbook(content: bytes, ext: str): normalized_ext = _detect_excel_format(content, ext) if normalized_ext == 'xls': content = _convert_excel_to_xlsx(content, 'xls') return load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True)