@kesha-antonov/react-native-background-downloader 4.5.8 → 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.
@@ -0,0 +1,36 @@
1
+ package com.eko
2
+
3
+ import com.facebook.react.bridge.Promise
4
+
5
+ /**
6
+ * Bridge helpers shared by the old- and new-architecture module wrappers so the
7
+ * try/resolve/reject boilerplate lives in exactly one place instead of being
8
+ * copy-pasted per method across both source sets.
9
+ */
10
+
11
+ /**
12
+ * Runs [block] and resolves the promise with `null` on success; rejects with
13
+ * [errorCode] (plus the exception message and cause) if it throws. Use for
14
+ * fire-and-forget bridge methods that only need to acknowledge completion.
15
+ */
16
+ inline fun Promise.resolveCatching(errorCode: String, block: () -> Unit) {
17
+ try {
18
+ block()
19
+ resolve(null)
20
+ } catch (e: Exception) {
21
+ reject(errorCode, e.message, e)
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Runs [block], which is responsible for resolving the promise itself (typically by
27
+ * handing it to the impl). Rejects with [errorCode] only if [block] throws before it
28
+ * gets a chance to resolve. Use for methods that return data through the promise.
29
+ */
30
+ inline fun Promise.rejectOnThrow(errorCode: String, block: () -> Unit) {
31
+ try {
32
+ block()
33
+ } catch (e: Exception) {
34
+ reject(errorCode, e.message, e)
35
+ }
36
+ }
@@ -14,6 +14,8 @@ import com.eko.handlers.OnBegin
14
14
  import com.eko.handlers.OnProgress
15
15
  import com.eko.handlers.OnProgressState
16
16
  import com.eko.utils.HeaderUtils
17
+ import com.eko.utils.ReadableConverters
18
+ import com.eko.utils.RedirectResolver
17
19
  import com.eko.utils.StorageManager
18
20
  import com.facebook.react.bridge.Arguments
19
21
  import com.facebook.react.bridge.Promise
@@ -25,8 +27,6 @@ import com.facebook.react.bridge.WritableMap
25
27
  import com.facebook.react.modules.core.DeviceEventManagerModule
26
28
  import org.json.JSONObject
27
29
  import java.io.File
28
- import java.net.HttpURLConnection
29
- import java.net.URL
30
30
  import java.util.concurrent.ExecutorService
31
31
  import java.util.concurrent.Executors
32
32
  import java.util.concurrent.Future
@@ -63,46 +63,6 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
63
63
  if (isLogsEnabled) Log.e(tag, message)
64
64
  }
65
65
 
66
- /**
67
- * Convert a ReadableMap to JSONObject.
68
- * Handles nested maps and arrays properly.
69
- */
70
- fun readableMapToJsonObject(map: ReadableMap?): JSONObject? {
71
- if (map == null) return null
72
- val json = JSONObject()
73
- val iterator = map.keySetIterator()
74
- while (iterator.hasNextKey()) {
75
- val key = iterator.nextKey()
76
- when (map.getType(key)) {
77
- ReadableType.Null -> json.put(key, JSONObject.NULL)
78
- ReadableType.Boolean -> json.put(key, map.getBoolean(key))
79
- ReadableType.Number -> json.put(key, map.getDouble(key))
80
- ReadableType.String -> json.put(key, map.getString(key))
81
- ReadableType.Map -> json.put(key, readableMapToJsonObject(map.getMap(key)))
82
- ReadableType.Array -> json.put(key, readableArrayToJsonArray(map.getArray(key)))
83
- }
84
- }
85
- return json
86
- }
87
-
88
- /**
89
- * Convert a ReadableArray to JSONArray.
90
- */
91
- private fun readableArrayToJsonArray(array: ReadableArray?): org.json.JSONArray? {
92
- if (array == null) return null
93
- val json = org.json.JSONArray()
94
- for (i in 0 until array.size()) {
95
- when (array.getType(i)) {
96
- ReadableType.Null -> json.put(JSONObject.NULL)
97
- ReadableType.Boolean -> json.put(array.getBoolean(i))
98
- ReadableType.Number -> json.put(array.getDouble(i))
99
- ReadableType.String -> json.put(array.getString(i))
100
- ReadableType.Map -> json.put(readableMapToJsonObject(array.getMap(i)))
101
- ReadableType.Array -> json.put(readableArrayToJsonArray(array.getArray(i)))
102
- }
103
- }
104
- return json
105
- }
106
66
  }
