silentFetchAndRefresh method

Future<FetchedProduct> silentFetchAndRefresh({
  1. required LocalDatabase localDatabase,
  2. required String barcode,
})

Fetches the product from the server and refreshes the local database.

Silent version.

Implementation

Future<FetchedProduct> silentFetchAndRefresh({
  required LocalDatabase localDatabase,
  required String barcode,
}) async {
  // Now we let "food" redirect the queries if needed, as we use
  // ProductTypeFilter.all
  const ProductType productType = ProductType.food;
  final UriProductHelper uriProductHelper = ProductQuery.getUriProductHelper(
    productType: productType,
  );
  try {
    final List<String> unwantedIngredients =
        (await UserPreferences.getUserPreferences())
            .getUnwantedIngredientTags();

    final OpenFoodFactsLanguage language = ProductQuery.getLanguage();
    final ProductResultV3 result = await OpenFoodAPIClient.getProductV3(
      getBarcodeQueryConfiguration(
        barcode,
        language,
        unwantedIngredients: IngredientsUnwantedParameter(
          unwantedIngredients,
        ),
      ),
      uriHelper: uriProductHelper,
      user: ProductQuery.getReadUser(),
    );
    if (result.product != null) {
      await DaoProduct(
        localDatabase,
      ).put(result.product!, language, productType: productType);
      localDatabase.upToDate.setLatestDownloadedProduct(result.product!);

      unawaited(_failSafeFolksonomyRefresh(barcode, localDatabase));

      return FetchedProduct.found(result.product!);
    }
    return const FetchedProduct.internetNotFound();
  } catch (e) {
    Logs.e('Refresh from server error', ex: e);
    final List<ConnectivityResult> connectivityResult = await Connectivity()
        .checkConnectivity();
    if (connectivityResult.contains(ConnectivityResult.none)) {
      return FetchedProduct.error(
        exceptionString: e.toString(),
        isConnected: false,
      );
    }
    final String host = uriProductHelper.host;
    final PingEvent pingEvent = await Ping(host, count: 1).stream.first;
    return FetchedProduct.error(
      exceptionString: e.toString(),
      isConnected: true,
      failedPingedHost: pingEvent is! PingError ? null : host,
    );
  }
}