Skip to content

Commit 24c5338

Browse files
authored
Merge pull request #31 from ChochaNaresh/Dev
- pick from recent bug fixed
2 parents de4e3b2 + 100378e commit 24c5338

File tree

6 files changed

+193
-24
lines changed

6 files changed

+193
-24
lines changed

filepickerlibrary/src/main/java/com/nareshchocha/filepickerlibrary/initializer/TimberInitializer.kt

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,51 @@ package com.nareshchocha.filepickerlibrary.initializer
22

33
import android.content.Context
44
import androidx.startup.Initializer
5+
import com.nareshchocha.filepickerlibrary.utilities.appConst.Const.copyFileFolder
6+
import kotlinx.coroutines.Dispatchers
7+
import kotlinx.coroutines.GlobalScope
8+
import kotlinx.coroutines.cancel
9+
import kotlinx.coroutines.launch
510
import timber.log.Timber
11+
import java.io.File
12+
import java.io.IOException
613

714
class TimberInitializer : Initializer<Unit> {
15+
companion object {
16+
private val TAG: String = TimberInitializer::class.java.name
17+
}
818

919
override fun create(context: Context) {
1020
// if (BuildConfig.DEBUG) {
1121
Timber.plant(Timber.DebugTree())
12-
Timber.v("TimberInitializer is initialized.")
13-
// }
22+
Timber.tag(TAG).v("TimberInitializer is initialized.")
23+
//Timber.tag(TAG).v("Delete copy Files")
24+
/*GlobalScope.launch(Dispatchers.IO) {
25+
try {
26+
deleteFiles(context.cacheDir.path+"/"+ copyFileFolder)
27+
*//*val isDeleted = File(context.cacheDir, copyFileFolder).deleteOnExit()
28+
Timber.tag(TAG).e("Delete Files isDeleted:: $isDeleted")*//*
29+
} catch (e: Exception) {
30+
Timber.tag(TAG).e("Delete Files Exception :: $e")
31+
}
32+
this.cancel()
33+
}.start()*/
1434
}
35+
/*fun deleteFiles(path: String) {
36+
val file = File(path)
37+
if (file.exists()) {
38+
val deleteCmd = "rm -r $path"
39+
val runtime = Runtime.getRuntime()
40+
try {
41+
Timber.tag(TAG).e(" BeFear Files Size:: ${File(path).list()?.size}")
42+
runtime.exec(deleteCmd)
43+
Timber.tag(TAG).e(" After Files Size:: ${File(path).list()?.size}")
44+
Timber.tag(TAG).e("Delete Files isDeleted:: Done")
45+
} catch (e: IOException) {
46+
Timber.tag(TAG).e("deleteFiles Exception :: $e")
47+
}
48+
}
49+
}*/
1550

1651
override fun dependencies(): List<Class<out Initializer<*>>> = emptyList()
1752
}

filepickerlibrary/src/main/java/com/nareshchocha/filepickerlibrary/utilities/FileUtils.kt

Lines changed: 131 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,18 @@ import android.net.Uri
77
import android.os.Environment
88
import android.provider.DocumentsContract
99
import android.provider.MediaStore
10+
import android.provider.OpenableColumns
1011
import androidx.annotation.Keep
12+
import com.nareshchocha.filepickerlibrary.utilities.appConst.Const
1113
import com.nareshchocha.filepickerlibrary.utilities.extentions.isDownloadsDocument
1214
import com.nareshchocha.filepickerlibrary.utilities.extentions.isExternalStorageDocument
15+
import com.nareshchocha.filepickerlibrary.utilities.extentions.isGoogleDriveUri
1316
import com.nareshchocha.filepickerlibrary.utilities.extentions.isGooglePhotosUri
1417
import com.nareshchocha.filepickerlibrary.utilities.extentions.isMediaDocument
18+
import timber.log.Timber
1519
import java.io.File
20+
import java.io.FileOutputStream
21+
import java.io.InputStream
1622

1723
@Keep
1824
internal object FileUtils {
@@ -32,30 +38,38 @@ internal object FileUtils {
3238
}
3339

3440
uri.isDownloadsDocument() -> {
35-
context.getDownloadsDocumentPath(uri)
41+
context.getDownloadsDocumentPath(uri) ?: context.copyFileToInternalStorage(
42+
uri
43+
)
3644
}
3745

3846
uri.isMediaDocument() -> {
39-
context.getMediaDocumentPath(uri)
47+
context.getMediaDocumentPath(uri) ?: context.copyFileToInternalStorage(uri)
4048
}
4149

4250
else -> {
43-
null
51+
context.copyFileToInternalStorage(uri)
4452
}
4553
}
4654
}
4755

