mirror of
https://github.com/agent0ai/agent-zero.git
synced 2026-12-06 02:18:44 +00:00
77 lines
2.8 KiB
Python
77 lines
2.8 KiB
Python
import asyncio
|
|
import json
|
|
from werkzeug.datastructures import FileStorage
|
|
from helpers.api import ApiHandler, Request, Response
|
|
from helpers.file_browser import FileBrowser
|
|
from helpers.file_transfers import FileLimitExceeded
|
|
from helpers import extension
|
|
from api import get_work_dir_files
|
|
import posixpath
|
|
|
|
|
|
class UploadWorkDirFiles(ApiHandler):
|
|
async def process(self, input: dict, request: Request) -> dict | Response:
|
|
manifest = request.form.get("manifest")
|
|
if not manifest and "files[]" not in request.files:
|
|
raise Exception("No files uploaded")
|
|
|
|
current_path = request.form.get("path", "")
|
|
uploaded_files = request.files.getlist("files[]")
|
|
try:
|
|
if manifest:
|
|
manifest = json.loads(manifest)
|
|
if not isinstance(manifest, dict):
|
|
raise ValueError("Invalid upload manifest")
|
|
successful, failed = await asyncio.to_thread(
|
|
FileBrowser().upload_tree, uploaded_files, current_path, manifest.get("files"), manifest.get("folders")
|
|
)
|
|
else:
|
|
successful, failed = await upload_files(uploaded_files, current_path)
|
|
except FileLimitExceeded as error:
|
|
return Response(json.dumps({"error": str(error)}), status=413, mimetype="application/json")
|
|
|
|
except (OSError, ValueError) as error:
|
|
return {"error": str(error)}
|
|
|
|
if not successful and failed:
|
|
return {"error": "Files could not be uploaded. Check destination permissions and free disk space.",
|
|
"successful": [], "failed": failed}
|
|
|
|
if successful:
|
|
await extension.call_extensions_async(
|
|
"workdir_file_mutation_after",
|
|
agent=None,
|
|
data={
|
|
"action": "upload",
|
|
"path": current_path,
|
|
"paths": [
|
|
posixpath.join(str(current_path).rstrip("/"), name)
|
|
for name in successful
|
|
],
|
|
"current_path": current_path,
|
|
},
|
|
)
|
|
|
|
result = await get_work_dir_files.get_files(current_path)
|
|
|
|
return {
|
|
"message": (
|
|
"Files uploaded successfully"
|
|
if not failed
|
|
else "Some files failed to upload"
|
|
),
|
|
"data": result,
|
|
"successful": successful,
|
|
"failed": failed,
|
|
}
|
|
|
|
|
|
async def upload_files(uploaded_files: list[FileStorage], current_path: str):
|
|
browser = FileBrowser()
|
|
return await asyncio.to_thread(browser.save_files, uploaded_files, current_path)
|
|
|
|
|
|
async def upload_file(current_path: str, filename: str, base64_content: str):
|
|
browser = FileBrowser()
|
|
return browser.save_file_b64(current_path, filename, base64_content)
|