Merge branch 'dev' into sophie
This commit is contained in:
commit
47ab49cf04
9 files changed
+287
-56
No files matched your search
@@ -2,6 +2,8 @@
|
||||
#docs/
|
||||
venv/
|
||||
backend/venv/
|
||||
backend/instance/
|
||||
tmpwork/
|
||||
env/
|
||||
|
||||
# .env
|
||||
@@ -54,4 +56,11 @@ Thumbs.db
|
||||
|
||||
# Runtime files
|
||||
.run/
|
||||
# tmp
|
||||
.tmp/
|
||||
.tmp2/
|
||||
|
||||
.npm-cache
|
||||
.npm-cache2
|
||||
.pip-cache
|
||||
|
||||
@@ -15,6 +15,7 @@ from sqlalchemy.exc import IntegrityError
|
||||
from datetime import datetime, timedelta
|
||||
import csv
|
||||
import io
|
||||
import re
|
||||
import requests
|
||||
import uuid
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
@@ -23,6 +24,25 @@ from app.auth_jwt import get_current_user as _get_auth_user
|
||||
admin_bp = Blueprint('admin', __name__)
|
||||
|
||||
|
||||
def _empty_to_none(value):
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, str) and value.strip() == '':
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def _is_valid_email(email: str) -> bool:
|
||||
# Practical validation: local@domain.tld (avoid over-strict RFC parsing)
|
||||
if not isinstance(email, str):
|
||||
return False
|
||||
email = email.strip()
|
||||
if len(email) > 254:
|
||||
return False
|
||||
pattern = r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$"
|
||||
return re.match(pattern, email) is not None
|
||||
|
||||
|
||||
def _serialize_wecom_notify_settings():
|
||||
return {
|
||||
'enabled': bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)),
|
||||
@@ -548,15 +568,19 @@ def create_user():
|
||||
if db.session.query(User).filter_by(username=data['username']).first():
|
||||
return jsonify({'error': 'Username exists'}), 400
|
||||
|
||||
email = _empty_to_none(data.get('email'))
|
||||
if email is not None and not _is_valid_email(email):
|
||||
return jsonify({'error': 'Invalid email format'}), 400
|
||||
|
||||
user = User(
|
||||
username=data['username'],
|
||||
email=data.get('email'),
|
||||
department=data.get('department'),
|
||||
email=email,
|
||||
department=_empty_to_none(data.get('department')),
|
||||
role=data.get('role', 'user'),
|
||||
status=data.get('status', 'active'),
|
||||
real_name=data.get('real_name'),
|
||||
employee_id=data.get('employee_id'),
|
||||
phone_number=data.get('phone_number')
|
||||
real_name=_empty_to_none(data.get('real_name')),
|
||||
employee_id=_empty_to_none(data.get('employee_id')),
|
||||
phone_number=_empty_to_none(data.get('phone_number'))
|
||||
)
|
||||
if data.get('password'): user.set_password(data['password'])
|
||||
|
||||
@@ -565,7 +589,18 @@ def create_user():
|
||||
user.agents = agents
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
try:
|
||||
db.session.commit()
|
||||
except IntegrityError as e:
|
||||
db.session.rollback()
|
||||
message = str(getattr(e, 'orig', e))
|
||||
if 'users_email_key' in message:
|
||||
return jsonify({'error': 'Email exists'}), 400
|
||||
if 'users_employee_id_key' in message:
|
||||
return jsonify({'error': 'Employee ID exists'}), 400
|
||||
if 'users_phone_number_key' in message:
|
||||
return jsonify({'error': 'Phone number exists'}), 400
|
||||
return jsonify({'error': 'Data uniqueness conflict'}), 400
|
||||
return jsonify({'id': user.id}), 201
|
||||
|
||||
@admin_bp.route('/users/<int:id>', methods=['PUT'])
|
||||
@@ -575,8 +610,17 @@ def update_user(id):
|
||||
if not user: return jsonify({'error': 'Not found'}), 404
|
||||
data = request.get_json() or {}
|
||||
|
||||
if 'email' in data:
|
||||
email = _empty_to_none(data.get('email'))
|
||||
if email is not None and not _is_valid_email(email):
|
||||
return jsonify({'error': 'Invalid email format'}), 400
|
||||
|
||||
for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||||
if k in data: setattr(user, k, data[k])
|
||||
if k in data:
|
||||
if k in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||
setattr(user, k, _empty_to_none(data[k]))
|
||||
else:
|
||||
setattr(user, k, data[k])
|
||||
|
||||
if data.get('password'): user.set_password(data['password'])
|
||||
|
||||
@@ -584,7 +628,18 @@ def update_user(id):
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
|
||||
db.session.commit()
|
||||
try:
|
||||
db.session.commit()
|
||||
except IntegrityError as e:
|
||||
db.session.rollback()
|
||||
message = str(getattr(e, 'orig', e))
|
||||
if 'users_email_key' in message:
|
||||
return jsonify({'error': 'Email exists'}), 400
|
||||
if 'users_employee_id_key' in message:
|
||||
return jsonify({'error': 'Employee ID exists'}), 400
|
||||
if 'users_phone_number_key' in message:
|
||||
return jsonify({'error': 'Phone number exists'}), 400
|
||||
return jsonify({'error': 'Data uniqueness conflict'}), 400
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
||||
|
||||
+88
-8
@@ -62,11 +62,69 @@ def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
def _fetch_preview_source_bytes(file_url: str):
|
||||
"""
|
||||
从上游文件 URL 拉取二进制内容(供预览接口复用)。
|
||||
如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。
|
||||
返回: (content_bytes, content_type, error_tuple)
|
||||
其中 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:
|
||||
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, timeout=(5, 20))
|
||||
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)
|
||||
@@ -328,10 +386,11 @@ def preview_excel():
|
||||
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',):
|
||||
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
|
||||
if ext and ext not in ('xlsx', 'xls'):
|
||||
return jsonify({'error': f'unsupported file extension: {ext}'}), 415
|
||||
|
||||
try:
|
||||
@@ -403,7 +462,10 @@ def preview_text():
|
||||
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()
|
||||
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'}
|
||||
if ext and ext not in allowed:
|
||||
return jsonify({'error': f'unsupported text extension: {ext}'}), 415
|
||||
@@ -447,7 +509,10 @@ def preview_file_raw():
|
||||
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()
|
||||
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)
|
||||
if err:
|
||||
msg, code = err
|
||||
@@ -457,14 +522,29 @@ def preview_file_raw():
|
||||
'pdf': 'application/pdf',
|
||||
'doc': 'application/msword',
|
||||
'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-'):
|
||||
return jsonify({'error': 'upstream did not return a valid pdf binary'}), 422
|
||||
|
||||
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"}'
|
||||
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.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'
|
||||
return resp
|
||||
@@ -1947,6 +1947,13 @@ def get_agent_details(id):
|
||||
'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'])
|
||||
def get_announcements():
|
||||
"""
|
||||
@@ -1961,7 +1968,8 @@ def get_announcements():
|
||||
'created_at': a.created_at.isoformat()
|
||||
} for a in anns])
|
||||
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'])
|
||||
def create_announcement():
|
||||
|
||||
@@ -19,13 +19,36 @@ class IntegrationApiService:
|
||||
|
||||
@staticmethod
|
||||
def _is_cache_valid(payload: Dict[str, Any]) -> bool:
|
||||
exp = payload.get("download_url_expires_at")
|
||||
if not exp:
|
||||
return True
|
||||
try:
|
||||
return datetime.fromisoformat(exp) > datetime.now().astimezone()
|
||||
except Exception:
|
||||
return True
|
||||
exp_str = payload.get("download_url_expires_at")
|
||||
if exp_str:
|
||||
try:
|
||||
return datetime.fromisoformat(exp_str) > datetime.now().astimezone()
|
||||
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
|
||||
|
||||
@staticmethod
|
||||
def lookup_file_by_dify(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||
|
||||
Generated
+17
-25
@@ -481,23 +481,6 @@
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-win32-x64-msvc": {
|
||||
"version": "1.0.0-rc.5",
|
||||
"resolved": "https://mirrors.tencent.com/npm/@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/pluginutils": {
|
||||
"version": "1.0.0-rc.2",
|
||||
"resolved": "https://mirrors.tencent.com/npm/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.2.tgz",
|
||||
@@ -559,7 +542,6 @@
|
||||
"integrity": "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"undici-types": "~7.16.0"
|
||||
}
|
||||
@@ -966,7 +948,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.9.0",
|
||||
"caniuse-lite": "^1.0.30001759",
|
||||
@@ -2057,7 +2038,6 @@
|
||||
"resolved": "https://mirrors.tencent.com/npm/picomatch/-/picomatch-4.0.3.tgz",
|
||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -2102,7 +2082,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.11",
|
||||
"picocolors": "^1.1.1",
|
||||
@@ -2354,6 +2333,23 @@
|
||||
"@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": {
|
||||
"version": "1.0.0-rc.5",
|
||||
"resolved": "https://mirrors.tencent.com/npm/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.5.tgz",
|
||||
@@ -2444,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",
|
||||
@@ -2546,7 +2541,6 @@
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -2605,7 +2599,6 @@
|
||||
"integrity": "sha512-RHX7IvsJlEfjyA1rS7MY0UsmF91etdLAamslHR5lfuO3W/BXRdXm2tRE64ztpSPZbKqB4wAAZ0AwtF6QzfKZLA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@oxc-project/runtime": "0.114.0",
|
||||
"lightningcss": "^1.31.1",
|
||||
@@ -2691,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",
|
||||
|
||||
@@ -57,8 +57,10 @@ const officeObjectUrl = ref<string>('');
|
||||
*/
|
||||
const getExt = (raw: string) => {
|
||||
const clean = (raw.split('?')[0] ?? '').toLowerCase();
|
||||
const i = clean.lastIndexOf('.');
|
||||
return i >= 0 ? clean.slice(i + 1) : '';
|
||||
const parts = clean.split('/');
|
||||
const lastPart = parts[parts.length - 1] ?? '';
|
||||
const i = lastPart.lastIndexOf('.');
|
||||
return i >= 0 ? lastPart.slice(i + 1) : '';
|
||||
};
|
||||
|
||||
const ext = computed(() => {
|
||||
@@ -71,8 +73,8 @@ const ext = computed(() => {
|
||||
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', 'csv', 'vtt', 'properties', 'html', 'htm'].includes(ext.value)) return 'markdown';
|
||||
if (['xlsx'].includes(ext.value)) return 'office';
|
||||
if (['docx'].includes(ext.value)) return 'office';
|
||||
if (['xlsx', 'xls'].includes(ext.value)) return 'office';
|
||||
if (['docx', 'doc', 'pdf'].includes(ext.value)) return 'iframe';
|
||||
return 'iframe';
|
||||
});
|
||||
const resolvedMode = ref<'markdown' | 'image' | 'iframe' | 'sheet' | 'office'>('iframe');
|
||||
@@ -148,6 +150,46 @@ const iframeSrc = computed(() => {
|
||||
|
||||
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 = () => {
|
||||
if (officeObjectUrl.value) {
|
||||
URL.revokeObjectURL(officeObjectUrl.value);
|
||||
@@ -179,8 +221,8 @@ const loadOfficeContent = async () => {
|
||||
officeObjectUrl.value = URL.createObjectURL(blob);
|
||||
officeSrc.value = officeObjectUrl.value;
|
||||
|
||||
if (ext.value === 'docx') officeKind.value = 'docx';
|
||||
else if (ext.value === 'xlsx') officeKind.value = 'excel';
|
||||
if (ext.value === 'docx' || ext.value === 'doc') officeKind.value = 'docx';
|
||||
else if (ext.value === 'xlsx' || ext.value === 'xls') officeKind.value = 'excel';
|
||||
else officeKind.value = null;
|
||||
};
|
||||
|
||||
@@ -270,6 +312,7 @@ const loadContent = async () => {
|
||||
const params = new URLSearchParams({
|
||||
agent_id: String(props.agentId),
|
||||
url: props.file.url,
|
||||
name: props.file.name || '',
|
||||
limit: '100',
|
||||
});
|
||||
const res = await fetch(`/api/chat/preview-excel?${params.toString()}`, {
|
||||
@@ -300,6 +343,7 @@ const loadContent = async () => {
|
||||
const params = new URLSearchParams({
|
||||
agent_id: String(props.agentId),
|
||||
url: props.file.url,
|
||||
name: props.file.name || '',
|
||||
});
|
||||
const res = await fetch(`/api/chat/preview-text?${params.toString()}`, {
|
||||
headers: props.authHeaders || {},
|
||||
@@ -349,7 +393,16 @@ watch(
|
||||
<div class="min-w-0">
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
|
||||
@@ -324,6 +324,7 @@ const messages = {
|
||||
msgs: {
|
||||
usernameRequired: 'Username is required',
|
||||
passwordRequired: 'Password is required for new users',
|
||||
invalidEmail: 'Invalid email format',
|
||||
created: 'User created successfully',
|
||||
updated: 'User updated successfully',
|
||||
deleted: 'User deleted successfully',
|
||||
@@ -1211,6 +1212,7 @@ const messages = {
|
||||
msgs: {
|
||||
usernameRequired: '用户名必填',
|
||||
passwordRequired: '新用户必须设置密码',
|
||||
invalidEmail: '邮箱格式不正确',
|
||||
created: '用户创建成功',
|
||||
updated: '用户更新成功',
|
||||
deleted: '用户删除成功',
|
||||
@@ -2061,6 +2063,7 @@ const messages = {
|
||||
msgs: {
|
||||
usernameRequired: '用戶名必填',
|
||||
passwordRequired: '新用戶必須設置密碼',
|
||||
invalidEmail: '郵箱格式不正確',
|
||||
created: '用戶創建成功',
|
||||
updated: '用戶更新成功',
|
||||
deleted: '用戶刪除成功',
|
||||
@@ -2916,6 +2919,7 @@ const messages = {
|
||||
msgs: {
|
||||
usernameRequired: 'กรุณากรอกชื่อผู้ใช้',
|
||||
passwordRequired: 'ต้องระบุรหัสผ่านสำหรับผู้ใช้ใหม่',
|
||||
invalidEmail: 'รูปแบบอีเมลไม่ถูกต้อง',
|
||||
created: 'สร้างผู้ใช้สำเร็จ',
|
||||
updated: 'อัปเดตผู้ใช้สำเร็จ',
|
||||
deleted: 'ลบผู้ใช้สำเร็จ',
|
||||
|
||||
@@ -50,6 +50,7 @@ import * as XLSX from 'xlsx';
|
||||
|
||||
const { t, locale } = useI18n();
|
||||
const { showMessageDialog } = useGlobalMessageDialog();
|
||||
const EMAIL_PATTERN = /^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$/;
|
||||
|
||||
const sidebarItems = computed(() => {
|
||||
const items = [
|
||||
@@ -308,6 +309,12 @@ const saveUser = async () => {
|
||||
showMessageDialog('warning', t('admin.user.msgs.usernameRequired'));
|
||||
return;
|
||||
}
|
||||
|
||||
const email = (editingUser.value.email || '').trim();
|
||||
if (email && !EMAIL_PATTERN.test(email)) {
|
||||
showMessageDialog('warning', t('admin.user.msgs.invalidEmail'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!editingUser.value.id && !editingUser.value.password) {
|
||||
showMessageDialog('warning', t('admin.user.msgs.passwordRequired'));
|
||||
|
||||
Reference in new issue
Block a user