282 lines
15 KiB
Python
282 lines
15 KiB
Python
import hashlib
|
|
import secrets
|
|
from django.core.cache import cache
|
|
from django.db import transaction
|
|
from django.utils import timezone
|
|
from rest_framework.views import APIView
|
|
from rest_framework.exceptions import ValidationError, PermissionDenied
|
|
from common.auth import TokenAuth
|
|
from common.result import result
|
|
from system_manage import ai_hub as hub
|
|
from system_manage.models.ai_hub import AIService, AITask
|
|
|
|
|
|
class HubView(APIView):
|
|
authentication_classes = [TokenAuth]
|
|
|
|
def delete(self, request, workspace_id, kind, pk=None):
|
|
if not pk:
|
|
raise ValidationError('请选择要删除的记录')
|
|
hub.delete_record(kind, pk, workspace_id, request.user)
|
|
return result.success(True)
|
|
|
|
def initial(self, request, *args, **kwargs):
|
|
super().initial(request, *args, **kwargs)
|
|
from users.serializers.user import get_workspace_list_by_user
|
|
if not request.user.is_active or kwargs['workspace_id'] not in {str(w['id']) for w in get_workspace_list_by_user(request.user.id)}:
|
|
raise PermissionDenied('无权访问')
|
|
from system_manage.platform_access import module_list
|
|
modules = module_list(request.user)
|
|
parser_request = kwargs.get('kind') in ('parsers', 'resources', 'parser_catalog') or isinstance(self, ParserTest)
|
|
if parser_request:
|
|
if not {'tool', 'mindmap'} & set(modules):
|
|
raise PermissionDenied('未授权使用文档解析')
|
|
elif 'mindmap' not in modules:
|
|
raise PermissionDenied('未授权使用思维导图')
|
|
|
|
def get(self, request, workspace_id, kind, pk=None):
|
|
if kind == 'parser_catalog':
|
|
from system_manage.parsers.catalog import catalogue
|
|
return result.success(catalogue())
|
|
if kind == 'resources':
|
|
parsers = hub.visible(hub.AIParserResource.objects.filter(workspace_id=workspace_id, enabled=True), request.user)
|
|
from users.models import User
|
|
from users.models.user_manage_ext import UserActivationApplication
|
|
pending = UserActivationApplication.objects.exclude(status='APPROVED').values_list('user_id', flat=True)
|
|
from system_manage.platform_access import grants_for
|
|
may_authorize = hub.admin(request.user) or grants_for(request.user).filter(
|
|
resource_type__in=['PARSER', 'SERVICE'], actions__contains=['AUTHORIZE']).exists()
|
|
return result.success({'parsers': [hub.serialize(p, user=request.user) for p in parsers
|
|
if 'USE' in hub.serialize(p, user=request.user)['actions']],
|
|
'models': list(hub.authorized_models(workspace_id, request.user).values('id', 'name', 'model_type')),
|
|
'users': [{'id': str(u.id), 'name': u.nick_name or u.username} for u in User.objects.filter(is_active=True).exclude(id__in=pending)] if may_authorize else [],
|
|
'is_admin': hub.admin(request.user)})
|
|
if pk:
|
|
obj = hub.one(kind, pk, workspace_id, request.user)
|
|
data = hub.serialize(obj, detail=True, user=request.user)
|
|
if kind == 'parsers' and 'EDIT' in data.get('actions', []):
|
|
data['endpoint'] = obj.endpoint
|
|
return result.success(data)
|
|
if kind not in hub.KINDS:
|
|
raise ValidationError('资源类型无效')
|
|
query = hub.visible(hub.KINDS[kind].objects.filter(workspace_id=workspace_id), request.user)
|
|
if kind == 'tasks':
|
|
query = query.defer('file_data', 'input_data', 'snapshot', 'result')
|
|
elif kind == 'artifacts':
|
|
query = query.defer('original', 'markdown', 'history')
|
|
return result.success([hub.serialize(obj, user=request.user) for obj in query.order_by('-created_at')[:200]])
|
|
|
|
def post(self, request, workspace_id, kind, pk=None):
|
|
data = request.data
|
|
if request.FILES:
|
|
import json
|
|
try:
|
|
data = json.loads(request.data.get('data', '{}'))
|
|
except (ValueError, TypeError):
|
|
raise ValidationError('任务参数无效')
|
|
if not isinstance(data, dict):
|
|
raise ValidationError('请求参数无效')
|
|
if kind == 'tasks':
|
|
from system_manage.access_control import enforce_task
|
|
if pk:
|
|
candidate = hub.one('tasks', pk, workspace_id, request.user, edit=True)
|
|
enforce_task(request, candidate.service_id, candidate.snapshot.get('nodes'))
|
|
else:
|
|
nodes = hub.one('flows', data['flow_id'], workspace_id, request.user).nodes if data.get('flow_id') else data.get('nodes')
|
|
enforce_task(request, nodes=nodes)
|
|
if pk:
|
|
with transaction.atomic():
|
|
if kind == 'tasks':
|
|
# Match submit/delete lock order so a retry cannot race a
|
|
# service deletion and become a pending, detached task.
|
|
task = hub.one(kind, pk, workspace_id, request.user, edit=True)
|
|
if task.service_id:
|
|
hub.one('services', task.service_id, workspace_id, request.user, lock=True)
|
|
authorization_only = kind in ('parsers', 'services') and set(data) <= {'allowed_users'}
|
|
obj = hub.one(kind, pk, workspace_id, request.user, edit=not authorization_only, lock=True)
|
|
if kind == 'parsers':
|
|
obj = hub.parser_save(workspace_id, request.user, data, obj)
|
|
elif kind == 'artifacts':
|
|
obj = hub.artifact_save(workspace_id, request.user, data, obj)
|
|
elif kind == 'services':
|
|
if set(data) - {'allowed_users'}:
|
|
hub.require_resource_action(request.user, obj, 'EDIT')
|
|
if 'allowed_users' in data:
|
|
hub.require_resource_action(request.user, obj, 'AUTHORIZE')
|
|
obj = AIService.objects.select_for_update().get(pk=obj.pk)
|
|
if 'name' in data:
|
|
obj.name = hub.text(data['name'], '名称', limit=128)
|
|
if 'requests_per_minute' in data:
|
|
obj.requests_per_minute = hub.integer(data['requests_per_minute'], 1, 600, '调用频率')
|
|
if 'enabled' in data:
|
|
if not isinstance(data['enabled'], bool):
|
|
raise ValidationError('启用状态无效')
|
|
obj.enabled = data['enabled']
|
|
if 'allowed_users' in data:
|
|
obj.allowed_users = hub.users(data['allowed_users'])
|
|
key = secrets.token_urlsafe(32) if data.get('rotate_key') else None
|
|
if key:
|
|
obj.key_hash = hashlib.sha256(key.encode()).hexdigest()
|
|
if data.get('revoke_key'):
|
|
obj.key_hash = ''
|
|
obj.save()
|
|
output = hub.serialize(obj)
|
|
if key:
|
|
output['api_key'] = key
|
|
return result.success(output)
|
|
elif kind == 'tasks':
|
|
obj = AITask.objects.select_for_update().get(pk=obj.pk)
|
|
if obj.status != 'FAILED':
|
|
raise ValidationError('仅失败任务可重试')
|
|
if hub.make_snapshot(workspace_id, request.user, obj.snapshot['nodes']) != obj.snapshot['nodes']:
|
|
raise ValidationError('资源版本已变更,请重新提交任务')
|
|
if obj.service_id and not obj.service.enabled:
|
|
raise ValidationError('服务已停用')
|
|
obj.status, obj.error, obj.steps = 'PENDING', '', []
|
|
obj.attempt += 1
|
|
obj.started_at = obj.finished_at = None
|
|
obj.save()
|
|
else:
|
|
raise ValidationError('流程版本不可修改,请另存版本')
|
|
return result.success(hub.serialize(obj, detail=True))
|
|
if kind == 'parsers':
|
|
obj = hub.parser_save(workspace_id, request.user, data)
|
|
elif kind == 'flows':
|
|
obj = hub.flow_create(workspace_id, request.user, data)
|
|
elif kind == 'services':
|
|
obj = hub.service_create(workspace_id, request.user, data)
|
|
elif kind == 'tasks':
|
|
# Bound pending backlog per user; GPU work is consumed by the isolated worker.
|
|
if AITask.objects.filter(owner_id=request.user.id, status__in=['PENDING', 'RUNNING']).count() >= 10:
|
|
raise ValidationError('待处理任务已达上限')
|
|
obj = hub.submit(workspace_id, request.user, data, request.FILES.get('file'), request=request)
|
|
elif kind == 'artifacts':
|
|
obj = hub.artifact_save(workspace_id, request.user, data)
|
|
else:
|
|
raise ValidationError('资源类型无效')
|
|
return result.success(hub.serialize(obj, detail=True))
|
|
|
|
|
|
class ParserTest(HubView):
|
|
http_method_names = ['post', 'options']
|
|
|
|
def post(self, request, workspace_id, pk):
|
|
parser = hub.one('parsers', pk, workspace_id, request.user)
|
|
hub.require_resource_action(request.user, parser, 'EDIT')
|
|
from system_manage.access_control import enforce
|
|
enforce(request, 'parser', parser.id)
|
|
return result.success(hub.parser_test(parser))
|
|
|
|
|
|
class AssetContent(HubView):
|
|
http_method_names = ['get', 'options']
|
|
|
|
def get(self, request, workspace_id, pk):
|
|
from django.http import HttpResponse
|
|
from system_manage.ai_hub_assets import image_bytes
|
|
content, meta = image_bytes(workspace_id, request.user, pk)
|
|
response = HttpResponse(content, content_type=meta['mime'])
|
|
response['Cache-Control'] = 'private, no-store'
|
|
response['X-Content-Type-Options'] = 'nosniff'
|
|
return response
|
|
|
|
|
|
class MarkdownExport(HubView):
|
|
http_method_names = ['post', 'options']
|
|
|
|
def post(self, request, workspace_id):
|
|
import io
|
|
import zipfile
|
|
from django.http import HttpResponse
|
|
from system_manage.ai_hub_assets import ASSET, asset_lock, image_bytes, normalize
|
|
markdown = hub.text(request.data.get('markdown'), '文档内容')
|
|
import re
|
|
filename = request.data.get('filename', 'document.md')
|
|
if not isinstance(filename, str): raise ValidationError('文件名无效')
|
|
filename = filename.replace('\\', '/').rsplit('/', 1)[-1]
|
|
filename = re.sub(r'[<>:\"/\\|?*\x00-\x1f]', '_', filename).strip(' .')[:180]
|
|
filename = (filename[:-3] if filename.lower().endswith('.md') else filename).strip(' .') or 'document'
|
|
filename += '.md'
|
|
with asset_lock():
|
|
markdown = normalize(markdown, workspace_id, request.user)
|
|
buffer = io.BytesIO()
|
|
with zipfile.ZipFile(buffer, 'w', zipfile.ZIP_DEFLATED) as archive:
|
|
replacements = {}
|
|
total = 0
|
|
for match in ASSET.finditer(markdown):
|
|
if match[0] in replacements:
|
|
continue
|
|
content, meta = image_bytes(workspace_id, request.user, match[2])
|
|
total += len(content)
|
|
if total > 100 * 1024 * 1024:
|
|
raise ValidationError('导出图片总大小超过限制')
|
|
extension = meta['mime'].split('/')[1]
|
|
name = f'images/{match[2]}.{extension}'
|
|
archive.writestr(name, content)
|
|
replacements[match[0]] = name
|
|
for url, name in replacements.items():
|
|
markdown = markdown.replace(url, name)
|
|
archive.writestr(filename, markdown)
|
|
response = HttpResponse(buffer.getvalue(), content_type='application/zip')
|
|
response['Content-Disposition'] = 'attachment; filename="markdown.zip"'
|
|
return response
|
|
|
|
|
|
class PublishedRun(HubView):
|
|
"""Internal service: login AND explicit resource grants; Key is an optional extra credential."""
|
|
authentication_classes = [TokenAuth]
|
|
http_method_names = ['post', 'options']
|
|
|
|
def post(self, request, workspace_id, pk):
|
|
service = hub.one('services', pk, workspace_id, request.user)
|
|
if service.key_hash:
|
|
supplied = hashlib.sha256(request.headers.get('X-Service-Key', '').encode()).hexdigest()
|
|
if not secrets.compare_digest(supplied, service.key_hash):
|
|
raise PermissionDenied('服务Key无效')
|
|
from system_manage.access_control import enforce_task
|
|
hub.require_use(request.user, service)
|
|
enforce_task(request, service.id, service.flow.nodes)
|
|
minute = int(timezone.now().timestamp()) // 60
|
|
key = f'ai-hub-rate:{service.id}:{minute}'
|
|
cache.add(key, 0, 70)
|
|
if cache.incr(key) > service.requests_per_minute:
|
|
raise ValidationError('调用过于频繁')
|
|
data = request.data
|
|
if request.FILES:
|
|
import json
|
|
try:
|
|
data = json.loads(request.data.get('data', '{}'))
|
|
except (ValueError, TypeError):
|
|
raise ValidationError('任务参数无效')
|
|
task = hub.submit(workspace_id, request.user, data, request.FILES.get('file'), service=service, request=request)
|
|
return result.success(hub.serialize(task))
|
|
|
|
|
|
class DocumentExport(HubView):
|
|
http_method_names = ['post', 'options']
|
|
|
|
def post(self, request, workspace_id):
|
|
from django.http import HttpResponse
|
|
from system_manage.document_export import export_document, ExportError, MAX_HTML
|
|
from system_manage.ai_hub_assets import ASSET, image_bytes
|
|
def image(src):
|
|
match = ASSET.fullmatch(src)
|
|
if not match or match[1] != workspace_id:
|
|
raise ExportError('请使用当前工作空间已保存的图片')
|
|
raw, _meta = image_bytes(workspace_id, request.user, match[2])
|
|
return raw
|
|
format_name = request.data.get('format', 'docx')
|
|
try:
|
|
upload = request.FILES.get('content')
|
|
if upload and upload.size > MAX_HTML: raise ExportError('导出内容超过24MB')
|
|
html = upload.read().decode('utf-8') if upload else request.data.get('html', '')
|
|
raw, mime = export_document(html, format_name,
|
|
image_resolver=image, paper=request.data.get('paper', 'A4'))
|
|
except (ExportError, ValueError, TypeError) as exc:
|
|
raise ValidationError(str(exc) if isinstance(exc, ExportError) else '文档内容格式无效') from exc
|
|
response = HttpResponse(raw, content_type=mime)
|
|
response['Content-Disposition'] = 'attachment; filename="document.' + format_name + '"'
|
|
response['Cache-Control'] = 'private, no-store'
|
|
response['X-Content-Type-Options'] = 'nosniff'
|
|
return response
|