vue-office
This commit is contained in:
1 parent
e72889acdb
commit
62ec5a3513
6 files changed
+598
-56
No files matched your search
@@ -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
|
||||
Reference in new issue
Block a user