upload method
- LocalDatabase localDatabase
override
Uploads the product image.
Implementation
@override
Future<void> upload(LocalDatabase localDatabase) async {
final UriProductHelper uriProductHelper = await getUriProductHelper(
localDatabase,
);
SendImage? image;
BackgroundCropResult? cropResult;
try {
final ImageField imageField = ImageField.fromOffTag(this.imageField)!;
final OpenFoodFactsLanguage language = getLanguage();
final User user = getUser();
Future<Status> addImage({required bool force}) async {
cropResult = await cropIfNeeded(
fullPath: fullPath,
rotationDegrees: rotationDegrees,
cropX1: cropX1,
cropY1: cropY1,
cropX2: cropX2,
cropY2: cropY2,
forceCompression: force,
eraserCoordinates: eraserCoordinates,
);
final String? path = cropResult!.filePath;
if (path == null) {
// TODO(monsieurtanuki): maybe something more refined when we dismiss the picture, like alerting the user, though it's not supposed to happen anymore from upstream.
throw Exception('Could not get image path after compression');
}
image = SendImage(
lang: language,
barcode: barcode,
imageField: imageField,
imageUri: Uri.parse(path),
);
return OpenFoodAPIClient.addProductImage(
user,
image!,
uriHelper: uriProductHelper,
);
}
Status status;
try {
status = await addImage(force: false);
} catch (e) {
if (e.toString().contains('413') ||
e.toString().contains('Request Entity Too Large')) {
status = await addImage(force: true);
} else {
rethrow;
}
}
if (status.status == 'status ok') {
// successfully uploaded a new picture and set it as field+language
return;
}
final int? imageId = status.imageId;
if (status.status == 'status not ok' && imageId != null) {
// The very same image was already uploaded and therefore was rejected.
// We just have to select this image, with no angle.
if (imageField == ImageField.OTHER) {
// we're done here: all we wanted was to have the image uploaded, and
// it is. And the server rejects "set as" operation for OTHER images.
return;
}
final String? imageUrl = await OpenFoodAPIClient.setProductImageAngle(
barcode: barcode,
imageField: imageField,
language: language,
imgid: '$imageId',
angle: ImageAngle.NOON,
user: user,
uriHelper: uriProductHelper,
);
if (imageUrl == null) {
throw Exception('Could not select picture');
}
return;
}
throw Exception(
'Could not upload picture: ${status.status} / ${status.error}',
);
} catch (e) {
throw Exception('$e $cropResult - ${image?.toJson()}');
}
}