/
Utils.kt
377 lines (342 loc) 路 14.2 KB
/
Utils.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
/*
* 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.utils
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.ClickableSpan
import android.text.style.StyleSpan
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.annotation.DrawableRes
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import androidx.core.text.inSpans
import androidx.core.view.children
import androidx.work.*
import com.afollestad.materialdialogs.MaterialDialog
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import openfoodfacts.github.scrachx.openfood.BuildConfig
import openfoodfacts.github.scrachx.openfood.R
import openfoodfacts.github.scrachx.openfood.features.scan.ContinuousScanActivity
import openfoodfacts.github.scrachx.openfood.features.search.ProductSearchActivity.Companion.start
import openfoodfacts.github.scrachx.openfood.jobs.ImagesUploaderWorker
import openfoodfacts.github.scrachx.openfood.network.ApiFields
import org.apache.commons.validator.routines.checkdigit.EAN13CheckDigit
import java.io.*
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.*
import java.util.concurrent.TimeUnit
private const val LOG_TAG_COMPRESS = "COMPRESS_IMAGE"
object Utils {
private const val UPLOAD_JOB_TAG = "upload_saved_product_job"
private var isUploadJobInitialised = false
const val HEADER_USER_AGENT_SCAN = "Scan"
const val HEADER_USER_AGENT_SEARCH = "Search"
const val NO_DRAWABLE_RESOURCE = 0
const val FORCE_REFRESH_TAXONOMIES = "force_refresh_taxonomies"
fun hideKeyboard(activity: Activity) {
val view = activity.currentFocus ?: return
(activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
.hideSoftInputFromWindow(view.windowToken, 0)
}
@JvmStatic
fun compressImage(fileUrl: String): String? {
val decodedBitmap = decodeFile(File(fileUrl))
if (decodedBitmap == null) {
Log.e(LOG_TAG_COMPRESS, "$fileUrl not found")
return null
}
val smallFileFront = File(fileUrl.replace(".png", "_small.png"))
try {
FileOutputStream(smallFileFront).use { stream -> decodedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream) }
} catch (e: IOException) {
Log.e(LOG_TAG_COMPRESS, e.message, e)
}
return smallFileFront.toString()
}
/**
* Check if a certain application is installed on a device.
*
* @param context the applications context.
* @param packageName the package name that you want to check.
* @return true if the application is installed, false otherwise.
*/
fun isApplicationInstalled(context: Context, packageName: String) = try {
// Check if the package name exists, if exception is thrown, package name does not
// exist.
context.packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES)
true
} catch (e: PackageManager.NameNotFoundException) {
false
}
/**
* Returns the NOVA group explanation given the group
*/
fun getNovaGroupExplanation(novaGroup: String, context: Context) = when (novaGroup) {
"1" -> context.resources.getString(R.string.nova_grp1_msg)
"2" -> context.resources.getString(R.string.nova_grp2_msg)
"3" -> context.resources.getString(R.string.nova_grp3_msg)
"4" -> context.resources.getString(R.string.nova_grp4_msg)
else -> null
}
fun Context.getBitmapFromDrawable(@DrawableRes drawableId: Int): Bitmap? {
val drawable = AppCompatResources.getDrawable(this, drawableId) ?: return null
val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return bitmap
}
/**
* Return a round float value **with 2 decimals**
*
* **BE CAREFUL:** THE METHOD DOESN'T CHECK THE NUMBER AS A NUMBER.
*
* @param value float value
* @return round value **with 2 decimals** or 0 if the value is empty or equals to 0
*/
fun getRoundNumber(value: CharSequence, locale: Locale = Locale.getDefault()) = when {
value.isEmpty() -> "?"
value == "0" -> value
else -> value.toString().toDoubleOrNull()
?.let { DecimalFormat("##.##", DecimalFormatSymbols(locale)).format(it) }
?: "?"
}
/**
* @see Utils.getRoundNumber
*/
fun getRoundNumber(value: Float, locale: Locale = Locale.getDefault()) = getRoundNumber(value.toString(), locale)
fun getRoundNumber(value: Double, locale: Locale = Locale.getDefault()) = getRoundNumber(value.toString(), locale)
/**
* Schedules job to download when network is available
*/
@Synchronized
fun scheduleProductUploadJob(context: Context) {
if (isUploadJobInitialised) return
val periodicity = TimeUnit.MINUTES.toSeconds(30).toInt()
val uploadWorkRequest = OneTimeWorkRequest.Builder(ImagesUploaderWorker::class.java)
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.UNMETERED).build())
.setInitialDelay(periodicity.toLong(), TimeUnit.SECONDS).build()
WorkManager.getInstance(context).enqueueUniqueWork(UPLOAD_JOB_TAG, ExistingWorkPolicy.KEEP, uploadWorkRequest)
isUploadJobInitialised = true
}
/**
* Check if the user is connected to a network. This can be any network.
*
* @param context of the application.
* @return true if connected or connecting. False otherwise.
*/
@Suppress("DEPRECATION")
fun isNetworkConnected(context: Context): Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val capability = cm.getNetworkCapabilities(cm.activeNetwork)
capability?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) ?: false
} else {
cm.activeNetworkInfo?.isConnectedOrConnecting ?: false
}
}
fun makeOrGetPictureDirectory(context: Context): File {
// determine the profile directory
var dir = context.filesDir
if (isExternalStorageWritable()) {
dir = context.getExternalFilesDir(null)
}
val picDir = File(dir, "Pictures")
if (picDir.exists()) {
return picDir
}
// creates the directory if not present yet
val mkdir = picDir.mkdirs()
if (!mkdir) {
Log.e(Utils::class.simpleName, "Can create dir $picDir")
}
return picDir
}
fun isExternalStorageWritable() = Environment.MEDIA_MOUNTED == Environment.getExternalStorageState()
fun getOutputPicUri(context: Context): Uri =
File(makeOrGetPictureDirectory(context), "${System.currentTimeMillis()}.jpg").toUri()
/**
* Function to open ContinuousScanActivity to facilitate scanning
*
* @param activity
*/
fun scan(activity: Activity) {
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)) {
MaterialAlertDialogBuilder(activity)
.setTitle(R.string.action_about)
.setMessage(R.string.permission_camera)
.setPositiveButton(android.R.string.ok) { d, _ ->
ActivityCompat.requestPermissions(
activity, arrayOf(Manifest.permission.CAMERA),
MY_PERMISSIONS_REQUEST_CAMERA
)
d.dismiss()
}
.setNegativeButton(android.R.string.cancel) { d, _ -> d.dismiss() }
.show()
} else {
ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.CAMERA), MY_PERMISSIONS_REQUEST_CAMERA)
}
} else {
activity.startActivity(Intent(activity, ContinuousScanActivity::class.java))
}
}
@JvmStatic
fun firstNotEmpty(vararg args: String?) = args.firstOrNull { it != null && it.isNotEmpty() }
}
fun isAllGranted(grantResults: IntArray) =
grantResults.isNotEmpty() && grantResults.none { it != PERMISSION_GRANTED }
fun buildSignInDialog(activity: Activity): MaterialDialog.Builder = MaterialDialog.Builder(activity)
.title(R.string.sign_in_to_edit)
.positiveText(R.string.txtSignIn)
.negativeText(R.string.dialog_cancel)
/**
* @param type Type of call (Search or Scan)
* @return Returns the header to be put in network call
*/
fun getUserAgent(type: String) = "${getUserAgent()} $type"
fun getUserAgent() = "${BuildConfig.APP_NAME} Official Android App ${BuildConfig.VERSION_NAME}"
/**
* Decodes image and scales it to reduce memory consumption
*/
private fun decodeFile(f: File): Bitmap? {
try {
// Decode image size
val o = BitmapFactory.Options()
o.inJustDecodeBounds = true
BitmapFactory.decodeStream(FileInputStream(f), null, o)
// The new size we want to scale to
// Find the correct scale value. It should be the power of 2.
var scale = 1
while (o.outWidth / scale / 2 >= REQUIRED_SIZE &&
o.outHeight / scale / 2 >= REQUIRED_SIZE
) {
scale *= 2
}
// Decode with inSampleSize
val o2 = BitmapFactory.Options().apply {
inSampleSize = scale
}
return BitmapFactory.decodeStream(FileInputStream(f), null, o2)
} catch (e: FileNotFoundException) {
Log.e(LOG_TAG, "Error while decoding file $f", e)
}
return null
}
private const val REQUIRED_SIZE = 1200
const val SPACE = " "
const val MY_PERMISSIONS_REQUEST_CAMERA = 1
const val MY_PERMISSIONS_REQUEST_STORAGE = 2
/**
* Returns a CharSequence that concatenates the specified array of CharSequence
* objects and then applies a list of zero or more tags to the entire range.
*
* @param content an array of character sequences to apply a style to
* @param styles the styled span objects to apply to the content
* such as android.text.style.StyleSpan
*/
private fun apply(content: Array<out CharSequence>, vararg styles: StyleSpan) = SpannableStringBuilder().let {
openStyles(it, styles)
content.forEach { item -> it.append(item) }
closeStyles(it, styles)
it.toString()
}
/**
* Iterates over an array of tags and applies them to the beginning of the specified
* Spannable object so that future text appended to the text will have the styling
* applied to it. Do not call this method directly.
*/
private fun openStyles(text: Spannable, tags: Array<out StyleSpan>) {
tags.forEach { text.setSpan(it, 0, 0, Spanned.SPAN_MARK_MARK) }
}
/**
* "Closes" the specified tags on a Spannable by updating the spans to be
* endpoint-exclusive so that future text appended to the end will not take
* on the same styling. Do not call this method directly.
*/
private fun closeStyles(text: Spannable, tags: Array<out StyleSpan>) {
tags.forEach {
if (text.isNotEmpty()) {
text.setSpan(it, 0, text.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
} else {
text.removeSpan(it)
}
}
}
fun getModifierNonDefault(modifier: String) = if (modifier != DEFAULT_MODIFIER) modifier else ""
private val LOG_TAG = Utils::class.simpleName!!
fun <T : View?> ViewGroup.getViewsByType(typeClass: Class<T>): List<T> {
val result = mutableListOf<T>()
children.forEach { view ->
if (view is ViewGroup) {
result += view.getViewsByType(typeClass)
}
if (typeClass.isInstance(view)) {
result += typeClass.cast(view)
}
}
return result
}
/**
* @param barcode
* @return true if valid according to [EAN13CheckDigit.EAN13_CHECK_DIGIT]
* and if the barcode doesn't start will 977/978/979 (Book barcode)
*/
fun isBarcodeValid(barcode: String?): Boolean {
// For debug only: the barcode '1' is used for test:
if (ApiFields.Defaults.DEBUG_BARCODE == barcode) return true
return barcode != null
&& EAN13CheckDigit.EAN13_CHECK_DIGIT.isValid(barcode)
&& barcode.length > 3
&& (!barcode.substring(0, 3).contains("977")
|| !barcode.substring(0, 3).contains("978")
|| !barcode.substring(0, 3).contains("979"))
}
/**
* Check if the device has a camera installed.
*
* @return true if installed, false otherwise.
*/
fun isHardwareCameraInstalled(context: Context) = context.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)
fun getSearchLinkText(
text: String,
type: SearchType,
activityToStart: Activity
): CharSequence = SpannableStringBuilder().inSpans(object : ClickableSpan() {
override fun onClick(view: View) = start(activityToStart, type, text)
}) { append(text) }