| 1 | import base64 |
| 2 | from werkzeug.datastructures import FileStorage |
| 3 | from helpers.api import ApiHandler, Request, Response |
| 4 | from helpers.file_browser import FileBrowser |
| 5 | from helpers import files, runtime, extension |
| 6 | from api import get_work_dir_files |
| 7 | import os |
| 8 | import posixpath |
| 9 | |
| 10 | |
| 11 | class UploadWorkDirFiles(ApiHandler): |
| 12 | async def process(self, input: dict, request: Request) -> dict | Response: |
| 13 | if "files[]" not in request.files: |
| 14 | raise Exception("No files uploaded") |
| 15 | |
| 16 | current_path = request.form.get("path", "") |
| 17 | uploaded_files = request.files.getlist("files[]") |
| 18 | |
| 19 | # browser = FileBrowser() |
| 20 | # successful, failed = browser.save_files(uploaded_files, current_path) |
| 21 | |
| 22 | successful, failed = await upload_files(uploaded_files, current_path) |
| 23 | |
| 24 | if not successful and failed: |
| 25 | raise Exception("All uploads failed") |
| 26 | |
| 27 | if successful: |
| 28 | await extension.call_extensions_async( |
| 29 | "workdir_file_mutation_after", |
| 30 | agent=None, |
| 31 | data={ |
| 32 | "action": "upload", |
| 33 | "path": current_path, |
| 34 | "paths": [ |
| 35 | posixpath.join(str(current_path).rstrip("/"), name) |
| 36 | for name in successful |
| 37 | ], |
| 38 | "current_path": current_path, |
| 39 | }, |
| 40 | ) |
| 41 | |
| 42 | # result = browser.get_files(current_path) |
| 43 | result = await runtime.call_development_function(get_work_dir_files.get_files, current_path) |
| 44 | |
| 45 | return { |
| 46 | "message": ( |
| 47 | "Files uploaded successfully" |
| 48 | if not failed |
| 49 | else "Some files failed to upload" |
| 50 | ), |
| 51 | "data": result, |
| 52 | "successful": successful, |
| 53 | "failed": failed, |
| 54 | } |
| 55 | |
| 56 | |
| 57 | async def upload_files(uploaded_files: list[FileStorage], current_path: str): |
| 58 | if runtime.is_development(): |
| 59 | successful = [] |
| 60 | failed = [] |
| 61 | for file in uploaded_files: |
| 62 | file_content = file.stream.read() |
| 63 | base64_content = base64.b64encode(file_content).decode("utf-8") |
| 64 | if await runtime.call_development_function( |
| 65 | upload_file, current_path, file.filename, base64_content |
| 66 | ): |
| 67 | successful.append(file.filename) |
| 68 | else: |
| 69 | failed.append(file.filename) |
| 70 | else: |
| 71 | browser = FileBrowser() |
| 72 | successful, failed = browser.save_files(uploaded_files, current_path) |
| 73 | |
| 74 | return successful, failed |
| 75 | |
| 76 | |
| 77 | async def upload_file(current_path: str, filename: str, base64_content: str): |
| 78 | browser = FileBrowser() |
| 79 | return browser.save_file_b64(current_path, filename, base64_content) |