import 'dart:convert'; import 'dart:typed_data'; import '../../../core/transport/server_url.dart'; import '../data/upload/chat_upload.dart'; import '../domain/chat_attachment_picker.dart'; /// Posts one file's bytes to a `POST /files?path=` URL. typedef FilesUploadPost = Future Function( Uri uri, { required String name, required String mime, required Uint8List bytes, }); /// The transport the Files panel uploads with. /// /// Production keeps [postChatUpload] (raw body, name header, session cookie). /// Widget tests swap in a recorder so no socket is opened. Restore it after a /// test. FilesUploadPost postFileUpload = postChatUpload; /// Why one file could not be stored, in words the panel shows as they are. class FilesUploadException implements Exception { const FilesUploadException(this.message); final String message; @override String toString() => message; } /// Uploads [file] into [directory] on the server behind [endpoint] and returns /// the stored path the server reports. Every failure is a /// [FilesUploadException]; nothing is retried or renamed on the caller's /// behalf, so an existing file is reported rather than replaced. Future uploadFileInto( String endpoint, String directory, ChatPickedFile file, ) async { final name = file.name.trim(); if (name.isEmpty) { throw const FilesUploadException( 'A file without a name cannot be uploaded.', ); } final Uri uri; try { uri = ServerUrl.resourceUri( endpoint, '/files', query: {'path': directory}, ); } on FormatException { throw const FilesUploadException( 'No server is configured to upload files to.', ); } final ChatUploadReply reply; try { reply = await postFileUpload( uri, name: name, mime: file.mime.trim().isEmpty ? 'application/octet-stream' : file.mime, bytes: file.bytes, ); } catch (error) { throw FilesUploadException('"$name" could not be uploaded: $error'); } final reason = reply.body.trim(); switch (reply.status) { case 200: break; case 401: throw const FilesUploadException( 'Sign in to upload files (Settings → Sign in).', ); case 409: throw FilesUploadException('"$name" already exists in this folder.'); case 413: throw FilesUploadException( '"$name" is too large to upload (100 MiB limit).', ); default: throw FilesUploadException( reason.isEmpty ? '"$name" could not be uploaded (HTTP ${reply.status}).' : '"$name" could not be uploaded: $reason', ); } try { final decoded = jsonDecode(reply.body); final path = decoded is Map ? decoded['path'] : null; if (path is String && path.isNotEmpty) return path; } on FormatException { // Reported below. } throw FilesUploadException('"$name" upload returned no stored path.'); }