@kesha-antonov/react-native-background-downloader 4.5.6 → 4.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +5 -1
  2. package/android/src/main/java/com/eko/DownloadConstants.kt +7 -0
  3. package/android/src/main/java/com/eko/Downloader.kt +80 -111
  4. package/android/src/main/java/com/eko/PromiseExtensions.kt +36 -0
  5. package/android/src/main/java/com/eko/RNBGDTaskConfig.kt +4 -1
  6. package/android/src/main/java/com/eko/RNBackgroundDownloaderModuleImpl.kt +102 -144
  7. package/android/src/main/java/com/eko/ResumableDownloadService.kt +153 -37
  8. package/android/src/main/java/com/eko/ResumableDownloader.kt +66 -12
  9. package/android/src/main/java/com/eko/UIDTDownloadJobService.kt +25 -4
  10. package/android/src/main/java/com/eko/UnmeteredNetworkGate.kt +366 -0
  11. package/android/src/main/java/com/eko/uidt/UIDTJobManager.kt +76 -14
  12. package/android/src/main/java/com/eko/uidt/UIDTJobState.kt +11 -0
  13. package/android/src/main/java/com/eko/utils/NetworkRequestUtils.kt +43 -0
  14. package/android/src/main/java/com/eko/utils/ReadableConverters.kt +55 -0
  15. package/android/src/main/java/com/eko/utils/RedirectResolver.kt +97 -0
  16. package/android/src/main/java/com/eko/utils/StorageManager.kt +45 -45
  17. package/android/src/newarch/java/com/eko/RNBackgroundDownloaderModule.kt +18 -70
  18. package/android/src/oldarch/java/com/eko/RNBackgroundDownloaderModule.kt +18 -70
  19. package/ios/RNBackgroundDownloader.mm +187 -91
  20. package/lib/DownloadTask.js +8 -7
  21. package/lib/UploadTask.js +11 -10
  22. package/lib/config.d.ts +1 -10
  23. package/lib/config.js +1 -44
  24. package/lib/index.js +34 -32
  25. package/lib/logger.d.ts +2 -0
  26. package/lib/logger.js +16 -0
  27. package/lib/notifications.d.ts +8 -0
  28. package/lib/notifications.js +34 -0
  29. package/package.json +7 -3
  30. package/src/DownloadTask.ts +2 -1
  31. package/src/UploadTask.ts +2 -1
  32. package/src/config.ts +4 -45
  33. package/src/index.ts +3 -1
  34. package/src/logger.ts +16 -0
  35. package/src/notifications.ts +31 -0
@@ -301,11 +301,23 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
301
301
  @synchronized (sharedLock) {
302
302
  if (urlSession == nil) {
303
303
  [self sendDebugLog:@"lazyRegisterSession: creating new session" taskId:nil];
304
- urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
305
- // Activate the session by calling getTasksWithCompletionHandler
306
- // This forces iOS to fully initialize the background session
307
- // On fresh installs, the session may not be ready to process tasks immediately
308
- [self activateSession];
304
+ // +sessionWithConfiguration: can raise NSInvalidArgumentException (the same
305
+ // failure mode as issues #161/#170). This is the one choke point every entry
306
+ // point funnels through, so we contain the throw here and leave urlSession nil
307
+ // rather than let it escape a void/promise method and crash Hermes off the JS
308
+ // thread. Callers already degrade on a nil session (download queues, the
309
+ // getExisting* methods reject with ERR_SESSION_NIL).
310
+ @try {
311
+ urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
312
+ // Activate the session by calling getTasksWithCompletionHandler
313
+ // This forces iOS to fully initialize the background session
314
+ // On fresh installs, the session may not be ready to process tasks immediately
315
+ [self activateSession];
316
+ } @catch (NSException *exception) {
317
+ urlSession = nil;
318
+ DLog(nil, @"[RNBackgroundDownloader] - [lazyRegisterSession] error: %@", exception.reason);
319
+ [self sendDebugLog:[NSString stringWithFormat:@"lazyRegisterSession: ERROR - %@", exception.reason] taskId:nil];
320
+ }
309
321
  } else {
310
322
  [self sendDebugLog:@"lazyRegisterSession: session already exists" taskId:nil];
311
323
  }
@@ -674,6 +686,51 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
674
686
  }
