diff --git a/.idea/deploymentTargetDropDown.xml b/.idea/deploymentTargetDropDown.xml
new file mode 100644
index 0000000..7d3a33c
--- /dev/null
+++ b/.idea/deploymentTargetDropDown.xml
@@ -0,0 +1,17 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/libs/mobile.aar b/app/libs/mobile.aar
index 7161d9c..30a259f 100644
Binary files a/app/libs/mobile.aar and b/app/libs/mobile.aar differ
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 947c18b..0105875 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -4,7 +4,10 @@
package="com.peernet.test">
-
+
diff --git a/app/src/main/java/com/peernet/test/FileUtils.java b/app/src/main/java/com/peernet/test/FileUtils.java
new file mode 100644
index 0000000..8d688d5
--- /dev/null
+++ b/app/src/main/java/com/peernet/test/FileUtils.java
@@ -0,0 +1,373 @@
+package com.peernet.test;
+
+import android.annotation.SuppressLint;
+import android.content.ContentUris;
+import android.content.Context;
+import android.database.Cursor;
+import android.net.Uri;
+import android.os.Build;
+import android.os.Environment;
+import android.provider.DocumentsContract;
+import android.provider.MediaStore;
+import android.provider.OpenableColumns;
+import android.text.TextUtils;
+import android.util.Log;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.util.List;
+
+public class FileUtils {
+ private static Uri contentUri = null;
+
+ /**
+ * Get a file path from a Uri. This will get the the path for Storage Access
+ * Framework Documents, as well as the _data field for the MediaStore and
+ * other file-based ContentProviders.
+ *
+ * Callers should check whether the path is local before assuming it
+ * represents a local file.
+ *
+ * @param context The context.
+ * @param uri The Uri to query.
+ */
+ @SuppressLint("NewApi")
+ public static String getPath(final Context context, final Uri uri) {
+ // check here to KITKAT or new version
+ final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
+ String selection = null;
+ String[] selectionArgs = null;
+ // DocumentProvider
+ if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
+ // ExternalStorageProvider
+ if (isExternalStorageDocument(uri)) {
+ final String docId = DocumentsContract.getDocumentId(uri);
+ final String[] split = docId.split(":");
+ final String type = split[0];
+
+ String fullPath = getPathFromExtSD(split);
+ if (fullPath != "") {
+ return fullPath;
+ } else {
+ return null;
+ }
+ }
+
+ // DownloadsProvider
+ else if (isDownloadsDocument(uri)) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ final String id;
+ Cursor cursor = null;
+ try {
+ cursor = context.getContentResolver().query(uri, new String[]{MediaStore.MediaColumns.DISPLAY_NAME}, null, null, null);
+ if (cursor != null && cursor.moveToFirst()) {
+ String fileName = cursor.getString(0);
+ String path = Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
+ if (!TextUtils.isEmpty(path)) {
+ return path;
+ }
+ }
+ } finally {
+ if (cursor != null)
+ cursor.close();
+ }
+ id = DocumentsContract.getDocumentId(uri);
+ if (!TextUtils.isEmpty(id)) {
+ if (id.startsWith("raw:")) {
+ return id.replaceFirst("raw:", "");
+ }
+ String[] contentUriPrefixesToTry = new String[]{
+ "content://downloads/public_downloads",
+ "content://downloads/my_downloads"
+ };
+ for (String contentUriPrefix : contentUriPrefixesToTry) {
+ try {
+ final Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
+
+ /* final Uri contentUri = ContentUris.withAppendedId(
+ Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));*/
+
+ return getDataColumn(context, contentUri, null, null);
+ } catch (NumberFormatException e) {
+ //In Android 8 and Android P the id is not a number
+ return uri.getPath().replaceFirst("^/document/raw:", "").replaceFirst("^raw:", "");
+ }
+ }
+
+
+ }
+
+ } else {
+ final String id = DocumentsContract.getDocumentId(uri);
+ final boolean isOreo = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O;
+ if (id.startsWith("raw:")) {
+ return id.replaceFirst("raw:", "");
+ }
+ try {
+ contentUri = ContentUris.withAppendedId(
+ Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
+
+ } catch (NumberFormatException e) {
+ e.printStackTrace();
+ }
+ if (contentUri != null) {
+ return getDataColumn(context, contentUri, null, null);
+ }
+ }
+
+
+ }
+ // MediaProvider
+ else if (isMediaDocument(uri)) {
+ final String docId = DocumentsContract.getDocumentId(uri);
+ final String[] split = docId.split(":");
+ final String type = split[0];
+
+ Uri contentUri = null;
+
+ if ("image".equals(type)) {
+ contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
+ } else if ("video".equals(type)) {
+ contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
+ } else if ("audio".equals(type)) {
+ contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
+ }
+ selection = "_id=?";
+ selectionArgs = new String[]{split[1]};
+
+
+ return getDataColumn(context, contentUri, selection,
+ selectionArgs);
+ } else if (isGoogleDriveUri(uri)) {
+ return getDriveFilePath(uri, context);
+ }
+ }
+
+
+ // MediaStore (and general)
+ else if ("content".equalsIgnoreCase(uri.getScheme())) {
+
+ if (isGooglePhotosUri(uri)) {
+ return uri.getLastPathSegment();
+ }
+
+ if (isGoogleDriveUri(uri)) {
+ return getDriveFilePath(uri, context);
+ }
+ if( Build.VERSION.SDK_INT == Build.VERSION_CODES.N)
+ {
+ // return getFilePathFromURI(context,uri);
+ return getMediaFilePathForN(uri, context);
+ // return getRealPathFromURI(context,uri);
+ }else
+ {
+
+ return getDataColumn(context, uri, null, null);
+ }
+
+
+ }
+ // File
+ else if ("file".equalsIgnoreCase(uri.getScheme())) {
+ return uri.getPath();
+ }
+
+ return null;
+ }
+
+ /**
+ * Check if a file exists on device
+ *
+ * @param filePath The absolute file path
+ */
+ private static boolean fileExists(String filePath) {
+ File file = new File(filePath);
+
+ return file.exists();
+ }
+
+
+ /**
+ * Get full file path from external storage
+ *
+ * @param pathData The storage type and the relative path
+ */
+ private static String getPathFromExtSD(String[] pathData) {
+ final String type = pathData[0];
+ final String relativePath = "/" + pathData[1];
+ String fullPath = "";
+
+ // on my Sony devices (4.4.4 & 5.1.1), `type` is a dynamic string
+ // something like "71F8-2C0A", some kind of unique id per storage
+ // don't know any API that can get the root path of that storage based on its id.
+ //
+ // so no "primary" type, but let the check here for other devices
+ if ("primary".equalsIgnoreCase(type)) {
+ fullPath = Environment.getExternalStorageDirectory() + relativePath;
+ if (fileExists(fullPath)) {
+ return fullPath;
+ }
+ }
+
+ // Environment.isExternalStorageRemovable() is `true` for external and internal storage
+ // so we cannot relay on it.
+ //
+ // instead, for each possible path, check if file exists
+ // we'll start with secondary storage as this could be our (physically) removable sd card
+ fullPath = System.getenv("SECONDARY_STORAGE") + relativePath;
+ if (fileExists(fullPath)) {
+ return fullPath;
+ }
+
+ fullPath = System.getenv("EXTERNAL_STORAGE") + relativePath;
+ if (fileExists(fullPath)) {
+ return fullPath;
+ }
+
+ return fullPath;
+ }
+
+ private static String getDriveFilePath(Uri uri, Context context) {
+ Uri returnUri = uri;
+ Cursor returnCursor = context.getContentResolver().query(returnUri, 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.
+ * */
+ int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
+ int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
+ returnCursor.moveToFirst();
+ String name = (returnCursor.getString(nameIndex));
+ String size = (Long.toString(returnCursor.getLong(sizeIndex)));
+ File file = new File(context.getCacheDir(), name);
+ try {
+ InputStream inputStream = context.getContentResolver().openInputStream(uri);
+ FileOutputStream outputStream = new FileOutputStream(file);
+ int read = 0;
+ int maxBufferSize = 1 * 1024 * 1024;
+ int bytesAvailable = inputStream.available();
+
+ //int bufferSize = 1024;
+ int bufferSize = Math.min(bytesAvailable, maxBufferSize);
+
+ final byte[] buffers = new byte[bufferSize];
+ while ((read = inputStream.read(buffers)) != -1) {
+ outputStream.write(buffers, 0, read);
+ }
+ Log.e("File Size", "Size " + file.length());
+ inputStream.close();
+ outputStream.close();
+ Log.e("File Path", "Path " + file.getPath());
+ Log.e("File Size", "Size " + file.length());
+ } catch (Exception e) {
+ Log.e("Exception", e.getMessage());
+ }
+ return file.getPath();
+ }
+
+ private static String getMediaFilePathForN(Uri uri, Context context) {
+ Uri returnUri = uri;
+ Cursor returnCursor = context.getContentResolver().query(returnUri, 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.
+ * */
+ int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
+ int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
+ returnCursor.moveToFirst();
+ String name = (returnCursor.getString(nameIndex));
+ String size = (Long.toString(returnCursor.getLong(sizeIndex)));
+ File file = new File(context.getFilesDir(), name);
+ try {
+ InputStream inputStream = context.getContentResolver().openInputStream(uri);
+ FileOutputStream outputStream = new FileOutputStream(file);
+ int read = 0;
+ int maxBufferSize = 1 * 1024 * 1024;
+ int bytesAvailable = inputStream.available();
+
+ //int bufferSize = 1024;
+ int bufferSize = Math.min(bytesAvailable, maxBufferSize);
+
+ final byte[] buffers = new byte[bufferSize];
+ while ((read = inputStream.read(buffers)) != -1) {
+ outputStream.write(buffers, 0, read);
+ }
+ Log.e("File Size", "Size " + file.length());
+ inputStream.close();
+ outputStream.close();
+ Log.e("File Path", "Path " + file.getPath());
+ Log.e("File Size", "Size " + file.length());
+ } catch (Exception e) {
+ Log.e("Exception", e.getMessage());
+ }
+ return file.getPath();
+ }
+
+
+ private static String getDataColumn(Context context, Uri uri,
+ String selection, String[] selectionArgs) {
+ Cursor cursor = null;
+ final String column = "_data";
+ final String[] projection = {column};
+
+ try {
+ cursor = context.getContentResolver().query(uri, projection,
+ selection, selectionArgs, null);
+
+ if (cursor != null && cursor.moveToFirst()) {
+ final int index = cursor.getColumnIndexOrThrow(column);
+ return cursor.getString(index);
+ }
+ } finally {
+ if (cursor != null)
+ cursor.close();
+ }
+
+ return null;
+ }
+
+ /**
+ * @param uri - The Uri to check.
+ * @return - Whether the Uri authority is ExternalStorageProvider.
+ */
+ private static boolean isExternalStorageDocument(Uri uri) {
+ return "com.android.externalstorage.documents".equals(uri.getAuthority());
+ }
+
+ /**
+ * @param uri - The Uri to check.
+ * @return - Whether the Uri authority is DownloadsProvider.
+ */
+ private static boolean isDownloadsDocument(Uri uri) {
+ return "com.android.providers.downloads.documents".equals(uri.getAuthority());
+ }
+
+ /**
+ * @param uri - The Uri to check.
+ * @return - Whether the Uri authority is MediaProvider.
+ */
+ private static boolean isMediaDocument(Uri uri) {
+ return "com.android.providers.media.documents".equals(uri.getAuthority());
+ }
+
+ /**
+ * @param uri - The Uri to check.
+ * @return - Whether the Uri authority is Google Photos.
+ */
+ private static boolean isGooglePhotosUri(Uri uri) {
+ return "com.google.android.apps.photos.content".equals(uri.getAuthority());
+ }
+
+
+ /**
+ * @param uri The Uri to check.
+ * @return Whether the Uri authority is Google Drive.
+ */
+ private static boolean isGoogleDriveUri(Uri uri) {
+ return "com.google.android.apps.docs.storage".equals(uri.getAuthority()) || "com.google.android.apps.docs.storage.legacy".equals(uri.getAuthority());
+ }
+
+
+}
diff --git a/app/src/main/java/com/peernet/test/MainActivity.kt b/app/src/main/java/com/peernet/test/MainActivity.kt
index 8b2a29c..ba26ee5 100644
--- a/app/src/main/java/com/peernet/test/MainActivity.kt
+++ b/app/src/main/java/com/peernet/test/MainActivity.kt
@@ -2,6 +2,7 @@ package com.peernet.test
import android.Manifest
import android.content.ContentValues.TAG
+import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
@@ -41,6 +42,15 @@ import com.android.volley.toolbox.JsonRequest
import org.json.JSONArray
import org.json.JSONObject
import org.json.JSONTokener
+import android.net.NetworkInfo
+
+import android.net.ConnectivityManager
+import android.widget.Toast
+import androidx.annotation.RequiresApi
+import androidx.core.net.toFile
+import androidx.core.net.toUri
+import java.nio.file.Files
+import java.nio.file.Paths
class MainActivity : AppCompatActivity() {
@@ -55,6 +65,15 @@ class MainActivity : AppCompatActivity() {
Mobile.mobileMain(this.filesDir.absolutePath)
+ if (isNetwork(this)){
+
+ Toast.makeText(this, "Internet Connected", Toast.LENGTH_SHORT).show()
+
+ } else {
+
+ Toast.makeText(this, "Internet Is Not Connected", Toast.LENGTH_SHORT).show()
+ }
+
val queue = Volley.newRequestQueue(this)
Timer().schedule(500){
@@ -208,13 +227,31 @@ class MainActivity : AppCompatActivity() {
// })
// }
+ @RequiresApi(Build.VERSION_CODES.O)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val queue = Volley.newRequestQueue(this)
if (requestCode == 777) {
- var filePath = data?.data?.path
+ var filePath = data?.data?.isAbsolute
+
+ val path = FileUtils.getPath(this, data?.data)
+
+ Log.d("path",path.toString())
+
+ // convert Path string to URI
+ val pathUri = path.toUri()
+
+ // convert file to bytes
+
+ var encoded: ByteArray
+ // try {
+ encoded = Files.readAllBytes(Paths.get(path))
+ Log.d("bytes", encoded.toString())
+// } catch (e: IOException) {
+// Log.d("bytes", e.toString())
+// }
// data?.data
@@ -256,7 +293,7 @@ class MainActivity : AppCompatActivity() {
// Log.d("myTag", errorresponse.toString());
// })
- val url2 = "http://127.0.0.1:5125/warehouse/create/path?path=" + java.net.URLEncoder.encode("/sdcard/Download/readingSmalltalk.pdf", "utf-8")
+ val url2 = "http://127.0.0.1:5125/warehouse/create/path?path=" + java.net.URLEncoder.encode(path, "utf-8")
val stringRequest2 = StringRequest(
Request.Method.GET, url2,
@@ -281,10 +318,10 @@ class MainActivity : AppCompatActivity() {
jsonobj.put("hash", ResponseObject.get("hash"))
jsonobj.put("type", 5)
jsonobj.put("format", 1)
- jsonobj.put("size", 2500)
- jsonobj.put("name", "readingSmalltalk.pdf")
- jsonobj.put("folder", "/sdcard/Download/")
- jsonobj.put("description", "I can C++ and Java But I can't read smalltalk")
+ jsonobj.put("size", encoded.size.toString())
+ jsonobj.put("name", path.substring(path.lastIndexOf("/")+1))
+ jsonobj.put("folder", path)
+ jsonobj.put("description", "")
val jsonArrayObj = JSONArray()
@@ -344,6 +381,15 @@ class MainActivity : AppCompatActivity() {
}
}
+ fun isNetwork(context: Context): Boolean {
+ val cm = context
+ .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
+ val netInfo = cm.activeNetworkInfo
+ return if (netInfo != null && netInfo.isConnectedOrConnecting) {
+ true
+ } else false
+ }
+
private fun getRealPathFromURI(contentURI: Uri): String? {
val result: String
val cursor: Cursor? = contentResolver.query(contentURI, null, null, null, null)
@@ -358,6 +404,19 @@ class MainActivity : AppCompatActivity() {
return result
}
+ @JvmName("getRealPathFromURI1")
+ fun getRealPathFromURI(contentUri: Uri?): String? {
+ var res: String? = null
+ val proj = arrayOf(MediaStore.Images.Media.DATA)
+ val cursor = contentResolver.query(contentUri!!, proj, null, null, null)
+ if (null != cursor && cursor.moveToFirst()) {
+ val column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
+ res = cursor.getString(column_index)
+ cursor.close()
+ }
+ return res
+ }
+
private fun requestAppPermissions() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return
diff --git a/app/src/main/java/com/peernet/test/Search.kt b/app/src/main/java/com/peernet/test/Search.kt
index bd043f7..8faee36 100644
--- a/app/src/main/java/com/peernet/test/Search.kt
+++ b/app/src/main/java/com/peernet/test/Search.kt
@@ -213,7 +213,7 @@ class Search : AppCompatActivity() {
// Get download path for the android phone
val DownloadPath = "/data/local/tmp"
- Log.d("myTag", DownloadPath.toString());
+ Log.d("download path", DownloadPath.toString());
// Get request URL to download the file
val DownloadURL = "http://127.0.0.1:5125/download/start?path=test.txt" + "&hash=" + FileHash + "&node=" + NodeID