ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Add S3 bucket browsing to the Files app (#14, #15)
Juan Denis845df9959e3f
diff --git a/backend/app/api/files.py b/backend/app/api/files.pyindex cfc01085..d8579b6a 100644--- a/backend/app/api/files.py+++ b/backend/app/api/files.py@@ -3,6 +3,7 @@from flask import Blueprint, request, jsonify, send_filefrom flask_jwt_extended import jwt_requiredfrom ..services.file_service import FileService+from ..services.storage_provider_service import StorageProviderServiceimport osimport tempfile@@ -413,3 +414,76 @@ def upload_file():return jsonify({'error': 'Permission denied'}), 403except Exception as e:return jsonify({'error': str(e)}), 500+++# ── S3 / object-storage browser (reuses the configured backup storage creds) ──++@files_bp.route('/s3/browse', methods=['GET'])+@jwt_required()+def s3_browse():+ """List a bucket prefix in the same entry shape as the local browser."""+ path = request.args.get('path', '/')+ result = StorageProviderService.s3_browse(path)+ return jsonify(result), 200 if result.get('success') else 400+++@files_bp.route('/s3/read', methods=['GET'])+@jwt_required()+def s3_read():+ """Read a text object for in-app editing."""+ path = request.args.get('path')+ if not path:+ return jsonify({'error': 'Path is required'}), 400+ result = StorageProviderService.s3_read(path)+ return jsonify(result), 200 if result.get('success') else 400+++@files_bp.route('/s3/write', methods=['POST'])+@jwt_required()+def s3_write():+ """Write (create or overwrite) an object from text content."""+ data = request.get_json() or {}+ path = data.get('path')+ content = data.get('content')+ if not path:+ return jsonify({'error': 'Path is required'}), 400+ if content is None:+ return jsonify({'error': 'Content is required'}), 400+ result = StorageProviderService.s3_write(path, content)+ return jsonify(result), 200 if result.get('success') else 400+++@files_bp.route('/s3/delete', methods=['DELETE'])+@jwt_required()+def s3_delete():+ """Delete an object (or every object beneath a prefix)."""+ path = request.args.get('path')+ if not path:+ return jsonify({'error': 'Path is required'}), 400+ result = StorageProviderService.s3_delete(path)+ return jsonify(result), 200 if result.get('success') else 400+++@files_bp.route('/s3/download-url', methods=['GET'])+@jwt_required()+def s3_download_url():+ """Return a short-lived presigned URL the browser can download directly."""+ path = request.args.get('path')+ if not path:+ return jsonify({'error': 'Path is required'}), 400+ result = StorageProviderService.s3_presigned_get(path)+ return jsonify(result), 200 if result.get('success') else 400+++@files_bp.route('/s3/upload', methods=['POST'])+@jwt_required()+def s3_upload():+ """Upload a file into the bucket at the given prefix."""+ if 'file' not in request.files:+ return jsonify({'error': 'No file provided'}), 400+ file = request.files['file']+ destination = request.form.get('destination', '/')+ if file.filename == '':+ return jsonify({'error': 'No file selected'}), 400+ result = StorageProviderService.s3_upload(destination, file.filename, file.stream)+ return jsonify(result), 201 if result.get('success') else 400diff --git a/backend/app/services/storage_provider_service.py b/backend/app/services/storage_provider_service.pyindex 2942c006..b4c041a5 100644--- a/backend/app/services/storage_provider_service.py+++ b/backend/app/services/storage_provider_service.py@@ -408,3 +408,174 @@ class StorageProviderService:return f"{size:.1f} {unit}"size /= 1024return f"{size:.1f} PB"++ # ── File-browser access (powers the Files app's "S3 bucket" target) ──+ # Paths arrive slash-rooted from the UI (e.g. "/photos/cat.jpg"); we strip the+ # leading slash to an S3 key. Root "/" → "" (bucket root). The configured+ # backup path_prefix is intentionally ignored so the browser sees the whole+ # bucket. All methods reuse the same boto3 client as backups (S3 / B2).++ S3_MAX_EDIT_SIZE = 5 * 1024 * 1024 # 5 MB+ _EDITABLE_EXT = {+ '.txt', '.md', '.markdown', '.json', '.yaml', '.yml', '.toml', '.ini', '.cfg',+ '.conf', '.env', '.csv', '.tsv', '.log', '.xml', '.html', '.htm', '.css', '.scss',+ '.js', '.jsx', '.ts', '.tsx', '.py', '.rb', '.php', '.go', '.rs', '.java', '.c',+ '.h', '.cpp', '.sh', '.bash', '.sql', '.svg',+ }++ @classmethod+ def _s3_client_bucket(cls):+ client, bucket, _ = cls._get_client()+ if client is None or not bucket:+ return None, None+ return client, bucket++ @staticmethod+ def _key_from_path(path):+ return (path or '').lstrip('/')++ @classmethod+ def _is_editable_key(cls, key, size):+ ext = os.path.splitext(key)[1].lower()+ return size <= cls.S3_MAX_EDIT_SIZE and ext in cls._EDITABLE_EXT++ @classmethod+ def s3_browse(cls, path='/'):+ client, bucket = cls._s3_client_bucket()+ if client is None:+ return {'success': False, 'error': 'No S3-compatible storage is configured'}+ import mimetypes+ prefix = cls._key_from_path(path)+ if prefix and not prefix.endswith('/'):+ prefix += '/'+ try:+ entries = []+ paginator = client.get_paginator('list_objects_v2')+ for page in paginator.paginate(Bucket=bucket, Prefix=prefix, Delimiter='/'):+ for cp in page.get('CommonPrefixes', []):+ full = cp['Prefix'].rstrip('/')+ entries.append({+ 'name': full.split('/')[-1], 'path': '/' + full,+ 'is_dir': True, 'is_file': False, 'is_link': False,+ 'size': 0, 'size_human': '—', 'modified': None,+ 'mime_type': None, 'is_editable': False,+ 'is_readable': True, 'is_writable': True,+ })+ for obj in page.get('Contents', []):+ key = obj['Key']+ if key == prefix: # the folder placeholder object itself+ continue+ name = key.split('/')[-1]+ if not name:+ continue+ size = obj.get('Size', 0)+ mime, _ = mimetypes.guess_type(name)+ entries.append({+ 'name': name, 'path': '/' + key,+ 'is_dir': False, 'is_file': True, 'is_link': False,+ 'size': size, 'size_human': cls._format_size(size),+ 'modified': obj['LastModified'].isoformat() if obj.get('LastModified') else None,+ 'mime_type': mime, 'is_editable': cls._is_editable_key(key, size),+ 'is_readable': True, 'is_writable': True,+ })+ entries.sort(key=lambda x: (not x['is_dir'], x['name'].lower()))++ parent = None+ stripped = prefix.rstrip('/')+ if stripped:+ parent = '/' + stripped.rsplit('/', 1)[0] if '/' in stripped else '/'+ return {'success': True, 'path': path or '/', 'parent': parent,+ 'entries': entries, 'total': len(entries)}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def s3_read(cls, path):+ client, bucket = cls._s3_client_bucket()+ if client is None:+ return {'success': False, 'error': 'No S3-compatible storage is configured'}+ key = cls._key_from_path(path)+ try:+ head = client.head_object(Bucket=bucket, Key=key)+ size = head.get('ContentLength', 0)+ if size > cls.S3_MAX_EDIT_SIZE:+ return {'success': False, 'error': f'File too large to edit ({cls._format_size(size)})'}+ obj = client.get_object(Bucket=bucket, Key=key)+ raw = obj['Body'].read()+ try:+ content = raw.decode('utf-8')+ except UnicodeDecodeError:+ return {'success': False, 'error': 'Binary file cannot be edited', 'is_binary': True}+ return {'success': True, 'path': path, 'content': content,+ 'encoding': 'utf-8', 'size': size, 'is_binary': False}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def s3_write(cls, path, content):+ client, bucket = cls._s3_client_bucket()+ if client is None:+ return {'success': False, 'error': 'No S3-compatible storage is configured'}+ key = cls._key_from_path(path)+ if not key:+ return {'success': False, 'error': 'A key is required'}+ try:+ body = (content or '').encode('utf-8')+ client.put_object(Bucket=bucket, Key=key, Body=body)+ return {'success': True, 'path': path, 'size': len(body)}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def s3_upload(cls, dest_path, filename, fileobj):+ client, bucket = cls._s3_client_bucket()+ if client is None:+ return {'success': False, 'error': 'No S3-compatible storage is configured'}+ prefix = cls._key_from_path(dest_path)+ if prefix and not prefix.endswith('/'):+ prefix += '/'+ key = f'{prefix}{filename}'+ try:+ client.upload_fileobj(fileobj, bucket, key)+ return {'success': True, 'path': '/' + key}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def s3_delete(cls, path):+ client, bucket = cls._s3_client_bucket()+ if client is None:+ return {'success': False, 'error': 'No S3-compatible storage is configured'}+ key = cls._key_from_path(path)+ if not key:+ return {'success': False, 'error': 'A key is required'}+ try:+ # Collect the object itself plus anything beneath it (folder delete).+ to_delete = set()+ paginator = client.get_paginator('list_objects_v2')+ for p in (key, key + '/'):+ for page in paginator.paginate(Bucket=bucket, Prefix=p):+ for obj in page.get('Contents', []):+ to_delete.add(obj['Key'])+ if not to_delete:+ client.delete_object(Bucket=bucket, Key=key)+ else:+ objs = [{'Key': k} for k in to_delete]+ for i in range(0, len(objs), 1000):+ client.delete_objects(Bucket=bucket, Delete={'Objects': objs[i:i + 1000]})+ return {'success': True, 'path': path}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def s3_presigned_get(cls, path, expires=300):+ client, bucket = cls._s3_client_bucket()+ if client is None:+ return {'success': False, 'error': 'No S3-compatible storage is configured'}+ key = cls._key_from_path(path)+ try:+ url = client.generate_presigned_url(+ 'get_object', Params={'Bucket': bucket, 'Key': key}, ExpiresIn=expires)+ return {'success': True, 'url': url}+ except Exception as e:+ return {'success': False, 'error': str(e)}diff --git a/docs/CONNECTIONS_ROADMAP.md b/docs/CONNECTIONS_ROADMAP.mdindex 32c8d5a4..281e8bfc 100644--- a/docs/CONNECTIONS_ROADMAP.md+++ b/docs/CONNECTIONS_ROADMAP.md@@ -26,17 +26,18 @@ Three consequences fall out of that table:----## ✅ Update (2026-06-15): Phases 1–3 shipped+## ✅ Update (2026-06-15): Phases 1–4 shippedBuilt in one session and verified — `npm run build` (frontend, clean), `eslint` (clean), `py_compile` + venv import (backend, clean). Runtime click-through with real provider credentials is still the operator's to do.- **Phase 1 — surface what exists:** #2 Infrastructure category (DigitalOcean / Hetzner / Vultr / Linode → existing `/cloud`), #3 S3 + Backblaze B2 storage cards (→ existing `/backups/storage`), #4 cross-links on every connected card ("N servers — Servers →", "N domains — Domains →", bucket → Backups, "New service →").- **Phase 2 — complete the tiles:** #5 GitLab source (full OAuth mirror of GitHub, 9 routes), #6 DigitalOcean DNS, #7 GoDaddy DNS (both as new dispatch branches in `dns_provider_service.py`), **#8 SMTP relay** — a real Postfix smarthost (`relayhost` + SASL `sasl_passwd`) with an OS-agnostic `smtplib` connection test; new `EmailRelayConfig` model (password Fernet-encrypted) + `/email/relay` routes + a presets-driven modal (Postmark / SES / Mailgun / SendGrid / custom). All four "coming soon" tiles are now live.- **Phase 3 — domain ownership & expiry:** #9 `RegistrarConnection` model (**Fernet-encrypted** from the start), #10 `RegistrarService` (GoDaddy portfolio + expiry), #11 *not needed as written* — expiry is sourced **live** from the registrar, so no `domains`-table migration was required, #12 the `RegistrarPortfolio` panel on the Domains page ("N days left", colour-coded by urgency, Sync button), #13 registrar card shows "N domains · M expiring ≤30d". **Namecheap** intentionally left "coming soon" (XML API + IP allow-listing).+- **Phase 4 — S3 in the Files app:** #14 `/files/s3/*` endpoints (browse / read / write / delete / download-url / upload) on `StorageProviderService`, reusing the configured backup bucket; #15 an "S3 bucket" target in the File Manager — paths stay slash-rooted in the UI and map to keys server-side, virtual folders from prefixes, edit/upload/download/delete work, and folders/rename/permissions are disabled. Offered only when an S3/B2 destination is configured.New backend: `models/registrar_connection.py`, `services/registrar_service.py`, `api/registrars.py` (`/api/v1/registrars`, registered). New/changed frontend: expanded `providerCatalog.js` (6 categories, 16 tiles), rebuilt `ConnectProviderModal.jsx` (5 provider kinds), `ConnectionsHub.jsx`, `ProviderCard.jsx` cross-links, `ProviderBrands.jsx` icons, `components/domains/RegistrarPortfolio.jsx`, `services/api/connections.js`.-**Still open:** Namecheap registrar, #14/#15 (S3 in the Files app), and Phase 5 #16/#17 (encrypt the *pre-existing* DNS + storage plaintext secrets — the new registrar + SMTP-relay secrets are already encrypted).+**Still open:** Namecheap registrar, and Phase 5 #16/#17 (encrypt the *pre-existing* DNS + storage plaintext secrets — the new registrar + SMTP-relay secrets are already encrypted).---@@ -170,15 +171,17 @@ The one system that genuinely doesn't exist. This is what turns Domains from "DN## Phase 4 — S3 as a first-class Files target (*"S3 connects in the files app"*)-### #14 — `/files/s3/*` endpoints over the storage client `[M]` ❌+### #14 — `/files/s3/*` endpoints over the storage client `[M]` ❌ — ✅ Done- **Today:** `file_service.py` / `api/files.py` are local-filesystem only (`ALLOWED_ROOTS`); no remote/pluggable backend. `storage_provider_service.py` already holds a working boto3 client.- **Do:** Add `GET /files/s3/browse`, `/read`, `POST /files/s3/write`, `DELETE /files/s3/delete`, `GET /files/s3/info` that map `list_objects_v2` / `get` / `put` / `delete` into the same entry shape `browse` returns (virtual folders from `/`-suffixed prefixes).- **Reuse:** The Phase 1 (#3) storage credentials — no new creds, no new config.- **Done when:** The API can list and transfer bucket objects in the File Manager's data shape.+- **Landed:** `StorageProviderService.s3_browse / s3_read / s3_write / s3_upload / s3_delete / s3_presigned_get` + routes `/api/v1/files/s3/{browse,read,write,delete,download-url,upload}`. UI paths are slash-rooted and mapped to keys server-side; folders are virtual (CommonPrefixes); download hands back a short-lived presigned URL; delete removes a single object or a whole prefix. Reuses the configured backup bucket — no new creds.-### #15 — S3 bucket in the File Manager target picker `[M]` ❌+### #15 — S3 bucket in the File Manager target picker `[M]` ❌ — ✅ Done- **Do:** Add an "S3 bucket" option to `FileManager.jsx`'s target picker (next to Local + agents). When active, browse by prefix and **disable** ops S3 can't do (mkdir, rename, chmod).- **Done when:** A user browses, uploads to, downloads from and deletes in their bucket from the Files app — the literal ask.+- **Landed:** `TargetPicker` gained a backward-compatible `extraOptions` prop; the File Manager shows an "S3 bucket" target when an S3/B2 backup destination is configured, routes browse/read/write/delete/download/upload through the existing `fileApi` adapter, disables folders/rename/permissions via the op guard, hides the local-only sidebar (quick-access/tree) on S3, and shows a context banner. Verified: `npm run build` + `eslint` (clean), backend `py_compile` + venv import.---diff --git a/frontend/src/components/TargetPicker.jsx b/frontend/src/components/TargetPicker.jsxindex 3a3cfa44..7b907de8 100644--- a/frontend/src/components/TargetPicker.jsx+++ b/frontend/src/components/TargetPicker.jsx@@ -11,8 +11,10 @@ import { api } from '../services/api';// reported capabilities yet (older builds) are filtered out — same// pattern as the cron picker.//-// onChange receives `{ kind: 'local' } | { kind: 'agent', server_id, name, allowedPaths }`.-export default function TargetPicker({ feature, value, onChange, includeLocal = true }) {+// onChange receives `{ kind: 'local' } | { kind: 'agent', server_id, name, allowedPaths }`,+// or `{ kind: <extra.value> }` for any caller-supplied `extraOptions` (e.g. an+// "S3 bucket" target in the File Manager).+export default function TargetPicker({ feature, value, onChange, includeLocal = true, extraOptions = [] }) {const [servers, setServers] = useState([]);useEffect(() => {@@ -38,6 +40,10 @@ export default function TargetPicker({ feature, value, onChange, includeLocal =onChange({ kind: 'local' });return;}+ if (extraOptions.some(o => o.value === id)) {+ onChange({ kind: id });+ return;+ }const s = eligible.find(x => x.id === id);if (!s) return;onChange({@@ -48,7 +54,9 @@ export default function TargetPicker({ feature, value, onChange, includeLocal =});}- const selectValue = value?.kind === 'agent' ? value.server_id : 'local';+ const selectValue = value?.kind === 'agent'+ ? value.server_id+ : (value?.kind && value.kind !== 'local' ? value.kind : 'local');return (<div className="target-picker">@@ -60,6 +68,9 @@ export default function TargetPicker({ feature, value, onChange, includeLocal ={s.name || s.hostname || s.id}</option>))}+ {extraOptions.map(o => (+ <option key={o.value} value={o.value}>{o.label}</option>+ ))}</select></div>);diff --git a/frontend/src/pages/FileManager.jsx b/frontend/src/pages/FileManager.jsxindex d22ecf55..57894025 100644--- a/frontend/src/pages/FileManager.jsx+++ b/frontend/src/pages/FileManager.jsx@@ -41,6 +41,11 @@ const QUICK_ACCESS = [// upload/download) is panel-host-only until the matching agent verbs land.const REMOTE_SUPPORTED = new Set(['browse', 'read', 'write']);+// Operations the S3 target can't serve (no real directories, permissions, or+// in-place rename). Everything else — browse/read/write/delete/upload/download —+// works against the bucket.+const S3_BLOCKED = new Set(['create file', 'create folder', 'rename', 'change permissions']);+function deriveParent(path) {if (!path || path === '/' || path === '') return null;// A Windows drive root ("C:/" or "C:") sits directly under the agent's@@ -98,8 +103,24 @@ function FileManager() {// operations the agent can't serve yet.const [target, setTarget] = useState({ kind: 'local' });const isRemote = target.kind === 'agent';+ const isS3 = target.kind === 's3';const previousTargetRef = useRef({ kind: 'local', server_id: null });+ // The "S3 bucket" target is offered only when an S3-compatible backup+ // destination is configured (Connections → Storage, or the Backups page).+ const [s3Available, setS3Available] = useState(false);+ useEffect(() => {+ let cancelled = false;+ api.getStorageConfig()+ .then((c) => {+ if (cancelled) return;+ const p = c?.provider;+ setS3Available((p === 's3' || p === 'b2') && Boolean(c?.[p]?.bucket));+ })+ .catch(() => {});+ return () => { cancelled = true; };+ }, []);+// ─── core ────────────────────────────────────────────const [currentPath, setCurrentPath] = useState(() => searchParams.get('path') || '/home');const [entries, setEntries] = useState([]);@@ -221,32 +242,41 @@ function FileManager() {// host while they think they're editing a remote server.const fileApi = useMemo(() => ({browse: async (path, hidden) => {+ if (isS3) return api.browseS3(path);if (isRemote) {return unwrapAgentData(await api.browseRemoteFiles(target.server_id, path));}return api.browseFiles(path, hidden);},read: async (path) => {+ if (isS3) return api.readS3(path);if (isRemote) {return unwrapAgentData(await api.readRemoteFile(target.server_id, path));}return api.readFile(path);},write: async (path, content) => {+ if (isS3) return api.writeS3(path, content);if (isRemote) {return unwrapAgentData(await api.writeRemoteFile(target.server_id, path, content));}return api.writeFile(path, content);},- }), [isRemote, target]);+ del: async (path) => (isS3 ? api.deleteS3(path) : api.deleteFile(path)),+ download: (entry) => (isS3 ? api.downloadS3File(entry.path) : api.downloadFile(entry.path)),+ }), [isRemote, isS3, target]);const remoteGuard = useCallback((op) => {if (isRemote && !REMOTE_SUPPORTED.has(op)) {toast.error(`${op} is not yet supported on remote agents`);return true;}+ if (isS3 && S3_BLOCKED.has(op)) {+ toast.error(`${op} isn't available on S3 buckets`);+ return true;+ }return false;- }, [isRemote, toast]);+ }, [isRemote, isS3, toast]);// When the user switches to a remote target, jump to its first// advertised allowed_path so they don't see a "panel /home" view@@ -260,6 +290,8 @@ function FileManager() {if (target.kind === 'agent' && Array.isArray(target.allowedPaths) && target.allowedPaths.length > 0) {setCurrentPath(target.allowedPaths[0]);+ } else if (target.kind === 's3') {+ setCurrentPath('/');} else if (target.kind === 'local') {setCurrentPath('/home');}@@ -518,7 +550,7 @@ function FileManager() {const failures = [];for (const it of items) {try {- await api.deleteFile(it.path);+ await fileApi.del(it.path);} catch (error) {failures.push(`${it.name}: ${error.message}`);}@@ -595,7 +627,8 @@ function FileManager() {const itemId = queue[i].id;try {setUploads((p) => p.map((u) => u.id === itemId ? { ...u, status: 'uploading' } : u));- await api.uploadFile(currentPath, file, (progress) => {+ const doUpload = isS3 ? api.uploadS3 : api.uploadFile;+ await doUpload(currentPath, file, (progress) => {setUploads((p) => p.map((u) => u.id === itemId ? { ...u, progress } : u));});setUploads((p) => p.map((u) => u.id === itemId ? { ...u, status: 'done', progress: 100 } : u));@@ -759,7 +792,7 @@ function FileManager() {};const downloadSelected = () => {- selectedEntries.filter((e) => !e.is_dir).forEach((e) => api.downloadFile(e.path));+ selectedEntries.filter((e) => !e.is_dir).forEach((e) => fileApi.download(e));};const getDiskColor = (percent) => {@@ -799,6 +832,13 @@ function FileManager() {</div>)}+ {isS3 && (+ <div className="file-manager-target-banner">+ Browsing your <strong>S3 bucket</strong>. Upload, download, edit and delete work;+ folders, rename and permissions don't apply to object storage.+ </div>+ )}+{uploads.length > 0 && (<div className="upload-tray"><div className="upload-tray-header">@@ -850,7 +890,7 @@ function FileManager() {<button className="nav-btn" onClick={goUp} disabled={!parentPath} title="Up"><ArrowUp size={14} /></button>- <button className="nav-btn" onClick={() => navigateTo('/home')} title="Home">+ <button className="nav-btn" onClick={() => navigateTo(isS3 ? '/' : '/home')} title="Home"><Home size={14} /></button></div>@@ -869,7 +909,12 @@ function FileManager() {</div></div><div className="toolbar-right">- <TargetPicker feature="files" value={target} onChange={setTarget} />+ <TargetPicker+ feature="files"+ value={target}+ onChange={setTarget}+ extraOptions={s3Available ? [{ value: 's3', label: 'S3 bucket' }] : []}+ /><div className="search-field"><Search size={14} className="search-field-icon" /><input@@ -959,6 +1004,7 @@ function FileManager() {<div className={`file-manager-body ${previewFile ? 'has-preview' : ''}`}>{sidebarVisible && (<aside className="file-manager-sidebar left">+ {!isS3 && (<>{/* Quick access (demo rail shortcuts) */}<div className="sidebar-section"><div className="sidebar-section-header static">@@ -1010,6 +1056,7 @@ function FileManager() {</div>)}</div>+ </>)}{/* Types */}<div className="sidebar-section">@@ -1172,7 +1219,7 @@ function FileManager() {onOpen={handleOpen}onToggleSelect={handleToggleSelect}onContext={openContextMenu}- onDownload={(e) => api.downloadFile(e.path)}+ onDownload={(e) => fileApi.download(e)}onRename={openRenameModal}onPermissions={openPermissionsModal}onDelete={(e) => handleDelete(e)}@@ -1193,7 +1240,7 @@ function FileManager() {onCancelEdit={() => setEditing(false)}onSave={handleSaveFile}onClose={() => { setPreviewFile(null); setEditing(false); }}- onDownload={(e) => api.downloadFile(e.path)}+ onDownload={(e) => fileApi.download(e)}onRename={openRenameModal}onPermissions={openPermissionsModal}onCopyPath={copyPathToClipboard}@@ -1243,7 +1290,7 @@ function FileManager() {selectionCount={selectedEntries.length}onClose={() => setContextMenu(null)}onOpen={handleOpen}- onDownload={(e) => api.downloadFile(e.path)}+ onDownload={(e) => fileApi.download(e)}onRename={openRenameModal}onPermissions={openPermissionsModal}onCopyPath={copyPathToClipboard}diff --git a/frontend/src/services/api/files.js b/frontend/src/services/api/files.jsindex 63936c88..579272d5 100644--- a/frontend/src/services/api/files.js+++ b/frontend/src/services/api/files.js@@ -130,6 +130,56 @@ export async function uploadFile(destination, file, onProgress = null) {});}+// S3 / object-storage browser (reuses the configured backup storage creds).+// Paths are slash-rooted (e.g. "/photos/cat.jpg"); the backend maps them to keys.+export async function browseS3(path = '/') {+ return this.request(`/files/s3/browse?path=${encodeURIComponent(path)}`);+}++export async function readS3(path) {+ return this.request(`/files/s3/read?path=${encodeURIComponent(path)}`);+}++export async function writeS3(path, content) {+ return this.request('/files/s3/write', { method: 'POST', body: { path, content } });+}++export async function deleteS3(path) {+ return this.request(`/files/s3/delete?path=${encodeURIComponent(path)}`, { method: 'DELETE' });+}++export async function downloadS3File(path) {+ const res = await this.request(`/files/s3/download-url?path=${encodeURIComponent(path)}`);+ if (res && res.url) window.open(res.url, '_blank');+ return res;+}++export async function uploadS3(destination, file, onProgress = null) {+ const token = this.getToken();+ const formData = new FormData();+ formData.append('file', file);+ formData.append('destination', destination);++ return new Promise((resolve, reject) => {+ const xhr = new XMLHttpRequest();+ xhr.open('POST', `${this.baseUrl}/files/s3/upload`);+ xhr.setRequestHeader('Authorization', `Bearer ${token}`);++ if (onProgress) {+ xhr.upload.onprogress = (e) => {+ if (e.lengthComputable) onProgress((e.loaded / e.total) * 100);+ };+ }++ xhr.onload = () => {+ if (xhr.status >= 200 && xhr.status < 300) resolve(JSON.parse(xhr.responseText));+ else reject(new Error(JSON.parse(xhr.responseText).error || 'Upload failed'));+ };+ xhr.onerror = () => reject(new Error('Upload failed'));+ xhr.send(formData);+ });+}+// FTP Server endpointsexport async function getFTPStatus() {return this.request('/ftp/status');