675
687
  }
676
688
 
689
+ // Same recovery as -createDownloadTaskWithRequest:identifier:, for uploads:
690
+ // -uploadTaskWithRequest:fromFile: raises NSInvalidArgumentException when the
691
+ // session has been invalidated, so recreate the background session and retry once.
692
+ // Must be called while holding sharedLock.
693
+ // See https://github.com/kesha-antonov/react-native-background-downloader/issues/170
694
+ - (NSURLSessionUploadTask *)createUploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL identifier:(NSString *)identifier {
695
+ @try {
696
+ return [urlSession uploadTaskWithRequest:request fromFile:fileURL];
697
+ } @catch (NSException *exception) {
698
+ DLog(identifier, @"[RNBackgroundDownloader] - [createUploadTask] session invalidated, recreating: %@", exception.reason);
699
+ [self sendDebugLog:[NSString stringWithFormat:@"createUploadTask: session invalidated, recreating (%@)", exception.reason] taskId:identifier];
700
+
701
+ // Recreate the background session directly (do not call unregisterSession,
702
+ // which would invalidateAndCancel and drop queued downloads).
703
+ urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
704
+ isSessionActivated = YES;
705
+
706
+ @try {
707
+ return [urlSession uploadTaskWithRequest:request fromFile:fileURL];
708
+ } @catch (NSException *retryException) {
709
+ DLog(identifier, @"[RNBackgroundDownloader] - [createUploadTask] retry failed: %@", retryException.reason);
710
+ [self sendDebugLog:[NSString stringWithFormat:@"createUploadTask: retry failed (%@)", retryException.reason] taskId:identifier];
711
+ return nil;
712
+ }
713
+ }
714
+ }
715
+
716
+ // Emits uploadFailed so the JS task errors out instead of hanging when upload
717
+ // setup fails before a task exists (bad params, unreadable file, task creation failure).
718
+ - (void)emitUploadFailed:(NSString *)identifier error:(NSString *)error errorCode:(NSInteger)errorCode {
719
+ if (identifier == nil) {
720
+ return;
721
+ }
722
+ NSDictionary *body = @{
723
+ @"id": identifier,
724
+ @"error": error ?: @"unknown error",
725
+ @"errorCode": @(errorCode)
726
+ };
727
+ #ifdef RCT_NEW_ARCH_ENABLED
728
+ [self safeEmitEvent:@"onUploadFailed" value:body];
729
+ #else
730
+ [self sendEventWithName:@"uploadFailed" body:body];
731
+ #endif
732
+ }
733
+
677
734
  - (void)pauseTaskInternal:(NSString *)identifier resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
678
735
  DLog(identifier, @"[RNBackgroundDownloader] - [pauseTask]");
