file download actor
This commit is contained in:
parent
0cdf3d7dbf
commit
0596fdec27
4 changed files with 179 additions and 0 deletions
57
lib/src/file_download_actor.dart
Normal file
57
lib/src/file_download_actor.dart
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import 'dart:typed_data';
|
||||
|
||||
import 'package:actors/actors.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import 'file_actor.dart';
|
||||
|
||||
sealed class FileDownloadMessage {
|
||||
const FileDownloadMessage();
|
||||
}
|
||||
|
||||
final class DownloadFile extends FileDownloadMessage {
|
||||
final String url;
|
||||
final String savePath;
|
||||
const DownloadFile({required this.url, required this.savePath});
|
||||
}
|
||||
|
||||
sealed class FileDownloadResult {
|
||||
const FileDownloadResult();
|
||||
}
|
||||
|
||||
final class FileDownloaded extends FileDownloadResult {
|
||||
final String savePath;
|
||||
const FileDownloaded(this.savePath);
|
||||
}
|
||||
|
||||
class FileDownloadActor
|
||||
with Handler<FileDownloadMessage, FileDownloadResult> {
|
||||
final FileActor _fileActor;
|
||||
final http.Client _httpClient;
|
||||
|
||||
FileDownloadActor({
|
||||
required FileActor fileActor,
|
||||
http.Client? httpClient,
|
||||
}) : _fileActor = fileActor,
|
||||
_httpClient = httpClient ?? http.Client();
|
||||
|
||||
@override
|
||||
Future<FileDownloadResult> handle(FileDownloadMessage message) =>
|
||||
switch (message) {
|
||||
DownloadFile(:final url, :final savePath) => _download(url, savePath),
|
||||
};
|
||||
|
||||
@override
|
||||
Future<void> close() async => _httpClient.close();
|
||||
|
||||
Future<FileDownloaded> _download(String url, String savePath) async {
|
||||
final response = await _httpClient.get(Uri.parse(url));
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
throw Exception('Download failed: HTTP ${response.statusCode}');
|
||||
}
|
||||
await _fileActor.handle(
|
||||
SaveBinaryFile(savePath, Uint8List.fromList(response.bodyBytes)),
|
||||
);
|
||||
return FileDownloaded(savePath);
|
||||
}
|
||||
}
|
||||
|
|
@ -5,4 +5,5 @@ export 'src/nostr_fetch_actor.dart';
|
|||
export 'src/nostr_signer_actor.dart';
|
||||
export 'src/geo_actor.dart';
|
||||
export 'src/file_upload_actor.dart';
|
||||
export 'src/file_download_actor.dart';
|
||||
export 'src/nostr_account_actor.dart';
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue