Skip to content

Commit

Permalink
feat: export DB (#4719)
Browse files Browse the repository at this point in the history
  • Loading branch information
g123k committed May 16, 2022
1 parent 843de4a commit 694b56f
Show file tree
Hide file tree
Showing 7 changed files with 120 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,14 @@ class PreferencesFragment : PreferenceFragmentCompat(), INavigationItem {

}

requirePreference<Preference>(getString(R.string.pref_export_db_key)) {

setOnPreferenceClickListener {
OFFDatabaseHelper.exportDB(requireContext())
true
}

}

requirePreference<ListPreference>(getString(R.string.pref_country_key)) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,7 @@ class AppModule {
fun provideDaoSession(@ApplicationContext context: Context): DaoSession {
// Use only during development: DaoMaster.DevOpenHelper (Drops all table on Upgrade!)
// Use only during production: OFFDatabaseHelper (see on Upgrade!)
val dbName = when (BuildConfig.FLAVOR) {
AppFlavors.OPFF -> "open_pet_food_facts"
AppFlavors.OBF -> "open_beauty_facts"
AppFlavors.OPF -> "open_products_facts"
AppFlavors.OFF -> "open_food_facts"
else -> "open_food_facts"
}
return DaoMaster(OFFDatabaseHelper(context, dbName).writableDb).newSession()
return DaoMaster(OFFDatabaseHelper(context).writableDb).newSession()
}

@Provides
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
package openfoodfacts.github.scrachx.openfood.utils

import androidx.core.content.FileProvider
import openfoodfacts.github.scrachx.openfood.BuildConfig

/**
* Created by prajwalm on 05/04/18.
*/
class GenericFileProvider : FileProvider()
class GenericFileProvider : FileProvider() {

companion object {

const val AUTHORITY = "${BuildConfig.APPLICATION_ID}.provider"

}


}
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
package openfoodfacts.github.scrachx.openfood.utils

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.database.sqlite.SQLiteDatabase.CursorFactory
import android.net.Uri
import android.util.Log
import androidx.core.app.ShareCompat
import androidx.core.content.FileProvider
import androidx.core.content.edit
import openfoodfacts.github.scrachx.openfood.AppFlavors
import openfoodfacts.github.scrachx.openfood.BuildConfig
import openfoodfacts.github.scrachx.openfood.models.DaoMaster
import openfoodfacts.github.scrachx.openfood.models.DaoMaster.OpenHelper
import openfoodfacts.github.scrachx.openfood.models.InvalidBarcodeDao
Expand Down Expand Up @@ -36,14 +42,22 @@ import openfoodfacts.github.scrachx.openfood.models.entities.store.StoreDao
import openfoodfacts.github.scrachx.openfood.models.entities.store.StoreNameDao
import openfoodfacts.github.scrachx.openfood.models.entities.tag.TagDao
import org.greenrobot.greendao.database.Database
import java.io.*
import java.nio.file.Files
import kotlin.io.path.Path


class OFFDatabaseHelper @JvmOverloads constructor(
context: Context,
name: String,
factory: CursorFactory? = null
) : OpenHelper(context, name, factory) {
context: Context,
factory: CursorFactory? = null
) : OpenHelper(context, DB_NAME, factory) {

private val settings: SharedPreferences by lazy { context.getAppPreferences() }

init {
removeExportedDatabase(context)
}

override fun onCreate(db: Database) {
Log.i(LOG_TAG, "Creating tables for schema version ${DaoMaster.SCHEMA_VERSION}")
DaoMaster.createAllTables(db, true)
Expand Down Expand Up @@ -98,29 +112,31 @@ class OFFDatabaseHelper @JvmOverloads constructor(
val updatedTables = listOf("additive_name", "additive", "category_name", "category", "label_name", "label")
updatedTables.forEach { table ->
newColumns.filterNot { isFieldExist(db, table, it) }
.forEach { column ->
db.execSQL("ALTER TABLE $table ADD COLUMN '$column' TEXT NOT NULL DEFAULT '';")
}
.forEach { column ->
db.execSQL("ALTER TABLE $table ADD COLUMN '$column' TEXT NOT NULL DEFAULT '';")
}
}
}
8 -> {
OfflineSavedProductDao.createTable(db, true)
}
9 -> {
listOf("additive_name", "additive").forEach { table ->
listOf("overexposure_risk", "exposure_mean_greater_than_adi", "exposure_mean_greater_than_noael",
"exposure95_th_greater_than_adi", "exposure95_th_greater_than_noael")
.filterNot { isFieldExist(db, table, it) }
.forEach { db.execSQL("ALTER TABLE $table ADD COLUMN '$it' TEXT;") }
listOf(
"overexposure_risk", "exposure_mean_greater_than_adi", "exposure_mean_greater_than_noael",
"exposure95_th_greater_than_adi", "exposure95_th_greater_than_noael"
)
.filterNot { isFieldExist(db, table, it) }
.forEach { db.execSQL("ALTER TABLE $table ADD COLUMN '$it' TEXT;") }
}
}
10 -> {
listOf("allergen_name", "allergen").forEach { table ->
listOf("WIKI_DATA_ID", "IS_WIKI_DATA_ID_PRESENT")
.filterNot { isFieldExist(db, table, it) }
.forEach { column ->
db.execSQL("ALTER TABLE $table ADD COLUMN '$column' TEXT NOT NULL DEFAULT '';")
}
.filterNot { isFieldExist(db, table, it) }
.forEach { column ->
db.execSQL("ALTER TABLE $table ADD COLUMN '$column' TEXT NOT NULL DEFAULT '';")
}
}
}
11 -> {
Expand Down Expand Up @@ -172,5 +188,59 @@ class OFFDatabaseHelper @JvmOverloads constructor(

companion object {
private const val LOG_TAG = "greenDAO"

private const val DB_NAME_OPEN_PET_FOOD_FACTS = "open_pet_food_facts"
private const val DB_NAME_OPEN_BEAUTY_FACTS = "open_beauty_facts"
private const val DB_NAME_OPEN_PRODUCTS_FACTS = "open_products_facts"
private const val DB_NAME_OPEN_FOOD_FACTS = "open_food_facts"

private fun dbOutputPath(context: Context) = File(context.filesDir, DB_NAME)

val DB_NAME = when (BuildConfig.FLAVOR) {
AppFlavors.OPFF -> DB_NAME_OPEN_PET_FOOD_FACTS
AppFlavors.OBF -> DB_NAME_OPEN_BEAUTY_FACTS
AppFlavors.OPF -> DB_NAME_OPEN_PRODUCTS_FACTS
AppFlavors.OFF -> DB_NAME_OPEN_FOOD_FACTS
else -> DB_NAME_OPEN_FOOD_FACTS
}

fun exportDB(context: Context) {
val databasePath = context.getDatabasePath(DB_NAME)
val outputPath = dbOutputPath(context)
copyFile(databasePath, outputPath)

val uri: Uri = FileProvider.getUriForFile(context, GenericFileProvider.AUTHORITY, outputPath)

val intent = ShareCompat.IntentBuilder(context)
.setStream(uri) // uri from FileProvider
.setType("application/vnd.sqlite3")
.intent
.setAction(Intent.ACTION_SEND) // Change if needed
.setDataAndType(uri, "application/vnd.sqlite3")
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

context.startActivity(intent)
}

fun removeExportedDatabase(context: Context) {
dbOutputPath(context).deleteOnExit()
}

private fun copyFile(source: File, destination: File) {
BufferedInputStream(
FileInputStream(source)
).use { `in` ->
BufferedOutputStream(
FileOutputStream(destination)
).use { out ->
val buffer = ByteArray(1024)
var lengthRead: Int
while (`in`.read(buffer).also { lengthRead = it } > 0) {
out.write(buffer, 0, lengthRead)
out.flush()
}
}
}
}
}
}
4 changes: 4 additions & 0 deletions app/src/main/res/values/pref_keys.xml
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@
<string name="pref_power_mode_title">Power mode scan</string>
<string name="pref_power_mode_summary">Quickly scan products in a supermarket to see which ones are not in the database.</string>

<string name="pref_export_db_key" translatable="false">exportDB</string>
<string name="pref_export_db_title">Export app database</string>
<string name="pref_export_db_summary">Extract the app database (containing your lists)</string>

<string name="pref_terms_key" translatable="false">Terms</string>
<string name="pref_terms_title">Terms</string>
<string name="pref_terms_summary">Terms and Privacy</string>
Expand Down
8 changes: 7 additions & 1 deletion app/src/main/res/xml/preferences.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
android:title="@string/preference_header_general">

<ListPreference
app:icon="@drawable/ic_baseline_language_24"
android:defaultValue="en"
android:dialogTitle="@string/preference_choose_language_dialog_title"
android:key="@string/pref_language_key"
android:title="@string/pref_language_title"
app:icon="@drawable/ic_baseline_language_24"
app:useSimpleSummaryProvider="true" />

<ListPreference
Expand Down Expand Up @@ -66,6 +66,12 @@
android:title="@string/pref_power_mode_title"
app:summary="@string/pref_power_mode_summary" />

<Preference
android:defaultValue="false"
android:key="@string/pref_export_db_key"
android:title="@string/pref_export_db_title"
app:summary="@string/pref_export_db_summary" />


</PreferenceCategory>

Expand Down
4 changes: 4 additions & 0 deletions app/src/main/res/xml/provider_paths.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,9 @@
<external-path
name="external_files"
path="." />

<files-path
name="files"
path="." />

</paths>

0 comments on commit 694b56f

Please sign in to comment.