56+
uri.isGoogleDriveUri() -> {
57+
context.getDriveFilePath(uri);
58+
}
59+
4860
"content".equals(uri.scheme, ignoreCase = true) -> {
4961
// Return the remote address
5062
if (uri.isGooglePhotosUri()) {
5163
uri.lastPathSegment
64+
} else if (uri.isGoogleDriveUri()) {
65+
return context.getDriveFilePath(uri);
5266
} else {
5367
getDataColumn(
5468
context,
5569
uri,
5670
null,
5771
null,
58-
)
72+
) ?: context.copyFileToInternalStorage(uri)
5973
}
6074
}
6175

@@ -64,9 +78,99 @@ internal object FileUtils {
6478
}
6579

6680
else -> {
67-
null
81+
context.copyFileToInternalStorage(uri)
82+
}
83+
}
84+
}
85+
86+
87+
/***
88+
* Used for Android Q+
89+
* @param uri
90+
* @param newDirName if you want to create a directory, you can set this variable
91+
* @return
92+
*/
93+
private fun Context.copyFileToInternalStorage(
94+
uri: Uri?,
95+
newDirName: String = Const.copyFileFolder
96+
): String? {
97+
if (uri == null) {
98+
return null
99+
}
100+
val returnCursor: Cursor? = this.contentResolver.query(
101+
uri, arrayOf(
102+
OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE
103+
), null, null, null
104+
)
105+
val nameIndex = returnCursor?.getColumnIndex(OpenableColumns.DISPLAY_NAME) ?: return null
106+
returnCursor.moveToFirst()
107+
val name = returnCursor.getString(nameIndex)
108+
val output: File = if (newDirName != "") {
109+
val dir = File(cacheDir, newDirName)
110+
if (!dir.exists()) {
111+
dir.mkdir()
112+
}
113+
File(cacheDir, "$newDirName/$name")
114+
} else {
115+
File(cacheDir, "/$name")
116+
}
117+
try {
118+
val inputStream: InputStream? = contentResolver.openInputStream(uri)
119+
val outputStream = FileOutputStream(output)
120+
var read: Int? = 0
121+
val bufferSize = 1024
122+
val buffers = ByteArray(bufferSize)
123+
while (inputStream?.read(buffers).also { read = it } != -1) {
124+
read?.let { outputStream.write(buffers, 0, it) }
68125
}
126+
inputStream?.close()
127+
outputStream.close()
128+
} catch (e: Exception) {
129+
output.delete()
130+
Timber.tag("Exception").e(e.message!!)
131+
return null
69132
}
133+
return output.path
134+
}
135+
136+
137+
private fun Context.getDriveFilePath(uri: Uri): String? {
138+
val returnCursor: Cursor? = contentResolver.query(
139+
uri,
140+
null,
141+
null,
142+
null,
143+
null
144+
)
145+
/*
146+
* Get the column indexes of the data in the Cursor,
147+
* * move to the first row in the Cursor, get the data,
148+
* * and display it.
149+
* */
150+
val nameIndex = returnCursor?.getColumnIndex(OpenableColumns.DISPLAY_NAME) ?: return null
151+
returnCursor.moveToFirst()
152+
val name = returnCursor.getString(nameIndex)
153+
val file = File(cacheDir, name)
154+
try {
155+
val inputStream: InputStream? = contentResolver.openInputStream(uri)
156+
val outputStream = FileOutputStream(file)
157+
var read: Int? = 0
158+
val maxBufferSize = 1 * 1024 * 1024
159+
val bytesAvailable = inputStream?.available() ?: 0
160+
161+
//int bufferSize = 1024;
162+
val bufferSize = bytesAvailable.coerceAtMost(maxBufferSize)
163+
val buffers = ByteArray(bufferSize)
164+
while (inputStream?.read(buffers).also { read = it } != -1) {
165+
read?.let { outputStream.write(buffers, 0, it) }
166+
}
167+
inputStream?.close()
168+
outputStream.close()
169+
} catch (e: Exception) {
170+
Timber.tag("Exception").e(e.message)
171+
return null
172+
}
173+
return file.path
70174
}
71175

