diff --git a/app/src/main/java/openfoodfacts/github/scrachx/openfood/features/allergensalert/AllergensAlertFragment.kt b/app/src/main/java/openfoodfacts/github/scrachx/openfood/features/allergensalert/AllergensAlertFragment.kt index ca624260aa63..0272825fc9a1 100644 --- a/app/src/main/java/openfoodfacts/github/scrachx/openfood/features/allergensalert/AllergensAlertFragment.kt +++ b/app/src/main/java/openfoodfacts/github/scrachx/openfood/features/allergensalert/AllergensAlertFragment.kt @@ -22,6 +22,7 @@ import android.view.* import androidx.appcompat.app.AppCompatActivity import androidx.core.content.edit import androidx.core.content.res.ResourcesCompat +import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView.AdapterDataObserver import com.afollestad.materialdialogs.MaterialDialog @@ -29,6 +30,8 @@ import dagger.hilt.android.AndroidEntryPoint import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.rxkotlin.addTo import io.reactivex.schedulers.Schedulers +import kotlinx.coroutines.launch +import kotlinx.coroutines.rx2.await import net.steamcrafted.loadtoast.LoadToast import openfoodfacts.github.scrachx.openfood.R import openfoodfacts.github.scrachx.openfood.analytics.AnalyticsEvent @@ -102,6 +105,7 @@ class AllergensAlertFragment : NavigationBaseFragment() { .doOnError { Log.e(LOG_TAG, "getAllergensByLanguageCode", it) } .subscribe { allergens -> allergensFromDao = allergens } .addTo(disp) + mSettings = requireActivity().getSharedPreferences("prefs", 0) } @@ -140,7 +144,9 @@ class AllergensAlertFragment : NavigationBaseFragment() { .title(R.string.title_dialog_alert) .items(allergens.map { it.name }) .itemsCallback { _, _, position, _ -> - productRepository.setAllergenEnabled(allergens[position].allergenTag, true) + viewLifecycleOwner.lifecycleScope.launch { + productRepository.setAllergenEnabled(allergens[position].allergenTag, true).await() + } mAllergensEnabled!!.add(allergens[position]) adapter.notifyItemInserted(mAllergensEnabled!!.size - 1) binding.allergensRecycle.scrollToPosition(adapter.itemCount - 1) diff --git a/app/src/main/java/openfoodfacts/github/scrachx/openfood/features/product/view/summary/SummaryProductFragment.kt b/app/src/main/java/openfoodfacts/github/scrachx/openfood/features/product/view/summary/SummaryProductFragment.kt index 7596fa643b45..7730155072c2 100644 --- a/app/src/main/java/openfoodfacts/github/scrachx/openfood/features/product/view/summary/SummaryProductFragment.kt +++ b/app/src/main/java/openfoodfacts/github/scrachx/openfood/features/product/view/summary/SummaryProductFragment.kt @@ -607,8 +607,9 @@ class SummaryProductFragment : BaseFragment(), ISummaryProductPresenter.View { binding.productAllergenAlertLayout.visibility = View.VISIBLE return } - binding.productAllergenAlertText.text = - "${resources.getString(R.string.product_allergen_prompt)}\n${data.allergens.joinToString(", ")}" + binding.productAllergenAlertText.text = StringBuilder(resources.getString(R.string.product_allergen_prompt)) + .append("\n").append(data.allergens.joinToString(", ")) + binding.productAllergenAlertLayout.visibility = View.VISIBLE } diff --git a/app/src/main/java/openfoodfacts/github/scrachx/openfood/models/entities/allergen/AllergenHelper.kt b/app/src/main/java/openfoodfacts/github/scrachx/openfood/models/entities/allergen/AllergenHelper.kt index 52e13750498d..c7c44e0386b7 100644 --- a/app/src/main/java/openfoodfacts/github/scrachx/openfood/models/entities/allergen/AllergenHelper.kt +++ b/app/src/main/java/openfoodfacts/github/scrachx/openfood/models/entities/allergen/AllergenHelper.kt @@ -7,17 +7,21 @@ import java.util.* object AllergenHelper { @Contract(" -> new") - private fun createEmpty() = Data(false, emptyList()) + private fun createEmpty() = Data(false, emptyList()) fun computeUserAllergen(product: Product, userAllergens: List): Data { if (userAllergens.isEmpty()) return createEmpty() - if (!product.statesTags.contains(ApiFields.StateTags.INGREDIENTS_COMPLETED)) - return Data(true, emptyList()) + if (ApiFields.StateTags.INGREDIENTS_COMPLETED !in product.statesTags) + return Data(true, emptyList()) + + val productAllergens = HashSet(product.allergensHierarchy) + .also { it += product.tracesTags } - val productAllergens = HashSet(product.allergensHierarchy).also { it += product.tracesTags } val allergenMatch = TreeSet() - userAllergens.filter { productAllergens.contains(it.allergenTag) }.mapTo(allergenMatch) { it.name } + userAllergens.filter { productAllergens.contains(it.allergenTag) } + .mapTo(allergenMatch) { it.name } + return Data(false, allergenMatch.toList()) } diff --git a/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/ApiFields.kt b/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/ApiFields.kt index c53186999e26..76d4c6c303c3 100644 --- a/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/ApiFields.kt +++ b/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/ApiFields.kt @@ -34,12 +34,12 @@ object ApiFields { const val INGREDIENTS_COMPLETED = "en:ingredients-completed" val INCOMPLETE_TAGS = listOf( - "to-be-completed", - "to-be-uploaded", - "to-be-checked", - "to-be-validated", - "to-be-selected", - "not-selected" + "to-be-completed", + "to-be-uploaded", + "to-be-checked", + "to-be-validated", + "to-be-selected", + "not-selected" ) } @@ -174,10 +174,10 @@ object ApiFields { const val SEARCH_TERMS = "search_terms" val TYPE_IMAGE = arrayOf( - ProductImageField.FRONT, - ProductImageField.INGREDIENTS, - ProductImageField.NUTRITION, - ProductImageField.PACKAGING + ProductImageField.FRONT, + ProductImageField.INGREDIENTS, + ProductImageField.NUTRITION, + ProductImageField.PACKAGING ) const val LANGUAGES_CODES = "languages_codes" const val URL = "url" @@ -196,108 +196,109 @@ object ApiFields { const val OTHER = "other" val PRODUCT_COMMON_FIELDS = setOf( - PRODUCT_NAME, - GENERIC_NAME, - IMAGE_SMALL_URL, - IMAGE_FRONT_URL, - IMAGE_INGREDIENTS_URL, - IMAGE_NUTRITION_URL, - IMAGE_PACKAGING_URL, - IMAGE_URL, - SELECTED_IMAGES, - LANGUAGES_CODES, - VITAMINS_TAGS, - MINERALS_TAGS, - AMINO_ACIDS_TAGS, - OTHER_NUTRITIONAL_SUBSTANCES_TAGS, - URL, - NUTRIMENTS, - BARCODE, - TRACES_TAGS, - INGREDIENTS_MAY_PALM_OIL_TAGS, - BRANDS_TAGS, - TRACES, - CATEGORIES_TAGS, - INGREDIENTS_TEXT, - INGREDIENTS_FROM_PALM_OIL_TAGS, - ADDITIVES_TAGS, - SERVING_SIZE, - ALLERGENS_TAGS, - ALLERGENS, - ORIGINS, - STORES, - NUTRITION_GRADE_FR, - NUTRITION_GRADES_TAGS, - NUTRIENT_LEVELS, - ECOSCORE, - COUNTRIES, - COUNTRIES_TAGS, - BRANDS, - PACKAGING, - LABELS_TAGS, - LABELS_HIERARCHY, - CITIES_TAGS, - QUANTITY, - INGREDIENTS_PALM_OIL_N, - LINK, - EMB_CODES_TAGS, - STATES_TAGS, - CREATOR, - CREATED_DATE_TIME, - LAST_MODIFIED_TIME, - LAST_MODIFIED_BY, - EDITORS_TAGS, - NOVA_GROUPS, - LANG, - PURCHASE_PLACES, - NUTRITION_DATA_PER, - NO_NUTRITION_DATA, - OTHER, - OTHER_INFORMATION, - CONSERVATION_CONDITIONS, - RECYCLING_INSTRUCTIONS_TO_DISCARD, - RECYCLING_INSTRUCTIONS_TO_RECYCLE, - WARNING, - CUSTOMER_SERVICE, - ENVIRONMENT_INFOCARD, - ENVIRONMENT_IMPACT_LEVEL_TAGS, - INGREDIENTS_ANALYSIS_TAGS, - INGREDIENTS, - STATES_TAGS + ALLERGENS_HIERARCHY, + PRODUCT_NAME, + GENERIC_NAME, + IMAGE_SMALL_URL, + IMAGE_FRONT_URL, + IMAGE_INGREDIENTS_URL, + IMAGE_NUTRITION_URL, + IMAGE_PACKAGING_URL, + IMAGE_URL, + SELECTED_IMAGES, + LANGUAGES_CODES, + VITAMINS_TAGS, + MINERALS_TAGS, + AMINO_ACIDS_TAGS, + OTHER_NUTRITIONAL_SUBSTANCES_TAGS, + URL, + NUTRIMENTS, + BARCODE, + TRACES_TAGS, + INGREDIENTS_MAY_PALM_OIL_TAGS, + BRANDS_TAGS, + TRACES, + CATEGORIES_TAGS, + INGREDIENTS_TEXT, + INGREDIENTS_FROM_PALM_OIL_TAGS, + ADDITIVES_TAGS, + SERVING_SIZE, + ALLERGENS_TAGS, + ALLERGENS, + ORIGINS, + STORES, + NUTRITION_GRADE_FR, + NUTRITION_GRADES_TAGS, + NUTRIENT_LEVELS, + ECOSCORE, + COUNTRIES, + COUNTRIES_TAGS, + BRANDS, + PACKAGING, + LABELS_TAGS, + LABELS_HIERARCHY, + CITIES_TAGS, + QUANTITY, + INGREDIENTS_PALM_OIL_N, + LINK, + EMB_CODES_TAGS, + STATES_TAGS, + CREATOR, + CREATED_DATE_TIME, + LAST_MODIFIED_TIME, + LAST_MODIFIED_BY, + EDITORS_TAGS, + NOVA_GROUPS, + LANG, + PURCHASE_PLACES, + NUTRITION_DATA_PER, + NO_NUTRITION_DATA, + OTHER, + OTHER_INFORMATION, + CONSERVATION_CONDITIONS, + RECYCLING_INSTRUCTIONS_TO_DISCARD, + RECYCLING_INSTRUCTIONS_TO_RECYCLE, + WARNING, + CUSTOMER_SERVICE, + ENVIRONMENT_INFOCARD, + ENVIRONMENT_IMPACT_LEVEL_TAGS, + INGREDIENTS_ANALYSIS_TAGS, + INGREDIENTS, + STATES_TAGS ) val PRODUCT_LOCAL_FIELDS = setOf( - PRODUCT_NAME to true, - GENERIC_NAME to true, - INGREDIENTS_TEXT to true, - OTHER_INFORMATION to true, - CONSERVATION_CONDITIONS to true, - RECYCLING_INSTRUCTIONS_TO_DISCARD to true, - RECYCLING_INSTRUCTIONS_TO_RECYCLE to true, - WARNING to true, - ATTRIBUTE_GROUPS to false, - CUSTOMER_SERVICE to true, - IMAGE_FRONT_URL to true, - IMAGE_INGREDIENTS_URL to true, - IMAGE_NUTRITION_URL to true, - IMAGE_PACKAGING_URL to true + PRODUCT_NAME to true, + GENERIC_NAME to true, + INGREDIENTS_TEXT to true, + OTHER_INFORMATION to true, + CONSERVATION_CONDITIONS to true, + RECYCLING_INSTRUCTIONS_TO_DISCARD to true, + RECYCLING_INSTRUCTIONS_TO_RECYCLE to true, + WARNING to true, + ATTRIBUTE_GROUPS to false, + CUSTOMER_SERVICE to true, + IMAGE_FRONT_URL to true, + IMAGE_INGREDIENTS_URL to true, + IMAGE_NUTRITION_URL to true, + IMAGE_PACKAGING_URL to true ) val PRODUCT_IMAGES_FIELDS = setOf( - PRODUCT_NAME, GENERIC_NAME, BARCODE, LANG, IMAGE_SMALL_URL, IMAGES, - IMAGE_FRONT_URL, IMAGE_INGREDIENTS_URL, IMAGE_NUTRITION_URL, - IMAGE_PACKAGING_URL, IMAGE_URL, SELECTED_IMAGES + PRODUCT_NAME, GENERIC_NAME, BARCODE, LANG, IMAGE_SMALL_URL, IMAGES, + IMAGE_FRONT_URL, IMAGE_INGREDIENTS_URL, IMAGE_NUTRITION_URL, + IMAGE_PACKAGING_URL, IMAGE_URL, SELECTED_IMAGES ) val PRODUCT_SEARCH_FIELDS = setOf( - BRANDS, - PRODUCT_NAME, - IMAGE_SMALL_URL, - QUANTITY, - NUTRITION_GRADE_FR, - BARCODE, - ECOSCORE, - NOVA_GROUPS + BRANDS, + PRODUCT_NAME, + IMAGE_SMALL_URL, + QUANTITY, + NUTRITION_GRADE_FR, + BARCODE, + ECOSCORE, + NOVA_GROUPS ) } } \ No newline at end of file diff --git a/app/src/main/java/openfoodfacts/github/scrachx/openfood/repositories/ProductRepository.kt b/app/src/main/java/openfoodfacts/github/scrachx/openfood/repositories/ProductRepository.kt index f6a88d3445ba..b8662a234b7b 100644 --- a/app/src/main/java/openfoodfacts/github/scrachx/openfood/repositories/ProductRepository.kt +++ b/app/src/main/java/openfoodfacts/github/scrachx/openfood/repositories/ProductRepository.kt @@ -58,11 +58,11 @@ import javax.inject.Singleton */ @Singleton class ProductRepository @Inject constructor( - @ApplicationContext private val context: Context, - private val daoSession: DaoSession, - private val analysisDataApi: AnalysisDataAPI, - private val robotoffApi: RobotoffAPI, - private val taxonomiesManager: TaxonomiesManager + @ApplicationContext private val context: Context, + private val daoSession: DaoSession, + private val analysisDataApi: AnalysisDataAPI, + private val robotoffApi: RobotoffAPI, + private val taxonomiesManager: TaxonomiesManager ) { /** @@ -71,14 +71,14 @@ class ProductRepository @Inject constructor( * @return The list of Labels. */ fun reloadLabelsFromServer() = - taxonomiesManager.getTaxonomyData(Taxonomy.LABEL, true, daoSession.labelDao, this) + taxonomiesManager.getTaxonomyData(Taxonomy.LABEL, true, daoSession.labelDao, this) fun loadLabels(lastModifiedDate: Long) = analysisDataApi.getLabels() - .map { it.map() } - .doOnSuccess { labels -> - saveLabels(labels) - updateLastDownloadDateInSettings(Taxonomy.LABEL, lastModifiedDate) - } + .map { it.map() } + .doOnSuccess { labels -> + saveLabels(labels) + updateLastDownloadDateInSettings(Taxonomy.LABEL, lastModifiedDate) + } /** * Load tags from the server or local database @@ -86,32 +86,32 @@ class ProductRepository @Inject constructor( * @return The list of Tags. */ fun reloadTagsFromServer() = taxonomiesManager.getTaxonomyData( - Taxonomy.TAGS, - true, - daoSession.tagDao, - this + Taxonomy.TAGS, + true, + daoSession.tagDao, + this ) fun loadTags(lastModifiedDate: Long) = analysisDataApi.getTags() - .map { it.tags } - .doOnSuccess { - saveTags(it) - updateLastDownloadDateInSettings(Taxonomy.TAGS, lastModifiedDate) - } + .map { it.tags } + .doOnSuccess { + saveTags(it) + updateLastDownloadDateInSettings(Taxonomy.TAGS, lastModifiedDate) + } fun reloadInvalidBarcodesFromServer() = taxonomiesManager.getTaxonomyData( - Taxonomy.INVALID_BARCODES, - true, - daoSession.invalidBarcodeDao, - this + Taxonomy.INVALID_BARCODES, + true, + daoSession.invalidBarcodeDao, + this ) fun loadInvalidBarcodes(lastModifiedDate: Long) = analysisDataApi.getInvalidBarcodes() - .map { strings -> strings.map { InvalidBarcode(it) } } - .doOnSuccess { - saveInvalidBarcodes(it) - updateLastDownloadDateInSettings(Taxonomy.INVALID_BARCODES, lastModifiedDate) - } + .map { strings -> strings.map { InvalidBarcode(it) } } + .doOnSuccess { + saveInvalidBarcodes(it) + updateLastDownloadDateInSettings(Taxonomy.INVALID_BARCODES, lastModifiedDate) + } /** * Load allergens from the server or local database @@ -119,18 +119,18 @@ class ProductRepository @Inject constructor( * @return The allergens in the product. */ fun reloadAllergensFromServer(): Single> = - // FIXME: this returns 404 - taxonomiesManager.getTaxonomyData(Taxonomy.ALLERGEN, true, daoSession.allergenDao, this) + // FIXME: this returns 404 + taxonomiesManager.getTaxonomyData(Taxonomy.ALLERGEN, true, daoSession.allergenDao, this) fun getAllergens(): Single> = - taxonomiesManager.getTaxonomyData(Taxonomy.ALLERGEN, false, daoSession.allergenDao, this) + taxonomiesManager.getTaxonomyData(Taxonomy.ALLERGEN, false, daoSession.allergenDao, this) fun loadAllergens(lastModifiedDate: Long): Single> = analysisDataApi.getAllergens() - .map { it.map() } - .doOnSuccess { - saveAllergens(it) - updateLastDownloadDateInSettings(Taxonomy.ALLERGEN, lastModifiedDate) - } + .map { it.map() } + .doOnSuccess { + saveAllergens(it) + updateLastDownloadDateInSettings(Taxonomy.ALLERGEN, lastModifiedDate) + } /** * Load countries from the server or local database @@ -138,14 +138,14 @@ class ProductRepository @Inject constructor( * @return The list of countries. */ fun reloadCountriesFromServer(): Single> = - taxonomiesManager.getTaxonomyData(Taxonomy.COUNTRY, true, daoSession.countryDao, this) + taxonomiesManager.getTaxonomyData(Taxonomy.COUNTRY, true, daoSession.countryDao, this) fun loadCountries(lastModifiedDate: Long): Single> = analysisDataApi.getCountries() - .map { it.map() } - .doOnSuccess { - saveCountries(it) - updateLastDownloadDateInSettings(Taxonomy.COUNTRY, lastModifiedDate) - } + .map { it.map() } + .doOnSuccess { + saveCountries(it) + updateLastDownloadDateInSettings(Taxonomy.COUNTRY, lastModifiedDate) + } /** * Load categories from the server or local database @@ -153,16 +153,16 @@ class ProductRepository @Inject constructor( * @return The list of categories. */ fun reloadCategoriesFromServer() = - taxonomiesManager.getTaxonomyData(Taxonomy.CATEGORY, true, daoSession.categoryDao, this) + taxonomiesManager.getTaxonomyData(Taxonomy.CATEGORY, true, daoSession.categoryDao, this) fun getCategories() = taxonomiesManager.getTaxonomyData(Taxonomy.CATEGORY, false, daoSession.categoryDao, this) fun loadCategories(lastModifiedDate: Long) = analysisDataApi.getCategories() - .map { it.map() } - .doOnSuccess { - saveCategories(it) - updateLastDownloadDateInSettings(Taxonomy.CATEGORY, lastModifiedDate) - } + .map { it.map() } + .doOnSuccess { + saveCategories(it) + updateLastDownloadDateInSettings(Taxonomy.CATEGORY, lastModifiedDate) + } /** * Load allergens which user selected earlier (i.e user's allergens) @@ -170,9 +170,9 @@ class ProductRepository @Inject constructor( * @return The list of allergens. */ fun getEnabledAllergens(): List = - daoSession.allergenDao.queryBuilder() - .where(AllergenDao.Properties.Enabled.eq("true")) - .list() + daoSession.allergenDao.queryBuilder() + .where(AllergenDao.Properties.Enabled.eq("true")) + .list() /** * Load additives from the server or local database @@ -180,14 +180,14 @@ class ProductRepository @Inject constructor( * @return The list of additives. */ fun reloadAdditivesFromServer() = - taxonomiesManager.getTaxonomyData(Taxonomy.ADDITIVE, true, daoSession.additiveDao, this) + taxonomiesManager.getTaxonomyData(Taxonomy.ADDITIVE, true, daoSession.additiveDao, this) fun loadAdditives(lastModifiedDate: Long) = analysisDataApi.getAdditives() - .map { it.map() } - .doOnSuccess { - saveAdditives(it) - updateLastDownloadDateInSettings(Taxonomy.ADDITIVE, lastModifiedDate) - } + .map { it.map() } + .doOnSuccess { + saveAdditives(it) + updateLastDownloadDateInSettings(Taxonomy.ADDITIVE, lastModifiedDate) + } /** * TODO to be improved by loading only in the user language ? @@ -200,14 +200,14 @@ class ProductRepository @Inject constructor( * @return The ingredients in the product. */ fun reloadIngredientsFromServer(): Single> = - taxonomiesManager.getTaxonomyData(Taxonomy.INGREDIENT, true, daoSession.ingredientDao, this) + taxonomiesManager.getTaxonomyData(Taxonomy.INGREDIENT, true, daoSession.ingredientDao, this) fun loadIngredients(lastModifiedDate: Long): Single> = analysisDataApi.getIngredients() - .map { it.map() } - .doOnSuccess { - saveIngredients(it) - updateLastDownloadDateInSettings(Taxonomy.INGREDIENT, lastModifiedDate) - } + .map { it.map() } + .doOnSuccess { + saveIngredients(it) + updateLastDownloadDateInSettings(Taxonomy.INGREDIENT, lastModifiedDate) + } /** * Load states from the server or local database @@ -215,14 +215,14 @@ class ProductRepository @Inject constructor( * @return The list of states. */ fun reloadStatesFromServer(): Single> = - taxonomiesManager.getTaxonomyData(Taxonomy.STATES, true, daoSession.statesDao, this) + taxonomiesManager.getTaxonomyData(Taxonomy.STATES, true, daoSession.statesDao, this) fun loadStates(lastModifiedDate: Long): Single> = analysisDataApi.getStates() - .map { it.map() } - .doOnSuccess { - saveState(it) - updateLastDownloadDateInSettings(Taxonomy.STATES, lastModifiedDate) - } + .map { it.map() } + .doOnSuccess { + saveState(it) + updateLastDownloadDateInSettings(Taxonomy.STATES, lastModifiedDate) + } /** * Load stores from the server or local database @@ -230,24 +230,24 @@ class ProductRepository @Inject constructor( * @return The list of stores. */ fun reloadStoresFromServer(): Single> = - taxonomiesManager.getTaxonomyData(Taxonomy.STORES, true, daoSession.storeDao, this) + taxonomiesManager.getTaxonomyData(Taxonomy.STORES, true, daoSession.storeDao, this) fun loadStores(lastModifiedDate: Long): Single> = analysisDataApi.getStores() - .map { it.map() } - .doOnSuccess { - saveStores(it) - updateLastDownloadDateInSettings(Taxonomy.STORES, lastModifiedDate) - } + .map { it.map() } + .doOnSuccess { + saveStores(it) + updateLastDownloadDateInSettings(Taxonomy.STORES, lastModifiedDate) + } fun reloadBrandsFromServer(): Single> = - taxonomiesManager.getTaxonomyData(Taxonomy.BRANDS, true, daoSession.brandDao, this) + taxonomiesManager.getTaxonomyData(Taxonomy.BRANDS, true, daoSession.brandDao, this) fun loadBrands(lastModifiedDate: Long): Single> = analysisDataApi.getBrands() - .map { it.map() } - .doOnSuccess { - saveBrands(it) - updateLastDownloadDateInSettings(Taxonomy.BRANDS, lastModifiedDate) - } + .map { it.map() } + .doOnSuccess { + saveBrands(it) + updateLastDownloadDateInSettings(Taxonomy.BRANDS, lastModifiedDate) + } /** * This function set lastDownloadtaxonomy setting @@ -257,7 +257,7 @@ class ProductRepository @Inject constructor( */ private fun updateLastDownloadDateInSettings(taxonomy: Taxonomy, lastDownload: Long) { context.getSharedPreferences("prefs", 0) - .edit { putLong(taxonomy.lastDownloadTimeStampPreferenceId, lastDownload) } + .edit { putLong(taxonomy.lastDownloadTimeStampPreferenceId, lastDownload) } Log.i(LOG_TAG, "Set lastDownload of $taxonomy to $lastDownload") } @@ -404,10 +404,12 @@ class ProductRepository @Inject constructor( daoSession.ingredientNameDao.deleteAll() daoSession.ingredientsRelationDao.deleteAll() val daoSession = daoSession - daoSession.database.execSQL("""update sqlite_sequence set seq=0 where name in + daoSession.database.execSQL( + """update sqlite_sequence set seq=0 where name in |('${daoSession.ingredientDao.tablename}', |'${daoSession.ingredientNameDao.tablename}', - |'${daoSession.ingredientsRelationDao.tablename}')""".trimMargin()) + |'${daoSession.ingredientsRelationDao.tablename}')""".trimMargin() + ) } /** @@ -523,7 +525,7 @@ class ProductRepository @Inject constructor( */ fun setAllergenEnabled(allergenTag: String, isEnabled: Boolean) = Completable.fromCallable { daoSession.allergenDao.queryBuilder().where( - AllergenDao.Properties.Tag.eq(allergenTag) + AllergenDao.Properties.Tag.eq(allergenTag) ).unique()?.let { it.enabled = isEnabled daoSession.allergenDao.update(it) @@ -539,8 +541,8 @@ class ProductRepository @Inject constructor( */ fun getLabelByTagAndLanguageCode(labelTag: String?, languageCode: String?) = Single.fromCallable { daoSession.labelNameDao.queryBuilder().where( - LabelNameDao.Properties.LabelTag.eq(labelTag), - LabelNameDao.Properties.LanguageCode.eq(languageCode) + LabelNameDao.Properties.LabelTag.eq(labelTag), + LabelNameDao.Properties.LanguageCode.eq(languageCode) ).unique() ?: LabelName() } @@ -551,7 +553,7 @@ class ProductRepository @Inject constructor( * @return The translated label */ fun getLabelByTagAndDefaultLanguageCode(labelTag: String?) = - getLabelByTagAndLanguageCode(labelTag, ApiFields.Defaults.DEFAULT_LANGUAGE) + getLabelByTagAndLanguageCode(labelTag, ApiFields.Defaults.DEFAULT_LANGUAGE) /** * Loads translated additive from the local database by unique tag of additive and language code @@ -562,8 +564,8 @@ class ProductRepository @Inject constructor( */ fun getAdditiveByTagAndLanguageCode(additiveTag: String?, languageCode: String?) = Single.fromCallable { daoSession.additiveNameDao.queryBuilder().where( - AdditiveNameDao.Properties.AdditiveTag.eq(additiveTag), - AdditiveNameDao.Properties.LanguageCode.eq(languageCode) + AdditiveNameDao.Properties.AdditiveTag.eq(additiveTag), + AdditiveNameDao.Properties.LanguageCode.eq(languageCode) ).unique() ?: AdditiveName() } @@ -574,20 +576,20 @@ class ProductRepository @Inject constructor( * @return The translated additive tag */ fun getAdditiveByTagAndDefaultLanguageCode(additiveTag: String?) = - getAdditiveByTagAndLanguageCode(additiveTag, ApiFields.Defaults.DEFAULT_LANGUAGE) + getAdditiveByTagAndLanguageCode(additiveTag, ApiFields.Defaults.DEFAULT_LANGUAGE) fun getCountries() = taxonomiesManager.getTaxonomyData( - Taxonomy.COUNTRY, - false, - daoSession.countryDao, - this + Taxonomy.COUNTRY, + false, + daoSession.countryDao, + this ) fun getCountryByCC2OrWorld(cc2: String?) = getCountries().flatMapMaybe { countries -> countries.asSequence() - .filter { it.cc2.equals(cc2, ignoreCase = true) } - .firstOrNull() - .let { if (it == null) Maybe.empty() else Maybe.just(it) } + .filter { it.cc2.equals(cc2, ignoreCase = true) } + .firstOrNull() + .let { if (it == null) Maybe.empty() else Maybe.just(it) } } /** @@ -598,12 +600,12 @@ class ProductRepository @Inject constructor( * @return The translated category name */ fun getCategoryByTagAndLanguageCode( - categoryTag: String, - languageCode: String = ApiFields.Defaults.DEFAULT_LANGUAGE + categoryTag: String, + languageCode: String = ApiFields.Defaults.DEFAULT_LANGUAGE ) = Single.fromCallable { daoSession.categoryNameDao.queryBuilder().where( - CategoryNameDao.Properties.CategoryTag.eq(categoryTag), - CategoryNameDao.Properties.LanguageCode.eq(languageCode) + CategoryNameDao.Properties.CategoryTag.eq(categoryTag), + CategoryNameDao.Properties.LanguageCode.eq(languageCode) ).unique() ?: CategoryName().apply { this.name = categoryTag this.categoryTag = categoryTag @@ -619,9 +621,9 @@ class ProductRepository @Inject constructor( */ fun getAllCategoriesByLanguageCode(languageCode: String?) = Single.fromCallable { daoSession.categoryNameDao.queryBuilder() - .where(CategoryNameDao.Properties.LanguageCode.eq(languageCode)) - .orderAsc(CategoryNameDao.Properties.Name) - .list() + .where(CategoryNameDao.Properties.LanguageCode.eq(languageCode)) + .orderAsc(CategoryNameDao.Properties.Name) + .list() } /** @@ -635,16 +637,17 @@ class ProductRepository @Inject constructor( * Loads translated and selected/unselected allergens. * * @param isEnabled depends on whether allergen was selected or unselected by user - * @param languageCode is a 2-digit language code + * @param lc is a 2-digit language code * @return The list of allergen names */ - fun getAllergensByEnabledAndLanguageCode(isEnabled: Boolean?, languageCode: String?) = Single.fromCallable { - val allergens = daoSession.allergenDao.queryBuilder().where(AllergenDao.Properties.Enabled.eq(isEnabled)).list() - ?: return@fromCallable emptyList() + fun getAllergensByEnabledAndLanguageCode(isEnabled: Boolean, lc: String) = Single.fromCallable { + val allergens = daoSession.allergenDao.queryBuilder().where( + AllergenDao.Properties.Enabled.eq(isEnabled) + ).list() ?: emptyList() allergens.mapNotNull { daoSession.allergenNameDao.queryBuilder().where( - AllergenNameDao.Properties.AllergenTag.eq(it.tag), - AllergenNameDao.Properties.LanguageCode.eq(languageCode) + AllergenNameDao.Properties.AllergenTag.eq(it.tag), + AllergenNameDao.Properties.LanguageCode.eq(lc) ).unique() } }.subscribeOn(Schedulers.io()) @@ -657,8 +660,8 @@ class ProductRepository @Inject constructor( */ fun getAllergensByLanguageCode(languageCode: String?) = Single.fromCallable { daoSession.allergenNameDao.queryBuilder() - .where(AllergenNameDao.Properties.LanguageCode.eq(languageCode)) - .list() + .where(AllergenNameDao.Properties.LanguageCode.eq(languageCode)) + .list() } /** @@ -670,14 +673,16 @@ class ProductRepository @Inject constructor( */ fun getAllergenByTagAndLanguageCode(allergenTag: String?, languageCode: String?) = Single.fromCallable { daoSession.allergenNameDao.queryBuilder() - .where(AllergenNameDao.Properties.AllergenTag.eq(allergenTag), - AllergenNameDao.Properties.LanguageCode.eq(languageCode)) - .unique() - ?: AllergenName().apply { - this.name = allergenTag - this.allergenTag = allergenTag - this.isWikiDataIdPresent = false - } + .where( + AllergenNameDao.Properties.AllergenTag.eq(allergenTag), + AllergenNameDao.Properties.LanguageCode.eq(languageCode) + ) + .unique() + ?: AllergenName().apply { + this.name = allergenTag + this.allergenTag = allergenTag + this.isWikiDataIdPresent = false + } }.subscribeOn(Schedulers.io()) /** @@ -687,7 +692,7 @@ class ProductRepository @Inject constructor( * @return The translated allergen name */ fun getAllergenByTagAndDefaultLanguageCode(allergenTag: String?) = - getAllergenByTagAndLanguageCode(allergenTag, ApiFields.Defaults.DEFAULT_LANGUAGE) + getAllergenByTagAndLanguageCode(allergenTag, ApiFields.Defaults.DEFAULT_LANGUAGE) /** * Loads translated states from the local database by unique tag of states and language code @@ -698,10 +703,12 @@ class ProductRepository @Inject constructor( */ fun getStatesByTagAndLanguageCode(statesTag: String, languageCode: String?) = Single.fromCallable { daoSession.statesNameDao.queryBuilder() - .where(StatesNameDao.Properties.StatesTag.eq(statesTag), - StatesNameDao.Properties.LanguageCode.eq(languageCode)) - .unique() - ?: StatesName(statesTag, statesTag.split(":").component1(), statesTag.split(":").component2()) + .where( + StatesNameDao.Properties.StatesTag.eq(statesTag), + StatesNameDao.Properties.LanguageCode.eq(languageCode) + ) + .unique() + ?: StatesName(statesTag, statesTag.split(":").component1(), statesTag.split(":").component2()) }.subscribeOn(Schedulers.io()) @@ -713,8 +720,8 @@ class ProductRepository @Inject constructor( * @return The single question */ fun getProductQuestion(code: String, lang: String) = robotoffApi.getProductQuestions(code, lang, 1) - .map { it.questions } - .flatMapMaybe { if (it.isEmpty()) Maybe.empty() else Maybe.just(it[0]) } + .map { it.questions } + .flatMapMaybe { if (it.isEmpty()) Maybe.empty() else Maybe.just(it[0]) } /** * Annotate the Robotoff insight response using insight id and annotation @@ -741,14 +748,14 @@ class ProductRepository @Inject constructor( * @return The analysis tags in the product. */ fun reloadAnalysisTagsFromServer() = - taxonomiesManager.getTaxonomyData(Taxonomy.ANALYSIS_TAGS, true, daoSession.analysisTagDao, this) + taxonomiesManager.getTaxonomyData(Taxonomy.ANALYSIS_TAGS, true, daoSession.analysisTagDao, this) fun loadAnalysisTags(lastModifiedDate: Long) = analysisDataApi.getAnalysisTags() - .map { it.map() } - .doOnSuccess { - saveAnalysisTags(it) - updateLastDownloadDateInSettings(Taxonomy.ANALYSIS_TAGS, lastModifiedDate) - } + .map { it.map() } + .doOnSuccess { + saveAnalysisTags(it) + updateLastDownloadDateInSettings(Taxonomy.ANALYSIS_TAGS, lastModifiedDate) + } /** * AnalysisTags saving to local database @@ -776,14 +783,14 @@ class ProductRepository @Inject constructor( } fun reloadAnalysisTagConfigsFromServer(): Single> = - taxonomiesManager.getTaxonomyData(Taxonomy.ANALYSIS_TAG_CONFIG, true, daoSession.analysisTagConfigDao, this) + taxonomiesManager.getTaxonomyData(Taxonomy.ANALYSIS_TAG_CONFIG, true, daoSession.analysisTagConfigDao, this) fun loadAnalysisTagConfigs(lastModifiedDate: Long): Single> = analysisDataApi.getAnalysisTagConfigs() - .map { it.map() } - .doOnSuccess { - saveAnalysisTagConfigs(it) - updateLastDownloadDateInSettings(Taxonomy.ANALYSIS_TAG_CONFIG, lastModifiedDate) - } + .map { it.map() } + .doOnSuccess { + saveAnalysisTagConfigs(it) + updateLastDownloadDateInSettings(Taxonomy.ANALYSIS_TAG_CONFIG, lastModifiedDate) + } private fun saveAnalysisTagConfigs(analysisTagConfigs: List) { daoSession.database.beginTransaction() @@ -803,26 +810,30 @@ class ProductRepository @Inject constructor( private fun updateAnalysisTagConfig(analysisTagConfig: AnalysisTagConfig?, languageCode: String) { if (analysisTagConfig != null) { var analysisTagName = daoSession.analysisTagNameDao.queryBuilder().where( - AnalysisTagNameDao.Properties.AnalysisTag.eq(analysisTagConfig.analysisTag), - AnalysisTagNameDao.Properties.LanguageCode.eq(languageCode) + AnalysisTagNameDao.Properties.AnalysisTag.eq(analysisTagConfig.analysisTag), + AnalysisTagNameDao.Properties.LanguageCode.eq(languageCode) ).unique() if (analysisTagName == null) { analysisTagName = daoSession.analysisTagNameDao.queryBuilder().where( - AnalysisTagNameDao.Properties.AnalysisTag.eq(analysisTagConfig.analysisTag), - AnalysisTagNameDao.Properties.LanguageCode.eq(ApiFields.Defaults.DEFAULT_LANGUAGE) + AnalysisTagNameDao.Properties.AnalysisTag.eq(analysisTagConfig.analysisTag), + AnalysisTagNameDao.Properties.LanguageCode.eq(ApiFields.Defaults.DEFAULT_LANGUAGE) ).unique() } analysisTagConfig.name = analysisTagName val type = "en:${analysisTagConfig.type}" var analysisTagTypeName = daoSession.analysisTagNameDao.queryBuilder() - .where(AnalysisTagNameDao.Properties.AnalysisTag.eq(type), - AnalysisTagNameDao.Properties.LanguageCode.eq(languageCode)) - .unique() + .where( + AnalysisTagNameDao.Properties.AnalysisTag.eq(type), + AnalysisTagNameDao.Properties.LanguageCode.eq(languageCode) + ) + .unique() if (analysisTagTypeName == null) { analysisTagTypeName = daoSession.analysisTagNameDao.queryBuilder() - .where(AnalysisTagNameDao.Properties.AnalysisTag.eq(type), - AnalysisTagNameDao.Properties.LanguageCode.eq(ApiFields.Defaults.DEFAULT_LANGUAGE)) - .unique() + .where( + AnalysisTagNameDao.Properties.AnalysisTag.eq(type), + AnalysisTagNameDao.Properties.LanguageCode.eq(ApiFields.Defaults.DEFAULT_LANGUAGE) + ) + .unique() } analysisTagConfig.typeName = if (analysisTagTypeName != null) analysisTagTypeName.name else analysisTagConfig.type } @@ -835,14 +846,14 @@ class ProductRepository @Inject constructor( */ fun getAnalysisTagConfigByTagAndLanguageCode(analysisTag: String?, languageCode: String) = Maybe.fromCallable { daoSession.analysisTagConfigDao.queryBuilder() - .where(AnalysisTagConfigDao.Properties.AnalysisTag.eq(analysisTag)) - .unique().also { updateAnalysisTagConfig(it, languageCode) } + .where(AnalysisTagConfigDao.Properties.AnalysisTag.eq(analysisTag)) + .unique().also { updateAnalysisTagConfig(it, languageCode) } }.subscribeOn(Schedulers.io()) fun getUnknownAnalysisTagConfigsByLanguageCode(languageCode: String) = Single.fromCallable { daoSession.analysisTagConfigDao.queryBuilder() - .where(StringCondition("""${AnalysisTagConfigDao.Properties.AnalysisTag.columnName} LIKE "%unknown%"""")) - .list().onEach { updateAnalysisTagConfig(it, languageCode) } + .where(StringCondition("""${AnalysisTagConfigDao.Properties.AnalysisTag.columnName} LIKE "%unknown%"""")) + .list().onEach { updateAnalysisTagConfig(it, languageCode) } }.subscribeOn(Schedulers.io())