Skip to content

Commit

Permalink
Merge pull request #31 from ChochaNaresh/Dev
Browse files Browse the repository at this point in the history
- pick from recent bug fixed
  • Loading branch information
ChochaNaresh authored Sep 29, 2023
2 parents de4e3b2 + 100378e commit 24c5338
Show file tree
Hide file tree
Showing 6 changed files with 193 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,51 @@ package com.nareshchocha.filepickerlibrary.initializer

import android.content.Context
import androidx.startup.Initializer
import com.nareshchocha.filepickerlibrary.utilities.appConst.Const.copyFileFolder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import timber.log.Timber
import java.io.File
import java.io.IOException

class TimberInitializer : Initializer<Unit> {
companion object {
private val TAG: String = TimberInitializer::class.java.name
}

override fun create(context: Context) {
// if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
Timber.v("TimberInitializer is initialized.")
// }
Timber.tag(TAG).v("TimberInitializer is initialized.")
//Timber.tag(TAG).v("Delete copy Files")
/*GlobalScope.launch(Dispatchers.IO) {
try {
deleteFiles(context.cacheDir.path+"/"+ copyFileFolder)
*//*val isDeleted = File(context.cacheDir, copyFileFolder).deleteOnExit()
Timber.tag(TAG).e("Delete Files isDeleted:: $isDeleted")*//*
} catch (e: Exception) {
Timber.tag(TAG).e("Delete Files Exception :: $e")
}
this.cancel()
}.start()*/
}
/*fun deleteFiles(path: String) {
val file = File(path)
if (file.exists()) {
val deleteCmd = "rm -r $path"
val runtime = Runtime.getRuntime()
try {
Timber.tag(TAG).e(" BeFear Files Size:: ${File(path).list()?.size}")
runtime.exec(deleteCmd)
Timber.tag(TAG).e(" After Files Size:: ${File(path).list()?.size}")
Timber.tag(TAG).e("Delete Files isDeleted:: Done")
} catch (e: IOException) {
Timber.tag(TAG).e("deleteFiles Exception :: $e")
}
}
}*/

override fun dependencies(): List<Class<out Initializer<*>>> = emptyList()
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,18 @@ import android.net.Uri
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.provider.OpenableColumns
import androidx.annotation.Keep
import com.nareshchocha.filepickerlibrary.utilities.appConst.Const
import com.nareshchocha.filepickerlibrary.utilities.extentions.isDownloadsDocument
import com.nareshchocha.filepickerlibrary.utilities.extentions.isExternalStorageDocument
import com.nareshchocha.filepickerlibrary.utilities.extentions.isGoogleDriveUri
import com.nareshchocha.filepickerlibrary.utilities.extentions.isGooglePhotosUri
import com.nareshchocha.filepickerlibrary.utilities.extentions.isMediaDocument
import timber.log.Timber
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream

@Keep
internal object FileUtils {
Expand All @@ -32,30 +38,38 @@ internal object FileUtils {
}

uri.isDownloadsDocument() -> {
context.getDownloadsDocumentPath(uri)
context.getDownloadsDocumentPath(uri) ?: context.copyFileToInternalStorage(
uri
)
}

uri.isMediaDocument() -> {
context.getMediaDocumentPath(uri)
context.getMediaDocumentPath(uri) ?: context.copyFileToInternalStorage(uri)
}

else -> {
null
context.copyFileToInternalStorage(uri)
}
}
}

uri.isGoogleDriveUri() -> {
context.getDriveFilePath(uri);
}

"content".equals(uri.scheme, ignoreCase = true) -> {
// Return the remote address
if (uri.isGooglePhotosUri()) {
uri.lastPathSegment
} else if (uri.isGoogleDriveUri()) {
return context.getDriveFilePath(uri);
} else {
getDataColumn(
context,
uri,
null,
null,
)
) ?: context.copyFileToInternalStorage(uri)
}
}

Expand All @@ -64,9 +78,99 @@ internal object FileUtils {
}

else -> {
null
context.copyFileToInternalStorage(uri)
}
}
}


/***
* Used for Android Q+
* @param uri
* @param newDirName if you want to create a directory, you can set this variable
* @return
*/
private fun Context.copyFileToInternalStorage(
uri: Uri?,
newDirName: String = Const.copyFileFolder
): String? {
if (uri == null) {
return null
}
val returnCursor: Cursor? = this.contentResolver.query(
uri, arrayOf(
OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE
), null, null, null
)
val nameIndex = returnCursor?.getColumnIndex(OpenableColumns.DISPLAY_NAME) ?: return null
returnCursor.moveToFirst()
val name = returnCursor.getString(nameIndex)
val output: File = if (newDirName != "") {
val dir = File(cacheDir, newDirName)
if (!dir.exists()) {
dir.mkdir()
}
File(cacheDir, "$newDirName/$name")
} else {
File(cacheDir, "/$name")
}
try {
val inputStream: InputStream? = contentResolver.openInputStream(uri)
val outputStream = FileOutputStream(output)
var read: Int? = 0
val bufferSize = 1024
val buffers = ByteArray(bufferSize)
while (inputStream?.read(buffers).also { read = it } != -1) {
read?.let { outputStream.write(buffers, 0, it) }
}
inputStream?.close()
outputStream.close()
} catch (e: Exception) {
output.delete()
Timber.tag("Exception").e(e.message!!)
return null
}
return output.path
}


