Skip to content

Commit

Permalink
v2.29.1: Android: Fixes copyFileAssets() implementation for SDKs < 35…
Browse files Browse the repository at this point in the history
… + Update of dependencies + Misc fixes

Android:
- Fixes copyFileAssets() implementation for SDKs < 35
- Misc code clean-up, guided by Android.Studio code analysis
- Corrects error code & message thrown by stat() when the file is not
found
  • Loading branch information
birdofpreyru committed Oct 28, 2024
1 parent fcdc509 commit 5df8019
Show file tree
Hide file tree
Showing 9 changed files with 96 additions and 97 deletions.
16 changes: 7 additions & 9 deletions android/src/main/java/com/drpogodin/reactnativefs/Downloader.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.drpogodin.reactnativefs

import android.os.AsyncTask
import android.os.Build
import android.util.Log
import java.io.BufferedInputStream
import java.io.FileOutputStream
Expand All @@ -15,7 +14,9 @@ class Downloader : AsyncTask<DownloadParams?, LongArray?, DownloadResult>() {
private var mParam: DownloadParams? = null
private val mAbort = AtomicBoolean(false)
var res: DownloadResult? = null
protected override fun doInBackground(vararg params: DownloadParams?): DownloadResult {

@Deprecated("Deprecated in Java")
override fun doInBackground(vararg params: DownloadParams?): DownloadResult {
mParam = params[0]
res = DownloadResult()
Thread {
Expand Down Expand Up @@ -59,7 +60,7 @@ class Downloader : AsyncTask<DownloadParams?, LongArray?, DownloadResult>() {
statusCode = connection.responseCode
lengthOfFile = getContentLength(connection)
}
if (statusCode >= 200 && statusCode < 300) {
if (statusCode in 200..299) {
val headers = connection.headerFields
val headersFlat: MutableMap<String, String> = HashMap()
for ((headerKey, value) in headers) {
Expand Down Expand Up @@ -114,22 +115,19 @@ class Downloader : AsyncTask<DownloadParams?, LongArray?, DownloadResult>() {
}

private fun getContentLength(connection: HttpURLConnection?): Long {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
connection!!.contentLengthLong
} else connection!!.contentLength.toLong()
return connection!!.contentLengthLong
}

fun stop() {
mAbort.set(true)
}

protected override fun onProgressUpdate(vararg args: LongArray?) {
@Deprecated("Deprecated in Java")
override fun onProgressUpdate(vararg args: LongArray?) {
val values = args[0]
super.onProgressUpdate(values)
if (values != null) {
mParam!!.onDownloadProgress?.onDownloadProgress(values[0], values[1])
}
}

protected fun onPostExecute(ex: Exception?) {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ enum class Errors(val message: String) {
}

override fun toString(): String {
return LOGTAG + ":" + name
return "$LOGTAG:$name"
}

companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import com.facebook.react.ReactActivity
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContext
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.bridge.WritableMap
Expand Down Expand Up @@ -133,6 +132,7 @@ class ReactNativeFsModule internal constructor(context: ReactApplicationContext)
@ReactMethod
override fun copyFile(filepath: String?, destPath: String?, options: ReadableMap?, promise: Promise) {
object : CopyFileTask() {
@Deprecated("Deprecated in Java")
override fun onPostExecute(ex: Exception?) {
if (ex == null) {
promise.resolve(null)
Expand Down Expand Up @@ -172,7 +172,7 @@ class ReactNativeFsModule internal constructor(context: ReactApplicationContext)
// If the queue has drained, it is success, we are done.
if (queue.isEmpty()) return promise.resolve(null)

val next = queue.removeLast()
val next = queue.removeAt(queue.size - 1)
currentFrom = next.first
currentInto = next.second
}
Expand Down Expand Up @@ -440,6 +440,7 @@ class ReactNativeFsModule internal constructor(context: ReactApplicationContext)
val inFile = File(filepath)
if (!inFile.renameTo(File(destPath))) {
object : CopyFileTask() {
@Deprecated("Deprecated in Java")
override fun onPostExecute(ex: Exception?) {
if (ex == null) {
inFile.delete()
Expand Down Expand Up @@ -667,7 +668,7 @@ class ReactNativeFsModule internal constructor(context: ReactApplicationContext)
try {
val originalFilepath = getOriginalFilepath(filepath, true)
val file = File(originalFilepath)
if (!file.exists()) throw Exception("File does not exist")
if (!file.exists()) throw FileNotFoundException("File does not exist")
val statMap = Arguments.createMap()
statMap.putInt("ctime", (file.lastModified() / 1000).toInt())
statMap.putInt("mtime", (file.lastModified() / 1000).toInt())
Expand Down Expand Up @@ -836,6 +837,7 @@ class ReactNativeFsModule internal constructor(context: ReactApplicationContext)
}

private open inner class CopyFileTask : AsyncTask<String?, Void?, Exception?>() {
@Deprecated("Deprecated in Java")
override fun doInBackground(vararg paths: String?): Exception? {
var `in`: InputStream? = null
var out: OutputStream? = null
Expand Down Expand Up @@ -982,7 +984,7 @@ class ReactNativeFsModule internal constructor(context: ReactApplicationContext)
promise.reject(ex.code, ex.message)
return
}
promise.reject("RNFS01", ex!!.message)
promise.reject("RNFS", ex!!.message)
}

private fun rejectFileNotFound(promise: Promise, filepath: String?) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ class ReactNativeFsPackage : TurboReactPackage() {
moduleInfos[ReactNativeFsModule.NAME] = ReactModuleInfo(
ReactNativeFsModule.NAME,
ReactNativeFsModule.NAME,
false, // canOverrideExistingModule
false, // needsEagerInit
true, // hasConstants
false, // isCxxModule
isTurboModule // isTurboModule
canOverrideExistingModule = false, // canOverrideExistingModule
needsEagerInit = false, // needsEagerInit
hasConstants = true, // hasConstants
isCxxModule = false, // isCxxModule
isTurboModule = isTurboModule // isTurboModule
)
moduleInfos
}
Expand Down
16 changes: 9 additions & 7 deletions android/src/main/java/com/drpogodin/reactnativefs/Uploader.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,14 @@ class Uploader : AsyncTask<UploadParams?, IntArray?, UploadResult>() {
private var mParams: UploadParams? = null
private var res: UploadResult? = null
private val mAbort = AtomicBoolean(false)

@Deprecated("Deprecated in Java")
override fun doInBackground(vararg uploadParams: UploadParams?): UploadResult {
mParams = uploadParams[0]
res = UploadResult()
Thread {
try {
upload(mParams, res!!)
upload(mParams)
mParams!!.onUploadComplete?.onUploadComplete(res!!)
} catch (e: Exception) {
res!!.exception = e
Expand All @@ -35,7 +37,7 @@ class Uploader : AsyncTask<UploadParams?, IntArray?, UploadResult>() {
}

@Throws(Exception::class)
private fun upload(params: UploadParams?, result: UploadResult) {
private fun upload(params: UploadParams?) {
var connection: HttpURLConnection? = null
var request: DataOutputStream? = null
val crlf = "\r\n"
Expand Down Expand Up @@ -81,7 +83,7 @@ class Uploader : AsyncTask<UploadParams?, IntArray?, UploadResult>() {
name = map.getString("name")!!
filename = map.getString("filename")!!
filetype = map.getString("filetype") ?: getMimeType(map.getString("filepath"))
val file = File(map.getString("filepath"))
val file = File(map.getString("filepath")!!)
val fileLength = file.length()
totalFileLength += fileLength
if (!binaryStreamOnly) {
Expand Down Expand Up @@ -116,7 +118,7 @@ class Uploader : AsyncTask<UploadParams?, IntArray?, UploadResult>() {
if (!binaryStreamOnly) {
request.writeBytes(fileHeader[fileCount])
}
val file = File(map.getString("filepath"))
val file = File(map.getString("filepath")!!)
val fileLength = file.length()
val bufferSize = ceil((fileLength / 100f).toDouble()).toLong()
var bytesRead: Long = 0
Expand All @@ -139,10 +141,10 @@ class Uploader : AsyncTask<UploadParams?, IntArray?, UploadResult>() {
}
request.flush()
request.close()
if (connection.errorStream != null) {
responseStream = BufferedInputStream(connection.errorStream)
responseStream = if (connection.errorStream != null) {
BufferedInputStream(connection.errorStream)
} else {
responseStream = BufferedInputStream(connection.inputStream)
BufferedInputStream(connection.inputStream)
}
responseStreamReader = BufferedReader(InputStreamReader(responseStream))
val responseHeaders = Arguments.createMap()
Expand Down
2 changes: 1 addition & 1 deletion example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"lodash": "^4.17.21",
"react": "18.3.1",
"react-native": "0.76.0",
"react-native-windows": "0.75.6"
"react-native-windows": "0.75.7"
},
"devDependencies": {
"@babel/core": "^7.26.0",
Expand Down
53 changes: 25 additions & 28 deletions example/src/TestBaseMethods.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1002,34 +1002,31 @@ const tests: { [name: string]: StatusOrEvaluator } = {
res = await stat(`${path}${SEP}non-existing-file.txt`);
return 'fail';
} catch (e: any) {
if (Platform.OS === 'android') {
if (
!isMatch(e, {
code: 'EUNSPECIFIED',
message: 'File does not exist',
})
) {
return 'fail';
}
} else if (Platform.OS === 'windows') {
if (
!isMatch(e, {
code: 'ENOENT',
message: `ENOENT: no such file or directory, open ${path}${SEP}non-existing-file.txt`,
})
) {
return 'fail';
}
} else {
if (
!isMatch(e, {
code: 'NSCocoaErrorDomain:260',
message:
'The file “non-existing-file.txt” couldn’t be opened because there is no such file.',
})
) {
return 'fail';
}
switch (Platform.OS) {
case 'android':
if (
!isMatch(e, {
code: 'ENOENT',
message: 'ENOENT: no such file or directory, open \'/data/user/0/drpogodin.reactnativefs.example/cache/stat-test/non-existing-file.txt\'',
})
) return 'fail';
break;
case 'windows':
if (
!isMatch(e, {
code: 'ENOENT',
message: `ENOENT: no such file or directory, open ${path}${SEP}non-existing-file.txt`,
})
) return 'fail';
break;
default:
if (
!isMatch(e, {
code: 'NSCocoaErrorDomain:260',
message:
'The file “non-existing-file.txt” couldn’t be opened because there is no such file.',
})
) return 'fail';
}
}

Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dr.pogodin/react-native-fs",
"version": "2.29.0",
"version": "2.29.1",
"description": "Native filesystem access for React Native",
"source": "./src/index.ts",
"main": "./lib/commonjs/index.js",
Expand Down Expand Up @@ -70,7 +70,7 @@
"react": "18.3.1",
"react-native": "0.76.0",
"react-native-builder-bob": "^0.30.3",
"react-native-windows": "0.75.6",
"react-native-windows": "0.75.7",
"typescript": "^5.6.3"
},
"resolutions": {
Expand Down
Loading

0 comments on commit 5df8019

Please sign in to comment.