Skip to content

Commit 7d32e45

Browse files
authored
feat: revive each background task according to its status (#17)
1 parent 1ad90b0 commit 7d32e45

File tree

2 files changed

+252
-34
lines changed

2 files changed

+252
-34
lines changed

src/index.ts

Lines changed: 57 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
completeHandler,
77
download,
88
DownloadTask,
9+
DownloadTaskState,
910
} from "react-native-background-downloader";
1011
import RNFS from "react-native-fs";
1112
import uuid from "react-uuid";
@@ -212,19 +213,7 @@ export default class DownloadQueue {
212213
this.isPausedByUser = !startActive;
213214

214215
// First revive tasks that were working in the background
215-
existingTasks.forEach(task => {
216-
const spec = this.specs.find(spec => spec.id === task.id);
217-
if (spec) {
218-
this.addTask(spec.url, task);
219-
if (this.active) {
220-
task.resume(); // Assuming checkForExistingDownloads() hasn't already
221-
} else {
222-
task.pause();
223-
}
224-
} else {
225-
task.stop();
226-
}
227-
});
216+
existingTasks.forEach(task => this.reviveTask(task));
228217

229218
// Now start downloads for specs that haven't finished
230219
const specsToDownload = this.specs.filter(
@@ -705,6 +694,61 @@ export default class DownloadQueue {
705694
}
706695
}
707696

697+
private reviveTask(task: DownloadTask) {
698+
const spec = this.specs.find(spec => spec.id === task.id);
699+
if (spec) {
700+
let shouldAddTask = true;
701+
702+
switch (task.state) {
703+
case DownloadTaskState.DOWNLOADING:
704+
// Since we're already downloading, make sure the client at least
705+
// gets a notification that it's started.
706+
this.handlers?.onBegin?.(spec.url, task.totalBytes);
707+
if (!this.active) {
708+
task.pause();
709+
}
710+
break;
711+
case DownloadTaskState.PAUSED:
712+
this.handlers?.onBegin?.(spec.url, task.totalBytes);
713+
if (this.active) {
714+
task.resume(); // Assuming checkForExistingDownloads() hasn't already
715+
}
716+
break;
717+
case DownloadTaskState.DONE:
718+
this.handlers?.onBegin?.(spec.url, task.totalBytes);
719+
this.handlers?.onDone?.(spec.url, spec.path);
720+
shouldAddTask = false;
721+
break;
722+
case DownloadTaskState.STOPPED:
723+
this.start(spec);
724+
shouldAddTask = false;
725+
break;
726+
case DownloadTaskState.FAILED:
727+
default:
728+
this.handlers?.onError?.(
729+
spec.url,
730+
"unknown error while backgrounded"
731+
);
732+
this.erroredIds.add(task.id);
733+
this.ensureErrorTimerOn();
734+
shouldAddTask = false;
735+
break;
736+
}
737+
738+
if (shouldAddTask) {
739+
this.addTask(spec.url, task);
740+
}
741+
} else {
742+
if (
743+
[DownloadTaskState.DOWNLOADING, DownloadTaskState.PAUSED].includes(
744+
task.state
745+
)
746+
) {
747+
task.stop();
748+
}
749+
}
750+
}
751+
708752
private async getDirFilenames() {
709753
try {
710754
return await RNFS.readdir(`${basePath()}/${this.domain}`);

0 commit comments

Comments
 (0)