Skip to content

Commit

Permalink
task cancellation bug fix
Browse files Browse the repository at this point in the history
  • Loading branch information
onikiri2007 committed Sep 20, 2019
1 parent a2f65a5 commit 8f3551e
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 63 deletions.
105 changes: 49 additions & 56 deletions android/src/main/java/com/bluechilli/flutteruploader/UploadWorker.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ public class UploadWorker extends Worker implements CountProgressListener {
private int lastNotificationProgress = 0;
private String tag;
private int primaryId;
private Call call;
private boolean isCancelled = false;

public UploadWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
Expand Down Expand Up @@ -200,7 +202,7 @@ public Result doWork() {
.readTimeout((long) timeout, TimeUnit.SECONDS)
.build();

Call call = client.newCall(request);
call = client.newCall(request);
Response response = call.execute();
String responseString = response.body().string();
statusCode = response.code();
Expand Down Expand Up @@ -261,65 +263,38 @@ public Result doWork() {
return Result.success(outputData);

} catch (JsonIOException ex) {
ex.printStackTrace();

if (showNotification) {
updateNotification(context, tag, UploadStatus.FAILED, 0, null);
}

return Result.failure(
createOutputErrorData(
UploadStatus.FAILED,
500,
"json_error",
ex.toString(),
getStacktraceAsStringList(ex.getStackTrace())));

return handleException(context, ex, "json_error");
} catch (UnknownHostException ex) {
ex.printStackTrace();

if (showNotification) {
updateNotification(context, tag, UploadStatus.FAILED, 0, null);
}

return Result.failure(
createOutputErrorData(
UploadStatus.FAILED,
500,
"unknown_host",
ex.toString(),
getStacktraceAsStringList(ex.getStackTrace())));
return handleException(context, ex, "unknown_host");
} catch (IOException ex) {
return handleException(context, ex, "io_error");
} catch (Exception ex) {
return handleException(context, ex, "upload error");
}
}

ex.printStackTrace();
private Result handleException(Context context,
Exception ex,
String code) {

if (showNotification) {
updateNotification(context, tag, UploadStatus.FAILED, 0, null);
}
ex.printStackTrace();

return Result.failure(
createOutputErrorData(
UploadStatus.FAILED,
500,
"io_error",
ex.toString(),
getStacktraceAsStringList(ex.getStackTrace())));
} catch (Exception ex) {

ex.printStackTrace();
int finalStatus= isCancelled ? UploadStatus.CANCELED : UploadStatus.FAILED;
String finalCode = isCancelled ? "upload_cancelled" : code;

if (showNotification) {
updateNotification(context, tag, UploadStatus.FAILED, 0, null);
}

return Result.failure(
createOutputErrorData(
UploadStatus.FAILED,
500,
"upload_error",
ex.toString(),
getStacktraceAsStringList(ex.getStackTrace())));
if (showNotification) {
updateNotification(context, tag, finalStatus, 0, null);
}

return Result.failure(
createOutputErrorData(
finalStatus,
500,
finalCode,
ex.toString(),
getStacktraceAsStringList(ex.getStackTrace())));

}

private String GetMimeType(String url) {
Expand Down Expand Up @@ -394,6 +369,7 @@ public void OnProgress(String taskId, long bytesWritten, long contentLength) {
+ ", lastProgress: "
+ lastProgress);
if (running) {

Context context = getApplicationContext();
sendUpdateProcessEvent(context, UploadStatus.RUNNING, progress);
boolean shouldSendNotification = isRunning(progress, lastNotificationProgress, 10);
Expand All @@ -406,6 +382,21 @@ public void OnProgress(String taskId, long bytesWritten, long contentLength) {
}
}

@Override
public void onStopped() {
super.onStopped();
Log.d(TAG, "UploadWorker - Stopped");
try {
isCancelled = true;
if(call != null && !call.isCanceled()) {
call.cancel();
}
}
catch (Exception ex) {
Log.d(TAG, "Upload Request cancelled", ex);
}
}

@Override
public void OnError(String taskId, String code, String message) {
Log.d(
Expand All @@ -419,6 +410,7 @@ public void OnError(String taskId, String code, String message) {
sendUpdateProcessEvent(getApplicationContext(), UploadStatus.FAILED, -1);
}


private void buildNotification(Context context) {
// Make a channel if necessary
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Expand Down Expand Up @@ -480,21 +472,22 @@ private void updateNotification(
}
}


private boolean isRunning(int currentProgress, int previousProgress, int step) {
int prev = previousProgress + step;
return (currentProgress == 0 || currentProgress > prev || currentProgress >= 100)
&& currentProgress != previousProgress;
}

private String[] getStacktraceAsStringList(StackTraceElement[] stacktraces) {
private String[] getStacktraceAsStringList(StackTraceElement[] stacktrace) {
List<String> output = new ArrayList<>();

if (stacktraces == null || (stacktraces != null && stacktraces.length == 0)) {
if (stacktrace == null || stacktrace.length == 0) {
return null;
}

for (StackTraceElement stacktrace : stacktraces) {
output.add(stacktrace.toString());
for (StackTraceElement stackTraceElement : stacktrace) {
output.add(stackTraceElement.toString());
}

return output.toArray(new String[0]);
Expand Down
8 changes: 8 additions & 0 deletions example/ios/Flutter/flutter_export_environment.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/bin/sh
# This is a generated file; do not edit or check into version control.
export "FLUTTER_ROOT=/Users/onikiri/Flutter/flutter"
export "FLUTTER_APPLICATION_PATH=/Users/onikiri/Flutter/flutter_uploader/example"
export "FLUTTER_TARGET=lib/main.dart"
export "FLUTTER_BUILD_DIR=build"
export "SYMROOT=${SOURCE_ROOT}/../build/ios"
export "FLUTTER_FRAMEWORK_DIR=/Users/onikiri/Flutter/flutter/bin/cache/artifacts/engine/ios"
28 changes: 21 additions & 7 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,27 @@ class UploadItem {
final String id;
final String tag;
final MediaType type;
int progress;
UploadTaskStatus status;
final int progress;
final UploadTaskStatus status;
UploadItem({
this.id,
this.tag,
this.type,
this.progress = 0,
this.status = UploadTaskStatus.undefined,
});

UploadItem copyWith({UploadTaskStatus status, int progress}) => UploadItem(
id: this.id,
tag: this.tag,
type: this.type,
status: status ?? this.status,
progress: progress ?? this.progress);

bool isCompleted() =>
this.status == UploadTaskStatus.canceled ||
this.status == UploadTaskStatus.complete ||
this.status == UploadTaskStatus.failed;
}

enum MediaType { Image, Video }
Expand All @@ -76,12 +88,13 @@ class _UploadScreenState extends State<UploadScreen> {
void initState() {
super.initState();
_progressSubscription = uploader.progress.listen((progress) {
print("progress: ${progress.progress} , tag: ${progress.tag}");
final task = _tasks[progress.tag];
print("progress: ${progress.progress} , tag: ${progress.tag}");
if (task == null) return;
if (task.isCompleted()) return;
setState(() {
task.progress = progress.progress;
task.status = progress.status;
_tasks[progress.tag] =
task.copyWith(progress: progress.progress, status: progress.status);
});
});
_resultSubscription = uploader.result.listen((result) {
Expand All @@ -92,7 +105,7 @@ class _UploadScreenState extends State<UploadScreen> {
if (task == null) return;

setState(() {
task.status = result.status;
_tasks[result.tag] = task.copyWith(status: result.status);
});
}, onError: (ex, stacktrace) {
print("exception: $ex");
Expand All @@ -102,7 +115,7 @@ class _UploadScreenState extends State<UploadScreen> {
if (task == null) return;

setState(() {
task.status = exp.status;
_tasks[exp.tag] = task.copyWith(status: exp.status);
});
});
}
Expand Down Expand Up @@ -150,6 +163,7 @@ class _UploadScreenState extends State<UploadScreen> {
itemCount: _tasks.length,
itemBuilder: (context, index) {
final item = _tasks.values.elementAt(index);
print("${item.tag} - ${item.status}");
return UploadItemView(
item: item,
onCancel: cancelUpload,
Expand Down

0 comments on commit 8f3551e

Please sign in to comment.