ente/lib/utils/file_download_util.dart

73 lines
2.5 KiB
Dart
Raw Normal View History

import 'dart:io' as io;
import 'dart:typed_data';
2021-08-09 06:21:09 +00:00
import 'package:dio/dio.dart';
import 'package:logging/logging.dart';
import 'package:photos/core/configuration.dart';
2023-02-03 07:39:04 +00:00
import 'package:photos/core/network/network.dart';
import 'package:photos/models/file.dart' as ente;
import 'package:photos/services/collections_service.dart';
2021-10-30 05:51:23 +00:00
import 'package:photos/utils/crypto_util.dart';
final _logger = Logger("file_download_util");
2022-12-29 13:36:35 +00:00
Future<io.File?> downloadAndDecrypt(
2022-06-11 08:23:52 +00:00
ente.File file, {
2022-12-29 13:36:35 +00:00
ProgressCallback? progressCallback,
2022-06-11 08:23:52 +00:00
}) {
_logger.info("Downloading file " + file.uploadedFileID.toString());
final encryptedFilePath = Configuration.instance.getTempDirectory() +
file.generatedID.toString() +
".encrypted";
final encryptedFile = io.File(encryptedFilePath);
final startTime = DateTime.now().millisecondsSinceEpoch;
2023-02-03 07:39:04 +00:00
return NetworkClient.instance
.getDio()
.download(
2022-09-23 01:48:25 +00:00
file.downloadUrl,
encryptedFilePath,
options: Options(
headers: {"X-Auth-Token": Configuration.instance.getToken()},
),
onReceiveProgress: progressCallback,
)
.then((response) async {
if (response.statusCode != 200) {
_logger.warning("Could not download file: ", response.toString());
return null;
} else if (!encryptedFile.existsSync()) {
_logger.warning("File was not downloaded correctly.");
return null;
}
_logger.info("File downloaded: " + file.uploadedFileID.toString());
2022-06-11 08:23:52 +00:00
_logger.info(
"Download speed: " +
(await io.File(encryptedFilePath).length() /
(DateTime.now().millisecondsSinceEpoch - startTime))
.toString() +
"kBps",
);
final decryptedFilePath = Configuration.instance.getTempDirectory() +
file.generatedID.toString() +
".decrypted";
final decryptedFile = io.File(decryptedFilePath);
2022-06-11 08:23:52 +00:00
await CryptoUtil.decryptFile(
encryptedFilePath,
decryptedFilePath,
2023-02-03 04:41:45 +00:00
CryptoUtil.base642bin(file.fileDecryptionHeader!),
2023-02-27 10:44:27 +00:00
getFileKey(file),
2022-06-11 08:23:52 +00:00
);
_logger.info("File decrypted: " + file.uploadedFileID.toString());
2021-08-09 06:21:09 +00:00
await encryptedFile.delete();
return decryptedFile;
});
}
2023-02-27 10:44:27 +00:00
Uint8List getFileKey(ente.File file) {
2023-02-03 04:41:45 +00:00
final encryptedKey = CryptoUtil.base642bin(file.encryptedKey!);
final nonce = CryptoUtil.base642bin(file.keyDecryptionNonce!);
final collectionKey =
2022-12-29 13:36:35 +00:00
CollectionsService.instance.getCollectionKey(file.collectionID!);
return CryptoUtil.decryptSync(encryptedKey, collectionKey, nonce);
}