679
736
  @try {
@@ -1630,114 +1687,153 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
1630
1687
  DLog(identifier, @"[RNBackgroundDownloader] - [upload] url %@ source %@ method %@", url, source, method);
1631
1688
  if (identifier == nil || url == nil || source == nil) {
1632
1689
  DLog(identifier, @"[RNBackgroundDownloader] - [Error] id, url and source must be set");
1690
+ [self emitUploadFailed:identifier error:@"id, url and source must be set" errorCode:-1];
1633
1691
  return;
1634
1692
  }
1635
1693
 
1636
- @synchronized (sharedLock) {
1637
- [self sendDebugLog:@"upload: calling lazyRegisterSession" taskId:identifier];
1638
- [self lazyRegisterSession];
1639
-
1640
- // Get file info
1641
- NSURL *fileURL = [NSURL fileURLWithPath:source];
1642
- NSError *fileError;
1643
- NSDictionary *fileAttrs = [[NSFileManager defaultManager] attributesOfItemAtPath:source error:&fileError];
1644
- if (fileError) {
1645
- DLog(identifier, @"[RNBackgroundDownloader] - [Error] Could not read file: %@", fileError.localizedDescription);
1646
- return;
1647
- }
1648
- unsigned long long fileSize = [fileAttrs fileSize];
1649
-
1650
- // Create request
1651
- NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
1652
- request.HTTPMethod = method;
1653
- [request setValue:identifier forHTTPHeaderField:@"uploadConfigId"];
1694
+ @try {
1695
+ @synchronized (sharedLock) {
1696
+ [self sendDebugLog:@"upload: calling lazyRegisterSession" taskId:identifier];
1697
+ [self lazyRegisterSession];
1654
1698
 
1655
- // Add custom headers
1656
- if (headers != nil) {
1657
- for (NSString *headerKey in headers) {
1658
- [request setValue:[headers valueForKey:headerKey] forHTTPHeaderField:headerKey];
1699
+ // Normalize file:// source paths so NSFileManager / fileURLWithPath get a plain path
1700
+ if ([source hasPrefix:@"file://"]) {
1701
+ NSString *sourcePath = [NSURL URLWithString:source].path;
1702
+ if (sourcePath == nil) {
1703
+ // URLWithString rejects unencoded paths (e.g. containing spaces)
1704
+ sourcePath = [[source substringFromIndex:@"file://".length] stringByRemovingPercentEncoding];
1705
+ }
1706
+ if (sourcePath != nil) {
1707
+ source = sourcePath;
1708
+ }
1659
1709
  }
1660
- }
1661
-
1662
- // Determine if we need multipart
1663
- BOOL useMultipart = (parameters != nil && parameters.count > 0) || fieldName != nil;
1664
1710
 
1665
- RNBGDUploadTaskConfig *taskConfig = [[RNBGDUploadTaskConfig alloc] initWithDictionary:@{
1666
- @"id": identifier,
1667
- @"url": url,
1668
- @"source": source,
1669
- @"method": method,
1670
- @"metadata": metadata,
1671
- @"fieldName": fieldName ?: [NSNull null],
1672
- @"mimeType": mimeType ?: [NSNull null],
1673
- @"parameters": parameters ?: [NSNull null]
1674
- }];
1675
- taskConfig.bytesTotal = fileSize;
1676
-
1677
- NSURLSessionUploadTask *uploadTask;
1711
+ NSURL *requestURL = [NSURL URLWithString:url];
1712
+ if (requestURL == nil) {
1713
+ DLog(identifier, @"[RNBackgroundDownloader] - [Error] invalid url: %@", url);
1714
+ [self emitUploadFailed:identifier error:[NSString stringWithFormat:@"invalid url: %@", url] errorCode:NSURLErrorBadURL];
1715
+ return;
1716
+ }
1678
1717
 
1679
- if (useMultipart) {
1680
- // Create multipart form data
1681
- NSString *boundary = [[NSUUID UUID] UUIDString];
1682
- [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];
1718
+ // Get file info
1719
+ NSURL *fileURL = [NSURL fileURLWithPath:source];
1720
+ NSError *fileError;
1721
+ NSDictionary *fileAttrs = [[NSFileManager defaultManager] attributesOfItemAtPath:source error:&fileError];
1722
+ if (fileError) {
1723
+ DLog(identifier, @"[RNBackgroundDownloader] - [Error] Could not read file: %@", fileError.localizedDescription);
1724
+ [self emitUploadFailed:identifier error:[NSString stringWithFormat:@"Could not read file: %@", fileError.localizedDescription] errorCode:NSURLErrorFileDoesNotExist];
1725
+ return;
1726
+ }
1727
+ unsigned long long fileSize = [fileAttrs fileSize];
1683
1728
 
1684
- // Build multipart body
1685
- NSMutableData *body = [NSMutableData data];
1729
+ // Create request
1730
+ NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:requestURL];
1731
+ request.HTTPMethod = method;
1732
+ [request setValue:identifier forHTTPHeaderField:@"uploadConfigId"];
1686
1733
 
1687
- // Add parameters
1688
- if (parameters != nil) {
1689
- for (NSString *key in parameters) {
1690
- [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
1691
- [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
1692
- [body appendData:[[NSString stringWithFormat:@"%@\r\n", parameters[key]] dataUsingEncoding:NSUTF8StringEncoding]];
1734
+ // Add custom headers
1735
+ if (headers != nil) {
1736
+ for (NSString *headerKey in headers) {
1737
+ [request setValue:[headers valueForKey:headerKey] forHTTPHeaderField:headerKey];
1693
1738
  }
1694
1739
  }
1695
1740
 
1696
- // Add file
1697
- NSString *filename = [source lastPathComponent];
1698
- NSString *contentType = mimeType ?: @"application/octet-stream";
1741
+ // Determine if we need multipart
1742
+ BOOL useMultipart = (parameters != nil && parameters.count > 0) || fieldName != nil;
1743
+
1744
+ RNBGDUploadTaskConfig *taskConfig = [[RNBGDUploadTaskConfig alloc] initWithDictionary:@{
1745
+ @"id": identifier,
1746
+ @"url": url,
1747
+ @"source": source,
1748
+ @"method": method,
1749
+ @"metadata": metadata,
1750
+ @"fieldName": fieldName ?: [NSNull null],
1751
+ @"mimeType": mimeType ?: [NSNull null],
1752
+ @"parameters": parameters ?: [NSNull null]
1753
+ }];
1754
+ taskConfig.bytesTotal = fileSize;
1699
1755
 
1700
- NSString *multipartFieldName = fieldName ?: @"file";
1701
- [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
1702
- [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", multipartFieldName, filename] dataUsingEncoding:NSUTF8StringEncoding]];
1703
- [body appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", contentType] dataUsingEncoding:NSUTF8StringEncoding]];
1756
+ NSURLSessionUploadTask *uploadTask;
1704
1757
 
1705
- NSData *fileData = [NSData dataWithContentsOfFile:source];
1706
- [body appendData:fileData];
1707
- [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
1758
+ if (useMultipart) {
1759
+ // Create multipart form data
1760
+ NSString *boundary = [[NSUUID UUID] UUIDString];
1761
+ [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];
1708
1762
 
1709
- // End boundary
1710
- [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
1763
+ // Build multipart body
1764
+ NSMutableData *body = [NSMutableData data];
1711
1765
 
1712
- // Write body to temp file for background upload
1713
- NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
1714
- [body writeToFile:tempPath atomically:YES];
1715
- NSURL *tempFileURL = [NSURL fileURLWithPath:tempPath];
1766
+ // Add parameters
1767
+ if (parameters != nil) {
1768
+ for (NSString *key in parameters) {
1769
+ [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
1770
+ [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
1771
+ [body appendData:[[NSString stringWithFormat:@"%@\r\n", parameters[key]] dataUsingEncoding:NSUTF8StringEncoding]];
1772
+ }
1773
+ }
1716
1774
 
1717
- taskConfig.bytesTotal = body.length;
1718
- uploadTask = [urlSession uploadTaskWithRequest:request fromFile:tempFileURL];
1719
- } else {
1720
- // Simple file upload
1721
- if (mimeType) {
1722
- [request setValue:mimeType forHTTPHeaderField:@"Content-Type"];
1775
+ // Add file
1776
+ NSString *filename = [source lastPathComponent];
1777
+ NSString *contentType = mimeType ?: @"application/octet-stream";
1778
+
1779
+ NSString *multipartFieldName = fieldName ?: @"file";
1780
+ [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
1781
+ [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", multipartFieldName, filename] dataUsingEncoding:NSUTF8StringEncoding]];
1782
+ [body appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", contentType] dataUsingEncoding:NSUTF8StringEncoding]];
1783
+
1784
+ // The file can disappear between the attributes check above and this
1785
+ // read (TOCTOU); appendData:nil would raise NSInvalidArgumentException
1786
+ NSData *fileData = [NSData dataWithContentsOfFile:source];
1787
+ if (fileData == nil) {
1788
+ DLog(identifier, @"[RNBackgroundDownloader] - [Error] Could not read file: %@", source);
1789
+ [self emitUploadFailed:identifier error:[NSString stringWithFormat:@"Could not read file: %@", source] errorCode:NSURLErrorCannotOpenFile];
1790
+ return;
1791
+ }
1792
+ [body appendData:fileData];
1793
+ [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
1794
+
1795
+ // End boundary
1796
+ [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
1797
+
1798
+ // Write body to temp file for background upload
1799
+ NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
1800
+ if (![body writeToFile:tempPath atomically:YES]) {
1801
+ DLog(identifier, @"[RNBackgroundDownloader] - [Error] Could not write multipart body to temp file");
1802
+ [self emitUploadFailed:identifier error:@"Could not write multipart body to temp file" errorCode:NSURLErrorCannotWriteToFile];
1803
+ return;
1804
+ }
1805
+ NSURL *tempFileURL = [NSURL fileURLWithPath:tempPath];
1806
+
1807
+ taskConfig.bytesTotal = body.length;
1808
+ uploadTask = [self createUploadTaskWithRequest:request fromFile:tempFileURL identifier:identifier];
1809
+ } else {
1810
+ // Simple file upload
1811
+ if (mimeType) {
1812
+ [request setValue:mimeType forHTTPHeaderField:@"Content-Type"];
1813
+ }
1814
+ uploadTask = [self createUploadTaskWithRequest:request fromFile:fileURL identifier:identifier];
1723
1815
  }
1724
- uploadTask = [urlSession uploadTaskWithRequest:request fromFile:fileURL];
1725
- }
1726
1816
 
1727
- if (uploadTask == nil) {
1728
- DLog(identifier, @"[RNBackgroundDownloader] - [Error] failed to create upload task");
1729
- return;
1730
- }
1817
+ if (uploadTask == nil) {
1818
+ DLog(identifier, @"[RNBackgroundDownloader] - [Error] failed to create upload task");
1819
+ [self emitUploadFailed:identifier error:@"failed to create upload task" errorCode:-1];
1820
+ return;
1821
+ }
1731
1822
 
1732
- uploadTaskToConfigMap[@(uploadTask.taskIdentifier)] = taskConfig;
1733
- [mmkv setData:[self serializeUploadConfig:uploadTaskToConfigMap] forKey:ID_TO_UPLOAD_CONFIG_MAP_KEY];
1823
+ uploadTaskToConfigMap[@(uploadTask.taskIdentifier)] = taskConfig;
1824
+ [mmkv setData:[self serializeUploadConfig:uploadTaskToConfigMap] forKey:ID_TO_UPLOAD_CONFIG_MAP_KEY];
1734
1825
 
1735
- idToUploadTaskMap[identifier] = uploadTask;
1736
- idToUploadPercentMap[identifier] = @0.0;
1737
- idToUploadLastBytesMap[identifier] = @0;
1826
+ idToUploadTaskMap[identifier] = uploadTask;
1827
+ idToUploadPercentMap[identifier] = @0.0;
1828
+ idToUploadLastBytesMap[identifier] = @0;
1738
1829
 
1739
- [uploadTask resume];
1740
- lastUploadProgressReportedAt = [[NSDate alloc] init];
1830
+ [uploadTask resume];
1831
+ lastUploadProgressReportedAt = [[NSDate alloc] init];
1832
+ }
1833
+ } @catch (NSException *exception) {
1834
+ DLog(identifier, @"[RNBackgroundDownloader] - [upload] error: %@", exception.reason);
1835
+ [self sendDebugLog:[NSString stringWithFormat:@"upload: ERROR - %@", exception.reason] taskId:identifier];
1836
+ [self emitUploadFailed:identifier error:exception.reason errorCode:-1];
1741
1837
  }
1742
1838
  }
1743
1839
 
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DownloadTask = void 0;
4
4
  const config_1 = require("./config");
5
+ const logger_1 = require("./logger");
5
6
  // Import shared native module getter to avoid duplicating TurboModule lookup
6
7
  // This is lazily imported to avoid circular dependency issues at module load time
7
8
  let getNativeModuleImpl = null;
@@ -100,19 +101,19 @@ class DownloadTask {
100
101
  if (this.state === 'PAUSED' && downloadParams.headers) {
101
102
  const headers = this.headersToUnsafeObject(downloadParams.headers);
102
103
  if (headers) {
103
- (0, config_1.log)('DownloadTask: setDownloadParams updating native headers', this.id);
104
+ (0, logger_1.log)('DownloadTask: setDownloadParams updating native headers', this.id);
104
105
  return getNativeModule().updateTaskHeaders(this.id, headers);
105
106
  }
106
107
  }
107
108
  return false;
108
109
  }
109
110
  async pause() {
110
- (0, config_1.log)('DownloadTask: pause', this.id);
111
+ (0, logger_1.log)('DownloadTask: pause', this.id);
111
112
  this.state = 'PAUSED';
112
113
  await getNativeModule().pauseTask(this.id);
113
114
  }
114
115
  async resume() {
115
- (0, config_1.log)('DownloadTask: resume', this.id);
116
+ (0, logger_1.log)('DownloadTask: resume', this.id);
116
117
  this.state = 'DOWNLOADING';
117
118
  this.errorCode = 0;
118
119
  await getNativeModule().resumeTask(this.id);
@@ -120,12 +121,12 @@ class DownloadTask {
120
121
  start() {
121
122
  var _a, _b, _c, _d, _e;
122
123
  if (this.state !== 'PENDING') {
123
- (0, config_1.log)('DownloadTask: start. Download already started, can\' start again... ', this.id);
124
+ (0, logger_1.log)('DownloadTask: start. Download already started, can\' start again... ', this.id);
124
125
  (_a = this.errorHandler) === null || _a === void 0 ? void 0 : _a.call(this, { error: 'Download already started', errorCode: -1 });
125
126
  return;
126
127
  }
127
128
  if (!this.downloadParams) {
128
- (0, config_1.log)('DownloadTask: start. downloadParams is missing. "setDownloadParams" wasn\'t called before "start"', this.id);
129
+ (0, logger_1.log)('DownloadTask: start. downloadParams is missing. "setDownloadParams" wasn\'t called before "start"', this.id);
129
130
  (_b = this.errorHandler) === null || _b === void 0 ? void 0 : _b.call(this, { error: 'downloadParams is missing. setDownloadParams must be called before start', errorCode: -2 });
130
131
  return;
131
132
  }
@@ -145,7 +146,7 @@ class DownloadTask {
145
146
  });
146
147
  }
147
148
  async stop() {
148
- (0, config_1.log)('DownloadTask: stop', this.id);
149
+ (0, logger_1.log)('DownloadTask: stop', this.id);
149
150
  this.state = 'STOPPED';
150
151
  await getNativeModule().stopTask(this.id);
151
152
  }
@@ -157,7 +158,7 @@ class DownloadTask {
157
158
  return (_a = metadata) !== null && _a !== void 0 ? _a : null;
158
159
  }
159
160
  catch (e) {
160
- (0, config_1.log)('DownloadTask tryParseJson', e);
161
+ (0, logger_1.log)('DownloadTask tryParseJson', e);
161
162
  return null;
162
163
  }
163
164
  }
package/lib/UploadTask.js CHANGED
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.UploadTask = void 0;
4
4
  const config_1 = require("./config");
5
+ const logger_1 = require("./logger");
5
6
  // Import shared native module getter to avoid duplicating TurboModule lookup
6
7
  // This is lazily imported to avoid circular dependency issues at module load time
7
8
  let getNativeModuleImpl = null;
@@ -88,39 +89,39 @@ class UploadTask {
88
89
  this.uploadParams = uploadParams;
89
90
  }
90
91
  async pause() {
91
- (0, config_1.log)('UploadTask: pause', this.id);
92
+ (0, logger_1.log)('UploadTask: pause', this.id);
92
93
  this.state = 'PAUSED';
93
94
  const nativeModule = getNativeModule();
94
95
  if (nativeModule.pauseUploadTask)
95
96
  await nativeModule.pauseUploadTask(this.id);
96
97
  else
97
- (0, config_1.log)('UploadTask: pause not supported - native implementation missing');
98
+ (0, logger_1.log)('UploadTask: pause not supported - native implementation missing');
98
99
  }
99
100
  async resume() {
100
- (0, config_1.log)('UploadTask: resume', this.id);
101
+ (0, logger_1.log)('UploadTask: resume', this.id);
101
102
  this.state = 'UPLOADING';
102
103
  this.errorCode = 0;
103
104
  const nativeModule = getNativeModule();
104
105
  if (nativeModule.resumeUploadTask)
105
106
  await nativeModule.resumeUploadTask(this.id);
106
107
  else
107
- (0, config_1.log)('UploadTask: resume not supported - native implementation missing');
108
+ (0, logger_1.log)('UploadTask: resume not supported - native implementation missing');
108
109
  }
109
110
  start() {
110
111
  var _a, _b, _c, _d, _e, _f;
111
112
  if (this.state !== 'PENDING') {
112
- (0, config_1.log)('UploadTask: start. Upload already started, can\' start again... ', this.id);
113
+ (0, logger_1.log)('UploadTask: start. Upload already started, can\' start again... ', this.id);
113
114
  (_a = this.errorHandler) === null || _a === void 0 ? void 0 : _a.call(this, { error: 'Upload already started', errorCode: -1 });
114
115
  return;
115
116
  }
116
117
  if (!this.uploadParams) {
117
- (0, config_1.log)('UploadTask: start. uploadParams is missing. "setUploadParams" wasn\'t called before "start"', this.id);
118
+ (0, logger_1.log)('UploadTask: start. uploadParams is missing. "setUploadParams" wasn\'t called before "start"', this.id);
118
119
  (_b = this.errorHandler) === null || _b === void 0 ? void 0 : _b.call(this, { error: 'uploadParams is missing. setUploadParams must be called before start', errorCode: -2 });
119
120
  return;
120
121
  }
121
122
  const nativeModule = getNativeModule();
122
123
  if (!nativeModule.upload) {
123
- (0, config_1.log)('UploadTask: start. Upload not supported - native implementation missing');
124
+ (0, logger_1.log)('UploadTask: start. Upload not supported - native implementation missing');
124
125
  (_c = this.errorHandler) === null || _c === void 0 ? void 0 : _c.call(this, { error: 'Upload not supported - native implementation missing', errorCode: -3 });
125
126
  return;
126
127
  }
@@ -139,13 +140,13 @@ class UploadTask {
139
140
  });
140
141
  }
141
142
  async stop() {
142
- (0, config_1.log)('UploadTask: stop', this.id);
143
+ (0, logger_1.log)('UploadTask: stop', this.id);
143
144
  this.state = 'STOPPED';
144
145
  const nativeModule = getNativeModule();
145
146
  if (nativeModule.stopUploadTask)
146
147
  await nativeModule.stopUploadTask(this.id);
147
148
  else
148
- (0, config_1.log)('UploadTask: stop not supported - native implementation missing');
149
+ (0, logger_1.log)('UploadTask: stop not supported - native implementation missing');
149
150
  }
150
151
  tryParseJson(metadata) {
151
152
  var _a;
@@ -155,7 +156,7 @@ class UploadTask {
155
156
  return (_a = metadata) !== null && _a !== void 0 ? _a : null;
156
157
  }
157
158
  catch (e) {
158
- (0, config_1.log)('UploadTask tryParseJson', e);
159
+ (0, logger_1.log)('UploadTask tryParseJson', e);
159
160
  return null;
160
161
  }
161
162
  }
package/lib/config.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { Headers, IosDataProtection, NotificationGroupingMode, NotificationsGroupingConfig, NotificationTexts } from './types';
2
+ import type { LogCallback } from './logger';
2
3
  export declare const DEFAULT_PROGRESS_INTERVAL = 1000;
3
4
  export declare const DEFAULT_PROGRESS_MIN_BYTES: number;
4
5
  export declare const DEFAULT_MAX_PARALLEL_DOWNLOADS = 4;
5
6
  export declare const DEFAULT_ALLOWS_CELLULAR_ACCESS = true;
6
7
  export declare const DEFAULT_IOS_DATA_PROTECTION: IosDataProtection;
7
8
  export declare const DEFAULT_NOTIFICATION_TEXTS: Required<NotificationTexts>;
8
- type LogCallback = (tag: string, message: string, ...args: unknown[]) => void;
9
9
  interface ConfigState {
10
10
  headers: Headers;
11
11
  progressInterval: number;
@@ -21,13 +21,4 @@ interface ConfigState {
21
21
  iosDataProtection: IosDataProtection;
22
22
  }
23
23
  export declare const config: ConfigState;
24
- /**
25
- * Get notification text with proper pluralization.
26
- */
27
- export declare function getGroupText(count: number): string;
28
- /**
29
- * Get notification texts config for native side (serializable).
30
- */
31
- export declare function getNotificationTextsForNative(): Record<string, string>;
32
- export declare const log: (...args: unknown[]) => void;
33
24
  export {};
package/lib/config.js CHANGED
@@ -1,8 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.log = exports.config = exports.DEFAULT_NOTIFICATION_TEXTS = exports.DEFAULT_IOS_DATA_PROTECTION = exports.DEFAULT_ALLOWS_CELLULAR_ACCESS = exports.DEFAULT_MAX_PARALLEL_DOWNLOADS = exports.DEFAULT_PROGRESS_MIN_BYTES = exports.DEFAULT_PROGRESS_INTERVAL = void 0;
4
- exports.getGroupText = getGroupText;
5
- exports.getNotificationTextsForNative = getNotificationTextsForNative;
3
+ exports.config = exports.DEFAULT_NOTIFICATION_TEXTS = exports.DEFAULT_IOS_DATA_PROTECTION = exports.DEFAULT_ALLOWS_CELLULAR_ACCESS = exports.DEFAULT_MAX_PARALLEL_DOWNLOADS = exports.DEFAULT_PROGRESS_MIN_BYTES = exports.DEFAULT_PROGRESS_INTERVAL = void 0;
6
4
  exports.DEFAULT_PROGRESS_INTERVAL = 1000;
7
5
  exports.DEFAULT_PROGRESS_MIN_BYTES = 1024 * 1024; // 1MB
8
6
  exports.DEFAULT_MAX_PARALLEL_DOWNLOADS = 4;
@@ -36,44 +34,3 @@ exports.config = {
36
34
  texts: exports.DEFAULT_NOTIFICATION_TEXTS,
37
35
  },
38
36
  };
39
- /**
40
- * Get notification text with proper pluralization.
41
- */
42
- function getGroupText(count) {
43
- var _a, _b;
44
- const groupText = (_b = (_a = exports.config.notificationsGrouping.texts) === null || _a === void 0 ? void 0 : _a.groupText) !== null && _b !== void 0 ? _b : exports.DEFAULT_NOTIFICATION_TEXTS.groupText;
45
- if (typeof groupText === 'function')
46
- return groupText(count);
47
- return groupText.replace('{count}', String(count));
48
- }
49
- /**
50
- * Get notification texts config for native side (serializable).
51
- */
52
- function getNotificationTextsForNative() {
53
- var _a, _b, _c, _d, _e, _f, _g, _h;
54
- const texts = (_a = exports.config.notificationsGrouping.texts) !== null && _a !== void 0 ? _a : exports.DEFAULT_NOTIFICATION_TEXTS;
55
- return {
56
- downloadTitle: (_b = texts.downloadTitle) !== null && _b !== void 0 ? _b : exports.DEFAULT_NOTIFICATION_TEXTS.downloadTitle,
57
- downloadStarting: (_c = texts.downloadStarting) !== null && _c !== void 0 ? _c : exports.DEFAULT_NOTIFICATION_TEXTS.downloadStarting,
58
- downloadProgress: (_d = texts.downloadProgress) !== null && _d !== void 0 ? _d : exports.DEFAULT_NOTIFICATION_TEXTS.downloadProgress,
59
- downloadPaused: (_e = texts.downloadPaused) !== null && _e !== void 0 ? _e : exports.DEFAULT_NOTIFICATION_TEXTS.downloadPaused,
60
- downloadFinished: (_f = texts.downloadFinished) !== null && _f !== void 0 ? _f : exports.DEFAULT_NOTIFICATION_TEXTS.downloadFinished,
61
- groupTitle: (_g = texts.groupTitle) !== null && _g !== void 0 ? _g : exports.DEFAULT_NOTIFICATION_TEXTS.groupTitle,
62
- // For native side, we send a pattern with {count} placeholder
63
- groupText: typeof texts.groupText === 'function'
64
- ? '{count} download(s) in progress' // Default pattern if function provided
65
- : ((_h = texts.groupText) !== null && _h !== void 0 ? _h : '{count} download(s) in progress'),
66
- };
67
- }
68
- const log = (...args) => {
69
- if (exports.config.isLogsEnabled) {
70
- console.log('[RNBackgroundDownloader]', ...args);
71
- // Call external log callback if provided
72
- if (exports.config.logCallback) {
73
- const message = args.length > 0 && typeof args[0] === 'string' ? args[0] : 'log';
74
- const restArgs = args.length > 1 ? args.slice(1) : [];
75
- exports.config.logCallback('RNBD', message, ...restArgs);
76
- }
77
- }
78
- };
79
- exports.log = log;