Upload fix, Progress fix

- transfer one by one
This commit is contained in:
lionel
2022-02-24 16:05:05 +01:00
parent f6b652fb7e
commit d87296a534
7 changed files with 411 additions and 381 deletions

View File

@ -8,34 +8,34 @@ import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.provider.OpenableColumns;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.FileProvider;
import androidx.preference.PreferenceManager;
import com.google.android.material.snackbar.Snackbar;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.text.CharacterIterator;
import java.text.SimpleDateFormat;
import java.text.StringCharacterIterator;
import java.util.Date;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.List;
public class Transfer {
@ -81,7 +81,46 @@ public class Transfer {
public static final int STATE_SUCCESS = 130;
public static final int STATE_FAILED = 140;
public static boolean runningTransfer = false;
public static Thread thread = new Thread();
Integer id;
public String name;
public long size;
Timestamp addedTime;
Timestamp startedTime;
static List<Transfer> instances = new ArrayList<>();
public static List<Transfer> getInstances() {
List<Transfer> in = new ArrayList<>();
for (Transfer file: instances) {
//if(Arrays.asList(STATE_STANDBY, STATE_RUNNING, STATE_SUCCESS, STATE_FAILED).contains(file.state)) {
if(file.state == STATE_STANDBY ||
file.state == STATE_RUNNING ||
file.state == STATE_SUCCESS ||
file.state == STATE_FAILED) {
in.add(file);
}
}
//in.sort(Comparator.comparing(Transfer::getAddedTime).reversed());
in.sort(Comparator.comparing(e -> e.addedTime));
return in;
}
public static Transfer getFileById(int id) {
for (Object obj: instances) {
Transfer p = (Transfer) obj;
if (p.id == id) return p;
}
return null;
}
public Integer getId() {
return id;
}
public static void parameter(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
@ -106,20 +145,125 @@ public class Transfer {
public void AddTransfer() {
if(!runningTransfer) {
state = STATE_STANDBY;
addedTime = new Timestamp(System.currentTimeMillis());
Thread.State state = thread.getState();
if(state == Thread.State.NEW || state == Thread.State.TERMINATED) {
thread = new Thread(startTransfers);
thread.start();
/*Intent serviceIntent = new Intent(activity, TransferService.class);
ContextCompat.startForegroundService(activity, serviceIntent);*/
runningTransfer = true;
state = STATE_STANDBY;
new Thread(() -> StartTransfer()).start();
}
}
public void StartTransfer() {
int x = 35 + 65;
public void startTransfer() {
}
private static URL checkRedirection(URL url) throws IOException {
public static Runnable startTransfers = () -> {
try {
for (Transfer transfer : getInstances()) {
if (transfer.state == Transfer.STATE_STANDBY) {
transfer.startTransfer();
thread.run(); // restart thread for another potential standby transfer
break; // ignore remainder instance
}
}
} catch (ConcurrentModificationException e) {
e.printStackTrace();
}
/*Intent serviceIntent = new Intent(Transfer.activity, TransferService.class);
Transfer.activity.stopService(serviceIntent);*/
};
public void progressUpdateDelay() {
// Run only every second to reduce CPU usage
if (System.currentTimeMillis() > (savedTimeMillis + 1000)) {
savedTimeMillis = System.currentTimeMillis();
progressUpdate();
}
}
private void progressUpdate(){
loadedSI = Transfer.humanReadableByteCountBin(loaded);
activity.runOnUiThread(() -> {
try {
notifBuilder.setSmallIcon(R.drawable.ic_upload_and_download_from_the_cloud)
.setContentTitle(name)
.setContentText(String.format("%d%% %s/%s", percent, loadedSI, sizeSI))
.setProgress(100, (int) percent, false)
.setContentIntent(pendingIntent);
notifiManager.notify(Transfer.NOTIF_SERVICE, notifBuilder.build());
if (app_started && fragment_on)
showProgressFragment();
} catch (ConcurrentModificationException e) {
e.printStackTrace();
}
});
}
public void progressEnd() {
progressUpdate();
activity.runOnUiThread(() -> {
notifiManager.cancel(Transfer.NOTIF_SERVICE);
if (!app_started) {
notifBuilder.setSmallIcon(R.drawable.ic_upload_and_download_from_the_cloud)
.setContentTitle(name)
.setContentText(info)
.setProgress(0, 0, false)
.setContentIntent(pendingIntent);
notifiManager.notify(id, notifBuilder.build());
}
System.out.println(message);
/*Snackbar.make(Transfer.activity.findViewById(R.id.view_pager), tr.message, Snackbar.LENGTH_LONG)
.setAction("Action", null).show();*/
Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
});
}
public void showProgressFragment(){
LinearLayout groot = fragment_progress.findViewById(R.id.groot);
View progress = groot.findViewById(id);
if (progress == null) {
progress = inflater.inflate(R.layout.progress, null);
progress.setId(id);
final View final_progress = progress;
activity.runOnUiThread(() -> {
groot.addView(final_progress, 0);
});
}
((ProgressBar) progress.findViewById(R.id.progressBar)).setProgress((int) percent);
((ImageView) progress.findViewById(R.id.transferType)).setImageResource(drawable);
((TextView) progress.findViewById(R.id.progressText)).setText(percent + " %");
((TextView) progress.findViewById(R.id.fileName)).setText(name);
((TextView) progress.findViewById(R.id.fileSize)).setText(String.format("%s/%s", loadedSI, sizeSI));
if (state == Transfer.STATE_SUCCESS)
((TextView) progress.findViewById(R.id.fileName)).setTextColor(Color.GREEN);
else if (state == Transfer.STATE_FAILED)
((TextView) progress.findViewById(R.id.fileName)).setTextColor(Color.RED);
}
static URL checkRedirection(URL url) throws IOException {
String location = null;
HttpURLConnection conn = null;
int responseCode;
@ -160,149 +304,6 @@ public class Transfer {
return url;
}
public static void handleSendFile(Uri uri) {
if (uri != null) {
new Thread(() -> {
try {
Transfer.uploadFile(uri);
} catch (IOException e) {
final String ExceptionName = e.getClass().getSimpleName();
final String ExceptionMess = e.getMessage();
if(ExceptionName != null && ExceptionMess != null) {
Transfer.errorSnackbar(ExceptionMess);
}
}
}).start();
}
}
public static void handleSendText(String sharedText) {
if (sharedText != null) {
SimpleDateFormat sdfDate = new SimpleDateFormat("text_yyyyMMdd_HHmmss");
Date now = new Date();
String strDate = sdfDate.format(now);
new Thread(() -> {
try {
File outputFile = new File(activity.getCacheDir(), strDate + ".txt");
FileOutputStream fileOut = new FileOutputStream(outputFile);
OutputStreamWriter OutWriter = new OutputStreamWriter(fileOut);
OutWriter.append(sharedText);
OutWriter.close();
fileOut.flush();
fileOut.close();
Uri uri = FileProvider.getUriForFile(activity, activity.getPackageName(), outputFile);
Transfer.uploadFile(uri);
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
public static String uploadFile(Uri uri) throws IOException {
String message = null;
URL url = null;
HttpURLConnection conn = null;
DataOutputStream request = null;
String boundary = "*****";
final int maxBufferSize = 1 * 1024 * 1024;
byte[] buffer = new byte[maxBufferSize];
int bufferLength;
long loaded = 0;
Cursor cursor = activity.getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String type = activity.getContentResolver().getType(uri);
String fileName = null;
int col_name = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
if (col_name != -1)
fileName = cursor.getString(col_name);
if(fileName == null)
fileName = type.split("/")[0] + "_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + "." + type.split("/")[1];
String fileNameUTF8 = new String(fileName.getBytes(), StandardCharsets.ISO_8859_1);
long fileSize = -1;
int col_size = cursor.getColumnIndex(OpenableColumns.SIZE);
if (col_size != -1)
fileSize = cursor.getLong(col_size);
url = new URL(protocol, host, port, root + "/upload.php");
url = checkRedirection(url);
Log.d("URL", url.toString());
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setChunkedStreamingMode(maxBufferSize);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
conn.connect();
request = new DataOutputStream(conn.getOutputStream());
request.writeBytes("--" + boundary + "\r\n");
request.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileNameUTF8 + "\"\r\n");
request.writeBytes("Content-Type: " + type + "\r\n\r\n");
InputStream in = activity.getContentResolver().openInputStream(uri);
if (fileSize < 1)
fileSize = in.available();
//Progress p = new Progress(fileName, fileSize, Progress.UPLOAD);
while ((bufferLength = in.read(buffer)) > 0) {
request.write(buffer, 0, bufferLength);
loaded+= (long) bufferLength;
//p.loaded = loaded;
//p.percent = ((loaded * 100) / fileSize);
}
request.writeBytes("\r\n");
request.writeBytes("--" + boundary + "--\r\n");
in.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
message = "File " + fileName + " successful upload";
//p.stopProgress();
}
else {
String s = conn.getResponseMessage();
throw new HttpErrorException("error code: " + responseCode + " " + s);
}
request.flush();
request.close();
conn.disconnect();
System.out.println(message);
if (activity != null) {
String finalMessage = message;
activity.runOnUiThread(() ->
Snackbar.make(activity.findViewById(R.id.view_pager), finalMessage, Snackbar.LENGTH_LONG)
.setAction("Action", null).show());
}
return message;
}
public static String getFileList() throws IOException {
URL url = null;
HttpURLConnection conn = null;