Skip to content

Commit

Permalink
feat(android): add a status() method (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
iJimmyWei authored May 16, 2021
1 parent 7300ab3 commit 1144670
Show file tree
Hide file tree
Showing 2 changed files with 144 additions and 7 deletions.
129 changes: 127 additions & 2 deletions android/src/main/java/com/reactnativefilegateway/FileGatewayModule.kt
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
package com.reactnativefilegateway

import android.annotation.SuppressLint
import android.content.ContentResolver
import android.net.Uri
import android.os.Build
import android.util.Base64
import android.webkit.MimeTypeMap
import androidx.annotation.RequiresApi
import com.facebook.react.bridge.*
import java.io.File
import java.io.IOException
import java.net.URLConnection
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardCopyOption
import java.nio.file.attribute.BasicFileAttributes
import java.text.SimpleDateFormat
import java.util.*

enum class DirectoryType {
Expand Down Expand Up @@ -81,9 +89,126 @@ class FileGatewayModule(reactContext: ReactApplicationContext) : ReactContextBas
}
}

// fileExists(path: string, promise: Promise)
private fun File.getCreationTime(): String? {
try {
val path = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Paths.get(this.path)
} else {
return null
}

val creationTime = Files.getAttribute(path, "creationTime")
return creationTime.toString()
} catch (e: IOException) {
return null
}
}

private fun File.getLastAccessedTime(): String? {
try {
val path = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Paths.get(this.path)
} else {
return null
}

val attrs = Files.readAttributes(path, BasicFileAttributes::class.java)
val time = attrs.lastAccessTime()
return time.toString()
} catch (e: IOException) {
return null
}
}

private fun File.getMimeType(): String? {
if (this.isDirectory) {
return null
}

fun fallbackMimeType(uri: Uri): String? {
return if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
reactApplicationContext.contentResolver.getType(uri)
} else {
val extension = MimeTypeMap.getFileExtensionFromUrl(uri.toString())
MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase(Locale.getDefault()))
}
}

fun catchUrlMimeType(): String? {
val uri = Uri.fromFile(this)

return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val path = Paths.get(uri.toString())
try {
Files.probeContentType(path) ?: fallbackMimeType(uri)
} catch (ignored: IOException) {
fallbackMimeType(uri)
}
} else {
fallbackMimeType(uri)
}
}

val stream = this.inputStream()
return try {
URLConnection.guessContentTypeFromStream(stream) ?: catchUrlMimeType()
} catch (ignored: IOException) {
catchUrlMimeType()
} finally {
stream.close()
}
}

/**
* Retrieves the status of a file given it's [path]
*/
@ReactMethod
fun status(path: String, promise: Promise) {
try {
val file = File(path);
if (!file.exists()) {
throw Error("File does not exist")
}

val statusMap = Arguments.createMap()

val bytes = file.length()
statusMap.putInt("size", bytes.toInt())

// stat(path: string) - TO:DO
val mimeType = file.getMimeType()
statusMap.putString("mime", mimeType)

val nameWithoutExtension = file.nameWithoutExtension
val extension = file.extension
statusMap.putString("nameWithoutExtension", nameWithoutExtension)
statusMap.putString("extension", extension)

val lastModified = file.lastModified() // returns back as unix time
val lastModifiedDate = Date(lastModified)
val formattedLastModifiedDate = toISO8601UTC(lastModifiedDate)
statusMap.putString("lastModified", formattedLastModifiedDate)

val creationTime = file.getCreationTime()
statusMap.putString("creationTime", creationTime.toString())

val lastAccessedTime = file.getLastAccessedTime()
statusMap.putString("lastAccessedTime", lastAccessedTime)

promise.resolve(statusMap)
} catch (e: Throwable) {
promise.reject(e)
}
}

@SuppressLint("SimpleDateFormat")
fun toISO8601UTC(date: Date?): String? {
val tz = TimeZone.getTimeZone("UTC")

// Use SimpleDateFormat for maximum backwards compatibility
val df = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
df.timeZone = tz
return df.format(date)
}

///////////////////////////
// Directory Methods
Expand Down
22 changes: 17 additions & 5 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
import { NativeModules } from "react-native";

const { FileGateway } = NativeModules;
const { readFile, writeFile, listFiles, exists, deleteFile, isDirectory, moveDirectory }: RawFileGatewayType = FileGateway;
const { readFile, writeFile, listFiles, exists, deleteFile,
isDirectory, moveDirectory, status }: RawFileGatewayType = FileGateway;

// export type DirectoryType = "Application" | "Cache" | "External";

interface RawStatus {
size: number;
mimeType?: string;
extension: string;
nameWithoutExtension: string;
lastModified: string;
creationTime?: string; // API Level 26 and above only
lastAccessedTime?: string; // API Level 26 and above only
}

type RawFileGatewayType = {
// File operations
readFile(path: string, encoding: Encoding): Promise<string>; //to:do encoding opt
writeFile(fileName: string, data: string, intention: string): Promise<string>; //to:do encoding opt
deleteFile(path: string): Promise<boolean>;

status(path: string): Promise<RawStatus>;

// Directory operations
listFiles(path: string, recursive: boolean): Promise<string[]>;
Expand All @@ -21,12 +32,12 @@ type RawFileGatewayType = {
exists(path: string): Promise<boolean>;
};

export function listFilesGateway(path: string, recursive?: boolean): Promise<string[]> {
function listFilesGateway(path: string, recursive?: boolean): Promise<string[]> {
return listFiles(path, recursive ?? false);
}

export type Encoding = "utf-8" | "base64";
export function readFileGateway(path: string, encoding?: Encoding): Promise<string> {
function readFileGateway(path: string, encoding?: Encoding): Promise<string> {
const defaultEncoding: Encoding = "utf-8";

return readFile(path, encoding ?? defaultEncoding);
Expand All @@ -49,7 +60,8 @@ const fileGateway: FileGatewayType = {
exists,
isDirectory,
moveDirectory,
deleteFile
deleteFile,
status
};

export default fileGateway;

0 comments on commit 1144670

Please sign in to comment.