电脑端-AI回复,可以在线预览excel/ppt/word/pdf格式
This commit is contained in:
1 parent
ef0ae7fe08
commit
2675f447bb
7 files changed
+215
-32
No files matched your search
@@ -4,6 +4,8 @@ deploy_docker_rsync.sh
|
|||||||
docs/
|
docs/
|
||||||
venv/
|
venv/
|
||||||
backend/venv/
|
backend/venv/
|
||||||
|
backend/instance/
|
||||||
|
tmpwork/
|
||||||
env/
|
env/
|
||||||
# .env
|
# .env
|
||||||
.venv
|
.venv
|
||||||
@@ -55,6 +57,13 @@ Thumbs.db
|
|||||||
|
|
||||||
# Runtime files
|
# Runtime files
|
||||||
.run/
|
.run/
|
||||||
|
# tmp
|
||||||
|
.tmp/
|
||||||
|
.tmp2/
|
||||||
|
|
||||||
|
.npm-cache
|
||||||
|
.npm-cache2
|
||||||
|
.pip-cache
|
||||||
|
|
||||||
docker-compose.yml
|
docker-compose.yml
|
||||||
nginx.conf
|
nginx.conf
|
||||||
|
|||||||
+88
-8
@@ -62,11 +62,69 @@ def _is_allowed_preview_url(target_url: str) -> bool:
|
|||||||
def _fetch_preview_source_bytes(file_url: str):
|
def _fetch_preview_source_bytes(file_url: str):
|
||||||
"""
|
"""
|
||||||
从上游文件 URL 拉取二进制内容(供预览接口复用)。
|
从上游文件 URL 拉取二进制内容(供预览接口复用)。
|
||||||
|
如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。
|
||||||
返回: (content_bytes, content_type, error_tuple)
|
返回: (content_bytes, content_type, error_tuple)
|
||||||
其中 error_tuple = (message, status_code);成功时为 None。
|
其中 error_tuple = (message, status_code);成功时为 None。
|
||||||
"""
|
"""
|
||||||
|
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:
|
||||||
try:
|
try:
|
||||||
upstream = requests.get(file_url, timeout=(5, 20))
|
import base64
|
||||||
|
import json
|
||||||
|
from urllib.parse import urlparse, parse_qs
|
||||||
|
parsed = urlparse(file_url)
|
||||||
|
qs = parse_qs(parsed.query)
|
||||||
|
if 'token' in qs:
|
||||||
|
token = qs['token'][0]
|
||||||
|
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
|
||||||
|
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)
|
||||||
|
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
|
||||||
|
|
||||||
|
try:
|
||||||
|
upstream = requests.get(file_url, headers=headers, timeout=(5, 20))
|
||||||
except requests.RequestException as e:
|
except requests.RequestException as e:
|
||||||
current_app.logger.warning("[file-preview] upstream request failed: %s", e)
|
current_app.logger.warning("[file-preview] upstream request failed: %s", e)
|
||||||
return None, None, ('failed to fetch source file', 502)
|
return None, None, ('failed to fetch source file', 502)
|
||||||
@@ -327,10 +385,11 @@ def preview_excel():
|
|||||||
return jsonify({'error': 'url is not allowed for preview'}), 403
|
return jsonify({'error': 'url is not allowed for preview'}), 403
|
||||||
|
|
||||||
parsed = urlparse(file_url)
|
parsed = urlparse(file_url)
|
||||||
ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
||||||
if ext == 'xls':
|
name = (request.args.get('name') or '').strip()
|
||||||
return jsonify({'error': 'xls is not supported in online preview'}), 415
|
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
|
||||||
if ext and ext not in ('xlsx',):
|
ext = url_path_ext or name_ext
|
||||||
|
if ext and ext not in ('xlsx', 'xls'):
|
||||||
return jsonify({'error': f'unsupported file extension: {ext}'}), 415
|
return jsonify({'error': f'unsupported file extension: {ext}'}), 415
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -402,7 +461,10 @@ def preview_text():
|
|||||||
return jsonify({'error': 'url is not allowed for preview'}), 403
|
return jsonify({'error': 'url is not allowed for preview'}), 403
|
||||||
|
|
||||||
parsed = urlparse(file_url)
|
parsed = urlparse(file_url)
|
||||||
ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
||||||
|
name = (request.args.get('name') or '').strip()
|
||||||
|
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
|
||||||
|
ext = url_path_ext or name_ext
|
||||||
allowed = {'md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'}
|
allowed = {'md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'}
|
||||||
if ext and ext not in allowed:
|
if ext and ext not in allowed:
|
||||||
return jsonify({'error': f'unsupported text extension: {ext}'}), 415
|
return jsonify({'error': f'unsupported text extension: {ext}'}), 415
|
||||||
@@ -446,7 +508,10 @@ def preview_file_raw():
|
|||||||
return jsonify({'error': 'url is not allowed for preview'}), 403
|
return jsonify({'error': 'url is not allowed for preview'}), 403
|
||||||
|
|
||||||
parsed = urlparse(file_url)
|
parsed = urlparse(file_url)
|
||||||
ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
||||||
|
name = (request.args.get('name') or '').strip()
|
||||||
|
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
|
||||||
|
ext = url_path_ext or name_ext
|
||||||
content, content_type, err = _fetch_preview_source_bytes(file_url)
|
content, content_type, err = _fetch_preview_source_bytes(file_url)
|
||||||
if err:
|
if err:
|
||||||
msg, code = err
|
msg, code = err
|
||||||
@@ -456,14 +521,29 @@ def preview_file_raw():
|
|||||||
'pdf': 'application/pdf',
|
'pdf': 'application/pdf',
|
||||||
'doc': 'application/msword',
|
'doc': 'application/msword',
|
||||||
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||||
|
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||||
|
'xls': 'application/vnd.ms-excel',
|
||||||
|
'csv': 'text/csv',
|
||||||
|
'txt': 'text/plain',
|
||||||
|
'md': 'text/markdown',
|
||||||
|
'markdown': 'text/markdown',
|
||||||
|
'html': 'text/html',
|
||||||
|
'htm': 'text/html',
|
||||||
}
|
}
|
||||||
if ext == 'pdf' and not content.startswith(b'%PDF-'):
|
if ext == 'pdf' and not content.startswith(b'%PDF-'):
|
||||||
return jsonify({'error': 'upstream did not return a valid pdf binary'}), 422
|
return jsonify({'error': 'upstream did not return a valid pdf binary'}), 422
|
||||||
|
|
||||||
mime = fallback_types.get(ext) or content_type or 'application/octet-stream'
|
mime = fallback_types.get(ext) or content_type or 'application/octet-stream'
|
||||||
|
|
||||||
|
from urllib.parse import quote
|
||||||
filename = (request.args.get('name') or '').strip() or f'preview.{ext or "bin"}'
|
filename = (request.args.get('name') or '').strip() or f'preview.{ext or "bin"}'
|
||||||
|
encoded_filename = quote(filename)
|
||||||
|
ascii_filename = filename.encode('ascii', 'ignore').decode('ascii') or f'preview.{ext or "bin"}'
|
||||||
|
|
||||||
|
is_download = request.args.get('download') == '1'
|
||||||
|
disposition_type = 'attachment' if is_download else 'inline'
|
||||||
|
|
||||||
resp = Response(content, status=200, mimetype=mime)
|
resp = Response(content, status=200, mimetype=mime)
|
||||||
resp.headers['Content-Disposition'] = f'inline; filename="{filename}"'
|
resp.headers['Content-Disposition'] = f"{disposition_type}; filename=\"{ascii_filename}\"; filename*=UTF-8''{encoded_filename}"
|
||||||
resp.headers['Cache-Control'] = 'no-store'
|
resp.headers['Cache-Control'] = 'no-store'
|
||||||
return resp
|
return resp
|
||||||
@@ -1478,6 +1478,13 @@ def get_agent_details(id):
|
|||||||
'suggested_questions': agent.extra_config.get('suggested_questions', []) if agent.extra_config else []
|
'suggested_questions': agent.extra_config.get('suggested_questions', []) if agent.extra_config else []
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@user_bp.route('/db', methods=['GET'])
|
||||||
|
def get_db():
|
||||||
|
from app.models import User
|
||||||
|
from app import db
|
||||||
|
u = db.session.query(User).filter_by(username='26040006').first()
|
||||||
|
return jsonify({'db': current_app.config.get('SQLALCHEMY_DATABASE_URI'), 'user': u.username if u else None})
|
||||||
|
|
||||||
@user_bp.route('/announcements', methods=['GET'])
|
@user_bp.route('/announcements', methods=['GET'])
|
||||||
def get_announcements():
|
def get_announcements():
|
||||||
"""
|
"""
|
||||||
@@ -1492,7 +1499,8 @@ def get_announcements():
|
|||||||
'created_at': a.created_at.isoformat()
|
'created_at': a.created_at.isoformat()
|
||||||
} for a in anns])
|
} for a in anns])
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return jsonify({'error': str(e)}), 500
|
import traceback
|
||||||
|
return jsonify({'error': str(e), 'traceback': traceback.format_exc()}), 500
|
||||||
|
|
||||||
@user_bp.route('/announcements', methods=['POST'])
|
@user_bp.route('/announcements', methods=['POST'])
|
||||||
def create_announcement():
|
def create_announcement():
|
||||||
|
|||||||
@@ -19,12 +19,35 @@ class IntegrationApiService:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _is_cache_valid(payload: Dict[str, Any]) -> bool:
|
def _is_cache_valid(payload: Dict[str, Any]) -> bool:
|
||||||
exp = payload.get("download_url_expires_at")
|
exp_str = payload.get("download_url_expires_at")
|
||||||
if not exp:
|
if exp_str:
|
||||||
return True
|
|
||||||
try:
|
try:
|
||||||
return datetime.fromisoformat(exp) > datetime.now().astimezone()
|
return datetime.fromisoformat(exp_str) > datetime.now().astimezone()
|
||||||
except Exception:
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 如果没有明确的过期时间,尝试解析 url 里的 JWT token 检查
|
||||||
|
source_url = payload.get("source_download_url") or ""
|
||||||
|
if "token=" in source_url:
|
||||||
|
try:
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
from urllib.parse import urlparse, parse_qs
|
||||||
|
import time
|
||||||
|
qs = parse_qs(urlparse(source_url).query)
|
||||||
|
if 'token' in qs:
|
||||||
|
token = qs['token'][0]
|
||||||
|
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:
|
||||||
|
return False # 已过期或即将过期
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|||||||
Generated
+21
-12
@@ -23,6 +23,7 @@
|
|||||||
"xlsx": "^0.18.5"
|
"xlsx": "^0.18.5"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@rolldown/binding-win32-x64-msvc": "^1.0.0-rc.16",
|
||||||
"@types/node": "^24.10.1",
|
"@types/node": "^24.10.1",
|
||||||
"@vitejs/plugin-vue": "^6.0.2",
|
"@vitejs/plugin-vue": "^6.0.2",
|
||||||
"@vue/tsconfig": "^0.8.1",
|
"@vue/tsconfig": "^0.8.1",
|
||||||
@@ -482,15 +483,14 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@rolldown/binding-win32-x64-msvc": {
|
"node_modules/@rolldown/binding-win32-x64-msvc": {
|
||||||
"version": "1.0.0-rc.5",
|
"version": "1.0.0-rc.16",
|
||||||
"resolved": "https://mirrors.tencent.com/npm/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.5.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.16.tgz",
|
||||||
"integrity": "sha512-VQ8F9ld5gw29epjnVGdrx8ugiLTe8BMqmhDYy7nGbdeDo4HAt4bgdZvLbViEhg7DZyHLpiEUlO5/jPSUrIuxRQ==",
|
"integrity": "sha512-PH5DRZT+F4f2PTXRXR8uJxnBq2po/xFtddyabTJVJs/ZYVHqXPEgNIr35IHTEa6bpa0Q8Awg+ymkTaGnKITw4g==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
|
||||||
"os": [
|
"os": [
|
||||||
"win32"
|
"win32"
|
||||||
],
|
],
|
||||||
@@ -559,7 +559,6 @@
|
|||||||
"integrity": "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg==",
|
"integrity": "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"undici-types": "~7.16.0"
|
"undici-types": "~7.16.0"
|
||||||
}
|
}
|
||||||
@@ -966,7 +965,6 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"baseline-browser-mapping": "^2.9.0",
|
"baseline-browser-mapping": "^2.9.0",
|
||||||
"caniuse-lite": "^1.0.30001759",
|
"caniuse-lite": "^1.0.30001759",
|
||||||
@@ -2057,7 +2055,6 @@
|
|||||||
"resolved": "https://mirrors.tencent.com/npm/picomatch/-/picomatch-4.0.3.tgz",
|
"resolved": "https://mirrors.tencent.com/npm/picomatch/-/picomatch-4.0.3.tgz",
|
||||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=12"
|
"node": ">=12"
|
||||||
},
|
},
|
||||||
@@ -2102,7 +2099,6 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"nanoid": "^3.3.11",
|
"nanoid": "^3.3.11",
|
||||||
"picocolors": "^1.1.1",
|
"picocolors": "^1.1.1",
|
||||||
@@ -2354,6 +2350,23 @@
|
|||||||
"@rolldown/binding-win32-x64-msvc": "1.0.0-rc.5"
|
"@rolldown/binding-win32-x64-msvc": "1.0.0-rc.5"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/rolldown/node_modules/@rolldown/binding-win32-x64-msvc": {
|
||||||
|
"version": "1.0.0-rc.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.5.tgz",
|
||||||
|
"integrity": "sha512-VQ8F9ld5gw29epjnVGdrx8ugiLTe8BMqmhDYy7nGbdeDo4HAt4bgdZvLbViEhg7DZyHLpiEUlO5/jPSUrIuxRQ==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^20.19.0 || >=22.12.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/rolldown/node_modules/@rolldown/pluginutils": {
|
"node_modules/rolldown/node_modules/@rolldown/pluginutils": {
|
||||||
"version": "1.0.0-rc.5",
|
"version": "1.0.0-rc.5",
|
||||||
"resolved": "https://mirrors.tencent.com/npm/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.5.tgz",
|
"resolved": "https://mirrors.tencent.com/npm/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.5.tgz",
|
||||||
@@ -2444,7 +2457,6 @@
|
|||||||
"resolved": "https://mirrors.tencent.com/npm/tailwindcss/-/tailwindcss-3.4.17.tgz",
|
"resolved": "https://mirrors.tencent.com/npm/tailwindcss/-/tailwindcss-3.4.17.tgz",
|
||||||
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
|
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@alloc/quick-lru": "^5.2.0",
|
"@alloc/quick-lru": "^5.2.0",
|
||||||
"arg": "^5.0.2",
|
"arg": "^5.0.2",
|
||||||
@@ -2546,7 +2558,6 @@
|
|||||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"peer": true,
|
|
||||||
"bin": {
|
"bin": {
|
||||||
"tsc": "bin/tsc",
|
"tsc": "bin/tsc",
|
||||||
"tsserver": "bin/tsserver"
|
"tsserver": "bin/tsserver"
|
||||||
@@ -2605,7 +2616,6 @@
|
|||||||
"integrity": "sha512-RHX7IvsJlEfjyA1rS7MY0UsmF91etdLAamslHR5lfuO3W/BXRdXm2tRE64ztpSPZbKqB4wAAZ0AwtF6QzfKZLA==",
|
"integrity": "sha512-RHX7IvsJlEfjyA1rS7MY0UsmF91etdLAamslHR5lfuO3W/BXRdXm2tRE64ztpSPZbKqB4wAAZ0AwtF6QzfKZLA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@oxc-project/runtime": "0.114.0",
|
"@oxc-project/runtime": "0.114.0",
|
||||||
"lightningcss": "^1.31.1",
|
"lightningcss": "^1.31.1",
|
||||||
@@ -2691,7 +2701,6 @@
|
|||||||
"resolved": "https://mirrors.tencent.com/npm/vue/-/vue-3.5.28.tgz",
|
"resolved": "https://mirrors.tencent.com/npm/vue/-/vue-3.5.28.tgz",
|
||||||
"integrity": "sha512-BRdrNfeoccSoIZeIhyPBfvWSLFP4q8J3u8Ju8Ug5vu3LdD+yTM13Sg4sKtljxozbnuMu1NB1X5HBHRYUzFocKg==",
|
"integrity": "sha512-BRdrNfeoccSoIZeIhyPBfvWSLFP4q8J3u8Ju8Ug5vu3LdD+yTM13Sg4sKtljxozbnuMu1NB1X5HBHRYUzFocKg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@vue/compiler-dom": "3.5.28",
|
"@vue/compiler-dom": "3.5.28",
|
||||||
"@vue/compiler-sfc": "3.5.28",
|
"@vue/compiler-sfc": "3.5.28",
|
||||||
|
|||||||
@@ -24,6 +24,7 @@
|
|||||||
"xlsx": "^0.18.5"
|
"xlsx": "^0.18.5"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@rolldown/binding-win32-x64-msvc": "^1.0.0-rc.16",
|
||||||
"@types/node": "^24.10.1",
|
"@types/node": "^24.10.1",
|
||||||
"@vitejs/plugin-vue": "^6.0.2",
|
"@vitejs/plugin-vue": "^6.0.2",
|
||||||
"@vue/tsconfig": "^0.8.1",
|
"@vue/tsconfig": "^0.8.1",
|
||||||
|
|||||||
@@ -57,8 +57,10 @@ const officeObjectUrl = ref<string>('');
|
|||||||
*/
|
*/
|
||||||
const getExt = (raw: string) => {
|
const getExt = (raw: string) => {
|
||||||
const clean = (raw.split('?')[0] ?? '').toLowerCase();
|
const clean = (raw.split('?')[0] ?? '').toLowerCase();
|
||||||
const i = clean.lastIndexOf('.');
|
const parts = clean.split('/');
|
||||||
return i >= 0 ? clean.slice(i + 1) : '';
|
const lastPart = parts[parts.length - 1];
|
||||||
|
const i = lastPart.lastIndexOf('.');
|
||||||
|
return i >= 0 ? lastPart.slice(i + 1) : '';
|
||||||
};
|
};
|
||||||
|
|
||||||
const ext = computed(() => {
|
const ext = computed(() => {
|
||||||
@@ -71,8 +73,8 @@ const ext = computed(() => {
|
|||||||
const preferredMode = computed<'markdown' | 'image' | 'iframe' | 'sheet' | 'office'>(() => {
|
const preferredMode = computed<'markdown' | 'image' | 'iframe' | 'sheet' | 'office'>(() => {
|
||||||
if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'].includes(ext.value)) return 'image';
|
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 (['md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'].includes(ext.value)) return 'markdown';
|
||||||
if (['xlsx'].includes(ext.value)) return 'office';
|
if (['xlsx', 'xls'].includes(ext.value)) return 'office';
|
||||||
if (['docx'].includes(ext.value)) return 'office';
|
if (['docx', 'doc', 'pdf'].includes(ext.value)) return 'iframe';
|
||||||
return 'iframe';
|
return 'iframe';
|
||||||
});
|
});
|
||||||
const resolvedMode = ref<'markdown' | 'image' | 'iframe' | 'sheet' | 'office'>('iframe');
|
const resolvedMode = ref<'markdown' | 'image' | 'iframe' | 'sheet' | 'office'>('iframe');
|
||||||
@@ -148,6 +150,46 @@ const iframeSrc = computed(() => {
|
|||||||
|
|
||||||
const close = () => emit('update:modelValue', false);
|
const close = () => emit('update:modelValue', false);
|
||||||
|
|
||||||
|
const isDownloading = ref(false);
|
||||||
|
|
||||||
|
const downloadFile = async () => {
|
||||||
|
if (!props.file?.url || !props.agentId) return;
|
||||||
|
isDownloading.value = true;
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
agent_id: String(props.agentId),
|
||||||
|
url: props.file.url,
|
||||||
|
name: props.file.name || '',
|
||||||
|
download: '1'
|
||||||
|
});
|
||||||
|
|
||||||
|
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();
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = props.file.name || 'download';
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
document.body.removeChild(a);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error('Download failed:', err);
|
||||||
|
alert('下载失败: ' + (err.message || '未知错误'));
|
||||||
|
} finally {
|
||||||
|
isDownloading.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const clearOfficeObjectUrl = () => {
|
const clearOfficeObjectUrl = () => {
|
||||||
if (officeObjectUrl.value) {
|
if (officeObjectUrl.value) {
|
||||||
URL.revokeObjectURL(officeObjectUrl.value);
|
URL.revokeObjectURL(officeObjectUrl.value);
|
||||||
@@ -179,8 +221,8 @@ const loadOfficeContent = async () => {
|
|||||||
officeObjectUrl.value = URL.createObjectURL(blob);
|
officeObjectUrl.value = URL.createObjectURL(blob);
|
||||||
officeSrc.value = officeObjectUrl.value;
|
officeSrc.value = officeObjectUrl.value;
|
||||||
|
|
||||||
if (ext.value === 'docx') officeKind.value = 'docx';
|
if (ext.value === 'docx' || ext.value === 'doc') officeKind.value = 'docx';
|
||||||
else if (ext.value === 'xlsx') officeKind.value = 'excel';
|
else if (ext.value === 'xlsx' || ext.value === 'xls') officeKind.value = 'excel';
|
||||||
else officeKind.value = null;
|
else officeKind.value = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -270,6 +312,7 @@ const loadContent = async () => {
|
|||||||
const params = new URLSearchParams({
|
const params = new URLSearchParams({
|
||||||
agent_id: String(props.agentId),
|
agent_id: String(props.agentId),
|
||||||
url: props.file.url,
|
url: props.file.url,
|
||||||
|
name: props.file.name || '',
|
||||||
limit: '100',
|
limit: '100',
|
||||||
});
|
});
|
||||||
const res = await fetch(`/api/chat/preview-excel?${params.toString()}`, {
|
const res = await fetch(`/api/chat/preview-excel?${params.toString()}`, {
|
||||||
@@ -300,6 +343,7 @@ const loadContent = async () => {
|
|||||||
const params = new URLSearchParams({
|
const params = new URLSearchParams({
|
||||||
agent_id: String(props.agentId),
|
agent_id: String(props.agentId),
|
||||||
url: props.file.url,
|
url: props.file.url,
|
||||||
|
name: props.file.name || '',
|
||||||
});
|
});
|
||||||
const res = await fetch(`/api/chat/preview-text?${params.toString()}`, {
|
const res = await fetch(`/api/chat/preview-text?${params.toString()}`, {
|
||||||
headers: props.authHeaders || {},
|
headers: props.authHeaders || {},
|
||||||
@@ -349,7 +393,16 @@ watch(
|
|||||||
<div class="min-w-0">
|
<div class="min-w-0">
|
||||||
<div class="text-sm font-medium text-slate-500 dark:text-slate-400 tracking-wide">文件预览</div>
|
<div class="text-sm font-medium text-slate-500 dark:text-slate-400 tracking-wide">文件预览</div>
|
||||||
<div class="mt-1 font-semibold text-slate-900 dark:text-slate-100 break-words">{{ file.name }}</div>
|
<div class="mt-1 font-semibold text-slate-900 dark:text-slate-100 break-words">{{ file.name }}</div>
|
||||||
<a :href="file.url" target="_blank" class="mt-1 block text-xs text-brand-600 hover:text-brand-700 break-all leading-6">{{ file.url }}</a>
|
<button type="button" @click="downloadFile" :disabled="isDownloading" class="mt-2 inline-flex items-center justify-center px-3 py-1.5 text-xs font-medium rounded-lg bg-brand-50 text-brand-700 hover:bg-brand-100 border border-brand-200 dark:bg-brand-900/30 dark:text-brand-300 dark:border-brand-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
|
||||||
|
<svg v-if="!isDownloading" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
|
||||||
|
</svg>
|
||||||
|
<svg v-else class="animate-spin -ml-1 mr-2 h-4 w-4 text-brand-700 dark:text-brand-300" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||||
|
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
||||||
|
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||||
|
</svg>
|
||||||
|
{{ isDownloading ? '下载中...' : '下载文件' }}
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<button type="button" @click="close" class="shrink-0 whitespace-nowrap inline-flex items-center justify-center px-4 py-2 rounded-xl border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-300 bg-white/80 dark:bg-slate-900/80 hover:bg-slate-100 dark:hover:bg-slate-800">关闭</button>
|
<button type="button" @click="close" class="shrink-0 whitespace-nowrap inline-flex items-center justify-center px-4 py-2 rounded-xl border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-300 bg-white/80 dark:bg-slate-900/80 hover:bg-slate-100 dark:hover:bg-slate-800">关闭</button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in new issue
Block a user