Skip to content

Commit

Permalink
fix: overhaul file handling and sharing badges (#967)
Browse files Browse the repository at this point in the history
Co-authored-by: kleines Filmröllchen <[email protected]>
  • Loading branch information
kleinesfilmroellchen and kleines Filmröllchen authored Jul 4, 2024
1 parent 55826f3 commit 6007613
Show file tree
Hide file tree
Showing 7 changed files with 39 additions and 72 deletions.
3 changes: 0 additions & 3 deletions android/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@
<uses-feature android:name="android.hardware.bluetooth" android:required="true"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
android:name=".BadgeMagicApp"
android:allowBackup="true"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class StorageFilesService : KoinComponent {
storageUtils.saveFile(filename, json)
}

fun getAbsPath(fileName: String): String? = storageUtils.getAbsolutePathofFiles(fileName)
fun getAbsPath(fileName: String): String = storageUtils.getAbsolutePathofFiles(fileName)

fun checkIfFilePresent(fileName: String): Boolean = storageUtils.checkIfFilePresent(fileName)
}
Original file line number Diff line number Diff line change
Expand Up @@ -143,19 +143,20 @@ class SavedBadgesFragment : BaseFragment() {

private fun transferItem(item: ConfigInfo) {
val intentShareFile = Intent(Intent.ACTION_SEND)
intentShareFile.type = "text/*"
val fileUri = FileProvider.getUriForFile(
requireContext(),
getString(R.string.file_provider_authority),
File(viewModel.getAbsPath(item.fileName))
)
intentShareFile.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intentShareFile.type = "text/plain"
intentShareFile.setDataAndType(fileUri, "text/plain")
intentShareFile.putExtra(
Intent.EXTRA_STREAM,
FileProvider.getUriForFile(
requireContext(),
getString(R.string.file_provider_authority),
File(
viewModel.getAbsPath(item.fileName)
)
)
fileUri
)
intentShareFile.putExtra(Intent.EXTRA_SUBJECT, "Badge Magic Share: " + item.fileName)
intentShareFile.putExtra(Intent.EXTRA_TEXT, "Badge Magic Share: " + item.fileName)
intentShareFile.putExtra(Intent.EXTRA_TEXT, File(viewModel.getAbsPath(item.fileName)).readText())

this.startActivity(Intent.createChooser(intentShareFile, item.fileName))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package org.fossasia.badgemagic.ui.fragments
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
Expand All @@ -21,7 +20,6 @@ import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.google.android.material.tabs.TabLayout
Expand Down Expand Up @@ -61,7 +59,6 @@ import java.util.TimerTask
class TextArtFragment : BaseFragment() {
companion object {
private const val SCAN_TIMEOUT_MS = 9500L
private const val REQUEST_PERMISSION_CODE = 10
@JvmStatic
fun newInstance() =
TextArtFragment()
Expand Down Expand Up @@ -116,9 +113,7 @@ class TextArtFragment : BaseFragment() {

private fun setupButton() = with(binding) {
saveButton.setOnClickListener {
if (checkStoragePermission()) {
startSaveFile()
}
startSaveFile()
}

transferButton.setOnClickListener {
Expand Down Expand Up @@ -155,29 +150,6 @@ class TextArtFragment : BaseFragment() {
showSaveFileDialog()
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
REQUEST_PERMISSION_CODE -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startSaveFile()
}
}
else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}

private fun checkStoragePermission(): Boolean {
return if (ActivityCompat.checkSelfPermission(
requireContext(),
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED
) {
requestPermissions(arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_PERMISSION_CODE)
false
} else
true
}

private val textChangedListener = object : TextWatcher {
var startPos = -1
var endPos = -1
Expand Down
50 changes: 22 additions & 28 deletions android/src/main/java/org/fossasia/badgemagic/util/StorageUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,27 +20,22 @@ import java.io.FileOutputStream
import java.io.InputStreamReader

class StorageUtils(val context: Context) {
private val externalStorageDir = context.getExternalFilesDir(null)?.absolutePath
private val externalClipartDir = "$externalStorageDir/ClipArts/"
private val clipartDir = File(context.filesDir, "ClipArts")
private val badgeDir = File(context.filesDir, "Badges")
private val badgeExt = ".txt"
private val clipExt = ".png"

private fun checkDirectory(): Boolean {
externalStorageDir?.let {
val directory = File(it)
val directoryClips = File(externalClipartDir)
if (!directory.exists())
return directory.mkdirs()
if (!directoryClips.exists())
return directoryClips.mkdirs()
return true
}
return false
if (!clipartDir.exists())
return clipartDir.mkdirs()
if (!badgeDir.exists())
return badgeDir.mkdirs()
return true
}

fun saveFile(filename: String, json: String) {
checkDirectory()
externalStorageDir?.let {
badgeDir.let {
val saveFile = File(it, "$filename$badgeExt")
saveFile.writeText(json)
}
Expand All @@ -50,8 +45,8 @@ class StorageUtils(val context: Context) {
checkDirectory()
val list = mutableListOf<ConfigInfo>()

externalStorageDir?.let {
val files = File(externalStorageDir).listFiles() ?: return list
badgeDir.let {
val files = badgeDir.listFiles() ?: return list
files.sortWith(Comparator<File> { a, b -> (b.lastModified() - a.lastModified()).toInt() })
for (i in files.indices) {
if (getFileExtension(files[i].name) == badgeExt) {
Expand All @@ -73,22 +68,20 @@ class StorageUtils(val context: Context) {

fun deleteFile(fileName: String) {
checkDirectory()
val deleteFile = File(externalStorageDir, fileName)
val deleteFile = File(badgeDir, fileName)
deleteFile.delete()
}

fun getAbsolutePathofFiles(fileName: String): String {
return "$externalStorageDir/$fileName"
}
fun getAbsolutePathofFiles(fileName: String): String = File(badgeDir, fileName).absolutePath

fun checkIfFilePresent(fileName: String): Boolean {
checkDirectory()
return (File(externalStorageDir, "$fileName$badgeExt").exists())
return (File(badgeDir, "$fileName$badgeExt").exists())
}

fun checkIfFilePresent(context: Context, uri: Uri?): Boolean {
checkDirectory()
return (File(externalStorageDir, getFileName(context, uri ?: Uri.EMPTY)).exists())
return (File(badgeDir, getFileName(context, uri ?: Uri.EMPTY)).exists())
}

fun copyFileToDirectory(context: Context, uri: Uri?): Boolean {
Expand All @@ -97,7 +90,7 @@ class StorageUtils(val context: Context) {
var fileName = getFileName(context, uri ?: Uri.EMPTY)
if (!fileName.contains(badgeExt))
fileName += badgeExt
val dest = File(externalStorageDir, fileName)
val dest = File(badgeDir, fileName)
inputStream?.let {
val jsonString = BufferedReader(InputStreamReader(it)).readLine()
if (checkValidJSON(jsonString)) {
Expand Down Expand Up @@ -149,13 +142,13 @@ class StorageUtils(val context: Context) {

fun saveEditedBadge(badgeConfig: BadgeConfig, fileName: String) {
checkDirectory()
val saveFile = File(externalStorageDir, fileName)
val saveFile = File(badgeDir, fileName)
saveFile.writeText(JSONHelper.encodeJSON(badgeConfig))
}

fun saveClipArt(bitmap: Bitmap): Boolean {
checkDirectory()
val file = File.createTempFile("clip", clipExt, File(externalClipartDir))
val file = File.createTempFile("clip", clipExt, clipartDir)
try {
val out = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
Expand All @@ -169,7 +162,7 @@ class StorageUtils(val context: Context) {

fun saveEditedClipart(bitmap: Bitmap, fileName: String): Boolean {
checkDirectory()
val file = File(externalClipartDir, fileName)
val file = File(clipartDir, fileName)
try {
val out = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
Expand All @@ -185,7 +178,7 @@ class StorageUtils(val context: Context) {
checkDirectory()
val list = mutableMapOf<String, Drawable?>()

val files = File(externalClipartDir).listFiles() ?: return list
val files = clipartDir.listFiles() ?: return list
files.sortWith(Comparator<File> { a, b -> (b.lastModified() - a.lastModified()).toInt() })
for (i in files.indices) {
if (getFileExtension(files[i].name) == clipExt) {
Expand All @@ -196,12 +189,13 @@ class StorageUtils(val context: Context) {
}

fun getClipartFromPath(filename: String): Drawable? {
return Drawable.createFromPath(File(externalClipartDir, filename).absolutePath)
checkDirectory()
return Drawable.createFromPath(File(clipartDir, filename).absolutePath)
}

fun deleteClipart(fileName: String) {
checkDirectory()
val deleteFile = File(externalClipartDir, fileName)
val deleteFile = File(clipartDir, fileName)
deleteFile.delete()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@ class FilesViewModel(

fun deleteFile(fileName: String) = storageFilesService.deleteFile(fileName)

fun getAbsPath(fileName: String): String? = storageFilesService.getAbsPath(fileName)
fun getAbsPath(fileName: String): String = storageFilesService.getAbsPath(fileName)
}
5 changes: 4 additions & 1 deletion android/src/main/res/xml/file_provider_paths.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
<external-files-path
name="external_files" path="." />
<files-path
name="files"
path="." />
</paths>

0 comments on commit 6007613

Please sign in to comment.