/
EditIngredientsFragment.kt
497 lines (426 loc) 路 19 KB
/
EditIngredientsFragment.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
/*
* Copyright 2016-2020 Open Food Facts
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package openfoodfacts.github.scrachx.openfood.features.product.edit.ingredients
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.core.net.toFile
import androidx.core.widget.doAfterTextChanged
import androidx.fragment.app.viewModels
import com.hootsuite.nachos.terminator.ChipTerminatorHandler
import com.hootsuite.nachos.validator.ChipifyingNachoValidator
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import dagger.hilt.android.AndroidEntryPoint
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.rxkotlin.addTo
import openfoodfacts.github.scrachx.openfood.R
import openfoodfacts.github.scrachx.openfood.analytics.AnalyticsEvent
import openfoodfacts.github.scrachx.openfood.analytics.AnalyticsView
import openfoodfacts.github.scrachx.openfood.analytics.MatomoAnalytics
import openfoodfacts.github.scrachx.openfood.databinding.FragmentAddProductIngredientsBinding
import openfoodfacts.github.scrachx.openfood.features.product.edit.ProductEditActivity
import openfoodfacts.github.scrachx.openfood.features.product.edit.ProductEditActivity.Companion.KEY_PERFORM_OCR
import openfoodfacts.github.scrachx.openfood.features.product.edit.ProductEditActivity.Companion.KEY_SEND_UPDATED
import openfoodfacts.github.scrachx.openfood.features.product.edit.ProductEditFragment
import openfoodfacts.github.scrachx.openfood.images.ProductImage
import openfoodfacts.github.scrachx.openfood.models.DaoSession
import openfoodfacts.github.scrachx.openfood.models.Product
import openfoodfacts.github.scrachx.openfood.models.ProductImageField
import openfoodfacts.github.scrachx.openfood.models.entities.OfflineSavedProduct
import openfoodfacts.github.scrachx.openfood.models.entities.allergen.AllergenNameDao
import openfoodfacts.github.scrachx.openfood.network.ApiFields
import openfoodfacts.github.scrachx.openfood.network.ApiFields.Keys.lcIngredientsKey
import openfoodfacts.github.scrachx.openfood.network.OpenFoodAPIClient
import openfoodfacts.github.scrachx.openfood.utils.*
import openfoodfacts.github.scrachx.openfood.utils.FileDownloader.download
import java.io.File
import javax.inject.Inject
/**
* Fragment for Add Product Ingredients
*
* @see R.layout.fragment_add_product_ingredients
*/
@AndroidEntryPoint
class EditIngredientsFragment : ProductEditFragment() {
private var _binding: FragmentAddProductIngredientsBinding? = null
private val binding get() = _binding!!
private val viewModel: EditIngredientsViewModel by viewModels()
@Inject
lateinit var daoSession: DaoSession
@Inject
lateinit var picasso: Picasso
@Inject
lateinit var client: OpenFoodAPIClient
@Inject
lateinit var matomoAnalytics: MatomoAnalytics
@Inject
lateinit var sharedPreferences: SharedPreferences
@Inject
lateinit var localeManager: LocaleManager
private val photoReceiverHandler by lazy {
PhotoReceiverHandler(sharedPreferences) {
val uri = it.toURI()
imagePath = uri.path
newImageSelected = true
photoFile = it
val image = ProductImage(code!!, ProductImageField.INGREDIENTS, it, localeManager.getLanguage()).apply {
filePath = uri.path
}
(activity as? ProductEditActivity)?.addToPhotoMap(image, 1)
matomoAnalytics.trackEvent(AnalyticsEvent.ProductIngredientsPictureEdited(code))
hideImageProgress(false, getString(R.string.image_uploaded_successfully))
}
}
private var photoFile: File? = null
private var code: String? = null
private var mOfflineSavedProduct: OfflineSavedProduct? = null
private var productDetails = mutableMapOf<String, String?>()
private var imagePath: String? = null
private var product: Product? = null
private var newImageSelected = false
override fun allValid() = true
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentAddProductIngredientsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val intent = if (activity == null) null else requireActivity().intent
if (intent != null
&& intent.getBooleanExtra(ProductEditActivity.KEY_MODIFY_NUTRITION_PROMPT, false)
&& !intent.getBooleanExtra(ProductEditActivity.KEY_MODIFY_CATEGORY_PROMPT, false)
) {
(activity as ProductEditActivity).proceed()
}
binding.btnAddImageIngredients.setOnClickListener { addIngredientsImage() }
binding.btnEditImageIngredients.setOnClickListener { editIngredientsImage() }
binding.btnNext.setOnClickListener { next() }
binding.btnLooksGood.setOnClickListener { verifyIngredients() }
binding.btnSkipIngredients.setOnClickListener { skipIngredients() }
binding.btnExtractIngredients.setOnClickListener { extractIngredients() }
binding.ingredientsList.doAfterTextChanged { toggleOCRButtonVisibility() }
val bundle = arguments
if (bundle == null) {
Toast.makeText(activity, R.string.error_adding_ingredients, Toast.LENGTH_SHORT).show()
requireActivity().finish()
return
}
product = getProductFromArgs()
mOfflineSavedProduct = getEditOfflineProductFromArgs()
if (product != null) {
code = product!!.code
}
if (isEditingFromArgs && product != null) {
code = product!!.code
preFillProductValues()
} else if (mOfflineSavedProduct != null) {
code = mOfflineSavedProduct!!.barcode
preFillValuesForOffline()
} else {
// Fast addition
val enabled = requireContext().isFastAdditionMode()
enableFastAdditionMode(enabled)
}
if (bundle.getBoolean(KEY_PERFORM_OCR)) extractIngredients()
if (bundle.getBoolean(KEY_SEND_UPDATED)) editIngredientsImage()
val ingredientsImg = getImageIngredients()
if (binding.ingredientsList.isEmpty() && !ingredientsImg.isNullOrEmpty()) {
binding.btnExtractIngredients.visibility = View.VISIBLE
imagePath = ingredientsImg
} else if (isEditingFromArgs
&& binding.ingredientsList.isEmpty()
&& !product!!.imageIngredientsUrl.isNullOrEmpty()
) {
binding.btnExtractIngredients.visibility = View.VISIBLE
}
viewModel.allergens.observe(viewLifecycleOwner) { loadAutoSuggestions(it) }
if (activity is ProductEditActivity && (activity as ProductEditActivity).initialValues != null) {
getAllDetails((activity as ProductEditActivity).initialValues!!)
}
}
override fun onResume() {
super.onResume()
matomoAnalytics.trackView(AnalyticsView.ProductEditIngredients)
}
private fun getImageIngredients() = productDetails[ApiFields.Keys.IMAGE_INGREDIENTS]
private fun getAddProductActivity() = activity as ProductEditActivity?
private fun extractTracesChipValues(product: Product?): List<String> =
product?.tracesTags?.map { getTracesName(localeManager.getLanguage(), it) } ?: emptyList()
/**
* Pre fill the fields of the product which are already present on the server.
*/
private fun preFillProductValues() {
loadIngredientsImage()
if (!product!!.ingredientsText.isNullOrEmpty()) {
binding.ingredientsList.setText(product!!.ingredientsText)
}
if (product!!.tracesTags.isNotEmpty()) {
val chipValues = extractTracesChipValues(product)
binding.traces.setText(chipValues)
}
}
/**
* Load ingredients image on the image view
*/
fun loadIngredientsImage() {
if (getAddProductActivity() == null) return
val newImageIngredientsUrl = product!!.getImageIngredientsUrl(getAddProductActivity()!!.getProductLanguageForEdition())
photoFile = null
if (newImageIngredientsUrl != null && newImageIngredientsUrl.isNotEmpty()) {
binding.imageProgress.visibility = View.VISIBLE
imagePath = newImageIngredientsUrl
picasso
.load(newImageIngredientsUrl)
.resize(dps50ToPixels, dps50ToPixels)
.centerInside()
.into(binding.btnAddImageIngredients, object : Callback {
override fun onSuccess() = imageLoaded()
override fun onError(ex: Exception) = imageLoaded()
})
}
}
/**
* Set visibility parameters when image is loaded
*/
private fun imageLoaded() {
binding.btnEditImageIngredients.visibility = View.VISIBLE
binding.imageProgress.visibility = View.GONE
}
/**
* returns alergen name from tag
*
* @param languageCode language in which additive name and tag are written
* @param tag Tag associated with the allergen
*/
private fun getTracesName(languageCode: String, tag: String): String {
return daoSession.allergenNameDao!!.queryBuilder()
.where(AllergenNameDao.Properties.AllergenTag.eq(tag), AllergenNameDao.Properties.LanguageCode.eq(languageCode))
.unique()?.name ?: tag
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
/**
* To enable fast addition mode
*/
private fun enableFastAdditionMode(isEnabled: Boolean) {
if (isEnabled) {
binding.traces.visibility = View.GONE
binding.sectionTraces.visibility = View.GONE
binding.hintTraces.visibility = View.GONE
binding.greyLine2.visibility = View.GONE
} else {
binding.traces.visibility = View.VISIBLE
binding.sectionTraces.visibility = View.VISIBLE
binding.hintTraces.visibility = View.VISIBLE
binding.greyLine2.visibility = View.VISIBLE
}
}
/**
* Pre fill the fields if the product is already present in SavedProductOffline db.
*/
private fun preFillValuesForOffline() {
val prod = mOfflineSavedProduct!!
productDetails = prod.productDetails.toMutableMap()
getImageIngredients()?.let {
binding.imageProgress.visibility = View.VISIBLE
picasso
.load(LOCALE_FILE_SCHEME + it)
.resize(dps50ToPixels, dps50ToPixels)
.centerInside()
.into(binding.btnAddImageIngredients, object : Callback {
override fun onSuccess() {
binding.imageProgress.visibility = View.GONE
}
override fun onError(ex: Exception) {
binding.imageProgress.visibility = View.GONE
}
})
}
prod.ingredients.let {
if (!it.isNullOrEmpty()) binding.ingredientsList.setText(it)
}
productDetails[ApiFields.Keys.ADD_TRACES]?.let {
val chipValues = it.split(Regex("\\s*,\\s*"))
binding.traces.setText(chipValues)
}
}
/**
* Automatically load suggestions for allergen names
*/
private fun loadAutoSuggestions(allergens: List<String>) {
val adapter = ArrayAdapter(requireActivity(), android.R.layout.simple_dropdown_item_1line, allergens)
binding.traces.addChipTerminator(',', ChipTerminatorHandler.BEHAVIOR_CHIPIFY_CURRENT_TOKEN)
binding.traces.setNachoValidator(ChipifyingNachoValidator())
binding.traces.enableEditChipOnTouch(false, true)
binding.traces.setAdapter(adapter)
}
override fun doOnPhotosPermissionGranted() = editIngredientsImage()
private fun addIngredientsImage() {
when {
imagePath == null -> editIngredientsImage()
photoFile != null -> cropRotateImage(photoFile!!, getString(R.string.ingredients_picture))
else -> {
download(requireContext(), imagePath!!, client)
.observeOn(AndroidSchedulers.mainThread())
.subscribe { uri ->
photoFile = uri.toFile()
cropRotateImage(uri, getString(R.string.ingredients_picture))
}.addTo(disp)
}
}
}
private fun editIngredientsImage() = doChooseOrTakePhotos()
private fun verifyIngredients() {
binding.ingredientsListVerified.visibility = View.VISIBLE
binding.traces.requestFocus()
binding.btnLooksGood.visibility = View.GONE
binding.btnSkipIngredients.visibility = View.GONE
}
private fun extractIngredients() {
(activity as? ProductEditActivity)?.let { activity ->
imagePath?.let { imagePath ->
if (!isEditingFromArgs || newImageSelected) {
photoFile = File(imagePath)
val image = ProductImage(code!!, ProductImageField.INGREDIENTS, photoFile!!, localeManager.getLanguage())
image.filePath = imagePath
activity.addToPhotoMap(image, 1)
} else {
activity.performOCR(
code!!,
"ingredients_" + activity.getProductLanguageForEdition()
)
}
}
}
}
private fun skipIngredients() {
binding.ingredientsList.text = null
binding.btnSkipIngredients.visibility = View.GONE
binding.btnLooksGood.visibility = View.GONE
}
private fun toggleOCRButtonVisibility() {
if (binding.ingredientsList.isEmpty()) {
binding.btnExtractIngredients.visibility = View.VISIBLE
} else {
binding.btnExtractIngredients.visibility = View.GONE
}
}
/**
* adds all the fields to the query map even those which are null or empty.
*/
private fun getAllDetails(targetMap: MutableMap<String, String?>) {
binding.traces.chipifyAllUnterminatedTokens()
(activity as? ProductEditActivity)?.let { activity ->
val lc = activity.getProductLanguageForEdition()
?.takeUnless { it.isEmpty() } ?: ApiFields.Defaults.DEFAULT_LANGUAGE
targetMap[lcIngredientsKey(lc)] = binding.ingredientsList.text.toString()
val string = binding.traces.chipValues.joinToString(",")
targetMap[ApiFields.Keys.ADD_TRACES.substring(4)] = string
}
}
/**
* adds only those fields to the query map which are not empty and have changed.
*/
override fun addUpdatedFieldsToMap(targetMap: MutableMap<String, String?>) {
binding.traces.chipifyAllUnterminatedTokens()
if (activity !is ProductEditActivity) return
binding.ingredientsList
.takeIf { it.isContentDifferent(product?.ingredientsText) }
?.let {
val languageCode = (activity as ProductEditActivity).getProductLanguageForEdition()
val lc = if (!languageCode.isNullOrEmpty()) languageCode else ApiFields.Defaults.DEFAULT_LANGUAGE
targetMap[lcIngredientsKey(lc)] = it.getContent()
}
binding.traces
.takeIf { it.isNotEmpty() && it.areChipsDifferent(extractTracesChipValues(product)) }
?.let {
targetMap[ApiFields.Keys.ADD_TRACES] = it.chipValues.joinToString(",")
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
photoReceiverHandler.onActivityResult(this, requestCode, resultCode, data)
}
/**
* Displays progress bar and hides other views util image is still loading
*/
override fun showImageProgress() {
binding.imageProgress.visibility = View.VISIBLE
binding.imageProgressText.visibility = View.VISIBLE
binding.imageProgressText.setText(R.string.toastSending)
binding.btnAddImageIngredients.visibility = View.INVISIBLE
binding.btnEditImageIngredients.visibility = View.INVISIBLE
}
/**
* After image is loaded hide image progress
*
* @param errorInUploading boolean variable is true, if there is an error while showing image
* @param message error message in case of failure to display image
*/
override fun hideImageProgress(errorInUploading: Boolean, message: String) {
binding.imageProgress.visibility = View.INVISIBLE
binding.imageProgressText.visibility = View.GONE
binding.btnAddImageIngredients.visibility = View.VISIBLE
binding.btnEditImageIngredients.visibility = View.VISIBLE
if (!errorInUploading) {
picasso
.load(photoFile!!)
.resize(dps50ToPixels, dps50ToPixels)
.centerInside()
.into(binding.btnAddImageIngredients)
}
}
/**
* Display the list of ingredients based on the result from ocr of IngredientsList photo
*
* @param status status of ocr, in case of proper OCR it returns "set" or "0"
* @param ocrResult resultant string obtained after OCR of image
*/
fun setIngredients(status: String?, ocrResult: String?) {
if (activity == null || requireActivity().isFinishing) return
when (status) {
"set" -> {
binding.ingredientsList.setText(ocrResult)
loadIngredientsImage()
}
"0" -> {
binding.ingredientsList.setText(ocrResult)
binding.btnLooksGood.visibility = View.VISIBLE
binding.btnSkipIngredients.visibility = View.VISIBLE
}
else -> Toast.makeText(activity, R.string.unable_to_extract_ingredients, Toast.LENGTH_SHORT).show()
}
}
fun showOCRProgress() {
binding.btnExtractIngredients.visibility = View.GONE
binding.ingredientsList.text = null
binding.ocrProgress.visibility = View.VISIBLE
binding.ocrProgressText.visibility = View.VISIBLE
}
fun hideOCRProgress() {
binding.ocrProgress.visibility = View.GONE
binding.ocrProgressText.visibility = View.GONE
}
private val dps50ToPixels by lazy { requireContext().dpsToPixel(50) }
}