import 'package:flutter/foundation.dart'; import '../../../core/api_gateway.dart'; import '../../../core/servers/elevation/elevating_gateway.dart'; import '../../../core/transport/pipelines_client.dart'; import '../data/directory_listing.dart'; import '../domain/chat_attachment_picker.dart'; import 'files_models.dart'; import 'files_mutations.dart'; import 'files_upload.dart'; import 'files_preferences.dart'; class FilesController extends ChangeNotifier { FilesController({ required this.gateway, required this.initialPath, this.sessionId, this.folderPreferences, }); final ApiGateway gateway; final String? sessionId; final FilesPreferences? folderPreferences; String initialPath; bool _started = false; DirectoryListing? listing; String? error; bool loading = false; bool showHidden = false; String filter = ''; FilesSort sort = const FilesSort(FilesSortKey.name); FilesViewMode view = FilesViewMode.list; int _request = 0; bool _disposed = false; /// Files still being stored and the size of the batch they belong to. int uploading = 0; int uploadTotal = 0; /// Why the last upload batch failed, until dismissed or a new batch starts. String? uploadError; /// The rename, move or delete in flight ("Renaming…"), and why the last one /// was refused, in the server's words, until dismissed or the next starts. String? mutationLabel; String? mutationError; bool get missingDirectory => initialPath.trim().isEmpty; String get uploadLabel => uploadTotal <= 1 ? 'Uploading…' : 'Uploading ${uploadTotal - uploading + 1} of $uploadTotal…'; List get entries { final current = listing; if (current == null) return const []; final needle = filter.trim().toLowerCase(); return sortFileEntries( current.entries.where( (entry) => (showHidden || !entry.hidden) && (needle.isEmpty || entry.name.toLowerCase().contains(needle)), ), sort, ); } Future start() { _started = true; return _openRemembered(); } Future _openRemembered() async { final remembered = sessionId == null || folderPreferences == null ? null : await folderPreferences!.rememberedFolder(sessionId!); if (_disposed) return; final candidate = remembered != null && _isWithinRoot(remembered) ? remembered : _rootPath; await _openWithFallback(candidate); } Future _openWithFallback(String candidate) async { var path = _isWithinRoot(candidate) ? _normal(candidate) : _rootPath; while (path.trim().isNotEmpty) { final request = ++_request; loading = true; error = null; _notify(); try { final next = await listDirectory(gateway, path); if (_disposed || request != _request) return; listing = next; filter = ''; await _remember(next.path); loading = false; _notify(); return; } catch (_) { if (_disposed || request != _request) return; final parent = _parentWithinRoot(path); if (parent == null) { error = "Couldn't load this folder."; loading = false; _notify(); return; } path = parent; } } } String? _parentWithinRoot(String path) { if (path == _rootPath) return null; final slash = path.lastIndexOf('/'); if (slash < 0) return null; final parent = slash == 0 ? '/' : path.substring(0, slash); return _isWithinRoot(parent) ? parent : null; } String get _rootPath => _normal(initialPath); String _normal(String path) { final value = path.trim(); return value.length > 1 && value.endsWith('/') ? value.replaceFirst(RegExp(r'/+$'), '') : value; } bool _isWithinRoot(String path) => isInsideHome(_rootPath, _normal(path)); Future _remember(String path) async { if (sessionId != null && folderPreferences != null) { await folderPreferences!.setRememberedFolder(sessionId!, path); } } /// Session metadata can arrive after the retained conversation is mounted. /// Keep a folder the operator navigated to; otherwise load the new root. Future updateInitialPath(String path) async { if (_disposed || path.trim().isEmpty || path == initialPath) return; final previous = initialPath; initialPath = path; if (_started && (listing == null || listing!.path == previous)) { listing = null; await _openRemembered(); } else { _notify(); } } Future open(String? path) async { if (path == null || path.trim().isEmpty) return; final request = ++_request; loading = true; error = null; _notify(); try { final next = await listDirectory(gateway, path); if (_disposed || request != _request) return; listing = next; filter = ''; await _remember(next.path); } catch (e) { if (_disposed || request != _request) return; error = "Couldn't load this folder."; } finally { if (!_disposed && request == _request) { loading = false; _notify(); } } } Future retry() => open(listing?.path ?? initialPath); /// Stores [files] in the shown folder, one request each, then reloads that /// folder so the new entries appear. Each refusal is kept in [uploadError] /// in the server's words; the remaining files are still attempted. Future upload(List files) async { final directory = listing?.path; if (files.isEmpty) return; if (directory == null) { reportUploadError('Open a folder before uploading files.'); return; } final endpoint = configuredGatewayEndpoint(gateway); uploadTotal += files.length; uploading += files.length; uploadError = null; _notify(); final failures = []; for (final file in files) { try { await uploadFileInto( endpoint, directory, file, elevation: elevationOf(gateway), ); } on FilesUploadException catch (error) { failures.add(error.message); } finally { uploading -= 1; } if (_disposed) return; _notify(); } if (uploading == 0) uploadTotal = 0; if (failures.isNotEmpty) uploadError = failures.join('\n'); _notify(); // The operator may have moved on while the batch was in flight; only the // folder that received the files is reloaded. if (listing?.path == directory) await retry(); } /// Shows a host-side upload failure (no picker, unreadable drop) in the /// same place as a server refusal. void reportUploadError(String message) { uploadError = message; _notify(); } void dismissUploadError() { uploadError = null; _notify(); } Future rename(DirectoryEntry entry, String name) async => await _mutate('Renaming…', () => renamePath(gateway, entry.path, name)) == null; Future move(DirectoryEntry entry, String into) async => await _mutate('Moving…', () => movePath(gateway, entry.path, into)) == null; /// A folder with contents is refused unless [recursive]; that refusal is /// returned as [FilesDeleteResult.notEmpty] for the panel to ask about and /// is not shown as an error. Future delete( DirectoryEntry entry, { bool recursive = false, }) async { final failure = await _mutate( 'Deleting…', () => deletePath(gateway, entry.path, recursive: recursive), report: (error) => !isFolderNotEmptyError(error), ); if (failure == null) return FilesDeleteResult.deleted; return isFolderNotEmptyError(failure) ? FilesDeleteResult.notEmpty : FilesDeleteResult.failed; } /// Runs one mutation, then reloads the shown folder whether it succeeded or /// not (a refusal such as "does not exist" means the listing is stale too). /// Returns the failure, recorded in [mutationError] unless [report] declines. Future _mutate( String label, Future Function() action, { bool Function(Object error)? report, }) async { mutationLabel = label; mutationError = null; _notify(); Object? failure; try { await action(); } catch (error) { failure = error; if (report == null || report(error)) mutationError = '$error'; } mutationLabel = null; if (_disposed) return failure; _notify(); await retry(); return failure; } void dismissMutationError() { mutationError = null; _notify(); } void toggleHidden(bool value) { showHidden = value; _notify(); } void setFilter(String value) { filter = value; _notify(); } void setSort(FilesSort value) { sort = value; _notify(); } void setView(FilesViewMode value) { view = value; _notify(); } void _notify() { if (!_disposed) notifyListeners(); } @override void dispose() { _disposed = true; _request++; super.dispose(); } }