Skip to content

Commit

Permalink
fixed error with progressInterval. corrected types & ts config. remov…
Browse files Browse the repository at this point in the history
…ed percent from progress event. changed params to object in all events. updated readme. made onProgress starting on app start
  • Loading branch information
kesha-antonov committed Feb 16, 2024
1 parent 312c357 commit b1bede2
Show file tree
Hide file tree
Showing 13 changed files with 1,573 additions and 1,651 deletions.
495 changes: 0 additions & 495 deletions .eslintrc

This file was deleted.

10 changes: 9 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ module.exports = {
plugins: [
'react',
'react-hooks',
'jest',
'@typescript-eslint',
],
settings: {
react: {
Expand Down Expand Up @@ -63,9 +65,15 @@ module.exports = {
'no-class-assign': 'off',
'no-useless-escape': 'off',
curly: [2, 'multi', 'consistent'],
'react/prop-types': 'off', // TODO: TURN ON AND FIX ALL WARNINGS
'react/display-name': 'off',
'react-hooks/exhaustive-deps': ['warn', {
}],
},
overrides: [{
files: ['**/*.ts', '**/*.tsx'],
parser: '@typescript-eslint/parser',
extends: ['plugin:@typescript-eslint/recommended'],
}],
globals: {
describe: 'readonly',
test: 'readonly',
Expand Down
37 changes: 18 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,10 +111,10 @@ let task = download({
metadata: {}
}).begin(({ expectedBytes, headers }) => {
console.log(`Going to download ${expectedBytes} bytes!`)
}).progress(percent => {
console.log(`Downloaded: ${percent * 100}%`)
}).done(() => {
console.log('Download is done!')
}).progress(({ bytesDownloaded, bytesTotal }) => {
console.log(`Downloaded: ${bytesDownloaded / bytesTotal * 100}%`)
}).done(({ bytesDownloaded, bytesTotal }) => {
console.log('Download is done!', { bytesDownloaded, bytesTotal })

// PROCESS YOUR STUFF

Expand Down Expand Up @@ -148,10 +148,10 @@ import RNBackgroundDownloader from '@kesha-antonov/react-native-background-downl
let lostTasks = await RNBackgroundDownloader.checkForExistingDownloads()
for (let task of lostTasks) {
console.log(`Task ${task.id} was found!`)
task.progress(percent => {
console.log(`Downloaded: ${percent * 100}%`)
}).done(() => {
console.log('Download is done!')
task.progress(({ bytesDownloaded, bytesTotal }) => {
console.log(`Downloaded: ${bytesDownloaded / bytesTotal * 100}%`)
}).done(({ bytesDownloaded, bytesTotal }) => {
console.log('Download is done!', { bytesDownloaded, bytesTotal })
}).error(error => {
console.log('Download canceled due to error: ', error)
})
Expand Down Expand Up @@ -182,10 +182,10 @@ let task = RNBackgroundDownloader.download({
}
}).begin(({ expectedBytes, headers }) => {
console.log(`Going to download ${expectedBytes} bytes!`)
}).progress(percent => {
console.log(`Downloaded: ${percent * 100}%`)
}).done(() => {
console.log('Download is done!')
}).progress(({ bytesDownloaded, bytesTotal }) => {
console.log(`Downloaded: ${bytesDownloaded / bytesTotal * 100}%`)
}).done(({ bytesDownloaded, bytesTotal }) => {
console.log('Download is done!', { bytesDownloaded, bytesTotal })
}).error(error => {
console.log('Download canceled due to error: ', error)
})
Expand Down Expand Up @@ -243,7 +243,6 @@ A class representing a download task created by `RNBackgroundDownloader.download
| -------------- | ------ | ---------------------------------------------------------------------------------------------------- |
| `id` | String | The id you gave the task when calling `RNBackgroundDownloader.download` |
| `metadata` | Object | The metadata you gave the task when calling `RNBackgroundDownloader.download` |
| `percent` | Number | The current percent of completion of the task between 0 and 1 |
| `bytesDownloaded` | Number | The number of bytes currently written by the task |
| `bytesTotal` | Number | The number bytes expected to be written by this task or more plainly, the file size being downloaded |

Expand Down Expand Up @@ -304,12 +303,12 @@ Use these methods to stay updated on what's happening with the task.

All callback methods return the current instance of the `DownloadTask` for chaining.

| Function | Callback Arguments | Info |
| ---------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `begin` | { expectedBytes, headers } | Called when the first byte is received. 💡: this is good place to check if the device has enough storage space for this download |
| `progress` | percent, bytesDownloaded, bytesTotal | Called at max every 1.5s so you can update your progress bar accordingly |
| `done` | | Called when the download is done, the file is at the destination you've set |
| `error` | error | Called when the download stops due to an error |
| Function | Callback Arguments | Info|
| ---------- | --------------------------------- | ---- |
| `begin` | { expectedBytes, headers } | Called when the first byte is received. 💡: this is good place to check if the device has enough storage space for this download |
| `progress` | { bytesDownloaded, bytesTotal } | Called at max every 1.5s so you can update your progress bar accordingly |
| `done` | { bytesDownloaded, bytesTotal } | Called when the download is done, the file is at the destination you've set |
| `error` | { error, errorCode } | Called when the download stops due to an error |

### `pause()`
Pauses the download
Expand Down
11 changes: 3 additions & 8 deletions android/src/main/java/com/eko/OnProgress.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,12 @@ public class OnProgress extends Thread {
private Cursor cursor;
private int lastBytesDownloaded;
private int bytesTotal;
private int progressInterval = 300;

private RNBGDTaskConfig config;
private DeviceEventManagerModule.RCTDeviceEventEmitter ee;

public OnProgress(RNBGDTaskConfig config, long downloadId,
DeviceEventManagerModule.RCTDeviceEventEmitter ee, Downloader downloader, int progressInterval) {
DeviceEventManagerModule.RCTDeviceEventEmitter ee, Downloader downloader) {
this.config = config;

this.downloadId = downloadId;
Expand All @@ -34,9 +33,6 @@ public OnProgress(RNBGDTaskConfig config, long downloadId,

this.ee = ee;
this.downloader = downloader;
if (progressInterval > 0) {
this.progressInterval = progressInterval;
}
}

private void handleInterrupt() {
Expand All @@ -56,7 +52,7 @@ public void run() {
Log.d("RNBackgroundDownloader", "RNBD: OnProgress-1. downloadId " + downloadId);
while (downloadId > 0) {
try {
Log.d("RNBackgroundDownloader", "RNBD: OnProgress-2. downloadId " + downloadId);
Log.d("RNBackgroundDownloader", "RNBD: OnProgress-2. downloadId " + downloadId + " destination " + config.destination);

cursor = downloader.downloadManager.query(query);

Expand All @@ -77,7 +73,7 @@ public void run() {
Thread.sleep(1000);
} else {
Log.d("RNBackgroundDownloader", "RNBD: OnProgress-2.3. downloadId " + downloadId);
Thread.sleep(progressInterval);
Thread.sleep(config.progressInterval);
}

// get total bytes of the file
Expand All @@ -101,7 +97,6 @@ public void run() {
params.putString("id", config.id);
params.putInt("bytesDownloaded", (int) lastBytesDownloaded);
params.putInt("bytesTotal", (int) bytesTotal);
params.putDouble("percent", ((double) lastBytesDownloaded / bytesTotal));

HashMap<String, WritableMap> progressReports = new HashMap<>();
progressReports.put(config.id, params);
Expand Down
4 changes: 3 additions & 1 deletion android/src/main/java/com/eko/RNBGDTaskConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@ public class RNBGDTaskConfig implements Serializable {
public String destination;
public String metadata = "{}";
public boolean reportedBegin;
public int progressInterval;

public RNBGDTaskConfig(String id, String url, String destination, String metadata) {
public RNBGDTaskConfig(String id, String url, String destination, String metadata, int progressInterval) {
this.id = id;
this.url = url;
this.destination = destination;
this.metadata = metadata;
this.reportedBegin = false;
this.progressInterval = progressInterval;
}
}
129 changes: 65 additions & 64 deletions android/src/main/java/com/eko/RNBackgroundDownloaderModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ public void onReceive(Context context, Intent intent) {
WritableMap params = Arguments.createMap();
params.putString("id", config.id);
params.putString("location", config.destination);
params.putInt("bytesDownloaded", downloadStatus.getInt("bytesDownloaded"));
params.putInt("bytesTotal", downloadStatus.getInt("bytesTotal"));

ee.emit("downloadComplete", params);
break;
Expand Down Expand Up @@ -148,13 +150,20 @@ public void onReceive(Context context, Intent intent) {
public RNBackgroundDownloaderModule(ReactApplicationContext reactContext) {
super(reactContext);

ReadableMap emptyMap = Arguments.createMap();
this.initDownloader(emptyMap);
loadConfigMap();

downloader = new Downloader(reactContext);

IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
compatRegisterReceiver(reactContext, downloadReceiver, filter, true);

// iterate over downloadIdToConfig
for(Map.Entry<Long, RNBGDTaskConfig> entry : downloadIdToConfig.entrySet()) {
Long downloadId = entry.getKey();
RNBGDTaskConfig config = entry.getValue();

startReportingTasks(downloadId, config);
}
}

// TAKEN FROM
Expand Down Expand Up @@ -220,15 +229,6 @@ public Map<String, Object> getConstants() {
return constants;
}

@ReactMethod
public void initDownloader(ReadableMap options) {
Log.d(getName(), "RNBD: initDownloader");

loadConfigMap();

// TODO. MAYBE REINIT DOWNLOADER
}

private void removeFromMaps(long downloadId) {
Log.d(getName(), "RNBD: removeFromMaps");

Expand Down Expand Up @@ -291,7 +291,7 @@ public void download(ReadableMap options) {
return;
}

RNBGDTaskConfig config = new RNBGDTaskConfig(id, url, destination, metadata);
RNBGDTaskConfig config = new RNBGDTaskConfig(id, url, destination, metadata, progressInterval);
final Request request = new Request(Uri.parse(url));
request.setAllowedOverRoaming(isAllowedOverRoaming);
request.setAllowedOverMetered(isAllowedOverMetered);
Expand Down Expand Up @@ -333,52 +333,59 @@ public void download(ReadableMap options) {
return;
}

config.reportedBegin = true;
saveConfigMap();

Log.d(getName(), "RNBD: download-2 downloadId: " + downloadId);
// report begin & progress
//
// overlaped with thread to not block main thread
new Thread(new Runnable() {
public void run() {
try {
Log.d(getName(), "RNBD: download-3 downloadId: " + downloadId);

while (true) {
WritableMap downloadStatus = downloader.checkDownloadStatus(downloadId);
int status = downloadStatus.getInt("status");

Log.d(getName(), "RNBD: download-3.1 " + status + " downloadId: " + downloadId);

if (status == DownloadManager.STATUS_RUNNING) {
break;
}
if (status == DownloadManager.STATUS_FAILED || status == DownloadManager.STATUS_SUCCESSFUL) {
Log.d(getName(), "RNBD: download-3.2 " + status + " downloadId: " + downloadId);
Thread.currentThread().interrupt();
}
startReportingTasks(downloadId, config);
}
}

Thread.sleep(500);
private void startReportingTasks(Long downloadId, RNBGDTaskConfig config) {
Log.d(getName(), "RNBD: startReportingTasks-1 downloadId " + downloadId + " config.id " + config.id);
config.reportedBegin = true;
downloadIdToConfig.put(downloadId, config);
saveConfigMap();

Log.d(getName(), "RNBD: startReportingTasks-2 downloadId: " + downloadId);
// report begin & progress
//
// overlaped with thread to not block main thread
new Thread(new Runnable() {
public void run() {
try {
Log.d(getName(), "RNBD: startReportingTasks-3 downloadId: " + downloadId);

while (true) {
WritableMap downloadStatus = downloader.checkDownloadStatus(downloadId);
int status = downloadStatus.getInt("status");

Log.d(getName(), "RNBD: startReportingTasks-3.1 " + status + " downloadId: " + downloadId);

if (status == DownloadManager.STATUS_RUNNING) {
break;
}
if (status == DownloadManager.STATUS_FAILED || status == DownloadManager.STATUS_SUCCESSFUL) {
Log.d(getName(), "RNBD: startReportingTasks-3.2 " + status + " downloadId: " + downloadId);
Thread.currentThread().interrupt();
}

// EMIT BEGIN
OnBegin onBeginTh = new OnBegin(config, ee);
onBeginTh.start();
// wait for onBeginTh to finish
onBeginTh.join();

Log.d(getName(), "RNBD: download-4 downloadId: " + downloadId);
OnProgress onProgressTh = new OnProgress(config, downloadId, ee, downloader, progressInterval);
onProgressThreads.put(config.id, onProgressTh);
onProgressTh.start();
Log.d(getName(), "RNBD: download-5 downloadId: " + downloadId);
} catch (Exception e) {
Thread.sleep(500);
}

// EMIT BEGIN
OnBegin onBeginTh = new OnBegin(config, ee);
onBeginTh.start();
// wait for onBeginTh to finish
onBeginTh.join();

Log.d(getName(), "RNBD: startReportingTasks-4 downloadId: " + downloadId);
OnProgress onProgressTh = new OnProgress(config, downloadId, ee, downloader);
onProgressThreads.put(config.id, onProgressTh);
onProgressTh.start();
Log.d(getName(), "RNBD: startReportingTasks-5 downloadId: " + downloadId);
} catch (Exception e) {
Log.d(getName(), "RNBD: Runnable e: " + e.toString());
}
}).start();
Log.d(getName(), "RNBD: download-6 downloadId: " + downloadId);
}
}
}).start();
Log.d(getName(), "RNBD: startReportingTasks-6 downloadId: " + downloadId);
}

// TODO: NOT WORKING WITH DownloadManager FOR NOW
Expand Down Expand Up @@ -453,24 +460,18 @@ public void checkForExistingDownloads(final Promise promise) {

if (cursor.moveToFirst()) {
do {
WritableMap result = downloader.getDownloadStatus(cursor);
Long downloadId = Long.parseLong(result.getString("downloadId"));
WritableMap downloadStatus = downloader.getDownloadStatus(cursor);
Long downloadId = Long.parseLong(downloadStatus.getString("downloadId"));

if (downloadIdToConfig.containsKey(downloadId)) {
Log.d(getName(), "RNBD: checkForExistingDownloads-2");
RNBGDTaskConfig config = downloadIdToConfig.get(downloadId);
WritableMap params = Arguments.createMap();
params.putString("id", config.id);
params.putString("metadata", config.metadata);
params.putInt("state", stateMap.get(result.getInt("status")));

int bytesDownloaded = result.getInt("bytesDownloaded");
params.putInt("bytesDownloaded", bytesDownloaded);

int bytesTotal = result.getInt("bytesTotal");
params.putInt("bytesTotal", bytesTotal);

params.putDouble("percent", ((double) bytesDownloaded / bytesTotal));
params.putInt("state", stateMap.get(downloadStatus.getInt("status")));
params.putInt("bytesDownloaded", downloadStatus.getInt("bytesDownloaded"));
params.putInt("bytesTotal", downloadStatus.getInt("bytesTotal"));

foundIds.pushMap(params);

Expand Down
Loading

0 comments on commit b1bede2

Please sign in to comment.