72176
@Keep
@@ -88,6 +192,10 @@ internal object FileUtils {
88192
"audio" -> {
89193
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
90194
}
195+
196+
else -> {
197+
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
198+
}
91199
}
92200
val selection = "_id=?"
93201
val selectionArgs = arrayOf(
@@ -109,11 +217,23 @@ internal object FileUtils {
109217
val file = File(id)
110218
if (file.exists()) return id
111219
}
112-
val contentUri = ContentUris.withAppendedId(
113-
Uri.parse("content://downloads/public_downloads"),
114-
java.lang.Long.valueOf(id),
220+
val contentUriPrefixesToTry = arrayOf(
221+
"content://downloads/public_downloads",
222+
"content://downloads/my_downloads"
115223
)
116-
return getDataColumn(this, contentUri, null, null)
224+
for (contentUriPrefix in contentUriPrefixesToTry) {
225+
return try {
226+
val contentUri = ContentUris.withAppendedId(
227+
Uri.parse(contentUriPrefix),
228+
java.lang.Long.valueOf(id)
229+
)
230+
getDataColumn(this, contentUri, null, null)
231+
} catch (e: NumberFormatException) {
232+
//In Android 8 and Android P the id is not a number
233+
uri.path!!.replaceFirst("^/document/raw:", "").replaceFirst("^raw:", "")
234+
}
235+
}
236+
return null
117237
}
118238

119239
@Keep
@@ -157,6 +277,8 @@ internal object FileUtils {
157277
selectionArgs,
158278
null,
159279
)
280+
Timber.tag("Checked:").d("cursor:: %s", cursor)
281+
160282
if (cursor != null && cursor.moveToFirst()) {
161283
val index = cursor.getColumnIndexOrThrow(column)
162284
return cursor.getString(index)

filepickerlibrary/src/main/java/com/nareshchocha/filepickerlibrary/utilities/appConst/Const.kt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ object Const {
1212

1313
// internal const val AUTHORITY = "com.nareshchocha.filepickerlibrary.fileprovider"
1414
internal const val AUTHORITY = ".library.fileprovider"
15+
internal const val copyFileFolder = "copyFileToInternalStorage"
16+
1517

1618
internal object LogTag {
1719
const val FILE_RESULT = "FILE_RESULT ::"

filepickerlibrary/src/main/java/com/nareshchocha/filepickerlibrary/utilities/extentions/FilePathExtentions.kt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,7 @@ internal fun Uri.isMediaDocument(): Boolean {
3333
internal fun Uri.isGooglePhotosUri(): Boolean {
3434
return "com.google.android.apps.photos.content" == authority
3535
}
36+
37+
internal fun Uri.isGoogleDriveUri(): Boolean {
38+
return "com.google.android.apps.docs.storage" == authority || "com.google.android.apps.docs.storage.legacy" == authority
39+
}

sample/src/main/java/com/nareshchocha/filepicker/JavaExampleActivity.java

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,9 @@
2424
import com.nareshchocha.filepickerlibrary.models.PopUpType;
2525
import com.nareshchocha.filepickerlibrary.models.VideoCaptureConfig;
2626
import com.nareshchocha.filepickerlibrary.ui.FilePicker;
27+
import com.nareshchocha.filepickerlibrary.utilities.appConst.Const;
2728

29+
import java.io.File;
2830
import java.util.ArrayList;
2931

3032
import timber.log.Timber;
@@ -192,18 +194,23 @@ private void setAdapter() {
192194
@Override
193195
public void onActivityResult(ActivityResult result) {
194196
uriList.clear();
195-
if (result != null && result.getResultCode() == Activity.RESULT_OK) {
196-
if (result.getData().getData() != null) {
197-
uriList.add(result.getData().getData());
198-
// content://com.nareshchocha.filepicker.library.fileprovider/secure_name/FilePicker/tempImage_1689140682218.jpg
199-
// content://com.nareshchocha.filepicker.library.fileprovider/secure_name/FilePicker/tempImage_1689140682218.jpg
200-
} else {
201-
ArrayList<Uri> listData = getClipDataUris(result.getData());
202-
// ArrayList<String> listData = result.getData().getStringArrayListExtra(Const.BundleExtras.FILE_PATH_LIST);
203-
uriList.addAll(listData);
197+
try {
198+
if (result != null && result.getResultCode() == Activity.RESULT_OK) {
199+
if (result.getData().getData() != null) {
200+
uriList.add(result.getData().getData());
201+
String listData = result.getData().getStringExtra(Const.BundleExtras.FILE_PATH);
202+
File testFile = new File(listData);
203+
Timber.tag("FILE_RESULT").v("Can Read::" + testFile.canRead() + " can Write::" + testFile.canWrite());
204+
} else {
205+
ArrayList<Uri> listData = getClipDataUris(result.getData());
206+
// ArrayList<String> listData = result.getData().getStringArrayListExtra(Const.BundleExtras.FILE_PATH_LIST);
207+
uriList.addAll(listData);
208+
}
209+
Timber.tag("FILE_RESULT").v(result.toString());
210+
Timber.tag("FILE_RESULT").v(result.getData().getExtras().toString());
204211
}
205-
Timber.tag("FILE_RESULT").v(result.toString());
206-
Timber.tag("FILE_RESULT").v(result.getData().getExtras().toString());
212+
} catch (Exception e) {
213+
Timber.tag("FILE_RESULT").e(e.toString());
207214
}
208215
mMediaAdapter.notifyItemRangeChanged(0, uriList.size());
209216
}

sample/src/main/java/com/nareshchocha/filepicker/MainActivity.kt

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,7 @@ class MainActivity : AppCompatActivity() {
8383
.pickDocumentFileBuild(
8484
DocumentFilePickerConfig(
8585
allowMultiple = true,
86-
87-
mMimeTypes = listOf("application/pdf", "image/*"),
86+
mMimeTypes = listOf("application/pdf"),
8887
),
8988
),
9089
)

0 commit comments

Comments
 (0)