Skip to content

Commit

Permalink
Remove deprecated APIs usage
Browse files Browse the repository at this point in the history
  • Loading branch information
anggrayudi committed Jul 1, 2021
1 parent 5e58aab commit ca082c9
Show file tree
Hide file tree
Showing 10 changed files with 83 additions and 105 deletions.
2 changes: 1 addition & 1 deletion .github/scripts/deploy_snapshot.sh
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ elif [ "${GITHUB_REF##*/}" != "master" ]; then
echo "Skipping deployment: wrong branch. Expected 'master' but was '${GITHUB_REF##*/}'."
else
echo "Deploying snapshot..."
./gradlew :storage:uploadArchives --no-daemon --no-parallel --stacktrace
./gradlew :storage:publish --no-daemon --no-parallel --stacktrace
echo "Snapshot released!"
fi
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,7 @@ fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
fastlane/readme.md

# Java dump memory
*.hprof
4 changes: 2 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ buildscript {

addRepos(repositories)

ext.kotlin_version = '1.5.10'
ext.kotlin_version = '1.5.20'

dependencies {
classpath 'com.android.tools.build:gradle:4.2.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.vanniktech:gradle-maven-publish-plugin:0.15.1'
classpath 'com.vanniktech:gradle-maven-publish-plugin:0.16.0'
classpath "org.jetbrains.dokka:dokka-gradle-plugin:1.4.20"
}
}
Expand Down
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ android.useAndroidX=true
android.enableJetifier=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
STORAGE_VERSION=0.9.0-SNAPSHOT
STORAGE_VERSION=0.9.0
9 changes: 7 additions & 2 deletions sample/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.anggrayudi.storage.sample">

<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<!-- Add this permission if your app requires full disk access -->
<uses-permission
android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />

