Skip to content

Commit

Permalink
[WDB-019] - add possibility to save file by custom path
Browse files Browse the repository at this point in the history
  • Loading branch information
kirillzyusko committed Jul 6, 2020
1 parent dd99456 commit ed7fe60
Show file tree
Hide file tree
Showing 8 changed files with 71 additions and 46 deletions.
28 changes: 15 additions & 13 deletions android/src/main/java/io/wifi/p2p/FileServerAsyncTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
Expand All @@ -16,43 +17,44 @@
import static io.wifi.p2p.Utils.copyBytes;

/**
* Created by kiryl on 18.7.18.
* Created by Kiryl on 18.7.18.
* A simple server socket that accepts connection and writes some data on
* the stream.
*/
public class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
private Context context;
private static final String TAG = "RNWiFiP2P";
private Callback callback;
private String destination;

/**
* @param context
* @param callback
* @param destination
*/
public FileServerAsyncTask(Context context, Callback callback) {
this.context = context;
public FileServerAsyncTask(Context context, Callback callback, String destination) {
this.callback = callback;
this.destination = destination;
}

@Override
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
System.out.println("Server: Socket opened");
Log.i(TAG, "Server: Socket opened");
Socket client = serverSocket.accept();
System.out.println("Server: connection done");
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");
Log.i(TAG, "Server: connection done");
final File f = new File(destination);
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
System.out.println("server: copying files " + f.toString());
Log.i(TAG, "Server: copying files " + f.toString());
InputStream inputstream = client.getInputStream();
copyBytes(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
System.err.println(e.getMessage());
Log.e(TAG, e.getMessage());
return null;
}
}
Expand All @@ -63,7 +65,7 @@ protected String doInBackground(Void... params) {
@Override
protected void onPostExecute(String result) {
if (result != null) {
System.out.println("File copied - " + result);
Log.i(TAG, "File copied - " + result);
callback.invoke(result);
}
}
Expand All @@ -73,6 +75,6 @@ protected void onPostExecute(String result) {
*/
@Override
protected void onPreExecute() {
System.out.println("Opening a server socket");
Log.i(TAG, "Opening a server socket");
}
}
14 changes: 8 additions & 6 deletions android/src/main/java/io/wifi/p2p/FileTransferService.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import java.io.FileNotFoundException;
import java.io.IOException;
Expand All @@ -26,6 +27,7 @@ public class FileTransferService extends IntentService {
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";
private static final String TAG = "RNWiFiP2P";

public FileTransferService(String name) {
super(name);
Expand All @@ -45,27 +47,27 @@ protected void onHandleIntent(Intent intent) {
if (intent.getAction().equals(ACTION_SEND_FILE)) {
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
Socket socket = new Socket();

try {
System.out.println("Opening client socket - ");
Log.i(TAG, "Opening client socket - ");
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);

System.out.println("Client socket - " + socket.isConnected());
Log.i(TAG, "Client socket connected - " + socket.isConnected());
OutputStream stream = socket.getOutputStream();
ContentResolver cr = context.getContentResolver();
InputStream is = null;
try {
is = cr.openInputStream(Uri.parse(fileUri));
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
Log.e(TAG, e.getMessage());
}
copyBytes(is, stream);
System.out.println("Client: Data written");
Log.i(TAG, ("Client: Data written");
} catch (IOException e) {
System.err.println(e.getMessage());
Log.e(TAG, e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
Expand Down
11 changes: 7 additions & 4 deletions android/src/main/java/io/wifi/p2p/MessageServerAsyncTask.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package io.wifi.p2p;

import android.os.AsyncTask;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
Expand All @@ -17,6 +19,7 @@
* the stream.
*/
public class MessageServerAsyncTask extends AsyncTask<Void, Void, String> {
private static final String TAG = "RNWiFiP2P";
private Callback callback;

/**
Expand Down Expand Up @@ -44,9 +47,9 @@ protected String convertStreamToString(InputStream is) throws IOException {
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
System.out.println("Server: Socket opened");
Log.i(TAG, "Server: Socket opened");
Socket client = serverSocket.accept();
System.out.println("Server: connection done");
Log.i(TAG, "Server: connection done");

InputStream inputstream = client.getInputStream();
String result = convertStreamToString(inputstream);
Expand All @@ -55,7 +58,7 @@ protected String doInBackground(Void... params) {

return result;
} catch (IOException e) {
System.err.println(e.getMessage());
Log.e(TAG, e.getMessage());
return null;
}
}
Expand All @@ -66,6 +69,6 @@ protected String doInBackground(Void... params) {
*/
@Override
protected void onPreExecute() {
System.out.println("Opening a server socket");
Log.i(TAG, "Opening a server socket");
}
}
14 changes: 7 additions & 7 deletions android/src/main/java/io/wifi/p2p/MessageTransferService.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.IOException;
Expand All @@ -24,6 +25,7 @@ public class MessageTransferService extends IntentService {
public static final String EXTRAS_DATA = "message";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";
private static final String TAG = "RNWiFiP2P";

public MessageTransferService(String name) {
super(name);
Expand All @@ -39,26 +41,25 @@ public MessageTransferService() {
*/
@Override
protected void onHandleIntent(Intent intent) {

Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_MESSAGE)) {
String message = intent.getExtras().getString(EXTRAS_DATA);
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
Socket socket = new Socket();

try {
System.out.println("Opening client socket - ");
Log.i(TAG, "Opening client socket - ");
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);

System.out.println("Client socket - " + socket.isConnected());
Log.i(TAG, "Client socket connected - " + socket.isConnected());
OutputStream stream = socket.getOutputStream();
InputStream is = new ByteArrayInputStream(message.getBytes(Charset.forName(CHARSET)));
copyBytes(is, stream);
System.out.println("Client: Data written");
Log.i(TAG, "Client: Data written");
} catch (IOException e) {
System.err.println(e.getMessage());
Log.e(TAG, e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
Expand All @@ -71,7 +72,6 @@ protected void onHandleIntent(Intent intent) {
}
}
}

}
}
}
6 changes: 5 additions & 1 deletion android/src/main/java/io/wifi/p2p/Utils.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package io.wifi.p2p;

import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
Expand All @@ -10,6 +12,8 @@

public class Utils {
public static final String CHARSET = "UTF-8";
private static final String TAG = "RNWiFiP2P";

public static boolean copyBytes(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
Expand All @@ -20,7 +24,7 @@ public static boolean copyBytes(InputStream inputStream, OutputStream out) {
out.close();
inputStream.close();
} catch (IOException e) {
System.err.println(e.getMessage());
Log.e(TAG, e.getMessage());
return false;
}
return true;
Expand Down
15 changes: 15 additions & 0 deletions android/src/main/java/io/wifi/p2p/WiFiP2PBroadcastReceiver.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.util.Log;

import androidx.annotation.Nullable;

import com.facebook.react.bridge.ReactApplicationContext;
Expand Down Expand Up @@ -42,6 +45,18 @@ public void onReceive(Context context, Intent intent) {
if (networkInfo.isConnected()) {
manager.requestConnectionInfo(channel, connectionListener);
}
} else if (intent.getAction().equals(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION)) {
this.manager.requestGroupInfo(channel, new WifiP2pManager.GroupInfoListener() {
@Override
public void onGroupInfoAvailable(WifiP2pGroup group) {
if (group != null){
// clients require these
String ssid = group.getNetworkName();
String passphrase = group.getPassphrase();
Log.i("WIFIP2PEVENT", ssid + ", " + passphrase);
}
}
});
}
}

Expand Down
25 changes: 12 additions & 13 deletions android/src/main/java/io/wifi/p2p/WiFiP2PManagerModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.util.Log;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
Expand All @@ -34,6 +34,7 @@ public class WiFiP2PManagerModule extends ReactContextBaseJavaModule implements
private WifiP2pManager.Channel channel;
private ReactApplicationContext reactContext;
private final IntentFilter intentFilter = new IntentFilter();
private static final String TAG = "RNWiFiP2P";
private WiFiP2PDeviceMapper mapper = new WiFiP2PDeviceMapper();

public WiFiP2PManagerModule(ReactApplicationContext reactContext) {
Expand All @@ -56,7 +57,7 @@ public void getConnectionInfo(final Promise promise) {
manager.requestConnectionInfo(channel, new WifiP2pManager.ConnectionInfoListener() {
@Override
public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInformation) {
System.out.println(wifiP2pInformation);
Log.i(TAG, wifiP2pInformation.toString());

wifiP2pInfo = wifiP2pInformation;

Expand Down Expand Up @@ -112,13 +113,11 @@ public void isSuccessfulInitialize(Promise promise) {
public void createGroup(final Callback callback) {
manager.createGroup(channel, new WifiP2pManager.ActionListener() {
public void onSuccess() {
callback.invoke();
//Group creation successful
callback.invoke(); // Group creation successful
}

public void onFailure(int reason) {
callback.invoke(Integer.valueOf(reason));
//Group creation failed
callback.invoke(Integer.valueOf(reason)); // Group creation failed
}
});
}
Expand Down Expand Up @@ -216,11 +215,10 @@ public void onFailure(int reasonCode) {

@ReactMethod
public void sendFile(String filePath, Callback callback) {
// User has picked an image. Transfer it to group owner i.e peer using
// FileTransferService.
// User has picked a file. Transfer it to group owner i.e peer using FileTransferService
Uri uri = Uri.fromFile(new File(filePath));
System.out.println("Sending: " + uri);
System.out.println("Intent----------- " + uri);
Log.i(TAG, "Sending: " + uri);
Log.i(TAG, "Intent----------- " + uri);
Intent serviceIntent = new Intent(getCurrentActivity(), FileTransferService.class);
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
Expand All @@ -233,12 +231,13 @@ public void sendFile(String filePath, Callback callback) {
}

@ReactMethod
public void receiveFile(final Callback callback) {
public void receiveFile(String folder, String fileName, final Callback callback) {
final String destination = folder + fileName;
manager.requestConnectionInfo(channel, new WifiP2pManager.ConnectionInfoListener() {
@Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
if (info.groupFormed && info.isGroupOwner) {
new FileServerAsyncTask(getCurrentActivity(), callback)
new FileServerAsyncTask(getCurrentActivity(), callback, destination)
.execute();
} else if (info.groupFormed) {
// The other device acts as the client. In this case, we enable the
Expand All @@ -251,7 +250,7 @@ public void onConnectionInfoAvailable(WifiP2pInfo info) {

@ReactMethod
public void sendMessage(String message, Callback callback) {
System.out.println("Sending message: " + message);
Log.i(TAG, "Sending message: " + message);
Intent serviceIntent = new Intent(getCurrentActivity(), MessageTransferService.class);
serviceIntent.setAction(MessageTransferService.ACTION_SEND_MESSAGE);
serviceIntent.putExtra(MessageTransferService.EXTRAS_DATA, message);
Expand Down
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@ const sendFile = (pathToFile) => new Promise((resolve, reject) => {
});
});

const receiveFile = () => new Promise((resolve, reject) => {
WiFiP2PManager.receiveFile((pathToFile) => {
const receiveFile = (folder, fileName) => new Promise((resolve, reject) => {
WiFiP2PManager.receiveFile(folder, fileName, (pathToFile) => {
resolve(pathToFile);
});
});
Expand Down

0 comments on commit ed7fe60

Please sign in to comment.