107
67
 
108
68
  // Storage manager for persistent state
@@ -599,88 +559,6 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
599
559
  )
600
560
  }
601
561
 
602
- /**
603
- * Resolve redirects for a URL up to maxRedirects limit
604
- * @param originalUrl The original URL to follow
605
- * @param maxRedirects Maximum number of redirects to follow (0 means no redirect resolution)
606
- * @param headers Headers to include in redirect resolution requests
607
- * @return The final resolved URL, or original URL if maxRedirects is 0 or resolution fails
608
- */
609
- private fun resolveRedirects(originalUrl: String, maxRedirects: Int, headers: ReadableMap?): String {
610
- if (maxRedirects <= 0) {
611
- return originalUrl
612
- }
613
-
614
- try {
615
- var currentUrl = originalUrl
616
- var redirectCount = 0
617
-
618
- while (redirectCount < maxRedirects) {
619
- val url = URL(currentUrl)
620
- val connection = url.openConnection() as HttpURLConnection
621
-
622
- // Add headers to the redirect resolution request
623
- HeaderUtils.applyToConnection(connection, headers)
624
-
625
- // Add default headers for consistency with DownloadManager
626
- HeaderUtils.applyDefaultHeaders(connection, headers)
627
-
628
- connection.instanceFollowRedirects = false
629
- connection.requestMethod = "HEAD" // Use HEAD to avoid downloading content
630
- connection.connectTimeout = DownloadConstants.REDIRECT_TIMEOUT_MS
631
- connection.readTimeout = DownloadConstants.REDIRECT_TIMEOUT_MS
632
-
633
- val responseCode = connection.responseCode
634
-
635
- if (responseCode in 300..399) {
636
- // This is a redirect
637
- val location = connection.getHeaderField("Location")
638
- if (location == null) {
639
- logW(NAME, "Redirect response without Location header at: $currentUrl")
640
- break
641
- }
642
-
643
- // Handle relative URLs
644
- currentUrl = when {
645
- location.startsWith("/") -> {
646
- val baseUrl = URL(currentUrl)
647
- "${baseUrl.protocol}://${baseUrl.host}$location"
648
- }
649
- !location.startsWith("http") -> {
650
- val baseUrl = URL(currentUrl)
651
- "${baseUrl.protocol}://${baseUrl.host}/$location"
652
- }
653
- else -> location
654
- }
655
-
656
- logD(NAME, "Redirect ${redirectCount + 1}/$maxRedirects: $currentUrl -> $location")
657
- redirectCount++
658
- } else {
659
- // Not a redirect, we've found the final URL
660
- break
661
- }
662
-
663
- connection.disconnect()
664
- }
665
-
666
- if (redirectCount >= maxRedirects) {
667
- logW(
668
- NAME,
669
- "Reached maximum redirects ($maxRedirects) for URL: $originalUrl. Final URL: $currentUrl"
670
- )
671
- } else {
672
- logD(NAME, "Resolved URL after $redirectCount redirects: $currentUrl")
673
- }
674
-
675
- return currentUrl
676
-
677
- } catch (e: Exception) {
678
- logE(NAME, "Failed to resolve redirects for URL: $originalUrl. Error: ${e.message}")
679
- // Return original URL if redirect resolution fails
680
- return originalUrl
681
- }
682
- }
683
-
684
562
  fun download(options: ReadableMap) {
685
563
  // Ensure event emitter is initialized before starting download
686
564
  // This fixes issues on first app install where download() might be called
@@ -704,7 +582,7 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
704
582
  // If passed as object, convert to JSON string properly
705
583
  try {
706
584
  val map = options.getMap("metadata")
707
- readableMapToJsonObject(map)?.toString() ?: "{}"
585
+ ReadableConverters.toJsonObject(map)?.toString() ?: "{}"
708
586
  } catch (e: Exception) {
709
587
  logW(NAME, "Failed to convert metadata map to string: ${e.message}")
710
588
  "{}"
@@ -752,7 +630,7 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
752
630
  // Resolve redirects if maxRedirects is specified
753
631
  if (maxRedirects > 0) {
754
632
  logD(NAME, "Resolving redirects for URL: $url (maxRedirects: $maxRedirects)")
755
- url = resolveRedirects(url, maxRedirects, headers)
633
+ url = RedirectResolver.resolve(url, maxRedirects, headers)
756
634
  logD(NAME, "Final resolved URL: $url")
757
635
  }
758
636
 
@@ -1435,7 +1313,7 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
1435
1313
  ReadableType.Map -> {
1436
1314
  try {
1437
1315
  val map = options.getMap("metadata")
1438
- readableMapToJsonObject(map)?.toString() ?: "{}"
1316
+ ReadableConverters.toJsonObject(map)?.toString() ?: "{}"
1439
1317
  } catch (e: Exception) {
1440
1318
  logW(NAME, "Failed to convert metadata map to string: ${e.message}")
1441
1319
  "{}"
@@ -0,0 +1,55 @@
1
+ package com.eko.utils
2
+
3
+ import com.facebook.react.bridge.ReadableArray
4
+ import com.facebook.react.bridge.ReadableMap
5
+ import com.facebook.react.bridge.ReadableType
6
+ import org.json.JSONArray
7
+ import org.json.JSONObject
8
+
9
+ /**
10
+ * Stateless conversion of React Native's ReadableMap/ReadableArray bridge types into
11
+ * org.json structures. Pure helpers with no module state - extracted from the module
12
+ * so the conversion logic is reusable and unit-testable on its own.
13
+ */
14
+ object ReadableConverters {
15
+
16
+ /**
17
+ * Convert a ReadableMap to JSONObject, handling nested maps and arrays.
18
+ */
19
+ fun toJsonObject(map: ReadableMap?): JSONObject? {
20
+ if (map == null) return null
21
+ val json = JSONObject()
22
+ val iterator = map.keySetIterator()
23
+ while (iterator.hasNextKey()) {
24
+ val key = iterator.nextKey()
25
+ when (map.getType(key)) {
26
+ ReadableType.Null -> json.put(key, JSONObject.NULL)
27
+ ReadableType.Boolean -> json.put(key, map.getBoolean(key))
28
+ ReadableType.Number -> json.put(key, map.getDouble(key))
29
+ ReadableType.String -> json.put(key, map.getString(key))
30
+ ReadableType.Map -> json.put(key, toJsonObject(map.getMap(key)))
31
+ ReadableType.Array -> json.put(key, toJsonArray(map.getArray(key)))
32
+ }
33
+ }
34
+ return json
35
+ }
36
+
37
+ /**
38
+ * Convert a ReadableArray to JSONArray.
39
+ */
40
+ fun toJsonArray(array: ReadableArray?): JSONArray? {
41
+ if (array == null) return null
42
+ val json = JSONArray()
43
+ for (i in 0 until array.size()) {
44
+ when (array.getType(i)) {
45
+ ReadableType.Null -> json.put(JSONObject.NULL)
46
+ ReadableType.Boolean -> json.put(array.getBoolean(i))
47
+ ReadableType.Number -> json.put(array.getDouble(i))
48
+ ReadableType.String -> json.put(array.getString(i))
49
+ ReadableType.Map -> json.put(toJsonObject(array.getMap(i)))
50
+ ReadableType.Array -> json.put(toJsonArray(array.getArray(i)))
51
+ }
52
+ }
53
+ return json
54
+ }
55
+ }
@@ -0,0 +1,97 @@
1
+ package com.eko.utils
2
+
3
+ import com.eko.DownloadConstants
4
+ import com.eko.RNBackgroundDownloaderModuleImpl
5
+ import com.facebook.react.bridge.ReadableMap
6
+ import java.net.HttpURLConnection
7
+ import java.net.URL
8
+
9
+ /**
10
+ * Follows HTTP 3xx redirects with HEAD requests to find the final download URL before
11
+ * handing it to DownloadManager (which does not expose the resolved URL). Stateless and
12
+ * self-contained - extracted from the module so the redirect logic is isolated and
13
+ * testable. Never throws: on any failure it returns the original URL unchanged.
14
+ */
15
+ object RedirectResolver {
16
+
17
+ private const val TAG = "RNBackgroundDownloader"
18
+
19
+ /**
20
+ * Resolve up to [maxRedirects] redirects starting from [originalUrl], applying
21
+ * [headers] to each probe. Returns the final URL, or [originalUrl] if resolution
22
+ * is disabled ([maxRedirects] <= 0) or fails.
23
+ */
24
+ fun resolve(originalUrl: String, maxRedirects: Int, headers: ReadableMap?): String {
25
+ if (maxRedirects <= 0) {
26
+ return originalUrl
27
+ }
28
+
29
+ try {
30
+ var currentUrl = originalUrl
31
+ var redirectCount = 0
32
+
33
+ while (redirectCount < maxRedirects) {
34
+ val url = URL(currentUrl)
35
+ val connection = url.openConnection() as HttpURLConnection
36
+
37
+ // Add headers to the redirect resolution request
38
+ HeaderUtils.applyToConnection(connection, headers)
39
+
40
+ // Add default headers for consistency with DownloadManager
41
+ HeaderUtils.applyDefaultHeaders(connection, headers)
42
+
43
+ connection.instanceFollowRedirects = false
44
+ connection.requestMethod = "HEAD" // Use HEAD to avoid downloading content
45
+ connection.connectTimeout = DownloadConstants.REDIRECT_TIMEOUT_MS
46
+ connection.readTimeout = DownloadConstants.REDIRECT_TIMEOUT_MS
47
+
48
+ val responseCode = connection.responseCode
49
+
50
+ if (responseCode in 300..399) {
51
+ // This is a redirect
52
+ val location = connection.getHeaderField("Location")
53
+ if (location == null) {
54
+ RNBackgroundDownloaderModuleImpl.logW(TAG, "Redirect response without Location header at: $currentUrl")
55
+ break
56
+ }
57
+
58
+ // Handle relative URLs
59
+ currentUrl = when {
60
+ location.startsWith("/") -> {
61
+ val baseUrl = URL(currentUrl)
62
+ "${baseUrl.protocol}://${baseUrl.host}$location"
63
+ }
64
+ !location.startsWith("http") -> {
65
+ val baseUrl = URL(currentUrl)
66
+ "${baseUrl.protocol}://${baseUrl.host}/$location"
67
+ }
68
+ else -> location
69
+ }
70
+
71
+ RNBackgroundDownloaderModuleImpl.logD(TAG, "Redirect ${redirectCount + 1}/$maxRedirects: $currentUrl -> $location")
72
+ redirectCount++
73
+ } else {
74
+ // Not a redirect, we've found the final URL
75
+ break
76
+ }
77
+
78
+ connection.disconnect()
79
+ }
80
+
81
+ if (redirectCount >= maxRedirects) {
82
+ RNBackgroundDownloaderModuleImpl.logW(
83
+ TAG,
84
+ "Reached maximum redirects ($maxRedirects) for URL: $originalUrl. Final URL: $currentUrl"
85
+ )
86
+ } else {
87
+ RNBackgroundDownloaderModuleImpl.logD(TAG, "Resolved URL after $redirectCount redirects: $currentUrl")
88
+ }
89
+
90
+ return currentUrl
91
+ } catch (e: Exception) {
92
+ RNBackgroundDownloaderModuleImpl.logE(TAG, "Failed to resolve redirects for URL: $originalUrl. Error: ${e.message}")
93
+ // Return original URL if redirect resolution fails
94
+ return originalUrl
95
+ }
96
+ }
97
+ }
@@ -188,6 +188,19 @@ class StorageManager(context: Context, private val name: String) {
188
188
  /**
189
189
  * Serializable data class for storing paused download information.
190
190
  * This is needed because Gson requires explicit serialization for complex types.
191
+ *
192
+ * PERSISTENCE MIGRATION INVARIANT — read before adding a field here.
193
+ * This DTO is written to MMKV/SharedPreferences by one app version and read back
194
+ * by the next, so it must stay forward/backward compatible with in-flight downloads
195
+ * across an app update. Every NEW field MUST:
196
+ * 1. be nullable (or have a default) so a record written by an older version -
197
+ * where the JSON key is simply absent - deserializes instead of failing; and
198
+ * 2. resolve its legacy meaning explicitly in [toInfo] with `?: <safe default>`,
199
+ * never relying on Gson's zero-value default (e.g. `false`/`0`), which is
200
+ * usually the wrong choice for an absent key.
201
+ * See `isAllowedOverMetered` below for the reference pattern, and keep the
202
+ * runtime<->DTO mapping in the single [toData]/[toInfo] pair so a field is added
203
+ * in exactly one place.
191
204
  */
192
205
  data class PausedDownloadInfoData(
193
206
  val configId: String,
@@ -30,53 +30,24 @@ class RNBackgroundDownloaderModule(reactContext: ReactApplicationContext) :
30
30
  impl.download(options)
31
31
  }
32
32
 
33
- override fun pauseTask(id: String, promise: com.facebook.react.bridge.Promise) {
34
- try {
35
- impl.pauseTask(id)
36
- promise.resolve(null)
37
- } catch (e: Exception) {
38
- promise.reject("ERR_PAUSE_TASK", e.message, e)
39
- }
40
- }
33
+ override fun pauseTask(id: String, promise: com.facebook.react.bridge.Promise) =
34
+ promise.resolveCatching("ERR_PAUSE_TASK") { impl.pauseTask(id) }
41
35
 
42
- override fun resumeTask(id: String, promise: com.facebook.react.bridge.Promise) {
43
- try {
44
- impl.resumeTask(id)
45
- promise.resolve(null)
46
- } catch (e: Exception) {
47
- promise.reject("ERR_RESUME_TASK", e.message, e)
48
- }
49
- }
36
+ override fun resumeTask(id: String, promise: com.facebook.react.bridge.Promise) =
37
+ promise.resolveCatching("ERR_RESUME_TASK") { impl.resumeTask(id) }
50
38
 
51
- override fun stopTask(id: String, promise: com.facebook.react.bridge.Promise) {
52
- try {
53
- impl.stopTask(id)
54
- promise.resolve(null)
55
- } catch (e: Exception) {
56
- promise.reject("ERR_STOP_TASK", e.message, e)
57
- }
58
- }
39
+ override fun stopTask(id: String, promise: com.facebook.react.bridge.Promise) =
40
+ promise.resolveCatching("ERR_STOP_TASK") { impl.stopTask(id) }
59
41
 
60
42
  override fun updateTaskHeaders(id: String, headers: com.facebook.react.bridge.ReadableMap, promise: com.facebook.react.bridge.Promise) {
61
43
  impl.updateTaskHeaders(id, headers, promise)
62
44
  }
63
45
 
64
- override fun completeHandler(jobId: String, promise: com.facebook.react.bridge.Promise) {
65
- try {
66
- impl.completeHandler(jobId)
67
- promise.resolve(null)
68
- } catch (e: Exception) {
69
- promise.reject("ERR_COMPLETE_HANDLER", e.message, e)
70
- }
71
- }
46
+ override fun completeHandler(jobId: String, promise: com.facebook.react.bridge.Promise) =
47
+ promise.resolveCatching("ERR_COMPLETE_HANDLER") { impl.completeHandler(jobId) }
72
48
 
73
- override fun getExistingDownloadTasks(promise: com.facebook.react.bridge.Promise) {
74
- try {
75
- impl.getExistingDownloadTasks(promise)
76
- } catch (e: Exception) {
77
- promise.reject("ERR_GET_EXISTING_TASKS", e.message, e)
78
- }
79
- }
49
+ override fun getExistingDownloadTasks(promise: com.facebook.react.bridge.Promise) =
50
+ promise.rejectOnThrow("ERR_GET_EXISTING_TASKS") { impl.getExistingDownloadTasks(promise) }
80
51
 
81
52
  override fun setLogsEnabled(enabled: Boolean) {
82
53
  impl.setLogsEnabled(enabled)
@@ -112,38 +83,15 @@ class RNBackgroundDownloaderModule(reactContext: ReactApplicationContext) :
112
83
  impl.upload(options)
113
84
  }
114
85
 
115
- override fun pauseUploadTask(id: String, promise: com.facebook.react.bridge.Promise) {
116
- try {
117
- impl.pauseUploadTask(id)
118
- promise.resolve(null)
119
- } catch (e: Exception) {
120
- promise.reject("ERR_PAUSE_UPLOAD_TASK", e.message, e)
121
- }
122
- }
86
+ override fun pauseUploadTask(id: String, promise: com.facebook.react.bridge.Promise) =
87
+ promise.resolveCatching("ERR_PAUSE_UPLOAD_TASK") { impl.pauseUploadTask(id) }
123
88
 
124
- override fun resumeUploadTask(id: String, promise: com.facebook.react.bridge.Promise) {
125
- try {
126
- impl.resumeUploadTask(id)
127
- promise.resolve(null)
128
- } catch (e: Exception) {
129
- promise.reject("ERR_RESUME_UPLOAD_TASK", e.message, e)
130
- }
131
- }
89
+ override fun resumeUploadTask(id: String, promise: com.facebook.react.bridge.Promise) =
90
+ promise.resolveCatching("ERR_RESUME_UPLOAD_TASK") { impl.resumeUploadTask(id) }
132
91
 
133
- override fun stopUploadTask(id: String, promise: com.facebook.react.bridge.Promise) {
134
- try {
135
- impl.stopUploadTask(id)
136
- promise.resolve(null)
137
- } catch (e: Exception) {
138
- promise.reject("ERR_STOP_UPLOAD_TASK", e.message, e)
139
- }
140
- }
92
+ override fun stopUploadTask(id: String, promise: com.facebook.react.bridge.Promise) =
93
+ promise.resolveCatching("ERR_STOP_UPLOAD_TASK") { impl.stopUploadTask(id) }
141
94
 
142
- override fun getExistingUploadTasks(promise: com.facebook.react.bridge.Promise) {
143
- try {
144
- impl.getExistingUploadTasks(promise)
145
- } catch (e: Exception) {
146
- promise.reject("ERR_GET_EXISTING_UPLOAD_TASKS", e.message, e)
147
- }
148
- }
95
+ override fun getExistingUploadTasks(promise: com.facebook.react.bridge.Promise) =
96
+ promise.rejectOnThrow("ERR_GET_EXISTING_UPLOAD_TASKS") { impl.getExistingUploadTasks(promise) }
149
97
  }
@@ -33,34 +33,16 @@ class RNBackgroundDownloaderModule(reactContext: ReactApplicationContext) :
33
33
  }
34
34
 
35
35
  @ReactMethod
36
- fun pauseTask(id: String, promise: Promise) {
37
- try {
38
- impl.pauseTask(id)
39
- promise.resolve(null)
40
- } catch (e: Exception) {
41
- promise.reject("ERR_PAUSE_TASK", e.message, e)
42
- }
43
- }
36
+ fun pauseTask(id: String, promise: Promise) =
37
+ promise.resolveCatching("ERR_PAUSE_TASK") { impl.pauseTask(id) }
44
38
 
45
39
  @ReactMethod
46
- fun resumeTask(id: String, promise: Promise) {
47
- try {
48
- impl.resumeTask(id)
49
- promise.resolve(null)
50
- } catch (e: Exception) {
51
- promise.reject("ERR_RESUME_TASK", e.message, e)
52
- }
53
- }
40
+ fun resumeTask(id: String, promise: Promise) =
41
+ promise.resolveCatching("ERR_RESUME_TASK") { impl.resumeTask(id) }
54
42
 
55
43
  @ReactMethod
56
- fun stopTask(id: String, promise: Promise) {
57
- try {
58
- impl.stopTask(id)
59
- promise.resolve(null)
60
- } catch (e: Exception) {
61
- promise.reject("ERR_STOP_TASK", e.message, e)
62
- }
63
- }
44
+ fun stopTask(id: String, promise: Promise) =
45
+ promise.resolveCatching("ERR_STOP_TASK") { impl.stopTask(id) }
64
46
 
65
47
  @ReactMethod
66
48
  fun updateTaskHeaders(id: String, headers: ReadableMap, promise: Promise) {
@@ -68,23 +50,12 @@ class RNBackgroundDownloaderModule(reactContext: ReactApplicationContext) :
68
50
  }
69
51
 
70
52
  @ReactMethod
71
- fun completeHandler(jobId: String, promise: Promise) {
72
- try {
73
- impl.completeHandler(jobId)
74
- promise.resolve(null)
75
- } catch (e: Exception) {
76
- promise.reject("ERR_COMPLETE_HANDLER", e.message, e)
77
- }
78
- }
53
+ fun completeHandler(jobId: String, promise: Promise) =
54
+ promise.resolveCatching("ERR_COMPLETE_HANDLER") { impl.completeHandler(jobId) }
79
55
 
80
56
  @ReactMethod
81
- fun getExistingDownloadTasks(promise: Promise) {
82
- try {
83
- impl.getExistingDownloadTasks(promise)
84
- } catch (e: Exception) {
85
- promise.reject("ERR_GET_EXISTING_TASKS", e.message, e)
86
- }
87
- }
57
+ fun getExistingDownloadTasks(promise: Promise) =
58
+ promise.rejectOnThrow("ERR_GET_EXISTING_TASKS") { impl.getExistingDownloadTasks(promise) }
88
59
 
89
60
  @ReactMethod
90
61
  fun setLogsEnabled(enabled: Boolean) {
@@ -124,41 +95,18 @@ class RNBackgroundDownloaderModule(reactContext: ReactApplicationContext) :
124
95
  }
125
96
 
126
97
  @ReactMethod
127
- fun pauseUploadTask(id: String, promise: Promise) {
128
- try {
129
- impl.pauseUploadTask(id)
130
- promise.resolve(null)
131
- } catch (e: Exception) {
132
- promise.reject("ERR_PAUSE_UPLOAD_TASK", e.message, e)
133
- }
134
- }
98
+ fun pauseUploadTask(id: String, promise: Promise) =
99
+ promise.resolveCatching("ERR_PAUSE_UPLOAD_TASK") { impl.pauseUploadTask(id) }
135
100
 
136
101
  @ReactMethod
137
- fun resumeUploadTask(id: String, promise: Promise) {
138
- try {
139
- impl.resumeUploadTask(id)
140
- promise.resolve(null)
141
- } catch (e: Exception) {
142
- promise.reject("ERR_RESUME_UPLOAD_TASK", e.message, e)
143
- }
144
- }
102
+ fun resumeUploadTask(id: String, promise: Promise) =
103
+ promise.resolveCatching("ERR_RESUME_UPLOAD_TASK") { impl.resumeUploadTask(id) }
145
104
 
146
105
  @ReactMethod
147
- fun stopUploadTask(id: String, promise: Promise) {
148
- try {
149
- impl.stopUploadTask(id)
150
- promise.resolve(null)
151
- } catch (e: Exception) {
152
- promise.reject("ERR_STOP_UPLOAD_TASK", e.message, e)
153
- }
154
- }
106
+ fun stopUploadTask(id: String, promise: Promise) =
107
+ promise.resolveCatching("ERR_STOP_UPLOAD_TASK") { impl.stopUploadTask(id) }
155
108
 
156
109
  @ReactMethod
157
- fun getExistingUploadTasks(promise: Promise) {
158
- try {
159
- impl.getExistingUploadTasks(promise)
160
- } catch (e: Exception) {
161
- promise.reject("ERR_GET_EXISTING_UPLOAD_TASKS", e.message, e)
162
- }
163
- }
110
+ fun getExistingUploadTasks(promise: Promise) =
111
+ promise.rejectOnThrow("ERR_GET_EXISTING_UPLOAD_TASKS") { impl.getExistingUploadTasks(promise) }
164
112
  }