π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:integration_test/integration_test.dart';
import 'package:logging/logging.dart';
import 'package:native_video_editor/native_video_editor.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path/path.dart' as path_helper;
import 'package:photo_manager/photo_manager.dart';
import 'package:photos/core/configuration.dart';
import 'package:photos/core/network/network.dart';
import 'package:photos/db/files_db.dart';
import 'package:photos/models/file/file.dart';
import 'package:photos/models/metadata/file_magic.dart';
import 'package:photos/module/download/file.dart';
import 'package:photos/module/metadata/local_file.dart';
import 'package:photos/service_locator.dart';
import 'package:photos/services/file_magic_service.dart';
import 'package:photos/ui/tools/editor/native_video_export_service.dart';
import 'package:photos/ui/tools/editor/video_crop_util.dart';
import 'package:photos/ui/tools/editor/video_editor/crop_value.dart';
import 'package:photos/ui/tools/editor/video_editor/video_editor_controller.dart';
import 'package:shared_preferences/shared_preferences.dart';
class TrimConfig {
final String label;
final Duration? duration;
final Duration startOffset;
const TrimConfig({
required this.label,
this.duration,
this.startOffset = Duration.zero,
});
bool get shouldTrim => duration != null;
@override
String toString() => label;
}
class TrimConfigs {
static const noTrim = TrimConfig(label: "no-trim", duration: null);
static TrimConfig fromSeconds(int seconds) {
return TrimConfig(
label: "trim-${seconds}s",
duration: Duration(seconds: seconds),
);
}
static TrimConfig fromDuration(Duration duration) {
final totalSeconds = duration.inSeconds;
return TrimConfig(label: "trim-${totalSeconds}s", duration: duration);
}
static TrimConfig fromRange({
required int startSeconds,
required int lengthSeconds,
}) {
return TrimConfig(
label: "trim-${startSeconds}s-${startSeconds + lengthSeconds}s",
duration: Duration(seconds: lengthSeconds),
startOffset: Duration(seconds: startSeconds),
);
}
}
class ValidationFailure {
final String fileId;
final String description;
final String failureType;
final String expected;
final String actual;
final String? stackTrace;
ValidationFailure({
required this.fileId,
required this.description,
required this.failureType,
required this.expected,
required this.actual,
this.stackTrace,
});
}
class IterationResult {
final List<ValidationFailure> validationFailures;
IterationResult({required this.validationFailures});
}
class TestFileConfig {
final List<int> fileIds;
final int? collectionId;
final List<TrimConfig> trimOptions;
final List<String> cropOptions;
final List<int> rotateOptions;
TestFileConfig({
required this.fileIds,
this.collectionId,
required this.trimOptions,
required this.cropOptions,
required this.rotateOptions,
});
int get totalIterationsPerFile =>
trimOptions.length * cropOptions.length * rotateOptions.length;
int get totalIterations => totalIterationsPerFile * fileIds.length;
}
// Run:
// flutter drive --driver=test_driver/integration_test.dart \
// --target=integration_test/video_editor_test.dart --flavor independent
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
final logger = Logger("VideoEditorIntegrationTest");
Logger.root.level = Level.INFO;
Logger.root.onRecord.listen((record) {
// ignore: avoid_print
print('[${record.level.name}] ${record.time}: ${record.message}');
});
final testFiles = [
TestFileConfig(
// TODO: Update with the generated file IDs available on the test device.
fileIds: [0],
collectionId: null,
trimOptions: [
TrimConfigs.fromSeconds(3),
TrimConfigs.fromRange(startSeconds: 1, lengthSeconds: 5),
],
cropOptions: ["1:1", "9:16", "16:9", "3:4", "4:3"],
rotateOptions: [0, 90, 180, 270],
),
];
group('Video Editor Integration Test', () {
testWidgets('Process videos with all trim/crop/rotate combinations', (
WidgetTester tester,
) async {
final prefs = await SharedPreferences.getInstance();
final packageInfo = await PackageInfo.fromPlatform();
await NetworkClient.instance.init(packageInfo, prefs);
ServiceLocator.instance.init(
prefs,
NetworkClient.instance.enteDio,
NetworkClient.instance.getDio(),
NetworkClient.instance.downloadDio,
packageInfo,
);
await Configuration.instance.init(prefs);
expect(
testFiles,
isNotEmpty,
reason: 'Please configure at least one test configuration',
);
for (final config in testFiles) {
expect(
config.fileIds,
isNotEmpty,
reason: 'Please set at least one fileId in each configuration',
);
for (final fileId in config.fileIds) {
expect(
fileId,
isNot(0),
reason: 'Please set valid fileIds (found 0)',
);
}
}
final totalFiles = testFiles.fold(
0,
(sum, config) => sum + config.fileIds.length,
);
final totalIterations = testFiles.fold(
0,
(sum, config) => sum + config.totalIterations,
);
logger.info('βββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
logger.info(
'Starting test with $totalFiles file(s), ${testFiles.length} configuration(s)',
);
logger.info('Total iterations: $totalIterations');
logger.info('βββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n');
int globalIterationCount = 0;
final successfulExports = <String>[];
final failedExports = <String, String>{};
final validationFailures = <ValidationFailure>[];
for (int configIndex = 0; configIndex < testFiles.length; configIndex++) {
final config = testFiles[configIndex];
logger.info(
'\nβββββββββββββββββββββββββββββββββββββββββββββββββββββββββ',
);
logger.info('β CONFIG ${configIndex + 1}/${testFiles.length}');
logger.info('β Files: ${config.fileIds}');
logger.info('β Iterations per file: ${config.totalIterationsPerFile}');
logger.info('β Trim: ${config.trimOptions}');
logger.info('β Crop: ${config.cropOptions}');
logger.info('β Rotate: ${config.rotateOptions}');
logger.info(
'βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n',
);
for (
int fileIndex = 0;
fileIndex < config.fileIds.length;
fileIndex++
) {
final fileId = config.fileIds[fileIndex];
logger.info('βββββββββββββββββββββββββββββββββββββββββββββββββββββ');
logger.info(
'File ${fileIndex + 1}/${config.fileIds.length} in config ${configIndex + 1}: ID $fileId',
);
logger.info('βββββββββββββββββββββββββββββββββββββββββββββββββββββ');
logger.info('Loading source file with ID: $fileId');
final sourceFile = await FilesDB.instance.getAnyUploadedFile(fileId);
expect(
sourceFile,
isNotNull,
reason: 'Uploaded file with ID $fileId not found',
);
File? sourceIoFile;
if (sourceFile!.localID != null) {
final assetEntity = await sourceFile.getAsset;
if (assetEntity != null) {
sourceIoFile = await assetEntity.file;
if (sourceIoFile == null || !sourceIoFile.existsSync()) {
logger.warning(
'Local asset file missing for uploaded file $fileId despite AssetEntity, will try server fetch.',
);
sourceIoFile = null;
}
} else {
logger.info(
'AssetEntity not found locally for uploaded file $fileId. Falling back to server fetch.',
);
}
}
if (sourceIoFile == null && sourceFile.isUploaded) {
logger.info('Fetching uploaded file $fileId from server cache...');
sourceIoFile = await getFileFromServer(sourceFile);
}
expect(
sourceIoFile,
isNotNull,
reason: 'Source video file not available for uploaded file $fileId',
);
expect(
sourceIoFile!.existsSync(),
isTrue,
reason: 'Downloaded source video file missing on disk for $fileId',
);
logger.info('Source file loaded: ${sourceFile.title}');
logger.info('Video path: ${sourceIoFile.path}\n');
int fileIterationCount = 0;
for (final trimOption in config.trimOptions) {
for (final cropOption in config.cropOptions) {
for (final rotateOption in config.rotateOptions) {
globalIterationCount++;
fileIterationCount++;
final description =
't: $trimOption, c: $cropOption, r: $rotateOption';
logger.info(
'βββββββββββββββββββββββββββββββββββββββββββββββββββββββ',
);
logger.info(
'File $fileId, Iteration $fileIterationCount/${config.totalIterationsPerFile} (Global: $globalIterationCount/$totalIterations)',
);
logger.info('Settings: $description');
logger.info(
'βββββββββββββββββββββββββββββββββββββββββββββββββββββββ',
);
try {
final result = await _processVideoIteration(
sourceFile: sourceFile,
sourceIoFile: sourceIoFile,
collectionId: config.collectionId,
trimOption: trimOption,
cropOption: cropOption,
rotateOption: rotateOption,
description: description,
logger: logger,
);
final totalFailures = result.validationFailures.length;
if (totalFailures == 0) {
successfulExports.add('File $fileId: $description');
logger.info('β Iteration completed successfully\n');
} else {
validationFailures.addAll(result.validationFailures);
final msg =
'β Iteration completed with $totalFailures validation failure(s)\n';
logger.warning(msg);
}
} catch (e, s) {
failedExports['File $fileId: $description'] = e.toString();
logger.severe('β Iteration FAILED', e, s);
logger.severe('Error: $e\n');
// Continue with next iteration instead of failing entire test
}
}
}
}
logger.info(
'File $fileId completed: $fileIterationCount/${config.totalIterationsPerFile} iterations\n',
);
}
logger.info('βββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
logger.info('Config ${configIndex + 1}/${testFiles.length} completed');
logger.info(
'βββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n',
);
}
logger.info(
'\nβββββββββββββββββββββββββββββββββββββββββββββββββββββββββ',
);
logger.info('β FINAL TEST SUMMARY');
logger.info('βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
logger.info('Total configurations: ${testFiles.length}');
logger.info('Total files processed: $totalFiles');
logger.info('Total iterations: $totalIterations');
logger.info('Successful: ${successfulExports.length}');
logger.info('Export failures: ${failedExports.length}');
logger.info('Validation failures: ${validationFailures.length}');
if (failedExports.isNotEmpty) {
logger.severe(
'\nβββββββββββββββββββββββββββββββββββββββββββββββββββββββββ',
);
logger.severe('β EXPORT FAILURES (${failedExports.length})');
logger.severe(
'βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ',
);
failedExports.forEach((desc, error) {
logger.severe(' β $desc');
logger.severe(' Error: $error\n');
});
}
if (validationFailures.isNotEmpty) {
logger.warning(
'\nβββββββββββββββββββββββββββββββββββββββββββββββββββββββββ',
);
logger.warning('β VALIDATION FAILURES (${validationFailures.length})');
logger.warning(
'βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ',
);
final groupedFailures = <String, List<ValidationFailure>>{};
for (final failure in validationFailures) {
groupedFailures
.putIfAbsent(failure.failureType, () => [])
.add(failure);
}
groupedFailures.forEach((type, failures) {
logger.warning(
'\n ${type.toUpperCase()} (${failures.length} failures):',
);
for (final failure in failures) {
logger.warning(
' β File ${failure.fileId}: ${failure.description}',
);
logger.warning(' Expected: ${failure.expected}');
logger.warning(' Actual: ${failure.actual}');
}
});
logger.warning('');
}
logger.info('βββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n');
final totalFailures = failedExports.length + validationFailures.length;
expect(
totalFailures,
0,
reason:
'$totalFailures failure(s) detected (${failedExports.length} export, ${validationFailures.length} validation). See logs above.',
);
});
});
}
Future<IterationResult> _processVideoIteration({
required EnteFile sourceFile,
required File sourceIoFile,
required int? collectionId,
required TrimConfig trimOption,
required String cropOption,
required int rotateOption,
required String description,
required Logger logger,
}) async {
VideoEditorController? controller;
File? tempOutputFile;
final failures = <ValidationFailure>[];
CropCalculation? cropCalc;
try {
logger.info(' β Initializing video editor controller...');
controller = VideoEditorController.file(
sourceIoFile,
minDuration: const Duration(
milliseconds: 100,
), // Allow very short videos for testing
);
await controller.initialize();
final originalDuration = controller.videoDuration;
final originalSize = controller.sourceDisplaySize;
logger.info(' β Controller initialized');
logger.info(
' - Original duration: ${originalDuration.inMilliseconds}ms',
);
logger.info(
' - Original size: ${originalSize.width.toInt()}x${originalSize.height.toInt()}',
);
var expectedWidth = originalSize.width.toInt();
var expectedHeight = originalSize.height.toInt();
Duration? expectedDuration;
if (trimOption.shouldTrim) {
final startOffset = trimOption.startOffset;
final trimmedStart = startOffset > controller.videoDuration
? controller.videoDuration
: startOffset;
final desiredEnd = trimmedStart + trimOption.duration!;
final trimmedEnd = desiredEnd > controller.videoDuration
? controller.videoDuration
: desiredEnd;
if (trimmedStart >= trimmedEnd) {
logger.warning(
' β Skipping trim: start (${trimmedStart.inMilliseconds}ms) >= end (${trimmedEnd.inMilliseconds}ms)',
);
expectedDuration = controller.videoDuration;
} else {
logger.info(
' β Applying trim from ${trimmedStart.inMilliseconds}ms to ${trimmedEnd.inMilliseconds}ms...',
);
controller.updateTrim(trimmedStart, trimmedEnd);
expectedDuration = trimmedEnd - trimmedStart;
}
} else {
expectedDuration = originalDuration;
logger.info(' β No trim applied');
}
if (cropOption != "None") {
logger.info(' β Applying crop: $cropOption...');
CropValue? cropValue;
switch (cropOption) {
case "1:1":
cropValue = CropValue.ratio_1_1;
break;
case "16:9":
cropValue = CropValue.ratio_16_9;
break;
case "9:16":
cropValue = CropValue.ratio_9_16;
break;
case "3:4":
cropValue = CropValue.ratio_3_4;
break;
case "4:3":
cropValue = CropValue.ratio_4_3;
break;
}
if (cropValue != null) {
final aspectRatio = cropValue.getFraction()?.toDouble();
if (aspectRatio != null) {
controller.preferredCropAspectRatio = aspectRatio;
}
}
try {
cropCalc = VideoCropUtil.calculateFileSpaceCrop(controller: controller);
expectedWidth = cropCalc.width;
expectedHeight = cropCalc.height;
logger.info(
' β Crop applied: $cropOption (${expectedWidth}x$expectedHeight)',
);
} catch (e) {
logger.warning(' - Failed to calculate crop dimensions: $e');
logger.info(' β Crop applied: $cropOption');
}
} else {
logger.info(' β No crop applied');
}
if (rotateOption != 0) {
logger.info(' β Applying rotation: $rotateOptionΒ°...');
while (controller.rotation != 0) {
controller.rotate90Degrees(VideoRotationDirection.left);
}
switch (rotateOption) {
case 90:
controller.rotate90Degrees(VideoRotationDirection.right);
break;
case 180:
controller.rotate90Degrees(VideoRotationDirection.left);
controller.rotate90Degrees(VideoRotationDirection.left);
break;
case 270:
controller.rotate90Degrees(VideoRotationDirection.left);
break;
}
logger.info(' β Rotation applied: ${controller.rotation}Β°');
} else {
logger.info(' β No rotation applied');
}
logger.info(' β Exporting video with native editor...');
final tempDir = Directory.systemTemp.createTempSync('video_export_test');
final outputPath = path_helper.join(
tempDir.path,
'export_${DateTime.now().millisecondsSinceEpoch}.mp4',
);
final exportedFile = await NativeVideoExportService.exportVideo(
controller: controller,
outputPath: outputPath,
onProgress: (progress) {
if ((progress * 100).round() % 25 == 0) {
logger.info(
' - Progress: ${(progress * 100).toStringAsFixed(0)}%',
);
}
},
onError: (e, s) {
logger.severe(
' β Native export failed - NO FFmpeg fallback in test!',
e,
s,
);
},
);
tempOutputFile = exportedFile;
logger.info(' β Export completed: ${exportedFile.path}');
logger.info(' β Saving to gallery...');
final suffixBuffer = StringBuffer();
if (trimOption.shouldTrim) {
suffixBuffer.write('_t');
}
if (cropOption != "None") {
suffixBuffer.write('_c_$cropOption');
}
if (rotateOption != 0) {
suffixBuffer.write('_r_$rotateOption');
}
final baseName = path_helper.basenameWithoutExtension(sourceFile.title!);
final fileName =
baseName +
suffixBuffer.toString() +
'_edited_' +
DateTime.now().microsecondsSinceEpoch.toString() +
'.mp4';
await PhotoManager.stopChangeNotify();
try {
final newAsset = await PhotoManager.editor.saveVideo(
exportedFile,
title: fileName,
);
logger.info(' β Saved to gallery: $fileName');
logger.info(' β Creating file entry in database...');
final newFile = fileFromAsset(sourceFile.deviceFolder ?? '', newAsset);
newFile.creationTime = sourceFile.creationTime;
newFile.collectionID = (collectionId == null || collectionId == 0)
? sourceFile.collectionID
: collectionId;
newFile.location = sourceFile.location;
newFile.generatedID = await FilesDB.instance.insertAndGetId(newFile);
logger.info(' β File entry created (ID: ${newFile.generatedID})');
final settingsToast = _buildSettingsToastMessage(
trimOption: trimOption,
cropOption: cropOption,
rotateOption: rotateOption,
);
if (settingsToast != null) {
await Fluttertoast.showToast(
msg: settingsToast,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.TOP,
);
}
logger.info(' β Validating exported video...');
try {
final videoInfo = await NativeVideoEditor.inspectVideo(
exportedFile.path,
);
final actualDuration = videoInfo.duration;
final actualWidth = videoInfo.width;
final actualHeight = videoInfo.height;
logger.info(
' - Actual duration: ${actualDuration.inMilliseconds}ms',
);
logger.info(' - Actual size: ${actualWidth}x$actualHeight');
// Allow 100ms for encoding variation.
final durationDiff =
(actualDuration.inMilliseconds - expectedDuration.inMilliseconds)
.abs();
if (durationDiff > 100) {
failures.add(
ValidationFailure(
fileId: sourceFile.generatedID.toString(),
description: description,
failureType: 'duration',
expected: '${expectedDuration.inMilliseconds}ms',
actual:
'${actualDuration.inMilliseconds}ms (diff: ${durationDiff}ms)',
),
);
logger.warning(
' β Duration mismatch! Expected: ${expectedDuration.inMilliseconds}ms, Got: ${actualDuration.inMilliseconds}ms',
);
}
final expectedRotation = rotateOption;
final isRotated = expectedRotation % 180 != 0;
var finalExpectedWidth = expectedWidth;
var finalExpectedHeight = expectedHeight;
if (isRotated) {
final temp = finalExpectedWidth;
finalExpectedWidth = finalExpectedHeight;
finalExpectedHeight = temp;
}
// Allow 2px for encoding variation.
bool widthOk = (actualWidth - finalExpectedWidth).abs() <= 2;
bool heightOk = (actualHeight - finalExpectedHeight).abs() <= 2;
if (!widthOk || !heightOk) {
final swappedWidth = finalExpectedHeight;
final swappedHeight = finalExpectedWidth;
final swappedWidthOk = (actualWidth - swappedWidth).abs() <= 2;
final swappedHeightOk = (actualHeight - swappedHeight).abs() <= 2;
if (swappedWidthOk && swappedHeightOk) {
logger.info(
' - Exported dimensions appear swapped (${actualWidth}x$actualHeight) vs expected ${finalExpectedWidth}x$finalExpectedHeight. '
'Accepting as valid.',
);
widthOk = true;
heightOk = true;
}
}
if (!widthOk) {
failures.add(
ValidationFailure(
fileId: sourceFile.generatedID.toString(),
description: description,
failureType: 'width',
expected: '$finalExpectedWidth',
actual: '$actualWidth',
),
);
logger.warning(
' β Width mismatch! Expected: $finalExpectedWidth, Got: $actualWidth',
);
}
if (!heightOk) {
failures.add(
ValidationFailure(
fileId: sourceFile.generatedID.toString(),
description: description,
failureType: 'height',
expected: '$finalExpectedHeight',
actual: '$actualHeight',
),
);
logger.warning(
' β Height mismatch! Expected: $finalExpectedHeight, Got: $actualHeight',
);
}
if (failures.isEmpty) {
logger.info(' β Validation passed');
} else {
logger.warning(' β Validation found ${failures.length} issue(s)');
}
} catch (e) {
logger.warning(' - Failed to validate video info: $e');
// Non-fatal - continue
}
logger.info(' β Updating video description...');
if (newFile.uploadedFileID != null) {
try {
await FileMagicService.instance.updatePublicMagicMetadata(
[newFile],
{captionKey: description},
);
logger.info(' β Description set: "$description"');
} catch (e) {
logger.warning(' - Failed to update description (non-fatal): $e');
}
} else {
logger.info(
' - Skipping description update (file not uploaded yet)',
);
}
if (tempOutputFile.existsSync()) {
tempOutputFile.deleteSync();
}
} finally {
await PhotoManager.startChangeNotify();
}
} finally {
controller?.dispose();
if (tempOutputFile != null && tempOutputFile.existsSync()) {
try {
tempOutputFile.deleteSync();
} catch (_) {}
}
}
return IterationResult(validationFailures: failures);
}
String? _buildSettingsToastMessage({
required TrimConfig trimOption,
required String cropOption,
required int rotateOption,
}) {
final parts = <String>[];
if (trimOption.shouldTrim) {
final start = trimOption.startOffset.inSeconds;
final end =
(trimOption.startOffset + (trimOption.duration ?? Duration.zero))
.inSeconds;
parts.add('Trim: ${start}s β ${end}s');
}
if (cropOption != 'None') {
parts.add('Crop: $cropOption');
}
if (rotateOption % 360 != 0) {
parts.add('Rotate: ${rotateOption % 360}Β°');
}
if (parts.isEmpty) {
return null;
}
return parts.join(' β’ ');
}