Files
pipelines/app/lib/features/chat/files/files_controller.dart
T
alan 9702d68d2d Ask for the password once and retry when a machine requires elevation
Carry the protocol error code, wrap each machine's gateway so an
elevation_required refusal shows one native password dialog, elevates that
connection and retries; send the upload token with file uploads; add a Settings
sign-in security section with the weak-password warning and sign out
everywhere; accept the __Host- session cookie.
2026-11-10 01:21:28 +00:00

238 lines
6.8 KiB
Dart

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';
class FilesController extends ChangeNotifier {
FilesController({required this.gateway, required this.initialPath});
final ApiGateway gateway;
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<DirectoryEntry> 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<void> start() {
_started = true;
return open(initialPath);
}
/// Session metadata can arrive after the retained conversation is mounted.
/// Keep a folder the operator navigated to; otherwise load the new root.
Future<void> 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 open(path);
} else {
_notify();
}
}
Future<void> 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 = '';
} catch (e) {
if (_disposed || request != _request) return;
error = "Couldn't load this folder.";
} finally {
if (!_disposed && request == _request) {
loading = false;
_notify();
}
}
}
Future<void> 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<void> upload(List<ChatPickedFile> 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 = <String>[];
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<bool> rename(DirectoryEntry entry, String name) async =>
await _mutate('Renaming…', () => renamePath(gateway, entry.path, name)) ==
null;
Future<bool> 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<FilesDeleteResult> 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<Object?> _mutate(
String label,
Future<String> 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();
}
}