private fun Context.getDriveFilePath(uri: Uri): String? {
val returnCursor: Cursor? = contentResolver.query(
uri,
null,
null,
null,
null
)
/*
* Get the column indexes of the data in the Cursor,
* * move to the first row in the Cursor, get the data,
* * and display it.
* */
val nameIndex = returnCursor?.getColumnIndex(OpenableColumns.DISPLAY_NAME) ?: return null
returnCursor.moveToFirst()
val name = returnCursor.getString(nameIndex)
val file = File(cacheDir, name)
try {
val inputStream: InputStream? = contentResolver.openInputStream(uri)
val outputStream = FileOutputStream(file)
var read: Int? = 0
val maxBufferSize = 1 * 1024 * 1024
val bytesAvailable = inputStream?.available() ?: 0

//int bufferSize = 1024;
val bufferSize = bytesAvailable.coerceAtMost(maxBufferSize)
val buffers = ByteArray(bufferSize)
while (inputStream?.read(buffers).also { read = it } != -1) {
read?.let { outputStream.write(buffers, 0, it) }
}
inputStream?.close()
outputStream.close()
} catch (e: Exception) {
Timber.tag("Exception").e(e.message)
return null
}
return file.path
}

@Keep
Expand All @@ -88,6 +192,10 @@ internal object FileUtils {
"audio" -> {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
}

else -> {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
}
}
val selection = "_id=?"
val selectionArgs = arrayOf(
Expand All @@ -109,11 +217,23 @@ internal object FileUtils {
val file = File(id)
if (file.exists()) return id
}
val contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),
java.lang.Long.valueOf(id),
val contentUriPrefixesToTry = arrayOf(
"content://downloads/public_downloads",
"content://downloads/my_downloads"
)
return getDataColumn(this, contentUri, null, null)
for (contentUriPrefix in contentUriPrefixesToTry) {
return try {
val contentUri = ContentUris.withAppendedId(
Uri.parse(contentUriPrefix),
java.lang.Long.valueOf(id)
)
getDataColumn(this, contentUri, null, null)
} catch (e: NumberFormatException) {
//In Android 8 and Android P the id is not a number
uri.path!!.replaceFirst("^/document/raw:", "").replaceFirst("^raw:", "")
}
}
return null
}

@Keep
Expand Down Expand Up @@ -157,6 +277,8 @@ internal object FileUtils {
selectionArgs,
null,
)
Timber.tag("Checked:").d("cursor:: %s", cursor)

if (cursor != null && cursor.moveToFirst()) {
val index = cursor.getColumnIndexOrThrow(column)
return cursor.getString(index)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ object Const {

// internal const val AUTHORITY = "com.nareshchocha.filepickerlibrary.fileprovider"
internal const val AUTHORITY = ".library.fileprovider"
internal const val copyFileFolder = "copyFileToInternalStorage"


internal object LogTag {
const val FILE_RESULT = "FILE_RESULT ::"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,7 @@ internal fun Uri.isMediaDocument(): Boolean {
internal fun Uri.isGooglePhotosUri(): Boolean {
return "com.google.android.apps.photos.content" == authority
}

internal fun Uri.isGoogleDriveUri(): Boolean {
return "com.google.android.apps.docs.storage" == authority || "com.google.android.apps.docs.storage.legacy" == authority
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@
import com.nareshchocha.filepickerlibrary.models.PopUpType;
import com.nareshchocha.filepickerlibrary.models.VideoCaptureConfig;
import com.nareshchocha.filepickerlibrary.ui.FilePicker;
import com.nareshchocha.filepickerlibrary.utilities.appConst.Const;

import java.io.File;
import java.util.ArrayList;

import timber.log.Timber;
Expand Down Expand Up @@ -192,18 +194,23 @@ private void setAdapter() {
@Override
public void onActivityResult(ActivityResult result) {
uriList.clear();
if (result != null && result.getResultCode() == Activity.RESULT_OK) {
if (result.getData().getData() != null) {
uriList.add(result.getData().getData());
// content://com.nareshchocha.filepicker.library.fileprovider/secure_name/FilePicker/tempImage_1689140682218.jpg
// content://com.nareshchocha.filepicker.library.fileprovider/secure_name/FilePicker/tempImage_1689140682218.jpg
} else {
ArrayList<Uri> listData = getClipDataUris(result.getData());
// ArrayList<String> listData = result.getData().getStringArrayListExtra(Const.BundleExtras.FILE_PATH_LIST);
uriList.addAll(listData);
try {
if (result != null && result.getResultCode() == Activity.RESULT_OK) {
if (result.getData().getData() != null) {
uriList.add(result.getData().getData());
String listData = result.getData().getStringExtra(Const.BundleExtras.FILE_PATH);
File testFile = new File(listData);
Timber.tag("FILE_RESULT").v("Can Read::" + testFile.canRead() + " can Write::" + testFile.canWrite());
} else {
ArrayList<Uri> listData = getClipDataUris(result.getData());
// ArrayList<String> listData = result.getData().getStringArrayListExtra(Const.BundleExtras.FILE_PATH_LIST);
uriList.addAll(listData);
}
Timber.tag("FILE_RESULT").v(result.toString());
Timber.tag("FILE_RESULT").v(result.getData().getExtras().toString());
}
Timber.tag("FILE_RESULT").v(result.toString());
Timber.tag("FILE_RESULT").v(result.getData().getExtras().toString());
} catch (Exception e) {
Timber.tag("FILE_RESULT").e(e.toString());
}
mMediaAdapter.notifyItemRangeChanged(0, uriList.size());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,7 @@ class MainActivity : AppCompatActivity() {
.pickDocumentFileBuild(
DocumentFilePickerConfig(
allowMultiple = true,

mMimeTypes = listOf("application/pdf", "image/*"),
mMimeTypes = listOf("application/pdf"),
),
),
)
Expand Down

0 comments on commit 24c5338

Please sign in to comment.