<application
android:name=".App"
Expand All @@ -11,7 +15,8 @@
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
android:theme="@style/AppTheme"
tools:ignore="AllowBackup">
<activity
android:name=".activity.MainActivity"
android:screenOrientation="portrait">
Expand Down
2 changes: 1 addition & 1 deletion sample/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
<resources>
<string name="app_name">SimpleStorage</string>
<string name="app_name" translatable="false">Simple Storage</string>
</resources>
5 changes: 4 additions & 1 deletion storage/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.anggrayudi.storage">

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
</manifest>
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.StatFs
import android.system.ErrnoException
import android.system.Os
import androidx.annotation.WorkerThread
import androidx.core.content.ContextCompat
Expand Down Expand Up @@ -692,8 +691,6 @@ object DocumentFileCompat {
internal fun getDirectorySequence(path: String) = path.split('/')
.filterNot { it.isBlank() }

private fun recreateAppDirectory(context: Context) = context.getAppDirectory().apply { File(this).mkdirs() }

/**
* Given the following `folderFullPaths`:
* * `/storage/9016-4EF8/Downloads`
Expand Down Expand Up @@ -770,115 +767,82 @@ object DocumentFileCompat {
}
}

/** Get available space in bytes. */
@JvmStatic
@Suppress("DEPRECATION")
fun getFreeSpace(context: Context, storageId: String): Long {
try {
if (storageId == PRIMARY || storageId == DATA) {
val stat = StatFs(recreateAppDirectory(context))
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
stat.availableBytes
else
(stat.blockSize * stat.availableBlocks).toLong()
} else if (Build.VERSION.SDK_INT >= 21) {
try {
val fileUri = getDocumentFileForStorageInfo(context, storageId)?.uri ?: return 0
context.contentResolver.openFileDescriptor(fileUri, "r")?.use {
return try {
val file = getDocumentFileForStorageInfo(context, storageId) ?: return 0
when {
file.isRawFile -> StatFs(file.uri.path!!).availableBytes
Build.VERSION.SDK_INT >= 21 -> {
context.contentResolver.openFileDescriptor(file.uri, "r")?.use {
val stats = Os.fstatvfs(it.fileDescriptor)
return stats.f_bavail * stats.f_frsize
}
} catch (e: ErrnoException) {
// ignore
stats.f_bavail * stats.f_frsize
} ?: 0
}
else -> 0
}
} catch (e: SecurityException) {
// ignore
} catch (e: IllegalArgumentException) {
// ignore
} catch (e: IOException) {
// ignore
} catch (e: Throwable) {
0
}
return 0
}

/** Get available space in bytes. */
@JvmStatic
@Suppress("DEPRECATION")
fun getUsedSpace(context: Context, storageId: String): Long {
try {
if (storageId == PRIMARY || storageId == DATA) {
val stat = StatFs(recreateAppDirectory(context))
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
stat.totalBytes - stat.availableBytes
else
(stat.blockSize * stat.blockCount - stat.blockSize * stat.availableBlocks).toLong()
} else if (Build.VERSION.SDK_INT >= 21) {
try {
val fileUri = getDocumentFileForStorageInfo(context, storageId)?.uri ?: return 0
context.contentResolver.openFileDescriptor(fileUri, "r")?.use {
return try {
val file = getDocumentFileForStorageInfo(context, storageId) ?: return 0
when {
file.isRawFile -> StatFs(file.uri.path!!).run { totalBytes - availableBytes }
Build.VERSION.SDK_INT >= 21 -> {
context.contentResolver.openFileDescriptor(file.uri, "r")?.use {
val stats = Os.fstatvfs(it.fileDescriptor)
return stats.f_blocks * stats.f_frsize - stats.f_bavail * stats.f_frsize
}
} catch (e: ErrnoException) {
// ignore
stats.f_blocks * stats.f_frsize - stats.f_bavail * stats.f_frsize
} ?: 0
}
else -> 0
}
} catch (e: SecurityException) {
// ignore
} catch (e: IllegalArgumentException) {
// ignore
} catch (e: IOException) {
// ignore
} catch (e: Throwable) {
0
}
return 0
}

@JvmStatic
@Suppress("DEPRECATION")
fun getStorageCapacity(context: Context, storageId: String): Long {
try {
if (storageId == PRIMARY || storageId == DATA) {
val stat = StatFs(recreateAppDirectory(context))
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
stat.totalBytes
else
(stat.blockSize * stat.blockCount).toLong()
} else if (Build.VERSION.SDK_INT >= 21) {
try {
val fileUri = getDocumentFileForStorageInfo(context, storageId)?.uri ?: return 0
context.contentResolver.openFileDescriptor(fileUri, "r")?.use {
return try {
val file = getDocumentFileForStorageInfo(context, storageId) ?: return 0
when {
file.isRawFile -> StatFs(file.uri.path!!).totalBytes
Build.VERSION.SDK_INT >= 21 -> {
context.contentResolver.openFileDescriptor(file.uri, "r")?.use {
val stats = Os.fstatvfs(it.fileDescriptor)
return stats.f_blocks * stats.f_frsize
}
} catch (e: ErrnoException) {
// ignore
stats.f_blocks * stats.f_frsize
} ?: 0
}
else -> 0
}
} catch (e: SecurityException) {
// ignore
} catch (e: IllegalArgumentException) {
// ignore
} catch (e: IOException) {
// ignore
} catch (e: Throwable) {
0
}
return 0
}

private fun getDocumentFileForStorageInfo(context: Context, storageId: String): DocumentFile? {
return if (storageId == PRIMARY || storageId == DATA) {
// use app private directory, so no permissions required
val privateAppDirectory = context.getExternalFilesDir(null) ?: return null
privateAppDirectory.mkdirs()
DocumentFile.fromFile(privateAppDirectory)
} else {
// /storage/131D-261A/Android/data/com.anggrayudi.storage.sample/files
val folder = File("/storage/$storageId/Android/data/${context.packageName}/files")
folder.mkdirs()
if (folder.canRead()) {
DocumentFile.fromFile(folder)
} else {
getAccessibleRootDocumentFile(context, folder.absolutePath, considerRawFile = false)
return when (storageId) {
PRIMARY -> {
// use app private directory, so no permissions required
val directory = context.getExternalFilesDir(null) ?: return null
DocumentFile.fromFile(directory)
}

DATA -> DocumentFile.fromFile(context.dataDirectory)

else -> {
// /storage/131D-261A/Android/data/com.anggrayudi.storage.sample/files
val folder = File("/storage/$storageId/Android/data/${context.packageName}/files")
folder.mkdirs()
if (folder.canRead()) {
DocumentFile.fromFile(folder)
} else {
getAccessibleRootDocumentFile(context, folder.absolutePath, considerRawFile = false)
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -731,10 +731,11 @@ fun DocumentFile.search(
return when {
!isDirectory || !canRead() -> emptyList()
recursive -> {
val thread = Thread.currentThread()
if (mimeTypes.isNullOrEmpty() || mimeTypes.any { it == MimeType.UNKNOWN }) {
walkFileTreeForSearch(documentType, emptyArray(), name, regex)
walkFileTreeForSearch(documentType, emptyArray(), name, regex, thread)
} else {
walkFileTreeForSearch(DocumentFileType.FILE, mimeTypes, name, regex)
walkFileTreeForSearch(DocumentFileType.FILE, mimeTypes, name, regex, thread)
}
}
else -> {
Expand Down Expand Up @@ -764,10 +765,12 @@ private fun DocumentFile.walkFileTreeForSearch(
documentType: DocumentFileType,
mimeTypes: Array<String>,
nameFilter: String,
regex: Regex?
regex: Regex?,
thread: Thread
): List<DocumentFile> {
val fileTree = mutableListOf<DocumentFile>()
for (file in listFiles()) {
if (thread.isInterrupted) break
if (!canRead()) continue

if (file.isFile) {
Expand All @@ -788,7 +791,7 @@ private fun DocumentFile.walkFileTreeForSearch(
fileTree.add(file)
}
}
fileTree.addAll(file.walkFileTreeForSearch(documentType, mimeTypes, nameFilter, regex))
fileTree.addAll(file.walkFileTreeForSearch(documentType, mimeTypes, nameFilter, regex, thread))
}
}
return fileTree
Expand Down
10 changes: 5 additions & 5 deletions storage/src/main/java/com/anggrayudi/storage/file/FileExt.kt
Original file line number Diff line number Diff line change
Expand Up @@ -291,20 +291,20 @@ fun File.moveTo(
context: Context,
targetFolder: String,
newFileNameInTarget: String? = null,
mode: FileCallback.ConflictResolution = FileCallback.ConflictResolution.CREATE_NEW
conflictResolution: FileCallback.ConflictResolution = FileCallback.ConflictResolution.CREATE_NEW
): File? {
return moveTo(context, File(targetFolder), newFileNameInTarget, mode)
return moveTo(context, File(targetFolder), newFileNameInTarget, conflictResolution)
}

/**
* @param mode using [FileCallback.ConflictResolution.SKIP] will return `null`
* @param conflictResolution using [FileCallback.ConflictResolution.SKIP] will return `null`
*/
@JvmOverloads
fun File.moveTo(
context: Context,
targetFolder: File,
newFileNameInTarget: String? = null,
mode: FileCallback.ConflictResolution = FileCallback.ConflictResolution.CREATE_NEW
conflictResolution: FileCallback.ConflictResolution = FileCallback.ConflictResolution.CREATE_NEW
): File? {
if (!exists() || !isWritable(context)) {
return null
Expand All @@ -322,7 +322,7 @@ fun File.moveTo(
return null
}
if (dest.exists()) {
when (mode) {
when (conflictResolution) {
FileCallback.ConflictResolution.SKIP -> return null
FileCallback.ConflictResolution.REPLACE -> if (!dest.forceDelete()) return null
FileCallback.ConflictResolution.CREATE_NEW -> {
Expand Down

0 comments on commit ca082c9

Please sign in to comment.